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