2008-10-01 [colin] 3.5.0cvs142
[claws.git] / src / imap.c
index d09da6b894cb441e02a4ea26caca1d60f322f70f..6a9245f12cf579a2bbf45083a3520a9f87289a40 100644 (file)
@@ -69,6 +69,8 @@
 #include "msgcache.h"
 #include "imap-thread.h"
 #include "account.h"
+#include "tags.h"
+#include "main.h"
 
 typedef struct _IMAPFolder     IMAPFolder;
 typedef struct _IMAPSession    IMAPSession;
@@ -129,20 +131,14 @@ struct _IMAPNameSpace
 
 #define IMAPBUFSIZE    8192
 
-typedef enum
-{
-       IMAP_FLAG_SEEN          = 1 << 0,
-       IMAP_FLAG_ANSWERED      = 1 << 1,
-       IMAP_FLAG_FLAGGED       = 1 << 2,
-       IMAP_FLAG_DELETED       = 1 << 3,
-       IMAP_FLAG_DRAFT         = 1 << 4
-} IMAPFlags;
-
 #define IMAP_IS_SEEN(flags)    ((flags & IMAP_FLAG_SEEN) != 0)
 #define IMAP_IS_ANSWERED(flags)        ((flags & IMAP_FLAG_ANSWERED) != 0)
 #define IMAP_IS_FLAGGED(flags) ((flags & IMAP_FLAG_FLAGGED) != 0)
 #define IMAP_IS_DELETED(flags) ((flags & IMAP_FLAG_DELETED) != 0)
 #define IMAP_IS_DRAFT(flags)   ((flags & IMAP_FLAG_DRAFT) != 0)
+#define IMAP_IS_FORWARDED(flags)       ((flags & IMAP_FLAG_FORWARDED) != 0)
+#define IMAP_IS_SPAM(flags)    ((flags & IMAP_FLAG_SPAM) != 0)
+#define IMAP_IS_HAM(flags)     ((flags & IMAP_FLAG_HAM) != 0)
 
 
 #define IMAP4_PORT     143
@@ -152,6 +148,12 @@ typedef enum
 
 #define IMAP_CMD_LIMIT 1000
 
+enum {
+       ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
+       ITEM_CAN_CREATE_FLAGS,
+       ITEM_CANNOT_CREATE_FLAGS
+};
+
 struct _IMAPFolderItem
 {
        FolderItem item;
@@ -167,6 +169,12 @@ struct _IMAPFolderItem
        guint32 last_sync;
        gboolean should_update;
        gboolean should_trash_cache;
+       gint can_create_flags;
+
+       GHashTable *tags_set_table;
+       GHashTable *tags_unset_table;
+       GSList *ok_flags;
+
 };
 
 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
@@ -182,8 +190,8 @@ static void  imap_folder_destroy    (Folder         *folder);
 
 static IMAPSession *imap_session_new   (Folder         *folder,
                                         const PrefsAccount     *account);
-static void    imap_session_authenticate(IMAPSession           *session,
-                                         const PrefsAccount    *account);
+static gint    imap_session_authenticate(IMAPSession   *session,
+                                         PrefsAccount  *account);
 static void    imap_session_destroy    (Session        *session);
 
 static gchar   *imap_fetch_msg         (Folder         *folder, 
@@ -275,16 +283,19 @@ static void imap_set_batch                (Folder         *folder,
                                         FolderItem     *item,
                                         gboolean        batch);
 static gint imap_set_message_flags     (IMAPSession    *session,
+                                        IMAPFolderItem *item,
                                         MsgNumberList  *numlist,
                                         IMAPFlags       flags,
+                                        GSList         *tags,
                                         gboolean        is_set);
 static gint imap_select                        (IMAPSession    *session,
                                         IMAPFolder     *folder,
-                                        const gchar    *path,
+                                        FolderItem     *item,
                                         gint           *exists,
                                         gint           *recent,
                                         gint           *unseen,
                                         guint32        *uid_validity,
+                                        gint           *can_create_flags,
                                         gboolean        block);
 static gint imap_status                        (IMAPSession    *session,
                                         IMAPFolder     *folder,
@@ -295,13 +306,19 @@ static gint imap_status                   (IMAPSession    *session,
                                         guint32        *uid_validity,
                                         gint           *unseen,
                                         gboolean        block);
+static void    imap_commit_tags        (FolderItem     *item, 
+                                        MsgInfo        *msginfo,
+                                        GSList         *set_tags,
+                                        GSList         *unset_tags);
 
 static gchar imap_get_path_separator           (IMAPSession    *session,
                                                 IMAPFolder     *folder,
-                                                const gchar    *path);
+                                                const gchar    *path,
+                                                gint           *ok);
 static gchar *imap_get_real_path               (IMAPSession    *session,
                                                 IMAPFolder     *folder,
-                                                const gchar    *path);
+                                                const gchar    *path,
+                                                gint           *ok);
 #ifdef HAVE_LIBETPAN
 static void imap_synchronise           (FolderItem     *item, gint days);
 #endif
@@ -324,6 +341,8 @@ static gint imap_cmd_select (IMAPSession    *session,
                                 gint           *recent,
                                 gint           *unseen,
                                 guint32        *uid_validity,
+                                gint           *can_create_flags,
+                                GSList         **ok_flags,
                                 gboolean        block);
 static gint imap_cmd_close     (IMAPSession    *session);
 static gint imap_cmd_examine   (IMAPSession    *session,
@@ -346,6 +365,7 @@ static gint imap_cmd_fetch  (IMAPSession    *sock,
                                 gboolean        headers,
                                 gboolean        body);
 static gint imap_cmd_append    (IMAPSession    *session,
+                                IMAPFolderItem *item,
                                 const gchar    *destfolder,
                                 const gchar    *file,
                                 IMAPFlags       flags,
@@ -357,17 +377,16 @@ static gint imap_cmd_copy       (IMAPSession *session,
                                 struct mailimap_set ** source,
                                 struct mailimap_set ** dest);
 static gint imap_cmd_store     (IMAPSession    *session,
+                                IMAPFolderItem *item,
                                 struct mailimap_set * set,
                                 IMAPFlags flags,
+                                GSList *tags,
                                 int do_add);
 static gint imap_cmd_expunge   (IMAPSession    *session);
 
 static void imap_path_separator_subst          (gchar          *str,
                                                 gchar           separator);
 
-static gchar *imap_utf8_to_modified_utf7       (const gchar    *from);
-static gchar *imap_modified_utf7_to_utf8       (const gchar    *mutf7_str);
-
 static gboolean imap_rename_folder_func                (GNode          *node,
                                                 gpointer        data);
 static gint imap_get_num_list                  (Folder         *folder,
@@ -404,11 +423,12 @@ static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *m
 static GSList * imap_uid_list_from_lep(clist * list);
 static GSList * imap_uid_list_from_lep_tab(carray * list);
 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
-                                                  GHashTable * hash);
+                                                  GHashTable * hash,
+                                                  GHashTable *tags_hash);
 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
                                       FolderItem *item);
 static void imap_lep_set_free(GSList *seq_list);
