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