2007-04-26 [colin] 2.9.1cvs28
[claws.git] / src / imap.c
index 72bf7cf5ddb70006d104d1ed4f37d5ae1edfc787..43656a1add4017b5cc35b6b0073552981b2658c0 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Claws Mail team
+ * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -31,6 +31,7 @@
 #include "imap_gtk.h"
 #include "inc.h"
 #include "xml.h"
+#include "alertpanel.h"
 
 #ifdef HAVE_LIBETPAN
 
@@ -63,7 +64,6 @@
 #include "inputdialog.h"
 #include "log.h"
 #include "remotefolder.h"
-#include "alertpanel.h"
 #include "claws.h"
 #include "statusbar.h"
 #include "msgcache.h"
@@ -110,6 +110,7 @@ struct _IMAPSession
        guint exists;
        Folder * folder;
        gboolean busy;
+       gboolean cancelled;
 };
 
 struct _IMAPNameSpace
@@ -168,6 +169,8 @@ struct _IMAPFolderItem
 
        GHashTable *flags_set_table;
        GHashTable *flags_unset_table;
+       guint32 last_change;
+       guint32 last_sync;
 };
 
 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
@@ -254,7 +257,8 @@ static gint imap_auth                       (IMAPSession    *session,
                                         IMAPAuthType    type);
 
 static gint imap_scan_tree_recursive   (IMAPSession    *session,
-                                        FolderItem     *item);
+                                        FolderItem     *item,
+                                        gboolean        subs_only);
 
 static void imap_create_missing_folders        (Folder         *folder);
 static FolderItem *imap_create_special_folder
@@ -293,11 +297,14 @@ static gint imap_status                   (IMAPSession    *session,
                                         gint           *unseen,
                                         gboolean        block);
 
-static gchar imap_get_path_separator           (IMAPFolder     *folder,
+static gchar imap_get_path_separator           (IMAPSession    *session,
+                                                IMAPFolder     *folder,
                                                 const gchar    *path);
-static gchar *imap_get_real_path               (IMAPFolder     *folder,
+static gchar *imap_get_real_path               (IMAPSession    *session,
+                                                IMAPFolder     *folder,
                                                 const gchar    *path);
 static void imap_synchronise           (FolderItem     *item);
+static gboolean imap_is_busy           (Folder *folder);
 
 static void imap_free_capabilities     (IMAPSession    *session);
 
@@ -538,7 +545,7 @@ static void imap_reset_uid_lists(Folder *folder)
        g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
 }
 
-int imap_get_capabilities(IMAPSession *session)
+static int imap_get_capabilities(IMAPSession *session)
 {
        struct mailimap_capability_data *capabilities = NULL;
        clistiter *cur;
@@ -572,7 +579,7 @@ int imap_get_capabilities(IMAPSession *session)
        return MAILIMAP_NO_ERROR;
 }
 
-gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
+static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
 {
        GSList *cur;
        for (cur = session->capability; cur; cur = cur->next) {
@@ -638,7 +645,7 @@ static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass
                                        "login refused.%s"),
                                        SESSION(session)->server, ext_info);
                        } else {
-                               log_error(_("Connection to %s failed: "
+                               log_error(LOG_PROTOCOL, _("Connection to %s failed: "
                                        "login refused.%s\n"),
                                        SESSION(session)->server, ext_info);
                        }
@@ -655,12 +662,12 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
           connection, if yes we don't try to reconnect */
        debug_print("reconnecting\n");
        if (rfolder->session == NULL) {
-               log_warning(_("Connecting to %s failed"),
+               log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
                            folder->account->recv_server);
                session_destroy(SESSION(session));
                session = NULL;
        } else {
-               log_warning(_("IMAP4 connection to %s has been"
+               log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
                            " disconnected. Reconnecting...\n"),
                            folder->account->recv_server);
                statusbar_print_all(_("IMAP4 connection to %s has been"
@@ -673,6 +680,7 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
                   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);
                statusbar_pop_all();
@@ -680,14 +688,40 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
        return session;
 }
 
-#define lock_session() {\
-       debug_print("locking session\n"); \
-       session->busy = TRUE;\
+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");
+       }
 }
 
-#define unlock_session() {\
-       debug_print("unlocking session\n"); \
-       session->busy = FALSE;\
+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)
@@ -700,7 +734,7 @@ static IMAPSession *imap_session_get(Folder *folder)
        g_return_val_if_fail(folder->account != NULL, NULL);
        
        if (prefs_common.work_offline && 
-           !inc_offline_should_override(
+           !inc_offline_should_override(FALSE,
                _("Claws Mail needs network access in order "
                  "to access the IMAP server."))) {
                return NULL;
@@ -709,18 +743,19 @@ static IMAPSession *imap_session_get(Folder *folder)
        /* Make sure we have a session */
        if (rfolder->session != NULL) {
                session = IMAP_SESSION(rfolder->session);
-               /* don't do that yet... 
-               if (session->busy) {
-                       return NULL;
-               } */
+       } else if (rfolder->connecting) {
+               debug_print("already connecting\n");
+               return NULL;
        } else {
                imap_reset_uid_lists(folder);
                if (time(NULL) - rfolder->last_failure <= 2)
                        return NULL;
+               rfolder->connecting = TRUE;
                session = imap_session_new(folder, folder->account);
        }
        if(session == NULL) {
                rfolder->last_failure = time(NULL);
+               rfolder->connecting = FALSE;
                return NULL;
        }
 
@@ -734,9 +769,12 @@ static IMAPSession *imap_session_get(Folder *folder)
                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
@@ -745,16 +783,19 @@ static IMAPSession *imap_session_get(Folder *folder)
         * A better solution than sending a NOOP every time would be
         * for every command to be prepared to retry until it is
         * successfully sent. -- mbp */
-       if (time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) {
+       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) {
                        debug_print("disconnected!\n");
                        session = imap_reconnect_if_possible(folder, session);
                }
+               
+               session->cancelled = FALSE;
        }
 
        rfolder->session = SESSION(session);
-       
+       rfolder->connecting = FALSE;
+
        return IMAP_SESSION(session);
 }
 