-static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags);
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
 
 typedef struct _hashtable_data {
        GSList *msglist;
@@ -417,16 +437,6 @@ typedef struct _hashtable_data {
 
 static FolderClass imap_class;
 
-typedef struct _thread_data {
-       gchar *server;
-       gushort port;
-       gboolean done;
-       SockInfo *sock;
-#if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
-       SSLType ssl_type;
-#endif
-} thread_data;
-
 FolderClass *imap_get_class(void)
 {
        if (imap_class.idstr == NULL) {
@@ -473,6 +483,7 @@ FolderClass *imap_get_class(void)
                imap_class.set_batch = imap_set_batch;
                imap_class.synchronise = imap_synchronise;
                imap_class.remove_cached_msg = imap_remove_cached_msg;
+               imap_class.commit_tags = imap_commit_tags;
 #ifdef USE_PTREAD
                pthread_mutex_init(&imap_mutex, NULL);
 #endif
@@ -518,20 +529,17 @@ static void unlock_session(IMAPSession *session)
        }
 }
 
-static void imap_disc_session_destroy(Folder *folder)
+static void imap_disc_session_destroy(IMAPSession *session)
 {
-       RemoteFolder *rfolder = REMOTE_FOLDER(folder);
-       IMAPSession *session = NULL;
+       RemoteFolder *rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
        
        if (!rfolder)
                return;
-       session = IMAP_SESSION(rfolder->session);
        if (!session)
                return;
-       rfolder->session = NULL;
        log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
        SESSION(session)->state = SESSION_DISCONNECTED;
-       session_destroy(SESSION(session));
+       SESSION(session)->sock = NULL;
 }
 
 static gboolean is_fatal(int libetpan_errcode)
@@ -549,146 +557,145 @@ static gboolean is_fatal(int libetpan_errcode)
 
 static void imap_handle_error(Session *session, int libetpan_errcode)
 {
+       const gchar *session_server = (session ? session->server:"(null)");
        switch(libetpan_errcode) {
        case MAILIMAP_NO_ERROR:
                return;
        case MAILIMAP_NO_ERROR_AUTHENTICATED:
-               log_warning(LOG_PROTOCOL, _("IMAP error: authenticated\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: authenticated\n"), session_server);
                break;
        case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
-               log_warning(LOG_PROTOCOL, _("IMAP error: not authenticated\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: not authenticated\n"), session_server);
                break;
        case MAILIMAP_ERROR_BAD_STATE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: bad state\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: bad state\n"), session_server);
                break;
        case MAILIMAP_ERROR_STREAM:
-               log_warning(LOG_PROTOCOL, _("IMAP error: stream error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: stream error\n"), session_server);
                break;
        case MAILIMAP_ERROR_PARSE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: parse error "
-                                           "(very probably non-RFC compliance from the server)\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: parse error "
+                                           "(very probably non-RFC compliance from the server)\n"), session_server);
                break;
        case MAILIMAP_ERROR_CONNECTION_REFUSED:
-               log_warning(LOG_PROTOCOL, _("IMAP error: connection refused\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection refused\n"), session_server);
                break;
        case MAILIMAP_ERROR_MEMORY:
-               log_warning(LOG_PROTOCOL, _("IMAP error: memory error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: memory error\n"), session_server);
                break;
        case MAILIMAP_ERROR_FATAL:
-               log_warning(LOG_PROTOCOL, _("IMAP error: fatal error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: fatal error\n"), session_server);
                break;
        case MAILIMAP_ERROR_PROTOCOL:
-               log_warning(LOG_PROTOCOL, _("IMAP error: protocol error"
-                                           "(very probably non-RFC compliance from the server)\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: protocol error"
+                                           "(very probably non-RFC compliance from the server)\n"), session_server);
                break;
        case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
-               log_warning(LOG_PROTOCOL, _("IMAP error: connection not accepted\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection not accepted\n"), session_server);
                break;
        case MAILIMAP_ERROR_APPEND:
-               log_warning(LOG_PROTOCOL, _("IMAP error: APPEND error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: APPEND error\n"), session_server);
                break;
        case MAILIMAP_ERROR_NOOP:
-               log_warning(LOG_PROTOCOL, _("IMAP error: NOOP error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: NOOP error\n"), session_server);
                break;
        case MAILIMAP_ERROR_LOGOUT:
-               log_warning(LOG_PROTOCOL, _("IMAP error: LOGOUT error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGOUT error\n"), session_server);
                break;
        case MAILIMAP_ERROR_CAPABILITY:
-               log_warning(LOG_PROTOCOL, _("IMAP error: CAPABILITY error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: CAPABILITY error\n"), session_server);
                break;
        case MAILIMAP_ERROR_CHECK:
-               log_warning(LOG_PROTOCOL, _("IMAP error: CHECK error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: CHECK error\n"), session_server);
                break;
        case MAILIMAP_ERROR_CLOSE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: CLOSE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: CLOSE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_EXPUNGE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: EXPUNGE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXPUNGE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_COPY:
-               log_warning(LOG_PROTOCOL, _("IMAP error: COPY error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: COPY error\n"), session_server);
                break;
        case MAILIMAP_ERROR_UID_COPY:
-               log_warning(LOG_PROTOCOL, _("IMAP error: UID COPY error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID COPY error\n"), session_server);
                break;
        case MAILIMAP_ERROR_CREATE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: CREATE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: CREATE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_DELETE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: DELETE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: DELETE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_EXAMINE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: EXAMINE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXAMINE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_FETCH:
-               log_warning(LOG_PROTOCOL, _("IMAP error: FETCH error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: FETCH error\n"), session_server);
                break;
        case MAILIMAP_ERROR_UID_FETCH:
-               log_warning(LOG_PROTOCOL, _("IMAP error: UID FETCH error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID FETCH error\n"), session_server);
                break;
        case MAILIMAP_ERROR_LIST:
-               log_warning(LOG_PROTOCOL, _("IMAP error: LIST error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: LIST error\n"), session_server);
                break;
        case MAILIMAP_ERROR_LOGIN:
-               log_warning(LOG_PROTOCOL, _("IMAP error: LOGIN error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGIN error\n"), session_server);
                break;
        case MAILIMAP_ERROR_LSUB:
-               log_warning(LOG_PROTOCOL, _("IMAP error: LSUB error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: LSUB error\n"), session_server);
                break;
        case MAILIMAP_ERROR_RENAME:
-               log_warning(LOG_PROTOCOL, _("IMAP error: RENAME error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: RENAME error\n"), session_server);
                break;
        case MAILIMAP_ERROR_SEARCH:
-               log_warning(LOG_PROTOCOL, _("IMAP error: SEARCH error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: SEARCH error\n"), session_server);
                break;
        case MAILIMAP_ERROR_UID_SEARCH:
-               log_warning(LOG_PROTOCOL, _("IMAP error: UID SEARCH error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID SEARCH error\n"), session_server);
                break;
        case MAILIMAP_ERROR_SELECT:
-               log_warning(LOG_PROTOCOL, _("IMAP error: SELECT error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: SELECT error\n"), session_server);
                break;
        case MAILIMAP_ERROR_STATUS:
-               log_warning(LOG_PROTOCOL, _("IMAP error: STATUS error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: STATUS error\n"), session_server);
                break;
        case MAILIMAP_ERROR_STORE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: STORE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: STORE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_UID_STORE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: UID STORE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID STORE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_SUBSCRIBE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: SUBSCRIBE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: SUBSCRIBE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_UNSUBSCRIBE:
-               log_warning(LOG_PROTOCOL, _("IMAP error: UNSUBSCRIBE error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: UNSUBSCRIBE error\n"), session_server);
                break;
        case MAILIMAP_ERROR_STARTTLS:
-               log_warning(LOG_PROTOCOL, _("IMAP error: STARTTLS error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: STARTTLS error\n"), session_server);
                break;
        case MAILIMAP_ERROR_INVAL:
-               log_warning(LOG_PROTOCOL, _("IMAP error: INVAL error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: INVAL error\n"), session_server);
                break;
        case MAILIMAP_ERROR_EXTENSION:
-               log_warning(LOG_PROTOCOL, _("IMAP error: EXTENSION error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXTENSION error\n"), session_server);
                break;
        case MAILIMAP_ERROR_SASL:
-               log_warning(LOG_PROTOCOL, _("IMAP error: SASL error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: SASL error\n"), session_server);
                break;
-#if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
        case MAILIMAP_ERROR_SSL:
-               log_warning(LOG_PROTOCOL, _("IMAP error: SSL error\n"));
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: SSL error\n"), session_server);
                break;
-#endif
 #endif
        default:
-               log_warning(LOG_PROTOCOL, _("IMAP error: Unknown error [%d]\n"),
-                       libetpan_errcode);
+               log_warning(LOG_PROTOCOL, _("IMAP error on %s: Unknown error [%d]\n"),
+                       session_server, libetpan_errcode);
                break;
        }
 
        if (session && is_fatal(libetpan_errcode)) {
-               imap_disc_session_destroy(IMAP_SESSION(session)->folder);
+               imap_disc_session_destroy(IMAP_SESSION(session));
        } else if (session && !is_fatal(libetpan_errcode)) {
                if (IMAP_SESSION(session)->busy)
                        unlock_session(IMAP_SESSION(session));
@@ -776,8 +783,7 @@ static int imap_get_capabilities(IMAPSession *session)
        capabilities = imap_threaded_capability(session->folder, &result);
 
        if (result != MAILIMAP_NO_ERROR) {
-               imap_handle_error(SESSION(session), result);
-               return MAILIMAP_ERROR_CAPABILITY;
+               return result;
        }
 
        if (capabilities == NULL) {
@@ -812,14 +818,16 @@ static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
                      IMAPAuthType type)
 {
-       gint ok = MAILIMAP_ERROR_BAD_STATE;
+       gint ok = MAILIMAP_ERROR_LOGIN;
        static time_t last_login_err = 0;
        gchar *ext_info = "";
        int r;
+       gchar *server = NULL;
        if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
                return r;
        }
+       server = g_strdup(SESSION(session)->server);
        switch(type) {
        case IMAP_AUTH_ANON:
                ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
@@ -827,6 +835,9 @@ static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass
        case IMAP_AUTH_CRAM_MD5:
                ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
                break;
+       case IMAP_AUTH_DIGEST_MD5:
+               ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
+               break;
        case IMAP_AUTH_LOGIN:
                ok = imap_cmd_login(session, user, pass, "LOGIN");
                break;
@@ -837,19 +848,21 @@ static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass
                debug_print("capabilities:\n"
                                "\t ANONYMOUS %d\n"
                                "\t CRAM-MD5 %d\n"
+                               "\t DIGEST-MD5 %d\n"
                                "\t LOGIN %d\n"
                                "\t GSSAPI %d\n", 
                        imap_has_capability(session, "ANONYMOUS"),
                        imap_has_capability(session, "CRAM-MD5"),
+                       imap_has_capability(session, "DIGEST-MD5"),
                        imap_has_capability(session, "LOGIN"),
                        imap_has_capability(session, "GSSAPI"));
                if (imap_has_capability(session, "CRAM-MD5"))
                        ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
-               if ((ok == MAILIMAP_ERROR_BAD_STATE ||
-                    ok == MAILIMAP_ERROR_LOGIN) && imap_has_capability(session, "GSSAPI"))
+               if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
+                       ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
+               if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
                        ok = imap_cmd_login(session, user, pass, "GSSAPI");
-               if (ok == MAILIMAP_ERROR_BAD_STATE||
-                   ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
+               if (ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
                        ok = imap_cmd_login(session, user, pass, "LOGIN");
        }
 
@@ -862,19 +875,26 @@ static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass
                                     "CRAM-MD5 SASL plugin is installed.");
                } 
 
+               if (type == IMAP_AUTH_DIGEST_MD5) {
+                       ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
+                                    "compiled with SASL support and the "
+                                    "DIGEST-MD5 SASL plugin is installed.");
+               } 
+
                if (time(NULL) - last_login_err > 10) {
                        if (!prefs_common.no_recv_err_panel) {
-                               alertpanel_error(_("Connection to %s failed: "
+                               alertpanel_error_log(_("Connection to %s failed: "
                                        "login refused.%s"),
-                                       SESSION(session)->server, ext_info);
+                                       server, ext_info);
                        } else {
                                log_error(LOG_PROTOCOL, _("Connection to %s failed: "
                                        "login refused.%s\n"),
-                                       SESSION(session)->server, ext_info);
+                                       server, ext_info);
                        }
                }
                last_login_err = time(NULL);
        }
+       g_free(server);
        return ok;
 }
 
@@ -887,6 +907,7 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
        if (rfolder->session == NULL) {
                log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
                            folder->account->recv_server);
+               SESSION(session)->sock = NULL;
                session_destroy(SESSION(session));
                session = NULL;
        } else {
@@ -898,6 +919,7 @@ static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *sess
                            " disconnected. Reconnecting...\n"),
                            folder->account->recv_server);
                SESSION(session)->state = SESSION_DISCONNECTED;
+               SESSION(session)->sock = NULL;
                session_destroy(SESSION(session));
                /* Clear folders session to make imap_session_get create
                   a new session, because of rfolder->session == NULL
@@ -929,12 +951,17 @@ static IMAPSession *imap_session_get(Folder *folder)
        }
 
        /* Make sure we have a session */
