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