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