-       if (rfolder->session != NULL) {
+       if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
                session = IMAP_SESSION(rfolder->session);
+       } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
+               session_destroy(SESSION(rfolder->session));
+               rfolder->session = NULL;
+               goto new_conn;
        } else if (rfolder->connecting) {
                debug_print("already connecting\n");
                return NULL;
        } else {
+new_conn:
                imap_reset_uid_lists(folder);
                if (time(NULL) - rfolder->last_failure <= 2)
                        return NULL;
@@ -949,13 +976,16 @@ static IMAPSession *imap_session_get(Folder *folder)
 
        /* Make sure session is authenticated */
        if (!IMAP_SESSION(session)->authenticated)
-               imap_session_authenticate(IMAP_SESSION(session), folder->account);
+               r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
        
-       if (!IMAP_SESSION(session)->authenticated) {
-               imap_threaded_disconnect(session->folder);
+       if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
                rfolder->session = NULL;
-               SESSION(session)->state = SESSION_DISCONNECTED;
-               session_destroy(SESSION(session));
+               if (!is_fatal(r)) {
+                       imap_threaded_disconnect(session->folder);
+                       SESSION(session)->state = SESSION_DISCONNECTED;
+                       SESSION(session)->sock = NULL;
+                       session_destroy(SESSION(session));
+               }
                rfolder->last_failure = time(NULL);
                rfolder->connecting = FALSE;
                return NULL;
@@ -975,8 +1005,11 @@ static IMAPSession *imap_session_get(Folder *folder)
                        debug_print("disconnected!\n");
                        if (!is_fatal(r))
                                session = imap_reconnect_if_possible(folder, session);
-                       else
+                       else {
+                               rfolder->session = NULL;
+                               rfolder->connecting = FALSE;
                                session = imap_session_get(folder);
+                       }
                }
                if (session)
                        session->cancelled = FALSE;
@@ -1023,13 +1056,16 @@ static IMAPSession *imap_session_new(Folder * folder,
 
        imap_init(folder);
        statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
+#ifndef G_OS_WIN32
        if (account->set_tunnelcmd) {
                r = imap_threaded_connect_cmd(folder,
                                              account->tunnelcmd,
                                              account->recv_server,
                                              port);
        }
-       else {
+       else 
+#endif
+       {
 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
                if (ssl_type == SSL_TUNNEL) {
                        r = imap_threaded_connect_ssl(folder,
@@ -1053,12 +1089,10 @@ static IMAPSession *imap_session_new(Folder * folder,
                authenticated = FALSE;
        }
        else {
-#if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
                if (r == MAILIMAP_ERROR_SSL)
                        log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
                else
-#endif
 #endif
                        imap_handle_error(NULL, r);
 
@@ -1074,9 +1108,10 @@ static IMAPSession *imap_session_new(Folder * folder,
        }
        
        session = g_new0(IMAPSession, 1);
-       session_init(SESSION(session));
+       session_init(SESSION(session), account, FALSE);
        SESSION(session)->type             = SESSION_IMAP;
        SESSION(session)->server           = g_strdup(account->recv_server);
+       SESSION(session)->port             = port;
        SESSION(session)->sock             = NULL;
        
        SESSION(session)->destroy          = imap_session_destroy;
@@ -1099,7 +1134,10 @@ static IMAPSession *imap_session_new(Folder * folder,
                ok = imap_cmd_starttls(session);
                if (ok != MAILIMAP_NO_ERROR) {
                        log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
-                       session_destroy(SESSION(session));
+                       if (!is_fatal(ok)) {
+                               SESSION(session)->sock = NULL;
+                               session_destroy(SESSION(session));
+                       }
                        return NULL;
                }
 
@@ -1115,49 +1153,55 @@ static IMAPSession *imap_session_new(Folder * folder,
        return session;
 }
 
-static void imap_session_authenticate(IMAPSession *session, 
-                                     const PrefsAccount *account)
+static gint imap_session_authenticate(IMAPSession *session, 
+                                     PrefsAccount *account)
 {
        gchar *pass, *acc_pass;
        gboolean failed = FALSE;
-
-       g_return_if_fail(account->userid != NULL);
+       gint ok = MAILIMAP_NO_ERROR;
+       g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
        acc_pass = account->passwd;
 try_again:
        pass = acc_pass;
        if (!pass && account->imap_auth_type != IMAP_AUTH_ANON) {
                gchar *tmp_pass;
-               tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
+               tmp_pass = input_dialog_query_password_keep(account->recv_server, 
+                                                           account->userid,
+                                                           &(account->session_passwd));
                if (!tmp_pass)
-                       return;
-               Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return;});
+                       return MAILIMAP_NO_ERROR;
+               Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
                g_free(tmp_pass);
        } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
                pass = "";
        }
        statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
                                account->recv_server);
-       if (imap_auth(session, account->userid, pass, account->imap_auth_type) != MAILIMAP_NO_ERROR) {
+       if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
                statusbar_pop_all();
                
-               if (!failed) {
+               if (!failed && !is_fatal(ok)) {
                        acc_pass = NULL;
                        failed = TRUE;
+                       if (account->session_passwd != NULL) {
+                               g_free(account->session_passwd);
+                               account->session_passwd = NULL;
+                       }
                        goto try_again;
                } else {
                        if (prefs_common.no_recv_err_panel) {
-                               log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s."), account->recv_server);
+                               log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
                                mainwindow_show_error();
                        } else
                                alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
                }               
 
-               return;
+               return ok;
        } 
 
        statuswindow_pop_all();
        session->authenticated = TRUE;
-       return;
+       return MAILIMAP_NO_ERROR;
 }
 
 static void imap_session_destroy(Session *session)
@@ -1167,8 +1211,6 @@ static void imap_session_destroy(Session *session)
        
        imap_free_capabilities(IMAP_SESSION(session));
        g_free(IMAP_SESSION(session)->mbox);
-       sock_close(session->sock);
-       session->sock = NULL;
 }
 
 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
@@ -1185,7 +1227,7 @@ static guint get_file_size_with_crs(const gchar *filename)
        if (filename == NULL)
                return -1;
        
-       fp = fopen(filename, "rb");
+       fp = g_fopen(filename, "rb");
        if (!fp)
                return -1;
        
@@ -1214,11 +1256,128 @@ static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *ms
        g_free(path);
 
        if (is_file_exist(filename)) {
-               g_unlink(filename);
+               claws_unlink(filename);
        }
        g_free(filename);
 }
 
+typedef struct _TagsData {
+       gchar *str;
+       GSList *msglist;
+       IMAPFolderItem *item;
+} TagsData;
+
+static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
+{
+       IMAPSession *session;
+       gint ok, can_create_tags;
+       Folder *folder = NULL;
+       TagsData *ht_data = NULL;
+       GSList *cur;
+
+       g_return_if_fail(item != NULL);
+       g_return_if_fail(msginfo != NULL);
+
+       folder = item->folder;
+       debug_print("getting session...\n");
+       session = imap_session_get(folder);
+       
+       if (!session) {
+               debug_print("can't get session\n");
+               return;
+       }
+
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
+
+       if (ok != MAILIMAP_NO_ERROR) {
+               return;
+       }
+
+       
+       if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
+               return;
+       
+       if (IMAP_FOLDER_ITEM(item)->batching) {
+               /* instead of performing an UID STORE command for each message change,
+                * as a lot of them can change "together", we just fill in hashtables
+                * and defer the treatment so that we're able to send only one
+                * command.
+                */
+               debug_print("IMAP batch mode on, deferring tags change\n");
+               for (cur = tags_set; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       if (cur_tag) {
+                               ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
+                                       GINT_TO_POINTER(cur_tag));
+                               if (ht_data == NULL) {
+                                       ht_data = g_new0(TagsData, 1);
+                                       ht_data->str = g_strdup(tags_get_tag(cur_tag));
+                                       ht_data->item = IMAP_FOLDER_ITEM(item);
+                                       g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
+                                               GINT_TO_POINTER(cur_tag), ht_data);
+                               }
+                               ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
+                       } 
+               }
+               for (cur = tags_unset; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       if (cur_tag) {
+                               ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
+                                       GINT_TO_POINTER(cur_tag));
+                               if (ht_data == NULL) {
+                                       ht_data = g_new0(TagsData, 1);
+                                       ht_data->str = g_strdup(tags_get_tag(cur_tag));
+                                       ht_data->item = IMAP_FOLDER_ITEM(item);
+                                       g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
+                                               GINT_TO_POINTER(cur_tag), ht_data);
+                               }
+                               ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
+                       }
+               }
+       } else {
+               GSList *list_set = NULL;
+               GSList *list_unset = NULL;
+               GSList numlist;
+               
+               numlist.data = GINT_TO_POINTER(msginfo->msgnum);
+               numlist.next = NULL;
+       
+               debug_print("IMAP changing tags NOW\n");
+               for (cur = tags_set; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       const gchar *str = tags_get_tag(cur_tag);
+                       if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
+                               list_set = g_slist_prepend(list_set, g_strdup(str));
+               }
+               if (list_set) {
+                       ok = imap_set_message_flags(session, 
+                               IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
+                       slist_free_strings(list_set);
+                       g_slist_free(list_set);
+                       if (ok != MAILIMAP_NO_ERROR) {
+                               return;
+                       }
+               }
+
+               for (cur = tags_unset; cur; cur = cur->next) {
+                       gint cur_tag = GPOINTER_TO_INT(cur->data);
+                       const gchar *str = tags_get_tag(cur_tag);
+                       if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
+                               list_unset = g_slist_prepend(list_unset, g_strdup(str));
+               }
+               if (list_unset) {
+                       ok = imap_set_message_flags(session, 
+                               IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
+                       slist_free_strings(list_unset);
+                       g_slist_free(list_unset);
+                       if (ok != MAILIMAP_NO_ERROR) {
+                               return;
+                       }
+               }
+       }
+}
+
 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                                  gboolean headers, gboolean body)
 {
@@ -1292,8 +1451,8 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
        lock_session(session); /* unlocked later in the function */
 
        debug_print("IMAP fetching messages\n");
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        if (ok != MAILIMAP_NO_ERROR) {
                g_warning("can't select mailbox %s\n", item->path);
                g_free(filename);
@@ -1427,8 +1586,9 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        if (!session) {
                return -1;
        }
-       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
-
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
+       if (is_fatal(ok))
+               return -1;
        statusbar_print_all(_("Adding messages..."));
        total = g_slist_length(file_list);
        for (cur = file_list; cur != NULL; cur = cur->next) {
@@ -1445,8 +1605,15 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                                iflags |= IMAP_FLAG_FLAGGED;
                        if (MSG_IS_REPLIED(*fileinfo->flags))
                                iflags |= IMAP_FLAG_ANSWERED;
+                       if (MSG_IS_FORWARDED(*fileinfo->flags))
+                               iflags |= IMAP_FLAG_FORWARDED;
+                       if (MSG_IS_SPAM(*fileinfo->flags))
+                               iflags |= IMAP_FLAG_SPAM;
+                       else
+                               iflags |= IMAP_FLAG_HAM;
                        if (!MSG_IS_UNREAD(*fileinfo->flags))
                                iflags |= IMAP_FLAG_SEEN;
+                       
                }
                
                if (real_file == NULL)
@@ -1458,7 +1625,7 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                    folder_has_parent_of_type(dest, F_TRASH))
                        iflags |= IMAP_FLAG_SEEN;
 
-               ok = imap_cmd_append(session, destdir, real_file, iflags, 
+               ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
                                     &new_uid);
 
                if (ok != MAILIMAP_NO_ERROR) {
@@ -1518,8 +1685,8 @@ static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
        }
        if (missing_uids) {
                gint a;
-               ok = imap_select(session, IMAP_FOLDER(folder), dest->path,
-                        &a, NULL, NULL, NULL, FALSE);
+               ok = imap_select(session, IMAP_FOLDER(folder), dest,
+                        &a, NULL, NULL, NULL, NULL, FALSE);
        }
        return last_uid;
 }
