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 /* That's all folks */
83 ssize_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
88 if (qemu_in_coroutine()) {
90 return qemu_co_recv(fd, buffer, size);
92 return qemu_co_send(fd, buffer, size);
96 while (offset < size) {
100 len = qemu_recv(fd, buffer + offset, size - offset, 0);
102 len = send(fd, buffer + offset, size - offset, 0);
106 err = socket_error();
108 /* recoverable error */
109 if (err == EINTR || (offset > 0 && err == EAGAIN)) {
113 /* unrecoverable error */
128 static ssize_t read_sync(int fd, void *buffer, size_t size)
130 /* Sockets are kept in blocking mode in the negotiation phase. After
131 * that, a non-readable socket simply means that another thread stole
132 * our request/reply. Synchronization is done with recv_coroutine, so
133 * that this is coroutine-safe.
135 return nbd_wr_sync(fd, buffer, size, true);
138 static ssize_t write_sync(int fd, void *buffer, size_t size)
142 /* For writes, we do expect the socket to be writable. */
143 ret = nbd_wr_sync(fd, buffer, size, false);
144 } while (ret == -EAGAIN);
148 static void combine_addr(char *buf, size_t len, const char* address,
151 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
152 if (strstr(address, ":")) {
153 snprintf(buf, len, "[%s]:%u", address, port);
155 snprintf(buf, len, "%s:%u", address, port);
159 int tcp_socket_outgoing(const char *address, uint16_t port)
161 char address_and_port[128];
162 combine_addr(address_and_port, 128, address, port);
163 return tcp_socket_outgoing_spec(address_and_port);
166 int tcp_socket_outgoing_spec(const char *address_and_port)
168 return inet_connect(address_and_port, true, NULL, NULL);
171 int tcp_socket_incoming(const char *address, uint16_t port)
173 char address_and_port[128];
174 combine_addr(address_and_port, 128, address, port);
175 return tcp_socket_incoming_spec(address_and_port);
178 int tcp_socket_incoming_spec(const char *address_and_port)
182 return inet_listen(address_and_port, ostr, olen, SOCK_STREAM, 0, NULL);
185 int unix_socket_incoming(const char *path)
190 return unix_listen(path, ostr, olen);
193 int unix_socket_outgoing(const char *path)
195 return unix_connect(path);
212 static int nbd_send_negotiate(int csock, off_t size, uint32_t flags)
214 char buf[8 + 8 + 8 + 128];
218 [ 0 .. 7] passwd ("NBDMAGIC")
219 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
222 [28 .. 151] reserved (0)
225 socket_set_block(csock);
228 TRACE("Beginning negotiation.");
229 memcpy(buf, "NBDMAGIC", 8);
230 cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
231 cpu_to_be64w((uint64_t*)(buf + 16), size);
232 cpu_to_be32w((uint32_t*)(buf + 24),
233 flags | NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
234 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
235 memset(buf + 28, 0, 124);
237 if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
242 TRACE("Negotiation succeeded.");
245 socket_set_nonblock(csock);
249 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
250 off_t *size, size_t *blocksize)
257 TRACE("Receiving negotiation.");
259 socket_set_block(csock);
262 if (read_sync(csock, buf, 8) != 8) {
268 if (strlen(buf) == 0) {
269 LOG("server connection closed");
273 TRACE("Magic is %c%c%c%c%c%c%c%c",
274 qemu_isprint(buf[0]) ? buf[0] : '.',
275 qemu_isprint(buf[1]) ? buf[1] : '.',
276 qemu_isprint(buf[2]) ? buf[2] : '.',
277 qemu_isprint(buf[3]) ? buf[3] : '.',
278 qemu_isprint(buf[4]) ? buf[4] : '.',
279 qemu_isprint(buf[5]) ? buf[5] : '.',
280 qemu_isprint(buf[6]) ? buf[6] : '.',
281 qemu_isprint(buf[7]) ? buf[7] : '.');
283 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
284 LOG("Invalid magic received");
288 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
292 magic = be64_to_cpu(magic);
293 TRACE("Magic is 0x%" PRIx64, magic);
296 uint32_t reserved = 0;
300 TRACE("Checking magic (opts_magic)");
301 if (magic != NBD_OPTS_MAGIC) {
302 LOG("Bad magic received");
305 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
306 LOG("flags read failed");
309 *flags = be16_to_cpu(tmp) << 16;
310 /* reserved for future use */
311 if (write_sync(csock, &reserved, sizeof(reserved)) !=
313 LOG("write failed (reserved)");
316 /* write the export name */
317 magic = cpu_to_be64(magic);
318 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
319 LOG("write failed (magic)");
322 opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
323 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
324 LOG("write failed (opt)");
327 namesize = cpu_to_be32(strlen(name));
328 if (write_sync(csock, &namesize, sizeof(namesize)) !=
330 LOG("write failed (namesize)");
333 if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
334 LOG("write failed (name)");
338 TRACE("Checking magic (cli_magic)");
340 if (magic != NBD_CLIENT_MAGIC) {
341 LOG("Bad magic received");
346 if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
350 *size = be64_to_cpu(s);
352 TRACE("Size is %" PRIu64, *size);
355 if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
356 LOG("read failed (flags)");
359 *flags = be32_to_cpup(flags);
361 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
362 LOG("read failed (tmp)");
365 *flags |= be32_to_cpu(tmp);
367 if (read_sync(csock, &buf, 124) != 124) {
368 LOG("read failed (buf)");
374 socket_set_nonblock(csock);
379 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
381 TRACE("Setting NBD socket");
383 if (ioctl(fd, NBD_SET_SOCK, csock) < 0) {
385 LOG("Failed to set NBD socket");
389 TRACE("Setting block size to %lu", (unsigned long)blocksize);
391 if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) < 0) {
393 LOG("Failed setting NBD block size");
397 TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
399 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) < 0) {
401 LOG("Failed setting size (in blocks)");
405 if (flags & NBD_FLAG_READ_ONLY) {
407 TRACE("Setting readonly attribute");
409 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
411 LOG("Failed setting read-only attribute");
416 if (ioctl(fd, NBD_SET_FLAGS, flags) < 0
417 && errno != ENOTTY) {
419 LOG("Failed setting flags");
423 TRACE("Negotiation ended");
428 int nbd_disconnect(int fd)
430 ioctl(fd, NBD_CLEAR_QUE);
431 ioctl(fd, NBD_DISCONNECT);
432 ioctl(fd, NBD_CLEAR_SOCK);
436 int nbd_client(int fd)
441 TRACE("Doing NBD loop");
443 ret = ioctl(fd, NBD_DO_IT);
444 if (ret < 0 && errno == EPIPE) {
445 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
446 * the socket via NBD_DISCONNECT. We do not want to return 1 in
453 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
455 TRACE("Clearing NBD queue");
456 ioctl(fd, NBD_CLEAR_QUE);
458 TRACE("Clearing NBD socket");
459 ioctl(fd, NBD_CLEAR_SOCK);
465 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
470 int nbd_disconnect(int fd)
475 int nbd_client(int fd)
481 ssize_t nbd_send_request(int csock, struct nbd_request *request)
483 uint8_t buf[NBD_REQUEST_SIZE];
486 cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
487 cpu_to_be32w((uint32_t*)(buf + 4), request->type);
488 cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
489 cpu_to_be64w((uint64_t*)(buf + 16), request->from);
490 cpu_to_be32w((uint32_t*)(buf + 24), request->len);
492 TRACE("Sending request to client: "
493 "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
494 request->from, request->len, request->handle, request->type);
496 ret = write_sync(csock, buf, sizeof(buf));
501 if (ret != sizeof(buf)) {
502 LOG("writing to socket failed");
508 static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
510 uint8_t buf[NBD_REQUEST_SIZE];
514 ret = read_sync(csock, buf, sizeof(buf));
519 if (ret != sizeof(buf)) {
525 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
526 [ 4 .. 7] type (0 == READ, 1 == WRITE)
532 magic = be32_to_cpup((uint32_t*)buf);
533 request->type = be32_to_cpup((uint32_t*)(buf + 4));
534 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
535 request->from = be64_to_cpup((uint64_t*)(buf + 16));
536 request->len = be32_to_cpup((uint32_t*)(buf + 24));
538 TRACE("Got request: "
539 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
540 magic, request->type, request->from, request->len);
542 if (magic != NBD_REQUEST_MAGIC) {
543 LOG("invalid magic (got 0x%x)", magic);
549 ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)
551 uint8_t buf[NBD_REPLY_SIZE];
555 ret = read_sync(csock, buf, sizeof(buf));
560 if (ret != sizeof(buf)) {
566 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
567 [ 4 .. 7] error (0 == no error)
571 magic = be32_to_cpup((uint32_t*)buf);
572 reply->error = be32_to_cpup((uint32_t*)(buf + 4));
573 reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
576 "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
577 magic, reply->error, reply->handle);
579 if (magic != NBD_REPLY_MAGIC) {
580 LOG("invalid magic (got 0x%x)", magic);
586 static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
588 uint8_t buf[NBD_REPLY_SIZE];
592 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
593 [ 4 .. 7] error (0 == no error)
596 cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
597 cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
598 cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
600 TRACE("Sending response to client");
602 ret = write_sync(csock, buf, sizeof(buf));
607 if (ret != sizeof(buf)) {
608 LOG("writing to socket failed");
614 #define MAX_NBD_REQUESTS 16
616 typedef struct NBDRequest NBDRequest;
619 QSIMPLEQ_ENTRY(NBDRequest) entry;
625 BlockDriverState *bs;
629 QSIMPLEQ_HEAD(, NBDRequest) requests;
634 void (*close)(NBDClient *client);
639 Coroutine *recv_coroutine;
642 Coroutine *send_coroutine;
647 static void nbd_client_get(NBDClient *client)
652 static void nbd_client_put(NBDClient *client)
654 if (--client->refcount == 0) {
659 static void nbd_client_close(NBDClient *client)
661 qemu_set_fd_handler2(client->sock, NULL, NULL, NULL, NULL);
665 client->close(client);
667 nbd_client_put(client);
670 static NBDRequest *nbd_request_get(NBDClient *client)
673 NBDExport *exp = client->exp;
675 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
676 client->nb_requests++;
678 if (QSIMPLEQ_EMPTY(&exp->requests)) {
679 req = g_malloc0(sizeof(NBDRequest));
680 req->data = qemu_blockalign(exp->bs, NBD_BUFFER_SIZE);
682 req = QSIMPLEQ_FIRST(&exp->requests);
683 QSIMPLEQ_REMOVE_HEAD(&exp->requests, entry);
685 nbd_client_get(client);
686 req->client = client;
690 static void nbd_request_put(NBDRequest *req)
692 NBDClient *client = req->client;
693 QSIMPLEQ_INSERT_HEAD(&client->exp->requests, req, entry);
694 if (client->nb_requests-- == MAX_NBD_REQUESTS) {
697 nbd_client_put(client);
700 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset,
701 off_t size, uint32_t nbdflags)
703 NBDExport *exp = g_malloc0(sizeof(NBDExport));
704 QSIMPLEQ_INIT(&exp->requests);
706 exp->dev_offset = dev_offset;
707 exp->nbdflags = nbdflags;
708 exp->size = size == -1 ? bdrv_getlength(bs) : size;
712 void nbd_export_close(NBDExport *exp)
714 while (!QSIMPLEQ_EMPTY(&exp->requests)) {
715 NBDRequest *first = QSIMPLEQ_FIRST(&exp->requests);
716 QSIMPLEQ_REMOVE_HEAD(&exp->requests, entry);
717 qemu_vfree(first->data);
725 static int nbd_can_read(void *opaque);
726 static void nbd_read(void *opaque);
727 static void nbd_restart_write(void *opaque);
729 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
732 NBDClient *client = req->client;
733 int csock = client->sock;
736 qemu_co_mutex_lock(&client->send_lock);
737 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read,
738 nbd_restart_write, client);
739 client->send_coroutine = qemu_coroutine_self();
742 rc = nbd_send_reply(csock, reply);
744 socket_set_cork(csock, 1);
745 rc = nbd_send_reply(csock, reply);
747 ret = qemu_co_send(csock, req->data, len);
752 socket_set_cork(csock, 0);
755 client->send_coroutine = NULL;
756 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);
757 qemu_co_mutex_unlock(&client->send_lock);
761 static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
763 NBDClient *client = req->client;
764 int csock = client->sock;
767 client->recv_coroutine = qemu_coroutine_self();
768 rc = nbd_receive_request(csock, request);
776 if (request->len > NBD_BUFFER_SIZE) {
777 LOG("len (%u) is larger than max len (%u)",
778 request->len, NBD_BUFFER_SIZE);
783 if ((request->from + request->len) < request->from) {
784 LOG("integer overflow detected! "
785 "you're probably being attacked");
790 TRACE("Decoding type");
792 if ((request->type & NBD_CMD_MASK_COMMAND) == NBD_CMD_WRITE) {
793 TRACE("Reading %u byte(s)", request->len);
795 if (qemu_co_recv(csock, req->data, request->len) != request->len) {
796 LOG("reading from socket failed");
804 client->recv_coroutine = NULL;
808 static void nbd_trip(void *opaque)
810 NBDClient *client = opaque;
811 NBDRequest *req = nbd_request_get(client);
812 NBDExport *exp = client->exp;
813 struct nbd_request request;
814 struct nbd_reply reply;
817 TRACE("Reading request.");
819 ret = nbd_co_receive_request(req, &request);
820 if (ret == -EAGAIN) {
827 reply.handle = request.handle;
835 if ((request.from + request.len) > exp->size) {
836 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
837 ", Offset: %" PRIu64 "\n",
838 request.from, request.len,
839 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
840 LOG("requested operation past EOF--bad client?");
841 goto invalid_request;
844 switch (request.type & NBD_CMD_MASK_COMMAND) {
846 TRACE("Request type is READ");
848 if (request.type & NBD_CMD_FLAG_FUA) {
849 ret = bdrv_co_flush(exp->bs);
857 ret = bdrv_read(exp->bs, (request.from + exp->dev_offset) / 512,
858 req->data, request.len / 512);
860 LOG("reading from file failed");
865 TRACE("Read %u byte(s)", request.len);
866 if (nbd_co_send_reply(req, &reply, request.len) < 0)
870 TRACE("Request type is WRITE");
872 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
873 TRACE("Server is read-only, return error");
878 TRACE("Writing to device");
880 ret = bdrv_write(exp->bs, (request.from + exp->dev_offset) / 512,
881 req->data, request.len / 512);
883 LOG("writing to file failed");
888 if (request.type & NBD_CMD_FLAG_FUA) {
889 ret = bdrv_co_flush(exp->bs);
897 if (nbd_co_send_reply(req, &reply, 0) < 0) {
902 TRACE("Request type is DISCONNECT");
906 TRACE("Request type is FLUSH");
908 ret = bdrv_co_flush(exp->bs);
913 if (nbd_co_send_reply(req, &reply, 0) < 0) {
918 TRACE("Request type is TRIM");
919 ret = bdrv_co_discard(exp->bs, (request.from + exp->dev_offset) / 512,
922 LOG("discard failed");
925 if (nbd_co_send_reply(req, &reply, 0) < 0) {
930 LOG("invalid request type (%u) received", request.type);
932 reply.error = -EINVAL;
934 if (nbd_co_send_reply(req, &reply, 0) < 0) {
940 TRACE("Request/Reply complete");
943 nbd_request_put(req);
947 nbd_request_put(req);
948 nbd_client_close(client);
951 static int nbd_can_read(void *opaque)
953 NBDClient *client = opaque;
955 return client->recv_coroutine || client->nb_requests < MAX_NBD_REQUESTS;
958 static void nbd_read(void *opaque)
960 NBDClient *client = opaque;
962 if (client->recv_coroutine) {
963 qemu_coroutine_enter(client->recv_coroutine, NULL);
965 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
969 static void nbd_restart_write(void *opaque)
971 NBDClient *client = opaque;
973 qemu_coroutine_enter(client->send_coroutine, NULL);
976 NBDClient *nbd_client_new(NBDExport *exp, int csock,
977 void (*close)(NBDClient *))
980 if (nbd_send_negotiate(csock, exp->size, exp->nbdflags) < 0) {
983 client = g_malloc0(sizeof(NBDClient));
984 client->refcount = 1;
986 client->sock = csock;
987 client->close = close;
988 qemu_co_mutex_init(&client->send_lock);
989 qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);