Initial js/nbd commit

Signed-off-by: Jeremy Kerr <jk@ozlabs.org>
diff --git a/LICENCE b/LICENCE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENCE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..6ee7fe1
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,3 @@
+sbin_PROGRAMS = nbd-proxy
+
+nbd_proxy_CPPFLAGS = -DRUNSTATEDIR=\"$(runstatedir)\"
diff --git a/README b/README
new file mode 100644
index 0000000..9401251
--- /dev/null
+++ b/README
@@ -0,0 +1,53 @@
+nbd-proxy
+=========
+
+Prototype javascript+websocket NBD server; this code demonstrates a javascript
+NBD implementation connected to the kernel nbd device over a websocket.
+
+There are two components here:
+
+  nbd-proxy: a little binary to initialise a nbd client, connected to a
+             unix domain socket, then proxy data between that socket and
+             stdio. This can be used with a websocket proxy to expose
+             that stdio as a websocket.
+
+  nbd.js:    a javascript implementation of a NBD server.
+
+Running
+-------
+
+You'll need a websocket proxy This connects the nbd-proxy
+component to a websocket endpoint.
+
+For experimentation, I use the `websocketd` infrastrcture to expose the
+websocket endpoint, plus serve the static HTML+js client:
+
+    git clone https://github.com/joewalnes/websocketd
+    (cd websocketd && make)
+
+    sudo websocketd/websocketd --port=8000 --staticdir=web --binary ./nbd-proxy
+
+Note that this type of invocation is very insecure, and intended just for
+experimentation. See the Security section below.
+
+For real deployments, you want your websocket-enabled service to run
+nbd-proxy, and connect its stdio to a websocket, running in binary mode. Your
+web interface will interact with this using an instance of the NBDServer object
+(defined in web/js/nbd.js):
+
+    var server = NBDServer(endpoint, file);
+    server.start();
+
+- where endpoint is the websocket URL (ws://...) and file is a File object. See
+web/index.html for an example.
+
+Security
+--------
+
+This code allows potentially-untrusted clients to export arbitrary block
+device data to your kernel. Therefore, you should ensure that only trusted
+clients can connect as NBD servers.
+
+There is no authentication or authorisation implemented in the nbd proxy. Your
+websocket proxy should implement proper authentication before nbd-proxy is
+connected to the websocket endpoint.
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..2e48ec4
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,17 @@
+AC_PREREQ([2.69])
+AC_INIT([nbd-proxy], 1.0, [jk@ozlabs.org])
+AC_CONFIG_HEADERS([config.h])
+AM_INIT_AUTOMAKE([subdir-objects -Wall -Werror foreign dist-xz])
+AM_SILENT_RULES([yes])
+
+AC_PROG_CC
+AM_PROG_AR
+AC_PROG_INSTALL
+AC_PROG_MAKE_SET
+
+AX_APPEND_COMPILE_FLAGS([-Wall -Werror], [CFLAGS])
+
+AC_CHECK_FUNCS(splice)
+
+AC_CONFIG_FILES([Makefile])
+AC_OUTPUT
diff --git a/nbd-proxy.c b/nbd-proxy.c
new file mode 100644
index 0000000..738b0d2
--- /dev/null
+++ b/nbd-proxy.c
@@ -0,0 +1,419 @@
+/* Copyright 2018 IBM Corp.
+ *
+ * Author: Jeremy Kerr <jk@ozlabs.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.  You may obtain a copy
+ * of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+#define _GNU_SOURCE
+
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/poll.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+
+#include "config.h"
+
+struct ctx {
+	int		sock;
+	int		sock_client;
+	int		signal_pipe[2];
+	char		*sock_path;
+	pid_t		nbd_client_pid;
+	uint8_t		*buf;
+	size_t		bufsize;
+};
+
+static const char *sockpath_tmpl = RUNSTATEDIR "/nbd.%d.sock";
+static const char *dev_path = "/dev/nbd0";
+static const size_t bufsize = 0x20000;
+
+static int open_nbd_socket(struct ctx *ctx)
+{
+	struct sockaddr_un addr;
+	char *path;
+	int sd, rc;
+
+	rc = asprintf(&path, sockpath_tmpl, getpid());
+	if (rc < 0)
+		return -1;
+
+	sd = socket(AF_UNIX, SOCK_STREAM, 0);
+	if (sd < 0) {
+		warn("can't create socket");
+		goto err_free;
+	}
+
+	rc = fchmod(sd, S_IRUSR | S_IWUSR);
+	if (rc) {
+		warn("can't set permissions on socket");
+		goto err_close;
+	}
+
+	addr.sun_family = AF_UNIX;
+	strncpy(addr.sun_path, path, sizeof(addr.sun_path));
+
+	rc = bind(sd, (struct sockaddr *)&addr, sizeof(addr));
+	if (rc) {
+		warn("can't bind to path %s", path);
+		goto err_close;
+	}
+
+	rc = listen(sd, 1);
+	if (rc) {
+		warn("can't listen on socket %s", path);
+		goto err_unlink;
+	}
+
+	ctx->sock = sd;
+	ctx->sock_path = path;
+	return 0;
+
+err_unlink:
+	unlink(path);
+err_close:
+	close(sd);
+err_free:
+	free(path);
+	return -1;
+}
+
+static int start_nbd_client(struct ctx *ctx)
+{
+	pid_t pid;
+
+	pid = fork();
+	if (pid < 0) {
+		warn("can't create client process");
+		return -1;
+	}
+
+	/* child process: run nbd-client in non-fork mode */
+	if (pid == 0) {
+		int fd;
+
+		fd = open("/dev/null", O_RDWR);
+		if (fd < 0)
+			err(EXIT_FAILURE, "can't open /dev/null");
+
+		dup2(fd, STDIN_FILENO);
+		dup2(fd, STDOUT_FILENO);
+		dup2(fd, STDERR_FILENO);
+		close(fd);
+		close(ctx->sock);
+
+		execlp("nbd-client", "nbd-client",
+				"-u", ctx->sock_path,
+				"-n",
+				dev_path,
+				NULL);
+		err(EXIT_FAILURE, "can't start ndb client");
+	}
+
+	ctx->nbd_client_pid = pid;
+	return 0;
+}
+
+static void stop_nbd_client(struct ctx *ctx)
+{
+	int rc;
+
+	if (!ctx->nbd_client_pid)
+		return;
+
+	rc = kill(ctx->nbd_client_pid, SIGTERM);
+	if (rc)
+		return;
+
+	waitpid(ctx->nbd_client_pid, NULL, 0);
+	ctx->nbd_client_pid = 0;
+}
+
+static int copy_fd(struct ctx *ctx, int fd_in, int fd_out)
+{
+#ifdef HAVE_SPLICE
+	int rc;
+
+	rc = splice(fd_in, NULL, fd_out, NULL, ctx->bufsize, 0);
+	if (rc < 0)
+		warn("splice");
+
+	return rc;
+#else
+	size_t len, pos;
+	ssize_t rc;
+
+	for (;;) {
+		errno = 0;
+		rc = read(fd_in, ctx->buf, ctx->bufsize);
+		if (rc < 0) {
+			if (errno == EINTR)
+				continue;
+			warn("read failure");
+			return -1;
+		}
+		if (rc == 0)
+			return 0;
+		break;
+	}
+
+	len = rc;
+
+	for (pos = 0; pos < len;) {
+		errno = 0;
+		rc = write(fd_out, ctx->buf + pos, len - pos);
+		if (rc < 0) {
+			if (errno == EINTR)
+				continue;
+			warn("write failure");
+			return -1;
+		}
+		if (rc == 0)
+			break;
+		pos += rc;
+	}
+
+	return pos;
+#endif
+}
+
+static int signal_pipe_fd = -1;
+
+static void signal_handler(int signal)
+{
+	int rc;
+
+	rc = write(signal_pipe_fd, &signal, sizeof(signal));
+
+	/* not a lot we can do here but exit... */
+	if (rc != sizeof(signal))
+		exit(EXIT_FAILURE);
+}
+
+static int setup_signals(struct ctx *ctx)
+{
+	struct sigaction sa;
+	int rc;
+
+	rc = pipe(ctx->signal_pipe);
+	if (rc) {
+		warn("cant setup signal pipe");
+		return -1;
+	}
+
+	signal_pipe_fd = ctx->signal_pipe[1];
+
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = signal_handler;
+
+	sigaction(SIGINT, &sa, NULL);
+	sigaction(SIGTERM, &sa, NULL);
+	sigaction(SIGCHLD, &sa, NULL);
+
+	return 0;
+}
+
+static void cleanup_signals(struct ctx *ctx)
+{
+	struct sigaction sa;
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = SIG_DFL;
+
+	sigaction(SIGINT, &sa, NULL);
+	sigaction(SIGTERM, &sa, NULL);
+	sigaction(SIGCHLD, &sa, NULL);
+
+	close(ctx->signal_pipe[0]);
+	close(ctx->signal_pipe[1]);
+}
+
+static int process_signal_pipe(struct ctx *ctx, bool *exit)
+{
+	int buf, rc, status;
+
+	rc = read(ctx->signal_pipe[0], &buf, sizeof(buf));
+	if (rc != sizeof(buf))
+		return -1;
+
+	*exit = false;
+
+	switch (buf) {
+	case SIGCHLD:
+		rc = waitpid(ctx->nbd_client_pid, &status, WNOHANG);
+		if (rc > 0) {
+			warnx("nbd client stopped (%s: %d); exiting",
+					WIFEXITED(status) ? "rc" : "sig",
+					WIFEXITED(status) ?
+						WEXITSTATUS(status) :
+						WTERMSIG(status));
+			ctx->nbd_client_pid = 0;
+		}
+		break;
+	case SIGINT:
+	case SIGTERM:
+		*exit = true;
+		break;
+	}
+
+	return 0;
+}
+
+static int wait_for_nbd_client(struct ctx *ctx)
+{
+	struct pollfd pollfds[2];
+	int rc;
+
+	pollfds[0].fd = ctx->sock;
+	pollfds[0].events = POLLIN;
+	pollfds[1].fd = ctx->signal_pipe[0];
+	pollfds[1].events = POLLIN;
+
+	for (;;) {
+		errno = 0;
+		rc = poll(pollfds, 2, -1);
+		if (rc < 0) {
+			if (errno == EINTR)
+				continue;
+			warn("poll failed");
+			return -1;
+		}
+
+		if (pollfds[0].revents) {
+			rc = accept(ctx->sock, NULL, NULL);
+			if (rc < 0) {
+				warn("can't create connection");
+				return -1;
+			}
+			ctx->sock_client = rc;
+			break;
+		}
+
+		if (pollfds[1].revents) {
+			bool exit;
+			rc = process_signal_pipe(ctx, &exit);
+			if (rc || exit)
+				return -1;
+		}
+	}
+
+	return 0;
+}
+
+
+static int run_proxy(struct ctx *ctx)
+{
+	struct pollfd pollfds[3];
+	bool exit = false;
+	int rc;
+
+	/* main proxy: forward data between stdio & socket */
+	pollfds[0].fd = ctx->sock_client;
+	pollfds[0].events = POLLIN;
+	pollfds[1].fd = STDIN_FILENO;
+	pollfds[1].events = POLLIN;
+	pollfds[2].fd = ctx->signal_pipe[0];
+	pollfds[2].events = POLLIN;
+
+	for (;;) {
+		errno = 0;
+		rc = poll(pollfds, 3, -1);
+		if (rc < 0) {
+			if (errno == EINTR)
+				continue;
+			warn("poll failed");
+			break;
+		}
+
+		if (pollfds[0].revents) {
+			rc = copy_fd(ctx, ctx->sock_client, STDOUT_FILENO);
+			if (rc <= 0)
+				break;
+		}
+
+		if (pollfds[1].revents) {
+			rc = copy_fd(ctx, STDIN_FILENO, ctx->sock_client);
+			if (rc <= 0)
+				break;
+		}
+
+		if (pollfds[2].revents) {
+			rc = process_signal_pipe(ctx, &exit);
+			if (rc || exit)
+				break;
+		}
+	}
+
+	return rc ? -1 : 0;
+}
+
+int main(void)
+{
+	struct ctx _ctx, *ctx;
+	int rc;
+
+	ctx = &_ctx;
+	ctx->bufsize = bufsize;
+	ctx->buf = malloc(ctx->bufsize);
+	ctx->sock_path = NULL;
+	ctx->nbd_client_pid = 0;
+
+	rc = open_nbd_socket(ctx);
+	if (rc)
+		goto out_free;
+
+	rc = setup_signals(ctx);
+	if (rc)
+		goto out_close;
+
+	rc = start_nbd_client(ctx);
+	if (rc)
+		goto out_stop_client;
+
+	rc = wait_for_nbd_client(ctx);
+	if (rc)
+		goto out_stop_client;
+
+	rc = run_proxy(ctx);
+
+out_stop_client:
+	/* we cleanup signals before stopping the client, because we
+	 * no longer care about SIGCHLD from the stopping nbd-client
+	 * process. stop_nbd_client will be a no-op if the client hasn't
+	 * been started. */
+	cleanup_signals(ctx);
+
+	stop_nbd_client(ctx);
+	close(ctx->sock_client);
+
+out_close:
+	if (ctx->sock_path) {
+		unlink(ctx->sock_path);
+		free(ctx->sock_path);
+	}
+	close(ctx->sock);
+out_free:
+	free(ctx->buf);
+	return rc ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..7a104c9
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<html>
+ <head>
+  <style type="text/css">
+body, input, #file { font-size: 12px; }
+pre {
+    border: thin solid #c0c0c0;
+    color: #404040;
+    font-family: Inconsolata, Ubuntu mono, fixed;
+    font-size: 9pt;
+    padding: 0.1em 0.4em;
+}
+  </style>
+  <script src="/js/nbd.js" type="text/javascript">
+  </script>
+  <script type="text/javascript">
+var server;
+
+function start_server()
+{ 
+    var file = document.getElementById("file").files[0];
+
+    server = new NBDServer("ws://" + location.host + "/", file);
+    server.onlog = function(msg) {
+        var container = document.getElementById("log");
+        container.innerText += msg + "\n";
+    }
+    server.start()
+}
+
+function stop_server()
+{
+    if (server)
+        server.stop();
+}
+
+document.addEventListener("DOMContentLoaded", function(event) {
+    document.getElementById("go").focus();
+});
+
+  </script>
+ </head>
+ <body>
+  <div>
+   <input type="file" id="file">
+   <input type="button" id="go" onclick="start_server()" value="Serve Image">
+   <input type="button" id="stop" onclick="stop_server()" value="Stop">
+  </div>
+  <pre id="log"></pre>
+ </body>
+</html>
diff --git a/web/js/nbd.js b/web/js/nbd.js
new file mode 100644
index 0000000..1de4d3b
--- /dev/null
+++ b/web/js/nbd.js
@@ -0,0 +1,355 @@
+/* Copyright 2018 IBM Corp.
+ *
+ * Author: Jeremy Kerr <jk@ozlabs.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.  You may obtain a copy
+ * of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* handshake flags */
+const NBD_FLAG_FIXED_NEWSTYLE = 0x1;
+const NBD_FLAG_NO_ZEROES = 0x2;
+
+/* transmission flags */
+const NBD_FLAG_HAS_FLAGS = 0x1;
+const NBD_FLAG_READ_ONLY = 0x2;
+
+/* option negotiation */
+const NBD_OPT_EXPORT_NAME = 0x1;
+const NBD_REP_FLAG_ERROR = 0x1 << 31;
+const NBD_REP_ERR_UNSUP = NBD_REP_FLAG_ERROR | 1;
+
+/* command definitions */
+const NBD_CMD_READ = 0;
+const NBD_CMD_WRITE = 1;
+const NBD_CMD_DISC = 2;
+const NBD_CMD_FLUSH = 3;
+const NBD_CMD_TRIM = 4;
+
+/* errno */
+const EPERM = 1;
+const EIO = 5;
+const ENOMEM = 12;
+const EINVAL = 22;
+const ENOSPC = 28;
+const EOVERFLOW = 75;
+const ESHUTDOWN = 108;
+
+/* internal object state */
+const NBD_STATE_UNKNOWN = 1;
+const NBD_STATE_OPEN = 2;
+const NBD_STATE_WAIT_CFLAGS = 3;
+const NBD_STATE_WAIT_OPTION = 4;
+const NBD_STATE_TRANSMISSION = 5;
+
+function NBDServer(endpoint, file)
+{
+    this.file = file;
+    this.endpoint = endpoint;
+    this.ws = null;
+    this.state = NBD_STATE_UNKNOWN;
+    this.msgbuf = null;
+
+    this.start = function()
+    {
+        this.state = NBD_STATE_OPEN;
+        this.ws = new WebSocket(this.endpoint);
+        this.ws.binaryType = 'arraybuffer';
+        this.ws.onmessage = this._on_ws_message.bind(this);
+        this.ws.onopen = this._on_ws_open.bind(this);
+    }
+
+    this.stop = function()
+    {
+        this.ws.close();
+        this.state = NBD_STATE_UNKNOWN;
+    }
+
+    this._log = function(msg)
+    {
+        if (this.onlog)
+            this.onlog(msg);
+    }
+
+    /* websocket event handlers */
+    this._on_ws_open = function(ev)
+    {
+        this.client = {
+            flags: 0,
+        };
+        this._negotiate();
+    }
+
+    this._on_ws_message = function(ev)
+    {
+        var data = ev.data;
+
+        if (this.msgbuf == null) {
+            this.msgbuf = data;
+        } else {
+            var tmp = new Uint8Array(this.msgbuf.byteLength + data.byteLength);
+            tmp.set(new Uint8Array(this.msgbuf), 0);
+            tmp.set(new Uint8Array(data), this.msgbuf.byteLength);
+            this.msgbuf = tmp.buffer;
+        }
+
+        for (;;) {
+            var handler = this.recv_handlers[this.state];
+            if (!handler) {
+                this._log("no handler for state " + this.state);
+                this.stop();
+                break;
+            }
+
+            var consumed = handler(this.msgbuf);
+            if (consumed < 0) {
+                this._log("handler[state=" + this.state +
+                        "] returned error " + consumed);
+                this.stop();
+                break;
+            }
+
+            if (consumed == 0)
+                break;
+
+            if (consumed > 0) {
+                if (consumed == this.msgbuf.byteLength) {
+                    this.msgbuf = null;
+                    break;
+                }
+                this.msgbuf = this.msgbuf.slice(consumed);
+            }
+        }
+    }
+
+    this._negotiate = function()
+    {
+        var buf = new ArrayBuffer(18);
+        var data = new DataView(buf, 0, 18);
+
+        /* NBD magic: NBDMAGIC */
+        data.setUint32(0,  0x4e42444d);
+        data.setUint32(4,  0x41474943);
+
+        /* newstyle negotiation: IHAVEOPT */
+        data.setUint32(8,  0x49484156);
+        data.setUint32(12, 0x454F5054);
+
+        /* flags: fixed newstyle negotiation, no padding */
+        data.setUint16(16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
+
+        this.state = NBD_STATE_WAIT_CFLAGS;
+        this.ws.send(buf);
+    }
+
+    /* handlers */
+    this._handle_cflags = function(buf)
+    {
+        if (buf.byteLength < 4)
+            return 0;
+
+        var data = new DataView(buf, 0, 4);
+        this.client.flags = data.getUint32(0);
+
+        this._log("client flags received: 0x" +
+                this.client.flags.toString(16));
+
+        this.state = NBD_STATE_WAIT_OPTION;
+        return 4;
+    }
+
+    this._handle_option = function(buf)
+    {
+        if (buf.byteLength < 16)
+            return 0;
+
+        var data = new DataView(buf, 0, 16);
+        if (data.getUint32(0) != 0x49484156 ||
+                data.getUint32(4) != 0x454F5054) {
+            this._log("invalid option magic");
+            return -1;
+        }
+
+        var opt = data.getUint32(8);
+        var len = data.getUint32(12);
+
+        this._log("client option received: 0x" + opt.toString(16));
+
+        if (buf.byteLength < 16 + len)
+            return 0;
+
+        switch (opt) {
+        case NBD_OPT_EXPORT_NAME:
+            this._log("negotiation complete, starting transmission mode");
+            var n = 10;
+            if (!(this.client.flags & NBD_FLAG_NO_ZEROES))
+                n += 124;
+            var resp = new ArrayBuffer(n);
+            var view = new DataView(resp, 0, 10);
+            /* export size. todo: 64 bits? */
+            view.setUint32(0, 0);
+            view.setUint32(4, this.file.size & 0xffffffff);
+            /* transmission flags: read-only */
+            view.setUint16(8, NBD_FLAG_HAS_FLAGS | NBD_FLAG_READ_ONLY);
+            this.ws.send(resp);
+
+            this.state = NBD_STATE_TRANSMISSION;
+            break;
+
+        default:
+            /* reject other options */
+            var resp = new ArrayBuffer(20);
+            var view = new DataView(resp, 0, 20);
+            view.setUint32(0, 0x0003e889);
+            view.setUint32(4, 0x045565a9);
+            view.setUint32(8, opt);
+            view.setUint32(12, NBD_REP_ERR_UNSUP);
+            view.setUint32(16, 0);
+            this.ws.send(resp);
+        }
+
+        return 16 + len;
+    }
+
+    this._create_cmd_response = function(req, rc, data = null)
+    {
+        var len = 16;
+        if (data)
+            len += data.byteLength;
+        var resp = new ArrayBuffer(len);
+        var view = new DataView(resp, 0, 16);
+        view.setUint32(0, 0x67446698);
+        view.setUint32(4, rc);
+        view.setUint32(8, req.handle_msB);
+        view.setUint32(12, req.handle_lsB);
+        if (data)
+            new Uint8Array(resp, 16).set(new Uint8Array(data));
+        return resp;
+    }
+
+    this._handle_cmd = function(buf)
+    {
+        if (buf.byteLength < 28)
+            return 0;
+
+        var view = new DataView(buf, 0, 28);
+
+        if (view.getUint32(0) != 0x25609513) {
+            this._log("invalid request magic");
+            return -1;
+        }
+
+        var req = {
+            flags: view.getUint16(4),
+            type: view.getUint16(6),
+            handle_msB: view.getUint32(8),
+            handle_lsB: view.getUint32(12),
+            offset_msB: view.getUint32(16),
+            offset_lsB: view.getUint32(20),
+            length: view.getUint32(24),
+        };
+
+        /* we don't support writes, so nothing needs the data at present */
+        /* req.data = buf.slice(28); */
+
+        var err = 0;
+	var consumed = 28;
+
+        /* the command handlers return 0 on success, and send their
+         * own response. Otherwise, a non-zero error code will be
+         * used as a simple error response
+         */
+        switch (req.type) {
+        case NBD_CMD_READ:
+            err = this._handle_cmd_read(req);
+            break;
+
+        case NBD_CMD_DISC:
+            err = this._handle_cmd_disconnect(req);
+            break;
+
+        case NBD_CMD_WRITE:
+	    /* we also need length bytes of data to consume a write
+	     * request */
+	    if (buf.byteLength < 28 + req.length)
+		    return 0;
+	    consumed += req.length;
+	    err = EPERM;
+	    break;
+
+        case NBD_CMD_TRIM:
+            err = EPERM;
+            break;
+        
+        default:
+            this._log("invalid command 0x" + req.type.toString(16));
+            err = EINVAL;
+        }
+
+        if (err) {
+            var resp = this._create_cmd_response(req, err);
+            this.ws.send(resp);
+        }
+
+        return consumed;
+    }
+
+    this._handle_cmd_read = function(req)
+    {
+        if (req.offset_msB)
+            return ENOSPC;
+
+        if (req.offset_lsB + req.length > file.size)
+            return ENOSPC;
+
+        this._log("read: 0x" + req.length.toString(16) +
+                " bytes, offset 0x" + req.offset_lsB.toString(16));
+
+        var blob = this.file.slice(req.offset_lsB,
+                req.offset_lsB + req.length);
+        var reader = new FileReader();
+
+        reader.onload = (function(ev) {
+            var reader = ev.target;
+            if (reader.readyState != FileReader.DONE)
+                return;
+            var resp = this._create_cmd_response(req, 0, reader.result);
+            this.ws.send(resp);
+        }).bind(this);
+
+        reader.onerror = (function(ev) {
+            var reader = ev.target;
+            this._log("error reading file: " + reader.error);
+            var resp = this._create_cmd_response(req, EIO);
+            this.ws.send(resp);
+        }).bind(this);
+
+        reader.readAsArrayBuffer(blob);
+
+        return 0;
+    }
+
+    this._handle_cmd_disconnect = function(req)
+    {
+            this._log("disconnect received");
+            this.stop();
+            return 0;
+    }
+
+    this.recv_handlers = Object.freeze({
+        [NBD_STATE_WAIT_CFLAGS]: this._handle_cflags.bind(this),
+        [NBD_STATE_WAIT_OPTION]: this._handle_option.bind(this),
+        [NBD_STATE_TRANSMISSION]: this._handle_cmd.bind(this),
+    });
+}
+
+