2007-12-06 [colin] 3.1.0cvs62
[claws.git] / src / imap.c
index 265f17e5e4ba39ea3628ac01e16547a621efea42..b57e5ca1dab85ccce3ce379fbd962c54527265e2 100644 (file)
@@ -45,7 +45,7 @@
 #  include <iconv.h>
 #endif
 
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
 #  include "ssl.h"
 #endif
 
@@ -69,6 +69,7 @@
 #include "msgcache.h"
 #include "imap-thread.h"
 #include "account.h"
+#include "tags.h"
 
 typedef struct _IMAPFolder     IMAPFolder;
 typedef struct _IMAPSession    IMAPSession;
@@ -91,6 +92,7 @@ struct _IMAPFolder
        GList *ns_shared;
        gchar last_seen_separator;
        guint refcnt;
+       guint max_set_size;
 };
 
 struct _IMAPSession
@@ -108,9 +110,16 @@ struct _IMAPSession
        /* CLAWS */
        gboolean folder_content_changed;
        guint exists;
+       guint recent;
+       guint expunge;
+       guint unseen;
+       guint uid_validity;
+       guint uid_next;
+
        Folder * folder;
        gboolean busy;
        gboolean cancelled;
+       gboolean sens_update_block;
 };
 
 struct _IMAPNameSpace
@@ -119,14 +128,6 @@ struct _IMAPNameSpace
        gchar separator;
 };
 
-#define IMAP_SUCCESS   0
-#define IMAP_SOCKET    2
-#define IMAP_AUTHFAIL  3
-#define IMAP_PROTOCOL  4
-#define IMAP_SYNTAX    5
-#define IMAP_IOERR     6
-#define IMAP_ERROR     7
-
 #define IMAPBUFSIZE    8192
 
 typedef enum
@@ -146,12 +147,18 @@ typedef enum
 
 
 #define IMAP4_PORT     143
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
 #define IMAPS_PORT     993
 #endif
 
 #define IMAP_CMD_LIMIT 1000
 
+enum {
+       ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
+       ITEM_CAN_CREATE_FLAGS,
+       ITEM_CANNOT_CREATE_FLAGS
+};
+
 struct _IMAPFolderItem
 {
        FolderItem item;
@@ -161,16 +168,17 @@ struct _IMAPFolderItem
        GSList *uid_list;
        gboolean batching;
 
-       time_t use_cache;
-       gint c_messages;
-       guint32 c_uid_next;
-       guint32 c_uid_validity;
-       gint c_unseen;
-
        GHashTable *flags_set_table;
        GHashTable *flags_unset_table;
        guint32 last_change;
        guint32 last_sync;
+       gboolean should_update;
+       gboolean should_trash_cache;
+       gint can_create_flags;
+
+       GHashTable *tags_set_table;
+       GHashTable *tags_unset_table;
+
 };
 
 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
@@ -281,14 +289,16 @@ static void imap_set_batch                (Folder         *folder,
 static gint imap_set_message_flags     (IMAPSession    *session,
                                         MsgNumberList  *numlist,
                                         IMAPFlags       flags,
+                                        GSList         *tags,
                                         gboolean        is_set);
 static gint imap_select                        (IMAPSession    *session,
                                         IMAPFolder     *folder,
-                                        const gchar    *path,
+                                        FolderItem     *item,
                                         gint           *exists,
                                         gint           *recent,
                                         gint           *unseen,
                                         guint32        *uid_validity,
+                                        gint           *can_create_flags,
                                         gboolean        block);
 static gint imap_status                        (IMAPSession    *session,
                                         IMAPFolder     *folder,
@@ -299,6 +309,10 @@ static gint imap_status                    (IMAPSession    *session,
                                         guint32        *uid_validity,
                                         gint           *unseen,
                                         gboolean        block);
+static void    imap_commit_tags        (FolderItem     *item, 
+                                        MsgInfo        *msginfo,
+                                        GSList         *set_tags,
+                                        GSList         *unset_tags);
 
 static gchar imap_get_path_separator           (IMAPSession    *session,
                                                 IMAPFolder     *folder,
@@ -306,7 +320,9 @@ static gchar imap_get_path_separator                (IMAPSession    *session,
 static gchar *imap_get_real_path               (IMAPSession    *session,
                                                 IMAPFolder     *folder,
                                                 const gchar    *path);
+#ifdef HAVE_LIBETPAN
 static void imap_synchronise           (FolderItem     *item, gint days);
+#endif
 static gboolean imap_is_busy           (Folder *folder);
 
 static void imap_free_capabilities     (IMAPSession    *session);
@@ -317,7 +333,7 @@ static gint imap_cmd_login  (IMAPSession    *session,
                                 const gchar    *pass,
                                 const gchar    *type);
 static gint imap_cmd_noop      (IMAPSession    *session);
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
 static gint imap_cmd_starttls  (IMAPSession    *session);
 #endif
 static gint imap_cmd_select    (IMAPSession    *session,
@@ -326,6 +342,7 @@ static gint imap_cmd_select (IMAPSession    *session,
                                 gint           *recent,
                                 gint           *unseen,
                                 guint32        *uid_validity,
+                                gint           *can_create_flags,
                                 gboolean        block);
 static gint imap_cmd_close     (IMAPSession    *session);
 static gint imap_cmd_examine   (IMAPSession    *session,
@@ -361,15 +378,13 @@ static gint imap_cmd_copy       (IMAPSession *session,
 static gint imap_cmd_store     (IMAPSession    *session,
                                 struct mailimap_set * set,
                                 IMAPFlags flags,
+                                GSList *tags,
                                 int do_add);
 static gint imap_cmd_expunge   (IMAPSession    *session);
 
 static void imap_path_separator_subst          (gchar          *str,
                                                 gchar           separator);
 
-static gchar *imap_utf8_to_modified_utf7       (const gchar    *from);
-static gchar *imap_modified_utf7_to_utf8       (const gchar    *mutf7_str);
-
 static gboolean imap_rename_folder_func                (GNode          *node,
                                                 gpointer        data);
 static gint imap_get_num_list                  (Folder         *folder,
@@ -401,19 +416,19 @@ static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
 /* data types conversion libetpan <-> claws */
 static GSList * imap_list_from_lep(IMAPFolder * folder,
                                   clist * list, const gchar * real_path, gboolean all);
-static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist);
-static GSList * imap_get_lep_set_from_msglist(MsgInfoList *msglist);
+static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
+static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
 static GSList * imap_uid_list_from_lep(clist * list);
 static GSList * imap_uid_list_from_lep_tab(carray * list);
 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
-                                                  GHashTable * hash);
+                                                  GHashTable * hash,
+                                                  GHashTable *tags_hash);
 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
                                       FolderItem *item);
 static void imap_lep_set_free(GSList *seq_list);
-static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags);
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags, GSList *tags);
 
 typedef struct _hashtable_data {
-       IMAPSession *session;
        GSList *msglist;
        IMAPFolderItem *item;
 } hashtable_data;
@@ -425,7 +440,7 @@ typedef struct _thread_data {
        gushort port;
        gboolean done;
        SockInfo *sock;
-#ifdef USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
        SSLType ssl_type;
 #endif
 } thread_data;
@@ -476,6 +491,7 @@ FolderClass *imap_get_class(void)
                imap_class.set_batch = imap_set_batch;
                imap_class.synchronise = imap_synchronise;
                imap_class.remove_cached_msg = imap_remove_cached_msg;
+               imap_class.commit_tags = imap_commit_tags;
 #ifdef USE_PTREAD
                pthread_mutex_init(&imap_mutex, NULL);
 #endif
@@ -484,6 +500,220 @@ FolderClass *imap_get_class(void)
        return &imap_class;
 }
 
+static void imap_refresh_sensitivity (IMAPSession *session)
+{
+        MainWindow *mainwin;
+
+       if (session->sens_update_block)
+               return;
+       mainwin = mainwindow_get_mainwindow();
+       if (mainwin) {
+               toolbar_main_set_sensitive(mainwin);
+               main_window_set_menu_sensitive(mainwin);
+       }
+}
+
+static void lock_session(IMAPSession *session)
+{
+       if (session) {
+               debug_print("locking session %p (%d)\n", session, session->busy);
+               if (session->busy)
+                       debug_print("         SESSION WAS LOCKED !!      \n");
+                session->busy = TRUE;
+               imap_refresh_sensitivity(session);
+       } else {
+               debug_print("can't lock null session\n");
+       }
+}
+
+static void unlock_session(IMAPSession *session)
+{
+       if (session) {
+               debug_print("unlocking session %p\n", session);
+               session->busy = FALSE;
+               imap_refresh_sensitivity(session);
+       } else {
+               debug_print("can't unlock null session\n");
+       }
+}
+
+static void imap_disc_session_destroy(Folder *folder)
+{
+       RemoteFolder *rfolder = REMOTE_FOLDER(folder);
+       IMAPSession *session = NULL;
+       
+       if (!rfolder)
+               return;
+       session = IMAP_SESSION(rfolder->session);
+       if (!session)
+               return;
+       rfolder->session = NULL;
+       log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
+       SESSION(session)->state = SESSION_DISCONNECTED;
+       session_destroy(SESSION(session));
+}
+
+static gboolean is_fatal(int libetpan_errcode)
+{
+       switch(libetpan_errcode) {
+       case MAILIMAP_ERROR_STREAM:
+       case MAILIMAP_ERROR_PROTOCOL:
+       case MAILIMAP_ERROR_PARSE:
+       case MAILIMAP_ERROR_BAD_STATE:
+               return TRUE;
+       default:
+               return FALSE;
+       }
+}
+
+static void imap_handle_error(Session *session, int libetpan_errcode)
+{
+       switch(libetpan_errcode) {
+       case MAILIMAP_NO_ERROR:
+               return;
+       case MAILIMAP_NO_ERROR_AUTHENTICATED:
+               log_warning(LOG_PROTOCOL, _("IMAP error: authenticated\n"));
+               break;
+       case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
+               log_warning(LOG_PROTOCOL, _("IMAP error: not authenticated\n"));
+               break;
+       case MAILIMAP_ERROR_BAD_STATE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: bad state\n"));
+               break;
+       case MAILIMAP_ERROR_STREAM:
+               log_warning(LOG_PROTOCOL, _("IMAP error: stream error\n"));
+               break;
+       case MAILIMAP_ERROR_PARSE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: parse error "
+                                           "(very probably non-RFC compliance from the server)\n"));
+               break;
+       case MAILIMAP_ERROR_CONNECTION_REFUSED:
+               log_warning(LOG_PROTOCOL, _("IMAP error: connection refused\n"));
+               break;
+       case MAILIMAP_ERROR_MEMORY:
+               log_warning(LOG_PROTOCOL, _("IMAP error: memory error\n"));
+               break;
+       case MAILIMAP_ERROR_FATAL:
+               log_warning(LOG_PROTOCOL, _("IMAP error: fatal error\n"));
+               break;
+       case MAILIMAP_ERROR_PROTOCOL:
+               log_warning(LOG_PROTOCOL, _("IMAP error: protocol error"
+                                           "(very probably non-RFC compliance from the server)\n"));
+               break;
+       case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
+               log_warning(LOG_PROTOCOL, _("IMAP error: connection not accepted\n"));
+               break;
+       case MAILIMAP_ERROR_APPEND:
+               log_warning(LOG_PROTOCOL, _("IMAP error: APPEND error\n"));
+               break;
+       case MAILIMAP_ERROR_NOOP:
+               log_warning(LOG_PROTOCOL, _("IMAP error: NOOP error\n"));
+               break;
+       case MAILIMAP_ERROR_LOGOUT:
+               log_warning(LOG_PROTOCOL, _("IMAP error: LOGOUT error\n"));
+               break;
+       case MAILIMAP_ERROR_CAPABILITY:
+               log_warning(LOG_PROTOCOL, _("IMAP error: CAPABILITY error\n"));
+               break;
+       case MAILIMAP_ERROR_CHECK:
+               log_warning(LOG_PROTOCOL, _("IMAP error: CHECK error\n"));
+               break;
+       case MAILIMAP_ERROR_CLOSE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: CLOSE error\n"));
+               break;
+       case MAILIMAP_ERROR_EXPUNGE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: EXPUNGE error\n"));
+               break;
+       case MAILIMAP_ERROR_COPY:
+               log_warning(LOG_PROTOCOL, _("IMAP error: COPY error\n"));
+               break;
+       case MAILIMAP_ERROR_UID_COPY:
+               log_warning(LOG_PROTOCOL, _("IMAP error: UID COPY error\n"));
+               break;
+       case MAILIMAP_ERROR_CREATE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: CREATE error\n"));
+               break;
+       case MAILIMAP_ERROR_DELETE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: DELETE error\n"));
+               break;
+       case MAILIMAP_ERROR_EXAMINE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: EXAMINE error\n"));
+               break;
+       case MAILIMAP_ERROR_FETCH:
+               log_warning(LOG_PROTOCOL, _("IMAP error: FETCH error\n"));
+               break;
+       case MAILIMAP_ERROR_UID_FETCH:
+               log_warning(LOG_PROTOCOL, _("IMAP error: UID FETCH error\n"));
+               break;
+       case MAILIMAP_ERROR_LIST:
+               log_warning(LOG_PROTOCOL, _("IMAP error: LIST error\n"));
+               break;
+       case MAILIMAP_ERROR_LOGIN:
+               log_warning(LOG_PROTOCOL, _("IMAP error: LOGIN error\n"));
+               break;
+       case MAILIMAP_ERROR_LSUB:
+               log_warning(LOG_PROTOCOL, _("IMAP error: LSUB error\n"));
+               break;
+       case MAILIMAP_ERROR_RENAME:
+               log_warning(LOG_PROTOCOL, _("IMAP error: RENAME error\n"));
+               break;
+       case MAILIMAP_ERROR_SEARCH:
+               log_warning(LOG_PROTOCOL, _("IMAP error: SEARCH error\n"));
+               break;
+       case MAILIMAP_ERROR_UID_SEARCH:
+               log_warning(LOG_PROTOCOL, _("IMAP error: UID SEARCH error\n"));
+               break;
+       case MAILIMAP_ERROR_SELECT:
+               log_warning(LOG_PROTOCOL, _("IMAP error: SELECT error\n"));
+               break;
+       case MAILIMAP_ERROR_STATUS:
+               log_warning(LOG_PROTOCOL, _("IMAP error: STATUS error\n"));
+               break;
+       case MAILIMAP_ERROR_STORE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: STORE error\n"));
+               break;
+       case MAILIMAP_ERROR_UID_STORE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: UID STORE error\n"));
+               break;
+       case MAILIMAP_ERROR_SUBSCRIBE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: SUBSCRIBE error\n"));
+               break;
+       case MAILIMAP_ERROR_UNSUBSCRIBE:
+               log_warning(LOG_PROTOCOL, _("IMAP error: UNSUBSCRIBE error\n"));
+               break;
+       case MAILIMAP_ERROR_STARTTLS:
+               log_warning(LOG_PROTOCOL, _("IMAP error: STARTTLS error\n"));
+               break;
+       case MAILIMAP_ERROR_INVAL:
+               log_warning(LOG_PROTOCOL, _("IMAP error: INVAL error\n"));
+               break;
+       case MAILIMAP_ERROR_EXTENSION:
+               log_warning(LOG_PROTOCOL, _("IMAP error: EXTENSION error\n"));
+               break;
+       case MAILIMAP_ERROR_SASL:
+               log_warning(LOG_PROTOCOL, _("IMAP error: SASL error\n"));
+               break;
+#if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
+       case MAILIMAP_ERROR_SSL:
+               log_warning(LOG_PROTOCOL, _("IMAP error: SSL error\n"));
+               break;
+#endif
+#endif
+       default:
+               log_warning(LOG_PROTOCOL, _("IMAP error: Unknown error [%d]\n"),
+                       libetpan_errcode);
+               break;
+       }
+
+       if (session && is_fatal(libetpan_errcode)) {
+               imap_disc_session_destroy(IMAP_SESSION(session)->folder);
+       } else if (session && !is_fatal(libetpan_errcode)) {
+               if (IMAP_SESSION(session)->busy)
+                       unlock_session(IMAP_SESSION(session));
+       }
+}
+
 static Folder *imap_folder_new(const gchar *name, const gchar *path)
 {
        Folder *folder;
@@ -508,6 +738,7 @@ static void imap_folder_init(Folder *folder, const gchar *name,
                             const gchar *path)
 {
        folder_remote_folder_init((Folder *)folder, name, path);
+       IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
 }
 
 static FolderItem *imap_folder_item_new(Folder *folder)
@@ -564,6 +795,7 @@ static int imap_get_capabilities(IMAPSession *session)
        capabilities = imap_threaded_capability(session->folder, &result);
 
        if (result != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), result);
                return MAILIMAP_ERROR_CAPABILITY;
        }
 
