Fix printf formats for size_t and goffset arguments.
[claws.git] / src / etpan / imap-thread.c
index ab212521638b53f3c427a249d6e1c886a1f55835..be5678cb8a2c185f5e3c0c47b38da1ca4e2213fb 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 2005-2009 DINH Viet Hoa and the Claws Mail team
+ * Copyright (C) 2005-2016 DINH Viet Hoa and the Claws Mail team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  *
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * 
  */
 
 #ifdef HAVE_CONFIG_H
 #  include "config.h"
+#include "claws-features.h"
 #endif
 
 #ifdef HAVE_LIBETPAN
 
+#include <glib.h>
+#include <glib/gi18n.h>
 #include "imap-thread.h"
 #include <imap.h>
 #include <sys/types.h>
 #include <gtk/gtk.h>
 #include <log.h>
 #include "etpan-thread-manager.h"
+#include "etpan-ssl.h"
 #include "utils.h"
 #include "mainwindow.h"
+#include "proxy.h"
+#include "file-utils.h"
 #include "ssl.h"
 #include "ssl_certificate.h"
 #include "socket.h"
 #include "remotefolder.h"
+#include "tags.h"
 
 #define DISABLE_LOG_DURING_LOGIN
 
@@ -54,27 +60,77 @@ static chash * session_hash = NULL;
 static guint thread_manager_signal = 0;
 static GIOChannel * io_channel = NULL;
 
