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