@@ -1606,15 +1773,19 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
 
        lock_session(session); /* unlocked later in the function */
 
-       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
 
        unlock_session(session);
 
-       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
+
+       if (is_fatal(ok))
+               return ok;
+
        seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
        uid_mapping = g_relation_new(2);
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
@@ -1788,13 +1959,15 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
 
        msginfo = (MsgInfo *)msglist->data;
 
-       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+       ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
 
-       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
+       destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
+       if (is_fatal(ok))
+               return ok;
        for (cur = msglist; cur; cur = cur->next) {
                msginfo = (MsgInfo *)cur->data;
                if (!MSG_IS_DELETED(msginfo->flags))
@@ -1807,7 +1980,7 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
 
        if (numlist != NULL) {
                ok = imap_set_message_flags
-                       (session, numlist, IMAP_FLAG_DELETED, TRUE);
+                       (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
                if (ok != MAILIMAP_NO_ERROR) {
                        log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
                        return ok;
@@ -1909,11 +2082,15 @@ static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
                extract_quote(root_folder, '"');
                subst_char(root_folder,
                           imap_get_path_separator(session, IMAP_FOLDER(folder),
-                                                  root_folder),
+                                                  root_folder, &r),
                           '/');
+               if (is_fatal(r))
+                       return -1;
                strtailchomp(root_folder, '/');
                real_path = imap_get_real_path
-                       (session, IMAP_FOLDER(folder), root_folder);
+                       (session, IMAP_FOLDER(folder), root_folder, &r);
+               if (is_fatal(r))
+                       return -1;
                debug_print("IMAP root directory: %s\n", real_path);
 
                /* check if root directory exist */
@@ -1989,7 +2166,9 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
        folder = item->folder;
        imapfolder = IMAP_FOLDER(folder);
 
-       separator = imap_get_path_separator(session, imapfolder, item->path);
+       separator = imap_get_path_separator(session, imapfolder, item->path, &r);
+       if (is_fatal(r))
+               return r;
 
        if (folder->ui_func)
                folder->ui_func(folder, item, folder->ui_func_data);
@@ -1998,7 +2177,9 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
                wildcard[0] = separator;
                wildcard[1] = '%';
                wildcard[2] = '\0';
-               real_path = imap_get_real_path(session, imapfolder, item->path);
+               real_path = imap_get_real_path(session, imapfolder, item->path, &r);
+               if (is_fatal(r))
+                       return r;
        } else {
                wildcard[0] = '%';
                wildcard[1] = '\0';
@@ -2017,6 +2198,7 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gbo
        if (r != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
                item_list = NULL;
+               return r;
        }
        else {
                item_list = imap_list_from_lep(imapfolder,
@@ -2130,13 +2312,17 @@ GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only,
        if (!session)
                return NULL;
 
-       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
+       if (is_fatal(r))
+               return NULL;
 
        if (item->path) {
                wildcard[0] = separator;
                wildcard[1] = '%';
                wildcard[2] = '\0';
-               real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
+               real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
+               if (is_fatal(r))
+                       return NULL;
        } else {
                wildcard[0] = '%';
                wildcard[1] = '\0';
@@ -2173,8 +2359,11 @@ GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only,
                }
                child_list = g_list_prepend(child_list,
                                imap_get_real_path(session, 
-                                       IMAP_FOLDER(folder), cur_item->path));
-               
+                                       IMAP_FOLDER(folder), cur_item->path, &r));
+               if (is_fatal(r)) {
+                       statusbar_pop_all();
+                       return NULL;
+               }
                folder_item_destroy(cur_item);
        }
        child_list = g_list_reverse(child_list);
@@ -2194,7 +2383,11 @@ GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only,
                        FolderItem *cur_item = FOLDER_ITEM(cur->data);
                        GList *oldlitem = NULL;
                        gchar *tmp = imap_get_real_path(session, 
-                                       IMAP_FOLDER(folder), cur_item->path);
+                                       IMAP_FOLDER(folder), cur_item->path, &r);
+                       if (r) {
+                               statusbar_pop_all();
+                               return NULL;
+                       }
                        folder_item_destroy(cur_item);
                        oldlitem = g_list_find_custom(
                                        child_list, tmp, (GCompareFunc)strcmp2);
@@ -2297,28 +2490,52 @@ static gchar *imap_folder_get_path(Folder *folder)
 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
 {
        gchar *folder_path, *path;
-
+       gchar *item_path = NULL;
+       
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(item != NULL, NULL);
        folder_path = imap_folder_get_path(folder);
 
        g_return_val_if_fail(folder_path != NULL, NULL);
-        if (folder_path[0] == G_DIR_SEPARATOR) {
-                if (item->path)
+       item_path = g_strdup(item->path);
+
+#ifdef G_OS_WIN32
+       if (strchr(item_path, ':') ||
+           strchr(item_path, '|') ||
+           strchr(item_path, '<') ||
+           strchr(item_path, '>') ||
+           strchr(item_path, '*') ||
+           strchr(item_path, '?') ||
+           strchr(item_path, '#') ||
+           strchr(item_path, ':')
+           ) {
+               g_free(item_path);
+               item_path = g_malloc(strlen(item->path)*3 +1);
+               qp_encode_line(item_path, item->path);
+       }
+#endif 
+
+        if (g_path_is_absolute(folder_path)) {
+                if (item_path)
                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
-                                           item->path, NULL);
+                                           item_path, NULL);
                 else
                         path = g_strdup(folder_path);
         } else {
-                if (item->path)
+                if (item_path)
                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
                                            folder_path, G_DIR_SEPARATOR_S,
-                                           item->path, NULL);
+                                           item_path, NULL);
                 else
                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
                                            folder_path, NULL);
         }
         g_free(folder_path);
+        g_free(item_path);
+#ifdef G_OS_WIN32
+       while (strchr(path, '/'))
+               *strchr(path, '/') = '\\';
+#endif
 
        return path;
 }
@@ -2366,14 +2583,16 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
 
        /* keep trailing directory separator to create a folder that contains
           sub folder */
-       imap_path = imap_utf8_to_modified_utf7(dirpath);
+       imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
 
        strtailchomp(dirpath, '/');
        Xstrdup_a(new_name, name, {
                g_free(dirpath); 
                return NULL;});
 
-       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
+       if (is_fatal(ok))
+               return NULL;
        imap_path_separator_subst(imap_path, separator);
        /* remove trailing / for display */
        strtailchomp(new_name, '/');
@@ -2491,13 +2710,17 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
                return -1;
        }
 
-       if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
+       if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
+               is_fatal(ok)) {
                g_warning(_("New folder name must not contain the namespace "
                            "path separator"));
                return -1;
        }
 
-       real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
+       real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
+       if (is_fatal(ok)) {
+               return -1;
+       }
 
        g_free(session->mbox);
        session->mbox = NULL;
@@ -2511,7 +2734,9 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
                return -1;
        }
 
-       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
+       separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
+       if (is_fatal(ok))
+               return -1;
        if (strchr(item->path, G_DIR_SEPARATOR)) {
                dirpath = g_path_get_dirname(item->path);
                newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
@@ -2519,7 +2744,7 @@ static gint imap_rename_folder(Folder *folder, FolderItem *item,
        } else
                newpath = g_strdup(name);
 
-       real_newpath = imap_utf8_to_modified_utf7(newpath);
+       real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
        imap_path_separator_subst(real_newpath, separator);
 
        ok = imap_cmd_rename(session, real_oldpath, real_newpath);
@@ -2569,8 +2794,8 @@ gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub
                return -1;
        }
        if (item && item->path) {
-               path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
-               if (!path)
+               path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
+               if (!path || is_fatal(r))
                        return -1;
                if (!strcmp(path, "INBOX") && sub == FALSE)
                        return -1;
@@ -2601,7 +2826,9 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
        if (!session) {
                return -1;
        }
-       path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
+       path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
+       if (is_fatal(ok))
+               return -1;
 
        imap_threaded_subscribe(folder, path, FALSE);
 
@@ -2611,17 +2838,17 @@ static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
                ok = imap_cmd_close(session);
                if (ok != MAILIMAP_NO_ERROR) {
                        debug_print("close err %d\n", ok);
-                       imap_handle_error(SESSION(session), ok);
                        return ok;
                }
        }
        ok = imap_cmd_delete(session, path);