-static void delete_imap(Folder *folder, mailimap *imap)
+static int do_mailimap_socket_connect(mailimap * imap, const char * server,
+                              gushort port, ProxyInfo * proxy_info)
 {
-       chashdatum key;
-       chashdatum value;
+       SockInfo * sock;
+       mailstream * stream;
 
-       key.data = &folder;
-       key.len = sizeof(folder);
-       value.data = imap;
-       value.len = 0;
-       chash_delete(session_hash, &key, NULL);
-       
-       key.data = &imap;
-       key.len = sizeof(imap);
-       chash_delete(courier_workaround_hash, &key, NULL);
-       if (imap && imap->imap_stream) {
-               /* we don't want libetpan to logout */
-               mailstream_close(imap->imap_stream);
-               imap->imap_stream = NULL;
+       if (!proxy_info)
+               return mailimap_socket_connect(imap, server, port);
+
+       if (port == 0)
+               port = 143;
+
+       sock = sock_connect(proxy_info->proxy_host, proxy_info->proxy_port);
+
+       if (sock == NULL)
+               return MAILIMAP_ERROR_CONNECTION_REFUSED;
+
+       if (proxy_connect(sock, server, port, proxy_info) < 0) {
+               sock_close(sock);
+               return MAILIMAP_ERROR_CONNECTION_REFUSED;
+       }
+
+       stream = mailstream_socket_open_timeout(sock->sock,
+                       imap->imap_timeout);
+       if (stream == NULL) {
+               sock_close(sock);
+               return MAILIMAP_ERROR_MEMORY;
+       }
+
+       return mailimap_connect(imap, stream);
+}
+
+static int do_mailimap_ssl_connect_with_callback(mailimap * imap, const char * server,
+       gushort port,
+       void (* callback)(struct mailstream_ssl_context * ssl_context, void * data),
+       void * data,
+       ProxyInfo *proxy_info)
+{
+       SockInfo * sock;
+       mailstream * stream;
+
+       if (!proxy_info)
+               return mailimap_ssl_connect_with_callback(imap, server,
+                               port, callback, data);
+
+       if (port == 0)
+               port = 993;
+
+       sock = sock_connect(proxy_info->proxy_host, proxy_info->proxy_port);
+
+       if (sock == NULL) {
+               debug_print("Can not connect to proxy %s:%d\n",
+                               proxy_info->proxy_host, proxy_info->proxy_port);
+               return MAILIMAP_ERROR_CONNECTION_REFUSED;
+       }
+
+       if (proxy_connect(sock, server, port, proxy_info) < 0) {
+               debug_print("Can not make proxy connection via %s:%d\n",
+                               proxy_info->proxy_host, proxy_info->proxy_port);
+               sock_close(sock);
+               return MAILIMAP_ERROR_CONNECTION_REFUSED;
        }
-       debug_print("removing mailimap %p\n", imap);
-       mailimap_free(imap);    
+
+       stream = mailstream_ssl_open_with_callback_timeout(sock->sock,
+                       imap->imap_timeout, callback, data);
+       if (stream == NULL) {
+               sock_close(sock);
+               return MAILIMAP_ERROR_SSL;
+       }
+
+       return mailimap_connect(imap, stream);
 }
 
 static gboolean thread_manager_event(GIOChannel * source,
@@ -105,7 +161,7 @@ static void imap_logger_cmd(int direction, const char * str, size_t size)
        int i = 0;
 
        if (size > 8192) {
-               log_print(LOG_PROTOCOL, "IMAP4%c [CMD data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [CMD data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
                return;
        }
        buf = malloc(size+1);
@@ -126,7 +182,7 @@ static void imap_logger_cmd(int direction, const char * str, size_t size)
        lines = g_strsplit(buf, "\n", -1);
 
        while (lines[i] && *lines[i]) {
-               log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+               log_print(LOG_PROTOCOL, "IMAP%c %s\n", direction?'>':'<', lines[i]);
                i++;
        }
        g_strfreev(lines);
@@ -140,7 +196,7 @@ static void imap_logger_fetch(int direction, const char * str, size_t size)
        int i = 0;
 
        if (size > 128 && !direction) {
-               log_print(LOG_PROTOCOL, "IMAP4%c [FETCH data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [FETCH data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
                return;
        }
        
@@ -162,11 +218,11 @@ static void imap_logger_fetch(int direction, const char * str, size_t size)
 
        if (direction != 0 || (buf[0] == '*' && buf[1] == ' ') || size < 32) {
                while (lines[i] && *lines[i]) {
-                       log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+                       log_print(LOG_PROTOCOL, "IMAP%c %s\n", direction?'>':'<', lines[i]);
                        i++;
                }
        } else {
-               log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
        }
        g_strfreev(lines);
        free(buf);
@@ -179,7 +235,7 @@ static void imap_logger_uid(int direction, const char * str, size_t size)
        int i = 0;
 
        if (size > 8192) {
-               log_print(LOG_PROTOCOL, "IMAP4%c [UID data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [UID data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
                return;
        }
        buf = malloc(size+1);
@@ -201,11 +257,11 @@ static void imap_logger_uid(int direction, const char * str, size_t size)
        while (lines[i] && *lines[i]) {
                int llen = strlen(lines[i]);
                if (llen < 64)
-                       log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+                       log_print(LOG_PROTOCOL, "IMAP%c %s\n", direction?'>':'<', lines[i]);
                else {
                        gchar tmp[64];
                        strncpy2(tmp, lines[i], 63);
-                       log_print(LOG_PROTOCOL, "IMAP4%c %s[... - %d bytes more]\n", direction?'>':'<', tmp,
+                       log_print(LOG_PROTOCOL, "IMAP%c %s[... - %d bytes more]\n", direction?'>':'<', tmp,
                                  llen-64);
                }
                i++;
@@ -221,10 +277,10 @@ static void imap_logger_append(int direction, const char * str, size_t size)
        int i = 0;
 
        if (size > 8192) {
-               log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [APPEND data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
                return;
        } else if (direction == 0 && size > 64) {
-               log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [APPEND data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
                return;
        } 
        buf = malloc(size+1);
@@ -245,11 +301,11 @@ static void imap_logger_append(int direction, const char * str, size_t size)
 
        if (direction == 0 || (buf[0] == '*' && buf[1] == ' ') || size < 64) {
                while (lines[i] && *lines[i]) {
-                       log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+                       log_print(LOG_PROTOCOL, "IMAP%c %s\n", direction?'>':'<', lines[i]);
                        i++;
                }
        } else {
-               log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
+               log_print(LOG_PROTOCOL, "IMAP%c [data - %"G_GSIZE_FORMAT" bytes]\n", direction?'>':'<', size);
        }
        g_strfreev(lines);
        free(buf);
@@ -296,9 +352,9 @@ void imap_main_set_timeout(int sec)
        mailstream_network_delay.tv_usec = 0;
 }
 
-void imap_main_done(void)
+void imap_main_done(gboolean have_connectivity)
 {
-       imap_disconnect_all();
+       imap_disconnect_all(have_connectivity);
        etpan_thread_manager_stop(thread_manager);
 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
        return;
@@ -351,7 +407,7 @@ void imap_done(Folder * folder)
        
        chash_delete(imap_hash, &key, NULL);
        
-       debug_print("remove thread");
+       debug_print("remove thread\n");
 }
 
 static struct etpan_thread * get_thread(Folder * folder)
@@ -359,13 +415,17 @@ static struct etpan_thread * get_thread(Folder * folder)
        struct etpan_thread * thread;
        chashdatum key;
        chashdatum value;
-       
+       int r;
+
        key.data = &folder;
        key.len = sizeof(folder);
-       
-       chash_get(imap_hash, &key, &value);
+
+       r = chash_get(imap_hash, &key, &value);
+       if (r < 0)
+               return NULL;
+
        thread = value.data;
-       
+
        return thread;
 }
 
@@ -403,45 +463,54 @@ static void generic_cb(int cancelled, void * result, void * callback_data)
        debug_print("generic_cb\n");
        if (op->imap && op->imap->imap_response_info &&
            op->imap->imap_response_info->rsp_alert) {
-               log_error(LOG_PROTOCOL, "IMAP4< Alert: %s\n", 
+               log_error(LOG_PROTOCOL, "IMAP< Alert: %s\n",
                        op->imap->imap_response_info->rsp_alert);
                g_timeout_add(10, cb_show_error, NULL);
        } 
        op->finished = 1;
 }
 
-static void threaded_run(Folder * folder, void * param, void * result,
-                        void (* func)(struct etpan_thread_op * ))
+/* Please do *not* blindly use imap pointers after this function returns,
+ * someone may have deleted it while this function was waiting for completion.
+ * Check return value to see if imap is still valid.
+ * Run get_imap(folder) again to get a fresh and valid pointer.
+ */
+static int threaded_run(Folder * folder, void * param, void * result,
+                       void (* func)(struct etpan_thread_op * ))
 {
        struct etpan_thread_op * op;
        struct etpan_thread * thread;
+       struct mailimap * imap = get_imap(folder);
        
        imap_folder_ref(folder);
 
        op = etpan_thread_op_new();
        
-       op->imap = get_imap(folder);
+       op->imap = imap;
        op->param = param;
        op->result = result;
        
-       op->cancellable = 0;
        op->run = func;
        op->callback = generic_cb;
        op->callback_data = op;
-       op->cleanup = NULL;
-       
-       op->finished = 0;
-       
+
        thread = get_thread(folder);
        etpan_thread_op_schedule(thread, op);
        
        while (!op->finished) {
                gtk_main_iteration();
        }
-       
+
        etpan_thread_op_free(op);
 
        imap_folder_unref(folder);
+
+       if (imap != get_imap(folder)) {
+               g_warning("returning from operation on a stale imap %p", imap);
+               return 1;
+       }
+
+       return 0;
 }
 
 
@@ -452,6 +521,7 @@ struct connect_param {
        PrefsAccount *account;
        const char * server;
        int port;
+       ProxyInfo * proxy_info;
 };
 
 struct connect_result {
@@ -465,6 +535,55 @@ struct connect_result {
        }                                                       \
 }
 
+
+static void delete_imap_run(struct etpan_thread_op * op)
+{
+       mailimap * imap = op->imap;
+
+       /* we don't want libetpan to logout */
+       if (imap->imap_stream) {
+               mailstream_close(imap->imap_stream);
+               imap->imap_stream = NULL;
+       }
+
+       mailimap_free(imap);
+}
+
+static void threaded_delete_imap(Folder *folder, mailimap *imap)
+{
+       struct etpan_thread_op * op;
+
+       /* No need to wait for completion, threaded_run() won't work here. */
+       op = etpan_thread_op_new();
+       op->imap = imap;
+       op->run = delete_imap_run;
+       op->cleanup = etpan_thread_op_free;
+
+       etpan_thread_op_schedule(get_thread(folder), op);
+
+       debug_print("threaded delete imap posted\n");
+}
+
+static void delete_imap(Folder *folder, mailimap *imap)
+{
+       chashdatum key;
+
+       key.data = &folder;
+       key.len = sizeof(folder);
+       chash_delete(session_hash, &key, NULL);
+
+       if (!imap)
+               return;
+       key.data = &imap;
+       key.len = sizeof(imap);
+       chash_delete(courier_workaround_hash, &key, NULL);
+       /* We can't just free imap here as there may be ops on it pending
+        * in the thread. Posting freeing as an op will synchronize against
+        * existing jobs and as imap is already removed from session_hash
+        * we are sure no new ops can be posted. */
+       threaded_delete_imap(folder, imap);
+}
+
 static void connect_run(struct etpan_thread_op * op)
 {
        int r;
@@ -476,14 +595,14 @@ static void connect_run(struct etpan_thread_op * op)
        
        CHECK_IMAP();
 
-       r = mailimap_socket_connect(param->imap,
-                                   param->server, param->port);
+       r = do_mailimap_socket_connect(param->imap,
+                                   param->server, param->port, param->proxy_info);
        
        result->error = r;
 }
 
 
-int imap_threaded_connect(Folder * folder, const char * server, int port)
+int imap_threaded_connect(Folder * folder, const char * server, int port, ProxyInfo *proxy_info)
 {
        struct connect_param param;
        struct connect_result result;
@@ -505,124 +624,20 @@ int imap_threaded_connect(Folder * folder, const char * server, int port)
        value.data = imap;
        value.len = 0;
        chash_set(session_hash, &key, &value, NULL);
-       
+
        param.imap = imap;
        param.server = server;
        param.port = port;
-       
+       param.proxy_info = proxy_info;
+
        refresh_resolvers();
        threaded_run(folder, &param, &result, connect_run);
-       
+
        debug_print("connect ok %i with imap %p\n", result.error, imap);
-       
-       return result.error;
-}
 
-static int etpan_certificate_check(const unsigned char *certificate, int len, void *data)
-{
-#ifdef USE_OPENSSL
-       struct connect_param *param = (struct connect_param *)data;
-       X509 *cert = NULL;
-       
-       if (certificate == NULL || len < 0) {
-               g_warning("no cert presented.\n");
-               return 0;
-       }
-       cert = d2i_X509(NULL, (const unsigned char **)&certificate, len);
-       if (cert == NULL) {
-               g_warning("IMAP: can't get cert\n");
-               return 0;
-       } else if (ssl_certificate_check(cert, NULL,
-               (gchar *)param->server, (gushort)param->port) == TRUE) {
-               X509_free(cert);
-               return 0;
-       } else {
-               X509_free(cert);
-               return -1;
-       }
-#elif USE_GNUTLS
-       struct connect_param *param = (struct connect_param *)data;
-       gnutls_x509_crt cert = NULL;
-       gnutls_datum tmp;
-       
-       if (certificate == NULL || len < 0) {
-               g_warning("no cert presented.\n");
-               return 0;
-       }
-       
-       tmp.data = malloc(len);
-       memcpy(tmp.data, certificate, len);
-       tmp.size = len;
-       gnutls_x509_crt_init(&cert);
-       if (gnutls_x509_crt_import(cert, &tmp, GNUTLS_X509_FMT_DER) < 0) {
-               g_warning("IMAP: can't get cert\n");
-               return 0;
-       } else if (ssl_certificate_check(cert, (guint)-1, NULL,
-               (gchar *)param->server, (gushort)param->port) == TRUE) {
-               gnutls_x509_crt_deinit(cert);
-               return 0;
-       } else {
-               gnutls_x509_crt_deinit(cert);
-               return -1;
-       }
-#endif
-       return 0;
+       return result.error;
 }
-
-static void connect_ssl_context_cb(struct mailstream_ssl_context * ssl_context, void * data)
-{
-#if (defined(USE_OPENSSL) || defined(USE_GNUTLS))
-       PrefsAccount *account = (PrefsAccount *)data;
-       const gchar *cert_path = NULL;
-       const gchar *password = NULL;
-#ifdef USE_OPENSSL
-       X509 *x509 = NULL;
-       EVP_PKEY *pkey = NULL;
-#else
-       gnutls_x509_crt x509 = NULL;
-       gnutls_x509_privkey pkey = NULL;
-#endif
-
-       if (account->in_ssl_client_cert_file && *account->in_ssl_client_cert_file)
-               cert_path = account->in_ssl_client_cert_file;
-       if (account->in_ssl_client_cert_pass && *account->in_ssl_client_cert_pass)
-               password = account->in_ssl_client_cert_pass;
-       
-       if (mailstream_ssl_set_client_certificate_data(ssl_context, NULL, 0) < 0 ||
-           mailstream_ssl_set_client_private_key_data(ssl_context, NULL, 0) < 0)
-               debug_print("Impossible to set the client certificate.\n");
-       x509 = ssl_certificate_get_x509_from_pem_file(cert_path);
-       pkey = ssl_certificate_get_pkey_from_pem_file(cert_path);
-       if (!(x509 && pkey)) {
-               /* try pkcs12 format */
-               ssl_certificate_get_x509_and_pkey_from_p12_file(cert_path, password, &x509, &pkey);
-       }
-       if (x509 && pkey) {
-               unsigned char *x509_der = NULL, *pkey_der = NULL;
-               size_t x509_len, pkey_len;
-               
-#ifndef USE_GNUTLS
-               x509_len = (size_t)i2d_X509(x509, &x509_der);
-               pkey_len = (size_t)i2d_PrivateKey(pkey, &pkey_der);
-#else
-               x509_len = (size_t)gnutls_i2d_X509(x509, &x509_der);
-               pkey_len = (size_t)gnutls_i2d_PrivateKey(pkey, &pkey_der);
-#endif
-               if (x509_len > 0 && pkey_len > 0) {
-                       if (mailstream_ssl_set_client_certificate_data(ssl_context, x509_der, x509_len) < 0 ||
-                           mailstream_ssl_set_client_private_key_data(ssl_context, pkey_der, pkey_len) < 0) 
-                               log_error(LOG_PROTOCOL, "Impossible to set the client certificate.\n");
-                       g_free(x509_der);
-                       g_free(pkey_der);
-               }
 #ifdef USE_GNUTLS
-               gnutls_x509_crt_deinit(x509);
-               gnutls_x509_privkey_deinit(pkey);
-#endif
-       }
-#endif
-}
-
 static void connect_ssl_run(struct etpan_thread_op * op)
 {
        int r;
@@ -634,26 +649,26 @@ static void connect_ssl_run(struct etpan_thread_op * op)
        
        CHECK_IMAP();
 
-       r = mailimap_ssl_connect_with_callback(param->imap,
+       r = do_mailimap_ssl_connect_with_callback(param->imap,
                                                param->server, param->port,
-                                               connect_ssl_context_cb, param->account);
+                                               etpan_connect_ssl_context_cb, param->account,
+                                               param->proxy_info);
        result->error = r;
 }
 
-int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
+int imap_threaded_connect_ssl(Folder * folder, const char * server, int port, ProxyInfo *proxy_info)
 {
        struct connect_param param;
        struct connect_result result;
        chashdatum key;
        chashdatum value;
        mailimap * imap, * oldimap;
-       unsigned char *certificate = NULL;
-       int cert_len;
-       
+       gboolean accept_if_valid = FALSE;
+
        oldimap = get_imap(folder);
 
        imap = mailimap_new(0, NULL);
-       
+
        if (oldimap) {
                debug_print("deleting old imap %p\n", oldimap);
                delete_imap(folder, oldimap);
@@ -664,28 +679,31 @@ int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
        value.data = imap;
        value.len = 0;
        chash_set(session_hash, &key, &value, NULL);
-       
+
        param.imap = imap;
        param.server = server;
        param.port = port;
        param.account = folder->account;
+       param.proxy_info = proxy_info;
+
+       if (folder->account)
+               accept_if_valid = folder->account->ssl_certs_auto_accept;
 
        refresh_resolvers();
-       threaded_run(folder, &param, &result, connect_ssl_run);
+       if (threaded_run(folder, &param, &result, connect_ssl_run))
+               return MAILIMAP_ERROR_INVAL;
 
        if ((result.error == MAILIMAP_NO_ERROR_AUTHENTICATED ||
             result.error == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) && !etpan_skip_ssl_cert_check) {
-               cert_len = (int)mailstream_ssl_get_certificate(imap->imap_stream, &certificate);
-               if (etpan_certificate_check(certificate, cert_len, &param) < 0)
-                       return -1;
-               if (certificate) 
-                       free(certificate); 
+               if (etpan_certificate_check(imap->imap_stream, server, port,
+                                           accept_if_valid) != TRUE)
+                       result.error = MAILIMAP_ERROR_SSL;
        }
        debug_print("connect %d with imap %p\n", result.error, imap);
-       
+
        return result.error;
 }
-
+#endif
 struct capa_param {
        mailimap * imap;
 };
@@ -714,7 +732,7 @@ static void capability_run(struct etpan_thread_op * op)
 }
 
 
-struct mailimap_capability_data * imap_threaded_capability(Folder *folder, int *ok)
+int imap_threaded_capability(Folder *folder, struct mailimap_capability_data ** caps)
 {
        struct capa_param param;
        struct capa_result result;
@@ -728,10 +746,10 @@ struct mailimap_capability_data * imap_threaded_capability(Folder *folder, int *
        
        debug_print("capa %d\n", result.error);
        
-       if (ok)
-               *ok = result.error;
+       if (result.error == MAILIMAP_NO_ERROR)
+               *caps = result.caps;
 
-       return result.caps;
+       return result.error;
        
 }
        
@@ -773,13 +791,11 @@ void imap_threaded_disconnect(Folder * folder)
        
        param.imap = imap;
        
-       threaded_run(folder, &param, &result, disconnect_run);
-       
-       if (imap == get_imap(folder)) {
+       if (threaded_run(folder, &param, &result, disconnect_run)) {
+               debug_print("imap already deleted %p\n", imap);
+       } else {
                debug_print("deleting old imap %p\n", imap);
                delete_imap(folder, imap);
-       } else {
-               debug_print("imap already deleted %p\n", imap);
        }
        
        debug_print("disconnect ok\n");
@@ -956,7 +972,7 @@ static void login_run(struct etpan_thread_op * op)
        old_debug = mailstream_debug;
        mailstream_debug = 0;
 #endif
-       if (!strcmp(param->type, "LOGIN"))
+       if (!strcmp(param->type, "plaintext"))
                r = mailimap_login(param->imap,
                           param->login, param->password);
        else if (!strcmp(param->type, "GSSAPI"))
@@ -964,7 +980,16 @@ static void login_run(struct etpan_thread_op * op)
                        param->type, param->server, NULL, NULL,
                        param->login, param->login,
                        param->password, NULL);
-       else 
+       else if (!strcmp(param->type, "SCRAM-SHA-1"))
+               /* 7th argument has to be NULL here, to stop libetpan sending the
+                * a= attribute in its initial SCRAM-SHA-1 message to server. At least
+                * Dovecot 2.2 doesn't seem to like that, and will not authenticate
+                * successfully. */
+               r = mailimap_authenticate(param->imap,
+                       param->type, NULL, NULL, NULL,
+                       NULL, param->login,
+                       param->password, NULL);
+       else
                r = mailimap_authenticate(param->imap,
                        param->type, NULL, NULL, NULL,
                        param->login, param->login,
@@ -988,6 +1013,9 @@ int imap_threaded_login(Folder * folder,
        
        debug_print("imap login - begin\n");
        
+       if (!folder)
+               return MAILIMAP_ERROR_INVAL;
+
        param.imap = get_imap(folder);
        param.login = login;
        param.password = password;
@@ -1124,8 +1152,9 @@ int imap_threaded_noop(Folder * folder, unsigned int * p_exists,
        imap = get_imap(folder);
        param.imap = imap;
 
-       threaded_run(folder, &param, &result, noop_run);
-       
+       if (threaded_run(folder, &param, &result, noop_run))
+               return MAILIMAP_ERROR_INVAL;
+
        if (result.error == 0 && imap && imap->imap_selection_info != NULL) {
                * p_exists = imap->imap_selection_info->sel_exists;
                * p_recent = imap->imap_selection_info->sel_recent;
@@ -1152,7 +1181,7 @@ int imap_threaded_noop(Folder * folder, unsigned int * p_exists,
        return result.error;
 }
 
-
+#ifdef USE_GNUTLS
 struct starttls_result {
        int error;
 };
@@ -1171,7 +1200,7 @@ static void starttls_run(struct etpan_thread_op * op)
        r = mailimap_starttls(param->imap);
        
        result->error = r;
-       debug_print("imap starttls run - end %i\n", r);
+       debug_print("imap STARTTLS run - end %i\n", r);
        
        if (r == 0) {
                mailimap *imap = param->imap;
@@ -1182,14 +1211,14 @@ static void starttls_run(struct etpan_thread_op * op)
                plain_low = mailstream_get_low(imap->imap_stream);
                fd = mailstream_low_get_fd(plain_low);
                if (fd == -1) {
-                       debug_print("imap starttls run - can't get fd\n");
+                       debug_print("imap STARTTLS run - can't get fd\n");
                        result->error = MAILIMAP_ERROR_STREAM;
                        return;
                }
 
-               tls_low = mailstream_low_tls_open_with_callback(fd, connect_ssl_context_cb, param->account);
+               tls_low = mailstream_low_tls_open_with_callback(fd, etpan_connect_ssl_context_cb, param->account);
                if (tls_low == NULL) {
-                       debug_print("imap starttls run - can't tls_open\n");
+                       debug_print("imap STARTTLS run - can't tls_open\n");
                        result->error = MAILIMAP_ERROR_STREAM;
                        return;
                }
@@ -1202,31 +1231,31 @@ int imap_threaded_starttls(Folder * folder, const gchar *host, int port)
 {
        struct connect_param param;
        struct starttls_result result;
-       int cert_len;
-       unsigned char *certificate;
-       
-       debug_print("imap starttls - begin\n");
-       
+       gboolean accept_if_valid = FALSE;
+
+       debug_print("imap STARTTLS - begin\n");
+
        param.imap = get_imap(folder);
        param.server = host;
        param.port = port;
        param.account = folder->account;
 
-       threaded_run(folder, &param, &result, starttls_run);
-       
-       debug_print("imap starttls - end\n");
+       if (folder->account)
+               accept_if_valid = folder->account->ssl_certs_auto_accept;
+
+       if (threaded_run(folder, &param, &result, starttls_run))
+               return MAILIMAP_ERROR_INVAL;
+
+       debug_print("imap STARTTLS - end\n");
 
        if (result.error == 0 && param.imap && !etpan_skip_ssl_cert_check) {
-               cert_len = (int)mailstream_ssl_get_certificate(param.imap->imap_stream, &certificate);
-               if (etpan_certificate_check(certificate, cert_len, &param) < 0)
-                       result.error = MAILIMAP_ERROR_STREAM;
-               if (certificate) 
-                       free(certificate); 
+               if (etpan_certificate_check(param.imap->imap_stream, host, port,
+                                           accept_if_valid) != TRUE)
+                       return MAILIMAP_ERROR_SSL;
        }       
        return result.error;
 }
-
-
+#endif
 
 struct create_param {
        mailimap * imap;
@@ -1409,8 +1438,9 @@ int imap_threaded_select(Folder * folder, const char * mb,
        param.imap = imap;
        param.mb = mb;
        
-       threaded_run(folder, &param, &result, select_run);
-       
+       if (threaded_run(folder, &param, &result, select_run))
+               return MAILIMAP_ERROR_INVAL;
+
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
@@ -1456,13 +1486,13 @@ int imap_threaded_select(Folder * folder, const char * mb,
                                        c_flag = IMAP_FLAG_SEEN;
                                        break;
                                case MAILIMAP_FLAG_KEYWORD:
-                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, "$Forwarded"))
+                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_FORWARDED))
                                                c_flag = IMAP_FLAG_FORWARDED;
-                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, "Junk"))
+                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_JUNK))
                                                c_flag = IMAP_FLAG_SPAM;
-                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, "NonJunk") ||
-                                           !strcasecmp(flag->fl_flag->fl_data.fl_keyword, "NoJunk") ||
-                                           !strcasecmp(flag->fl_flag->fl_data.fl_keyword, "NotJunk"))
+                                       if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NON_JUNK) ||
+                                           !strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NO_JUNK) ||
+                                           !strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NOT_JUNK))
                                                c_flag = IMAP_FLAG_HAM;
                                        break;
                                default:
@@ -1560,8 +1590,9 @@ int imap_threaded_examine(Folder * folder, const char * mb,
        param.imap = imap;
        param.mb = mb;
        
-       threaded_run(folder, &param, &result, examine_run);
-       
+       if (threaded_run(folder, &param, &result, examine_run))
+               return MAILIMAP_ERROR_INVAL;
+
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
@@ -1584,7 +1615,9 @@ int imap_threaded_examine(Folder * folder, const char * mb,
 struct search_param {
        mailimap * imap;
        int type;
+       const char *charset;
        struct mailimap_set * set;
+       IMAPSearchKey* key;
 };
 
 struct search_result {
@@ -1600,15 +1633,24 @@ static struct mailimap_set_item *sc_mailimap_set_item_copy(struct mailimap_set_i
 static struct mailimap_set *sc_mailimap_set_copy(struct mailimap_set *orig)
 {
        clist *list = orig ? orig->set_list : NULL;
-       clist *newlist = clist_new();
+       clist *newlist;
        clistiter *cur;
-       
+
        if (!orig)
                return NULL;
-       for (cur = clist_begin(list); cur; cur = clist_next(cur))
-               clist_append(newlist, 
+
+       newlist = clist_new();
+       if (!newlist)
+               return NULL;
+
+       for (cur = clist_begin(list); cur; cur = clist_next(cur)) {
+               if (clist_append(newlist,
                        sc_mailimap_set_item_copy(
-                       (struct mailimap_set_item *)clist_content(cur)));
+                       (struct mailimap_set_item *)clist_content(cur))) != 0) {
+                       clist_free(newlist);
+                       return NULL;
+               }
+       }
        return mailimap_set_new(newlist);
 }
 
@@ -1619,9 +1661,9 @@ static void search_run(struct etpan_thread_op * op)
        int r;
        struct mailimap_search_key * key = NULL;
        struct mailimap_search_key * uid_key = NULL;
-       struct mailimap_search_key * search_type_key;
+       struct mailimap_search_key * search_type_key = NULL;
        clist * search_result;
-       
+
        param = op->param;
        result = op->result;
 
@@ -1633,70 +1675,33 @@ static void search_run(struct etpan_thread_op * op)
        } else if (param->type == IMAP_SEARCH_TYPE_SIMPLE) {
                uid_key = mailimap_search_key_new_all();
        }
-       search_type_key = NULL;
        switch (param->type) {
        case IMAP_SEARCH_TYPE_SIMPLE:
                search_type_key = NULL;
                break;
-               
        case IMAP_SEARCH_TYPE_SEEN:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_SEEN,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
                break;
-               
        case IMAP_SEARCH_TYPE_UNSEEN:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNSEEN,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
                break;
-               
        case IMAP_SEARCH_TYPE_ANSWERED:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_ANSWERED,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
                break;
-               
        case IMAP_SEARCH_TYPE_FLAGGED:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_FLAGGED,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
                break;
        case IMAP_SEARCH_TYPE_DELETED:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_DELETED,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
                break;
        case IMAP_SEARCH_TYPE_FORWARDED:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_KEYWORD,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         strdup("$Forwarded"), NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
                break;
        case IMAP_SEARCH_TYPE_SPAM:
-               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_KEYWORD,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         strdup("Junk"), NULL, NULL, NULL, NULL,
-                                                         NULL, NULL, NULL, NULL, 0,
-                                                         NULL, NULL, NULL, NULL, NULL,
-                                                         NULL, 0, NULL, NULL, NULL);
+               search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
+               break;
+       case IMAP_SEARCH_TYPE_KEYED:
+               search_type_key = param->key;
                break;
        }
        
@@ -1720,7 +1725,7 @@ static void search_run(struct etpan_thread_op * op)
        } else {
                mailstream_logger = imap_logger_uid;
 
-               r = mailimap_uid_search(param->imap, NULL, key, &search_result);
+               r = mailimap_uid_search(param->imap, param->charset, key, &search_result);
 
                mailstream_logger = imap_logger_cmd;
 
@@ -1733,8 +1738,9 @@ static void search_run(struct etpan_thread_op * op)
        debug_print("imap search run - end %i\n", result->error);
 }
 
-int imap_threaded_search(Folder * folder, int search_type,
-                        struct mailimap_set * set, clist ** search_result)
+int imap_threaded_search(Folder * folder, int search_type, IMAPSearchKey* key,
+                        const char *charset, struct mailimap_set * set,
+                        clist ** search_result)
 {
        struct search_param param;
        struct search_result result;
@@ -1745,8 +1751,10 @@ int imap_threaded_search(Folder * folder, int search_type,
        imap = get_imap(folder);
        param.imap = imap;
        param.set = set;
+       param.charset = charset;
        param.type = search_type;
-       
+       param.key = key;
+
        threaded_run(folder, &param, &result, search_run);
        
        if (result.error != MAILIMAP_NO_ERROR)
@@ -1760,6 +1768,160 @@ int imap_threaded_search(Folder * folder, int search_type,
 }
 
 
+struct _IMAPSearchKey {
+       struct mailimap_search_key* key;
+};
+
+IMAPSearchKey* imap_search_new(gint             criteria, 
+                               const gchar     *header,
+                               const gchar     *expr,
+                               int              value)
+{
+       char* sk_bcc = NULL;
+       struct mailimap_date* sk_before = NULL;
+       char* sk_body = NULL;
+       char* sk_cc = NULL;
+       char* sk_from = NULL;
+       char* sk_keyword = NULL;
+       struct mailimap_date* sk_on = NULL;
+       struct mailimap_date* sk_since = NULL;
+       char* sk_subject = NULL;
+       char* sk_text = NULL;
+       char* sk_to = NULL;
+       char* sk_unkeyword = NULL;
+       char* sk_header_name = NULL;
+       char* sk_header_value = NULL;
+       uint32_t sk_larger = 0;
+       struct mailimap_search_key* sk_not = NULL;
+       struct mailimap_search_key* sk_or1 = NULL;
+       struct mailimap_search_key* sk_or2 = NULL;
+       struct mailimap_date* sk_sentbefore = NULL;
+       struct mailimap_date* sk_senton = NULL;
+       struct mailimap_date* sk_sentsince = NULL;
+       uint32_t sk_smaller = 0;
+       struct mailimap_set* sk_uid = NULL;
+       struct mailimap_set* sk_set = NULL;
+       clist* sk_multiple = NULL;
+       int etpan_matcher_type;
+
+       switch (criteria) {
+       case IMAP_SEARCH_CRITERIA_ALL: etpan_matcher_type = MAILIMAP_SEARCH_KEY_ALL; break;
+       case IMAP_SEARCH_CRITERIA_READ: etpan_matcher_type = MAILIMAP_SEARCH_KEY_SEEN; break;
+       case IMAP_SEARCH_CRITERIA_UNREAD: etpan_matcher_type = MAILIMAP_SEARCH_KEY_UNSEEN; break;
+       case IMAP_SEARCH_CRITERIA_NEW: etpan_matcher_type = MAILIMAP_SEARCH_KEY_NEW; break;
+       case IMAP_SEARCH_CRITERIA_MARKED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_FLAGGED; break;
+       case IMAP_SEARCH_CRITERIA_REPLIED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_ANSWERED; break;
+       case IMAP_SEARCH_CRITERIA_DELETED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_DELETED; break;
+
+       case IMAP_SEARCH_CRITERIA_TAG:
+               sk_keyword = strdup(expr);
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_KEYWORD;
+               break;
+
+       case IMAP_SEARCH_CRITERIA_SUBJECT:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_SUBJECT;
+               sk_subject = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_TO:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_TO;
+               sk_to = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_CC:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_CC;
+               sk_cc = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_AGE_GREATER:
+       case IMAP_SEARCH_CRITERIA_AGE_LOWER:
+               {
+                       struct tm tm;
+                       time_t limit = time(NULL) - 60 * 60 * 24 * value;
+
+                       tzset();
+                       localtime_r(&limit, &tm);
+                       if (criteria == IMAP_SEARCH_CRITERIA_AGE_GREATER) {
+                               etpan_matcher_type = MAILIMAP_SEARCH_KEY_SENTBEFORE;
+                               sk_sentbefore = mailimap_date_new(tm.tm_mday, tm.tm_mon, tm.tm_year + 1900);
+                       } else {
+                               etpan_matcher_type = MAILIMAP_SEARCH_KEY_SENTSINCE;
+                               sk_sentsince = mailimap_date_new(tm.tm_mday, tm.tm_mon, tm.tm_year + 1900);
+                       }
+                       break;
+               }
+
+       case IMAP_SEARCH_CRITERIA_BODY:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_BODY;
+               sk_body = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_MESSAGE:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_TEXT;
+               sk_text = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_HEADER:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_HEADER;
+               sk_header_name = strdup(header);
+               sk_header_value = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_FROM:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_FROM;
+               sk_from = strdup(expr);
+               break;
+
+       case IMAP_SEARCH_CRITERIA_SIZE_GREATER:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_LARGER;
+               sk_larger = value;
+               break;
+
+       case IMAP_SEARCH_CRITERIA_SIZE_SMALLER:
+               etpan_matcher_type = MAILIMAP_SEARCH_KEY_SMALLER;
+               sk_smaller = value;
+               break;
+
+       default:
+               return NULL;
+       }
+
+       return mailimap_search_key_new(etpan_matcher_type,
+               sk_bcc, sk_before, sk_body, sk_cc, sk_from, sk_keyword,
+               sk_on, sk_since, sk_subject, sk_text, sk_to,
+               sk_unkeyword, sk_header_name,sk_header_value, sk_larger,
+               sk_not, sk_or1, sk_or2, sk_sentbefore, sk_senton,
+               sk_sentsince, sk_smaller, sk_uid, sk_set, sk_multiple);
+}
+
+IMAPSearchKey* imap_search_not(IMAPSearchKey* key)
+{
+       return mailimap_search_key_new_not(key);
+}
+
+IMAPSearchKey* imap_search_or(IMAPSearchKey* l, IMAPSearchKey* r)
+{
+       return mailimap_search_key_new_or(l, r);
+}
+
+IMAPSearchKey* imap_search_and(IMAPSearchKey* l, IMAPSearchKey* r)
+{
+       IMAPSearchKey* result = mailimap_search_key_new_multiple_empty();
+       mailimap_search_key_multiple_add(result, l);
+       mailimap_search_key_multiple_add(result, r);
+
+       return result;
+}
+
+void imap_search_free(IMAPSearchKey* key)
+{
+       if (!key)
+           return;
+
+       mailimap_search_key_free(key);
+}
+
+
 
 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
                                 uint32_t * puid,
@@ -1913,7 +2075,7 @@ static void fetch_uid_run(struct etpan_thread_op * op)
 
        fetch_result = NULL;
        mailstream_logger = imap_logger_noop;
-       log_print(LOG_PROTOCOL, "IMAP4- [fetching UIDs...]\n");
+       log_print(LOG_PROTOCOL, "IMAP- [fetching UIDs...]\n");
 
        r = imap_get_messages_list(param->imap, param->first_index,
                                   &fetch_result);
@@ -2048,8 +2210,7 @@ result_to_uid_flags_list(clist * fetch_result, carray ** result)
   
  free_list:
        imap_fetch_uid_flags_list_free(tab);
-       slist_free_strings(tags);
-       g_slist_free(tags);
+       slist_free_strings_full(tags);
  err:
        return res;
 }
@@ -2171,7 +2332,7 @@ int imap_threaded_fetch_uid_flags(Folder * folder, uint32_t first_index,
        param.first_index = first_index;
        
        mailstream_logger = imap_logger_noop;
-       log_print(LOG_PROTOCOL, "IMAP4- [fetching flags...]\n");
+       log_print(LOG_PROTOCOL, "IMAP- [fetching flags...]\n");
 
        threaded_run(folder, &param, &result, fetch_uid_flags_run);
 
@@ -2465,27 +2626,27 @@ static void fetch_content_run(struct etpan_thread_op * op)
                        goto free;
                }
                
-               f = fdopen(fd, "wb");
+               f = claws_fdopen(fd, "wb");
                if (f == NULL) {
                        result->error = MAILIMAP_ERROR_FETCH;
                        goto close;
                }
                
-               r = fwrite(content, 1, content_size, f);
+               r = claws_fwrite(content, 1, content_size, f);
                if (r < content_size) {
                        result->error = MAILIMAP_ERROR_FETCH;
-                       goto fclose;
+                       goto do_fclose;
                }
                
-               r = fclose(f);
+               r = claws_safe_fclose(f);
                if (r == EOF) {
                        result->error = MAILIMAP_ERROR_FETCH;
                        goto unlink;
                }
                goto free;
                
-       fclose:
-               fclose(f);
+       do_fclose:
+               claws_fclose(f);
                goto unlink;
        close:
                close(fd);
@@ -2566,13 +2727,13 @@ static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, GSList
                                flags &= ~MSG_NEW;
                                break;
                        case MAILIMAP_FLAG_KEYWORD:
-                               if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "$Forwarded"))
+                               if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_FORWARDED))
                                        flags |= MSG_FORWARDED;
