3 libnbd - network block device (NBD) client library in userspace
9 struct nbd_handle *nbd;
12 if ((nbd = nbd_create ()) == NULL ||
13 nbd_connect_tcp (nbd, "server.example.com", "nbd") == -1 ||
14 nbd_pread (nbd, buf, sizeof buf, 0, 0) == -1)
15 fprintf (stderr, "%s\n", nbd_get_error ());
23 cc prog.c -o prog -lnbd
25 cc prog.c -o prog `pkg-config libnbd --cflags --libs`
29 Network Block Device (NBD) is a network protocol for accessing block
30 devices over the network. Block devices are hard disks and things
31 that behave like hard disks such as disk images and virtual machines.
33 Libnbd is a client library for the NBD protocol which can access most
34 of the features of NBD while being simple to use and powerful.
36 This manual page gives an overview of libnbd, using C as an example,
37 but the library is available from other programming languages.
41 =item L<nbd_create(3)>, L<nbd_pread(3)>, etc.
43 Each manual page covers one function from the C API in detail. There
44 is a full list in section L</C API> below.
46 =item L<libnbd-ocaml(3)>
48 Using the API from OCaml.
50 =item L<libnbd-golang(3)>
52 Using the API from Go.
56 Using the NBD shell (nbdsh) for command line and Python scripting.
62 To use the API at all you must first open a handle by calling
63 L<nbd_create(3)> (or its equivalent in other languages):
65 struct nbd_handle *nbd;
69 This creates and returns a handle, which is associated with
70 one connection to an NBD server, initially not connected.
72 Each handle is a complex state machine which can be in
73 states such as created, connected to a remote server, handshaking,
74 idle and ready to issue commands, or busy sending or receiving
77 Handles have a name used in debugging messages. The name is normally
78 generated (C<nbd1>, C<nbd2> etc) but you can set a friendly name with
79 L<nbd_set_handle_name(3)>. Also there is a private field in the
80 handle for use by the application, see L<nbd_set_private_data(3)>.
82 When you have finished with the handle you must call L<nbd_close(3)>
83 which closes the underlying socket (if necessary) and frees up all
86 =head1 SYNCHRONOUS VS ASYNCHRONOUS API
88 There are two levels of API available. A simple high level
89 synchronous API lets you give the handle high level instructions like
90 “connect to the server”, “read a block”, “write a block”, etc. Each
91 of these functions will run to completion, blocking the current thread
92 before returning. A more complicated low level non-blocking
93 asynchronous API is also available where you can integrate with
94 L<poll(2)> or another main loop.
96 You can freely mix the two APIs on the same handle. You can also call
97 APIs on a single handle from multiple threads. Single API calls on
98 the handle are atomic — they either take a lock on the handle while
99 they run or are careful to access handle fields atomically.
101 Libnbd does B<not> create its own threads.
103 =head1 USING THE SYNCHRONOUS (“HIGH LEVEL”) API
105 This is the simplest way to use the API, with the possible drawback
106 that each libnbd function blocks until it is finished.
108 Create a handle and connect to the server:
110 struct nbd_handle *nbd;
114 fprintf (stderr, "%s\n", nbd_get_error ());
118 if (nbd_connect_tcp (nbd, "server.example.com", "nbd") == -1) {
119 fprintf (stderr, "%s\n", nbd_get_error ());
124 Read the first sector (512 bytes) from the NBD export:
128 if (nbd_pread (nbd, buf, sizeof buf, 0, 0) == -1) {
129 fprintf (stderr, "%s\n", nbd_get_error ());
138 You can call the high level API from multiple threads, but each libnbd
139 API call takes a lock on the handle and so commands will not run in
142 =head1 USING THE ASYNCHRONOUS (“LOW LEVEL”) API
144 The low level API is useful if you want to use libnbd in non-blocking
145 code; or if you want to issue commands in parallel from multiple
146 threads; or if you need more control especially over having multiple
147 commands in-flight on a single connection.
149 To use the low level API you will need to integrate with L<poll(2)> or
150 another “main loop” such as the GLib main event loop.
152 =head2 Issuing asynchronous commands
154 Use the C<nbd_aio_*> variants to issue commands asynchronously
155 (without waiting for the command to complete before returning). For
156 example the asynchronous variant of L<nbd_pread(3)> is:
160 cookie = nbd_aio_pread (nbd, buf, sizeof buf,
161 NBD_NULL_COMPLETION, 0);
163 fprintf (stderr, "%s\n", nbd_get_error ());
168 There are several things to note here:
174 This only starts the command. The command is still in flight when the
179 A buffer (C<buf>) has been assigned to collect the result of the read,
180 but it is not guaranteed to be filled with data until the command has
181 completed (see examples below). The buffer must not be freed until
182 the command has finished running.
186 You can issue multiple commands on the same handle at the same time.
190 A cookie is returned which identifies this command in subsequent
191 calls. The cookie is unique (per libnbd handle) and E<ge> 1.
195 You may register a function which is called when the command
196 completes, see L</Completion callbacks> below. In this case we have
197 specified a null completion callback.
201 =head2 Socket and direction
203 Each libnbd handle has an associated socket (once it has started
204 connecting). You can read the file descriptor of the socket using:
206 int fd = nbd_aio_get_fd (nbd);
208 The socket is non-blocking. Between calls into libnbd it is in the
209 "would block" condition. You can find out if libnbd is expecting to
210 read or write from the socket next by calling:
212 int dir = nbd_aio_get_direction (nbd);
214 which returns one of C<LIBNBD_AIO_DIRECTION_READ>,
215 C<LIBNBD_AIO_DIRECTION_WRITE> or C<LIBNBD_AIO_DIRECTION_BOTH> (=
216 C<READ|WRITE>). And so to set up the next call to L<poll(2)> or other
217 main loop you must translate this to C<POLLIN>, C<POLLOUT> or
218 C<POLLIN|POLLOUT> (or whatever mechanism your main loop uses).
220 =head2 Notifying libnbd when an event happens
222 When you detect (eg. using L<poll(2)>) that a read or write event has
223 happened on the socket, you must then tell libnbd about it. You have
224 to check the direction I<again> (since it may have been changed by
225 another thread), and notify libnbd:
229 dir = nbd_aio_get_direction (nbd);
231 if ((dir & LIBNBD_AIO_DIRECTION_READ) &&
232 a_read_event_occurred ())
233 r = nbd_aio_notify_read (nbd);
234 else if ((dir & LIBNBD_AIO_DIRECTION_WRITE) &&
235 a_write_event_occurred ())
236 r = nbd_aio_notify_write (nbd);
239 fprintf (stderr, "%s\n", nbd_get_error ());
243 The notify calls move the state machine along, reading and writing
244 from the socket possibly multiple times, until the socket would block
245 again, at which point they return control to the caller.
247 =head2 Simple implementation with L<nbd_poll(3)>
249 In fact if you want to use L<poll(2)> on a single handle, a simple
250 implementation has already been written called L<nbd_poll(3)>. It is
251 also useful to examine how this is implemented (F<lib/poll.c> in the
252 libnbd source code) because that will tell you how to integrate libnbd
253 with more complex main loops.
255 Some examples of using L<nbd_poll(3)> follow.
257 As with the high level API, it all starts by creating a handle:
259 struct nbd_handle *nbd;
263 fprintf (stderr, "%s\n", nbd_get_error ());
268 To connect to the server asynchronously, we start the connection using
269 L<nbd_aio_connect(3)> and then enter our main loop to check for events
270 until the connection becomes ready:
273 struct sockaddr_un addr;
276 /* some code to set up addr,
278 if (nbd_aio_connect (nbd, &addr, len) == -1) {
279 fprintf (stderr, "%s\n", nbd_get_error ());
283 while (! nbd_aio_is_ready (nbd)) {
284 if (nbd_poll (nbd, -1) == -1) {
285 fprintf (stderr, "%s\n", nbd_get_error ());
291 To read data asynchronously, start an asynchronous read command, which
292 returns a 64 bit command cookie, and enter the main loop until the
293 command has completed:
298 cookie = nbd_aio_pread (nbd, buf, sizeof buf, offset,
299 NBD_NULL_COMPLETION, 0);
301 fprintf (stderr, "%s\n", nbd_get_error ());
305 while (! nbd_aio_command_completed (nbd, cookie)) {
306 if (nbd_poll (nbd, -1) == -1) {
307 fprintf (stderr, "%s\n", nbd_get_error ());
313 For almost all high level synchronous calls (eg. L<nbd_pread(3)>) there
314 is a low level asynchronous equivalent (eg. L<nbd_aio_pread(3)>) for
317 =head2 glib2 integration
320 L<https://gitlab.com/nbdkit/libnbd/blob/master/examples/glib-main-loop.c>
322 =head2 libev integration
325 L<https://gitlab.com/nbdkit/libnbd/blob/master/examples/copy-libev.c>
327 =head1 ERROR HANDLING
329 When any API call returns an error (C<-1> or C<NULL> depending on the
330 API), an error message and sometimes an errno value are available.
331 You can retrieve the error message and/or errno of the most recently
332 failed call using L<nbd_get_error(3)> and L<nbd_get_errno(3)>. For example:
334 if (nbd_connect_tcp (nbd, "remote", "nbd") == -1) {
336 "failed to connect to remote server: %s (errno = %d)\n",
337 nbd_get_error (), nbd_get_errno ());
340 These functions use thread-local storage to return the most recent
341 error in the current thread. This is why you don't need to pass the
342 handle to these calls. They even work if L<nbd_create(3)> returns
343 C<NULL> when there is no handle at all.
345 For this reason you cannot call them from a different thread. You
346 should call them immediately after the failed API call, from the same
347 thread. Furthermore the error string returned by L<nbd_get_error(3)> is
348 only valid until the next libnbd API call in the current thread, so if
349 you need to keep the string you must copy it (eg. using L<strdup(3)>).
353 For some errors, a system call error number (see L<errno(3)>) is
354 available. You can find the error number by calling
355 L<nbd_get_errno(3)>. It works the same way as L<nbd_get_error(3)>
356 with respect to threads.
358 Even when a call returns an error, L<nbd_get_errno(3)> might return
359 C<0>. This does I<not> mean there was no error. It means no
360 additional errno information is available for this error.
362 The error number is often the raw error returned by a system call that
365 It can also be used to indicate special conditions. The most common
372 Invalid parameters or state for the current libnbd call. (This can
373 also indicate that requests are not aligned to
374 L</Block size constraints>).
378 The libnbd call is not available in this build of libnbd (eg. when
379 using a TLS API if the library was compiled without TLS support).
383 The library ran out of memory while performing some operation.
387 A request is too large, for example if you try to read too many bytes
388 in a single L<nbd_pread(3)> call.
392 A pointer parameter was C<NULL> when it should be non-NULL.
393 See the section below.
397 =head2 Non-NULL parameters
399 Almost all libnbd functions when called from C take one or more
400 pointer parameters that must not be C<NULL>. For example, the handle
401 parameter, strings and buffers should usually not be C<NULL>.
403 If a C<NULL> is passed as one of these parameters, libnbd attempts to
404 return an error with L<nbd_get_errno(3)> returning C<EFAULT>.
406 However it may cause other compiler-related warnings and even
407 undefined behaviour, so you should try to avoid this programming
410 =head1 DEBUGGING MESSAGES
412 Libnbd can print lots of debugging messages, useful if you have a
413 problem with the library. Either enable debugging after creating the
417 nbd_set_debug (nbd, true);
419 or set the C<LIBNBD_DEBUG=1> environment variable which will enable
420 debugging by default on all new handles.
422 Debugging messages are sent to stderr by default, but you can redirect
423 them to a logging system using L<nbd_set_debug_callback(3)>.
425 =head1 CONNECTING TO LOCAL OR REMOTE NBD SERVERS
427 There are several ways to connect to NBD servers, and you can even run
428 a server from libnbd. Normally you would connect to a server which is
429 already running, over a local Unix domain socket or a remote TCP
430 connection. The high level API calls are:
432 nbd_connect_unix (nbd, "socket");
433 nbd_connect_tcp (nbd, "localhost", "nbd");
435 For L<nbd_connect_tcp(3)> the third parameter is the port name or number,
436 which can either be a name from F</etc/services> or the port number as
437 a string (eg. C<"10809">).
439 =head2 Connecting to an NBD URI
442 L<NBD URI specification|https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md>.
443 The format of URIs is documented in L<nbd_connect_uri(3)>.
445 You can connect to a URI as in these examples (using the high level
448 nbd_connect_uri (nbd, "nbd://example.com/");
452 nbd_connect_uri (nbd, "nbds+unix:///export?socket=/tmp/nbd.sock");
454 This feature is implemented by calling other libnbd APIs to set up the
455 export name, TLS parameters, and finally connect over a Unix domain
458 URI support is an optional feature of the library, requiring libxml2
459 at compile time. The L<nbd_connect_uri(3)> and
460 L<nbd_aio_connect_uri(3)> calls will raise an error (with
461 L<nbd_get_errno(3)> returning C<ENOTSUP>) if it was not built with
462 this feature, and you can also test for it explicitly using
463 L<nbd_supports_uri(3)>.
465 =head2 Connecting to a subprocess
467 Some NBD servers — notably L<nbdkit(1)> with the I<-s> parameter, and
468 L<nbd-server(1)> with the port parameter set to 0 — can also accept a
469 single NBD connection on stdin/stdout. You can run these servers as a
470 subprocess of your main program using L<nbd_connect_command(3)>. This
471 example creates a 1G writable RAM disk:
473 char *argv[] = { "nbdkit", "-s", "--exit-with-parent",
474 "memory", "1G", NULL };
475 nbd_connect_command (nbd, argv);
477 When the handle is closed the nbdkit subprocess is killed, which in
478 this case means the RAM disk is discarded, so this is useful for
481 =head2 Connecting to a subprocess using systemd socket activation
483 Some NBD servers — notably L<nbdkit(1)> and L<qemu-nbd(1)> — support
484 systemd socket activation allowing libnbd to pass a socket to the
485 subprocess. This works very similarly to L<nbd_connect_command(3)>
486 described above, but you must use
487 L<nbd_connect_systemd_socket_activation(3)> instead.
489 =head2 Connecting to any socket
491 If none of the other nbd_connect* methods are suitable you can create
492 a connected socket yourself and pass it to L<nbd_connect_socket(3)>.
494 One use for this is in fuzzing where we use L<socketpair(2)> to create
495 the socket, then fork, then have the test harness in the child process
496 connected to libnbd over the socket pair (see:
497 L<https://gitlab.com/nbdkit/libnbd/-/blob/master/fuzzing/libnbd-fuzz-wrapper.c>).
499 Another use is to connect libnbd to an address family that it does not
500 support natively, such as XDP or IB.
502 =head1 CONTROLLING NEGOTIATION
504 By default, when beginning a connection, libnbd will handle all
505 negotiation with the server, using only the configuration
506 (eg. L<nbd_set_export_name(3)> or L<nbd_add_meta_context(3)>) that was
507 requested before the connection attempt; this phase continues until
508 L<nbd_aio_is_connecting(3)> no longer returns true, at which point,
509 either data commands are ready to use or else the connection has
510 failed with an error.
512 But there are scenarios in which it is useful to also control the
513 handshaking commands sent during negotiation, such as asking the
514 server for a list of available exports prior to selecting which one to
515 use. This is done by calling L<nbd_set_opt_mode(3)> before
516 connecting; then after requesting a connection, the state machine will
517 pause at L<nbd_aio_is_negotiating(3)> at any point that the user can
518 decide which handshake command to send next. Note that the
519 negotiation state is only reachable from newstyle servers; older
520 servers cannot negotiate and will progress all the way to the ready
523 When the negotiating state is reached, you can initiate option
524 commands such as L<nbd_opt_list(3)> or their asynchronous equivalents,
525 as well as alter configuration such as export name that previously had
526 to be set before connection. Since the NBD protocol does not allow
527 parallel negotiating commands, no cookie is involved, and you can
528 track completion of each command when the state is no longer
529 L<nbd_aio_is_connecting(3)>. If L<nbd_opt_go(3)> fails but the
530 connection is still live, you will be back in negotiation state, where
531 you can request a different export name and try again. Exiting the
532 negotiation state is only possible with a successful L<nbd_opt_go(3)>
533 which moves to the data phase, or L<nbd_opt_abort(3)> which performs a
534 clean shutdown of the connection by skipping the data phase.
536 =head1 EXPORTS AND FLAGS
538 It is possible for NBD servers to serve different content on different
539 “exports”. For this you must pass the right export name to the
540 server. Call this API before connecting:
542 nbd_set_export_name (nbd, "export");
544 Note that there are some servers (like L<nbdkit(1)> E<le> 1.14) which
545 ignore this, and other servers (like L<qemu-nbd(8)>) which require it
546 to be set correctly but cannot serve different content.
548 These APIs are also available after a successful L<nbd_opt_info(3)>
549 during the negotiation phase, if you used L<nbd_set_opt_mode(3)> prior
554 After connecting the server will send back a set of flags describing
555 the export, such as whether it is writable and if it can support flush
556 to permanent storage. These flags can be accessed from libnbd using
559 int is_read_only = nbd_is_read_only (nbd);
560 int can_flush = nbd_can_flush (nbd);
562 Flag calls are: __API_FLAG_LINKS__
564 =head2 Size of the export
566 To get the size of the export in bytes, use L<nbd_get_size(3)>:
568 int64_t size = nbd_get_size (nbd);
570 =head2 Block size constraints
572 Some NBD servers cannot handle requests at any byte boundary. They
573 might, for example, require all requests to be aligned to 512 byte
576 Also some servers advertise a preferred block size. This is not a
577 requirement, but is the minimum block size that can be accessed
578 efficiently (usually without triggering expensive read-modify-write
579 cycles inside the server).
581 These are referred to as block size constraints and can be queried by
582 calling L<nbd_get_block_size(3)>. Pay attention in particular to the
583 C<LIBNBD_SIZE_MINIMUM> constraint as some servers will fail requests
584 which are smaller or not aligned to this block size with C<EINVAL>
585 ("Invalid argument") errors.
589 You can read and write data from the NBD server using L<nbd_pread(3)>
590 and L<nbd_pwrite(3)> or their asynchronous equivalents.
592 All data commands support a C<flags> argument (mandatory in C, but
593 optional in languages where it can default to 0). For convenience,
594 the constant C<LIBNBD_CMD_FLAG_MASK> is defined with the set of flags
595 currently recognized by libnbd, where future NBD protocol extensions
596 may result in additional flags being supported; but in general,
597 specific data commands only accept a subset of known flags.
599 Libnbd defaults to performing some client-side sanity checking in each
600 of its data commands; for example, attempts to write to a server that
601 has advertised a read-only connection are rejected. It is possible to
602 override aspects of this checking by using L<nbd_set_strict_mode(3)>.
604 Some servers also support:
610 If L<nbd_can_trim(3)> returns true, L<nbd_trim(3)> can be used to “punch
611 holes” in the backing storage of the disk on the server. Normally
612 (although not in every case) the holes read back as zeroes but take up
617 If L<nbd_can_zero(3)> returns true, L<nbd_zero(3)> can be used to
618 efficiently zero parts of the disk without having to send large
619 amounts of zero bytes over the network (as would be necessary if using
622 This is slightly different from trimming because the backing storage
623 is still allocated. For some storage types this can make future
624 writes more efficient and/or less likely to fail because of out of
629 Some servers can commit data to permanent storage and tell you that
630 this has happened reliably. There are two export flags associated
631 with this: L<nbd_can_flush(3)> and L<nbd_can_fua(3)>.
633 The L<nbd_flush(3)> call (available if L<nbd_can_flush(3)> returns true)
634 flushes all pending writes to disk and does not complete until that
635 operation has finished. It is similar to using L<sync(2)> on POSIX
638 A more efficient way to achieve this is to set the flag
639 C<LIBNBD_CMD_FLAG_FUA> on write-like calls (like write, trim and
640 zero). This flag means the call will not complete until committed to
641 permanent storage, but it does not involve flushing the entire disk.
645 Some servers can prefetch data, making subsequent reads faster. The
646 L<nbd_cache(3)> call (available if L<nbd_can_cache(3)> returns true) is used
651 Some servers are able to provide information about the various extents
652 within the image, via the notion of one or more meta contexts. The
653 most common meta context is "base:allocation" (available in libnbd.h
654 as C<LIBNBD_CONTEXT_BASE_ALLOCATION>), which can be used to learn
655 which portions of a file are allocated or read as zero. Other
656 contexts may be available; for example, L<qemu-nbd(8)> can expose a
657 meta context "qemu:dirty-bitmap:NAME" for tracking which portions of a
658 file are tracked by a qcow2 dirty bitmap.
660 In order to utilize block status, the client must call
661 L<nbd_add_meta_context(3)> prior to connecting, for each meta context
662 in which it is interested, then check L<nbd_can_meta_context(3)> after
663 connection to see which contexts the server actually supports. If a
664 context is supported, the client can then use L<nbd_block_status(3)>
665 with a callback function that will receive an array of 32-bit integer
666 pairs describing consecutive extents within a context. In each pair,
667 the first integer is the length of the extent, the second is a bitmask
668 description of that extent (for the "base:allocation" context, the
669 bitmask may include C<LIBNBD_STATE_HOLE> for unallocated portions of
670 the file, and/or C<LIBNBD_STATE_ZERO> for portions of the file known
673 There is a full example of requesting meta context and using block
675 L<https://gitlab.com/nbdkit/libnbd/blob/master/interop/dirty-bitmap.c>
681 =head2 Issuing multiple in-flight requests
683 NBD servers which properly implement the specification can handle
684 multiple data requests in flight over the same connection at the same
685 time. Libnbd supports this when using the low level API.
687 To use it you simply issue more requests as needed (eg. using calls
688 like L<nbd_aio_pread(3)>, L<nbd_aio_pwrite(3)>) without waiting for previous
689 commands to complete. You need to be careful that requests in flight
690 do not overlap with disk offsets of other write-like commands in
691 flight — an overlapping read may see indeterminate data, and an
692 overlapping write may even cause disk corruption where the resulting
693 disk contents do not match either of the two writes.
695 Each request is identified by a unique 64 bit cookie (assigned by
696 libnbd), allowing libnbd and callers to match replies to requests.
697 Replies may arrive out of order. A request that is rejected
698 client-side for failing a sanity check (such as attempting to write to
699 a read-only server, see L<nbd_set_strict_mode(3)>) will fail rather
700 than returning a cookie, although closure cleanup is still performed.
702 Although in theory you can have an indefinite number of requests in
703 flight at the same time, in practice it's a good idea to limit them to
704 some number. Libnbd will queue commands in the handle even if it
705 cannot write them to the server, so this limit is largely to prevent a
706 backlog of commands from consuming too much memory. It is suggested
707 to start with a limit of 64 requests in flight (per NBD connection),
708 and measure how adjusting the limit up and down affects performance
709 for your local configuration.
711 There is a full example using multiple in-flight requests available at
712 L<https://gitlab.com/nbdkit/libnbd/blob/master/examples/threaded-reads-and-writes.c>
716 Some NBD servers advertise “multi-conn” which means that it is safe to
717 make multiple connections to the server and load-balance commands
718 across all of the connections.
720 To do this you should open a single connection first and test for this
721 feature using L<nbd_can_multi_conn(3)>. Without error handling it
722 would look like this:
724 struct nbd_handle *nbd[4];
726 bool supports_multi_conn;
728 nbd[0] = nbd_create ();
729 nbd_connect_tcp (nbd[0], "server", "10809");
730 supports_multi_conn = nbd_can_multi_conn (nbd[0]) > 0;
732 If multi-conn is supported then you can open further connections:
734 if (supports_multi_conn) {
735 for (i = 1; i <= 3; ++i) {
736 nbd[i] = nbd_create ();
737 nbd_connect_tcp (nbd[i], "server", "10809");
741 If you are issuing multiple in-flight requests (see above) and
742 limiting the number, then the limit should be applied to each
743 individual NBD connection.
745 =head1 ENCRYPTION AND AUTHENTICATION
747 The NBD protocol and libnbd supports TLS (sometimes incorrectly called
748 “SSL”) for encryption of the data stream and authentication of clients
749 and servers. Libnbd defaults to TLS I<disabled> for maximum
750 interoperability. To enable it on a handle you must call
751 L<nbd_set_tls(3)> before connecting.
753 To allow TLS, but fall back to unencrypted:
755 nbd_set_tls (nbd, LIBNBD_TLS_ALLOW);
757 Use L<nbd_get_tls_negotiated(3)> to find out if TLS negotiation was
758 successful. Avoid C<LIBNBD_TLS_ALLOW> if man-in-the-middle attacks
761 The most secure mode is to require TLS and fail to connect if the
762 server does not support it:
764 nbd_set_tls (nbd, LIBNBD_TLS_REQUIRE);
766 It may also be necessary to verify that the server’s identity is
767 correct. For some servers it may be necessary to verify to the server
768 that the client is permitted to connect. This can be done using
769 either X.509 certificates, or TLS Pre-Shared Keys (PSK). Certificates
770 are more secure. PSK is far more convenient, but you must have an
771 existing secure channel to distribute the keys.
773 =head2 Setting up X.509 using system certificate authorities (CAs)
775 This is the default if you don’t call any other C<nbd_set_tls_*>
776 functions. In this case the server must have a public (eg. HTTPS)
777 certificate which can be verified against the CAs registered on your
778 system (eg. under F</etc/pki>).
780 To disable server name verification — which opens you up to a potential
781 Man-In-The-Middle (MITM) attack — use:
783 nbd_set_tls_verify_peer (nbd, false);
785 =head2 Setting up an X.509 certificate authority (CA)
787 You can set up your own CA and register clients and servers with it,
788 issuing client and server certificates which will reliably
789 authenticate your clients and servers to each other.
791 Doing this is described in detail in the L<nbdkit-tls(1)> manual. The
792 only differences for libnbd are:
798 Non-root certificates must be placed in C<$HOME/.pki/libnbd/> or
799 C<$HOME/.config/pki/libnbd/>
803 Libnbd reads F<client-cert.pem> and F<client-key.pem> (instead of
804 F<server-cert.pem> and F<server-key.pem>).
808 Once you have set up the directory containing the certificates, call:
810 nbd_set_tls_certificates (nbd, "/path/to/directory");
812 =head2 Setting up Pre-Shared Keys (PSK)
814 TLS Pre-Shared Keys are a much more convenient method of setting up
815 TLS, and more appropriate for NBD, but you should have an existing
816 secure method available to distribute the keys. They are therefore
817 ideal if you want to set up an NBD service as an adjunct to an
818 existing secure REST API.
820 Use L<psktool(1)> to create a file of C<username:key> pairs:
822 psktool -u username -p keys.psk
824 and pass this path to libnbd:
826 nbd_set_tls_psk_file (nbd, "keys.psk");
828 If necessary you may need to set the client username (otherwise libnbd
829 will use your login name):
831 nbd_set_tls_username (nbd, "username");
835 Some libnbd calls take callbacks (eg. L<nbd_set_debug_callback(3)>,
836 L<nbd_aio_pread(3)>). Libnbd can call these functions while processing.
838 In the C API these libnbd calls take a structure which contains the
839 function pointer and an optional opaque C<void *user_data> pointer:
841 nbd_aio_pread (nbd, buf, sizeof buf, offset,
842 (nbd_completion_callback) { .callback = my_fn,
843 .user_data = my_data },
846 For optional callbacks, if you don't want the callback, either set
847 C<.callback> to C<NULL> or use the equivalent macros (such as
848 C<NBD_NULL_COMPLETION>) defined in C<libnbd.h>:
850 nbd_aio_pread (nbd, buf, sizeof buf, offset,
851 NBD_NULL_COMPLETION, 0);
853 From other languages the structure and opaque pointer are not needed
854 because you can use closures to achieve the same effect.
856 =head2 Callback lifetimes
858 You can associate an optional free function with callbacks. Libnbd
859 will call this function when the callback will not be called again by
860 libnbd, including in the case where the API fails.
862 This can be used to free associated C<user_data>. For example:
864 void *my_data = malloc (...);
866 nbd_aio_pread_structured (nbd, buf, sizeof buf, offset,
867 (nbd_chunk_callback) { .callback = my_fn,
868 .user_data = my_data,
873 will call L<free(3)> once on C<my_data> after the point where it is
874 known that the S<C<chunk.callback = my_fn>> function can no longer be
875 called, regardless of how many times C<my_fn> was actually called. If
876 both a mid-command and completion callback are supplied, the functions
877 will be reached in this order: mid-function callbacks, completion
878 callback, mid-function free, and finally completion free.
880 The free function is only accessible in the C API as it is not needed
881 in garbage collected programming languages.
883 =head2 Callbacks with C<.callback=NULL> and C<.free!=NULL>
885 It is possible to register a callback like this:
888 (nbd_completion_callback) { .callback = NULL,
889 .user_data = my_data,
893 The meaning of this is that the callback is never called, but the free
894 function is still called after the last time the callback would have
895 been called. This is useful for applying generic freeing actions when
896 asynchronous commands are retired.
898 =head2 Callbacks and locking
900 The callbacks are invoked at a point where the libnbd lock is held; as
901 such, it is unsafe for the callback to call any C<nbd_*> APIs on the
902 same nbd object, as it would cause deadlock.
904 =head2 Completion callbacks
906 All of the asychronous commands have an optional completion callback
907 function that is used right before the command is marked complete,
908 after any mid-command callbacks have finished, and before any free
911 When the completion callback returns C<1>, the command is
912 automatically retired (there is no need to call
913 L<nbd_aio_command_completed(3)>); for any other return value, the
914 command still needs to be manually retired (otherwise, the command
915 will tie up resources until L<nbd_close(3)> is eventually reached).
917 =head2 Callbacks with C<int *error> parameter
919 Some of the high-level commands (L<nbd_pread_structured(3)>,
920 L<nbd_block_status(3)>) involve the use of a callback function invoked
921 by the state machine at appropriate points in the server's reply
922 before the overall command is complete. These callback functions,
923 along with all of the completion callbacks, include a parameter
924 C<error> which is a pointer containing the value of any error detected
925 so far. If a callback function fails and wants to change the
926 resulting error of the overall command visible later in the API
927 sequence, it should assign back into C<error> and return C<-1> in the
928 C API. Assignments into C<error> are ignored for any other return
929 value; similarly, assigning C<0> into C<error> does not have an
930 effect. In other language bindings, reporting callback errors is
931 generally done by raising an exception rather than by return value.
933 Note that a mid-command callback might never be reached, such as if
934 libnbd detects that the command was invalid to send (see
935 L<nbd_set_strict_mode(3)>) or if the server reports a failure that
936 concludes the command. It is safe for a mid-command callback to
937 ignore non-zero C<error>: all the other parameters to the mid-command
938 callback will still be valid (corresponding to the current portion of
939 the server's reply), and the overall command will still fail (at the
940 completion callback or L<nbd_aio_command_completed(3)> for an
941 asynchronous command, or as the result of the overall synchronous
942 command). Returing C<-1> from a mid-command callback does not prevent
943 that callback from being reached again, if the server sends more
944 mid-command replies that warrant another use of that callback. A
945 mid-command callback may be reached more times than expected if the
946 server is non-compliant.
948 On the other hand, if a completion callback is supplied (only possible
949 with asynchronous commands), it will always be reached exactly once,
950 and the completion callback must not ignore the value pointed to by
951 C<error>. In particular, the content of a buffer passed to
952 L<nbd_aio_pread(3)> or L<nbd_aio_pread_structured(3)> is undefined
953 if C<*error> is non-zero on entry to the completion callback. It is
954 recommended that if you choose to use automatic command retirement
955 (where the completion callback returns C<1> to avoid needing to call
956 L<nbd_aio_command_completed(3)> later), your completion function
957 should return C<1> on all control paths, even when handling errors
958 (note that with automatic retirement, assigning into C<error> is
959 pointless as there is no later API to see that value).
961 =head1 STATISTICS COUNTERS
963 Libnbd tracks several statistics counters, useful for tracking how
964 much traffic was sent over the connection. The counters track the
965 number of plaintext bytes sent and received by the NBD protocol (not
966 necessarily the number of bytes sent over the socket, particularly
967 when TLS is enabled), as well as the number of protocol chunks (a
968 group of bytes delineated by a magic number, and not the same as the
969 number of TCP packets).
971 printf ("bytes: sent=%" PRIu64 " received=%" PRIu64,
972 nbd_stats_bytes_sent (nbd), nbd_stats_bytes_received (nbd));
973 printf ("chunks: sent=%" PRIu64 " received=%" PRIu64,
974 nbd_stats_chunks_sent (nbd), nbd_stats_chunks_received (nbd));
978 Libnbd does not install signal handlers. It attempts to disable
979 C<SIGPIPE> when writing to the NBD socket using the C<MSG_NOSIGNAL>
980 flag of L<send(2)>, or the C<SO_NOSIGPIPE> socket option, on platforms
983 On some old Linux or newer non-Linux platforms the main program may
984 wish to register a signal handler to ignore SIGPIPE:
986 signal (SIGPIPE, SIG_IGN);
988 =head1 COMPILING YOUR PROGRAM
990 On most systems, C programs that use libnbd can be compiled like this:
992 cc prog.c -o prog -lnbd
994 To detect if the libnbd library and header file is installed, the
995 preferred method is to use L<pkg-config(1)> or L<pkgconf(1)>:
997 pkg-config libnbd --exists || fail libnbd is required
999 In case the library or header file are not installed in the usual
1000 system locations, you can compile your program like this, using
1001 pkg-config to detect the proper location of libnbd:
1003 cc prog.c -o prog `pkg-config libnbd --cflags --libs`
1005 To compile an external project against a built copy of the libnbd
1006 source tree which hasn't been installed, see the F<./run> script.
1008 =head2 Autoconf projects
1010 External projects which use autoconf and need to check if libnbd is
1011 installed should use the C<PKG_CHECK_MODULES> macro in F<configure.ac>
1014 PKG_CHECK_MODULES([LIBNBD], [libnbd])
1016 This will define C<@LIBNBD_CFLAGS@> and C<@LIBNBD_LIBS@> which you
1017 will need to add to your F<Makefile.am>.
1019 =head2 CMake projects
1021 For CMake projects use:
1023 find_package(PkgConfig REQUIRED)
1024 pkg_check_modules(LIBNBD REQUIRED libnbd)
1025 target_link_libraries(prog ${LIBNBD_LIBRARIES})
1026 target_include_directories(prog PUBLIC ${LIBNBD_INCLUDE_DIRS})
1027 target_compile_options(prog PUBLIC ${LIBNBD_CFLAGS_OTHER})
1029 =head2 Meson projects
1031 For meson projects use:
1033 nbd_dep = dependency('libnbd')
1034 executable('prog', 'prog.c', dependencies : [nbd_dep])
1036 =head1 ENVIRONMENT VARIABLES
1042 Used in some situations to find TLS certificates. See
1043 L<nbd_set_tls_certificates(3)>.
1045 =item C<LIBNBD_DEBUG>
1047 If this is set to the exact string C<1> when the handle is created
1048 then debugging is enabled. See L</DEBUGGING MESSAGES> above.
1052 The default TLS username. See L<nbd_set_tls_username(3)>.
1068 =head2 Encryption tools
1076 L<https://github.com/NetworkBlockDevice/nbd/blob/master/doc/proto.md>,
1077 L<https://github.com/NetworkBlockDevice/nbd/blob/master/doc/uri.md>.
1079 =head2 Release notes
1081 L<libnbd-release-notes-1.14(1)>,
1082 L<libnbd-release-notes-1.12(1)>,
1083 L<libnbd-release-notes-1.10(1)>,
1084 L<libnbd-release-notes-1.8(1)>,
1085 L<libnbd-release-notes-1.6(1)>,
1086 L<libnbd-release-notes-1.4(1)>,
1087 L<libnbd-release-notes-1.2(1)>.
1091 L<libnbd-security(3)>,