-       if (ok != MAILIMAP_NO_ERROR) {
+       if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
                gchar *tmp = g_strdup_printf("%s%c", path, 
-                               imap_get_path_separator(session, IMAP_FOLDER(folder), path));
+                               imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
                g_free(path);
                path = tmp;
-               ok = imap_cmd_delete(session, path);
+               if (!is_fatal(ok))
+                       ok = imap_cmd_delete(session, path);
        }
 
        if (ok != MAILIMAP_NO_ERROR) {
@@ -2677,10 +2904,10 @@ static void *imap_get_uncached_messages_thread(void *data)
        IMAPSession *session = stuff->session;
        FolderItem *item = stuff->item;
        MsgNumberList *numlist = stuff->numlist;
-       
        GSList *newlist = NULL;
        GSList *llast = NULL;
        GSList *seq_list, *cur;
+       gboolean got_alien_tags = FALSE;
 
        debug_print("uncached_messages\n");
        
@@ -2718,14 +2945,39 @@ static void *imap_get_uncached_messages_thread(void *data)
                session_set_access_time(SESSION(session));
 
                count = 0;
-               for(i = 0 ; i < carray_count(env_list) ; i ++) {
+               for(i = 0 ; i < carray_count(env_list) ; i += 2) {
                        struct imap_fetch_env_info * info;
                        MsgInfo * msginfo;
-                       
+                       GSList *tags = NULL, *cur = NULL;
                        info = carray_get(env_list, i);
+                       tags = carray_get(env_list, i+1);
                        msginfo = imap_envelope_from_lep(info, item);
-                       if (msginfo == NULL)
+                       if (msginfo == NULL) {
+                               slist_free_strings(tags);
+                               g_slist_free(tags);
                                continue;
+                       }
+                       if (tags != NULL) {
+                               g_slist_free(msginfo->tags);
+                               msginfo->tags = NULL;
+                       }
+                       for (cur = tags; cur; cur = cur->next) {
+                               gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
+                               gint id = 0;
+                               id = tags_get_id_for_str(real_tag);
+                               if (id == -1) {
+                                       id = tags_add_tag(real_tag);
+                                       got_alien_tags = TRUE;
+                               }
+                               if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
+                                       msginfo->tags = g_slist_append(
+                                                       msginfo->tags,
+                                                       GINT_TO_POINTER(id));
+                               }
+                               g_free(real_tag);
+                       }
+                       slist_free_strings(tags);
+                       g_slist_free(tags);
                        msginfo->folder = item;
                        if (!newlist)
                                llast = newlist = g_slist_append(newlist, msginfo);
@@ -2739,6 +2991,11 @@ static void *imap_get_uncached_messages_thread(void *data)
                imap_fetch_env_free(env_list);
        }
        
+       if (got_alien_tags) {
+               tags_write_tags();
+               main_window_reflect_tags_changes(mainwindow_get_mainwindow());
+       }
+
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
                struct mailimap_set * imapset;
                
@@ -2855,7 +3112,7 @@ gchar imap_get_path_separator_for_item(FolderItem *item)
        IMAPFolder *imap_folder = NULL;
        IMAPSession *session = NULL;
        gchar result = '/';
-       
+       gint ok;
        if (!item)
                return '/';
        folder = item->folder;
@@ -2870,11 +3127,11 @@ 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);
+       result = imap_get_path_separator(session, imap_folder, item->path, &ok);
        return result;
 }
 
-static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
+static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
 {
        clist * lep_list;
        int r;
@@ -2886,6 +3143,7 @@ static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folde
        if (r != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
                log_warning(LOG_PROTOCOL, _("LIST failed\n"));
+               *ok = r;
                return '\0';
        }
 
@@ -2897,20 +3155,21 @@ static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folde
                separator = mb->mb_delimiter;
                debug_print("got separator: %c\n", folder->last_seen_separator);
        }
+       *ok = MAILIMAP_NO_ERROR;
        mailimap_list_result_free(lep_list);
        return separator;
 }
 
-static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
+static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
 {
        gchar separator = '/';
 
        if (folder->last_seen_separator == 0) {
-               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
+               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
        }
 
        if (folder->last_seen_separator == 0) {
-               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
+               folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
        }
 
        if (folder->last_seen_separator != 0) {
@@ -2921,7 +3180,7 @@ static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, c
        return separator;
 }
 
-static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
+static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
 {
        gchar *real_path;
        gchar separator;
@@ -2929,16 +3188,18 @@ static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(path != NULL, NULL);
 
-       real_path = imap_utf8_to_modified_utf7(path);
-       separator = imap_get_path_separator(session, folder, path);
+       real_path = imap_utf8_to_modified_utf7(path, FALSE);
+       separator = imap_get_path_separator(session, folder, path, ok);
        imap_path_separator_subst(real_path, separator);
 
        return real_path;
 }
 
 static gint imap_set_message_flags(IMAPSession *session,
+                                  IMAPFolderItem *item,
                                   MsgNumberList *numlist,
                                   IMAPFlags flags,
+                                  GSList *tags,
                                   gboolean is_set)
 {
        gint ok = 0;
@@ -2972,8 +3233,8 @@ static gint imap_set_message_flags(IMAPSession *session,
 
                statusbar_progress_all(set_item->set_first, total, 1);
 
-               ok = imap_cmd_store(session, imapset,
-                                   flags, is_set);
+               ok = imap_cmd_store(session, item, imapset,
+                                   flags, tags, is_set);
                statusbar_progress_all(set_item->set_last, total, 1);
                if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
                        /* reduce max set size */
@@ -3005,19 +3266,32 @@ typedef struct _select_data {
 } select_data;
 
 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
-                       const gchar *path,
+                       FolderItem *item,
                        gint *exists, gint *recent, gint *unseen,
-                       guint32 *uid_validity, gboolean block)
+                       guint32 *uid_validity, gint *can_create_flags,
+                       gboolean block)
 {
        gchar *real_path;
        gint ok;
        gint exists_, recent_, unseen_;
        guint32 uid_validity_;
-       
-       if (!exists && !recent && !unseen && !uid_validity) {
+       gint can_create_flags_;
+       const gchar *path = item ? item->path:NULL;
+
+       if (!item) {
+               return MAILIMAP_ERROR_BAD_STATE;
+       }
+
+       if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
                if (session->mbox && strcmp(session->mbox, path) == 0)
                        return MAILIMAP_NO_ERROR;
        }
+       if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
+               if (session->mbox && strcmp(session->mbox, path) == 0) {
+                       if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
+                               return MAILIMAP_NO_ERROR;
+               }
+       }
        if (!exists)
                exists = &exists_;
        if (!recent)
@@ -3026,6 +3300,8 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
                unseen = &unseen_;
        if (!uid_validity)
                uid_validity = &uid_validity_;
+       if (!can_create_flags)
+               can_create_flags = &can_create_flags_;
 
        g_free(session->mbox);
        session->mbox = NULL;
@@ -3033,10 +3309,14 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        session->recent = 0;
        session->expunge = 0;
 
-       real_path = imap_get_real_path(session, folder, path);
-
+       real_path = imap_get_real_path(session, folder, path, &ok);
+       if (is_fatal(ok))
+               return ok;              
+       g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
+       IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
        ok = imap_cmd_select(session, real_path,
-                            exists, recent, unseen, uid_validity, block);
+                            exists, recent, unseen, uid_validity, can_create_flags, 
+                            &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
        if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
        } else {
@@ -3047,9 +3327,14 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
                session->expunge = 0;
                session->unseen = *unseen;
                session->uid_validity = *uid_validity;
-               debug_print("select: exists %d recent %d expunge %d uid_validity %d\n", 
+               debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
                        session->exists, session->recent, session->expunge,
-                       session->uid_validity);
+                       session->uid_validity, *can_create_flags);
+       }
+       if (*can_create_flags) {
+               IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
+       } else {
+               IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
        }
        g_free(real_path);
 
@@ -3069,7 +3354,9 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
        gchar *real_path;
        guint mask = 0;
        
-       real_path = imap_get_real_path(session, folder, path);
+       real_path = imap_get_real_path(session, folder, path, &r);
+       if (is_fatal(r))
+               return r;
 
        if (messages) {
                mask |= 1 << 0;
@@ -3092,7 +3379,6 @@ static gint imap_status(IMAPSession *session, IMAPFolder *folder,
            !strcmp(session->mbox, item->item.path)) {
                r = imap_cmd_close(session);
                if (r != MAILIMAP_NO_ERROR) {
-                       imap_handle_error(SESSION(session), r);
                        debug_print("close err %d\n", r);
                        return r;
                }
@@ -3198,11 +3484,11 @@ static gint imap_cmd_login(IMAPSession *session,
                                        "has been compiled without OpenSSL "
                                        "support.\n"),
                                        SESSION(session)->server);
-                       return MAILIMAP_ERROR_BAD_STATE;
+                       return MAILIMAP_ERROR_LOGIN;
 #endif
                } else {
                        log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
-                       return MAILIMAP_ERROR_BAD_STATE;
+                       return MAILIMAP_ERROR_LOGIN;
                }
        }
 
@@ -3281,12 +3567,13 @@ static gint imap_cmd_starttls(IMAPSession *session)
 
 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
                            gint *exists, gint *recent, gint *unseen,
-                           guint32 *uid_validity, gboolean block)
+                           guint32 *uid_validity, gint *can_create_flags,
+                           GSList **ok_flags, gboolean block)
 {
        int r;
 
        r = imap_threaded_select(session->folder, folder,
-                                exists, recent, unseen, uid_validity);
+                                exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
        if (r != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
                debug_print("select err %d\n", r);
@@ -3337,7 +3624,6 @@ static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
        r = imap_threaded_create(session->folder, folder);
        if (r != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
-               
                return r;
        }
 
@@ -3401,7 +3687,7 @@ static void *imap_cmd_fetch_thread(void *data)
        if (r != MAILIMAP_NO_ERROR) {
                imap_handle_error(SESSION(session), r);
                debug_print("fetch err %d\n", r);
-               return GINT_TO_POINTER(MAILIMAP_ERROR_BAD_STATE);
+               return GINT_TO_POINTER(r);
        }
        return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
 }
@@ -3434,7 +3720,9 @@ static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
 }
 
 
-static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
+static gint imap_cmd_append(IMAPSession *session, 
+                           IMAPFolderItem *item,
+                           const gchar *destfolder,
                            const gchar *file, IMAPFlags flags, 
                            guint32 *new_uid)
 {
@@ -3443,7 +3731,7 @@ static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
        
        g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
 
-       flag_list = imap_flag_to_lep(flags);
+       flag_list = imap_flag_to_lep(item, flags, NULL);
        lock_session(session);
        r = imap_threaded_append(session->folder, destfolder,
                         file, flag_list, (int *)new_uid);
@@ -3479,15 +3767,17 @@ static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
        return MAILIMAP_NO_ERROR;
 }
 
-static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
-                          IMAPFlags flags, int do_add)
+static gint imap_cmd_store(IMAPSession *session, 
+                          IMAPFolderItem *item,
+                          struct mailimap_set * set,
+                          IMAPFlags flags, GSList *tags, int do_add)
 {
        int r;
-       struct mailimap_flag_list * flag_list;
+       struct mailimap_flag_list * flag_list = NULL;
        struct mailimap_store_att_flags * store_att_flags;
        
-       flag_list = imap_flag_to_lep(flags);
-       
+       flag_list = imap_flag_to_lep(item, flags, tags);
+
        if (do_add)
                store_att_flags =
                        mailimap_store_att_flags_new_add_flags_silent(flag_list);
@@ -3542,278 +3832,59 @@ static void imap_path_separator_subst(gchar *str, gchar separator)
        }
 }
 
