added gnutls backend and moved backend code into new files
[ircu2.10.12-pk.git] / ircd / engine_devpoll.c
1 /*
2  * IRC - Internet Relay Chat, ircd/engine_devpoll.c
3  * Copyright (C) 2001 Kevin L. Mitchell <klmitch@mit.edu>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 1, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /** @file
20  * @brief Solaris /dev/poll event engine.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "ircd_events.h"
26
27 #include "ircd.h"
28 #include "ircd_alloc.h"
29 #include "ircd_features.h"
30 #include "ircd_log.h"
31 #include "s_debug.h"
32
33 /* #include <assert.h> -- Now using assert in ircd_log.h */
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <sys/devpoll.h>
37 #include <sys/poll.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42
43 #define DEVPOLL_ERROR_THRESHOLD 20      /**< after 20 devpoll errors, restart */
44 #define ERROR_EXPIRE_TIME       3600    /**< expire errors after an hour */
45
46 /* Figure out what bits to set for read */
47 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
48 #  define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
49 #elif defined(POLLIN) && defined(POLLRDNORM)
50 #  define POLLREADFLAGS (POLLIN|POLLRDNORM)
51 #elif defined(POLLIN)
52 #  define POLLREADFLAGS POLLIN
53 #elif defined(POLLRDNORM)
54 #  define POLLREADFLAGS POLLRDNORM
55 #endif
56
57 /* Figure out what bits to set for write */
58 #if defined(POLLOUT) && defined(POLLWRNORM)
59 #  define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
60 #elif defined(POLLOUT)
61 #  define POLLWRITEFLAGS POLLOUT
62 #elif defined(POLLWRNORM)
63 #  define POLLWRITEFLAGS POLLWRNORM
64 #endif
65
66 /** Array of active Socket structures, indexed by file descriptor. */
67 static struct Socket** sockList;
68 /** Maximum file descriptor supported, plus one. */
69 static int devpoll_max;
70 /** File descriptor for /dev/poll device. */
71 static int devpoll_fd;
72
73 /** Number of recent errors from /dev/poll. */
74 static int errors = 0;
75 /** Periodic timer to forget errors. */
76 static struct Timer clear_error;
77 /** Array of currently polled file descriptors. */
78 static struct pollfd *polls;
79 /** Number of ::polls elements that have been populated. */
80 static int polls_used;
81
82 /** Decrement the error count (once per hour).
83  * @param[in] ev Expired timer event (ignored).
84  */
85 static void
86 error_clear(struct Event* ev)
87 {
88   if (!--errors) /* remove timer when error count reaches 0 */
89     timer_del(ev_timer(ev));
90 }
91
92 /** Initialize the /dev/poll engine.
93  * @param[in] max_sockets Maximum number of file descriptors to support.
94  * @return Non-zero on success, or zero on failure.
95  */
96 static int
97 engine_init(int max_sockets)
98 {
99   int i;
100
101   if ((devpoll_fd = open("/dev/poll", O_RDWR)) < 0) {
102     log_write(LS_SYSTEM, L_WARNING, 0,
103               "/dev/poll engine cannot open device: %m");
104     return 0; /* engine cannot be initialized; defer */
105   }
106
107   /* allocate necessary memory */
108   sockList = (struct Socket**) MyMalloc(sizeof(struct Socket*) * max_sockets);
109
110   /* initialize the data */
111   for (i = 0; i < max_sockets; i++)
112     sockList[i] = 0;
113
114   devpoll_max = max_sockets; /* number of sockets allocated */
115
116   return 1;
117 }
118
119 /** Figure out what events go with a given state.
120  * @param[in] state %Socket state to consider.
121  * @param[in] events User-specified preferred event set.
122  * @return Actual set of preferred events.
123  */
124 static unsigned int
125 state_to_events(enum SocketState state, unsigned int events)
126 {
127   switch (state) {
128   case SS_CONNECTING: /* connecting socket */
129     return SOCK_EVENT_WRITABLE;
130     break;
131
132   case SS_LISTENING: /* listening socket */
133   case SS_NOTSOCK: /* our signal socket */
134     return SOCK_EVENT_READABLE;
135     break;
136
137   case SS_CONNECTED: case SS_DATAGRAM: case SS_CONNECTDG:
138     return events; /* ordinary socket */
139     break;
140   }
141
142   /*NOTREACHED*/
143   return 0;
144 }
145
146 /** Set the desired events for a socket.
147  * @param[in,out] sock Socket to operate on.
148  * @param[in] events User-specified preferred event set.
149  */
150 static void
151 set_events(struct Socket* sock, unsigned int events)
152 {
153   struct pollfd pfd;
154
155   pfd.fd = s_fd(sock);
156
157   if (s_ed_int(sock)) { /* is one in /dev/poll already? */
158     pfd.events = POLLREMOVE; /* First, remove old pollfd */
159
160     Debug((DEBUG_ENGINE, "devpoll: Removing old entry for socket %d [%p]",
161            s_fd(sock), sock));
162
163     if (write(devpoll_fd, &pfd, sizeof(pfd)) != sizeof(pfd)) {
164       event_generate(ET_ERROR, sock, errno); /* report error */
165       return;
166     }
167
168     s_ed_int(sock) = 0; /* mark that it's gone */
169   }
170
171   if (!(events & SOCK_EVENT_MASK)) /* no events, so stop here */
172     return;
173
174   pfd.events = 0; /* Now, set up new pollfd... */
175   if (events & SOCK_EVENT_READABLE)
176     pfd.events |= POLLREADFLAGS; /* look for readable conditions */
177   if (events & SOCK_EVENT_WRITABLE)
178     pfd.events |= POLLWRITEFLAGS; /* look for writable conditions */
179
180   Debug((DEBUG_ENGINE, "devpoll: Registering interest on %d [%p] (state %s, "
181          "mask [%s])", s_fd(sock), sock, state_to_name(s_state(sock)),
182          sock_flags(s_events(sock))));
183
184   if (write(devpoll_fd, &pfd, sizeof(pfd)) != sizeof(pfd)) {
185     event_generate(ET_ERROR, sock, errno); /* report error */
186     return;
187   }
188
189   s_ed_int(sock) = 1; /* mark that we've added a pollfd */
190 }
191
192 /** Add a socket to the event engine.
193  * @param[in] sock Socket to add to engine.
194  * @return Non-zero on success, or zero on error.
195  */
196 static int
197 engine_add(struct Socket* sock)
198 {
199   assert(0 != sock);
200   assert(0 == sockList[s_fd(sock)]);
201
202   /* bounds-check... */
203   if (s_fd(sock) >= devpoll_max) {
204     log_write(LS_SYSTEM, L_ERROR, 0,
205               "Attempt to add socket %d (> %d) to event engine", s_fd(sock),
206               devpoll_max);
207     return 0;
208   }
209
210   sockList[s_fd(sock)] = sock; /* add to list */
211
212   Debug((DEBUG_ENGINE, "devpoll: Adding socket %d [%p], state %s, to engine",
213          s_fd(sock), sock, state_to_name(s_state(sock))));
214
215   /* set the correct events */
216   set_events(sock, state_to_events(s_state(sock), s_events(sock)));
217
218   return 1; /* success */
219 }
220
221 /** Handle state transition for a socket.
222  * @param[in] sock Socket changing state.
223  * @param[in] new_state New state for socket.
224  */
225 static void
226 engine_state(struct Socket* sock, enum SocketState new_state)
227 {
228   assert(0 != sock);
229   assert(sock == sockList[s_fd(sock)]);
230
231   Debug((DEBUG_ENGINE, "devpoll: Changing state for socket %p to %s", sock,
232          state_to_name(new_state)));
233
234   /* set the correct events */
235   set_events(sock, state_to_events(new_state, s_events(sock)));
236 }
237
238 /** Handle change to preferred socket events.
239  * @param[in] sock Socket getting new interest list.
240  * @param[in] new_events New set of interesting events for socket.
241  */
242 static void
243 engine_events(struct Socket* sock, unsigned int new_events)
244 {
245   assert(0 != sock);
246   assert(sock == sockList[s_fd(sock)]);
247
248   Debug((DEBUG_ENGINE, "devpoll: Changing event mask for socket %p to [%s]",
249          sock, sock_flags(new_events)));
250
251   /* set the correct events */
252   set_events(sock, state_to_events(s_state(sock), new_events));
253 }
254
255 /** Remove a socket from the event engine.
256  * @param[in] sock Socket being destroyed.
257  */
258 static void
259 engine_delete(struct Socket* sock)
260 {
261   int ii;
262
263   assert(0 != sock);
264   assert(sock == sockList[s_fd(sock)]);
265
266   Debug((DEBUG_ENGINE, "devpoll: Deleting socket %d [%p], state %s",
267          s_fd(sock), sock, state_to_name(s_state(sock))));
268
269   set_events(sock, 0); /* get rid of the socket */
270
271   sockList[s_fd(sock)] = 0; /* zero the socket list entry */
272
273   /* Drop any unprocessed events citing this socket. */
274   for (ii = 0; ii < polls_used; ii++) {
275     if (polls[ii].fd == s_fd(sock)) {
276       polls[ii] = polls[--polls_used];
277     }
278   }
279 }
280
281 /** Run engine event loop.
282  * @param[in] gen Lists of generators of various types.
283  */
284 static void
285 engine_loop(struct Generators* gen)
286 {
287   struct dvpoll dopoll;
288   int polls_count;
289   struct Socket* sock;
290   struct pollfd *pfd;
291   int nfds;
292   int i;
293   int errcode;
294   socklen_t codesize;
295
296   if ((polls_count = feature_int(FEAT_POLLS_PER_LOOP)) < 20)
297     polls_count = 20;
298   polls = (struct pollfd *)MyMalloc(sizeof(struct pollfd) * polls_count);
299
300   while (running) {
301     if ((i = feature_int(FEAT_POLLS_PER_LOOP)) >= 20 && i != polls_count) {
302       polls = (struct pollfd *)MyRealloc(polls, sizeof(struct pollfd) * i);
303       polls_count = i;
304     }
305
306     dopoll.dp_fds = polls; /* set up the struct dvpoll */
307     dopoll.dp_nfds = polls_count;
308
309     /* calculate the proper timeout */
310     dopoll.dp_timeout = timer_next(gen) ?
311       (timer_next(gen) - CurrentTime) * 1000 : -1;
312
313     Debug((DEBUG_ENGINE, "devpoll: delay: %Tu (%Tu) %d", timer_next(gen),
314            CurrentTime, dopoll.dp_timeout));
315
316     /* check for active files */
317     polls_used = ioctl(devpoll_fd, DP_POLL, &dopoll);
318
319     CurrentTime = time(0); /* set current time... */
320
321     if (polls_used < 0) {
322       if (errno != EINTR) { /* ignore interrupts */
323         /* Log the poll error */
324         log_write(LS_SOCKET, L_ERROR, 0, "ioctl(DP_POLL) error: %m");
325         if (!errors++)
326           timer_add(timer_init(&clear_error), error_clear, 0, TT_PERIODIC,
327                     ERROR_EXPIRE_TIME);
328         else if (errors > DEVPOLL_ERROR_THRESHOLD) /* too many errors... */
329           server_restart("too many /dev/poll errors");
330       }
331       /* old code did a sleep(1) here; with usage these days,
332        * that may be too expensive
333        */
334       continue;
335     }
336
337     while (polls_used > 0) {
338       pfd = &polls[--polls_used];
339       assert(-1 < pfd->fd);
340
341       sock = sockList[pfd->fd];
342       if (!sock) /* slots may become empty while processing events */
343         continue;
344
345       assert(s_fd(sock) == pfd->fd);
346
347       gen_ref_inc(sock); /* can't have it going away on us */
348
349       Debug((DEBUG_ENGINE, "devpoll: Checking socket %p (fd %d) state %s, "
350              "events %s", sock, s_fd(sock), state_to_name(s_state(sock)),
351              sock_flags(s_events(sock))));
352
353       if (s_state(sock) != SS_NOTSOCK) {
354         errcode = 0; /* check for errors on socket */
355         codesize = sizeof(errcode);
356         if (getsockopt(s_fd(sock), SOL_SOCKET, SO_ERROR, &errcode,
357                        &codesize) < 0)
358           errcode = errno; /* work around Solaris implementation */
359
360         if (errcode) { /* an error occurred; generate an event */
361           Debug((DEBUG_ENGINE, "devpoll: Error %d on fd %d, socket %p",
362                  errcode, s_fd(sock), sock));
363           event_generate(ET_ERROR, sock, errcode);
364           gen_ref_dec(sock); /* careful not to leak reference counts */
365           continue;
366         }
367       }
368
369       assert(!(pfd->revents & POLLERR));
370
371 #ifdef POLLHUP
372       if (pfd->revents & POLLHUP) { /* hang-up on socket */
373         Debug((DEBUG_ENGINE, "devpoll: EOF from client (POLLHUP)"));
374         event_generate(ET_EOF, sock, 0);
375         nfds--;
376         continue;
377       }
378 #endif /* POLLHUP */
379
380       switch (s_state(sock)) {
381       case SS_CONNECTING:
382         if (pfd->revents & POLLWRITEFLAGS) { /* connection completed */
383           Debug((DEBUG_ENGINE, "devpoll: Connection completed"));
384           event_generate(ET_CONNECT, sock, 0);
385         }
386         break;
387
388       case SS_LISTENING:
389         if (pfd->revents & POLLREADFLAGS) { /* connect. to be accept. */
390           Debug((DEBUG_ENGINE, "devpoll: Ready for accept"));
391           event_generate(ET_ACCEPT, sock, 0);
392         }
393         break;
394
395       case SS_NOTSOCK:
396         if (pfd->revents & POLLREADFLAGS) { /* data on socket */
397           /* can't peek; it's not a socket */
398           Debug((DEBUG_ENGINE, "devpoll: non-socket readable"));
399           event_generate(ET_READ, sock, 0);
400         }
401         break;
402
403       case SS_CONNECTED:
404         if (pfd->revents & POLLREADFLAGS) { /* data on socket */
405           char c;
406
407           switch (recv(s_fd(sock), &c, 1, MSG_PEEK)) { /* check EOF */
408           case -1: /* error occurred?!? */
409             if (errno == EAGAIN) {
410               Debug((DEBUG_ENGINE, "devpoll: Resource temporarily "
411                      "unavailable?"));
412               continue;
413             }
414             Debug((DEBUG_ENGINE, "devpoll: Uncaught error!"));
415             event_generate(ET_ERROR, sock, errno);
416             break;
417
418           case 0: /* EOF from client */
419             Debug((DEBUG_ENGINE, "devpoll: EOF from client"));
420             event_generate(ET_EOF, sock, 0);
421             break;
422
423           default: /* some data can be read */
424             Debug((DEBUG_ENGINE, "devpoll: Data to be read"));
425             event_generate(ET_READ, sock, 0);
426             break;
427           }
428         }
429         if (pfd->revents & POLLWRITEFLAGS) { /* socket writable */
430           Debug((DEBUG_ENGINE, "devpoll: Data can be written"));
431           event_generate(ET_WRITE, sock, 0);
432         }
433         break;
434
435       case SS_DATAGRAM: case SS_CONNECTDG:
436         if (pfd->revents & POLLREADFLAGS) { /* socket readable */
437           Debug((DEBUG_ENGINE, "devpoll: Datagram to be read"));
438           event_generate(ET_READ, sock, 0);
439         }
440         if (pfd->revents & POLLWRITEFLAGS) { /* socket writable */
441           Debug((DEBUG_ENGINE, "devpoll: Datagram can be written"));
442           event_generate(ET_WRITE, sock, 0);
443         }
444         break;
445       }
446
447       gen_ref_dec(sock); /* we're done with it */
448     }
449
450     timer_run(); /* execute any pending timers */
451   }
452 }
453
454 /** Descriptor for /dev/poll event engine. */
455 struct Engine engine_devpoll = {
456   "/dev/poll",          /* Engine name */
457   engine_init,          /* Engine initialization function */
458   0,                    /* Engine signal registration function */
459   engine_add,           /* Engine socket registration function */
460   engine_state,         /* Engine socket state change function */
461   engine_events,        /* Engine socket events mask function */
462   engine_delete,        /* Engine socket deletion function */
463   engine_loop           /* Core engine event loop */
464 };