@@ -599,13 +831,14 @@ static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
                      IMAPAuthType type)
 {
-       gint ok = IMAP_ERROR;
+       gint ok = MAILIMAP_ERROR_BAD_STATE;
        static time_t last_login_err = 0;
        gchar *ext_info = "";
-       
-       if (imap_get_capabilities(session) != MAILIMAP_NO_ERROR)
-               return IMAP_ERROR;
-
+       int r;
+       if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
+               return r;
+       }
        switch(type) {
        case IMAP_AUTH_ANON:
                ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
@@ -631,13 +864,15 @@ static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass
                        imap_has_capability(session, "GSSAPI"));
                if (imap_has_capability(session, "CRAM-MD5"))
                        ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
-               if (ok == IMAP_ERROR && imap_has_capability(session, "GSSAPI"))
+               if ((ok == MAILIMAP_ERROR_BAD_STATE ||
+                    ok == MAILIMAP_ERROR_LOGIN) && imap_has_capability(session, "GSSAPI"))
                        ok = imap_cmd_login(session, user, pass, "GSSAPI");
-               if (ok == IMAP_ERROR) /* we always try LOGIN before giving up */
+               if (ok == MAILIMAP_ERROR_BAD_STATE||
+                   ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
                        ok = imap_cmd_login(session, user, pass, "LOGIN");
        }
 
-       if (ok == IMAP_SUCCESS)
+       if (ok == MAILIMAP_NO_ERROR)
                session->authenticated = TRUE;
        else {
                if (type == IMAP_AUTH_CRAM_MD5) {
@@ -674,6 +909,7 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
                session_destroy(SESSION(session));
                session = NULL;
        } else {
+               rfolder->session = NULL;
                log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
                            " disconnected. Reconnecting...\n"),
                            folder->account->recv_server);
@@ -686,7 +922,6 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
                   a new session, because of rfolder->session == NULL
                   it will not try to reconnect again and so avoid an
                   endless loop */
-               rfolder->session = NULL;
                debug_print("getting session...\n");
                session = imap_session_get(folder);
                rfolder->session = SESSION(session);
@@ -695,46 +930,11 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
        return session;
 }
 
-static void lock_session(IMAPSession *session)
-{
-       if (session) {
-                MainWindow *mainwin;
-               
-               debug_print("locking session %p (%d)\n", session, session->busy);
-               if (session->busy)
-                       debug_print("         SESSION WAS LOCKED !!      \n");
-                session->busy = TRUE;
-               mainwin = mainwindow_get_mainwindow();
-               if (mainwin) {
-                       toolbar_main_set_sensitive(mainwin);
-                       main_window_set_menu_sensitive(mainwin);
-               }
-       } else {
-               debug_print("can't lock null session\n");
-       }
-}
-
-static void unlock_session(IMAPSession *session)
-{
-       if (session) {
-                MainWindow *mainwin;
-               
-               debug_print("unlocking session %p\n", session);
-               session->busy = FALSE;
-               mainwin = mainwindow_get_mainwindow();
-               if (mainwin) {
-                       toolbar_main_set_sensitive(mainwin);
-                       main_window_set_menu_sensitive(mainwin);
-                }
-       } else {
-               debug_print("can't unlock null session\n");
-       }
-}
-
 static IMAPSession *imap_session_get(Folder *folder)
 {
        RemoteFolder *rfolder = REMOTE_FOLDER(folder);
        IMAPSession *session = NULL;
+       gint r = MAILIMAP_NO_ERROR;
 
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
@@ -772,16 +972,14 @@ static IMAPSession *imap_session_get(Folder *folder)
        
        if (!IMAP_SESSION(session)->authenticated) {
                imap_threaded_disconnect(session->folder);
+               rfolder->session = NULL;
                SESSION(session)->state = SESSION_DISCONNECTED;
                session_destroy(SESSION(session));
-               rfolder->session = NULL;
                rfolder->last_failure = time(NULL);
                rfolder->connecting = FALSE;
                return NULL;
        }
 
-       lock_session(session);
-
        /* I think the point of this code is to avoid sending a
         * keepalive if we've used the session recently and therefore
         * think it's still alive.  Unfortunately, most of the code
@@ -792,9 +990,12 @@ static IMAPSession *imap_session_get(Folder *folder)
         * successfully sent. -- mbp */
        if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
                /* verify that the session is still alive */
-               if (imap_cmd_noop(session) != IMAP_SUCCESS) {
+               if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
                        debug_print("disconnected!\n");
-                       session = imap_reconnect_if_possible(folder, session);
+                       if (!is_fatal(r))
+                               session = imap_reconnect_if_possible(folder, session);
+                       else
+                               session = imap_session_get(folder);
                }
                if (session)
                        session->cancelled = FALSE;
@@ -814,7 +1015,7 @@ static IMAPSession *imap_session_new(Folder * folder,
        int r;
        int authenticated = FALSE;
        
-#ifdef USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
        /* FIXME: IMAP over SSL only... */ 
        SSLType ssl_type;
 
@@ -840,15 +1041,18 @@ static IMAPSession *imap_session_new(Folder * folder,
 #endif
 
        imap_init(folder);
-       statusbar_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
+       statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
+#ifndef G_OS_WIN32
        if (account->set_tunnelcmd) {
                r = imap_threaded_connect_cmd(folder,
                                              account->tunnelcmd,
                                              account->recv_server,
                                              port);
        }
-       else {
-#ifdef USE_OPENSSL
+       else 
+#endif
+       {
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
                if (ssl_type == SSL_TUNNEL) {
                        r = imap_threaded_connect_ssl(folder,
                                                      account->recv_server,
@@ -863,7 +1067,7 @@ static IMAPSession *imap_session_new(Folder * folder,
                }
        }
        
-       statusbar_pop_all();
+       statuswindow_pop_all();
        if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
                authenticated = TRUE;
        }
@@ -872,11 +1076,14 @@ static IMAPSession *imap_session_new(Folder * folder,
        }
        else {
 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
-#ifdef USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
                if (r == MAILIMAP_ERROR_SSL)
                        log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
+               else
 #endif
 #endif
+                       imap_handle_error(NULL, r);
+
                if(!prefs_common.no_recv_err_panel) {
                        alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
                                         account->recv_server, port);
@@ -900,16 +1107,19 @@ static IMAPSession *imap_session_new(Folder * folder,
        
        session->authenticated = authenticated;
        session->mbox = NULL;
+       session->exists = 0;
+       session->recent = 0;
+       session->expunge = 0;
        session->cmd_count = 0;
        session->folder = folder;
        IMAP_FOLDER(session->folder)->last_seen_separator = 0;
 
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
        if (account->ssl_imap == SSL_STARTTLS) {
                gint ok;
 
                ok = imap_cmd_starttls(session);
-               if (ok != IMAP_SUCCESS) {
+               if (ok != MAILIMAP_NO_ERROR) {
                        log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
                        session_destroy(SESSION(session));
                        return NULL;
@@ -947,9 +1157,9 @@ try_again:
        } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
                pass = "";
        }
-       statusbar_print_all(_("Connecting to IMAP4 server %s...\n"),
+       statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
                                account->recv_server);
-       if (imap_auth(session, account->userid, pass, account->imap_auth_type) != IMAP_SUCCESS) {
+       if (imap_auth(session, account->userid, pass, account->imap_auth_type) != MAILIMAP_NO_ERROR) {
                statusbar_pop_all();
                
                if (!failed) {
@@ -967,7 +1177,7 @@ try_again:
                return;
        } 
 
-       statusbar_pop_all();
+       statuswindow_pop_all();
        session->authenticated = TRUE;
        return;
 }
@@ -1031,6 +1241,120 @@ static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *ms
        g_free(filename);
 }
 
+typedef struct _TagsData {
+       gchar *str;
+       GSList *msglist;
+       IMAPFolderItem *item;
+} TagsData;
+
+static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
+{
+       IMAPSession *session;
+       gint ok, can_create_tags;
+       Folder *folder = NULL;
+       TagsData *ht_data = NULL;
+       GSList *cur;
+
+       g_return_if_fail(item != NULL);
+       g_return_if_fail(msginfo != NULL);
+
+       folder = item->folder;
+       debug_print("getting session...\n");
+       session = imap_session_get(folder);
+       
+       if (!session) {
+               debug_print("can't get session\n");
+               return;
+       }
+
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
+
+       if (ok != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), ok);
+               return;
+       }
+
+       
+       if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
+               return;
+       
+       if (IMAP_FOLDER_ITEM(item)->batching) {
+               /* instead of performing an UID STORE command for each message change,
+                * as a lot of them can change "together", we just fill in hashtables
+                * and defer the treatment so that we're able to send only one
+                * command.
+                */
+               debug_print("IMAP batch mode on, deferring tags change\n");
+               for (cur = tags_set; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       if (cur_tag) {
+                               ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
+                                       GINT_TO_POINTER(cur_tag));
+                               if (ht_data == NULL) {
+                                       ht_data = g_new0(TagsData, 1);
+                                       ht_data->str = g_strdup(tags_get_tag(cur_tag));
+                                       ht_data->item = IMAP_FOLDER_ITEM(item);
+                                       g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
+                                               GINT_TO_POINTER(cur_tag), ht_data);
+                               }
+                               ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
+                       } 
+               }
+               for (cur = tags_unset; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       if (cur_tag) {
+                               ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
+                                       GINT_TO_POINTER(cur_tag));
+                               if (ht_data == NULL) {
+                                       ht_data = g_new0(TagsData, 1);
+                                       ht_data->str = g_strdup(tags_get_tag(cur_tag));
+                                       ht_data->item = IMAP_FOLDER_ITEM(item);
+                                       g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
+                                               GINT_TO_POINTER(cur_tag), ht_data);
+                               }
+                               ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
+                       }
+               }
+       } else {
+               GSList *list_set = NULL;
+               GSList *list_unset = NULL;
+               GSList numlist;
+               
+               numlist.data = GINT_TO_POINTER(msginfo->msgnum);
+               numlist.next = NULL;
+       
+               debug_print("IMAP changing tags NOW\n");
+               for (cur = tags_set; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       const gchar *str = tags_get_tag(cur_tag);
+                       list_set = g_slist_prepend(list_set, g_strdup(str));
+               }
+               if (list_set) {
+                       ok = imap_set_message_flags(session, &numlist, 0, list_set, TRUE);
+                       slist_free_strings(list_set);
+                       g_slist_free(list_set);
+                       if (ok != MAILIMAP_NO_ERROR) {
+                               return;
+                       }
+               }
+
+               for (cur = tags_unset; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       const gchar *str = tags_get_tag(cur_tag);
+                       list_unset = g_slist_prepend(list_unset, g_strdup(str));
+               }
+               if (list_unset) {
+                       ok = imap_set_message_flags(session, &numlist, 0, list_unset, FALSE);
+                       slist_free_strings(list_unset);
+                       g_slist_free(list_unset);
+                       if (ok != MAILIMAP_NO_ERROR) {
+                               return;
+                       }
+               }
+       }
+}
+
 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                                  gboolean headers, gboolean body)
 {
@@ -1055,22 +1379,40 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                 * or not. As the IMAP server reports size with \r chars,
                 * we have to update the local file (UNIX \n only) size */
                MsgInfo *cached = msgcache_get_msg(item->cache,uid);
-               guint have_size = get_file_size_with_crs(filename);
+               guint have_size = -1;
 
                if (cached)
-                       debug_print("message %d has been already %scached (%d/%d).\n", uid,
-                               have_size >= cached->size ? "fully ":"",
-                               have_size, (int)cached->size);
+                       debug_print("message %d has been already %scached.\n", uid,
+                               MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
                
-               if (cached && (cached->size <= have_size || !body)) {
+               if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
+                       have_size = get_file_size_with_crs(filename);
+                       if (cached && (cached->size <= have_size || !body)) {
+                               procmsg_msginfo_free(cached);
+                               ok = file_strip_crs(filename);
+                               if (ok == 0 && cached && cached->size <= have_size) {
+                                       /* we have it all and stripped */
+                                       debug_print("...fully cached in fact; setting flag.\n");
+                                       procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
+                               }
+                               return filename;
+                       } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
+                               debug_print("message not cached and file recent, considering file complete\n");
+                               ok = file_strip_crs(filename);
+                               if (ok == 0)
+                                       return filename;
+                       } else {
+                               procmsg_msginfo_free(cached);
+                       }
+               }
+               if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
                        procmsg_msginfo_free(cached);
-                       file_strip_crs(filename);
                        return filename;
-               } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
-                       debug_print("message not cached and file recent, considering file complete\n");
-                       file_strip_crs(filename);
-                       return filename;
-               } else {
+               }
+       } else {
+               MsgInfo *cached = msgcache_get_msg(item->cache,uid);
+               if (cached) {
+                       procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
                        procmsg_msginfo_free(cached);
                }
        }
