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