@@ -826,14 +867,14 @@ static IMAPSession *imap_session_new(Folder * folder,
 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
 #ifdef USE_OPENSSL
                if (r == MAILIMAP_ERROR_SSL)
-                       log_error(_("SSL handshake failed\n"));
+                       log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
 #endif
 #endif
                if(!prefs_common.no_recv_err_panel) {
                        alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
                                         account->recv_server, port);
                } else {
-                       log_error(_("Can't connect to IMAP4 server: %s:%d\n"),
+                       log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
                                         account->recv_server, port);
                } 
                
@@ -862,7 +903,7 @@ static IMAPSession *imap_session_new(Folder * folder,
 
                ok = imap_cmd_starttls(session);
                if (ok != IMAP_SUCCESS) {
-                       log_warning(_("Can't start TLS session.\n"));
+                       log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
                        session_destroy(SESSION(session));
                        return NULL;
                }
@@ -873,7 +914,7 @@ static IMAPSession *imap_session_new(Folder * folder,
                session->cmd_count = 1;
        }
 #endif
-       log_message("IMAP connection is %s-authenticated\n",
+       log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
                    (session->authenticated) ? "pre" : "un");
        
        return session;
@@ -910,7 +951,7 @@ try_again:
                        goto try_again;
                } else {
                        if (prefs_common.no_recv_err_panel) {
-                               log_error(_("Couldn't login to IMAP server %s."), account->recv_server);
+                               log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s."), account->recv_server);
                                mainwindow_show_error();
                        } else
                                alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
@@ -940,22 +981,22 @@ static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
        return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
 }
 
-static guint get_size_with_crs(MsgInfo *info
+static guint get_file_size_with_crs(const gchar *filename
 {
        FILE *fp = NULL;
        guint cnt = 0;
        gchar buf[4096];
        
-       if (info == NULL)
+       if (filename == NULL)
                return -1;
        
-       fp = procmsg_open_message(info);
+       fp = fopen(filename, "rb");
        if (!fp)
                return -1;
        
        while (fgets(buf, sizeof (buf), fp) != NULL) {
                cnt += strlen(buf);
-               if (!strstr(buf, "\r") && strstr(buf, "\n"))
+               if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
                        cnt++;
        }
        
@@ -986,9 +1027,8 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                /* see whether the local file represents the whole message
                 * or not. As the IMAP server reports size with \r chars,
                 * we have to update the local file (UNIX \n only) size */
-               MsgInfo *msginfo = imap_parse_msg(filename, item);
                MsgInfo *cached = msgcache_get_msg(item->cache,uid);
-               guint have_size = get_size_with_crs(msginfo);
+               guint have_size = get_file_size_with_crs(filename);
 
                if (cached)
                        debug_print("message %d has been already %scached (%d/%d).\n", uid,
@@ -997,20 +1037,18 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                
                if (cached && (cached->size <= have_size || !body)) {
                        procmsg_msginfo_free(cached);
-                       procmsg_msginfo_free(msginfo);
                        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");
-                       procmsg_msginfo_free(msginfo);
                        file_strip_crs(filename);
                        return filename;
                } else {
                        procmsg_msginfo_free(cached);
-                       procmsg_msginfo_free(msginfo);
                }
        }
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        
        if (!session) {
@@ -1018,15 +1056,13 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                return NULL;
        }
 
-       lock_session();
-
        debug_print("IMAP fetching messages\n");
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
                         NULL, NULL, NULL, NULL, FALSE);
        if (ok != IMAP_SUCCESS) {
                g_warning("can't select mailbox %s\n", item->path);
                g_free(filename);
-               unlock_session();
+               unlock_session(session);
                return NULL;
        }
 
@@ -1036,15 +1072,64 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
        if (ok != IMAP_SUCCESS) {
                g_warning("can't fetch message %d\n", uid);
                g_free(filename);
-               unlock_session();
+               unlock_session(session);
                return NULL;
        }
 
-       unlock_session();
+       unlock_session(session);
        file_strip_crs(filename);
        return filename;
 }
 
+static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
+{
+       gchar *path, *filename;
+       guint size = 0;
+       MsgInfo *cached = msgcache_get_msg(item->cache,uid);
+       
+       if (!cached)
+               return FALSE;
+
+       path = folder_item_get_path(item);
+       if (!is_dir_exist(path))
+               return FALSE;
+
+       filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
+       g_free(path);
+       if (is_file_exist(filename)) {
+               if (cached && cached->total_size == cached->size) {
+                       /* fast path */
+                       g_free(filename);
+                       return TRUE;
+               }
+               size = get_file_size_with_crs(filename);
+               g_free(filename);
+       }
+       if (cached && size >= cached->size) {
+               cached->total_size = cached->size;
+               procmsg_msginfo_free(cached);
+               return TRUE;
+       }
+       if (cached)
+               procmsg_msginfo_free(cached);
+       return FALSE;   
+}
+
+void imap_cache_msg(FolderItem *item, gint msgnum)
+{
+       Folder *folder = NULL;
+       
+       if (!item)
+               return;
+       folder = item->folder;
+       
+       if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
+               gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
+               debug_print("fetched %s\n", tmp);
+               g_free(tmp);
+       }
+}
+
 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
                         const gchar *file, MsgFlags *flags)
 {
@@ -1080,12 +1165,12 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        g_return_val_if_fail(dest != NULL, -1);
        g_return_val_if_fail(file_list != NULL, -1);
        
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                return -1;
        }
-       lock_session();
-       destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
 
        statusbar_print_all(_("Adding messages..."));
        total = g_slist_length(file_list);
@@ -1095,7 +1180,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                gchar *real_file = NULL;
                fileinfo = (MsgFileInfo *)cur->data;
 
-               statusbar_progress_all(curnum, total, 1);
+               statusbar_progress_all(curnum, total, total < 10 ? 1:10);
                curnum++;
 
                if (fileinfo->flags) {
@@ -1123,7 +1208,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                        g_warning("can't append message %s\n", real_file);
                        g_free(real_file);
                        g_free(destdir);
-                       unlock_session();
+                       unlock_session(session);
                        statusbar_progress_all(0,0,0);
                        statusbar_pop_all();
                        return -1;
@@ -1164,7 +1249,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        statusbar_pop_all();
        
        imap_cmd_expunge(session);
-       unlock_session();
+       unlock_session(session);
        
        g_free(destdir);
 
@@ -1188,19 +1273,20 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        g_return_val_if_fail(dest != NULL, -1);
        g_return_val_if_fail(msglist != NULL, -1);
        
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        
        if (!session) {
                return -1;
        }
-       lock_session();
+
        msginfo = (MsgInfo *)msglist->data;
        if (msglist->next == NULL)
                single = TRUE;
        src = msginfo->folder;
        if (src == dest) {
                g_warning("the src folder is identical to the dest.\n");
-               unlock_session();
+               unlock_session(session);
                return -1;
        }
 
@@ -1215,6 +1301,7 @@ 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;
@@ -1228,11 +1315,11 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
                         NULL, NULL, NULL, NULL, FALSE);
        if (ok != IMAP_SUCCESS) {
-               unlock_session();
+               unlock_session(session);
                return ok;
        }
 