@@ -1082,29 +1424,47 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                g_free(filename);
                return NULL;
        }
+       session_set_access_time(SESSION(session));
+       lock_session(session); /* unlocked later in the function */
 
        debug_print("IMAP fetching messages\n");
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
-       if (ok != IMAP_SUCCESS) {
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       if (ok != MAILIMAP_NO_ERROR) {
                g_warning("can't select mailbox %s\n", item->path);
                g_free(filename);
-               unlock_session(session);
                return NULL;
        }
 
+       session_set_access_time(SESSION(session));
+
        debug_print("getting message %d...\n", uid);
        ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
 
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                g_warning("can't fetch message %d\n", uid);
                g_free(filename);
-               unlock_session(session);
                return NULL;
        }
 
+       session_set_access_time(SESSION(session));
        unlock_session(session);
-       file_strip_crs(filename);
+
+       ok = file_strip_crs(filename);
+
+       if (ok == 0 && headers && body) {
+               MsgInfo *cached = msgcache_get_msg(item->cache,uid);
+               if (cached) {
+                       procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
+                       procmsg_msginfo_free(cached);
+               }
+       } else if (ok == -1) {
+               MsgInfo *cached = msgcache_get_msg(item->cache,uid);
+               if (cached) {
+                       procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
+                       procmsg_msginfo_free(cached);
+               }
+       }
        return filename;
 }
 
@@ -1117,6 +1477,10 @@ static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint
        if (!cached)
                return FALSE;
 
+       if (MSG_IS_FULLY_CACHED(cached->flags)) {
+               procmsg_msginfo_free(cached);
+               return TRUE;
+       }
        path = folder_item_get_path(item);
        if (!is_dir_exist(path))
                return FALSE;
@@ -1127,6 +1491,7 @@ static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint
                if (cached && cached->total_size == cached->size) {
                        /* fast path */
                        g_free(filename);
+                       procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
                        return TRUE;
                }
                size = get_file_size_with_crs(filename);
@@ -1134,6 +1499,7 @@ static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint
        }
        if (cached && size >= cached->size) {
                cached->total_size = cached->size;
+               procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
                procmsg_msginfo_free(cached);
                return TRUE;
        }
@@ -1176,41 +1542,6 @@ static gint imap_add_msg(Folder *folder, FolderItem *dest,
        return ret;
 }
 
-static gint imap_get_msg_from_local(Folder *folder, FolderItem *dest, const gchar *real_file)
-{
-       /* don't get session, already done. */
-       MsgInfo *msginfo;
-       MsgFlags flags = {0, 0};
-       gint msgnum = 0;
-       msginfo = procheader_parse_file(real_file, flags, FALSE, FALSE);
-
-       if (msginfo && msginfo->msgid) {
-               GSList *msglist = folder_item_get_msg_list(dest);
-               GSList *cur;
-               gint found_num = 0;
-
-               /* gets last matching mail with msgid. Slower than by msgid but gets the
-                * most recent one */
-               for (cur = msglist ; cur != NULL ; cur = cur->next) {
-                       MsgInfo * r_msginfo;
-
-                       r_msginfo = (MsgInfo *) cur->data;
-                       
-                       if (r_msginfo->msgid && !strcmp(r_msginfo->msgid,msginfo->msgid)) {
-                               if (found_num < r_msginfo->msgnum) {
-                                       found_num = r_msginfo->msgnum;
-                               }
-                       }
-                       procmsg_msginfo_free(r_msginfo);
-               }
-               msgnum = found_num;
-               g_slist_free(msglist);
-
-       }
-       procmsg_msginfo_free(msginfo);
-       return msgnum;
-}
-
 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                   GRelation *relation)
 {
@@ -1219,7 +1550,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        guint32 last_uid = 0;
        GSList *cur;
        MsgFileInfo *fileinfo;
-       gint ok;
+       gint ok = MAILIMAP_NO_ERROR;
        gint curnum = 0, total = 0;
        gboolean missing_uids = FALSE;
 
@@ -1266,11 +1597,10 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                ok = imap_cmd_append(session, destdir, real_file, iflags, 
                                     &new_uid);
 
-               if (ok != IMAP_SUCCESS) {
+               if (ok != MAILIMAP_NO_ERROR) {
                        g_warning("can't append message %s\n", real_file);
                        g_free(real_file);
                        g_free(destdir);
-                       unlock_session(session);
                        statusbar_progress_all(0,0,0);
                        statusbar_pop_all();
                        return -1;
@@ -1310,52 +1640,23 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                g_free(real_file);
        }
        
-       if (missing_uids) {
-               unlock_session(IMAP_SESSION(REMOTE_FOLDER(folder)->session));
-               folder_item_scan_full(dest, FALSE);
-               lock_session(IMAP_SESSION(REMOTE_FOLDER(folder)->session));
-               for (cur = file_list; cur != NULL; cur = cur->next) {
-                       guint32 new_uid = 0;
-                       fileinfo = (MsgFileInfo *)cur->data;
-                       
-                       if (!fileinfo->file)
-                               continue;
-
-                       new_uid = imap_get_msg_from_local(folder, dest, fileinfo->file);
-                       debug_print("new uid %d from scanning\n", new_uid);
-                       if (new_uid > 0) {
-                               gchar *cache_path = folder_item_get_path(dest);
-                               if (!is_dir_exist(cache_path))
-                                       make_dir_hier(cache_path);
-                               if (is_dir_exist(cache_path)) {
-                                       gchar *cache_file = g_strconcat(
-                                               cache_path, G_DIR_SEPARATOR_S, 
-                                               itos(new_uid), NULL);
-                                       copy_file(fileinfo->file, cache_file, TRUE);
-                                       debug_print("copied to cache: %s\n", cache_file);
-                                       g_free(cache_file);
-                               }
-                               g_free(cache_path);
-                               g_relation_delete(relation, fileinfo->msginfo != NULL ? 
-                                                 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
-                                                 0);
-
-                               g_relation_insert(relation, fileinfo->msginfo != NULL ? 
-                                                 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
-                                                 GINT_TO_POINTER(new_uid));
-                       }
-                       if (last_uid < new_uid) {
-                               last_uid = new_uid;
-                       }
-               }
-       }
        statusbar_progress_all(0,0,0);
        statusbar_pop_all();
        
-       unlock_session(session);
        
        g_free(destdir);
 
+       imap_scan_required(folder, dest);
+
+       session = imap_session_get(folder);
+       if (!session) {
+               return -1;
+       }
+       if (missing_uids) {
+               gint a;
+               ok = imap_select(session, IMAP_FOLDER(folder), dest,
+                        &a, NULL, NULL, NULL, NULL, FALSE);
+       }
        return last_uid;
 }
 
@@ -1393,7 +1694,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        GSList *seq_list, *cur;
        MsgInfo *msginfo;
        IMAPSession *session;
-       gint ok = IMAP_SUCCESS;
+       gint ok = MAILIMAP_NO_ERROR;
        GRelation *uid_mapping;
        gint last_num = 0;
        gboolean single = FALSE;
@@ -1415,7 +1716,6 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        src = msginfo->folder;
        if (src == dest) {
                g_warning("the src folder is identical to the dest.\n");
-               unlock_session(session);
                return -1;
        }
 
@@ -1430,7 +1730,6 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                        infolist = g_slist_prepend(infolist, fileinfo);
                }
                infolist = g_slist_reverse(infolist);
-               unlock_session(session);
                res = folder_item_add_msgs(dest, infolist, FALSE);
                for (cur = infolist; cur; cur = cur->next) {
                        MsgFileInfo *info = (MsgFileInfo *)cur->data;
@@ -1441,15 +1740,18 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                return res;
        } 
 
-       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-                        NULL, NULL, NULL, NULL, FALSE);
-       if (ok != IMAP_SUCCESS) {
-               unlock_session(session);
+       lock_session(session); /* unlocked later in the function */
+
+       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
 
+       unlock_session(session);
+
        destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
-       seq_list = imap_get_lep_set_from_msglist(msglist);
+       seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
        uid_mapping = g_relation_new(2);
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
        
@@ -1463,10 +1765,16 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                debug_print("Copying messages from %s to %s ...\n",
                            src->path, destdir);
 
+               lock_session(session); /* unlocked later in the function */
                ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
                        &source, &dest);
                
-               if (ok == IMAP_SUCCESS) {
+               if (is_fatal(ok)) {
+                       session = NULL;
+               }
+
+               if (ok == MAILIMAP_NO_ERROR) {
+                       unlock_session(session);
                        if (relation && source && dest) {
                                GSList *s_list = flatten_mailimap_set(source);
                                GSList *d_list = flatten_mailimap_set(dest);
@@ -1493,10 +1801,9 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                if (dest)
                        mailimap_set_free(dest);
 
-               if (ok != IMAP_SUCCESS) {
+               if (ok != MAILIMAP_NO_ERROR) {
                        g_relation_destroy(uid_mapping);
                        imap_lep_set_free(seq_list);
-                       unlock_session(session);
                        statusbar_pop_all();
                        return -1;
                }
@@ -1556,8 +1863,8 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
        IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
 
-       unlock_session(session);
-       if (ok == IMAP_SUCCESS)
+       imap_scan_required(folder, dest);
+       if (ok == MAILIMAP_NO_ERROR)
                return last_num;
        else
                return -1;
@@ -1600,7 +1907,7 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        GSList *numlist = NULL, *cur;
        MsgInfo *msginfo;
        IMAPSession *session;
-       gint ok = IMAP_SUCCESS;
+       gint ok = MAILIMAP_NO_ERROR;
        GRelation *uid_mapping;
        
        g_return_val_if_fail(folder != NULL, -1);
@@ -1613,12 +1920,13 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
                return -1;
        }
 
+       lock_session(session); /* unlocked later in the function */
+
        msginfo = (MsgInfo *)msglist->data;
 
-       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-                        NULL, NULL, NULL, NULL, FALSE);
-       if (ok != IMAP_SUCCESS) {
-               unlock_session(session);
+       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
 
@@ -1633,20 +1941,23 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        uid_mapping = g_relation_new(2);
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
 
-       ok = imap_set_message_flags
-               (session, numlist, IMAP_FLAG_DELETED, TRUE);
-       if (ok != IMAP_SUCCESS) {
-               log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
-               unlock_session(session);
-               return ok;
-       }
+       if (numlist != NULL) {
+               ok = imap_set_message_flags
+                       (session, numlist, IMAP_FLAG_DELETED, NULL, TRUE);
+               if (ok != MAILIMAP_NO_ERROR) {
+                       log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
+                       return ok;
+               }
+       } /* else we just need to expunge */
        ok = imap_cmd_expunge(session);
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't expunge\n"));
-               unlock_session(session);
                return ok;
        }
        
+       session->folder_content_changed = TRUE;
+       unlock_session(session);
+
        dir = folder_item_get_path(msginfo->folder);
        if (is_dir_exist(dir)) {
                for (cur = msglist; cur; cur = cur->next) {
@@ -1659,9 +1970,10 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        g_relation_destroy(uid_mapping);
        g_slist_free(numlist);
 
+       imap_scan_required(folder, dest);
+
        g_free(destdir);
-       unlock_session(session);
-       if (ok == IMAP_SUCCESS)
+       if (ok == MAILIMAP_NO_ERROR)
                return 0;
        else
                return -1;
@@ -1703,7 +2015,7 @@ static gint imap_close(Folder *folder, FolderItem *item)
        return 0;
 }
 
-gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
+static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
 {
        FolderItem *item = NULL;
        IMAPSession *session;
@@ -1729,7 +2041,7 @@ gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
                int r;
                clist * lep_list;
 
-               Xstrdup_a(root_folder, folder->account->imap_dir, {unlock_session(session);return -1;});
+               Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
                extract_quote(root_folder, '"');
                subst_char(root_folder,
                           imap_get_path_separator(session, IMAP_FOLDER(folder),
@@ -1744,13 +2056,16 @@ gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
 
                r = imap_threaded_list(session->folder, "", real_path,
                                       &lep_list);
+
+               if (r != MAILIMAP_NO_ERROR)
+                       imap_handle_error(SESSION(session), r);
+
                if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
                        if (!folder->node) {
                                item = folder_item_new(folder, folder->name, NULL);
                                item->folder = folder;
                                folder->node = item->node = g_node_new(item);
                        }
-                       unlock_session(session);
                        return -1;
                }
                mailimap_list_result_free(lep_list);
@@ -1775,7 +2090,6 @@ gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
 
        imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
        imap_create_missing_folders(folder);
-       unlock_session(session);
 
        return 0;
 }
@@ -1828,7 +2142,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
        }
 
        Xstrcat_a(wildcard_path, real_path, wildcard,
-                 {g_free(real_path); return IMAP_ERROR;});
+                 {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
        lep_list = NULL;
        
        if (subs_only)
@@ -1837,6 +2151,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
                r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
 
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                item_list = NULL;
        }
        else {
@@ -1932,7 +2247,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
 
        g_slist_free(item_list);
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
@@ -2177,7 +2492,7 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        else if (folder->account->imap_dir && *folder->account->imap_dir) {
                gchar *imap_dir;
 
-               Xstrdup_a(imap_dir, folder->account->imap_dir, {unlock_session(session);return NULL;});
+               Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
                strtailchomp(imap_dir, '/');
                dirpath = g_strconcat(imap_dir, "/", name, NULL);
        } else
@@ -2187,12 +2502,11 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
 
        /* keep trailing directory separator to create a folder that contains
           sub folder */
-       imap_path = imap_utf8_to_modified_utf7(dirpath);
+       imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
 
        strtailchomp(dirpath, '/');
        Xstrdup_a(new_name, name, {
                g_free(dirpath); 
-               unlock_session(session);                
                return NULL;});
 
        separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
@@ -2208,12 +2522,12 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                argbuf = g_ptr_array_new();
                r = imap_threaded_list(folder, "", imap_path, &lep_list);
                if (r != MAILIMAP_NO_ERROR) {
+                       imap_handle_error(SESSION(session), r);
                        log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
                        g_free(imap_path);
                        g_free(dirpath);
                        ptr_array_free_strings(argbuf);
                        g_ptr_array_free(argbuf, TRUE);
-                       unlock_session(session);
                        return NULL;
                }
                
@@ -2223,11 +2537,10 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                lep_list = NULL;
                if (!exist) {
                        ok = imap_cmd_create(session, imap_path);
-                       if (ok != IMAP_SUCCESS) {
+                       if (ok != MAILIMAP_NO_ERROR) {
                                log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
                                g_free(imap_path);
                                g_free(dirpath);
-                               unlock_session(session);
                                return NULL;
                        }
                        r = imap_threaded_list(folder, "", imap_path, &lep_list);
@@ -2241,6 +2554,8 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                                        g_slist_free(item_list);
                                } 
                                mailimap_list_result_free(lep_list);
+                       } else {
+                               imap_handle_error(SESSION(session), r);
                        }
                }
                imap_threaded_subscribe(folder, imap_path, TRUE);
@@ -2259,6 +2574,8 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                                g_slist_free(item_list);
                        } 
                        mailimap_list_result_free(lep_list);
+               } else {
+                       imap_handle_error(SESSION(session), r);
                }
        }
 
