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