2007-08-19 [colin] 2.10.0cvs133
[claws.git] / src / etpan / imap-thread.c
index 45ae45e00f3fb500ef68c980b2b9ba9b7153676f..c65eaf21fc0462fbe7e55e6d994b13f6dd2902b5 100644 (file)
@@ -1,20 +1,79 @@
-#include "imap-thread.h"
+/*
+ * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
+ * Copyright (C) 2005-2007 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * 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"
+#endif
 
+#ifdef HAVE_LIBETPAN
+
+#include "imap-thread.h"
+#include <imap.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#if (defined(__DragonFly__) || defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__CYGWIN__))
+#include <sys/socket.h>
+#endif
 #include <fcntl.h>
 #include <sys/mman.h>
 #include <sys/wait.h>
 
 #include <gtk/gtk.h>
+#include <log.h>
 #include "etpan-thread-manager.h"
+#include "utils.h"
+#include "mainwindow.h"
+#include "ssl_certificate.h"
+#include "socket.h"
+#include "remotefolder.h"
+
+#define DISABLE_LOG_DURING_LOGIN
 
 static struct etpan_thread_manager * thread_manager = NULL;
+static chash * courier_workaround_hash = NULL;
 static chash * imap_hash = NULL;
 static chash * session_hash = NULL;
 static guint thread_manager_signal = 0;
 static GIOChannel * io_channel = NULL;
 
+static void delete_imap(Folder *folder, mailimap *imap)
+{
+       chashdatum key;
+       chashdatum value;
+
+       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;
+       }
+       debug_print("removing mailimap %p\n", imap);
+       mailimap_free(imap);    
+}
 
 static gboolean thread_manager_event(GIOChannel * source,
     GIOCondition condition,
@@ -25,21 +84,182 @@ static gboolean thread_manager_event(GIOChannel * source,
        return TRUE;
 }
 
+static void imap_logger_cmd(int direction, const char * str, size_t size) 
+{
+       gchar *buf;
+       gchar **lines;
+       int i = 0;
+
+       if (size > 8192) {
+               log_print(LOG_PROTOCOL, "IMAP4%c [CMD data - %zd bytes]\n", direction?'>':'<', size);
+               return;
+       }
+       buf = malloc(size+1);
+       memset(buf, 0, size+1);
+       strncpy(buf, str, size);
+       buf[size] = '\0';
+
+       if (!strncmp(buf, "<<<<<<<", 7) 
+       ||  !strncmp(buf, ">>>>>>>", 7)) {
+               free(buf);
+               return;
+       }
+       while (strstr(buf, "\r"))
+               *strstr(buf, "\r") = ' ';
+       while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
+               buf[strlen(buf)-1] = '\0';
+
+       lines = g_strsplit(buf, "\n", -1);
+
+       while (lines[i] && *lines[i]) {
+               log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+               i++;
+       }
+       g_strfreev(lines);
+       free(buf);
+}
+
+static void imap_logger_fetch(int direction, const char * str, size_t size) 
+{
+       gchar *buf;
+       gchar **lines;
+       int i = 0;
+
+       if (size > 128 && !direction) {
+               log_print(LOG_PROTOCOL, "IMAP4%c [FETCH data - %zd bytes]\n", direction?'>':'<', size);
+               return;
+       }
+       
+       buf = malloc(size+1);
+       memset(buf, 0, size+1);
+       strncpy(buf, str, size);
+       buf[size] = '\0';
+       if (!strncmp(buf, "<<<<<<<", 7) 
+       ||  !strncmp(buf, ">>>>>>>", 7)) {
+               free(buf);
+               return;
+       }
+       while (strstr(buf, "\r"))
+               *strstr(buf, "\r") = ' ';
+       while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
+               buf[strlen(buf)-1] = '\0';
+
+       lines = g_strsplit(buf, "\n", -1);
+
+       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]);
+                       i++;
+               }
+       } else {
+               log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
+       }
+       g_strfreev(lines);
+       free(buf);
+}
+
+static void imap_logger_uid(int direction, const char * str, size_t size) 
+{
+       gchar *buf;
+       gchar **lines;
+       int i = 0;
+
+       if (size > 8192) {
+               log_print(LOG_PROTOCOL, "IMAP4%c [UID data - %zd bytes]\n", direction?'>':'<', size);
+               return;
+       }
+       buf = malloc(size+1);
+       memset(buf, 0, size+1);
+       strncpy(buf, str, size);
+       buf[size] = '\0';
+       if (!strncmp(buf, "<<<<<<<", 7) 
+       ||  !strncmp(buf, ">>>>>>>", 7)) {
+               free(buf);
+               return;
+       }
+       while (strstr(buf, "\r"))
+               *strstr(buf, "\r") = ' ';
+       while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
+               buf[strlen(buf)-1] = '\0';
+
+       lines = g_strsplit(buf, "\n", -1);
+
+       while (lines[i] && *lines[i]) {
+               int llen = strlen(lines[i]);
+               if (llen < 64)
+                       log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
+               else {
+                       gchar tmp[64];
+                       strncpy2(tmp, lines[i], 63);
+                       log_print(LOG_PROTOCOL, "IMAP4%c %s[... - %zd bytes more]\n", direction?'>':'<', tmp,
+                                 llen-64);
+               }
+               i++;
+       }
+       g_strfreev(lines);
+       free(buf);
+}
+
+static void imap_logger_append(int direction, const char * str, size_t size) 
+{
+       gchar *buf;
+       gchar **lines;
+       int i = 0;
+
+       if (size > 8192) {
+               log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
+               return;
+       } else if (direction == 0 && size > 64) {
+               log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
+               return;
+       } 
+       buf = malloc(size+1);
+       memset(buf, 0, size+1);
+       strncpy(buf, str, size);
+       buf[size] = '\0';
+       if (!strncmp(buf, "<<<<<<<", 7) 
+       ||  !strncmp(buf, ">>>>>>>", 7)) {
+               free(buf);
+               return;
+       }
+       while (strstr(buf, "\r"))
+               *strstr(buf, "\r") = ' ';
+       while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
+               buf[strlen(buf)-1] = '\0';
+
+       lines = g_strsplit(buf, "\n", -1);
+
+       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]);
+                       i++;
+               }
+       } else {
+               log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
+       }
+       g_strfreev(lines);
+       free(buf);
+}
 
 #define ETPAN_DEFAULT_NETWORK_TIMEOUT 60
+static gboolean etpan_skip_ssl_cert_check = FALSE;
+extern void mailsasl_ref(void);
 
-void imap_main_init(void)
+void imap_main_init(gboolean skip_ssl_cert_check)
 {
        int fd_thread_manager;
        
+       etpan_skip_ssl_cert_check = skip_ssl_cert_check;
        mailstream_network_delay.tv_sec = ETPAN_DEFAULT_NETWORK_TIMEOUT;
        mailstream_network_delay.tv_usec = 0;
-
-#if 0
+       
        mailstream_debug = 1;
-#endif
+       mailstream_logger = imap_logger_cmd;
+       mailsasl_ref();
+       
        imap_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
        session_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
+       courier_workaround_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
        
        thread_manager = etpan_thread_manager_new();
        
@@ -61,13 +281,15 @@ void imap_main_set_timeout(int sec)
 
 void imap_main_done(void)
 {
+       etpan_thread_manager_stop(thread_manager);
+       etpan_thread_manager_join(thread_manager);
+       
        g_source_remove(thread_manager_signal);
        g_io_channel_unref(io_channel);
        
-       etpan_thread_manager_stop(thread_manager);
-       etpan_thread_manager_join(thread_manager);
        etpan_thread_manager_free(thread_manager);
        
+       chash_free(courier_workaround_hash);
        chash_free(session_hash);
        chash_free(imap_hash);
 }
@@ -104,9 +326,11 @@ void imap_done(Folder * folder)
        
        thread = value.data;
        
-       etpan_thread_stop(thread);
+       etpan_thread_unbind(thread);
        
        chash_delete(imap_hash, &key, NULL);
+       
+       debug_print("remove thread");
 }
 
 static struct etpan_thread * get_thread(Folder * folder)
@@ -139,18 +363,25 @@ static mailimap * get_imap(Folder * folder)
                return NULL;
        
        imap = value.data;
-       
+       debug_print("found imap %p\n", imap);
        return imap;
 }
 
 
 static void generic_cb(int cancelled, void * result, void * callback_data)
 {
-       int * p_finished;
-       
-       p_finished = callback_data;
+       struct etpan_thread_op * op;
        
-       * p_finished = 1;
+       op = (struct etpan_thread_op *) 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", 
+                       op->imap->imap_response_info->rsp_alert);
+               mainwindow_show_error();
+       } 
+       op->finished = 1;
 }
 
 static void threaded_run(Folder * folder, void * param, void * result,
@@ -158,28 +389,33 @@ static void threaded_run(Folder * folder, void * param, void * result,
 {
        struct etpan_thread_op * op;
        struct etpan_thread * thread;
-       int finished;
        
+       imap_folder_ref(folder);
+
        op = etpan_thread_op_new();
+       
+       op->imap = get_imap(folder);
        op->param = param;
        op->result = result;
        
        op->cancellable = 0;
        op->run = func;
        op->callback = generic_cb;
-       op->callback_data = &finished;
+       op->callback_data = op;
        op->cleanup = NULL;
        
-       finished = 0;
+       op->finished = 0;
        
        thread = get_thread(folder);
        etpan_thread_op_schedule(thread, op);
        
-       while (!finished) {
+       while (!op->finished) {
                gtk_main_iteration();
        }
        
        etpan_thread_op_free(op);
+
+       imap_folder_unref(folder);
 }
 
 
@@ -195,6 +431,13 @@ struct connect_result {
        int error;
 };
 
+#define CHECK_IMAP() {                                         \
+       if (!param->imap) {                                     \
+               result->error = MAILIMAP_ERROR_BAD_STATE;       \
+               return;                                         \
+       }                                                       \
+}
+
 static void connect_run(struct etpan_thread_op * op)
 {
        int r;
@@ -204,6 +447,8 @@ static void connect_run(struct etpan_thread_op * op)
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = mailimap_socket_connect(param->imap,
                                    param->server, param->port);
        
@@ -217,10 +462,17 @@ int imap_threaded_connect(Folder * folder, const char * server, int port)
        struct connect_result result;
        chashdatum key;
        chashdatum value;
-       mailimap * imap;
+       mailimap * imap, * oldimap;
        
+       oldimap = get_imap(folder);
+
        imap = mailimap_new(0, NULL);
        
+       if (oldimap) {
+               debug_print("deleting old imap %p\n", oldimap);
+               delete_imap(folder, oldimap);
+       }
+       
        key.data = &folder;
        key.len = sizeof(folder);
        value.data = imap;
@@ -231,13 +483,40 @@ int imap_threaded_connect(Folder * folder, const char * server, int port)
        param.server = server;
        param.port = port;
        
+       refresh_resolvers();
        threaded_run(folder, &param, &result, connect_run);
        
-       debug_print("connect ok %i\n", result.error);
+       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, &certificate, len);
+       if (cert == NULL) {
+               g_warning("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;
+       }
+#else
+       return 0;
+#endif
+}
 
 static void connect_ssl_run(struct etpan_thread_op * op)
 {
@@ -248,9 +527,10 @@ static void connect_ssl_run(struct etpan_thread_op * op)
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = mailimap_ssl_connect(param->imap,
                                 param->server, param->port);
-       
        result->error = r;
 }
 
@@ -260,10 +540,19 @@ int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
        struct connect_result result;
        chashdatum key;
        chashdatum value;
-       mailimap * imap;
+       mailimap * imap, * oldimap;
+       unsigned char *certificate = NULL;
+       int cert_len;
        
+       oldimap = get_imap(folder);
+
        imap = mailimap_new(0, NULL);
        
+       if (oldimap) {
+               debug_print("deleting old imap %p\n", oldimap);
+               delete_imap(folder, oldimap);
+       }
+
        key.data = &folder;
        key.len = sizeof(folder);
        value.data = imap;
@@ -274,12 +563,70 @@ int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
        param.server = server;
        param.port = port;
        
+       refresh_resolvers();
        threaded_run(folder, &param, &result, connect_ssl_run);
-       
-       debug_print("connect ok\n");
+
+       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); 
+       }
+       debug_print("connect %d with imap %p\n", result.error, imap);
        
        return result.error;
 }
+
+struct capa_param {
+       mailimap * imap;
+};
+
+struct capa_result {
+       int error;
+       struct mailimap_capability_data *caps;
+};
+
+static void capability_run(struct etpan_thread_op * op)
+{
+       int r;
+       struct capa_param * param;
+       struct capa_result * result;
+       struct mailimap_capability_data *caps;
+
+       param = op->param;
+       result = op->result;
+       
+       CHECK_IMAP();
+
+       r = mailimap_capability(param->imap, &caps);
+       
+       result->error = r;
+       result->caps = (r == 0 ? caps : NULL);
+}
+
+
+struct mailimap_capability_data * imap_threaded_capability(Folder *folder, int *ok)
+{
+       struct capa_param param;
+       struct capa_result result;
+       mailimap *imap;
+       
+       imap = get_imap(folder);
+       
+       param.imap = imap;
+       
+       threaded_run(folder, &param, &result, capability_run);
+       
+       debug_print("capa %d\n", result.error);
+       
+       if (ok)
+               *ok = result.error;
+
+       return result.caps;
+       
+}
        
 struct disconnect_param {
        mailimap * imap;
@@ -298,6 +645,8 @@ static void disconnect_run(struct etpan_thread_op * op)
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = mailimap_logout(param->imap);
        
        result->error = r;
@@ -307,8 +656,6 @@ void imap_threaded_disconnect(Folder * folder)
 {
        struct connect_param param;
        struct connect_result result;
-       chashdatum key;
-       chashdatum value;
        mailimap * imap;
        
        imap = get_imap(folder);
@@ -321,13 +668,12 @@ void imap_threaded_disconnect(Folder * folder)
        
        threaded_run(folder, &param, &result, disconnect_run);
        
-       key.data = &folder;
-       key.len = sizeof(folder);
-       value.data = imap;
-       value.len = 0;
-       chash_delete(session_hash, &key, NULL);
-       
-       mailimap_free(imap);
+       if (imap == get_imap(folder)) {
+               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");
 }
@@ -337,6 +683,7 @@ struct list_param {
        mailimap * imap;
        const char * base;
        const char * wildcard;
+       gboolean sub_only;
 };
 
 struct list_result {
@@ -352,11 +699,24 @@ static void list_run(struct etpan_thread_op * op)
        clist * list;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        list = NULL;
-       r = mailimap_list(param->imap, param->base,
-                         param->wildcard, &list);
        
-       result = op->result;
+       if (param->base == NULL || param->wildcard == NULL) {
+               result->list = list;
+               result->error = -1;
+               debug_print("no base or wildcard (%p %p)\n", param->base, param->wildcard);
+               return;
+       }
+       if (param->sub_only)
+               r = mailimap_lsub(param->imap, param->base,
+                         param->wildcard, &list);
+       else
+               r = mailimap_list(param->imap, param->base,
+                         param->wildcard, &list);
        result->error = r;
        result->list = list;
        debug_print("imap list run - end\n");
@@ -374,7 +734,8 @@ int imap_threaded_list(Folder * folder, const char * base,
        param.imap = get_imap(folder);
        param.base = base;
        param.wildcard = wildcard;
-       
+       param.sub_only = FALSE;
+
        threaded_run(folder, &param, &result, list_run);
        
        * p_result = result.list;
@@ -384,12 +745,86 @@ int imap_threaded_list(Folder * folder, const char * base,
        return result.error;
 }
 
+int imap_threaded_lsub(Folder * folder, const char * base,
+                      const char * wildcard,
+                      clist ** p_result)
+{
+       struct list_param param;
+       struct list_result result;
+       
+       debug_print("imap lsub - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.base = base;
+       param.wildcard = wildcard;
+       param.sub_only = TRUE;
+       
+       threaded_run(folder, &param, &result, list_run);
+       
+       * p_result = result.list;
+       
+       debug_print("imap lsub - end %p\n", result.list);
+       
+       return result.error;
+}
+
+struct subscribe_param {
+       mailimap * imap;
+       const char * mb;
+       gboolean subscribe;
+};
+
+struct subscribe_result {
+       int error;
+};
+
+static void subscribe_run(struct etpan_thread_op * op)
+{
+       struct subscribe_param * param;
+       struct subscribe_result * result;
+       int r;
+       
+       param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
+       if (param->mb == NULL) {
+               result->error = -1;
+               debug_print("no mb\n");
+               return;
+       }
+       if (param->subscribe)
+               r = mailimap_subscribe(param->imap, param->mb);
+       else
+               r = mailimap_unsubscribe(param->imap, param->mb);
+       result->error = r;
+       debug_print("imap %ssubscribe run - end %d\n", param->subscribe?"":"un", r);
+}
+
+int imap_threaded_subscribe(Folder * folder, const char * mb,
+                      gboolean subscribe)
+{
+       struct subscribe_param param;
+       struct subscribe_result result;
+       
+       debug_print("imap list - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.mb = mb;
+       param.subscribe = subscribe;
 
+       threaded_run(folder, &param, &result, subscribe_run);
+       
+       return result.error;
+}
 
 struct login_param {
        mailimap * imap;
        const char * login;
        const char * password;
+       const char * type;
+       const char * server;
 };
 
 struct login_result {
@@ -401,18 +836,43 @@ static void login_run(struct etpan_thread_op * op)
        struct login_param * param;
        struct login_result * result;
        int r;
+#ifdef DISABLE_LOG_DURING_LOGIN
+       int old_debug;
+#endif
        
        param = op->param;
-       r = mailimap_login(param->imap,
+       result = op->result;
+
+       CHECK_IMAP();
+
+#ifdef DISABLE_LOG_DURING_LOGIN
+       old_debug = mailstream_debug;
+       mailstream_debug = 0;
+#endif
+       if (!strcmp(param->type, "LOGIN"))
+               r = mailimap_login(param->imap,
                           param->login, param->password);
+       else if (!strcmp(param->type, "GSSAPI"))
+               r = mailimap_authenticate(param->imap,
+                       param->type, param->server, NULL, NULL,
+                       param->login, param->login,
+                       param->password, NULL);
+       else 
+               r = mailimap_authenticate(param->imap,
+                       param->type, NULL, NULL, NULL,
+                       param->login, param->login,
+                       param->password, NULL);
+#ifdef DISABLE_LOG_DURING_LOGIN
+       mailstream_debug = old_debug;
+#endif
        
-       result = op->result;
        result->error = r;
        debug_print("imap login run - end %i\n", r);
 }
 
 int imap_threaded_login(Folder * folder,
-                       const char * login, const char * password)
+                       const char * login, const char * password,
+                       const char * type)
 {
        struct login_param param;
        struct login_result result;
@@ -422,7 +882,12 @@ int imap_threaded_login(Folder * folder,
        param.imap = get_imap(folder);
        param.login = login;
        param.password = password;
-       
+       param.type = type;
+       if (folder && folder->account)
+               param.server = folder->account->recv_server;
+       else
+               param.server = NULL;
+
        threaded_run(folder, &param, &result, login_run);
        
        debug_print("imap login - end\n");
@@ -451,6 +916,8 @@ static void status_run(struct etpan_thread_op * op)
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = mailimap_status(param->imap, param->mb,
                            param->status_att_list,
                            &result->data_status);
@@ -460,7 +927,8 @@ static void status_run(struct etpan_thread_op * op)
 }
 
 int imap_threaded_status(Folder * folder, const char * mb,
-                        struct mailimap_mailbox_data_status ** data_status)
+                        struct mailimap_mailbox_data_status ** data_status,
+                        guint mask)
 {
        struct status_param param;
        struct status_result result;
@@ -469,17 +937,26 @@ int imap_threaded_status(Folder * folder, const char * mb,
        debug_print("imap status - begin\n");
        
        status_att_list = mailimap_status_att_list_new_empty();
-       mailimap_status_att_list_add(status_att_list,
+       if (mask & 1 << 0) {
+               mailimap_status_att_list_add(status_att_list,
                                     MAILIMAP_STATUS_ATT_MESSAGES);
-       mailimap_status_att_list_add(status_att_list,
+       }
+       if (mask & 1 << 1) {
+               mailimap_status_att_list_add(status_att_list,
                                     MAILIMAP_STATUS_ATT_RECENT);
-       mailimap_status_att_list_add(status_att_list,
+       }
+       if (mask & 1 << 2) {
+               mailimap_status_att_list_add(status_att_list,
                                     MAILIMAP_STATUS_ATT_UIDNEXT);
-       mailimap_status_att_list_add(status_att_list,
+       }
+       if (mask & 1 << 3) {
+               mailimap_status_att_list_add(status_att_list,
                                     MAILIMAP_STATUS_ATT_UIDVALIDITY);
-       mailimap_status_att_list_add(status_att_list,
+       }
+       if (mask & 1 << 4) {
+               mailimap_status_att_list_add(status_att_list,
                                     MAILIMAP_STATUS_ATT_UNSEEN);
-       
+       }
        param.imap = get_imap(folder);
        param.mb = mb;
        param.status_att_list = status_att_list;
@@ -490,6 +967,8 @@ int imap_threaded_status(Folder * folder, const char * mb,
        
        * data_status = result.data_status;
        
+       mailimap_status_att_list_free(status_att_list);
+       
        return result.error;
 }
 
@@ -510,14 +989,22 @@ static void noop_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_noop(param->imap);
        
-       result = op->result;
        result->error = r;
        debug_print("imap noop run - end %i\n", r);
 }
 
-int imap_threaded_noop(Folder * folder, unsigned int * p_exists)
+int imap_threaded_noop(Folder * folder, unsigned int * p_exists, 
+                      unsigned int *p_recent, 
+                      unsigned int *p_expunge,
+                      unsigned int *p_unseen,
+                      unsigned int *p_uidnext,
+                      unsigned int *p_uidval)
 {
        struct noop_param param;
        struct noop_result result;
@@ -527,57 +1014,105 @@ 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 (imap->imap_selection_info != NULL) {
+       if (result.error == 0 && imap && imap->imap_selection_info != NULL) {
                * p_exists = imap->imap_selection_info->sel_exists;
-       }
-       else {
+               * p_recent = imap->imap_selection_info->sel_recent;
+               * p_unseen = imap->imap_selection_info->sel_unseen;
+               * p_uidnext = imap->imap_selection_info->sel_uidnext;
+               * p_uidval = imap->imap_selection_info->sel_uidvalidity;
+       } else {
                * p_exists = 0;
+               * p_recent = 0;
+               * p_unseen = 0;
+               * p_uidnext = 0;
+               * p_uidval = 0;
        }
-       
-       debug_print("imap noop - end\n");
+       if (result.error == 0 && imap && imap->imap_response_info != NULL &&
+           imap->imap_response_info->rsp_expunged != NULL) {
+               * p_expunge = clist_count(imap->imap_response_info->rsp_expunged);
+       } else {
+               * p_expunge = 0;
+       }       
+       debug_print("imap noop - end [EXISTS %d RECENT %d EXPUNGE %d UNSEEN %d UIDNEXT %d UIDVAL %d]\n",
+               *p_exists, *p_recent, *p_expunge, *p_unseen,
+               *p_uidnext, *p_uidval);
        
        return result.error;
 }
 
 
-struct starttls_param {
-       mailimap * imap;
-};
-
 struct starttls_result {
        int error;
 };
 
 static void starttls_run(struct etpan_thread_op * op)
 {
-       struct starttls_param * param;
+       struct connect_param * param;
        struct starttls_result * result;
        int r;
-       
+
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_starttls(param->imap);
        
-       result = op->result;
        result->error = r;
        debug_print("imap starttls run - end %i\n", r);
+       
+       if (r == 0) {
+               mailimap *imap = param->imap;
+               mailstream_low *plain_low = NULL;
+               mailstream_low *tls_low = NULL;
+               int fd = -1;
+               
+               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");
+                       result->error = MAILIMAP_ERROR_STREAM;
+                       return;
+               }
+
+               tls_low = mailstream_low_tls_open(fd);
+               if (tls_low == NULL) {
+                       debug_print("imap starttls run - can't tls_open\n");
+                       result->error = MAILIMAP_ERROR_STREAM;
+                       return;
+               }
+               mailstream_low_free(plain_low);
+               mailstream_set_low(imap->imap_stream, tls_low);
+       }
 }
 
-int imap_threaded_starttls(Folder * folder)
+int imap_threaded_starttls(Folder * folder, const gchar *host, int port)
 {
-       struct starttls_param param;
+       struct connect_param param;
        struct starttls_result result;
+       int cert_len;
+       unsigned char *certificate;
        
        debug_print("imap starttls - begin\n");
        
        param.imap = get_imap(folder);
+       param.server = host;
+       param.port = port;
        
        threaded_run(folder, &param, &result, starttls_run);
        
        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); 
+       }       
        return result.error;
 }
 
@@ -599,9 +1134,12 @@ static void create_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_create(param->imap, param->mb);
        
-       result = op->result;
        result->error = r;
        debug_print("imap create run - end %i\n", r);
 }
@@ -643,9 +1181,12 @@ static void rename_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_rename(param->imap, param->mb, param->new_name);
        
-       result = op->result;
        result->error = r;
        debug_print("imap rename run - end %i\n", r);
 }
@@ -688,9 +1229,12 @@ static void delete_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_delete(param->imap, param->mb);
        
-       result = op->result;
        result->error = r;
        debug_print("imap delete run - end %i\n", r);
 }
@@ -730,9 +1274,12 @@ static void select_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_select(param->imap, param->mb);
        
-       result = op->result;
        result->error = r;
        debug_print("imap select run - end %i\n", r);
 }
@@ -756,7 +1303,7 @@ int imap_threaded_select(Folder * folder, const char * mb,
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
-       if (imap->imap_selection_info == NULL)
+       if (!imap || imap->imap_selection_info == NULL)
                return MAILIMAP_ERROR_PARSE;
        
        * exists = imap->imap_selection_info->sel_exists;
@@ -769,7 +1316,43 @@ int imap_threaded_select(Folder * folder, const char * mb,
        return result.error;
 }
 
+static void close_run(struct etpan_thread_op * op)
+{
+       struct select_param * param;
+       struct select_result * result;
+       int r;
+       
+       param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
 
+       r = mailimap_close(param->imap);
+       
+       result->error = r;
+       debug_print("imap close run - end %i\n", r);
+}
+
+int imap_threaded_close(Folder * folder)
+{
+       struct select_param param;
+       struct select_result result;
+       mailimap * imap;
+       
+       debug_print("imap close - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       
+       threaded_run(folder, &param, &result, close_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap close - end\n");
+       
+       return result.error;
+}
 
 struct examine_param {
        mailimap * imap;
@@ -787,9 +1370,12 @@ static void examine_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_examine(param->imap, param->mb);
        
-       result = op->result;
        result->error = r;
        debug_print("imap examine run - end %i\n", r);
 }
@@ -813,7 +1399,7 @@ int imap_threaded_examine(Folder * folder, const char * mb,
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
-       if (imap->imap_selection_info == NULL)
+       if (!imap || imap->imap_selection_info == NULL)
                return MAILIMAP_ERROR_PARSE;
        
        * exists = imap->imap_selection_info->sel_exists;
@@ -840,20 +1426,47 @@ struct search_result {
        clist * search_result;
 };
 
+static struct mailimap_set_item *sc_mailimap_set_item_copy(struct mailimap_set_item *orig)
+{
+       return mailimap_set_item_new(orig->set_first, orig->set_last);
+}
+
+static struct mailimap_set *sc_mailimap_set_copy(struct mailimap_set *orig)
+{
+       clist *list = orig ? orig->set_list : NULL;
+       clist *newlist = clist_new();
+       clistiter *cur;
+       
+       if (!orig)
+               return NULL;
+       for (cur = clist_begin(list); cur; cur = clist_next(cur))
+               clist_append(newlist, 
+                       sc_mailimap_set_item_copy(
+                       (struct mailimap_set_item *)clist_content(cur)));
+       return mailimap_set_new(newlist);
+}
+
 static void search_run(struct etpan_thread_op * op)
 {
        struct search_param * param;
        struct search_result * result;
        int r;
-       struct mailimap_search_key * key;
-       struct mailimap_search_key * uid_key;
+       struct mailimap_search_key * key = NULL;
+       struct mailimap_search_key * uid_key = NULL;
        struct mailimap_search_key * search_type_key;
        clist * search_result;
        
        param = op->param;
-       
-       uid_key = mailimap_search_key_new_uid(param->set);
-       
+       result = op->result;
+
+       CHECK_IMAP();
+
+       /* we copy the mailimap_set because freeing the key is recursive */
+       if (param->set != NULL) {
+               uid_key = mailimap_search_key_new_uid(sc_mailimap_set_copy(param->set));
+       } 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:
@@ -895,62 +1508,290 @@ static void search_run(struct etpan_thread_op * op)
                                                          NULL, NULL, NULL, NULL, NULL,
                                                          NULL, 0, NULL, NULL, NULL);
                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);
