2007-08-08 [colin] 2.10.0cvs99
[claws.git] / src / imap.c
index 574605d321424b473b645e50e5cba317046d37e5..ce86d94e6beafd55b42fbfc1950dce4a65e3369f 100644 (file)
@@ -4,7 +4,7 @@
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
@@ -13,8 +13,8 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * 
  */
 
 #ifdef HAVE_CONFIG_H
@@ -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);
@@ -195,6 +198,9 @@ static gchar   *imap_fetch_msg_full (Folder         *folder,
                                         gint            uid,
                                         gboolean        headers,
                                         gboolean        body);
+static void    imap_remove_cached_msg  (Folder         *folder, 
+                                        FolderItem     *item, 
+                                        MsgInfo        *msginfo);
 static gint    imap_add_msg            (Folder         *folder,
                                         FolderItem     *dest,
                                         const gchar    *file, 
@@ -300,7 +306,8 @@ static gchar imap_get_path_separator                (IMAPSession    *session,
 static gchar *imap_get_real_path               (IMAPSession    *session,
                                                 IMAPFolder     *folder,
                                                 const gchar    *path);
-static void imap_synchronise           (FolderItem     *item);
+static void imap_synchronise           (FolderItem     *item, gint days);
+static gboolean imap_is_busy           (Folder *folder);
 
 static void imap_free_capabilities     (IMAPSession    *session);
 
@@ -397,6 +404,8 @@ static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist);
 static GSList * imap_get_lep_set_from_msglist(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);
 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
                                       FolderItem *item);
 static void imap_lep_set_free(GSList *seq_list);
@@ -465,6 +474,7 @@ FolderClass *imap_get_class(void)
                imap_class.get_flags = imap_get_flags;
                imap_class.set_batch = imap_set_batch;
                imap_class.synchronise = imap_synchronise;
+               imap_class.remove_cached_msg = imap_remove_cached_msg;
 #ifdef USE_PTREAD
                pthread_mutex_init(&imap_mutex, NULL);
 #endif
@@ -641,7 +651,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);
                        }
@@ -658,12 +668,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"
@@ -684,24 +694,40 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
        return session;
 }
 
-#define lock_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;\
-       } else {\
-               debug_print("can't lock null session\n"); \
-       }\
+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() {\
-       if (session) { \
-               debug_print("unlocking session %p\n", session); \
-               session->busy = FALSE;\
-       } else {\
-               debug_print("can't unlock 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)
@@ -714,7 +740,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;
@@ -723,14 +749,19 @@ static IMAPSession *imap_session_get(Folder *folder)
        /* Make sure we have a session */
        if (rfolder->session != NULL) {
                session = IMAP_SESSION(rfolder->session);
+       } 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;
        }
 
@@ -744,10 +775,11 @@ 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();
+       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
@@ -757,15 +789,18 @@ 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);
                }
+               if (session)
+                       session->cancelled = FALSE;
        }
 
        rfolder->session = SESSION(session);
+       rfolder->connecting = FALSE;
 
        return IMAP_SESSION(session);
 }
@@ -838,14 +873,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);
                } 
                
@@ -874,7 +909,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;
                }
@@ -885,7 +920,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;
@@ -922,7 +957,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);
@@ -952,22 +987,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++;
        }
        
@@ -975,6 +1010,26 @@ static guint get_size_with_crs(MsgInfo *info)
        return cnt;
 }
 
+static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
+{
+       gchar *path, *filename;
+
+       path = folder_item_get_path(item);
+
+       if (!is_dir_exist(path)) {
+               g_free(path);
+               return;
+       }
+
+       filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
+       g_free(path);
+
+       if (is_file_exist(filename)) {
+               g_unlink(filename);
+       }
+       g_free(filename);
+}
+
 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                                  gboolean headers, gboolean body)
 {
@@ -998,9 +1053,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,
@@ -1009,17 +1063,14 @@ 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);
                }
        }
 
@@ -1037,7 +1088,7 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
        if (ok != IMAP_SUCCESS) {
                g_warning("can't select mailbox %s\n", item->path);
                g_free(filename);
-               unlock_session();
+               unlock_session(session);
                return NULL;
        }
 
