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