a66af6f8b8fbb8badf2db3e20f71fbf4c98693d2
[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     assert(engine == NULL);
97
98 #if WITH_IOSET_KQUEUE
99     if (!engine && io_engine_kqueue.init())
100         engine = &io_engine_kqueue;
101 #endif
102
103 #if WITH_IOSET_EPOLL
104     if (!engine && io_engine_epoll.init())
105         engine = &io_engine_epoll;
106 #endif
107
108 #if WITH_IOSET_WIN32
109     if (!engine && io_engine_win32.init())
110         engine = &io_engine_win32;
111 #endif
112
113     if (engine) {
114         /* we found one that works */
115     } else if (io_engine_select.init())
116         engine = &io_engine_select;
117     else
118         log_module(MAIN_LOG, LOG_FATAL, "No usable I/O engine found.");
119     log_module(MAIN_LOG, LOG_DEBUG, "Using %s I/O engine.", engine->name);
120 }
121
122 void
123 ioset_cleanup(void) {
124     engine->cleanup();
125 }
126
127 struct io_fd *
128 ioset_add(int fd) {
129     struct io_fd *res;
130     int flags;
131
132     if (fd < 0) {
133         log_module(MAIN_LOG, LOG_ERROR, "Somebody called ioset_add(%d) on a negative fd!", fd);
134         return 0;
135     }
136     res = calloc(1, sizeof(*res));
137     if (!res)
138         return 0;
139     res->fd = fd;
140     ioq_init(&res->send, 1024);
141     ioq_init(&res->recv, 1024);
142     engine->add(res);
143     flags = fcntl(fd, F_GETFL);
144     fcntl(fd, F_SETFL, flags|O_NONBLOCK);
145     return res;
146 }
147
148 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))
149 {
150     struct io_fd *io_fd;
151     unsigned int opt;
152     int res;
153     int fd;
154
155     fd = socket(local ? local->sa_family : PF_INET, SOCK_STREAM, 0);
156     if (fd < 0) {
157         log_module(MAIN_LOG, LOG_ERROR, "Unable to create listening socket: %s", strerror(errno));
158         return NULL;
159     }
160
161     if (local && sa_size) {
162         res = bind(fd, local, sa_size);
163         if (res < 0) {
164             log_module(MAIN_LOG, LOG_ERROR, "Unable to bind listening socket %d: %s", fd, strerror(errno));
165             close(fd);
166             return NULL;
167         }
168
169         opt = 1;
170         res = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
171         if (res < 0) {
172             log_module(MAIN_LOG, LOG_WARNING, "Unable to mark listener address as re-usable: %s", strerror(errno));
173         }
174     }
175
176     res = listen(fd, 1);
177     if (res < 0) {
178         log_module(MAIN_LOG, LOG_ERROR, "Unable to listen on socket %d: %s", fd, strerror(errno));
179         close(fd);
180         return NULL;
181     }
182
183     io_fd = ioset_add(fd);
184     if (!io_fd) {
185         close(fd);
186         return NULL;
187     }
188     io_fd->state = IO_LISTENING;
189     io_fd->data = data;
190     io_fd->accept_cb = accept_cb;
191     engine->update(io_fd);
192     return io_fd;
193 }
194
195 struct io_fd *
196 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)) {
197     struct addrinfo hints;
198     struct addrinfo *ai;
199     struct io_fd *io_fd;
200     struct io_fd *old_active;
201     int res;
202     int fd;
203     char portnum[10];
204
205     memset(&hints, 0, sizeof(hints));
206     hints.ai_family = local ? local->sa_family : 0;
207     hints.ai_socktype = SOCK_STREAM;
208     snprintf(portnum, sizeof(portnum), "%u", port);
209     if (getaddrinfo(peer, portnum, &hints, &ai)) {
210         log_module(MAIN_LOG, LOG_ERROR, "getaddrinfo(%s, %s) failed.", peer, portnum);
211         return NULL;
212     }
213
214     if (local) {
215         if ((fd = socket(local->sa_family, SOCK_STREAM, 0)) < 0) {
216             log_module(MAIN_LOG, LOG_ERROR, "socket() for %s returned errno %d (%s)", peer, errno, strerror(errno));
217             freeaddrinfo(ai);
218             return NULL;
219         }
220         if (bind(fd, local, sa_size) < 0) {
221             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));
222         }
223     } else {
224         if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
225             log_module(MAIN_LOG, LOG_ERROR, "socket() for %s returned errno %d (%s).", peer, errno, strerror(errno));
226             freeaddrinfo(ai);
227             return NULL;
228         }
229     }
230
231     if (blocking) {
232         res = connect(fd, ai->ai_addr, ai->ai_addrlen);
233         io_fd = ioset_add(fd);
234     } else {
235         io_fd = ioset_add(fd);
236         res = connect(fd, ai->ai_addr, ai->ai_addrlen);
237     }
238     freeaddrinfo(ai);
239     if (!io_fd) {
240         close(fd);
241         return NULL;
242     }
243     io_fd->state = IO_CONNECTING;
244     io_fd->data = data;
245     io_fd->connect_cb = connect_cb;
246     if (res < 0) {
247         switch (errno) {
248         case EINPROGRESS: /* only if !blocking */
249             engine->update(io_fd);
250             return io_fd;
251         default:
252             log_module(MAIN_LOG, LOG_ERROR, "connect(%s:%d) (fd %d) returned errno %d (%s).", peer, port, io_fd->fd, errno, strerror(errno));
253             /* then fall through */
254         case EHOSTUNREACH:
255         case ECONNREFUSED:
256             ioset_close(io_fd, 1);
257             engine->update(io_fd);
258             return NULL;
259         }
260     }
261     io_fd->state = IO_CONNECTED;
262     old_active = active_fd;
263     if (connect_cb)
264         connect_cb(io_fd, ((res < 0) ? errno : 0));
265     if (active_fd)
266         engine->update(io_fd);
267     if (old_active != io_fd)
268         active_fd = old_active;
269     return io_fd;
270 }
271
272 static void
273 ioset_try_write(struct io_fd *fd) {
274     int res;
275     unsigned int req = ioq_get_avail(&fd->send);
276     res = write(fd->fd, fd->send.buf+fd->send.get, req);
277     if (res < 0) {
278         switch (errno) {
279         case EAGAIN:
280             break;
281         default:
282             log_module(MAIN_LOG, LOG_ERROR, "write() on fd %d error %d: %s", fd->fd, errno, strerror(errno));
283         }
284     } else {
285         fd->send.get += res;
286         if (fd->send.get == fd->send.size)
287             fd->send.get = 0;
288         engine->update(fd);
289     }
290 }
291
292 void
293 ioset_close(struct io_fd *fdp, int os_close) {
294     if (!fdp)
295         return;
296     if (active_fd == fdp)
297         active_fd = NULL;
298     if (fdp->destroy_cb)
299         fdp->destroy_cb(fdp);
300     if (fdp->send.get != fdp->send.put) {
301         int flags;
302
303         flags = fcntl(fdp->fd, F_GETFL);
304         fcntl(fdp->fd, F_SETFL, flags&~O_NONBLOCK);
305         ioset_try_write(fdp);
306         /* it may need to send the beginning of the buffer now.. */
307         if (fdp->send.get != fdp->send.put)
308             ioset_try_write(fdp);
309     }
310     free(fdp->send.buf);
311     free(fdp->recv.buf);
312     if (os_close)
313         close(fdp->fd);
314     engine->remove(fdp);
315     free(fdp);
316 }
317
318 static void
319 ioset_accept(struct io_fd *listener)
320 {
321     struct io_fd *old_active;
322     struct io_fd *new_fd;
323     int fd;
324
325     fd = accept(listener->fd, NULL, 0);
326     if (fd < 0) {
327         log_module(MAIN_LOG, LOG_ERROR, "Unable to accept new connection on listener %d: %s", listener->fd, strerror(errno));
328         return;
329     }
330
331     new_fd = ioset_add(fd);
332     new_fd->state = IO_CONNECTED;
333     old_active = active_fd;
334     active_fd = new_fd;
335     listener->accept_cb(listener, new_fd);
336     assert(active_fd == NULL || active_fd == new_fd);
337     if (active_fd == new_fd) {
338         if (new_fd->send.get != new_fd->send.put)
339             ioset_try_write(new_fd);
340         else
341             engine->update(new_fd);
342     }
343     active_fd = old_active;
344 }
345
346 static int
347 ioset_find_line_length(struct io_fd *fd) {
348     unsigned int pos, max, len;
349     len = 0;
350     max = (fd->recv.put < fd->recv.get) ? fd->recv.size : fd->recv.put;
351     for (pos = fd->recv.get; pos < max; ++pos, ++len)
352         if (IS_EOL(fd->recv.buf[pos]))
353             return fd->line_len = len + 1;
354     if (fd->recv.put < fd->recv.get)
355         for (pos = 0; pos < fd->recv.put; ++pos, ++len)
356             if (IS_EOL(fd->recv.buf[pos]))
357                 return fd->line_len = len + 1;
358     return fd->line_len = 0;
359 }
360
361 static void
362 ioset_buffered_read(struct io_fd *fd) {
363     int put_avail, nbr, fdnum;
364
365     if (!(put_avail = ioq_put_avail(&fd->recv)))
366         put_avail = ioq_grow(&fd->recv);
367     nbr = read(fd->fd, fd->recv.buf + fd->recv.put, put_avail);
368     if (nbr < 0) {
369         switch (errno) {
370         case EAGAIN:
371             break;
372         default:
373             log_module(MAIN_LOG, LOG_ERROR, "Unexpected read() error %d on fd %d: %s", errno, fd->fd, strerror(errno));
374             /* Just flag it as EOF and call readable_cb() to notify the fd's owner. */
375             fd->state = IO_CLOSED;
376             fd->readable_cb(fd);
377             if (active_fd == fd)
378                 engine->update(fd);
379         }
380     } else if (nbr == 0) {
381         fd->state = IO_CLOSED;
382         fd->readable_cb(fd);
383         if (active_fd == fd)
384             engine->update(fd);
385     } else {
386         if (fd->line_len == 0) {
387             unsigned int pos;
388             for (pos = fd->recv.put; pos < fd->recv.put + nbr; ++pos) {
389                 if (IS_EOL(fd->recv.buf[pos])) {
390                     if (fd->recv.put < fd->recv.get)
391                         fd->line_len = fd->recv.size + pos + 1 - fd->recv.get;
392                     else
393                         fd->line_len = pos + 1 - fd->recv.get;
394                     break;
395                 }
396             }
397         }
398         fd->recv.put += nbr;
399         if (fd->recv.put == fd->recv.size)
400             fd->recv.put = 0;
401         fdnum = fd->fd;
402         while (fd->wants_reads && (fd->line_len > 0)) {
403             struct io_fd *old_active;
404             int died = 0;
405
406             old_active = active_fd;
407             active_fd = fd;
408             fd->readable_cb(fd);
409             if (active_fd)
410                 ioset_find_line_length(fd);
411             else
412                 died = 1;
413             if (old_active != fd)
414                 active_fd = old_active;
415             if (died)
416                 break;
417         }
418     }
419 }
420
421 int
422 ioset_line_read(struct io_fd *fd, char *dest, int max) {
423     int avail, done;
424     if ((fd->state == IO_CLOSED) && (!ioq_get_avail(&fd->recv) ||  (fd->line_len < 0)))
425         return 0;
426     if (fd->line_len < 0)
427         return -1;
428     if (fd->line_len < max)
429         max = fd->line_len;
430     avail = ioq_get_avail(&fd->recv);
431     if (max > avail) {
432         memcpy(dest, fd->recv.buf + fd->recv.get, avail);
433         fd->recv.get += avail;
434         assert(fd->recv.get == fd->recv.size);
435         fd->recv.get = 0;
436         done = avail;
437     } else {
438         done = 0;
439     }
440     memcpy(dest + done, fd->recv.buf + fd->recv.get, max - done);
441     fd->recv.get += max - done;
442     if (fd->recv.get == fd->recv.size)
443         fd->recv.get = 0;
444     dest[max] = 0;
445     ioset_find_line_length(fd);
446     return max;
447 }
448
449 void
450 ioset_events(struct io_fd *fd, int readable, int writable)
451 {
452     if (!fd || (!readable && !writable))
453         return;
454     active_fd = fd;
455     switch (fd->state) {
456     case IO_CLOSED:
457         break;
458     case IO_LISTENING:
459         if (active_fd && readable)
460             ioset_accept(fd);
461         break;
462     case IO_CONNECTING:
463         assert(active_fd == NULL || active_fd == fd);
464         if (active_fd && readable) {
465             socklen_t arglen;
466             int rc;
467             arglen = sizeof(rc);
468             if (getsockopt(fd->fd, SOL_SOCKET, SO_ERROR, &rc, &arglen) < 0)
469                 rc = errno;
470             fd->state = IO_CLOSED;
471             if (fd->connect_cb)
472                 fd->connect_cb(fd, rc);
473         } else if (active_fd && writable) {
474             fd->state = IO_CONNECTED;
475             if (fd->connect_cb)
476                 fd->connect_cb(fd, 0);
477         }
478         if (active_fd != fd)
479             break;
480         engine->update(fd);
481         /* and fall through */
482     case IO_CONNECTED:
483         assert(active_fd == NULL || active_fd == fd);
484         if (active_fd && readable) {
485             if (fd->line_reads)
486                 ioset_buffered_read(fd);
487             else
488                 fd->readable_cb(fd);
489         }
490
491         assert(active_fd == NULL || active_fd == fd);
492         if (active_fd && writable)
493             ioset_try_write(fd);
494         break;
495     }
496 }
497
498 void
499 ioset_run(void) {
500     extern struct io_fd *socket_io_fd;
501     struct timeval timeout;
502     time_t wakey;
503
504     while (!quit_services) {
505         while (!socket_io_fd)
506             uplink_connect();
507
508         /* How long to sleep? (fill in select_timeout) */
509         wakey = timeq_next();
510         if ((wakey - now) < 0)
511             timeout.tv_sec = 0;
512         else
513             timeout.tv_sec = wakey - now;
514         timeout.tv_usec = 0;
515
516         if (engine->loop(&timeout))
517             continue;
518
519         /* Call any timeq events we need to call. */
520         timeq_run();
521         if (do_write_dbs) {
522             saxdb_write_all();
523             do_write_dbs = 0;
524         }
525         if (do_reopen) {
526             extern char *services_config;
527             conf_read(services_config);
528             do_reopen = 0;
529         }
530     }
531 }
532
533 void
534 ioset_write(struct io_fd *fd, const char *buf, unsigned int nbw) {
535     unsigned int avail;
536     while (ioq_used(&fd->send) + nbw >= fd->send.size)
537         ioq_grow(&fd->send);
538     avail = ioq_put_avail(&fd->send);
539     if (nbw > avail) {
540         memcpy(fd->send.buf + fd->send.put, buf, avail);
541         buf += avail;
542         nbw -= avail;
543         fd->send.put = 0;
544     }
545     memcpy(fd->send.buf + fd->send.put, buf, nbw);
546     fd->send.put += nbw;
547     if (fd->send.put == fd->send.size)
548         fd->send.put = 0;
549     engine->update(fd);
550 }
551
552 int
553 ioset_printf(struct io_fd *fd, const char *fmt, ...) {
554     char tmpbuf[MAXLEN];
555     va_list ap;
556     int res;
557
558     va_start(ap, fmt);
559     res = vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
560     va_end(ap);
561     if (res > 0 && (size_t)res <= sizeof(tmpbuf))
562         ioset_write(fd, tmpbuf, res);
563     return res;
564 }
565
566 void
567 ioset_set_time(unsigned long new_now) {
568     clock_skew = new_now - time(NULL);
569     now = new_now;
570 }