+               break;
        }
        
        if (search_type_key != NULL) {
-               key = mailimap_search_key_new_multiple_empty();
-               mailimap_search_key_multiple_add(key, search_type_key);
-               mailimap_search_key_multiple_add(key, uid_key);
-       }
-       else {
+               if (param->set != NULL) {
+                       key = mailimap_search_key_new_multiple_empty();
+                       mailimap_search_key_multiple_add(key, search_type_key);
+                       mailimap_search_key_multiple_add(key, uid_key);
+               } else {
+                       key = search_type_key;
+               }
+       } else if (uid_key != NULL) {
                key = uid_key;
        }
        
-       r = mailimap_uid_search(param->imap, NULL, key, &search_result);
+       if (key == NULL) {
+               g_warning("no key!");
+               result = op->result;
+               result->error = -1;
+               result->search_result = NULL;
+       } else {
+               mailstream_logger = imap_logger_uid;
+
+               r = mailimap_uid_search(param->imap, NULL, key, &search_result);
+
+               mailstream_logger = imap_logger_cmd;
+
+               /* free the key (with the imapset) */
+               mailimap_search_key_free(key);
+
+               result->error = r;
+               result->search_result = search_result;
+       }
+       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)
+{
+       struct search_param param;
+       struct search_result result;
+       mailimap * imap;
+       
+       debug_print("imap search - begin\n");
+
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.set = set;
+       param.type = search_type;
+       
+       threaded_run(folder, &param, &result, search_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap search - end\n");
+       
+       * search_result = result.search_result;
+       
+       return result.error;
+}
+
+
+
+static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
+                                uint32_t * puid,
+                                char ** pheaders,
+                                size_t * pref_size,
+                                struct mailimap_msg_att_dynamic ** patt_dyn);
+
+static int
+result_to_uid_list(clist * fetch_result, carray ** result)
+{
+       clistiter * cur;
+       int r;
+       int res;
+       carray * tab;
+       
+       tab = carray_new(128);
+       if (tab == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+       
+       for(cur = clist_begin(fetch_result) ; cur != NULL ;
+           cur = clist_next(cur)) {
+               struct mailimap_msg_att * msg_att;
+               uint32_t uid;
+               uint32_t * puid;
+               
+               msg_att = clist_content(cur);
+               
+               uid = 0;
+               imap_get_msg_att_info(msg_att, &uid, NULL, NULL, NULL);
+               
+               puid = malloc(sizeof(* puid));
+               if (puid == NULL) {
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
+               * puid = uid;
+                       
+               r = carray_add(tab, puid, NULL);
+               if (r < 0) {
+                       free(puid);
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
+       }
+               
+       * result = tab;
+
+       return MAILIMAP_NO_ERROR;
+  
+ free_list:
+       imap_fetch_uid_list_free(tab);
+ err:
+       return res;
+}
+
+static int imap_get_messages_list(mailimap * imap,
+                                 uint32_t first_index,
+                                 carray ** result)
+{
+       carray * env_list;
+       int r;
+       struct mailimap_fetch_att * fetch_att;
+       struct mailimap_fetch_type * fetch_type;
+       struct mailimap_set * set;
+       clist * fetch_result;
+       int res;
+       
+       set = mailimap_set_new_interval(first_index, 0);
+       if (set == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+
+       fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
+       if (fetch_type == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_set;
+       }
+
+       fetch_att = mailimap_fetch_att_new_uid();
+       if (fetch_att == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+       if (r != MAILIMAP_NO_ERROR) {
+               mailimap_fetch_att_free(fetch_att);
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+
+       mailstream_logger = imap_logger_fetch;
+       
+       r = mailimap_uid_fetch(imap, set,
+                              fetch_type, &fetch_result);
+
+       mailstream_logger = imap_logger_cmd;
+       mailimap_fetch_type_free(fetch_type);
+       mailimap_set_free(set);
+
+       if (r != MAILIMAP_NO_ERROR) {
+               res = r;
+               goto err;
+       }
+
+       env_list = NULL;
+       r = result_to_uid_list(fetch_result, &env_list);
+       mailimap_fetch_list_free(fetch_result);
+       
+       * result = env_list;
+
+       return MAILIMAP_NO_ERROR;
+
+ free_fetch_type:
+       mailimap_fetch_type_free(fetch_type);
+ free_set:
+       mailimap_set_free(set);
+ err:
+       return res;
+}
+
+
+
+
+struct fetch_uid_param {
+       mailimap * imap;
+       uint32_t first_index;
+};
+
+struct fetch_uid_result {
+       int error;
+       carray * fetch_result;
+};
+
+static void fetch_uid_run(struct etpan_thread_op * op)
+{
+       struct fetch_uid_param * param;
+       struct fetch_uid_result * result;
+       carray * fetch_result;
+       int r;
        
+       param = op->param;
        result = op->result;
+
+       CHECK_IMAP();
+
+       fetch_result = NULL;
+       mailstream_logger = NULL;
+       log_print(LOG_PROTOCOL, "IMAP4- [fetching UIDs...]\n");
+
+       r = imap_get_messages_list(param->imap, param->first_index,
+                                  &fetch_result);
+       
+       mailstream_logger = imap_logger_cmd;
+
        result->error = r;
-       result->search_result = search_result;
-       debug_print("imap search run - end %i\n", r);
+       result->fetch_result = fetch_result;
+       debug_print("imap fetch_uid run - end %i\n", r);
 }
 
-int imap_threaded_search(Folder * folder, int search_type,
-                        struct mailimap_set * set, clist ** search_result)
+int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
+                           carray ** fetch_result)
 {
-       struct search_param param;
-       struct search_result result;
+       struct fetch_uid_param param;
+       struct fetch_uid_result result;
        mailimap * imap;
        
-       debug_print("imap search - begin\n");
+       debug_print("imap fetch_uid - begin\n");
        
        imap = get_imap(folder);
        param.imap = imap;
-       param.set = set;
-       param.type = search_type;
+       param.first_index = first_index;
        
-       threaded_run(folder, &param, &result, search_run);
+       threaded_run(folder, &param, &result, fetch_uid_run);
        
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
-       debug_print("imap search - end\n");
+       debug_print("imap fetch_uid - end\n");
        
-       * search_result = result.search_result;
+       * fetch_result = result.fetch_result;
        
        return result.error;
 }
 
 
+void imap_fetch_uid_list_free(carray * uid_list)
+{
+       unsigned int i;
+       
+       for(i = 0 ; i < carray_count(uid_list) ; i ++) {
+               uint32_t * puid;
+               
+               puid = carray_get(uid_list, i);
+               free(puid);
+       }
+       carray_free(uid_list);
+}
+
+
 
 
+static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn);
+
 static int
-uid_list_to_env_list(clist * fetch_result, carray ** result)
+result_to_uid_flags_list(clist * fetch_result, carray ** result)
 {
        clistiter * cur;
        int r;
        int res;
        carray * tab;
-       unsigned int i;
        
        tab = carray_new(128);
        if (tab == NULL) {
@@ -961,31 +1802,23 @@ uid_list_to_env_list(clist * fetch_result, carray ** result)
        for(cur = clist_begin(fetch_result) ; cur != NULL ;
            cur = clist_next(cur)) {
                struct mailimap_msg_att * msg_att;
-               clistiter * item_cur;
                uint32_t uid;
-               size_t size;
                uint32_t * puid;
+               struct mailimap_msg_att_dynamic * att_dyn;
+               int flags;
+               int * pflags;
                
                msg_att = clist_content(cur);
                
                uid = 0;
-               size = 0;
-               for(item_cur = clist_begin(msg_att->att_list) ;
-                   item_cur != NULL ;
-                   item_cur = clist_next(item_cur)) {
-                       struct mailimap_msg_att_item * item;
-                       
-                       item = clist_content(item_cur);
-                       
-                       switch (item->att_type) {
-                       case MAILIMAP_MSG_ATT_ITEM_STATIC:
-                               switch (item->att_data.att_static->att_type) {
-                               case MAILIMAP_MSG_ATT_UID:
-                                       uid = item->att_data.att_static->att_data.att_uid;
-                                       break;
-                               }
-                       }
-               }
+               att_dyn = NULL;
+               imap_get_msg_att_info(msg_att, &uid, NULL, NULL, &att_dyn);
+               if (uid == 0)
+                       continue;
+               if (att_dyn == NULL)
+                       continue;
+               
+               flags = imap_flags_to_flags(att_dyn);
                
                puid = malloc(sizeof(* puid));
                if (puid == NULL) {
@@ -993,13 +1826,25 @@ uid_list_to_env_list(clist * fetch_result, carray ** result)
                        goto free_list;
                }
                * puid = uid;
-                       
+               
                r = carray_add(tab, puid, NULL);
                if (r < 0) {
                        free(puid);
                        res = MAILIMAP_ERROR_MEMORY;
                        goto free_list;
                }
+               pflags = malloc(sizeof(* pflags));
+               if (pflags == NULL) {
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
+               * pflags = flags;
+               r = carray_add(tab, pflags, NULL);
+               if (r < 0) {
+                       free(pflags);
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
        }
                
        * result = tab;
@@ -1007,15 +1852,14 @@ uid_list_to_env_list(clist * fetch_result, carray ** result)
        return MAILIMAP_NO_ERROR;
   
  free_list:
-       for(i = 0 ; i < carray_count(tab) ; i++)
-               mailmessage_free(carray_get(tab, i));
+       imap_fetch_uid_flags_list_free(tab);
  err:
        return res;
 }
 
-static int imap_get_messages_list(mailimap * imap,
-                                 uint32_t first_index,
-                                 carray ** result)
+static int imap_get_messages_flags_list(mailimap * imap,
+                                       uint32_t first_index,
+                                       carray ** result)
 {
        carray * env_list;
        int r;
@@ -1037,6 +1881,19 @@ static int imap_get_messages_list(mailimap * imap,
                goto free_set;
        }
 
+       fetch_att = mailimap_fetch_att_new_flags();
+       if (fetch_att == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+       
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+       if (r != MAILIMAP_NO_ERROR) {
+               mailimap_fetch_att_free(fetch_att);
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+       
        fetch_att = mailimap_fetch_att_new_uid();
        if (fetch_att == NULL) {
                res = MAILIMAP_ERROR_MEMORY;
@@ -1050,9 +1907,12 @@ static int imap_get_messages_list(mailimap * imap,
                goto free_fetch_type;
        }
 
+       mailstream_logger = imap_logger_fetch;
+       
        r = mailimap_uid_fetch(imap, set,
                               fetch_type, &fetch_result);
 
+       mailstream_logger = imap_logger_cmd;
        mailimap_fetch_type_free(fetch_type);
        mailimap_set_free(set);
 
@@ -1062,7 +1922,7 @@ static int imap_get_messages_list(mailimap * imap,
        }
 
        env_list = NULL;
-       r = uid_list_to_env_list(fetch_result, &env_list);
+       r = result_to_uid_flags_list(fetch_result, &env_list);
        mailimap_fetch_list_free(fetch_result);
        
        * result = env_list;
@@ -1079,18 +1939,7 @@ static int imap_get_messages_list(mailimap * imap,
 
 
 
-
-struct fetch_uid_param {
-       mailimap * imap;
-       uint32_t first_index;
-};
-
-struct fetch_uid_result {
-       int error;
-       carray * fetch_result;
-};
-
-static void fetch_uid_run(struct etpan_thread_op * op)
+static void fetch_uid_flags_run(struct etpan_thread_op * op)
 {
        struct fetch_uid_param * param;
        struct fetch_uid_result * result;
@@ -1098,18 +1947,21 @@ static void fetch_uid_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
-       
-       r = imap_get_messages_list(param->imap, param->first_index,
-                                  &fetch_result);
-       
        result = op->result;
+
+       CHECK_IMAP();
+
+       fetch_result = NULL;
+       r = imap_get_messages_flags_list(param->imap, param->first_index,
+                                        &fetch_result);
+       
        result->error = r;
        result->fetch_result = fetch_result;
        debug_print("imap fetch_uid run - end %i\n", r);
 }
 
-int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
-                           carray ** fetch_result)
+int imap_threaded_fetch_uid_flags(Folder * folder, uint32_t first_index,
+                                 carray ** fetch_result)
 {
        struct fetch_uid_param param;
        struct fetch_uid_result result;
@@ -1121,7 +1973,13 @@ int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
        param.imap = imap;
        param.first_index = first_index;
        
-       threaded_run(folder, &param, &result, fetch_uid_run);
+       mailstream_logger = NULL;
+       log_print(LOG_PROTOCOL, "IMAP4- [fetching flags...]\n");
+
+       threaded_run(folder, &param, &result, fetch_uid_flags_run);
+
+       mailstream_logger = imap_logger_cmd;
+
        
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
@@ -1134,17 +1992,17 @@ int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
 }
 
 
-void imap_fetch_uid_list_free(carray * uid_list)
+void imap_fetch_uid_flags_list_free(carray * uid_flags_list)
 {
        unsigned int i;
        
-       for(i = 0 ; i < carray_count(uid_list) ; i ++) {
-               uint32_t * puid;
+       for(i = 0 ; i < carray_count(uid_flags_list) ; i ++) {
+               void * data;
                
-               puid = carray_get(uid_list, i);
-               free(puid);
+               data = carray_get(uid_flags_list, i);
+               free(data);
        }
-       carray_free(uid_list);
+       carray_free(uid_flags_list);
 }
 
 
@@ -1192,9 +2050,13 @@ static int imap_fetch(mailimap * imap,
                goto free_fetch_att;
        }
 
+       mailstream_logger = imap_logger_fetch;
+       
        r = mailimap_uid_fetch(imap, set,
                               fetch_type, &fetch_result);
   
+       mailstream_logger = imap_logger_cmd;
+       
        mailimap_fetch_type_free(fetch_type);
        mailimap_set_free(set);
   
@@ -1292,8 +2154,11 @@ static int imap_fetch_header(mailimap * imap,
     goto free_fetch_att;
   }
 
+  mailstream_logger = imap_logger_fetch;
+  
   r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
   
+  mailstream_logger = imap_logger_cmd;
   mailimap_fetch_type_free(fetch_type);
   mailimap_set_free(set);
 
@@ -1371,7 +2236,12 @@ static void fetch_content_run(struct etpan_thread_op * op)
        FILE * f;
        
        param = op->param;
-       
+       result = op->result;
+
+       CHECK_IMAP();
+
+       content = NULL;
+       content_size = 0;
        if (param->with_body)
                r = imap_fetch(param->imap, param->msg_index,
                               &content, &content_size);
@@ -1379,7 +2249,6 @@ static void fetch_content_run(struct etpan_thread_op * op)
                r = imap_fetch_header(param->imap, param->msg_index,
                                      &content, &content_size);
        
-       result = op->result;
        result->error = r;
        
        if (r == MAILIMAP_NO_ERROR) {
@@ -1402,7 +2271,7 @@ static void fetch_content_run(struct etpan_thread_op * op)
                
                r = fclose(f);
                if (r == EOF) {
-                       unlink(param->filename);
+                       g_unlink(param->filename);
                        goto close;
                }
                goto free;
@@ -1413,7 +2282,7 @@ static void fetch_content_run(struct etpan_thread_op * op)
        close:
                close(fd);
        unlink:
-               unlink(param->filename);
+               g_unlink(param->filename);
        
        free:
                if (mmap_string_unref(content) != 0)
@@ -1565,6 +2434,8 @@ fetch_to_env_info(struct mailimap_msg_att * msg_att)
        imap_get_msg_att_info(msg_att, &uid, &headers, &size,
                              &att_dyn);
        
+       if (!headers)
+               return NULL;
        info = malloc(sizeof(* info));
        info->uid = uid;
        info->headers = strdup(headers);
@@ -1581,7 +2452,6 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
        clistiter * cur;
        unsigned int i;
        carray * env_list;
-  
        i = 0;
   
        env_list = carray_new(16);
@@ -1594,6 +2464,8 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
                msg_att = clist_content(cur);
 
                env_info = fetch_to_env_info(msg_att);
+               if (!env_info)
+                       return MAILIMAP_ERROR_MEMORY;
                carray_add(env_list, env_info, NULL);
        }
   
@@ -1602,7 +2474,7 @@ imap_fetch_result_to_envelop_list(clist * fetch_result,
        return MAIL_NO_ERROR;
 }
 
-int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
+static int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
 {
        struct mailimap_fetch_att * fetch_att;
        int r;
@@ -1638,6 +2510,18 @@ int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
        return MAIL_NO_ERROR;
 }
 
+static int imap_add_header_fetch_att(struct mailimap_fetch_type * fetch_type)
+{
+       struct mailimap_fetch_att * fetch_att;
+       struct mailimap_section * section;
+       
+       section = mailimap_section_new_header();
+       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;
+}
+
 static int
 imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
                        carray ** p_env_list)
@@ -1647,7 +2531,9 @@ imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
        int res;
        clist * fetch_result;
        int r;
-       carray * env_list;
+       carray * env_list = NULL;
+       chashdatum key;
+       chashdatum value;
        
        fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
   
@@ -1664,20 +2550,31 @@ imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
        r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
   
        /* headers */
-       r = imap_add_envelope_fetch_att(fetch_type);
+       key.data = &imap;
+       key.len = sizeof(imap);
+       r = chash_get(courier_workaround_hash, &key, &value);
+       if (r < 0)
+               r = imap_add_envelope_fetch_att(fetch_type);
+       else
+               r = imap_add_header_fetch_att(fetch_type);
+       
+       mailstream_logger = imap_logger_fetch;
        
        r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
        
+       mailstream_logger = imap_logger_cmd;
        switch (r) {
        case MAILIMAP_NO_ERROR:
                break;
        default:
                mailimap_fetch_type_free(fetch_type);
+               debug_print("uid_fetch: %d\n", r);
                return r;
        }
        
        if (clist_begin(fetch_result) == NULL) {
                res = MAILIMAP_ERROR_FETCH;
+               debug_print("clist_begin = NULL\n");
                goto err;
        }
        
@@ -1687,6 +2584,7 @@ imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
        if (r != MAILIMAP_NO_ERROR) {
                mailimap_fetch_type_free(fetch_type);
                res = MAILIMAP_ERROR_MEMORY;
+               debug_print("fetch_result_to_envelop_list: %d\n", res);
                goto err;
        }
        
@@ -1718,11 +2616,14 @@ static void fetch_env_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
-       
+       result = op->result;
+
+       CHECK_IMAP();
+
+       env_list = NULL;
        r = imap_get_envelopes_list(param->imap, param->set,
                                    &env_list);
        
-       result = op->result;
        result->error = r;
        result->fetch_env_result = env_list;
        
@@ -1744,6 +2645,23 @@ int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
        
        threaded_run(folder, &param, &result, fetch_env_run);
        
+       if (result.error != MAILIMAP_NO_ERROR) {
+               chashdatum key;
+               chashdatum value;
+               int r;
+               
+               key.data = &imap;
+               key.len = sizeof(imap);
+               r = chash_get(courier_workaround_hash, &key, &value);
+               if (r < 0) {
+                       value.data = NULL;
+                       value.len = 0;
+                       chash_set(courier_workaround_hash, &key, &value, NULL);
+                       
+                       threaded_run(folder, &param, &result, fetch_env_run);
+               }
+       }
+       
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
@@ -1781,6 +2699,7 @@ struct append_param {
 
 struct append_result {
        int error;
+       int uid;
 };
 
 static void append_run(struct etpan_thread_op * op)
@@ -1792,10 +2711,13 @@ static void append_run(struct etpan_thread_op * op)
        size_t size;
        struct stat stat_buf;
        int fd;
+       guint32 uid = 0, val = 0;
        
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = stat(param->filename, &stat_buf);
        if (r < 0) {
                result->error = MAILIMAP_ERROR_APPEND;
@@ -1816,21 +2738,26 @@ static void append_run(struct etpan_thread_op * op)
                return;
        }
        
-       r = mailimap_append(param->imap, param->mailbox,
+       mailstream_logger = imap_logger_append;
+       
+       r = mailimap_uidplus_append(param->imap, param->mailbox,
                            param->flag_list, NULL,
-                           data, size);
+                           data, size, &val, &uid);
+
+       mailstream_logger = imap_logger_cmd;
        
        munmap(data, size);
        close(fd);
        
        result->error = r;
-       
-       debug_print("imap append run - end %i\n", r);
+       result->uid = uid;
+       debug_print("imap append run - end %i uid %d\n", r, uid);
 }
 
 int imap_threaded_append(Folder * folder, const char * mailbox,
                         const char * filename,
-                        struct mailimap_flag_list * flag_list)
+                        struct mailimap_flag_list * flag_list,
+                        int *uid)
 {
        struct append_param param;
        struct append_result result;
@@ -1850,7 +2777,9 @@ int imap_threaded_append(Folder * folder, const char * mailbox,
                return result.error;
        
        debug_print("imap append - end\n");
-       
+       if (uid != NULL)
+               *uid = result.uid;
+
        return result.error;
 }
 
@@ -1872,9 +2801,12 @@ static void expunge_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_expunge(param->imap);
        
-       result = op->result;
        result->error = r;
        debug_print("imap expunge run - end %i\n", r);
 }
@@ -1904,6 +2836,8 @@ struct copy_param {
 
 struct copy_result {
        int error;
+       struct mailimap_set *source;
+       struct mailimap_set *dest;
 };
 
 static void copy_run(struct etpan_thread_op * op)
@@ -1911,19 +2845,31 @@ static void copy_run(struct etpan_thread_op * op)
        struct copy_param * param;
        struct copy_result * result;
        int r;
-       
+       guint32 val;
+       struct mailimap_set *source = NULL, *dest = NULL;
+
        param = op->param;
-       
-       r = mailimap_uid_copy(param->imap, param->set, param->mb);
-       
        result = op->result;
-       result->error = r;
+
+       CHECK_IMAP();
+
+       r = mailimap_uidplus_uid_copy(param->imap, param->set, param->mb,
+               &val, &source, &dest);
        
+       result->error = r;
+       if (r == 0) {
+               result->source = source;
+               result->dest = dest;
+       } else {
+               result->source = NULL;
+               result->dest = NULL;
+       }
        debug_print("imap copy run - end %i\n", r);
 }
 
 int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
-                      const char * mb)
+                      const char * mb, struct mailimap_set **source,
+                      struct mailimap_set **dest)
 {
        struct copy_param param;
        struct copy_result result;
@@ -1937,10 +2883,15 @@ int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
        param.mb = mb;
        
        threaded_run(folder, &param, &result, copy_run);
+       *source = NULL;
+       *dest = NULL;
        
        if (result.error != MAILIMAP_NO_ERROR)
                return result.error;
        
+       *source = result.source;
+       *dest = result.dest;
+
        debug_print("imap copy - end\n");
        
        return result.error;
@@ -1965,11 +2916,13 @@ static void store_run(struct etpan_thread_op * op)
        int r;
        
        param = op->param;
-       
+       result = op->result;
+
+       CHECK_IMAP();
+
        r = mailimap_uid_store(param->imap, param->set,
                               param->store_att_flags);
        
-       result = op->result;
        result->error = r;
        
        debug_print("imap store run - end %i\n", r);
@@ -2000,33 +2953,54 @@ int imap_threaded_store(Folder * folder, struct mailimap_set * set,
 }
 
 
+#define ENV_BUFFER_SIZE 512
 
 static void do_exec_command(int fd, const char * command,
                            const char * servername, uint16_t port)
 {
        int i, maxopen;
-  
+#ifdef SOLARIS
+       char env_buffer[ENV_BUFFER_SIZE];
+#endif
+       
        if (fork() > 0) {
                /* Fork again to become a child of init rather than
                   the etpan client. */
                exit(0);
        }
   
+#ifdef SOLARIS
+       if (servername)
+               snprintf(env_buffer, ENV_BUFFER_SIZE,
+                        "ETPANSERVER=%s", servername);
+       else
+               snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANSERVER=");
+       putenv(env_buffer);
+#else
        if (servername)
                setenv("ETPANSERVER", servername, 1);
        else
                unsetenv("ETPANSERVER");
+#endif
   
+#ifdef SOLARIS
+       if (port)
+               snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANPORT=%d", port);
+       else
+               snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANPORT=");
+       putenv(env_buffer);
+#else
        if (port) {
                char porttext[20];
-    
+               
                snprintf(porttext, sizeof(porttext), "%d", port);
                setenv("ETPANPORT", porttext, 1);
        }
        else {
                unsetenv("ETPANPORT");
        }
-  
+#endif
+               
        /* Not a lot we can do if there's an error other than bail. */
        if (dup2(fd, 0) == -1)
                exit(1);
@@ -2084,7 +3058,7 @@ static int subcommand_connect(const char *command,
        return sockfds[0];
 }
 
-int socket_connect_cmd(mailimap * imap, const char * command,
+static int socket_connect_cmd(mailimap * imap, const char * command,
                       const char * server, int port)
 {
        int fd;
@@ -2102,12 +3076,15 @@ int socket_connect_cmd(mailimap * imap, const char * command,
        }
        
        r = mailimap_connect(imap, s);
-       if (r != MAILIMAP_NO_ERROR) {
+       if (r != MAILIMAP_NO_ERROR_AUTHENTICATED
+       &&  r != MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
                mailstream_close(s);
+               if (imap)
+                       imap->imap_stream = NULL;
                return r;
        }
        
-       return MAILIMAP_NO_ERROR;
+       return r;
 }
 
 /* connect cmd */
@@ -2132,6 +3109,8 @@ static void connect_cmd_run(struct etpan_thread_op * op)
        param = op->param;
        result = op->result;
        
+       CHECK_IMAP();
+
        r = socket_connect_cmd(param->imap, param->command,
                               param->server, param->port);
        
@@ -2146,10 +3125,17 @@ int imap_threaded_connect_cmd(Folder * folder, const char * command,
        struct connect_cmd_result result;
        chashdatum key;
        chashdatum value;
-       mailimap * imap;
+       mailimap * imap, * oldimap;
        
+       oldimap = get_imap(folder);
+
        imap = mailimap_new(0, NULL);
        
+       if (oldimap) {
+               debug_print("deleting old imap %p\n", oldimap);
+               delete_imap(folder, oldimap);
+       }
+
        key.data = &folder;
        key.len = sizeof(folder);
        value.data = imap;
@@ -2163,7 +3149,34 @@ int imap_threaded_connect_cmd(Folder * folder, const char * command,
        
        threaded_run(folder, &param, &result, connect_cmd_run);
        
-       debug_print("connect_cmd ok %i\n", result.error);
+       debug_print("connect_cmd ok %i with imap %p\n", result.error, imap);
        
        return result.error;
 }
+
+void imap_threaded_cancel(Folder * folder)
+{
+       mailimap * imap;
+       
+       imap = get_imap(folder);
+       if (imap->imap_stream != NULL)
+               mailstream_cancel(imap->imap_stream);
+}
+
+#else
+
+void imap_main_init(void)
+{
+}
+void imap_main_done(void)
+{
+}
+void imap_main_set_timeout(int sec)
+{
+}
+
+void imap_threaded_cancel(Folder * folder);
+{
+}
+
+#endif