]> git.ozlabs.org Git - ccan/blob - ccan/io/io.h
ccan/io: rewrite.
[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 enum io_direction {
10         IO_IN,
11         IO_OUT
12 };
13
14 /**
15  * struct io_plan - a plan for input or output.
16  *
17  * Each io_conn has zero to two of these active at any time.
18  */
19 struct io_plan;
20
21 /**
22  * struct io_conn - a connection associated with an fd.
23  */
24 struct io_conn;
25
26 /**
27  * io_new_conn - create a new connection.
28  * @ctx: the context to tal from (or NULL)
29  * @fd: the file descriptor.
30  * @init: the function to call for a new connection
31  * @arg: the argument to @init.
32  *
33  * This creates a connection which owns @fd, it then calls
34  * @init to initialize the connection, which sets up an io_plan.
35  *
36  * Returns NULL on error (and sets errno).
37  *
38  * Example:
39  * // Dumb init function to print string and tell conn to close.
40  * static struct io_plan *conn_init(struct io_conn *conn, const char *msg)
41  * {
42  *      printf("Created conn %p: %s", conn, msg);
43  *      return io_close(conn);
44  * }
45  *
46  * static void create_self_closing_pipe(void)
47  * {
48  *      int fd[2];
49  *      struct io_conn *conn;
50  *
51  *      pipe(fd);
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().
113  *
114  * Returns NULL on error (and sets errno).
115  *
116  * Example:
117  * #include <sys/types.h>
118  * #include <sys/socket.h>
119  * #include <netdb.h>
120  *
121  * ...
122  *
123  * // Set up a listening socket, return it.
124  * static struct io_listener *do_listen(const char *port)
125  * {
126  *      struct addrinfo *addrinfo, hints;
127  *      int fd, on = 1;
128  *
129  *      memset(&hints, 0, sizeof(hints));
130  *      hints.ai_family = AF_UNSPEC;
131  *      hints.ai_socktype = SOCK_STREAM;
132  *      hints.ai_flags = AI_PASSIVE;
133  *      hints.ai_protocol = 0;
134  *
135  *      if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
136  *              return NULL;
137  *
138  *      fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
139  *                  addrinfo->ai_protocol);
140  *      if (fd < 0)
141  *              return NULL;
142  *
143  *      freeaddrinfo(addrinfo);
144  *      setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
145  *      if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
146  *              close(fd);
147  *              return NULL;
148  *      }
149  *      if (listen(fd, 1) != 0) {
150  *              close(fd);
151  *              return NULL;
152  *      }
153  *      return io_new_listener(NULL, fd, conn_init, (const char *)"listened!");
154  * }
155  */
156 #define io_new_listener(ctx, fd, init, arg)                             \
157         io_new_listener_((ctx), (fd),                                   \
158                          typesafe_cb_preargs(struct io_plan *, void *,  \
159                                              (init), (arg),             \
160                                              struct io_conn *conn),     \
161                          (void *)(arg))
162 struct io_listener *io_new_listener_(const tal_t *ctx, int fd,
163                                      struct io_plan *(*init)(struct io_conn *,
164                                                              void *),
165                                      void *arg);
166
167 /**
168  * io_close_listener - delete a listener.
169  * @listener: the listener returned from io_new_listener.
170  *
171  * This closes the fd and frees @listener.
172  *
173  * Example:
174  * ...
175  *      struct io_listener *l = do_listen("8111");
176  *      if (l) {
177  *              io_loop();
178  *              io_close_listener(l);
179  *      }
180  */
181 void io_close_listener(struct io_listener *listener);
182
183 /**
184  * io_write - output plan to write data.
185  * @conn: the connection that plan is for.
186  * @data: the data buffer.
187  * @len: the length to write.
188  * @next: function to call output is done.
189  * @arg: @next argument
190  *
191  * This updates the output plan, to write out a data buffer.  Once it's all
192  * written, the @next function will be called: on an error, the finish
193  * function is called instead.
194  *
195  * Note that the I/O may actually be done immediately.
196  *
197  * Example:
198  * static struct io_plan *write_to_conn(struct io_conn *conn, const char *msg)
199  * {
200  *      // Write message, then close.
201  *      return io_write(conn, msg, strlen(msg), io_close_cb, NULL);
202  * }
203  */
204 #define io_write(conn, data, len, next, arg)                            \
205         io_write_((conn), (data), (len),                                \
206                   typesafe_cb_preargs(struct io_plan *, void *,         \
207                                       (next), (arg), struct io_conn *), \
208                   (arg))
209 struct io_plan *io_write_(struct io_conn *conn,
210                           const void *data, size_t len,
211                           struct io_plan *(*next)(struct io_conn *, void *),
212                           void *arg);
213
214 /**
215  * io_read - input plan to read data.
216  * @conn: the connection that plan is for.
217  * @data: the data buffer.
218  * @len: the length to read.
219  * @next: function to call once input is done.
220  * @arg: @next argument
221  *
222  * This creates a plan to read data into a buffer.  Once it's all
223  * read, the @next function will be called: on an error, the finish
224  * function is called instead.
225  *
226  * Note that the I/O may actually be done immediately.
227  *
228  * Example:
229  * static struct io_plan *read_from_conn(struct io_conn *conn, char *buf)
230  * {
231  *      // Read message, then close.
232  *      return io_read(conn, buf, 12, io_close_cb, NULL);
233  * }
234  */
235 #define io_read(conn, data, len, next, arg)                             \
236         io_read_((conn), (data), (len),                                 \
237                  typesafe_cb_preargs(struct io_plan *, void *,          \
238                                      (next), (arg), struct io_conn *),  \
239                  (arg))
240 struct io_plan *io_read_(struct io_conn *conn,
241                          void *data, size_t len,
242                          struct io_plan *(*next)(struct io_conn *, void *),
243                          void *arg);
244
245
246 /**
247  * io_read_partial - input plan to read some data.
248  * @conn: the connection that plan is for.
249  * @data: the data buffer.
250  * @maxlen: the maximum length to read
251  * @lenp: set to the length actually read.
252  * @next: function to call once input is done.
253  * @arg: @next argument
254  *
255  * This creates a plan to read data into a buffer.  Once any data is
256  * read, @len is updated and the @next function will be called: on an
257  * error, the finish function is called instead.
258  *
259  * Note that the I/O may actually be done immediately.
260  *
261  * Example:
262  * struct buf {
263  *      size_t len;
264  *      char buf[12];
265  * };
266  *
267  * static struct io_plan *dump(struct io_conn *conn, struct buf *b)
268  * {
269  *      printf("Partial read: '%*s'\n", (int)b->len, b->buf);
270  *      free(b);
271  *      return io_close(conn);
272  * }
273  *
274  * static struct io_plan *read_part(struct io_conn *conn, struct buf *b)
275  * {
276  *      // Read message, then dump and close.
277  *      return io_read_partial(conn, b->buf, sizeof(b->buf), &b->len, dump, b);
278  * }
279  */
280 #define io_read_partial(conn, data, maxlen, lenp, next, arg)            \
281         io_read_partial_((conn), (data), (maxlen), (lenp),              \
282                          typesafe_cb_preargs(struct io_plan *, void *,  \
283                                              (next), (arg),             \
284                                              struct io_conn *),         \
285                          (arg))
286 struct io_plan *io_read_partial_(struct io_conn *conn,
287                                  void *data, size_t maxlen, size_t *lenp,
288                                  struct io_plan *(*next)(struct io_conn *,
289                                                          void *),
290                                  void *arg);
291
292 /**
293  * io_write_partial - output plan to write some data.
294  * @conn: the connection that plan is for.
295  * @data: the data buffer.
296  * @maxlen: the maximum length to write
297  * @lenp: set to the length actually written.
298  * @next: function to call once output is done.
299  * @arg: @next argument
300  *
301  * This creates a plan to write data from a buffer.   Once any data is
302  * written, @len is updated and the @next function will be called: on an
303  * error, the finish function is called instead.
304  *
305  * Note that the I/O may actually be done immediately.
306  *
307  * Example:
308  * struct buf {
309  *      size_t len;
310  *      char buf[12];
311  * };
312  *
313  * static struct io_plan *show_partial(struct io_conn *conn, struct buf *b)
314  * {
315  *      printf("Only wrote: '%*s'\n", (int)b->len, b->buf);
316  *      free(b);
317  *      return io_close(conn);
318  * }
319  *
320  * static struct io_plan *write_part(struct io_conn *conn, struct buf *b)
321  * {
322  *      // Write message, then dump and close.
323  *      strcpy(b->buf, "Hello world");
324  *      return io_write_partial(conn, b->buf, strlen(b->buf),
325  *                              &b->len, show_partial, b);
326  * }
327  */
328 #define io_write_partial(conn, data, maxlen, lenp, next, arg)           \
329         io_write_partial_((conn), (data), (maxlen), (lenp),             \
330                           typesafe_cb_preargs(struct io_plan *, void *, \
331                                               (next), (arg),            \
332                                               struct io_conn *),        \
333                           (arg))
334 struct io_plan *io_write_partial_(struct io_conn *conn,
335                                   const void *data, size_t maxlen, size_t *lenp,
336                                   struct io_plan *(*next)(struct io_conn *,
337                                                           void*),
338                                   void *arg);
339
340 /**
341  * io_always - plan to immediately call next callback
342  * @conn: the connection that plan is for.
343  * @dir: IO_IN or IO_OUT
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_IN, io_close_cb, NULL);
356  * }
357  */
358 #define io_always(conn, dir, next, arg)                                 \
359         io_always_((conn), dir, 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, enum io_direction dir,
365                            struct io_plan *(*next)(struct io_conn *, void *),
366                            void *arg);
367
368 /**
369  * io_connect - create an asynchronous connection to a listening socket.
370  * @conn: the connection that plan is for.
371  * @addr: where to connect.
372  * @init: function to call once it's connected
373  * @arg: @init argument
374  *
375  * This initiates a connection, and creates a plan for
376  * (asynchronously) completing it.  Once complete, the @init function
377  * will be called.
378  *
379  * Example:
380  * #include <sys/types.h>
381  * #include <sys/socket.h>
382  * #include <netdb.h>
383  *
384  * // Write, then close socket.
385  * static struct io_plan *init_connect(struct io_conn *conn,
386  *                                     struct addrinfo *addrinfo)
387  * {
388  *      return io_connect(conn, addrinfo, io_close_cb, NULL);
389  * }
390  *
391  * ...
392  *
393  *      int fd;
394  *      struct addrinfo *addrinfo;
395  *
396  *      fd = socket(AF_INET, SOCK_STREAM, 0);
397  *      getaddrinfo("localhost", "8111", NULL, &addrinfo);
398  *      io_new_conn(NULL, fd, init_connect, addrinfo);
399  */
400 struct addrinfo;
401 #define io_connect(conn, addr, next, arg)                               \
402         io_connect_((conn), (addr),                                     \
403                     typesafe_cb_preargs(struct io_plan *, void *,       \
404                                         (next), (arg),                  \
405                                         struct io_conn *),              \
406                     (arg))
407
408 struct io_plan *io_connect_(struct io_conn *conn, const struct addrinfo *addr,
409                             struct io_plan *(*next)(struct io_conn *, void *),
410                             void *arg);
411
412 /**
413  * io_wait - leave a plan idle until something wakes us.
414  * @conn: the connection that plan is for.
415  * @waitaddr: the address to wait on.
416  * @dir: IO_IN or IO_OUT
417  * @next: function to call after waiting.
418  * @arg: @next argument
419  *
420  * This leaves the input or output idle: io_wake(@waitaddr) will be
421  * called later to restart the connection.
422  *
423  * Example:
424  * // Silly example to wait then close.
425  * static struct io_plan *wait(struct io_conn *conn, void *b)
426  * {
427  *      return io_wait(conn, b, IO_IN, io_close_cb, NULL);
428  * }
429  */
430 #define io_wait(conn, waitaddr, dir, next, arg)                         \
431         io_wait_((conn), (waitaddr), (dir),                             \
432                  typesafe_cb_preargs(struct io_plan *, void *,          \
433                                      (next), (arg),                     \
434                                      struct io_conn *),                 \
435                  (arg))
436
437 struct io_plan *io_wait_(struct io_conn *conn,
438                          const void *wait, enum io_direction dir,
439                          struct io_plan *(*next)(struct io_conn *, void *),
440                          void *arg);
441
442
443 /**
444  * io_wake - wake up any connections waiting on @wait
445  * @waitaddr: the address to trigger.
446  *
447  * All io_conns who have returned io_wait() on @waitaddr will move on
448  * to their next callback.
449  *
450  * Example:
451  * static struct io_plan *wake_it(struct io_conn *conn, void *b)
452  * {
453  *      io_wake(b);
454  *      return io_close(conn);
455  * }
456  */
457 void io_wake(const void *wait);
458
459 /**
460  * io_break - return from io_loop()
461  * @ret: non-NULL value to return from io_loop().
462  *
463  * This breaks out of the io_loop.  As soon as the current function
464  * returns, any io_close()'d connections will have their finish
465  * callbacks called, then io_loop() with return with @ret.
466  *
467  * If io_loop() is called again, then @plan will be carried out.
468  *
469  * Example:
470  *      static struct io_plan *fail_on_timeout(struct io_conn *conn, char *msg)
471  *      {
472  *              io_break(msg);
473  *              return io_close(conn);
474  *      }
475  */
476 void io_break(const void *ret);
477
478 /**
479  * io_never - assert if callback is called.
480  * @conn: the connection that plan is for.
481  *
482  * Sometimes you want to make it clear that a callback should never happen
483  * (eg. for io_break).  This will assert() if called.
484  *
485  * Example:
486  * static struct io_plan *break_out(struct io_conn *conn, void *unused)
487  * {
488  *      io_break(conn);
489  *      // We won't ever return from io_break
490  *      return io_never(conn);
491  * }
492  */
493 struct io_plan *io_never(struct io_conn *conn);
494
495 /* FIXME: io_recvfrom/io_sendto */
496
497 /**
498  * io_close - plan to close a connection.
499  * @conn: the connection to close.
500  *
501  * On return to io_loop, the connection will be closed.  It doesn't have
502  * to be the current connection and it doesn't need to be idle.  No more
503  * IO or callbacks will occur.
504  *
505  * You can close a connection twice without harmful effects.
506  *
507  * Example:
508  * static struct io_plan *close_on_timeout(struct io_conn *conn, const char *msg)
509  * {
510  *      printf("closing: %s\n", msg);
511  *      return io_close(conn);
512  * }
513  */
514 struct io_plan *io_close(struct io_conn *conn);
515
516 /**
517  * io_close_cb - helper callback to close a connection.
518  * @conn: the connection.
519  *
520  * This schedules a connection to be closed; designed to be used as
521  * a callback function.
522  *
523  * Example:
524  *      #define close_on_timeout io_close_cb
525  */
526 struct io_plan *io_close_cb(struct io_conn *, void *unused);
527
528 /**
529  * io_loop - process fds until all closed on io_break.
530  *
531  * This is the core loop; it exits with the io_break() arg, or NULL if
532  * all connections and listeners are closed.
533  *
534  * Example:
535  *      io_loop();
536  */
537 void *io_loop(void);
538
539 /**
540  * io_conn_fd - get the fd from a connection.
541  * @conn: the connection.
542  *
543  * Sometimes useful, eg for getsockname().
544  */
545 int io_conn_fd(const struct io_conn *conn);
546 #endif /* CCAN_IO_H */