6813d9e53bc45ac1376998d276a939947513bb25
[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         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 = g_strdup(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                 }
1051                 SESSION(session)->state = SESSION_DISCONNECTED;
1052                 SESSION(session)->sock = NULL;
1053                 imap_safe_destroy(session);
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                 r = imap_cmd_noop(session);
1070
1071                 if (r != MAILIMAP_NO_ERROR) {
1072                         debug_print("disconnected!\n");
1073                         if (!is_fatal(r))
1074                                 session = imap_reconnect_if_possible(folder, session);
1075                         else {
1076                                 rfolder->session = NULL;
1077                                 rfolder->connecting = FALSE;
1078                                 SESSION(session)->state = SESSION_DISCONNECTED;
1079                                 SESSION(session)->sock = NULL;
1080                                 imap_safe_destroy(session);
1081                                 session = imap_session_get(folder);
1082                         }
1083                 }
1084                 if (session)
1085                         session->cancelled = FALSE;
1086         }
1087
1088         rfolder->session = SESSION(session);
1089         rfolder->connecting = FALSE;
1090
1091         return IMAP_SESSION(session);
1092 }
1093
1094 static IMAPSession *imap_session_new(Folder * folder,
1095                                      const PrefsAccount *account)
1096 {
1097         IMAPSession *session;
1098         gushort port;
1099         int r;
1100         int authenticated = FALSE;
1101         gchar *buf;
1102
1103 #ifdef USE_GNUTLS
1104         /* FIXME: IMAP over SSL only... */ 
1105         SSLType ssl_type;
1106
1107         port = account->set_imapport ? account->imapport
1108                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1109         ssl_type = account->ssl_imap;   
1110 #else
1111         if (account->ssl_imap != SSL_NONE) {
1112                 if (alertpanel_full(_("Insecure connection"),
1113                         _("This connection is configured to be secured "
1114                           "using SSL, but SSL is not available in this "
1115                           "build of Claws Mail. \n\n"
1116                           "Do you want to continue connecting to this "
1117                           "server? The communication would not be "
1118                           "secure."),
1119                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1120                           NULL, FALSE, NULL, ALERT_WARNING,
1121                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1122                         return NULL;
1123         }
1124         port = account->set_imapport ? account->imapport
1125                 : IMAP4_PORT;
1126 #endif
1127
1128         imap_init(folder);
1129         buf = g_strdup_printf(_("Account '%s': Connecting to IMAP4 server: %s:%d..."),
1130                                 folder->account->account_name, folder->account->recv_server,
1131                                 port);
1132         statuswindow_print_all("%s", buf);
1133         log_message(LOG_PROTOCOL, "%s\n", buf);
1134         g_free(buf);
1135
1136 #ifndef G_OS_WIN32
1137         if (account->set_tunnelcmd) {
1138                 r = imap_threaded_connect_cmd(folder,
1139                                               account->tunnelcmd,
1140                                               account->recv_server,
1141                                               port);
1142         }
1143         else 
1144 #endif
1145         {
1146 #ifdef USE_GNUTLS
1147                 if (ssl_type == SSL_TUNNEL) {
1148                         r = imap_threaded_connect_ssl(folder,
1149                                                       account->recv_server,
1150                                                       port);
1151                 }
1152                 else 
1153 #endif
1154                 {
1155                         r = imap_threaded_connect(folder,
1156                                                   account->recv_server,
1157                                                   port);
1158                 }
1159         }
1160         
1161         statuswindow_pop_all();
1162         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1163                 authenticated = TRUE;
1164         }
1165         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1166                 authenticated = FALSE;
1167         }
1168         else {
1169 #ifdef USE_GNUTLS
1170                 if (r == MAILIMAP_ERROR_SSL)
1171                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1172                 else
1173 #endif
1174                         imap_handle_error(NULL, account->recv_server, r);
1175
1176                 if(!prefs_common.no_recv_err_panel) {
1177                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1178                                          account->recv_server, port);
1179                 } else {
1180                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1181                                          account->recv_server, port);
1182                 } 
1183                 
1184                 return NULL;
1185         }
1186         
1187         session = g_new0(IMAPSession, 1);
1188         session_init(SESSION(session), account, FALSE);
1189         SESSION(session)->type             = SESSION_IMAP;
1190         SESSION(session)->server           = g_strdup(account->recv_server);
1191         SESSION(session)->port             = port;
1192         SESSION(session)->sock             = NULL;
1193         
1194         SESSION(session)->destroy          = imap_session_destroy;
1195
1196         session->capability = NULL;
1197         
1198         session->authenticated = authenticated;
1199         session->mbox = NULL;
1200         session->exists = 0;
1201         session->recent = 0;
1202         session->expunge = 0;
1203         session->cmd_count = 0;
1204         session->folder = folder;
1205         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1206
1207 #ifdef USE_GNUTLS
1208         if (account->ssl_imap == SSL_STARTTLS) {
1209                 gint ok;
1210
1211                 ok = imap_cmd_starttls(session);
1212                 if (ok != MAILIMAP_NO_ERROR) {
1213                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1214                         if (!is_fatal(ok)) {
1215                                 SESSION(session)->sock = NULL;
1216                                 imap_safe_destroy(session);
1217                         }
1218                         return NULL;
1219                 }
1220
1221                 imap_free_capabilities(session);
1222                 session->authenticated = FALSE;
1223                 session->uidplus = FALSE;
1224                 session->cmd_count = 1;
1225         }
1226 #endif
1227         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1228                     (session->authenticated) ? "pre" : "un");
1229         
1230         session_register_ping(SESSION(session), imap_ping);
1231
1232         return session;
1233 }
1234
1235 static gint imap_session_authenticate(IMAPSession *session, 
1236                                       PrefsAccount *account)
1237 {
1238         gchar *pass, *acc_pass;
1239         gboolean failed = FALSE;
1240         gint ok = MAILIMAP_NO_ERROR;
1241         g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1242
1243         if (password_get(account->userid, account->recv_server, "imap",
1244                          SESSION(session)->port, &pass)) {
1245                 Xstrdup_a(acc_pass, pass, {g_free(pass); return MAILIMAP_NO_ERROR;});
1246                 g_free(pass);
1247         } else {
1248                 acc_pass = account->passwd;
1249         }
1250 try_again:
1251         pass = acc_pass;
1252         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1253                 gchar *tmp_pass;
1254                 tmp_pass = input_dialog_query_password_keep(account->recv_server, 
1255                                                             account->userid,
1256                                                             &(account->session_passwd));
1257                 if (!tmp_pass)
1258                         return MAILIMAP_NO_ERROR;
1259                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1260                 g_free(tmp_pass);
1261         } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1262                 pass = "";
1263         }
1264         if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1265                 
1266                 if (!failed && !is_fatal(ok)) {
1267                         acc_pass = NULL;
1268                         failed = TRUE;
1269                         if (account->session_passwd != NULL) {
1270                                 g_free(account->session_passwd);
1271                                 account->session_passwd = NULL;
1272                         }
1273                         goto try_again;
1274                 } else {
1275                         if (prefs_common.no_recv_err_panel) {
1276                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1277                                 mainwindow_show_error();
1278                         } else
1279                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1280                 }               
1281
1282                 return ok;
1283         } 
1284
1285         statuswindow_pop_all();
1286         session->authenticated = TRUE;
1287         return MAILIMAP_NO_ERROR;
1288 }
1289
1290 static void imap_session_destroy(Session *session)
1291 {
1292         if (session->state != SESSION_DISCONNECTED)
1293                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1294         
1295         imap_free_capabilities(IMAP_SESSION(session));
1296         g_free(IMAP_SESSION(session)->mbox);
1297 }
1298
1299 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1300 {
1301         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1302 }
1303
1304 static guint get_file_size_with_crs(const gchar *filename) 
1305 {
1306         FILE *fp = NULL;
1307         guint cnt = 0;
1308         gchar buf[4096];
1309         
1310         if (filename == NULL)
1311                 return -1;
1312         
1313         fp = g_fopen(filename, "rb");
1314         if (!fp)
1315                 return -1;
1316         
1317         while (fgets(buf, sizeof (buf), fp) != NULL) {
1318                 cnt += strlen(buf);
1319                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1320                         cnt++;
1321         }
1322         
1323         fclose(fp);
1324         return cnt;
1325 }
1326
1327 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1328 {
1329         gchar *path, *filename;
1330
1331         path = folder_item_get_path(item);
1332
1333         if (!is_dir_exist(path)) {
1334                 g_free(path);
1335                 return;
1336         }
1337
1338         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1339         g_free(path);
1340
1341         if (is_file_exist(filename)) {
1342                 claws_unlink(filename);
1343         }
1344         g_free(filename);
1345 }
1346
1347 typedef struct _TagsData {
1348         gchar *str;
1349         GSList *msglist;
1350         IMAPFolderItem *item;
1351 } TagsData;
1352
1353 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1354 {
1355         IMAPSession *session;
1356         gint ok, can_create_tags;
1357         Folder *folder = NULL;
1358         TagsData *ht_data = NULL;
1359         GSList *cur;
1360
1361         g_return_if_fail(item != NULL);
1362         g_return_if_fail(msginfo != NULL);
1363
1364         folder = item->folder;
1365         debug_print("getting session...\n");
1366         session = imap_session_get(folder);
1367         
1368         if (!session) {
1369                 debug_print("can't get session\n");
1370                 return;
1371         }
1372
1373         ok = imap_select(session, IMAP_FOLDER(folder), item,
1374                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1375
1376         if (ok != MAILIMAP_NO_ERROR) {
1377                 return;
1378         }
1379
1380         
1381         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1382                 return;
1383         
1384         if (IMAP_FOLDER_ITEM(item)->batching) {
1385                 /* instead of performing an UID STORE command for each message change,
1386                  * as a lot of them can change "together", we just fill in hashtables
1387                  * and defer the treatment so that we're able to send only one
1388                  * command.
1389                  */
1390                 debug_print("IMAP batch mode on, deferring tags change\n");
1391                 for (cur = tags_set; cur; cur = cur->next) {
1392                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1393                         if (cur_tag) {
1394                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1395                                         GINT_TO_POINTER(cur_tag));
1396                                 if (ht_data == NULL) {
1397                                         ht_data = g_new0(TagsData, 1);
1398                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1399                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1400                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1401                                                 GINT_TO_POINTER(cur_tag), ht_data);
1402                                 }
1403                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1404                         } 
1405                 }
1406                 for (cur = tags_unset; cur; cur = cur->next) {
1407                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1408                         if (cur_tag) {
1409                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1410                                         GINT_TO_POINTER(cur_tag));
1411                                 if (ht_data == NULL) {
1412                                         ht_data = g_new0(TagsData, 1);
1413                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1414                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1415                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1416                                                 GINT_TO_POINTER(cur_tag), ht_data);
1417                                 }
1418                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1419                         }
1420                 }
1421         } else {
1422                 GSList *list_set = NULL;
1423                 GSList *list_unset = NULL;
1424                 GSList numlist;
1425                 
1426                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1427                 numlist.next = NULL;
1428         
1429                 debug_print("IMAP changing tags NOW\n");
1430                 for (cur = tags_set; cur; cur = cur->next) {
1431                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1432                         const gchar *str = tags_get_tag(cur_tag);
1433                         if (IS_NOT_RESERVED_TAG(str))
1434                                 list_set = g_slist_prepend(list_set, g_strdup(str));
1435                 }
1436                 if (list_set) {
1437                         ok = imap_set_message_flags(session, 
1438                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1439                         slist_free_strings_full(list_set);
1440                         if (ok != MAILIMAP_NO_ERROR) {
1441                                 return;
1442                         }
1443                 }
1444
1445                 for (cur = tags_unset; cur; cur = cur->next) {
1446                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1447                         const gchar *str = tags_get_tag(cur_tag);
1448                         if (IS_NOT_RESERVED_TAG(str))
1449                                 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1450                 }
1451                 if (list_unset) {
1452                         ok = imap_set_message_flags(session, 
1453                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1454                         slist_free_strings_full(list_unset);
1455                         if (ok != MAILIMAP_NO_ERROR) {
1456                                 return;
1457                         }
1458                 }
1459         }
1460 }
1461
1462 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1463                                   gboolean headers, gboolean body)
1464 {
1465         gchar *path, *filename;
1466         IMAPSession *session;
1467         gint ok;
1468
1469         g_return_val_if_fail(folder != NULL, NULL);
1470         g_return_val_if_fail(item != NULL, NULL);
1471
1472         if (uid == 0)
1473                 return NULL;
1474
1475         path = folder_item_get_path(item);
1476         if (!is_dir_exist(path))
1477                 make_dir_hier(path);
1478         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1479         g_free(path);
1480         debug_print("trying to fetch cached %s\n", filename);
1481         if (is_file_exist(filename)) {
1482                 /* see whether the local file represents the whole message
1483                  * or not. As the IMAP server reports size with \r chars,
1484                  * we have to update the local file (UNIX \n only) size */
1485                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1486                 guint have_size = -1;
1487
1488                 if (cached)
1489                         debug_print("message %d has been already %scached.\n", uid,
1490                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1491                 
1492                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1493                         have_size = get_file_size_with_crs(filename);
1494                         if (cached && (cached->size <= have_size || !body)) {
1495                                 ok = file_strip_crs(filename);
1496                                 if (ok == 0 && cached && cached->size <= have_size) {
1497                                         /* we have it all and stripped */
1498                                         debug_print("...fully cached in fact (%u/%zd); setting flag.\n",
1499                                                         have_size, cached->size);
1500                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1501                                 }
1502                                 procmsg_msginfo_free(cached);
1503                                 return filename;
1504                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1505                                 debug_print("message not cached and file recent, considering file complete\n");
1506                                 ok = file_strip_crs(filename);
1507                                 if (ok == 0)
1508                                         return filename;
1509                         } else {
1510                                 procmsg_msginfo_free(cached);
1511                         }
1512                 }
1513                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1514                         procmsg_msginfo_free(cached);
1515                         return filename;
1516                 }
1517         } else {
1518                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1519                 if (cached) {
1520                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1521                         procmsg_msginfo_free(cached);
1522                 }
1523         }
1524
1525         debug_print("getting session...\n");
1526         session = imap_session_get(folder);
1527         
1528         if (!session) {
1529                 g_free(filename);
1530                 return NULL;
1531         }
1532         session_set_access_time(SESSION(session));
1533         lock_session(session); /* unlocked later in the function */
1534
1535         debug_print("IMAP fetching messages\n");
1536         ok = imap_select(session, IMAP_FOLDER(folder), item,
1537                          NULL, NULL, NULL, NULL, NULL, FALSE);
1538         if (ok != MAILIMAP_NO_ERROR) {
1539                 g_warning("can't select mailbox %s\n", item->path);
1540                 g_free(filename);
1541                 return NULL;
1542         }
1543
1544         session_set_access_time(SESSION(session));
1545
1546         debug_print("getting message %d...\n", uid);
1547         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1548
1549         if (ok != MAILIMAP_NO_ERROR) {
1550                 g_warning("can't fetch message %d\n", uid);
1551                 g_free(filename);
1552                 return NULL;
1553         }
1554
1555         session_set_access_time(SESSION(session));
1556         unlock_session(session);
1557
1558         ok = file_strip_crs(filename);
1559
1560         if (ok == 0 && headers && body) {
1561                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1562                 if (cached) {
1563                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1564                         procmsg_msginfo_free(cached);
1565                 }
1566         } else if (ok == -1) {
1567                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1568                 if (cached) {
1569                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1570                         procmsg_msginfo_free(cached);
1571                 }
1572         }
1573         return filename;
1574 }
1575
1576 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1577 {
1578         gchar *path, *filename;
1579         guint size = 0;
1580         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1581         
1582         if (!cached)
1583                 return FALSE;
1584
1585         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1586                 procmsg_msginfo_free(cached);
1587                 return TRUE;
1588         }
1589         path = folder_item_get_path(item);
1590         if (!is_dir_exist(path)) {
1591                 g_free(path);
1592                 return FALSE;
1593         }
1594
1595         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1596         g_free(path);
1597         if (is_file_exist(filename)) {
1598                 if (cached && cached->total_size == cached->size) {
1599                         /* fast path */
1600                         g_free(filename);
1601                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1602                         return TRUE;
1603                 }
1604                 size = get_file_size_with_crs(filename);
1605         }
1606         g_free(filename);
1607         debug_print("msg %d cached, has size %d, full should be %zd.\n", uid, size, cached->size);
1608         if (cached && size >= cached->size) {
1609                 cached->total_size = cached->size;
1610                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1611                 procmsg_msginfo_free(cached);
1612                 return TRUE;
1613         }
1614         if (cached)
1615                 procmsg_msginfo_free(cached);
1616         return FALSE;   
1617 }
1618
1619 void imap_cache_msg(FolderItem *item, gint msgnum)
1620 {
1621         Folder *folder = NULL;
1622         
1623         if (!item)
1624                 return;
1625         folder = item->folder;
1626         
1627         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1628                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1629                 debug_print("fetched %s\n", tmp);
1630                 g_free(tmp);
1631         }
1632 }
1633
1634 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1635                          const gchar *file, MsgFlags *flags)
1636 {
1637         gint ret;
1638         GSList file_list;
1639         MsgFileInfo fileinfo;
1640
1641         g_return_val_if_fail(file != NULL, -1);
1642
1643         fileinfo.msginfo = NULL;
1644         fileinfo.file = (gchar *)file;
1645         fileinfo.flags = flags;
1646         file_list.data = &fileinfo;
1647         file_list.next = NULL;
1648
1649         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1650         return ret;
1651 }
1652
1653 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1654                    GHashTable *relation)
1655 {
1656         gchar *destdir;
1657         IMAPSession *session;
1658         guint32 last_uid = 0;
1659         GSList *cur;
1660         MsgFileInfo *fileinfo;
1661         gint ok = MAILIMAP_NO_ERROR;
1662         gint curnum = 0, total = 0;
1663         gboolean missing_uids = FALSE;
1664
1665         g_return_val_if_fail(folder != NULL, -1);
1666         g_return_val_if_fail(dest != NULL, -1);
1667         g_return_val_if_fail(file_list != NULL, -1);
1668         
1669         debug_print("getting session...\n");
1670         session = imap_session_get(folder);
1671         if (!session) {
1672                 return -1;
1673         }
1674         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1675         if (is_fatal(ok))
1676                 return -1;
1677         statusbar_print_all(_("Adding messages..."));
1678         total = g_slist_length(file_list);
1679         for (cur = file_list; cur != NULL; cur = cur->next) {
1680                 IMAPFlags iflags = 0;
1681                 guint32 new_uid = 0;
1682                 gchar *real_file = NULL;
1683                 fileinfo = (MsgFileInfo *)cur->data;
1684
1685                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1686                 curnum++;
1687
1688                 if (fileinfo->flags) {
1689                         if (MSG_IS_MARKED(*fileinfo->flags))
1690                                 iflags |= IMAP_FLAG_FLAGGED;
1691                         if (MSG_IS_REPLIED(*fileinfo->flags))
1692                                 iflags |= IMAP_FLAG_ANSWERED;
1693                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1694                                 iflags |= IMAP_FLAG_FORWARDED;
1695                         if (MSG_IS_SPAM(*fileinfo->flags))
1696                                 iflags |= IMAP_FLAG_SPAM;
1697                         else
1698                                 iflags |= IMAP_FLAG_HAM;
1699                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1700                                 iflags |= IMAP_FLAG_SEEN;
1701                         
1702                 }
1703                 
1704                 if (real_file == NULL)
1705                         real_file = g_strdup(fileinfo->file);
1706                 
1707                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1708                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1709                     folder_has_parent_of_type(dest, F_DRAFT) ||
1710                     folder_has_parent_of_type(dest, F_TRASH))
1711                         iflags |= IMAP_FLAG_SEEN;
1712
1713                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1714                                      &new_uid);
1715
1716                 if (ok != MAILIMAP_NO_ERROR) {
1717                         g_warning("can't append message %s\n", real_file);
1718                         g_free(real_file);
1719                         g_free(destdir);
1720                         statusbar_progress_all(0,0,0);
1721                         statusbar_pop_all();
1722                         return -1;
1723                 } else {
1724                         debug_print("appended new message as %d\n", new_uid);
1725                         /* put the local file in the imapcache, so that we don't
1726                          * have to fetch it back later. */
1727                         
1728                         if (new_uid == 0) {
1729                                 missing_uids = TRUE;
1730                                 debug_print("Missing UID (0)\n");
1731                         }
1732                         if (new_uid > 0) {
1733                                 gchar *cache_path = folder_item_get_path(dest);
1734                                 if (!is_dir_exist(cache_path))
1735                                         make_dir_hier(cache_path);
1736                                 if (is_dir_exist(cache_path)) {
1737                                         gchar *cache_file = g_strconcat(
1738                                                 cache_path, G_DIR_SEPARATOR_S, 
1739                                                 itos(new_uid), NULL);
1740                                         copy_file(real_file, cache_file, TRUE);
1741                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1742                                         g_free(cache_file);
1743                                 }
1744                                 g_free(cache_path);
1745                         }
1746                 }
1747
1748                 if (relation != NULL)
1749                         g_hash_table_insert(relation, fileinfo->msginfo != NULL ? 
1750                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1751                                           GINT_TO_POINTER(new_uid));
1752                 if (last_uid < new_uid) {
1753                         last_uid = new_uid;
1754                 }
1755
1756                 g_free(real_file);
1757         }
1758         
1759         statusbar_progress_all(0,0,0);
1760         statusbar_pop_all();
1761         
1762         
1763         g_free(destdir);
1764
1765         imap_scan_required(folder, dest);
1766
1767         session = imap_session_get(folder);
1768         if (!session) {
1769                 return -1;
1770         }
1771         if (missing_uids) {
1772                 gint a;
1773                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1774                          &a, NULL, NULL, NULL, NULL, FALSE);
1775         }
1776         return last_uid;
1777 }
1778
1779 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1780 {
1781         GSList *result = NULL;
1782         clistiter *list;
1783         guint32 start, end, t;
1784         GSList *cur;
1785
1786         if (!set || !set->set_list)
1787                 return NULL;
1788
1789         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1790                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1791                 start = item->set_first;
1792                 end = item->set_last;
1793                 if (start <= end) {
1794                         for (t = start; t <= end; t++) {
1795                                 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1796                         }
1797                 }
1798         }
1799         result = g_slist_reverse(result);
1800         if (debug_get_mode()) {
1801                 debug_print("flat imap set: ");
1802                 for (cur = result; cur; cur = cur->next) {
1803                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1804                 }
1805                 debug_print("\n");
1806         }
1807         
1808         return result;
1809 }
1810 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1811                               MsgInfoList *msglist, GHashTable *relation)
1812 {
1813         FolderItem *src;
1814         gchar *destdir;
1815         GSList *seq_list, *cur;
1816         MsgInfo *msginfo;
1817         IMAPSession *session;
1818         gint ok = MAILIMAP_NO_ERROR;
1819         GHashTable *uid_hash;
1820         gint last_num = 0;
1821
1822         g_return_val_if_fail(folder != NULL, -1);
1823         g_return_val_if_fail(dest != NULL, -1);
1824         g_return_val_if_fail(msglist != NULL, -1);
1825         
1826         debug_print("getting session...\n");
1827         session = imap_session_get(folder);
1828         
1829         if (!session) {
1830                 return -1;
1831         }
1832
1833         msginfo = (MsgInfo *)msglist->data;
1834         src = msginfo->folder;
1835         if (src == dest) {
1836                 g_warning("the src folder is identical to the dest.\n");
1837                 return -1;
1838         }
1839
1840         if (src->folder != dest->folder) {
1841                 GSList *infolist = NULL, *cur;
1842                 int res = -1;
1843                 for (cur = msglist; cur; cur = cur->next) {
1844                         msginfo = (MsgInfo *)cur->data;
1845                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1846                         fileinfo->file = procmsg_get_message_file(msginfo);
1847                         fileinfo->flags = &(msginfo->flags);
1848                         infolist = g_slist_prepend(infolist, fileinfo);
1849                 }
1850                 infolist = g_slist_reverse(infolist);
1851                 res = folder_item_add_msgs(dest, infolist, FALSE);
1852                 for (cur = infolist; cur; cur = cur->next) {
1853                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1854                         g_free(info->file);
1855                         g_free(info);
1856                 }
1857                 g_slist_free(infolist);
1858                 return res;
1859         } 
1860
1861         lock_session(session); /* unlocked later in the function */
1862
1863         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1864                          NULL, NULL, NULL, NULL, NULL, FALSE);
1865         if (ok != MAILIMAP_NO_ERROR) {
1866                 return ok;
1867         }
1868
1869         unlock_session(session);
1870
1871         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1872
1873         if (is_fatal(ok))
1874                 return ok;
1875
1876         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1877         uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
1878         
1879         statusbar_print_all(_("Copying messages..."));
1880         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1881                 struct mailimap_set * seq_set;
1882                 struct mailimap_set * source = NULL;
1883                 struct mailimap_set * dest = NULL;
1884                 seq_set = cur->data;
1885
1886                 debug_print("Copying messages from %s to %s ...\n",
1887                             src->path, destdir);
1888
1889                 lock_session(session); /* unlocked later in the function */
1890                 ok = imap_cmd_copy(session, seq_set, destdir,
1891                         &source, &dest);
1892                 
1893                 if (is_fatal(ok)) {
1894                         session = NULL;
1895                 }
1896
1897                 if (ok == MAILIMAP_NO_ERROR) {
1898                         unlock_session(session);
1899                         if (relation && source && dest) {
1900                                 GSList *s_list = flatten_mailimap_set(source);
1901                                 GSList *d_list = flatten_mailimap_set(dest);
1902                                 GSList *s_cur, *d_cur;
1903                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1904
1905                                         for (s_cur = s_list, d_cur = d_list; 
1906                                              s_cur && d_cur; 
1907                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1908                                                 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
1909                                         }
1910
1911                                 } else {
1912                                         debug_print("hhhmm, source list length != dest list length.\n");
1913                                 }
1914                                 g_slist_free(s_list);
1915                                 g_slist_free(d_list);
1916                         }
1917                 }
1918
1919
1920                 if (source)
1921                         mailimap_set_free(source);
1922                 if (dest)
1923                         mailimap_set_free(dest);
1924
1925                 if (ok != MAILIMAP_NO_ERROR) {
1926                         g_hash_table_destroy(uid_hash);
1927                         imap_lep_set_free(seq_list);
1928                         statusbar_pop_all();
1929                         return -1;
1930                 }
1931         }
1932
1933         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1934                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1935                 gpointer hashval;
1936
1937                 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
1938                 
1939                 if (hashval != NULL) {
1940                         gint num = GPOINTER_TO_INT(hashval);
1941                         g_hash_table_insert(relation, msginfo,
1942                                           GINT_TO_POINTER(num));
1943                         if (num > last_num)
1944                                 last_num = num;
1945                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1946                         /* put the local file in the imapcache, so that we don't
1947                          * have to fetch it back later. */
1948                         if (num > 0) {
1949                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1950                                 gchar *real_file = g_strconcat(
1951                                         cache_path, G_DIR_SEPARATOR_S, 
1952                                         itos(msginfo->msgnum), NULL);
1953                                 gchar *cache_file = NULL;
1954                                 g_free(cache_path);
1955                                 cache_path = folder_item_get_path(dest);
1956                                 cache_file = g_strconcat(
1957                                         cache_path, G_DIR_SEPARATOR_S, 
1958                                         itos(num), NULL);
1959                                 if (!is_dir_exist(cache_path))
1960                                         make_dir_hier(cache_path);
1961                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1962                                         copy_file(real_file, cache_file, TRUE);
1963                                         debug_print("copied to cache: %s\n", cache_file);
1964                                 }
1965                                 g_free(real_file);
1966                                 g_free(cache_file);
1967                                 g_free(cache_path);
1968                         }
1969                 } else
1970                         g_hash_table_insert(relation, msginfo,
1971                                           GINT_TO_POINTER(0));
1972         }
1973         statusbar_pop_all();
1974
1975         g_hash_table_destroy(uid_hash);
1976         imap_lep_set_free(seq_list);
1977
1978         g_free(destdir);
1979         
1980         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1981         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1982         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1983         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1984
1985         imap_scan_required(folder, dest);
1986         if (ok == MAILIMAP_NO_ERROR)
1987                 return last_num;
1988         else
1989                 return -1;
1990 }
1991
1992 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1993 {
1994         GSList msglist;
1995
1996         g_return_val_if_fail(msginfo != NULL, -1);
1997
1998         msglist.data = msginfo;
1999         msglist.next = NULL;
2000
2001         return imap_copy_msgs(folder, dest, &msglist, NULL);
2002 }
2003
2004 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
2005                     MsgInfoList *msglist, GHashTable *relation)
2006 {
2007         MsgInfo *msginfo;
2008         gint ret;
2009
2010         g_return_val_if_fail(folder != NULL, -1);
2011         g_return_val_if_fail(dest != NULL, -1);
2012         g_return_val_if_fail(msglist != NULL, -1);
2013
2014         msginfo = (MsgInfo *)msglist->data;
2015         g_return_val_if_fail(msginfo->folder != NULL, -1);
2016
2017         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
2018         return ret;
2019 }
2020
2021 static gboolean imap_matcher_type_is_local(gint matchertype)
2022 {
2023         switch (matchertype) {
2024         case MATCHCRITERIA_FROM:
2025         case MATCHCRITERIA_TO:
2026         case MATCHCRITERIA_CC:
2027         case MATCHCRITERIA_TO_OR_CC:
2028         case MATCHCRITERIA_SUBJECT:
2029         case MATCHCRITERIA_REFERENCES:
2030         case MATCHCRITERIA_INREPLYTO:
2031         case MATCHCRITERIA_AGE_GREATER:
2032         case MATCHCRITERIA_AGE_LOWER:
2033         case MATCHCRITERIA_FORWARDED:
2034         case MATCHCRITERIA_SPAM:
2035         case MATCHCRITERIA_UNREAD:
2036         case MATCHCRITERIA_NEW:
2037         case MATCHCRITERIA_MARKED:
2038         case MATCHCRITERIA_REPLIED:
2039         case MATCHCRITERIA_DELETED:
2040         case MATCHCRITERIA_SIZE_GREATER:
2041         case MATCHCRITERIA_SIZE_SMALLER:
2042         case MATCHCRITERIA_SIZE_EQUAL:
2043                 return TRUE;
2044         }
2045         return FALSE;
2046 }
2047
2048 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2049 {
2050         if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2051                 IMAPSearchKey* result = NULL;
2052                 gboolean invert = FALSE;
2053                 gint matchertype = match->criteria;
2054
2055                 if (is_all) {
2056                         *is_all = FALSE;
2057                 }
2058
2059                 switch (matchertype) {
2060                 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2061                 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2062                 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2063                 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2064                 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2065                 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2066                 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2067                 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2068                 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2069                 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2070                 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2071                 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2072                 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2073                 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2074                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2075                 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2076                 }
2077
2078                 /* 
2079                  * this aborts conversion even for predicates understood by the following code.
2080                  * while that might seem wasteful, claws local search for information listed below
2081                  * has proven faster than IMAP search plus network roundtrips. once this changes,
2082                  * consider removing these exceptions.
2083                  */
2084                 if (imap_matcher_type_is_local(matchertype))
2085                         return NULL;
2086
2087                 /* the Message-ID header is also cached */
2088                 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2089                         return NULL;
2090                 }
2091
2092                 switch (matchertype) {
2093                 case MATCHCRITERIA_FORWARDED:
2094                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2095                         break;
2096
2097                 case MATCHCRITERIA_SPAM:
2098                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2099                         break;
2100
2101                 case MATCHCRITERIA_INREPLYTO:
2102                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2103                         break;
2104
2105                 case MATCHCRITERIA_REFERENCES:
2106                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2107                         break;
2108
2109                 case MATCHCRITERIA_TO_OR_CC:
2110                         result = imap_search_or(
2111                                         imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2112                                         imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2113                                         );
2114                         break;
2115
2116                 case MATCHCRITERIA_HEADERS_PART:
2117                         result = imap_search_and(
2118                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2119                                         imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2120                                         );
2121                         break;
2122
2123                 case MATCHCRITERIA_SIZE_EQUAL:
2124                         result = imap_search_and(
2125                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2126                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2127                                         );
2128                         break;
2129
2130                 case MATCHCRITERIA_NOT_UNREAD:
2131                         result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2132                         break;
2133
2134                 case MATCHCRITERIA_UNREAD:
2135                         result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2136                         break;
2137
2138                 case MATCHCRITERIA_NEW:
2139                         result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2140                         break;
2141
2142                 case MATCHCRITERIA_MARKED:
2143                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2144                         break;
2145
2146                 case MATCHCRITERIA_DELETED:
2147                         result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2148                         break;
2149
2150                 case MATCHCRITERIA_REPLIED:
2151                         result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2152                         break;
2153
2154                 case MATCHCRITERIA_TAG:
2155                         {
2156                                 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2157                                 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2158                                 g_free(tmp);
2159                         }
2160                         break;
2161
2162                 case MATCHCRITERIA_SUBJECT:
2163                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2164                         break;
2165
2166                 case MATCHCRITERIA_FROM:
2167                         result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2168                         break;
2169
2170                 case MATCHCRITERIA_TO:
2171                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2172                         break;
2173
2174                 case MATCHCRITERIA_CC:
2175                         result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2176                         break;
2177
2178                 case MATCHCRITERIA_AGE_GREATER:
2179                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2180                         break;
2181
2182                 case MATCHCRITERIA_AGE_LOWER:
2183                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2184                         break;
2185
2186                 case MATCHCRITERIA_BODY_PART:
2187                         result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2188                         break;
2189
2190                 case MATCHCRITERIA_MESSAGE:
2191                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2192                         break;
2193
2194                 case MATCHCRITERIA_HEADER:
2195                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2196                         break;
2197
2198                 case MATCHCRITERIA_SIZE_GREATER:
2199                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2200                         break;
2201
2202                 case MATCHCRITERIA_SIZE_SMALLER:
2203                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2204                         break;
2205
2206                 default:
2207                         result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2208                         if (is_all) {
2209                                 *is_all = TRUE;
2210                         }
2211                         break;
2212                 }
2213
2214                 if (invert) {
2215                         result = imap_search_not(result);
2216                         if (is_all && *is_all) {
2217                                 *is_all = FALSE;
2218                         }
2219                 }
2220
2221                 return result;
2222         }
2223
2224         return NULL;
2225 }
2226
2227 static void imap_change_search_charset(IMAPFolder *folder)
2228 {
2229         /* If server supports charset in searches, but the last used one failed,
2230          * changed to the next preferred charset. If none are still available,
2231          * disable charset searches.
2232          * Charsets are tried in the following order: 
2233          * UTF-8, locale's charset, UTF-7.
2234          */
2235
2236         if (folder->search_charset_supported) {
2237                 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2238                         folder->search_charset = "UTF-8";
2239                 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2240                         folder->search_charset = "UTF-7";
2241                 else {
2242                         folder->search_charset = NULL;
2243                         folder->search_charset_supported = FALSE;
2244                 }
2245         }
2246 }
2247
2248 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2249                                                   MatcherProp *utf8_prop,
2250                                                   gchar **charset)
2251 {
2252         /* If the match is going to be done locally, or the criteria is on
2253          * tag (special-cased to modified-UTF-7), or the expression searched
2254          * is ASCII, don't bother converting.
2255          */
2256         if (imap_matcher_type_is_local(utf8_prop->criteria)
2257          || utf8_prop->criteria == MATCHCRITERIA_TAG
2258          || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2259          || utf8_prop->expr == NULL
2260          || is_ascii_str(utf8_prop->expr))
2261                 return matcherprop_new(utf8_prop->criteria,
2262                                utf8_prop->header,
2263                                utf8_prop->matchtype,
2264                                utf8_prop->expr,
2265                                utf8_prop->value);
2266         else {
2267                 gchar *conv_expr = NULL;
2268
2269                 /* If the search is server-side and the server doesn't support
2270                  * searching with the charsets we handle, bail out.
2271                  */
2272                 if (folder->search_charset_supported == FALSE)
2273                         return NULL;
2274
2275                 /* Else, convert. */
2276                 if (*charset == NULL)
2277                         *charset = g_strdup(folder->search_charset);
2278
2279                 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2280
2281                 if (conv_expr == NULL)
2282                         conv_expr = g_strdup(utf8_prop->expr);
2283
2284                 return matcherprop_new(utf8_prop->criteria,
2285                                utf8_prop->header,
2286                                utf8_prop->matchtype,
2287                                conv_expr,
2288                                utf8_prop->value);
2289         }
2290 }
2291
2292 static gint     search_msgs             (Folder                 *folder,
2293                                          FolderItem             *container,
2294                                          MsgNumberList          **msgs,
2295                                          gboolean               *on_server,
2296                                          MatcherList            *predicate,
2297                                          SearchProgressNotify   progress_cb,
2298                                          gpointer               progress_data)
2299 {
2300         IMAPSearchKey* key = NULL;
2301         GSList* cur;
2302         int result = -1;
2303         clist* uidlist = NULL;
2304         gboolean server_filtering_useless = FALSE;
2305         IMAPSession *session;
2306         gchar *charset_to_use = NULL;
2307
2308         if (on_server == NULL || !*on_server) {
2309                 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2310                                 predicate, progress_cb, progress_data);
2311         }
2312
2313         for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2314                 IMAPSearchKey* matcherPart = NULL;
2315                 MatcherProp* prop = (MatcherProp*) cur->data;
2316                 gboolean is_all;
2317                 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2318
2319                 if (imap_prop == NULL) {
2320                         /* Couldn't convert matcherprop to IMAP - probably not ascii
2321                          * and server doesn't support the charsets we do. */
2322                          return -1;
2323                 }
2324
2325                 matcherPart = search_make_key(imap_prop, &is_all);
2326
2327                 matcherprop_free(imap_prop);
2328
2329                 if (on_server) {
2330                         *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2331                 }
2332
2333                 if (matcherPart) {
2334                         if (key == NULL) {
2335                                 key = matcherPart;
2336                                 server_filtering_useless = is_all;
2337                         } else if (predicate->bool_and) {
2338                                 key = imap_search_and(key, matcherPart);
2339                                 server_filtering_useless &= is_all;
2340                         } else {
2341                                 key = imap_search_or(key, matcherPart);
2342                                 server_filtering_useless |= is_all;
2343                         }
2344                 }
2345         }
2346
2347         if (server_filtering_useless) {
2348                 imap_search_free(key);
2349                 key = NULL;
2350         }
2351
2352         if (key == NULL && progress_cb != NULL) {
2353                 GSList* cur;
2354                 GSList* list;
2355                 int count = 0;
2356
2357                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2358                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2359
2360                 list = folder_item_get_msg_list(container);
2361                 for (cur = list; cur != NULL; cur = cur->next) {
2362                         *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2363                         count++;
2364                 }
2365                 procmsg_msg_list_free(list);
2366
2367                 *msgs = g_slist_reverse(*msgs);
2368
2369                 return count;
2370         }
2371
2372         session = imap_session_get(folder);
2373         if (!session) {
2374                 return -1;
2375         }
2376         result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2377                          NULL, NULL, NULL, NULL, NULL, TRUE);
2378         if (result != MAILIMAP_NO_ERROR)
2379                 return -1;
2380
2381         if (progress_cb)
2382                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2383         result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2384         if (progress_cb)
2385                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2386
2387         if (result == MAILIMAP_NO_ERROR) {
2388                 gint result = 0;
2389
2390                 *msgs = imap_uid_list_from_lep(uidlist, &result);
2391
2392                 mailimap_search_result_free(uidlist);
2393
2394                 if (charset_to_use != NULL)
2395                         g_free(charset_to_use);
2396
2397                 return result;
2398         } else if (charset_to_use != NULL) {
2399                 /* If search failed and was on an 8-bit string, try the next
2400                  * available charset to search if there still are some.
2401                  */
2402                 g_free(charset_to_use);
2403                 
2404                 imap_change_search_charset(IMAP_FOLDER(folder));
2405                 if (IMAP_FOLDER(folder)->search_charset_supported)
2406                         return search_msgs(folder, container, msgs, on_server, predicate,
2407                                    progress_cb, progress_data);
2408                 else
2409                         return -1;
2410         } else {
2411                 return -1;
2412         }
2413 }
2414
2415
2416 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
2417                                 MsgInfoList *msglist, GHashTable *relation)
2418 {
2419         gchar *destdir, *dir;
2420         GSList *numlist = NULL, *cur;
2421         MsgInfo *msginfo;
2422         IMAPSession *session;
2423         gint ok = MAILIMAP_NO_ERROR;
2424         
2425         g_return_val_if_fail(folder != NULL, -1);
2426         g_return_val_if_fail(dest != NULL, -1);
2427         g_return_val_if_fail(msglist != NULL, -1);
2428
2429         debug_print("getting session...\n");
2430         session = imap_session_get(folder);
2431         if (!session) {
2432                 return -1;
2433         }
2434
2435         lock_session(session); /* unlocked later in the function */
2436
2437         msginfo = (MsgInfo *)msglist->data;
2438
2439         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2440                          NULL, NULL, NULL, NULL, NULL, FALSE);
2441         if (ok != MAILIMAP_NO_ERROR) {
2442                 return ok;
2443         }
2444
2445         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2446         if (is_fatal(ok)) {
2447                 g_free(destdir);
2448                 return ok;
2449         }
2450         for (cur = msglist; cur; cur = cur->next) {
2451                 msginfo = (MsgInfo *)cur->data;
2452                 if (!MSG_IS_DELETED(msginfo->flags))
2453                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2454         }
2455         numlist = g_slist_reverse(numlist);
2456
2457         if (numlist != NULL) {
2458                 ok = imap_set_message_flags
2459                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2460                 if (ok != MAILIMAP_NO_ERROR) {
2461                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2462                         g_free(destdir);
2463                         return ok;
2464                 }
2465         } /* else we just need to expunge */
2466         ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
2467         if (ok != MAILIMAP_NO_ERROR) {
2468                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2469                 g_free(destdir);
2470                 return ok;
2471         }
2472         
2473         session->folder_content_changed = TRUE;
2474         unlock_session(session);
2475
2476         dir = folder_item_get_path(msginfo->folder);
2477         if (is_dir_exist(dir)) {
2478                 for (cur = msglist; cur; cur = cur->next) {
2479                         msginfo = (MsgInfo *)cur->data;
2480                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2481                 }
2482         }
2483         g_free(dir);
2484
2485         g_slist_free(numlist);
2486
2487         imap_scan_required(folder, dest);
2488
2489         g_free(destdir);
2490         if (ok == MAILIMAP_NO_ERROR)
2491                 return 0;
2492         else
2493                 return -1;
2494 }
2495
2496 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2497                     MsgInfoList *msglist, GHashTable *relation)
2498 {
2499         MsgInfo *msginfo;
2500
2501         g_return_val_if_fail(folder != NULL, -1);
2502         g_return_val_if_fail(dest != NULL, -1);
2503         if (msglist == NULL)
2504                 return 0;
2505
2506         msginfo = (MsgInfo *)msglist->data;
2507         g_return_val_if_fail(msginfo->folder != NULL, -1);
2508
2509         return imap_do_remove_msgs(folder, dest, msglist, relation);
2510 }
2511
2512 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2513 {
2514         GSList *list = folder_item_get_msg_list(item);
2515         gint res = imap_remove_msgs(folder, item, list, NULL);
2516         procmsg_msg_list_free(list);
2517         return res;
2518 }
2519
2520 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2521                                     MsgInfo *msginfo)
2522 {
2523         /* TODO: properly implement this method */
2524         return FALSE;
2525 }
2526
2527 static gint imap_close(Folder *folder, FolderItem *item)
2528 {
2529         return 0;
2530 }
2531
2532 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2533 {
2534         FolderItem *item = NULL;
2535         IMAPSession *session;
2536         gchar *root_folder = NULL;
2537
2538         g_return_val_if_fail(folder != NULL, -1);
2539         g_return_val_if_fail(folder->account != NULL, -1);
2540
2541         debug_print("getting session...\n");
2542         session = imap_session_get(folder);
2543         if (!session) {
2544                 if (!folder->node) {
2545                         folder_tree_destroy(folder);
2546                         item = folder_item_new(folder, folder->name, NULL);
2547                         item->folder = folder;
2548                         folder->node = item->node = g_node_new(item);
2549                 }
2550                 return -1;
2551         }
2552
2553         if (folder->account->imap_dir && *folder->account->imap_dir) {
2554                 gchar *real_path;
2555                 int r = MAILIMAP_NO_ERROR;
2556                 clist * lep_list;
2557
2558                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2559                 extract_quote(root_folder, '"');
2560                 subst_char(root_folder,
2561                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2562                                                    root_folder, &r),
2563                            '/');
2564                 if (is_fatal(r))
2565                         return -1;
2566                 strtailchomp(root_folder, '/');
2567                 real_path = imap_get_real_path
2568                         (session, IMAP_FOLDER(folder), root_folder, &r);
2569                 if (is_fatal(r))
2570                         return -1;
2571                 debug_print("IMAP root directory: %s\n", real_path);
2572
2573                 /* check if root directory exist */
2574
2575                 r = imap_threaded_list(session->folder, "", real_path,
2576                                        &lep_list);
2577
2578                 if (r != MAILIMAP_NO_ERROR)
2579                         imap_handle_error(SESSION(session), NULL, r);
2580
2581                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2582                         if (!folder->node) {
2583                                 item = folder_item_new(folder, folder->name, NULL);
2584                                 item->folder = folder;
2585                                 folder->node = item->node = g_node_new(item);
2586                         }
2587                         return -1;
2588                 }
2589                 mailimap_list_result_free(lep_list);
2590                                 
2591                 g_free(real_path);
2592         }
2593
2594         if (folder->node)
2595                 item = FOLDER_ITEM(folder->node->data);
2596                 
2597         if (item && !item->path && root_folder) {
2598                 item->path = g_strdup(root_folder);
2599         }
2600
2601         if (!item || ((item->path || root_folder) &&
2602                       strcmp2(item->path, root_folder) != 0)) {
2603                 folder_tree_destroy(folder);
2604                 item = folder_item_new(folder, folder->name, root_folder);
2605                 item->folder = folder;
2606                 folder->node = item->node = g_node_new(item);
2607         }
2608
2609         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2610         imap_create_missing_folders(folder);
2611
2612         return 0;
2613 }
2614
2615 static gint imap_scan_tree(Folder *folder)
2616 {
2617         gboolean subs_only = FALSE;
2618         if (folder->account) {
2619                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2620                 subs_only = folder->account->imap_subsonly;
2621         }
2622         return imap_scan_tree_real(folder, subs_only);
2623 }
2624
2625 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2626 {
2627         Folder *folder;
2628         IMAPFolder *imapfolder;
2629         FolderItem *new_item;
2630         GSList *item_list, *cur;
2631         GNode *node;
2632         gchar *real_path;
2633         gchar *wildcard_path;
2634         gchar separator;
2635         gchar wildcard[3];
2636         clist * lep_list;
2637         int r = MAILIMAP_NO_ERROR;
2638         
2639         g_return_val_if_fail(item != NULL, -1);
2640         g_return_val_if_fail(item->folder != NULL, -1);
2641         g_return_val_if_fail(item->no_sub == FALSE, -1);
2642
2643         folder = item->folder;
2644         imapfolder = IMAP_FOLDER(folder);
2645
2646         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2647         if (is_fatal(r))
2648                 return r;
2649
2650         if (folder->ui_func)
2651                 folder->ui_func(folder, item, folder->ui_func_data);
2652
2653         if (item->path) {
2654                 wildcard[0] = separator;
2655                 wildcard[1] = '%';
2656                 wildcard[2] = '\0';
2657                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2658                 if (is_fatal(r)) {
2659                         g_free(real_path);
2660                         return r;
2661                 }
2662         } else {
2663                 wildcard[0] = '%';
2664                 wildcard[1] = '\0';
2665                 real_path = g_strdup("");
2666         }
2667
2668         Xstrcat_a(wildcard_path, real_path, wildcard,
2669                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2670         lep_list = NULL;
2671         
2672         if (subs_only)
2673                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2674         else
2675                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2676
2677         if (r != MAILIMAP_NO_ERROR) {
2678                 imap_handle_error(SESSION(session), NULL, r);
2679                 item_list = NULL;
2680                 g_free(real_path);
2681                 return r;
2682         }
2683         else {
2684                 item_list = imap_list_from_lep(imapfolder,
2685                                                lep_list, real_path, FALSE);
2686                 mailimap_list_result_free(lep_list);
2687         }
2688         
2689         g_free(real_path);
2690
2691         node = item->node->children;
2692         while (node != NULL) {
2693                 FolderItem *old_item = FOLDER_ITEM(node->data);
2694                 GNode *next = node->next;
2695
2696                 new_item = NULL;
2697                 for (cur = item_list; cur != NULL; cur = cur->next) {
2698                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2699                         if (!strcmp2(old_item->path, cur_item->path)) {
2700                                 new_item = cur_item;
2701                                 break;
2702                         }
2703                 }
2704                 if (!new_item) {
2705                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2706                                 debug_print("not removing INBOX\n");
2707                         } else {
2708                                 debug_print("folder '%s' not found. removing...\n",
2709                                             old_item->path);
2710                                 folder_item_remove(old_item);
2711                         }
2712                 } else {
2713                         old_item->no_sub = new_item->no_sub;
2714                         old_item->no_select = new_item->no_select;
2715                         if (old_item->no_sub == TRUE && node->children) {
2716                                 debug_print("folder '%s' doesn't have "
2717                                             "subfolders. removing...\n",
2718                                             old_item->path);
2719                                 folder_item_remove_children(old_item);
2720                         }
2721                 }
2722
2723                 node = next;
2724         }
2725
2726         for (cur = item_list; cur != NULL; cur = cur->next) {
2727                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2728                 new_item = NULL;
2729
2730                 for (node = item->node->children; node != NULL;
2731                      node = node->next) {
2732                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2733                                      cur_item->path)) {
2734                                 new_item = FOLDER_ITEM(node->data);
2735                                 folder_item_destroy(cur_item);
2736                                 cur_item = NULL;
2737                                 break;
2738                         }
2739                 }
2740                 if (!new_item) {
2741                         new_item = cur_item;
2742                         debug_print("new folder '%s' found.\n", new_item->path);
2743                         folder_item_append(item, new_item);
2744                 }
2745
2746                 if (!strcmp(new_item->path, "INBOX")) {
2747                         new_item->stype = F_INBOX;
2748                         folder->inbox = new_item;
2749                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2750                         gchar *base;
2751
2752                         base = g_path_get_basename(new_item->path);
2753
2754                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2755                                 new_item->stype = F_OUTBOX;
2756                                 folder->outbox = new_item;
2757                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2758                                 new_item->stype = F_DRAFT;
2759                                 folder->draft = new_item;
2760                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2761                                 new_item->stype = F_QUEUE;
2762                                 folder->queue = new_item;
2763                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2764                                 new_item->stype = F_TRASH;
2765                                 folder->trash = new_item;
2766                         }
2767                         g_free(base);
2768                 }
2769
2770                 if (new_item->no_sub == FALSE)
2771                         imap_scan_tree_recursive(session, new_item, subs_only);
2772         }
2773
2774         g_slist_free(item_list);
2775
2776         return MAILIMAP_NO_ERROR;
2777 }
2778
2779 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2780 {
2781         IMAPSession *session = imap_session_get(folder);
2782         gchar *real_path;
2783         gchar *wildcard_path;
2784         gchar separator;
2785         gchar wildcard[3];
2786         clist * lep_list;
2787         GSList *item_list = NULL, *cur;
2788         GList *child_list = NULL, *tmplist = NULL;
2789         GSList *sub_list = NULL;
2790         int r = MAILIMAP_NO_ERROR;
2791
2792         if (!session)
2793                 return NULL;
2794
2795         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2796         if (is_fatal(r))
2797                 return NULL;
2798
2799         if (item->path) {
2800                 wildcard[0] = separator;
2801                 wildcard[1] = '%';
2802                 wildcard[2] = '\0';
2803                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2804                 if (is_fatal(r)) {
2805                         g_free(real_path);
2806                         return NULL;
2807                 }
2808         } else {
2809                 wildcard[0] = '%';
2810                 wildcard[1] = '\0';
2811                 real_path = g_strdup("");
2812         }
2813
2814         Xstrcat_a(wildcard_path, real_path, wildcard,
2815                   {g_free(real_path); return NULL;});
2816         lep_list = NULL;
2817         
2818         if (unsubs_only)
2819                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2820                                 item->path?item->path:item->name);
2821         else
2822                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2823                                 item->path?item->path:item->name);
2824
2825         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2826         if (r) {
2827                 g_free(real_path);
2828                 statusbar_pop_all();
2829                 return NULL;
2830         }
2831         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2832                                lep_list, real_path, FALSE);
2833         mailimap_list_result_free(lep_list);
2834
2835         for (cur = item_list; cur != NULL; cur = cur->next) {
2836                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2837                 if (recursive) {
2838                         tmplist = imap_scan_subtree(folder, cur_item, 
2839                                         unsubs_only, recursive);
2840                         if (tmplist)
2841                                 child_list = g_list_concat(child_list, tmplist);
2842                 }
2843                 child_list = g_list_prepend(child_list,
2844                                 imap_get_real_path(session, 
2845                                         IMAP_FOLDER(folder), cur_item->path, &r));
2846                 if (is_fatal(r)) {
2847                         g_free(real_path);
2848                         statusbar_pop_all();
2849                         return NULL;
2850                 }
2851                 folder_item_destroy(cur_item);
2852         }
2853         child_list = g_list_reverse(child_list);
2854         g_slist_free(item_list);
2855
2856         if (unsubs_only) {
2857                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2858                 if (r) {
2859                         g_free(real_path);
2860                         statusbar_pop_all();
2861                         return NULL;
2862                 }
2863                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2864                                        lep_list, real_path, FALSE);
2865                 mailimap_list_result_free(lep_list);
2866
2867                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2868                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2869                         GList *oldlitem = NULL;
2870                         gchar *tmp = imap_get_real_path(session, 
2871                                         IMAP_FOLDER(folder), cur_item->path, &r);
2872                         if (r) {
2873                                 g_free(real_path);
2874                                 statusbar_pop_all();
2875                                 return NULL;
2876                         }
2877                         folder_item_destroy(cur_item);
2878                         oldlitem = g_list_find_custom(
2879                                         child_list, tmp, (GCompareFunc)strcmp2);
2880                         if (oldlitem) {
2881                                 child_list = g_list_remove_link(child_list, oldlitem);
2882                                 g_free(oldlitem->data);
2883                                 g_list_free(oldlitem);
2884                         }
2885                         g_free(tmp);
2886                 }
2887         }
2888
2889         g_free(real_path);
2890         statusbar_pop_all();
2891
2892         return child_list;
2893 }
2894
2895 static gint imap_create_tree(Folder *folder)
2896 {
2897         g_return_val_if_fail(folder != NULL, -1);
2898         g_return_val_if_fail(folder->node != NULL, -1);
2899         g_return_val_if_fail(folder->node->data != NULL, -1);
2900         g_return_val_if_fail(folder->account != NULL, -1);
2901
2902         imap_scan_tree(folder);
2903         imap_create_missing_folders(folder);
2904
2905         return 0;
2906 }
2907
2908 static void imap_create_missing_folders(Folder *folder)
2909 {
2910         g_return_if_fail(folder != NULL);
2911
2912         if (!folder->inbox)
2913                 folder->inbox = imap_create_special_folder
2914                         (folder, F_INBOX, "INBOX");
2915         if (!folder->trash)
2916                 folder->trash = imap_create_special_folder
2917                         (folder, F_TRASH, "Trash");
2918         if (!folder->queue)
2919                 folder->queue = imap_create_special_folder
2920                         (folder, F_QUEUE, "Queue");
2921         if (!folder->outbox)
2922                 folder->outbox = imap_create_special_folder
2923                         (folder, F_OUTBOX, "Sent");
2924         if (!folder->draft)
2925                 folder->draft = imap_create_special_folder
2926                         (folder, F_DRAFT, "Drafts");
2927 }
2928
2929 static FolderItem *imap_create_special_folder(Folder *folder,
2930                                               SpecialFolderItemType stype,
2931                                               const gchar *name)
2932 {
2933         FolderItem *item;
2934         FolderItem *new_item;
2935
2936         g_return_val_if_fail(folder != NULL, NULL);
2937         g_return_val_if_fail(folder->node != NULL, NULL);
2938         g_return_val_if_fail(folder->node->data != NULL, NULL);
2939         g_return_val_if_fail(folder->account != NULL, NULL);
2940         g_return_val_if_fail(name != NULL, NULL);
2941
2942         item = FOLDER_ITEM(folder->node->data);
2943         new_item = imap_create_folder(folder, item, name);
2944
2945         if (!new_item) {
2946                 g_warning("Can't create '%s'\n", name);
2947                 if (!folder->inbox) return NULL;
2948
2949                 new_item = imap_create_folder(folder, folder->inbox, name);
2950                 if (!new_item)
2951                         g_warning("Can't create '%s' under INBOX\n", name);
2952                 else
2953                         new_item->stype = stype;
2954         } else
2955                 new_item->stype = stype;
2956
2957         return new_item;
2958 }
2959
2960 static gchar *imap_folder_get_path(Folder *folder)
2961 {
2962         gchar *folder_path;
2963
2964         g_return_val_if_fail(folder != NULL, NULL);
2965         g_return_val_if_fail(folder->account != NULL, NULL);
2966
2967         folder_path = g_strconcat(get_imap_cache_dir(),
2968                                   G_DIR_SEPARATOR_S,
2969                                   folder->account->recv_server,
2970                                   G_DIR_SEPARATOR_S,
2971                                   folder->account->userid,
2972                                   NULL);
2973
2974         return folder_path;
2975 }
2976
2977 #ifdef G_OS_WIN32
2978 static gchar *imap_encode_unsafe_chars(const gchar *str)
2979 {
2980         gchar *ret = NULL, *o_ret;
2981         gchar *i;
2982         if (!str) 
2983                 return NULL;
2984         ret = g_malloc(3*strlen(str)+1);
2985         o_ret = ret;
2986         for (i = str; *i; i++) {
2987                 switch(*i) {
2988                         case ':':
2989                         case '|':
2990                         case '<':
2991                         case '>':
2992                         case '*':
2993                         case '?':
2994                         case '#':
2995                                 *ret++ = '%';
2996                                 *ret++ = '0'+(*i/10);
2997                                 *ret++ = '0'+(*i%10);
2998                                 break;
2999                         default:
3000                                 *ret++ = *i;
3001                 }
3002         }
3003         *ret++ = '\0';
3004         return o_ret;
3005 }
3006 #endif
3007 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3008 {
3009         gchar *folder_path, *path;
3010         gchar *item_path = NULL;
3011         
3012         g_return_val_if_fail(folder != NULL, NULL);
3013         g_return_val_if_fail(item != NULL, NULL);
3014         folder_path = imap_folder_get_path(folder);
3015
3016         g_return_val_if_fail(folder_path != NULL, NULL);
3017
3018 #ifdef G_OS_UNIX
3019         item_path = g_strdup(item->path);
3020 #else
3021         item_path = imap_encode_unsafe_chars(item->path);
3022 #endif  
3023
3024         if (g_path_is_absolute(folder_path)) {
3025                 if (item_path)
3026                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3027                                            item_path, NULL);
3028                 else
3029                         path = g_strdup(folder_path);
3030         } else {
3031                 if (item_path)
3032                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3033                                            folder_path, G_DIR_SEPARATOR_S,
3034                                            item_path, NULL);
3035                 else
3036                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3037                                            folder_path, NULL);
3038         }
3039         g_free(folder_path);
3040         g_free(item_path);
3041 #ifdef G_OS_WIN32
3042         while (strchr(path, '/'))
3043                 *strchr(path, '/') = '\\';
3044 #endif
3045
3046         return path;
3047 }
3048
3049 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3050                                const gchar *name)
3051 {
3052         gchar *dirpath, *imap_path;
3053         IMAPSession *session;
3054         FolderItem *new_item;
3055         gchar separator;
3056         gchar *new_name;
3057         const gchar *p;
3058         gint ok = MAILIMAP_NO_ERROR;
3059         gboolean no_select = FALSE, no_sub = FALSE;
3060         gboolean exist = FALSE;
3061         
3062         g_return_val_if_fail(folder != NULL, NULL);
3063         g_return_val_if_fail(folder->account != NULL, NULL);
3064         g_return_val_if_fail(parent != NULL, NULL);
3065         g_return_val_if_fail(name != NULL, NULL);
3066
3067         debug_print("getting session...\n");
3068         session = imap_session_get(folder);
3069         if (!session) {
3070                 return NULL;
3071         }
3072
3073         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
3074                 dirpath = g_strdup(name);
3075         }else if (parent->path)
3076                 dirpath = g_strconcat(parent->path, "/", name, NULL);
3077         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3078                 dirpath = g_strdup(name);
3079         else if (folder->account->imap_dir && *folder->account->imap_dir) {
3080                 gchar *imap_dir;
3081
3082                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3083                 strtailchomp(imap_dir, '/');
3084                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3085         } else
3086                 dirpath = g_strdup(name);
3087                 
3088         
3089
3090         /* keep trailing directory separator to create a folder that contains
3091            sub folder */
3092         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3093
3094         strtailchomp(dirpath, '/');
3095         Xstrdup_a(new_name, name, {
3096                 g_free(dirpath); 
3097                 g_free(imap_path);
3098                 return NULL;});
3099
3100         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3101         if (is_fatal(ok)) {
3102                 g_free(imap_path);
3103                 return NULL;
3104         }
3105         imap_path_separator_subst(imap_path, separator);
3106         /* remove trailing / for display */
3107         strtailchomp(new_name, '/');
3108
3109         if (strcmp(dirpath, "INBOX") != 0) {
3110                 GPtrArray *argbuf;
3111                 int r;
3112                 clist * lep_list;
3113                 
3114                 argbuf = g_ptr_array_new();
3115                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3116                 if (r != MAILIMAP_NO_ERROR) {
3117                         imap_handle_error(SESSION(session), NULL, r);
3118                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3119                         g_free(imap_path);
3120                         g_free(dirpath);
3121                         ptr_array_free_strings(argbuf);
3122                         g_ptr_array_free(argbuf, TRUE);
3123                         return NULL;
3124                 }
3125                 
3126                 if (clist_count(lep_list) > 0)
3127                         exist = TRUE;
3128                 mailimap_list_result_free(lep_list);
3129                 lep_list = NULL;
3130                 if (!exist) {
3131                         ok = imap_cmd_create(session, imap_path);
3132                         if (ok != MAILIMAP_NO_ERROR) {
3133                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3134                                 g_free(imap_path);
3135                                 g_free(dirpath);
3136                                 return NULL;
3137                         }
3138                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
3139                         if (r == MAILIMAP_NO_ERROR) {
3140                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3141                                                lep_list, dirpath, TRUE);
3142                                 if (item_list) {
3143                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3144                                         no_select = cur_item->no_select;
3145                                         no_sub = cur_item->no_sub;
3146                                         g_slist_free(item_list);
3147                                 } 
3148                                 mailimap_list_result_free(lep_list);
3149                         } else {
3150                                 imap_handle_error(SESSION(session), NULL, r);
3151                         }
3152                 }
3153                 imap_threaded_subscribe(folder, imap_path, TRUE);
3154         } else {
3155                 clist *lep_list;
3156                 int r;
3157                 /* just get flags */
3158                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3159                 if (r == MAILIMAP_NO_ERROR) {
3160                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3161                                        lep_list, dirpath, TRUE);
3162                         if (item_list) {
3163                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3164                                 no_select = cur_item->no_select;
3165                                 no_sub = cur_item->no_sub;
3166                                 g_slist_free(item_list);
3167                         } 
3168                         mailimap_list_result_free(lep_list);
3169                 } else {
3170                         imap_handle_error(SESSION(session), NULL, r);
3171                 }
3172         }
3173
3174         new_item = folder_item_new(folder, new_name, dirpath);
3175         new_item->no_select = no_select;
3176         new_item->no_sub = no_sub;
3177         folder_item_append(parent, new_item);
3178         g_free(imap_path);
3179         g_free(dirpath);
3180
3181         dirpath = folder_item_get_path(new_item);
3182         if (!is_dir_exist(dirpath))
3183                 make_dir_hier(dirpath);
3184         g_free(dirpath);
3185
3186         if (exist) {
3187                 /* folder existed, scan it */
3188                 imap_scan_required(folder, new_item);
3189                 folder_item_scan_full(new_item, FALSE);
3190         }
3191
3192         return new_item;
3193 }
3194
3195 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3196                                const gchar *name)
3197 {
3198         gchar *dirpath;
3199         gchar *newpath;
3200         gchar *real_oldpath;
3201         gchar *real_newpath;
3202         gchar *paths[2];
3203         gchar *old_cache_dir;
3204         gchar *new_cache_dir;
3205         IMAPSession *session;
3206         gchar separator;
3207         gint ok = MAILIMAP_NO_ERROR;
3208         gint exists, recent, unseen;
3209         guint32 uid_validity;
3210
3211         g_return_val_if_fail(folder != NULL, -1);
3212         g_return_val_if_fail(item != NULL, -1);
3213         g_return_val_if_fail(item->path != NULL, -1);
3214         g_return_val_if_fail(name != NULL, -1);
3215
3216         debug_print("getting session...\n");
3217         session = imap_session_get(folder);
3218         if (!session) {
3219                 return -1;
3220         }
3221
3222         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3223                 is_fatal(ok)) {
3224                 g_warning(_("New folder name must not contain the namespace "
3225                             "path separator"));
3226                 return -1;
3227         }
3228
3229         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3230         if (is_fatal(ok)) {
3231                 return -1;
3232         }
3233
3234         g_free(session->mbox);
3235         session->mbox = NULL;
3236         session->exists = 0;
3237         session->recent = 0;
3238         session->expunge = 0;
3239         ok = imap_cmd_examine(session, "INBOX",
3240                               &exists, &recent, &unseen, &uid_validity, FALSE);
3241         if (ok != MAILIMAP_NO_ERROR) {
3242                 g_free(real_oldpath);
3243                 return -1;
3244         }
3245
3246         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3247         if (is_fatal(ok))
3248                 return -1;
3249         if (strchr(item->path, G_DIR_SEPARATOR)) {
3250                 dirpath = g_path_get_dirname(item->path);
3251                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
3252                 g_free(dirpath);
3253         } else
3254                 newpath = g_strdup(name);
3255
3256         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3257         imap_path_separator_subst(real_newpath, separator);
3258
3259         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3260         if (ok != MAILIMAP_NO_ERROR) {
3261                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3262                             real_oldpath, real_newpath);
3263                 g_free(real_oldpath);
3264                 g_free(newpath);
3265                 g_free(real_newpath);
3266                 return -1;
3267         }
3268         g_free(item->name);
3269         item->name = g_strdup(name);
3270
3271         old_cache_dir = folder_item_get_path(item);
3272
3273         paths[0] = g_strdup(item->path);
3274         paths[1] = newpath;
3275         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3276                         imap_rename_folder_func, paths);
3277
3278         if (is_dir_exist(old_cache_dir)) {
3279                 new_cache_dir = folder_item_get_path(item);
3280                 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3281                         FILE_OP_ERROR(old_cache_dir, "rename");
3282                 }
3283                 g_free(new_cache_dir);
3284         }
3285
3286         g_free(old_cache_dir);
3287         g_free(paths[0]);
3288         g_free(newpath);
3289         g_free(real_oldpath);
3290         g_free(real_newpath);
3291         return 0;
3292 }
3293
3294 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
3295 {
3296         gchar *path;
3297         gint r = MAILIMAP_NO_ERROR;
3298         IMAPSession *session;
3299         debug_print("getting session...\n");
3300
3301         session = imap_session_get(folder);
3302         if (!session) {
3303                 return -1;
3304         }
3305         if (item && item->path) {
3306                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3307                 if (!path)
3308                         return -1;
3309                 if (is_fatal(r)) {
3310                         g_free(path);
3311                         return -1;
3312                 }
3313                 if (!strcmp(path, "INBOX") && sub == FALSE) {
3314                         g_free(path);
3315                         return -1;
3316                 }
3317                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
3318                 r = imap_threaded_subscribe(folder, path, sub);
3319                 g_free(path);
3320         } else if (rpath) {
3321                 r = imap_threaded_subscribe(folder, rpath, sub);
3322         } else
3323                 return -1;
3324         return r;
3325 }
3326
3327 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
3328 {
3329         gint ok = MAILIMAP_NO_ERROR;
3330         IMAPSession *session;
3331         gchar *path;
3332         gchar *cache_dir;
3333         gboolean selected_folder;
3334
3335         g_return_val_if_fail(folder != NULL, -1);
3336         g_return_val_if_fail(item != NULL, -1);
3337         g_return_val_if_fail(item->path != NULL, -1);
3338
3339         debug_print("getting session...\n");
3340         session = imap_session_get(folder);
3341         if (!session) {
3342                 return -1;
3343         }
3344         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3345         if (is_fatal(ok))
3346                 return -1;
3347
3348         imap_threaded_subscribe(folder, path, FALSE);
3349
3350         selected_folder = (session->mbox != NULL) &&
3351                           (!strcmp(session->mbox, item->path));
3352         if (selected_folder) {
3353                 ok = imap_cmd_close(session);
3354                 if (ok != MAILIMAP_NO_ERROR) {
3355                         debug_print("close err %d\n", ok);
3356                         return ok;
3357                 }
3358         }
3359         ok = imap_cmd_delete(session, path);
3360         if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
3361                 gchar *tmp = NULL;
3362                 
3363                 ok = MAILIMAP_NO_ERROR;
3364                 tmp = g_strdup_printf("%s%c", path, 
3365                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
3366                 g_free(path);
3367                 path = tmp;
3368                 if (!is_fatal(ok))
3369                         ok = imap_cmd_delete(session, path);
3370         }
3371
3372         if (ok != MAILIMAP_NO_ERROR) {
3373                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
3374                 g_free(path);
3375                 return -1;
3376         }
3377
3378         g_free(path);
3379         cache_dir = folder_item_get_path(item);
3380         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
3381                 g_warning("can't remove directory '%s'\n", cache_dir);
3382         g_free(cache_dir);
3383         folder_item_remove(item);
3384         return 0;
3385 }
3386
3387 static gint imap_remove_folder(Folder *folder, FolderItem *item)
3388 {
3389         GNode *node, *next;
3390
3391         g_return_val_if_fail(item != NULL, -1);
3392         g_return_val_if_fail(item->folder != NULL, -1);
3393         g_return_val_if_fail(item->node != NULL, -1);
3394
3395         node = item->node->children;
3396         while (node != NULL) {
3397                 next = node->next;
3398                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
3399                         return -1;
3400                 node = next;
3401         }
3402         debug_print("IMAP removing %s\n", item->path);
3403
3404         if (imap_remove_all_msg(folder, item) < 0)
3405                 return -1;
3406         return imap_remove_folder_real(folder, item);
3407 }
3408
3409 typedef struct _uncached_data {
3410         IMAPSession *session;
3411         FolderItem *item;
3412         MsgNumberList *numlist;
3413         guint cur;
3414         guint total;
3415         gboolean done;
3416         int ok;
3417 } uncached_data;
3418
3419 static void *imap_get_uncached_messages_thread(void *data)
3420 {
3421         uncached_data *stuff = (uncached_data *)data;
3422         IMAPSession *session = stuff->session;
3423         FolderItem *item = stuff->item;
3424         MsgNumberList *numlist = stuff->numlist;
3425         GSList *newlist = NULL;
3426         GSList *llast = NULL;
3427         GSList *seq_list, *cur;
3428         gboolean got_alien_tags = FALSE;
3429
3430         debug_print("uncached_messages\n");
3431         
3432         if (session == NULL || item == NULL || item->folder == NULL
3433             || FOLDER_CLASS(item->folder) != &imap_class) {
3434                 stuff->done = TRUE;
3435                 return NULL;
3436         }
3437         
3438         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
3439         debug_print("get msgs info\n");
3440         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3441                 struct mailimap_set * imapset;
3442                 unsigned int i;
3443                 int r;
3444                 carray * env_list;
3445                 int count;
3446                 
3447                 if (session->cancelled)
3448                         break;
3449                 
3450                 imapset = cur->data;
3451                 
3452                 r = imap_threaded_fetch_env(session->folder,
3453                                             imapset, &env_list);
3454                 if (r != MAILIMAP_NO_ERROR) {
3455                         imap_handle_error(SESSION(session), NULL, r);
3456                         if (is_fatal(r)) {
3457                                 stuff->ok = r;
3458                                 return NULL;
3459                         }
3460                         continue;
3461                 }
3462
3463                 session_set_access_time(SESSION(session));
3464
3465                 count = 0;
3466                 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3467                         struct imap_fetch_env_info * info;
3468                         MsgInfo * msginfo;
3469                         GSList *tags = NULL, *cur = NULL;
3470                         info = carray_get(env_list, i);
3471                         tags = carray_get(env_list, i+1);
3472                         msginfo = imap_envelope_from_lep(info, item);
3473                         if (msginfo == NULL) {
3474                                 slist_free_strings_full(tags);
3475                                 continue;
3476                         }
3477                         g_slist_free(msginfo->tags);
3478                         msginfo->tags = NULL;
3479
3480                         for (cur = tags; cur; cur = cur->next) {
3481                                 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3482                                 gint id = 0;
3483                                 id = tags_get_id_for_str(real_tag);
3484                                 if (id == -1) {
3485                                         id = tags_add_tag(real_tag);
3486                                         got_alien_tags = TRUE;
3487                                 }
3488                                 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3489                                         msginfo->tags = g_slist_prepend(
3490                                                         msginfo->tags,
3491                                                         GINT_TO_POINTER(id));
3492                                 }
3493                                 g_free(real_tag);
3494                         }
3495                         if (msginfo->tags)
3496                                 msginfo->tags = g_slist_reverse(msginfo->tags);
3497                         slist_free_strings_full(tags);
3498                         msginfo->folder = item;
3499                         if (!newlist)
3500                                 llast = newlist = g_slist_append(newlist, msginfo);
3501                         else {
3502                                 llast = g_slist_append(llast, msginfo);
3503                                 llast = llast->next;
3504                         }
3505                         count ++;
3506                 }
3507                 
3508                 imap_fetch_env_free(env_list);
3509         }
3510         
3511         if (got_alien_tags) {
3512                 tags_write_tags();
3513                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3514         }
3515
3516         imap_lep_set_free(seq_list);
3517         
3518         session_set_access_time(SESSION(session));
3519         stuff->done = TRUE;
3520         return newlist;
3521 }
3522
3523 #define MAX_MSG_NUM 50
3524
3525 static GSList *imap_get_uncached_messages(IMAPSession *session,
3526                                         FolderItem *item,
3527                                         MsgNumberList *numlist,
3528                                         int *r)
3529 {
3530         GSList *result = NULL;
3531         GSList * cur;
3532         uncached_data *data = g_new0(uncached_data, 1);
3533         
3534         cur = numlist;
3535         data->total = g_slist_length(numlist);
3536         data->ok = MAILIMAP_NO_ERROR;
3537         debug_print("messages list : %i\n", data->total);
3538
3539         while (cur != NULL) {
3540                 GSList * partial_result;
3541                 int count;
3542                 GSList * newlist;
3543                 GSList * llast;
3544                 
3545                 llast = NULL;
3546                 count = 0;
3547                 newlist = NULL;
3548                 while (count < MAX_MSG_NUM) {
3549                         void * p;
3550                         
3551                         p = cur->data;
3552                         
3553                         if (newlist == NULL)
3554                                 llast = newlist = g_slist_append(newlist, p);
3555                         else {
3556                                 llast = g_slist_append(llast, p);
3557                                 llast = llast->next;
3558                         }
3559                         count ++;
3560                         
3561                         cur = cur->next;
3562                         if (cur == NULL)
3563                                 break;
3564                 }
3565                 
3566                 data->done = FALSE;
3567                 data->session = session;
3568                 data->item = item;
3569                 data->numlist = newlist;
3570                 data->cur += count;
3571                 
3572                 if (prefs_common.work_offline && 
3573                     !inc_offline_should_override(FALSE,
3574                         _("Claws Mail needs network access in order "
3575                           "to access the IMAP server."))) {
3576                         g_free(data);
3577                         return NULL;
3578                 }
3579                 
3580                 partial_result =
3581                         (GSList *)imap_get_uncached_messages_thread(data);
3582                 *r = data->ok;
3583                 if (data->ok != MAILIMAP_NO_ERROR) {
3584                         goto bail;
3585                 }
3586                 statusbar_progress_all(data->cur,data->total, 1);
3587                 
3588                 g_slist_free(newlist);
3589                 
3590                 result = g_slist_concat(result, partial_result);
3591         }
3592 bail:
3593         g_free(data);
3594         
3595         statusbar_progress_all(0,0,0);
3596         statusbar_pop_all();
3597         
3598         return result;
3599 }
3600
3601 static void imap_delete_all_cached_messages(FolderItem *item)
3602 {
3603         gchar *dir;
3604
3605         g_return_if_fail(item != NULL);
3606         g_return_if_fail(item->folder != NULL);
3607         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3608
3609         debug_print("Deleting all cached messages...\n");
3610
3611         dir = folder_item_get_path(item);
3612         if (is_dir_exist(dir))
3613                 remove_all_numbered_files(dir);
3614         g_free(dir);
3615
3616         debug_print("done.\n");
3617 }
3618
3619 gchar imap_get_path_separator_for_item(FolderItem *item)
3620 {
3621         Folder *folder = NULL;
3622         IMAPFolder *imap_folder = NULL;
3623         IMAPSession *session = NULL;
3624         gchar result = '/';
3625         gint ok = MAILIMAP_NO_ERROR;
3626         if (!item)
3627                 return '/';
3628         folder = item->folder;
3629         
3630         if (!folder)
3631                 return '/';
3632         
3633         imap_folder = IMAP_FOLDER(folder);
3634         
3635         if (!imap_folder)
3636                 return '/';
3637         
3638         debug_print("getting session...");
3639         session = imap_session_get(FOLDER(folder));
3640         result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3641         return result;
3642 }
3643
3644 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3645 {
3646         clist * lep_list;
3647         int r;
3648         gchar separator = '\0';
3649         
3650         g_return_val_if_fail(session != NULL, '/');
3651         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3652         
3653         if (r != MAILIMAP_NO_ERROR) {
3654                 imap_handle_error(SESSION(session), NULL, r);
3655                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3656                 *ok = r;
3657                 return '\0';
3658         }
3659
3660         if (lep_list != NULL && clist_count(lep_list) > 0) {
3661                 clistiter * iter = clist_begin(lep_list); 
3662                 struct mailimap_mailbox_list * mb;
3663                 mb = clist_content(iter);
3664
3665                 separator = mb->mb_delimiter;
3666                 debug_print("got separator: %c\n", folder->last_seen_separator);
3667         }
3668         *ok = MAILIMAP_NO_ERROR;
3669         mailimap_list_result_free(lep_list);
3670         return separator;
3671 }
3672
3673 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3674 {
3675         gchar separator = '/';
3676         *ok = MAILIMAP_NO_ERROR;
3677         if (folder->last_seen_separator == 0) {
3678                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3679         }
3680
3681         if (folder->last_seen_separator == 0) {
3682                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3683         }
3684
3685         if (folder->last_seen_separator != 0) {
3686                 debug_print("using separator: %c\n", folder->last_seen_separator);
3687                 return folder->last_seen_separator;
3688         }
3689
3690         return separator;
3691 }
3692
3693 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3694 {
3695         gchar *real_path = NULL;
3696         gchar separator;
3697         
3698         g_return_val_if_fail(folder != NULL, NULL);
3699         g_return_val_if_fail(path != NULL, NULL);
3700
3701         *ok = MAILIMAP_NO_ERROR;
3702         
3703         real_path = imap_utf8_to_modified_utf7(path, FALSE);
3704         separator = imap_get_path_separator(session, folder, path, ok);
3705         if (*ok == MAILIMAP_NO_ERROR)
3706                 imap_path_separator_subst(real_path, separator);
3707
3708         return real_path;
3709 }
3710
3711 static gint imap_set_message_flags(IMAPSession *session,
3712                                    IMAPFolderItem *item,
3713                                    MsgNumberList *numlist,
3714                                    IMAPFlags flags,
3715                                    GSList *tags,
3716                                    gboolean is_set)
3717 {
3718         gint ok = 0;
3719         GSList *seq_list;
3720         GSList * cur;
3721         gint total = 0;
3722         IMAPFolder *folder = NULL;
3723         GSList *sorted_list = NULL;
3724
3725         if (numlist == NULL || session == NULL)
3726                 return MAILIMAP_ERROR_BAD_STATE;
3727         
3728         folder = IMAP_FOLDER(session->folder);
3729         
3730         sorted_list = g_slist_copy(numlist);
3731         sorted_list = g_slist_sort(sorted_list, g_int_compare);
3732         
3733         cur = g_slist_last(sorted_list);
3734
3735         if (cur)
3736                 total = GPOINTER_TO_INT(cur->data);
3737         
3738         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3739
3740         statusbar_print_all(_("Flagging messages..."));
3741
3742         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3743                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3744                 struct mailimap_set_item *set_item = NULL;
3745                 
3746                 if (imapset->set_list)
3747                         set_item = clist_content(clist_begin(imapset->set_list));
3748                 else
3749                         continue;
3750
3751                 if (set_item == NULL)
3752                         continue;
3753
3754                 statusbar_progress_all(set_item->set_first, total, 1);
3755
3756                 ok = imap_cmd_store(session, item, imapset,
3757                                     flags, tags, is_set);
3758                 statusbar_progress_all(set_item->set_last, total, 1);
3759                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3760                         /* reduce max set size */
3761                         folder->max_set_size /= 2;
3762                 }
3763                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3764                         break;
3765                 }
3766         }
3767         
3768         g_slist_free(sorted_list);
3769
3770         statusbar_progress_all(0,0,0);
3771         statusbar_pop_all();
3772
3773         imap_lep_set_free(seq_list);
3774         
3775         return ok;
3776 }
3777
3778 typedef struct _select_data {
3779         IMAPSession *session;
3780         gchar *real_path;
3781         gint *exists;
3782         gint *recent;
3783         gint *unseen;
3784         guint32 *uid_validity;
3785         gboolean done;
3786 } select_data;
3787
3788 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3789                         FolderItem *item,
3790                         gint *exists, gint *recent, gint *unseen,
3791                         guint32 *uid_validity, gint *can_create_flags,
3792                         gboolean block)
3793 {
3794         gchar *real_path;
3795         gint ok = MAILIMAP_NO_ERROR;
3796         gint exists_, recent_, unseen_;
3797         guint32 uid_validity_;
3798         gint can_create_flags_;
3799         const gchar *path = item ? item->path:NULL;
3800
3801         if (!item) {
3802                 return MAILIMAP_ERROR_BAD_STATE;
3803         }
3804
3805         if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3806                 if (session->mbox && strcmp(session->mbox, path) == 0)
3807                         return MAILIMAP_NO_ERROR;
3808         }
3809         if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3810                 if (session->mbox && strcmp(session->mbox, path) == 0) {
3811                         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3812                                 return MAILIMAP_NO_ERROR;
3813                 }
3814         }
3815         if (!exists)
3816                 exists = &exists_;
3817         if (!recent)
3818                 recent = &recent_;
3819         if (!unseen)
3820                 unseen = &unseen_;
3821         if (!uid_validity)
3822                 uid_validity = &uid_validity_;
3823         if (!can_create_flags)
3824                 can_create_flags = &can_create_flags_;
3825
3826         g_free(session->mbox);
3827         session->mbox = NULL;
3828         session->exists = 0;
3829         session->recent = 0;
3830         session->expunge = 0;
3831
3832         real_path = imap_get_real_path(session, folder, path, &ok);
3833         if (is_fatal(ok))
3834                 return ok;              
3835         g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3836         IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3837         ok = imap_cmd_select(session, real_path,
3838                              exists, recent, unseen, uid_validity, can_create_flags, 
3839                              &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3840         if (ok != MAILIMAP_NO_ERROR) {
3841                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3842         } else {
3843                 session->mbox = g_strdup(path);
3844                 session->folder_content_changed = FALSE;
3845                 session->exists = *exists;
3846                 session->recent = *recent;
3847                 session->expunge = 0;
3848                 session->unseen = *unseen;
3849                 session->uid_validity = *uid_validity;
3850                 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
3851                         session->exists, session->recent, session->expunge,
3852                         session->uid_validity, *can_create_flags);
3853         }
3854         if (*can_create_flags) {
3855                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3856         } else {
3857                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3858         }
3859         g_free(real_path);
3860
3861         return ok;
3862 }
3863
3864 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3865                         const gchar *path, IMAPFolderItem *item,
3866        &nb