-       destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
        seq_list = imap_get_lep_set_from_msglist(msglist);
        uid_mapping = g_relation_new(2);
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
@@ -1273,7 +1360,8 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                if (ok != IMAP_SUCCESS) {
                        g_relation_destroy(uid_mapping);
                        imap_lep_set_free(seq_list);
-                       unlock_session();
+                       unlock_session(session);
+                       statusbar_pop_all();
                        return -1;
                }
        }
@@ -1332,7 +1420,7 @@ 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();
+       unlock_session(session);
        if (ok == IMAP_SUCCESS)
                return last_num;
        else
@@ -1383,21 +1471,22 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        g_return_val_if_fail(dest != NULL, -1);
        g_return_val_if_fail(msglist != NULL, -1);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                return -1;
        }
-       lock_session();
+
        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();
+               unlock_session(session);
                return ok;
        }
 
-       destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
        for (cur = msglist; cur; cur = cur->next) {
                msginfo = (MsgInfo *)cur->data;
                if (!MSG_IS_DELETED(msginfo->flags))
@@ -1409,17 +1498,16 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
 
        ok = imap_set_message_flags
-               (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
-               numlist, IMAP_FLAG_DELETED, TRUE);
+               (session, numlist, IMAP_FLAG_DELETED, TRUE);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't set deleted flags\n"));
-               unlock_session();
+               log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
+               unlock_session(session);
                return ok;
        }
        ok = imap_cmd_expunge(session);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't expunge\n"));
-               unlock_session();
+               log_warning(LOG_PROTOCOL, _("can't expunge\n"));
+               unlock_session(session);
                return ok;
        }
        
@@ -1436,7 +1524,7 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
        g_slist_free(numlist);
 
        g_free(destdir);
-       unlock_session();
+       unlock_session(session);
        if (ok == IMAP_SUCCESS)
                return 0;
        else
@@ -1479,7 +1567,7 @@ static gint imap_close(Folder *folder, FolderItem *item)
        return 0;
 }
 
-static gint imap_scan_tree(Folder *folder)
+gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
 {
        FolderItem *item = NULL;
        IMAPSession *session;
@@ -1488,6 +1576,7 @@ static gint imap_scan_tree(Folder *folder)
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(folder->account != NULL, -1);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                if (!folder->node) {
@@ -1499,21 +1588,20 @@ static gint imap_scan_tree(Folder *folder)
                return -1;
        }
 
-       lock_session();
        if (folder->account->imap_dir && *folder->account->imap_dir) {
                gchar *real_path;
                int r;
                clist * lep_list;
 
-               Xstrdup_a(root_folder, folder->account->imap_dir, {unlock_session();return -1;});
+               Xstrdup_a(root_folder, folder->account->imap_dir, {unlock_session(session);return -1;});
                extract_quote(root_folder, '"');
                subst_char(root_folder,
-                          imap_get_path_separator(IMAP_FOLDER(folder),
+                          imap_get_path_separator(session, IMAP_FOLDER(folder),
                                                   root_folder),
                           '/');
                strtailchomp(root_folder, '/');
                real_path = imap_get_real_path
-                       (IMAP_FOLDER(folder), root_folder);
+                       (session, IMAP_FOLDER(folder), root_folder);
                debug_print("IMAP root directory: %s\n", real_path);
 
                /* check if root directory exist */
@@ -1526,16 +1614,21 @@ static gint imap_scan_tree(Folder *folder)
                                item->folder = folder;
                                folder->node = item->node = g_node_new(item);
                        }
-                       unlock_session();
+                       unlock_session(session);
                        return -1;
                }
                mailimap_list_result_free(lep_list);
-               
+                               
                g_free(real_path);
        }
 
        if (folder->node)
                item = FOLDER_ITEM(folder->node->data);
+               
+       if (item && !item->path && root_folder) {
+               item->path = g_strdup(root_folder);
+       }
+
        if (!item || ((item->path || root_folder) &&
                      strcmp2(item->path, root_folder) != 0)) {
                folder_tree_destroy(folder);
@@ -1544,14 +1637,24 @@ static gint imap_scan_tree(Folder *folder)
                folder->node = item->node = g_node_new(item);
        }
 
-       imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data));
+       imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
        imap_create_missing_folders(folder);
-       unlock_session();
+       unlock_session(session);
 
        return 0;
 }
 
-static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
+static gint imap_scan_tree(Folder *folder)
+{
+       gboolean subs_only = FALSE;
+       if (folder->account) {
+               debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
+               subs_only = folder->account->imap_subsonly;
+       }
+       return imap_scan_tree_real(folder, subs_only);
+}
+
+static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
 {
        Folder *folder;
        IMAPFolder *imapfolder;
@@ -1572,7 +1675,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        folder = item->folder;
        imapfolder = IMAP_FOLDER(folder);
 
-       separator = imap_get_path_separator(imapfolder, item->path);
+       separator = imap_get_path_separator(session, imapfolder, item->path);
 
        if (folder->ui_func)
                folder->ui_func(folder, item, folder->ui_func_data);
@@ -1581,7 +1684,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
                wildcard[0] = separator;
                wildcard[1] = '%';
                wildcard[2] = '\0';
-               real_path = imap_get_real_path(imapfolder, item->path);
+               real_path = imap_get_real_path(session, imapfolder, item->path);
        } else {
                wildcard[0] = '%';
                wildcard[1] = '\0';
@@ -1591,7 +1694,12 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        Xstrcat_a(wildcard_path, real_path, wildcard,
                  {g_free(real_path); return IMAP_ERROR;});
        lep_list = NULL;
-       r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
+       
+       if (subs_only)
+               r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
+       else
+               r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
+
        if (r != MAILIMAP_NO_ERROR) {
                item_list = NULL;
        }
@@ -1617,9 +1725,13 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
                        }
                }
                if (!new_item) {
-                       debug_print("folder '%s' not found. removing...\n",
-                                   old_item->path);
-                       folder_item_remove(old_item);
+                       if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
+                               debug_print("not removing INBOX\n");
+                       } else {
+                               debug_print("folder '%s' not found. removing...\n",
+                                           old_item->path);
+                               folder_item_remove(old_item);
+                       }
                } else {
                        old_item->no_sub = new_item->no_sub;
                        old_item->no_select = new_item->no_select;
@@ -1679,7 +1791,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
                }
 
                if (new_item->no_sub == FALSE)