-/* ===================================================================
- * UTF-7 conversion routines as in RFC 2192
- * =================================================================== 
- * These two functions from: 
- * libimap library.
- * Copyright (C) 2003-2004 Pawel Salek. */
+static gboolean imap_rename_folder_func(GNode *node, gpointer data)
+{
+       FolderItem *item = node->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);
+       gint ok;
+       oldpathlen = strlen(oldpath);
+       if (strncmp(oldpath, item->path, oldpathlen) != 0) {
+               g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
+               return TRUE;
+       }
 
-/* UTF7 modified base64 alphabet */
-static char base64chars[] =
-  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
-#define UNDEFINED 64
+       base = item->path + oldpathlen;
+       while (*base == G_DIR_SEPARATOR) base++;
+       if (*base == '\0')
+               new_itempath = g_strdup(newpath);
+       else
+               new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
+                                          NULL);
 
-/* UTF16 definitions */
-#define UTF16MASK       0x03FFUL
-#define UTF16SHIFT      10
-#define UTF16BASE       0x10000UL
-#define UTF16HIGHSTART  0xD800UL
-#define UTF16HIGHEND    0xDBFFUL
-#define UTF16LOSTART    0xDC00UL
-#define UTF16LOEND      0xDFFFUL
+       real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
+       g_free(item->path);
+       item->path = new_itempath;
+       
+       real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
+       
+       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;
+}
 
-/* Convert an IMAP mailbox to a UTF-8 string.
- *  dst needs to have roughly 4 times the storage space of src
- *    Hex encoding can triple the size of the input
- *    UTF-7 can be slightly denser than UTF-8
- *     (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
- */
-static char*
-imap_modified_utf7_to_utf8(const char *mbox)
+static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
 {
-  unsigned c, i, bitcount;
-  unsigned long ucs4, utf16, bitbuf;
-  unsigned char base64[256];
-  const char *src;
-  char *dst, *res  = malloc(2*strlen(mbox)+1);
+       GSList *uidlist, *elem;
+       int r = -1;
+       clist * lep_uidlist;
+       gint ok, nummsgs = 0, lastuid_old;
 
-  bitbuf = 0;
-  dst = res;
-  src = mbox;
-  if(!dst) return NULL;
-  /* initialize modified base64 decoding table */
-  memset(base64, UNDEFINED, sizeof (base64));
-  for (i = 0; i < sizeof (base64chars); ++i) {
-    base64[(unsigned)base64chars[i]] = i;
-  }
+       if (session == NULL) {
+               return -1;
+       }
 
-  /* loop until end of string */
-  while (*src != '\0') {
-    c = *src++;
-    /* deal with literal characters and &- */
-    if (c != '&' || *src == '-') {
-      /* encode literally */
-      *dst++ = c;
-      /* skip over the '-' if this is an &- sequence */
-      if (c == '&') ++src;
-    } else {
-      /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
-      bitbuf = 0;
-      bitcount = 0;
-      ucs4 = 0;
-      while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
-        ++src;
-        bitbuf = (bitbuf << 6) | c;
-        bitcount += 6;
-        /* enough bits for a UTF-16 character? */
-        if (bitcount >= 16) {
-          bitcount -= 16;
-          utf16 = (bitcount ? bitbuf >> bitcount
-                   : bitbuf) & 0xffff;
-          /* convert UTF16 to UCS4 */
-          if
-            (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
-            ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
-            continue;
-          } else if
-            (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
-            ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
-          } else {
-            ucs4 = utf16;
-          }
-
-          /* convert UTF-16 range of UCS4 to UTF-8 */
-          if (ucs4 <= 0x7fUL) {
-            dst[0] = ucs4;
-            dst += 1;
-          } else if (ucs4 <= 0x7ffUL) {
-            dst[0] = 0xc0 | (ucs4 >> 6);
-            dst[1] = 0x80 | (ucs4 & 0x3f);
-            dst += 2;
-          } else if (ucs4 <= 0xffffUL) {
-            dst[0] = 0xe0 | (ucs4 >> 12);
-            dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
-            dst[2] = 0x80 | (ucs4 & 0x3f);
-            dst += 3;
-          } else {
-            dst[0] = 0xf0 | (ucs4 >> 18);
-            dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
-            dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
-            dst[3] = 0x80 | (ucs4 & 0x3f);
-            dst += 4;
-          }
-        }
-      }
-      /* skip over trailing '-' in modified UTF-7 encoding */
-      if (*src == '-') ++src;
-    }
-  }
-  /* terminate destination string */
-  *dst = '\0';
-  return res;
-}
-
-/* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
- *  dst should be about twice the length of src to deal with non-hex
- *  coded URLs
- */
-static char*
-imap_utf8_to_modified_utf7(const char *src)
-{
-  unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
-  unsigned long ucs4 = 0, bitbuf = 0;
-
-  /* initialize hex lookup table */
-  char *dst, *res = malloc(2*strlen(src)+1);
-  dst = res;
-  if(!dst) return NULL;
-
-  utf7mode = 0;
-  utf8total = 0;
-  bitstogo = 0;
-  utf8pos = 0;
-  while ((c = (unsigned char)*src) != '\0') {
-    ++src;
-    /* normal character? */
-    if (c >= ' ' && c <= '~') {
-      /* switch out of UTF-7 mode */
-      if (utf7mode) {
-        if (bitstogo) {
-          *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
-        }
-        *dst++ = '-';
-        utf7mode = 0;
-        utf8pos  = 0;
-        bitstogo = 0;
-        utf8total= 0;
-      }
-      *dst++ = c;
-      /* encode '&' as '&-' */
-      if (c == '&') {
-        *dst++ = '-';
-      }
-      continue;
-    }
-    /* switch to UTF-7 mode */
-    if (!utf7mode) {
-      *dst++ = '&';
-      utf7mode = 1;
-    }
-    /* Encode US-ASCII characters as themselves */
-    if (c < 0x80) {
-      ucs4 = c;
-      utf8total = 1;
-    } else if (utf8total) {
-      /* save UTF8 bits into UCS4 */
-      ucs4 = (ucs4 << 6) | (c & 0x3FUL);
-      if (++utf8pos < utf8total) {
-        continue;
-      }
-    } else {
-      utf8pos = 1;
-      if (c < 0xE0) {
-        utf8total = 2;
-        ucs4 = c & 0x1F;
-      } else if (c < 0xF0) {
-        utf8total = 3;
-        ucs4 = c & 0x0F;
-      } else {
-        /* NOTE: can't convert UTF8 sequences longer than 4 */
-        utf8total = 4;
-        ucs4 = c & 0x03;
-      }
-      continue;
-    }
-    /* loop to split ucs4 into two utf16 chars if necessary */
-    utf8total = 0;
-    do {
-      if (ucs4 >= UTF16BASE) {
-        ucs4 -= UTF16BASE;
-        bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
-                                   + UTF16HIGHSTART);
-        ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
-        utf16flag = 1;
-      } else {
-        bitbuf = (bitbuf << 16) | ucs4;
-        utf16flag = 0;
-      }
-      bitstogo += 16;
-      /* spew out base64 */
-      while (bitstogo >= 6) {
-        bitstogo -= 6;
-        *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
-                              : bitbuf)
-                             & 0x3F];
-      }
-    } while (utf16flag);
-  }
-  /* if in UTF-7 mode, finish in ASCII */
-  if (utf7mode) {
-    if (bitstogo) {
-      *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
-    }
-    *dst++ = '-';
-  }
-  /* tie off string */
-  *dst = '\0';
-  return res;
-}
-
-static gboolean imap_rename_folder_func(GNode *node, gpointer data)
-{
-       FolderItem *item = node->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) {
-               g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
-               return TRUE;
-       }
-
-       base = item->path + oldpathlen;
-       while (*base == G_DIR_SEPARATOR) base++;
-       if (*base == '\0')
-               new_itempath = g_strdup(newpath);
-       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;
-}
-
-static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
-{
-       GSList *uidlist, *elem;
-       int r = -1;
-       clist * lep_uidlist;
-       gint ok, nummsgs = 0, lastuid_old;
-
-       if (session == NULL) {
-               return -1;
-       }
-
-       ok = imap_select(session, IMAP_FOLDER(folder), item->item.path,
-                        NULL, NULL, NULL, NULL, TRUE);
+       ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
+                        NULL, NULL, NULL, NULL, NULL, TRUE);
        if (ok != MAILIMAP_NO_ERROR) {
                return -1;
        }
@@ -3836,8 +3907,11 @@ static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderIte
                uidlist = g_slist_concat(fetchuid_list, uidlist);
        } else {
                carray * lep_uidtab;
-               if (r != -1) /* inited */
+               if (r != -1) /* inited */
                        imap_handle_error(SESSION(session), r);
+                       if (is_fatal(r))
+                               return -1;
+               }
                r = imap_threaded_fetch_uid(folder, 1,
                                    &lep_uidtab);
                if (r == MAILIMAP_NO_ERROR) {
@@ -4010,8 +4084,8 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
        lock_session(session); /* unlocked later in the function */
 
        debug_print("IMAP getting msginfos\n");
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        if (ok != MAILIMAP_NO_ERROR) {
                return NULL;
        }
@@ -4213,6 +4287,19 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
        if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
                flags_unset |= IMAP_FLAG_ANSWERED;
 
+       if (!MSG_IS_FORWARDED(msginfo->flags) &&  (newflags & MSG_FORWARDED))
+               flags_set |= IMAP_FLAG_FORWARDED;
+       if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
+               flags_unset |= IMAP_FLAG_FORWARDED;
+
+       if (!MSG_IS_SPAM(msginfo->flags) &&  (newflags & MSG_SPAM)) {
+               flags_set |= IMAP_FLAG_SPAM;
+               flags_unset |= IMAP_FLAG_HAM;
+       }
+       if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
+               flags_set |= IMAP_FLAG_HAM;
+               flags_unset |= IMAP_FLAG_SPAM;
+       }
        if (!MSG_IS_DELETED(msginfo->flags) &&  (newflags & MSG_DELETED))
                flags_set |= IMAP_FLAG_DELETED;
        if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
@@ -4231,8 +4318,8 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
                return;
        }
 
-       if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
-           NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
+       if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
+           NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
                return;
        }
        numlist.next = NULL;
