1=head1 NAME
2
3nbdkit-plugin - how to write nbdkit plugins
4
5=head1 SYNOPSIS
6
7 #define NBDKIT_API_VERSION 2
8 #include <nbdkit-plugin.h>
9
10 #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS
11
12 static void *
13 myplugin_open (void)
14 {
15   /* create a handle ... */
16   return handle;
17 }
18
19 static struct nbdkit_plugin plugin = {
20   .name              = "myplugin",
21   .open              = myplugin_open,
22   .get_size          = myplugin_get_size,
23   .pread             = myplugin_pread,
24   .pwrite            = myplugin_pwrite,
25   /* etc */
26 };
27 NBDKIT_REGISTER_PLUGIN(plugin)
28
29Compile the plugin as a shared library:
30
31 gcc -fPIC -shared myplugin.c -o myplugin.so
32
33and load it into nbdkit:
34
35 nbdkit [--args ...] ./myplugin.so [key=value ...]
36
37When debugging, use the I<-fv> options:
38
39 nbdkit -fv ./myplugin.so [key=value ...]
40
41=head1 DESCRIPTION
42
43An nbdkit plugin is a new source device which can be served using the
44Network Block Device (NBD) protocol.  This manual page describes how
45to create an nbdkit plugin in C.
46
47To see example plugins:
48L<https://github.com/libguestfs/nbdkit/tree/master/plugins>
49
50To write plugins in other languages, see:
51__LANG_PLUGIN_LINKS__.
52
53=head2 API and ABI guarantee for C plugins
54
55Plugins written in C have an ABI guarantee: a plugin compiled against
56an older version of nbdkit will still work correctly when loaded with
57a newer nbdkit.  We also try (but cannot guarantee) to support plugins
58compiled against a newer version of nbdkit when loaded with an older
59nbdkit, although the plugin may have reduced functionality if it
60depends on features only provided by newer nbdkit.
61
62For plugins written in C, we also provide an API guarantee: a plugin
63written against an older header will still compile unmodified with a
64newer nbdkit.
65
66The API guarantee does not always apply to plugins written in other
67(non-C) languages which may have to adapt to changes when recompiled
68against a newer nbdkit.
69
70=head1 WRITING AN NBDKIT PLUGIN
71
72=head2 C<#define NBDKIT_API_VERSION 2>
73
74Plugins must choose which API version they want to use, by defining
75NBDKIT_API_VERSION before including C<E<lt>nbdkit-plugin.hE<gt>> (or
76any other nbdkit header).
77
78If omitted, the default version is 1 for backwards-compatibility with
79nbdkit v1.1.26 and earlier; however, it is recommended that new
80plugins be written to the maximum version (currently 2) as it enables
81more features and better interaction with nbdkit filters.
82
83The rest of this document only covers the version 2 interface.  A
84newer nbdkit will always support plugins written in C which use any
85prior API version.
86
87=head2 C<#include E<lt>nbdkit-plugin.hE<gt>>
88
89All plugins should start by including this header file (after
90optionally choosing an API version).
91
92=head2 C<#define THREAD_MODEL ...>
93
94All plugins must define a thread model.  See L</Threads> below for
95details.  It is generally safe to use:
96
97 #define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS
98
99=head2 C<struct nbdkit_plugin>
100
101All plugins must define and register one C<struct nbdkit_plugin>,
102which contains the name of the plugin and pointers to callback
103functions, and use the C<NBDKIT_REGISTER_PLUGIN(plugin)> macro:
104
105 static struct nbdkit_plugin plugin = {
106   .name              = "myplugin",
107   .longname          = "My Plugin",
108   .description       = "This is my great plugin for nbdkit",
109   .open              = myplugin_open,
110   .get_size          = myplugin_get_size,
111   .pread             = myplugin_pread,
112   .pwrite            = myplugin_pwrite,
113   /* etc */
114 };
115 NBDKIT_REGISTER_PLUGIN(plugin)
116
117The C<.name> field is the name of the plugin.
118
119The callbacks are described below (see L</CALLBACKS>).  Only C<.name>,
120C<.open>, C<.get_size> and C<.pread> are required.  All other
121callbacks can be omitted, although typical plugins need to use more.
122
123=head2 Callback lifecycle
124
125Callbacks are called in the following order over the lifecycle of
126the plugin:
127
128         ┌──────────────────┐
129         │ load             │
130         └─────────┬────────┘
131                   │           configuration phase starts     ─┐
132         ┌─────────┴────────┐                                  ┆
133         │ config           │  config is called once per       ┆
134         └─────────┬────────┘↺ key=value on the command line   ┆
135         ┌─────────┴────────┐                                  ┆
136         │ config_complete  │                                  ┆
137         └─────────┬────────┘                                  ┆
138         ┌─────────┴────────┐                                  ┆
139         │ thread_model     │                                  ┆
140         └─────────┬────────┘  configuration phase ends       ─┘
141         ┌─────────┴────────┐
142         │ get_ready        │
143         └─────────┬────────┘
144                   │           nbdkit forks into the background
145                   │           and starts serving clients
146147        ┌──────────┴─────────────┬─ ─ ─ ─ ─ ─ ─ ─ ─
148 ┌──────┴─────┐ client #1        │
149 │ preconnect │                  │
150 └──────┬─────┘                  │
151 ┌──────┴─────┐                  │
152 │ open       │                  │
153 └──────┬─────┘                  │
154 ┌──────┴─────┐  NBD option      │
155 │ can_write  │  negotiation     │
156 └──────┬─────┘                  │
157 ┌──────┴─────┐           ┌──────┴─────┐ client #2
158 │ get_size   │           │ preconnect │
159 └──────┬─────┘           └──────┬─────┘
160 ┌──────┴─────┐ data      ┌──────┴─────┐
161 │ pread      │ serving   │ open       │
162 └──────┬─────┘↺          └──────┬─────┘
163 ┌──────┴─────┐                 ...
164 │ pwrite     │
165 └──────┬─────┘↺          ┌──────┴─────┐
166 ┌──────┴─────┐           │ close      │
167 │ close      │           └────────────┘
168 └────────────┘
169
170                   │           before nbdkit exits
171172         ┌─────────┴────────┐
173         │ unload           │
174         └──────────────────┘
175
176=over 4
177
178=item C<.load>
179
180is called once just after the plugin is loaded into memory.
181
182=item C<.config> and C<.config_complete>
183
184C<.config> is called zero or more times during command line parsing.
185C<.config_complete> is called once after all configuration information
186has been passed to the plugin (but not during C<nbdkit --dump-plugin>).
187
188Both are called after loading the plugin but before any connections
189are accepted.
190
191=item C<.thread_model>
192
193In normal operation, C<.thread_model> is called once after
194C<.config_complete> has validated all configuration information, and
195before any connections are accepted.  However, during C<nbdkit
196--dump-plugin>, it is called after any C<.config> calls but without
197C<.config_complete> (so a plugin which determines the results from a
198script must be prepared for a missing script).
199
200=item C<.get_ready>
201
202In normal operation, C<.get_ready> is called before the server starts
203serving.  It is called before the server forks or changes directory.
204It is the last chance to do any global preparation that is needed to
205serve connections.
206
207=item C<.preconnect>
208
209Called when a TCP connection has been made to the server.  This
210happens early, before NBD or TLS negotiation.
211
212=item C<.open>
213
214A new client has connected and finished the NBD handshake.  TLS
215negotiation (if required) has been completed successfully.
216
217=item C<.can_write>, C<.get_size> and other option negotiation callbacks
218
219These are called during option negotiation with the client, but before
220any data is served.  These callbacks may return different values
221across different C<.open> calls, but within a single connection, they
222are called at most once and cached by nbdkit for that connection.
223
224=item C<.pread>, C<.pwrite> and other data serving callbacks
225
226After option negotiation has finished, these may be called to serve
227data.  Depending on the thread model chosen, they might be called in
228parallel from multiple threads.  The data serving callbacks include a
229flags argument; the results of the negotiation callbacks influence
230whether particular flags will ever be passed to a data callback.
231
232=item C<.close>
233
234The client has disconnected.
235
236=item C<.preconnect>, C<.open> ... C<.close>
237
238The sequence C<.preconnect>, C<.open> ... C<.close> can be called
239repeatedly over the lifetime of the plugin, and can be called in
240parallel (depending on the thread model).
241
242=item C<.unload>
243
244is called once just before the plugin is unloaded from memory.
245
246=back
247
248=head2 Flags
249
250The following flags are defined by nbdkit, and used in various data
251serving callbacks as follows:
252
253=over 4
254
255=item C<NBDKIT_FLAG_MAY_TRIM>
256
257This flag is used by the C<.zero> callback; there is no way to disable
258this flag, although a plugin that does not support trims as a way to
259write zeroes may ignore the flag without violating expected semantics.
260
261=item C<NBDKIT_FLAG_FUA>
262
263This flag represents Forced Unit Access semantics.  It is used by the
264C<.pwrite>, C<.zero>, and C<.trim> callbacks to indicate that the
265plugin must not return a result until the action has landed in
266persistent storage.  This flag will not be sent to the plugin unless
267C<.can_fua> is provided and returns C<NBDKIT_FUA_NATIVE>.
268
269=back
270
271The following defines are valid as successful return values for
272C<.can_fua>:
273
274=over 4
275
276=item C<NBDKIT_FUA_NONE>
277
278Forced Unit Access is not supported; the client must manually request
279a flush after writes have completed.  The C<NBDKIT_FLAG_FUA> flag will
280not be passed to the plugin's write callbacks.
281
282=item C<NBDKIT_FUA_EMULATE>
283
284The client may request Forced Unit Access, but it is implemented by
285emulation, where nbdkit calls C<.flush> after a write operation; this
286is semantically correct, but may hurt performance as it tends to flush
287more data than just what the client requested.  The C<NBDKIT_FLAG_FUA>
288flag will not be passed to the plugin's write callbacks.
289
290=item C<NBDKIT_FUA_NATIVE>
291
292The client may request Forced Unit Access, which results in the
293C<NBDKIT_FLAG_FUA> flag being passed to the plugin's write callbacks
294(C<.pwrite>, C<.trim>, and C<.zero>).  When the flag is set, these
295callbacks must not return success until the client's request has
296landed in persistent storage.
297
298=back
299
300The following defines are valid as successful return values for
301C<.can_cache>:
302
303=over 4
304
305=item C<NBDKIT_CACHE_NONE>
306
307The server does not advertise caching support, and rejects any
308client-requested caching. Any C<.cache> callback is ignored.
309
310=item C<NBDKIT_CACHE_EMULATE>
311
312The nbdkit server advertises cache support to the client, where the
313client may request that the server cache a region of the export to
314potentially speed up future read and/or write operations on that
315region. The nbdkit server implements the caching by calling C<.pread>
316and ignoring the results. This option exists to ease the
317implementation of a common form of caching; any C<.cache> callback is
318ignored.
319
320=item C<NBDKIT_CACHE_NATIVE>
321
322The nbdkit server advertises cache support to the client, where the
323client may request that the server cache a region of the export to
324potentially speed up future read and/or write operations on that
325region. The nbdkit server calls the C<.cache> callback to perform the
326caching; if that callback is missing, the client's cache request
327succeeds without doing anything.
328
329=back
330
331=head2 Threads
332
333Each nbdkit plugin must declare its maximum thread safety model by
334defining the C<THREAD_MODEL> macro.  (This macro is used by
335C<NBDKIT_REGISTER_PLUGIN>).  Additionally, a plugin may implement the
336C<.thread_model> callback, called right after C<.config_complete> to
337make a runtime decision on which thread model to use.  The nbdkit
338server chooses the most restrictive model between the plugin's
339C<THREAD_MODEL>, the C<.thread_model> if present, any restrictions
340requested by filters, and any limitations imposed by the operating
341system.
342
343In C<nbdkit --dump-plugin PLUGIN> output, the C<max_thread_model> line
344matches the C<THREAD_MODEL> macro, and the C<thread_model> line
345matches what the system finally settled on after applying all
346restrictions.
347
348The possible settings for C<THREAD_MODEL> are defined below.
349
350=over 4
351
352=item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_CONNECTIONS>
353
354Only a single handle can be open at any time, and all requests happen
355from one thread.
356
357Note this means only one client can connect to the server at any time.
358If a second client tries to connect it will block waiting for the
359first client to close the connection.
360
361=item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_ALL_REQUESTS>
362
363I<This is a safe default for most plugins>.
364
365Multiple handles can be open at the same time, but requests are
366serialized so that for the plugin as a whole only one
367open/read/write/close (etc) request will be in progress at any time.
368
369This is a useful setting if the library you are using is not
370thread-safe.  However performance may not be good.
371
372=item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_SERIALIZE_REQUESTS>
373
374Multiple handles can be open and multiple data requests can happen in
375parallel.  However only one request will happen per handle at a time
376(but requests on different handles might happen concurrently).
377
378=item C<#define THREAD_MODEL NBDKIT_THREAD_MODEL_PARALLEL>
379
380Multiple handles can be open and multiple data requests can happen in
381parallel (even on the same handle).  The server may reorder replies,
382answering a later request before an earlier one.
383
384All the libraries you use must be thread-safe and reentrant, and any
385code that creates a file descriptor should atomically set
386C<FD_CLOEXEC> if you do not want it accidentally leaked to another
387thread's child process.  You may also need to provide mutexes for
388fields in your connection handle.
389
390=back
391
392If none of the above thread models are suitable, use
393C<NBDKIT_THREAD_MODEL_PARALLEL> and implement your own locking using
394C<pthread_mutex_t> etc.
395
396=head2 Error handling
397
398If there is an error in the plugin, the plugin should call
399C<nbdkit_error> to report an error message; additionally, if the
400callback is involved in serving data, the plugin should call
401C<nbdkit_set_error> to influence the error code that will be sent to
402the client.  These two functions can be called in either order.  Then,
403the callback should return the appropriate error indication,
404eg. C<NULL> or C<-1>.
405
406If the call to C<nbdkit_set_error> is omitted while serving data, then
407the global variable C<errno> may be used.  For plugins which have
408C<.errno_is_preserved != 0> the core code will use C<errno>.  In
409plugins written in non-C languages, we usually cannot trust that
410C<errno> will not be overwritten when returning from that language to
411C.  In that case, either the plugin must call C<nbdkit_set_error> or
412hard-coded C<EIO> is used.
413
414C<nbdkit_error> has the following prototype and works like
415L<printf(3)>:
416
417 void nbdkit_error (const char *fs, ...);
418 void nbdkit_verror (const char *fs, va_list args);
419
420For convenience, C<nbdkit_error> preserves the value of C<errno>, and
421also supports the glibc extension of a single C<%m> in a format string
422expanding to C<strerror(errno)>, even on platforms that don't support
423that natively.
424
425C<nbdkit_set_error> can be called at any time, but only has an impact
426during callbacks for serving data, and only when the callback returns
427an indication of failure.  It has the following prototype:
428
429 void nbdkit_set_error (int err);
430
431=head1 CALLBACKS
432
433=head2 C<.name>
434
435 const char *name;
436
437This field (a string) is required, and B<must> contain only ASCII
438alphanumeric characters and be unique amongst all plugins.
439
440=head2 C<.version>
441
442 const char *version;
443
444Plugins may optionally set a version string which is displayed in help
445and debugging output.
446
447=head2 C<.longname>
448
449 const char *longname;
450
451An optional free text name of the plugin.  This field is used in error
452messages.
453
454=head2 C<.description>
455
456 const char *description;
457
458An optional multi-line description of the plugin.
459
460=head2 C<.load>
461
462 void load (void);
463
464This is called once just after the plugin is loaded into memory.  You
465can use this to perform any global initialization needed by the
466plugin.
467
468=head2 C<.unload>
469
470 void unload (void);
471
472This may be called once just before the plugin is unloaded from
473memory.  Note that it's not guaranteed that C<.unload> will always be
474called (eg. the server might be killed or segfault), so you should try
475to make the plugin as robust as possible by not requiring cleanup.
476See also L</SHUTDOWN> below.
477
478=head2 C<.dump_plugin>
479
480 void dump_plugin (void);
481
482This optional callback is called when the
483S<C<nbdkit plugin --dump-plugin>> command is used.  It should print
484any additional informative C<key=value> fields to stdout as needed.
485Prefixing the keys with the name of the plugin will avoid conflicts.
486
487=head2 C<.config>
488
489 int config (const char *key, const char *value);
490
491On the nbdkit command line, after the plugin filename, come an
492optional list of C<key=value> arguments.  These are passed to the
493plugin through this callback when the plugin is first loaded and
494before any connections are accepted.
495
496This callback may be called zero or more times.
497
498Both C<key> and C<value> parameters will be non-NULL.  The strings are
499owned by nbdkit but will remain valid for the lifetime of the plugin,
500so the plugin does not need to copy them.
501
502The key will be a non-empty string beginning with an ASCII alphabetic
503character (C<A-Z> C<a-z>).  The rest of the key must contain only
504ASCII alphanumeric plus period, underscore or dash characters (C<A-Z>
505C<a-z> C<0-9> C<.> C<_> C<->).  The value may be an arbitrary string,
506including an empty string.
507
508The names of C<key>s accepted by plugins is up to the plugin, but you
509should probably look at other plugins and follow the same conventions.
510
511If the value is a relative path, then note that the server changes
512directory when it starts up.  See L</FILENAMES AND PATHS> above.
513
514If C<nbdkit_stdio_safe> returns 1, the value of the configuration
515parameter may be used to trigger reading additional data through stdin
516(such as a password or inline script).
517
518If the C<.config> callback is not provided by the plugin, and the user
519tries to specify any C<key=value> arguments, then nbdkit will exit
520with an error.
521
522If there is an error, C<.config> should call C<nbdkit_error> with an
523error message and return C<-1>.
524
525=head2 C<.magic_config_key>
526
527 const char *magic_config_key;
528
529This optional string can be used to set a "magic" key used when
530parsing plugin parameters.  It affects how "bare parameters" (those
531which do not contain an C<=> character) are parsed on the command
532line.
533
534If C<magic_config_key != NULL> then any bare parameters are passed to
535the C<.config> method as: S<C<config (magic_config_key, argv[i]);>>.
536
537If C<magic_config_key> is not set then we behave as in nbdkit E<lt>
5381.7: If the first parameter on the command line is bare then it is
539passed to the C<.config> method as: S<C<config ("script", value);>>.
540Any other bare parameters give errors.
541
542=head2 C<.config_complete>
543
544 int config_complete (void);
545
546This optional callback is called after all the configuration has been
547passed to the plugin.  It is a good place to do checks, for example
548that the user has passed the required parameters to the plugin.
549
550If there is an error, C<.config_complete> should call C<nbdkit_error>
551with an error message and return C<-1>.
552
553=head2 C<.config_help>
554
555 const char *config_help;
556
557This optional multi-line help message should summarize any
558C<key=value> parameters that it takes.  It does I<not> need to repeat
559what already appears in C<.description>.
560
561If the plugin doesn't take any config parameters you should probably
562omit this.
563
564=head2 C<.thread_model>
565
566 int thread_model (void)
567
568This optional callback is called after all the configuration has been
569passed to the plugin.  It can be used to force a stricter thread model
570based on configuration, compared to C<THREAD_MODEL>.  See L</Threads>
571above for details.  Attempts to request a looser (more parallel) model
572are silently ignored.
573
574If there is an error, C<.thread_model> should call C<nbdkit_error>
575with an error message and return C<-1>.
576
577=head2 C<.get_ready>
578
579 int get_ready (void);
580
581This optional callback is called before the server starts serving.  It
582is called before the server forks or changes directory.  It is the
583last chance to do any global preparation that is needed to serve
584connections.
585
586If there is an error, C<.get_ready> should call C<nbdkit_error> with
587an error message and return C<-1>.
588
589=head2 C<.preconnect>
590
591 int preconnect (int readonly);
592
593This optional callback is called when a TCP connection has been made
594to the server.  This happens early, before NBD or TLS negotiation.  If
595TLS authentication is required to access the server, then it has
596B<not> been negotiated at this point.
597
598For security reasons (to avoid denial of service attacks) this
599callback should be written to be as fast and take as few resources as
600possible.  If you use this callback, only use it to do basic access
601control, such as checking C<nbdkit_peer_name> against a whitelist (see
602L</PEER NAME> and L<nbdkit-ip-filter(1)>).  It may be better to do
603access control outside the server, for example using TCP wrappers or a
604firewall.
605
606The C<readonly> flag informs the plugin that the server was started
607with the I<-r> flag on the command line.
608
609Returning C<0> will allow the connection to continue.  If there is an
610error or you want to deny the connection, call C<nbdkit_error> with an
611error message and return C<-1>.
612
613=head2 C<.open>
614
615 void *open (int readonly);
616
617This is called when a new client connects to the nbdkit server.  The
618callback should allocate a handle and return it.  This handle
619is passed back to other callbacks and could be freed in the C<.close>
620callback.
621
622Note that the handle is completely opaque to nbdkit, but it must not
623be NULL.  If you don't need to use a handle, return
624C<NBDKIT_HANDLE_NOT_NEEDED> which is a static non-NULL pointer.
625
626The C<readonly> flag informs the plugin that the server was started
627with the I<-r> flag on the command line which forces connections to be
628read-only.  Note that the plugin may I<additionally> force the
629connection to be readonly (even if this flag is false) by returning
630false from the C<.can_write> callback.  So if your plugin can only
631serve read-only, you can ignore this parameter.
632
633This callback is called after the NBD handshake has completed, which
634includes TLS authentication (if required).  If the plugin defines a
635C<.preconnect> callback, then it must be called and return with
636success before C<.open> is called.
637
638If there is an error, C<.open> should call C<nbdkit_error> with an
639error message and return C<NULL>.
640
641=head2 C<.close>
642
643 void close (void *handle);
644
645This is called when the client closes the connection.  It should clean
646up any per-connection resources.
647
648Note there is no way in the NBD protocol to communicate close errors
649back to the client, for example if your plugin calls L<close(2)> and
650you are checking for errors (as you should do).  Therefore the best
651you can do is to log the error on the server.  Well-behaved NBD
652clients I<should> try to flush the connection before it is closed and
653check for errors, but obviously this is outside the scope of nbdkit.
654
655=head2 C<.get_size>
656
657 int64_t get_size (void *handle);
658
659This is called during the option negotiation phase of the protocol
660to get the size (in bytes) of the block device being exported.
661
662The returned size must be E<ge> 0.  If there is an error, C<.get_size>
663should call C<nbdkit_error> with an error message and return C<-1>.
664
665=head2 C<.can_write>
666
667 int can_write (void *handle);
668
669This is called during the option negotiation phase to find out if the
670handle supports writes.
671
672If there is an error, C<.can_write> should call C<nbdkit_error> with
673an error message and return C<-1>.
674
675This callback is not required.  If omitted, then we return true iff a
676C<.pwrite> callback has been defined.
677
678=head2 C<.can_flush>
679
680 int can_flush (void *handle);
681
682This is called during the option negotiation phase to find out if the
683handle supports the flush-to-disk operation.
684
685If there is an error, C<.can_flush> should call C<nbdkit_error> with
686an error message and return C<-1>.
687
688This callback is not required.  If omitted, then we return true iff a
689C<.flush> callback has been defined.
690
691=head2 C<.is_rotational>
692
693 int is_rotational (void *handle);
694
695This is called during the option negotiation phase to find out if the
696backing disk is a rotational medium (like a traditional hard disk) or
697not (like an SSD).  If true, this may cause the client to reorder
698requests to make them more efficient for a slow rotating disk.
699
700If there is an error, C<.is_rotational> should call C<nbdkit_error>
701with an error message and return C<-1>.
702
703This callback is not required.  If omitted, then we return false.
704
705=head2 C<.can_trim>
706
707 int can_trim (void *handle);
708
709This is called during the option negotiation phase to find out if the
710plugin supports the trim/discard operation for punching holes in the
711backing storage.
712
713If there is an error, C<.can_trim> should call C<nbdkit_error> with an
714error message and return C<-1>.
715
716This callback is not required.  If omitted, then we return true iff a
717C<.trim> callback has been defined.
718
719=head2 C<.can_zero>
720
721 int can_zero (void *handle);
722
723This is called during the option negotiation phase to find out if the
724plugin wants the C<.zero> callback to be utilized.  Support for
725writing zeroes is still advertised to the client (unless the
726L<nbdkit-nozero-filter(1)> is also used), so returning false merely
727serves as a way to avoid complicating the C<.zero> callback to have to
728fail with C<ENOTSUP> or C<EOPNOTSUPP> on the connections where it will
729never be more efficient than using C<.pwrite> up front.
730
731If there is an error, C<.can_zero> should call C<nbdkit_error> with an
732error message and return C<-1>.
733
734This callback is not required.  If omitted, then for a normal zero
735request, nbdkit always tries C<.zero> first if it is present, and
736gracefully falls back to C<.pwrite> if C<.zero> was absent or failed
737with C<ENOTSUP> or C<EOPNOTSUPP>.
738
739=head2 C<.can_fast_zero>
740
741 int can_fast_zero (void *handle);
742
743This is called during the option negotiation phase to find out if the
744plugin wants to advertise support for fast zero requests.  If this
745support is not advertised, a client cannot attempt fast zero requests,
746and has no way to tell if writing zeroes offers any speedups compared
747to using C<.pwrite> (other than compressed network traffic).  If
748support is advertised, then C<.zero> will have
749C<NBDKIT_FLAG_FAST_ZERO> set when the client has requested a fast
750zero, in which case the plugin must fail with C<ENOTSUP> or
751C<EOPNOTSUPP> up front if the request would not offer any benefits
752over C<.pwrite>.  Advertising support for fast zero requests does not
753require that writing zeroes be fast, only that the result (whether
754success or failure) is fast, so this should be advertised when
755feasible.
756
757If there is an error, C<.can_fast_zero> should call C<nbdkit_error>
758with an error message and return C<-1>.
759
760This callback is not required.  If omitted, then nbdkit returns true
761if C<.zero> is absent or C<.can_zero> returns false (in those cases,
762nbdkit fails all fast zero requests, as its fallback to C<.pwrite> is
763not inherently faster), otherwise false (since it cannot be determined
764in advance if the plugin's C<.zero> will properly honor the semantics
765of C<NBDKIT_FLAG_FAST_ZERO>).
766
767=head2 C<.can_extents>
768
769 int can_extents (void *handle);
770
771This is called during the option negotiation phase to find out if the
772plugin supports detecting allocated (non-sparse) regions of the disk
773with the C<.extents> callback.
774
775If there is an error, C<.can_extents> should call C<nbdkit_error> with
776an error message and return C<-1>.
777
778This callback is not required.  If omitted, then we return true iff a
779C<.extents> callback has been defined.
780
781=head2 C<.can_fua>
782
783 int can_fua (void *handle);
784
785This is called during the option negotiation phase to find out if the
786plugin supports the Forced Unit Access (FUA) flag on write, zero, and
787trim requests.  If this returns C<NBDKIT_FUA_NONE>, FUA support is not
788advertised to the client; if this returns C<NBDKIT_FUA_EMULATE>, the
789C<.flush> callback must work (even if C<.can_flush> returns false),
790and FUA support is emulated by calling C<.flush> after any write
791operation; if this returns C<NBDKIT_FUA_NATIVE>, then the C<.pwrite>,
792C<.zero>, and C<.trim> callbacks (if implemented) must handle the flag
793C<NBDKIT_FLAG_FUA>, by not returning until that action has landed in
794persistent storage.
795
796If there is an error, C<.can_fua> should call C<nbdkit_error> with an
797error message and return C<-1>.
798
799This callback is not required unless a plugin wants to specifically
800handle FUA requests.  If omitted, nbdkit checks whether C<.flush>
801exists, and behaves as if this function returns C<NBDKIT_FUA_NONE> or
802C<NBDKIT_FUA_EMULATE> as appropriate.
803
804=head2 C<.can_multi_conn>
805
806 int can_multi_conn (void *handle);
807
808This is called during the option negotiation phase to find out if the
809plugin is prepared to handle multiple connections from a single
810client.  If the plugin sets this to true then a client may try to open
811multiple connections to the nbdkit server and spread requests across
812all connections to maximize parallelism.  If the plugin sets it to
813false (which is the default) then well-behaved clients should only
814open a single connection, although we cannot control what clients do
815in practice.
816
817Specifically it means that either the plugin does not cache requests
818at all.  Or if it does cache them then the effects of a C<.flush>
819request or setting C<NBDKIT_FLAG_FUA> on a request must be visible
820across all connections to the plugin before the plugin replies to that
821request.
822
823Properly working clients should send the same export name for each of
824these connections.
825
826If you use Linux L<nbd-client(8)> option S<I<-C num>> with
827S<num E<gt> 1> then Linux checks this flag and will refuse to connect
828if C<.can_multi_conn> is false.
829
830If there is an error, C<.can_multi_conn> should call C<nbdkit_error>
831with an error message and return C<-1>.
832
833This callback is not required.  If omitted, then we return false.
834
835=head2 C<.can_cache>
836
837 int can_cache (void *handle);
838
839This is called during the option negotiation phase to find out if the
840plugin supports a cache operation. The nature of the caching is
841unspecified (including whether there are limits on how much can be
842cached at once, and whether writes to a cached region have
843write-through or write-back semantics), but the command exists to let
844clients issue a hint to the server that they will be accessing that
845region of the export.
846
847If this returns C<NBDKIT_CACHE_NONE>, cache support is not advertised
848to the client; if this returns C<NBDKIT_CACHE_EMULATE>, caching is
849emulated by the server calling C<.pread> and ignoring the results; if
850this returns C<NBDKIT_CACHE_NATIVE>, then the C<.cache> callback will
851be used.  If there is an error, C<.can_cache> should call
852C<nbdkit_error> with an error message and return C<-1>.
853
854This callback is not required.  If omitted, then we return
855C<NBDKIT_CACHE_NONE> if the C<.cache> callback is missing, or
856C<NBDKIT_CACHE_NATIVE> if it is defined.
857
858=head2 C<.pread>
859
860 int pread (void *handle, void *buf, uint32_t count, uint64_t offset,
861            uint32_t flags);
862
863During the data serving phase, nbdkit calls this callback to read data
864from the backing store.  C<count> bytes starting at C<offset> in the
865backing store should be read and copied into C<buf>.  nbdkit takes
866care of all bounds- and sanity-checking, so the plugin does not need
867to worry about that.
868
869The parameter C<flags> exists in case of future NBD protocol
870extensions; at this time, it will be 0 on input.
871
872The callback must read the whole C<count> bytes if it can.  The NBD
873protocol doesn't allow partial reads (instead, these would be errors).
874If the whole C<count> bytes was read, the callback should return C<0>
875to indicate there was I<no> error.
876
877If there is an error (including a short read which couldn't be
878recovered from), C<.pread> should call C<nbdkit_error> with an error
879message, and C<nbdkit_set_error> to record an appropriate error
880(unless C<errno> is sufficient), then return C<-1>.
881
882=head2 C<.pwrite>
883
884 int pwrite (void *handle, const void *buf, uint32_t count, uint64_t offset,
885             uint32_t flags);
886
887During the data serving phase, nbdkit calls this callback to write
888data to the backing store.  C<count> bytes starting at C<offset> in
889the backing store should be written using the data in C<buf>.  nbdkit
890takes care of all bounds- and sanity-checking, so the plugin does not
891need to worry about that.
892
893This function will not be called if C<.can_write> returned false.  The
894parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based on
895the result of C<.can_fua>.
896
897The callback must write the whole C<count> bytes if it can.  The NBD
898protocol doesn't allow partial writes (instead, these would be
899errors).  If the whole C<count> bytes was written successfully, the
900callback should return C<0> to indicate there was I<no> error.
901
902If there is an error (including a short write which couldn't be
903recovered from), C<.pwrite> should call C<nbdkit_error> with an error
904message, and C<nbdkit_set_error> to record an appropriate error
905(unless C<errno> is sufficient), then return C<-1>.
906
907=head2 C<.flush>
908
909 int flush (void *handle, uint32_t flags);
910
911During the data serving phase, this callback is used to
912L<fdatasync(2)> the backing store, ie. to ensure it has been
913completely written to a permanent medium.  If that is not possible
914then you can omit this callback.
915
916This function will not be called directly by the client if
917C<.can_flush> returned false; however, it may still be called by
918nbdkit if C<.can_fua> returned C<NBDKIT_FUA_EMULATE>.  The parameter
919C<flags> exists in case of future NBD protocol extensions; at this
920time, it will be 0 on input.
921
922If there is an error, C<.flush> should call C<nbdkit_error> with an
923error message, and C<nbdkit_set_error> to record an appropriate error
924(unless C<errno> is sufficient), then return C<-1>.
925
926=head2 C<.trim>
927
928 int trim (void *handle, uint32_t count, uint64_t offset, uint32_t flags);
929
930During the data serving phase, this callback is used to "punch holes"
931in the backing store.  If that is not possible then you can omit this
932callback.
933
934This function will not be called if C<.can_trim> returned false.  The
935parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based on
936the result of C<.can_fua>.
937
938If there is an error, C<.trim> should call C<nbdkit_error> with an
939error message, and C<nbdkit_set_error> to record an appropriate error
940(unless C<errno> is sufficient), then return C<-1>.
941
942=head2 C<.zero>
943
944 int zero (void *handle, uint32_t count, uint64_t offset, uint32_t flags);
945
946During the data serving phase, this callback is used to write C<count>
947bytes of zeroes at C<offset> in the backing store.
948
949This function will not be called if C<.can_zero> returned false.  On
950input, the parameter C<flags> may include C<NBDKIT_FLAG_MAY_TRIM>
951unconditionally, C<NBDKIT_FLAG_FUA> based on the result of
952C<.can_fua>, and C<NBDKIT_FLAG_FAST_ZERO> based on the result of
953C<.can_fast_zero>.
954
955If C<NBDKIT_FLAG_MAY_TRIM> is requested, the operation can punch a
956hole instead of writing actual zero bytes, but only if subsequent
957reads from the hole read as zeroes.
958
959If C<NBDKIT_FLAG_FAST_ZERO> is requested, the plugin must decide up
960front if the implementation is likely to be faster than a
961corresponding C<.pwrite>; if not, then it must immediately fail with
962C<ENOTSUP> or C<EOPNOTSUPP> (whether by C<nbdkit_set_error> or
963C<errno>) and preferably without modifying the exported image.  It is
964acceptable to always fail a fast zero request (as a fast failure is
965better than attempting the write only to find out after the fact that
966it was not fast after all).  Note that on Linux, support for
967C<ioctl(BLKZEROOUT)> is insufficient for determining whether a zero
968request to a block device will be fast (because the kernel will
969perform a slow fallback when needed).
970
971The callback must write the whole C<count> bytes if it can.  The NBD
972protocol doesn't allow partial writes (instead, these would be
973errors).  If the whole C<count> bytes was written successfully, the
974callback should return C<0> to indicate there was I<no> error.
975
976If there is an error, C<.zero> should call C<nbdkit_error> with an
977error message, and C<nbdkit_set_error> to record an appropriate error
978(unless C<errno> is sufficient), then return C<-1>.
979
980If this callback is omitted, or if it fails with C<ENOTSUP> or
981C<EOPNOTSUPP> (whether by C<nbdkit_set_error> or C<errno>), then
982C<.pwrite> will be used as an automatic fallback except when the
983client requested a fast zero.
984
985=head2 C<.extents>
986
987 int extents (void *handle, uint32_t count, uint64_t offset,
988              uint32_t flags, struct nbdkit_extents *extents);
989
990During the data serving phase, this callback is used to detect
991allocated, sparse and zeroed regions of the disk.
992
993This function will not be called if C<.can_extents> returned false.
994nbdkit's default behaviour in this case is to treat the whole virtual
995disk as if it was allocated.  Also, this function will not be called
996by a client that does not request structured replies (the I<--no-sr>
997option of nbdkit can be used to test behavior when C<.extents> is
998unavailable to the client).
999
1000The callback should detect and return the list of extents overlapping
1001the range C<[offset...offset+count-1]>.  The C<extents> parameter
1002points to an opaque object which the callback should fill in by
1003calling C<nbdkit_add_extent>.  See L</Extents list> below.
1004
1005If there is an error, C<.extents> should call C<nbdkit_error> with an
1006error message, and C<nbdkit_set_error> to record an appropriate error
1007(unless C<errno> is sufficient), then return C<-1>.
1008
1009=head3 Extents list
1010
1011The plugin C<extents> callback is passed an opaque pointer C<struct
1012nbdkit_extents *extents>.  This structure represents a list of
1013L<filesystem extents|https://en.wikipedia.org/wiki/Extent_(file_systems)>
1014describing which areas of the disk are allocated, which are sparse
1015(“holes”), and, if supported, which are zeroes.
1016
1017The C<extents> callback should scan the disk starting at C<offset> and
1018call C<nbdkit_add_extent> for each extent found.
1019
1020Extents overlapping the range C<[offset...offset+count-1]> should be
1021returned if possible.  However nbdkit ignores extents E<lt> offset so
1022the plugin may, if it is easier to implement, return all extent
1023information for the whole disk.  The plugin may return extents beyond
1024the end of the range.  It may also return extent information for less
1025than the whole range, but it must return at least one extent
1026overlapping C<offset>.
1027
1028The extents B<must> be added in ascending order, and B<must> be
1029contiguous.
1030
1031The C<flags> parameter of the C<.extents> callback may contain the
1032flag C<NBDKIT_FLAG_REQ_ONE>.  This means that the client is only
1033requesting information about the extent overlapping C<offset>.  The
1034plugin may ignore this flag, or as an optimization it may return just
1035a single extent for C<offset>.
1036
1037 int nbdkit_add_extent (struct nbdkit_extents *extents,
1038                        uint64_t offset, uint64_t length, uint32_t type);
1039
1040Add an extent covering C<[offset...offset+length-1]> of one of
1041the following four types:
1042
1043=over 4
1044
1045=item C<type = 0>
1046
1047A normal, allocated data extent.
1048
1049=item C<type = NBDKIT_EXTENT_HOLE|NBDKIT_EXTENT_ZERO>
1050
1051An unallocated extent, a.k.a. a “hole”, which reads back as zeroes.
1052This is the normal type of hole applicable to most disks.
1053
1054=item C<type = NBDKIT_EXTENT_ZERO>
1055
1056An allocated extent which is known to contain only zeroes.
1057
1058=item C<type = NBDKIT_EXTENT_HOLE>
1059
1060An unallocated extent (hole) which does not read back as zeroes.  Note
1061this should only be used in specialized circumstances such as when
1062writing a plugin for (or to emulate) certain SCSI drives which do not
1063guarantee that trimmed blocks read back as zeroes.
1064
1065=back
1066
1067C<nbdkit_add_extent> returns C<0> on success or C<-1> on failure.  On
1068failure C<nbdkit_error> and/or C<nbdkit_set_error> has already been
1069called.  C<errno> will be set to a suitable value.
1070
1071=head2 C<.cache>
1072
1073 int cache (void *handle, uint32_t count, uint64_t offset, uint32_t flags);
1074
1075During the data serving phase, this callback is used to give the
1076plugin a hint that the client intends to make further accesses to the
1077given region of the export.  The nature of caching is not specified
1078further by the NBD specification (for example, a server may place
1079limits on how much may be cached at once, and there is no way to
1080control if writes to a cached area have write-through or write-back
1081semantics).  In fact, the cache command can always fail and still be
1082compliant, and success might not guarantee a performance gain.  If
1083this callback is omitted, then the results of C<.can_cache> determine
1084whether nbdkit will reject cache requests, treat them as instant
1085success, or emulate caching by calling C<.pread> over the same region
1086and ignoring the results.
1087
1088This function will not be called if C<.can_cache> did not return
1089C<NBDKIT_CACHE_NATIVE>.  The parameter C<flags> exists in case of
1090future NBD protocol extensions; at this time, it will be 0 on input. A
1091plugin must fail this function if C<flags> includes an unrecognized
1092flag, as that may indicate a requirement that the plugin comply must
1093with a specific caching semantic.
1094
1095If there is an error, C<.cache> should call C<nbdkit_error> with an
1096error message, and C<nbdkit_set_error> to record an appropriate error
1097(unless C<errno> is sufficient), then return C<-1>.
1098
1099=head2 C<.errno_is_preserved>
1100
1101This field defaults to 0; if non-zero, nbdkit can reliably use the
1102value of C<errno> when a callback reports failure, rather than the
1103plugin having to call C<nbdkit_set_error>.
1104
1105=head1 SHUTDOWN
1106
1107When nbdkit receives certain signals it will shut down (see
1108L<nbdkit(1)/SIGNALS>).  The server will wait for any currently running
1109plugin callbacks to finish and also call the C<.unload> callback
1110before unloading the plugin.
1111
1112Note that it's not guaranteed this can always happen (eg. the server
1113might be killed by C<SIGKILL> or segfault).
1114
1115=head2 Requesting asynchronous shutdown
1116
1117Plugins and filters can call L<exit(3)> in the configuration phase
1118(before and including C<.get_ready>, but not in connected callbacks).
1119
1120Once nbdkit has started serving connections, plugins and filters
1121should not call L<exit(3)>.  However they may instruct nbdkit to shut
1122down by calling C<nbdkit_shutdown>:
1123
1124 void nbdkit_shutdown (void);
1125
1126This function requests an asynchronous shutdown and returns (I<note>
1127that it does I<not> exit the process immediately).  It ensures that
1128the plugin and all filters are unloaded cleanly which may take some
1129time.  Further callbacks from nbdkit into the plugin or filter may
1130occur after you have called this.
1131
1132=head1 PARSING COMMAND LINE PARAMETERS
1133
1134=head2 Parsing numbers
1135
1136There are several functions for parsing numbers.  These all deal
1137correctly with overflow, out of range and parse errors, and you should
1138use them instead of unsafe functions like L<sscanf(3)>, L<atoi(3)> and
1139similar.
1140
1141 int nbdkit_parse_int (const char *what, const char *str, int *r);
1142 int nbdkit_parse_unsigned (const char *what,
1143                            const char *str, unsigned *r);
1144 int nbdkit_parse_int8_t (const char *what,
1145                          const char *str, int8_t *r);
1146 int nbdkit_parse_uint8_t (const char *what,
1147                           const char *str, uint8_t *r);
1148 int nbdkit_parse_int16_t (const char *what,
1149                           const char *str, int16_t *r);
1150 int nbdkit_parse_uint16_t (const char *what,
1151                            const char *str, uint16_t *r);
1152 int nbdkit_parse_int32_t (const char *what,
1153                           const char *str, int32_t *r);
1154 int nbdkit_parse_uint32_t (const char *what,
1155                            const char *str, uint32_t *r);
1156 int nbdkit_parse_int64_t (const char *what,
1157                           const char *str, int64_t *r);
1158 int nbdkit_parse_uint64_t (const char *what,
1159                            const char *str, uint64_t *r);
1160
1161Parse string C<str> into an integer of various types.  These functions
1162parse a decimal, hexadecimal (C<"0x...">) or octal (C<"0...">) number.
1163
1164On success the functions return C<0> and set C<*r> to the parsed value
1165(unless C<*r == NULL> in which case the result is discarded).  On
1166error, C<nbdkit_error> is called and the functions return C<-1>.  On
1167error C<*r> is always unchanged.
1168
1169The C<what> parameter is printed in error messages to provide context.
1170It should usually be a short descriptive string of what you are trying
1171to parse, eg:
1172
1173 if (nbdkit_parse_int ("random seed", argv[1], &seed) == -1)
1174   return -1;
1175
1176might print an error:
1177
1178 random seed: could not parse number: "lalala"
1179
1180=head2 Parsing sizes
1181
1182Use the C<nbdkit_parse_size> utility function to parse human-readable
1183size strings such as "100M" into the size in bytes.
1184
1185 int64_t nbdkit_parse_size (const char *str);
1186
1187C<str> can be a string in a number of common formats.  The function
1188returns the size in bytes.  If there was an error, it returns C<-1>.
1189
1190=head2 Parsing booleans
1191
1192Use the C<nbdkit_parse_bool> utility function to parse human-readable
1193strings such as "on" into a boolean value.
1194
1195 int nbdkit_parse_bool (const char *str);
1196
1197C<str> can be a string containing a case-insensitive form of various
1198common toggle values.  The function returns 0 or 1 if the parse was
1199successful.  If there was an error, it returns C<-1>.
1200
1201=head2 Reading passwords
1202
1203The C<nbdkit_read_password> utility function can be used to read
1204passwords from config parameters:
1205
1206 int nbdkit_read_password (const char *value, char **password);
1207
1208For example:
1209
1210 char *password = NULL;
1211
1212 static int
1213 myplugin_config (const char *key, const char *value)
1214 {
1215   ..
1216   if (strcmp (key, "password") == 0) {
1217     free (password);
1218     if (nbdkit_read_password (value, &password) == -1)
1219       return -1;
1220   }
1221   ..
1222 }
1223
1224The C<password> result string is allocated by malloc, and so you may
1225need to free it.
1226
1227This function recognizes several password formats.  A password may be
1228used directly on the command line, eg:
1229
1230 nbdkit myplugin password=mostsecret
1231
1232But more securely this function can also read a password
1233interactively:
1234
1235 nbdkit myplugin password=-
1236
1237or from a file:
1238
1239 nbdkit myplugin password=+/tmp/secret
1240
1241or from a file descriptor inherited by nbdkit:
1242
1243 nbdkit myplugin password=-99
1244
1245=head3 Notes on reading passwords
1246
1247If the password begins with a C<-> or C<+> character then it must be
1248passed in a file.
1249
1250C<password=-> can only be used when stdin is a terminal.
1251
1252C<password=-FD> cannot be used with stdin, stdout or stderr
1253(ie. C<-0>, C<-1> or C<-2>).  The reason is that after reading the
1254password the file descriptor is closed, which causes bad stuff to
1255happen.
1256
1257=head2 Safely interacting with stdin and stdout
1258
1259 int nbdkit_stdio_safe (void);
1260
1261The C<nbdkit_stdio_safe> utility function returns C<1> if it is safe
1262to interact with stdin and stdout during the configuration phase, and
1263C<0> otherwise.  This is because when the nbdkit I<-s> option is used
1264the plugin must not directly interact with stdin, because that would
1265interfere with the client.
1266
1267The result of this function only matters in callbacks up to
1268C<.config_complete>.  Once nbdkit reaches C<.get_ready>, the plugin
1269should assume that nbdkit may have closed the original stdin and
1270stdout in order to become a daemon.
1271
1272L<nbdkit-sh-plugin(3)> uses this function to determine whether it is
1273safe to support C<script=-> to read a script from stdin.  Also
1274constructs like C<password=-> (see L</Reading passwords> above) are
1275disabled when reading from stdio is not safe.
1276
1277=head1 FILENAMES AND PATHS
1278
1279The server usually (not always) changes directory to C</> before it
1280starts serving connections.  This means that any relative paths passed
1281during configuration will not work when the server is running
1282(example: S<C<nbdkit plugin.so disk.img>>).
1283
1284To avoid problems, prepend relative paths with the current directory
1285before storing them in the handle.  Or open files and store the file
1286descriptor.
1287
1288=head2 C<nbdkit_absolute_path>
1289
1290 char *nbdkit_absolute_path (const char *filename);
1291
1292The utility function C<nbdkit_absolute_path> converts any path to an
1293absolute path: if it is relative, then all this function does is
1294prepend the current working directory to the path, with no extra
1295checks.
1296
1297Note that this function works I<only> when used in the C<.config>,
1298C<.config_complete> and C<.get_ready> callbacks.
1299
1300If conversion was not possible, this calls C<nbdkit_error> and returns
1301C<NULL>.  Note that this function does not check that the file exists.
1302
1303The returned string must be freed by the caller.
1304
1305=head2 C<nbdkit_realpath>
1306
1307 char *nbdkit_realpath (const char *filename);
1308
1309The utility function C<nbdkit_realpath> converts any path to an
1310absolute path, resolving symlinks.  Under the hood it uses the
1311C<realpath> function, and thus it fails if the path does not exist,
1312or it is not possible to access to any of the components of the path.
1313
1314Note that this function works I<only> when used in the C<.config>,
1315C<.config_complete> and C<.get_ready> callbacks.
1316
1317If the path resolution was not possible, this calls C<nbdkit_error>
1318and returns C<NULL>.
1319
1320The returned string must be freed by the caller.
1321
1322=head2 umask
1323
1324All plugins will see a L<umask(2)> of C<0022>.
1325
1326=head1 SLEEPING
1327
1328A plugin that needs to sleep may call L<sleep(2)>, L<nanosleep(2)> and
1329similar.  However that can cause nbdkit to delay excessively when
1330shutting down (since it must wait for any plugin or filter which is
1331sleeping).  To avoid this there is a special wrapper around nanosleep
1332which plugins and filters should use instead.
1333
1334=head2 C<nbdkit_nanosleep>
1335
1336 int nbdkit_nanosleep (unsigned sec, unsigned nsec);
1337
1338The utility function C<nbdkit_nanosleep> suspends the current thread,
1339and returns 0 if it slept at least as many seconds and nanoseconds as
1340requested, or -1 after calling C<nbdkit_error> if there is no point in
1341continuing the current command.  Attempts to sleep more than
1342C<INT_MAX> seconds are treated as an error.
1343
1344=head1 EXPORT NAME
1345
1346If the client negotiated an NBD export name with nbdkit then plugins
1347may read this from any connected callbacks.  Nbdkit's normal behaviour
1348is to accept any export name passed by the client, log it in debug
1349output, but otherwise ignore it.  By using C<nbdkit_export_name>
1350plugins may choose to filter by export name or serve different
1351content.
1352
1353=head2 C<nbdkit_export_name>
1354
1355 const char *nbdkit_export_name (void);
1356
1357Return the optional NBD export name if one was negotiated with the
1358current client (this uses thread-local magic so no parameter is
1359required).  The returned string is only valid while the client is
1360connected, so if you need to store it in the plugin you must copy it.
1361
1362The export name is a free-form text string, it is not necessarily a
1363path or filename and it does not need to begin with a C<'/'>
1364character.  The NBD protocol describes the empty string (C<"">) as a
1365representing a "default export" or to be used in cases where the
1366export name does not make sense.  B<The export name is untrusted
1367client data, be cautious when parsing it.>
1368
1369On error, C<nbdkit_error> is called and the call returns C<NULL>.
1370
1371=head1 PEER NAME
1372
1373It is possible to get the address of the client when you are running
1374in any connected callback.
1375
1376=head2 C<nbdkit_peer_name>
1377
1378 int nbdkit_peer_name (struct sockaddr *addr, socklen_t *addrlen);
1379
1380Return the peer (client) address, if available.  The C<addr> and
1381C<addrlen> parameters behave like L<getpeername(2)>.  In particular
1382you must initialize C<addrlen> with the size of the buffer pointed to
1383by C<addr>, and if C<addr> is not large enough then the address will
1384be truncated.
1385
1386In some cases this is not available or the address returned will be
1387meaningless (eg. if there is a proxy between the client and nbdkit).
1388This call uses thread-local magic so no parameter is required to
1389specify the current connection.
1390
1391On success this returns C<0>.  On error, C<nbdkit_error> is called and
1392this call returns C<-1>.
1393
1394=head1 DEBUGGING
1395
1396Run the server with I<-f> and I<-v> options so it doesn't fork and you
1397can see debugging information:
1398
1399 nbdkit -fv ./myplugin.so [key=value [key=value [...]]]
1400
1401To print debugging information from within the plugin, call
1402C<nbdkit_debug>, which has the following prototype and works like
1403L<printf(3)>:
1404
1405 void nbdkit_debug (const char *fs, ...);
1406 void nbdkit_vdebug (const char *fs, va_list args);
1407
1408For convenience, C<nbdkit_debug> preserves the value of C<errno>, and
1409also supports the glibc extension of a single C<%m> in a format string
1410expanding to C<strerror(errno)>, even on platforms that don't support
1411that natively. Note that C<nbdkit_debug> only prints things when the
1412server is in verbose mode (I<-v> option).
1413
1414=head2 Debug Flags
1415
1416The I<-v> option switches general debugging on or off, and this
1417debugging should be used for messages which are useful for all users
1418of your plugin.
1419
1420In cases where you want to enable specific extra debugging to track
1421down bugs in plugins or filters — mainly for use by the plugin/filter
1422developers themselves — you can define Debug Flags.  These are global
1423ints called C<myplugin_debug_*>:
1424
1425 int myplugin_debug_foo;
1426 int myplugin_debug_bar;
1427 ...
1428 if (myplugin_debug_foo) {
1429   nbdkit_debug ("lots of extra debugging about foo: ...");
1430 }
1431
1432Debug Flags can be controlled on the command line using the I<-D> (or
1433I<--debug>) option:
1434
1435 nbdkit -f -v -D myplugin.foo=1 -D myplugin.bar=2 myplugin [...]
1436
1437Note C<myplugin> is the name passed to C<.name> in the C<struct
1438nbdkit_plugin>.
1439
1440You should only use this feature for debug settings.  For general
1441settings use ordinary plugin parameters.  Debug Flags can only be C
1442ints.  They are not supported by non-C language plugins.
1443
1444For convenience C<'.'> characters are replaced with C<'_'> characters
1445in the variable name, so both of these parameters:
1446
1447 -D myplugin.foo_bar=1
1448 -D myplugin.foo.bar=1
1449
1450correspond to the plugin variable C<myplugin_debug_foo_bar>.
1451
1452=head1 COMPILING THE PLUGIN
1453
1454Plugins should be compiled as shared libraries.  There are various
1455ways to achieve this, but most Linux compilers support a I<-shared>
1456option to create the shared library directly, for example:
1457
1458 gcc -fPIC -shared myplugin.c -o myplugin.so
1459
1460Note that the shared library will have undefined symbols for functions
1461that you call like C<nbdkit_parse_int> or C<nbdkit_error>.  These will
1462be resolved by the server binary when nbdkit dlopens the plugin.
1463
1464=head2 PKG-CONFIG/PKGCONF
1465
1466nbdkit provides a pkg-config/pkgconf file called C<nbdkit.pc> which
1467should be installed on the correct path when the nbdkit plugin
1468development environment is installed.  You can use this in autoconf
1469F<configure.ac> scripts to test for the development environment:
1470
1471 PKG_CHECK_MODULES([NBDKIT], [nbdkit >= 1.2.3])
1472
1473The above will fail unless nbdkit E<ge> 1.2.3 and the header file is
1474installed, and will set C<NBDKIT_CFLAGS> and C<NBDKIT_LIBS>
1475appropriately for compiling plugins.
1476
1477You can also run pkg-config/pkgconf directly, for example:
1478
1479 if ! pkg-config nbdkit --exists; then
1480   echo "you must install the nbdkit plugin development environment"
1481   exit 1
1482 fi
1483
1484You can also substitute the plugindir variable by doing:
1485
1486 PKG_CHECK_VAR([NBDKIT_PLUGINDIR], [nbdkit], [plugindir])
1487
1488which defines C<$(NBDKIT_PLUGINDIR)> in automake-generated Makefiles.
1489
1490If nbdkit development headers are installed in a non-standard location
1491then you may need to compile plugins using:
1492
1493 gcc -fPIC -shared myplugin.c -o myplugin.so \
1494   `pkg-config nbdkit --cflags --libs`
1495
1496=head1 INSTALLING THE PLUGIN
1497
1498The plugin is a C<*.so> file and possibly a manual page.  You can of
1499course install the plugin C<*.so> file wherever you want, and users
1500will be able to use it by running:
1501
1502 nbdkit /path/to/plugin.so [args]
1503
1504However B<if> the shared library has a name of the form
1505C<nbdkit-I<name>-plugin.so> B<and if> the library is installed in the
1506C<$plugindir> directory, then users can be run it by only typing:
1507
1508 nbdkit name [args]
1509
1510The location of the C<$plugindir> directory is set when nbdkit is
1511compiled and can be found by doing:
1512
1513 nbdkit --dump-config
1514
1515If using the pkg-config/pkgconf system then you can also find the
1516plugin directory at compile time by doing:
1517
1518 pkg-config nbdkit --variable=plugindir
1519
1520=head1 WRITING PLUGINS IN OTHER PROGRAMMING LANGUAGES
1521
1522You can also write nbdkit plugins in Go, Lua, OCaml, Perl, Python,
1523Ruby, Rust, shell script or Tcl.  Other programming languages may be
1524offered in future.
1525
1526For more information see:
1527__LANG_PLUGIN_LINKS__.
1528
1529Plugins written in scripting languages may also be installed in
1530C<$plugindir>.  These must be called C<nbdkit-I<name>-plugin> without
1531any extension.  They must be executable, and they must use the shebang
1532header (see L<nbdkit(1)/Shebang scripts>).  For example a plugin
1533written in Perl called C<foo.pl> might be installed like this:
1534
1535 $ head -1 foo.pl
1536 #!/usr/sbin/nbdkit perl
1537
1538 $ sudo install -m 0755 foo.pl $plugindir/nbdkit-foo-plugin
1539
1540and then users will be able to run it like this:
1541
1542 $ nbdkit foo [args ...]
1543
1544=head1 SEE ALSO
1545
1546L<nbdkit(1)>,
1547L<nbdkit-nozero-filter(3)>,
1548L<nbdkit-filter(3)>.
1549
1550Standard plugins provided by nbdkit:
1551
1552__PLUGIN_LINKS__.
1553
1554=head1 AUTHORS
1555
1556Eric Blake
1557
1558Richard W.M. Jones
1559
1560Pino Toscano
1561
1562=head1 COPYRIGHT
1563
1564Copyright (C) 2013-2020 Red Hat Inc.
1565