@@ -2273,10 +2590,10 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        if (!is_dir_exist(dirpath))
                make_dir_hier(dirpath);
        g_free(dirpath);
-       unlock_session(session);
 
        if (exist) {
                /* folder existed, scan it */
+               imap_scan_required(folder, new_item);
                folder_item_scan_full(new_item, FALSE);
        }
 
@@ -2313,7 +2630,6 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
                g_warning(_("New folder name must not contain the namespace "
                            "path separator"));
-               unlock_session(session);
                return -1;
        }
 
@@ -2321,11 +2637,13 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
 
        g_free(session->mbox);
        session->mbox = NULL;
+       session->exists = 0;
+       session->recent = 0;
+       session->expunge = 0;
        ok = imap_cmd_examine(session, "INBOX",
                              &exists, &recent, &unseen, &uid_validity, FALSE);
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                g_free(real_oldpath);
-               unlock_session(session);
                return -1;
        }
 
@@ -2337,17 +2655,16 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        } else
                newpath = g_strdup(name);
 
-       real_newpath = imap_utf8_to_modified_utf7(newpath);
+       real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
        imap_path_separator_subst(real_newpath, separator);
 
        ok = imap_cmd_rename(session, real_oldpath, real_newpath);
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
                            real_oldpath, real_newpath);
                g_free(real_oldpath);
                g_free(newpath);
                g_free(real_newpath);
-               unlock_session(session);
                return -1;
        }
        g_free(item->name);
@@ -2373,7 +2690,6 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        g_free(newpath);
        g_free(real_oldpath);
        g_free(real_newpath);
-       unlock_session(session);
        return 0;
 }
 
@@ -2410,6 +2726,7 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
        IMAPSession *session;
        gchar *path;
        gchar *cache_dir;
+       gboolean selected_folder;
 
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(item != NULL, -1);
@@ -2423,8 +2740,19 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
        path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
 
        imap_threaded_subscribe(folder, path, FALSE);
+
+       selected_folder = (session->mbox != NULL) &&
+                         (!strcmp(session->mbox, item->path));
+       if (selected_folder) {
+               ok = imap_cmd_close(session);
+               if (ok != MAILIMAP_NO_ERROR) {
+                       debug_print("close err %d\n", ok);
+                       imap_handle_error(SESSION(session), ok);
+                       return ok;
+               }
+       }
        ok = imap_cmd_delete(session, path);
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                gchar *tmp = g_strdup_printf("%s%c", path, 
                                imap_get_path_separator(session, IMAP_FOLDER(folder), path));
                g_free(path);
@@ -2432,10 +2760,9 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
                ok = imap_cmd_delete(session, path);
        }
 
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
                g_free(path);
-               unlock_session(session);
                return -1;
        }
 
@@ -2445,7 +2772,6 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
                g_warning("can't remove directory '%s'\n", cache_dir);
        g_free(cache_dir);
        folder_item_remove(item);
-       unlock_session(session);
        return 0;
 }
 
@@ -2478,6 +2804,7 @@ typedef struct _uncached_data {
        guint cur;
        guint total;
        gboolean done;
+       int ok;
 } uncached_data;
 
 static void *imap_get_uncached_messages_thread(void *data)
@@ -2486,10 +2813,10 @@ static void *imap_get_uncached_messages_thread(void *data)
        IMAPSession *session = stuff->session;
        FolderItem *item = stuff->item;
        MsgNumberList *numlist = stuff->numlist;
-       
        GSList *newlist = NULL;
        GSList *llast = NULL;
        GSList *seq_list, *cur;
+       gboolean got_alien_tags = FALSE;
 
        debug_print("uncached_messages\n");
        
@@ -2499,7 +2826,7 @@ static void *imap_get_uncached_messages_thread(void *data)
                return NULL;
        }
        
-       seq_list = imap_get_lep_set_from_numlist(numlist);
+       seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
        debug_print("get msgs info\n");
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
                struct mailimap_set * imapset;
@@ -2515,20 +2842,52 @@ static void *imap_get_uncached_messages_thread(void *data)
                
                r = imap_threaded_fetch_env(session->folder,
                                            imapset, &env_list);
-               if (r != MAILIMAP_NO_ERROR)
+               if (r != MAILIMAP_NO_ERROR) {
+                       imap_handle_error(SESSION(session), r);
+                       if (is_fatal(r)) {
+                               stuff->ok = r;
+                               return NULL;
+                       }
                        continue;
-               
+               }
+
                session_set_access_time(SESSION(session));
 
                count = 0;
-               for(i = 0 ; i < carray_count(env_list) ; i ++) {
+               for(i = 0 ; i < carray_count(env_list) ; i += 2) {
                        struct imap_fetch_env_info * info;
                        MsgInfo * msginfo;
-                       
+                       GSList *tags = NULL, *cur = NULL;
                        info = carray_get(env_list, i);
+                       tags = carray_get(env_list, i+1);
                        msginfo = imap_envelope_from_lep(info, item);
-                       if (msginfo == NULL)
+                       if (msginfo == NULL) {
+                               slist_free_strings(tags);
+                               g_slist_free(tags);
                                continue;
+                       }
+                       if (tags != NULL) {
+                               g_slist_free(msginfo->tags);
+                               msginfo->tags = NULL;
+                       }
+                       for (cur = tags; cur; cur = cur->next) {
+                               gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
+                               gint id = 0;
+                               id = tags_get_id_for_str(real_tag);
+                               printf("tag %s %d\n", real_tag, id);
+                               if (id == -1) {
+                                       id = tags_add_tag(real_tag);
+                                       got_alien_tags = TRUE;
+                               }
+                               if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
+                                       msginfo->tags = g_slist_append(
+                                                       msginfo->tags,
+                                                       GINT_TO_POINTER(id));
+                               }
+                               g_free(real_tag);
+                       }
+                       slist_free_strings(tags);
+                       g_slist_free(tags);
                        msginfo->folder = item;
                        if (!newlist)
                                llast = newlist = g_slist_append(newlist, msginfo);
@@ -2542,6 +2901,11 @@ static void *imap_get_uncached_messages_thread(void *data)
                imap_fetch_env_free(env_list);
        }
        
+       if (got_alien_tags) {
+               tags_write_tags();
+               main_window_reflect_tags_changes(mainwindow_get_mainwindow());
+       }
+
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
                struct mailimap_set * imapset;
                
@@ -2558,7 +2922,8 @@ static void *imap_get_uncached_messages_thread(void *data)
 
 static GSList *imap_get_uncached_messages(IMAPSession *session,
                                        FolderItem *item,
-                                       MsgNumberList *numlist)
+                                       MsgNumberList *numlist,
+                                       int *r)
 {
        GSList *result = NULL;
        GSList * cur;
@@ -2568,6 +2933,7 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
        finished = 0;
        cur = numlist;
        data->total = g_slist_length(numlist);
+       data->ok = MAILIMAP_NO_ERROR;
        debug_print("messages list : %i\n", data->total);
 
        while (cur != NULL) {
@@ -2613,13 +2979,17 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
                
                partial_result =
                        (GSList *)imap_get_uncached_messages_thread(data);
-               
+               *r = data->ok;
+               if (data->ok != MAILIMAP_NO_ERROR) {
+                       goto bail;
+               }
                statusbar_progress_all(data->cur,data->total, 1);
                
                g_slist_free(newlist);
                
                result = g_slist_concat(result, partial_result);
        }
+bail:
        g_free(data);
        
        statusbar_progress_all(0,0,0);
@@ -2668,7 +3038,6 @@ gchar imap_get_path_separator_for_item(FolderItem *item)
        debug_print("getting session...");
        session = imap_session_get(FOLDER(folder));
        result = imap_get_path_separator(session, imap_folder, item->path);
-       unlock_session(session);
        return result;
 }
 
@@ -2682,6 +3051,7 @@ static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folde
        r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
        
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                log_warning(LOG_PROTOCOL, _("LIST failed\n"));
                return '\0';
        }
@@ -2726,7 +3096,7 @@ static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(path != NULL, NULL);
 
-       real_path = imap_utf8_to_modified_utf7(path);
+       real_path = imap_utf8_to_modified_utf7(path, FALSE);
        separator = imap_get_path_separator(session, folder, path);
        imap_path_separator_subst(real_path, separator);
 
@@ -2736,26 +3106,60 @@ static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const
 static gint imap_set_message_flags(IMAPSession *session,
                                   MsgNumberList *numlist,
                                   IMAPFlags flags,
+                                  GSList *tags,
                                   gboolean is_set)
 {
        gint ok = 0;
        GSList *seq_list;
        GSList * cur;
+       gint total = 0;
+       IMAPFolder *folder = NULL;
+       GSList *sorted_list = NULL;
+
+       if (numlist == NULL || session == NULL)
+               return MAILIMAP_ERROR_BAD_STATE;
+       
+       folder = IMAP_FOLDER(session->folder);
+       
+       sorted_list = g_slist_copy(numlist);
+       sorted_list = g_slist_sort(sorted_list, g_int_compare);
+       
+       cur = g_slist_last(sorted_list);
 
-       seq_list = imap_get_lep_set_from_numlist(numlist);
+       if (cur)
+               total = GPOINTER_TO_INT(cur->data);
        
+       seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
+
+       statusbar_print_all(_("Flagging messages..."));
+
        for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
-               struct mailimap_set * imapset;
-               
-               imapset = cur->data;
-               
+               struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
+               struct mailimap_set_item *set_item = clist_content(
+                                                       clist_begin(imapset->set_list));
+
+               statusbar_progress_all(set_item->set_first, total, 1);
+
                ok = imap_cmd_store(session, imapset,
-                                   flags, is_set);
+                                   flags, tags, is_set);
+               statusbar_progress_all(set_item->set_last, total, 1);
+               if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
+                       /* reduce max set size */
+                       folder->max_set_size /= 2;
+               }
+               if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
+                       break;
+               }
        }
        
+       g_slist_free(sorted_list);
+
+       statusbar_progress_all(0,0,0);
+       statusbar_pop_all();
+
        imap_lep_set_free(seq_list);
        
-       return IMAP_SUCCESS;
+       return ok;
 }
 
 typedef struct _select_data {
@@ -2769,18 +3173,31 @@ typedef struct _select_data {
 } select_data;
 
 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
-                       const gchar *path,
+                       FolderItem *item,
                        gint *exists, gint *recent, gint *unseen,
-                       guint32 *uid_validity, gboolean block)
+                       guint32 *uid_validity, gint *can_create_flags,
+                       gboolean block)
 {
        gchar *real_path;
        gint ok;
        gint exists_, recent_, unseen_;
        guint32 uid_validity_;
-       
-       if (!exists && !recent && !unseen && !uid_validity) {
+       gint can_create_flags_;
+       const gchar *path = item ? item->path:NULL;
+
+       if (!item) {
+               return MAILIMAP_ERROR_BAD_STATE;
+       }
+
+       if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
                if (session->mbox && strcmp(session->mbox, path) == 0)
-                       return IMAP_SUCCESS;
+                       return MAILIMAP_NO_ERROR;
+       }
+       if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
+               if (session->mbox && strcmp(session->mbox, path) == 0) {
+                       if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
+                               return MAILIMAP_NO_ERROR;
+               }
        }
        if (!exists)
                exists = &exists_;
@@ -2790,19 +3207,37 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
                unseen = &unseen_;
        if (!uid_validity)
                uid_validity = &uid_validity_;
+       if (!can_create_flags)
+               can_create_flags = &can_create_flags_;
 
        g_free(session->mbox);
        session->mbox = NULL;
+       session->exists = 0;
+       session->recent = 0;
+       session->expunge = 0;
 
        real_path = imap_get_real_path(session, folder, path);
 
        ok = imap_cmd_select(session, real_path,
-                            exists, recent, unseen, uid_validity, block);
-       if (ok != IMAP_SUCCESS)
+                            exists, recent, unseen, uid_validity, can_create_flags, block);
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
-       else {
+       else {
                session->mbox = g_strdup(path);
                session->folder_content_changed = FALSE;
+               session->exists = *exists;
+               session->recent = *recent;
+               session->expunge = 0;
+               session->unseen = *unseen;
+               session->uid_validity = *uid_validity;
+               debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
+                       session->exists, session->recent, session->expunge,
+                       session->uid_validity, *can_create_flags);
+       }
+       if (*can_create_flags) {
+               IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
+       } else {
+               IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
        }
        g_free(real_path);
 
