]> git.ozlabs.org Git - ccan/blob - ccan/io/io.h
d0c0a39a3888526df10c4174ed4dd8e69b8e7153
[ccan] / ccan / io / io.h
1 /* Licensed under LGPLv2.1+ - see LICENSE file for details */
2 #ifndef CCAN_IO_H
3 #define CCAN_IO_H
4 #include <ccan/tal/tal.h>
5 #include <ccan/typesafe_cb/typesafe_cb.h>
6 #include <stdbool.h>
7 #include <unistd.h>
8
9 struct timers;
10 struct list_head;
11
12 /**
13  * struct io_plan - a plan for input or output.
14  *
15  * Each io_conn has zero to two of these active at any time.
16  */
17 struct io_plan;
18
19 /**
20  * struct io_conn - a connection associated with an fd.
21  */
22 struct io_conn;
23
24 /**
25  * io_new_conn - create a new connection.
26  * @ctx: the context to tal from (or NULL)
27  * @fd: the file descriptor.
28  * @init: the function to call for a new connection
29  * @arg: the argument to @init.
30  *
31  * This creates a connection which owns @fd, it then calls
32  * @init to initialize the connection, which sets up an io_plan.
33  *
34  * Returns NULL on error (and sets errno).
35  *
36  * Example:
37  * // Dumb init function to print string and tell conn to close.
38  * static struct io_plan *conn_init(struct io_conn *conn, const char *msg)
39  * {
40  *      printf("Created conn %p: %s", conn, msg);
41  *      return io_close(conn);
42  * }
43  *
44  * static void create_self_closing_pipe(void)
45  * {
46  *      int fd[2];
47  *      struct io_conn *conn;
48  *
49  *      pipe(fd);
50  *      conn = io_new_conn(NULL, fd[0], conn_init, (const char *)"hi!");
51  *      if (!conn)
52  *              exit(1);
53  * }
54  */
55 #define io_new_conn(ctx, fd, init, arg)                                 \
56         io_new_conn_((ctx), (fd),                                       \
57                      typesafe_cb_preargs(struct io_plan *, void *,      \
58                                          (init), (arg),                 \
59                                          struct io_conn *conn),         \
60                      (void *)(arg))
61
62 struct io_conn *io_new_conn_(const tal_t *ctx, int fd,
63                              struct io_plan *(*init)(struct io_conn *, void *),
64                              void *arg);
65
66 /**
67  * io_set_finish - set finish function on a connection.
68  * @conn: the connection.
69  * @finish: the function to call when it's closed or fails.
70  * @arg: the argument to @finish.
71  *
72  * @finish will be called when an I/O operation fails, or you call
73  * io_close() on the connection.  errno will be set to the value
74  * after the failed I/O, or at the call to io_close().  The fd
75  * will be closed before @finish is called.
76  *
77  * Example:
78  * static void finish(struct io_conn *conn, const char *msg)
79  * {
80  *      // errno is not 0 after success, so this is a bit useless.
81  *      printf("Conn %p closed with errno %i (%s)\n", conn, errno, msg);
82  * }
83  *
84  * // Dumb init function to print string and tell conn to close.
85  * static struct io_plan *conn_init(struct io_conn *conn, const char *msg)
86  * {
87  *      io_set_finish(conn, finish, msg);
88  *      return io_close(conn);
89  * }
90  */
91 #define io_set_finish(conn, finish, arg)                                \
92         io_set_finish_((conn),                                          \
93                        typesafe_cb_preargs(void, void *,                \
94                                            (finish), (arg),             \
95                                            struct io_conn *),           \
96                        (void *)(arg))
97 void io_set_finish_(struct io_conn *conn,
98                     void (*finish)(struct io_conn *, void *),
99                     void *arg);
100
101
102 /**
103  * io_new_listener - create a new accepting listener.
104  * @ctx: the context to tal from (or NULL)
105  * @fd: the file descriptor.
106  * @init: the function to call for a new connection
107  * @arg: the argument to @init.
108  *
109  * When @fd becomes readable, we accept(), create a new connection,
110  * (tal'ocated off @ctx) and pass that to init().
111  *
112  * Returns NULL on error (and sets errno).
113  *
114  * Example:
115  * #include <sys/types.h>
116  * #include <sys/socket.h>
117  * #include <netdb.h>
118  *
119  * ...
120  *
121  * // Set up a listening socket, return it.
122  * static struct io_listener *do_listen(const char *port)
123  * {
124  *      struct addrinfo *addrinfo, hints;
125  *      int fd, on = 1;
126  *
127  *      memset(&hints, 0, sizeof(hints));
128  *      hints.ai_family = AF_UNSPEC;
129  *      hints.ai_socktype = SOCK_STREAM;
130  *      hints.ai_flags = AI_PASSIVE;
131  *      hints.ai_protocol = 0;
132  *
133  *      if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
134  *              return NULL;
135  *
136  *      fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
137  *                  addrinfo->ai_protocol);
138  *      if (fd < 0)
139  *              return NULL;
140  *
141  *      freeaddrinfo(addrinfo);
142  *      setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
143  *      if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
144  *              close(fd);
145  *              return NULL;
146  *      }
147  *      if (listen(fd, 1) != 0) {
148  *              close(fd);
149  *              return NULL;
150  *      }
151  *      return io_new_listener(NULL, fd, conn_init, (const char *)"listened!");
152  * }
153  */
154 #define io_new_listener(ctx, fd, init, arg)                             \
155         io_new_listener_((ctx), (fd),                                   \
156                          typesafe_cb_preargs(struct io_plan *, void *,  \
157                                              (init), (arg),             \
158                                              struct io_conn *conn),     \
159                          (void *)(arg))
160 struct io_listener *io_new_listener_(const tal_t *ctx, int fd,
161                                      struct io_plan *(*init)(struct io_conn *,
162                                                              void *),
163                                      void *arg);
164
165 /**
166  * io_close_listener - delete a listener.
167  * @listener: the listener returned from io_new_listener.
168  *
169  * This closes the fd and frees @listener.
170  *
171  * Example:
172  * ...
173  *      struct io_listener *l = do_listen("8111");
174  *      if (l) {
175  *              io_loop(NULL, NULL);
176  *              io_close_listener(l);
177  *      }
178  */
179 void io_close_listener(struct io_listener *listener);
180
181 /**
182  * io_write - output plan to write data.
183  * @conn: the connection that plan is for.
184  * @data: the data buffer.
185  * @len: the length to write.
186  * @next: function to call output is done.
187  * @arg: @next argument
188  *
189  * This updates the output plan, to write out a data buffer.  Once it's all
190  * written, the @next function will be called: on an error, the finish
191  * function is called instead.
192  *
193  * Note that the I/O may actually be done immediately.
194  *
195  * Example:
196  * static struct io_plan *write_to_conn(struct io_conn *conn, const char *msg)
197  * {
198  *      // Write message, then close.
199  *      return io_write(conn, msg, strlen(msg), io_close_cb, NULL);
200  * }
201  */
202 #define io_write(conn, data, len, next, arg)                            \
203         io_write_((conn), (data), (len),                                \
204                   typesafe_cb_preargs(struct io_plan *, void *,         \
205                                       (next), (arg), struct io_conn *), \
206                   (arg))
207 struct io_plan *io_write_(struct io_conn *conn,
208                           const void *data, size_t len,
209                           struct io_plan *(*next)(struct io_conn *, void *),
210                           void *arg);
211
212 /**
213  * io_read - input plan to read data.
214  * @conn: the connection that plan is for.
215  * @data: the data buffer.
216  * @len: the length to read.
217  * @next: function to call once input is done.
218  * @arg: @next argument
219  *
220  * This creates a plan to read data into a buffer.  Once it's all
221  * read, the @next function will be called: on an error, the finish
222  * function is called instead.
223  *
224  * Note that the I/O may actually be done immediately.
225  *
226  * Example:
227  * static struct io_plan *read_from_conn(struct io_conn *conn, char *buf)
228  * {
229  *      // Read message, then close.
230  *      return io_read(conn, buf, 12, io_close_cb, NULL);
231  * }
232  */
233 #define io_read(conn, data, len, next, arg)                             \
234         io_read_((conn), (data), (len),                                 \
235                  typesafe_cb_preargs(struct io_plan *, void *,          \
236                                      (next), (arg), struct io_conn *),  \
237                  (arg))
238 struct io_plan *io_read_(struct io_conn *conn,
239                          void *data, size_t len,
240                          struct io_plan *(*next)(struct io_conn *, void *),
241                          void *arg);
242
243
244 /**
245  * io_read_partial - input plan to read some data.
246  * @conn: the connection that plan is for.
247  * @data: the data buffer.
248  * @maxlen: the maximum length to read
249  * @lenp: set to the length actually read.
250  * @next: function to call once input is done.
251  * @arg: @next argument
252  *
253  * This creates a plan to read data into a buffer.  Once any data is
254  * read, @len is updated and the @next function will be called: on an
255  * error, the finish function is called instead.
256  *
257  * Note that the I/O may actually be done immediately.
258  *
259  * Example:
260  * struct buf {
261  *      size_t len;
262  *      char buf[12];
263  * };
264  *
265  * static struct io_plan *dump(struct io_conn *conn, struct buf *b)
266  * {
267  *      printf("Partial read: '%*s'\n", (int)b->len, b->buf);
268  *      free(b);
269  *      return io_close(conn);
270  * }
271  *
272  * static struct io_plan *read_part(struct io_conn *conn, struct buf *b)
273  * {
274  *      // Read message, then dump and close.
275  *      return io_read_partial(conn, b->buf, sizeof(b->buf), &b->len, dump, b);
276  * }
277  */
278 #define io_read_partial(conn, data, maxlen, lenp, next, arg)            \
279         io_read_partial_((conn), (data), (maxlen), (lenp),              \
280                          typesafe_cb_preargs(struct io_plan *, void *,  \
281                                              (next), (arg),             \
282                                              struct io_conn *),         \
283                          (arg))
284 struct io_plan *io_read_partial_(struct io_conn *conn,
285                                  void *data, size_t maxlen, size_t *lenp,
286                                  struct io_plan *(*next)(struct io_conn *,
287                                                          void *),
288                                  void *arg);
289
290 /**
291  * io_write_partial - output plan to write some data.
292  * @conn: the connection that plan is for.
293  * @data: the data buffer.
294  * @maxlen: the maximum length to write
295  * @lenp: set to the length actually written.
296  * @next: function to call once output is done.
297  * @arg: @next argument
298  *
299  * This creates a plan to write data from a buffer.   Once any data is
300  * written, @len is updated and the @next function will be called: on an
301  * error, the finish function is called instead.
302  *
303  * Note that the I/O may actually be done immediately.
304  *
305  * Example:
306  * struct buf {
307  *      size_t len;
308  *      char buf[12];
309  * };
310  *
311  * static struct io_plan *show_partial(struct io_conn *conn, struct buf *b)
312  * {
313  *      printf("Only wrote: '%*s'\n", (int)b->len, b->buf);
314  *      free(b);
315  *      return io_close(conn);
316  * }
317  *
318  * static struct io_plan *write_part(struct io_conn *conn, struct buf *b)
319  * {
320  *      // Write message, then dump and close.
321  *      strcpy(b->buf, "Hello world");
322  *      return io_write_partial(conn, b->buf, strlen(b->buf),
323  *                              &b->len, show_partial, b);
324  * }
325  */
326 #define io_write_partial(conn, data, maxlen, lenp, next, arg)           \
327         io_write_partial_((conn), (data), (maxlen), (lenp),             \
328                           typesafe_cb_preargs(struct io_plan *, void *, \
329                                               (next), (arg),            \
330                                               struct io_conn *),        \
331                           (arg))
332 struct io_plan *io_write_partial_(struct io_conn *conn,
333                                   const void *data, size_t maxlen, size_t *lenp,
334                                   struct io_plan *(*next)(struct io_conn *,
335                                                           void*),
336                                   void *arg);
337
338 /**
339  * io_always - plan to immediately call next callback
340  * @conn: the connection that plan is for.
341  * @next: function to call.
342  * @arg: @next argument
343  *
344  * Sometimes it's neater to plan a callback rather than call it directly;
345  * for example, if you only need to read data for one path and not another.
346  *
347  * Example:
348  * static struct io_plan *init_conn_with_nothing(struct io_conn *conn,
349  *                                               void *unused)
350  * {
351  *      // Silly example: close on next time around loop.
352  *      return io_always(conn, io_close_cb, NULL);
353  * }
354  */
355 #define io_always(conn, next, arg)                                      \
356         io_always_((conn), typesafe_cb_preargs(struct io_plan *, void *, \
357                                                (next), (arg),           \
358                                                struct io_conn *),       \
359                    (arg))
360
361 struct io_plan *io_always_(struct io_conn *conn,
362                            struct io_plan *(*next)(struct io_conn *, void *),
363                            void *arg);
364
365 /**
366  * io_connect - create an asynchronous connection to a listening socket.
367  * @conn: the connection that plan is for.
368  * @addr: where to connect.
369  * @init: function to call once it's connected
370  * @arg: @init argument
371  *
372  * This initiates a connection, and creates a plan for
373  * (asynchronously) completing it.  Once complete, the @init function
374  * will be called.
375  *
376  * Example:
377  * #include <sys/types.h>
378  * #include <sys/socket.h>
379  * #include <netdb.h>
380  *
381  * // Write, then close socket.
382  * static struct io_plan *init_connect(struct io_conn *conn,
383  *                                     struct addrinfo *addrinfo)
384  * {
385  *      return io_connect(conn, addrinfo, io_close_cb, NULL);
386  * }
387  *
388  * ...
389  *
390  *      int fd;
391  *      struct addrinfo *addrinfo;
392  *
393  *      fd = socket(AF_INET, SOCK_STREAM, 0);
394  *      getaddrinfo("localhost", "8111", NULL, &addrinfo);
395  *      io_new_conn(NULL, fd, init_connect, addrinfo);
396  */
397 struct addrinfo;
398 #define io_connect(conn, addr, next, arg)                               \
399         io_connect_((conn), (addr),                                     \
400                     typesafe_cb_preargs(struct io_plan *, void *,       \
401                                         (next), (arg),                  \
402                                         struct io_conn *),              \
403                     (arg))
404
405 struct io_plan *io_connect_(struct io_conn *conn, const struct addrinfo *addr,
406                             struct io_plan *(*next)(struct io_conn *, void *),
407                             void *arg);
408
409 /**
410  * io_duplex - set plans for both input and output.
411  * @conn: the connection that plan is for.
412  * @in: the input plan
413  * @out: the output plan
414  *
415  * Most plans are either for input or output; io_duplex creates a plan
416  * which does both.  This is often used in the init function to create
417  * two independent streams, though it can be used once on any connection.
418  *
419  * Note that if either plan closes the connection, it will be closed.
420  *
421  * Note that if one plan is io_wait or io_always, that causes a problem:
422  * they look at the input and output plan slots to figure out which to
423  * use, but if the other plan hasn't been evaluated yet, that will fail.
424  * In this case, you'll need to ensure the other plan is evaluated first,
425  * eg. "struct io_plan *r = io_read(...); return io_duplex(r, io_always(...))"
426  *
427  * Example:
428  * struct buf {
429  *      char in[100];
430  *      char out[100];
431  * };
432  *
433  * static struct io_plan *read_and_write(struct io_conn *conn, struct buf *b)
434  * {
435  *      return io_duplex(conn,
436  *                       io_read(conn, b->in, sizeof(b->in), io_close_cb, b),
437  *                       io_write(conn, b->out, sizeof(b->out), io_close_cb,b));
438  * }
439  */
440 #define io_duplex(conn, in_plan, out_plan) \
441         (io_duplex_prepare(conn), io_duplex_(in_plan, out_plan))
442
443 struct io_plan *io_duplex_(struct io_plan *in_plan, struct io_plan *out_plan);
444 void io_duplex_prepare(struct io_conn *conn);
445
446 /**
447  * io_halfclose - close half of an io_duplex connection.
448  * @conn: the connection that plan is for.
449  *
450  * It's common to want to close a duplex connection after both input and
451  * output plans have completed.  If either calls io_close() the connection
452  * closes immediately.  Instead, io_halfclose() needs to be called twice.
453  *
454  * Example:
455  * struct buf {
456  *      char in[100];
457  *      char out[100];
458  * };
459  *
460  * static struct io_plan *finish(struct io_conn *conn, struct buf *b)
461  * {
462  *      return io_halfclose(conn);
463  * }
464  *
465  * static struct io_plan *read_and_write(struct io_conn *conn, struct buf *b)
466  * {
467  *      return io_duplex(conn,
468  *                       io_read(conn, b->in, sizeof(b->in), finish, b),
469  *                       io_write(conn, b->out, sizeof(b->out), finish, b));
470  * }
471  */
472 struct io_plan *io_halfclose(struct io_conn *conn);
473
474 /**
475  * io_wait - leave a plan idle until something wakes us.
476  * @conn: the connection that plan is for.
477  * @waitaddr: the address to wait on.
478  * @next: function to call after waiting.
479  * @arg: @next argument
480  *
481  * This leaves the input or output idle: io_wake(@waitaddr) will be
482  * called later to restart the connection.
483  *
484  * Example:
485  * // Silly example to wait then close.
486  * static struct io_plan *wait(struct io_conn *conn, void *b)
487  * {
488  *      return io_wait(conn, b, io_close_cb, NULL);
489  * }
490  */
491 #define io_wait(conn, waitaddr, next, arg)                              \
492         io_wait_((conn), (waitaddr),                                    \
493                  typesafe_cb_preargs(struct io_plan *, void *,          \
494                                      (next), (arg),                     \
495                                      struct io_conn *),                 \
496                  (arg))
497
498 struct io_plan *io_wait_(struct io_conn *conn,
499                          const void *wait,
500                          struct io_plan *(*next)(struct io_conn *, void *),
501                          void *arg);
502
503
504 /**
505  * io_wake - wake up any connections waiting on @wait
506  * @waitaddr: the address to trigger.
507  *
508  * All io_conns who have returned io_wait() on @waitaddr will move on
509  * to their next callback.
510  *
511  * Example:
512  * static struct io_plan *wake_it(struct io_conn *conn, void *b)
513  * {
514  *      io_wake(b);
515  *      return io_close(conn);
516  * }
517  */
518 void io_wake(const void *wait);
519
520 /**
521  * io_break - return from io_loop()
522  * @ret: non-NULL value to return from io_loop().
523  *
524  * This breaks out of the io_loop.  As soon as the current function
525  * returns, any io_close()'d connections will have their finish
526  * callbacks called, then io_loop() with return with @ret.
527  *
528  * If io_loop() is called again, then @plan will be carried out.
529  *
530  * Example:
531  *      static struct io_plan *fail_on_timeout(struct io_conn *conn, char *msg)
532  *      {
533  *              io_break(msg);
534  *              return io_close(conn);
535  *      }
536  */
537 void io_break(const void *ret);
538
539 /**
540  * io_never - assert if callback is called.
541  * @conn: the connection that plan is for.
542  * @unused: an unused parameter to make this suitable for use as a callback.
543  *
544  * Sometimes you want to make it clear that a callback should never happen
545  * (eg. for io_break).  This will assert() if called.
546  *
547  * Example:
548  * static struct io_plan *break_out(struct io_conn *conn, void *unused)
549  * {
550  *      io_break(conn);
551  *      // We won't ever return from io_break
552  *      return io_never(conn, NULL);
553  * }
554  */
555 struct io_plan *io_never(struct io_conn *conn, void *unused);
556
557 /* FIXME: io_recvfrom/io_sendto */
558
559 /**
560  * io_close - plan to close a connection.
561  * @conn: the connection to close.
562  *
563  * On return to io_loop, the connection will be closed.  It doesn't have
564  * to be the current connection and it doesn't need to be idle.  No more
565  * IO or callbacks will occur.
566  *
567  * You can close a connection twice without harmful effects.
568  *
569  * Example:
570  * static struct io_plan *close_on_timeout(struct io_conn *conn, const char *msg)
571  * {
572  *      printf("closing: %s\n", msg);
573  *      return io_close(conn);
574  * }
575  */
576 struct io_plan *io_close(struct io_conn *conn);
577
578 /**
579  * io_close_cb - helper callback to close a connection.
580  * @conn: the connection.
581  *
582  * This schedules a connection to be closed; designed to be used as
583  * a callback function.
584  *
585  * Example:
586  *      #define close_on_timeout io_close_cb
587  */
588 struct io_plan *io_close_cb(struct io_conn *, void *unused);
589
590 /**
591  * io_loop - process fds until all closed on io_break.
592  * @timers - timers which are waiting to go off (or NULL for none)
593  * @expired - a list filled with expired timers (can be NULL if @timers is)
594  *
595  * This is the core loop; it exits with the io_break() arg, or NULL if
596  * all connections and listeners are closed, or with @expired set to a
597  * list of expired timers (if @timers isn't NULL).
598  *
599  * Example:
600  *      io_loop(NULL, NULL);
601  */
602 void *io_loop(struct timers *timers, struct list_head *expired);
603
604 /**
605  * io_conn_fd - get the fd from a connection.
606  * @conn: the connection.
607  *
608  * Sometimes useful, eg for getsockname().
609  */
610 int io_conn_fd(const struct io_conn *conn);
611
612 /**
613  * io_set_debug - set synchronous mode on a connection.
614  * @conn: the connection.
615  * @debug: whether to enable or disable debug.
616  *
617  * Once @debug is true on a connection, all I/O is done synchronously
618  * as soon as it is set, until it is unset or @conn is closed.  This
619  * makes it easy to debug what's happening with a connection, but note
620  * that other connections are starved while this is being done.
621  *
622  * See also: io_debug_complete()
623  *
624  * Example:
625  * // Dumb init function to set debug and tell conn to close.
626  * static struct io_plan *conn_init(struct io_conn *conn, const char *msg)
627  * {
628  *      io_set_debug(conn, true);
629  *      return io_close(conn);
630  * }
631  */
632 void io_set_debug(struct io_conn *conn, bool debug);
633
634 /**
635  * io_debug_complete - empty function called when conn is closing/waiting.
636  * @conn: the connection.
637  *
638  * This is for putting a breakpoint onto, when debugging.  It is called
639  * when a conn with io_set_debug() true can no longer be synchronous:
640  * 1) It is io_close()'d
641  * 2) It enters io_wait() (sychronous debug will resume after io_wake())
642  * 3) io_break() is called (sychronous debug will resume after io_loop())
643  */
644 void io_debug_complete(struct io_conn *conn);
645 #endif /* CCAN_IO_H */