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