in the UI replace 'POP3' with 'POP' and 'IMAP4' with 'IMAP'
[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                         g_free(acc_pass);
1327                         memset(acc_pass, 0, strlen(acc_pass));
1328                 }
1329
1330                 return ok;
1331         } 
1332
1333         if (acc_pass) {
1334                 memset(acc_pass, 0, strlen(acc_pass));
1335                 g_free(acc_pass);
1336         }
1337         statuswindow_pop_all();
1338         session->authenticated = TRUE;
1339         return MAILIMAP_NO_ERROR;
1340 }
1341
1342 static void imap_session_destroy(Session *session)
1343 {
1344         if (session->state != SESSION_DISCONNECTED)
1345                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1346         
1347         imap_free_capabilities(IMAP_SESSION(session));
1348         g_free(IMAP_SESSION(session)->mbox);
1349 }
1350
1351 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1352 {
1353         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1354 }
1355
1356 static guint get_file_size_with_crs(const gchar *filename) 
1357 {
1358         FILE *fp = NULL;
1359         guint cnt = 0;
1360         gchar buf[4096];
1361         
1362         if (filename == NULL)
1363                 return -1;
1364         
1365         fp = g_fopen(filename, "rb");
1366         if (!fp)
1367                 return -1;
1368         
1369         while (fgets(buf, sizeof (buf), fp) != NULL) {
1370                 cnt += strlen(buf);
1371                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1372                         cnt++;
1373         }
1374         
1375         fclose(fp);
1376         return cnt;
1377 }
1378
1379 static gchar *imap_get_cached_filename(FolderItem *item, guint msgnum)
1380 {
1381         gchar *path, *filename;
1382
1383         cm_return_val_if_fail(item != NULL, NULL);
1384
1385         path = folder_item_get_path(item);
1386
1387         if (!is_dir_exist(path)) {
1388                 g_free(path);
1389                 return NULL;
1390         }
1391
1392         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
1393
1394         if (is_dir_exist(filename)) {
1395                 g_free(filename);
1396                 filename = g_strconcat(path, G_DIR_SEPARATOR_S, ".", itos(msgnum), NULL);
1397         }
1398         g_free(path);
1399
1400         return filename;
1401 }
1402
1403 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1404 {
1405         gchar *filename;
1406
1407         filename = imap_get_cached_filename(item, msginfo->msgnum);
1408
1409         cm_return_if_fail(filename != NULL);
1410
1411         if (is_file_exist(filename)) {
1412                 claws_unlink(filename);
1413         }
1414         g_free(filename);
1415 }
1416
1417 typedef struct _TagsData {
1418         gchar *str;
1419         GSList *msglist;
1420         IMAPFolderItem *item;
1421 } TagsData;
1422
1423 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1424 {
1425         IMAPSession *session;
1426         gint ok, can_create_tags;
1427         Folder *folder = NULL;
1428         TagsData *ht_data = NULL;
1429         GSList *cur;
1430
1431         g_return_if_fail(item != NULL);
1432         g_return_if_fail(msginfo != NULL);
1433
1434         folder = item->folder;
1435         debug_print("getting session...\n");
1436         session = imap_session_get(folder);
1437         
1438         if (!session) {
1439                 debug_print("can't get session\n");
1440                 return;
1441         }
1442
1443         ok = imap_select(session, IMAP_FOLDER(folder), item,
1444                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1445
1446         if (ok != MAILIMAP_NO_ERROR) {
1447                 return;
1448         }
1449
1450         
1451         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1452                 return;
1453         
1454         if (IMAP_FOLDER_ITEM(item)->batching) {
1455                 /* instead of performing an UID STORE command for each message change,
1456                  * as a lot of them can change "together", we just fill in hashtables
1457                  * and defer the treatment so that we're able to send only one
1458                  * command.
1459                  */
1460                 debug_print("IMAP batch mode on, deferring tags change\n");
1461                 for (cur = tags_set; cur; cur = cur->next) {
1462                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1463                         if (cur_tag) {
1464                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1465                                         GINT_TO_POINTER(cur_tag));
1466                                 if (ht_data == NULL) {
1467                                         ht_data = g_new0(TagsData, 1);
1468                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1469                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1470                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1471                                                 GINT_TO_POINTER(cur_tag), ht_data);
1472                                 }
1473                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1474                         } 
1475                 }
1476                 for (cur = tags_unset; cur; cur = cur->next) {
1477                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1478                         if (cur_tag) {
1479                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1480                                         GINT_TO_POINTER(cur_tag));
1481                                 if (ht_data == NULL) {
1482                                         ht_data = g_new0(TagsData, 1);
1483                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1484                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1485                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1486                                                 GINT_TO_POINTER(cur_tag), ht_data);
1487                                 }
1488                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1489                         }
1490                 }
1491         } else {
1492                 GSList *list_set = NULL;
1493                 GSList *list_unset = NULL;
1494                 GSList numlist;
1495                 
1496                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1497                 numlist.next = NULL;
1498         
1499                 debug_print("IMAP changing tags NOW\n");
1500                 for (cur = tags_set; cur; cur = cur->next) {
1501                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1502                         const gchar *str = tags_get_tag(cur_tag);
1503                         if (IS_NOT_RESERVED_TAG(str))
1504                                 list_set = g_slist_prepend(list_set, g_strdup(str));
1505                 }
1506                 if (list_set) {
1507                         ok = imap_set_message_flags(session, 
1508                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1509                         slist_free_strings_full(list_set);
1510                         if (ok != MAILIMAP_NO_ERROR) {
1511                                 return;
1512                         }
1513                 }
1514
1515                 for (cur = tags_unset; cur; cur = cur->next) {
1516                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1517                         const gchar *str = tags_get_tag(cur_tag);
1518                         if (IS_NOT_RESERVED_TAG(str))
1519                                 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1520                 }
1521                 if (list_unset) {
1522                         ok = imap_set_message_flags(session, 
1523                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1524                         slist_free_strings_full(list_unset);
1525                         if (ok != MAILIMAP_NO_ERROR) {
1526                                 return;
1527                         }
1528                 }
1529         }
1530 }
1531
1532 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1533                                   gboolean headers, gboolean body)
1534 {
1535         gchar *path, *filename;
1536         IMAPSession *session;
1537         gint ok;
1538
1539         g_return_val_if_fail(folder != NULL, NULL);
1540         g_return_val_if_fail(item != NULL, NULL);
1541
1542         if (uid == 0)
1543                 return NULL;
1544
1545         path = folder_item_get_path(item);
1546         if (!is_dir_exist(path)) {
1547                 if(is_file_exist(path))
1548                         claws_unlink(path);
1549                 make_dir_hier(path);
1550         }
1551         g_free(path);
1552
1553         filename = imap_get_cached_filename(item, uid);
1554         debug_print("trying to fetch cached %s\n", filename);
1555
1556         if (is_file_exist(filename)) {
1557                 /* see whether the local file represents the whole message
1558                  * or not. As the IMAP server reports size with \r chars,
1559                  * we have to update the local file (UNIX \n only) size */
1560                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1561                 guint have_size = -1;
1562
1563                 if (cached)
1564                         debug_print("message %d has been already %scached.\n", uid,
1565                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1566                 
1567                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1568                         have_size = get_file_size_with_crs(filename);
1569                         if (cached && (cached->size <= have_size || !body)) {
1570                                 ok = file_strip_crs(filename);
1571                                 if (ok == 0 && cached && cached->size <= have_size) {
1572                                         /* we have it all and stripped */
1573                                         debug_print("...fully cached in fact (%u/%zd); setting flag.\n",
1574                                                         have_size, cached->size);
1575                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1576                                 }
1577                                 procmsg_msginfo_free(&cached);
1578                                 return filename;
1579                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1580                                 debug_print("message not cached and file recent, considering file complete\n");
1581                                 ok = file_strip_crs(filename);
1582                                 if (ok == 0)
1583                                         return filename;
1584                         } else {
1585                                 procmsg_msginfo_free(&cached);
1586                         }
1587                 }
1588                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1589                         procmsg_msginfo_free(&cached);
1590                         return filename;
1591                 }
1592         } else {
1593                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1594                 if (cached) {
1595                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1596                         procmsg_msginfo_free(&cached);
1597                 }
1598         }
1599
1600         debug_print("getting session...\n");
1601         session = imap_session_get(folder);
1602         
1603         if (!session) {
1604                 g_free(filename);
1605                 return NULL;
1606         }
1607         session_set_access_time(SESSION(session));
1608         lock_session(session); /* unlocked later in the function */
1609
1610         debug_print("IMAP fetching messages\n");
1611         ok = imap_select(session, IMAP_FOLDER(folder), item,
1612                          NULL, NULL, NULL, NULL, NULL, FALSE);
1613         if (ok != MAILIMAP_NO_ERROR) {
1614                 g_warning("can't select mailbox %s", item->path);
1615                 g_free(filename);
1616                 return NULL;
1617         }
1618
1619         session_set_access_time(SESSION(session));
1620
1621         debug_print("getting message %d...\n", uid);
1622         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1623
1624         if (ok != MAILIMAP_NO_ERROR) {
1625                 g_warning("can't fetch message %d", uid);
1626                 g_free(filename);
1627                 return NULL;
1628         }
1629
1630         session_set_access_time(SESSION(session));
1631         unlock_session(session);
1632
1633         ok = file_strip_crs(filename);
1634
1635         if (ok == 0 && headers && body) {
1636                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1637                 if (cached) {
1638                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1639                         procmsg_msginfo_free(&cached);
1640                 }
1641         } else if (ok == -1) {
1642                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1643                 if (cached) {
1644                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1645                         procmsg_msginfo_free(&cached);
1646                 }
1647         }
1648         return filename;
1649 }
1650
1651 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1652 {
1653         gchar *filename;
1654         guint size = 0;
1655         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1656         
1657         if (!cached)
1658                 return FALSE;
1659
1660         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1661                 procmsg_msginfo_free(&cached);
1662                 return TRUE;
1663         }
1664
1665         filename = imap_get_cached_filename(item, uid);
1666
1667         if (is_file_exist(filename)) {
1668                 if (cached && cached->total_size == cached->size) {
1669                         /* fast path */
1670                         g_free(filename);
1671                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1672                         return TRUE;
1673                 }
1674                 size = get_file_size_with_crs(filename);
1675         }
1676         g_free(filename);
1677         debug_print("msg %d cached, has size %d, full should be %zd.\n", uid, size, cached->size);
1678         if (cached && size >= cached->size) {
1679                 cached->total_size = cached->size;
1680                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1681                 procmsg_msginfo_free(&cached);
1682                 return TRUE;
1683         }
1684         if (cached)
1685                 procmsg_msginfo_free(&cached);
1686         return FALSE;   
1687 }
1688
1689 void imap_cache_msg(FolderItem *item, gint msgnum)
1690 {
1691         Folder *folder = NULL;
1692         
1693         if (!item)
1694                 return;
1695         folder = item->folder;
1696         
1697         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1698                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1699                 debug_print("fetched %s\n", tmp);
1700                 g_free(tmp);
1701         }
1702 }
1703
1704 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1705                          const gchar *file, MsgFlags *flags)
1706 {
1707         gint ret;
1708         GSList file_list;
1709         MsgFileInfo fileinfo;
1710
1711         g_return_val_if_fail(file != NULL, -1);
1712
1713         fileinfo.msginfo = NULL;
1714         fileinfo.file = (gchar *)file;
1715         fileinfo.flags = flags;
1716         file_list.data = &fileinfo;
1717         file_list.next = NULL;
1718
1719         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1720         return ret;
1721 }
1722
1723 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1724                    GHashTable *relation)
1725 {
1726         gchar *destdir;
1727         IMAPSession *session;
1728         guint32 last_uid = 0;
1729         GSList *cur;
1730         MsgFileInfo *fileinfo;
1731         gint ok = MAILIMAP_NO_ERROR;
1732         gint curnum = 0, total = 0;
1733         gboolean missing_uids = FALSE;
1734
1735         g_return_val_if_fail(folder != NULL, -1);
1736         g_return_val_if_fail(dest != NULL, -1);
1737         g_return_val_if_fail(file_list != NULL, -1);
1738         
1739         debug_print("getting session...\n");
1740         session = imap_session_get(folder);
1741         if (!session) {
1742                 return -1;
1743         }
1744         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1745         if (is_fatal(ok)) {
1746                 g_free(destdir);
1747                 return -1;
1748         }
1749         statusbar_print_all(_("Adding messages..."));
1750         total = g_slist_length(file_list);
1751         for (cur = file_list; cur != NULL; cur = cur->next) {
1752                 IMAPFlags iflags = 0;
1753                 guint32 new_uid = 0;
1754                 gchar *real_file = NULL;
1755                 fileinfo = (MsgFileInfo *)cur->data;
1756
1757                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1758                 curnum++;
1759
1760                 if (fileinfo->flags) {
1761                         if (MSG_IS_MARKED(*fileinfo->flags))
1762                                 iflags |= IMAP_FLAG_FLAGGED;
1763                         if (MSG_IS_REPLIED(*fileinfo->flags))
1764                                 iflags |= IMAP_FLAG_ANSWERED;
1765                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1766                                 iflags |= IMAP_FLAG_FORWARDED;
1767                         if (MSG_IS_SPAM(*fileinfo->flags))
1768                                 iflags |= IMAP_FLAG_SPAM;
1769                         else
1770                                 iflags |= IMAP_FLAG_HAM;
1771                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1772                                 iflags |= IMAP_FLAG_SEEN;
1773                         
1774                 }
1775                 
1776                 if (real_file == NULL)
1777                         real_file = g_strdup(fileinfo->file);
1778                 
1779                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1780                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1781                     folder_has_parent_of_type(dest, F_DRAFT) ||
1782                     folder_has_parent_of_type(dest, F_TRASH))
1783                         iflags |= IMAP_FLAG_SEEN;
1784
1785                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1786                                      &new_uid);
1787
1788                 if (ok != MAILIMAP_NO_ERROR) {
1789                         g_warning("can't append message %s", real_file);
1790                         g_free(real_file);
1791                         g_free(destdir);
1792                         statusbar_progress_all(0,0,0);
1793                         statusbar_pop_all();
1794                         return -1;
1795                 } else {
1796                         debug_print("appended new message as %d\n", new_uid);
1797                         /* put the local file in the imapcache, so that we don't
1798                          * have to fetch it back later. */
1799                         
1800                         if (new_uid == 0) {
1801                                 missing_uids = TRUE;
1802                                 debug_print("Missing UID (0)\n");
1803                         }
1804                         if (new_uid > 0) {
1805                                 gchar *cache_path = folder_item_get_path(dest);
1806                                 if (!is_dir_exist(cache_path))
1807                                         make_dir_hier(cache_path);
1808                                 if (is_dir_exist(cache_path)) {
1809                                         gchar *cache_file = g_strconcat(
1810                                                 cache_path, G_DIR_SEPARATOR_S, 
1811                                                 itos(new_uid), NULL);
1812                                         copy_file(real_file, cache_file, TRUE);
1813                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1814                                         g_free(cache_file);
1815                                 }
1816                                 g_free(cache_path);
1817                         }
1818                 }
1819
1820                 if (relation != NULL)
1821                         g_hash_table_insert(relation, fileinfo->msginfo != NULL ? 
1822                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1823                                           GINT_TO_POINTER(new_uid));
1824                 if (last_uid < new_uid) {
1825                         last_uid = new_uid;
1826                 }
1827
1828                 g_free(real_file);
1829         }
1830         
1831         statusbar_progress_all(0,0,0);
1832         statusbar_pop_all();
1833         
1834         
1835         g_free(destdir);
1836
1837         imap_scan_required(folder, dest);
1838
1839         session = imap_session_get(folder);
1840         if (!session) {
1841                 return -1;
1842         }
1843         if (missing_uids) {
1844                 gint a;
1845                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1846                          &a, NULL, NULL, NULL, NULL, FALSE);
1847         }
1848         return last_uid;
1849 }
1850
1851 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1852 {
1853         GSList *result = NULL;
1854         clistiter *list;
1855         guint32 start, end, t;
1856         GSList *cur;
1857
1858         if (!set || !set->set_list)
1859                 return NULL;
1860
1861         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1862                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1863                 start = item->set_first;
1864                 end = item->set_last;
1865                 if (start <= end) {
1866                         for (t = start; t <= end; t++) {
1867                                 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1868                         }
1869                 }
1870         }
1871         result = g_slist_reverse(result);
1872         if (debug_get_mode()) {
1873                 debug_print("flat imap set: ");
1874                 for (cur = result; cur; cur = cur->next) {
1875                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1876                 }
1877                 debug_print("\n");
1878         }
1879         
1880         return result;
1881 }
1882 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1883                               MsgInfoList *msglist, GHashTable *relation,
1884                               gboolean same_dest_ok)
1885 {
1886         FolderItem *src;
1887         gchar *destdir;
1888         GSList *seq_list, *cur;
1889         MsgInfo *msginfo;
1890         IMAPSession *session;
1891         gint ok = MAILIMAP_NO_ERROR;
1892         GHashTable *uid_hash;
1893         gint last_num = 0;
1894
1895         g_return_val_if_fail(folder != NULL, -1);
1896         g_return_val_if_fail(dest != NULL, -1);
1897         g_return_val_if_fail(msglist != NULL, -1);
1898         
1899         debug_print("getting session...\n");
1900         session = imap_session_get(folder);
1901         
1902         if (!session) {
1903                 return -1;
1904         }
1905
1906         msginfo = (MsgInfo *)msglist->data;
1907         src = msginfo->folder;
1908         if (!same_dest_ok && src == dest) {
1909                 g_warning("the src folder is identical to the dest.");
1910                 return -1;
1911         }
1912
1913         if (src->folder != dest->folder) {
1914                 GSList *infolist = NULL, *cur;
1915                 int res = -1;
1916                 for (cur = msglist; cur; cur = cur->next) {
1917                         msginfo = (MsgInfo *)cur->data;
1918                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1919                         fileinfo->file = procmsg_get_message_file(msginfo);
1920                         fileinfo->flags = &(msginfo->flags);
1921                         infolist = g_slist_prepend(infolist, fileinfo);
1922                 }
1923                 infolist = g_slist_reverse(infolist);
1924                 res = folder_item_add_msgs(dest, infolist, FALSE);
1925                 for (cur = infolist; cur; cur = cur->next) {
1926                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1927                         g_free(info->file);
1928                         g_free(info);
1929                 }
1930                 g_slist_free(infolist);
1931                 return res;
1932         } 
1933
1934         lock_session(session); /* unlocked later in the function */
1935
1936         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1937                          NULL, NULL, NULL, NULL, NULL, FALSE);
1938         if (ok != MAILIMAP_NO_ERROR) {
1939                 return ok;
1940         }
1941
1942         unlock_session(session);
1943
1944         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1945
1946         if (is_fatal(ok)) {
1947                 g_free(destdir);
1948                 return ok;
1949         }
1950
1951         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1952         uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
1953         
1954         statusbar_print_all(_("Copying messages..."));
1955         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1956                 struct mailimap_set * seq_set;
1957                 struct mailimap_set * source = NULL;
1958                 struct mailimap_set * dest = NULL;
1959                 seq_set = cur->data;
1960
1961                 debug_print("Copying messages from %s to %s ...\n",
1962                             src->path, destdir);
1963
1964                 lock_session(session); /* unlocked later in the function */
1965                 ok = imap_cmd_copy(session, seq_set, destdir,
1966                         &source, &dest);
1967                 
1968                 if (is_fatal(ok)) {
1969                         session = NULL;
1970                 }
1971
1972                 if (ok == MAILIMAP_NO_ERROR) {
1973                         unlock_session(session);
1974                         if (relation && source && dest) {
1975                                 GSList *s_list = flatten_mailimap_set(source);
1976                                 GSList *d_list = flatten_mailimap_set(dest);
1977                                 GSList *s_cur, *d_cur;
1978                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1979
1980                                         for (s_cur = s_list, d_cur = d_list; 
1981                                              s_cur && d_cur; 
1982                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1983                                                 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
1984                                         }
1985
1986                                 } else {
1987                                         debug_print("hhhmm, source list length != dest list length.\n");
1988                                 }
1989                                 g_slist_free(s_list);
1990                                 g_slist_free(d_list);
1991                         }
1992                 }
1993
1994
1995                 if (source)
1996                         mailimap_set_free(source);
1997                 if (dest)
1998                         mailimap_set_free(dest);
1999
2000                 if (ok != MAILIMAP_NO_ERROR) {
2001                         g_hash_table_destroy(uid_hash);
2002                         imap_lep_set_free(seq_list);
2003                         statusbar_pop_all();
2004                         return -1;
2005                 }
2006         }
2007
2008         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
2009                 MsgInfo *msginfo = (MsgInfo *)cur->data;
2010                 gpointer hashval;
2011
2012                 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
2013                 
2014                 if (hashval != NULL) {
2015                         gint num = GPOINTER_TO_INT(hashval);
2016                         g_hash_table_insert(relation, msginfo,
2017                                           GINT_TO_POINTER(num));
2018                         if (num > last_num)
2019                                 last_num = num;
2020                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
2021                         /* put the local file in the imapcache, so that we don't
2022                          * have to fetch it back later. */
2023                         if (num > 0) {
2024                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
2025                                 gchar *real_file = g_strconcat(
2026                                         cache_path, G_DIR_SEPARATOR_S, 
2027                                         itos(msginfo->msgnum), NULL);
2028                                 gchar *cache_file = NULL;
2029                                 g_free(cache_path);
2030                                 cache_path = folder_item_get_path(dest);
2031                                 cache_file = g_strconcat(
2032                                         cache_path, G_DIR_SEPARATOR_S, 
2033                                         itos(num), NULL);
2034                                 if (!is_dir_exist(cache_path))
2035                                         make_dir_hier(cache_path);
2036                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
2037                                         if (copy_file(real_file, cache_file, TRUE) < 0)
2038                                                 debug_print("couldn't cache to %s: %s\n", cache_file,
2039                                                             strerror(errno));
2040                                         else
2041                                                 debug_print("copied to cache: %s\n", cache_file);
2042                                 }
2043                                 g_free(real_file);
2044                                 g_free(cache_file);
2045                                 g_free(cache_path);
2046                         }
2047                 } else
2048                         g_hash_table_insert(relation, msginfo,
2049                                           GINT_TO_POINTER(0));
2050         }
2051         statusbar_pop_all();
2052
2053         g_hash_table_destroy(uid_hash);
2054         imap_lep_set_free(seq_list);
2055
2056         g_free(destdir);
2057         
2058         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
2059         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
2060         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
2061         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
2062
2063         imap_scan_required(folder, dest);
2064         if (ok == MAILIMAP_NO_ERROR)
2065                 return last_num;
2066         else
2067                 return -1;
2068 }
2069
2070 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
2071 {
2072         GSList msglist;
2073
2074         g_return_val_if_fail(msginfo != NULL, -1);
2075
2076         msglist.data = msginfo;
2077         msglist.next = NULL;
2078
2079         return imap_copy_msgs(folder, dest, &msglist, NULL);
2080 }
2081
2082 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
2083                     MsgInfoList *msglist, GHashTable *relation)
2084 {
2085         MsgInfo *msginfo;
2086         gint ret;
2087
2088         g_return_val_if_fail(folder != NULL, -1);
2089         g_return_val_if_fail(dest != NULL, -1);
2090         g_return_val_if_fail(msglist != NULL, -1);
2091
2092         msginfo = (MsgInfo *)msglist->data;
2093         g_return_val_if_fail(msginfo->folder != NULL, -1);
2094
2095         ret = imap_do_copy_msgs(folder, dest, msglist, relation, FALSE);
2096         return ret;
2097 }
2098
2099 static gboolean imap_matcher_type_is_local(gint matchertype)
2100 {
2101         switch (matchertype) {
2102         case MATCHCRITERIA_FROM:
2103         case MATCHCRITERIA_TO:
2104         case MATCHCRITERIA_CC:
2105         case MATCHCRITERIA_TO_OR_CC:
2106         case MATCHCRITERIA_SUBJECT:
2107         case MATCHCRITERIA_REFERENCES:
2108         case MATCHCRITERIA_MESSAGEID:
2109         case MATCHCRITERIA_INREPLYTO:
2110         case MATCHCRITERIA_AGE_GREATER:
2111         case MATCHCRITERIA_AGE_LOWER:
2112         case MATCHCRITERIA_FORWARDED:
2113         case MATCHCRITERIA_SPAM:
2114         case MATCHCRITERIA_UNREAD:
2115         case MATCHCRITERIA_NEW:
2116         case MATCHCRITERIA_MARKED:
2117         case MATCHCRITERIA_REPLIED:
2118         case MATCHCRITERIA_DELETED:
2119         case MATCHCRITERIA_SIZE_GREATER:
2120         case MATCHCRITERIA_SIZE_SMALLER:
2121         case MATCHCRITERIA_SIZE_EQUAL:
2122                 return TRUE;
2123         }
2124         return FALSE;
2125 }
2126
2127 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2128 {
2129         if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2130                 IMAPSearchKey* result = NULL;
2131                 gboolean invert = FALSE;
2132                 gint matchertype = match->criteria;
2133
2134                 if (is_all) {
2135                         *is_all = FALSE;
2136                 }
2137
2138                 switch (matchertype) {
2139                 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2140                 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2141                 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2142                 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2143                 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2144                 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2145                 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2146                 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2147                 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2148                 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2149                 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2150                 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2151                 case MATCHCRITERIA_NOT_HEADERS_CONT: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_CONT; break;
2152                 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2153                 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2154                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2155                 case MATCHCRITERIA_NOT_MESSAGEID: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGEID; break;
2156                 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2157                 }
2158
2159                 /* 
2160                  * this aborts conversion even for predicates understood by the following code.
2161                  * while that might seem wasteful, claws local search for information listed below
2162                  * has proven faster than IMAP search plus network roundtrips. once this changes,
2163                  * consider removing these exceptions.
2164                  */
2165                 if (imap_matcher_type_is_local(matchertype))
2166                         return NULL;
2167
2168                 /* the Message-ID header is also cached */
2169                 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2170                         return NULL;
2171                 }
2172
2173                 switch (matchertype) {
2174                 case MATCHCRITERIA_FORWARDED:
2175                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2176                         break;
2177
2178                 case MATCHCRITERIA_SPAM:
2179                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2180                         break;
2181
2182                 case MATCHCRITERIA_MESSAGEID:
2183                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "Message-ID", match->expr, 0);
2184                         break;
2185
2186                 case MATCHCRITERIA_INREPLYTO:
2187                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2188                         break;
2189
2190                 case MATCHCRITERIA_REFERENCES:
2191                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2192                         break;
2193
2194                 case MATCHCRITERIA_TO_OR_CC:
2195                         result = imap_search_or(
2196                                         imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2197                                         imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2198                                         );
2199                         break;
2200
2201                 case MATCHCRITERIA_HEADERS_PART:
2202                 case MATCHCRITERIA_HEADERS_CONT:
2203                         result = imap_search_and(
2204                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2205                                         imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2206                                         );
2207                         break;
2208
2209                 case MATCHCRITERIA_SIZE_EQUAL:
2210                         result = imap_search_and(
2211                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2212                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2213                                         );
2214                         break;
2215
2216                 case MATCHCRITERIA_NOT_UNREAD:
2217                         result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2218                         break;
2219
2220                 case MATCHCRITERIA_UNREAD:
2221                         result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2222                         break;
2223
2224                 case MATCHCRITERIA_NEW:
2225                         result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2226                         break;
2227
2228                 case MATCHCRITERIA_MARKED:
2229                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2230                         break;
2231
2232                 case MATCHCRITERIA_DELETED:
2233                         result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2234                         break;
2235
2236                 case MATCHCRITERIA_REPLIED:
2237                         result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2238                         break;
2239
2240                 case MATCHCRITERIA_TAG:
2241                         {
2242                                 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2243                                 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2244                                 g_free(tmp);
2245                         }
2246                         break;
2247
2248                 case MATCHCRITERIA_SUBJECT:
2249                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2250                         break;
2251
2252                 case MATCHCRITERIA_FROM:
2253                         result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2254                         break;
2255
2256                 case MATCHCRITERIA_TO:
2257                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2258                         break;
2259
2260                 case MATCHCRITERIA_CC:
2261                         result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2262                         break;
2263
2264                 case MATCHCRITERIA_AGE_GREATER:
2265                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2266                         break;
2267
2268                 case MATCHCRITERIA_AGE_LOWER:
2269                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2270                         break;
2271
2272                 case MATCHCRITERIA_BODY_PART:
2273                         result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2274                         break;
2275
2276                 case MATCHCRITERIA_MESSAGE:
2277                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2278                         break;
2279
2280                 case MATCHCRITERIA_HEADER:
2281                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2282                         break;
2283
2284                 case MATCHCRITERIA_SIZE_GREATER:
2285                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2286                         break;
2287
2288                 case MATCHCRITERIA_SIZE_SMALLER:
2289                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2290                         break;
2291
2292                 default:
2293                         result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2294                         if (is_all) {
2295                                 *is_all = TRUE;
2296                         }
2297                         break;
2298                 }
2299
2300                 if (invert) {
2301                         result = imap_search_not(result);
2302                         if (is_all && *is_all) {
2303                                 *is_all = FALSE;
2304                         }
2305                 }
2306
2307                 return result;
2308         }
2309
2310         return NULL;
2311 }
2312
2313 static void imap_change_search_charset(IMAPFolder *folder)
2314 {
2315         /* If server supports charset in searches, but the last used one failed,
2316          * changed to the next preferred charset. If none are still available,
2317          * disable charset searches.
2318          * Charsets are tried in the following order: 
2319          * UTF-8, locale's charset, UTF-7.
2320          */
2321
2322         if (folder->search_charset_supported) {
2323                 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2324                         folder->search_charset = "UTF-8";
2325                 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2326                         folder->search_charset = "UTF-7";
2327                 else {
2328                         folder->search_charset = NULL;
2329                         folder->search_charset_supported = FALSE;
2330                 }
2331         }
2332 }
2333
2334 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2335                                                   MatcherProp *utf8_prop,
2336                                                   gchar **charset)
2337 {
2338         /* If the match is going to be done locally, or the criteria is on
2339          * tag (special-cased to modified-UTF-7), or the expression searched
2340          * is ASCII, don't bother converting.
2341          */
2342         if (imap_matcher_type_is_local(utf8_prop->criteria)
2343          || utf8_prop->criteria == MATCHCRITERIA_TAG
2344          || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2345          || utf8_prop->expr == NULL
2346          || is_ascii_str(utf8_prop->expr))
2347                 return matcherprop_new(utf8_prop->criteria,
2348                                utf8_prop->header,
2349                                utf8_prop->matchtype,
2350                                utf8_prop->expr,
2351                                utf8_prop->value);
2352         else {
2353                 gchar *conv_expr = NULL;
2354
2355                 /* If the search is server-side and the server doesn't support
2356                  * searching with the charsets we handle, bail out.
2357                  */
2358                 if (folder->search_charset_supported == FALSE)
2359                         return NULL;
2360
2361                 /* Else, convert. */
2362                 if (*charset == NULL)
2363                         *charset = g_strdup(folder->search_charset);
2364
2365                 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2366
2367                 if (conv_expr == NULL)
2368                         conv_expr = g_strdup(utf8_prop->expr);
2369
2370                 return matcherprop_new(utf8_prop->criteria,
2371                                utf8_prop->header,
2372                                utf8_prop->matchtype,
2373                                conv_expr,
2374                                utf8_prop->value);
2375         }
2376 }
2377
2378 static gint     search_msgs             (Folder                 *folder,
2379                                          FolderItem             *container,
2380                                          MsgNumberList          **msgs,
2381                                          gboolean               *on_server,
2382                                          MatcherList            *predicate,
2383                                          SearchProgressNotify   progress_cb,
2384                                          gpointer               progress_data)
2385 {
2386         IMAPSearchKey* key = NULL;
2387         GSList* cur;
2388         int result = -1;
2389         clist* uidlist = NULL;
2390         gboolean server_filtering_useless = FALSE;
2391         IMAPSession *session;
2392         gchar *charset_to_use = NULL;
2393
2394         if (on_server == NULL || !*on_server) {
2395                 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2396                                 predicate, progress_cb, progress_data);
2397         }
2398
2399         for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2400                 IMAPSearchKey* matcherPart = NULL;
2401                 MatcherProp* prop = (MatcherProp*) cur->data;
2402                 gboolean is_all;
2403                 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2404
2405                 if (imap_prop == NULL) {
2406                         /* Couldn't convert matcherprop to IMAP - probably not ascii
2407                          * and server doesn't support the charsets we do. */
2408                          return -1;
2409                 }
2410
2411                 matcherPart = search_make_key(imap_prop, &is_all);
2412
2413                 matcherprop_free(imap_prop);
2414
2415                 if (on_server) {
2416                         *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2417                 }
2418
2419                 if (matcherPart) {
2420                         if (key == NULL) {
2421                                 key = matcherPart;
2422                                 server_filtering_useless = is_all;
2423                         } else if (predicate->bool_and) {
2424                                 key = imap_search_and(key, matcherPart);
2425                                 server_filtering_useless &= is_all;
2426                         } else {
2427                                 key = imap_search_or(key, matcherPart);
2428                                 server_filtering_useless |= is_all;
2429                         }
2430                 }
2431         }
2432
2433         if (server_filtering_useless) {
2434                 imap_search_free(key);
2435                 key = NULL;
2436         }
2437
2438         if (key == NULL && progress_cb != NULL) {
2439                 GSList* cur;
2440                 GSList* list;
2441                 int count = 0;
2442
2443                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2444                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2445
2446                 list = folder_item_get_msg_list(container);
2447                 for (cur = list; cur != NULL; cur = cur->next) {
2448                         *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2449                         count++;
2450                 }
2451                 procmsg_msg_list_free(list);
2452
2453                 *msgs = g_slist_reverse(*msgs);
2454
2455                 return count;
2456         }
2457
2458         session = imap_session_get(folder);
2459         if (!session) {
2460                 return -1;
2461         }
2462         result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2463                          NULL, NULL, NULL, NULL, NULL, TRUE);
2464         if (result != MAILIMAP_NO_ERROR)
2465                 return -1;
2466
2467         if (progress_cb)
2468                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2469         result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2470         if (progress_cb)
2471                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2472
2473         if (result == MAILIMAP_NO_ERROR) {
2474                 gint result = 0;
2475
2476                 *msgs = imap_uid_list_from_lep(uidlist, &result);
2477
2478                 mailimap_search_result_free(uidlist);
2479
2480                 if (charset_to_use != NULL)
2481                         g_free(charset_to_use);
2482
2483                 return result;
2484         } else if (charset_to_use != NULL) {
2485                 /* If search failed and was on an 8-bit string, try the next
2486                  * available charset to search if there still are some.
2487                  */
2488                 g_free(charset_to_use);
2489                 
2490                 imap_change_search_charset(IMAP_FOLDER(folder));
2491                 if (IMAP_FOLDER(folder)->search_charset_supported)
2492                         return search_msgs(folder, container, msgs, on_server, predicate,
2493                                    progress_cb, progress_data);
2494                 else
2495                         return -1;
2496         } else {
2497                 return -1;
2498         }
2499 }
2500
2501
2502 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
2503                                 MsgInfoList *msglist, GHashTable *relation)
2504 {
2505         gchar *destdir, *dir;
2506         GSList *numlist = NULL, *cur;
2507         MsgInfo *msginfo;
2508         IMAPSession *session;
2509         gint ok = MAILIMAP_NO_ERROR;
2510         
2511         g_return_val_if_fail(folder != NULL, -1);
2512         g_return_val_if_fail(dest != NULL, -1);
2513         g_return_val_if_fail(msglist != NULL, -1);
2514
2515         debug_print("getting session...\n");
2516         session = imap_session_get(folder);
2517         if (!session) {
2518                 return -1;
2519         }
2520
2521         lock_session(session); /* unlocked later in the function */
2522
2523         msginfo = (MsgInfo *)msglist->data;
2524
2525         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2526                          NULL, NULL, NULL, NULL, NULL, FALSE);
2527         if (ok != MAILIMAP_NO_ERROR) {
2528                 return ok;
2529         }
2530
2531         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2532         if (is_fatal(ok)) {
2533                 g_free(destdir);
2534                 return ok;
2535         }
2536         for (cur = msglist; cur; cur = cur->next) {
2537                 msginfo = (MsgInfo *)cur->data;
2538                 if (!MSG_IS_DELETED(msginfo->flags))
2539                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2540         }
2541         numlist = g_slist_reverse(numlist);
2542
2543         if (numlist != NULL) {
2544                 ok = imap_set_message_flags
2545                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2546                 if (ok != MAILIMAP_NO_ERROR) {
2547                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2548                         g_free(destdir);
2549                         return ok;
2550                 }
2551         } /* else we just need to expunge */
2552         ok = imap_cmd_expunge(session);
2553         if (ok != MAILIMAP_NO_ERROR) {
2554                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2555                 g_free(destdir);
2556                 return ok;
2557         }
2558         
2559         session->folder_content_changed = TRUE;
2560         unlock_session(session);
2561
2562         dir = folder_item_get_path(msginfo->folder);
2563         if (is_dir_exist(dir)) {
2564                 for (cur = msglist; cur; cur = cur->next) {
2565                         msginfo = (MsgInfo *)cur->data;
2566                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2567                 }
2568         }
2569         g_free(dir);
2570
2571         g_slist_free(numlist);
2572
2573         imap_scan_required(folder, dest);
2574
2575         g_free(destdir);
2576
2577         return 0;
2578 }
2579
2580 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2581                     MsgInfoList *msglist, GHashTable *relation)
2582 {
2583         MsgInfo *msginfo;
2584
2585         g_return_val_if_fail(folder != NULL, -1);
2586         g_return_val_if_fail(dest != NULL, -1);
2587         if (msglist == NULL)
2588                 return 0;
2589
2590         msginfo = (MsgInfo *)msglist->data;
2591         g_return_val_if_fail(msginfo->folder != NULL, -1);
2592
2593         return imap_do_remove_msgs(folder, dest, msglist, relation);
2594 }
2595
2596 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2597 {
2598         GSList *list = folder_item_get_msg_list(item);
2599         gint res = imap_remove_msgs(folder, item, list, NULL);
2600         procmsg_msg_list_free(list);
2601         return res;
2602 }
2603
2604 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2605                                     MsgInfo *msginfo)
2606 {
2607         /* TODO: properly implement this method */
2608         return FALSE;
2609 }
2610
2611 static gint imap_close(Folder *folder, FolderItem *item)
2612 {
2613         return 0;
2614 }
2615
2616 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2617 {
2618         FolderItem *item = NULL;
2619         IMAPSession *session;
2620         gchar *root_folder = NULL;
2621
2622         g_return_val_if_fail(folder != NULL, -1);
2623         g_return_val_if_fail(folder->account != NULL, -1);
2624
2625         debug_print("getting session...\n");
2626         session = imap_session_get(folder);
2627         if (!session) {
2628                 if (!folder->node) {
2629                         folder_tree_destroy(folder);
2630                         item = folder_item_new(folder, folder->name, NULL);
2631                         item->folder = folder;
2632                         folder->node = item->node = g_node_new(item);
2633                 }
2634                 return -1;
2635         }
2636
2637         if (folder->account->imap_dir && *folder->account->imap_dir) {
2638                 gchar *real_path;
2639                 int r = MAILIMAP_NO_ERROR;
2640                 clist * lep_list;
2641
2642                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2643                 extract_quote(root_folder, '"');
2644                 subst_char(root_folder,
2645                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2646                                                    root_folder, &r),
2647                            '/');
2648                 if (is_fatal(r))
2649                         return -1;
2650                 strtailchomp(root_folder, '/');
2651                 real_path = imap_get_real_path
2652                         (session, IMAP_FOLDER(folder), root_folder, &r);
2653                 if (is_fatal(r)) {
2654                         g_free(real_path);
2655                         return -1;
2656                 }
2657                 debug_print("IMAP root directory: %s\n", real_path);
2658
2659                 /* check if root directory exist */
2660
2661                 r = imap_threaded_list(session->folder, "", real_path,
2662                                        &lep_list);
2663
2664                 if (r != MAILIMAP_NO_ERROR)
2665                         imap_handle_error(SESSION(session), NULL, r);
2666
2667                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2668                         if (!folder->node) {
2669                                 item = folder_item_new(folder, folder->name, NULL);
2670                                 item->folder = folder;
2671                                 folder->node = item->node = g_node_new(item);
2672                         }
2673                         return -1;
2674                 }
2675                 mailimap_list_result_free(lep_list);
2676                                 
2677                 g_free(real_path);
2678         }
2679
2680         if (folder->node)
2681                 item = FOLDER_ITEM(folder->node->data);
2682                 
2683         if (item && !item->path && root_folder) {
2684                 item->path = g_strdup(root_folder);
2685         }
2686
2687         if (!item || ((item->path || root_folder) &&
2688                       strcmp2(item->path, root_folder) != 0)) {
2689                 folder_tree_destroy(folder);
2690                 item = folder_item_new(folder, folder->name, root_folder);
2691                 item->folder = folder;
2692                 folder->node = item->node = g_node_new(item);
2693         }
2694
2695         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2696         imap_create_missing_folders(folder);
2697
2698         return 0;
2699 }
2700
2701 static gint imap_scan_tree(Folder *folder)
2702 {
2703         gboolean subs_only = FALSE;
2704         if (folder->account) {
2705                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2706                 subs_only = folder->account->imap_subsonly;
2707         }
2708         return imap_scan_tree_real(folder, subs_only);
2709 }
2710
2711 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2712 {
2713         Folder *folder;
2714         IMAPFolder *imapfolder;
2715         FolderItem *new_item;
2716         GSList *item_list, *cur;
2717         GNode *node;
2718         gchar *real_path;
2719         gchar *wildcard_path;
2720         gchar separator;
2721         gchar wildcard[3];
2722         clist * lep_list;
2723         int r = MAILIMAP_NO_ERROR;
2724         
2725         g_return_val_if_fail(item != NULL, -1);
2726         g_return_val_if_fail(item->folder != NULL, -1);
2727         g_return_val_if_fail(item->no_sub == FALSE, -1);
2728
2729         folder = item->folder;
2730         imapfolder = IMAP_FOLDER(folder);
2731
2732         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2733         if (is_fatal(r))
2734                 return r;
2735
2736         if (folder->ui_func)
2737                 folder->ui_func(folder, item, folder->ui_func_data);
2738
2739         if (item->path) {
2740                 wildcard[0] = separator;
2741                 wildcard[1] = '%';
2742                 wildcard[2] = '\0';
2743                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2744                 if (is_fatal(r)) {
2745                         g_free(real_path);
2746                         return r;
2747                 }
2748         } else {
2749                 wildcard[0] = '%';
2750                 wildcard[1] = '\0';
2751                 real_path = g_strdup("");
2752         }
2753
2754         Xstrcat_a(wildcard_path, real_path, wildcard,
2755                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2756         lep_list = NULL;
2757         
2758         if (subs_only)
2759                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2760         else
2761                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2762
2763         if (r != MAILIMAP_NO_ERROR) {
2764                 imap_handle_error(SESSION(session), NULL, r);
2765                 item_list = NULL;
2766                 g_free(real_path);
2767                 return r;
2768         }
2769         else {
2770                 item_list = imap_list_from_lep(imapfolder,
2771                                                lep_list, real_path, FALSE);
2772                 mailimap_list_result_free(lep_list);
2773         }
2774         
2775         g_free(real_path);
2776
2777         node = item->node->children;
2778         while (node != NULL) {
2779                 FolderItem *old_item = FOLDER_ITEM(node->data);
2780                 GNode *next = node->next;
2781
2782                 new_item = NULL;
2783                 for (cur = item_list; cur != NULL; cur = cur->next) {
2784                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2785                         if (!strcmp2(old_item->path, cur_item->path)) {
2786                                 new_item = cur_item;
2787                                 break;
2788                         }
2789                 }
2790                 if (!new_item) {
2791                         if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2792                                 debug_print("not removing INBOX\n");
2793                         } else {
2794                                 debug_print("folder '%s' not found. removing...\n",
2795                                             old_item->path);
2796                                 folder_item_remove(old_item);
2797                         }
2798                 } else {
2799                         old_item->no_sub = new_item->no_sub;
2800                         old_item->no_select = new_item->no_select;
2801                         if (old_item->no_sub == TRUE && node->children) {
2802                                 debug_print("folder '%s' doesn't have "
2803                                             "subfolders. removing...\n",
2804                                             old_item->path);
2805                                 folder_item_remove_children(old_item);
2806                         }
2807                 }
2808
2809                 node = next;
2810         }
2811
2812         for (cur = item_list; cur != NULL; cur = cur->next) {
2813                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2814                 new_item = NULL;
2815
2816                 for (node = item->node->children; node != NULL;
2817                      node = node->next) {
2818                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2819                                      cur_item->path)) {
2820                                 new_item = FOLDER_ITEM(node->data);
2821                                 folder_item_destroy(cur_item);
2822                                 cur_item = NULL;
2823                                 break;
2824                         }
2825                 }
2826                 if (!new_item) {
2827                         new_item = cur_item;
2828                         debug_print("new folder '%s' found.\n", new_item->path);
2829                         folder_item_append(item, new_item);
2830                 }
2831
2832                 if (!strcasecmp(new_item->path, "INBOX")) {
2833                         new_item->stype = F_INBOX;
2834                         folder->inbox = new_item;
2835                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2836                         gchar *base;
2837
2838                         base = g_path_get_basename(new_item->path);
2839
2840                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2841                                 new_item->stype = F_OUTBOX;
2842                                 folder->outbox = new_item;
2843                         } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2844                                 new_item->stype = F_DRAFT;
2845                                 folder->draft = new_item;
2846                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2847                                 new_item->stype = F_QUEUE;
2848                                 folder->queue = new_item;
2849                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2850                                 new_item->stype = F_TRASH;
2851                                 folder->trash = new_item;
2852                         }
2853                         g_free(base);
2854                 }
2855
2856                 if (new_item->no_sub == FALSE)
2857                         imap_scan_tree_recursive(session, new_item, subs_only);
2858         }
2859
2860         g_slist_free(item_list);
2861
2862         return MAILIMAP_NO_ERROR;
2863 }
2864
2865 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2866 {
2867         IMAPSession *session = imap_session_get(folder);
2868         gchar *real_path;
2869         gchar *wildcard_path;
2870         gchar separator;
2871         gchar wildcard[3];
2872         clist * lep_list;
2873         GSList *item_list = NULL, *cur;
2874         GList *child_list = NULL, *tmplist = NULL;
2875         GSList *sub_list = NULL;
2876         int r = MAILIMAP_NO_ERROR;
2877
2878         if (!session)
2879                 return NULL;
2880
2881         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2882         if (is_fatal(r))
2883                 return NULL;
2884
2885         if (item->path) {
2886                 wildcard[0] = separator;
2887                 wildcard[1] = '%';
2888                 wildcard[2] = '\0';
2889                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2890                 if (is_fatal(r)) {
2891                         g_free(real_path);
2892                         return NULL;
2893                 }
2894         } else {
2895                 wildcard[0] = '%';
2896                 wildcard[1] = '\0';
2897                 real_path = g_strdup("");
2898         }
2899
2900         Xstrcat_a(wildcard_path, real_path, wildcard,
2901                   {g_free(real_path); return NULL;});
2902         lep_list = NULL;
2903         
2904         if (unsubs_only)
2905                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2906                                 item->path?item->path:item->name);
2907         else
2908                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2909                                 item->path?item->path:item->name);
2910
2911         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2912         if (r) {
2913                 g_free(real_path);
2914                 statusbar_pop_all();
2915                 return NULL;
2916         }
2917         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2918                                lep_list, real_path, FALSE);
2919         mailimap_list_result_free(lep_list);
2920
2921         for (cur = item_list; cur != NULL; cur = cur->next) {
2922                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2923                 if (recursive) {
2924                         tmplist = imap_scan_subtree(folder, cur_item, 
2925                                         unsubs_only, recursive);
2926                         if (tmplist)
2927                                 child_list = g_list_concat(child_list, tmplist);
2928                 }
2929                 child_list = g_list_prepend(child_list,
2930                                 imap_get_real_path(session, 
2931                                         IMAP_FOLDER(folder), cur_item->path, &r));
2932                 if (is_fatal(r)) {
2933                         g_free(real_path);
2934                         statusbar_pop_all();
2935                         return NULL;
2936                 }
2937                 folder_item_destroy(cur_item);
2938         }
2939         child_list = g_list_reverse(child_list);
2940         g_slist_free(item_list);
2941
2942         if (unsubs_only) {
2943                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2944                 if (r) {
2945                         g_free(real_path);
2946                         statusbar_pop_all();
2947                         return NULL;
2948                 }
2949                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2950                                        lep_list, real_path, FALSE);
2951                 mailimap_list_result_free(lep_list);
2952
2953                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2954                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2955                         GList *oldlitem = NULL;
2956                         gchar *tmp = imap_get_real_path(session, 
2957                                         IMAP_FOLDER(folder), cur_item->path, &r);
2958                         if (r) {
2959                                 g_free(real_path);
2960                                 statusbar_pop_all();
2961                                 g_free(tmp);
2962                                 return NULL;
2963                         }
2964                         folder_item_destroy(cur_item);
2965                         oldlitem = g_list_find_custom(
2966                                         child_list, tmp, (GCompareFunc)strcmp2);
2967                         if (oldlitem) {
2968                                 child_list = g_list_remove_link(child_list, oldlitem);
2969                                 g_free(oldlitem->data);
2970                                 g_list_free(oldlitem);
2971                         }
2972                         g_free(tmp);
2973                 }
2974         }
2975
2976         g_free(real_path);
2977         statusbar_pop_all();
2978
2979         return child_list;
2980 }
2981
2982 static gint imap_create_tree(Folder *folder)
2983 {
2984         g_return_val_if_fail(folder != NULL, -1);
2985         g_return_val_if_fail(folder->node != NULL, -1);
2986         g_return_val_if_fail(folder->node->data != NULL, -1);
2987         g_return_val_if_fail(folder->account != NULL, -1);
2988
2989         imap_scan_tree(folder);
2990         imap_create_missing_folders(folder);
2991
2992         return 0;
2993 }
2994
2995 static void imap_create_missing_folders(Folder *folder)
2996 {
2997         g_return_if_fail(folder != NULL);
2998
2999         if (!folder->inbox)
3000                 folder->inbox = imap_create_special_folder
3001                         (folder, F_INBOX, "INBOX");
3002         if (!folder->trash)
3003                 folder->trash = imap_create_special_folder
3004                         (folder, F_TRASH, "Trash");
3005         if (!folder->queue)
3006                 folder->queue = imap_create_special_folder
3007                         (folder, F_QUEUE, "Queue");
3008         if (!folder->outbox)
3009                 folder->outbox = imap_create_special_folder
3010                         (folder, F_OUTBOX, "Sent");
3011         if (!folder->draft)
3012                 folder->draft = imap_create_special_folder
3013                         (folder, F_DRAFT, "Drafts");
3014 }
3015
3016 static FolderItem *imap_create_special_folder(Folder *folder,
3017                                               SpecialFolderItemType stype,
3018                                               const gchar *name)
3019 {
3020         FolderItem *item;
3021         FolderItem *new_item;
3022
3023         g_return_val_if_fail(folder != NULL, NULL);
3024         g_return_val_if_fail(folder->node != NULL, NULL);
3025         g_return_val_if_fail(folder->node->data != NULL, NULL);
3026         g_return_val_if_fail(folder->account != NULL, NULL);
3027         g_return_val_if_fail(name != NULL, NULL);
3028
3029         item = FOLDER_ITEM(folder->node->data);
3030         new_item = imap_create_folder(folder, item, name);
3031
3032         if (!new_item) {
3033                 g_warning("Can't create '%s'", name);
3034                 if (!folder->inbox) return NULL;
3035
3036                 new_item = imap_create_folder(folder, folder->inbox, name);
3037                 if (!new_item)
3038                         g_warning("Can't create '%s' under INBOX", name);
3039                 else
3040                         new_item->stype = stype;
3041         } else
3042                 new_item->stype = stype;
3043
3044         return new_item;
3045 }
3046
3047 static gchar *imap_folder_get_path(Folder *folder)
3048 {
3049         gchar *folder_path;
3050
3051         g_return_val_if_fail(folder != NULL, NULL);
3052         g_return_val_if_fail(folder->account != NULL, NULL);
3053
3054 #ifdef G_OS_WIN32
3055         gchar *sanitized_dirname = g_strdup(folder->account->recv_server);
3056         g_strdelimit(sanitized_dirname, ":", ',');
3057 #endif
3058
3059         folder_path = g_strconcat(get_imap_cache_dir(),
3060                                   G_DIR_SEPARATOR_S,
3061 #ifdef G_OS_WIN32
3062                                                                                                                                         sanitized_dirname,
3063 #else
3064                                   folder->account->recv_server,
3065 #endif
3066                                   G_DIR_SEPARATOR_S,
3067                                   folder->account->userid,
3068                                   NULL);
3069
3070 #ifdef G_OS_WIN32
3071         g_free(sanitized_dirname);
3072 #endif
3073         return folder_path;
3074 }
3075
3076 #ifdef G_OS_WIN32
3077 static gchar *imap_encode_unsafe_chars(const gchar *str)
3078 {
3079         gchar *ret = NULL, *o_ret;
3080         gchar *i;
3081         if (!str) 
3082                 return NULL;
3083         ret = g_malloc(3*strlen(str)+1);
3084         o_ret = ret;
3085         for (i = (gchar *)str; *i; i++) {
3086                 switch(*i) {
3087                         case ':':
3088                         case '|':
3089                         case '<':
3090                         case '>':
3091                         case '*':
3092                         case '?':
3093                         case '#':
3094                                 *ret++ = '%';
3095                                 *ret++ = '0'+(*i/10);
3096                                 *ret++ = '0'+(*i%10);
3097                                 break;
3098                         default:
3099                                 *ret++ = *i;
3100                 }
3101         }
3102         *ret++ = '\0';
3103         return o_ret;
3104 }
3105 #endif
3106 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3107 {
3108         gchar *folder_path, *path;
3109         gchar *item_path = NULL;
3110         
3111         g_return_val_if_fail(folder != NULL, NULL);
3112         g_return_val_if_fail(item != NULL, NULL);
3113         folder_path = imap_folder_get_path(folder);
3114
3115         g_return_val_if_fail(folder_path != NULL, NULL);
3116
3117 #ifdef G_OS_UNIX
3118         item_path = g_strdup(item->path);
3119 #else
3120         item_path = imap_encode_unsafe_chars(item->path);
3121 #endif  
3122
3123         if (g_path_is_absolute(folder_path)) {
3124                 if (item_path)
3125                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3126                                            item_path, NULL);
3127                 else
3128                         path = g_strdup(folder_path);
3129         } else {
3130                 if (item_path)
3131                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3132                                            folder_path, G_DIR_SEPARATOR_S,
3133                                            item_path, NULL);
3134                 else
3135                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3136                                            folder_path, NULL);
3137         }
3138         g_free(folder_path);
3139         g_free(item_path);
3140 #ifdef G_OS_WIN32
3141         while (strchr(path, '/'))
3142                 *strchr(path, '/') = '\\';
3143 #endif
3144
3145         return path;
3146 }
3147
3148 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3149                                const gchar *name)
3150 {
3151         gchar *dirpath, *imap_path;
3152         IMAPSession *session;
3153         FolderItem *new_item;
3154         gchar separator;
3155         gchar *new_name;
3156         const gchar *p;
3157         gint ok = MAILIMAP_NO_ERROR;
3158         gboolean no_select = FALSE, no_sub = FALSE;
3159         gboolean exist = FALSE;
3160         
3161         g_return_val_if_fail(folder != NULL, NULL);
3162         g_return_val_if_fail(folder->account != NULL, NULL);
3163         g_return_val_if_fail(parent != NULL, NULL);
3164         g_return_val_if_fail(name != NULL, NULL);
3165
3166         if (to_number(name) > 0) {
3167                 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3168                 if (is_file_exist(cached_msg)) {
3169                         if (claws_unlink(cached_msg) != 0) {
3170                                 return NULL;
3171                         }
3172                 }
3173         }
3174
3175         debug_print("getting session...\n");
3176         session = imap_session_get(folder);
3177         if (!session) {
3178                 return NULL;
3179         }
3180
3181         if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3182                 dirpath = g_strdup(name);
3183         }else if (parent->path)
3184                 dirpath = g_strconcat(parent->path, "/", name, NULL);
3185         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3186                 dirpath = g_strdup(name);
3187         else if (folder->account->imap_dir && *folder->account->imap_dir) {
3188                 gchar *imap_dir;
3189
3190                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3191                 strtailchomp(imap_dir, '/');
3192                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3193         } else
3194                 dirpath = g_strdup(name);
3195                 
3196         
3197
3198         /* keep trailing directory separator to create a folder that contains
3199            sub folder */
3200         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3201
3202         strtailchomp(dirpath, '/');
3203         Xstrdup_a(new_name, name, {
3204                 g_free(dirpath); 
3205                 g_free(imap_path);
3206                 return NULL;});
3207
3208         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3209         if (is_fatal(ok)) {
3210                 g_free(imap_path);
3211                 return NULL;
3212         }
3213         imap_path_separator_subst(imap_path, separator);
3214         /* remove trailing / for display */
3215         strtailchomp(new_name, '/');
3216
3217         if (strcasecmp(dirpath, "INBOX") != 0) {
3218                 GPtrArray *argbuf;
3219                 int r;
3220                 clist * lep_list;
3221                 
3222                 argbuf = g_ptr_array_new();
3223                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3224                 if (r != MAILIMAP_NO_ERROR) {
3225                         imap_handle_error(SESSION(session), NULL, r);
3226                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3227                         g_free(imap_path);
3228                         g_free(dirpath);
3229                         ptr_array_free_strings(argbuf);
3230                         g_ptr_array_free(argbuf, TRUE);
3231                         return NULL;
3232                 }
3233                 
3234                 if (clist_count(lep_list) > 0)
3235                         exist = TRUE;
3236                 mailimap_list_result_free(lep_list);
3237                 lep_list = NULL;
3238                 if (!exist) {
3239                         ok = imap_cmd_create(session, imap_path);
3240                         if (ok != MAILIMAP_NO_ERROR) {
3241                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3242                                 g_free(imap_path);
3243                                 g_free(dirpath);
3244                                 return NULL;
3245                         }
3246                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
3247                         if (r == MAILIMAP_NO_ERROR) {
3248                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3249                                                lep_list, dirpath, TRUE);
3250                                 if (item_list) {
3251                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3252                                         no_select = cur_item->no_select;
3253                                         no_sub = cur_item->no_sub;
3254                                         g_slist_free(item_list);
3255                                 } 
3256                                 mailimap_list_result_free(lep_list);
3257                         } else {
3258                                 imap_handle_error(SESSION(session), NULL, r);
3259                         }
3260                 }
3261                 imap_threaded_subscribe(folder, imap_path, TRUE);
3262         } else {
3263                 clist *lep_list;
3264                 int r;
3265                 /* just get flags */
3266                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3267                 if (r == MAILIMAP_NO_ERROR) {
3268                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),