@@ -1047,15 +1098,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)
 {
@@ -1075,6 +1175,41 @@ 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)
 {
@@ -1085,7 +1220,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        MsgFileInfo *fileinfo;
        gint ok;
        gint curnum = 0, total = 0;
-
+       gboolean missing_uids = FALSE;
 
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(dest != NULL, -1);
@@ -1134,7 +1269,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;
@@ -1142,6 +1277,11 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                        debug_print("appended new message as %d\n", new_uid);
                        /* put the local file in the imapcache, so that we don't
                         * have to fetch it back later. */
+                       
+                       if (new_uid == 0) {
+                               missing_uids = TRUE;
+                               debug_print("Missing UID (0)\n");
+                       }
                        if (new_uid > 0) {
                                gchar *cache_path = folder_item_get_path(dest);
                                if (!is_dir_exist(cache_path))
@@ -1151,7 +1291,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                                                cache_path, G_DIR_SEPARATOR_S, 
                                                itos(new_uid), NULL);
                                        copy_file(real_file, cache_file, TRUE);
-                                       debug_print("copied to cache: %s\n", cache_file);
+                                       debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
                                        g_free(cache_file);
                                }
                                g_free(cache_path);
@@ -1161,27 +1301,89 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                if (relation != NULL)
                        g_relation_insert(relation, fileinfo->msginfo != NULL ? 
                                          (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
-                                         GINT_TO_POINTER(dest->last_num + 1));
-               if (new_uid == 0) {
-                       new_uid = dest->last_num+1;
-               }
+                                         GINT_TO_POINTER(new_uid));
                if (last_uid < new_uid) {
                        last_uid = new_uid;
                }
 
                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();
        
-       imap_cmd_expunge(session);
-       unlock_session();
+       unlock_session(session);
        
        g_free(destdir);
 
        return last_uid;
 }
 
+static GSList *flatten_mailimap_set(struct mailimap_set * set) 
+{
+       GSList *result = NULL;
+       clistiter *list;
+       int start, end, t;
+       GSList *cur;
+
+       for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
+               struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
+               start = item->set_first;
+               end = item->set_last;
+               for (t = start; t <= end; t++) {
+                       result = g_slist_prepend(result, GINT_TO_POINTER(t));
+               }
+       }
+       result = g_slist_reverse(result);
+       if (debug_get_mode()) {
+               debug_print("flat imap set: ");
+               for (cur = result; cur; cur = cur->next) {
+                       debug_print("%d ", GPOINTER_TO_INT(cur->data));
+               }
+               debug_print("\n");
+       }
+       
+       return result;
+}
 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
                              MsgInfoList *msglist, GRelation *relation)
 {
@@ -1212,7 +1414,7 @@ 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();
+               unlock_session(session);
                return -1;
        }
 
@@ -1227,7 +1429,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                        infolist = g_slist_prepend(infolist, fileinfo);
                }
                infolist = g_slist_reverse(infolist);
-               unlock_session();
+               unlock_session(session);
                res = folder_item_add_msgs(dest, infolist, FALSE);
                for (cur = infolist; cur; cur = cur->next) {
                        MsgFileInfo *info = (MsgFileInfo *)cur->data;
@@ -1241,7 +1443,7 @@ 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;
        }
 
@@ -1264,16 +1466,23 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                        &source, &dest);
                
                if (ok == IMAP_SUCCESS) {
-                       if (single && relation && source && dest) {
-                               clistiter *l = clist_begin(source->set_list);
-                               struct mailimap_set_item *i = (struct mailimap_set_item *)clist_content(l);
-                               int snum = i->set_first;
-                               int dnum = 0;
-                               l = clist_begin(dest->set_list);
-                               i = (struct mailimap_set_item *)clist_content(l);
-                               dnum = i->set_first;
-                               g_relation_insert(uid_mapping, GINT_TO_POINTER(snum), 
-                                       GINT_TO_POINTER(dnum));
+                       if (relation && source && dest) {
+                               GSList *s_list = flatten_mailimap_set(source);
+                               GSList *d_list = flatten_mailimap_set(dest);
+                               GSList *s_cur, *d_cur;
+                               if (g_slist_length(s_list) == g_slist_length(d_list)) {
+
+                                       for (s_cur = s_list, d_cur = d_list; 
+                                            s_cur && d_cur; 
+                                            s_cur = s_cur->next, d_cur = d_cur->next) {
+                                               g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
+                                       }
+
+                               } else {
+                                       debug_print("hhhmm, source list length != dest list length.\n");
+                               }
+                               g_slist_free(s_list);
+                               g_slist_free(d_list);
                        }
                }
 
@@ -1286,7 +1495,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;
                }
        }
