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