-                               else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "Junk")) 
+                               else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_JUNK)) 
                                        flags |= MSG_SPAM;
-                               else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "NonJunk") ||
-                                        !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "NoJunk") ||
-                                        !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "NotJunk")) 
+                               else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NON_JUNK) ||
+                                        !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NO_JUNK) ||
+                                        !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NOT_JUNK)) 
                                        flags &= ~MSG_SPAM;
                                else if (s_tags)
                                        tags = g_slist_prepend(tags, g_strdup(flag_fetch->fl_flag->fl_data.fl_keyword));
@@ -2677,13 +2838,11 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
                                  carray ** p_env_list)
 {
        clistiter * cur;
-       unsigned int i;
-       carray * env_list;
 
-       i = 0;
-       env_list = carray_new(16);
-  
        if (fetch_result) {
+               carray * env_list;
+               env_list = carray_new(16);
+
                for(cur = clist_begin(fetch_result) ; cur != NULL ;
                    cur = clist_next(cur)) {
                        struct mailimap_msg_att * msg_att;
@@ -2693,10 +2852,12 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
                        msg_att = clist_content(cur);
 
                        env_info = fetch_to_env_info(msg_att, &tags);
-                       if (!env_info)
+                       if (!env_info
+                        || carray_add(env_list, env_info, NULL) != 0
+                        || carray_add(env_list, tags, NULL) != 0) {
+                               carray_free(env_list);
                                return MAILIMAP_ERROR_MEMORY;
-                       carray_add(env_list, env_info, NULL);
-                       carray_add(env_list, tags, NULL);
+                       }
                }
                * p_env_list = env_list;
        } else {
@@ -2709,36 +2870,34 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
 static int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
 {
        struct mailimap_fetch_att * fetch_att;
-       int r;
+       int i;
        char * header;
        clist * hdrlist;
        struct mailimap_header_list * imap_hdrlist;
        struct mailimap_section * section;
+       char *headers[] = {
+                       "Date", "From", "To", "Cc", "Subject", "Message-ID",
+                       "References", "In-Reply-To", NULL
+               };
 
        hdrlist = clist_new();
-  
-       header = strdup("Date");
-       r = clist_append(hdrlist, header);
-       header = strdup("From");
-       r = clist_append(hdrlist, header);
-       header = strdup("To");
-       r = clist_append(hdrlist, header);
-       header = strdup("Cc");
-       r = clist_append(hdrlist, header);
-       header = strdup("Subject");
-       r = clist_append(hdrlist, header);
-       header = strdup("Message-ID");
-       r = clist_append(hdrlist, header);
-       header = strdup("References");
-       r = clist_append(hdrlist, header);
-       header = strdup("In-Reply-To");
-       r = clist_append(hdrlist, header);
-  
+       if (!hdrlist)
+               return MAIL_ERROR_MEMORY;
+       i = 0;
+       while (headers[i] != NULL) {
+               header = strdup(headers[i]);
+               if (header == NULL || clist_append(hdrlist, header) != 0) {
+                       clist_free(hdrlist);
+                       return MAIL_ERROR_MEMORY;
+               }
+               ++i;
+       }
+
        imap_hdrlist = mailimap_header_list_new(hdrlist);
        section = mailimap_section_new_header_fields(imap_hdrlist);
        fetch_att = mailimap_fetch_att_new_body_peek_section(section);
        mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
-  
+
        return MAIL_NO_ERROR;
 }
 
@@ -2789,7 +2948,12 @@ imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
                r = imap_add_envelope_fetch_att(fetch_type);
        else
                r = imap_add_header_fetch_att(fetch_type);
-       
+
+       if (r != MAILIMAP_NO_ERROR) {
+               debug_print("add fetch attr: %d\n", r);
+               return r;
+       }
+
        mailstream_logger = imap_logger_fetch;
        
        r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
@@ -2875,8 +3039,9 @@ int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
        param.imap = imap;
        param.set = set;
        
-       threaded_run(folder, &param, &result, fetch_env_run);
-       
+       if (threaded_run(folder, &param, &result, fetch_env_run))
+               return MAILIMAP_ERROR_INVAL;
+
        if (result.error != MAILIMAP_NO_ERROR) {
                chashdatum key;
                chashdatum value;
@@ -3398,7 +3563,7 @@ void imap_threaded_cancel(Folder * folder)
 void imap_main_init(void)
 {
 }
-void imap_main_done(void)
+void imap_main_done(gboolean have_connectivity)
 {
 }
 void imap_main_set_timeout(int sec)