]> git.ozlabs.org Git - ccan/blob - ccan/io/io.h
io failtest timer tools: fallout from time changes.
[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 /**
319  * io_connect - plan to connect to a listening socket.
320  * @fd: file descriptor.
321  * @addr: where to connect.
322  * @cb: function to call once it's done.
323  * @arg: @cb argument
324  *
325  * This initiates a connection, and creates a plan for
326  * (asynchronously).  completing it.  Once complete, @len is updated
327  * and the @cb function will be called: on an error, the finish
328  * function is called instead.
329  *
330  * Note that the connect may actually be done immediately.
331  *
332  * Example:
333  * #include <sys/types.h>
334  * #include <sys/socket.h>
335  * #include <netdb.h>
336  *
337  * // Write, then close socket.
338  * static struct io_plan start_write(struct io_conn *conn, void *unused)
339  * {
340  *      return io_write("hello", 5, io_close_cb, NULL);
341  * }
342  *
343  * ...
344  *
345  *      int fd;
346  *      struct addrinfo *addrinfo;
347  *
348  *      fd = socket(AF_INET, SOCK_STREAM, 0);
349  *      getaddrinfo("localhost", "8111", NULL, &addrinfo);
350  *      io_new_conn(fd, io_connect(fd, addrinfo, start_write, NULL));
351  */
352 struct addrinfo;
353 #define io_connect(fd, addr, cb, arg)                                   \
354         io_debug(io_connect_((fd), (addr),                              \
355                              typesafe_cb_preargs(struct io_plan, void *, \
356                                                  (cb), (arg),           \
357                                                  struct io_conn *),     \
358                              (arg)))
359 struct io_plan io_connect_(int fd, const struct addrinfo *addr,
360                            struct io_plan (*cb)(struct io_conn *, void*),
361                            void *arg);
362
363 /**
364  * io_wait - plan to wait for something.
365  * @wait: the address to wait on.
366  * @cb: function to call after waiting.
367  * @arg: @cb argument
368  *
369  * This indicates the connection is idle: io_wake() will be called later to
370  * restart the connection.
371  *
372  * Example:
373  *      struct io_conn *sleeper;
374  *      unsigned int counter = 0;
375  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY),
376  *                            io_wait(&counter, io_close_cb, NULL));
377  *      if (!sleeper)
378  *              exit(1);
379  */
380 #define io_wait(wait, cb, arg)                                          \
381         io_debug(io_wait_(wait,                                         \
382                           typesafe_cb_preargs(struct io_plan, void *,   \
383                                               (cb), (arg),              \
384                                               struct io_conn *),        \
385                           (arg)))
386
387 struct io_plan io_wait_(const void *wait,
388                         struct io_plan (*cb)(struct io_conn *, void *),
389                         void *arg);
390
391 /**
392  * io_timeout - set timeout function if the callback doesn't complete.
393  * @conn: the current connection.
394  * @t: how long until the timeout should be called.
395  * @cb: callback to call.
396  * @arg: argument to @cb.
397  *
398  * If the usual next callback is not called for this connection before @ts,
399  * this function will be called.  If next callback is called, the timeout
400  * is automatically removed.
401  *
402  * Returns false on allocation failure.  A connection can only have one
403  * timeout.
404  *
405  * Example:
406  *      static struct io_plan close_on_timeout(struct io_conn *conn, char *msg)
407  *      {
408  *              printf("%s\n", msg);
409  *              return io_close();
410  *      }
411  *
412  *      ...
413  *      io_timeout(sleeper, time_from_msec(100),
414  *                 close_on_timeout, (char *)"Bye!");
415  */
416 #define io_timeout(conn, ts, fn, arg)                                   \
417         io_timeout_((conn), (ts),                                       \
418                     typesafe_cb_preargs(struct io_plan, void *,         \
419                                         (fn), (arg),                    \
420                                         struct io_conn *),              \
421                     (arg))
422 bool io_timeout_(struct io_conn *conn, struct timerel t,
423                  struct io_plan (*fn)(struct io_conn *, void *), void *arg);
424
425 /**
426  * io_duplex - split an fd into two connections.
427  * @conn: a connection.
428  * @plan: the first I/O function to call.
429  *
430  * Sometimes you want to be able to simultaneously read and write on a
431  * single fd, but io forces a linear call sequence.  The solution is
432  * to have two connections for the same fd, and use one for read
433  * operations and one for write.
434  *
435  * You must io_close() both of them to close the fd.
436  *
437  * Example:
438  *      static void setup_read_write(int fd,
439  *                                   char greet_in[5], const char greet_out[5])
440  *      {
441  *              struct io_conn *writer, *reader;
442  *
443  *              // Read their greeting and send ours at the same time.
444  *              writer = io_new_conn(fd,
445  *                                   io_write(greet_out, 5, io_close_cb, NULL));
446  *              reader = io_duplex(writer,
447  *                                   io_read(greet_in, 5, io_close_cb, NULL));
448  *              if (!reader || !writer)
449  *                      exit(1);
450  *      }
451  */
452 #define io_duplex(conn, plan)                           \
453         (io_plan_no_debug(), io_duplex_((conn), (plan)))
454 struct io_conn *io_duplex_(struct io_conn *conn, struct io_plan plan);
455
456 /**
457  * io_wake - wake up any connections waiting on @wait
458  * @wait: the address to trigger.
459  *
460  * Example:
461  *      unsigned int wait;
462  *
463  *      io_new_conn(open("/dev/null", O_RDONLY),
464  *                 io_wait(&wait, io_close_cb, NULL));
465  *
466  *      io_wake(&wait);
467  */
468 void io_wake(const void *wait);
469
470 /**
471  * io_break - return from io_loop()
472  * @ret: non-NULL value to return from io_loop().
473  * @plan: I/O to perform on return (if any)
474  *
475  * This breaks out of the io_loop.  As soon as the current @next
476  * function returns, any io_closed()'d connections will have their
477  * finish callbacks called, then io_loop() with return with @ret.
478  *
479  * If io_loop() is called again, then @plan will be carried out.
480  *
481  * Example:
482  *      static struct io_plan fail_on_timeout(struct io_conn *conn, char *msg)
483  *      {
484  *              return io_break(msg, io_close());
485  *      }
486  */
487 #define io_break(ret, plan) (io_plan_no_debug(), io_break_((ret), (plan)))
488 struct io_plan io_break_(void *ret, struct io_plan plan);
489
490 /**
491  * io_never - assert if callback is called.
492  *
493  * Sometimes you want to make it clear that a callback should never happen
494  * (eg. for io_break).  This will assert() if called.
495  *
496  * Example:
497  * static struct io_plan break_out(struct io_conn *conn, void *unused)
498  * {
499  *      // We won't ever return from io_break
500  *      return io_break(conn, io_never());
501  * }
502  */
503 struct io_plan io_never(void);
504
505 /* FIXME: io_recvfrom/io_sendto */
506
507 /**
508  * io_close - plan to close a connection.
509  *
510  * On return to io_loop, the connection will be closed.
511  *
512  * Example:
513  * static struct io_plan close_on_timeout(struct io_conn *conn, const char *msg)
514  * {
515  *      printf("closing: %s\n", msg);
516  *      return io_close();
517  * }
518  */
519 #define io_close() io_debug(io_close_())
520 struct io_plan io_close_(void);
521
522 /**
523  * io_close_cb - helper callback to close a connection.
524  * @conn: the connection.
525  *
526  * This schedules a connection to be closed; designed to be used as
527  * a callback function.
528  *
529  * Example:
530  *      #define close_on_timeout io_close_cb
531  */
532 struct io_plan io_close_cb(struct io_conn *, void *unused);
533
534 /**
535  * io_close_other - close different connection next time around the I/O loop.
536  * @conn: the connection to close.
537  *
538  * This is used to force a different connection to close: no more I/O will
539  * happen on @conn, even if it's pending.
540  *
541  * It's a bug to use this on the current connection!
542  *
543  * Example:
544  * static void stop_connection(struct io_conn *conn)
545  * {
546  *      printf("forcing stop on connection\n");
547  *      io_close_other(conn);
548  * }
549  */
550 void io_close_other(struct io_conn *conn);
551
552 /**
553  * io_loop - process fds until all closed on io_break.
554  *
555  * This is the core loop; it exits with the io_break() arg, or NULL if
556  * all connections and listeners are closed.
557  *
558  * Example:
559  *      io_loop();
560  */
561 void *io_loop(void);
562
563 /**
564  * io_conn_fd - get the fd from a connection.
565  * @conn: the connection.
566  *
567  * Sometimes useful, eg for getsockname().
568  */
569 int io_conn_fd(const struct io_conn *conn);
570
571 /**
572  * io_set_alloc - set alloc/realloc/free function for io to use.
573  * @allocfn: allocator function
574  * @reallocfn: reallocator function, ptr may be NULL, size never 0.
575  * @freefn: free function
576  *
577  * By default io uses malloc/realloc/free, and returns NULL if they fail.
578  * You can set your own variants here.
579  */
580 void io_set_alloc(void *(*allocfn)(size_t size),
581                   void *(*reallocfn)(void *ptr, size_t size),
582                   void (*freefn)(void *ptr));
583 #endif /* CCAN_IO_H */