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