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