]> git.ozlabs.org Git - ccan/blob - ccan/io/io.h
4468cee3ab0d10d14aacd6cc3cfa3462bc8ec114
[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_connect - plan to connect to a listening socket.
295  * @fd: file descriptor.
296  * @addr: where to connect.
297  * @cb: function to call once it's done.
298  * @arg: @cb argument
299  *
300  * This initiates a connection, and creates a plan for
301  * (asynchronously).  completing it.  Once complete, @len is updated
302  * and the @cb function will be called: on an error, the finish
303  * function is called instead.
304  *
305  * Note that the connect may actually be done immediately.
306  *
307  * Example:
308  * #include <sys/types.h>
309  * #include <sys/socket.h>
310  * #include <netdb.h>
311  *
312  * // Write, then close socket.
313  * static struct io_plan start_write(struct io_conn *conn, void *unused)
314  * {
315  *      return io_write("hello", 5, io_close_cb, NULL);
316  * }
317  *
318  * ...
319  *
320  *      int fd;
321  *      struct addrinfo *addrinfo;
322  *
323  *      fd = socket(AF_INET, SOCK_STREAM, 0);
324  *      getaddrinfo("localhost", "8111", NULL, &addrinfo);
325  *      io_new_conn(fd, io_connect(fd, addrinfo, start_write, NULL));
326  */
327 struct addrinfo;
328 #define io_connect(fd, addr, cb, arg)                                   \
329         io_debug(io_connect_((fd), (addr),                              \
330                              typesafe_cb_preargs(struct io_plan, void *, \
331                                                  (cb), (arg),           \
332                                                  struct io_conn *),     \
333                              (arg)))
334 struct io_plan io_connect_(int fd, const struct addrinfo *addr,
335                            struct io_plan (*cb)(struct io_conn *, void*),
336                            void *arg);
337
338 /**
339  * io_idle - plan to do nothing.
340  *
341  * This indicates the connection is idle: io_wake() will be called later do
342  * give the connection a new plan.
343  *
344  * Example:
345  *      struct io_conn *sleeper;
346  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
347  *      if (!sleeper)
348  *              exit(1);
349  */
350 #define io_idle() io_debug(io_idle_())
351 struct io_plan io_idle_(void);
352
353 /**
354  * io_timeout - set timeout function if the callback doesn't complete.
355  * @conn: the current connection.
356  * @ts: how long until the timeout should be called.
357  * @cb: callback to call.
358  * @arg: argument to @cb.
359  *
360  * If the usual next callback is not called for this connection before @ts,
361  * this function will be called.  If next callback is called, the timeout
362  * is automatically removed.
363  *
364  * Returns false on allocation failure.  A connection can only have one
365  * timeout.
366  *
367  * Example:
368  *      static struct io_plan close_on_timeout(struct io_conn *conn, char *msg)
369  *      {
370  *              printf("%s\n", msg);
371  *              return io_close();
372  *      }
373  *
374  *      ...
375  *      io_timeout(sleeper, time_from_msec(100),
376  *                 close_on_timeout, (char *)"Bye!");
377  */
378 #define io_timeout(conn, ts, fn, arg)                                   \
379         io_timeout_((conn), (ts),                                       \
380                     typesafe_cb_preargs(struct io_plan, void *,         \
381                                         (fn), (arg),                    \
382                                         struct io_conn *),              \
383                     (arg))
384 bool io_timeout_(struct io_conn *conn, struct timespec ts,
385                  struct io_plan (*fn)(struct io_conn *, void *), void *arg);
386
387 /**
388  * io_duplex - split an fd into two connections.
389  * @conn: a connection.
390  * @plan: the first I/O function to call.
391  *
392  * Sometimes you want to be able to simultaneously read and write on a
393  * single fd, but io forces a linear call sequence.  The solution is
394  * to have two connections for the same fd, and use one for read
395  * operations and one for write.
396  *
397  * You must io_close() both of them to close the fd.
398  *
399  * Example:
400  *      static void setup_read_write(int fd,
401  *                                   char greet_in[5], const char greet_out[5])
402  *      {
403  *              struct io_conn *writer, *reader;
404  *
405  *              // Read their greeting and send ours at the same time.
406  *              writer = io_new_conn(fd,
407  *                                   io_write(greet_out, 5, io_close_cb, NULL));
408  *              reader = io_duplex(writer,
409  *                                   io_read(greet_in, 5, io_close_cb, NULL));
410  *              if (!reader || !writer)
411  *                      exit(1);
412  *      }
413  */
414 #define io_duplex(conn, plan)                           \
415         (io_plan_no_debug(), io_duplex_((conn), (plan)))
416 struct io_conn *io_duplex_(struct io_conn *conn, struct io_plan plan);
417
418 /**
419  * io_wake - wake up an idle connection.
420  * @conn: an idle connection.
421  * @plan: the next I/O plan for @conn.
422  *
423  * This makes @conn ready to do I/O the next time around the io_loop().
424  *
425  * Example:
426  *      struct io_conn *sleeper;
427  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
428  *
429  *      io_wake(sleeper, io_write("junk", 4, io_close_cb, NULL));
430  */
431 #define io_wake(conn, plan) (io_plan_no_debug(), io_wake_((conn), (plan)))
432 void io_wake_(struct io_conn *conn, struct io_plan plan);
433
434 /**
435  * io_is_idle - is a connection idle?
436  *
437  * This can be useful for complex protocols, eg. where you want a connection
438  * to send something, so you queue it and wake it if it's idle.
439  *
440  * Example:
441  *      struct io_conn *sleeper;
442  *      sleeper = io_new_conn(open("/dev/null", O_RDONLY), io_idle());
443  *
444  *      assert(io_is_idle(sleeper));
445  *      io_wake(sleeper, io_write("junk", 4, io_close_cb, NULL));
446  */
447 bool io_is_idle(const struct io_conn *conn);
448
449 /**
450  * io_break - return from io_loop()
451  * @ret: non-NULL value to return from io_loop().
452  * @plan: I/O to perform on return (if any)
453  *
454  * This breaks out of the io_loop.  As soon as the current @next
455  * function returns, any io_closed()'d connections will have their
456  * finish callbacks called, then io_loop() with return with @ret.
457  *
458  * If io_loop() is called again, then @plan will be carried out.
459  *
460  * Example:
461  *      static struct io_plan fail_on_timeout(struct io_conn *conn, char *msg)
462  *      {
463  *              return io_break(msg, io_close());
464  *      }
465  */
466 #define io_break(ret, plan) (io_plan_no_debug(), io_break_((ret), (plan)))
467 struct io_plan io_break_(void *ret, struct io_plan plan);
468
469 /* FIXME: io_recvfrom/io_sendto */
470
471 /**
472  * io_close - plan to close a connection.
473  *
474  * On return to io_loop, the connection will be closed.
475  *
476  * Example:
477  * static struct io_plan close_on_timeout(struct io_conn *conn, const char *msg)
478  * {
479  *      printf("closing: %s\n", msg);
480  *      return io_close();
481  * }
482  */
483 #define io_close() io_debug(io_close_())
484 struct io_plan io_close_(void);
485
486 /**
487  * io_close_cb - helper callback to close a connection.
488  * @conn: the connection.
489  *
490  * This schedules a connection to be closed; designed to be used as
491  * a callback function.
492  *
493  * Example:
494  *      #define close_on_timeout io_close_cb
495  */
496 struct io_plan io_close_cb(struct io_conn *, void *unused);
497
498 /**
499  * io_loop - process fds until all closed on io_break.
500  *
501  * This is the core loop; it exits with the io_break() arg, or NULL if
502  * all connections and listeners are closed.
503  *
504  * Example:
505  *      io_loop();
506  */
507 void *io_loop(void);
508
509 /**
510  * io_conn_fd - get the fd from a connection.
511  * @conn: the connection.
512  *
513  * Sometimes useful, eg for getsockname().
514  */
515 int io_conn_fd(const struct io_conn *conn);
516
517 /**
518  * io_set_alloc - set alloc/realloc/free function for io to use.
519  * @allocfn: allocator function
520  * @reallocfn: reallocator function, ptr may be NULL, size never 0.
521  * @freefn: free function
522  *
523  * By default io uses malloc/realloc/free, and returns NULL if they fail.
524  * You can set your own variants here.
525  */
526 void io_set_alloc(void *(*allocfn)(size_t size),
527                   void *(*reallocfn)(void *ptr, size_t size),
528                   void (*freefn)(void *ptr));
529 #endif /* CCAN_IO_H */