-                       imap_scan_tree_recursive(session, new_item);
+                       imap_scan_tree_recursive(session, new_item, subs_only);
        }
 
        g_slist_free(item_list);
@@ -1687,6 +1799,104 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        return IMAP_SUCCESS;
 }
 
+GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
+{
+       IMAPSession *session = imap_session_get(folder);
+       gchar *real_path;
+       gchar *wildcard_path;
+       gchar separator;
+       gchar wildcard[3];
+       clist * lep_list;
+       GSList *item_list = NULL, *cur;
+       GList *child_list = NULL, *tmplist = NULL;
+       GSList *sub_list = NULL;
+       int r;
+
+       if (!session)
+               return NULL;
+
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
+
+       if (item->path) {
+               wildcard[0] = separator;
+               wildcard[1] = '%';
+               wildcard[2] = '\0';
+               real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
+       } else {
+               wildcard[0] = '%';
+               wildcard[1] = '\0';
+               real_path = g_strdup("");
+       }
+
+       Xstrcat_a(wildcard_path, real_path, wildcard,
+                 {g_free(real_path); return NULL;});
+       lep_list = NULL;
+       
+       if (unsubs_only)
+               statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
+                               item->path?item->path:item->name);
+       else
+               statusbar_print_all(_("Looking for subfolders of %s..."), 
+                               item->path?item->path:item->name);
+
+       r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
+       if (r) {
+               statusbar_pop_all();
+               return NULL;
+       }
+       item_list = imap_list_from_lep(IMAP_FOLDER(folder),
+                              lep_list, real_path, FALSE);
+       mailimap_list_result_free(lep_list);
+
+       for (cur = item_list; cur != NULL; cur = cur->next) {
+               FolderItem *cur_item = FOLDER_ITEM(cur->data);
+               if (recursive) {
+                       tmplist = imap_scan_subtree(folder, cur_item, 
+                                       unsubs_only, recursive);
+                       if (tmplist)
+                               child_list = g_list_concat(child_list, tmplist);
+               }
+               child_list = g_list_prepend(child_list,
+                               imap_get_real_path(session, 
+                                       IMAP_FOLDER(folder), cur_item->path));
+               
+               folder_item_destroy(cur_item);
+       }
+       child_list = g_list_reverse(child_list);
+       g_slist_free(item_list);
+
+       if (unsubs_only) {
+               r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
+               if (r) {
+                       statusbar_pop_all();
+                       return NULL;
+               }
+               sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
+                                      lep_list, real_path, FALSE);
+               mailimap_list_result_free(lep_list);
+
+               for (cur = sub_list; cur != NULL; cur = cur->next) {
+                       FolderItem *cur_item = FOLDER_ITEM(cur->data);
+                       GList *oldlitem = NULL;
+                       gchar *tmp = imap_get_real_path(session, 
+                                       IMAP_FOLDER(folder), cur_item->path);
+                       folder_item_destroy(cur_item);
+                       oldlitem = g_list_find_custom(
+                                       child_list, tmp, (GCompareFunc)strcmp2);
+                       if (oldlitem) {
+                               child_list = g_list_remove_link(child_list, oldlitem);
+                               g_free(oldlitem->data);
+                               g_list_free(oldlitem);
+                       }
+                       g_free(tmp);
+               }
+       }
+
+       statusbar_pop_all();
+
+       return child_list;
+}
+
 static gint imap_create_tree(Folder *folder)
 {
        g_return_val_if_fail(folder != NULL, -1);
@@ -1809,18 +2019,19 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        const gchar *p;
        gint ok;
        gboolean no_select = FALSE, no_sub = FALSE;
+       gboolean exist = FALSE;
        
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(folder->account != NULL, NULL);
        g_return_val_if_fail(parent != NULL, NULL);
        g_return_val_if_fail(name != NULL, NULL);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                return NULL;
        }
 
-       lock_session();
        if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
                dirpath = g_strdup(name);
        }else if (parent->path)
@@ -1830,7 +2041,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();return NULL;});
+               Xstrdup_a(imap_dir, folder->account->imap_dir, {unlock_session(session);return NULL;});
                strtailchomp(imap_dir, '/');
                dirpath = g_strconcat(imap_dir, "/", name, NULL);
        } else
@@ -1845,29 +2056,28 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        strtailchomp(dirpath, '/');
        Xstrdup_a(new_name, name, {
                g_free(dirpath); 
-               unlock_session();               
+               unlock_session(session);                
                return NULL;});
 
-       separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
        imap_path_separator_subst(imap_path, separator);
        /* remove trailing / for display */
        strtailchomp(new_name, '/');
 
        if (strcmp(dirpath, "INBOX") != 0) {
                GPtrArray *argbuf;
-               gboolean exist = FALSE;
                int r;
                clist * lep_list;
                
                argbuf = g_ptr_array_new();
                r = imap_threaded_list(folder, "", imap_path, &lep_list);
                if (r != MAILIMAP_NO_ERROR) {
-                       log_warning(_("can't create mailbox: LIST failed\n"));
+                       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();
+                       unlock_session(session);
                        return NULL;
                }
                
@@ -1878,10 +2088,10 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                if (!exist) {
                        ok = imap_cmd_create(session, imap_path);
                        if (ok != IMAP_SUCCESS) {
-                               log_warning(_("can't create mailbox\n"));
+                               log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
                                g_free(imap_path);
                                g_free(dirpath);
-                               unlock_session();
+                               unlock_session(session);
                                return NULL;
                        }
                        r = imap_threaded_list(folder, "", imap_path, &lep_list);
@@ -1896,8 +2106,8 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                                } 
                                mailimap_list_result_free(lep_list);
                        }
-
                }
