Update to latest madtty.
[apps/madmutt.git] / lib-sys / evtloop.c
index ed9eca5..1c94706 100644 (file)
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
- *
- *  Copyright © 2006 Pierre Habouzit
+ */
+/*
+ *  Copyright © 2007 Pierre Habouzit
  */
 
+#include <netdb.h>
+#include <pthread.h>
 #include <sys/epoll.h>
 #include <sys/socket.h>
 #ifndef EPOLLRDHUP
 #endif
 #include "evtloop.h"
 #include "mutt.h"
+#include "mutt_ssl.li"
+#ifdef HAVE_LIBIDN
+#include <idna.h>
+#endif
+
+DO_ARRAY_TYPE(job_t, job);
 
 static int epollfd = -1;
+static job_array jobs;
+static pthread_mutex_t el_mx;
+static pthread_cond_t el_cond;
+static pthread_t el_thread;
 
 static int el_job_setemode(job_t *w, el_mode emode)
 {
@@ -69,19 +82,94 @@ int el_job_setmode(job_t *w, el_mode mode)
     }
 }
 
+void job_wipe(job_t *w)
+{
+    if (w->xcred)
+        gnutls_certificate_free_credentials(w->xcred);
+    if (w->session)
+        gnutls_deinit(w->session);
+}
+
+static void job_arrau_dtor(job_t **j)
+{
+    if (*j)
+        IGNORE(el_job_release(*j, EL_KILLED));
+}
+
+DO_ARRAY_FUNCS(job_t, job, job_arrau_dtor);
+
+static void job_array_remove(job_array *arr, job_t *j)
+{
+    for (int i = 0; i < arr->len; i++) {
+        if (arr->arr[i] == j) {
+            job_array_take(arr, i);
+            break;
+        }
+    }
+}
+
+job_t *el_job_start(const machine_t *m, void *cfg)
+{
+    job_t *w = job_new();
+    w->m = m;
+    job_array_append(&jobs, w);
+    return m->setup(w, cfg) < 0 ? NULL : w;
+}
+
 int el_job_release(job_t *w, el_status reason)
 {
+    if (w->cond) {
+        pthread_cond_signal(&el_cond);
+        w->cond = false;
+    }
     w->state = EL_LLP_FINI;
     if (w->m && w->m->finalize) {
         w->m->finalize(w, reason);
     }
     if (w->fd >= 0) {
+        if (w->session)
+            gnutls_bye(w->session, GNUTLS_SHUT_RDWR);
         close(w->fd);
     }
+    job_array_remove(&jobs, w);
     job_delete(&w);
     return -1;
 }
 
+static int el_job_tlsing(job_t *w, int starttls)
+{
+    int err = gnutls_handshake(w->session);
+    if (err < 0 && !gnutls_error_is_fatal(err)) {
+        int wr = gnutls_record_get_direction(w->session);
+        return el_job_setemode(w, wr ? EL_WRITING : EL_READING);
+    }
+    if (err < 0)
+        return el_job_release(w, EL_RDHUP);
+
+#if 0
+    if (!tls_check_certificate (conn))
+        return -1;
+#endif
+
+    /* set Security Strength Factor (SSF) for SASL */
+    /* NB: gnutls_cipher_get_key_size() returns key length in bytes */
+    w->ssf   = gnutls_cipher_get_key_size(gnutls_cipher_get(w->session)) * 8;
+    w->state = EL_LLP_READY;
+    if (starttls)
+        return el_job_setemode(w, w->mode);
+    return w->m->on_event(w, EL_EVT_RUNNING);
+}
+
+static int el_job_starttlsing(job_t *w)
+{
+    return el_job_tlsing(w, true);
+}
+
+static int el_job_connecting_ssl(job_t *w)
+{
+    return el_job_tlsing(w, false);
+}
+
 static int el_job_connecting(job_t *w)
 {
     int err = 0;
@@ -90,12 +178,49 @@ static int el_job_connecting(job_t *w)
     if (getsockopt(w->fd, SOL_SOCKET, SO_ERROR, (void *)&err, &len) || err)
         return el_job_release(w, EL_ERROR);
 
+    if (w->session) {
+        w->llp = &el_job_connecting_ssl;
+        return w->llp(w);
+    }
     w->state = EL_LLP_READY;
     return w->m->on_event(w, EL_EVT_RUNNING);
 }
 