@@ -1304,7 +1514,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                                          GINT_TO_POINTER(num));
                        if (num > last_num)
                                last_num = num;
-                       debug_print("copied new message as %d\n", num);
+                       debug_print("copied message %d as %d\n", msginfo->msgnum, num);
                        /* put the local file in the imapcache, so that we don't
                         * have to fetch it back later. */
                        if (num > 0) {
@@ -1345,7 +1555,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
@@ -1407,7 +1617,7 @@ static gint imap_do_remove_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;
        }
 
@@ -1423,17 +1633,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;
        }
        
@@ -1450,7 +1659,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
@@ -1519,7 +1728,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();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(session, IMAP_FOLDER(folder),
@@ -1540,7 +1749,7 @@ gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
                                item->folder = folder;
                                folder->node = item->node = g_node_new(item);
                        }
-                       unlock_session();
+                       unlock_session(session);
                        return -1;
                }
                mailimap_list_result_free(lep_list);
@@ -1565,7 +1774,7 @@ 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();
+       unlock_session(session);
 
        return 0;
 }
@@ -1967,7 +2176,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
@@ -1982,7 +2191,7 @@ 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(session, IMAP_FOLDER(folder), imap_path);
@@ -1998,12 +2207,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) {
-                       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;
                }
                
@@ -2014,10 +2223,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);
@@ -2063,7 +2272,7 @@ 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 */
@@ -2103,7 +2312,7 @@ 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();
+               unlock_session(session);
                return -1;
        }
 
@@ -2115,7 +2324,7 @@ 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;
        }
 
@@ -2132,15 +2341,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);
 
@@ -2164,7 +2372,7 @@ 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;
 }
 
@@ -2224,9 +2432,9 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
        }
 
        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;
        }
 
@@ -2236,7 +2444,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;
 }
 
@@ -2299,6 +2507,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,
@@ -2392,7 +2603,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);
@@ -2456,7 +2667,7 @@ 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();
+       unlock_session(session);
        return result;
 }
 
@@ -2470,7 +2681,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) {
-               log_warning(_("LIST failed\n"));
+               log_warning(LOG_PROTOCOL, _("LIST failed\n"));
                return '\0';
        }
 
@@ -2587,7 +2798,7 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        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;
@@ -2614,15 +2825,19 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
 
        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);
@@ -2647,31 +2862,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;
 }
@@ -2696,21 +2918,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"),
@@ -2718,22 +2940,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;
        }
@@ -2890,7 +3112,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);
@@ -2975,7 +3197,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;
@@ -3192,9 +3414,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) {
@@ -3209,9 +3433,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;
 }
 
@@ -3232,8 +3465,8 @@ static void *get_list_of_uids_thread(void *data)
        gint ok, nummsgs = 0, lastuid_old;
        IMAPSession *session;
        GSList *uidlist, *elem;
+       int r = -1;
        clist * lep_uidlist;
-       int r;
 
        session = stuff->session;
        if (session == NULL) {
@@ -3250,32 +3483,34 @@ static void *get_list_of_uids_thread(void *data)
 
        uidlist = NULL;
        
-       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
+       if (folder->account && folder->account->low_bandwidth) {
+               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
                                 &lep_uidlist);
+       }
        
        if (r == MAILIMAP_NO_ERROR) {
-               GSList * fetchuid_list;
-               
-               fetchuid_list =
+               GSList * fetchuid_list =
                        imap_uid_list_from_lep(lep_uidlist);
                mailimap_search_result_free(lep_uidlist);
                
                uidlist = g_slist_concat(fetchuid_list, uidlist);
-       }
-       else {
-               GSList * fetchuid_list;
+       } else {
                carray * lep_uidtab;
-               
-               r = imap_threaded_fetch_uid(folder, item->lastuid + 1,
-                                           &lep_uidtab);
+               r = imap_threaded_fetch_uid(folder, 1,
+                                   &lep_uidtab);
                if (r == MAILIMAP_NO_ERROR) {
-                       fetchuid_list =
+                       GSList * fetchuid_list =
                                imap_uid_list_from_lep_tab(lep_uidtab);
                        imap_fetch_uid_list_free(lep_uidtab);
                        uidlist = g_slist_concat(fetchuid_list, uidlist);
                }
        }
        
