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