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