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