@@ -2845,8 +3280,9 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
            !strcmp(session->mbox, item->item.path)) {
                r = imap_cmd_close(session);
                if (r != MAILIMAP_NO_ERROR) {
+                       imap_handle_error(SESSION(session), r);
                        debug_print("close err %d\n", r);
-                       return IMAP_ERROR;
+                       return r;
                }
        }
        
@@ -2855,14 +3291,15 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
 
        g_free(real_path);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("status err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
        
        if (data_status->st_info_list == NULL) {
                mailimap_mailbox_data_status_free(data_status);
                debug_print("status->st_info_list == NULL\n");
-               return IMAP_ERROR;
+               return MAILIMAP_ERROR_BAD_STATE;
        }
        
        got_values = 0;
@@ -2906,7 +3343,7 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
        if (got_values != mask) {
                g_warning("status: incomplete values received (%d)\n", got_values);
        }
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static void imap_free_capabilities(IMAPSession *session)
@@ -2926,20 +3363,21 @@ static gint imap_cmd_login(IMAPSession *session,
        gint ok;
 
        if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
-               gint ok = IMAP_ERROR;
+               gint ok = MAILIMAP_ERROR_BAD_STATE;
                if (imap_has_capability(session, "STARTTLS")) {
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
                        log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
                        ok = imap_cmd_starttls(session);
-                       if (ok != IMAP_SUCCESS) {
+                       if (ok != MAILIMAP_NO_ERROR) {
                                log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
-                               return IMAP_ERROR;
+                               return ok;
                        } else {
                                /* refresh capas */
                                imap_free_capabilities(session);
-                               if (imap_get_capabilities(session) != MAILIMAP_NO_ERROR) {
+                               if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
+                                       imap_handle_error(SESSION(session), r);
                                        log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
-                                       return IMAP_ERROR;
+                                       return r;
                                }
                        }
 #else          
@@ -2948,11 +3386,11 @@ static gint imap_cmd_login(IMAPSession *session,
                                        "has been compiled without OpenSSL "
                                        "support.\n"),
                                        SESSION(session)->server);
-                       return IMAP_ERROR;
+                       return MAILIMAP_ERROR_BAD_STATE;
 #endif
                } else {
                        log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
-                       return IMAP_ERROR;
+                       return MAILIMAP_ERROR_BAD_STATE;
                }
        }
 
@@ -2962,13 +3400,14 @@ static gint imap_cmd_login(IMAPSession *session,
                        type);
        r = imap_threaded_login(session->folder, user, pass, type);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
                                SESSION(session)->server);
-               ok = IMAP_ERROR;
+               ok = r;
        } else {
                log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
                                SESSION(session)->server);
-               ok = IMAP_SUCCESS;
+               ok = MAILIMAP_NO_ERROR;
        }
        return ok;
 }
@@ -2976,20 +3415,43 @@ static gint imap_cmd_login(IMAPSession *session,
 static gint imap_cmd_noop(IMAPSession *session)
 {
        int r;
-       unsigned int exists;
+       unsigned int exists, recent, expunge, unseen, uidnext, uidval;
        
-       r = imap_threaded_noop(session->folder, &exists);
+       r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("noop err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
+
+       session->folder_content_changed = FALSE;
+
+       if ((exists && exists != session->exists)
+        || (recent && recent != session->recent)
+        || (expunge && expunge != session->expunge)
+        || (unseen && unseen != session->unseen)) {
+               session->folder_content_changed = TRUE;
+       }
+       if (uidnext != 0 && uidnext != session->uid_next) {
+               session->uid_next = uidnext;
+               session->folder_content_changed = TRUE;
+       }
+       if (uidval != 0 && uidval != session->uid_validity) {
+               session->uid_validity = uidval;
+               session->folder_content_changed = TRUE;
+       }
+
        session->exists = exists;
+       session->recent = recent;
+       session->expunge = expunge;
+       session->unseen = unseen;
+
        session_set_access_time(SESSION(session));
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
-#if USE_OPENSSL
+#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
 static gint imap_cmd_starttls(IMAPSession *session)
 {
        int r;
@@ -2997,26 +3459,29 @@ static gint imap_cmd_starttls(IMAPSession *session)
        r = imap_threaded_starttls(session->folder, 
                SESSION(session)->server, SESSION(session)->port);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("starttls err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 #endif
 
 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
                            gint *exists, gint *recent, gint *unseen,
-                           guint32 *uid_validity, gboolean block)
+                           guint32 *uid_validity, gint *can_create_flags,
+                           gboolean block)
 {
        int r;
 
        r = imap_threaded_select(session->folder, folder,
-                                exists, recent, unseen, uid_validity);
+                                exists, recent, unseen, uid_validity, can_create_flags);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("select err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_close(IMAPSession *session)
@@ -3025,12 +3490,16 @@ static gint imap_cmd_close(IMAPSession *session)
 
        r = imap_threaded_close(session->folder);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("close err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
        g_free(session->mbox);
        session->mbox = NULL;
-       return IMAP_SUCCESS;
+       session->exists = 0;
+       session->recent = 0;
+       session->expunge = 0;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
@@ -3042,11 +3511,12 @@ static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
        r = imap_threaded_examine(session->folder, folder,
                                  exists, recent, unseen, uid_validity);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("examine err %d\n", r);
                
-               return IMAP_ERROR;
+               return r;
        }
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
@@ -3055,11 +3525,12 @@ static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
 
        r = imap_threaded_create(session->folder, folder);
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                
-               return IMAP_ERROR;
+               return r;
        }
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
@@ -3070,11 +3541,11 @@ static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
        r = imap_threaded_rename(session->folder, old_folder,
                                 new_folder);
        if (r != MAILIMAP_NO_ERROR) {
-               
-               return IMAP_ERROR;
+               imap_handle_error(SESSION(session), r);
+               return r;
        }
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
@@ -3084,11 +3555,11 @@ static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
 
        r = imap_threaded_delete(session->folder, folder);
        if (r != MAILIMAP_NO_ERROR) {
-               
-               return IMAP_ERROR;
+               imap_handle_error(SESSION(session), r);
+               return r;
        }
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 typedef struct _fetch_data {
@@ -3117,10 +3588,11 @@ static void *imap_cmd_fetch_thread(void *data)
                                                uid, 0, filename);
        }
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("fetch err %d\n", r);
-               return GINT_TO_POINTER(IMAP_ERROR);
+               return GINT_TO_POINTER(MAILIMAP_ERROR_BAD_STATE);
        }
-       return GINT_TO_POINTER(IMAP_SUCCESS);
+       return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
 }
 
 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
@@ -3158,18 +3630,23 @@ static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
        struct mailimap_flag_list * flag_list;
        int r;
        
-       g_return_val_if_fail(file != NULL, IMAP_ERROR);
+       g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
 
-       flag_list = imap_flag_to_lep(flags);
+       flag_list = imap_flag_to_lep(flags, NULL);
+       lock_session(session);
        r = imap_threaded_append(session->folder, destfolder,
                         file, flag_list, (int *)new_uid);
        mailimap_flag_list_free(flag_list);
 
        if (r != MAILIMAP_NO_ERROR) {
+               imap_handle_error(SESSION(session), r);
                debug_print("append err %d\n", r);
-               return IMAP_ERROR;
+               return r;
        }
-       return IMAP_SUCCESS;
+
+       unlock_session(session);
+
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
@@ -3178,28 +3655,28 @@ static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
 {
        int r;
        
-       g_return_val_if_fail(session != NULL, IMAP_ERROR);
-       g_return_val_if_fail(set != NULL, IMAP_ERROR);
-       g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
+       g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
+       g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
+       g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
 
        r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
        if (r != MAILIMAP_NO_ERROR) {
-               
-               return IMAP_ERROR;
+               imap_handle_error(SESSION(session), r);
+               return r;
        }
 
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
-                          IMAPFlags flags, int do_add)
+                          IMAPFlags flags, GSList *tags, int do_add)
 {
        int r;
-       struct mailimap_flag_list * flag_list;
+       struct mailimap_flag_list * flag_list = NULL;
        struct mailimap_store_att_flags * store_att_flags;
        
-       flag_list = imap_flag_to_lep(flags);
-       
+       flag_list = imap_flag_to_lep(flags, tags);
+
        if (do_add)
                store_att_flags =
                        mailimap_store_att_flags_new_add_flags_silent(flag_list);
@@ -3210,11 +3687,11 @@ static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
        r = imap_threaded_store(session->folder, set, store_att_flags);
        mailimap_store_att_flags_free(store_att_flags);
        if (r != MAILIMAP_NO_ERROR) {
-               
-               return IMAP_ERROR;
+               imap_handle_error(SESSION(session), r);
+               return r;
        }
        
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint imap_cmd_expunge(IMAPSession *session)
@@ -3230,207 +3707,28 @@ static gint imap_cmd_expunge(IMAPSession *session)
 
        r = imap_threaded_expunge(session->folder);
        if (r != MAILIMAP_NO_ERROR) {
-               
-               return IMAP_ERROR;
-       }
-
-       return IMAP_SUCCESS;
-}
-
-static void imap_path_separator_subst(gchar *str, gchar separator)
-{
-       gchar *p;
-       gboolean in_escape = FALSE;
-
-       if (!separator || separator == '/') return;
-
-       for (p = str; *p != '\0'; p++) {
-               if (*p == '/' && !in_escape)
-                       *p = separator;
-               else if (*p == '&' && *(p + 1) != '-' && !in_escape)
-                       in_escape = TRUE;
-               else if (*p == '-' && in_escape)
-                       in_escape = FALSE;
-       }
-}
-
-static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
-{
-       static iconv_t cd = (iconv_t)-1;
-       static gboolean iconv_ok = TRUE;
-       GString *norm_utf7;
-       gchar *norm_utf7_p;
-       size_t norm_utf7_len;
-       const gchar *p;
-       gchar *to_str, *to_p;
-       size_t to_len;
-       gboolean in_escape = FALSE;
-
-       if (!iconv_ok) return g_strdup(mutf7_str);
-
-       if (cd == (iconv_t)-1) {
-               cd = iconv_open(CS_INTERNAL, CS_UTF_7);
-               if (cd == (iconv_t)-1) {
-                       g_warning("iconv cannot convert UTF-7 to %s\n",
-                                 CS_INTERNAL);
-                       iconv_ok = FALSE;
-                       return g_strdup(mutf7_str);
-               }
-       }
-
-       /* modified UTF-7 to normal UTF-7 conversion */
-       norm_utf7 = g_string_new(NULL);
-
-       for (p = mutf7_str; *p != '\0'; p++) {
-               /* replace: '&'  -> '+',
-                           "&-" -> '&',
-                           escaped ','  -> '/' */
-               if (!in_escape && *p == '&') {
-                       if (*(p + 1) != '-') {
-                               g_string_append_c(norm_utf7, '+');
-                               in_escape = TRUE;
-                       } else {
-                               g_string_append_c(norm_utf7, '&');
-                               p++;
-                       }
-               } else if (in_escape && *p == ',') {
-                       g_string_append_c(norm_utf7, '/');
-               } else if (in_escape && *p == '-') {
-                       g_string_append_c(norm_utf7, '-');
-                       in_escape = FALSE;
-               } else {
-                       g_string_append_c(norm_utf7, *p);
-               }
-       }
-
-       norm_utf7_p = norm_utf7->str;
-       norm_utf7_len = norm_utf7->len;
-       to_len = strlen(mutf7_str) * 5;
-       to_p = to_str = g_malloc(to_len + 1);
-
-       if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
-                 &to_p, &to_len) == -1) {
-               g_warning(_("iconv cannot convert UTF-7 to %s\n"),
-                         conv_get_locale_charset_str());
-               g_string_free(norm_utf7, TRUE);
-               g_free(to_str);
-               return g_strdup(mutf7_str);
-       }
-
-       /* second iconv() call for flushing */
-       iconv(cd, NULL, NULL, &to_p, &to_len);
-       g_string_free(norm_utf7, TRUE);
-       *to_p = '\0';
-
-       return to_str;
-}
-
-static gchar *imap_utf8_to_modified_utf7(const gchar *from)
-{
-       static iconv_t cd = (iconv_t)-1;
-       static gboolean iconv_ok = TRUE;
-       gchar *norm_utf7, *norm_utf7_p;
-       size_t from_len, norm_utf7_len;
-       GString *to_str;
-       gchar *from_tmp, *to, *p;
-       gboolean in_escape = FALSE;
-
-       if (!iconv_ok) return g_strdup(from);
-
-       if (cd == (iconv_t)-1) {
-               cd = iconv_open(CS_UTF_7, CS_INTERNAL);
-               if (cd == (iconv_t)-1) {
-                       g_warning(_("iconv cannot convert %s to UTF-7\n"),
-                                 CS_INTERNAL);
-                       iconv_ok = FALSE;
-                       return g_strdup(from);
-               }
-       }
-
-       /* UTF-8 to normal UTF-7 conversion */
-       Xstrdup_a(from_tmp, from, return g_strdup(from));
-       from_len = strlen(from);
-       norm_utf7_len = from_len * 5;
-       Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
-       norm_utf7_p = norm_utf7;
-
-#define IS_PRINT(ch) (isprint(ch) && IS_ASCII(ch))
-
-       while (from_len > 0) {
-               if (*from_tmp == '+') {
-                       *norm_utf7_p++ = '+';
-                       *norm_utf7_p++ = '-';
-                       norm_utf7_len -= 2;
-                       from_tmp++;
-                       from_len--;
-               } else if (IS_PRINT(*(guchar *)from_tmp)) {
-                       /* printable ascii char */
-                       *norm_utf7_p = *from_tmp;
-                       norm_utf7_p++;
-                       norm_utf7_len--;
-                       from_tmp++;
-                       from_len--;
-               } else {
-                       size_t conv_len = 0;
-
-                       /* unprintable char: convert to UTF-7 */
-                       p = from_tmp;
-                       while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
-                               conv_len += g_utf8_skip[*(guchar *)p];
-                               p += g_utf8_skip[*(guchar *)p];
-                       }
-
-                       from_len -= conv_len;
-                       if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
-                                 &conv_len,
-                                 &norm_utf7_p, &norm_utf7_len) == -1) {
-                               g_warning(_("iconv cannot convert UTF-8 to UTF-7\n"));
-                               return g_strdup(from);
-                       }
-
-                       /* second iconv() call for flushing */
-                       iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
-               }
-       }
-
-#undef IS_PRINT
-
-       *norm_utf7_p = '\0';
-       to_str = g_string_new(NULL);
-       for (p = norm_utf7; p < norm_utf7_p; p++) {
-               /* replace: '&' -> "&-",
-                           '+' -> '&',
-                           "+-" -> '+',
-                           BASE64 '/' -> ',' */
-               if (!in_escape && *p == '&') {
-                       g_string_append(to_str, "&-");
-               } else if (!in_escape && *p == '+') {
-                       if (*(p + 1) == '-') {
-                               g_string_append_c(to_str, '+');
-                               p++;
-                       } else {
-                               g_string_append_c(to_str, '&');
-                               in_escape = TRUE;
-                       }
-               } else if (in_escape && *p == '/') {
-                       g_string_append_c(to_str, ',');
-               } else if (in_escape && *p == '-') {
-                       g_string_append_c(to_str, '-');
-                       in_escape = FALSE;
-               } else {
-                       g_string_append_c(to_str, *p);
-               }
+               imap_handle_error(SESSION(session), r);
+               return r;
        }
 
