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