1 /* 2 * Copyright (C) 2016-2018 Red Hat, Inc. 3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws> 4 * 5 * Network Block Device Server Side 6 * 7 * This program is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; under version 2 of the License. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 #include "qemu/osdep.h" 21 #include "qapi/error.h" 22 #include "qemu/queue.h" 23 #include "trace.h" 24 #include "nbd-internal.h" 25 #include "qemu/units.h" 26 27 #define NBD_META_ID_BASE_ALLOCATION 0 28 #define NBD_META_ID_DIRTY_BITMAP 1 29 30 /* 31 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical 32 * constant. If an increase is needed, note that the NBD protocol 33 * recommends no larger than 32 mb, so that the client won't consider 34 * the reply as a denial of service attack. 35 */ 36 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8) 37 38 static int system_errno_to_nbd_errno(int err) 39 { 40 switch (err) { 41 case 0: 42 return NBD_SUCCESS; 43 case EPERM: 44 case EROFS: 45 return NBD_EPERM; 46 case EIO: 47 return NBD_EIO; 48 case ENOMEM: 49 return NBD_ENOMEM; 50 #ifdef EDQUOT 51 case EDQUOT: 52 #endif 53 case EFBIG: 54 case ENOSPC: 55 return NBD_ENOSPC; 56 case EOVERFLOW: 57 return NBD_EOVERFLOW; 58 case ENOTSUP: 59 #if ENOTSUP != EOPNOTSUPP 60 case EOPNOTSUPP: 61 #endif 62 return NBD_ENOTSUP; 63 case ESHUTDOWN: 64 return NBD_ESHUTDOWN; 65 case EINVAL: 66 default: 67 return NBD_EINVAL; 68 } 69 } 70 71 /* Definitions for opaque data types */ 72 73 typedef struct NBDRequestData NBDRequestData; 74 75 struct NBDRequestData { 76 QSIMPLEQ_ENTRY(NBDRequestData) entry; 77 NBDClient *client; 78 uint8_t *data; 79 bool complete; 80 }; 81 82 struct NBDExport { 83 int refcount; 84 void (*close)(NBDExport *exp); 85 86 BlockBackend *blk; 87 char *name; 88 char *description; 89 uint64_t dev_offset; 90 uint64_t size; 91 uint16_t nbdflags; 92 QTAILQ_HEAD(, NBDClient) clients; 93 QTAILQ_ENTRY(NBDExport) next; 94 95 AioContext *ctx; 96 97 BlockBackend *eject_notifier_blk; 98 Notifier eject_notifier; 99 100 BdrvDirtyBitmap *export_bitmap; 101 char *export_bitmap_context; 102 }; 103 104 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports); 105 106 /* NBDExportMetaContexts represents a list of contexts to be exported, 107 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for 108 * NBD_OPT_LIST_META_CONTEXT. */ 109 typedef struct NBDExportMetaContexts { 110 NBDExport *exp; 111 bool valid; /* means that negotiation of the option finished without 112 errors */ 113 bool base_allocation; /* export base:allocation context (block status) */ 114 bool bitmap; /* export qemu:dirty-bitmap:<export bitmap name> */ 115 } NBDExportMetaContexts; 116 117 struct NBDClient { 118 int refcount; 119 void (*close_fn)(NBDClient *client, bool negotiated); 120 121 NBDExport *exp; 122 QCryptoTLSCreds *tlscreds; 123 char *tlsauthz; 124 QIOChannelSocket *sioc; /* The underlying data channel */ 125 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */ 126 127 Coroutine *recv_coroutine; 128 129 CoMutex send_lock; 130 Coroutine *send_coroutine; 131 132 QTAILQ_ENTRY(NBDClient) next; 133 int nb_requests; 134 bool closing; 135 136 uint32_t check_align; /* If non-zero, check for aligned client requests */ 137 138 bool structured_reply; 139 NBDExportMetaContexts export_meta; 140 141 uint32_t opt; /* Current option being negotiated */ 142 uint32_t optlen; /* remaining length of data in ioc for the option being 143 negotiated now */ 144 }; 145 146 static void nbd_client_receive_next_request(NBDClient *client); 147 148 /* Basic flow for negotiation 149 150 Server Client 151 Negotiate 152 153 or 154 155 Server Client 156 Negotiate #1 157 Option 158 Negotiate #2 159 160 ---- 161 162 followed by 163 164 Server Client 165 Request 166 Response 167 Request 168 Response 169 ... 170 ... 171 Request (type == 2) 172 173 */ 174 175 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option, 176 uint32_t type, uint32_t length) 177 { 178 stq_be_p(&rep->magic, NBD_REP_MAGIC); 179 stl_be_p(&rep->option, option); 180 stl_be_p(&rep->type, type); 181 stl_be_p(&rep->length, length); 182 } 183 184 /* Send a reply header, including length, but no payload. 185 * Return -errno on error, 0 on success. */ 186 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type, 187 uint32_t len, Error **errp) 188 { 189 NBDOptionReply rep; 190 191 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt), 192 type, nbd_rep_lookup(type), len); 193 194 assert(len < NBD_MAX_BUFFER_SIZE); 195 196 set_be_option_rep(&rep, client->opt, type, len); 197 return nbd_write(client->ioc, &rep, sizeof(rep), errp); 198 } 199 200 /* Send a reply header with default 0 length. 201 * Return -errno on error, 0 on success. */ 202 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type, 203 Error **errp) 204 { 205 return nbd_negotiate_send_rep_len(client, type, 0, errp); 206 } 207 208 /* Send an error reply. 209 * Return -errno on error, 0 on success. */ 210 static int GCC_FMT_ATTR(4, 0) 211 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type, 212 Error **errp, const char *fmt, va_list va) 213 { 214 g_autofree char *msg = NULL; 215 int ret; 216 size_t len; 217 218 msg = g_strdup_vprintf(fmt, va); 219 len = strlen(msg); 220 assert(len < 4096); 221 trace_nbd_negotiate_send_rep_err(msg); 222 ret = nbd_negotiate_send_rep_len(client, type, len, errp); 223 if (ret < 0) { 224 return ret; 225 } 226 if (nbd_write(client->ioc, msg, len, errp) < 0) { 227 error_prepend(errp, "write failed (error message): "); 228 return -EIO; 229 } 230 231 return 0; 232 } 233 234 /* Send an error reply. 235 * Return -errno on error, 0 on success. */ 236 static int GCC_FMT_ATTR(4, 5) 237 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type, 238 Error **errp, const char *fmt, ...) 239 { 240 va_list va; 241 int ret; 242 243 va_start(va, fmt); 244 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va); 245 va_end(va); 246 return ret; 247 } 248 249 /* Drop remainder of the current option, and send a reply with the 250 * given error type and message. Return -errno on read or write 251 * failure; or 0 if connection is still live. */ 252 static int GCC_FMT_ATTR(4, 0) 253 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp, 254 const char *fmt, va_list va) 255 { 256 int ret = nbd_drop(client->ioc, client->optlen, errp); 257 258 client->optlen = 0; 259 if (!ret) { 260 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va); 261 } 262 return ret; 263 } 264 265 static int GCC_FMT_ATTR(4, 5) 266 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp, 267 const char *fmt, ...) 268 { 269 int ret; 270 va_list va; 271 272 va_start(va, fmt); 273 ret = nbd_opt_vdrop(client, type, errp, fmt, va); 274 va_end(va); 275 276 return ret; 277 } 278 279 static int GCC_FMT_ATTR(3, 4) 280 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...) 281 { 282 int ret; 283 va_list va; 284 285 va_start(va, fmt); 286 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va); 287 va_end(va); 288 289 return ret; 290 } 291 292 /* Read size bytes from the unparsed payload of the current option. 293 * Return -errno on I/O error, 0 if option was completely handled by 294 * sending a reply about inconsistent lengths, or 1 on success. */ 295 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size, 296 Error **errp) 297 { 298 if (size > client->optlen) { 299 return nbd_opt_invalid(client, errp, 300 "Inconsistent lengths in option %s", 301 nbd_opt_lookup(client->opt)); 302 } 303 client->optlen -= size; 304 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1; 305 } 306 307 /* Drop size bytes from the unparsed payload of the current option. 308 * Return -errno on I/O error, 0 if option was completely handled by 309 * sending a reply about inconsistent lengths, or 1 on success. */ 310 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp) 311 { 312 if (size > client->optlen) { 313 return nbd_opt_invalid(client, errp, 314 "Inconsistent lengths in option %s", 315 nbd_opt_lookup(client->opt)); 316 } 317 client->optlen -= size; 318 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1; 319 } 320 321 /* nbd_opt_read_name 322 * 323 * Read a string with the format: 324 * uint32_t len (<= NBD_MAX_STRING_SIZE) 325 * len bytes string (not 0-terminated) 326 * 327 * On success, @name will be allocated. 328 * If @length is non-null, it will be set to the actual string length. 329 * 330 * Return -errno on I/O error, 0 if option was completely handled by 331 * sending a reply about inconsistent lengths, or 1 on success. 332 */ 333 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length, 334 Error **errp) 335 { 336 int ret; 337 uint32_t len; 338 g_autofree char *local_name = NULL; 339 340 *name = NULL; 341 ret = nbd_opt_read(client, &len, sizeof(len), errp); 342 if (ret <= 0) { 343 return ret; 344 } 345 len = cpu_to_be32(len); 346 347 if (len > NBD_MAX_STRING_SIZE) { 348 return nbd_opt_invalid(client, errp, 349 "Invalid name length: %" PRIu32, len); 350 } 351 352 local_name = g_malloc(len + 1); 353 ret = nbd_opt_read(client, local_name, len, errp); 354 if (ret <= 0) { 355 return ret; 356 } 357 local_name[len] = '\0'; 358 359 if (length) { 360 *length = len; 361 } 362 *name = g_steal_pointer(&local_name); 363 364 return 1; 365 } 366 367 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload. 368 * Return -errno on error, 0 on success. */ 369 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp, 370 Error **errp) 371 { 372 size_t name_len, desc_len; 373 uint32_t len; 374 const char *name = exp->name ? exp->name : ""; 375 const char *desc = exp->description ? exp->description : ""; 376 QIOChannel *ioc = client->ioc; 377 int ret; 378 379 trace_nbd_negotiate_send_rep_list(name, desc); 380 name_len = strlen(name); 381 desc_len = strlen(desc); 382 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE); 383 len = name_len + desc_len + sizeof(len); 384 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp); 385 if (ret < 0) { 386 return ret; 387 } 388 389 len = cpu_to_be32(name_len); 390 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) { 391 error_prepend(errp, "write failed (name length): "); 392 return -EINVAL; 393 } 394 395 if (nbd_write(ioc, name, name_len, errp) < 0) { 396 error_prepend(errp, "write failed (name buffer): "); 397 return -EINVAL; 398 } 399 400 if (nbd_write(ioc, desc, desc_len, errp) < 0) { 401 error_prepend(errp, "write failed (description buffer): "); 402 return -EINVAL; 403 } 404 405 return 0; 406 } 407 408 /* Process the NBD_OPT_LIST command, with a potential series of replies. 409 * Return -errno on error, 0 on success. */ 410 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp) 411 { 412 NBDExport *exp; 413 assert(client->opt == NBD_OPT_LIST); 414 415 /* For each export, send a NBD_REP_SERVER reply. */ 416 QTAILQ_FOREACH(exp, &exports, next) { 417 if (nbd_negotiate_send_rep_list(client, exp, errp)) { 418 return -EINVAL; 419 } 420 } 421 /* Finish with a NBD_REP_ACK. */ 422 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp); 423 } 424 425 static void nbd_check_meta_export(NBDClient *client) 426 { 427 client->export_meta.valid &= client->exp == client->export_meta.exp; 428 } 429 430 /* Send a reply to NBD_OPT_EXPORT_NAME. 431 * Return -errno on error, 0 on success. */ 432 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes, 433 Error **errp) 434 { 435 g_autofree char *name = NULL; 436 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = ""; 437 size_t len; 438 int ret; 439 uint16_t myflags; 440 441 /* Client sends: 442 [20 .. xx] export name (length bytes) 443 Server replies: 444 [ 0 .. 7] size 445 [ 8 .. 9] export flags 446 [10 .. 133] reserved (0) [unless no_zeroes] 447 */ 448 trace_nbd_negotiate_handle_export_name(); 449 if (client->optlen > NBD_MAX_STRING_SIZE) { 450 error_setg(errp, "Bad length received"); 451 return -EINVAL; 452 } 453 name = g_malloc(client->optlen + 1); 454 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) { 455 return -EIO; 456 } 457 name[client->optlen] = '\0'; 458 client->optlen = 0; 459 460 trace_nbd_negotiate_handle_export_name_request(name); 461 462 client->exp = nbd_export_find(name); 463 if (!client->exp) { 464 error_setg(errp, "export not found"); 465 return -EINVAL; 466 } 467 468 myflags = client->exp->nbdflags; 469 if (client->structured_reply) { 470 myflags |= NBD_FLAG_SEND_DF; 471 } 472 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags); 473 stq_be_p(buf, client->exp->size); 474 stw_be_p(buf + 8, myflags); 475 len = no_zeroes ? 10 : sizeof(buf); 476 ret = nbd_write(client->ioc, buf, len, errp); 477 if (ret < 0) { 478 error_prepend(errp, "write failed: "); 479 return ret; 480 } 481 482 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next); 483 nbd_export_get(client->exp); 484 nbd_check_meta_export(client); 485 486 return 0; 487 } 488 489 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes. 490 * The buffer does NOT include the info type prefix. 491 * Return -errno on error, 0 if ready to send more. */ 492 static int nbd_negotiate_send_info(NBDClient *client, 493 uint16_t info, uint32_t length, void *buf, 494 Error **errp) 495 { 496 int rc; 497 498 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length); 499 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO, 500 sizeof(info) + length, errp); 501 if (rc < 0) { 502 return rc; 503 } 504 info = cpu_to_be16(info); 505 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) { 506 return -EIO; 507 } 508 if (nbd_write(client->ioc, buf, length, errp) < 0) { 509 return -EIO; 510 } 511 return 0; 512 } 513 514 /* nbd_reject_length: Handle any unexpected payload. 515 * @fatal requests that we quit talking to the client, even if we are able 516 * to successfully send an error reply. 517 * Return: 518 * -errno transmission error occurred or @fatal was requested, errp is set 519 * 0 error message successfully sent to client, errp is not set 520 */ 521 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp) 522 { 523 int ret; 524 525 assert(client->optlen); 526 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length", 527 nbd_opt_lookup(client->opt)); 528 if (fatal && !ret) { 529 error_setg(errp, "option '%s' has unexpected length", 530 nbd_opt_lookup(client->opt)); 531 return -EINVAL; 532 } 533 return ret; 534 } 535 536 /* Handle NBD_OPT_INFO and NBD_OPT_GO. 537 * Return -errno on error, 0 if ready for next option, and 1 to move 538 * into transmission phase. */ 539 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp) 540 { 541 int rc; 542 g_autofree char *name = NULL; 543 NBDExport *exp; 544 uint16_t requests; 545 uint16_t request; 546 uint32_t namelen; 547 bool sendname = false; 548 bool blocksize = false; 549 uint32_t sizes[3]; 550 char buf[sizeof(uint64_t) + sizeof(uint16_t)]; 551 uint32_t check_align = 0; 552 uint16_t myflags; 553 554 /* Client sends: 555 4 bytes: L, name length (can be 0) 556 L bytes: export name 557 2 bytes: N, number of requests (can be 0) 558 N * 2 bytes: N requests 559 */ 560 rc = nbd_opt_read_name(client, &name, &namelen, errp); 561 if (rc <= 0) { 562 return rc; 563 } 564 trace_nbd_negotiate_handle_export_name_request(name); 565 566 rc = nbd_opt_read(client, &requests, sizeof(requests), errp); 567 if (rc <= 0) { 568 return rc; 569 } 570 requests = be16_to_cpu(requests); 571 trace_nbd_negotiate_handle_info_requests(requests); 572 while (requests--) { 573 rc = nbd_opt_read(client, &request, sizeof(request), errp); 574 if (rc <= 0) { 575 return rc; 576 } 577 request = be16_to_cpu(request); 578 trace_nbd_negotiate_handle_info_request(request, 579 nbd_info_lookup(request)); 580 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE; 581 * everything else is either a request we don't know or 582 * something we send regardless of request */ 583 switch (request) { 584 case NBD_INFO_NAME: 585 sendname = true; 586 break; 587 case NBD_INFO_BLOCK_SIZE: 588 blocksize = true; 589 break; 590 } 591 } 592 if (client->optlen) { 593 return nbd_reject_length(client, false, errp); 594 } 595 596 exp = nbd_export_find(name); 597 if (!exp) { 598 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN, 599 errp, "export '%s' not present", 600 name); 601 } 602 603 /* Don't bother sending NBD_INFO_NAME unless client requested it */ 604 if (sendname) { 605 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name, 606 errp); 607 if (rc < 0) { 608 return rc; 609 } 610 } 611 612 /* Send NBD_INFO_DESCRIPTION only if available, regardless of 613 * client request */ 614 if (exp->description) { 615 size_t len = strlen(exp->description); 616 617 assert(len <= NBD_MAX_STRING_SIZE); 618 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION, 619 len, exp->description, errp); 620 if (rc < 0) { 621 return rc; 622 } 623 } 624 625 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size 626 * according to whether the client requested it, and according to 627 * whether this is OPT_INFO or OPT_GO. */ 628 /* minimum - 1 for back-compat, or actual if client will obey it. */ 629 if (client->opt == NBD_OPT_INFO || blocksize) { 630 check_align = sizes[0] = blk_get_request_alignment(exp->blk); 631 } else { 632 sizes[0] = 1; 633 } 634 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE); 635 /* preferred - Hard-code to 4096 for now. 636 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */ 637 sizes[1] = MAX(4096, sizes[0]); 638 /* maximum - At most 32M, but smaller as appropriate. */ 639 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE); 640 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]); 641 sizes[0] = cpu_to_be32(sizes[0]); 642 sizes[1] = cpu_to_be32(sizes[1]); 643 sizes[2] = cpu_to_be32(sizes[2]); 644 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE, 645 sizeof(sizes), sizes, errp); 646 if (rc < 0) { 647 return rc; 648 } 649 650 /* Send NBD_INFO_EXPORT always */ 651 myflags = exp->nbdflags; 652 if (client->structured_reply) { 653 myflags |= NBD_FLAG_SEND_DF; 654 } 655 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags); 656 stq_be_p(buf, exp->size); 657 stw_be_p(buf + 8, myflags); 658 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT, 659 sizeof(buf), buf, errp); 660 if (rc < 0) { 661 return rc; 662 } 663 664 /* 665 * If the client is just asking for NBD_OPT_INFO, but forgot to 666 * request block sizes in a situation that would impact 667 * performance, then return an error. But for NBD_OPT_GO, we 668 * tolerate all clients, regardless of alignments. 669 */ 670 if (client->opt == NBD_OPT_INFO && !blocksize && 671 blk_get_request_alignment(exp->blk) > 1) { 672 return nbd_negotiate_send_rep_err(client, 673 NBD_REP_ERR_BLOCK_SIZE_REQD, 674 errp, 675 "request NBD_INFO_BLOCK_SIZE to " 676 "use this export"); 677 } 678 679 /* Final reply */ 680 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp); 681 if (rc < 0) { 682 return rc; 683 } 684 685 if (client->opt == NBD_OPT_GO) { 686 client->exp = exp; 687 client->check_align = check_align; 688 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next); 689 nbd_export_get(client->exp); 690 nbd_check_meta_export(client); 691 rc = 1; 692 } 693 return rc; 694 } 695 696 697 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the 698 * new channel for all further (now-encrypted) communication. */ 699 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client, 700 Error **errp) 701 { 702 QIOChannel *ioc; 703 QIOChannelTLS *tioc; 704 struct NBDTLSHandshakeData data = { 0 }; 705 706 assert(client->opt == NBD_OPT_STARTTLS); 707 708 trace_nbd_negotiate_handle_starttls(); 709 ioc = client->ioc; 710 711 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) { 712 return NULL; 713 } 714 715 tioc = qio_channel_tls_new_server(ioc, 716 client->tlscreds, 717 client->tlsauthz, 718 errp); 719 if (!tioc) { 720 return NULL; 721 } 722 723 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls"); 724 trace_nbd_negotiate_handle_starttls_handshake(); 725 data.loop = g_main_loop_new(g_main_context_default(), FALSE); 726 qio_channel_tls_handshake(tioc, 727 nbd_tls_handshake, 728 &data, 729 NULL, 730 NULL); 731 732 if (!data.complete) { 733 g_main_loop_run(data.loop); 734 } 735 g_main_loop_unref(data.loop); 736 if (data.error) { 737 object_unref(OBJECT(tioc)); 738 error_propagate(errp, data.error); 739 return NULL; 740 } 741 742 return QIO_CHANNEL(tioc); 743 } 744 745 /* nbd_negotiate_send_meta_context 746 * 747 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT 748 * 749 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead. 750 */ 751 static int nbd_negotiate_send_meta_context(NBDClient *client, 752 const char *context, 753 uint32_t context_id, 754 Error **errp) 755 { 756 NBDOptionReplyMetaContext opt; 757 struct iovec iov[] = { 758 {.iov_base = &opt, .iov_len = sizeof(opt)}, 759 {.iov_base = (void *)context, .iov_len = strlen(context)} 760 }; 761 762 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE); 763 if (client->opt == NBD_OPT_LIST_META_CONTEXT) { 764 context_id = 0; 765 } 766 767 trace_nbd_negotiate_meta_query_reply(context, context_id); 768 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT, 769 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len); 770 stl_be_p(&opt.context_id, context_id); 771 772 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0; 773 } 774 775 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern. 776 * @match is never set to false. 777 * 778 * Return -errno on I/O error, 0 if option was completely handled by 779 * sending a reply about inconsistent lengths, or 1 on success. 780 * 781 * Note: return code = 1 doesn't mean that we've read exactly @pattern. 782 * It only means that there are no errors. 783 */ 784 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match, 785 Error **errp) 786 { 787 int ret; 788 char *query; 789 size_t len = strlen(pattern); 790 791 assert(len); 792 793 query = g_malloc(len); 794 ret = nbd_opt_read(client, query, len, errp); 795 if (ret <= 0) { 796 g_free(query); 797 return ret; 798 } 799 800 if (strncmp(query, pattern, len) == 0) { 801 trace_nbd_negotiate_meta_query_parse(pattern); 802 *match = true; 803 } else { 804 trace_nbd_negotiate_meta_query_skip("pattern not matched"); 805 } 806 g_free(query); 807 808 return 1; 809 } 810 811 /* 812 * Read @len bytes, and set @match to true if they match @pattern, or if @len 813 * is 0 and the client is performing _LIST_. @match is never set to false. 814 * 815 * Return -errno on I/O error, 0 if option was completely handled by 816 * sending a reply about inconsistent lengths, or 1 on success. 817 * 818 * Note: return code = 1 doesn't mean that we've read exactly @pattern. 819 * It only means that there are no errors. 820 */ 821 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern, 822 uint32_t len, bool *match, Error **errp) 823 { 824 if (len == 0) { 825 if (client->opt == NBD_OPT_LIST_META_CONTEXT) { 826 *match = true; 827 } 828 trace_nbd_negotiate_meta_query_parse("empty"); 829 return 1; 830 } 831 832 if (len != strlen(pattern)) { 833 trace_nbd_negotiate_meta_query_skip("different lengths"); 834 return nbd_opt_skip(client, len, errp); 835 } 836 837 return nbd_meta_pattern(client, pattern, match, errp); 838 } 839 840 /* nbd_meta_base_query 841 * 842 * Handle queries to 'base' namespace. For now, only the base:allocation 843 * context is available. 'len' is the amount of text remaining to be read from 844 * the current name, after the 'base:' portion has been stripped. 845 * 846 * Return -errno on I/O error, 0 if option was completely handled by 847 * sending a reply about inconsistent lengths, or 1 on success. 848 */ 849 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta, 850 uint32_t len, Error **errp) 851 { 852 return nbd_meta_empty_or_pattern(client, "allocation", len, 853 &meta->base_allocation, errp); 854 } 855 856 /* nbd_meta_bitmap_query 857 * 858 * Handle query to 'qemu:' namespace. 859 * @len is the amount of text remaining to be read from the current name, after 860 * the 'qemu:' portion has been stripped. 861 * 862 * Return -errno on I/O error, 0 if option was completely handled by 863 * sending a reply about inconsistent lengths, or 1 on success. */ 864 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta, 865 uint32_t len, Error **errp) 866 { 867 bool dirty_bitmap = false; 868 size_t dirty_bitmap_len = strlen("dirty-bitmap:"); 869 int ret; 870 871 if (!meta->exp->export_bitmap) { 872 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported"); 873 return nbd_opt_skip(client, len, errp); 874 } 875 876 if (len == 0) { 877 if (client->opt == NBD_OPT_LIST_META_CONTEXT) { 878 meta->bitmap = true; 879 } 880 trace_nbd_negotiate_meta_query_parse("empty"); 881 return 1; 882 } 883 884 if (len < dirty_bitmap_len) { 885 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:"); 886 return nbd_opt_skip(client, len, errp); 887 } 888 889 len -= dirty_bitmap_len; 890 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp); 891 if (ret <= 0) { 892 return ret; 893 } 894 if (!dirty_bitmap) { 895 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:"); 896 return nbd_opt_skip(client, len, errp); 897 } 898 899 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:"); 900 901 return nbd_meta_empty_or_pattern( 902 client, meta->exp->export_bitmap_context + 903 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp); 904 } 905 906 /* nbd_negotiate_meta_query 907 * 908 * Parse namespace name and call corresponding function to parse body of the 909 * query. 910 * 911 * The only supported namespaces are 'base' and 'qemu'. 912 * 913 * The function aims not wasting time and memory to read long unknown namespace 914 * names. 915 * 916 * Return -errno on I/O error, 0 if option was completely handled by 917 * sending a reply about inconsistent lengths, or 1 on success. */ 918 static int nbd_negotiate_meta_query(NBDClient *client, 919 NBDExportMetaContexts *meta, Error **errp) 920 { 921 /* 922 * Both 'qemu' and 'base' namespaces have length = 5 including a 923 * colon. If another length namespace is later introduced, this 924 * should certainly be refactored. 925 */ 926 int ret; 927 size_t ns_len = 5; 928 char ns[5]; 929 uint32_t len; 930 931 ret = nbd_opt_read(client, &len, sizeof(len), errp); 932 if (ret <= 0) { 933 return ret; 934 } 935 len = cpu_to_be32(len); 936 937 if (len > NBD_MAX_STRING_SIZE) { 938 trace_nbd_negotiate_meta_query_skip("length too long"); 939 return nbd_opt_skip(client, len, errp); 940 } 941 if (len < ns_len) { 942 trace_nbd_negotiate_meta_query_skip("length too short"); 943 return nbd_opt_skip(client, len, errp); 944 } 945 946 len -= ns_len; 947 ret = nbd_opt_read(client, ns, ns_len, errp); 948 if (ret <= 0) { 949 return ret; 950 } 951 952 if (!strncmp(ns, "base:", ns_len)) { 953 trace_nbd_negotiate_meta_query_parse("base:"); 954 return nbd_meta_base_query(client, meta, len, errp); 955 } else if (!strncmp(ns, "qemu:", ns_len)) { 956 trace_nbd_negotiate_meta_query_parse("qemu:"); 957 return nbd_meta_qemu_query(client, meta, len, errp); 958 } 959 960 trace_nbd_negotiate_meta_query_skip("unknown namespace"); 961 return nbd_opt_skip(client, len, errp); 962 } 963 964 /* nbd_negotiate_meta_queries 965 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT 966 * 967 * Return -errno on I/O error, or 0 if option was completely handled. */ 968 static int nbd_negotiate_meta_queries(NBDClient *client, 969 NBDExportMetaContexts *meta, Error **errp) 970 { 971 int ret; 972 g_autofree char *export_name = NULL; 973 NBDExportMetaContexts local_meta; 974 uint32_t nb_queries; 975 int i; 976 977 if (!client->structured_reply) { 978 return nbd_opt_invalid(client, errp, 979 "request option '%s' when structured reply " 980 "is not negotiated", 981 nbd_opt_lookup(client->opt)); 982 } 983 984 if (client->opt == NBD_OPT_LIST_META_CONTEXT) { 985 /* Only change the caller's meta on SET. */ 986 meta = &local_meta; 987 } 988 989 memset(meta, 0, sizeof(*meta)); 990 991 ret = nbd_opt_read_name(client, &export_name, NULL, errp); 992 if (ret <= 0) { 993 return ret; 994 } 995 996 meta->exp = nbd_export_find(export_name); 997 if (meta->exp == NULL) { 998 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp, 999 "export '%s' not present", export_name); 1000 } 1001 1002 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp); 1003 if (ret <= 0) { 1004 return ret; 1005 } 1006 nb_queries = cpu_to_be32(nb_queries); 1007 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt), 1008 export_name, nb_queries); 1009 1010 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) { 1011 /* enable all known contexts */ 1012 meta->base_allocation = true; 1013 meta->bitmap = !!meta->exp->export_bitmap; 1014 } else { 1015 for (i = 0; i < nb_queries; ++i) { 1016 ret = nbd_negotiate_meta_query(client, meta, errp); 1017 if (ret <= 0) { 1018 return ret; 1019 } 1020 } 1021 } 1022 1023 if (meta->base_allocation) { 1024 ret = nbd_negotiate_send_meta_context(client, "base:allocation", 1025 NBD_META_ID_BASE_ALLOCATION, 1026 errp); 1027 if (ret < 0) { 1028 return ret; 1029 } 1030 } 1031 1032 if (meta->bitmap) { 1033 ret = nbd_negotiate_send_meta_context(client, 1034 meta->exp->export_bitmap_context, 1035 NBD_META_ID_DIRTY_BITMAP, 1036 errp); 1037 if (ret < 0) { 1038 return ret; 1039 } 1040 } 1041 1042 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp); 1043 if (ret == 0) { 1044 meta->valid = true; 1045 } 1046 1047 return ret; 1048 } 1049 1050 /* nbd_negotiate_options 1051 * Process all NBD_OPT_* client option commands, during fixed newstyle 1052 * negotiation. 1053 * Return: 1054 * -errno on error, errp is set 1055 * 0 on successful negotiation, errp is not set 1056 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect, 1057 * errp is not set 1058 */ 1059 static int nbd_negotiate_options(NBDClient *client, Error **errp) 1060 { 1061 uint32_t flags; 1062 bool fixedNewstyle = false; 1063 bool no_zeroes = false; 1064 1065 /* Client sends: 1066 [ 0 .. 3] client flags 1067 1068 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO: 1069 [ 0 .. 7] NBD_OPTS_MAGIC 1070 [ 8 .. 11] NBD option 1071 [12 .. 15] Data length 1072 ... Rest of request 1073 1074 [ 0 .. 7] NBD_OPTS_MAGIC 1075 [ 8 .. 11] Second NBD option 1076 [12 .. 15] Data length 1077 ... Rest of request 1078 */ 1079 1080 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) { 1081 return -EIO; 1082 } 1083 trace_nbd_negotiate_options_flags(flags); 1084 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) { 1085 fixedNewstyle = true; 1086 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE; 1087 } 1088 if (flags & NBD_FLAG_C_NO_ZEROES) { 1089 no_zeroes = true; 1090 flags &= ~NBD_FLAG_C_NO_ZEROES; 1091 } 1092 if (flags != 0) { 1093 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags); 1094 return -EINVAL; 1095 } 1096 1097 while (1) { 1098 int ret; 1099 uint32_t option, length; 1100 uint64_t magic; 1101 1102 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) { 1103 return -EINVAL; 1104 } 1105 trace_nbd_negotiate_options_check_magic(magic); 1106 if (magic != NBD_OPTS_MAGIC) { 1107 error_setg(errp, "Bad magic received"); 1108 return -EINVAL; 1109 } 1110 1111 if (nbd_read32(client->ioc, &option, "option", errp) < 0) { 1112 return -EINVAL; 1113 } 1114 client->opt = option; 1115 1116 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) { 1117 return -EINVAL; 1118 } 1119 assert(!client->optlen); 1120 client->optlen = length; 1121 1122 if (length > NBD_MAX_BUFFER_SIZE) { 1123 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)", 1124 length, NBD_MAX_BUFFER_SIZE); 1125 return -EINVAL; 1126 } 1127 1128 trace_nbd_negotiate_options_check_option(option, 1129 nbd_opt_lookup(option)); 1130 if (client->tlscreds && 1131 client->ioc == (QIOChannel *)client->sioc) { 1132 QIOChannel *tioc; 1133 if (!fixedNewstyle) { 1134 error_setg(errp, "Unsupported option 0x%" PRIx32, option); 1135 return -EINVAL; 1136 } 1137 switch (option) { 1138 case NBD_OPT_STARTTLS: 1139 if (length) { 1140 /* Unconditionally drop the connection if the client 1141 * can't start a TLS negotiation correctly */ 1142 return nbd_reject_length(client, true, errp); 1143 } 1144 tioc = nbd_negotiate_handle_starttls(client, errp); 1145 if (!tioc) { 1146 return -EIO; 1147 } 1148 ret = 0; 1149 object_unref(OBJECT(client->ioc)); 1150 client->ioc = QIO_CHANNEL(tioc); 1151 break; 1152 1153 case NBD_OPT_EXPORT_NAME: 1154 /* No way to return an error to client, so drop connection */ 1155 error_setg(errp, "Option 0x%x not permitted before TLS", 1156 option); 1157 return -EINVAL; 1158 1159 default: 1160 /* Let the client keep trying, unless they asked to 1161 * quit. Always try to give an error back to the 1162 * client; but when replying to OPT_ABORT, be aware 1163 * that the client may hang up before receiving the 1164 * error, in which case we are fine ignoring the 1165 * resulting EPIPE. */ 1166 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD, 1167 option == NBD_OPT_ABORT ? NULL : errp, 1168 "Option 0x%" PRIx32 1169 " not permitted before TLS", option); 1170 if (option == NBD_OPT_ABORT) { 1171 return 1; 1172 } 1173 break; 1174 } 1175 } else if (fixedNewstyle) { 1176 switch (option) { 1177 case NBD_OPT_LIST: 1178 if (length) { 1179 ret = nbd_reject_length(client, false, errp); 1180 } else { 1181 ret = nbd_negotiate_handle_list(client, errp); 1182 } 1183 break; 1184 1185 case NBD_OPT_ABORT: 1186 /* NBD spec says we must try to reply before 1187 * disconnecting, but that we must also tolerate 1188 * guests that don't wait for our reply. */ 1189 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL); 1190 return 1; 1191 1192 case NBD_OPT_EXPORT_NAME: 1193 return nbd_negotiate_handle_export_name(client, no_zeroes, 1194 errp); 1195 1196 case NBD_OPT_INFO: 1197 case NBD_OPT_GO: 1198 ret = nbd_negotiate_handle_info(client, errp); 1199 if (ret == 1) { 1200 assert(option == NBD_OPT_GO); 1201 return 0; 1202 } 1203 break; 1204 1205 case NBD_OPT_STARTTLS: 1206 if (length) { 1207 ret = nbd_reject_length(client, false, errp); 1208 } else if (client->tlscreds) { 1209 ret = nbd_negotiate_send_rep_err(client, 1210 NBD_REP_ERR_INVALID, errp, 1211 "TLS already enabled"); 1212 } else { 1213 ret = nbd_negotiate_send_rep_err(client, 1214 NBD_REP_ERR_POLICY, errp, 1215 "TLS not configured"); 1216 } 1217 break; 1218 1219 case NBD_OPT_STRUCTURED_REPLY: 1220 if (length) { 1221 ret = nbd_reject_length(client, false, errp); 1222 } else if (client->structured_reply) { 1223 ret = nbd_negotiate_send_rep_err( 1224 client, NBD_REP_ERR_INVALID, errp, 1225 "structured reply already negotiated"); 1226 } else { 1227 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp); 1228 client->structured_reply = true; 1229 } 1230 break; 1231 1232 case NBD_OPT_LIST_META_CONTEXT: 1233 case NBD_OPT_SET_META_CONTEXT: 1234 ret = nbd_negotiate_meta_queries(client, &client->export_meta, 1235 errp); 1236 break; 1237 1238 default: 1239 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp, 1240 "Unsupported option %" PRIu32 " (%s)", 1241 option, nbd_opt_lookup(option)); 1242 break; 1243 } 1244 } else { 1245 /* 1246 * If broken new-style we should drop the connection 1247 * for anything except NBD_OPT_EXPORT_NAME 1248 */ 1249 switch (option) { 1250 case NBD_OPT_EXPORT_NAME: 1251 return nbd_negotiate_handle_export_name(client, no_zeroes, 1252 errp); 1253 1254 default: 1255 error_setg(errp, "Unsupported option %" PRIu32 " (%s)", 1256 option, nbd_opt_lookup(option)); 1257 return -EINVAL; 1258 } 1259 } 1260 if (ret < 0) { 1261 return ret; 1262 } 1263 } 1264 } 1265 1266 /* nbd_negotiate 1267 * Return: 1268 * -errno on error, errp is set 1269 * 0 on successful negotiation, errp is not set 1270 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect, 1271 * errp is not set 1272 */ 1273 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp) 1274 { 1275 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = ""; 1276 int ret; 1277 1278 /* Old style negotiation header, no room for options 1279 [ 0 .. 7] passwd ("NBDMAGIC") 1280 [ 8 .. 15] magic (NBD_CLIENT_MAGIC) 1281 [16 .. 23] size 1282 [24 .. 27] export flags (zero-extended) 1283 [28 .. 151] reserved (0) 1284 1285 New style negotiation header, client can send options 1286 [ 0 .. 7] passwd ("NBDMAGIC") 1287 [ 8 .. 15] magic (NBD_OPTS_MAGIC) 1288 [16 .. 17] server flags (0) 1289 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO.... 1290 */ 1291 1292 qio_channel_set_blocking(client->ioc, false, NULL); 1293 1294 trace_nbd_negotiate_begin(); 1295 memcpy(buf, "NBDMAGIC", 8); 1296 1297 stq_be_p(buf + 8, NBD_OPTS_MAGIC); 1298 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES); 1299 1300 if (nbd_write(client->ioc, buf, 18, errp) < 0) { 1301 error_prepend(errp, "write failed: "); 1302 return -EINVAL; 1303 } 1304 ret = nbd_negotiate_options(client, errp); 1305 if (ret != 0) { 1306 if (ret < 0) { 1307 error_prepend(errp, "option negotiation failed: "); 1308 } 1309 return ret; 1310 } 1311 1312 /* Attach the channel to the same AioContext as the export */ 1313 if (client->exp && client->exp->ctx) { 1314 qio_channel_attach_aio_context(client->ioc, client->exp->ctx); 1315 } 1316 1317 assert(!client->optlen); 1318 trace_nbd_negotiate_success(); 1319 1320 return 0; 1321 } 1322 1323 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request, 1324 Error **errp) 1325 { 1326 uint8_t buf[NBD_REQUEST_SIZE]; 1327 uint32_t magic; 1328 int ret; 1329 1330 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp); 1331 if (ret < 0) { 1332 return ret; 1333 } 1334 1335 /* Request 1336 [ 0 .. 3] magic (NBD_REQUEST_MAGIC) 1337 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...) 1338 [ 6 .. 7] type (NBD_CMD_READ, ...) 1339 [ 8 .. 15] handle 1340 [16 .. 23] from 1341 [24 .. 27] len 1342 */ 1343 1344 magic = ldl_be_p(buf); 1345 request->flags = lduw_be_p(buf + 4); 1346 request->type = lduw_be_p(buf + 6); 1347 request->handle = ldq_be_p(buf + 8); 1348 request->from = ldq_be_p(buf + 16); 1349 request->len = ldl_be_p(buf + 24); 1350 1351 trace_nbd_receive_request(magic, request->flags, request->type, 1352 request->from, request->len); 1353 1354 if (magic != NBD_REQUEST_MAGIC) { 1355 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic); 1356 return -EINVAL; 1357 } 1358 return 0; 1359 } 1360 1361 #define MAX_NBD_REQUESTS 16 1362 1363 void nbd_client_get(NBDClient *client) 1364 { 1365 client->refcount++; 1366 } 1367 1368 void nbd_client_put(NBDClient *client) 1369 { 1370 if (--client->refcount == 0) { 1371 /* The last reference should be dropped by client->close, 1372 * which is called by client_close. 1373 */ 1374 assert(client->closing); 1375 1376 qio_channel_detach_aio_context(client->ioc); 1377 object_unref(OBJECT(client->sioc)); 1378 object_unref(OBJECT(client->ioc)); 1379 if (client->tlscreds) { 1380 object_unref(OBJECT(client->tlscreds)); 1381 } 1382 g_free(client->tlsauthz); 1383 if (client->exp) { 1384 QTAILQ_REMOVE(&client->exp->clients, client, next); 1385 nbd_export_put(client->exp); 1386 } 1387 g_free(client); 1388 } 1389 } 1390 1391 static void client_close(NBDClient *client, bool negotiated) 1392 { 1393 if (client->closing) { 1394 return; 1395 } 1396 1397 client->closing = true; 1398 1399 /* Force requests to finish. They will drop their own references, 1400 * then we'll close the socket and free the NBDClient. 1401 */ 1402 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, 1403 NULL); 1404 1405 /* Also tell the client, so that they release their reference. */ 1406 if (client->close_fn) { 1407 client->close_fn(client, negotiated); 1408 } 1409 } 1410 1411 static NBDRequestData *nbd_request_get(NBDClient *client) 1412 { 1413 NBDRequestData *req; 1414 1415 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1); 1416 client->nb_requests++; 1417 1418 req = g_new0(NBDRequestData, 1); 1419 nbd_client_get(client); 1420 req->client = client; 1421 return req; 1422 } 1423 1424 static void nbd_request_put(NBDRequestData *req) 1425 { 1426 NBDClient *client = req->client; 1427 1428 if (req->data) { 1429 qemu_vfree(req->data); 1430 } 1431 g_free(req); 1432 1433 client->nb_requests--; 1434 nbd_client_receive_next_request(client); 1435 1436 nbd_client_put(client); 1437 } 1438 1439 static void blk_aio_attached(AioContext *ctx, void *opaque) 1440 { 1441 NBDExport *exp = opaque; 1442 NBDClient *client; 1443 1444 trace_nbd_blk_aio_attached(exp->name, ctx); 1445 1446 exp->ctx = ctx; 1447 1448 QTAILQ_FOREACH(client, &exp->clients, next) { 1449 qio_channel_attach_aio_context(client->ioc, ctx); 1450 if (client->recv_coroutine) { 1451 aio_co_schedule(ctx, client->recv_coroutine); 1452 } 1453 if (client->send_coroutine) { 1454 aio_co_schedule(ctx, client->send_coroutine); 1455 } 1456 } 1457 } 1458 1459 static void blk_aio_detach(void *opaque) 1460 { 1461 NBDExport *exp = opaque; 1462 NBDClient *client; 1463 1464 trace_nbd_blk_aio_detach(exp->name, exp->ctx); 1465 1466 QTAILQ_FOREACH(client, &exp->clients, next) { 1467 qio_channel_detach_aio_context(client->ioc); 1468 } 1469 1470 exp->ctx = NULL; 1471 } 1472 1473 static void nbd_eject_notifier(Notifier *n, void *data) 1474 { 1475 NBDExport *exp = container_of(n, NBDExport, eject_notifier); 1476 AioContext *aio_context; 1477 1478 aio_context = exp->ctx; 1479 aio_context_acquire(aio_context); 1480 nbd_export_close(exp); 1481 aio_context_release(aio_context); 1482 } 1483 1484 NBDExport *nbd_export_new(BlockDriverState *bs, uint64_t dev_offset, 1485 uint64_t size, const char *name, const char *desc, 1486 const char *bitmap, bool readonly, bool shared, 1487 void (*close)(NBDExport *), bool writethrough, 1488 BlockBackend *on_eject_blk, Error **errp) 1489 { 1490 AioContext *ctx; 1491 BlockBackend *blk; 1492 NBDExport *exp = g_new0(NBDExport, 1); 1493 uint64_t perm; 1494 int ret; 1495 1496 /* 1497 * NBD exports are used for non-shared storage migration. Make sure 1498 * that BDRV_O_INACTIVE is cleared and the image is ready for write 1499 * access since the export could be available before migration handover. 1500 * ctx was acquired in the caller. 1501 */ 1502 assert(name && strlen(name) <= NBD_MAX_STRING_SIZE); 1503 ctx = bdrv_get_aio_context(bs); 1504 bdrv_invalidate_cache(bs, NULL); 1505 1506 /* Don't allow resize while the NBD server is running, otherwise we don't 1507 * care what happens with the node. */ 1508 perm = BLK_PERM_CONSISTENT_READ; 1509 if (!readonly) { 1510 perm |= BLK_PERM_WRITE; 1511 } 1512 blk = blk_new(ctx, perm, 1513 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED | 1514 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD); 1515 ret = blk_insert_bs(blk, bs, errp); 1516 if (ret < 0) { 1517 goto fail; 1518 } 1519 blk_set_enable_write_cache(blk, !writethrough); 1520 blk_set_allow_aio_context_change(blk, true); 1521 1522 exp->refcount = 1; 1523 QTAILQ_INIT(&exp->clients); 1524 exp->blk = blk; 1525 assert(dev_offset <= INT64_MAX); 1526 exp->dev_offset = dev_offset; 1527 exp->name = g_strdup(name); 1528 assert(!desc || strlen(desc) <= NBD_MAX_STRING_SIZE); 1529 exp->description = g_strdup(desc); 1530 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH | 1531 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE); 1532 if (readonly) { 1533 exp->nbdflags |= NBD_FLAG_READ_ONLY; 1534 if (shared) { 1535 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN; 1536 } 1537 } else { 1538 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES | 1539 NBD_FLAG_SEND_FAST_ZERO); 1540 } 1541 assert(size <= INT64_MAX - dev_offset); 1542 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE); 1543 1544 if (bitmap) { 1545 BdrvDirtyBitmap *bm = NULL; 1546 1547 while (true) { 1548 bm = bdrv_find_dirty_bitmap(bs, bitmap); 1549 if (bm != NULL || bs->backing == NULL) { 1550 break; 1551 } 1552 1553 bs = bs->backing->bs; 1554 } 1555 1556 if (bm == NULL) { 1557 error_setg(errp, "Bitmap '%s' is not found", bitmap); 1558 goto fail; 1559 } 1560 1561 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) { 1562 goto fail; 1563 } 1564 1565 if (readonly && bdrv_is_writable(bs) && 1566 bdrv_dirty_bitmap_enabled(bm)) { 1567 error_setg(errp, 1568 "Enabled bitmap '%s' incompatible with readonly export", 1569 bitmap); 1570 goto fail; 1571 } 1572 1573 bdrv_dirty_bitmap_set_busy(bm, true); 1574 exp->export_bitmap = bm; 1575 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE); 1576 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s", 1577 bitmap); 1578 assert(strlen(exp->export_bitmap_context) < NBD_MAX_STRING_SIZE); 1579 } 1580 1581 exp->close = close; 1582 exp->ctx = ctx; 1583 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp); 1584 1585 if (on_eject_blk) { 1586 blk_ref(on_eject_blk); 1587 exp->eject_notifier_blk = on_eject_blk; 1588 exp->eject_notifier.notify = nbd_eject_notifier; 1589 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier); 1590 } 1591 QTAILQ_INSERT_TAIL(&exports, exp, next); 1592 nbd_export_get(exp); 1593 return exp; 1594 1595 fail: 1596 blk_unref(blk); 1597 g_free(exp->name); 1598 g_free(exp->description); 1599 g_free(exp); 1600 return NULL; 1601 } 1602 1603 NBDExport *nbd_export_find(const char *name) 1604 { 1605 NBDExport *exp; 1606 QTAILQ_FOREACH(exp, &exports, next) { 1607 if (strcmp(name, exp->name) == 0) { 1608 return exp; 1609 } 1610 } 1611 1612 return NULL; 1613 } 1614 1615 AioContext * 1616 nbd_export_aio_context(NBDExport *exp) 1617 { 1618 return exp->ctx; 1619 } 1620 1621 void nbd_export_close(NBDExport *exp) 1622 { 1623 NBDClient *client, *next; 1624 1625 nbd_export_get(exp); 1626 /* 1627 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a 1628 * close mode that stops advertising the export to new clients but 1629 * still permits existing clients to run to completion? Because of 1630 * that possibility, nbd_export_close() can be called more than 1631 * once on an export. 1632 */ 1633 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) { 1634 client_close(client, true); 1635 } 1636 if (exp->name) { 1637 nbd_export_put(exp); 1638 g_free(exp->name); 1639 exp->name = NULL; 1640 QTAILQ_REMOVE(&exports, exp, next); 1641 } 1642 g_free(exp->description); 1643 exp->description = NULL; 1644 nbd_export_put(exp); 1645 } 1646 1647 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp) 1648 { 1649 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) { 1650 nbd_export_close(exp); 1651 return; 1652 } 1653 1654 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE); 1655 1656 error_setg(errp, "export '%s' still in use", exp->name); 1657 error_append_hint(errp, "Use mode='hard' to force client disconnect\n"); 1658 } 1659 1660 void nbd_export_get(NBDExport *exp) 1661 { 1662 assert(exp->refcount > 0); 1663 exp->refcount++; 1664 } 1665 1666 void nbd_export_put(NBDExport *exp) 1667 { 1668 assert(exp->refcount > 0); 1669 if (exp->refcount == 1) { 1670 nbd_export_close(exp); 1671 } 1672 1673 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen 1674 * if someone calls nbd_export_put() on named export not through 1675 * nbd_export_set_name() when refcount is 1. So, let's assert that 1676 * it is > 0. 1677 */ 1678 assert(exp->refcount > 0); 1679 if (--exp->refcount == 0) { 1680 assert(exp->name == NULL); 1681 assert(exp->description == NULL); 1682 1683 if (exp->close) { 1684 exp->close(exp); 1685 } 1686 1687 if (exp->blk) { 1688 if (exp->eject_notifier_blk) { 1689 notifier_remove(&exp->eject_notifier); 1690 blk_unref(exp->eject_notifier_blk); 1691 } 1692 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached, 1693 blk_aio_detach, exp); 1694 blk_unref(exp->blk); 1695 exp->blk = NULL; 1696 } 1697 1698 if (exp->export_bitmap) { 1699 bdrv_dirty_bitmap_set_busy(exp->export_bitmap, false); 1700 g_free(exp->export_bitmap_context); 1701 } 1702 1703 g_free(exp); 1704 } 1705 } 1706 1707 BlockBackend *nbd_export_get_blockdev(NBDExport *exp) 1708 { 1709 return exp->blk; 1710 } 1711 1712 void nbd_export_close_all(void) 1713 { 1714 NBDExport *exp, *next; 1715 AioContext *aio_context; 1716 1717 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) { 1718 aio_context = exp->ctx; 1719 aio_context_acquire(aio_context); 1720 nbd_export_close(exp); 1721 aio_context_release(aio_context); 1722 } 1723 } 1724 1725 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov, 1726 unsigned niov, Error **errp) 1727 { 1728 int ret; 1729 1730 g_assert(qemu_in_coroutine()); 1731 qemu_co_mutex_lock(&client->send_lock); 1732 client->send_coroutine = qemu_coroutine_self(); 1733 1734 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0; 1735 1736 client->send_coroutine = NULL; 1737 qemu_co_mutex_unlock(&client->send_lock); 1738 1739 return ret; 1740 } 1741 1742 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error, 1743 uint64_t handle) 1744 { 1745 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC); 1746 stl_be_p(&reply->error, error); 1747 stq_be_p(&reply->handle, handle); 1748 } 1749 1750 static int nbd_co_send_simple_reply(NBDClient *client, 1751 uint64_t handle, 1752 uint32_t error, 1753 void *data, 1754 size_t len, 1755 Error **errp) 1756 { 1757 NBDSimpleReply reply; 1758 int nbd_err = system_errno_to_nbd_errno(error); 1759 struct iovec iov[] = { 1760 {.iov_base = &reply, .iov_len = sizeof(reply)}, 1761 {.iov_base = data, .iov_len = len} 1762 }; 1763 1764 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err), 1765 len); 1766 set_be_simple_reply(&reply, nbd_err, handle); 1767 1768 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp); 1769 } 1770 1771 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags, 1772 uint16_t type, uint64_t handle, uint32_t length) 1773 { 1774 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC); 1775 stw_be_p(&chunk->flags, flags); 1776 stw_be_p(&chunk->type, type); 1777 stq_be_p(&chunk->handle, handle); 1778 stl_be_p(&chunk->length, length); 1779 } 1780 1781 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client, 1782 uint64_t handle, 1783 Error **errp) 1784 { 1785 NBDStructuredReplyChunk chunk; 1786 struct iovec iov[] = { 1787 {.iov_base = &chunk, .iov_len = sizeof(chunk)}, 1788 }; 1789 1790 trace_nbd_co_send_structured_done(handle); 1791 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0); 1792 1793 return nbd_co_send_iov(client, iov, 1, errp); 1794 } 1795 1796 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client, 1797 uint64_t handle, 1798 uint64_t offset, 1799 void *data, 1800 size_t size, 1801 bool final, 1802 Error **errp) 1803 { 1804 NBDStructuredReadData chunk; 1805 struct iovec iov[] = { 1806 {.iov_base = &chunk, .iov_len = sizeof(chunk)}, 1807 {.iov_base = data, .iov_len = size} 1808 }; 1809 1810 assert(size); 1811 trace_nbd_co_send_structured_read(handle, offset, data, size); 1812 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0, 1813 NBD_REPLY_TYPE_OFFSET_DATA, handle, 1814 sizeof(chunk) - sizeof(chunk.h) + size); 1815 stq_be_p(&chunk.offset, offset); 1816 1817 return nbd_co_send_iov(client, iov, 2, errp); 1818 } 1819 1820 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client, 1821 uint64_t handle, 1822 uint32_t error, 1823 const char *msg, 1824 Error **errp) 1825 { 1826 NBDStructuredError chunk; 1827 int nbd_err = system_errno_to_nbd_errno(error); 1828 struct iovec iov[] = { 1829 {.iov_base = &chunk, .iov_len = sizeof(chunk)}, 1830 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0}, 1831 }; 1832 1833 assert(nbd_err); 1834 trace_nbd_co_send_structured_error(handle, nbd_err, 1835 nbd_err_lookup(nbd_err), msg ? msg : ""); 1836 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle, 1837 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len); 1838 stl_be_p(&chunk.error, nbd_err); 1839 stw_be_p(&chunk.message_length, iov[1].iov_len); 1840 1841 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp); 1842 } 1843 1844 /* Do a sparse read and send the structured reply to the client. 1845 * Returns -errno if sending fails. bdrv_block_status_above() failure is 1846 * reported to the client, at which point this function succeeds. 1847 */ 1848 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client, 1849 uint64_t handle, 1850 uint64_t offset, 1851 uint8_t *data, 1852 size_t size, 1853 Error **errp) 1854 { 1855 int ret = 0; 1856 NBDExport *exp = client->exp; 1857 size_t progress = 0; 1858 1859 while (progress < size) { 1860 int64_t pnum; 1861 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL, 1862 offset + progress, 1863 size - progress, &pnum, NULL, 1864 NULL); 1865 bool final; 1866 1867 if (status < 0) { 1868 char *msg = g_strdup_printf("unable to check for holes: %s", 1869 strerror(-status)); 1870 1871 ret = nbd_co_send_structured_error(client, handle, -status, msg, 1872 errp); 1873 g_free(msg); 1874 return ret; 1875 } 1876 assert(pnum && pnum <= size - progress); 1877 final = progress + pnum == size; 1878 if (status & BDRV_BLOCK_ZERO) { 1879 NBDStructuredReadHole chunk; 1880 struct iovec iov[] = { 1881 {.iov_base = &chunk, .iov_len = sizeof(chunk)}, 1882 }; 1883 1884 trace_nbd_co_send_structured_read_hole(handle, offset + progress, 1885 pnum); 1886 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0, 1887 NBD_REPLY_TYPE_OFFSET_HOLE, 1888 handle, sizeof(chunk) - sizeof(chunk.h)); 1889 stq_be_p(&chunk.offset, offset + progress); 1890 stl_be_p(&chunk.length, pnum); 1891 ret = nbd_co_send_iov(client, iov, 1, errp); 1892 } else { 1893 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset, 1894 data + progress, pnum); 1895 if (ret < 0) { 1896 error_setg_errno(errp, -ret, "reading from file failed"); 1897 break; 1898 } 1899 ret = nbd_co_send_structured_read(client, handle, offset + progress, 1900 data + progress, pnum, final, 1901 errp); 1902 } 1903 1904 if (ret < 0) { 1905 break; 1906 } 1907 progress += pnum; 1908 } 1909 return ret; 1910 } 1911 1912 /* 1913 * Populate @extents from block status. Update @bytes to be the actual 1914 * length encoded (which may be smaller than the original), and update 1915 * @nb_extents to the number of extents used. 1916 * 1917 * Returns zero on success and -errno on bdrv_block_status_above failure. 1918 */ 1919 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset, 1920 uint64_t *bytes, NBDExtent *extents, 1921 unsigned int *nb_extents) 1922 { 1923 uint64_t remaining_bytes = *bytes; 1924 NBDExtent *extent = extents, *extents_end = extents + *nb_extents; 1925 bool first_extent = true; 1926 1927 assert(*nb_extents); 1928 while (remaining_bytes) { 1929 uint32_t flags; 1930 int64_t num; 1931 int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes, 1932 &num, NULL, NULL); 1933 1934 if (ret < 0) { 1935 return ret; 1936 } 1937 1938 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) | 1939 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0); 1940 1941 if (first_extent) { 1942 extent->flags = flags; 1943 extent->length = num; 1944 first_extent = false; 1945 } else if (flags == extent->flags) { 1946 /* extend current extent */ 1947 extent->length += num; 1948 } else { 1949 if (extent + 1 == extents_end) { 1950 break; 1951 } 1952 1953 /* start new extent */ 1954 extent++; 1955 extent->flags = flags; 1956 extent->length = num; 1957 } 1958 offset += num; 1959 remaining_bytes -= num; 1960 } 1961 1962 extents_end = extent + 1; 1963 1964 for (extent = extents; extent < extents_end; extent++) { 1965 extent->flags = cpu_to_be32(extent->flags); 1966 extent->length = cpu_to_be32(extent->length); 1967 } 1968 1969 *bytes -= remaining_bytes; 1970 *nb_extents = extents_end - extents; 1971 1972 return 0; 1973 } 1974 1975 /* nbd_co_send_extents 1976 * 1977 * @length is only for tracing purposes (and may be smaller or larger 1978 * than the client's original request). @last controls whether 1979 * NBD_REPLY_FLAG_DONE is sent. @extents should already be in 1980 * big-endian format. 1981 */ 1982 static int nbd_co_send_extents(NBDClient *client, uint64_t handle, 1983 NBDExtent *extents, unsigned int nb_extents, 1984 uint64_t length, bool last, 1985 uint32_t context_id, Error **errp) 1986 { 1987 NBDStructuredMeta chunk; 1988 1989 struct iovec iov[] = { 1990 {.iov_base = &chunk, .iov_len = sizeof(chunk)}, 1991 {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])} 1992 }; 1993 1994 trace_nbd_co_send_extents(handle, nb_extents, context_id, length, last); 1995 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0, 1996 NBD_REPLY_TYPE_BLOCK_STATUS, 1997 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len); 1998 stl_be_p(&chunk.context_id, context_id); 1999 2000 return nbd_co_send_iov(client, iov, 2, errp); 2001 } 2002 2003 /* Get block status from the exported device and send it to the client */ 2004 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle, 2005 BlockDriverState *bs, uint64_t offset, 2006 uint32_t length, bool dont_fragment, 2007 bool last, uint32_t context_id, 2008 Error **errp) 2009 { 2010 int ret; 2011 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS; 2012 NBDExtent *extents = g_new(NBDExtent, nb_extents); 2013 uint64_t final_length = length; 2014 2015 ret = blockstatus_to_extents(bs, offset, &final_length, extents, 2016 &nb_extents); 2017 if (ret < 0) { 2018 g_free(extents); 2019 return nbd_co_send_structured_error( 2020 client, handle, -ret, "can't get block status", errp); 2021 } 2022 2023 ret = nbd_co_send_extents(client, handle, extents, nb_extents, 2024 final_length, last, context_id, errp); 2025 2026 g_free(extents); 2027 2028 return ret; 2029 } 2030 2031 /* 2032 * Populate @extents from a dirty bitmap. Unless @dont_fragment, the 2033 * final extent may exceed the original @length. Store in @length the 2034 * byte length encoded (which may be smaller or larger than the 2035 * original), and return the number of extents used. 2036 */ 2037 static unsigned int bitmap_to_extents(BdrvDirtyBitmap *bitmap, uint64_t offset, 2038 uint64_t *length, NBDExtent *extents, 2039 unsigned int nb_extents, 2040 bool dont_fragment) 2041 { 2042 uint64_t begin = offset, end = offset; 2043 uint64_t overall_end = offset + *length; 2044 unsigned int i = 0; 2045 BdrvDirtyBitmapIter *it; 2046 bool dirty; 2047 2048 bdrv_dirty_bitmap_lock(bitmap); 2049 2050 it = bdrv_dirty_iter_new(bitmap); 2051 dirty = bdrv_dirty_bitmap_get_locked(bitmap, offset); 2052 2053 assert(begin < overall_end && nb_extents); 2054 while (begin < overall_end && i < nb_extents) { 2055 bool next_dirty = !dirty; 2056 2057 if (dirty) { 2058 end = bdrv_dirty_bitmap_next_zero(bitmap, begin, UINT64_MAX); 2059 } else { 2060 bdrv_set_dirty_iter(it, begin); 2061 end = bdrv_dirty_iter_next(it); 2062 } 2063 if (end == -1 || end - begin > UINT32_MAX) { 2064 /* Cap to an aligned value < 4G beyond begin. */ 2065 end = MIN(bdrv_dirty_bitmap_size(bitmap), 2066 begin + UINT32_MAX + 1 - 2067 bdrv_dirty_bitmap_granularity(bitmap)); 2068 next_dirty = dirty; 2069 } 2070 if (dont_fragment && end > overall_end) { 2071 end = overall_end; 2072 } 2073 2074 extents[i].length = cpu_to_be32(end - begin); 2075 extents[i].flags = cpu_to_be32(dirty ? NBD_STATE_DIRTY : 0); 2076 i++; 2077 begin = end; 2078 dirty = next_dirty; 2079 } 2080 2081 bdrv_dirty_iter_free(it); 2082 2083 bdrv_dirty_bitmap_unlock(bitmap); 2084 2085 assert(offset < end); 2086 *length = end - offset; 2087 return i; 2088 } 2089 2090 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle, 2091 BdrvDirtyBitmap *bitmap, uint64_t offset, 2092 uint32_t length, bool dont_fragment, bool last, 2093 uint32_t context_id, Error **errp) 2094 { 2095 int ret; 2096 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS; 2097 NBDExtent *extents = g_new(NBDExtent, nb_extents); 2098 uint64_t final_length = length; 2099 2100 nb_extents = bitmap_to_extents(bitmap, offset, &final_length, extents, 2101 nb_extents, dont_fragment); 2102 2103 ret = nbd_co_send_extents(client, handle, extents, nb_extents, 2104 final_length, last, context_id, errp); 2105 2106 g_free(extents); 2107 2108 return ret; 2109 } 2110 2111 /* nbd_co_receive_request 2112 * Collect a client request. Return 0 if request looks valid, -EIO to drop 2113 * connection right away, and any other negative value to report an error to 2114 * the client (although the caller may still need to disconnect after reporting 2115 * the error). 2116 */ 2117 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request, 2118 Error **errp) 2119 { 2120 NBDClient *client = req->client; 2121 int valid_flags; 2122 2123 g_assert(qemu_in_coroutine()); 2124 assert(client->recv_coroutine == qemu_coroutine_self()); 2125 if (nbd_receive_request(client->ioc, request, errp) < 0) { 2126 return -EIO; 2127 } 2128 2129 trace_nbd_co_receive_request_decode_type(request->handle, request->type, 2130 nbd_cmd_lookup(request->type)); 2131 2132 if (request->type != NBD_CMD_WRITE) { 2133 /* No payload, we are ready to read the next request. */ 2134 req->complete = true; 2135 } 2136 2137 if (request->type == NBD_CMD_DISC) { 2138 /* Special case: we're going to disconnect without a reply, 2139 * whether or not flags, from, or len are bogus */ 2140 return -EIO; 2141 } 2142 2143 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE || 2144 request->type == NBD_CMD_CACHE) 2145 { 2146 if (request->len > NBD_MAX_BUFFER_SIZE) { 2147 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)", 2148 request->len, NBD_MAX_BUFFER_SIZE); 2149 return -EINVAL; 2150 } 2151 2152 if (request->type != NBD_CMD_CACHE) { 2153 req->data = blk_try_blockalign(client->exp->blk, request->len); 2154 if (req->data == NULL) { 2155 error_setg(errp, "No memory"); 2156 return -ENOMEM; 2157 } 2158 } 2159 } 2160 2161 if (request->type == NBD_CMD_WRITE) { 2162 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data", 2163 errp) < 0) 2164 { 2165 return -EIO; 2166 } 2167 req->complete = true; 2168 2169 trace_nbd_co_receive_request_payload_received(request->handle, 2170 request->len); 2171 } 2172 2173 /* Sanity checks. */ 2174 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY && 2175 (request->type == NBD_CMD_WRITE || 2176 request->type == NBD_CMD_WRITE_ZEROES || 2177 request->type == NBD_CMD_TRIM)) { 2178 error_setg(errp, "Export is read-only"); 2179 return -EROFS; 2180 } 2181 if (request->from > client->exp->size || 2182 request->len > client->exp->size - request->from) { 2183 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32 2184 ", Size: %" PRIu64, request->from, request->len, 2185 client->exp->size); 2186 return (request->type == NBD_CMD_WRITE || 2187 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL; 2188 } 2189 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len, 2190 client->check_align)) { 2191 /* 2192 * The block layer gracefully handles unaligned requests, but 2193 * it's still worth tracing client non-compliance 2194 */ 2195 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type), 2196 request->from, 2197 request->len, 2198 client->check_align); 2199 } 2200 valid_flags = NBD_CMD_FLAG_FUA; 2201 if (request->type == NBD_CMD_READ && client->structured_reply) { 2202 valid_flags |= NBD_CMD_FLAG_DF; 2203 } else if (request->type == NBD_CMD_WRITE_ZEROES) { 2204 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO; 2205 } else if (request->type == NBD_CMD_BLOCK_STATUS) { 2206 valid_flags |= NBD_CMD_FLAG_REQ_ONE; 2207 } 2208 if (request->flags & ~valid_flags) { 2209 error_setg(errp, "unsupported flags for command %s (got 0x%x)", 2210 nbd_cmd_lookup(request->type), request->flags); 2211 return -EINVAL; 2212 } 2213 2214 return 0; 2215 } 2216 2217 /* Send simple reply without a payload, or a structured error 2218 * @error_msg is ignored if @ret >= 0 2219 * Returns 0 if connection is still live, -errno on failure to talk to client 2220 */ 2221 static coroutine_fn int nbd_send_generic_reply(NBDClient *client, 2222 uint64_t handle, 2223 int ret, 2224 const char *error_msg, 2225 Error **errp) 2226 { 2227 if (client->structured_reply && ret < 0) { 2228 return nbd_co_send_structured_error(client, handle, -ret, error_msg, 2229 errp); 2230 } else { 2231 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0, 2232 NULL, 0, errp); 2233 } 2234 } 2235 2236 /* Handle NBD_CMD_READ request. 2237 * Return -errno if sending fails. Other errors are reported directly to the 2238 * client as an error reply. */ 2239 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request, 2240 uint8_t *data, Error **errp) 2241 { 2242 int ret; 2243 NBDExport *exp = client->exp; 2244 2245 assert(request->type == NBD_CMD_READ); 2246 2247 /* XXX: NBD Protocol only documents use of FUA with WRITE */ 2248 if (request->flags & NBD_CMD_FLAG_FUA) { 2249 ret = blk_co_flush(exp->blk); 2250 if (ret < 0) { 2251 return nbd_send_generic_reply(client, request->handle, ret, 2252 "flush failed", errp); 2253 } 2254 } 2255 2256 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) && 2257 request->len) 2258 { 2259 return nbd_co_send_sparse_read(client, request->handle, request->from, 2260 data, request->len, errp); 2261 } 2262 2263 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data, 2264 request->len); 2265 if (ret < 0) { 2266 return nbd_send_generic_reply(client, request->handle, ret, 2267 "reading from file failed", errp); 2268 } 2269 2270 if (client->structured_reply) { 2271 if (request->len) { 2272 return nbd_co_send_structured_read(client, request->handle, 2273 request->from, data, 2274 request->len, true, errp); 2275 } else { 2276 return nbd_co_send_structured_done(client, request->handle, errp); 2277 } 2278 } else { 2279 return nbd_co_send_simple_reply(client, request->handle, 0, 2280 data, request->len, errp); 2281 } 2282 } 2283 2284 /* 2285 * nbd_do_cmd_cache 2286 * 2287 * Handle NBD_CMD_CACHE request. 2288 * Return -errno if sending fails. Other errors are reported directly to the 2289 * client as an error reply. 2290 */ 2291 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request, 2292 Error **errp) 2293 { 2294 int ret; 2295 NBDExport *exp = client->exp; 2296 2297 assert(request->type == NBD_CMD_CACHE); 2298 2299 ret = blk_co_preadv(exp->blk, request->from + exp->dev_offset, request->len, 2300 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH); 2301 2302 return nbd_send_generic_reply(client, request->handle, ret, 2303 "caching data failed", errp); 2304 } 2305 2306 /* Handle NBD request. 2307 * Return -errno if sending fails. Other errors are reported directly to the 2308 * client as an error reply. */ 2309 static coroutine_fn int nbd_handle_request(NBDClient *client, 2310 NBDRequest *request, 2311 uint8_t *data, Error **errp) 2312 { 2313 int ret; 2314 int flags; 2315 NBDExport *exp = client->exp; 2316 char *msg; 2317 2318 switch (request->type) { 2319 case NBD_CMD_CACHE: 2320 return nbd_do_cmd_cache(client, request, errp); 2321 2322 case NBD_CMD_READ: 2323 return nbd_do_cmd_read(client, request, data, errp); 2324 2325 case NBD_CMD_WRITE: 2326 flags = 0; 2327 if (request->flags & NBD_CMD_FLAG_FUA) { 2328 flags |= BDRV_REQ_FUA; 2329 } 2330 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset, 2331 data, request->len, flags); 2332 return nbd_send_generic_reply(client, request->handle, ret, 2333 "writing to file failed", errp); 2334 2335 case NBD_CMD_WRITE_ZEROES: 2336 flags = 0; 2337 if (request->flags & NBD_CMD_FLAG_FUA) { 2338 flags |= BDRV_REQ_FUA; 2339 } 2340 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) { 2341 flags |= BDRV_REQ_MAY_UNMAP; 2342 } 2343 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) { 2344 flags |= BDRV_REQ_NO_FALLBACK; 2345 } 2346 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset, 2347 request->len, flags); 2348 return nbd_send_generic_reply(client, request->handle, ret, 2349 "writing to file failed", errp); 2350 2351 case NBD_CMD_DISC: 2352 /* unreachable, thanks to special case in nbd_co_receive_request() */ 2353 abort(); 2354 2355 case NBD_CMD_FLUSH: 2356 ret = blk_co_flush(exp->blk); 2357 return nbd_send_generic_reply(client, request->handle, ret, 2358 "flush failed", errp); 2359 2360 case NBD_CMD_TRIM: 2361 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset, 2362 request->len); 2363 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) { 2364 ret = blk_co_flush(exp->blk); 2365 } 2366 return nbd_send_generic_reply(client, request->handle, ret, 2367 "discard failed", errp); 2368 2369 case NBD_CMD_BLOCK_STATUS: 2370 if (!request->len) { 2371 return nbd_send_generic_reply(client, request->handle, -EINVAL, 2372 "need non-zero length", errp); 2373 } 2374 if (client->export_meta.valid && 2375 (client->export_meta.base_allocation || 2376 client->export_meta.bitmap)) 2377 { 2378 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE; 2379 2380 if (client->export_meta.base_allocation) { 2381 ret = nbd_co_send_block_status(client, request->handle, 2382 blk_bs(exp->blk), request->from, 2383 request->len, dont_fragment, 2384 !client->export_meta.bitmap, 2385 NBD_META_ID_BASE_ALLOCATION, 2386 errp); 2387 if (ret < 0) { 2388 return ret; 2389 } 2390 } 2391 2392 if (client->export_meta.bitmap) { 2393 ret = nbd_co_send_bitmap(client, request->handle, 2394 client->exp->export_bitmap, 2395 request->from, request->len, 2396 dont_fragment, 2397 true, NBD_META_ID_DIRTY_BITMAP, errp); 2398 if (ret < 0) { 2399 return ret; 2400 } 2401 } 2402 2403 return 0; 2404 } else { 2405 return nbd_send_generic_reply(client, request->handle, -EINVAL, 2406 "CMD_BLOCK_STATUS not negotiated", 2407 errp); 2408 } 2409 2410 default: 2411 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received", 2412 request->type); 2413 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg, 2414 errp); 2415 g_free(msg); 2416 return ret; 2417 } 2418 } 2419 2420 /* Owns a reference to the NBDClient passed as opaque. */ 2421 static coroutine_fn void nbd_trip(void *opaque) 2422 { 2423 NBDClient *client = opaque; 2424 NBDRequestData *req; 2425 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */ 2426 int ret; 2427 Error *local_err = NULL; 2428 2429 trace_nbd_trip(); 2430 if (client->closing) { 2431 nbd_client_put(client); 2432 return; 2433 } 2434 2435 req = nbd_request_get(client); 2436 ret = nbd_co_receive_request(req, &request, &local_err); 2437 client->recv_coroutine = NULL; 2438 2439 if (client->closing) { 2440 /* 2441 * The client may be closed when we are blocked in 2442 * nbd_co_receive_request() 2443 */ 2444 goto done; 2445 } 2446 2447 nbd_client_receive_next_request(client); 2448 if (ret == -EIO) { 2449 goto disconnect; 2450 } 2451 2452 if (ret < 0) { 2453 /* It wans't -EIO, so, according to nbd_co_receive_request() 2454 * semantics, we should return the error to the client. */ 2455 Error *export_err = local_err; 2456 2457 local_err = NULL; 2458 ret = nbd_send_generic_reply(client, request.handle, -EINVAL, 2459 error_get_pretty(export_err), &local_err); 2460 error_free(export_err); 2461 } else { 2462 ret = nbd_handle_request(client, &request, req->data, &local_err); 2463 } 2464 if (ret < 0) { 2465 error_prepend(&local_err, "Failed to send reply: "); 2466 goto disconnect; 2467 } 2468 2469 /* We must disconnect after NBD_CMD_WRITE if we did not 2470 * read the payload. 2471 */ 2472 if (!req->complete) { 2473 error_setg(&local_err, "Request handling failed in intermediate state"); 2474 goto disconnect; 2475 } 2476 2477 done: 2478 nbd_request_put(req); 2479 nbd_client_put(client); 2480 return; 2481 2482 disconnect: 2483 if (local_err) { 2484 error_reportf_err(local_err, "Disconnect client, due to: "); 2485 } 2486 nbd_request_put(req); 2487 client_close(client, true); 2488 nbd_client_put(client); 2489 } 2490 2491 static void nbd_client_receive_next_request(NBDClient *client) 2492 { 2493 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) { 2494 nbd_client_get(client); 2495 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client); 2496 aio_co_schedule(client->exp->ctx, client->recv_coroutine); 2497 } 2498 } 2499 2500 static coroutine_fn void nbd_co_client_start(void *opaque) 2501 { 2502 NBDClient *client = opaque; 2503 Error *local_err = NULL; 2504 2505 qemu_co_mutex_init(&client->send_lock); 2506 2507 if (nbd_negotiate(client, &local_err)) { 2508 if (local_err) { 2509 error_report_err(local_err); 2510 } 2511 client_close(client, false); 2512 return; 2513 } 2514 2515 nbd_client_receive_next_request(client); 2516 } 2517 2518 /* 2519 * Create a new client listener using the given channel @sioc. 2520 * Begin servicing it in a coroutine. When the connection closes, call 2521 * @close_fn with an indication of whether the client completed negotiation. 2522 */ 2523 void nbd_client_new(QIOChannelSocket *sioc, 2524 QCryptoTLSCreds *tlscreds, 2525 const char *tlsauthz, 2526 void (*close_fn)(NBDClient *, bool)) 2527 { 2528 NBDClient *client; 2529 Coroutine *co; 2530 2531 client = g_new0(NBDClient, 1); 2532 client->refcount = 1; 2533 client->tlscreds = tlscreds; 2534 if (tlscreds) { 2535 object_ref(OBJECT(client->tlscreds)); 2536 } 2537 client->tlsauthz = g_strdup(tlsauthz); 2538 client->sioc = sioc; 2539 object_ref(OBJECT(client->sioc)); 2540 client->ioc = QIO_CHANNEL(sioc); 2541 object_ref(OBJECT(client->ioc)); 2542 client->close_fn = close_fn; 2543 2544 co = qemu_coroutine_create(nbd_co_client_start, client); 2545 qemu_coroutine_enter(co); 2546 } 2547