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