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