1b5d72309cef952a833b2043f31670f8b729a1be
[apps/madmutt.git] / lib-sys / evtloop.c
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or (at
5  *  your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15  *  MA 02110-1301, USA.
16  *
17  *  Copyright © 2006 Pierre Habouzit
18  */
19
20 #include <sys/epoll.h>
21 #include <sys/socket.h>
22 #ifndef EPOLLRDHUP
23 #  include <linux/poll.h>
24 #  ifdef POLLRDHUP
25 #    define EPOLLRDHUP POLLRDHUP
26 #  else
27 #    define EPOLLRDHUP 0
28 #  endif
29 #endif
30 #include "evtloop.h"
31 #include "mutt.h"
32
33 static int epollfd = -1;
34
35 int el_job_release(job_t *w, el_status reason)
36 {
37     w->state = EL_LLP_FINI;
38     if (w->m && w->m->finalize) {
39         w->m->finalize(w, reason);
40     }
41     if (w->fd >= 0) {
42         close(w->fd);
43     }
44     p_delete(&w);
45     return -1;
46 }
47
48 int el_dispatch(int timeout)
49 {
50     struct epoll_event events[FD_SETSIZE];
51     int count = epoll_wait(epollfd, events, countof(events), timeout);
52
53     if (count < 0) {
54         if (errno == EAGAIN || errno == EINTR)
55             return 0;
56         mutt_error("epoll_wait");
57         mutt_exit(EXIT_FAILURE);
58     }
59
60     while (--count >= 0) {
61         job_t *w  = events[count].data.ptr;
62         int event = events[count].events;
63         int evt   = 0;
64
65         switch (w->state) {
66           case EL_LLP_INIT:
67             w->llp(w);
68             break;
69
70           case EL_LLP_READY:
71             if (event & EPOLLRDHUP) {
72                 IGNORE(el_job_release(w, EL_RDHUP));
73             } else if (w->mode != w->emode) {
74                     w->m->on_event(w, EL_EVT_INOUT ^ w->emode);
75             } else {
76                 if (event & EPOLLIN)
77                     evt |= EL_EVT_IN;
78                 if (event & EPOLLOUT)
79                     evt |= EL_EVT_OUT;
80                 w->m->on_event(w, evt);
81             }
82             break;
83
84           default:
85             IGNORE(el_job_release(w, EL_ERROR));
86             break;
87         }
88     }
89
90     return 0;
91 }