Update Red Hat Copyright Notices
[nbdkit.git] / docs / nbdkit-filter.pod
blobf4ee3789c378223cecd2bf940445bcb9b79c6e33
1 =head1 NAME
3 nbdkit-filter - how to write nbdkit filters
5 =head1 SYNOPSIS
7  #include <nbdkit-filter.h>
9  static int
10  myfilter_config (nbdkit_next_config *next, void *nxdata,
11                   const char *key, const char *value)
12  {
13    if (strcmp (key, "myparameter") == 0) {
14      // ...
15      return 0;
16    }
17    else {
18      // pass through to next filter or plugin
19      return next (nxdata, key, value);
20    }
21  }
23  static struct nbdkit_filter filter = {
24    .name              = "filter",
25    .config            = myfilter_config,
26    /* etc */
27  };
29  NBDKIT_REGISTER_FILTER(filter)
31 When this has been compiled to a shared library, do:
33  nbdkit [--args ...] --filter=./myfilter.so plugin [key=value ...]
35 When debugging, use the I<-fv> options:
37  nbdkit -fv --filter=./myfilter.so plugin [key=value ...]
39 =head1 DESCRIPTION
41 One or more nbdkit filters can be placed in front of an nbdkit plugin
42 to modify the behaviour of the plugin.  This manual page describes how
43 to create an nbdkit filter.
45 Filters can be used for example to limit requests to an offset/limit,
46 add copy-on-write support, or inject delays or errors (for testing).
48 Different filters can be stacked:
50      NBD     ┌─────────┐    ┌─────────┐          ┌────────┐
51   client ───▶│ filter1 │───▶│ filter2 │── ─ ─ ──▶│ plugin │
52  request     └─────────┘    └─────────┘          └────────┘
54 Each filter intercepts plugin functions (see L<nbdkit-plugin(3)>) and
55 can call the next filter or plugin in the chain, modifying parameters,
56 calling before the filter function, in the middle or after.  Filters
57 may even short-cut the chain.  As an example, to process its own
58 parameters the filter can intercept the C<.config> method:
60  static int
61  myfilter_config (nbdkit_next_config *next, void *nxdata,
62                   const char *key, const char *value)
63  {
64    if (strcmp (key, "myparameter") == 0) {
65      // ...
66      // here you would handle this key, value
67      // ...
68      return 0;
69    }
70    else {
71      // pass through to next filter or plugin
72      return next (nxdata, key, value);
73    }
74  }
76  static struct nbdkit_filter filter = {
77    // ...
78    .config            = myfilter_config,
79    // ...
80  };
82 The call to C<next (nxdata, ...)> calls the C<.config> method of the
83 next filter or plugin in the chain.  In the example above any
84 instances of C<myparameter=...> on the command line would not be seen
85 by the plugin.
87 To see example filters:
88 L<https://gitlab.com/nbdkit/nbdkit/tree/master/filters>
90 Filters must be written in C.
92 Unlike plugins, where we provide a stable ABI guarantee that permits
93 operation across version differences, filters can only be run with the
94 same version of nbdkit that they were compiled with.  The reason for
95 this is two-fold: the filter API includes access to struct
96 nbdkit_next_ops that is likely to change if new callbacks are added
97 (old nbdkit cannot safely run new filters that access new methods);
98 and if we added new methods then an old filter would not see them and
99 so they would be passed unmodified through the filter, and in some
100 cases that leads to data corruption (new nbdkit cannot safely run old
101 filters unaware of new methods).  Therefore, unlike plugins, you
102 should not expect to distribute filters separately from nbdkit.
104 =head1 C<#include E<lt>nbdkit-filter.hE<gt>>
106 All filters should start by including this header file.
108 =head1 C<struct nbdkit_filter>
110 All filters must define and register one C<struct nbdkit_filter>,
111 which contains the name of the filter and pointers to plugin methods
112 that the filter wants to intercept.
114  static struct nbdkit_filter filter = {
115    .name              = "filter",
116    .longname          = "My Filter",
117    .description       = "This is my great filter for nbdkit",
118    .config            = myfilter_config,
119    /* etc */
120  };
122  NBDKIT_REGISTER_FILTER(filter)
124 The C<.name> field is the name of the filter.  This is the only field
125 which is required.
127 =head1 NEXT PLUGIN
129 F<nbdkit-filter.h> defines some function types (C<nbdkit_next_config>,
130 C<nbdkit_next_config_complete>, C<nbdkit_next_preconnect>,
131 C<nbdkit_next_list_exports>, C<nbdkit_next_default_export>,
132 C<nbdkit_next_open>) and a structure called C<struct nbdkit_next_ops>.
133 These abstract the next plugin or filter in the chain.  There is also
134 an opaque pointer C<backend>, C<context> or C<nxdata> which must be
135 passed along when calling these functions.  The value of C<backend> is
136 stable between C<.after_fork>, C<.preconnect>, C<.list_exports>, and
137 C<.default_export>, and can also be obtained by using
138 C<nbdkit_context_get_backend> on the C<context> parameter to C<.open>.
140 Meanwhile, if the filter does not use C<nbdkit_context_set_next>, the
141 value of C<next> passed to C<.prepare> has a stable lifetime that
142 lasts to the corresponding C<.finalize>, with all intermediate
143 functions (such as C<.pread>) receiving the same value for
144 convenience.  Functions where C<nxdata> is not reused are C<.config>,
145 C<.config_complete>, and C<.get_ready>, which are all called during
146 initialization outside any connections.  The value of C<backend>
147 passed to C<.after_fork> also occurs without connections, but is
148 shared with C<.preconnect>, C<.list_exports>, and C<.default_export>,
149 and can also be obtained from the C<context> passed to C<.open>, and
150 has a lifetime that lasts to C<.cleanup> for use by
151 C<nbdkit_next_context_open>.  In turn, the value of C<context> passed
152 to C<.open> has a lifetime that lasts until the matching C<.close> for
153 use by C<nbdkit_context_get_backend> and C<nbdkit_context_set_next>.
155 =head2 Next config, open and close
157 The filter’s C<.config>, C<.config_complete>, C<.get_ready>,
158 C<.after_fork>, C<.preconnect>, C<.list_exports>, C<.default_export>
159 and C<.open> methods may only call the next C<.config>,
160 C<.config_complete>, C<.get_ready>, C<.after_fork>, C<.preconnect>,
161 C<.list_exports>, C<.default_export> and C<.open> method in the chain
162 (optionally for C<.config> and C<.open>).
164 The filter’s C<.close> method is called when an old connection closed,
165 and this has no C<next> parameter because it cannot be
166 short-circuited.
168 =head2 C<nbdkit_next>
170 The filter generally needs to call into the underlying plugin, which
171 is done via a pointer to C<struct nbdkit_next_ops>, also available as
172 the typedef C<nbdkit_next>.  The most common behavior is to create a
173 next context per connection by calling the C<next_open> parameter
174 during C<.open>, at which point the next context will be automatically
175 provided to the filter’s other methods like C<.prepare>, C<.get_size>,
176 C<.pread> etc.  The C<nbdkit_next> struct contains a comparable set of
177 accessors to plugin methods that can be called during a connection.
178 When using automatic registration, the C<next> parameter is stable
179 between C<.prepare> and C<.finalize>, and nbdkit automatically
180 prepares, finalizes, and closes the next context at the right point in
181 the filter connection lifecycle.
183 Alternatively, the filter can manage plugin contexts manually, whether
184 to multiplex multiple client connections through a single context into
185 the plugin, or to open multiple plugin contexts to perform retries or
186 otherwise service a single client connection more efficiently.  In
187 this mode of operation, the filter uses C<nbdkit_next_context_open> to
188 open a plugin context using the C<backend> parameter passed to
189 C<.after_fork>, C<.preconnect>, C<.list_exports>, C<.default_export>,
190 or obtained from using C<nbdkit_context_get_backend> on the C<context>
191 parameter to C<.open>.  The resulting next context has a lifecycle
192 under manual control, where the filter must use C<next-E<gt>prepare
193 (next)> before using any other function pointers within the next
194 context, and must reclaim the memory using C<next-E<gt>finalize
195 (next)> and C<nbdkit_next_context_close> when done.  A filter using
196 manual lifecycle management may use C<nbdkit_context_set_next> to
197 associate the next context into the current connection, which lets
198 nbdkit then pass that context as the C<next> parameter to future
199 connection-related functions like C<.pread> and take over lifecycle
200 responsibility.
202 =head3 C<nbdkit_context_get_backend>
204 =head3 C<nbdkit_next_context_open>
206 =head3 C<nbdkit_next_context_close>
208 =head3 C<nbdkit_context_set_next>
210  nbdkit_backend *nbdkit_context_get_backend (nbdkit_context *context);
212 Obtains the backend pointer from the C<context> parameter to C<.open>,
213 matching the backend pointer available to C<.after_fork>,
214 C<.preconnect>, C<.list_exports>, and C<.default_export>.  This
215 backend pointer has a stable lifetime from the time of C<.after_fork>
216 until C<.cleanup>.
218  nbdkit_next *nbdkit_next_context_open (nbdkit_backend *backend,
219                                         int readonly, const char *exportname,
220                                         int shared);
222 This function attempts to open a new context into the plugin in
223 relation to the filter's current C<backend>.  The C<readonly> and
224 C<exportname> parameters behave the same as documented in C<.open>.
225 The resulting context will be under the filter's manual lifecycle
226 control unless the filter associates it into the connection with
227 C<nbdkit_context_set_next>.  The filter should be careful to not
228 violate any threading model restrictions of the plugin if it opens
229 more than one context.
231 If C<shared> is false, this function must be called while servicing an
232 existing client connection, and the new context will share the same
233 connection details (export name, tls status, and shorter interned
234 string lifetimes) as the current connection, and thus should not be
235 used after the client connection ends.  Conversely, if C<shared> is
236 true, this function may be called outside of a current client
237 connection (such as during C<.after_fork>), and the resulting context
238 may be freely shared among multiple client connections.  In shared
239 mode, it will not be possible for the plugin to differentiate content
240 based on the client export name, the result of the plugin calling
241 nbdkit_is_tls() will depend solely whether I<--tls=require> was on the
242 command line, the lifetime of interned strings (via
243 C<nbdkit_strdup_intern> and friends) lasts for the life of the filter,
244 and the filter must take care to not expose potentially-secure
245 information from the backend to an insecure client.
247  void nbdkit_next_context_close (nbdkit_next *next);
249 This function closes a context into the plugin.  If the context has
250 previously been prepared, it should first be finalized before using
251 this function.  This function does not need to be called for a plugin
252 context that has been associated with the filter connection via
253 C<nbdkit_context_set_next> prior to the C<.close> callback.
255  nbdkit_next *nbdkit_context_set_next (nbdkit_context *context,
256                                        nbdkit_next *next);
258 This function associates a plugin context with the filter's current
259 connection context, given by the C<context> parameter to C<.open>.
260 Once associated, this plugin context will be given as the C<next>
261 parameter to all other connection-specific callbacks.  If associated
262 during C<.open>, nbdkit will take care of preparing the context prior
263 to C<.prepare>; if still associated before C<.finalize>, nbdkit will
264 take care of finalizing the context, and also for closing it.  A
265 filter may also pass C<NULL> for C<next>, to remove any association;
266 if no plugin context is associated with the connection, then filter
267 callbacks such as C<.pread> will receive C<NULL> for their C<next>
268 parameter.
270 This function returns the previous context that had been associated
271 with the connection prior to switching the association to C<next>;
272 this result will be C<NULL> if there was no previous association.  The
273 filter assumes manual responsibility for any remaining lifecycle
274 functions that must be called on the returned context.
276 =head2 Using C<nbdkit_next>
278 Regardless of whether the plugin context is managed automatically or
279 manually, it is possible for a filter to issue (for example) extra
280 C<next-E<gt>pread> calls in response to a single C<.pwrite> call.
282 The C<next> parameter serves two purposes: it serves as the struct
283 to access the pointers to all the plugin connection functions, and it
284 serves as the opaque data that must be passed as the first parameter
285 to those functions.  For example, calling the plugin's can_flush
286 functionality would be done via
288  next->can_flush (next)
290 Note that the semantics of the functions in C<struct nbdkit_next_ops>
291 are slightly different from what a plugin implements: for example,
292 when a plugin's C<.pread> returns -1 on error, the error value to
293 advertise to the client is implicit (via the plugin calling
294 C<nbdkit_set_error> or setting C<errno>), whereas
295 C<next-E<gt>pread> exposes this via an explicit parameter,
296 allowing a filter to learn or modify this error if desired.
298 Use of C<next-E<gt>prepare> and C<next-E<gt>finalize> is only
299 needed when manually managing the plugin context lifetime.
301 =head2 Other considerations
303 You can modify parameters when you call the C<next> function.  However
304 be careful when modifying strings because for some methods
305 (eg. C<.config>) the plugin may save the string pointer that you pass
306 along.  So you may have to ensure that the string is not freed for the
307 lifetime of the server; you may find C<nbdkit_strdup_intern> helpful
308 for avoiding a memory leak while still obeying lifecycle constraints.
310 Note that if your filter registers a callback but in that callback it
311 doesn't call the C<next> function then the corresponding method in the
312 plugin will never be called.  In particular, your C<.open> method, if
313 you have one, B<must> call the C<next> method if you want the
314 underlying plugin to be available to all further C<nbdkit_next> use.
316 =head1 CALLBACKS
318 C<struct nbdkit_filter> has some static fields describing the filter
319 and optional callback functions which can be used to intercept plugin
320 methods.
322 =head2 C<.name>
324  const char *name;
326 This field (a string) is required, and B<must> contain only ASCII
327 alphanumeric characters or non-leading dashes, and be unique amongst
328 all filters.
330 =head2 C<.longname>
332  const char *longname;
334 An optional free text name of the filter.  This field is used in error
335 messages.
337 =head2 C<.description>
339  const char *description;
341 An optional multi-line description of the filter.
343 =head2 C<.load>
345  void load (void);
347 This is called once just after the filter is loaded into memory.  You
348 can use this to perform any global initialization needed by the
349 filter.
351 =head2 C<.unload>
353  void unload (void);
355 This may be called once just before the filter is unloaded from
356 memory.  Note that it's not guaranteed that C<.unload> will always be
357 called (eg. the server might be killed or segfault), so you should try
358 to make the filter as robust as possible by not requiring cleanup.
359 See also L<nbdkit-plugin(3)/SHUTDOWN>.
361 =head2 C<.config>
363  int (*config) (nbdkit_next_config *next, void *nxdata,
364                 const char *key, const char *value);
366 This intercepts the plugin C<.config> method and can be used by the
367 filter to parse its own command line parameters.  You should try to
368 make sure that command line parameter keys that the filter uses do not
369 conflict with ones that could be used by a plugin.
371 If there is an error, C<.config> should call C<nbdkit_error> with an
372 error message and return C<-1>.
374 =head2 C<.config_complete>
376  int (*config_complete) (nbdkit_next_config_complete *next, void *nxdata);
378 This intercepts the plugin C<.config_complete> method and can be used
379 to ensure that all parameters needed by the filter were supplied on
380 the command line.
382 If there is an error, C<.config_complete> should call C<nbdkit_error>
383 with an error message and return C<-1>.
385 =head2 C<.config_help>
387  const char *config_help;
389 This optional multi-line help message should summarize any
390 C<key=value> parameters that it takes.  It does I<not> need to repeat
391 what already appears in C<.description>.
393 If the filter doesn't take any config parameters you should probably
394 omit this.
396 =head2 C<.thread_model>
398  int (*thread_model) (void);
400 Filters may tighten (but not relax) the thread model of the plugin, by
401 defining this callback.  Note that while plugins use a compile-time
402 definition of C<THREAD_MODEL>, filters do not need to declare a model
403 at compile time; instead, this callback is called after
404 C<.config_complete> and before any connections are created.  See
405 L<nbdkit-plugin(3)/THREADS> for a discussion of thread models.
407 The final thread model used by nbdkit is the smallest (ie. most
408 serialized) out of all the filters and the plugin, and applies for all
409 connections.  Requests for a model larger than permitted by the plugin
410 are silently ignored. It is acceptable for decisions made during
411 C<.config> and C<.config_complete> to determine which model to
412 request.
414 This callback is optional; if it is not present, the filter must be
415 written to handle fully parallel requests, including when multiple
416 requests are issued in parallel on the same connection, similar to a
417 plugin requesting C<NBDKIT_THREAD_MODEL_PARALLEL>.  This ensures the
418 filter doesn't slow down other filters or plugins.
420 If there is an error, C<.thread_model> should call C<nbdkit_error>
421 with an error message and return C<-1>.
423 =head2 C<.get_ready>
425  int (*get_ready) (int thread_model);
427 This optional callback is reached if the plugin C<.get_ready> method
428 succeeded (if the plugin failed, nbdkit has already exited), and can
429 be used by the filter to get ready to serve requests.
431 The C<thread_model> parameter informs the filter about the final
432 thread model chosen by nbdkit after considering the results of
433 C<.thread_model> of all filters in the chain after
434 C<.config_complete>.
436 If there is an error, C<.get_ready> should call C<nbdkit_error> with
437 an error message and return C<-1>.
439 =head2 C<.after_fork>
441  int (*after_fork) (nbdkit_backend *backend);
443 This optional callback is reached after the plugin C<.after_fork>
444 method has succeeded (if the plugin failed, nbdkit has already
445 exited), and can be used by the filter to start background threads.
446 The C<backend> parameter is valid until C<.cleanup>, for creating manual
447 contexts into the backend with C<nbdkit_next_context_open>.
449 If there is an error, C<.after_fork> should call C<nbdkit_error> with
450 an error message and return C<-1>.
452 =head2 C<.cleanup>
454  int (cleanup) (nbdkit_backend *backend);
456 This optional callback is reached once after all client connections
457 have been closed, but before the underlying plugin C<.cleanup> or any
458 C<.unload> callbacks.  It can be used by the filter to gracefully
459 close any background threads created during C<.after_fork>, as well as
460 close any manual contexts into C<backend> previously opened with
461 C<nbdkit_next_context_open>.
463 Note that it's not guaranteed that C<.cleanup> will always be called
464 (eg. the server might be killed or segfault), so you should try to
465 make the filter as robust as possible by not requiring cleanup.  See
466 also L<nbdkit-plugin(3)/SHUTDOWN>.
468 =head2 C<.preconnect>
470  int (*preconnect) (nbdkit_next_preconnect *next, nbdkit_backend *nxdata,
471                     int readonly);
473 This intercepts the plugin C<.preconnect> method and can be used to
474 filter access to the server.
476 If there is an error, C<.preconnect> should call C<nbdkit_error> with
477 an error message and return C<-1>.
479 =head2 C<.list_exports>
481  int (*list_exports) (nbdkit_next_list_exports *next, nbdkit_backend *nxdata,
482                       int readonly, int is_tls,
483                       struct nbdkit_exports *exports);
485 This intercepts the plugin C<.list_exports> method and can be used to
486 filter which exports are advertised.
488 The C<readonly> parameter matches what is passed to <.preconnect> and
489 C<.open>, and may be changed by the filter when calling into the
490 plugin.  The C<is_tls> parameter informs the filter whether TLS
491 negotiation has been completed by the client, but is not passed on to
492 C<next> because it cannot be altered.
494 It is possible for filters to transform the exports list received back
495 from the layer below.  Without error checking it would look like this:
497  myfilter_list_exports (...)
499    size_t i;
500    struct nbdkit_exports *exports2;
501    struct nbdkit_export e;
502    char *name, *desc;
504    exports2 = nbdkit_exports_new ();
505    next_list_exports (nxdata, readonly, exports);
506    for (i = 0; i < nbdkit_exports_count (exports2); ++i) {
507      e = nbdkit_get_export (exports2, i);
508      name = adjust (e.name);
509      desc = adjust (e.desc);
510      nbdkit_add_export (exports, name, desc);
511      free (name);
512      free (desc);
513    }
514    nbdkit_exports_free (exports2);
517 If there is an error, C<.list_exports> should call C<nbdkit_error> with
518 an error message and return C<-1>.
520 =head3 Allocating and freeing nbdkit_exports list
522 Two functions are provided to filters only for allocating and freeing
523 the list:
525  struct nbdkit_exports *nbdkit_exports_new (void);
527 Allocates and returns a new, empty exports list.
529 On error this function can return C<NULL>.  In this case it calls
530 C<nbdkit_error> as required.  C<errno> will be set to a suitable
531 value.
533  void nbdkit_exports_free (struct nbdkit_exports *);
535 Frees an existing exports list.
537 =head3 Iterating over nbdkit_exports list
539 Two functions are provided to filters only to iterate over the exports
540 in order:
542  size_t nbdkit_exports_count (const struct nbdkit_exports *);
544 Returns the number of exports in the list.
546  struct nbdkit_export {
547    char *name;
548    char *description;
549  };
550  const struct nbdkit_export nbdkit_get_export (const struct nbdkit_exports *,
551                                                size_t i);
553 Returns a copy of the C<i>'th export.
555 =head2 C<.default_export>
557  const char *default_export (nbdkit_next_default_export *next,
558                              nbdkit_backend *nxdata,
559                              int readonly, int is_tls)
561 This intercepts the plugin C<.default_export> method and can be used to
562 alter the canonical export name used in place of the default C<"">.
564 The C<readonly> parameter matches what is passed to <.preconnect> and
565 C<.open>, and may be changed by the filter when calling into the
566 plugin.  The C<is_tls> parameter informs the filter whether TLS
567 negotiation has been completed by the client, but is not passed on to
568 C<next> because it cannot be altered.
570 =head2 C<.open>
572  void * (*open) (nbdkit_next_open *next, nbdkit_context *context,
573                  int readonly, const char *exportname, int is_tls);
575 This is called when a new client connection is opened and can be used
576 to allocate any per-connection data structures needed by the filter.
577 The handle (which is not the same as the plugin handle) is passed back
578 to other filter callbacks and could be freed in the C<.close>
579 callback.
581 Note that the handle is completely opaque to nbdkit, but it must not
582 be NULL.  If you don't need to use a handle, return
583 C<NBDKIT_HANDLE_NOT_NEEDED> which is a static non-NULL pointer.
585 If there is an error, C<.open> should call C<nbdkit_error> with an
586 error message and return C<NULL>.
588 This callback is optional, but if provided, it should call C<next>,
589 passing C<readonly> and C<exportname> possibly modified according to
590 how the filter plans to use the plugin (C<is_tls> is not passed,
591 because a filter cannot modify it).  Typically, the filter passes the
592 same values as it received, or passes readonly=true to provide a
593 writable layer on top of a read-only backend.  However, it is also
594 acceptable to attempt write access to the plugin even if this filter
595 is readonly, such as when a file system mounted read-only still
596 requires write access to the underlying device in case a journal needs
597 to be replayed for consistency as part of the mounting process.
599 The C<exportname> string is only guaranteed to be available during the
600 call (different than the lifetime for the return of C<nbdkit_export_name>
601 used by plugins).  If the filter needs to use it (other than immediately
602 passing it down to the next layer) it must take a copy, although
603 C<nbdkit_strdup_intern> is useful for this task.  The C<exportname> and
604 C<is_tls> parameters are provided so that filters do not need to use
605 the plugin-only interfaces of C<nbdkit_export_name> and
606 C<nbdkit_is_tls>.
608 The filter should generally call C<next> as its first step, to
609 allocate from the plugin outwards, so that C<.close> running from the
610 outer filter to the plugin will be in reverse.  Skipping a call to
611 C<next> is acceptable if the filter will not access C<nbdkit_next>
612 during any of the remaining callbacks reached on the same connection.
613 The C<next> function is provided for convenience; the same
614 functionality can be obtained manually (other than error checking) by
615 using the following:
617  nbdkit_context_set_next (context, nbdkit_next_context_open
618     (nbdkit_context_get_backend (context), readonly, exportname, false));
620 The value of C<context> in this call has a lifetime that lasts until
621 the counterpart C<.close>, and it is this value that may be passed to
622 C<nbdkit_context_get_backend> to obtain the C<backend> parameter used
623 to open a plugin context with C<nbdkit_next_context_open>, as well as
624 the C<context> parameter used to associate a plugin context into the
625 current connection with C<nbdkit_context_set_next>.
627 =head2 C<.close>
629  void (*close) (void *handle);
631 This is called when the client closes the connection.  It should clean
632 up any per-connection resources used by the filter.  It is called
633 beginning with the outermost filter and ending with the plugin (the
634 opposite order of C<.open> if all filters call C<next> first),
635 although this order technically does not matter since the callback
636 cannot report failures or access the underlying plugin.
638 =head2 C<.prepare>
640 =head2 C<.finalize>
642   int (*prepare) (nbdkit_next *next, void *handle, int readonly);
643   int (*finalize) (nbdkit_next *next, void *handle);
645 These two methods can be used to perform any necessary operations just
646 after opening the connection (C<.prepare>) or just before closing the
647 connection (C<.finalize>).
649 For example if you need to scan the underlying disk to check for a
650 partition table, you could do it in your C<.prepare> method (calling
651 the plugin's C<.get_size> and C<.pread> methods via C<next>).  Or
652 if you need to cleanly update superblock data in the image on close
653 you can do it in your C<.finalize> method (calling the plugin's
654 C<.pwrite> method).  Doing these things in the filter's C<.open> or
655 C<.close> method is not possible without using manual context
656 lifecycle management.
658 For C<.prepare>, the value of C<readonly> is the same as was passed to
659 C<.open>, declaring how this filter will be used.
661 Note that nbdkit performs sanity checking on requests made to the
662 underlying plugin; for example, C<next-E<gt>pread> cannot be
663 called on a given connection unless C<next-E<gt>get_size> has
664 first been called at least once in the same connection (to ensure the
665 read requests are in bounds), and C<next-E<gt>pwrite> further
666 requires an earlier successful call to C<next-E<gt>can_write>.  In
667 many filters, these prerequisites will be automatically called during
668 the client negotiation phase, but there are cases where a filter
669 overrides query functions or makes I/O calls into the plugin before
670 handshaking is complete, where the filter needs to make those
671 prerequisite calls manually during C<.prepare>.
673 While there are C<next-E<gt>prepare> and C<next-E<gt>finalize>
674 functions, these are different from other filter methods, in that any
675 plugin context associated with the current connection (via the C<next>
676 parameter to C<.open>, or via C<nbdkit_context_set_next>, is prepared
677 and finalized automatically by nbdkit, so they are only used during
678 manual lifecycle management.  Prepare methods are called starting with
679 the filter closest to the plugin and proceeding outwards (matching the
680 order of C<.open> if all filters call C<next> before doing anything
681 locally), and only when an outer filter did not skip the C<next> call
682 during C<.open>.  Finalize methods are called in the reverse order of
683 prepare methods, with the outermost filter first (and matching the
684 order of C<.close>), and only if the prepare method succeeded.
686 If there is an error, both callbacks should call C<nbdkit_error> with
687 an error message and return C<-1>.  An error in C<.prepare> is
688 reported to the client, but leaves the connection open (a client may
689 try again with a different export name, for example); while an error
690 in C<.finalize> forces the client to disconnect.
692 =head2 C<.get_size>
694  int64_t (*get_size) (nbdkit_next *next, void *handle);
696 This intercepts the plugin C<.get_size> method and can be used to read
697 or modify the apparent size of the block device that the NBD client
698 will see.
700 The returned size must be E<ge> 0.  If there is an error, C<.get_size>
701 should call C<nbdkit_error> with an error message and return C<-1>.
702 This function is only called once per connection and cached by nbdkit.
703 Similarly, repeated calls to C<next-E<gt>get_size> will return a
704 cached value.
706 =head2 C<.export_description>
708  const char *export_description (nbdkit_next *next, void *handle);
710 This intercepts the plugin C<.export_description> method and can be
711 used to read or modify the export description that the NBD client
712 will see.
714 =head2 C<.block_size>
716  int block_size (nbdkit_next *next, void *handle, uint32_t *minimum,
717                  uint32_t *preferred, uint32_t *maximum);
719 This intercepts the plugin C<.block_size> method and can be used to
720 read or modify the block size constraints that the NBD client will
721 see.
723 =head2 C<.can_write>
725 =head2 C<.can_flush>
727 =head2 C<.is_rotational>
729 =head2 C<.can_trim>
731 =head2 C<.can_zero>
733 =head2 C<.can_fast_zero>
735 =head2 C<.can_extents>
737 =head2 C<.can_fua>
739 =head2 C<.can_multi_conn>
741 =head2 C<.can_cache>
743  int (*can_write) (nbdkit_next *next, void *handle);
744  int (*can_flush) (nbdkit_next *next, void *handle);
745  int (*is_rotational) (nbdkit_next *next, void *handle);
746  int (*can_trim) (nbdkit_next *next, void *handle);
747  int (*can_zero) (nbdkit_next *next, void *handle);
748  int (*can_fast_zero) (nbdkit_next *next, void *handle);
749  int (*can_extents) (nbdkit_next *next, void *handle);
750  int (*can_fua) (nbdkit_next *next, void *handle);
751  int (*can_multi_conn) (nbdkit_next *next, void *handle);
752  int (*can_cache) (nbdkit_next *next, void *handle);
754 These intercept the corresponding plugin methods, and control feature
755 bits advertised to the client.
757 Of note, the semantics of C<.can_zero> callback in the filter are
758 slightly different from the plugin, and must be one of three success
759 values visible only to filters:
761 =over 4
763 =item C<NBDKIT_ZERO_NONE>
765 Completely suppress advertisement of write zero support (this can only
766 be done from filters, not plugins).
768 =item C<NBDKIT_ZERO_EMULATE>
770 Inform nbdkit that write zeroes should immediately fall back to
771 C<.pwrite> emulation without trying C<.zero> (this value is returned
772 by C<next-E<gt>can_zero> if the plugin returned false in its
773 C<.can_zero>).
775 =item C<NBDKIT_ZERO_NATIVE>
777 Inform nbdkit that write zeroes should attempt to use C<.zero>,
778 although it may still fall back to C<.pwrite> emulation for C<ENOTSUP>
779 or C<EOPNOTSUPP> failures (this value is returned by
780 C<next-E<gt>can_zero> if the plugin returned true in its
781 C<.can_zero>).
783 =back
785 Remember that most of the feature check functions return merely a
786 boolean success value, while C<.can_zero>, C<.can_fua> and
787 C<.can_cache> have three success values.
789 The difference between C<.can_fua> values may affect choices made in
790 the filter: when splitting a write request that requested FUA from the
791 client, if C<next-E<gt>can_fua> returns C<NBDKIT_FUA_NATIVE>, then
792 the filter should pass the FUA flag on to each sub-request; while if
793 it is known that FUA is emulated by a flush because of a return of
794 C<NBDKIT_FUA_EMULATE>, it is more efficient to only flush once after
795 all sub-requests have completed (often by passing C<NBDKIT_FLAG_FUA>
796 on to only the final sub-request, or by dropping the flag and ending
797 with a direct call to C<next-E<gt>flush>).
799 If there is an error, the callback should call C<nbdkit_error> with an
800 error message and return C<-1>.  These functions are called at most
801 once per connection and cached by nbdkit. Similarly, repeated calls to
802 any of the C<nbdkit_next> counterparts will return a cached value; by
803 calling into the plugin during C<.prepare>, you can ensure that later
804 use of the cached values during data commands like <.pwrite> will not
805 fail.
807 =head2 C<.pread>
809  int (*pread) (nbdkit_next *next,
810                void *handle, void *buf, uint32_t count, uint64_t offset,
811                uint32_t flags, int *err);
813 This intercepts the plugin C<.pread> method and can be used to read or
814 modify data read by the plugin.
816 The parameter C<flags> exists in case of future NBD protocol
817 extensions; at this time, it will be 0 on input, and the filter should
818 not pass any flags to C<next-E<gt>pread>.
820 If there is an error (including a short read which couldn't be
821 recovered from), C<.pread> should call C<nbdkit_error> with an error
822 message B<and> return -1 with C<err> set to the positive errno value
823 to return to the client.
825 =head2 C<.pwrite>
827  int (*pwrite) (nbdkit_next *next,
828                 void *handle,
829                 const void *buf, uint32_t count, uint64_t offset,
830                 uint32_t flags, int *err);
832 This intercepts the plugin C<.pwrite> method and can be used to modify
833 data written by the plugin.
835 This function will not be called if C<.can_write> returned false; in
836 turn, the filter should not call C<next-E<gt>pwrite> if
837 C<next-E<gt>can_write> did not return true.
839 The parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based
840 on the result of C<.can_fua>.  In turn, the filter should only pass
841 C<NBDKIT_FLAG_FUA> on to C<next-E<gt>pwrite> if
842 C<next-E<gt>can_fua> returned a positive value.
844 If there is an error (including a short write which couldn't be
845 recovered from), C<.pwrite> should call C<nbdkit_error> with an error
846 message B<and> return -1 with C<err> set to the positive errno value
847 to return to the client.
849 =head2 C<.flush>
851  int (*flush) (nbdkit_next *next,
852                void *handle, uint32_t flags, int *err);
854 This intercepts the plugin C<.flush> method and can be used to modify
855 flush requests.
857 This function will not be called if C<.can_flush> returned false; in
858 turn, the filter should not call C<next-E<gt>flush> if
859 C<next-E<gt>can_flush> did not return true.
861 The parameter C<flags> exists in case of future NBD protocol
862 extensions; at this time, it will be 0 on input, and the filter should
863 not pass any flags to C<next-E<gt>flush>.
865 If there is an error, C<.flush> should call C<nbdkit_error> with an
866 error message B<and> return -1 with C<err> set to the positive errno
867 value to return to the client.
869 =head2 C<.trim>
871  int (*trim) (nbdkit_next *next,
872               void *handle, uint32_t count, uint64_t offset,
873               uint32_t flags, int *err);
875 This intercepts the plugin C<.trim> method and can be used to modify
876 trim requests.
878 This function will not be called if C<.can_trim> returned false; in
879 turn, the filter should not call C<next-E<gt>trim> if
880 C<next-E<gt>can_trim> did not return true.
882 The parameter C<flags> may include C<NBDKIT_FLAG_FUA> on input based
883 on the result of C<.can_fua>.  In turn, the filter should only pass
884 C<NBDKIT_FLAG_FUA> on to C<next-E<gt>trim> if
885 C<next-E<gt>can_fua> returned a positive value.
887 If there is an error, C<.trim> should call C<nbdkit_error> with an
888 error message B<and> return -1 with C<err> set to the positive errno
889 value to return to the client.
891 =head2 C<.zero>
893  int (*zero) (nbdkit_next *next,
894               void *handle, uint32_t count, uint64_t offset, uint32_t flags,
895               int *err);
897 This intercepts the plugin C<.zero> method and can be used to modify
898 zero requests.
900 This function will not be called if C<.can_zero> returned
901 C<NBDKIT_ZERO_NONE> or C<NBDKIT_ZERO_EMULATE>; in turn, the filter
902 should not call C<next-E<gt>zero> if C<next-E<gt>can_zero> returned
903 C<NBDKIT_ZERO_NONE>.
905 On input, the parameter C<flags> may include C<NBDKIT_FLAG_MAY_TRIM>
906 unconditionally, C<NBDKIT_FLAG_FUA> based on the result of
907 C<.can_fua>, and C<NBDKIT_FLAG_FAST_ZERO> based on the result of
908 C<.can_fast_zero>.  In turn, the filter may pass
909 C<NBDKIT_FLAG_MAY_TRIM> unconditionally, but should only pass
910 C<NBDKIT_FLAG_FUA> or C<NBDKIT_FLAG_FAST_ZERO> on to
911 C<next-E<gt>zero> if the corresponding C<next-E<gt>can_fua> or
912 C<next-E<gt>can_fast_zero> returned a positive value.
914 Note that unlike the plugin C<.zero> which is permitted to fail with
915 C<ENOTSUP> or C<EOPNOTSUPP> to force a fallback to C<.pwrite>, the
916 function C<next-E<gt>zero> will not fail with C<err> set to
917 C<ENOTSUP> or C<EOPNOTSUPP> unless C<NBDKIT_FLAG_FAST_ZERO> was used,
918 because otherwise the fallback has already taken place.
920 If there is an error, C<.zero> should call C<nbdkit_error> with an
921 error message B<and> return -1 with C<err> set to the positive errno
922 value to return to the client.  The filter should not fail with
923 C<ENOTSUP> or C<EOPNOTSUPP> unless C<flags> includes
924 C<NBDKIT_FLAG_FAST_ZERO> (while plugins have automatic fallback to
925 C<.pwrite>, filters do not).
927 =head2 C<.extents>
929  int (*extents) (nbdkit_next *next,
930                  void *handle, uint32_t count, uint64_t offset, uint32_t flags,
931                  struct nbdkit_extents *extents,
932                  int *err);
934 This intercepts the plugin C<.extents> method and can be used to
935 modify extent requests.
937 This function will not be called if C<.can_extents> returned false; in
938 turn, the filter should not call C<next-E<gt>extents> if
939 C<next-E<gt>can_extents> did not return true.
941 It is possible for filters to transform the extents list received back
942 from the layer below.  Without error checking it would look like this:
944  myfilter_extents (..., uint32_t count, uint64_t offset, ...)
946    size_t i;
947    struct nbdkit_extents *extents2;
948    struct nbdkit_extent e;
949    int64_t size;
951    size = next->get_size (next);
952    extents2 = nbdkit_extents_new (offset + shift, size);
953    next->extents (next, count, offset + shift, flags, extents2, err);
954    for (i = 0; i < nbdkit_extents_count (extents2); ++i) {
955      e = nbdkit_get_extent (extents2, i);
956      e.offset -= shift;
957      nbdkit_add_extent (extents, e.offset, e.length, e.type);
958    }
959    nbdkit_extents_free (extents2);
962 If there is an error, C<.extents> should call C<nbdkit_error> with an
963 error message B<and> return -1 with C<err> set to the positive errno
964 value to return to the client.
966 =head3 Allocating and freeing nbdkit_extents list
968 Two functions are provided to filters only for allocating and freeing
969 the map:
971  struct nbdkit_extents *nbdkit_extents_new (uint64_t start, uint64_t end);
973 Allocates and returns a new, empty extents list.  The C<start>
974 parameter is the start of the range described in the list, and the
975 C<end> parameter is the offset of the byte beyond the end.  Normally
976 you would pass in C<offset> as the start and the size of the plugin as
977 the end, but for filters which adjust offsets, they should pass in the
978 adjusted offset.
980 On error this function can return C<NULL>.  In this case it calls
981 C<nbdkit_error> and/or C<nbdkit_set_error> as required.  C<errno> will
982 be set to a suitable value.
984  void nbdkit_extents_free (struct nbdkit_extents *);
986 Frees an existing extents list.
988 =head3 Iterating over nbdkit_extents list
990 Two functions are provided to filters only to iterate over the extents
991 in order:
993  size_t nbdkit_extents_count (const struct nbdkit_extents *);
995 Returns the number of extents in the list.
997  struct nbdkit_extent {
998    uint64_t offset;
999    uint64_t length;
1000    uint32_t type;
1001  };
1002  struct nbdkit_extent nbdkit_get_extent (const struct nbdkit_extents *,
1003                                          size_t i);
1005 Returns a copy of the C<i>'th extent.
1007 =head3 Reading the full extents from the plugin
1009 A convenience function is provided to filters only which makes one or
1010 more requests to the underlying plugin until we have a full set of
1011 extents covering the region C<[offset..offset+count-1]>.
1013  struct nbdkit_extents *nbdkit_extents_full (
1014                              nbdkit_next *next,
1015                              uint32_t count, uint64_t offset,
1016                              uint32_t flags, int *err);
1018 Note this allocates a new C<struct nbdkit_extents> which the caller
1019 must free.  C<flags> is passed through to the underlying plugin, but
1020 C<NBDKIT_FLAG_REQ_ONE> is removed from the set of flags so that the
1021 plugin returns as much information as possible (this is usually what
1022 you want).
1024 On error this function can return C<NULL>.  In this case it calls
1025 C<nbdkit_error> and/or C<nbdkit_set_error> as required.  C<*err> will
1026 be set to a suitable value.
1028 =head3 Enforcing alignment of an nbdkit_extents list
1030 A convenience function is provided to filters only which makes it
1031 easier to ensure that the client only encounters aligned extents.
1033  int nbdkit_extents_aligned (nbdkit_next *next,
1034                              uint32_t count, uint64_t offset,
1035                              uint32_t flags, uint32_t align,
1036                              struct nbdkit_extents *extents, int *err);
1038 Calls C<next-E<gt>extents> as needed until at least C<align> bytes are
1039 obtained, where C<align> is a power of 2.  Anywhere the underlying
1040 plugin returns differing extents within C<align> bytes, this function
1041 treats that portion of the disk as a single extent with zero and
1042 sparse status bits determined by the intersection of all underlying
1043 extents.  It is an error to call this function with C<count> or
1044 C<offset> that is not already aligned.
1046 =head2 C<.cache>
1048  int (*cache) (nbdkit_next *next,
1049                void *handle, uint32_t count, uint64_t offset,
1050                uint32_t flags, int *err);
1052 This intercepts the plugin C<.cache> method and can be used to modify
1053 cache requests.
1055 This function will not be called if C<.can_cache> returned
1056 C<NBDKIT_CACHE_NONE> or C<NBDKIT_CACHE_EMULATE>; in turn, the filter
1057 should not call C<next-E<gt>cache> if
1058 C<next-E<gt>can_cache> returned C<NBDKIT_CACHE_NONE>.
1060 The parameter C<flags> exists in case of future NBD protocol
1061 extensions; at this time, it will be 0 on input, and the filter should
1062 not pass any flags to C<next-E<gt>cache>.
1064 If there is an error, C<.cache> should call C<nbdkit_error> with an
1065 error message B<and> return -1 with C<err> set to the positive errno
1066 value to return to the client.
1068 =head1 ERROR HANDLING
1070 If there is an error in the filter itself, the filter should call
1071 C<nbdkit_error> to report an error message.  If the callback is
1072 involved in serving data, the explicit C<err> parameter determines the
1073 error code that will be sent to the client; other callbacks should
1074 return the appropriate error indication, eg. C<NULL> or C<-1>.
1076 C<nbdkit_error> has the following prototype and works like
1077 L<printf(3)>:
1079  void nbdkit_error (const char *fs, ...);
1080  void nbdkit_verror (const char *fs, va_list args);
1082 For convenience, C<nbdkit_error> preserves the value of C<errno>, and
1083 also supports the glibc extension of a single C<%m> in a format string
1084 expanding to C<strerror(errno)>, even on platforms that don't support
1085 that natively.
1087 =head1 DEBUGGING
1089 Run the server with I<-f> and I<-v> options so it doesn't fork and you
1090 can see debugging information:
1092  nbdkit -fv --filter=./myfilter.so plugin [key=value [key=value [...]]]
1094 To print debugging information from within the filter, call
1095 C<nbdkit_debug>, which has the following prototype and works like
1096 L<printf(3)>:
1098  void nbdkit_debug (const char *fs, ...);
1099  void nbdkit_vdebug (const char *fs, va_list args);
1101 For convenience, C<nbdkit_debug> preserves the value of C<errno>, and
1102 also supports the glibc extension of a single C<%m> in a format string
1103 expanding to C<strerror(errno)>, even on platforms that don't support
1104 that natively.  Note that C<nbdkit_debug> only prints things when the
1105 server is in verbose mode (I<-v> option).
1107 =head2 Debug Flags
1109 Debug Flags in filters work exactly the same way as plugins.  See
1110 L<nbdkit-plugin(3)/Debug Flags>.
1112 =head1 INSTALLING THE FILTER
1114 The filter is a C<*.so> file and possibly a manual page.  You can of
1115 course install the filter C<*.so> file wherever you want, and users
1116 will be able to use it by running:
1118  nbdkit --filter=/path/to/filter.so plugin [args]
1120 However B<if> the shared library has a name of the form
1121 C<nbdkit-I<name>-filter.so> B<and if> the library is installed in the
1122 C<$filterdir> directory, then users can be run it by only typing:
1124  nbdkit --filter=name plugin [args]
1126 The location of the C<$filterdir> directory is set when nbdkit is
1127 compiled and can be found by doing:
1129  nbdkit --dump-config
1131 If using the pkg-config/pkgconf system then you can also find the
1132 filter directory at compile time by doing:
1134  pkg-config nbdkit --variable=filterdir
1136 =head1 PKG-CONFIG/PKGCONF
1138 nbdkit provides a pkg-config/pkgconf file called C<nbdkit.pc> which
1139 should be installed on the correct path when the nbdkit development
1140 environment is installed.  You can use this in autoconf
1141 F<configure.ac> scripts to test for the development environment:
1143  PKG_CHECK_MODULES([NBDKIT], [nbdkit >= 1.2.3])
1145 The above will fail unless nbdkit E<ge> 1.2.3 and the header file is
1146 installed, and will set C<NBDKIT_CFLAGS> and C<NBDKIT_LIBS>
1147 appropriately for compiling filters.
1149 You can also run pkg-config/pkgconf directly, for example:
1151  if ! pkg-config nbdkit --exists; then
1152    echo "you must install the nbdkit development environment"
1153    exit 1
1154  fi
1156 You can also substitute the filterdir variable by doing:
1158  PKG_CHECK_VAR([NBDKIT_FILTERDIR], [nbdkit], [filterdir])
1160 which defines C<$(NBDKIT_FILTERDIR)> in automake-generated Makefiles.
1162 =head1 WRITING FILTERS IN C++
1164 Instead of using C, it is possible to write filters in C++.  However
1165 for inclusion in upstream nbdkit we would generally prefer filters
1166 written in C.
1168 Filters in C++ work almost exactly like those in C, but the way you
1169 define the C<nbdkit_filter> struct is slightly different:
1171  namespace {
1172    nbdkit_filter create_filter() {
1173      nbdkit_filter filter = nbdkit_filter ();
1174      filter.name   = "myfilter";
1175      filter.config = myfilter_config;
1176      return filter;
1177    }
1179  static struct nbdkit_filter filter = create_filter ();
1180  NBDKIT_REGISTER_FILTER(filter)
1182 =head1 SEE ALSO
1184 L<nbdkit(1)>,
1185 L<nbdkit-plugin(3)>.
1187 Standard filters provided by nbdkit:
1189 __FILTER_LINKS__.
1191 =head1 AUTHORS
1193 Eric Blake
1195 Richard W.M. Jones
1197 =head1 COPYRIGHT
1199 Copyright Red Hat