+       if (r != MAILIMAP_NO_ERROR) {
+               stuff->done = TRUE;
+               return GINT_TO_POINTER(-1);
+       }
+
        lastuid_old = item->lastuid;
        *msgnum_list = g_slist_copy(item->uid_list);
        nummsgs = g_slist_length(*msgnum_list);
@@ -3309,7 +3544,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);
@@ -3361,7 +3596,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;
                        }
                }
@@ -3386,7 +3621,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)
@@ -3422,7 +3657,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");
@@ -3435,15 +3670,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;
        }
 
@@ -3473,7 +3709,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;
 }
 
@@ -3524,7 +3760,7 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
        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) || 
@@ -3551,8 +3787,9 @@ 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) {
@@ -3579,7 +3816,7 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
 
                g_slist_free(sorted_list);
        }
-       unlock_session();
+       unlock_session(session);
        return ret;
 }
 
@@ -3634,14 +3871,14 @@ gboolean imap_scan_required(Folder *folder, FolderItem *_item)
 
                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;
                }
 
@@ -3655,11 +3892,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;
 }
 
@@ -3713,7 +3951,7 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
 
        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;
@@ -3758,7 +3996,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;
                        }
                }
@@ -3766,13 +4004,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;
 }
 
@@ -3794,18 +4032,17 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        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;
        }
 
@@ -3819,8 +4056,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;
        }
 
@@ -3830,7 +4067,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;
 }
 
@@ -3874,43 +4111,38 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
 {
        get_flags_data *stuff = (get_flags_data *)data;
        Folder *folder = stuff->folder;
-       FolderItem *item = stuff->item;
+       FolderItem *fitem = (FolderItem *) stuff->item;
        MsgInfoList *msginfo_list = stuff->msginfo_list;
        GRelation *msgflags = stuff->msgflags;
-       gboolean full_search = stuff->full_search;
+       GSList *elem;
+       carray * lep_uidtab;
        IMAPSession *session;
+       gint ok;
+       int r;
+       GHashTable *flags_hash = NULL;
+       gboolean full_search = stuff->full_search;
        GSList *sorted_list = NULL;
        GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL;
        GSList *p_unseen, *p_answered, *p_flagged, *p_deleted;
-       GSList *elem;
        GSList *seq_list, *cur;
        gboolean reverse_seen = FALSE;
-       GString *cmd_buf;
-       gint ok;
-       gint exists_cnt, unseen_cnt;
        gboolean selected_folder;
+       gint exists_cnt, unseen_cnt;
        
-       if (folder == NULL || item == NULL) {
-               stuff->done = TRUE;
-               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);
        }
-
        selected_folder = (session->mbox != NULL) &&
-                         (!strcmp(session->mbox, item->path));
+                         (!strcmp(session->mbox, fitem->path));
 
        if (!selected_folder) {
-               ok = imap_select(session, IMAP_FOLDER(folder), item->path,
+               ok = imap_select(session, IMAP_FOLDER(folder), fitem->path,
                        &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
                if (ok != IMAP_SUCCESS) {
                        stuff->done = TRUE;
-                       unlock_session();
+                       unlock_session(session);
                        return GINT_TO_POINTER(-1);
                }
 
@@ -3918,12 +4150,10 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                        reverse_seen = TRUE;
        } 
        else {
-               if (item->unread_msgs > item->total_msgs / 2)
+               if (fitem->unread_msgs > fitem->total_msgs / 2)
                        reverse_seen = TRUE;
        }
 
-       cmd_buf = g_string_new(NULL);
-
        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);
@@ -3933,54 +4163,32 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                seq_list = g_slist_append(NULL, set);
        }
 
