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