+               imap_threaded_subscribe(folder, imap_path, TRUE);
        } else {
                clist *lep_list;
                int r;
@@ -1927,7 +2137,13 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
        if (!is_dir_exist(dirpath))
                make_dir_hier(dirpath);
        g_free(dirpath);
-       unlock_session();
+       unlock_session(session);
+
+       if (exist) {
+               /* folder existed, scan it */
+               folder_item_scan_full(new_item, FALSE);
+       }
+
        return new_item;
 }
 
@@ -1952,20 +2168,20 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        g_return_val_if_fail(item->path != NULL, -1);
        g_return_val_if_fail(name != NULL, -1);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                return -1;
        }
-       lock_session();
 
-       if (strchr(name, imap_get_path_separator(IMAP_FOLDER(folder), item->path)) != NULL) {
+       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();
+               unlock_session(session);
                return -1;
        }
 
-       real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
+       real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
 
        g_free(session->mbox);
        session->mbox = NULL;
@@ -1973,11 +2189,11 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
                              &exists, &recent, &unseen, &uid_validity, FALSE);
        if (ok != IMAP_SUCCESS) {
                g_free(real_oldpath);
-               unlock_session();
+               unlock_session(session);
                return -1;
        }
 
-       separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
        if (strchr(item->path, G_DIR_SEPARATOR)) {
                dirpath = g_path_get_dirname(item->path);
                newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
@@ -1990,15 +2206,14 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
 
        ok = imap_cmd_rename(session, real_oldpath, real_newpath);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't rename mailbox: %s to %s\n"),
+               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();
+               unlock_session(session);
                return -1;
        }
-
        g_free(item->name);
        item->name = g_strdup(name);
 
@@ -2022,10 +2237,37 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        g_free(newpath);
        g_free(real_oldpath);
        g_free(real_newpath);
-       unlock_session();
+       unlock_session(session);
        return 0;
 }
 
+gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
+{
+       gchar *path;
+       gint r = -1;
+       IMAPSession *session;
+       debug_print("getting session...\n");
+
+       session = imap_session_get(folder);
+       if (!session) {
+               return -1;
+       }
+       if (item && item->path) {
+               path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
+               if (!path)
+                       return -1;
+               if (!strcmp(path, "INBOX") && sub == FALSE)
+                       return -1;
+               debug_print("%ssubscribing %s\n", sub?"":"un", path);
+               r = imap_threaded_subscribe(folder, path, sub);
+               g_free(path);
+       } else if (rpath) {
+               r = imap_threaded_subscribe(folder, rpath, sub);
+       } else
+               return -1;
+       return r;
+}
+
 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
 {
        gint ok;
@@ -2037,26 +2279,27 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
        g_return_val_if_fail(item != NULL, -1);
        g_return_val_if_fail(item->path != NULL, -1);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) {
                return -1;
        }
-       lock_session();
-       path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
+       path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
 
+       imap_threaded_subscribe(folder, path, FALSE);
        ok = imap_cmd_delete(session, path);
        if (ok != IMAP_SUCCESS) {
                gchar *tmp = g_strdup_printf("%s%c", path, 
-                               imap_get_path_separator(IMAP_FOLDER(folder), path));
+                               imap_get_path_separator(session, IMAP_FOLDER(folder), path));
                g_free(path);
                path = tmp;
                ok = imap_cmd_delete(session, path);
        }
 
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't delete mailbox\n"));
+               log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
                g_free(path);
-               unlock_session();
+               unlock_session(session);
                return -1;
        }
 
@@ -2066,7 +2309,7 @@ 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();
+       unlock_session(session);
        return 0;
 }
 
@@ -2129,6 +2372,9 @@ static void *imap_get_uncached_messages_thread(void *data)
                carray * env_list;
                int count;
                