-       if (in_escape) {
-               in_escape = FALSE;
-               g_string_append_c(to_str, '-');
-       }
+       return MAILIMAP_NO_ERROR;
+}
+
+static void imap_path_separator_subst(gchar *str, gchar separator)
+{
+       gchar *p;
+       gboolean in_escape = FALSE;
 
-       to = to_str->str;
-       g_string_free(to_str, FALSE);
+       if (!separator || separator == '/') return;
 
-       return to;
+       for (p = str; *p != '\0'; p++) {
+               if (*p == '/' && !in_escape)
+                       *p = separator;
+               else if (*p == '&' && *(p + 1) != '-' && !in_escape)
+                       in_escape = TRUE;
+               else if (*p == '-' && in_escape)
+                       in_escape = FALSE;
+       }
 }
 
 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
@@ -3473,39 +3771,26 @@ static gboolean imap_rename_folder_func(GNode *node, gpointer data)
        return FALSE;
 }
 
-typedef struct _get_list_uid_data {
-       Folder *folder;
-       IMAPSession *session;
-       IMAPFolderItem *item;
-       GSList **msgnum_list;
-       gboolean done;
-} get_list_uid_data;
-
-static void *get_list_of_uids_thread(void *data)
+static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
 {
-       get_list_uid_data *stuff = (get_list_uid_data *)data;
-       Folder *folder = stuff->folder;
-       IMAPFolderItem *item = stuff->item;
-       GSList **msgnum_list = stuff->msgnum_list;
-       gint ok, nummsgs = 0, lastuid_old;
-       IMAPSession *session;
        GSList *uidlist, *elem;
        int r = -1;
        clist * lep_uidlist;
+       gint ok, nummsgs = 0, lastuid_old;
 
-       session = stuff->session;
        if (session == NULL) {
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(-1);
+               return -1;
        }
-       /* no session locking here, it's already locked by caller */
-       ok = imap_select(session, IMAP_FOLDER(folder), item->item.path,
-                        NULL, NULL, NULL, NULL, TRUE);
-       if (ok != IMAP_SUCCESS) {
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(-1);
+
+       ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
+                        NULL, NULL, NULL, NULL, NULL, TRUE);
+       if (ok != MAILIMAP_NO_ERROR) {
+               return -1;
        }
 
+       g_slist_free(item->uid_list);
+       item->uid_list = NULL;
+
        uidlist = NULL;
        
        if (folder->account && folder->account->low_bandwidth) {
@@ -3521,6 +3806,8 @@ static void *get_list_of_uids_thread(void *data)
                uidlist = g_slist_concat(fetchuid_list, uidlist);
        } else {
                carray * lep_uidtab;
+               if (r != -1) /* inited */
+                       imap_handle_error(SESSION(session), r);
                r = imap_threaded_fetch_uid(folder, 1,
                                    &lep_uidtab);
                if (r == MAILIMAP_NO_ERROR) {
@@ -3532,53 +3819,26 @@ static void *get_list_of_uids_thread(void *data)
        }
        
        if (r != MAILIMAP_NO_ERROR) {
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(-1);
+               imap_handle_error(SESSION(session), r);
+               return -1;
        }
 
        lastuid_old = item->lastuid;
-       *msgnum_list = g_slist_copy(item->uid_list);
-       nummsgs = g_slist_length(*msgnum_list);
-       debug_print("Got %d uids from cache\n", g_slist_length(item->uid_list));
 
        for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
                guint msgnum;
 
                msgnum = GPOINTER_TO_INT(elem->data);
-               if (msgnum > lastuid_old) {
-                       *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
-                       item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
-                       nummsgs++;
 
-                       if(msgnum > item->lastuid)
-                               item->lastuid = msgnum;
-               }
+               *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
+               item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
+               nummsgs++;
        }
        g_slist_free(uidlist);
-       stuff->done = TRUE;
-       return GINT_TO_POINTER(nummsgs);
-}
 
-static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
-{
-       gint result;
-       get_list_uid_data *data = g_new0(get_list_uid_data, 1);
-       data->done = FALSE;
-       data->folder = folder;
-       data->item = item;
-       data->msgnum_list = msgnum_list;
-       data->session = session;
-       if (prefs_common.work_offline && 
-           !inc_offline_should_override(FALSE,
-               _("Claws Mail needs network access in order "
-                 "to access the IMAP server."))) {
-               g_free(data);
-               return -1;
-       }
+       unlock_session(session); /* locked from imap_get_num_list */
 
-       result = GPOINTER_TO_INT(get_list_of_uids_thread(data));
-       g_free(data);
-       return result;
+       return nummsgs;
 
 }
 
@@ -3586,11 +3846,11 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
 {
        IMAPFolderItem *item = (IMAPFolderItem *)_item;
        IMAPSession *session;
-       gint ok, nummsgs = 0, exists;
-       guint32 uid_next = 0, uid_val = 0;
+       gint nummsgs;
        GSList *uidlist = NULL;
        gchar *dir;
        gboolean selected_folder;
+       gint known_list_len = 0;
        debug_print("get_num_list\n");
        
        g_return_val_if_fail(folder != NULL, -1);
@@ -3599,10 +3859,31 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
        g_return_val_if_fail(folder->account != NULL, -1);
 
+       known_list_len = g_slist_length(item->uid_list);
+       if (!item->should_update) {
+               debug_print("get_num_list: nothing to update\n");
+               *old_uids_valid = TRUE;
+               if (known_list_len == item->item.total_msgs
+                && known_list_len > 0) {
+                       *msgnum_list = g_slist_copy(item->uid_list);
+                       return known_list_len;
+               } else {
+                       debug_print("don't know the list length...\n");
+               }
+       }
+
+       if (prefs_common.work_offline && 
+           !inc_offline_should_override(FALSE,
+               _("Claws Mail needs network access in order "
+                 "to access the IMAP server."))) {
+               return -1;
+       }
+       
        debug_print("getting session...\n");
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, -1);
 
+       lock_session(session); /* unlocked by get_list_of_uids */
        if (FOLDER_ITEM(item)->path) 
                statusbar_print_all(_("Scanning folder %s%c%s ..."),
                                      FOLDER_ITEM(item)->folder->name, 
@@ -3614,115 +3895,31 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
 
        selected_folder = (session->mbox != NULL) &&
                          (!strcmp(session->mbox, item->item.path));
-       if (selected_folder && time(NULL) - item->use_cache < 2) {
-               ok = imap_cmd_noop(session);
-               if (ok != IMAP_SUCCESS) {
-                       debug_print("disconnected!\n");
-                       session = imap_reconnect_if_possible(folder, session);
-                       if (session == NULL) {
-                               statusbar_pop_all();
-                               unlock_session(session);
-                               return -1;
-                       }
-               }
-               exists = session->exists;
+       
+       if (item->should_trash_cache) {
+               *old_uids_valid = FALSE;
+               debug_print("get_num_list: trashing num list\n");
+               debug_print("Freeing imap uid cache\n");
+               item->lastuid = 0;
+               g_slist_free(item->uid_list);
+               item->uid_list = NULL;
 
-               uid_next = item->c_uid_next;
-               uid_val = item->c_uid_validity;
-               *old_uids_valid = TRUE;
+               imap_delete_all_cached_messages((FolderItem *)item);
        } else {
-               if (item->use_cache && time(NULL) - item->use_cache < 2) {
-                       exists = item->c_messages;
-                       uid_next = item->c_uid_next;
-                       uid_val = item->c_uid_validity;
-                       ok = IMAP_SUCCESS;
-                       debug_print("using cache %d %d %d\n", exists, uid_next, uid_val);
-               } else {
-                       ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, item,
-                                &exists, &uid_next, &uid_val, NULL, FALSE);
-               }
-               item->item.last_num = uid_next - 1;
-               
-               item->use_cache = (time_t)0;
-               if (ok != IMAP_SUCCESS) {
-                       statusbar_pop_all();
-                       unlock_session(session);
-                       return -1;
-               }
-               if(item->item.mtime == uid_val)
-                       *old_uids_valid = TRUE;
-               else {
-                       *old_uids_valid = FALSE;
-
-                       debug_print("Freeing imap uid cache (%d != %d)\n",
-                                       (int)item->item.mtime, uid_val);
-                       item->lastuid = 0;
-                       g_slist_free(item->uid_list);
-                       item->uid_list = NULL;
-               
-                       item->item.mtime = uid_val;
-
-                       imap_delete_all_cached_messages((FolderItem *)item);
-               }
-       }
-
-       /* If old uid_next matches new uid_next we can be sure no message
-          was added to the folder */
-       debug_print("uid_next is %d and item->uid_next %d \n", 
-               uid_next, item->uid_next);
-       if (uid_next == item->uid_next) {
-               nummsgs = g_slist_length(item->uid_list);
-
-               /* If number of messages is still the same we
-                   know our caches message numbers are still valid,
-                   otherwise if the number of messages has decrease
-                  we discard our cache to start a new scan to find
-                  out which numbers have been removed */
-               if (exists == nummsgs) {
-                       debug_print("exists == nummsgs\n");
-                       *msgnum_list = g_slist_copy(item->uid_list);
-                       statusbar_pop_all();
-                       unlock_session(session);
-                       return nummsgs;
-               } else if (exists < nummsgs) {
-                       debug_print("Freeing imap uid cache");
-                       item->lastuid = 0;
-                       g_slist_free(item->uid_list);
-                       item->uid_list = NULL;
-               }
-       }
-
-       if (exists == 0) {
-               *msgnum_list = NULL;
-               statusbar_pop_all();
-               unlock_session(session);
-               return 0;
+               debug_print("get_num_list: updating num list\n");
+               *old_uids_valid = TRUE;
        }
 
-       item->last_change = time(NULL);
        nummsgs = get_list_of_uids(session, folder, item, &uidlist);
+       /* session could be broken now, in case of fatal error */
+
+       debug_print("get_num_list: got %d msgs\n", nummsgs);
 
        if (nummsgs < 0) {
                statusbar_pop_all();
-               unlock_session(session);
                return -1;
        }
 
-       if (nummsgs != exists) {
-               /* Cache contains more messages then folder, we have cached
-                   an old UID of a message that was removed and new messages
-                   have been added too, otherwise the uid_next check would
-                  not have failed */
-               debug_print("Freeing imap uid cache");
-               item->lastuid = 0;
-               g_slist_free(item->uid_list);
-               item->uid_list = NULL;
-
-               g_slist_free(*msgnum_list);
-
-               nummsgs = get_list_of_uids(session, folder, item, &uidlist);
-       }
-
        *msgnum_list = uidlist;
 
        dir = folder_item_get_path((FolderItem *)item);
@@ -3730,11 +3927,10 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        remove_numbered_files_not_in_list(dir, *msgnum_list);
        g_free(dir);
        
-       item->uid_next = uid_next;
-       
        debug_print("get_num_list - ok - %i\n", nummsgs);
        statusbar_pop_all();
-       unlock_session(session);
+       item->should_trash_cache = FALSE;
+       item->should_update = FALSE;
        return nummsgs;
 }
 
@@ -3781,21 +3977,27 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, NULL);
 
+       lock_session(session); /* unlocked later in the function */
+
        debug_print("IMAP getting msginfos\n");
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
-       if (ok != IMAP_SUCCESS) {
-               unlock_session(session);
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       if (ok != MAILIMAP_NO_ERROR) {
                return NULL;
        }
        if (!(folder_has_parent_of_type(item, F_DRAFT) || 
              folder_has_parent_of_type(item, F_QUEUE))) {
                ret = g_slist_concat(ret,
                        imap_get_uncached_messages(session, item,
-                                                  msgnum_list));
+                                                  msgnum_list, &ok));
+               if (ok != MAILIMAP_NO_ERROR)
+                       return NULL;
+               unlock_session(session);
        } else {
                MsgNumberList *sorted_list, *elem, *llast = NULL;
                gint startnum, lastnum;
+       
+               unlock_session(session);
 
                sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
 
@@ -3812,9 +4014,7 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
                                int i;
                                for (i = startnum; i <= lastnum; ++i) {
                                        gchar *file;
-                                       unlock_session(session);
                                        file = imap_fetch_msg(folder, item, i);
-                                       lock_session(session);
                                        if (file != NULL) {
                                                MsgInfo *msginfo = imap_parse_msg(file, item);
                                                if (msginfo != NULL) {
@@ -3828,7 +4028,6 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
                                                }
                                                g_free(file);
                                        }
-                                       session_set_access_time(SESSION(session));
                                }
 
                                if (elem == NULL)
@@ -3841,7 +4040,6 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
 
                g_slist_free(sorted_list);
        }
-       unlock_session(session);
        return ret;
 }
 
@@ -3879,50 +4077,79 @@ gboolean imap_scan_required(Folder *folder, FolderItem *_item)
        if (item->item.path == NULL)
                return FALSE;
 
+       if (item->should_update) {
+               debug_print("scan already required\n");
+               return TRUE;
+       }
        debug_print("getting session...\n");
        session = imap_session_get(folder);
+       
        g_return_val_if_fail(session != NULL, FALSE);
+       lock_session(session); /* unlocked later in the function */
 
        selected_folder = (session->mbox != NULL) &&
                          (!strcmp(session->mbox, item->item.path));
