further pop_mx_ng work
[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 /*
18  *  Copyright © 2007 Pierre Habouzit
19  */
20
21 #include <pthread.h>
22 #include <sys/epoll.h>
23 #include <sys/socket.h>
24 #ifndef EPOLLRDHUP
25 #  include <linux/poll.h>
26 #  ifdef POLLRDHUP
27 #    define EPOLLRDHUP POLLRDHUP
28 #  else
29 #    define EPOLLRDHUP 0
30 #  endif
31 #endif
32 #include "evtloop.h"
33 #include "mutt.h"
34 #include "mutt_ssl.li"
35
36 DO_ARRAY_TYPE(job_t, job);
37
38 static int epollfd = -1;
39 static job_array jobs;
40 static pthread_mutex_t el_mx;
41 static pthread_cond_t el_cond;
42 static pthread_t el_thread;
43
44 static int el_job_setemode(job_t *w, el_mode emode)
45 {
46     static int const evtmode_to_epoll[] = {
47         [EL_NEW]     = EPOLLRDHUP,
48         [EL_READING] = EPOLLIN,
49         [EL_WRITING] = EPOLLOUT,
50         [EL_RDWR]    = EPOLLIN | EPOLLOUT,
51         [EL_IDLE]    = EPOLLRDHUP,
52     };
53
54     assert (w->mode == emode || emode == EL_WRITING || emode == EL_READING);
55
56     if (emode != w->emode) {
57         struct epoll_event event = {
58             .data.ptr = w,
59             .events   = evtmode_to_epoll[emode],
60         };
61         int action = w->emode == EL_NEW ? EPOLL_CTL_ADD : EPOLL_CTL_MOD;
62         if (epoll_ctl(epollfd, action, w->fd, &event) < 0) {
63             return el_job_release(w, true);
64         }
65     }
66     w->emode = emode;
67     return 0;
68 }
69
70 int el_job_setmode(job_t *w, el_mode mode)
71 {
72     if (w->mode == w->emode) {
73         w->mode = mode;
74         return el_job_setemode(w, mode);
75     } else {
76         w->mode = mode;
77         return 0;
78     }
79 }
80
81 void job_wipe(job_t *w)
82 {
83     if (w->xcred)
84         gnutls_certificate_free_credentials(w->xcred);
85     if (w->session)
86         gnutls_deinit(w->session);
87 }
88
89 static void job_arrau_dtor(job_t **j)
90 {
91     if (*j)
92         IGNORE(el_job_release(*j, EL_KILLED));
93 }
94
95 DO_ARRAY_FUNCS(job_t, job, job_arrau_dtor);
96
97 static void job_array_remove(job_array *arr, job_t *j)
98 {
99     for (int i = 0; i < arr->len; i++) {
100         if (arr->arr[i] == j) {
101             job_array_take(arr, i);
102             break;
103         }
104     }
105 }
106
107 job_t *el_job_start(const machine_t *m, void *cfg)
108 {
109     job_t *w = job_new();
110     w->m = m;
111     job_array_append(&jobs, w);
112     return m->setup(w, cfg) < 0 ? NULL : w;
113 }
114
115 int el_job_release(job_t *w, el_status reason)
116 {
117     if (w->cond) {
118         pthread_cond_signal(&el_cond);
119         w->cond = false;
120     }
121     w->state = EL_LLP_FINI;
122     if (w->m && w->m->finalize) {
123         w->m->finalize(w, reason);
124     }
125     if (w->fd >= 0) {
126         if (w->session)
127             gnutls_bye(w->session, GNUTLS_SHUT_RDWR);
128         close(w->fd);
129     }
130     job_array_remove(&jobs, w);
131     job_delete(&w);
132     return -1;
133 }
134
135 static int el_job_tlsing(job_t *w, int starttls)
136 {
137     int err = gnutls_handshake(w->session);
138     if (err < 0 && !gnutls_error_is_fatal(err)) {
139         int wr = gnutls_record_get_direction(w->session);
140         return el_job_setemode(w, wr ? EL_WRITING : EL_READING);
141     }
142     if (err < 0)
143         return el_job_release(w, EL_RDHUP);
144
145 #if 0
146     if (!tls_check_certificate (conn))
147         return -1;
148 #endif
149
150     /* set Security Strength Factor (SSF) for SASL */
151     /* NB: gnutls_cipher_get_key_size() returns key length in bytes */
152     w->ssf   = gnutls_cipher_get_key_size(gnutls_cipher_get(w->session)) * 8;
153     w->state = EL_LLP_READY;
154     if (starttls)
155         return el_job_setemode(w, w->mode);
156     return w->m->on_event(w, EL_EVT_RUNNING);
157 }
158
159 static int el_job_starttlsing(job_t *w)
160 {
161     return el_job_tlsing(w, true);
162 }
163
164 static int el_job_connecting_ssl(job_t *w)
165 {
166     return el_job_tlsing(w, false);
167 }
168
169 static int el_job_connecting(job_t *w)
170 {
171     int err = 0;
172     socklen_t len = sizeof(err);
173
174     if (getsockopt(w->fd, SOL_SOCKET, SO_ERROR, (void *)&err, &len) || err)
175         return el_job_release(w, EL_ERROR);
176
177     if (w->session) {
178         w->llp = &el_job_connecting_ssl;
179         return w->llp(w);
180     }
181     w->state = EL_LLP_READY;
182     return w->m->on_event(w, EL_EVT_RUNNING);
183 }
184
185 static int tls_negotiate(job_t *w)
186 {
187     static int protocol_priority[] = { GNUTLS_TLS1, GNUTLS_SSL3, 0 };
188
189     if (gnutls_certificate_allocate_credentials(&w->xcred) < 0)
190         return -1;
191
192     /* ignore errors, maybe file doesn't exist yet */
193     gnutls_certificate_set_x509_trust_file(w->xcred, mod_ssl.cert_file,
194                                            GNUTLS_X509_FMT_PEM);
195
196     if (mod_ssl.ca_certificates_file) {
197         gnutls_certificate_set_x509_trust_file(w->xcred,
198             mod_ssl.ca_certificates_file, GNUTLS_X509_FMT_PEM);
199     }
200     gnutls_init(&w->session, GNUTLS_CLIENT);
201
202     /* set socket */
203     gnutls_transport_set_ptr(w->session, (gnutls_transport_ptr)(intptr_t)w->fd);
204
205     /* disable TLS/SSL protocols as needed */
206     if (!mod_ssl.use_sslv3) {
207         protocol_priority[1] = 0;
208     }
209
210     /* We use default priorities (see gnutls documentation),
211        except for protocol version */
212     gnutls_set_default_priority(w->session);
213     gnutls_protocol_set_priority(w->session, protocol_priority);
214     gnutls_credentials_set(w->session, GNUTLS_CRD_CERTIFICATE, w->xcred);
215     return 0;
216 }
217
218 int el_job_connect(job_t *w, struct sockaddr *addr, socklen_t len,
219                    int type, int proto, int ssl)
220 {
221     int res, sock = socket(addr->sa_family, type, proto);
222
223     if (sock < 0)
224         goto error;
225
226     res = fcntl(sock, F_GETFL);
227     if (res < 0)
228         goto error;
229     if (fcntl(sock, F_SETFL, res | O_NONBLOCK) < 0)
230         goto error;
231     if (connect(sock, addr, len) < 0)
232         goto error;
233
234     w->fd  = sock;
235     if (ssl && tls_negotiate(w) < 0)
236         goto error;
237
238     w->llp = &el_job_connecting;
239     return el_job_setmode(w, EL_WRITING);
240
241   error:
242     close(sock);
243     return el_job_release(w, EL_ERROR);
244 }
245
246 int el_job_starttls(job_t *w)
247 {
248     if (tls_negotiate(w) < 0)
249         return el_job_release(w, EL_RDHUP);
250     w->state = EL_LLP_INIT;
251     w->llp   = &el_job_starttlsing;
252     return w->llp(w);
253 }
254
255 ssize_t el_job_read(job_t *w, buffer_t *buf)
256 {
257     ssize_t nr;
258
259     buffer_ensure(buf, BUFSIZ);
260
261     if (w->session) {
262         nr = gnutls_record_recv(w->session, buf->data + buf->len, BUFSIZ);
263         if (nr < 0 && !gnutls_error_is_fatal(nr)) {
264             int wr = gnutls_record_get_direction(w->session);
265             return el_job_setemode(w, wr ? EL_WRITING : EL_READING);
266         }
267         EL_JOB_CHECK(el_job_setemode(w, w->mode));
268     } else {
269         nr = read(w->fd, buf->data + buf->len, BUFSIZ);
270         if (nr < 0 && (errno == EINTR || errno == EAGAIN))
271             return 0;
272     }
273     if (nr <= 0)
274         return el_job_release(w, EL_RDHUP);
275     buffer_extend(buf, nr);
276     return nr;
277 }
278
279 ssize_t el_job_write(job_t *w, buffer_t *buf)
280 {
281     ssize_t nr;
282
283     if (buf->len == 0)
284         return 0;
285
286     if (w->session) {
287         nr = gnutls_record_send(w->session, buf->data, buf->len);
288         if (nr < 0 && !gnutls_error_is_fatal(nr)) {
289             int wr = gnutls_record_get_direction(w->session);
290             return el_job_setemode(w, wr ? EL_WRITING : EL_READING);
291         }
292         EL_JOB_CHECK(el_job_setemode(w, w->mode));
293     } else {
294         nr = write(w->fd, buf->data, buf->len);
295         if (nr < 0 && (errno == EINTR || errno == EAGAIN))
296             return 0;
297     }
298     if (nr <= 0)
299         return el_job_release(w, EL_RDHUP);
300     buffer_splice(buf, 0, nr, NULL, 0);
301     return nr;
302 }
303
304 void el_lock(void)
305 {
306     pthread_mutex_lock(&el_mx);
307 }
308
309 void el_unlock(void)
310 {
311     pthread_mutex_unlock(&el_mx);
312 }
313
314 int el_dispatch(int timeout)
315 {
316     struct epoll_event events[FD_SETSIZE];
317     int count = epoll_wait(epollfd, events, countof(events), timeout);
318
319     if (count < 0) {
320         if (errno == EAGAIN || errno == EINTR)
321             return 0;
322         mutt_error("epoll_wait");
323         mutt_exit(EXIT_FAILURE);
324     }
325
326     el_lock();
327     while (--count >= 0) {
328         job_t *w  = events[count].data.ptr;
329         int event = events[count].events;
330         int evt   = 0;
331
332         if (w->cond) {
333             pthread_cond_signal(&el_cond);
334             w->cond = false;
335         }
336         gettimeofday(&w->mru, NULL);
337         switch (w->state) {
338           case EL_LLP_INIT:
339             w->llp(w);
340             break;
341
342           case EL_LLP_READY:
343             if (event & EPOLLRDHUP) {
344                 IGNORE(el_job_release(w, EL_RDHUP));
345             } else if (w->mode != w->emode) {
346                 IGNORE(w->m->on_event(w, EL_EVT_INOUT ^ w->emode));
347             } else {
348                 if (event & EPOLLIN)
349                     evt |= EL_EVT_IN;
350                 if (event & EPOLLOUT)
351                     evt |= EL_EVT_OUT;
352                 IGNORE(w->m->on_event(w, evt));
353             }
354             break;
355
356           default:
357             IGNORE(el_job_release(w, EL_ERROR));
358             break;
359         }
360     }
361     el_unlock();
362
363     return 0;
364 }
365
366 void el_wait(job_t *w)
367 {
368     w->cond = true;
369     pthread_cond_wait(&el_cond, &el_mx);
370 }
371
372 static void *el_loop(void *data)
373 {
374     time_t sec = time(NULL);
375
376     for (;;) {
377         struct timeval now;
378
379         el_dispatch(100);
380         pthread_testcancel();
381
382         gettimeofday(&now, NULL);
383         if (sec >= now.tv_sec)
384             continue;
385         sec = now.tv_sec;
386         now.tv_sec -= 10;
387
388         el_lock();
389         for (int i = jobs.len - 1; i >= 0; --i) {
390             job_t *w = jobs.arr[i];
391             if (timercmp(&now, &w->mru, >)) {
392                 if (w->cond) {
393                     pthread_cond_signal(&el_cond);
394                     w->cond = false;
395                 }
396                 IGNORE(w->m->on_event(w, EL_EVT_WAKEUP));
397             }
398         }
399         el_unlock();
400     }
401 }
402
403 void el_initialize(void)
404 {
405     pthread_mutexattr_t attr;
406
407     pthread_mutexattr_init(&attr);
408     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
409     pthread_mutex_init(&el_mx, &attr);
410     pthread_mutexattr_destroy(&attr);
411
412     gnutls_global_init();
413     epollfd = epoll_create(1024);
414     if (epollfd < 0) {
415         mutt_error("epoll_create");
416         mutt_exit(EXIT_FAILURE);
417     }
418     job_array_init(&jobs);
419     pthread_create(&el_thread, NULL, &el_loop, NULL);
420 }
421
422 void el_shutdown(void)
423 {
424     pthread_cancel(el_thread);
425     pthread_join(el_thread, NULL);
426     job_array_wipe(&jobs);
427     close(epollfd);
428     gnutls_global_deinit();
429     pthread_mutex_destroy(&el_mx);
430 }