]> git.ozlabs.org Git - ccan/blob - ccan/io/io.h
io: io_never for events that should never happen.
[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/typesafe_cb/typesafe_cb.h>
5 #include <ccan/time/time.h>
6 #include <stdbool.h>
7 #include <unistd.h>
8 #include "io_plan.h"
9
10 /**
11  * io_new_conn - create a new connection.
12  * @fd: the file descriptor.
13  * @plan: the first I/O to perform.
14  *
15  * This creates a connection which owns @fd.  @plan will be called on the
16  * next io_loop().
17  *
18  * Returns NULL on error (and sets errno).
19  *
20  * Example:
21  *      int fd[2];
22  *      struct io_conn *conn;
23  *
24  *      pipe(fd);
25  *      // Plan is to close the fd immediately.
26  *      conn = io_new_conn(fd[0], io_close());
27  *      if (!conn)
28  *              exit(1);
29  */
30 #define io_new_conn(fd, plan)                           \
31         (io_plan_no_debug(), io_new_conn_((fd), (plan)))
32 struct io_conn *io_new_conn_(int fd, struct io_plan plan);
33
34 /**
35  * io_set_finish - set finish function on a connection.
36  * @conn: the connection.
37  * @finish: the function to call when it's closed or fails.
38  * @arg: the argument to @finish.
39  *
40  * @finish will be called when an I/O operation fails, or you call
41  * io_close() on the connection.  errno will be set to the value
42  * after the failed I/O, or at the call to io_close().  The fd
43  * will be closed (unless a duplex) before @finish is called.
44  *
45  * Example:
46  * static void finish(struct io_conn *conn, void *unused)
47  * {
48  *      // errno is not 0 after success, so this is a bit useless.
49  *      printf("Conn %p closed with errno %i\n", conn, errno);
50  * }
51  * ...
52  *      io_set_finish(conn, finish, NULL);
53  */
54 #define io_set_finish(conn, finish, arg)                                \
55         io_set_finish_((conn),                                          \
56                        typesafe_cb_preargs(void, void *,                \
57                                            (finish), (arg),             \
58                                            struct io_conn *),           \
59                        (arg))
60 void io_set_finish_(struct io_conn *conn,
61                     void (*finish)(struct io_conn *, void *),
62                     void *arg);
63
64 /**
65  * io_new_listener - create a new accepting listener.
66  * @fd: the file descriptor.
67  * @init: the function to call for a new connection
68  * @arg: the argument to @init.
69  *
70  * When @fd becomes readable, we accept() and pass that fd to init().
71  *
72  * Returns NULL on error (and sets errno).
73  *
74  * Example:
75  * #include <sys/types.h>
76  * #include <sys/socket.h>
77  * #include <netdb.h>
78  *
79  * static void start_conn(int fd, char *msg)
80  * {
81  *      printf("%s fd %i\n", msg, fd);
82  *      close(fd);
83  * }
84  *
85  * // Set up a listening socket, return it.
86  * static struct io_listener *do_listen(const char *port)
87  * {
88  *      struct addrinfo *addrinfo, hints;
89  *      int fd, on = 1;
90  *
91  *      memset(&hints, 0, sizeof(hints));
92  *      hints.ai_family = AF_UNSPEC;
93  *      hints.ai_socktype = SOCK_STREAM;
94  *      hints.ai_flags = AI_PASSIVE;
95  *      hints.ai_protocol = 0;
96  *
97  *      if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
98  *              return NULL;
99  *
100  *      fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
101  *                  addrinfo->ai_protocol);
102  *      if (fd < 0)
103  *              return NULL;
104  *
105  *      freeaddrinfo(addrinfo);
106  *      setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
107  *      if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
108  *              close(fd);
109  *              return NULL;
110  *      }
111  *      if (listen(fd, 1) != 0) {
112  *              close(fd);
113  *              return NULL;
114  *      }
115  *      return io_new_listener(fd, start_conn, (char *)"Got one!");
116  * }
117  */
118 #define io_new_listener(fd, init, arg)                                  \
119         io_new_listener_((fd),                                          \
120                          typesafe_cb_preargs(void, void *,              \
121                                              (init), (arg),             \
122                                              int fd),                   \
123                          (arg))
124 struct io_listener *io_new_listener_(int fd,
125                                      void (*init)(int fd, void *arg),
126                                      void *arg);
127
128 /**
129  * io_close_listener - delete a listener.
130  * @listener: the listener returned from io_new_listener.
131  *
132  * This closes the fd and frees @listener.
133  *
134  * Example:
135  * ...
136  *      struct io_listener *l = do_listen("8111");
137  *      if (l) {
138  *              io_loop();
139  *              io_close_listener(l);
140  *      }
141  */
142 void io_close_listener(struct io_listener *listener);
143
144 /**
145  * io_write - plan to write data.
146  * @data: the data buffer.
147  * @len: the length to write.
148  * @cb: function to call once it's done.
149  * @arg: @cb argument
150  *
151  * This creates a plan write out a data buffer.  Once it's all
152  * written, the @cb function will be called: on an error, the finish
153  * function is called instead.
154  *
155  * Note that the I/O may actually be done immediately.
156  *
157  * Example:
158  * static void start_conn_with_write(int fd, const char *msg)
159  * {
160  *      // Write message, then close.
161  *      io_new_conn(fd, io_write(msg, strlen(msg), io_close_cb, NULL));
162  * }
163  */
164 #define io_write(data, len, cb, arg)                                    \
165         io_debug(io_write_((data), (len),                               \
166                            typesafe_cb_preargs(struct io_plan, void *,  \
167                                                (cb), (arg), struct io_conn *), \
168                            (arg)))
169 struct io_plan io_write_(const void *data, size_t len,
170                          struct io_plan (*cb)(struct io_conn *, void *),
171                          void *arg);
172
173 /**
174  * io_read - plan to read data.
175  * @data: the data buffer.
176  * @len: the length to read.
177  * @cb: function to call once it's done.
178  * @arg: @cb argument
179  *
180  * This creates a plan to read data into a buffer.  Once it's all
181  * read, the @cb function will be called: on an error, the finish
182  * function is called instead.
183  *
184  * Note that the I/O may actually be done immediately.
185  *
186  * Example:
187  * static void start_conn_with_read(int fd, char msg[12])
188  * {
189  *      // Read message, then close.
190  *      io_new_conn(fd, io_read(msg, 12, io_close_cb, NULL));
191  * }
192  */
193 #define io_read(data, len, cb, arg)                                     \
194         io_debug(io_read_((data), (len),                                \
195                           typesafe_cb_preargs(struct io_plan, void *,   \
196                                               (cb), (arg), struct io_conn *), \
197                           (arg)))
198 struct io_plan io_read_(void *data, size_t len,
199                         struct io_plan (*cb)(struct io_conn *, void *),
200                         void *arg);
201
202
203 /**
204  * io_read_partial - plan to read some data.
205  * @data: the data buffer.
206  * @len: the maximum length to read, set to the length actually read.
207  * @cb: function to call once it's done.
208  * @arg: @cb argument
209  *
210  * This creates a plan to read data into a buffer.  Once any data is
211  * read, @len is updated and the @cb function will be called: on an
212  * error, the finish function is called instead.
213  *
214  * Note that the I/O may actually be done immediately.
215  *
216  * Example:
217  * struct buf {
218  *      size_t len;
219  *      char buf[12];
220  * };
221  *
222  * static struct io_plan dump_and_close(struct io_conn *conn, struct buf *b)
223  * {
224  *      printf("Partial read: '%*s'\n", (int)b->len, b->buf);
225  *      free(b);
226  *      return io_close();
227  * }
228  *
229  * static void start_conn_with_part_read(int fd, void *unused)
230  * {
231  *      struct buf *b = malloc(sizeof(*b));
232  *
233  *      // Read message, then dump and close.
234  *      b->len = sizeof(b->buf);
235  *      io_new_conn(fd, io_read_partial(b->buf, &b->len, dump_and_close, b));
236  * }
237  */
238 #define io_read_partial(data, len, cb, arg)                             \
239         io_debug(io_read_partial_((data), (len),                        \
240                                   typesafe_cb_preargs(struct io_plan, void *, \
241                                                       (cb), (arg),      \
242                                                       struct io_conn *), \
243                                   (arg)))
244 struct io_plan io_read_partial_(void *data, size_t *len,
245                                 struct io_plan (*cb)(struct io_conn *, void *),
246                                 void *arg);
247
248 /**
249  * io_write_partial - plan to write some data.
250  * @data: the data buffer.
251  * @len: the maximum length to write, set to the length actually written.
252  * @cb: function to call once it's done.
253  * @arg: @cb argument
254  *
255  * This creates a plan to write data from a buffer.   Once any data is
256  * written, @len is updated and the @cb 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 show_remainder(struct io_conn *conn, struct buf *b)
268  * {
269  *      printf("Only wrote: '%*s'\n", (int)b->len, b->buf);
270  *      free(b);
271  *      return io_close();
272  * }
273  *
274  * static void start_conn_with_part_read(int fd, void *unused)
275  * {
276  *      struct buf *b = malloc(sizeof(*b));
277  *
278  *      // Write message, then dump and close.
279  *      b->len = sizeof(b->buf);
280  *      strcpy(b->buf, "Hello world");
281  *      io_new_conn(fd, io_write_partial(b->buf, &b->len, show_remainder, b));
282  * }
283  */
284 #define io_write_partial(data, len, cb, arg)                            \
285         io_debug(io_write_partial_((data), (len),                       \
286                                    typesafe_cb_preargs(struct io_plan, void *, \
287                                                        (cb), (arg),     \
288                                                        struct io_conn *), \
289                                    (arg)))
290 struct io_plan io_write_partial_(const void *data, size_t *len,
291                                  struct io_plan (*cb)(struct io_conn *, void*),
292                                  void *arg);
293
294 /**
295  * io_always - plan to immediately call next callback.
296  * @cb: function to call.
297  * @arg: @cb argument
298  *
299  * Sometimes it's neater to plan a callback rather than call it directly;
300  * for example, if you only need to read data for one path and not another.
301  *
302  * Example:
303  * static void start_conn_with_nothing(int fd)
304  * {
305  *      // Silly example: close on next time around loop.
306  *      io_new_conn(fd, io_always(io_close_cb, NULL));
307  * }
308  */
309 #define io_always(cb, arg)                                              \
310         io_debug(io_always_(typesafe_cb_preargs(struct io_plan, void *, \
311                                                 (cb), (arg),            \
312                                                 struct io_conn *),      \
313                             (arg)))
314 struct io_plan io_always_(struct io_plan (*cb)(struct io_conn *, void *),
315                           void *arg);
316
317 /**
318  * io_connect - plan to connect to a listening socket.
319  * @fd: file descriptor.
320  * @addr: where to connect.
321  * @cb: function to call once it's done.
322  * @arg: @cb argument
323  *
324  * This initiates a connection, and creates a plan for
325  * (asynchronously).  completing it.  Once complete, @len is updated
326  * and the @cb function will be called: on an error, the finish
327  * function is called instead.
328  *
329  * Note that the connect may actually be done immediately.
330  *
331  * Example:
332  * #include <sys/types.h>
333  * #include <sys/socket.h>
334  * #include <netdb.h>
335  *
336  * // Write, then close socket.
337  * static struct io_plan start_write(struct io_conn *conn, void *unused)
338  * {
339  *      return io_write("hello", 5, io_close_cb, NULL);
340  * }
341  *
342  * ...
343  *
344  *      int fd;
345  *      struct addrinfo *addrinfo;
346  *
347  *      fd = socket(AF_INET, SOCK_STREAM, 0);
348  *      getaddrinfo("localhost", "8111", NULL, &addrinfo);
349  *      io_new_conn(fd, io_connect(fd, addrinfo, start_write, NULL));
350  */
351 struct addrinfo;
352 #define io_connect(fd, addr, cb, arg)                                   \
353         io_debug(io_connect_((fd), (addr),                              \
354                              typesafe_cb_preargs(struct io_plan, void *, \
355                                                  (cb), (arg),           \
356                                                  struct io_conn *),     \
357                              (arg)))
358 struct io_plan io_connect_(int fd, const struct addrinfo *addr,
359                            struct io_plan (*cb)(struct io_conn *, void*),
360                            void *arg);
361
362 /**
363  * io_idle - plan to do nothing.
364  *
365  * This indicates the connection is idle: io_wake() will be called later do
366  * give the connection a new plan.
367  *
368  * Example:
369  *      struct io_conn *sleeper;
370  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
371  *      if (!sleeper)
372  *              exit(1);
373  */
374 #define io_idle() io_debug(io_idle_())
375 struct io_plan io_idle_(void);
376
377 /**
378  * io_timeout - set timeout function if the callback doesn't complete.
379  * @conn: the current connection.
380  * @ts: how long until the timeout should be called.
381  * @cb: callback to call.
382  * @arg: argument to @cb.
383  *
384  * If the usual next callback is not called for this connection before @ts,
385  * this function will be called.  If next callback is called, the timeout
386  * is automatically removed.
387  *
388  * Returns false on allocation failure.  A connection can only have one
389  * timeout.
390  *
391  * Example:
392  *      static struct io_plan close_on_timeout(struct io_conn *conn, char *msg)
393  *      {
394  *              printf("%s\n", msg);
395  *              return io_close();
396  *      }
397  *
398  *      ...
399  *      io_timeout(sleeper, time_from_msec(100),
400  *                 close_on_timeout, (char *)"Bye!");
401  */
402 #define io_timeout(conn, ts, fn, arg)                                   \
403         io_timeout_((conn), (ts),                                       \
404                     typesafe_cb_preargs(struct io_plan, void *,         \
405                                         (fn), (arg),                    \
406                                         struct io_conn *),              \
407                     (arg))
408 bool io_timeout_(struct io_conn *conn, struct timespec ts,
409                  struct io_plan (*fn)(struct io_conn *, void *), void *arg);
410
411 /**
412  * io_duplex - split an fd into two connections.
413  * @conn: a connection.
414  * @plan: the first I/O function to call.
415  *
416  * Sometimes you want to be able to simultaneously read and write on a
417  * single fd, but io forces a linear call sequence.  The solution is
418  * to have two connections for the same fd, and use one for read
419  * operations and one for write.
420  *
421  * You must io_close() both of them to close the fd.
422  *
423  * Example:
424  *      static void setup_read_write(int fd,
425  *                                   char greet_in[5], const char greet_out[5])
426  *      {
427  *              struct io_conn *writer, *reader;
428  *
429  *              // Read their greeting and send ours at the same time.
430  *              writer = io_new_conn(fd,
431  *                                   io_write(greet_out, 5, io_close_cb, NULL));
432  *              reader = io_duplex(writer,
433  *                                   io_read(greet_in, 5, io_close_cb, NULL));
434  *              if (!reader || !writer)
435  *                      exit(1);
436  *      }
437  */
438 #define io_duplex(conn, plan)                           \
439         (io_plan_no_debug(), io_duplex_((conn), (plan)))
440 struct io_conn *io_duplex_(struct io_conn *conn, struct io_plan plan);
441
442 /**
443  * io_wake - wake up an idle connection.
444  * @conn: an idle connection.
445  * @plan: the next I/O plan for @conn.
446  *
447  * This makes @conn ready to do I/O the next time around the io_loop().
448  *
449  * Example:
450  *      struct io_conn *sleeper;
451  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
452  *
453  *      io_wake(sleeper, io_write("junk", 4, io_close_cb, NULL));
454  */
455 #define io_wake(conn, plan) (io_plan_no_debug(), io_wake_((conn), (plan)))
456 void io_wake_(struct io_conn *conn, struct io_plan plan);
457
458 /**
459  * io_is_idle - is a connection idle?
460  *
461  * This can be useful for complex protocols, eg. where you want a connection
462  * to send something, so you queue it and wake it if it's idle.
463  *
464  * Example:
465  *      struct io_conn *sleeper;
466  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
467  *
468  *      assert(io_is_idle(sleeper));
469  *      io_wake(sleeper, io_write("junk", 4, io_close_cb, NULL));
470  */
471 bool io_is_idle(const struct io_conn *conn);
472
473 /**
474  * io_break - return from io_loop()
475  * @ret: non-NULL value to return from io_loop().
476  * @plan: I/O to perform on return (if any)
477  *
478  * This breaks out of the io_loop.  As soon as the current @next
479  * function returns, any io_closed()'d connections will have their
480  * finish callbacks called, then io_loop() with return with @ret.
481  *
482  * If io_loop() is called again, then @plan will be carried out.
483  *
484  * Example:
485  *      static struct io_plan fail_on_timeout(struct io_conn *conn, char *msg)
486  *      {
487  *              return io_break(msg, io_close());
488  *      }
489  */
490 #define io_break(ret, plan) (io_plan_no_debug(), io_break_((ret), (plan)))
491 struct io_plan io_break_(void *ret, struct io_plan plan);
492
493 /**
494  * io_never - assert if callback is called.
495  *
496  * Sometimes you want to make it clear that a callback should never happen
497  * (eg. for io_break).  This will assert() if called.
498  *
499  * Example:
500  * static struct io_plan break_out(struct io_conn *conn, void *unused)
501  * {
502  *      // We won't ever return from io_break
503  *      return io_break(conn, io_never());
504  * }
505  */
506 struct io_plan io_never(void);
507
508 /* FIXME: io_recvfrom/io_sendto */
509
510 /**
511  * io_close - plan to close a connection.
512  *
513  * On return to io_loop, the connection will be closed.
514  *
515  * Example:
516  * static struct io_plan close_on_timeout(struct io_conn *conn, const char *msg)
517  * {
518  *      printf("closing: %s\n", msg);
519  *      return io_close();
520  * }
521  */
522 #define io_close() io_debug(io_close_())
523 struct io_plan io_close_(void);
524
525 /**
526  * io_close_cb - helper callback to close a connection.
527  * @conn: the connection.
528  *
529  * This schedules a connection to be closed; designed to be used as
530  * a callback function.
531  *
532  * Example:
533  *      #define close_on_timeout io_close_cb
534  */
535 struct io_plan io_close_cb(struct io_conn *, void *unused);
536
537 /**
538  * io_close_other - close different connection next time around the I/O loop.
539  * @conn: the connection to close.
540  *
541  * This is used to force a different connection to close: no more I/O will
542  * happen on @conn, even if it's pending.
543  *
544  * It's a bug to use this on the current connection!
545  *
546  * Example:
547  * static void stop_connection(struct io_conn *conn)
548  * {
549  *      printf("forcing stop on connection\n");
550  *      io_close_other(conn);
551  * }
552  */
553 void io_close_other(struct io_conn *conn);
554
555 /**
556  * io_loop - process fds until all closed on io_break.
557  *
558  * This is the core loop; it exits with the io_break() arg, or NULL if
559  * all connections and listeners are closed.
560  *
561  * Example:
562  *      io_loop();
563  */
564 void *io_loop(void);
565
566 /**
567  * io_conn_fd - get the fd from a connection.
568  * @conn: the connection.
569  *
570  * Sometimes useful, eg for getsockname().
571  */
572 int io_conn_fd(const struct io_conn *conn);
573
574 /**
575  * io_set_alloc - set alloc/realloc/free function for io to use.
576  * @allocfn: allocator function
577  * @reallocfn: reallocator function, ptr may be NULL, size never 0.
578  * @freefn: free function
579  *
580  * By default io uses malloc/realloc/free, and returns NULL if they fail.
581  * You can set your own variants here.
582  */
583 void io_set_alloc(void *(*allocfn)(size_t size),
584                   void *(*reallocfn)(void *ptr, size_t size),
585                   void (*freefn)(void *ptr));
586 #endif /* CCAN_IO_H */