-       if (selected_folder && time(NULL) - item->use_cache < 2) {
-               ok = imap_cmd_noop(session);
-               if (ok != IMAP_SUCCESS) {
-                       debug_print("disconnected!\n");
-                       session = imap_reconnect_if_possible(folder, session);
-                       if (session == NULL)
-                               return FALSE;
-               }
+       if (selected_folder) {
+               if (!session->folder_content_changed) {
+                       ok = imap_cmd_noop(session);
+                       if (ok != MAILIMAP_NO_ERROR) {
+                               debug_print("disconnected!\n");
+                               if (!is_fatal(ok))
+                                       session = imap_reconnect_if_possible(folder, session);
+                               else
+                                       session = imap_session_get(folder);
+                               if (session == NULL)
+                                       return FALSE;
+                       }
 
-               if (session->folder_content_changed
-               ||  session->exists != item->item.total_msgs) {
+                       if (session->folder_content_changed) {
+                               debug_print("CHANGED (self-noop)! scan_required\n");
+                               item->should_update = TRUE;
+                               if (session->uid_validity && session->uid_validity != item->item.mtime) {
+                                       item->item.mtime = session->uid_validity;
+                                       item->should_trash_cache = TRUE;
+                               }
+                               unlock_session(session);
+                               return TRUE;
+                       }
+               } else {
+                       debug_print("CHANGED (previous noop)! scan_required\n");
+                       item->should_update = TRUE;
+                       if (session->uid_validity && session->uid_validity != item->item.mtime) {
+                               item->item.mtime = session->uid_validity;
+                               item->should_trash_cache = TRUE;
+                       }
                        unlock_session(session);
                        return TRUE;
                }
        } else {
                ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
                                 &exists, &uid_next, &uid_val, &unseen, FALSE);
-               if (ok != IMAP_SUCCESS) {
-                       unlock_session(session);
+               if (ok != MAILIMAP_NO_ERROR) {
                        return FALSE;
                }
-
-               item->use_cache = time(NULL);
-               item->c_messages = exists;
-               item->c_uid_next = uid_next;
-               item->c_uid_validity = uid_val;
-               item->c_unseen = unseen;
-               item->item.last_num = uid_next - 1;
-               debug_print("uidnext %d, item->uid_next %d, exists %d, item->item.total_msgs %d\n", 
-                       uid_next, item->uid_next, exists, item->item.total_msgs);
-               if ((uid_next != item->uid_next) || (exists != item->item.total_msgs)
-                   || unseen != item->item.unread_msgs || uid_val != item->item.mtime) {
-                       unlock_session(session);
+               
+               debug_print("exists %d, item->item.total_msgs %d\n", 
+                       exists, item->item.total_msgs);
+               if (exists != item->item.total_msgs
+                   || unseen != item->item.unread_msgs 
+                   || uid_next != item->uid_next
+                   || uid_val != item->item.mtime) {
+                       debug_print("CHANGED (status)! scan_required\n");
                        item->last_change = time(NULL);
+                       item->should_update = TRUE;
+                       item->uid_next = uid_next;
+                       if (uid_val != item->item.mtime) {
+                               item->item.mtime = uid_val;
+                               item->should_trash_cache = TRUE;
+                       }
+                       unlock_session(session);
                        return TRUE;
                }
        }
        unlock_session(session);
+
+       item->should_update = FALSE;
        return FALSE;
 }
 
@@ -3930,7 +4157,7 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
 {
        IMAPSession *session;
        IMAPFlags flags_set = 0, flags_unset = 0;
-       gint ok = IMAP_SUCCESS;
+       gint ok = MAILIMAP_NO_ERROR;
        MsgNumberList numlist;
        hashtable_data *ht_data = NULL;
 
@@ -3974,9 +4201,8 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                return;
        }
 
-       if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-           NULL, NULL, NULL, NULL, FALSE)) != IMAP_SUCCESS) {
-               unlock_session(session);
+       if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+           NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
                return;
        }
        numlist.next = NULL;
@@ -3994,48 +4220,41 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                                GINT_TO_POINTER(flags_set));
                        if (ht_data == NULL) {
                                ht_data = g_new0(hashtable_data, 1);
-                               ht_data->session = session;
                                ht_data->item = IMAP_FOLDER_ITEM(item);
                                g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table, 
                                        GINT_TO_POINTER(flags_set), ht_data);
                        }
-                       if (!g_slist_find(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum)))
-                               ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
+                       ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
                } 
                if (flags_unset) {
                        ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
                                GINT_TO_POINTER(flags_unset));
                        if (ht_data == NULL) {
                                ht_data = g_new0(hashtable_data, 1);
-                               ht_data->session = session;
                                ht_data->item = IMAP_FOLDER_ITEM(item);
                                g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
                                        GINT_TO_POINTER(flags_unset), ht_data);
                        }
-                       if (!g_slist_find(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum)))
-                               ht_data->msglist = g_slist_prepend(ht_data->msglist, 
+                       ht_data->msglist = g_slist_prepend(ht_data->msglist, 
                                        GINT_TO_POINTER(msginfo->msgnum));              
                }
        } else {
                debug_print("IMAP changing flags\n");
                if (flags_set) {
-                       ok = imap_set_message_flags(session, &numlist, flags_set, TRUE);
-                       if (ok != IMAP_SUCCESS) {
-                               unlock_session(session);
+                       ok = imap_set_message_flags(session, &numlist, flags_set, NULL, TRUE);
+                       if (ok != MAILIMAP_NO_ERROR) {
                                return;
                        }
                }
 
                if (flags_unset) {
-                       ok = imap_set_message_flags(session, &numlist, flags_unset, FALSE);
-                       if (ok != IMAP_SUCCESS) {
-                               unlock_session(session);
+                       ok = imap_set_message_flags(session, &numlist, flags_unset, NULL, FALSE);
+                       if (ok != MAILIMAP_NO_ERROR) {
                                return;
                        }
                }
        }
        msginfo->flags.perm_flags = newflags;
-       unlock_session(session);
        return;
 }
 
@@ -4054,20 +4273,18 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        session = imap_session_get(folder);
        if (!session) return -1;
 
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
-       if (ok != IMAP_SUCCESS) {
-               unlock_session(session);
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
        numlist.next = NULL;
        numlist.data = GINT_TO_POINTER(uid);
        
        ok = imap_set_message_flags
-               (session, &numlist, IMAP_FLAG_DELETED, TRUE);
-       if (ok != IMAP_SUCCESS) {
+               (session, &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
-               unlock_session(session);
                return ok;
        }
 
@@ -4080,9 +4297,8 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
                ok = imap_cmd_expunge(session);
                g_free(uidstr);
        }
-       if (ok != IMAP_SUCCESS) {
+       if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't expunge\n"));
-               unlock_session(session);
                return ok;
        }
 
@@ -4092,8 +4308,7 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        if (is_dir_exist(dir))
                remove_numbered_files(dir, uid, uid);
        g_free(dir);
-       unlock_session(session);
-       return IMAP_SUCCESS;
+       return MAILIMAP_NO_ERROR;
 }
 
 static gint compare_msginfo(gconstpointer a, gconstpointer b)
@@ -4143,8 +4358,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        carray * lep_uidtab;
        IMAPSession *session;
        gint ok;
-       int r;
+       int r = MAILIMAP_NO_ERROR;
        GHashTable *flags_hash = NULL;
+       GHashTable *tags_hash = NULL;
        gboolean full_search = stuff->full_search;
        GSList *sorted_list = NULL;
        GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL;
@@ -4153,8 +4369,10 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        gboolean reverse_seen = FALSE;
        gboolean selected_folder;
        gint exists_cnt, unseen_cnt;
-       
+       gboolean got_alien_tags = FALSE;
+
        session = imap_session_get(folder);
+
        if (session == NULL) {
                stuff->done = TRUE;
                return GINT_TO_POINTER(-1);
@@ -4162,12 +4380,12 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        selected_folder = (session->mbox != NULL) &&
                          (!strcmp(session->mbox, fitem->path));
 
+       lock_session(session);
        if (!selected_folder) {
-               ok = imap_select(session, IMAP_FOLDER(folder), fitem->path,
-                       &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
-               if (ok != IMAP_SUCCESS) {
+               ok = imap_select(session, IMAP_FOLDER(folder), fitem,
+                       &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
+               if (ok != MAILIMAP_NO_ERROR) {
                        stuff->done = TRUE;
-                       unlock_session(session);
                        return GINT_TO_POINTER(-1);
                }
 
@@ -4181,7 +4399,7 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
 
        sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
        if (!full_search) {
-               seq_list = imap_get_lep_set_from_msglist(msginfo_list);
+               seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
        } else {
                struct mailimap_set * set;
                set = mailimap_set_new_interval(1, 0);
@@ -4211,6 +4429,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                mailimap_search_result_free(lep_uidlist);
 
                                unseen = g_slist_concat(unseen, uidlist);
+                       } else {
+                               imap_handle_error(SESSION(session), r);
+                               goto bail;
                        }
 
                        r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
@@ -4222,6 +4443,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                mailimap_search_result_free(lep_uidlist);
 
                                flagged = g_slist_concat(flagged, uidlist);
+                       } else {
+                               imap_handle_error(SESSION(session), r);
+                               goto bail;
                        }
 
                        if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
@@ -4234,6 +4458,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                        mailimap_search_result_free(lep_uidlist);
 
                                        answered = g_slist_concat(answered, uidlist);
+                               } else {
+                                       imap_handle_error(SESSION(session), r);
+                                       goto bail;
                                }
 
                                r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
@@ -4245,6 +4472,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                        mailimap_search_result_free(lep_uidlist);
 
                                        deleted = g_slist_concat(deleted, uidlist);
+                               } else {
+                                       imap_handle_error(SESSION(session), r);
+                                       goto bail;
                                }
                        }
                }
@@ -4256,11 +4486,20 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        } else {
                r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
                if (r == MAILIMAP_NO_ERROR) {
-                       flags_hash = g_hash_table_new_full(g_int_hash, g_int_equal, free, NULL);
-                       imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash);
+                       flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
+                       tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
+                       imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
                        imap_fetch_uid_flags_list_free(lep_uidtab);
+               } else {
+                       imap_handle_error(SESSION(session), r);
+                       goto bail;
                }
        }
+
+bail:
+       if (r == MAILIMAP_NO_ERROR)
+               unlock_session(session);
+       
        for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
                MsgInfo *msginfo;
                MsgPermFlags flags, oldflags;
@@ -4304,13 +4543,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                        }
                } else {
                        if (flags_hash != NULL) {
-                               gint * puid;
 
-                               puid = malloc(sizeof(* puid));
-                               * puid = msginfo->msgnum;
-
-                               flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, puid));
-                               free(puid);
+                               flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, 
+                                               GINT_TO_POINTER(msginfo->msgnum)));
                        }
 
                        if ((flags & MSG_UNREAD) == 0)
@@ -4318,13 +4553,47 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                        else if (wasnew)
                                flags |= MSG_NEW;
                        flags |= oldflags;
+                       
+                       if (tags_hash != NULL) {
+                               GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
+                               GSList *cur;
+
+                               if (tags != NULL) {
+                                       g_slist_free(msginfo->tags);
+                                       msginfo->tags = NULL;
+                               }
+                               for (cur = tags; cur; cur = cur->next) {
+                                       gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
+                                       gint id = 0;
+                                       id = tags_get_id_for_str(real_tag);
+                                       if (id == -1) {
+                                               id = tags_add_tag(real_tag);
+                                               got_alien_tags = TRUE;
+                                       }
+                                       if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
+                                               msginfo->tags = g_slist_append(
+                                                               msginfo->tags,
+                                                               GINT_TO_POINTER(id));
+                                       }
+                                       g_free(real_tag);
+                               }
+                               slist_free_strings(tags);
+                               g_slist_free(tags);
+                       }
                }
 
                g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
        }
        
+       if (got_alien_tags) {
+               tags_write_tags();
+               main_window_reflect_tags_changes(mainwindow_get_mainwindow());
+       }
+
        if (flags_hash)
                g_hash_table_destroy(flags_hash);
+       if (tags_hash)
+               g_hash_table_destroy(tags_hash);
 
        imap_lep_set_free(seq_list);
        g_slist_free(flagged);
@@ -4333,7 +4602,6 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        g_slist_free(unseen);
        g_slist_free(sorted_list);
 
-       unlock_session(session);
        stuff->done = TRUE;
        return GINT_TO_POINTER(0);
 }
@@ -4384,7 +4652,7 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
        hashtable_data *data = (hashtable_data *)value;
        IMAPFolderItem *_item = data->item;
        FolderItem *item = (FolderItem *)_item;
-       gint ok = IMAP_ERROR;
+       gint ok = MAILIMAP_ERROR_BAD_STATE;
        IMAPSession *session = NULL;
        
        debug_print("getting session...\n");
@@ -4397,18 +4665,64 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
                flags_value,
                g_slist_length(data->msglist));
        