+               if (session->cancelled)
+                       break;
+               
                imapset = cur->data;
                
                r = imap_threaded_fetch_env(session->folder,
@@ -2222,7 +2468,7 @@ static GSList *imap_get_uncached_messages(IMAPSession *session,
                data->cur += count;
                
                if (prefs_common.work_offline && 
-                   !inc_offline_should_override(
+                   !inc_offline_should_override(FALSE,
                        _("Claws Mail needs network access in order "
                          "to access the IMAP server."))) {
                        g_free(data);
@@ -2268,6 +2514,9 @@ gchar imap_get_path_separator_for_item(FolderItem *item)
 {
        Folder *folder = NULL;
        IMAPFolder *imap_folder = NULL;
+       IMAPSession *session = NULL;
+       gchar result = '/';
+       
        if (!item)
                return '/';
        folder = item->folder;
@@ -2280,12 +2529,15 @@ gchar imap_get_path_separator_for_item(FolderItem *item)
        if (!imap_folder)
                return '/';
        
-       return imap_get_path_separator(imap_folder, item->path);
+       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;
 }
 
-static gchar imap_refresh_path_separator(IMAPFolder *folder, const gchar *subfolder)
+static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
 {
-       IMAPSession *session = imap_session_get(FOLDER(folder));
        clist * lep_list;
        int r;
        gchar separator = '\0';
@@ -2294,7 +2546,7 @@ static gchar imap_refresh_path_separator(IMAPFolder *folder, const gchar *subfol
        r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
        
        if (r != MAILIMAP_NO_ERROR) {
-               log_warning(_("LIST failed\n"));
+               log_warning(LOG_PROTOCOL, _("LIST failed\n"));
                return '\0';
        }
 
@@ -2310,18 +2562,16 @@ static gchar imap_refresh_path_separator(IMAPFolder *folder, const gchar *subfol
        return separator;
 }
 
-static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
+static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
 {
        gchar separator = '/';
-       IMAPSession *session = imap_session_get(FOLDER(folder));
-       g_return_val_if_fail(session != NULL, '/');
 
        if (folder->last_seen_separator == 0) {
-               folder->last_seen_separator = imap_refresh_path_separator(folder, "");
+               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
        }
 
        if (folder->last_seen_separator == 0) {
-               folder->last_seen_separator = imap_refresh_path_separator(folder, "INBOX");
+               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
        }
 
        if (folder->last_seen_separator != 0) {
@@ -2332,7 +2582,7 @@ static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
        return separator;
 }
 
-static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
+static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
 {
        gchar *real_path;
        gchar separator;
@@ -2341,7 +2591,7 @@ static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
        g_return_val_if_fail(path != NULL, NULL);
 
        real_path = imap_utf8_to_modified_utf7(path);
-       separator = imap_get_path_separator(folder, path);
+       separator = imap_get_path_separator(session, folder, path);
        imap_path_separator_subst(real_path, separator);
 
        return real_path;
@@ -2408,12 +2658,12 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        g_free(session->mbox);
        session->mbox = NULL;
 
-       real_path = imap_get_real_path(folder, path);
+       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)
-               log_warning(_("can't select folder: %s\n"), real_path);
+               log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
        else {
                session->mbox = g_strdup(path);
                session->folder_content_changed = FALSE;
@@ -2436,19 +2686,23 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
        gchar *real_path;
        guint mask = 0;
        
-       real_path = imap_get_real_path(folder, path);
+       real_path = imap_get_real_path(session, folder, path);
 
        if (messages) {
                mask |= 1 << 0;
+               *messages = 0;
        }
        if (uid_next) {
                mask |= 1 << 2;
+               *uid_next = 0;
        }
        if (uid_validity) {
                mask |= 1 << 3;
+               *uid_validity = 0;
        }
        if (unseen) {
                mask |= 1 << 4;
+               *unseen = 0;
        }
        r = imap_threaded_status(FOLDER(folder), real_path, 
                &data_status, mask);
@@ -2473,31 +2727,38 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
                info = clist_content(iter);
                switch (info->st_att) {
                case MAILIMAP_STATUS_ATT_MESSAGES:
-                       * messages = info->st_value;
-                       got_values |= 1 << 0;
+                       if (messages) {
+                               * messages = info->st_value;
+                               got_values |= 1 << 0;
+                       }
                        break;
                        
                case MAILIMAP_STATUS_ATT_UIDNEXT:
-                       * uid_next = info->st_value;
-                       got_values |= 1 << 2;
+                       if (uid_next) {
+                               * uid_next = info->st_value;
+                               got_values |= 1 << 2;
+                       }
                        break;
                        
                case MAILIMAP_STATUS_ATT_UIDVALIDITY:
-                       * uid_validity = info->st_value;
-                       got_values |= 1 << 3;
+                       if (uid_validity) {
+                               * uid_validity = info->st_value;
+                               got_values |= 1 << 3;
+                       }
                        break;
                        
                case MAILIMAP_STATUS_ATT_UNSEEN:
-                       * unseen = info->st_value;
-                       got_values |= 1 << 4;
+                       if (unseen) {
+                               * unseen = info->st_value;
+                               got_values |= 1 << 4;
+                       }
                        break;
                }
        }
        mailimap_mailbox_data_status_free(data_status);
        
        if (got_values != mask) {
-               debug_print("status: incomplete values received (%d)\n", got_values);
-               return IMAP_ERROR;
+               g_warning("status: incomplete values received (%d)\n", got_values);
        }
        return IMAP_SUCCESS;
 }
@@ -2522,21 +2783,21 @@ static gint imap_cmd_login(IMAPSession *session,
                gint ok = IMAP_ERROR;
                if (imap_has_capability(session, "STARTTLS")) {
 #if USE_OPENSSL
-                       log_warning(_("Server requires TLS to log in.\n"));
+                       log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
                        ok = imap_cmd_starttls(session);
                        if (ok != IMAP_SUCCESS) {
-                               log_warning(_("Can't start TLS session.\n"));
+                               log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
                                return IMAP_ERROR;
                        } else {
                                /* refresh capas */
                                imap_free_capabilities(session);
                                if (imap_get_capabilities(session) != MAILIMAP_NO_ERROR) {
-                                       log_warning(_("Can't refresh capabilities.\n"));
+                                       log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
                                        return IMAP_ERROR;
                                }
                        }
 #else          
-                       log_error(_("Connection to %s failed: "
+                       log_error(LOG_PROTOCOL, _("Connection to %s failed: "
                                        "server requires TLS, but Claws Mail "
                                        "has been compiled without OpenSSL "
                                        "support.\n"),
@@ -2544,22 +2805,22 @@ static gint imap_cmd_login(IMAPSession *session,
                        return IMAP_ERROR;
 #endif
                } else {
-                       log_error(_("Server logins are disabled.\n"));
+                       log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
                        return IMAP_ERROR;
                }
        }
 
-       log_print("IMAP4> Logging %s to %s using %s\n", 
+       log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
                        user,
                        SESSION(session)->server,
                        type);
        r = imap_threaded_login(session->folder, user, pass, type);
        if (r != MAILIMAP_NO_ERROR) {
-               log_print("IMAP4< Error logging in to %s\n",
+               log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
                                SESSION(session)->server);
                ok = IMAP_ERROR;
        } else {
-               log_print("IMAP4< Login to %s successful\n",
+               log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
                                SESSION(session)->server);
                ok = IMAP_SUCCESS;
        }
@@ -2716,7 +2977,7 @@ static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
        data->body = body;
 
        if (prefs_common.work_offline && 
-           !inc_offline_should_override(
+           !inc_offline_should_override(FALSE,
                _("Claws Mail needs network access in order "
                  "to access the IMAP server."))) {
                g_free(data);
@@ -2801,7 +3062,7 @@ static gint imap_cmd_expunge(IMAPSession *session)
        int r;
        
        if (prefs_common.work_offline && 
-           !inc_offline_should_override(
+           !inc_offline_should_override(FALSE,
                _("Claws Mail needs network access in order "
                  "to access the IMAP server."))) {
                return -1;
@@ -3018,9 +3279,11 @@ static gboolean imap_rename_folder_func(GNode *node, gpointer data)
        gchar **paths = data;
        const gchar *oldpath = paths[0];
        const gchar *newpath = paths[1];
+       gchar *real_oldpath, *real_newpath;
        gchar *base;
        gchar *new_itempath;
        gint oldpathlen;
+       IMAPSession *session = imap_session_get(item->folder);
 
        oldpathlen = strlen(oldpath);
        if (strncmp(oldpath, item->path, oldpathlen) != 0) {
@@ -3035,9 +3298,18 @@ static gboolean imap_rename_folder_func(GNode *node, gpointer data)
        else
                new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
                                           NULL);
+
+       real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
        g_free(item->path);
        item->path = new_itempath;
+       
+       real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
+       
+       imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
+       imap_threaded_subscribe(item->folder, real_newpath, TRUE);
 
+       g_free(real_oldpath);
+       g_free(real_newpath);
        return FALSE;
 }
 
@@ -3135,7 +3407,7 @@ static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderIte
        data->msgnum_list = msgnum_list;
        data->session = session;
        if (prefs_common.work_offline && 
-           !inc_offline_should_override(
+           !inc_offline_should_override(FALSE,
                _("Claws Mail needs network access in order "
                  "to access the IMAP server."))) {
                g_free(data);
@@ -3165,9 +3437,9 @@ 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);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, -1);
-       lock_session();
 
        if (FOLDER_ITEM(item)->path) 
                statusbar_print_all(_("Scanning folder %s%c%s ..."),
@@ -3187,7 +3459,7 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
                        session = imap_reconnect_if_possible(folder, session);
                        if (session == NULL) {
                                statusbar_pop_all();
-                               unlock_session();
+                               unlock_session(session);
                                return -1;
                        }
                }
@@ -3212,7 +3484,7 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
                item->use_cache = (time_t)0;
                if (ok != IMAP_SUCCESS) {
                        statusbar_pop_all();
-                       unlock_session();
+                       unlock_session(session);
                        return -1;
                }
                if(item->item.mtime == uid_val)
@@ -3248,7 +3520,7 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
                        debug_print("exists == nummsgs\n");
                        *msgnum_list = g_slist_copy(item->uid_list);
                        statusbar_pop_all();
-                       unlock_session();
+                       unlock_session(session);
                        return nummsgs;
                } else if (exists < nummsgs) {
                        debug_print("Freeing imap uid cache");
@@ -3261,15 +3533,16 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        if (exists == 0) {
                *msgnum_list = NULL;
                statusbar_pop_all();
-               unlock_session();
+               unlock_session(session);
                return 0;
        }
 
+       item->last_change = time(NULL);
        nummsgs = get_list_of_uids(session, folder, item, &uidlist);
 
        if (nummsgs < 0) {
                statusbar_pop_all();
-               unlock_session();
+               unlock_session(session);
                return -1;
        }
 
@@ -3299,7 +3572,7 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        
        debug_print("get_num_list - ok - %i\n", nummsgs);
        statusbar_pop_all();
-       unlock_session();
+       unlock_session(session);
        return nummsgs;
 }
 
@@ -3342,14 +3615,15 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
        g_return_val_if_fail(item != NULL, NULL);
        g_return_val_if_fail(msgnum_list != NULL, NULL);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, NULL);
-       lock_session();
+
        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();
+               unlock_session(session);
                return NULL;
        }
        if (!(folder_has_parent_of_type(item, F_DRAFT) || 
@@ -3404,7 +3678,7 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
 
                g_slist_free(sorted_list);
        }
-       unlock_session();
+       unlock_session(session);
        return ret;
 }
 
@@ -3442,9 +3716,10 @@ gboolean imap_scan_required(Folder *folder, FolderItem *_item)
        if (item->item.path == NULL)
                return FALSE;
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        g_return_val_if_fail(session != NULL, FALSE);
-       lock_session();
+
        selected_folder = (session->mbox != NULL) &&
                          (!strcmp(session->mbox, item->item.path));
        if (selected_folder && time(NULL) - item->use_cache < 2) {
@@ -3454,19 +3729,18 @@ gboolean imap_scan_required(Folder *folder, FolderItem *_item)
                        session = imap_reconnect_if_possible(folder, session);
                        if (session == NULL)
                                return FALSE;
-                       lock_session();
                }
 
                if (session->folder_content_changed
                ||  session->exists != item->item.total_msgs) {
-                       unlock_session();
+                       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();
+                       unlock_session(session);
                        return FALSE;
                }
 
@@ -3480,11 +3754,12 @@ gboolean imap_scan_required(Folder *folder, FolderItem *_item)
                        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();
+                       unlock_session(session);
+                       item->last_change = time(NULL);
                        return TRUE;
                }
        }
-       unlock_session();
+       unlock_session(session);
        return FALSE;
 }
 
@@ -3503,11 +3778,6 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
        g_return_if_fail(msginfo != NULL);
        g_return_if_fail(msginfo->folder == item);
 
-       session = imap_session_get(folder);
-       if (!session) {
-               return;
-       }
-
        if (!MSG_IS_MARKED(msginfo->flags) &&  (newflags & MSG_MARKED))
                flags_set |= IMAP_FLAG_FLAGGED;
        if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
@@ -3535,10 +3805,15 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                return;
        }
 
-       lock_session();
+       debug_print("getting session...\n");
+       session = imap_session_get(folder);
+       if (!session) {
+               return;
+       }
+
        if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
            NULL, NULL, NULL, NULL, FALSE)) != IMAP_SUCCESS) {
-               unlock_session();
+               unlock_session(session);
                return;
        }
        numlist.next = NULL;
@@ -3583,7 +3858,7 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                if (flags_set) {
                        ok = imap_set_message_flags(session, &numlist, flags_set, TRUE);
                        if (ok != IMAP_SUCCESS) {
-                               unlock_session();
+                               unlock_session(session);
                                return;
                        }
                }
@@ -3591,13 +3866,13 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                if (flags_unset) {
                        ok = imap_set_message_flags(session, &numlist, flags_unset, FALSE);
                        if (ok != IMAP_SUCCESS) {
-                               unlock_session();
+                               unlock_session(session);
                                return;
                        }
                }
        }
        msginfo->flags.perm_flags = newflags;
-       unlock_session();
+       unlock_session(session);
        return;
 }
 
@@ -3612,24 +3887,24 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
        g_return_val_if_fail(item != NULL, -1);
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (!session) return -1;
-       lock_session();
+
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
                         NULL, NULL, NULL, NULL, FALSE);
        if (ok != IMAP_SUCCESS) {
-               unlock_session();
+               unlock_session(session);
                return ok;
        }
        numlist.next = NULL;
        numlist.data = GINT_TO_POINTER(uid);
        
        ok = imap_set_message_flags
