444579e9c46d7fb84d58eb75a65f047096a3f1f6
[srvx.git] / src / ioset.c
1 /* ioset.h - srvx event loop
2  * Copyright 2002-2004, 2006 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "ioset-impl.h"
22 #include "log.h"
23 #include "timeq.h"
24 #include "saxdb.h"
25 #include "conf.h"
26
27 #ifdef HAVE_FCNTL_H
28 #include <fcntl.h>
29 #endif
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
32 #endif
33
34 #define IS_EOL(CH) ((CH) == '\n')
35
36 extern int uplink_connect(void);
37 int clock_skew;
38 int do_write_dbs;
39 int do_reopen;
40 static struct io_engine *engine;
41 static struct io_fd *active_fd;
42
43 static void
44 ioq_init(struct ioq *ioq, int size) {
45     ioq->buf = malloc(size);
46     ioq->get = ioq->put = 0;
47     ioq->size = size;
48 }
49
50 static unsigned int
51 ioq_put_avail(const struct ioq *ioq) {
52     /* Subtract 1 from ioq->get to be sure we don't fill the buffer
53      * and make it look empty even when there's data in it. */
54     if (ioq->put < ioq->get)
55         return ioq->get - ioq->put - 1;
56     else if (ioq->get == 0)
57         return ioq->size - ioq->put - 1;
58     else
59         return ioq->size - ioq->put;
60 }
61
62 static unsigned int
63 ioq_get_avail(const struct ioq *ioq) {
64     return ((ioq->put < ioq->get) ? ioq->size : ioq->put) - ioq->get;
65 }
66
67 static unsigned int
68 ioq_used(const struct ioq *ioq) {
69     return ((ioq->put < ioq->get) ? ioq->size : 0) + ioq->put - ioq->get;
70 }
71
72 static unsigned int
73 ioq_grow(struct ioq *ioq) {
74     int new_size = ioq->size << 1;
75     char *new_buf = malloc(new_size);
76     int get_avail = ioq_get_avail(ioq);
77     memcpy(new_buf, ioq->buf + ioq->get, get_avail);
78     if (ioq->put < ioq->get)
79         memcpy(new_buf + get_avail, ioq->buf, ioq->put);
80     free(ioq->buf);
81     ioq->put = ioq_used(ioq);
82     ioq->get = 0;
83     ioq->buf = new_buf;
84     ioq->size = new_size;
85     return new_size - ioq->put;
86 }
87
88 extern struct io_engine io_engine_kqueue;
89 extern struct io_engine io_engine_epoll;
90 extern struct io_engine io_engine_win32;
91 extern struct io_engine io_engine_select;
92
93 void
94 ioset_init(void)
95 {
96     if (engine) /* someone beat us to it */
97         return;
98
99 #if WITH_IOSET_KQUEUE
100     if (!engine && io_engine_kqueue.init())
101         engine = &io_engine_kqueue;
102 #endif
103
104 #if WITH_IOSET_EPOLL
105     if (!engine && io_engine_epoll.init())
106         engine = &io_engine_epoll;
107 #endif
108
109 #if WITH_IOSET_WIN32
110     if (!engine && io_engine_win32.init())
111         engine = &io_engine_win32;
112 #endif
113
114     if (engine) {
115         /* we found one that works */
116     } else if (io_engine_select.init())
117         engine = &io_engine_select;
118     else
119         log_module(MAIN_LOG, LOG_FATAL, "No usable I/O engine found.");
120     log_module(MAIN_LOG, LOG_DEBUG, "Using %s I/O engine.", engine->name);
121 }
122
123 void
124 ioset_cleanup(void) {
125     engine->cleanup();
126 }
127
128 struct io_fd *
129 ioset_add(int fd) {
130     struct io_fd *res;
131     int flags;
132
133     if (fd < 0) {
134         log_module(MAIN_LOG, LOG_ERROR, "Somebody called ioset_add(%d) on a negative fd!", fd);
135         return 0;
136     }
137     if (!engine)
138         ioset_init();
139     res = calloc(1, sizeof(*res));
140     if (!res)
141         return 0;
142     res->fd = fd;
143     ioq_init(&res->send, 1024);
144     ioq_init(&res->recv, 1024);
145     flags = fcntl(fd, F_GETFL);
146     fcntl(fd, F_SETFL, flags|O_NONBLOCK);
147     flags = fcntl(fd, F_GETFD);
148     fcntl(fd, F_SETFD, flags|FD_CLOEXEC);
149     engine->add(res);
150     return res;
151 }
152
153 struct io_fd *ioset_listen(struct sockaddr *local, unsigned int sa_size, void *data, void (*accept_cb)(struct io_fd *listener, struct io_fd *new_connect))
154 {
155     struct io_fd *io_fd;
156     unsigned int opt;
157     int res;
158     int fd;
159
160     fd = socket(local ? local->sa_family : PF_INET, SOCK_STREAM, 0);
161     if (fd < 0) {
162         log_module(MAIN_LOG, LOG_ERROR, "Unable to create listening socket: %s", strerror(errno));
163         return NULL;
164     }
165
166     if (local && sa_size) {
167         res = bind(fd, local, sa_size);
168         if (res < 0) {
169             log_module(MAIN_LOG, LOG_ERROR, "Unable to bind listening socket %d: %s", fd, strerror(errno));
170             close(fd);
171             return NULL;
172         }
173
174         opt = 1;
175         res = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
176         if (res < 0) {
177             log_module(MAIN_LOG, LOG_WARNING, "Unable to mark listener address as re-usable: %s", strerror(errno));
178         }
179     }
180
181     res = listen(fd, 1);
182     if (res < 0) {
183         log_module(MAIN_LOG, LOG_ERROR, "Unable to listen on socket %d: %s", fd, strerror(errno));
184         close(fd);
185         return NULL;
186     }
187
188     io_fd = ioset_add(fd);
189     if (!io_fd) {
190         close(fd);
191         return NULL;
192     }
193     io_fd->state = IO_LISTENING;
194     io_fd->data = data;
195     io_fd->accept_cb = accept_cb;
196     engine->update(io_fd);
197     return io_fd;
198 }
199
200 struct io_fd *
201 ioset_connect(struct sockaddr *local, unsigned int sa_size, const char *peer, unsigned int port, int blocking, void *data, void (*connect_cb)(struct io_fd *fd, int error)) {
202     struct addrinfo hints;
203     struct addrinfo *ai;
204     struct io_fd *io_fd;
205     struct io_fd *old_active;
206     int res;
207     int fd;
208     char portnum[10];
209
210     memset(&hints, 0, sizeof(hints));
211     hints.ai_family = local ? local->sa_family : 0;
212     hints.ai_socktype = SOCK_STREAM;
213     snprintf(portnum, sizeof(portnum), "%u", port);
214     if (getaddrinfo(peer, portnum, &hints, &ai)) {
215         log_module(MAIN_LOG, LOG_ERROR, "getaddrinfo(%s, %s) failed.", peer, portnum);
216         return NULL;
217     }
218
219     if (local) {
220         if ((fd = socket(local->sa_family, SOCK_STREAM, 0)) < 0) {
221             log_module(MAIN_LOG, LOG_ERROR, "socket() for %s returned errno %d (%s)", peer, errno, strerror(errno));
222             freeaddrinfo(ai);
223             return NULL;
224         }
225         if (bind(fd, local, sa_size) < 0) {
226             log_module(MAIN_LOG, LOG_ERROR, "bind() of socket for %s (fd %d) returned errno %d (%s).  Will let operating system choose.", peer, fd, errno, strerror(errno));
227         }
228     } else {
229         if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
230             log_module(MAIN_LOG, LOG_ERROR, "socket() for %s returned errno %d (%s).", peer, errno, strerror(errno));
231             freeaddrinfo(ai);
232             return NULL;
233         }
234     }
235
236     if (blocking) {
237         res = connect(fd, ai->ai_addr, ai->ai_addrlen);
238         io_fd = ioset_add(fd);
239     } else {
240         io_fd = ioset_add(fd);
241         res = connect(fd, ai->ai_addr, ai->ai_addrlen);
242     }
243     freeaddrinfo(ai);
244     if (!io_fd) {
245         close(fd);
246         return NULL;
247     }
248     io_fd->state = IO_CONNECTING;
249     io_fd->data = data;
250     io_fd->connect_cb = connect_cb;
251     if (res < 0) {
252         switch (errno) {
253         case EINPROGRESS: /* only if !blocking */
254             engine->update(io_fd);
255             return io_fd;
256         default:
257             log_module(MAIN_LOG, LOG_ERROR, "connect(%s:%d) (fd %d) returned errno %d (%s).", peer, port, io_fd->fd, errno, strerror(errno));
258             /* then fall through */
259         case EHOSTUNREACH:
260         case ECONNREFUSED:
261             ioset_close(io_fd, 1);
262             engine->update(io_fd);
263             return NULL;
264         }
265     }
266     io_fd->state = IO_CONNECTED;
267     old_active = active_fd;
268     if (connect_cb)
269         connect_cb(io_fd, ((res < 0) ? errno : 0));
270     if (active_fd)
271         engine->update(io_fd);
272     if (old_active != io_fd)
273         active_fd = old_active;
274     return io_fd;
275 }
276
277 void ioset_update(struct io_fd *fd) {
278     engine->update(fd);
279 }
280
281 static void
282 ioset_try_write(struct io_fd *fd) {
283     int res;
284     unsigned int req;
285
286     req = ioq_get_avail(&fd->send);
287     res = write(fd->fd, fd->send.buf+fd->send.get, req);
288     if (res < 0) {
289         switch (errno) {
290         case EAGAIN:
291             break;
292         default:
293             log_module(MAIN_LOG, LOG_ERROR, "write() on fd %d error %d: %s", fd->fd, errno, strerror(errno));
294         }
295     } else {
296         fd->send.get += res;
297         if (fd->send.get == fd->send.size)
298             fd->send.get = 0;
299         engine->update(fd);
300     }
301 }
302
303 void
304 ioset_close(struct io_fd *fdp, int os_close) {
305     if (!fdp)
306         return;
307     if (active_fd == fdp)
308         active_fd = NULL;
309     if (fdp->destroy_cb)
310         fdp->destroy_cb(fdp);
311     if (fdp->send.get != fdp->send.put && (os_close & 2)) {
312         int flags;
313
314         flags = fcntl(fdp->fd, F_GETFL);
315         fcntl(fdp->fd, F_SETFL, flags&~O_NONBLOCK);
316         ioset_try_write(fdp);
317         /* it may need to send the beginning of the buffer now.. */
318         if (fdp->send.get != fdp->send.put)
319             ioset_try_write(fdp);
320     }
321     free(fdp->send.buf);
322     free(fdp->recv.buf);
323     if (os_close & 1)
324         close(fdp->fd);
325     engine->remove(fdp);
326     free(fdp);
327 }
328
329 static void
330 ioset_accept(struct io_fd *listener)
331 {
332     struct io_fd *old_active;
333     struct io_fd *new_fd;
334     int fd;
335
336     fd = accept(listener->fd, NULL, 0);
337     if (fd < 0) {
338         log_module(MAIN_LOG, LOG_ERROR, "Unable to accept new connection on listener %d: %s", listener->fd, strerror(errno));
339         return;
340     }
341
342     new_fd = ioset_add(fd);
343     new_fd->state = IO_CONNECTED;
344     old_active = active_fd;
345     active_fd = new_fd;
346     listener->accept_cb(listener, new_fd);
347     assert(active_fd == NULL || active_fd == new_fd);
348     if (active_fd == new_fd) {
349         if (new_fd->send.get != new_fd->send.put)
350             ioset_try_write(new_fd);
351         else
352             engine->update(new_fd);
353     }
354     active_fd = old_active;
355 }
356
357 static int
358 ioset_find_line_length(struct io_fd *fd) {
359     unsigned int pos, max, len;
360     len = 0;
361     max = (fd->recv.put < fd->recv.get) ? fd->recv.size : fd->recv.put;
362     for (pos = fd->recv.get; pos < max; ++pos, ++len)
363         if (IS_EOL(fd->recv.buf[pos]))
364             return fd->line_len = len + 1;
365     if (fd->recv.put < fd->recv.get)
366         for (pos = 0; pos < fd->recv.put; ++pos, ++len)
367             if (IS_EOL(fd->recv.buf[pos]))
368                 return fd->line_len = len + 1;
369     return fd->line_len = 0;
370 }
371
372 static void
373 ioset_buffered_read(struct io_fd *fd) {
374     int put_avail, nbr, fdnum;
375
376     if (!(put_avail = ioq_put_avail(&fd->recv)))
377         put_avail = ioq_grow(&fd->recv);
378     nbr = read(fd->fd, fd->recv.buf + fd->recv.put, put_avail);
379     if (nbr < 0) {
380         switch (errno) {
381         case EAGAIN:
382             break;
383         default:
384             log_module(MAIN_LOG, LOG_ERROR, "Unexpected read() error %d on fd %d: %s", errno, fd->fd, strerror(errno));
385             /* Just flag it as EOF and call readable_cb() to notify the fd's owner. */
386             fd->state = IO_CLOSED;
387             fd->readable_cb(fd);
388             if (active_fd == fd)
389                 engine->update(fd);
390         }
391     } else if (nbr == 0) {
392         fd->state = IO_CLOSED;
393         fd->readable_cb(fd);
394         if (active_fd == fd)
395             engine->update(fd);
396     } else {
397         if (fd->line_len == 0) {
398             unsigned int pos;
399             for (pos = fd->recv.put; pos < fd->recv.put + nbr; ++pos) {
400                 if (IS_EOL(fd->recv.buf[pos])) {
401                     if (fd->recv.put < fd->recv.get)
402                         fd->line_len = fd->recv.size + pos + 1 - fd->recv.get;
403                     else
404                         fd->line_len = pos + 1 - fd->recv.get;
405                     break;
406                 }
407             }
408         }
409         fd->recv.put += nbr;
410         if (fd->recv.put == fd->recv.size)
411             fd->recv.put = 0;
412         fdnum = fd->fd;
413         while (fd->line_len > 0) {
414             struct io_fd *old_active;
415             int died = 0;
416
417             old_active = active_fd;
418             active_fd = fd;
419             fd->readable_cb(fd);
420             if (active_fd)
421                 ioset_find_line_length(fd);
422             else
423                 died = 1;
424             if (old_active != fd)
425                 active_fd = old_active;
426             if (died)
427                 break;
428         }
429     }
430 }
431
432 int
433 ioset_line_read(struct io_fd *fd, char *dest, int max) {
434     int avail, done;
435     if ((fd->state == IO_CLOSED) && (!ioq_get_avail(&fd->recv) ||  (fd->line_len < 0)))
436         return 0;
437     if (fd->line_len < 0)
438         return -1;
439     if (fd->line_len < max)
440         max = fd->line_len;
441     avail = ioq_get_avail(&fd->recv);
442     if (max > avail) {
443         memcpy(dest, fd->recv.buf + fd->recv.get, avail);
444         fd->recv.get += avail;
445         assert(fd->recv.get == fd->recv.size);
446         fd->recv.get = 0;
447         done = avail;
448     } else {
449         done = 0;
450     }
451     memcpy(dest + done, fd->recv.buf + fd->recv.get, max - done);
452     fd->recv.get += max - done;
453     if (fd->recv.get == fd->recv.size)
454         fd->recv.get = 0;
455     dest[max] = 0;
456     ioset_find_line_length(fd);
457     return max;
458 }
459
460 void
461 ioset_events(struct io_fd *fd, int readable, int writable)
462 {
463     if (!fd || (!readable && !writable))
464         return;
465     active_fd = fd;
466     switch (fd->state) {
467     case IO_CLOSED:
468         break;
469     case IO_LISTENING:
470         if (active_fd && readable)
471             ioset_accept(fd);
472         break;
473     case IO_CONNECTING:
474         assert(active_fd == NULL || active_fd == fd);
475         if (active_fd && readable) {
476             socklen_t arglen;
477             int rc;
478             arglen = sizeof(rc);
479             if (getsockopt(fd->fd, SOL_SOCKET, SO_ERROR, &rc, &arglen) < 0)
480                 rc = errno;
481             fd->state = IO_CLOSED;
482             if (fd->connect_cb)
483                 fd->connect_cb(fd, rc);
484         } else if (active_fd && writable) {
485             fd->state = IO_CONNECTED;
486             if (fd->connect_cb)
487                 fd->connect_cb(fd, 0);
488         }
489         if (active_fd != fd)
490             break;
491         engine->update(fd);
492         /* and fall through */
493     case IO_CONNECTED:
494         assert(active_fd == NULL || active_fd == fd);
495         if (active_fd && readable) {
496             if (fd->line_reads)
497                 ioset_buffered_read(fd);
498             else
499                 fd->readable_cb(fd);
500         }
501
502         assert(active_fd == NULL || active_fd == fd);
503         if (active_fd && writable)
504             ioset_try_write(fd);
505         break;
506     }
507 }
508
509 void
510 ioset_run(void) {
511     extern struct io_fd *socket_io_fd;
512     struct timeval timeout;
513     time_t wakey;
514
515     while (!quit_services) {
516         while (!socket_io_fd)
517             uplink_connect();
518
519         /* How long to sleep? (fill in select_timeout) */
520         wakey = timeq_next();
521         if ((wakey - now) < 0)
522             timeout.tv_sec = 0;
523         else
524             timeout.tv_sec = wakey - now;
525         timeout.tv_usec = 0;
526
527         if (engine->loop(&timeout))
528             continue;
529
530         /* Call any timeq events we need to call. */
531         timeq_run();
532         if (do_write_dbs) {
533             saxdb_write_all();
534             do_write_dbs = 0;
535         }
536         if (do_reopen) {
537             extern char *services_config;
538             conf_read(services_config);
539             do_reopen = 0;
540         }
541     }
542 }
543
544 void
545 ioset_write(struct io_fd *fd, const char *buf, unsigned int nbw) {
546     unsigned int avail;
547     while (ioq_used(&fd->send) + nbw >= fd->send.size)
548         ioq_grow(&fd->send);
549     avail = ioq_put_avail(&fd->send);
550     if (nbw > avail) {
551         memcpy(fd->send.buf + fd->send.put, buf, avail);
552         buf += avail;
553         nbw -= avail;
554         fd->send.put = 0;
555     }
556     memcpy(fd->send.buf + fd->send.put, buf, nbw);
557     fd->send.put += nbw;
558     if (fd->send.put == fd->send.size)
559         fd->send.put = 0;
560     engine->update(fd);
561 }
562
563 int
564 ioset_printf(struct io_fd *fd, const char *fmt, ...) {
565     char tmpbuf[MAXLEN];
566     va_list ap;
567     int res;
568
569     va_start(ap, fmt);
570     res = vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
571     va_end(ap);
572     if (res > 0 && (size_t)res <= sizeof(tmpbuf))
573         ioset_write(fd, tmpbuf, res);
574     return res;
575 }
576
577 void
578 ioset_set_time(unsigned long new_now) {
579     clock_skew = new_now - time(NULL);
580     now = new_now;
581 }