+       lock_session(session);
        if (session) {
-               ok = imap_select(session, IMAP_FOLDER(item->folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+               ok = imap_select(session, IMAP_FOLDER(item->folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        }
-       if (ok == IMAP_SUCCESS) {
-               imap_set_message_flags(data->session, data->msglist, flags_value, flags_set);
+       if (ok == MAILIMAP_NO_ERROR) {
+               ok = imap_set_message_flags(session, data->msglist, flags_value, NULL, flags_set);
        } else {
                g_warning("can't select mailbox %s\n", item->path);
        }
 
-       unlock_session(session);
+       if (!is_fatal(ok))
+               unlock_session(session);
+
+       g_slist_free(data->msglist);    
+       g_free(data);
+       return TRUE;
+}
+
+static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
+{
+       gboolean tags_set = GPOINTER_TO_INT(user_data);
+       TagsData *data = (TagsData *)value;
+       IMAPFolderItem *_item = data->item;
+       FolderItem *item = (FolderItem *)_item;
+       gchar *str = data->str;
+       gint ok = MAILIMAP_ERROR_BAD_STATE;
+       IMAPSession *session = NULL;
+       
+       debug_print("getting session...\n");
+       session = imap_session_get(item->folder);
+
+       data->msglist = g_slist_reverse(data->msglist);
+       
+       debug_print("IMAP %ssetting tags %s for %d messages\n",
+               tags_set?"":"un",
+               str,
+               g_slist_length(data->msglist));
+       
+       lock_session(session);
+       if (session) {
+               ok = imap_select(session, IMAP_FOLDER(item->folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       }
+       if (ok == MAILIMAP_NO_ERROR) {
+               GSList list;
+               list.data = str;
+               list.next = NULL;
+               ok = imap_set_message_flags(session, data->msglist, 0, &list, tags_set);
+       } else {
+               g_warning("can't select mailbox %s\n", item->path);
+       }
+
+       if (!is_fatal(ok))
+               unlock_session(session);
+
        g_slist_free(data->msglist);    
+       g_free(data->str);
        g_free(data);
        return TRUE;
 }
@@ -4425,11 +4739,23 @@ static void process_hashtable(IMAPFolderItem *item)
                g_hash_table_destroy(item->flags_unset_table);
                item->flags_unset_table = NULL;
        }
+       if (item->tags_set_table) {
+               g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
+               g_hash_table_destroy(item->tags_set_table);
+               item->tags_set_table = NULL;
+       }
+       if (item->tags_unset_table) {
+               g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
+               g_hash_table_destroy(item->tags_unset_table);
+               item->tags_unset_table = NULL;
+       }
+       
 }
 
 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
 {
        IMAPFolderItem *item = (IMAPFolderItem *)_item;
+       IMAPSession *session;
 
        g_return_if_fail(item != NULL);
        
@@ -4445,11 +4771,27 @@ static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
                if (!item->flags_unset_table) {
                        item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
                }
+               if (!item->tags_set_table) {
+                       item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
+               }
+               if (!item->tags_unset_table) {
+                       item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
+               }
+               session = imap_session_get(folder);
+               if (session) {
+                       imap_refresh_sensitivity(session);
+                       session->sens_update_block = TRUE;
+               }
        } else {
                debug_print("IMAP switching away from batch mode\n");
                /* process stuff */
                process_hashtable(item);
                item->batching = FALSE;
+               session = imap_session_get(folder);
+               if (session) {
+                       session->sens_update_block = FALSE;
+                       imap_refresh_sensitivity(session);
+               }
        }
 }
 
@@ -4550,8 +4892,8 @@ static GSList * imap_list_from_lep(IMAPFolder * folder,
                        dup_name[strlen(dup_name)-1] = '\0';
                }
                
-               loc_name = imap_modified_utf7_to_utf8(base);
-               loc_path = imap_modified_utf7_to_utf8(dup_name);
+               loc_name = imap_modified_utf7_to_utf8(base, FALSE);
+               loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
                
                new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
                if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
@@ -4577,19 +4919,17 @@ static GSList * imap_list_from_lep(IMAPFolder * folder,
        return item_list;
 }
 
-static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist)
+static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
 {
        GSList *sorted_list, *cur;
        guint first, last, next;
        GSList *ret_list = NULL, *llast = NULL;
-       unsigned int count;
        struct mailimap_set * current_set;
        unsigned int item_count;
        
        if (numlist == NULL)
                return NULL;
        
-       count = 0;
        current_set = mailimap_set_new_empty();
        
        sorted_list = g_slist_copy(numlist);
@@ -4610,16 +4950,15 @@ static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist)
                else
                        next = 0;
 
-               if (last + 1 != next || next == 0) {
+               if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
 
                        struct mailimap_set_item * item;
                        item = mailimap_set_item_new(first, last);
                        mailimap_set_add(current_set, item);
-                       count ++;
                        
                        first = next;
-                       
-                       if (count >= IMAP_SET_MAX_COUNT) {
+
+                       if (item_count >= folder->max_set_size) {
                                if (ret_list == NULL)
                                        llast = ret_list = g_slist_append(ret_list,
                                                          current_set);
@@ -4627,11 +4966,11 @@ static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist)
                                        llast = g_slist_append(llast, current_set);
                                        llast = llast->next;
                                }
+
                                current_set = mailimap_set_new_empty();
-                               count = 0;
                                item_count = 0;
                        }
-               }
+               } 
        }
        
        if (clist_count(current_set->set_list) > 0) {
@@ -4644,7 +4983,7 @@ static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist)
        return ret_list;
 }
 
-static GSList * imap_get_lep_set_from_msglist(MsgInfoList *msglist)
+static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
 {
        MsgNumberList *numlist = NULL;
        MsgInfoList *cur;
@@ -4656,7 +4995,7 @@ static GSList * imap_get_lep_set_from_msglist(MsgInfoList *msglist)
                numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
        }
        numlist = g_slist_reverse(numlist);
-       seq_list = imap_get_lep_set_from_numlist(numlist);
+       seq_list = imap_get_lep_set_from_numlist(folder, numlist);
        g_slist_free(numlist);
 
        return seq_list;
@@ -4699,24 +5038,25 @@ static GSList * imap_uid_list_from_lep_tab(carray * list)
 }
 
 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
-                                                  GHashTable * hash)
+                                                  GHashTable * hash,
+                                                  GHashTable * tags_hash)
 {
        unsigned int i;
        GSList * result;
        
        result = NULL;
        
-       for(i = 0 ; i < carray_count(list) ; i += 2) {
+       for(i = 0 ; i < carray_count(list) ; i += 3) {
                uint32_t * puid;
                int * pflags;
-               gint * pguid;
+               GSList *tags;
                
                puid = carray_get(list, i);
                pflags = carray_get(list, i + 1);
-               pguid = malloc(sizeof(* pguid));
-               * pguid = * puid;
+               tags = carray_get(list, i + 2);
                
-               g_hash_table_insert(hash, pguid, GINT_TO_POINTER(* pflags));
+               g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
+               g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
        }
 }
 
@@ -4764,10 +5104,11 @@ static void imap_lep_set_free(GSList *seq_list)
        g_slist_free(seq_list);
 }
 
-static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags, GSList *tags)
 {
        struct mailimap_flag_list * flag_list;
-       
+       GSList *cur = tags;
+
        flag_list = mailimap_flag_list_new_empty();
        
        if (IMAP_IS_SEEN(flags))
@@ -4786,6 +5127,15 @@ static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
                mailimap_flag_list_add(flag_list,
                                       mailimap_flag_new_draft());
        
+       for (; cur; cur = cur->next) {
+               gchar *enc_str = 
+                       imap_utf8_to_modified_utf7(cur->data, TRUE);
+               g_strstrip(enc_str);
+       
+               mailimap_flag_list_add(flag_list,
+                       mailimap_flag_new_flag_keyword(enc_str));
+       }
+
        return flag_list;
 }
 
@@ -4837,7 +5187,7 @@ void imap_cancel_all(void)
                                IMAPSession *imap_session;
                                RemoteFolder *rfolder;
                                
-                               fprintf(stderr, "cancelled\n");
+                               g_printerr("cancelled\n");
                                imap_threaded_cancel(folder);
                                rfolder = (RemoteFolder *) folder;
                                imap_session = (IMAPSession *) rfolder->session;
@@ -4953,11 +5303,6 @@ void imap_disconnect_all(void)
 {
 }
 
-gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
-{
-       return -1;
-}
-
 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
 {
        return -1;
@@ -4983,9 +5328,9 @@ gboolean imap_cancel_all_enabled(void)
 
 #endif
 
-void imap_synchronise(FolderItem *item, gint days) 
-{
 #ifdef HAVE_LIBETPAN
+static void imap_synchronise(FolderItem *item, gint days) 
+{
        if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
                debug_print("%s already synced\n", item->path?item->path:item->name);
                return;
@@ -4993,8 +5338,8 @@ void imap_synchronise(FolderItem *item, gint days)
        debug_print("syncing %s\n", item->path?item->path:item->name);
        imap_gtk_synchronise(item, days);
        IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
-#endif
 }
+#endif
 
 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
 {
@@ -5037,3 +5382,226 @@ static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
 #endif
        return tag;
 }
+
+/* ===================================================================
+ * UTF-7 conversion routines as in RFC 2192
+ * =================================================================== 
+ * These two functions from: 
+ * libimap library.
+ * Copyright (C) 2003-2004 Pawel Salek. */
+
+/* UTF7 modified base64 alphabet */
+static char base64chars[] =
+  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
+#define UNDEFINED 64
+
+/* UTF16 definitions */
+#define UTF16MASK       0x03FFUL
+#define UTF16SHIFT      10
+#define UTF16BASE       0x10000UL
+#define UTF16HIGHSTART  0xD800UL
+#define UTF16HIGHEND    0xDBFFUL
+#define UTF16LOSTART    0xDC00UL
+#define UTF16LOEND      0xDFFFUL
+
+
+/* Convert an IMAP mailbox to a UTF-8 string.
+ *  dst needs to have roughly 4 times the storage space of src
+ *    Hex encoding can triple the size of the input
+ *    UTF-7 can be slightly denser than UTF-8
+ *     (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
+ */
+char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
+{
+  unsigned c, i, bitcount;
+  unsigned long ucs4, utf16, bitbuf;
+  unsigned char base64[256];
+  const char *src;
+  char *dst, *res  = malloc(2*strlen(mbox)+1);
+
+  bitbuf = 0;
+  dst = res;
+  src = mbox;
+  if(!dst) return NULL;
+  /* initialize modified base64 decoding table */
+  memset(base64, UNDEFINED, sizeof (base64));
+  for (i = 0; i < sizeof (base64chars); ++i) {
+    base64[(unsigned)base64chars[i]] = i;
+  }
+
+  /* loop until end of string */
+  while (*src != '\0') {
+    c = *src++;
+    /* deal with literal characters and &- */
+    if (c != '&' || *src == '-') {
+      /* encode literally */
+      if (change_spaces && c == '_')
+       *dst++ = ' ';
+      else
+        *dst++ = c;
+      /* skip over the '-' if this is an &- sequence */
+      if (c == '&') ++src;
+    } else {
+      /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
+      bitbuf = 0;
+      bitcount = 0;
+      ucs4 = 0;
+      while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
+        ++src;
+        bitbuf = (bitbuf << 6) | c;
+        bitcount += 6;
+        /* enough bits for a UTF-16 character? */
+        if (bitcount >= 16) {
+          bitcount -= 16;
+          utf16 = (bitcount ? bitbuf >> bitcount
+                   : bitbuf) & 0xffff;
+          /* convert UTF16 to UCS4 */
+          if
+            (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
+            ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
+            continue;
+          } else if
+            (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
+            ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
+          } else {
+            ucs4 = utf16;
+          }
+
+          /* convert UTF-16 range of UCS4 to UTF-8 */
+          if (ucs4 <= 0x7fUL) {
+            dst[0] = ucs4;
+            dst += 1;
+          } else if (ucs4 <= 0x7ffUL) {
+            dst[0] = 0xc0 | (ucs4 >> 6);
+            dst[1] = 0x80 | (ucs4 & 0x3f);
+            dst += 2;
+          } else if (ucs4 <= 0xffffUL) {
+            dst[0] = 0xe0 | (ucs4 >> 12);
+            dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
+            dst[2] = 0x80 | (ucs4 & 0x3f);
+            dst += 3;
+          } else {
+            dst[0] = 0xf0 | (ucs4 >> 18);
+            dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
+            dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
+            dst[3] = 0x80 | (ucs4 & 0x3f);
+            dst += 4;
+          }
+        }
+      }
+      /* skip over trailing '-' in modified UTF-7 encoding */
+      if (*src == '-') ++src;
+    }
+  }
+  /* terminate destination string */
+  *dst = '\0';
+  return res;
+}
+
+/* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
+ *  dst should be about twice the length of src to deal with non-hex
+ *  coded URLs
+ */
+char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
+{
+  unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
+  unsigned long ucs4 = 0, bitbuf = 0;
+
+  /* initialize hex lookup table */
+  char *dst, *res = malloc(2*strlen(src)+1);
+  dst = res;
+  if(!dst) return NULL;
+
+  utf7mode = 0;
+  utf8total = 0;
+  bitstogo = 0;
+  utf8pos = 0;
+  while ((c = (unsigned char)*src) != '\0') {
+    ++src;
+    /* normal character? */
+    if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
+      /* switch out of UTF-7 mode */
+      if (utf7mode) {
+        if (bitstogo) {
+          *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
+        }
+        *dst++ = '-';
+        utf7mode = 0;
+        utf8pos  = 0;
+        bitstogo = 0;
+        utf8total= 0;
+      }
+      if (change_spaces && c == ' ')
+        *dst++ = '_';
+      else
+       *dst++ = c;
+      /* encode '&' as '&-' */
+      if (c == '&') {
+        *dst++ = '-';
+      }
+      continue;
+    }
+    /* switch to UTF-7 mode */
+    if (!utf7mode) {
+      *dst++ = '&';
+      utf7mode = 1;
+    }
+    /* Encode US-ASCII characters as themselves */
+    if (c < 0x80) {
+      ucs4 = c;
+      utf8total = 1;
+    } else if (utf8total) {
+      /* save UTF8 bits into UCS4 */
+      ucs4 = (ucs4 << 6) | (c & 0x3FUL);
+      if (++utf8pos < utf8total) {
+        continue;
+      }
+    } else {
+      utf8pos = 1;
+      if (c < 0xE0) {
+        utf8total = 2;
+        ucs4 = c & 0x1F;
+      } else if (c < 0xF0) {
+        utf8total = 3;
+        ucs4 = c & 0x0F;
+      } else {
+        /* NOTE: can't convert UTF8 sequences longer than 4 */
+        utf8total = 4;
+        ucs4 = c & 0x03;
+      }
+      continue;
+    }
+    /* loop to split ucs4 into two utf16 chars if necessary */
+    utf8total = 0;
+    do {
+      if (ucs4 >= UTF16BASE) {
+        ucs4 -= UTF16BASE;
+        bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
+                                   + UTF16HIGHSTART);
+        ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
+        utf16flag = 1;
+      } else {
+        bitbuf = (bitbuf << 16) | ucs4;
+        utf16flag = 0;
+      }
+      bitstogo += 16;
+      /* spew out base64 */
+      while (bitstogo >= 6) {
+        bitstogo -= 6;
+        *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
+                              : bitbuf)
+                             & 0x3F];
+      }
+    } while (utf16flag);
+  }
+  /* if in UTF-7 mode, finish in ASCII */
+  if (utf7mode) {
+    if (bitstogo) {
+      *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
+    }
+    *dst++ = '-';
+  }
+  /* tie off string */
+  *dst = '\0';
+  return res;
+}