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