-       for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
-               struct mailimap_set * imapset;
-               clist * lep_uidlist;
-               int r;
-               
-               imapset = cur->data;
-               if (reverse_seen) {
-                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
-                                                full_search ? NULL:imapset, &lep_uidlist);
-               }
-               else {
-                       r = imap_threaded_search(folder,
-                                                IMAP_SEARCH_TYPE_UNSEEN,
-                                                full_search ? NULL:imapset, &lep_uidlist);
-               }
-               if (r == MAILIMAP_NO_ERROR) {
-                       GSList * uidlist;
-                       
-                       uidlist = imap_uid_list_from_lep(lep_uidlist);
-                       mailimap_search_result_free(lep_uidlist);
-                       
-                       unseen = g_slist_concat(unseen, uidlist);
-               }
-               
-               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
-                                        full_search ? NULL:imapset, &lep_uidlist);
-               if (r == MAILIMAP_NO_ERROR) {
-                       GSList * uidlist;
+       if (folder->account && folder->account->low_bandwidth) {
+               for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
+                       struct mailimap_set * imapset;
+                       clist * lep_uidlist;
+                       int r;
 
-                       uidlist = imap_uid_list_from_lep(lep_uidlist);
-                       mailimap_search_result_free(lep_uidlist);
-
-                       flagged = g_slist_concat(flagged, uidlist);
-               }
-
-               if (item->opened || item->processing_pending || item == folder->inbox) {
-                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
-                                                full_search ? NULL:imapset, &lep_uidlist);
+                       imapset = cur->data;
+                       if (reverse_seen) {
+                               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
+                                                        full_search ? NULL:imapset, &lep_uidlist);
+                       }
+                       else {
+                               r = imap_threaded_search(folder,
+                                                        IMAP_SEARCH_TYPE_UNSEEN,
+                                                        full_search ? NULL:imapset, &lep_uidlist);
+                       }
                        if (r == MAILIMAP_NO_ERROR) {
                                GSList * uidlist;
 
                                uidlist = imap_uid_list_from_lep(lep_uidlist);
                                mailimap_search_result_free(lep_uidlist);
 
-                               answered = g_slist_concat(answered, uidlist);
+                               unseen = g_slist_concat(unseen, uidlist);
                        }
 
-                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
+                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
                                                 full_search ? NULL:imapset, &lep_uidlist);
                        if (r == MAILIMAP_NO_ERROR) {
                                GSList * uidlist;
@@ -3988,56 +4196,110 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                uidlist = imap_uid_list_from_lep(lep_uidlist);
                                mailimap_search_result_free(lep_uidlist);
 
-                               deleted = g_slist_concat(deleted, uidlist);
+                               flagged = g_slist_concat(flagged, uidlist);
                        }
-               }
-       }
 
-       p_unseen = unseen;
-       p_answered = answered;
-       p_flagged = flagged;
-       p_deleted = deleted;
+                       if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
+                               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
+                                                        full_search ? NULL:imapset, &lep_uidlist);
+                               if (r == MAILIMAP_NO_ERROR) {
+                                       GSList * uidlist;
+
+                                       uidlist = imap_uid_list_from_lep(lep_uidlist);
+                                       mailimap_search_result_free(lep_uidlist);
+
+                                       answered = g_slist_concat(answered, uidlist);
+                               }
+
+                               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
+                                                        full_search ? NULL:imapset, &lep_uidlist);
+                               if (r == MAILIMAP_NO_ERROR) {
+                                       GSList * uidlist;
+
+                                       uidlist = imap_uid_list_from_lep(lep_uidlist);
+                                       mailimap_search_result_free(lep_uidlist);
 
+                                       deleted = g_slist_concat(deleted, uidlist);
+                               }
+                       }
+               }
+               p_unseen = unseen;
+               p_answered = answered;
+               p_flagged = flagged;
+               p_deleted = deleted;
+
+       } 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);
+                       imap_fetch_uid_flags_list_free(lep_uidtab);
+               }
+       }
        for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
                MsgInfo *msginfo;
-               MsgPermFlags flags;
+               MsgPermFlags flags, oldflags;
                gboolean wasnew;
-               
+
                msginfo = (MsgInfo *) elem->data;
                flags = msginfo->flags.perm_flags;
                wasnew = (flags & MSG_NEW);
