2008-09-22 [colin] 3.5.0cvs122
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include "imap.h"
31 #include "imap_gtk.h"
32 #include "inc.h"
33 #include "xml.h"
34 #include "alertpanel.h"
35
36 #ifdef HAVE_LIBETPAN
37
38 #include <stdlib.h>
39 #include <dirent.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <errno.h>
44 #if HAVE_ICONV
45 #  include <iconv.h>
46 #endif
47
48 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
49 #  include "ssl.h"
50 #endif
51
52 #include "folder.h"
53 #include "session.h"
54 #include "procmsg.h"
55 #include "socket.h"
56 #include "recv.h"
57 #include "procheader.h"
58 #include "prefs_account.h"
59 #include "codeconv.h"
60 #include "md5.h"
61 #include "base64.h"
62 #include "utils.h"
63 #include "prefs_common.h"
64 #include "inputdialog.h"
65 #include "log.h"
66 #include "remotefolder.h"
67 #include "claws.h"
68 #include "statusbar.h"
69 #include "msgcache.h"
70 #include "imap-thread.h"
71 #include "account.h"
72 #include "tags.h"
73 #include "main.h"
74
75 typedef struct _IMAPFolder      IMAPFolder;
76 typedef struct _IMAPSession     IMAPSession;
77 typedef struct _IMAPNameSpace   IMAPNameSpace;
78 typedef struct _IMAPFolderItem  IMAPFolderItem;
79
80 #include "prefs_account.h"
81
82 #define IMAP_FOLDER(obj)        ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj)   ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj)       ((IMAPSession *)obj)
85
86 struct _IMAPFolder
87 {
88         RemoteFolder rfolder;
89
90         /* list of IMAPNameSpace */
91         GList *ns_personal;
92         GList *ns_others;
93         GList *ns_shared;
94         gchar last_seen_separator;
95         guint refcnt;
96         guint max_set_size;
97 };
98
99 struct _IMAPSession
100 {
101         Session session;
102
103         gboolean authenticated;
104
105         GSList *capability;
106         gboolean uidplus;
107
108         gchar *mbox;
109         guint cmd_count;
110
111         /* CLAWS */
112         gboolean folder_content_changed;
113         guint exists;
114         guint recent;
115         guint expunge;
116         guint unseen;
117         guint uid_validity;
118         guint uid_next;
119
120         Folder * folder;
121         gboolean busy;
122         gboolean cancelled;
123         gboolean sens_update_block;
124 };
125
126 struct _IMAPNameSpace
127 {
128         gchar *name;
129         gchar separator;
130 };
131
132 #define IMAPBUFSIZE     8192
133
134 #define IMAP_IS_SEEN(flags)     ((flags & IMAP_FLAG_SEEN) != 0)
135 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
136 #define IMAP_IS_FLAGGED(flags)  ((flags & IMAP_FLAG_FLAGGED) != 0)
137 #define IMAP_IS_DELETED(flags)  ((flags & IMAP_FLAG_DELETED) != 0)
138 #define IMAP_IS_DRAFT(flags)    ((flags & IMAP_FLAG_DRAFT) != 0)
139 #define IMAP_IS_FORWARDED(flags)        ((flags & IMAP_FLAG_FORWARDED) != 0)
140 #define IMAP_IS_SPAM(flags)     ((flags & IMAP_FLAG_SPAM) != 0)
141 #define IMAP_IS_HAM(flags)      ((flags & IMAP_FLAG_HAM) != 0)
142
143
144 #define IMAP4_PORT      143
145 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
146 #define IMAPS_PORT      993
147 #endif
148
149 #define IMAP_CMD_LIMIT  1000
150
151 enum {
152         ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
153         ITEM_CAN_CREATE_FLAGS,
154         ITEM_CANNOT_CREATE_FLAGS
155 };
156
157 struct _IMAPFolderItem
158 {
159         FolderItem item;
160
161         guint lastuid;
162         guint uid_next;
163         GSList *uid_list;
164         gboolean batching;
165
166         GHashTable *flags_set_table;
167         GHashTable *flags_unset_table;
168         guint32 last_change;
169         guint32 last_sync;
170         gboolean should_update;
171         gboolean should_trash_cache;
172         gint can_create_flags;
173
174         GHashTable *tags_set_table;
175         GHashTable *tags_unset_table;
176         GSList *ok_flags;
177
178 };
179
180 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
181 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
182
183 static void imap_folder_init            (Folder         *folder,
184                                          const gchar    *name,
185                                          const gchar    *path);
186
187 static Folder   *imap_folder_new        (const gchar    *name,
188                                          const gchar    *path);
189 static void      imap_folder_destroy    (Folder         *folder);
190
191 static IMAPSession *imap_session_new    (Folder         *folder,
192                                          const PrefsAccount     *account);
193 static gint     imap_session_authenticate(IMAPSession   *session,
194                                           PrefsAccount  *account);
195 static void     imap_session_destroy    (Session        *session);
196
197 static gchar   *imap_fetch_msg          (Folder         *folder, 
198                                          FolderItem     *item, 
199                                          gint            uid);
200 static gchar   *imap_fetch_msg_full     (Folder         *folder, 
201                                          FolderItem     *item, 
202                                          gint            uid,
203                                          gboolean        headers,
204                                          gboolean        body);
205 static void     imap_remove_cached_msg  (Folder         *folder, 
206                                          FolderItem     *item, 
207                                          MsgInfo        *msginfo);
208 static gint     imap_add_msg            (Folder         *folder,
209                                          FolderItem     *dest,
210                                          const gchar    *file, 
211                                          MsgFlags       *flags);
212 static gint     imap_add_msgs           (Folder         *folder, 
213                                          FolderItem     *dest,
214                                          GSList         *file_list,
215                                          GRelation      *relation);
216
217 static gint     imap_copy_msg           (Folder         *folder,
218                                          FolderItem     *dest, 
219                                          MsgInfo        *msginfo);
220 static gint     imap_copy_msgs          (Folder         *folder, 
221                                          FolderItem     *dest, 
222                                          MsgInfoList    *msglist, 
223                                          GRelation      *relation);
224
225 static gint     imap_remove_msg         (Folder         *folder, 
226                                          FolderItem     *item, 
227                                          gint            uid);
228 static gint     imap_remove_msgs        (Folder         *folder, 
229                                          FolderItem     *dest, 
230                                          MsgInfoList    *msglist, 
231                                          GRelation      *relation);
232 static gint     imap_remove_all_msg     (Folder         *folder, 
233                                          FolderItem     *item);
234
235 static gboolean imap_is_msg_changed     (Folder         *folder,
236                                          FolderItem     *item, 
237                                          MsgInfo        *msginfo);
238
239 static gint     imap_close              (Folder         *folder, 
240                                          FolderItem     *item);
241
242 static gint     imap_scan_tree          (Folder         *folder);
243
244 static gint     imap_create_tree        (Folder         *folder);
245
246 static FolderItem *imap_create_folder   (Folder         *folder,
247                                          FolderItem     *parent,
248                                          const gchar    *name);
249 static gint     imap_rename_folder      (Folder         *folder,
250                                          FolderItem     *item, 
251                                          const gchar    *name);
252 static gint     imap_remove_folder      (Folder         *folder, 
253                                          FolderItem     *item);
254
255 static FolderItem *imap_folder_item_new (Folder         *folder);
256 static void imap_folder_item_destroy    (Folder         *folder,
257                                          FolderItem     *item);
258
259 static IMAPSession *imap_session_get    (Folder         *folder);
260
261 static gint imap_auth                   (IMAPSession    *session,
262                                          const gchar    *user,
263                                          const gchar    *pass,
264                                          IMAPAuthType    type);
265
266 static gint imap_scan_tree_recursive    (IMAPSession    *session,
267                                          FolderItem     *item,
268                                          gboolean        subs_only);
269
270 static void imap_create_missing_folders (Folder         *folder);
271 static FolderItem *imap_create_special_folder
272                                         (Folder                 *folder,
273                                          SpecialFolderItemType   stype,
274                                          const gchar            *name);
275
276 static gint imap_do_copy_msgs           (Folder         *folder,
277                                          FolderItem     *dest,
278                                          MsgInfoList    *msglist,
279                                          GRelation      *relation);
280
281 static void imap_delete_all_cached_messages     (FolderItem     *item);
282 static void imap_set_batch              (Folder         *folder,
283                                          FolderItem     *item,
284                                          gboolean        batch);
285 static gint imap_set_message_flags      (IMAPSession    *session,
286                                          IMAPFolderItem *item,
287                                          MsgNumberList  *numlist,
288                                          IMAPFlags       flags,
289                                          GSList         *tags,
290                                          gboolean        is_set);
291 static gint imap_select                 (IMAPSession    *session,
292                                          IMAPFolder     *folder,
293                                          FolderItem     *item,
294                                          gint           *exists,
295                                          gint           *recent,
296                                          gint           *unseen,
297                                          guint32        *uid_validity,
298                                          gint           *can_create_flags,
299                                          gboolean        block);
300 static gint imap_status                 (IMAPSession    *session,
301                                          IMAPFolder     *folder,
302                                          const gchar    *path,
303                                          IMAPFolderItem *item,
304                                          gint           *messages,
305                                          guint32        *uid_next,
306                                          guint32        *uid_validity,
307                                          gint           *unseen,
308                                          gboolean        block);
309 static void     imap_commit_tags        (FolderItem     *item, 
310                                          MsgInfo        *msginfo,
311                                          GSList         *set_tags,
312                                          GSList         *unset_tags);
313
314 static gchar imap_get_path_separator            (IMAPSession    *session,
315                                                  IMAPFolder     *folder,
316                                                  const gchar    *path,
317                                                  gint           *ok);
318 static gchar *imap_get_real_path                (IMAPSession    *session,
319                                                  IMAPFolder     *folder,
320                                                  const gchar    *path,
321                                                  gint           *ok);
322 #ifdef HAVE_LIBETPAN
323 static void imap_synchronise            (FolderItem     *item, gint days);
324 #endif
325 static gboolean imap_is_busy            (Folder *folder);
326
327 static void imap_free_capabilities      (IMAPSession    *session);
328
329 /* low-level IMAP4rev1 commands */
330 static gint imap_cmd_login      (IMAPSession    *session,
331                                  const gchar    *user,
332                                  const gchar    *pass,
333                                  const gchar    *type);
334 static gint imap_cmd_noop       (IMAPSession    *session);
335 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
336 static gint imap_cmd_starttls   (IMAPSession    *session);
337 #endif
338 static gint imap_cmd_select     (IMAPSession    *session,
339                                  const gchar    *folder,
340                                  gint           *exists,
341                                  gint           *recent,
342                                  gint           *unseen,
343                                  guint32        *uid_validity,
344                                  gint           *can_create_flags,
345                                  GSList         **ok_flags,
346                                  gboolean        block);
347 static gint imap_cmd_close      (IMAPSession    *session);
348 static gint imap_cmd_examine    (IMAPSession    *session,
349                                  const gchar    *folder,
350                                  gint           *exists,
351                                  gint           *recent,
352                                  gint           *unseen,
353                                  guint32        *uid_validity,
354                                  gboolean        block);
355 static gint imap_cmd_create     (IMAPSession    *sock,
356                                  const gchar    *folder);
357 static gint imap_cmd_rename     (IMAPSession    *sock,
358                                  const gchar    *oldfolder,
359                                  const gchar    *newfolder);
360 static gint imap_cmd_delete     (IMAPSession    *session,
361                                  const gchar    *folder);
362 static gint imap_cmd_fetch      (IMAPSession    *sock,
363                                  guint32         uid,
364                                  const gchar    *filename,
365                                  gboolean        headers,
366                                  gboolean        body);
367 static gint imap_cmd_append     (IMAPSession    *session,
368                                  IMAPFolderItem *item,
369                                  const gchar    *destfolder,
370                                  const gchar    *file,
371                                  IMAPFlags       flags,
372                                  guint32        *new_uid);
373 static gint imap_cmd_copy       (IMAPSession *session,
374                                  struct mailimap_set * set,
375                                  const gchar *destfolder,
376                                  GRelation *uid_mapping,
377                                  struct mailimap_set ** source,
378                                  struct mailimap_set ** dest);
379 static gint imap_cmd_store      (IMAPSession    *session,
380                                  IMAPFolderItem *item,
381                                  struct mailimap_set * set,
382                                  IMAPFlags flags,
383                                  GSList *tags,
384                                  int do_add);
385 static gint imap_cmd_expunge    (IMAPSession    *session);
386
387 static void imap_path_separator_subst           (gchar          *str,
388                                                  gchar           separator);
389
390 static gboolean imap_rename_folder_func         (GNode          *node,
391                                                  gpointer        data);
392 static gint imap_get_num_list                   (Folder         *folder,
393                                                  FolderItem     *item,
394                                                  GSList        **list,
395                                                  gboolean       *old_uids_valid);
396 static GSList *imap_get_msginfos                (Folder         *folder,
397                                                  FolderItem     *item,
398                                                  GSList         *msgnum_list);
399 static MsgInfo *imap_get_msginfo                (Folder         *folder,
400                                                  FolderItem     *item,
401                                                  gint            num);
402 static gboolean imap_scan_required              (Folder         *folder,
403                                                  FolderItem     *item);
404 static void imap_change_flags                   (Folder         *folder,
405                                                  FolderItem     *item,
406                                                  MsgInfo        *msginfo,
407                                                  MsgPermFlags    newflags);
408 static gint imap_get_flags                      (Folder         *folder,
409                                                  FolderItem     *item,
410                                                  MsgInfoList    *msglist,
411                                                  GRelation      *msgflags);
412 static gchar *imap_folder_get_path              (Folder         *folder);
413 static gchar *imap_item_get_path                (Folder         *folder,
414                                                  FolderItem     *item);
415 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
416
417
418 /* data types conversion libetpan <-> claws */
419 static GSList * imap_list_from_lep(IMAPFolder * folder,
420                                    clist * list, const gchar * real_path, gboolean all);
421 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
422 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
423 static GSList * imap_uid_list_from_lep(clist * list);
424 static GSList * imap_uid_list_from_lep_tab(carray * list);
425 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
426                                                    GHashTable * hash,
427                                                    GHashTable *tags_hash);
428 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
429                                        FolderItem *item);
430 static void imap_lep_set_free(GSList *seq_list);
431 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
432
433 typedef struct _hashtable_data {
434         GSList *msglist;
435         IMAPFolderItem *item;
436 } hashtable_data;
437
438 static FolderClass imap_class;
439
440 FolderClass *imap_get_class(void)
441 {
442         if (imap_class.idstr == NULL) {
443                 imap_class.type = F_IMAP;
444                 imap_class.idstr = "imap";
445                 imap_class.uistr = "IMAP4";
446
447                 /* Folder functions */
448                 imap_class.new_folder = imap_folder_new;
449                 imap_class.destroy_folder = imap_folder_destroy;
450                 imap_class.scan_tree = imap_scan_tree;
451                 imap_class.create_tree = imap_create_tree;
452
453                 /* FolderItem functions */
454                 imap_class.item_new = imap_folder_item_new;
455                 imap_class.item_destroy = imap_folder_item_destroy;
456                 imap_class.item_get_path = imap_item_get_path;
457                 imap_class.create_folder = imap_create_folder;
458                 imap_class.rename_folder = imap_rename_folder;
459                 imap_class.remove_folder = imap_remove_folder;
460                 imap_class.close = imap_close;
461                 imap_class.get_num_list = imap_get_num_list;
462                 imap_class.scan_required = imap_scan_required;
463                 imap_class.set_xml = folder_set_xml;
464                 imap_class.get_xml = folder_get_xml;
465                 imap_class.item_set_xml = imap_item_set_xml;
466                 imap_class.item_get_xml = imap_item_get_xml;
467
468                 /* Message functions */
469                 imap_class.get_msginfo = imap_get_msginfo;
470                 imap_class.get_msginfos = imap_get_msginfos;
471                 imap_class.fetch_msg = imap_fetch_msg;
472                 imap_class.fetch_msg_full = imap_fetch_msg_full;
473                 imap_class.add_msg = imap_add_msg;
474                 imap_class.add_msgs = imap_add_msgs;
475                 imap_class.copy_msg = imap_copy_msg;
476                 imap_class.copy_msgs = imap_copy_msgs;
477                 imap_class.remove_msg = imap_remove_msg;
478                 imap_class.remove_msgs = imap_remove_msgs;
479                 imap_class.remove_all_msg = imap_remove_all_msg;
480                 imap_class.is_msg_changed = imap_is_msg_changed;
481                 imap_class.change_flags = imap_change_flags;
482                 imap_class.get_flags = imap_get_flags;
483                 imap_class.set_batch = imap_set_batch;
484                 imap_class.synchronise = imap_synchronise;
485                 imap_class.remove_cached_msg = imap_remove_cached_msg;
486                 imap_class.commit_tags = imap_commit_tags;
487 #ifdef USE_PTREAD
488                 pthread_mutex_init(&imap_mutex, NULL);
489 #endif
490         }
491         
492         return &imap_class;
493 }
494
495 static void imap_refresh_sensitivity (IMAPSession *session)
496 {
497         MainWindow *mainwin;
498
499         if (session->sens_update_block)
500                 return;
501         mainwin = mainwindow_get_mainwindow();
502         if (mainwin) {
503                 toolbar_main_set_sensitive(mainwin);
504                 main_window_set_menu_sensitive(mainwin);
505         }
506 }
507
508 static void lock_session(IMAPSession *session)
509 {
510         if (session) {
511                 debug_print("locking session %p (%d)\n", session, session->busy);
512                 if (session->busy)
513                         debug_print("         SESSION WAS LOCKED !!      \n");
514                 session->busy = TRUE;
515                 imap_refresh_sensitivity(session);
516         } else {
517                 debug_print("can't lock null session\n");
518         }
519 }
520
521 static void unlock_session(IMAPSession *session)
522 {
523         if (session) {
524                 debug_print("unlocking session %p\n", session);
525                 session->busy = FALSE;
526                 imap_refresh_sensitivity(session);
527         } else {
528                 debug_print("can't unlock null session\n");
529         }
530 }
531
532 static void imap_disc_session_destroy(IMAPSession *session)
533 {
534         RemoteFolder *rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
535         
536         if (!rfolder)
537                 return;
538         if (!session)
539                 return;
540         log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
541         SESSION(session)->state = SESSION_DISCONNECTED;
542         SESSION(session)->sock = NULL;
543 }
544
545 static gboolean is_fatal(int libetpan_errcode)
546 {
547         switch(libetpan_errcode) {
548         case MAILIMAP_ERROR_STREAM:
549         case MAILIMAP_ERROR_PROTOCOL:
550         case MAILIMAP_ERROR_PARSE:
551         case MAILIMAP_ERROR_BAD_STATE:
552                 return TRUE;
553         default:
554                 return FALSE;
555         }
556 }
557
558 static void imap_handle_error(Session *session, int libetpan_errcode)
559 {
560         switch(libetpan_errcode) {
561         case MAILIMAP_NO_ERROR:
562                 return;
563         case MAILIMAP_NO_ERROR_AUTHENTICATED:
564                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: authenticated\n"), session->server);
565                 break;
566         case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
567                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: not authenticated\n"), session->server);
568                 break;
569         case MAILIMAP_ERROR_BAD_STATE:
570                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: bad state\n"), session->server);
571                 break;
572         case MAILIMAP_ERROR_STREAM:
573                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: stream error\n"), session->server);
574                 break;
575         case MAILIMAP_ERROR_PARSE:
576                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: parse error "
577                                             "(very probably non-RFC compliance from the server)\n"), session->server);
578                 break;
579         case MAILIMAP_ERROR_CONNECTION_REFUSED:
580                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection refused\n"), session->server);
581                 break;
582         case MAILIMAP_ERROR_MEMORY:
583                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: memory error\n"), session->server);
584                 break;
585         case MAILIMAP_ERROR_FATAL:
586                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: fatal error\n"), session->server);
587                 break;
588         case MAILIMAP_ERROR_PROTOCOL:
589                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: protocol error"
590                                             "(very probably non-RFC compliance from the server)\n"), session->server);
591                 break;
592         case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
593                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection not accepted\n"), session->server);
594                 break;
595         case MAILIMAP_ERROR_APPEND:
596                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: APPEND error\n"), session->server);
597                 break;
598         case MAILIMAP_ERROR_NOOP:
599                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: NOOP error\n"), session->server);
600                 break;
601         case MAILIMAP_ERROR_LOGOUT:
602                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGOUT error\n"), session->server);
603                 break;
604         case MAILIMAP_ERROR_CAPABILITY:
605                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CAPABILITY error\n"), session->server);
606                 break;
607         case MAILIMAP_ERROR_CHECK:
608                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CHECK error\n"), session->server);
609                 break;
610         case MAILIMAP_ERROR_CLOSE:
611                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CLOSE error\n"), session->server);
612                 break;
613         case MAILIMAP_ERROR_EXPUNGE:
614                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXPUNGE error\n"), session->server);
615                 break;
616         case MAILIMAP_ERROR_COPY:
617                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: COPY error\n"), session->server);
618                 break;
619         case MAILIMAP_ERROR_UID_COPY:
620                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID COPY error\n"), session->server);
621                 break;
622         case MAILIMAP_ERROR_CREATE:
623                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CREATE error\n"), session->server);
624                 break;
625         case MAILIMAP_ERROR_DELETE:
626                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: DELETE error\n"), session->server);
627                 break;
628         case MAILIMAP_ERROR_EXAMINE:
629                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXAMINE error\n"), session->server);
630                 break;
631         case MAILIMAP_ERROR_FETCH:
632                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: FETCH error\n"), session->server);
633                 break;
634         case MAILIMAP_ERROR_UID_FETCH:
635                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID FETCH error\n"), session->server);
636                 break;
637         case MAILIMAP_ERROR_LIST:
638                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LIST error\n"), session->server);
639                 break;
640         case MAILIMAP_ERROR_LOGIN:
641                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGIN error\n"), session->server);
642                 break;
643         case MAILIMAP_ERROR_LSUB:
644                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LSUB error\n"), session->server);
645                 break;
646         case MAILIMAP_ERROR_RENAME:
647                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: RENAME error\n"), session->server);
648                 break;
649         case MAILIMAP_ERROR_SEARCH:
650                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SEARCH error\n"), session->server);
651                 break;
652         case MAILIMAP_ERROR_UID_SEARCH:
653                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID SEARCH error\n"), session->server);
654                 break;
655         case MAILIMAP_ERROR_SELECT:
656                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SELECT error\n"), session->server);
657                 break;
658         case MAILIMAP_ERROR_STATUS:
659                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STATUS error\n"), session->server);
660                 break;
661         case MAILIMAP_ERROR_STORE:
662                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STORE error\n"), session->server);
663                 break;
664         case MAILIMAP_ERROR_UID_STORE:
665                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID STORE error\n"), session->server);
666                 break;
667         case MAILIMAP_ERROR_SUBSCRIBE:
668                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SUBSCRIBE error\n"), session->server);
669                 break;
670         case MAILIMAP_ERROR_UNSUBSCRIBE:
671                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UNSUBSCRIBE error\n"), session->server);
672                 break;
673         case MAILIMAP_ERROR_STARTTLS:
674                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STARTTLS error\n"), session->server);
675                 break;
676         case MAILIMAP_ERROR_INVAL:
677                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: INVAL error\n"), session->server);
678                 break;
679         case MAILIMAP_ERROR_EXTENSION:
680                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXTENSION error\n"), session->server);
681                 break;
682         case MAILIMAP_ERROR_SASL:
683                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SASL error\n"), session->server);
684                 break;
685 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
686         case MAILIMAP_ERROR_SSL:
687                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SSL error\n"), session->server);
688                 break;
689 #endif
690         default:
691                 log_warning(LOG_PROTOCOL, _("IMAP error on %s: Unknown error [%d]\n"),
692                         session->server, libetpan_errcode);
693                 break;
694         }
695
696         if (session && is_fatal(libetpan_errcode)) {
697                 imap_disc_session_destroy(IMAP_SESSION(session));
698         } else if (session && !is_fatal(libetpan_errcode)) {
699                 if (IMAP_SESSION(session)->busy)
700                         unlock_session(IMAP_SESSION(session));
701         }
702 }
703
704 static Folder *imap_folder_new(const gchar *name, const gchar *path)
705 {
706         Folder *folder;
707
708         folder = (Folder *)g_new0(IMAPFolder, 1);
709         folder->klass = &imap_class;
710         imap_folder_init(folder, name, path);
711
712         return folder;
713 }
714
715 static void imap_folder_destroy(Folder *folder)
716 {
717         while (imap_folder_get_refcnt(folder) > 0)
718                 gtk_main_iteration();
719         
720         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
721         imap_done(folder);
722 }
723
724 static void imap_folder_init(Folder *folder, const gchar *name,
725                              const gchar *path)
726 {
727         folder_remote_folder_init((Folder *)folder, name, path);
728         IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
729 }
730
731 static FolderItem *imap_folder_item_new(Folder *folder)
732 {
733         IMAPFolderItem *item;
734         
735         item = g_new0(IMAPFolderItem, 1);
736         item->lastuid = 0;
737         item->uid_next = 0;
738         item->uid_list = NULL;
739
740         return (FolderItem *)item;
741 }
742
743 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
744 {
745         IMAPFolderItem *item = (IMAPFolderItem *)_item;
746
747         g_return_if_fail(item != NULL);
748         g_slist_free(item->uid_list);
749
750         g_free(_item);
751 }
752
753 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
754 {
755         IMAPFolderItem *item = (IMAPFolderItem *)node->data;
756         
757         item->lastuid = 0;
758         g_slist_free(item->uid_list);
759         item->uid_list = NULL;
760         
761         return FALSE;
762 }
763
764 static void imap_reset_uid_lists(Folder *folder)
765 {
766         if(folder->node == NULL)
767                 return;
768         
769         /* Destroy all uid lists and rest last uid */
770         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
771 }
772
773 static int imap_get_capabilities(IMAPSession *session)
774 {
775         struct mailimap_capability_data *capabilities = NULL;
776         clistiter *cur;
777         int result = -1;
778
779         if (session->capability != NULL)
780                 return MAILIMAP_NO_ERROR;
781
782         capabilities = imap_threaded_capability(session->folder, &result);
783
784         if (result != MAILIMAP_NO_ERROR) {
785                 return result;
786         }
787
788         if (capabilities == NULL) {
789                 return MAILIMAP_NO_ERROR;
790         }
791
792         for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
793             cur = clist_next(cur)) {
794                 struct mailimap_capability * cap = 
795                         clist_content(cur);
796                 if (!cap || cap->cap_data.cap_name == NULL)
797                         continue;
798                 session->capability = g_slist_append
799                                 (session->capability,
800                                  g_strdup(cap->cap_data.cap_name));
801                 debug_print("got capa %s\n", cap->cap_data.cap_name);
802         }
803         mailimap_capability_data_free(capabilities);
804         return MAILIMAP_NO_ERROR;
805 }
806
807 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
808 {
809         GSList *cur;
810         for (cur = session->capability; cur; cur = cur->next) {
811                 if (!g_ascii_strcasecmp(cur->data, cap))
812                         return TRUE;
813         }
814         return FALSE;
815 }
816
817 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
818                       IMAPAuthType type)
819 {
820         gint ok = MAILIMAP_ERROR_LOGIN;
821         static time_t last_login_err = 0;
822         gchar *ext_info = "";
823         int r;
824         gchar *server = NULL;
825         if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
826                 imap_handle_error(SESSION(session), r);
827                 return r;
828         }
829         server = g_strdup(SESSION(session)->server);
830         switch(type) {
831         case IMAP_AUTH_ANON:
832                 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
833                 break;
834         case IMAP_AUTH_CRAM_MD5:
835                 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
836                 break;
837         case IMAP_AUTH_DIGEST_MD5:
838                 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
839                 break;
840         case IMAP_AUTH_LOGIN:
841                 ok = imap_cmd_login(session, user, pass, "LOGIN");
842                 break;
843         case IMAP_AUTH_GSSAPI:
844                 ok = imap_cmd_login(session, user, pass, "GSSAPI");
845                 break;
846         default:
847                 debug_print("capabilities:\n"
848                                 "\t ANONYMOUS %d\n"
849                                 "\t CRAM-MD5 %d\n"
850                                 "\t DIGEST-MD5 %d\n"
851                                 "\t LOGIN %d\n"
852                                 "\t GSSAPI %d\n", 
853                         imap_has_capability(session, "ANONYMOUS"),
854                         imap_has_capability(session, "CRAM-MD5"),
855                         imap_has_capability(session, "DIGEST-MD5"),
856                         imap_has_capability(session, "LOGIN"),
857                         imap_has_capability(session, "GSSAPI"));
858                 if (imap_has_capability(session, "CRAM-MD5"))
859                         ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
860                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
861                         ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
862                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
863                         ok = imap_cmd_login(session, user, pass, "GSSAPI");
864                 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
865                         ok = imap_cmd_login(session, user, pass, "LOGIN");
866         }
867
868         if (ok == MAILIMAP_NO_ERROR)
869                 session->authenticated = TRUE;
870         else {
871                 if (type == IMAP_AUTH_CRAM_MD5) {
872                         ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
873                                      "compiled with SASL support and the "
874                                      "CRAM-MD5 SASL plugin is installed.");
875                 } 
876
877                 if (type == IMAP_AUTH_DIGEST_MD5) {
878                         ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
879                                      "compiled with SASL support and the "
880                                      "DIGEST-MD5 SASL plugin is installed.");
881                 } 
882
883                 if (time(NULL) - last_login_err > 10) {
884                         if (!prefs_common.no_recv_err_panel) {
885                                 alertpanel_error_log(_("Connection to %s failed: "
886                                         "login refused.%s"),
887                                         server, ext_info);
888                         } else {
889                                 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
890                                         "login refused.%s\n"),
891                                         server, ext_info);
892                         }
893                 }
894                 last_login_err = time(NULL);
895         }
896         g_free(server);
897         return ok;
898 }
899
900 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
901 {
902         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
903         /* Check if this is the first try to establish a
904            connection, if yes we don't try to reconnect */
905         debug_print("reconnecting\n");
906         if (rfolder->session == NULL) {
907                 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
908                             folder->account->recv_server);
909                 SESSION(session)->sock = NULL;
910                 session_destroy(SESSION(session));
911                 session = NULL;
912         } else {
913                 rfolder->session = NULL;
914                 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
915                             " disconnected. Reconnecting...\n"),
916                             folder->account->recv_server);
917                 statusbar_print_all(_("IMAP4 connection to %s has been"
918                             " disconnected. Reconnecting...\n"),
919                             folder->account->recv_server);
920                 SESSION(session)->state = SESSION_DISCONNECTED;
921                 SESSION(session)->sock = NULL;
922                 session_destroy(SESSION(session));
923                 /* Clear folders session to make imap_session_get create
924                    a new session, because of rfolder->session == NULL
925                    it will not try to reconnect again and so avoid an
926                    endless loop */
927                 debug_print("getting session...\n");
928                 session = imap_session_get(folder);
929                 rfolder->session = SESSION(session);
930                 statusbar_pop_all();
931         }
932         return session;
933 }
934
935 static IMAPSession *imap_session_get(Folder *folder)
936 {
937         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
938         IMAPSession *session = NULL;
939         gint r = MAILIMAP_NO_ERROR;
940
941         g_return_val_if_fail(folder != NULL, NULL);
942         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
943         g_return_val_if_fail(folder->account != NULL, NULL);
944         
945         if (prefs_common.work_offline && 
946             !inc_offline_should_override(FALSE,
947                 _("Claws Mail needs network access in order "
948                   "to access the IMAP server."))) {
949                 return NULL;
950         }
951
952         /* Make sure we have a session */
953         if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
954                 session = IMAP_SESSION(rfolder->session);
955         } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
956                 session_destroy(SESSION(rfolder->session));
957                 rfolder->session = NULL;
958                 goto new_conn;
959         } else if (rfolder->connecting) {
960                 debug_print("already connecting\n");
961                 return NULL;
962         } else {
963 new_conn:
964                 imap_reset_uid_lists(folder);
965                 if (time(NULL) - rfolder->last_failure <= 2)
966                         return NULL;
967                 rfolder->connecting = TRUE;
968                 session = imap_session_new(folder, folder->account);
969         }
970         if(session == NULL) {
971                 rfolder->last_failure = time(NULL);
972                 rfolder->connecting = FALSE;
973                 return NULL;
974         }
975
976         /* Make sure session is authenticated */
977         if (!IMAP_SESSION(session)->authenticated)
978                 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
979         
980         if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
981                 rfolder->session = NULL;
982                 if (!is_fatal(r)) {
983                         imap_threaded_disconnect(session->folder);
984                         SESSION(session)->state = SESSION_DISCONNECTED;
985                         SESSION(session)->sock = NULL;
986                         session_destroy(SESSION(session));
987                 }
988                 rfolder->last_failure = time(NULL);
989                 rfolder->connecting = FALSE;
990                 return NULL;
991         }
992
993         /* I think the point of this code is to avoid sending a
994          * keepalive if we've used the session recently and therefore
995          * think it's still alive.  Unfortunately, most of the code
996          * does not yet check for errors on the socket, and so if the
997          * connection drops we don't notice until the timeout expires.
998          * A better solution than sending a NOOP every time would be
999          * for every command to be prepared to retry until it is
1000          * successfully sent. -- mbp */
1001         if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1002                 /* verify that the session is still alive */
1003                 if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
1004                         debug_print("disconnected!\n");
1005                         if (!is_fatal(r))
1006                                 session = imap_reconnect_if_possible(folder, session);
1007                         else {
1008                                 rfolder->session = NULL;
1009                                 rfolder->connecting = FALSE;
1010                                 session = imap_session_get(folder);
1011                         }
1012                 }
1013                 if (session)
1014                         session->cancelled = FALSE;
1015         }
1016
1017         rfolder->session = SESSION(session);
1018         rfolder->connecting = FALSE;
1019
1020         return IMAP_SESSION(session);
1021 }
1022
1023 static IMAPSession *imap_session_new(Folder * folder,
1024                                      const PrefsAccount *account)
1025 {
1026         IMAPSession *session;
1027         gushort port;
1028         int r;
1029         int authenticated = FALSE;
1030         
1031 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1032         /* FIXME: IMAP over SSL only... */ 
1033         SSLType ssl_type;
1034
1035         port = account->set_imapport ? account->imapport
1036                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1037         ssl_type = account->ssl_imap;   
1038 #else
1039         if (account->ssl_imap != SSL_NONE) {
1040                 if (alertpanel_full(_("Insecure connection"),
1041                         _("This connection is configured to be secured "
1042                           "using SSL, but SSL is not available in this "
1043                           "build of Claws Mail. \n\n"
1044                           "Do you want to continue connecting to this "
1045                           "server? The communication would not be "
1046                           "secure."),
1047                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1048                           NULL, FALSE, NULL, ALERT_WARNING,
1049                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1050                         return NULL;
1051         }
1052         port = account->set_imapport ? account->imapport
1053                 : IMAP4_PORT;
1054 #endif
1055
1056         imap_init(folder);
1057         statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
1058 #ifndef G_OS_WIN32
1059         if (account->set_tunnelcmd) {
1060                 r = imap_threaded_connect_cmd(folder,
1061                                               account->tunnelcmd,
1062                                               account->recv_server,
1063                                               port);
1064         }
1065         else 
1066 #endif
1067         {
1068 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1069                 if (ssl_type == SSL_TUNNEL) {
1070                         r = imap_threaded_connect_ssl(folder,
1071                                                       account->recv_server,
1072                                                       port);
1073                 }
1074                 else 
1075 #endif
1076                 {
1077                         r = imap_threaded_connect(folder,
1078                                                   account->recv_server,
1079                                                   port);
1080                 }
1081         }
1082         
1083         statuswindow_pop_all();
1084         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1085                 authenticated = TRUE;
1086         }
1087         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1088                 authenticated = FALSE;
1089         }
1090         else {
1091 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1092                 if (r == MAILIMAP_ERROR_SSL)
1093                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1094                 else
1095 #endif
1096                         imap_handle_error(NULL, r);
1097
1098                 if(!prefs_common.no_recv_err_panel) {
1099                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1100                                          account->recv_server, port);
1101                 } else {
1102                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1103                                          account->recv_server, port);
1104                 } 
1105                 
1106                 return NULL;
1107         }
1108         
1109         session = g_new0(IMAPSession, 1);
1110         session_init(SESSION(session), account, FALSE);
1111         SESSION(session)->type             = SESSION_IMAP;
1112         SESSION(session)->server           = g_strdup(account->recv_server);
1113         SESSION(session)->port             = port;
1114         SESSION(session)->sock             = NULL;
1115         
1116         SESSION(session)->destroy          = imap_session_destroy;
1117
1118         session->capability = NULL;
1119         
1120         session->authenticated = authenticated;
1121         session->mbox = NULL;
1122         session->exists = 0;
1123         session->recent = 0;
1124         session->expunge = 0;
1125         session->cmd_count = 0;
1126         session->folder = folder;
1127         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1128
1129 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1130         if (account->ssl_imap == SSL_STARTTLS) {
1131                 gint ok;
1132
1133                 ok = imap_cmd_starttls(session);
1134                 if (ok != MAILIMAP_NO_ERROR) {
1135                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1136                         if (!is_fatal(ok)) {
1137                                 SESSION(session)->sock = NULL;
1138                                 session_destroy(SESSION(session));
1139                         }
1140                         return NULL;
1141                 }
1142
1143                 imap_free_capabilities(session);
1144                 session->authenticated = FALSE;
1145                 session->uidplus = FALSE;
1146                 session->cmd_count = 1;
1147         }
1148 #endif
1149         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1150                     (session->authenticated) ? "pre" : "un");
1151         
1152         return session;
1153 }
1154
1155 static gint imap_session_authenticate(IMAPSession *session, 
1156                                       PrefsAccount *account)
1157 {
1158         gchar *pass, *acc_pass;
1159         gboolean failed = FALSE;
1160         gint ok = MAILIMAP_NO_ERROR;
1161         g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1162         acc_pass = account->passwd;
1163 try_again:
1164         pass = acc_pass;
1165         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON) {
1166                 gchar *tmp_pass;
1167                 tmp_pass = input_dialog_query_password_keep(account->recv_server, 
1168                                                             account->userid,
1169                                                             &(account->session_passwd));
1170                 if (!tmp_pass)
1171                         return MAILIMAP_NO_ERROR;
1172                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1173                 g_free(tmp_pass);
1174         } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
1175                 pass = "";
1176         }
1177         statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
1178                                 account->recv_server);
1179         if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1180                 statusbar_pop_all();
1181                 
1182                 if (!failed && !is_fatal(ok)) {
1183                         acc_pass = NULL;
1184                         failed = TRUE;
1185                         if (account->session_passwd != NULL) {
1186                                 g_free(account->session_passwd);
1187                                 account->session_passwd = NULL;
1188                         }
1189                         goto try_again;
1190                 } else {
1191                         if (prefs_common.no_recv_err_panel) {
1192                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1193                                 mainwindow_show_error();
1194                         } else
1195                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1196                 }               
1197
1198                 return ok;
1199         } 
1200
1201         statuswindow_pop_all();
1202         session->authenticated = TRUE;
1203         return MAILIMAP_NO_ERROR;
1204 }
1205
1206 static void imap_session_destroy(Session *session)
1207 {
1208         if (session->state != SESSION_DISCONNECTED)
1209                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1210         
1211         imap_free_capabilities(IMAP_SESSION(session));
1212         g_free(IMAP_SESSION(session)->mbox);
1213 }
1214
1215 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1216 {
1217         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1218 }
1219
1220 static guint get_file_size_with_crs(const gchar *filename) 
1221 {
1222         FILE *fp = NULL;
1223         guint cnt = 0;
1224         gchar buf[4096];
1225         
1226         if (filename == NULL)
1227                 return -1;
1228         
1229         fp = g_fopen(filename, "rb");
1230         if (!fp)
1231                 return -1;
1232         
1233         while (fgets(buf, sizeof (buf), fp) != NULL) {
1234                 cnt += strlen(buf);
1235                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1236                         cnt++;
1237         }
1238         
1239         fclose(fp);
1240         return cnt;
1241 }
1242
1243 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1244 {
1245         gchar *path, *filename;
1246
1247         path = folder_item_get_path(item);
1248
1249         if (!is_dir_exist(path)) {
1250                 g_free(path);
1251                 return;
1252         }
1253
1254         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1255         g_free(path);
1256
1257         if (is_file_exist(filename)) {
1258                 claws_unlink(filename);
1259         }
1260         g_free(filename);
1261 }
1262
1263 typedef struct _TagsData {
1264         gchar *str;
1265         GSList *msglist;
1266         IMAPFolderItem *item;
1267 } TagsData;
1268
1269 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1270 {
1271         IMAPSession *session;
1272         gint ok, can_create_tags;
1273         Folder *folder = NULL;
1274         TagsData *ht_data = NULL;
1275         GSList *cur;
1276
1277         g_return_if_fail(item != NULL);
1278         g_return_if_fail(msginfo != NULL);
1279
1280         folder = item->folder;
1281         debug_print("getting session...\n");
1282         session = imap_session_get(folder);
1283         
1284         if (!session) {
1285                 debug_print("can't get session\n");
1286                 return;
1287         }
1288
1289         ok = imap_select(session, IMAP_FOLDER(folder), item,
1290                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1291
1292         if (ok != MAILIMAP_NO_ERROR) {
1293                 return;
1294         }
1295
1296         
1297         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1298                 return;
1299         
1300         if (IMAP_FOLDER_ITEM(item)->batching) {
1301                 /* instead of performing an UID STORE command for each message change,
1302                  * as a lot of them can change "together", we just fill in hashtables
1303                  * and defer the treatment so that we're able to send only one
1304                  * command.
1305                  */
1306                 debug_print("IMAP batch mode on, deferring tags change\n");
1307                 for (cur = tags_set; cur; cur = cur->next) {
1308                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1309                         if (cur_tag) {
1310                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1311                                         GINT_TO_POINTER(cur_tag));
1312                                 if (ht_data == NULL) {
1313                                         ht_data = g_new0(TagsData, 1);
1314                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1315                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1316                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1317                                                 GINT_TO_POINTER(cur_tag), ht_data);
1318                                 }
1319                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1320                         } 
1321                 }
1322                 for (cur = tags_unset; cur; cur = cur->next) {
1323                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1324                         if (cur_tag) {
1325                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1326                                         GINT_TO_POINTER(cur_tag));
1327                                 if (ht_data == NULL) {
1328                                         ht_data = g_new0(TagsData, 1);
1329                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1330                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1331                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1332                                                 GINT_TO_POINTER(cur_tag), ht_data);
1333                                 }
1334                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1335                         }
1336                 }
1337         } else {
1338                 GSList *list_set = NULL;
1339                 GSList *list_unset = NULL;
1340                 GSList numlist;
1341                 
1342                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1343                 numlist.next = NULL;
1344         
1345                 debug_print("IMAP changing tags NOW\n");
1346                 for (cur = tags_set; cur; cur = cur->next) {
1347                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1348                         const gchar *str = tags_get_tag(cur_tag);
1349                         if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1350                                 list_set = g_slist_prepend(list_set, g_strdup(str));
1351                 }
1352                 if (list_set) {
1353                         ok = imap_set_message_flags(session, 
1354                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1355                         slist_free_strings(list_set);
1356                         g_slist_free(list_set);
1357                         if (ok != MAILIMAP_NO_ERROR) {
1358                                 return;
1359                         }
1360                 }
1361
1362                 for (cur = tags_unset; cur; cur = cur->next) {
1363                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1364                         const gchar *str = tags_get_tag(cur_tag);
1365                         if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1366                                 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1367                 }
1368                 if (list_unset) {
1369                         ok = imap_set_message_flags(session, 
1370                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1371                         slist_free_strings(list_unset);
1372                         g_slist_free(list_unset);
1373                         if (ok != MAILIMAP_NO_ERROR) {
1374                                 return;
1375                         }
1376                 }
1377         }
1378 }
1379
1380 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1381                                   gboolean headers, gboolean body)
1382 {
1383         gchar *path, *filename;
1384         IMAPSession *session;
1385         gint ok;
1386
1387         g_return_val_if_fail(folder != NULL, NULL);
1388         g_return_val_if_fail(item != NULL, NULL);
1389
1390         if (uid == 0)
1391                 return NULL;
1392
1393         path = folder_item_get_path(item);
1394         if (!is_dir_exist(path))
1395                 make_dir_hier(path);
1396         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1397         g_free(path);
1398         debug_print("trying to fetch cached %s\n", filename);
1399         if (is_file_exist(filename)) {
1400                 /* see whether the local file represents the whole message
1401                  * or not. As the IMAP server reports size with \r chars,
1402                  * we have to update the local file (UNIX \n only) size */
1403                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1404                 guint have_size = -1;
1405
1406                 if (cached)
1407                         debug_print("message %d has been already %scached.\n", uid,
1408                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1409                 
1410                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1411                         have_size = get_file_size_with_crs(filename);
1412                         if (cached && (cached->size <= have_size || !body)) {
1413                                 procmsg_msginfo_free(cached);
1414                                 ok = file_strip_crs(filename);
1415                                 if (ok == 0 && cached && cached->size <= have_size) {
1416                                         /* we have it all and stripped */
1417                                         debug_print("...fully cached in fact; setting flag.\n");
1418                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1419                                 }
1420                                 return filename;
1421                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1422                                 debug_print("message not cached and file recent, considering file complete\n");
1423                                 ok = file_strip_crs(filename);
1424                                 if (ok == 0)
1425                                         return filename;
1426                         } else {
1427                                 procmsg_msginfo_free(cached);
1428                         }
1429                 }
1430                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1431                         procmsg_msginfo_free(cached);
1432                         return filename;
1433                 }
1434         } else {
1435                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1436                 if (cached) {
1437                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1438                         procmsg_msginfo_free(cached);
1439                 }
1440         }
1441
1442         debug_print("getting session...\n");
1443         session = imap_session_get(folder);
1444         
1445         if (!session) {
1446                 g_free(filename);
1447                 return NULL;
1448         }
1449         session_set_access_time(SESSION(session));
1450         lock_session(session); /* unlocked later in the function */
1451
1452         debug_print("IMAP fetching messages\n");
1453         ok = imap_select(session, IMAP_FOLDER(folder), item,
1454                          NULL, NULL, NULL, NULL, NULL, FALSE);
1455         if (ok != MAILIMAP_NO_ERROR) {
1456                 g_warning("can't select mailbox %s\n", item->path);
1457                 g_free(filename);
1458                 return NULL;
1459         }
1460
1461         session_set_access_time(SESSION(session));
1462
1463         debug_print("getting message %d...\n", uid);
1464         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1465
1466         if (ok != MAILIMAP_NO_ERROR) {
1467                 g_warning("can't fetch message %d\n", uid);
1468                 g_free(filename);
1469                 return NULL;
1470         }
1471
1472         session_set_access_time(SESSION(session));
1473         unlock_session(session);
1474
1475         ok = file_strip_crs(filename);
1476
1477         if (ok == 0 && headers && body) {
1478                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1479                 if (cached) {
1480                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1481                         procmsg_msginfo_free(cached);
1482                 }
1483         } else if (ok == -1) {
1484                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1485                 if (cached) {
1486                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1487                         procmsg_msginfo_free(cached);
1488                 }
1489         }
1490         return filename;
1491 }
1492
1493 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1494 {
1495         gchar *path, *filename;
1496         guint size = 0;
1497         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1498         
1499         if (!cached)
1500                 return FALSE;
1501
1502         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1503                 procmsg_msginfo_free(cached);
1504                 return TRUE;
1505         }
1506         path = folder_item_get_path(item);
1507         if (!is_dir_exist(path))
1508                 return FALSE;
1509
1510         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1511         g_free(path);
1512         if (is_file_exist(filename)) {
1513                 if (cached && cached->total_size == cached->size) {
1514                         /* fast path */
1515                         g_free(filename);
1516                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1517                         return TRUE;
1518                 }
1519                 size = get_file_size_with_crs(filename);
1520                 g_free(filename);
1521         }
1522         if (cached && size >= cached->size) {
1523                 cached->total_size = cached->size;
1524                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1525                 procmsg_msginfo_free(cached);
1526                 return TRUE;
1527         }
1528         if (cached)
1529                 procmsg_msginfo_free(cached);
1530         return FALSE;   
1531 }
1532
1533 void imap_cache_msg(FolderItem *item, gint msgnum)
1534 {
1535         Folder *folder = NULL;
1536         
1537         if (!item)
1538                 return;
1539         folder = item->folder;
1540         
1541         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1542                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1543                 debug_print("fetched %s\n", tmp);
1544                 g_free(tmp);
1545         }
1546 }
1547
1548 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1549                          const gchar *file, MsgFlags *flags)
1550 {
1551         gint ret;
1552         GSList file_list;
1553         MsgFileInfo fileinfo;
1554
1555         g_return_val_if_fail(file != NULL, -1);
1556
1557         fileinfo.msginfo = NULL;
1558         fileinfo.file = (gchar *)file;
1559         fileinfo.flags = flags;
1560         file_list.data = &fileinfo;
1561         file_list.next = NULL;
1562
1563         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1564         return ret;
1565 }
1566
1567 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1568                    GRelation *relation)
1569 {
1570         gchar *destdir;
1571         IMAPSession *session;
1572         guint32 last_uid = 0;
1573         GSList *cur;
1574         MsgFileInfo *fileinfo;
1575         gint ok = MAILIMAP_NO_ERROR;
1576         gint curnum = 0, total = 0;
1577         gboolean missing_uids = FALSE;
1578
1579         g_return_val_if_fail(folder != NULL, -1);
1580         g_return_val_if_fail(dest != NULL, -1);
1581         g_return_val_if_fail(file_list != NULL, -1);
1582         
1583         debug_print("getting session...\n");
1584         session = imap_session_get(folder);
1585         if (!session) {
1586                 return -1;
1587         }
1588         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1589         if (is_fatal(ok))
1590                 return -1;
1591         statusbar_print_all(_("Adding messages..."));
1592         total = g_slist_length(file_list);
1593         for (cur = file_list; cur != NULL; cur = cur->next) {
1594                 IMAPFlags iflags = 0;
1595                 guint32 new_uid = 0;
1596                 gchar *real_file = NULL;
1597                 fileinfo = (MsgFileInfo *)cur->data;
1598
1599                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1600                 curnum++;
1601
1602                 if (fileinfo->flags) {
1603                         if (MSG_IS_MARKED(*fileinfo->flags))
1604                                 iflags |= IMAP_FLAG_FLAGGED;
1605                         if (MSG_IS_REPLIED(*fileinfo->flags))
1606                                 iflags |= IMAP_FLAG_ANSWERED;
1607                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1608                                 iflags |= IMAP_FLAG_FORWARDED;
1609                         if (MSG_IS_SPAM(*fileinfo->flags))
1610                                 iflags |= IMAP_FLAG_SPAM;
1611                         else
1612                                 iflags |= IMAP_FLAG_HAM;
1613                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1614                                 iflags |= IMAP_FLAG_SEEN;
1615                         
1616                 }
1617                 
1618                 if (real_file == NULL)
1619                         real_file = g_strdup(fileinfo->file);
1620                 
1621                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1622                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1623                     folder_has_parent_of_type(dest, F_DRAFT) ||
1624                     folder_has_parent_of_type(dest, F_TRASH))
1625                         iflags |= IMAP_FLAG_SEEN;
1626
1627                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1628                                      &new_uid);
1629
1630                 if (ok != MAILIMAP_NO_ERROR) {
1631                         g_warning("can't append message %s\n", real_file);
1632                         g_free(real_file);
1633                         g_free(destdir);
1634                         statusbar_progress_all(0,0,0);
1635                         statusbar_pop_all();
1636                         return -1;
1637                 } else {
1638                         debug_print("appended new message as %d\n", new_uid);
1639                         /* put the local file in the imapcache, so that we don't
1640                          * have to fetch it back later. */
1641                         
1642                         if (new_uid == 0) {
1643                                 missing_uids = TRUE;
1644                                 debug_print("Missing UID (0)\n");
1645                         }
1646                         if (new_uid > 0) {
1647                                 gchar *cache_path = folder_item_get_path(dest);
1648                                 if (!is_dir_exist(cache_path))
1649                                         make_dir_hier(cache_path);
1650                                 if (is_dir_exist(cache_path)) {
1651                                         gchar *cache_file = g_strconcat(
1652                                                 cache_path, G_DIR_SEPARATOR_S, 
1653                                                 itos(new_uid), NULL);
1654                                         copy_file(real_file, cache_file, TRUE);
1655                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1656                                         g_free(cache_file);
1657                                 }
1658                                 g_free(cache_path);
1659                         }
1660                 }
1661
1662                 if (relation != NULL)
1663                         g_relation_insert(relation, fileinfo->msginfo != NULL ? 
1664                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1665                                           GINT_TO_POINTER(new_uid));
1666                 if (last_uid < new_uid) {
1667                         last_uid = new_uid;
1668                 }
1669
1670                 g_free(real_file);
1671         }
1672         
1673         statusbar_progress_all(0,0,0);
1674         statusbar_pop_all();
1675         
1676         
1677         g_free(destdir);
1678
1679         imap_scan_required(folder, dest);
1680
1681         session = imap_session_get(folder);
1682         if (!session) {
1683                 return -1;
1684         }
1685         if (missing_uids) {
1686                 gint a;
1687                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1688                          &a, NULL, NULL, NULL, NULL, FALSE);
1689         }
1690         return last_uid;
1691 }
1692
1693 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1694 {
1695         GSList *result = NULL;
1696         clistiter *list;
1697         int start, end, t;
1698         GSList *cur;
1699
1700         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1701                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1702                 start = item->set_first;
1703                 end = item->set_last;
1704                 for (t = start; t <= end; t++) {
1705                         result = g_slist_prepend(result, GINT_TO_POINTER(t));
1706                 }
1707         }
1708         result = g_slist_reverse(result);
1709         if (debug_get_mode()) {
1710                 debug_print("flat imap set: ");
1711                 for (cur = result; cur; cur = cur->next) {
1712                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1713                 }
1714                 debug_print("\n");
1715         }
1716         
1717         return result;
1718 }
1719 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1720                               MsgInfoList *msglist, GRelation *relation)
1721 {
1722         FolderItem *src;
1723         gchar *destdir;
1724         GSList *seq_list, *cur;
1725         MsgInfo *msginfo;
1726         IMAPSession *session;
1727         gint ok = MAILIMAP_NO_ERROR;
1728         GRelation *uid_mapping;
1729         gint last_num = 0;
1730         gboolean single = FALSE;
1731
1732         g_return_val_if_fail(folder != NULL, -1);
1733         g_return_val_if_fail(dest != NULL, -1);
1734         g_return_val_if_fail(msglist != NULL, -1);
1735         
1736         debug_print("getting session...\n");
1737         session = imap_session_get(folder);
1738         
1739         if (!session) {
1740                 return -1;
1741         }
1742
1743         msginfo = (MsgInfo *)msglist->data;
1744         if (msglist->next == NULL)
1745                 single = TRUE;
1746         src = msginfo->folder;
1747         if (src == dest) {
1748                 g_warning("the src folder is identical to the dest.\n");
1749                 return -1;
1750         }
1751
1752         if (src->folder != dest->folder) {
1753                 GSList *infolist = NULL, *cur;
1754                 int res = -1;
1755                 for (cur = msglist; cur; cur = cur->next) {
1756                         msginfo = (MsgInfo *)cur->data;
1757                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1758                         fileinfo->file = procmsg_get_message_file(msginfo);
1759                         fileinfo->flags = &(msginfo->flags);
1760                         infolist = g_slist_prepend(infolist, fileinfo);
1761                 }
1762                 infolist = g_slist_reverse(infolist);
1763                 res = folder_item_add_msgs(dest, infolist, FALSE);
1764                 for (cur = infolist; cur; cur = cur->next) {
1765                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1766                         g_free(info->file);
1767                         g_free(info);
1768                 }
1769                 g_slist_free(infolist);
1770                 return res;
1771         } 
1772
1773         lock_session(session); /* unlocked later in the function */
1774
1775         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1776                          NULL, NULL, NULL, NULL, NULL, FALSE);
1777         if (ok != MAILIMAP_NO_ERROR) {
1778                 return ok;
1779         }
1780
1781         unlock_session(session);
1782
1783         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1784
1785         if (is_fatal(ok))
1786                 return ok;
1787
1788         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1789         uid_mapping = g_relation_new(2);
1790         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1791         
1792         statusbar_print_all(_("Copying messages..."));
1793         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1794                 struct mailimap_set * seq_set;
1795                 struct mailimap_set * source = NULL;
1796                 struct mailimap_set * dest = NULL;
1797                 seq_set = cur->data;
1798
1799                 debug_print("Copying messages from %s to %s ...\n",
1800                             src->path, destdir);
1801
1802                 lock_session(session); /* unlocked later in the function */
1803                 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
1804                         &source, &dest);
1805                 
1806                 if (is_fatal(ok)) {
1807                         session = NULL;
1808                 }
1809
1810                 if (ok == MAILIMAP_NO_ERROR) {
1811                         unlock_session(session);
1812                         if (relation && source && dest) {
1813                                 GSList *s_list = flatten_mailimap_set(source);
1814                                 GSList *d_list = flatten_mailimap_set(dest);
1815                                 GSList *s_cur, *d_cur;
1816                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1817
1818                                         for (s_cur = s_list, d_cur = d_list; 
1819                                              s_cur && d_cur; 
1820                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1821                                                 g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
1822                                         }
1823
1824                                 } else {
1825                                         debug_print("hhhmm, source list length != dest list length.\n");
1826                                 }
1827                                 g_slist_free(s_list);
1828                                 g_slist_free(d_list);
1829                         }
1830                 }
1831
1832
1833                 if (source)
1834                         mailimap_set_free(source);
1835                 if (dest)
1836                         mailimap_set_free(dest);
1837
1838                 if (ok != MAILIMAP_NO_ERROR) {
1839                         g_relation_destroy(uid_mapping);
1840                         imap_lep_set_free(seq_list);
1841                         statusbar_pop_all();
1842                         return -1;
1843                 }
1844         }
1845
1846         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1847                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1848                 GTuples *tuples;
1849
1850                 tuples = g_relation_select(uid_mapping, 
1851                                            GINT_TO_POINTER(msginfo->msgnum),
1852                                            0);
1853                 if (tuples->len > 0) {
1854                         gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1855                         g_relation_insert(relation, msginfo,
1856                                           GINT_TO_POINTER(num));
1857                         if (num > last_num)
1858                                 last_num = num;
1859                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1860                         /* put the local file in the imapcache, so that we don't
1861                          * have to fetch it back later. */
1862                         if (num > 0) {
1863                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1864                                 gchar *real_file = g_strconcat(
1865                                         cache_path, G_DIR_SEPARATOR_S, 
1866                                         itos(msginfo->msgnum), NULL);
1867                                 gchar *cache_file = NULL;
1868                                 g_free(cache_path);
1869                                 cache_path = folder_item_get_path(dest);
1870                                 cache_file = g_strconcat(
1871                                         cache_path, G_DIR_SEPARATOR_S, 
1872                                         itos(num), NULL);
1873                                 if (!is_dir_exist(cache_path))
1874                                         make_dir_hier(cache_path);
1875                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1876                                         copy_file(real_file, cache_file, TRUE);
1877                                         debug_print("copied to cache: %s\n", cache_file);
1878                                 }
1879                                 g_free(real_file);
1880                                 g_free(cache_file);
1881                                 g_free(cache_path);
1882                         }
1883                 } else
1884                         g_relation_insert(relation, msginfo,
1885                                           GINT_TO_POINTER(0));
1886                 g_tuples_destroy(tuples);
1887         }
1888         statusbar_pop_all();
1889
1890         g_relation_destroy(uid_mapping);
1891         imap_lep_set_free(seq_list);
1892
1893         g_free(destdir);
1894         
1895         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1896         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1897         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1898         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1899
1900         imap_scan_required(folder, dest);
1901         if (ok == MAILIMAP_NO_ERROR)
1902                 return last_num;
1903         else
1904                 return -1;
1905 }
1906
1907 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1908 {
1909         GSList msglist;
1910
1911         g_return_val_if_fail(msginfo != NULL, -1);
1912
1913         msglist.data = msginfo;
1914         msglist.next = NULL;
1915
1916         return imap_copy_msgs(folder, dest, &msglist, NULL);
1917 }
1918
1919 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1920                     MsgInfoList *msglist, GRelation *relation)
1921 {
1922         MsgInfo *msginfo;
1923         gint ret;
1924
1925         g_return_val_if_fail(folder != NULL, -1);
1926         g_return_val_if_fail(dest != NULL, -1);
1927         g_return_val_if_fail(msglist != NULL, -1);
1928
1929         msginfo = (MsgInfo *)msglist->data;
1930         g_return_val_if_fail(msginfo->folder != NULL, -1);
1931
1932         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1933         return ret;
1934 }
1935
1936
1937 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1938                                 MsgInfoList *msglist, GRelation *relation)
1939 {
1940         gchar *destdir, *dir;
1941         GSList *numlist = NULL, *cur;
1942         MsgInfo *msginfo;
1943         IMAPSession *session;
1944         gint ok = MAILIMAP_NO_ERROR;
1945         GRelation *uid_mapping;
1946         
1947         g_return_val_if_fail(folder != NULL, -1);
1948         g_return_val_if_fail(dest != NULL, -1);
1949         g_return_val_if_fail(msglist != NULL, -1);
1950
1951         debug_print("getting session...\n");
1952         session = imap_session_get(folder);
1953         if (!session) {
1954                 return -1;
1955         }
1956
1957         lock_session(session); /* unlocked later in the function */
1958
1959         msginfo = (MsgInfo *)msglist->data;
1960
1961         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1962                          NULL, NULL, NULL, NULL, NULL, FALSE);
1963         if (ok != MAILIMAP_NO_ERROR) {
1964                 return ok;
1965         }
1966
1967         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1968         if (is_fatal(ok))
1969                 return ok;
1970         for (cur = msglist; cur; cur = cur->next) {
1971                 msginfo = (MsgInfo *)cur->data;
1972                 if (!MSG_IS_DELETED(msginfo->flags))
1973                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1974         }
1975         numlist = g_slist_reverse(numlist);
1976
1977         uid_mapping = g_relation_new(2);
1978         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1979
1980         if (numlist != NULL) {
1981                 ok = imap_set_message_flags
1982                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
1983                 if (ok != MAILIMAP_NO_ERROR) {
1984                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1985                         return ok;
1986                 }
1987         } /* else we just need to expunge */
1988         ok = imap_cmd_expunge(session);
1989         if (ok != MAILIMAP_NO_ERROR) {
1990                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1991                 return ok;
1992         }
1993         
1994         session->folder_content_changed = TRUE;
1995         unlock_session(session);
1996
1997         dir = folder_item_get_path(msginfo->folder);
1998         if (is_dir_exist(dir)) {
1999                 for (cur = msglist; cur; cur = cur->next) {
2000                         msginfo = (MsgInfo *)cur->data;
2001                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2002                 }
2003         }
2004         g_free(dir);
2005
2006         g_relation_destroy(uid_mapping);
2007         g_slist_free(numlist);
2008
2009         imap_scan_required(folder, dest);
2010
2011         g_free(destdir);
2012         if (ok == MAILIMAP_NO_ERROR)
2013                 return 0;
2014         else
2015                 return -1;
2016 }
2017
2018 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2019                     MsgInfoList *msglist, GRelation *relation)
2020 {
2021         MsgInfo *msginfo;
2022
2023         g_return_val_if_fail(folder != NULL, -1);
2024         g_return_val_if_fail(dest != NULL, -1);
2025         if (msglist == NULL)
2026                 return 0;
2027
2028         msginfo = (MsgInfo *)msglist->data;
2029         g_return_val_if_fail(msginfo->folder != NULL, -1);
2030
2031         return imap_do_remove_msgs(folder, dest, msglist, relation);
2032 }
2033
2034 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2035 {
2036         GSList *list = folder_item_get_msg_list(item);
2037         gint res = imap_remove_msgs(folder, item, list, NULL);
2038         procmsg_msg_list_free(list);
2039         return res;
2040 }
2041
2042 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2043                                     MsgInfo *msginfo)
2044 {
2045         /* TODO: properly implement this method */
2046         return FALSE;
2047 }
2048
2049 static gint imap_close(Folder *folder, FolderItem *item)
2050 {
2051         return 0;
2052 }
2053
2054 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2055 {
2056         FolderItem *item = NULL;
2057         IMAPSession *session;
2058         gchar *root_folder = NULL;
2059
2060         g_return_val_if_fail(folder != NULL, -1);
2061         g_return_val_if_fail(folder->account != NULL, -1);
2062
2063         debug_print("getting session...\n");
2064         session = imap_session_get(folder);
2065         if (!session) {
2066                 if (!folder->node) {
2067                         folder_tree_destroy(folder);
2068                         item = folder_item_new(folder, folder->name, NULL);
2069                         item->folder = folder;
2070                         folder->node = item->node = g_node_new(item);
2071                 }
2072                 return -1;
2073         }
2074
2075         if (folder->account->imap_dir && *folder->account->imap_dir) {
2076                 gchar *real_path;
2077                 int r;
2078                 clist * lep_list;
2079
2080                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2081                 extract_quote(root_folder, '"');
2082                 subst_char(root_folder,
2083                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2084                                                    root_folder, &r),
2085                            '/');
2086                 if (is_fatal(r))
2087                         return -1;
2088                 strtailchomp(root_folder, '/');
2089                 real_path = imap_get_real_path
2090                         (session, IMAP_FOLDER(folder), root_folder, &r);
2091                 if (is_fatal(r))
2092                         return -1;
2093                 debug_print("IMAP root directory: %s\n", real_path);
2094
2095                 /* check if root directory exist */
2096
2097                 r = imap_threaded_list(session->folder, "", real_path,
2098                                        &lep_list);
2099
2100                 if (r != MAILIMAP_NO_ERROR)
2101                         imap_handle_error(SESSION(session), r);
2102
2103                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2104                         if (!folder->node) {
2105                                 item = folder_item_new(folder, folder->name, NULL);
2106                                 item->folder = folder;
2107                                 folder->node = item->node = g_node_new(item);
2108                         }
2109                         return -1;
2110                 }
2111                 mailimap_list_result_free(lep_list);
2112                                 
2113                 g_free(real_path);
2114         }
2115
2116         if (folder->node)
2117                 item = FOLDER_ITEM(folder->node->data);
2118                 
2119         if (item && !item->path && root_folder) {
2120                 item->path = g_strdup(root_folder);
2121         }
2122
2123         if (!item || ((item->path || root_folder) &&
2124                       strcmp2(item->path, root_folder) != 0)) {
2125                 folder_tree_destroy(folder);
2126                 item = folder_item_new(folder, folder->name, root_folder);
2127                 item->folder = folder;
2128                 folder->node = item->node = g_node_new(item);
2129         }
2130
2131         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2132         imap_create_missing_folders(folder);
2133
2134         return 0;
2135 }
2136
2137 static gint imap_scan_tree(Folder *folder)
2138 {
2139         gboolean subs_only = FALSE;
2140         if (folder->account) {
2141                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2142                 subs_only = folder->account->imap_subsonly;
2143         }
2144         return imap_scan_tree_real(folder, subs_only);
2145 }
2146
2147 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2148 {
2149         Folder *folder;
2150         IMAPFolder *imapfolder;
2151         FolderItem *new_item;
2152         GSList *item_list, *cur;
2153         GNode *node;
2154         gchar *real_path;
2155         gchar *wildcard_path;
2156         gchar separator;
2157         gchar wildcard[3];
2158         clist * lep_list;
2159         int r;
2160         
2161         g_return_val_if_fail(item != NULL, -1);
2162         g_return_val_if_fail(item->folder != NULL, -1);
2163         g_return_val_if_fail(item->no_sub == FALSE, -1);
2164
2165         folder = item->folder;
2166         imapfolder = IMAP_FOLDER(folder);
2167
2168         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2169         if (is_fatal(r))
2170                 return r;
2171
2172         if (folder->ui_func)
2173                 folder->ui_func(folder, item, folder->ui_func_data);
2174
2175         if (item->path) {
2176                 wildcard[0] = separator;
2177                 wildcard[1] = '%';
2178                 wildcard[2] = '\0';
2179                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2180                 if (is_fatal(r))
2181                         return r;
2182         } else {
2183                 wildcard[0] = '%';
2184                 wildcard[1] = '\0';
2185                 real_path = g_strdup("");
2186         }
2187
2188         Xstrcat_a(wildcard_path, real_path, wildcard,
2189                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2190         lep_list = NULL;
2191         
2192         if (subs_only)
2193                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2194         else
2195                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2196
2197         if (r != MAILIMAP_NO_ERROR) {
2198                 imap_handle_error(SESSION(session), r);
2199                 item_list = NULL;
2200                 return r;
2201         }
2202         else {
2203                 item_list = imap_list_from_lep(imapfolder,
2204                                                lep_list, real_path, FALSE);
2205                 mailimap_list_result_free(lep_list);
2206         }
2207         
2208         g_free(real_path);
2209
2210         node = item->node->children;
2211         while (node != NULL) {
2212                 FolderItem *old_item = FOLDER_ITEM(node->data);
2213                 GNode *next = node->next;
2214
2215                 new_item = NULL;
2216                 for (cur = item_list; cur != NULL; cur = cur->next) {
2217                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2218                         if (!strcmp2(old_item->path, cur_item->path)) {
2219                                 new_item = cur_item;
2220                                 break;
2221                         }
2222                 }
2223                 if (!new_item) {
2224                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2225                                 debug_print("not removing INBOX\n");
2226                         } else {
2227                                 debug_print("folder '%s' not found. removing...\n",
2228                                             old_item->path);
2229                                 folder_item_remove(old_item);
2230                         }
2231                 } else {
2232                         old_item->no_sub = new_item->no_sub;
2233                         old_item->no_select = new_item->no_select;
2234                         if (old_item->no_sub == TRUE && node->children) {
2235                                 debug_print("folder '%s' doesn't have "
2236                                             "subfolders. removing...\n",
2237                                             old_item->path);
2238                                 folder_item_remove_children(old_item);
2239                         }
2240                 }
2241
2242                 node = next;
2243         }
2244
2245         for (cur = item_list; cur != NULL; cur = cur->next) {
2246                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2247                 new_item = NULL;
2248
2249                 for (node = item->node->children; node != NULL;
2250                      node = node->next) {
2251                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2252                                      cur_item->path)) {
2253                                 new_item = FOLDER_ITEM(node->data);
2254                                 folder_item_destroy(cur_item);
2255                                 cur_item = NULL;
2256                                 break;
2257                         }
2258                 }
2259                 if (!new_item) {
2260                         new_item = cur_item;
2261                         debug_print("new folder '%s' found.\n", new_item->path);
2262                         folder_item_append(item, new_item);
2263                 }
2264
2265                 if (!strcmp(new_item->path, "INBOX")) {
2266                         new_item->stype = F_INBOX;
2267                         folder->inbox = new_item;
2268                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2269                         gchar *base;
2270
2271                         base = g_path_get_basename(new_item->path);
2272
2273                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2274                                 new_item->stype = F_OUTBOX;
2275                                 folder->outbox = new_item;
2276                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2277                                 new_item->stype = F_DRAFT;
2278                                 folder->draft = new_item;
2279                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2280                                 new_item->stype = F_QUEUE;
2281                                 folder->queue = new_item;
2282                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2283                                 new_item->stype = F_TRASH;
2284                                 folder->trash = new_item;
2285                         }
2286                         g_free(base);
2287                 }
2288
2289                 if (new_item->no_sub == FALSE)
2290                         imap_scan_tree_recursive(session, new_item, subs_only);
2291         }
2292
2293         g_slist_free(item_list);
2294
2295         return MAILIMAP_NO_ERROR;
2296 }
2297
2298 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2299 {
2300         IMAPSession *session = imap_session_get(folder);
2301         gchar *real_path;
2302         gchar *wildcard_path;
2303         gchar separator;
2304         gchar wildcard[3];
2305         clist * lep_list;
2306         GSList *item_list = NULL, *cur;
2307         GList *child_list = NULL, *tmplist = NULL;
2308         GSList *sub_list = NULL;
2309         int r;
2310
2311         if (!session)
2312                 return NULL;
2313
2314         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2315         if (is_fatal(r))
2316                 return NULL;
2317
2318         if (item->path) {
2319                 wildcard[0] = separator;
2320                 wildcard[1] = '%';
2321                 wildcard[2] = '\0';
2322                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2323                 if (is_fatal(r))
2324                         return NULL;
2325         } else {
2326                 wildcard[0] = '%';
2327                 wildcard[1] = '\0';
2328                 real_path = g_strdup("");
2329         }
2330
2331         Xstrcat_a(wildcard_path, real_path, wildcard,
2332                   {g_free(real_path); return NULL;});
2333         lep_list = NULL;
2334         
2335         if (unsubs_only)
2336                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2337                                 item->path?item->path:item->name);
2338         else
2339                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2340                                 item->path?item->path:item->name);
2341
2342         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2343         if (r) {
2344                 statusbar_pop_all();
2345                 return NULL;
2346         }
2347         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2348                                lep_list, real_path, FALSE);
2349         mailimap_list_result_free(lep_list);
2350
2351         for (cur = item_list; cur != NULL; cur = cur->next) {
2352                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2353                 if (recursive) {
2354                         tmplist = imap_scan_subtree(folder, cur_item, 
2355                                         unsubs_only, recursive);
2356                         if (tmplist)
2357                                 child_list = g_list_concat(child_list, tmplist);
2358                 }
2359                 child_list = g_list_prepend(child_list,
2360                                 imap_get_real_path(session, 
2361                                         IMAP_FOLDER(folder), cur_item->path, &r));
2362                 if (is_fatal(r)) {
2363                         statusbar_pop_all();
2364                         return NULL;
2365                 }
2366                 folder_item_destroy(cur_item);
2367         }
2368         child_list = g_list_reverse(child_list);
2369         g_slist_free(item_list);
2370
2371         if (unsubs_only) {
2372                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2373                 if (r) {
2374                         statusbar_pop_all();
2375                         return NULL;
2376                 }
2377                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2378                                        lep_list, real_path, FALSE);
2379                 mailimap_list_result_free(lep_list);
2380
2381                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2382                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2383                         GList *oldlitem = NULL;
2384                         gchar *tmp = imap_get_real_path(session, 
2385                                         IMAP_FOLDER(folder), cur_item->path, &r);
2386                         if (r) {
2387                                 statusbar_pop_all();
2388                                 return NULL;
2389                         }
2390                         folder_item_destroy(cur_item);
2391                         oldlitem = g_list_find_custom(
2392                                         child_list, tmp, (GCompareFunc)strcmp2);
2393                         if (oldlitem) {
2394                                 child_list = g_list_remove_link(child_list, oldlitem);
2395                                 g_free(oldlitem->data);
2396                                 g_list_free(oldlitem);
2397                         }
2398                         g_free(tmp);
2399                 }
2400         }
2401
2402         statusbar_pop_all();
2403
2404         return child_list;
2405 }
2406
2407 static gint imap_create_tree(Folder *folder)
2408 {
2409         g_return_val_if_fail(folder != NULL, -1);
2410         g_return_val_if_fail(folder->node != NULL, -1);
2411         g_return_val_if_fail(folder->node->data != NULL, -1);
2412         g_return_val_if_fail(folder->account != NULL, -1);
2413
2414         imap_scan_tree(folder);
2415         imap_create_missing_folders(folder);
2416
2417         return 0;
2418 }
2419
2420 static void imap_create_missing_folders(Folder *folder)
2421 {
2422         g_return_if_fail(folder != NULL);
2423
2424         if (!folder->inbox)
2425                 folder->inbox = imap_create_special_folder
2426                         (folder, F_INBOX, "INBOX");
2427         if (!folder->trash)
2428                 folder->trash = imap_create_special_folder
2429                         (folder, F_TRASH, "Trash");
2430         if (!folder->queue)
2431                 folder->queue = imap_create_special_folder
2432                         (folder, F_QUEUE, "Queue");
2433         if (!folder->outbox)
2434                 folder->outbox = imap_create_special_folder
2435                         (folder, F_OUTBOX, "Sent");
2436         if (!folder->draft)
2437                 folder->draft = imap_create_special_folder
2438                         (folder, F_DRAFT, "Drafts");
2439 }
2440
2441 static FolderItem *imap_create_special_folder(Folder *folder,
2442                                               SpecialFolderItemType stype,
2443                                               const gchar *name)
2444 {
2445         FolderItem *item;
2446         FolderItem *new_item;
2447
2448         g_return_val_if_fail(folder != NULL, NULL);
2449         g_return_val_if_fail(folder->node != NULL, NULL);
2450         g_return_val_if_fail(folder->node->data != NULL, NULL);
2451         g_return_val_if_fail(folder->account != NULL, NULL);
2452         g_return_val_if_fail(name != NULL, NULL);
2453
2454         item = FOLDER_ITEM(folder->node->data);
2455         new_item = imap_create_folder(folder, item, name);
2456
2457         if (!new_item) {
2458                 g_warning("Can't create '%s'\n", name);
2459                 if (!folder->inbox) return NULL;
2460
2461                 new_item = imap_create_folder(folder, folder->inbox, name);
2462                 if (!new_item)
2463                         g_warning("Can't create '%s' under INBOX\n", name);
2464                 else
2465                         new_item->stype = stype;
2466         } else
2467                 new_item->stype = stype;
2468
2469         return new_item;
2470 }
2471
2472 static gchar *imap_folder_get_path(Folder *folder)
2473 {
2474         gchar *folder_path;
2475
2476         g_return_val_if_fail(folder != NULL, NULL);
2477         g_return_val_if_fail(folder->account != NULL, NULL);
2478
2479         folder_path = g_strconcat(get_imap_cache_dir(),
2480                                   G_DIR_SEPARATOR_S,
2481                                   folder->account->recv_server,
2482                                   G_DIR_SEPARATOR_S,
2483                                   folder->account->userid,
2484                                   NULL);
2485
2486         return folder_path;
2487 }
2488
2489 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2490 {
2491         gchar *folder_path, *path;
2492
2493         g_return_val_if_fail(folder != NULL, NULL);
2494         g_return_val_if_fail(item != NULL, NULL);
2495         folder_path = imap_folder_get_path(folder);
2496
2497         g_return_val_if_fail(folder_path != NULL, NULL);
2498         if (g_path_is_absolute(folder_path)) {
2499                 if (item->path)
2500                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2501                                            item->path, NULL);
2502                 else
2503                         path = g_strdup(folder_path);
2504         } else {
2505                 if (item->path)
2506                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2507                                            folder_path, G_DIR_SEPARATOR_S,
2508                                            item->path, NULL);
2509                 else
2510                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2511                                            folder_path, NULL);
2512         }
2513         g_free(folder_path);
2514 #ifdef G_OS_WIN32
2515         while (strchr(path, '/'))
2516                 *strchr(path, '/') = '\\';
2517 #endif
2518
2519         return path;
2520 }
2521
2522 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2523                                const gchar *name)
2524 {
2525         gchar *dirpath, *imap_path;
2526         IMAPSession *session;
2527         FolderItem *new_item;
2528         gchar separator;
2529         gchar *new_name;
2530         const gchar *p;
2531         gint ok;
2532         gboolean no_select = FALSE, no_sub = FALSE;
2533         gboolean exist = FALSE;
2534         
2535         g_return_val_if_fail(folder != NULL, NULL);
2536         g_return_val_if_fail(folder->account != NULL, NULL);
2537         g_return_val_if_fail(parent != NULL, NULL);
2538         g_return_val_if_fail(name != NULL, NULL);
2539
2540         debug_print("getting session...\n");
2541         session = imap_session_get(folder);
2542         if (!session) {
2543                 return NULL;
2544         }
2545
2546         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2547                 dirpath = g_strdup(name);
2548         }else if (parent->path)
2549                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2550         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2551                 dirpath = g_strdup(name);
2552         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2553                 gchar *imap_dir;
2554
2555                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2556                 strtailchomp(imap_dir, '/');
2557                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2558         } else
2559                 dirpath = g_strdup(name);
2560                 
2561         
2562
2563         /* keep trailing directory separator to create a folder that contains
2564            sub folder */
2565         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
2566
2567         strtailchomp(dirpath, '/');
2568         Xstrdup_a(new_name, name, {
2569                 g_free(dirpath); 
2570                 return NULL;});
2571
2572         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
2573         if (is_fatal(ok))
2574                 return NULL;
2575         imap_path_separator_subst(imap_path, separator);
2576         /* remove trailing / for display */
2577         strtailchomp(new_name, '/');
2578
2579         if (strcmp(dirpath, "INBOX") != 0) {
2580                 GPtrArray *argbuf;
2581                 int r;
2582                 clist * lep_list;
2583                 
2584                 argbuf = g_ptr_array_new();
2585                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2586                 if (r != MAILIMAP_NO_ERROR) {
2587                         imap_handle_error(SESSION(session), r);
2588                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2589                         g_free(imap_path);
2590                         g_free(dirpath);
2591                         ptr_array_free_strings(argbuf);
2592                         g_ptr_array_free(argbuf, TRUE);
2593                         return NULL;
2594                 }
2595                 
2596                 if (clist_count(lep_list) > 0)
2597                         exist = TRUE;
2598                 mailimap_list_result_free(lep_list);
2599                 lep_list = NULL;
2600                 if (!exist) {
2601                         ok = imap_cmd_create(session, imap_path);
2602                         if (ok != MAILIMAP_NO_ERROR) {
2603                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2604                                 g_free(imap_path);
2605                                 g_free(dirpath);
2606                                 return NULL;
2607                         }
2608                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2609                         if (r == MAILIMAP_NO_ERROR) {
2610                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2611                                                lep_list, dirpath, TRUE);
2612                                 if (item_list) {
2613                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2614                                         no_select = cur_item->no_select;
2615                                         no_sub = cur_item->no_sub;
2616                                         g_slist_free(item_list);
2617                                 } 
2618                                 mailimap_list_result_free(lep_list);
2619                         } else {
2620                                 imap_handle_error(SESSION(session), r);
2621                         }
2622                 }
2623                 imap_threaded_subscribe(folder, imap_path, TRUE);
2624         } else {
2625                 clist *lep_list;
2626                 int r;
2627                 /* just get flags */
2628                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2629                 if (r == MAILIMAP_NO_ERROR) {
2630                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2631                                        lep_list, dirpath, TRUE);
2632                         if (item_list) {
2633                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2634                                 no_select = cur_item->no_select;
2635                                 no_sub = cur_item->no_sub;
2636                                 g_slist_free(item_list);
2637                         } 
2638                         mailimap_list_result_free(lep_list);
2639                 } else {
2640                         imap_handle_error(SESSION(session), r);
2641                 }
2642         }
2643
2644         new_item = folder_item_new(folder, new_name, dirpath);
2645         new_item->no_select = no_select;
2646         new_item->no_sub = no_sub;
2647         folder_item_append(parent, new_item);
2648         g_free(imap_path);
2649         g_free(dirpath);
2650
2651         dirpath = folder_item_get_path(new_item);
2652         if (!is_dir_exist(dirpath))
2653                 make_dir_hier(dirpath);
2654         g_free(dirpath);
2655
2656         if (exist) {
2657                 /* folder existed, scan it */
2658                 imap_scan_required(folder, new_item);
2659                 folder_item_scan_full(new_item, FALSE);
2660         }
2661
2662         return new_item;
2663 }
2664
2665 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2666                                const gchar *name)
2667 {
2668         gchar *dirpath;
2669         gchar *newpath;
2670         gchar *real_oldpath;
2671         gchar *real_newpath;
2672         gchar *paths[2];
2673         gchar *old_cache_dir;
2674         gchar *new_cache_dir;
2675         IMAPSession *session;
2676         gchar separator;
2677         gint ok;
2678         gint exists, recent, unseen;
2679         guint32 uid_validity;
2680
2681         g_return_val_if_fail(folder != NULL, -1);
2682         g_return_val_if_fail(item != NULL, -1);
2683         g_return_val_if_fail(item->path != NULL, -1);
2684         g_return_val_if_fail(name != NULL, -1);
2685
2686         debug_print("getting session...\n");
2687         session = imap_session_get(folder);
2688         if (!session) {
2689                 return -1;
2690         }
2691
2692         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
2693                 is_fatal(ok)) {
2694                 g_warning(_("New folder name must not contain the namespace "
2695                             "path separator"));
2696                 return -1;
2697         }
2698
2699         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2700         if (is_fatal(ok)) {
2701                 return -1;
2702         }
2703
2704         g_free(session->mbox);
2705         session->mbox = NULL;
2706         session->exists = 0;
2707         session->recent = 0;
2708         session->expunge = 0;
2709         ok = imap_cmd_examine(session, "INBOX",
2710                               &exists, &recent, &unseen, &uid_validity, FALSE);
2711         if (ok != MAILIMAP_NO_ERROR) {
2712                 g_free(real_oldpath);
2713                 return -1;
2714         }
2715
2716         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
2717         if (is_fatal(ok))
2718                 return -1;
2719         if (strchr(item->path, G_DIR_SEPARATOR)) {
2720                 dirpath = g_path_get_dirname(item->path);
2721                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2722                 g_free(dirpath);
2723         } else
2724                 newpath = g_strdup(name);
2725
2726         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
2727         imap_path_separator_subst(real_newpath, separator);
2728
2729         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2730         if (ok != MAILIMAP_NO_ERROR) {
2731                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2732                             real_oldpath, real_newpath);
2733                 g_free(real_oldpath);
2734                 g_free(newpath);
2735                 g_free(real_newpath);
2736                 return -1;
2737         }
2738         g_free(item->name);
2739         item->name = g_strdup(name);
2740
2741         old_cache_dir = folder_item_get_path(item);
2742
2743         paths[0] = g_strdup(item->path);
2744         paths[1] = newpath;
2745         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2746                         imap_rename_folder_func, paths);
2747
2748         if (is_dir_exist(old_cache_dir)) {
2749                 new_cache_dir = folder_item_get_path(item);
2750                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2751                         FILE_OP_ERROR(old_cache_dir, "rename");
2752                 }
2753                 g_free(new_cache_dir);
2754         }
2755
2756         g_free(old_cache_dir);
2757         g_free(paths[0]);
2758         g_free(newpath);
2759         g_free(real_oldpath);
2760         g_free(real_newpath);
2761         return 0;
2762 }
2763
2764 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2765 {
2766         gchar *path;
2767         gint r = -1;
2768         IMAPSession *session;
2769         debug_print("getting session...\n");
2770
2771         session = imap_session_get(folder);
2772         if (!session) {
2773                 return -1;
2774         }
2775         if (item && item->path) {
2776                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2777                 if (!path || is_fatal(r))
2778                         return -1;
2779                 if (!strcmp(path, "INBOX") && sub == FALSE)
2780                         return -1;
2781                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2782                 r = imap_threaded_subscribe(folder, path, sub);
2783                 g_free(path);
2784         } else if (rpath) {
2785                 r = imap_threaded_subscribe(folder, rpath, sub);
2786         } else
2787                 return -1;
2788         return r;
2789 }
2790
2791 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2792 {
2793         gint ok;
2794         IMAPSession *session;
2795         gchar *path;
2796         gchar *cache_dir;
2797         gboolean selected_folder;
2798
2799         g_return_val_if_fail(folder != NULL, -1);
2800         g_return_val_if_fail(item != NULL, -1);
2801         g_return_val_if_fail(item->path != NULL, -1);
2802
2803         debug_print("getting session...\n");
2804         session = imap_session_get(folder);
2805         if (!session) {
2806                 return -1;
2807         }
2808         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2809         if (is_fatal(ok))
2810                 return -1;
2811
2812         imap_threaded_subscribe(folder, path, FALSE);
2813
2814         selected_folder = (session->mbox != NULL) &&
2815                           (!strcmp(session->mbox, item->path));
2816         if (selected_folder) {
2817                 ok = imap_cmd_close(session);
2818                 if (ok != MAILIMAP_NO_ERROR) {
2819                         debug_print("close err %d\n", ok);
2820                         return ok;
2821                 }
2822         }
2823         ok = imap_cmd_delete(session, path);
2824         if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
2825                 gchar *tmp = g_strdup_printf("%s%c", path, 
2826                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
2827                 g_free(path);
2828                 path = tmp;
2829                 if (!is_fatal(ok))
2830                         ok = imap_cmd_delete(session, path);
2831         }
2832
2833         if (ok != MAILIMAP_NO_ERROR) {
2834                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2835                 g_free(path);
2836                 return -1;
2837         }
2838
2839         g_free(path);
2840         cache_dir = folder_item_get_path(item);
2841         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2842                 g_warning("can't remove directory '%s'\n", cache_dir);
2843         g_free(cache_dir);
2844         folder_item_remove(item);
2845         return 0;
2846 }
2847
2848 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2849 {
2850         GNode *node, *next;
2851
2852         g_return_val_if_fail(item != NULL, -1);
2853         g_return_val_if_fail(item->folder != NULL, -1);
2854         g_return_val_if_fail(item->node != NULL, -1);
2855
2856         node = item->node->children;
2857         while (node != NULL) {
2858                 next = node->next;
2859                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2860                         return -1;
2861                 node = next;
2862         }
2863         debug_print("IMAP removing %s\n", item->path);
2864
2865         if (imap_remove_all_msg(folder, item) < 0)
2866                 return -1;
2867         return imap_remove_folder_real(folder, item);
2868 }
2869
2870 typedef struct _uncached_data {
2871         IMAPSession *session;
2872         FolderItem *item;
2873         MsgNumberList *numlist;
2874         guint cur;
2875         guint total;
2876         gboolean done;
2877         int ok;
2878 } uncached_data;
2879
2880 static void *imap_get_uncached_messages_thread(void *data)
2881 {
2882         uncached_data *stuff = (uncached_data *)data;
2883         IMAPSession *session = stuff->session;
2884         FolderItem *item = stuff->item;
2885         MsgNumberList *numlist = stuff->numlist;
2886         GSList *newlist = NULL;
2887         GSList *llast = NULL;
2888         GSList *seq_list, *cur;
2889         gboolean got_alien_tags = FALSE;
2890
2891         debug_print("uncached_messages\n");
2892         
2893         if (session == NULL || item == NULL || item->folder == NULL
2894             || FOLDER_CLASS(item->folder) != &imap_class) {
2895                 stuff->done = TRUE;
2896                 return NULL;
2897         }
2898         
2899         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2900         debug_print("get msgs info\n");
2901         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2902                 struct mailimap_set * imapset;
2903                 unsigned int i;
2904                 int r;
2905                 carray * env_list;
2906                 int count;
2907                 
2908                 if (session->cancelled)
2909                         break;
2910                 
2911                 imapset = cur->data;
2912                 
2913                 r = imap_threaded_fetch_env(session->folder,
2914                                             imapset, &env_list);
2915                 if (r != MAILIMAP_NO_ERROR) {
2916                         imap_handle_error(SESSION(session), r);
2917                         if (is_fatal(r)) {
2918                                 stuff->ok = r;
2919                                 return NULL;
2920                         }
2921                         continue;
2922                 }
2923
2924                 session_set_access_time(SESSION(session));
2925
2926                 count = 0;
2927                 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
2928                         struct imap_fetch_env_info * info;
2929                         MsgInfo * msginfo;
2930                         GSList *tags = NULL, *cur = NULL;
2931                         info = carray_get(env_list, i);
2932                         tags = carray_get(env_list, i+1);
2933                         msginfo = imap_envelope_from_lep(info, item);
2934                         if (msginfo == NULL) {
2935                                 slist_free_strings(tags);
2936                                 g_slist_free(tags);
2937                                 continue;
2938                         }
2939                         if (tags != NULL) {
2940                                 g_slist_free(msginfo->tags);
2941                                 msginfo->tags = NULL;
2942                         }
2943                         for (cur = tags; cur; cur = cur->next) {
2944                                 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
2945                                 gint id = 0;
2946                                 id = tags_get_id_for_str(real_tag);
2947                                 if (id == -1) {
2948                                         id = tags_add_tag(real_tag);
2949                                         got_alien_tags = TRUE;
2950                                 }
2951                                 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
2952                                         msginfo->tags = g_slist_append(
2953                                                         msginfo->tags,
2954                                                         GINT_TO_POINTER(id));
2955                                 }
2956                                 g_free(real_tag);
2957                         }
2958                         slist_free_strings(tags);
2959                         g_slist_free(tags);
2960                         msginfo->folder = item;
2961                         if (!newlist)
2962                                 llast = newlist = g_slist_append(newlist, msginfo);
2963                         else {
2964                                 llast = g_slist_append(llast, msginfo);
2965                                 llast = llast->next;
2966                         }
2967                         count ++;
2968                 }
2969                 
2970                 imap_fetch_env_free(env_list);
2971         }
2972         
2973         if (got_alien_tags) {
2974                 tags_write_tags();
2975                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
2976         }
2977
2978         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2979                 struct mailimap_set * imapset;
2980                 
2981                 imapset = cur->data;
2982                 mailimap_set_free(imapset);
2983         }
2984         
2985         session_set_access_time(SESSION(session));
2986         stuff->done = TRUE;
2987         return newlist;
2988 }
2989
2990 #define MAX_MSG_NUM 50
2991
2992 static GSList *imap_get_uncached_messages(IMAPSession *session,
2993                                         FolderItem *item,
2994                                         MsgNumberList *numlist,
2995                                         int *r)
2996 {
2997         GSList *result = NULL;
2998         GSList * cur;
2999         uncached_data *data = g_new0(uncached_data, 1);
3000         int finished;
3001         
3002         finished = 0;
3003         cur = numlist;
3004         data->total = g_slist_length(numlist);
3005         data->ok = MAILIMAP_NO_ERROR;
3006         debug_print("messages list : %i\n", data->total);
3007
3008         while (cur != NULL) {
3009                 GSList * partial_result;
3010                 int count;
3011                 GSList * newlist;
3012                 GSList * llast;
3013                 
3014                 llast = NULL;
3015                 count = 0;
3016                 newlist = NULL;
3017                 while (count < MAX_MSG_NUM) {
3018                         void * p;
3019                         
3020                         p = cur->data;
3021                         
3022                         if (newlist == NULL)
3023                                 llast = newlist = g_slist_append(newlist, p);
3024                         else {
3025                                 llast = g_slist_append(llast, p);
3026                                 llast = llast->next;
3027                         }
3028                         count ++;
3029                         
3030                         cur = cur->next;
3031                         if (cur == NULL)
3032                                 break;
3033                 }
3034                 
3035                 data->done = FALSE;
3036                 data->session = session;
3037                 data->item = item;
3038                 data->numlist = newlist;
3039                 data->cur += count;
3040                 
3041                 if (prefs_common.work_offline && 
3042                     !inc_offline_should_override(FALSE,
3043                         _("Claws Mail needs network access in order "
3044                           "to access the IMAP server."))) {
3045                         g_free(data);
3046                         return NULL;
3047                 }
3048                 
3049                 partial_result =
3050                         (GSList *)imap_get_uncached_messages_thread(data);
3051                 *r = data->ok;
3052                 if (data->ok != MAILIMAP_NO_ERROR) {
3053                         goto bail;
3054                 }
3055                 statusbar_progress_all(data->cur,data->total, 1);
3056                 
3057                 g_slist_free(newlist);
3058                 
3059                 result = g_slist_concat(result, partial_result);
3060         }
3061 bail:
3062         g_free(data);
3063         
3064         statusbar_progress_all(0,0,0);
3065         statusbar_pop_all();
3066         
3067         return result;
3068 }
3069
3070 static void imap_delete_all_cached_messages(FolderItem *item)
3071 {
3072         gchar *dir;
3073
3074         g_return_if_fail(item != NULL);
3075         g_return_if_fail(item->folder != NULL);
3076         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3077
3078         debug_print("Deleting all cached messages...\n");
3079
3080         dir = folder_item_get_path(item);
3081         if (is_dir_exist(dir))
3082                 remove_all_numbered_files(dir);
3083         g_free(dir);
3084
3085         debug_print("done.\n");
3086 }
3087
3088 gchar imap_get_path_separator_for_item(FolderItem *item)
3089 {
3090         Folder *folder = NULL;
3091         IMAPFolder *imap_folder = NULL;
3092         IMAPSession *session = NULL;
3093         gchar result = '/';
3094         gint ok;
3095         if (!item)
3096                 return '/';
3097         folder = item->folder;
3098         
3099         if (!folder)
3100                 return '/';
3101         
3102         imap_folder = IMAP_FOLDER(folder);
3103         
3104         if (!imap_folder)
3105                 return '/';
3106         
3107         debug_print("getting session...");
3108         session = imap_session_get(FOLDER(folder));
3109         result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3110         return result;
3111 }
3112
3113 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3114 {
3115         clist * lep_list;
3116         int r;
3117         gchar separator = '\0';
3118         
3119         g_return_val_if_fail(session != NULL, '/');
3120         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3121         
3122         if (r != MAILIMAP_NO_ERROR) {
3123                 imap_handle_error(SESSION(session), r);
3124                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3125                 *ok = r;
3126                 return '\0';
3127         }
3128
3129         if (clist_count(lep_list) > 0) {
3130                 clistiter * iter = clist_begin(lep_list); 
3131                 struct mailimap_mailbox_list * mb;
3132                 mb = clist_content(iter);
3133
3134                 separator = mb->mb_delimiter;
3135                 debug_print("got separator: %c\n", folder->last_seen_separator);
3136         }
3137         *ok = MAILIMAP_NO_ERROR;
3138         mailimap_list_result_free(lep_list);
3139         return separator;
3140 }
3141
3142 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3143 {
3144         gchar separator = '/';
3145
3146         if (folder->last_seen_separator == 0) {
3147                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3148         }
3149
3150         if (folder->last_seen_separator == 0) {
3151                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3152         }
3153
3154         if (folder->last_seen_separator != 0) {
3155                 debug_print("using separator: %c\n", folder->last_seen_separator);
3156                 return folder->last_seen_separator;
3157         }
3158
3159         return separator;
3160 }
3161
3162 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3163 {
3164         gchar *real_path;
3165         gchar separator;
3166
3167         g_return_val_if_fail(folder != NULL, NULL);
3168         g_return_val_if_fail(path != NULL, NULL);
3169
3170         real_path = imap_utf8_to_modified_utf7(path, FALSE);
3171         separator = imap_get_path_separator(session, folder, path, ok);
3172         imap_path_separator_subst(real_path, separator);
3173
3174         return real_path;
3175 }
3176
3177 static gint imap_set_message_flags(IMAPSession *session,
3178                                    IMAPFolderItem *item,
3179                                    MsgNumberList *numlist,
3180                                    IMAPFlags flags,
3181                                    GSList *tags,
3182                                    gboolean is_set)
3183 {
3184         gint ok = 0;
3185         GSList *seq_list;
3186         GSList * cur;
3187         gint total = 0;
3188         IMAPFolder *folder = NULL;
3189         GSList *sorted_list = NULL;
3190
3191         if (numlist == NULL || session == NULL)
3192                 return MAILIMAP_ERROR_BAD_STATE;
3193         
3194         folder = IMAP_FOLDER(session->folder);
3195         
3196         sorted_list = g_slist_copy(numlist);
3197         sorted_list = g_slist_sort(sorted_list, g_int_compare);
3198         
3199         cur = g_slist_last(sorted_list);
3200
3201         if (cur)
3202                 total = GPOINTER_TO_INT(cur->data);
3203         
3204         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3205
3206         statusbar_print_all(_("Flagging messages..."));
3207
3208         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3209                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3210                 struct mailimap_set_item *set_item = clist_content(
3211                                                         clist_begin(imapset->set_list));
3212
3213                 statusbar_progress_all(set_item->set_first, total, 1);
3214
3215                 ok = imap_cmd_store(session, item, imapset,
3216                                     flags, tags, is_set);
3217                 statusbar_progress_all(set_item->set_last, total, 1);
3218                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3219                         /* reduce max set size */
3220                         folder->max_set_size /= 2;
3221                 }
3222                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3223                         break;
3224                 }
3225         }
3226         
3227         g_slist_free(sorted_list);
3228
3229         statusbar_progress_all(0,0,0);
3230         statusbar_pop_all();
3231
3232         imap_lep_set_free(seq_list);
3233         
3234         return ok;
3235 }
3236
3237 typedef struct _select_data {
3238         IMAPSession *session;
3239         gchar *real_path;
3240         gint *exists;
3241         gint *recent;
3242         gint *unseen;
3243         guint32 *uid_validity;
3244         gboolean done;
3245 } select_data;
3246
3247 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3248                         FolderItem *item,
3249                         gint *exists, gint *recent, gint *unseen,
3250                         guint32 *uid_validity, gint *can_create_flags,
3251                         gboolean block)
3252 {
3253         gchar *real_path;
3254         gint ok;
3255         gint exists_, recent_, unseen_;
3256         guint32 uid_validity_;
3257         gint can_create_flags_;
3258         const gchar *path = item ? item->path:NULL;
3259
3260         if (!item) {
3261                 return MAILIMAP_ERROR_BAD_STATE;
3262         }
3263
3264         if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3265                 if (session->mbox && strcmp(session->mbox, path) == 0)
3266                         return MAILIMAP_NO_ERROR;
3267         }
3268         if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3269                 if (session->mbox && strcmp(session->mbox, path) == 0) {
3270                         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3271                                 return MAILIMAP_NO_ERROR;
3272                 }
3273         }
3274         if (!exists)
3275                 exists = &exists_;
3276         if (!recent)
3277                 recent = &recent_;
3278         if (!unseen)
3279                 unseen = &unseen_;
3280         if (!uid_validity)
3281                 uid_validity = &uid_validity_;
3282         if (!can_create_flags)
3283                 can_create_flags = &can_create_flags_;
3284
3285         g_free(session->mbox);
3286         session->mbox = NULL;
3287         session->exists = 0;
3288         session->recent = 0;
3289         session->expunge = 0;
3290
3291         real_path = imap_get_real_path(session, folder, path, &ok);
3292         if (is_fatal(ok))
3293                 return ok;              
3294         g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3295         IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3296         ok = imap_cmd_select(session, real_path,
3297                              exists, recent, unseen, uid_validity, can_create_flags, 
3298                              &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3299         if (ok != MAILIMAP_NO_ERROR) {
3300                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3301         } else {
3302                 session->mbox = g_strdup(path);
3303                 session->folder_content_changed = FALSE;
3304                 session->exists = *exists;
3305                 session->recent = *recent;
3306                 session->expunge = 0;
3307                 session->unseen = *unseen;
3308                 session->uid_validity = *uid_validity;
3309                 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
3310                         session->exists, session->recent, session->expunge,
3311                         session->uid_validity, *can_create_flags);
3312         }
3313         if (*can_create_flags) {
3314                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3315         } else {
3316                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3317         }
3318         g_free(real_path);
3319
3320         return ok;
3321 }
3322
3323 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3324                         const gchar *path, IMAPFolderItem *item,
3325                         gint *messages,
3326                         guint32 *uid_next, guint32 *uid_validity,
3327                         gint *unseen, gboolean block)
3328 {
3329         int r;
3330         clis