6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
22 #include "qemu-coroutine.h"
27 #include <sys/ioctl.h>
29 #if defined(__sun__) || defined(__HAIKU__)
30 #include <sys/ioccom.h>
39 #include "qemu_socket.h"
40 #include "qemu-queue.h"
45 #define TRACE(msg, ...) do { \
46 LOG(msg, ## __VA_ARGS__); \
49 #define TRACE(msg, ...) \
53 #define LOG(msg, ...) do { \
54 fprintf(stderr, "%s:%s():L%d: " msg "\n", \
55 __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
58 /* This is all part of the "official" NBD API */
60 #define NBD_REQUEST_SIZE (4 + 4 + 8 + 8 + 4)
61 #define NBD_REPLY_SIZE (4 + 4 + 8)
62 #define NBD_REQUEST_MAGIC 0x25609513
63 #define NBD_REPLY_MAGIC 0x67446698
64 #define NBD_OPTS_MAGIC 0x49484156454F5054LL
65 #define NBD_CLIENT_MAGIC 0x0000420281861253LL
67 #define NBD_SET_SOCK _IO(0xab, 0)
68 #define NBD_SET_BLKSIZE _IO(0xab, 1)
69 #define NBD_SET_SIZE _IO(0xab, 2)
70 #define NBD_DO_IT _IO(0xab, 3)
71 #define NBD_CLEAR_SOCK _IO(0xab, 4)
72 #define NBD_CLEAR_QUE _IO(0xab, 5)
73 #define NBD_PRINT_DEBUG _IO(0xab, 6)
74 #define NBD_SET_SIZE_BLOCKS _IO(0xab, 7)
75 #define NBD_DISCONNECT _IO(0xab, 8)
76 #define NBD_SET_TIMEOUT _IO(0xab, 9)
77 #define NBD_SET_FLAGS _IO(0xab, 10)
79 #define NBD_OPT_EXPORT_NAME (1 << 0)
81 /* Definitions for opaque data types */
83 typedef struct NBDRequest NBDRequest;
86 QSIMPLEQ_ENTRY(NBDRequest) entry;
97 QSIMPLEQ_HEAD(, NBDRequest) requests;
102 void (*close)(NBDClient *client);
107 Coroutine *recv_coroutine;
110 Coroutine *send_coroutine;
116 /* That's all folks */
118 ssize_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
123 if (qemu_in_coroutine()) {
125 return qemu_co_recv(fd, buffer, size);
127 return qemu_co_send(fd, buffer, size);
131 while (offset < size) {
135 len = qemu_recv(fd, buffer + offset, size - offset, 0);
137 len = send(fd, buffer + offset, size - offset, 0);
141 err = socket_error();
143 /* recoverable error */
144 if (err == EINTR || (offset > 0 && err == EAGAIN)) {
148 /* unrecoverable error */
163 static ssize_t read_sync(int fd, void *buffer, size_t size)
165 /* Sockets are kept in blocking mode in the negotiation phase. After
166 * that, a non-readable socket simply means that another thread stole
167 * our request/reply. Synchronization is done with recv_coroutine, so
168 * that this is coroutine-safe.
170 return nbd_wr_sync(fd, buffer, size, true);
173 static ssize_t write_sync(int fd, void *buffer, size_t size)
177 /* For writes, we do expect the socket to be writable. */
178 ret = nbd_wr_sync(fd, buffer, size, false);
179 } while (ret == -EAGAIN);
183 static void combine_addr(char *buf, size_t len, const char* address,
186 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
187 if (strstr(address, ":")) {
188 snprintf(buf, len, "[%s]:%u", address, port);
190 snprintf(buf, len, "%s:%u", address, port);
194 int tcp_socket_outgoing(const char *address, uint16_t port)
196 char address_and_port[128];
197 combine_addr(address_and_port, 128, address, port);
198 return tcp_socket_outgoing_spec(address_and_port);
201 int tcp_socket_outgoing_spec(const char *address_and_port)
203 return inet_connect(address_and_port, true, NULL, NULL);
206 int tcp_socket_incoming(const char *address, uint16_t port)
208 char address_and_port[128];
209 combine_addr(address_and_port, 128, address, port);
210 return tcp_socket_incoming_spec(address_and_port);
213 int tcp_socket_incoming_spec(const char *address_and_port)
217 return inet_listen(address_and_port, ostr, olen, SOCK_STREAM, 0, NULL);
220 int unix_socket_incoming(const char *path)
225 return unix_listen(path, ostr, olen);
228 int unix_socket_outgoing(const char *path)
230 return unix_connect(path);
247 static int nbd_send_negotiate(NBDClient *client)
249 int csock = client->sock;
250 char buf[8 + 8 + 8 + 128];
254 [ 0 .. 7] passwd ("NBDMAGIC")
255 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
258 [28 .. 151] reserved (0)
261 socket_set_block(csock);
264 TRACE("Beginning negotiation.");
265 memcpy(buf, "NBDMAGIC", 8);
266 cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
267 cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
268 cpu_to_be32w((uint32_t*)(buf + 24),
269 client->exp->nbdflags | NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
270 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
271 memset(buf + 28, 0, 124);
273 if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
278 TRACE("Negotiation succeeded.");
281 socket_set_nonblock(csock);
285 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
286 off_t *size, size_t *blocksize)
293 TRACE("Receiving negotiation.");
295 socket_set_block(csock);
298 if (read_sync(csock, buf, 8) != 8) {
304 if (strlen(buf) == 0) {
305 LOG("server connection closed");
309 TRACE("Magic is %c%c%c%c%c%c%c%c",
310 qemu_isprint(buf[0]) ? buf[0] : '.',
311 qemu_isprint(buf[1]) ? buf[1] : '.',
312 qemu_isprint(buf[2]) ? buf[2] : '.',
313 qemu_isprint(buf[3]) ? buf[3] : '.',
314 qemu_isprint(buf[4]) ? buf[4] : '.',
315 qemu_isprint(buf[5]) ? buf[5] : '.',
316 qemu_isprint(buf[6]) ? buf[6] : '.',
317 qemu_isprint(buf[7]) ? buf[7] : '.');
319 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
320 LOG("Invalid magic received");
324 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
328 magic = be64_to_cpu(magic);
329 TRACE("Magic is 0x%" PRIx64, magic);
332 uint32_t reserved = 0;
336 TRACE("Checking magic (opts_magic)");
337 if (magic != NBD_OPTS_MAGIC) {
338 LOG("Bad magic received");
341 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
342 LOG("flags read failed");
345 *flags = be16_to_cpu(tmp) << 16;
346 /* reserved for future use */
347 if (write_sync(csock, &reserved, sizeof(reserved)) !=
349 LOG("write failed (reserved)");
352 /* write the export name */
353 magic = cpu_to_be64(magic);
354 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
355 LOG("write failed (magic)");
358 opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
359 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
360 LOG("write failed (opt)");
363 namesize = cpu_to_be32(strlen(name));
364 if (write_sync(csock, &namesize, sizeof(namesize)) !=
366 LOG("write failed (namesize)");
369 if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
370 LOG("write failed (name)");
374 TRACE("Checking magic (cli_magic)");
376 if (magic != NBD_CLIENT_MAGIC) {
377 LOG("Bad magic received");
382 if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
386 *size = be64_to_cpu(s);
388 TRACE("Size is %" PRIu64, *size);
391 if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
392 LOG("read failed (flags)");
395 *flags = be32_to_cpup(flags);
397 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
398 LOG("read failed (tmp)");
401 *flags |= be32_to_cpu(tmp);
403 if (read_sync(csock, &buf, 124) != 124) {
404 LOG("read failed (buf)");
410 socket_set_nonblock(csock);
415 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
417 TRACE("Setting NBD socket");
419 if (ioctl(fd, NBD_SET_SOCK, csock) < 0) {
421 LOG("Failed to set NBD socket");
425 TRACE("Setting block size to %lu", (unsigned long)blocksize);
427 if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) < 0) {
429 LOG("Failed setting NBD block size");
433 TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
435 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) < 0) {
437 LOG("Failed setting size (in blocks)");
441 if (flags & NBD_FLAG_READ_ONLY) {
443 TRACE("Setting readonly attribute");
445 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
447 LOG("Failed setting read-only attribute");
452 if (ioctl(fd, NBD_SET_FLAGS, flags) < 0
453 && errno != ENOTTY) {
455 LOG("Failed setting flags");
459 TRACE("Negotiation ended");
464 int nbd_disconnect(int fd)
466 ioctl(fd, NBD_CLEAR_QUE);
467 ioctl(fd, NBD_DISCONNECT);
468 ioctl(fd, NBD_CLEAR_SOCK);
472 int nbd_client(int fd)
477 TRACE("Doing NBD loop");
479 ret = ioctl(fd, NBD_DO_IT);
480 if (ret < 0 && errno == EPIPE) {
481 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
482 * the socket via NBD_DISCONNECT. We do not want to return 1 in
489 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
491 TRACE("Clearing NBD queue");
492 ioctl(fd, NBD_CLEAR_QUE);
494 TRACE("Clearing NBD socket");
495 ioctl(fd, NBD_CLEAR_SOCK);
501 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
506 int nbd_disconnect(int fd)
511 int nbd_client(int fd)
517 ssize_t nbd_send_request(int csock, struct nbd_request *request)
519 uint8_t buf[NBD_REQUEST_SIZE];
522 cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
523 cpu_to_be32w((uint32_t*)(buf + 4), request->type);
524 cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
525 cpu_to_be64w((uint64_t*)(buf + 16), request->from);
526 cpu_to_be32w((uint32_t*)(buf + 24), request->len);
528 TRACE("Sending request to client: "
529 "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
530 request->from, request->len, request->handle, request->type);
532 ret = write_sync(csock, buf, sizeof(buf));
537 if (ret != sizeof(buf)) {
538 LOG("writing to socket failed");
544 static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
546 uint8_t buf[NBD_REQUEST_SIZE];
550 ret = read_sync(csock, buf, sizeof(buf));
555 if (ret != sizeof(buf)) {
561 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
562 [ 4 .. 7] type (0 == READ, 1 == WRITE)
568 magic = be32_to_cpup((uint32_t*)buf);
569 request->type = be32_to_cpup((uint32_t*)(buf + 4));
570 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
571 request->from = be64_to_cpup((uint64_t*)(buf + 16));
572 request->len = be32_to_cpup((uint32_t*)(buf + 24));
574 TRACE("Got request: "
575 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
576 magic, request->type, request->from, request->len);
578 if (magic != NBD_REQUEST_MAGIC) {
579 LOG("invalid magic (got 0x%x)", magic);
585 ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)
587 uint8_t buf[NBD_REPLY_SIZE];
591 ret = read_sync(csock, buf, sizeof(buf));
596 if (ret != sizeof(buf)) {
602 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
603 [ 4 .. 7] error (0 == no error)
607 magic = be32_to_cpup((uint32_t*)buf);
608 reply->error = be32_to_cpup((uint32_t*)(buf + 4));
609 reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
612 "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
613 magic, reply->error, reply->handle);
615 if (magic != NBD_REPLY_MAGIC) {
616 LOG("invalid magic (got 0x%x)", magic);
622 static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
624 uint8_t buf[NBD_REPLY_SIZE];
628 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
629 [ 4 .. 7] error (0 == no error)
632 cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
633 cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
634 cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
636 TRACE("Sending response to client");
638 ret = write_sync(csock, buf, sizeof(buf));
643 if (ret != sizeof(buf)) {
644 LOG("writing to socket failed");
650 #define MAX_NBD_REQUESTS 16
652 void nbd_client_get(NBDClient *client)
657 void nbd_client_put(NBDClient *client)
659 if (--client->refcount == 0) {
660 /* The last reference should be dropped by client->close,
661 * which is called by nbd_client_close.
663 assert(client->closing);
665 qemu_set_fd_handler2(client->sock, NULL, NULL, NULL, NULL);
668 nbd_export_put(client->exp);
673 void nbd_client_close(NBDClient *client)
675 if (client->closing) {
679 client->closing = true;
681 /* Force requests to finish. They will drop their own references,
682 * then we'll close the socket and free the NBDClient.
684 shutdown(client->sock, 2);
686 /* Also tell the client, so that they release their reference. */
688 client->close(client);
692 static NBDRequest *nbd_request_get(NBDClient *client)
695 NBDExport *exp = client->exp;
697 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
698 client->nb_requests++;
700 if (QSIMPLEQ_EMPTY(&exp->requests)) {
701 req = g_malloc0(sizeof(NBDRequest));
702 req->data = qemu_blockalign(exp->bs, NBD_BUFFER_SIZE);
704 req = QSIMPLEQ_FIRST(&exp->requests);
705 QSIMPLEQ_REMOVE_HEAD(&exp->requests, entry);
707 nbd_client_get(client);
708 req->client = client;
712 static void nbd_request_put(NBDRequest *req)
714 NBDClient *client = req->client;
715 QSIMPLEQ_INSERT_HEAD(&client->exp->requests, req, entry);
716 if (client->nb_requests-- == MAX_NBD_REQUESTS) {
719 nbd_client_put(client);
722 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset,
723 off_t size, uint32_t nbdflags)
725 NBDExport *exp = g_malloc0(sizeof(NBDExport));
726 QSIMPLEQ_INIT(&exp->requests);
729 exp->dev_offset = dev_offset;
730 exp->nbdflags = nbdflags;
731 exp->size = size == -1 ? bdrv_getlength(bs) : size;
735 void nbd_export_close(NBDExport *exp)
737 assert(exp->refcount == 1);
742 void nbd_export_get(NBDExport *exp)
744 assert(exp->refcount > 0);
748 void nbd_export_put(NBDExport *exp)
750 assert(exp->refcount > 0);
751 if (exp->refcount == 1) {
752 nbd_export_close(exp);
755 if (--exp->refcount == 0) {
756 while (!QSIMPLEQ_EMPTY(&exp->requests)) {
757 NBDRequest *first = QSIMPLEQ_FIRST(&exp->requests);
758 QSIMPLEQ_REMOVE_HEAD(&exp->requests, entry);
759 qemu_vfree(first->data);
767 static int nbd_can_read(void *opaque);
768 static void nbd_read(void *opaque);
769 static void nbd_restart_write(void *opaque);
771 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
774 NBDClient *client = req->client;
775 int csock = client->sock;
778 qemu_co_mutex_lock(&client->send_lock);
779 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read,
780 nbd_restart_write, client);
781 client->send_coroutine = qemu_coroutine_self();
784 rc = nbd_send_reply(csock, reply);
786 socket_set_cork(csock, 1);
787 rc = nbd_send_reply(csock, reply);
789 ret = qemu_co_send(csock, req->data, len);
794 socket_set_cork(csock, 0);
797 client->send_coroutine = NULL;
798 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);
799 qemu_co_mutex_unlock(&client->send_lock);
803 static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
805 NBDClient *client = req->client;
806 int csock = client->sock;
809 client->recv_coroutine = qemu_coroutine_self();
810 rc = nbd_receive_request(csock, request);
818 if (request->len > NBD_BUFFER_SIZE) {
819 LOG("len (%u) is larger than max len (%u)",
820 request->len, NBD_BUFFER_SIZE);
825 if ((request->from + request->len) < request->from) {
826 LOG("integer overflow detected! "
827 "you're probably being attacked");
832 TRACE("Decoding type");
834 if ((request->type & NBD_CMD_MASK_COMMAND) == NBD_CMD_WRITE) {
835 TRACE("Reading %u byte(s)", request->len);
837 if (qemu_co_recv(csock, req->data, request->len) != request->len) {
838 LOG("reading from socket failed");
846 client->recv_coroutine = NULL;
850 static void nbd_trip(void *opaque)
852 NBDClient *client = opaque;
853 NBDExport *exp = client->exp;
855 struct nbd_request request;
856 struct nbd_reply reply;
859 TRACE("Reading request.");
860 if (client->closing) {
864 req = nbd_request_get(client);
865 ret = nbd_co_receive_request(req, &request);
866 if (ret == -EAGAIN) {
873 reply.handle = request.handle;
881 if ((request.from + request.len) > exp->size) {
882 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
883 ", Offset: %" PRIu64 "\n",
884 request.from, request.len,
885 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
886 LOG("requested operation past EOF--bad client?");
887 goto invalid_request;
890 switch (request.type & NBD_CMD_MASK_COMMAND) {
892 TRACE("Request type is READ");
894 if (request.type & NBD_CMD_FLAG_FUA) {
895 ret = bdrv_co_flush(exp->bs);
903 ret = bdrv_read(exp->bs, (request.from + exp->dev_offset) / 512,
904 req->data, request.len / 512);
906 LOG("reading from file failed");
911 TRACE("Read %u byte(s)", request.len);
912 if (nbd_co_send_reply(req, &reply, request.len) < 0)
916 TRACE("Request type is WRITE");
918 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
919 TRACE("Server is read-only, return error");
924 TRACE("Writing to device");
926 ret = bdrv_write(exp->bs, (request.from + exp->dev_offset) / 512,
927 req->data, request.len / 512);
929 LOG("writing to file failed");
934 if (request.type & NBD_CMD_FLAG_FUA) {
935 ret = bdrv_co_flush(exp->bs);
943 if (nbd_co_send_reply(req, &reply, 0) < 0) {
948 TRACE("Request type is DISCONNECT");
952 TRACE("Request type is FLUSH");
954 ret = bdrv_co_flush(exp->bs);
959 if (nbd_co_send_reply(req, &reply, 0) < 0) {
964 TRACE("Request type is TRIM");
965 ret = bdrv_co_discard(exp->bs, (request.from + exp->dev_offset) / 512,
968 LOG("discard failed");
971 if (nbd_co_send_reply(req, &reply, 0) < 0) {
976 LOG("invalid request type (%u) received", request.type);
978 reply.error = -EINVAL;
980 if (nbd_co_send_reply(req, &reply, 0) < 0) {
986 TRACE("Request/Reply complete");
989 nbd_request_put(req);
993 nbd_request_put(req);
994 nbd_client_close(client);
997 static int nbd_can_read(void *opaque)
999 NBDClient *client = opaque;
1001 return client->recv_coroutine || client->nb_requests < MAX_NBD_REQUESTS;
1004 static void nbd_read(void *opaque)
1006 NBDClient *client = opaque;
1008 if (client->recv_coroutine) {
1009 qemu_coroutine_enter(client->recv_coroutine, NULL);
1011 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1015 static void nbd_restart_write(void *opaque)
1017 NBDClient *client = opaque;
1019 qemu_coroutine_enter(client->send_coroutine, NULL);
1022 NBDClient *nbd_client_new(NBDExport *exp, int csock,
1023 void (*close)(NBDClient *))
1026 client = g_malloc0(sizeof(NBDClient));
1027 client->refcount = 1;
1029 client->sock = csock;
1030 if (nbd_send_negotiate(client) < 0) {
1034 client->close = close;
1035 qemu_co_mutex_init(&client->send_lock);
1036 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);
1038 nbd_export_get(exp);