+static int tls_negotiate(job_t *w)
+{
+    static int protocol_priority[] = { GNUTLS_TLS1, GNUTLS_SSL3, 0 };
+
+    if (gnutls_certificate_allocate_credentials(&w->xcred) < 0)
+        return -1;
+
+    /* ignore errors, maybe file doesn't exist yet */
+    gnutls_certificate_set_x509_trust_file(w->xcred, mod_ssl.cert_file,
+                                           GNUTLS_X509_FMT_PEM);
+
+    if (mod_ssl.ca_certificates_file) {
+        gnutls_certificate_set_x509_trust_file(w->xcred,
+            mod_ssl.ca_certificates_file, GNUTLS_X509_FMT_PEM);
+    }
+    gnutls_init(&w->session, GNUTLS_CLIENT);
+
+    /* set socket */
+    gnutls_transport_set_ptr(w->session, (gnutls_transport_ptr)(intptr_t)w->fd);
+
+    /* disable TLS/SSL protocols as needed */
+    if (!mod_ssl.use_sslv3) {
+        protocol_priority[1] = 0;
+    }
+
+    /* We use default priorities (see gnutls documentation),
+       except for protocol version */
+    gnutls_set_default_priority(w->session);
+    gnutls_protocol_set_priority(w->session, protocol_priority);
+    gnutls_credentials_set(w->session, GNUTLS_CRD_CERTIFICATE, w->xcred);
+    return 0;
+}
+
 int el_job_connect(job_t *w, struct sockaddr *addr, socklen_t len,
-                   int type, int proto)
+                   int type, int proto, int ssl)
 {
     int res, sock = socket(addr->sa_family, type, proto);
 
@@ -107,10 +232,15 @@ int el_job_connect(job_t *w, struct sockaddr *addr, socklen_t len,
         goto error;
     if (fcntl(sock, F_SETFL, res | O_NONBLOCK) < 0)
         goto error;
+    if (fcntl(sock, F_SETFD, FD_CLOEXEC) < 0)
+        goto error;
     if (connect(sock, addr, len) < 0)
         goto error;
 
     w->fd  = sock;
+    if (ssl && tls_negotiate(w) < 0)
+        goto error;
+
     w->llp = &el_job_connecting;
     return el_job_setmode(w, EL_WRITING);
 
@@ -119,6 +249,56 @@ int el_job_connect(job_t *w, struct sockaddr *addr, socklen_t len,
     return el_job_release(w, EL_ERROR);
 }
 
+int el_job_connect2(job_t *w, const ACCOUNT *act)
+{
+    int rc;
+    char *host = NULL;
+    struct addrinfo *res;
+    struct addrinfo hints = {
+        .ai_family = AF_UNSPEC,
+        .ai_socktype = SOCK_STREAM,
+    };
+
+# ifdef HAVE_LIBIDN
+    if (idna_to_ascii_lz(act->host, &host, 1) != IDNA_SUCCESS) {
+        mutt_error(_("Bad IDN \"%s\"."), act->host);
+        return -1;
+    }
+# else
+    host = act->host;
+# endif
+    mutt_message(_("Looking up %s..."), act->host);
+    rc = getaddrinfo(host, NULL, &hints, &res);
+# ifdef HAVE_LIBIDN
+    p_delete(&host);
+# endif
+
+    if (rc) {
+        mutt_error(_("Could not find the host \"%s\""), act->host);
+        mutt_sleep(2);
+        return -1;
+    }
+    mutt_message(_("Connecting to %s..."), act->host);
+    rc = el_job_connect(w, res->ai_addr, res->ai_addrlen, res->ai_socktype,
+                        res->ai_protocol, act->has_ssl);
+    freeaddrinfo (res);
+    if (rc) {
+        mutt_error(_("Could not connect to %s (%m)."), act->host);
+        mutt_sleep(2);
+        return -1;
+    }
+    return 0;
+}
+
+int el_job_starttls(job_t *w)
+{
+    if (tls_negotiate(w) < 0)
+        return el_job_release(w, EL_RDHUP);
+    w->state = EL_LLP_INIT;
+    w->llp   = &el_job_starttlsing;
+    return w->llp(w);
+}
+
 ssize_t el_job_read(job_t *w, buffer_t *buf)
 {
     ssize_t nr;
@@ -168,6 +348,16 @@ ssize_t el_job_write(job_t *w, buffer_t *buf)
     return nr;
 }
 
+void el_lock(void)
+{
+    pthread_mutex_lock(&el_mx);
+}
+
+void el_unlock(void)
+{
+    pthread_mutex_unlock(&el_mx);
+}
+
 int el_dispatch(int timeout)
 {
     struct epoll_event events[FD_SETSIZE];
@@ -180,11 +370,17 @@ int el_dispatch(int timeout)
         mutt_exit(EXIT_FAILURE);
     }
 
+    el_lock();
     while (--count >= 0) {
         job_t *w  = events[count].data.ptr;
         int event = events[count].events;
         int evt   = 0;
 
+        if (w->cond) {
+            pthread_cond_signal(&el_cond);
+            w->cond = false;
+        }
+        gettimeofday(&w->mru, NULL);
         switch (w->state) {
           case EL_LLP_INIT:
             w->llp(w);
@@ -194,13 +390,13 @@ int el_dispatch(int timeout)
             if (event & EPOLLRDHUP) {
                 IGNORE(el_job_release(w, EL_RDHUP));
             } else if (w->mode != w->emode) {
-                    w->m->on_event(w, EL_EVT_INOUT ^ w->emode);
+                IGNORE(w->m->on_event(w, EL_EVT_INOUT ^ w->emode));
             } else {
                 if (event & EPOLLIN)
                     evt |= EL_EVT_IN;
                 if (event & EPOLLOUT)
                     evt |= EL_EVT_OUT;
-                w->m->on_event(w, evt);
+                IGNORE(w->m->on_event(w, evt));
             }
             break;
 
@@ -209,6 +405,73 @@ int el_dispatch(int timeout)
             break;
         }
     }
+    el_unlock();
 
     return 0;
 }
+
+void el_wait(volatile job_t *w)
+{
+    w->cond = true;
+    pthread_cond_wait(&el_cond, &el_mx);
+}
+
+static void *el_loop(void *data)
+{
+    time_t sec = time(NULL);
+
+    for (;;) {
+        struct timeval now;
+
+        el_dispatch(100);
+        pthread_testcancel();
+
+        gettimeofday(&now, NULL);
+        if (sec >= now.tv_sec)
+            continue;
+        sec = now.tv_sec;
+        now.tv_sec -= 10;
+
+        el_lock();
+        for (int i = jobs.len - 1; i >= 0; --i) {
+            job_t *w = jobs.arr[i];
+            if (timercmp(&now, &w->mru, >)) {
+                if (w->cond) {
+                    pthread_cond_signal(&el_cond);
+                    w->cond = false;
+                }
+                IGNORE(w->m->on_event(w, EL_EVT_WAKEUP));
+            }
+        }
+        el_unlock();
+    }
+}
+
+void el_initialize(void)
+{
+    pthread_mutexattr_t attr;
+
+    pthread_mutexattr_init(&attr);
+    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
+    pthread_mutex_init(&el_mx, &attr);
+    pthread_mutexattr_destroy(&attr);
+
+    gnutls_global_init();
+    epollfd = epoll_create(1024);
+    if (epollfd < 0) {
+        mutt_error("epoll_create");
+        mutt_exit(EXIT_FAILURE);
+    }
+    job_array_init(&jobs);
+    pthread_create(&el_thread, NULL, &el_loop, NULL);
+}
+
+void el_shutdown(void)
+{
+    pthread_cancel(el_thread);
+    pthread_join(el_thread, NULL);
+    job_array_wipe(&jobs);
+    close(epollfd);
+    gnutls_global_deinit();
+    pthread_mutex_destroy(&el_mx);
+}