]> git.ozlabs.org Git - ccan/blob - ccan/io/io.c
fdpass: fix complilation on FreeBSD.
[ccan] / ccan / io / io.c
1 /* Licensed under LGPLv2.1+ - see LICENSE file for details */
2 #include "io.h"
3 #include "backend.h"
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netdb.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <stdlib.h>
10 #include <assert.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <ccan/container_of/container_of.h>
14
15 void *io_loop_return;
16
17 struct io_plan io_conn_freed;
18 static bool io_extended_errors;
19
20 struct io_listener *io_new_listener_(const tal_t *ctx, int fd,
21                                      struct io_plan *(*init)(struct io_conn *,
22                                                              void *),
23                                      void *arg)
24 {
25         struct io_listener *l = tal(ctx, struct io_listener);
26         if (!l)
27                 return NULL;
28
29         l->fd.listener = true;
30         l->fd.fd = fd;
31         l->init = init;
32         l->arg = arg;
33         l->ctx = ctx;
34         if (!add_listener(l))
35                 return tal_free(l);
36         return l;
37 }
38
39 void io_close_listener(struct io_listener *l)
40 {
41         tal_free(l);
42 }
43
44 static struct io_plan *io_never_called(struct io_conn *conn, void *arg)
45 {
46         abort();
47 }
48
49 /* Returns false if conn was freed. */
50 static bool next_plan(struct io_conn *conn, struct io_plan *plan)
51 {
52         struct io_plan *(*next)(struct io_conn *, void *arg);
53
54         next = plan->next;
55
56         plan->status = IO_UNSET;
57         plan->io = NULL;
58         plan->next = io_never_called;
59
60         plan = next(conn, plan->next_arg);
61
62         if (plan == &io_conn_freed)
63                 return false;
64
65         assert(plan == &conn->plan[plan->dir]);
66         assert(conn->plan[IO_IN].status != IO_UNSET
67                || conn->plan[IO_OUT].status != IO_UNSET);
68
69         backend_new_plan(conn);
70         return true;
71 }
72
73 bool io_fd_block(int fd, bool block)
74 {
75         int flags = fcntl(fd, F_GETFL);
76
77         if (flags == -1)
78                 return false;
79
80         if (block)
81                 flags &= ~O_NONBLOCK;
82         else
83                 flags |= O_NONBLOCK;
84
85         return fcntl(fd, F_SETFL, flags) != -1;
86 }
87
88 struct io_conn *io_new_conn_(const tal_t *ctx, int fd,
89                              struct io_plan *(*init)(struct io_conn *, void *),
90                              void *arg)
91 {
92         struct io_conn *conn = tal(ctx, struct io_conn);
93
94         if (!conn)
95                 return NULL;
96
97         conn->fd.listener = false;
98         conn->fd.fd = fd;
99         conn->finish = NULL;
100         conn->finish_arg = NULL;
101
102         if (!add_conn(conn))
103                 return tal_free(conn);
104
105         /* Keep our I/O async. */
106         io_fd_block(fd, false);
107
108         /* So we can get back from plan -> conn later */
109         conn->plan[IO_OUT].dir = IO_OUT;
110         conn->plan[IO_IN].dir = IO_IN;
111
112         /* We start with out doing nothing, and in doing our init. */
113         conn->plan[IO_OUT].status = IO_UNSET;
114
115         conn->plan[IO_IN].next = init;
116         conn->plan[IO_IN].next_arg = arg;
117         if (!next_plan(conn, &conn->plan[IO_IN]))
118                 return NULL;
119
120         return conn;
121 }
122
123 bool io_conn_exclusive(struct io_conn *conn, bool exclusive)
124 {
125         return backend_set_exclusive(&conn->plan[IO_IN], exclusive);
126 }
127
128 bool io_conn_out_exclusive(struct io_conn *conn, bool exclusive)
129 {
130         return backend_set_exclusive(&conn->plan[IO_OUT], exclusive);
131 }
132
133 void io_set_finish_(struct io_conn *conn,
134                     void (*finish)(struct io_conn *, void *),
135                     void *arg)
136 {
137         conn->finish = finish;
138         conn->finish_arg = arg;
139 }
140
141 struct io_plan_arg *io_plan_arg(struct io_conn *conn, enum io_direction dir)
142 {
143         assert(conn->plan[dir].status == IO_UNSET);
144
145         conn->plan[dir].status = IO_POLLING_NOTSTARTED;
146         return &conn->plan[dir].arg;
147 }
148
149 static struct io_plan *set_always(struct io_conn *conn,
150                                   enum io_direction dir,
151                                   struct io_plan *(*next)(struct io_conn *,
152                                                           void *),
153                                   void *arg)
154 {
155         struct io_plan *plan = &conn->plan[dir];
156
157         plan->status = IO_ALWAYS;
158         /* Only happens on OOM, and only with non-default tal_backend. */
159         if (!backend_new_always(plan))
160                 return NULL;
161         return io_set_plan(conn, dir, NULL, next, arg);
162 }
163
164 static struct io_plan *io_always_dir(struct io_conn *conn,
165                                      enum io_direction dir,
166                                      struct io_plan *(*next)(struct io_conn *,
167                                                              void *),
168                                      void *arg)
169 {
170         return set_always(conn, dir, next, arg);
171 }
172
173 struct io_plan *io_always_(struct io_conn *conn,
174                            struct io_plan *(*next)(struct io_conn *, void *),
175                            void *arg)
176 {
177         return io_always_dir(conn, IO_IN, next, arg);
178 }
179
180 struct io_plan *io_out_always_(struct io_conn *conn,
181                                struct io_plan *(*next)(struct io_conn *,
182                                                        void *),
183                                void *arg)
184 {
185         return io_always_dir(conn, IO_OUT, next, arg);
186 }
187
188 static int do_write(int fd, struct io_plan_arg *arg)
189 {
190         ssize_t ret = write(fd, arg->u1.cp, arg->u2.s);
191         if (ret < 0)
192                 return -1;
193
194         arg->u1.cp += ret;
195         arg->u2.s -= ret;
196         return arg->u2.s == 0;
197 }
198
199 /* Queue some data to be written. */
200 struct io_plan *io_write_(struct io_conn *conn, const void *data, size_t len,
201                           struct io_plan *(*next)(struct io_conn *, void *),
202                           void *next_arg)
203 {
204         struct io_plan_arg *arg = io_plan_arg(conn, IO_OUT);
205
206         if (len == 0)
207                 return set_always(conn, IO_OUT, next, next_arg);
208
209         arg->u1.const_vp = data;
210         arg->u2.s = len;
211
212         return io_set_plan(conn, IO_OUT, do_write, next, next_arg);
213 }
214
215 static int do_read(int fd, struct io_plan_arg *arg)
216 {
217         ssize_t ret = read(fd, arg->u1.cp, arg->u2.s);
218         if (ret <= 0) {
219                 /* Errno isn't set if we hit EOF, so set it to distinct value */
220                 if (ret == 0)
221                         errno = 0;
222                 return -1;
223         }
224
225         arg->u1.cp += ret;
226         arg->u2.s -= ret;
227         return arg->u2.s == 0;
228 }
229
230 /* Queue a request to read into a buffer. */
231 struct io_plan *io_read_(struct io_conn *conn,
232                          void *data, size_t len,
233                          struct io_plan *(*next)(struct io_conn *, void *),
234                          void *next_arg)
235 {
236         struct io_plan_arg *arg = io_plan_arg(conn, IO_IN);
237
238         if (len == 0)
239                 return set_always(conn, IO_IN, next, next_arg);
240
241         arg->u1.cp = data;
242         arg->u2.s = len;
243
244         return io_set_plan(conn, IO_IN, do_read, next, next_arg);
245 }
246
247 static int do_read_partial(int fd, struct io_plan_arg *arg)
248 {
249         ssize_t ret = read(fd, arg->u1.cp, *(size_t *)arg->u2.vp);
250         if (ret <= 0) {
251                 /* Errno isn't set if we hit EOF, so set it to distinct value */
252                 if (ret == 0)
253                         errno = 0;
254                 return -1;
255         }
256
257         *(size_t *)arg->u2.vp = ret;
258         return 1;
259 }
260
261 /* Queue a partial request to read into a buffer. */
262 struct io_plan *io_read_partial_(struct io_conn *conn,
263                                  void *data, size_t maxlen, size_t *len,
264                                  struct io_plan *(*next)(struct io_conn *,
265                                                          void *),
266                                  void *next_arg)
267 {
268         struct io_plan_arg *arg = io_plan_arg(conn, IO_IN);
269
270         if (maxlen == 0)
271                 return set_always(conn, IO_IN, next, next_arg);
272
273         arg->u1.cp = data;
274         /* We store the max len in here temporarily. */
275         *len = maxlen;
276         arg->u2.vp = len;
277
278         return io_set_plan(conn, IO_IN, do_read_partial, next, next_arg);
279 }
280
281 static int do_write_partial(int fd, struct io_plan_arg *arg)
282 {
283         ssize_t ret = write(fd, arg->u1.cp, *(size_t *)arg->u2.vp);
284         if (ret < 0)
285                 return -1;
286
287         *(size_t *)arg->u2.vp = ret;
288         return 1;
289 }
290
291 /* Queue a partial write request. */
292 struct io_plan *io_write_partial_(struct io_conn *conn,
293                                   const void *data, size_t maxlen, size_t *len,
294                                   struct io_plan *(*next)(struct io_conn *,
295                                                           void*),
296                                   void *next_arg)
297 {
298         struct io_plan_arg *arg = io_plan_arg(conn, IO_OUT);
299
300         if (maxlen == 0)
301                 return set_always(conn, IO_OUT, next, next_arg);
302
303         arg->u1.const_vp = data;
304         /* We store the max len in here temporarily. */
305         *len = maxlen;
306         arg->u2.vp = len;
307
308         return io_set_plan(conn, IO_OUT, do_write_partial, next, next_arg);
309 }
310
311 static int do_connect(int fd, struct io_plan_arg *arg)
312 {
313         int err, ret;
314         socklen_t len = sizeof(err);
315
316         /* Has async connect finished? */
317         ret = getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
318         if (ret < 0)
319                 return -1;
320
321         if (err == 0) {
322                 return 1;
323         } else if (err == EINPROGRESS)
324                 return 0;
325
326         errno = err;
327         return -1;
328 }
329
330 struct io_plan *io_connect_(struct io_conn *conn, const struct addrinfo *addr,
331                             struct io_plan *(*next)(struct io_conn *, void *),
332                             void *next_arg)
333 {
334         int fd = io_conn_fd(conn);
335
336         /* We don't actually need the arg, but we need it polling. */
337         io_plan_arg(conn, IO_OUT);
338
339         /* Note that io_new_conn() will make fd O_NONBLOCK */
340
341         /* Immediate connect can happen. */
342         if (connect(fd, addr->ai_addr, addr->ai_addrlen) == 0)
343                 return set_always(conn, IO_OUT, next, next_arg);
344
345         if (errno != EINPROGRESS)
346                 return io_close(conn);
347
348         return io_set_plan(conn, IO_OUT, do_connect, next, next_arg);
349 }
350
351 static struct io_plan *io_wait_dir(struct io_conn *conn,
352                                    const void *wait,
353                                    enum io_direction dir,
354                                    struct io_plan *(*next)(struct io_conn *,
355                                                            void *),
356                                    void *next_arg)
357 {
358         struct io_plan_arg *arg = io_plan_arg(conn, dir);
359         arg->u1.const_vp = wait;
360
361         conn->plan[dir].status = IO_WAITING;
362
363         return io_set_plan(conn, dir, NULL, next, next_arg);
364 }
365
366 struct io_plan *io_wait_(struct io_conn *conn,
367                          const void *wait,
368                          struct io_plan *(*next)(struct io_conn *, void *),
369                          void *next_arg)
370 {
371         return io_wait_dir(conn, wait, IO_IN, next, next_arg);
372 }
373
374 struct io_plan *io_out_wait_(struct io_conn *conn,
375                              const void *wait,
376                              struct io_plan *(*next)(struct io_conn *, void *),
377                              void *next_arg)
378 {
379         return io_wait_dir(conn, wait, IO_OUT, next, next_arg);
380 }
381
382 void io_wake(const void *wait)
383 {
384         backend_wake(wait);
385 }
386
387 enum plan_result {
388         /* Destroyed, do not touch */
389         FREED,
390         /* Worked, call again. */
391         KEEP_GOING,
392         /* Failed with EAGAIN or did partial. */
393         EXHAUSTED,
394         /* No longer interested in read (or write) */
395         UNINTERESTED
396 };
397
398 static enum plan_result do_plan(struct io_conn *conn, struct io_plan *plan,
399                                 bool idle_on_epipe)
400 {
401         /* We shouldn't have polled for this event if this wasn't true! */
402         assert(plan->status == IO_POLLING_NOTSTARTED
403                || plan->status == IO_POLLING_STARTED);
404
405         switch (plan->io(conn->fd.fd, &plan->arg)) {
406         case -1:
407                 /* This is expected, as we call optimistically! */
408                 if (errno == EAGAIN)
409                         return EXHAUSTED;
410                 if (errno == EPIPE && idle_on_epipe) {
411                         plan->status = IO_UNSET;
412                         backend_new_plan(conn);
413                         return UNINTERESTED;
414                 }
415                 io_close(conn);
416                 return FREED;
417         case 0:
418                 plan->status = IO_POLLING_STARTED;
419                 /* If it started but didn't finish, don't call again. */
420                 return EXHAUSTED;
421         case 1:
422                 if (!next_plan(conn, plan))
423                         return FREED;
424                 if (plan->status == IO_POLLING_NOTSTARTED)
425                         return KEEP_GOING;
426                 return UNINTERESTED;
427         default:
428                 /* IO should only return -1, 0 or 1 */
429                 abort();
430         }
431 }
432
433 void io_ready(struct io_conn *conn, int pollflags)
434 {
435         enum plan_result res;
436
437         if (pollflags & POLLIN) {
438                 for (;;) {
439                         res = do_plan(conn, &conn->plan[IO_IN], false);
440                         switch (res) {
441                         case FREED:
442                                 return;
443                         case EXHAUSTED:
444                         case UNINTERESTED:
445                                 goto try_write;
446                         case KEEP_GOING:
447                                 continue;
448                         }
449                         abort();
450                 }
451         }
452
453 try_write:
454         if (pollflags & POLLOUT) {
455                 for (;;) {
456                         /* If we're writing to a closed pipe, we need to wait for
457                          * read to fail if we're duplex: we want to drain it! */
458                         res = do_plan(conn, &conn->plan[IO_OUT],
459                                       conn->plan[IO_IN].status == IO_POLLING_NOTSTARTED
460                                       || conn->plan[IO_IN].status == IO_POLLING_STARTED);
461                         switch (res) {
462                         case FREED:
463                         case EXHAUSTED:
464                         case UNINTERESTED:
465                                 return;
466                         case KEEP_GOING:
467                                 continue;
468                         }
469                         abort();
470                 }
471         }
472 }
473
474 void io_do_always(struct io_plan *plan)
475 {
476         struct io_conn *conn;
477
478         assert(plan->status == IO_ALWAYS);
479         conn = container_of(plan, struct io_conn, plan[plan->dir]);
480
481         next_plan(conn, plan);
482 }
483
484 void io_do_wakeup(struct io_conn *conn, enum io_direction dir)
485 {
486         struct io_plan *plan = &conn->plan[dir];
487
488         assert(plan->status == IO_WAITING);
489
490         set_always(conn, dir, plan->next, plan->next_arg);
491 }
492
493 /* Close the connection, we're done. */
494 struct io_plan *io_close(struct io_conn *conn)
495 {
496         tal_free(conn);
497         return &io_conn_freed;
498 }
499
500 struct io_plan *io_close_cb(struct io_conn *conn, void *next_arg)
501 {
502         return io_close(conn);
503 }
504
505 struct io_plan *io_close_taken_fd(struct io_conn *conn)
506 {
507         io_fd_block(conn->fd.fd, true);
508
509         cleanup_conn_without_close(conn);
510         return io_close(conn);
511 }
512
513 /* Exit the loop, returning this (non-NULL) arg. */
514 void io_break(const void *ret)
515 {
516         assert(ret);
517         io_loop_return = (void *)ret;
518 }
519
520 struct io_plan *io_never(struct io_conn *conn, void *unused)
521 {
522         return io_always(conn, io_never_called, NULL);
523 }
524
525 int io_conn_fd(const struct io_conn *conn)
526 {
527         return conn->fd.fd;
528 }
529
530 struct io_plan *io_duplex(struct io_conn *conn,
531                           struct io_plan *in_plan, struct io_plan *out_plan)
532 {
533         assert(conn == container_of(in_plan, struct io_conn, plan[IO_IN]));
534         /* in_plan must be conn->plan[IO_IN], out_plan must be [IO_OUT] */
535         assert(out_plan == in_plan + 1);
536         return in_plan;
537 }
538
539 struct io_plan *io_halfclose(struct io_conn *conn)
540 {
541         /* Both unset?  OK. */
542         if (conn->plan[IO_IN].status == IO_UNSET
543             && conn->plan[IO_OUT].status == IO_UNSET)
544                 return io_close(conn);
545
546         /* We leave this unset then. */
547         if (conn->plan[IO_IN].status == IO_UNSET)
548                 return &conn->plan[IO_IN];
549         else
550                 return &conn->plan[IO_OUT];
551 }
552
553 struct io_plan *io_set_plan(struct io_conn *conn, enum io_direction dir,
554                             int (*io)(int fd, struct io_plan_arg *arg),
555                             struct io_plan *(*next)(struct io_conn *, void *),
556                             void *next_arg)
557 {
558         struct io_plan *plan = &conn->plan[dir];
559
560         plan->io = io;
561         plan->next = next;
562         plan->next_arg = next_arg;
563         assert(next != NULL);
564
565         return plan;
566 }
567
568 bool io_plan_in_started(const struct io_conn *conn)
569 {
570         return conn->plan[IO_IN].status == IO_POLLING_STARTED;
571 }
572
573 bool io_plan_out_started(const struct io_conn *conn)
574 {
575         return conn->plan[IO_OUT].status == IO_POLLING_STARTED;
576 }
577
578 /* Despite being a TCP expert, I missed the full extent of this
579  * problem.  The legendary ZmnSCPxj implemented it (with the URL
580  * pointing to the explanation), and I imitate that here. */
581 struct io_plan *io_sock_shutdown(struct io_conn *conn)
582 {
583         if (shutdown(io_conn_fd(conn), SHUT_WR) != 0)
584                 return io_close(conn);
585
586         /* And leave unset .*/
587         return &conn->plan[IO_IN];
588 }
589
590 bool io_flush_sync(struct io_conn *conn)
591 {
592         struct io_plan *plan = &conn->plan[IO_OUT];
593         bool ok;
594
595         /* Not writing?  Nothing to do. */
596         if (plan->status != IO_POLLING_STARTED
597             && plan->status != IO_POLLING_NOTSTARTED)
598                 return true;
599
600         /* Synchronous please. */
601         io_fd_block(io_conn_fd(conn), true);
602
603 again:
604         switch (plan->io(conn->fd.fd, &plan->arg)) {
605         case -1:
606                 ok = false;
607                 break;
608         /* Incomplete, try again. */
609         case 0:
610                 plan->status = IO_POLLING_STARTED;
611                 goto again;
612         case 1:
613                 ok = true;
614                 /* In case they come back. */
615                 set_always(conn, IO_OUT, plan->next, plan->next_arg);
616                 break;
617         default:
618                 /* IO should only return -1, 0 or 1 */
619                 abort();
620         }
621
622         io_fd_block(io_conn_fd(conn), false);
623         return ok;
624 }
625
626 void io_set_extended_errors(bool state)
627 {
628         io_extended_errors = state;
629 }
630
631 bool io_get_extended_errors(void)
632 {
633         return io_extended_errors;
634 }