revert last commit, it's not needed
[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                 result = folder_item_search_msgs_local(folder, container, msgs,                             NULL, predicate, progress_cb, progress_data);
2502                 if (result < 0) {
2503                         debug_print("search_msgs - got protocol error, aborting\n");
2504                         alertpanel_error_log(_("Search failed due to server error."));
2505                         return -1;
2506                 }
2507
2508                 return result;
2509         } if (result == MAILIMAP_NO_ERROR) {
2510                 gint result = 0;
2511
2512                 *msgs = imap_uid_list_from_lep(uidlist, &result);
2513
2514                 mailimap_search_result_free(uidlist);
2515
2516                 if (charset_to_use != NULL)
2517                         g_free(charset_to_use);
2518
2519                 return result;
2520         } else if (charset_to_use != NULL) {
2521                 /* If search failed and was on an 8-bit string, try the next
2522                  * available charset to search if there still are some.
2523                  */
2524                 g_free(charset_to_use);
2525                 
2526                 imap_change_search_charset(IMAP_FOLDER(folder));
2527                 if (IMAP_FOLDER(folder)->search_charset_supported)
2528                         return search_msgs(folder, container, msgs, on_server, predicate,
2529                                    progress_cb, progress_data);
2530                 else {
2531                         imap_handle_error(SESSION(session), NULL, result);
2532                         return -1;
2533                 }
2534         } else {
2535                 imap_handle_error(SESSION(session), NULL, result);
2536                 return -1;
2537         }
2538 }
2539
2540
2541 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
2542                                 MsgInfoList *msglist, GHashTable *relation)
2543 {
2544         gchar *destdir, *dir;
2545         GSList *numlist = NULL, *cur;
2546         MsgInfo *msginfo;
2547         IMAPSession *session;
2548         gint ok = MAILIMAP_NO_ERROR;
2549         
2550         g_return_val_if_fail(folder != NULL, -1);
2551         g_return_val_if_fail(dest != NULL, -1);
2552         g_return_val_if_fail(msglist != NULL, -1);
2553
2554         debug_print("getting session...\n");
2555         session = imap_session_get(folder);
2556         if (!session) {
2557                 return -1;
2558         }
2559
2560         lock_session(session); /* unlocked later in the function */
2561
2562         msginfo = (MsgInfo *)msglist->data;
2563
2564         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2565                          NULL, NULL, NULL, NULL, NULL, FALSE);
2566         if (ok != MAILIMAP_NO_ERROR) {
2567                 return ok;
2568         }
2569
2570         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2571         if (is_fatal(ok)) {
2572                 g_free(destdir);
2573                 return ok;
2574         }
2575         for (cur = msglist; cur; cur = cur->next) {
2576                 msginfo = (MsgInfo *)cur->data;
2577                 if (!MSG_IS_DELETED(msginfo->flags))
2578                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2579         }
2580         numlist = g_slist_reverse(numlist);
2581
2582         if (numlist != NULL) {
2583                 ok = imap_set_message_flags
2584                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2585                 if (ok != MAILIMAP_NO_ERROR) {
2586                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2587                         g_free(destdir);
2588                         return ok;
2589                 }
2590         } /* else we just need to expunge */
2591         ok = imap_cmd_expunge(session);
2592         if (ok != MAILIMAP_NO_ERROR) {
2593                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2594                 g_free(destdir);
2595                 return ok;
2596         }
2597         
2598         session->folder_content_changed = TRUE;
2599         unlock_session(session);
2600
2601         dir = folder_item_get_path(msginfo->folder);
2602         if (is_dir_exist(dir)) {
2603                 for (cur = msglist; cur; cur = cur->next) {
2604                         msginfo = (MsgInfo *)cur->data;
2605                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2606                 }
2607         }
2608         g_free(dir);
2609
2610         g_slist_free(numlist);
2611
2612         imap_scan_required(folder, dest);
2613
2614         g_free(destdir);
2615
2616         return 0;
2617 }
2618
2619 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2620                     MsgInfoList *msglist, GHashTable *relation)
2621 {
2622         MsgInfo *msginfo;
2623
2624         g_return_val_if_fail(folder != NULL, -1);
2625         g_return_val_if_fail(dest != NULL, -1);
2626         if (msglist == NULL)
2627                 return 0;
2628
2629         msginfo = (MsgInfo *)msglist->data;
2630         g_return_val_if_fail(msginfo->folder != NULL, -1);
2631
2632         return imap_do_remove_msgs(folder, dest, msglist, relation);
2633 }
2634
2635 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2636 {
2637         GSList *list = folder_item_get_msg_list(item);
2638         gint res = imap_remove_msgs(folder, item, list, NULL);
2639         procmsg_msg_list_free(list);
2640         return res;
2641 }
2642
2643 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2644                                     MsgInfo *msginfo)
2645 {
2646         /* TODO: properly implement this method */
2647         return FALSE;
2648 }
2649
2650 static gint imap_close(Folder *folder, FolderItem *item)
2651 {
2652         return 0;
2653 }
2654
2655 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2656 {
2657         FolderItem *item = NULL;
2658         IMAPSession *session;
2659         gchar *root_folder = NULL;
2660
2661         g_return_val_if_fail(folder != NULL, -1);
2662         g_return_val_if_fail(folder->account != NULL, -1);
2663
2664         debug_print("getting session...\n");
2665         session = imap_session_get(folder);
2666         if (!session) {
2667                 if (!folder->node) {
2668                         folder_tree_destroy(folder);
2669                         item = folder_item_new(folder, folder->name, NULL);
2670                         item->folder = folder;
2671                         folder->node = item->node = g_node_new(item);
2672                 }
2673                 return -1;
2674         }
2675
2676         if (folder->account->imap_dir && *folder->account->imap_dir) {
2677                 gchar *real_path;
2678                 int r = MAILIMAP_NO_ERROR;
2679                 clist * lep_list;
2680
2681                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2682                 extract_quote(root_folder, '"');
2683                 subst_char(root_folder,
2684                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2685                                                    root_folder, &r),
2686                            '/');
2687                 if (is_fatal(r))
2688                         return -1;
2689                 strtailchomp(root_folder, '/');
2690                 real_path = imap_get_real_path
2691                         (session, IMAP_FOLDER(folder), root_folder, &r);
2692                 if (is_fatal(r)) {
2693                         g_free(real_path);
2694                         return -1;
2695                 }
2696                 debug_print("IMAP root directory: %s\n", real_path);
2697
2698                 /* check if root directory exist */
2699
2700                 r = imap_threaded_list(session->folder, "", real_path,
2701                                        &lep_list);
2702
2703                 if (r != MAILIMAP_NO_ERROR)
2704                         imap_handle_error(SESSION(session), NULL, r);
2705
2706                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2707                         if (!folder->node) {
2708                                 item = folder_item_new(folder, folder->name, NULL);
2709                                 item->folder = folder;
2710                                 folder->node = item->node = g_node_new(item);
2711                         }
2712                         return -1;
2713                 }
2714                 mailimap_list_result_free(lep_list);
2715                                 
2716                 g_free(real_path);
2717         }
2718
2719         if (folder->node)
2720                 item = FOLDER_ITEM(folder->node->data);
2721                 
2722         if (item && !item->path && root_folder) {
2723                 item->path = g_strdup(root_folder);
2724         }
2725
2726         if (!item || ((item->path || root_folder) &&
2727                       g_strcmp0(item->path, root_folder) != 0)) {
2728                 folder_tree_destroy(folder);
2729                 item = folder_item_new(folder, folder->name, root_folder);
2730                 item->folder = folder;
2731                 folder->node = item->node = g_node_new(item);
2732         }
2733
2734         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2735         imap_create_missing_folders(folder);
2736
2737         return 0;
2738 }
2739
2740 static gint imap_scan_tree(Folder *folder)
2741 {
2742         gboolean subs_only = FALSE;
2743         if (folder->account) {
2744                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2745                 subs_only = folder->account->imap_subsonly;
2746         }
2747         return imap_scan_tree_real(folder, subs_only);
2748 }
2749
2750 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2751 {
2752         Folder *folder;
2753         IMAPFolder *imapfolder;
2754         FolderItem *new_item;
2755         GSList *item_list, *cur;
2756         GNode *node;
2757         gchar *real_path;
2758         gchar *wildcard_path;
2759         gchar separator;
2760         gchar wildcard[3];
2761         clist * lep_list;
2762         int r = MAILIMAP_NO_ERROR;
2763         
2764         g_return_val_if_fail(item != NULL, -1);
2765         g_return_val_if_fail(item->folder != NULL, -1);
2766         g_return_val_if_fail(item->no_sub == FALSE, -1);
2767
2768         folder = item->folder;
2769         imapfolder = IMAP_FOLDER(folder);
2770
2771         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2772         if (is_fatal(r))
2773                 return r;
2774
2775         if (folder->ui_func)
2776                 folder->ui_func(folder, item, folder->ui_func_data);
2777
2778         if (item->path) {
2779                 wildcard[0] = separator;
2780                 wildcard[1] = '%';
2781                 wildcard[2] = '\0';
2782                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2783                 if (is_fatal(r)) {
2784                         g_free(real_path);
2785                         return r;
2786                 }
2787         } else {
2788                 wildcard[0] = '%';
2789                 wildcard[1] = '\0';
2790                 real_path = g_strdup("");
2791         }
2792
2793         Xstrcat_a(wildcard_path, real_path, wildcard,
2794                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2795         lep_list = NULL;
2796         
2797         if (subs_only)
2798                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2799         else
2800                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2801
2802         if (r != MAILIMAP_NO_ERROR) {
2803                 imap_handle_error(SESSION(session), NULL, r);
2804                 item_list = NULL;
2805                 g_free(real_path);
2806                 return r;
2807         }
2808         else {
2809                 item_list = imap_list_from_lep(imapfolder,
2810                                                lep_list, real_path, FALSE);
2811                 mailimap_list_result_free(lep_list);
2812         }
2813         
2814         g_free(real_path);
2815
2816         node = item->node->children;
2817         while (node != NULL) {
2818                 FolderItem *old_item = FOLDER_ITEM(node->data);
2819                 GNode *next = node->next;
2820
2821                 new_item = NULL;
2822                 for (cur = item_list; cur != NULL; cur = cur->next) {
2823                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2824                         if (!g_strcmp0(old_item->path, cur_item->path)) {
2825                                 new_item = cur_item;
2826                                 break;
2827                         }
2828                 }
2829                 if (!new_item) {
2830                         if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2831                                 debug_print("not removing INBOX\n");
2832                         } else {
2833                                 debug_print("folder '%s' not found. removing...\n",
2834                                             old_item->path);
2835                                 folder_item_remove(old_item);
2836                         }
2837                 } else {
2838                         old_item->no_sub = new_item->no_sub;
2839                         old_item->no_select = new_item->no_select;
2840                         if (old_item->no_sub == TRUE && node->children) {
2841                                 debug_print("folder '%s' doesn't have "
2842                                             "subfolders. removing...\n",
2843                                             old_item->path);
2844                                 folder_item_remove_children(old_item);
2845                         }
2846                 }
2847
2848                 node = next;
2849         }
2850
2851         for (cur = item_list; cur != NULL; cur = cur->next) {
2852                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2853                 new_item = NULL;
2854
2855                 for (node = item->node->children; node != NULL;
2856                      node = node->next) {
2857                         if (!g_strcmp0(FOLDER_ITEM(node->data)->path,
2858                                      cur_item->path)) {
2859                                 new_item = FOLDER_ITEM(node->data);
2860                                 folder_item_destroy(cur_item);
2861                                 cur_item = NULL;
2862                                 break;
2863                         }
2864                 }
2865                 if (!new_item) {
2866                         new_item = cur_item;
2867                         debug_print("new folder '%s' found.\n", new_item->path);
2868                         folder_item_append(item, new_item);
2869                 }
2870
2871                 if (!strcasecmp(new_item->path, "INBOX")) {
2872                         new_item->stype = F_INBOX;
2873                         folder->inbox = new_item;
2874                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2875                         gchar *base;
2876
2877                         base = g_path_get_basename(new_item->path);
2878
2879                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2880                                 new_item->stype = F_OUTBOX;
2881                                 folder->outbox = new_item;
2882                         } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2883                                 new_item->stype = F_DRAFT;
2884                                 folder->draft = new_item;
2885                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2886                                 new_item->stype = F_QUEUE;
2887                                 folder->queue = new_item;
2888                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2889                                 new_item->stype = F_TRASH;
2890                                 folder->trash = new_item;
2891                         }
2892                         g_free(base);
2893                 }
2894
2895                 if (new_item->no_sub == FALSE)
2896                         imap_scan_tree_recursive(session, new_item, subs_only);
2897         }
2898
2899         g_slist_free(item_list);
2900
2901         return MAILIMAP_NO_ERROR;
2902 }
2903
2904 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2905 {
2906         IMAPSession *session = imap_session_get(folder);
2907         gchar *real_path;
2908         gchar *wildcard_path;
2909         gchar separator;
2910         gchar wildcard[3];
2911         clist * lep_list;
2912         GSList *item_list = NULL, *cur;
2913         GList *child_list = NULL, *tmplist = NULL;
2914         GSList *sub_list = NULL;
2915         int r = MAILIMAP_NO_ERROR;
2916
2917         if (!session)
2918                 return NULL;
2919
2920         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2921         if (is_fatal(r))
2922                 return NULL;
2923
2924         if (item->path) {
2925                 wildcard[0] = separator;
2926                 wildcard[1] = '%';
2927                 wildcard[2] = '\0';
2928                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2929                 if (is_fatal(r)) {
2930                         g_free(real_path);
2931                         return NULL;
2932                 }
2933         } else {
2934                 wildcard[0] = '%';
2935                 wildcard[1] = '\0';
2936                 real_path = g_strdup("");
2937         }
2938
2939         Xstrcat_a(wildcard_path, real_path, wildcard,
2940                   {g_free(real_path); return NULL;});
2941         lep_list = NULL;
2942         
2943         if (unsubs_only)
2944                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2945                                 item->path?item->path:item->name);
2946         else
2947                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2948                                 item->path?item->path:item->name);
2949
2950         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2951         if (r) {
2952                 g_free(real_path);
2953                 statusbar_pop_all();
2954                 return NULL;
2955         }
2956         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2957                                lep_list, real_path, FALSE);
2958         mailimap_list_result_free(lep_list);
2959
2960         for (cur = item_list; cur != NULL; cur = cur->next) {
2961                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2962                 if (recursive) {
2963                         tmplist = imap_scan_subtree(folder, cur_item, 
2964                                         unsubs_only, recursive);
2965                         if (tmplist)
2966                                 child_list = g_list_concat(child_list, tmplist);
2967                 }
2968                 child_list = g_list_prepend(child_list,
2969                                 imap_get_real_path(session, 
2970                                         IMAP_FOLDER(folder), cur_item->path, &r));
2971                 if (is_fatal(r)) {
2972                         g_free(real_path);
2973                         statusbar_pop_all();
2974                         return NULL;
2975                 }
2976                 folder_item_destroy(cur_item);
2977         }
2978         child_list = g_list_reverse(child_list);
2979         g_slist_free(item_list);
2980
2981         if (unsubs_only) {
2982                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2983                 if (r) {
2984                         g_free(real_path);
2985                         statusbar_pop_all();
2986                         return NULL;
2987                 }
2988                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2989                                        lep_list, real_path, FALSE);
2990                 mailimap_list_result_free(lep_list);
2991
2992                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2993                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2994                         GList *oldlitem = NULL;
2995                         gchar *tmp = imap_get_real_path(session, 
2996                                         IMAP_FOLDER(folder), cur_item->path, &r);
2997                         if (r) {
2998                                 g_free(real_path);
2999                                 statusbar_pop_all();
3000                                 g_free(tmp);
3001                                 return NULL;
3002                         }
3003                         folder_item_destroy(cur_item);
3004                         oldlitem = g_list_find_custom(
3005                                         child_list, tmp, (GCompareFunc)g_strcmp0);
3006                         if (oldlitem) {
3007                                 child_list = g_list_remove_link(child_list, oldlitem);
3008                                 g_free(oldlitem->data);
3009                                 g_list_free(oldlitem);
3010                         }
3011                         g_free(tmp);
3012                 }
3013         }
3014
3015         g_free(real_path);
3016         statusbar_pop_all();
3017
3018         return child_list;
3019 }
3020
3021 static gint imap_create_tree(Folder *folder)
3022 {
3023         g_return_val_if_fail(folder != NULL, -1);
3024         g_return_val_if_fail(folder->node != NULL, -1);
3025         g_return_val_if_fail(folder->node->data != NULL, -1);
3026         g_return_val_if_fail(folder->account != NULL, -1);
3027
3028         imap_scan_tree(folder);
3029         imap_create_missing_folders(folder);
3030
3031         return 0;
3032 }
3033
3034 static void imap_create_missing_folders(Folder *folder)
3035 {
3036         g_return_if_fail(folder != NULL);
3037
3038         if (!folder->inbox)
3039                 folder->inbox = imap_create_special_folder
3040                         (folder, F_INBOX, "INBOX");
3041         if (!folder->trash)
3042                 folder->trash = imap_create_special_folder
3043                         (folder, F_TRASH, "Trash");
3044         if (!folder->queue)
3045                 folder->queue = imap_create_special_folder
3046                         (folder, F_QUEUE, "Queue");
3047         if (!folder->outbox)
3048                 folder->outbox = imap_create_special_folder
3049                         (folder, F_OUTBOX, "Sent");
3050         if (!folder->draft)
3051                 folder->draft = imap_create_special_folder
3052                         (folder, F_DRAFT, "Drafts");
3053 }
3054
3055 static FolderItem *imap_create_special_folder(Folder *folder,
3056                                               SpecialFolderItemType stype,
3057                                               const gchar *name)
3058 {
3059         FolderItem *item;
3060         FolderItem *new_item;
3061
3062         g_return_val_if_fail(folder != NULL, NULL);
3063         g_return_val_if_fail(folder->node != NULL, NULL);
3064         g_return_val_if_fail(folder->node->data != NULL, NULL);
3065         g_return_val_if_fail(folder->account != NULL, NULL);
3066         g_return_val_if_fail(name != NULL, NULL);
3067
3068         item = FOLDER_ITEM(folder->node->data);
3069         new_item = imap_create_folder(folder, item, name);
3070
3071         if (!new_item) {
3072                 g_warning("Can't create '%s'", name);
3073                 if (!folder->inbox) return NULL;
3074
3075                 new_item = imap_create_folder(folder, folder->inbox, name);
3076                 if (!new_item)
3077                         g_warning("Can't create '%s' under INBOX", name);
3078                 else
3079                         new_item->stype = stype;
3080         } else
3081                 new_item->stype = stype;
3082
3083         return new_item;
3084 }
3085
3086 #ifdef G_OS_WIN32
3087 static gchar *imap_encode_unsafe_chars(const gchar *str)
3088 {
3089         gchar *ret = NULL, *o_ret;
3090         gchar *i;
3091         if (!str) 
3092                 return NULL;
3093         ret = g_malloc(3*strlen(str)+1);
3094         o_ret = ret;
3095         for (i = (gchar *)str; *i; i++) {
3096                 switch(*i) {
3097                         case ':':
3098                         case '|':
3099                         case '<':
3100                         case '>':
3101                         case '*':
3102                         case '?':
3103                         case '#':
3104                                 *ret++ = '%';
3105                                 *ret++ = '0'+(*i/10);
3106                                 *ret++ = '0'+(*i%10);
3107                                 break;
3108                         default:
3109                                 *ret++ = *i;
3110                 }
3111         }
3112         *ret++ = '\0';
3113         return o_ret;
3114 }
3115 #endif
3116 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3117 {
3118         gchar *folder_path, *path;
3119         gchar *item_path = NULL;
3120         
3121         g_return_val_if_fail(folder != NULL, NULL);
3122         g_return_val_if_fail(folder->account != NULL, NULL);
3123         g_return_val_if_fail(item != NULL, NULL);
3124         folder_path = prefs_account_cache_dir(folder->account, FALSE);
3125
3126         g_return_val_if_fail(folder_path != NULL, NULL);
3127
3128 #ifdef G_OS_UNIX
3129         item_path = g_strdup(item->path);
3130 #else
3131         item_path = imap_encode_unsafe_chars(item->path);
3132 #endif  
3133
3134         if (g_path_is_absolute(folder_path)) {
3135                 if (item_path)
3136                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3137                                            item_path, NULL);
3138                 else
3139                         path = g_strdup(folder_path);
3140         } else {
3141                 if (item_path)
3142                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3143                                            folder_path, G_DIR_SEPARATOR_S,
3144                                            item_path, NULL);
3145                 else
3146                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3147                                            folder_path, NULL);
3148         }
3149         g_free(folder_path);
3150         g_free(item_path);
3151 #ifdef G_OS_WIN32
3152         while (strchr(path, '/'))
3153                 *strchr(path, '/') = '\\';
3154 #endif
3155
3156         return path;
3157 }
3158
3159 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3160                                const gchar *name)
3161 {
3162         gchar *dirpath, *imap_path;
3163         IMAPSession *session;
3164         FolderItem *new_item;
3165         gchar separator;
3166         gchar *new_name;
3167         const gchar *p;
3168         gint ok = MAILIMAP_NO_ERROR;
3169         gboolean no_select = FALSE, no_sub = FALSE;
3170         gboolean exist = FALSE;
3171         
3172         g_return_val_if_fail(folder != NULL, NULL);
3173         g_return_val_if_fail(folder->account != NULL, NULL);
3174         g_return_val_if_fail(parent != NULL, NULL);
3175         g_return_val_if_fail(name != NULL, NULL);
3176
3177         if (to_number(name) > 0) {
3178                 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3179                 if (is_file_exist(cached_msg)) {
3180                         if (claws_unlink(cached_msg) != 0) {
3181                                 return NULL;
3182                         }
3183                 }
3184         }
3185
3186         debug_print("getting session...\n");
3187         session = imap_session_get(folder);
3188         if (!session) {
3189                 return NULL;
3190         }
3191
3192         if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3193                 dirpath = g_strdup(name);
3194         }else if (parent->path)
3195                 dirpath = g_strconcat(parent->path, "/", name, NULL);
3196         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3197                 dirpath = g_strdup(name);
3198         else if (folder->account->imap_dir && *folder->account->imap_dir) {
3199                 gchar *imap_dir;
3200
3201                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3202                 strtailchomp(imap_dir, '/');
3203                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3204         } else
3205                 dirpath = g_strdup(name);
3206                 
3207         
3208
3209         /* keep trailing directory separator to create a folder that contains
3210            sub folder */
3211         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3212
3213         strtailchomp(dirpath, '/');
3214         Xstrdup_a(new_name, name, {
3215                 g_free(dirpath); 
3216                 g_free(imap_path);
3217                 return NULL;});
3218
3219         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3220         if (is_fatal(ok)) {
3221                 g_free(imap_path);
3222                 return NULL;
3223         }
3224         imap_path_separator_subst(imap_path, separator);
3225         /* remove trailing / for display */
3226         strtailchomp(new_name, '/');
3227
3228         if (strcasecmp(dirpath, "INBOX") != 0) {
3229                 int r;
3230                 clist * lep_list;
3231                 
3232                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3233                 if (r != MAILIMAP_NO_ERROR) {
3234                         imap_handle_error(SESSION(session), NULL, r);
3235                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3236                         g_free(imap_path);
3237                         g_free(dirpath);
3238                         return NULL;
3239                 }
3240                 
3241                 if (clist_count(lep_list) > 0)
3242                         exist = TRUE;
3243                 mailimap_list_result_free(lep_list);
3244                 lep_list = NULL;
3245                 if (!exist) {
3246                         ok = imap_cmd_create(session, imap_path);
3247                         if (ok != MAILIMAP_NO_ERROR) {
3248                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3249                                 g_free(imap_path);
3250                                 g_free(dirpath);
3251                                 return NULL;
3252                         }
3253                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
3254                         if (r == MAILIMAP_NO_ERROR) {
3255                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3256                                                lep_list, dirpath, TRUE);
3257                                 if (item_list) {
3258                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3259                                         no_select = cur_item->no_select;
3260                                         no_sub = cur_item->no_sub;
3261                                         g_slist_free(item_list);
3262                                 } 
3263                                 mailimap_list_result_free(lep_list);
3264                         } else {
3265                                 imap_handle_error(SESSION(session), NULL, r);
3266