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