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