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