@@ -4271,14 +4358,14 @@ void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPe
        } else {
                debug_print("IMAP changing flags\n");
                if (flags_set) {
-                       ok = imap_set_message_flags(session, &numlist, flags_set, TRUE);
+                       ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
                        if (ok != MAILIMAP_NO_ERROR) {
                                return;
                        }
                }
 
                if (flags_unset) {
-                       ok = imap_set_message_flags(session, &numlist, flags_unset, FALSE);
+                       ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
                        if (ok != MAILIMAP_NO_ERROR) {
                                return;
                        }
@@ -4303,8 +4390,8 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        session = imap_session_get(folder);
        if (!session) return -1;
 
-       ok = imap_select(session, IMAP_FOLDER(folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+       ok = imap_select(session, IMAP_FOLDER(folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        if (ok != MAILIMAP_NO_ERROR) {
                return ok;
        }
@@ -4312,7 +4399,7 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        numlist.data = GINT_TO_POINTER(uid);
        
        ok = imap_set_message_flags
-               (session, &numlist, IMAP_FLAG_DELETED, TRUE);
+               (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
        if (ok != MAILIMAP_NO_ERROR) {
                log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
                return ok;
@@ -4359,6 +4446,19 @@ static guint gslist_find_next_num(MsgNumberList **list, guint num)
        return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
 }
 
+static gboolean flag_ok(IMAPFolderItem *item, guint flag)
+{
+       if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
+               debug_print("flag %d is OK\n", flag);
+               return TRUE;
+       }
+       if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
+               debug_print("creating flags is OK\n");
+               return TRUE;
+       }
+       return FALSE;
+}
+
 /*
  * NEW and DELETED flags are not syncronized
  * - The NEW/RECENT flags in IMAP folders can not really be directly
@@ -4390,15 +4490,16 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
        gint ok;
        int r = MAILIMAP_NO_ERROR;
        GHashTable *flags_hash = NULL;
+       GHashTable *tags_hash = NULL;
        gboolean full_search = stuff->full_search;
        GSList *sorted_list = NULL;
-       GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL;
-       GSList *p_unseen, *p_answered, *p_flagged, *p_deleted;
+       GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
        GSList *seq_list, *cur;
        gboolean reverse_seen = FALSE;
        gboolean selected_folder;
        gint exists_cnt, unseen_cnt;
-       
+       gboolean got_alien_tags = FALSE;
+
        session = imap_session_get(folder);
 
        if (session == NULL) {
@@ -4410,8 +4511,8 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
 
        lock_session(session);
        if (!selected_folder) {
-               ok = imap_select(session, IMAP_FOLDER(folder), fitem->path,
-                       &exists_cnt, NULL, &unseen_cnt, NULL, TRUE);
+               ok = imap_select(session, IMAP_FOLDER(folder), fitem,
+                       &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
                if (ok != MAILIMAP_NO_ERROR) {
                        stuff->done = TRUE;
                        return GINT_TO_POINTER(-1);
@@ -4491,6 +4592,38 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                        goto bail;
                                }
 
+                               if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
+                                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED,
+                                                                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);
+
+                                               forwarded = g_slist_concat(forwarded, uidlist);
+                                       } else {
+                                               imap_handle_error(SESSION(session), r);
+                                               goto bail;
+                                       }
+                               }
+
+                               if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
+                                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM,
+                                                                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);
+
+                                               spam = g_slist_concat(spam, uidlist);
+                                       } else {
+                                               imap_handle_error(SESSION(session), r);
+                                               goto bail;
+                                       }
+                               }
+
                                r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
                                                         full_search ? NULL:imapset, &lep_uidlist);
                                if (r == MAILIMAP_NO_ERROR) {
@@ -4506,16 +4639,13 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                                }
                        }
                }
-               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);
+                       flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
+                       tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
+                       imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
                        imap_fetch_uid_flags_list_free(lep_uidtab);
                } else {
                        imap_handle_error(SESSION(session), r);
@@ -4535,17 +4665,17 @@ bail:
                msginfo = (MsgInfo *) elem->data;
                flags = msginfo->flags.perm_flags;
                wasnew = (flags & MSG_NEW);
-               oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_MARKED|MSG_DELETED);
+               oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
 
                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);
+                               flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
                        } 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 (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
                                if (!reverse_seen) {
                                        flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
                                } else {
@@ -4553,30 +4683,34 @@ bail:
                                }
                        }
 
-                       if (gslist_find_next_num(&p_flagged, msginfo->msgnum) == msginfo->msgnum)
+                       if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
                                flags |= MSG_MARKED;
                        else
                                flags &= ~MSG_MARKED;
 
                        if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
-                               if (gslist_find_next_num(&p_answered, msginfo->msgnum) == msginfo->msgnum)
+                               if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
                                        flags |= MSG_REPLIED;
                                else
                                        flags &= ~MSG_REPLIED;
-                               if (gslist_find_next_num(&p_deleted, msginfo->msgnum) == msginfo->msgnum)
+                               if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
+                                       flags |= MSG_FORWARDED;
+                               else
+                                       flags &= ~MSG_FORWARDED;
+                               if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
+                                       flags |= MSG_SPAM;
+                               else
+                                       flags &= ~MSG_SPAM;
+                               if (gslist_find_next_num(&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);
+                               flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, 
+                                               GINT_TO_POINTER(msginfo->msgnum)));
                        }
 
                        if ((flags & MSG_UNREAD) == 0)
@@ -4584,18 +4718,54 @@ bail:
                        else if (wasnew)
                                flags |= MSG_NEW;
                        flags |= oldflags;
+                       
+                       if (tags_hash != NULL) {
+                               GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
+                               GSList *cur;
+
+                               if (tags != NULL) {
+                                       g_slist_free(msginfo->tags);
+                                       msginfo->tags = NULL;
+                               }
+                               for (cur = tags; cur; cur = cur->next) {
+                                       gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
+                                       gint id = 0;
+                                       id = tags_get_id_for_str(real_tag);
+                                       if (id == -1) {
+                                               id = tags_add_tag(real_tag);
+                                               got_alien_tags = TRUE;
+                                       }
+                                       if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
+                                               msginfo->tags = g_slist_append(
+                                                               msginfo->tags,
+                                                               GINT_TO_POINTER(id));
+                                       }
+                                       g_free(real_tag);
+                               }
+                               slist_free_strings(tags);
+                               g_slist_free(tags);
+                       }
                }
 
                g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
        }
        
+       if (got_alien_tags) {
+               tags_write_tags();
+               main_window_reflect_tags_changes(mainwindow_get_mainwindow());
+       }
+
        if (flags_hash)
                g_hash_table_destroy(flags_hash);
+       if (tags_hash)
+               g_hash_table_destroy(tags_hash);
 
        imap_lep_set_free(seq_list);
        g_slist_free(flagged);
        g_slist_free(deleted);
        g_slist_free(answered);
+       g_slist_free(forwarded);
+       g_slist_free(spam);
        g_slist_free(unseen);
        g_slist_free(sorted_list);
 
@@ -4664,11 +4834,55 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
        
        lock_session(session);
        if (session) {
-               ok = imap_select(session, IMAP_FOLDER(item->folder), item->path,
-                        NULL, NULL, NULL, NULL, FALSE);
+               ok = imap_select(session, IMAP_FOLDER(item->folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
+       }
+       if (ok == MAILIMAP_NO_ERROR) {
+               ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
+                       data->msglist, flags_value, NULL, flags_set);
+       } else {
+               g_warning("can't select mailbox %s\n", item->path);
+       }
+
+       if (!is_fatal(ok))
+               unlock_session(session);
+
+       g_slist_free(data->msglist);    
+       g_free(data);
+       return TRUE;
+}
+
+static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
+{
+       gboolean tags_set = GPOINTER_TO_INT(user_data);
+       TagsData *data = (TagsData *)value;
+       IMAPFolderItem *_item = data->item;
+       FolderItem *item = (FolderItem *)_item;
+       gchar *str = data->str;
+       gint ok = MAILIMAP_ERROR_BAD_STATE;
+       IMAPSession *session = NULL;
+       
+       debug_print("getting session...\n");
+       session = imap_session_get(item->folder);
+
+       data->msglist = g_slist_reverse(data->msglist);
+       
+       debug_print("IMAP %ssetting tags %s for %d messages\n",
+               tags_set?"":"un",
+               str,
+               g_slist_length(data->msglist));
+       
+       lock_session(session);
+       if (session) {
+               ok = imap_select(session, IMAP_FOLDER(item->folder), item,
+                        NULL, NULL, NULL, NULL, NULL, FALSE);
        }
        if (ok == MAILIMAP_NO_ERROR) {
-               ok = imap_set_message_flags(session, data->msglist, flags_value, flags_set);
+               GSList list;
+               list.data = str;
+               list.next = NULL;
+               ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
+                       data->msglist, 0, &list, tags_set);
        } else {
                g_warning("can't select mailbox %s\n", item->path);
        }
@@ -4677,6 +4891,7 @@ static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
                unlock_session(session);
 
        g_slist_free(data->msglist);    
+       g_free(data->str);
        g_free(data);
        return TRUE;
 }
@@ -4693,6 +4908,16 @@ static void process_hashtable(IMAPFolderItem *item)
                g_hash_table_destroy(item->flags_unset_table);
                item->flags_unset_table = NULL;
        }
+       if (item->tags_set_table) {
+               g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
+               g_hash_table_destroy(item->tags_set_table);
+               item->tags_set_table = NULL;
+       }
+       if (item->tags_unset_table) {
+               g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
+               g_hash_table_destroy(item->tags_unset_table);
+               item->tags_unset_table = NULL;
+       }
        
 }
 
@@ -4715,6 +4940,12 @@ static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
                if (!item->flags_unset_table) {
                        item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
                }
+               if (!item->tags_set_table) {
+                       item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
+               }
+               if (!item->tags_unset_table) {
+                       item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
+               }
                session = imap_session_get(folder);
                if (session) {
                        imap_refresh_sensitivity(session);
@@ -4830,8 +5061,8 @@ static GSList * imap_list_from_lep(IMAPFolder * folder,
                        dup_name[strlen(dup_name)-1] = '\0';
                }
                
-               loc_name = imap_modified_utf7_to_utf8(base);
-               loc_path = imap_modified_utf7_to_utf8(dup_name);
+               loc_name = imap_modified_utf7_to_utf8(base, FALSE);
+               loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
                
                new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
                if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
@@ -4976,24 +5207,25 @@ static GSList * imap_uid_list_from_lep_tab(carray * list)
 }
 
 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
-                                                  GHashTable * hash)
+                                                  GHashTable * hash,
+                                                  GHashTable * tags_hash)
 {
        unsigned int i;
        GSList * result;
        
        result = NULL;
        
-       for(i = 0 ; i < carray_count(list) ; i += 2) {
+       for(i = 0 ; i < carray_count(list) ; i += 3) {
                uint32_t * puid;
                int * pflags;
-               gint * pguid;
+               GSList *tags;
                
                puid = carray_get(list, i);
                pflags = carray_get(list, i + 1);
-               pguid = malloc(sizeof(* pguid));
-               * pguid = * puid;
+               tags = carray_get(list, i + 2);
                
-               g_hash_table_insert(hash, pguid, GINT_TO_POINTER(* pflags));
+               g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
+               g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
        }
 }
 
@@ -5002,7 +5234,7 @@ static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
 {
        MsgInfo *msginfo = NULL;
        guint32 uid = 0;
-       size_t size = 0;
+       goffset size = 0;
        MsgFlags flags = {0, 0};
        
        if (info->headers == NULL)
@@ -5017,7 +5249,7 @@ static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
        flags.perm_flags = info->flags;
        
        uid = info->uid;
-       size = info->size;
+       size = (goffset) info->size;
        msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
        
        if (msginfo) {
@@ -5041,10 +5273,11 @@ static void imap_lep_set_free(GSList *seq_list)
        g_slist_free(seq_list);
 }
 
-static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
 {
        struct mailimap_flag_list * flag_list;
-       
+       GSList *cur = tags;
+
        flag_list = mailimap_flag_list_new_empty();
        
        if (IMAP_IS_SEEN(flags))
@@ -5062,7 +5295,25 @@ static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
        if (IMAP_IS_DRAFT(flags))
                mailimap_flag_list_add(flag_list,
                                       mailimap_flag_new_draft());
+       if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_flag_keyword(strdup("$Forwarded")));
+       if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_flag_keyword(strdup("Junk")));
+       else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_flag_keyword(strdup("NonJunk")));
        
+       for (; cur; cur = cur->next) {
+               gchar *enc_str = 
+                       imap_utf8_to_modified_utf7(cur->data, TRUE);
+               g_strstrip(enc_str);
+       
+               mailimap_flag_list_add(flag_list,
+                       mailimap_flag_new_flag_keyword(enc_str));
+       }
+
        return flag_list;
 }
 
@@ -5079,6 +5330,25 @@ void imap_folder_ref(Folder *folder)
 void imap_disconnect_all(void)
 {
        GList *list;
+       gboolean short_timeout;
+#ifdef HAVE_NETWORKMANAGER_SUPPORT
+       GError *error;
+#endif
+
+#ifdef HAVE_NETWORKMANAGER_SUPPORT
+       error = NULL;
+       short_timeout = !networkmanager_is_online(&error);
+       if(error) {
+               short_timeout = TRUE;
+               g_error_free(error);
+       }
+#else
+       short_timeout = TRUE;
+#endif
+
+       if(short_timeout)
+               imap_main_set_timeout(1);
+
        for (list = account_get_list(); list != NULL; list = list->next) {
                PrefsAccount *account = list->data;
                if (account->protocol == A_IMAP4) {
@@ -5087,11 +5357,15 @@ void imap_disconnect_all(void)
                                IMAPSession *session = (IMAPSession *)folder->session;
                                imap_threaded_disconnect(FOLDER(folder));
                                SESSION(session)->state = SESSION_DISCONNECTED;
+                               SESSION(session)->sock = NULL;
                                session_destroy(SESSION(session));
                                folder->session = NULL;
                        }
                }
        }
+
+       if(short_timeout)
+               imap_main_set_timeout(prefs_common.io_timeout_secs);
 }
 
 void imap_folder_unref(Folder *folder)
@@ -5309,3 +5583,226 @@ static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
 #endif
        return tag;
 }
+
+/* ===================================================================
+ * UTF-7 conversion routines as in RFC 2192
+ * =================================================================== 
+ * These two functions from: 
+ * libimap library.
+ * Copyright (C) 2003-2004 Pawel Salek. */
+
+/* UTF7 modified base64 alphabet */
+static char base64chars[] =
+  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
+#define UNDEFINED 64
+
+/* UTF16 definitions */
+#define UTF16MASK       0x03FFUL
+#define UTF16SHIFT      10
+#define UTF16BASE       0x10000UL
+#define UTF16HIGHSTART  0xD800UL
+#define UTF16HIGHEND    0xDBFFUL
+#define UTF16LOSTART    0xDC00UL
+#define UTF16LOEND      0xDFFFUL
+
+
+/* Convert an IMAP mailbox to a UTF-8 string.
+ *  dst needs to have roughly 4 times the storage space of src
+ *    Hex encoding can triple the size of the input
+ *    UTF-7 can be slightly denser than UTF-8
+ *     (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
+ */
+char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
+{
+  unsigned c, i, bitcount;
+  unsigned long ucs4, utf16, bitbuf;
+  unsigned char base64[256];
+  const char *src;
+  char *dst, *res  = malloc(2*strlen(mbox)+1);
+
+  bitbuf = 0;
+  dst = res;
+  src = mbox;
+  if(!dst) return NULL;
+  /* initialize modified base64 decoding table */
+  memset(base64, UNDEFINED, sizeof (base64));
+  for (i = 0; i < sizeof (base64chars); ++i) {
+    base64[(unsigned)base64chars[i]] = i;
+  }
+
+  /* loop until end of string */
+  while (*src != '\0') {
+    c = *src++;
+    /* deal with literal characters and &- */
+    if (c != '&' || *src == '-') {
+      /* encode literally */
+      if (change_spaces && c == '_')
+       *dst++ = ' ';
+      else
+        *dst++ = c;
+      /* skip over the '-' if this is an &- sequence */
+      if (c == '&') ++src;
+    } else {
+      /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
+      bitbuf = 0;
+      bitcount = 0;
+      ucs4 = 0;
+      while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
+        ++src;
+        bitbuf = (bitbuf << 6) | c;
+        bitcount += 6;
+        /* enough bits for a UTF-16 character? */
+        if (bitcount >= 16) {
+          bitcount -= 16;
+          utf16 = (bitcount ? bitbuf >> bitcount
+                   : bitbuf) & 0xffff;
+          /* convert UTF16 to UCS4 */
+          if
+            (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
+            ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
+            continue;
+          } else if
+            (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
+            ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
+          } else {
+            ucs4 = utf16;
+          }
+
+          /* convert UTF-16 range of UCS4 to UTF-8 */
+          if (ucs4 <= 0x7fUL) {
+            dst[0] = ucs4;
+            dst += 1;
+          } else if (ucs4 <= 0x7ffUL) {
+            dst[0] = 0xc0 | (ucs4 >> 6);
+            dst[1] = 0x80 | (ucs4 & 0x3f);
+            dst += 2;
+          } else if (ucs4 <= 0xffffUL) {
+            dst[0] = 0xe0 | (ucs4 >> 12);
+            dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
+            dst[2] = 0x80 | (ucs4 & 0x3f);
+            dst += 3;
+          } else {
+            dst[0] = 0xf0 | (ucs4 >> 18);
+            dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
+            dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
+            dst[3] = 0x80 | (ucs4 & 0x3f);
+            dst += 4;
+          }
+        }
+      }
+      /* skip over trailing '-' in modified UTF-7 encoding */
+      if (*src == '-') ++src;
+    }
+  }
+  /* terminate destination string */
+  *dst = '\0';
+  return res;
+}
+
+/* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
+ *  dst should be about twice the length of src to deal with non-hex
+ *  coded URLs
+ */
+char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
+{
+  unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
+  unsigned long ucs4 = 0, bitbuf = 0;
+
+  /* initialize hex lookup table */
+  char *dst, *res = malloc(2*strlen(src)+1);
+  dst = res;
+  if(!dst) return NULL;
+
+  utf7mode = 0;
+  utf8total = 0;
+  bitstogo = 0;
+  utf8pos = 0;
+  while ((c = (unsigned char)*src) != '\0') {
+    ++src;
+    /* normal character? */
+    if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
+      /* switch out of UTF-7 mode */
+      if (utf7mode) {
+        if (bitstogo) {
+          *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
+        }
+        *dst++ = '-';
+        utf7mode = 0;
+        utf8pos  = 0;
+        bitstogo = 0;
+        utf8total= 0;
+      }
+      if (change_spaces && c == ' ')
+        *dst++ = '_';
+      else
+       *dst++ = c;
+      /* encode '&' as '&-' */
+      if (c == '&') {
+        *dst++ = '-';
+      }
+      continue;
+    }
+    /* switch to UTF-7 mode */
+    if (!utf7mode) {
+      *dst++ = '&';
+      utf7mode = 1;
+    }
+    /* Encode US-ASCII characters as themselves */
+    if (c < 0x80) {
+      ucs4 = c;
+      utf8total = 1;
+    } else if (utf8total) {
+      /* save UTF8 bits into UCS4 */
+      ucs4 = (ucs4 << 6) | (c & 0x3FUL);
+      if (++utf8pos < utf8total) {
+        continue;
+      }
+    } else {
+      utf8pos = 1;
+      if (c < 0xE0) {
+        utf8total = 2;
+        ucs4 = c & 0x1F;
+      } else if (c < 0xF0) {
+        utf8total = 3;
+        ucs4 = c & 0x0F;
+      } else {
+        /* NOTE: can't convert UTF8 sequences longer than 4 */
+        utf8total = 4;
+        ucs4 = c & 0x03;
+      }
+      continue;
+    }
+    /* loop to split ucs4 into two utf16 chars if necessary */
+    utf8total = 0;
+    do {
+      if (ucs4 >= UTF16BASE) {
+        ucs4 -= UTF16BASE;
+        bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
+                                   + UTF16HIGHSTART);
+        ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
+        utf16flag = 1;
+      } else {
+        bitbuf = (bitbuf << 16) | ucs4;
+        utf16flag = 0;
+      }
+      bitstogo += 16;
+      /* spew out base64 */
+      while (bitstogo >= 6) {
+        bitstogo -= 6;
+        *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
+                              : bitbuf)
+                             & 0x3F];
+      }
+    } while (utf16flag);
+  }
+  /* if in UTF-7 mode, finish in ASCII */
+  if (utf7mode) {
+    if (bitstogo) {
+      *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
+    }
+    *dst++ = '-';
+  }
+  /* tie off string */
+  *dst = '\0';
+  return res;
+}