-               (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
-               &numlist, IMAP_FLAG_DELETED, TRUE);
+               (session, &numlist, IMAP_FLAG_DELETED, TRUE);
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't set deleted flags: %d\n"), uid);
-               unlock_session();
+               log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
+               unlock_session(session);
                return ok;
        }
 
@@ -3643,8 +3918,8 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
                g_free(uidstr);
        }
        if (ok != IMAP_SUCCESS) {
-               log_warning(_("can't expunge\n"));
-               unlock_session();
+               log_warning(LOG_PROTOCOL, _("can't expunge\n"));
+               unlock_session(session);
                return ok;
        }
 
@@ -3654,7 +3929,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();
+       unlock_session(session);
        return IMAP_SUCCESS;
 }
 
@@ -3719,12 +3994,13 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                return GINT_TO_POINTER(-1);
        }
 
+       debug_print("getting session...\n");
        session = imap_session_get(folder);
        if (session == NULL) {
                stuff->done = TRUE;
                return GINT_TO_POINTER(-1);
        }
-       lock_session();
+
        selected_folder = (session->mbox != NULL) &&
                          (!strcmp(session->mbox, item->path));
 
@@ -3733,7 +4009,7 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                        &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
                if (ok != IMAP_SUCCESS) {
                        stuff->done = TRUE;
-                       unlock_session();
+                       unlock_session(session);
                        return GINT_TO_POINTER(-1);
                }
 