-               if (item->opened || item->processing_pending || item == folder->inbox) {
-                       flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_MARKED);
-               } else {
-                       flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
-               }
-               if (reverse_seen)
-                       flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
-               if (gslist_find_next_num(&p_unseen, msginfo->msgnum) == msginfo->msgnum) {
-                       if (!reverse_seen) {
-                               flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
+               oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_MARKED|MSG_DELETED);
+
+               if (folder->account && folder->account->low_bandwidth) {
+                       if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
+                               flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_MARKED);
                        } else {
-                               flags &= ~(MSG_UNREAD | MSG_NEW);
+                               flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
+                       }
+                       if (reverse_seen)
+                               flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
+                       if (gslist_find_next_num(&p_unseen, msginfo->msgnum) == msginfo->msgnum) {
+                               if (!reverse_seen) {
+                                       flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
+                               } else {
+                                       flags &= ~(MSG_UNREAD | MSG_NEW);
+                               }
                        }
-               }
-               
-               if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
-                       flags |= MSG_MARKED;
-               else
-                       flags &= ~MSG_MARKED;
 
-               if (item->opened || item->processing_pending || item == folder->inbox) {
-                       if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
-                               flags |= MSG_REPLIED;
+                       if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
+                               flags |= MSG_MARKED;
                        else
-                               flags &= ~MSG_REPLIED;
-                       if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
-                               flags |= MSG_DELETED;
-                       else
-                               flags &= ~MSG_DELETED;
+                               flags &= ~MSG_MARKED;
+
+                       if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
+                               if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
+                                       flags |= MSG_REPLIED;
+                               else
+                                       flags &= ~MSG_REPLIED;
+                               if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
+                                       flags |= MSG_DELETED;
+                               else
+                                       flags &= ~MSG_DELETED;
+                       }
+               } 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);
+                       }
+
+                       if ((flags & MSG_UNREAD) == 0)
+                               flags &= ~MSG_NEW;
+                       else if (wasnew)
+                               flags |= MSG_NEW;
+                       flags |= oldflags;
                }
+
                g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
        }
+       
+       if (flags_hash)
+               g_hash_table_destroy(flags_hash);
 
        imap_lep_set_free(seq_list);
        g_slist_free(flagged);
@@ -4045,10 +4307,9 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        g_slist_free(answered);
        g_slist_free(unseen);
        g_slist_free(sorted_list);
-       g_string_free(cmd_buf, TRUE);
 
+       unlock_session(session);
        stuff->done = TRUE;
-       unlock_session();
        return GINT_TO_POINTER(0);
 }
 
@@ -4067,7 +4328,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);
@@ -4121,7 +4382,7 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
                g_warning("can't select mailbox %s\n", item->path);
        }
 
-       unlock_session();
+       unlock_session(session);
        g_slist_free(data->msglist);    
        g_free(data);
        return TRUE;
@@ -4412,6 +4673,28 @@ static GSList * imap_uid_list_from_lep_tab(carray * list)
        return result;
 }
 
+static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
+                                                  GHashTable * hash)
+{
+       unsigned int i;
+       GSList * result;
+       
+       result = NULL;
+       
+       for(i = 0 ; i < carray_count(list) ; i += 2) {
+               uint32_t * puid;
+               int * pflags;
+               gint * pguid;
+               
+               puid = carray_get(list, i);
+               pflags = carray_get(list, i + 1);
+               pguid = malloc(sizeof(* pguid));
+               * pguid = * puid;
+               
+               g_hash_table_insert(hash, pguid, GINT_TO_POINTER(* pflags));
+       }
+}
+
 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
                                       FolderItem *item)
 {
@@ -4515,6 +4798,63 @@ 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;
+                               if (imap_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;
@@ -4600,13 +4940,35 @@ gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub
 
 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
 {
-       return -1;
+       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) 
+void imap_synchronise(FolderItem *item, gint days
 {
-       imap_gtk_synchronise(item);
+#ifdef HAVE_LIBETPAN
+       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, days);
+       IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
+#endif
 }
 
 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
@@ -4623,7 +4985,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
 }
 
@@ -4636,6 +5004,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;