@@ -3871,7 +4147,7 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        g_string_free(cmd_buf, TRUE);
 
        stuff->done = TRUE;
-       unlock_session();
+       unlock_session(session);
        return GINT_TO_POINTER(0);
 }
 
@@ -3890,7 +4166,7 @@ static gint imap_get_flags(Folder *folder, FolderItem *item,
        GSList *tmp = NULL, *cur;
        
        if (prefs_common.work_offline && 
-           !inc_offline_should_override(
+           !inc_offline_should_override(FALSE,
                _("Claws Mail needs network access in order "
                  "to access the IMAP server."))) {
                g_free(data);
@@ -3922,7 +4198,10 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
        IMAPFolderItem *_item = data->item;
        FolderItem *item = (FolderItem *)_item;
        gint ok = IMAP_ERROR;
-       IMAPSession *session = imap_session_get(item->folder);
+       IMAPSession *session = NULL;
+       
+       debug_print("getting session...\n");
+       session = imap_session_get(item->folder);
 
        data->msglist = g_slist_reverse(data->msglist);
        
@@ -3932,7 +4211,6 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
                g_slist_length(data->msglist));
        
        if (session) {
-               lock_session();
                ok = imap_select(session, IMAP_FOLDER(item->folder), item->path,
                         NULL, NULL, NULL, NULL, FALSE);
        }
@@ -3941,8 +4219,8 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
        } else {
                g_warning("can't select mailbox %s\n", item->path);
        }
-       if (session)
-               unlock_session();
+
+       unlock_session(session);
        g_slist_free(data->msglist);    
        g_free(data);
        return TRUE;
@@ -4075,17 +4353,14 @@ static GSList * imap_list_from_lep(IMAPFolder * folder,
                        free(dup_name);
                        continue;
                }
-               
-               if (!all && strcmp(dup_name, real_path) == 0) {
+               if (!all && path_cmp(name, real_path) == 0) {
                        g_free(base);
                        free(dup_name);
                        continue;
                }
 
                if (!all && dup_name[strlen(dup_name)-1] == '/') {
-                       g_free(base);
-                       free(dup_name);
-                       continue;
+                       dup_name[strlen(dup_name)-1] = '\0';
                }
                
                loc_name = imap_modified_utf7_to_utf8(base);
@@ -4339,6 +4614,62 @@ void imap_folder_unref(Folder *folder)
                ((IMAPFolder *)folder)->refcnt--;
 }
 
+void imap_cancel_all(void)
+{
+       GList *folderlist;
+       GList *cur;
+       
+       folderlist = folder_get_list();
+       for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
+               Folder *folder = (Folder *) cur->data;
+
+               if (folder->klass == &imap_class) {
+                       if (imap_is_busy(folder)) {
+                               IMAPSession *imap_session;
+                               RemoteFolder *rfolder;
+                               
+                               fprintf(stderr, "cancelled\n");
+                               imap_threaded_cancel(folder);
+                               rfolder = (RemoteFolder *) folder;
+                               imap_session = (IMAPSession *) rfolder->session;
+                               imap_session->cancelled = 1;
+                       }
+               }
+       }
+}
+
+gboolean imap_cancel_all_enabled(void)
+{
+       GList *folderlist;
+       GList *cur;
+       
+       folderlist = folder_get_list();
+       for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
+               Folder *folder = (Folder *) cur->data;
+
+               if (folder->klass == &imap_class) {
+                       if (imap_is_busy(folder)) {
+                               return TRUE;
+                       }
+               }
+       }
+       
+       return FALSE;
+}
+
+static gboolean imap_is_busy(Folder *folder)
+{
+       IMAPSession *imap_session;
+       RemoteFolder *rfolder;
+       
+       rfolder = (RemoteFolder *) folder;
+       imap_session = (IMAPSession *) rfolder->session;
+       if (imap_session == NULL)
+               return FALSE;
+       
+       return imap_session->busy;
+}
+
 #else /* HAVE_LIBETPAN */
 
 static FolderClass imap_class;
@@ -4412,11 +4743,45 @@ 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;
+}
+
+GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
+{
+       return NULL;
+}
+
+void imap_cache_msg(FolderItem *item, gint msgnum)
+{
+}
+
+void imap_cancel_all(void)
+{
+}
+
+gboolean imap_cancel_all_enabled(void)
+{
+       return FALSE;
+}
+
 #endif
 
 void imap_synchronise(FolderItem *item) 
 {
+       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;
+       }
+       debug_print("syncing %s\n", item->path?item->path:item->name);
        imap_gtk_synchronise(item);
+       IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
 }
 
 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
@@ -4433,7 +4798,13 @@ static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
                if (!attr || !attr->name || !attr->value) continue;
                if (!strcmp(attr->name, "uidnext"))
                        IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
+               if (!strcmp(attr->name, "last_sync"))
+                       IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
+               if (!strcmp(attr->name, "last_change"))
+                       IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
        }
+       if (IMAP_FOLDER_ITEM(item)->last_change == 0)
+               IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
 #endif
 }
 
@@ -4446,6 +4817,10 @@ static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
 #ifdef HAVE_LIBETPAN
        xml_tag_add_attr(tag, xml_attr_new_int("uidnext", 
                        IMAP_FOLDER_ITEM(item)->uid_next));
+       xml_tag_add_attr(tag, xml_attr_new_int("last_sync", 
+                       IMAP_FOLDER_ITEM(item)->last_sync));
+       xml_tag_add_attr(tag, xml_attr_new_int("last_change", 
+                       IMAP_FOLDER_ITEM(item)->last_change));
 
 #endif
        return tag;