More Coverity fixes
[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                 g_free(destdir);
1677                 return -1;
1678         }
1679         statusbar_print_all(_("Adding messages..."));
1680         total = g_slist_length(file_list);
1681         for (cur = file_list; cur != NULL; cur = cur->next) {
1682                 IMAPFlags iflags = 0;
1683                 guint32 new_uid = 0;
1684                 gchar *real_file = NULL;
1685                 fileinfo = (MsgFileInfo *)cur->data;
1686
1687                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1688                 curnum++;
1689
1690                 if (fileinfo->flags) {
1691                         if (MSG_IS_MARKED(*fileinfo->flags))
1692                                 iflags |= IMAP_FLAG_FLAGGED;
1693                         if (MSG_IS_REPLIED(*fileinfo->flags))
1694                                 iflags |= IMAP_FLAG_ANSWERED;
1695                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1696                                 iflags |= IMAP_FLAG_FORWARDED;
1697                         if (MSG_IS_SPAM(*fileinfo->flags))
1698                                 iflags |= IMAP_FLAG_SPAM;
1699                         else
1700                                 iflags |= IMAP_FLAG_HAM;
1701                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1702                                 iflags |= IMAP_FLAG_SEEN;
1703                         
1704                 }
1705                 
1706                 if (real_file == NULL)
1707                         real_file = g_strdup(fileinfo->file);
1708                 
1709                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1710                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1711                     folder_has_parent_of_type(dest, F_DRAFT) ||
1712                     folder_has_parent_of_type(dest, F_TRASH))
1713                         iflags |= IMAP_FLAG_SEEN;
1714
1715                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1716                                      &new_uid);
1717
1718                 if (ok != MAILIMAP_NO_ERROR) {
1719                         g_warning("can't append message %s\n", real_file);
1720                         g_free(real_file);
1721                         g_free(destdir);
1722                         statusbar_progress_all(0,0,0);
1723                         statusbar_pop_all();
1724                         return -1;
1725                 } else {
1726                         debug_print("appended new message as %d\n", new_uid);
1727                         /* put the local file in the imapcache, so that we don't
1728                          * have to fetch it back later. */
1729                         
1730                         if (new_uid == 0) {
1731                                 missing_uids = TRUE;
1732                                 debug_print("Missing UID (0)\n");
1733                         }
1734                         if (new_uid > 0) {
1735                                 gchar *cache_path = folder_item_get_path(dest);
1736                                 if (!is_dir_exist(cache_path))
1737                                         make_dir_hier(cache_path);
1738                                 if (is_dir_exist(cache_path)) {
1739                                         gchar *cache_file = g_strconcat(
1740                                                 cache_path, G_DIR_SEPARATOR_S, 
1741                                                 itos(new_uid), NULL);
1742                                         copy_file(real_file, cache_file, TRUE);
1743                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1744                                         g_free(cache_file);
1745                                 }
1746                                 g_free(cache_path);
1747                         }
1748                 }
1749
1750                 if (relation != NULL)
1751                         g_hash_table_insert(relation, fileinfo->msginfo != NULL ? 
1752                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1753                                           GINT_TO_POINTER(new_uid));
1754                 if (last_uid < new_uid) {
1755                         last_uid = new_uid;
1756                 }
1757
1758                 g_free(real_file);
1759         }
1760         
1761         statusbar_progress_all(0,0,0);
1762         statusbar_pop_all();
1763         
1764         
1765         g_free(destdir);
1766
1767         imap_scan_required(folder, dest);
1768
1769         session = imap_session_get(folder);
1770         if (!session) {
1771                 return -1;
1772         }
1773         if (missing_uids) {
1774                 gint a;
1775                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1776                          &a, NULL, NULL, NULL, NULL, FALSE);
1777         }
1778         return last_uid;
1779 }
1780
1781 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1782 {
1783         GSList *result = NULL;
1784         clistiter *list;
1785         guint32 start, end, t;
1786         GSList *cur;
1787
1788         if (!set || !set->set_list)
1789                 return NULL;
1790
1791         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1792                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1793                 start = item->set_first;
1794                 end = item->set_last;
1795                 if (start <= end) {
1796                         for (t = start; t <= end; t++) {
1797                                 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1798                         }
1799                 }
1800         }
1801         result = g_slist_reverse(result);
1802         if (debug_get_mode()) {
1803                 debug_print("flat imap set: ");
1804                 for (cur = result; cur; cur = cur->next) {
1805                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1806                 }
1807                 debug_print("\n");
1808         }
1809         
1810         return result;
1811 }
1812 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1813                               MsgInfoList *msglist, GHashTable *relation)
1814 {
1815         FolderItem *src;
1816         gchar *destdir;
1817         GSList *seq_list, *cur;
1818         MsgInfo *msginfo;
1819         IMAPSession *session;
1820         gint ok = MAILIMAP_NO_ERROR;
1821         GHashTable *uid_hash;
1822         gint last_num = 0;
1823
1824         g_return_val_if_fail(folder != NULL, -1);
1825         g_return_val_if_fail(dest != NULL, -1);
1826         g_return_val_if_fail(msglist != NULL, -1);
1827         
1828         debug_print("getting session...\n");
1829         session = imap_session_get(folder);
1830         
1831         if (!session) {
1832                 return -1;
1833         }
1834
1835         msginfo = (MsgInfo *)msglist->data;
1836         src = msginfo->folder;
1837         if (src == dest) {
1838                 g_warning("the src folder is identical to the dest.\n");
1839                 return -1;
1840         }
1841
1842         if (src->folder != dest->folder) {
1843                 GSList *infolist = NULL, *cur;
1844                 int res = -1;
1845                 for (cur = msglist; cur; cur = cur->next) {
1846                         msginfo = (MsgInfo *)cur->data;
1847                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1848                         fileinfo->file = procmsg_get_message_file(msginfo);
1849                         fileinfo->flags = &(msginfo->flags);
1850                         infolist = g_slist_prepend(infolist, fileinfo);
1851                 }
1852                 infolist = g_slist_reverse(infolist);
1853                 res = folder_item_add_msgs(dest, infolist, FALSE);
1854                 for (cur = infolist; cur; cur = cur->next) {
1855                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1856                         g_free(info->file);
1857                         g_free(info);
1858                 }
1859                 g_slist_free(infolist);
1860                 return res;
1861         } 
1862
1863         lock_session(session); /* unlocked later in the function */
1864
1865         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1866                          NULL, NULL, NULL, NULL, NULL, FALSE);
1867         if (ok != MAILIMAP_NO_ERROR) {
1868                 return ok;
1869         }
1870
1871         unlock_session(session);
1872
1873         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1874
1875         if (is_fatal(ok)) {
1876                 g_free(destdir);
1877                 return ok;
1878         }
1879
1880         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1881         uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
1882         
1883         statusbar_print_all(_("Copying messages..."));
1884         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1885                 struct mailimap_set * seq_set;
1886                 struct mailimap_set * source = NULL;
1887                 struct mailimap_set * dest = NULL;
1888                 seq_set = cur->data;
1889
1890                 debug_print("Copying messages from %s to %s ...\n",
1891                             src->path, destdir);
1892
1893                 lock_session(session); /* unlocked later in the function */
1894                 ok = imap_cmd_copy(session, seq_set, destdir,
1895                         &source, &dest);
1896                 
1897                 if (is_fatal(ok)) {
1898                         session = NULL;
1899                 }
1900
1901                 if (ok == MAILIMAP_NO_ERROR) {
1902                         unlock_session(session);
1903                         if (relation && source && dest) {
1904                                 GSList *s_list = flatten_mailimap_set(source);
1905                                 GSList *d_list = flatten_mailimap_set(dest);
1906                                 GSList *s_cur, *d_cur;
1907                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1908
1909                                         for (s_cur = s_list, d_cur = d_list; 
1910                                              s_cur && d_cur; 
1911                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1912                                                 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
1913                                         }
1914
1915                                 } else {
1916                                         debug_print("hhhmm, source list length != dest list length.\n");
1917                                 }
1918                                 g_slist_free(s_list);
1919                                 g_slist_free(d_list);
1920                         }
1921                 }
1922
1923
1924                 if (source)
1925                         mailimap_set_free(source);
1926                 if (dest)
1927                         mailimap_set_free(dest);
1928
1929                 if (ok != MAILIMAP_NO_ERROR) {
1930                         g_hash_table_destroy(uid_hash);
1931                         imap_lep_set_free(seq_list);
1932                         statusbar_pop_all();
1933                         return -1;
1934                 }
1935         }
1936
1937         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1938                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1939                 gpointer hashval;
1940
1941                 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
1942                 
1943                 if (hashval != NULL) {
1944                         gint num = GPOINTER_TO_INT(hashval);
1945                         g_hash_table_insert(relation, msginfo,
1946                                           GINT_TO_POINTER(num));
1947                         if (num > last_num)
1948                                 last_num = num;
1949                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1950                         /* put the local file in the imapcache, so that we don't
1951                          * have to fetch it back later. */
1952                         if (num > 0) {
1953                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1954                                 gchar *real_file = g_strconcat(
1955                                         cache_path, G_DIR_SEPARATOR_S, 
1956                                         itos(msginfo->msgnum), NULL);
1957                                 gchar *cache_file = NULL;
1958                                 g_free(cache_path);
1959                                 cache_path = folder_item_get_path(dest);
1960                                 cache_file = g_strconcat(
1961                                         cache_path, G_DIR_SEPARATOR_S, 
1962                                         itos(num), NULL);
1963                                 if (!is_dir_exist(cache_path))
1964                                         make_dir_hier(cache_path);
1965                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1966                                         copy_file(real_file, cache_file, TRUE);
1967                                         debug_print("copied to cache: %s\n", cache_file);
1968                                 }
1969                                 g_free(real_file);
1970                                 g_free(cache_file);
1971                                 g_free(cache_path);
1972                         }
1973                 } else
1974                         g_hash_table_insert(relation, msginfo,
1975                                           GINT_TO_POINTER(0));
1976         }
1977         statusbar_pop_all();
1978
1979         g_hash_table_destroy(uid_hash);
1980         imap_lep_set_free(seq_list);
1981
1982         g_free(destdir);
1983         
1984         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1985         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1986         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1987         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1988
1989         imap_scan_required(folder, dest);
1990         if (ok == MAILIMAP_NO_ERROR)
1991                 return last_num;
1992         else
1993                 return -1;
1994 }
1995
1996 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1997 {
1998         GSList msglist;
1999
2000         g_return_val_if_fail(msginfo != NULL, -1);
2001
2002         msglist.data = msginfo;
2003         msglist.next = NULL;
2004
2005         return imap_copy_msgs(folder, dest, &msglist, NULL);
2006 }
2007
2008 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
2009                     MsgInfoList *msglist, GHashTable *relation)
2010 {
2011         MsgInfo *msginfo;
2012         gint ret;
2013
2014         g_return_val_if_fail(folder != NULL, -1);
2015         g_return_val_if_fail(dest != NULL, -1);
2016         g_return_val_if_fail(msglist != NULL, -1);
2017
2018         msginfo = (MsgInfo *)msglist->data;
2019         g_return_val_if_fail(msginfo->folder != NULL, -1);
2020
2021         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
2022         return ret;
2023 }
2024
2025 static gboolean imap_matcher_type_is_local(gint matchertype)
2026 {
2027         switch (matchertype) {
2028         case MATCHCRITERIA_FROM:
2029         case MATCHCRITERIA_TO:
2030         case MATCHCRITERIA_CC:
2031         case MATCHCRITERIA_TO_OR_CC:
2032         case MATCHCRITERIA_SUBJECT:
2033         case MATCHCRITERIA_REFERENCES:
2034         case MATCHCRITERIA_INREPLYTO:
2035         case MATCHCRITERIA_AGE_GREATER:
2036         case MATCHCRITERIA_AGE_LOWER:
2037         case MATCHCRITERIA_FORWARDED:
2038         case MATCHCRITERIA_SPAM:
2039         case MATCHCRITERIA_UNREAD:
2040         case MATCHCRITERIA_NEW:
2041         case MATCHCRITERIA_MARKED:
2042         case MATCHCRITERIA_REPLIED:
2043         case MATCHCRITERIA_DELETED:
2044         case MATCHCRITERIA_SIZE_GREATER:
2045         case MATCHCRITERIA_SIZE_SMALLER:
2046         case MATCHCRITERIA_SIZE_EQUAL:
2047                 return TRUE;
2048         }
2049         return FALSE;
2050 }
2051
2052 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2053 {
2054         if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2055                 IMAPSearchKey* result = NULL;
2056                 gboolean invert = FALSE;
2057                 gint matchertype = match->criteria;
2058
2059                 if (is_all) {
2060                         *is_all = FALSE;
2061                 }
2062
2063                 switch (matchertype) {
2064                 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2065                 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2066                 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2067                 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2068                 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2069                 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2070                 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2071                 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2072                 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2073                 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2074                 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2075                 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2076                 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2077                 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2078                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2079                 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2080                 }
2081
2082                 /* 
2083                  * this aborts conversion even for predicates understood by the following code.
2084                  * while that might seem wasteful, claws local search for information listed below
2085                  * has proven faster than IMAP search plus network roundtrips. once this changes,
2086                  * consider removing these exceptions.
2087                  */
2088                 if (imap_matcher_type_is_local(matchertype))
2089                         return NULL;
2090
2091                 /* the Message-ID header is also cached */
2092                 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2093                         return NULL;
2094                 }
2095
2096                 switch (matchertype) {
2097                 case MATCHCRITERIA_FORWARDED:
2098                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2099                         break;
2100
2101                 case MATCHCRITERIA_SPAM:
2102                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2103                         break;
2104
2105                 case MATCHCRITERIA_INREPLYTO:
2106                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2107                         break;
2108
2109                 case MATCHCRITERIA_REFERENCES:
2110                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2111                         break;
2112
2113                 case MATCHCRITERIA_TO_OR_CC:
2114                         result = imap_search_or(
2115                                         imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2116                                         imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2117                                         );
2118                         break;
2119
2120                 case MATCHCRITERIA_HEADERS_PART:
2121                         result = imap_search_and(
2122                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2123                                         imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2124                                         );
2125                         break;
2126
2127                 case MATCHCRITERIA_SIZE_EQUAL:
2128                         result = imap_search_and(
2129                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2130                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2131                                         );
2132                         break;
2133
2134                 case MATCHCRITERIA_NOT_UNREAD:
2135                         result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2136                         break;
2137
2138                 case MATCHCRITERIA_UNREAD:
2139                         result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2140                         break;
2141
2142                 case MATCHCRITERIA_NEW:
2143                         result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2144                         break;
2145
2146                 case MATCHCRITERIA_MARKED:
2147                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2148                         break;
2149
2150                 case MATCHCRITERIA_DELETED:
2151                         result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2152                         break;
2153
2154                 case MATCHCRITERIA_REPLIED:
2155                         result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2156                         break;
2157
2158                 case MATCHCRITERIA_TAG:
2159                         {
2160                                 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2161                                 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2162                                 g_free(tmp);
2163                         }
2164                         break;
2165
2166                 case MATCHCRITERIA_SUBJECT:
2167                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2168                         break;
2169
2170                 case MATCHCRITERIA_FROM:
2171                         result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2172                         break;
2173
2174                 case MATCHCRITERIA_TO:
2175                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2176                         break;
2177
2178                 case MATCHCRITERIA_CC:
2179                         result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2180                         break;
2181
2182                 case MATCHCRITERIA_AGE_GREATER:
2183                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2184                         break;
2185
2186                 case MATCHCRITERIA_AGE_LOWER:
2187                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2188                         break;
2189
2190                 case MATCHCRITERIA_BODY_PART:
2191                         result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2192                         break;
2193
2194                 case MATCHCRITERIA_MESSAGE:
2195                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2196                         break;
2197
2198                 case MATCHCRITERIA_HEADER:
2199                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2200                         break;
2201
2202                 case MATCHCRITERIA_SIZE_GREATER:
2203                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2204                         break;
2205
2206                 case MATCHCRITERIA_SIZE_SMALLER:
2207                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2208                         break;
2209
2210                 default:
2211                         result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2212                         if (is_all) {
2213                                 *is_all = TRUE;
2214                         }
2215                         break;
2216                 }
2217
2218                 if (invert) {
2219                         result = imap_search_not(result);
2220                         if (is_all && *is_all) {
2221                                 *is_all = FALSE;
2222                         }
2223                 }
2224
2225                 return result;
2226         }
2227
2228         return NULL;
2229 }
2230
2231 static void imap_change_search_charset(IMAPFolder *folder)
2232 {
2233         /* If server supports charset in searches, but the last used one failed,
2234          * changed to the next preferred charset. If none are still available,
2235          * disable charset searches.
2236          * Charsets are tried in the following order: 
2237          * UTF-8, locale's charset, UTF-7.
2238          */
2239
2240         if (folder->search_charset_supported) {
2241                 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2242                         folder->search_charset = "UTF-8";
2243                 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2244                         folder->search_charset = "UTF-7";
2245                 else {
2246                         folder->search_charset = NULL;
2247                         folder->search_charset_supported = FALSE;
2248                 }
2249         }
2250 }
2251
2252 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2253                                                   MatcherProp *utf8_prop,
2254                                                   gchar **charset)
2255 {
2256         /* If the match is going to be done locally, or the criteria is on
2257          * tag (special-cased to modified-UTF-7), or the expression searched
2258          * is ASCII, don't bother converting.
2259          */
2260         if (imap_matcher_type_is_local(utf8_prop->criteria)
2261          || utf8_prop->criteria == MATCHCRITERIA_TAG
2262          || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2263          || utf8_prop->expr == NULL
2264          || is_ascii_str(utf8_prop->expr))
2265                 return matcherprop_new(utf8_prop->criteria,
2266                                utf8_prop->header,
2267                                utf8_prop->matchtype,
2268                                utf8_prop->expr,
2269                                utf8_prop->value);
2270         else {
2271                 gchar *conv_expr = NULL;
2272
2273                 /* If the search is server-side and the server doesn't support
2274                  * searching with the charsets we handle, bail out.
2275                  */
2276                 if (folder->search_charset_supported == FALSE)
2277                         return NULL;
2278
2279                 /* Else, convert. */
2280                 if (*charset == NULL)
2281                         *charset = g_strdup(folder->search_charset);
2282
2283                 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2284
2285                 if (conv_expr == NULL)
2286                         conv_expr = g_strdup(utf8_prop->expr);
2287
2288                 return matcherprop_new(utf8_prop->criteria,
2289                                utf8_prop->header,
2290                                utf8_prop->matchtype,
2291                                conv_expr,
2292                                utf8_prop->value);
2293         }
2294 }
2295
2296 static gint     search_msgs             (Folder                 *folder,
2297                                          FolderItem             *container,
2298                                          MsgNumberList          **msgs,
2299                                          gboolean               *on_server,
2300                                          MatcherList            *predicate,
2301                                          SearchProgressNotify   progress_cb,
2302                                          gpointer               progress_data)
2303 {
2304         IMAPSearchKey* key = NULL;
2305         GSList* cur;
2306         int result = -1;
2307         clist* uidlist = NULL;
2308         gboolean server_filtering_useless = FALSE;
2309         IMAPSession *session;
2310         gchar *charset_to_use = NULL;
2311
2312         if (on_server == NULL || !*on_server) {
2313                 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2314                                 predicate, progress_cb, progress_data);
2315         }
2316
2317         for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2318                 IMAPSearchKey* matcherPart = NULL;
2319                 MatcherProp* prop = (MatcherProp*) cur->data;
2320                 gboolean is_all;
2321                 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2322
2323                 if (imap_prop == NULL) {
2324                         /* Couldn't convert matcherprop to IMAP - probably not ascii
2325                          * and server doesn't support the charsets we do. */
2326                          return -1;
2327                 }
2328
2329                 matcherPart = search_make_key(imap_prop, &is_all);
2330
2331                 matcherprop_free(imap_prop);
2332
2333                 if (on_server) {
2334                         *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2335                 }
2336
2337                 if (matcherPart) {
2338                         if (key == NULL) {
2339                                 key = matcherPart;
2340                                 server_filtering_useless = is_all;
2341                         } else if (predicate->bool_and) {
2342                                 key = imap_search_and(key, matcherPart);
2343                                 server_filtering_useless &= is_all;
2344                         } else {
2345                                 key = imap_search_or(key, matcherPart);
2346                                 server_filtering_useless |= is_all;
2347                         }
2348                 }
2349         }
2350
2351         if (server_filtering_useless) {
2352                 imap_search_free(key);
2353                 key = NULL;
2354         }
2355
2356         if (key == NULL && progress_cb != NULL) {
2357                 GSList* cur;
2358                 GSList* list;
2359                 int count = 0;
2360
2361                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2362                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2363
2364                 list = folder_item_get_msg_list(container);
2365                 for (cur = list; cur != NULL; cur = cur->next) {
2366                         *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2367                         count++;
2368                 }
2369                 procmsg_msg_list_free(list);
2370
2371                 *msgs = g_slist_reverse(*msgs);
2372
2373                 return count;
2374         }
2375
2376         session = imap_session_get(folder);
2377         if (!session) {
2378                 return -1;
2379         }
2380         result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2381                          NULL, NULL, NULL, NULL, NULL, TRUE);
2382         if (result != MAILIMAP_NO_ERROR)
2383                 return -1;
2384
2385         if (progress_cb)
2386                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2387         result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2388         if (progress_cb)
2389                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2390
2391         if (result == MAILIMAP_NO_ERROR) {
2392                 gint result = 0;
2393
2394                 *msgs = imap_uid_list_from_lep(uidlist, &result);
2395
2396                 mailimap_search_result_free(uidlist);
2397
2398                 if (charset_to_use != NULL)
2399                         g_free(charset_to_use);
2400
2401                 return result;
2402         } else if (charset_to_use != NULL) {
2403                 /* If search failed and was on an 8-bit string, try the next
2404                  * available charset to search if there still are some.
2405                  */
2406                 g_free(charset_to_use);
2407                 
2408                 imap_change_search_charset(IMAP_FOLDER(folder));
2409                 if (IMAP_FOLDER(folder)->search_charset_supported)
2410                         return search_msgs(folder, container, msgs, on_server, predicate,
2411                                    progress_cb, progress_data);
2412                 else
2413                         return -1;
2414         } else {
2415                 return -1;
2416         }
2417 }
2418
2419
2420 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
2421                                 MsgInfoList *msglist, GHashTable *relation)
2422 {
2423         gchar *destdir, *dir;
2424         GSList *numlist = NULL, *cur;
2425         MsgInfo *msginfo;
2426         IMAPSession *session;
2427         gint ok = MAILIMAP_NO_ERROR;
2428         
2429         g_return_val_if_fail(folder != NULL, -1);
2430         g_return_val_if_fail(dest != NULL, -1);
2431         g_return_val_if_fail(msglist != NULL, -1);
2432
2433         debug_print("getting session...\n");
2434         session = imap_session_get(folder);
2435         if (!session) {
2436                 return -1;
2437         }
2438
2439         lock_session(session); /* unlocked later in the function */
2440
2441         msginfo = (MsgInfo *)msglist->data;
2442
2443         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2444                          NULL, NULL, NULL, NULL, NULL, FALSE);
2445         if (ok != MAILIMAP_NO_ERROR) {
2446                 return ok;
2447         }
2448
2449         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2450         if (is_fatal(ok)) {
2451                 g_free(destdir);
2452                 return ok;
2453         }
2454         for (cur = msglist; cur; cur = cur->next) {
2455                 msginfo = (MsgInfo *)cur->data;
2456                 if (!MSG_IS_DELETED(msginfo->flags))
2457                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2458         }
2459         numlist = g_slist_reverse(numlist);
2460
2461         if (numlist != NULL) {
2462                 ok = imap_set_message_flags
2463                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2464                 if (ok != MAILIMAP_NO_ERROR) {
2465                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2466                         g_free(destdir);
2467                         return ok;
2468                 }
2469         } /* else we just need to expunge */
2470         ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
2471         if (ok != MAILIMAP_NO_ERROR) {
2472                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2473                 g_free(destdir);
2474                 return ok;
2475         }
2476         
2477         session->folder_content_changed = TRUE;
2478         unlock_session(session);
2479
2480         dir = folder_item_get_path(msginfo->folder);
2481         if (is_dir_exist(dir)) {
2482                 for (cur = msglist; cur; cur = cur->next) {
2483                         msginfo = (MsgInfo *)cur->data;
2484                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2485                 }
2486         }
2487         g_free(dir);
2488
2489         g_slist_free(numlist);
2490
2491         imap_scan_required(folder, dest);
2492
2493         g_free(destdir);
2494
2495         return 0;
2496 }
2497
2498 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2499                     MsgInfoList *msglist, GHashTable *relation)
2500 {
2501         MsgInfo *msginfo;
2502
2503         g_return_val_if_fail(folder != NULL, -1);
2504         g_return_val_if_fail(dest != NULL, -1);
2505         if (msglist == NULL)
2506                 return 0;
2507
2508         msginfo = (MsgInfo *)msglist->data;
2509         g_return_val_if_fail(msginfo->folder != NULL, -1);
2510
2511         return imap_do_remove_msgs(folder, dest, msglist, relation);
2512 }
2513
2514 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2515 {
2516         GSList *list = folder_item_get_msg_list(item);
2517         gint res = imap_remove_msgs(folder, item, list, NULL);
2518         procmsg_msg_list_free(list);
2519         return res;
2520 }
2521
2522 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2523                                     MsgInfo *msginfo)
2524 {
2525         /* TODO: properly implement this method */
2526         return FALSE;
2527 }
2528
2529 static gint imap_close(Folder *folder, FolderItem *item)
2530 {
2531         return 0;
2532 }
2533
2534 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2535 {
2536         FolderItem *item = NULL;
2537         IMAPSession *session;
2538         gchar *root_folder = NULL;
2539
2540         g_return_val_if_fail(folder != NULL, -1);
2541         g_return_val_if_fail(folder->account != NULL, -1);
2542
2543         debug_print("getting session...\n");
2544         session = imap_session_get(folder);
2545         if (!session) {
2546                 if (!folder->node) {
2547                         folder_tree_destroy(folder);
2548                         item = folder_item_new(folder, folder->name, NULL);
2549                         item->folder = folder;
2550                         folder->node = item->node = g_node_new(item);
2551                 }
2552                 return -1;
2553         }
2554
2555         if (folder->account->imap_dir && *folder->account->imap_dir) {
2556                 gchar *real_path;
2557                 int r = MAILIMAP_NO_ERROR;
2558                 clist * lep_list;
2559
2560                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2561                 extract_quote(root_folder, '"');
2562                 subst_char(root_folder,
2563                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2564                                                    root_folder, &r),
2565                            '/');
2566                 if (is_fatal(r))
2567                         return -1;
2568                 strtailchomp(root_folder, '/');
2569                 real_path = imap_get_real_path
2570                         (session, IMAP_FOLDER(folder), root_folder, &r);
2571                 if (is_fatal(r)) {
2572                         g_free(real_path);
2573                         return -1;
2574                 }
2575                 debug_print("IMAP root directory: %s\n", real_path);
2576
2577                 /* check if root directory exist */
2578
2579                 r = imap_threaded_list(session->folder, "", real_path,
2580                                        &lep_list);
2581
2582                 if (r != MAILIMAP_NO_ERROR)
2583                         imap_handle_error(SESSION(session), NULL, r);
2584
2585                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2586                         if (!folder->node) {
2587                                 item = folder_item_new(folder, folder->name, NULL);
2588                                 item->folder = folder;
2589                                 folder->node = item->node = g_node_new(item);
2590                         }
2591                         return -1;
2592                 }
2593                 mailimap_list_result_free(lep_list);
2594                                 
2595                 g_free(real_path);
2596         }
2597
2598         if (folder->node)
2599                 item = FOLDER_ITEM(folder->node->data);
2600                 
2601         if (item && !item->path && root_folder) {
2602                 item->path = g_strdup(root_folder);
2603         }
2604
2605         if (!item || ((item->path || root_folder) &&
2606                       strcmp2(item->path, root_folder) != 0)) {
2607                 folder_tree_destroy(folder);
2608                 item = folder_item_new(folder, folder->name, root_folder);
2609                 item->folder = folder;
2610                 folder->node = item->node = g_node_new(item);
2611         }
2612
2613         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2614         imap_create_missing_folders(folder);
2615
2616         return 0;
2617 }
2618
2619 static gint imap_scan_tree(Folder *folder)
2620 {
2621         gboolean subs_only = FALSE;
2622         if (folder->account) {
2623                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2624                 subs_only = folder->account->imap_subsonly;
2625         }
2626         return imap_scan_tree_real(folder, subs_only);
2627 }
2628
2629 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2630 {
2631         Folder *folder;
2632         IMAPFolder *imapfolder;
2633         FolderItem *new_item;
2634         GSList *item_list, *cur;
2635         GNode *node;
2636         gchar *real_path;
2637         gchar *wildcard_path;
2638         gchar separator;
2639         gchar wildcard[3];
2640         clist * lep_list;
2641         int r = MAILIMAP_NO_ERROR;
2642         
2643         g_return_val_if_fail(item != NULL, -1);
2644         g_return_val_if_fail(item->folder != NULL, -1);
2645         g_return_val_if_fail(item->no_sub == FALSE, -1);
2646
2647         folder = item->folder;
2648         imapfolder = IMAP_FOLDER(folder);
2649
2650         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2651         if (is_fatal(r))
2652                 return r;
2653
2654         if (folder->ui_func)
2655                 folder->ui_func(folder, item, folder->ui_func_data);
2656
2657         if (item->path) {
2658                 wildcard[0] = separator;
2659                 wildcard[1] = '%';
2660                 wildcard[2] = '\0';
2661                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2662                 if (is_fatal(r)) {
2663                         g_free(real_path);
2664                         return r;
2665                 }
2666         } else {
2667                 wildcard[0] = '%';
2668                 wildcard[1] = '\0';
2669                 real_path = g_strdup("");
2670         }
2671
2672         Xstrcat_a(wildcard_path, real_path, wildcard,
2673                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2674         lep_list = NULL;
2675         
2676         if (subs_only)
2677                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2678         else
2679                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2680
2681         if (r != MAILIMAP_NO_ERROR) {
2682                 imap_handle_error(SESSION(session), NULL, r);
2683                 item_list = NULL;
2684                 g_free(real_path);
2685                 return r;
2686         }
2687         else {
2688                 item_list = imap_list_from_lep(imapfolder,
2689                                                lep_list, real_path, FALSE);
2690                 mailimap_list_result_free(lep_list);
2691         }
2692         
2693         g_free(real_path);
2694
2695         node = item->node->children;
2696         while (node != NULL) {
2697                 FolderItem *old_item = FOLDER_ITEM(node->data);
2698                 GNode *next = node->next;
2699
2700                 new_item = NULL;
2701                 for (cur = item_list; cur != NULL; cur = cur->next) {
2702                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2703                         if (!strcmp2(old_item->path, cur_item->path)) {
2704                                 new_item = cur_item;
2705                                 break;
2706                         }
2707                 }
2708                 if (!new_item) {
2709                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2710                                 debug_print("not removing INBOX\n");
2711                         } else {
2712                                 debug_print("folder '%s' not found. removing...\n",
2713                                             old_item->path);
2714                                 folder_item_remove(old_item);
2715                         }
2716                 } else {
2717                         old_item->no_sub = new_item->no_sub;
2718                         old_item->no_select = new_item->no_select;
2719                         if (old_item->no_sub == TRUE && node->children) {
2720                                 debug_print("folder '%s' doesn't have "
2721                                             "subfolders. removing...\n",
2722                                             old_item->path);
2723                                 folder_item_remove_children(old_item);
2724                         }
2725                 }
2726
2727                 node = next;
2728         }
2729
2730         for (cur = item_list; cur != NULL; cur = cur->next) {
2731                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2732                 new_item = NULL;
2733
2734                 for (node = item->node->children; node != NULL;
2735                      node = node->next) {
2736                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2737                                      cur_item->path)) {
2738                                 new_item = FOLDER_ITEM(node->data);
2739                                 folder_item_destroy(cur_item);
2740                                 cur_item = NULL;
2741                                 break;
2742                         }
2743                 }
2744                 if (!new_item) {
2745                         new_item = cur_item;
2746                         debug_print("new folder '%s' found.\n", new_item->path);
2747                         folder_item_append(item, new_item);
2748                 }
2749
2750                 if (!strcmp(new_item->path, "INBOX")) {
2751                         new_item->stype = F_INBOX;
2752                         folder->inbox = new_item;
2753                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2754                         gchar *base;
2755
2756                         base = g_path_get_basename(new_item->path);
2757
2758                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2759                                 new_item->stype = F_OUTBOX;
2760                                 folder->outbox = new_item;
2761                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2762                                 new_item->stype = F_DRAFT;
2763                                 folder->draft = new_item;
2764                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2765                                 new_item->stype = F_QUEUE;
2766                                 folder->queue = new_item;
2767                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2768                                 new_item->stype = F_TRASH;
2769                                 folder->trash = new_item;
2770                         }
2771                         g_free(base);
2772                 }
2773
2774                 if (new_item->no_sub == FALSE)
2775                         imap_scan_tree_recursive(session, new_item, subs_only);
2776         }
2777
2778         g_slist_free(item_list);
2779
2780         return MAILIMAP_NO_ERROR;
2781 }
2782
2783 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2784 {
2785         IMAPSession *session = imap_session_get(folder);
2786         gchar *real_path;
2787         gchar *wildcard_path;
2788         gchar separator;
2789         gchar wildcard[3];
2790         clist * lep_list;
2791         GSList *item_list = NULL, *cur;
2792         GList *child_list = NULL, *tmplist = NULL;
2793         GSList *sub_list = NULL;
2794         int r = MAILIMAP_NO_ERROR;
2795
2796         if (!session)
2797                 return NULL;
2798
2799         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2800         if (is_fatal(r))
2801                 return NULL;
2802
2803         if (item->path) {
2804                 wildcard[0] = separator;
2805                 wildcard[1] = '%';
2806                 wildcard[2] = '\0';
2807                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2808                 if (is_fatal(r)) {
2809                         g_free(real_path);
2810                         return NULL;
2811                 }
2812         } else {
2813                 wildcard[0] = '%';
2814                 wildcard[1] = '\0';
2815                 real_path = g_strdup("");
2816         }
2817
2818         Xstrcat_a(wildcard_path, real_path, wildcard,
2819                   {g_free(real_path); return NULL;});
2820         lep_list = NULL;
2821         
2822         if (unsubs_only)
2823                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2824                                 item->path?item->path:item->name);
2825         else
2826                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2827                                 item->path?item->path:item->name);
2828
2829         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2830         if (r) {
2831                 g_free(real_path);
2832                 statusbar_pop_all();
2833                 return NULL;
2834         }
2835         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2836                                lep_list, real_path, FALSE);
2837         mailimap_list_result_free(lep_list);
2838
2839         for (cur = item_list; cur != NULL; cur = cur->next) {
2840                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2841                 if (recursive) {
2842                         tmplist = imap_scan_subtree(folder, cur_item, 
2843                                         unsubs_only, recursive);
2844                         if (tmplist)
2845                                 child_list = g_list_concat(child_list, tmplist);
2846                 }
2847                 child_list = g_list_prepend(child_list,
2848                                 imap_get_real_path(session, 
2849                                         IMAP_FOLDER(folder), cur_item->path, &r));
2850                 if (is_fatal(r)) {
2851                         g_free(real_path);
2852                         statusbar_pop_all();
2853                         return NULL;
2854                 }
2855                 folder_item_destroy(cur_item);
2856         }
2857         child_list = g_list_reverse(child_list);
2858         g_slist_free(item_list);
2859
2860         if (unsubs_only) {
2861                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2862                 if (r) {
2863                         g_free(real_path);
2864                         statusbar_pop_all();
2865                         return NULL;
2866                 }
2867                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2868                                        lep_list, real_path, FALSE);
2869                 mailimap_list_result_free(lep_list);
2870
2871                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2872                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2873                         GList *oldlitem = NULL;
2874                         gchar *tmp = imap_get_real_path(session, 
2875                                         IMAP_FOLDER(folder), cur_item->path, &r);
2876                         if (r) {
2877                                 g_free(real_path);
2878                                 statusbar_pop_all();
2879                                 g_free(tmp);
2880                                 return NULL;
2881                         }
2882                         folder_item_destroy(cur_item);
2883                         oldlitem = g_list_find_custom(
2884                                         child_list, tmp, (GCompareFunc)strcmp2);
2885                         if (oldlitem) {
2886                                 child_list = g_list_remove_link(child_list, oldlitem);
2887                                 g_free(oldlitem->data);
2888                                 g_list_free(oldlitem);
2889                         }
2890                         g_free(tmp);
2891                 }
2892         }
2893
2894         g_free(real_path);
2895         statusbar_pop_all();
2896
2897         return child_list;
2898 }
2899
2900 static gint imap_create_tree(Folder *folder)
2901 {
2902         g_return_val_if_fail(folder != NULL, -1);
2903         g_return_val_if_fail(folder->node != NULL, -1);
2904         g_return_val_if_fail(folder->node->data != NULL, -1);
2905         g_return_val_if_fail(folder->account != NULL, -1);
2906
2907         imap_scan_tree(folder);
2908         imap_create_missing_folders(folder);
2909
2910         return 0;
2911 }
2912
2913 static void imap_create_missing_folders(Folder *folder)
2914 {
2915         g_return_if_fail(folder != NULL);
2916
2917         if (!folder->inbox)
2918                 folder->inbox = imap_create_special_folder
2919                         (folder, F_INBOX, "INBOX");
2920         if (!folder->trash)
2921                 folder->trash = imap_create_special_folder
2922                         (folder, F_TRASH, "Trash");
2923         if (!folder->queue)
2924                 folder->queue = imap_create_special_folder
2925                         (folder, F_QUEUE, "Queue");
2926         if (!folder->outbox)
2927                 folder->outbox = imap_create_special_folder
2928                         (folder, F_OUTBOX, "Sent");
2929         if (!folder->draft)
2930                 folder->draft = imap_create_special_folder
2931                         (folder, F_DRAFT, "Drafts");
2932 }
2933
2934 static FolderItem *imap_create_special_folder(Folder *folder,
2935                                               SpecialFolderItemType stype,
2936                                               const gchar *name)
2937 {
2938         FolderItem *item;
2939         FolderItem *new_item;
2940
2941         g_return_val_if_fail(folder != NULL, NULL);
2942         g_return_val_if_fail(folder->node != NULL, NULL);
2943         g_return_val_if_fail(folder->node->data != NULL, NULL);
2944         g_return_val_if_fail(folder->account != NULL, NULL);
2945         g_return_val_if_fail(name != NULL, NULL);
2946
2947         item = FOLDER_ITEM(folder->node->data);
2948         new_item = imap_create_folder(folder, item, name);
2949
2950         if (!new_item) {
2951                 g_warning("Can't create '%s'\n", name);
2952                 if (!folder->inbox) return NULL;
2953
2954                 new_item = imap_create_folder(folder, folder->inbox, name);
2955                 if (!new_item)
2956                         g_warning("Can't create '%s' under INBOX\n", name);
2957                 else
2958                         new_item->stype = stype;
2959         } else
2960                 new_item->stype = stype;
2961
2962         return new_item;
2963 }
2964
2965 static gchar *imap_folder_get_path(Folder *folder)
2966 {
2967         gchar *folder_path;
2968
2969         g_return_val_if_fail(folder != NULL, NULL);
2970         g_return_val_if_fail(folder->account != NULL, NULL);
2971
2972         folder_path = g_strconcat(get_imap_cache_dir(),
2973                                   G_DIR_SEPARATOR_S,
2974                                   folder->account->recv_server,
2975                                   G_DIR_SEPARATOR_S,
2976                                   folder->account->userid,
2977                                   NULL);
2978
2979         return folder_path;
2980 }
2981
2982 #ifdef G_OS_WIN32
2983 static gchar *imap_encode_unsafe_chars(const gchar *str)
2984 {
2985         gchar *ret = NULL, *o_ret;
2986         gchar *i;
2987         if (!str) 
2988                 return NULL;
2989         ret = g_malloc(3*strlen(str)+1);
2990         o_ret = ret;
2991         for (i = str; *i; i++) {
2992                 switch(*i) {
2993                         case ':':
2994                         case '|':
2995                         case '<':
2996                         case '>':
2997                         case '*':
2998                         case '?':
2999                         case '#':
3000                                 *ret++ = '%';
3001                                 *ret++ = '0'+(*i/10);
3002                                 *ret++ = '0'+(*i%10);
3003                                 break;
3004                         default:
3005                                 *ret++ = *i;
3006                 }
3007         }
3008         *ret++ = '\0';
3009         return o_ret;
3010 }
3011 #endif
3012 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3013 {
3014         gchar *folder_path, *path;
3015         gchar *item_path = NULL;
3016         
3017         g_return_val_if_fail(folder != NULL, NULL);
3018         g_return_val_if_fail(item != NULL, NULL);
3019         folder_path = imap_folder_get_path(folder);
3020
3021         g_return_val_if_fail(folder_path != NULL, NULL);
3022
3023 #ifdef G_OS_UNIX
3024         item_path = g_strdup(item->path);
3025 #else
3026         item_path = imap_encode_unsafe_chars(item->path);
3027 #endif  
3028
3029         if (g_path_is_absolute(folder_path)) {
3030                 if (item_path)
3031                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3032                                            item_path, NULL);
3033                 else
3034                         path = g_strdup(folder_path);
3035         } else {
3036                 if (item_path)
3037                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3038                                            folder_path, G_DIR_SEPARATOR_S,
3039                                            item_path, NULL);
3040                 else
3041                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3042                                            folder_path, NULL);
3043         }
3044         g_free(folder_path);
3045         g_free(item_path);
3046 #ifdef G_OS_WIN32
3047         while (strchr(path, '/'))
3048                 *strchr(path, '/') = '\\';
3049 #endif
3050
3051         return path;
3052 }
3053
3054 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3055                                const gchar *name)
3056 {
3057         gchar *dirpath, *imap_path;
3058         IMAPSession *session;
3059         FolderItem *new_item;
3060         gchar separator;
3061         gchar *new_name;
3062         const gchar *p;
3063         gint ok = MAILIMAP_NO_ERROR;
3064         gboolean no_select = FALSE, no_sub = FALSE;
3065         gboolean exist = FALSE;
3066         
3067         g_return_val_if_fail(folder != NULL, NULL);
3068         g_return_val_if_fail(folder->account != NULL, NULL);
3069         g_return_val_if_fail(parent != NULL, NULL);
3070         g_return_val_if_fail(name != NULL, NULL);
3071
3072         debug_print("getting session...\n");
3073         session = imap_session_get(folder);
3074         if (!session) {
3075                 return NULL;
3076         }
3077
3078         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
3079                 dirpath = g_strdup(name);
3080         }else if (parent->path)
3081                 dirpath = g_strconcat(parent->path, "/", name, NULL);
3082         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3083                 dirpath = g_strdup(name);
3084         else if (folder->account->imap_dir && *folder->account->imap_dir) {
3085                 gchar *imap_dir;
3086
3087                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3088                 strtailchomp(imap_dir, '/');
3089                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3090         } else
3091                 dirpath = g_strdup(name);
3092                 
3093         
3094
3095         /* keep trailing directory separator to create a folder that contains
3096            sub folder */
3097         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3098
3099         strtailchomp(dirpath, '/');
3100         Xstrdup_a(new_name, name, {
3101                 g_free(dirpath); 
3102                 g_free(imap_path);
3103                 return NULL;});
3104
3105         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3106         if (is_fatal(ok)) {
3107                 g_free(imap_path);
3108                 return NULL;
3109         }
3110         imap_path_separator_subst(imap_path, separator);
3111         /* remove trailing / for display */
3112         strtailchomp(new_name, '/');
3113
3114         if (strcmp(dirpath, "INBOX") != 0) {
3115                 GPtrArray *argbuf;
3116                 int r;
3117                 clist * lep_list;
3118                 
3119                 argbuf = g_ptr_array_new();
3120                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3121                 if (r != MAILIMAP_NO_ERROR) {
3122                         imap_handle_error(SESSION(session), NULL, r);
3123                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3124                         g_free(imap_path);
3125                         g_free(dirpath);
3126                         ptr_array_free_strings(argbuf);
3127                         g_ptr_array_free(argbuf, TRUE);
3128                         return NULL;
3129                 }
3130                 
3131                 if (clist_count(lep_list) > 0)
3132                         exist = TRUE;
3133                 mailimap_list_result_free(lep_list);
3134                 lep_list = NULL;
3135                 if (!exist) {
3136                         ok = imap_cmd_create(session, imap_path);
3137                         if (ok != MAILIMAP_NO_ERROR) {
3138                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3139                                 g_free(imap_path);
3140                                 g_free(dirpath);
3141                                 return NULL;
3142                         }
3143                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
3144                         if (r == MAILIMAP_NO_ERROR) {
3145                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3146                                                lep_list, dirpath, TRUE);
3147                                 if (item_list) {
3148                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3149                                         no_select = cur_item->no_select;
3150                                         no_sub = cur_item->no_sub;
3151                                         g_slist_free(item_list);
3152                                 } 
3153                                 mailimap_list_result_free(lep_list);
3154                         } else {
3155                                 imap_handle_error(SESSION(session), NULL, r);
3156                         }
3157                 }
3158                 imap_threaded_subscribe(folder, imap_path, TRUE);
3159         } else {
3160                 clist *lep_list;
3161                 int r;
3162                 /* just get flags */
3163                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3164                 if (r == MAILIMAP_NO_ERROR) {
3165                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3166                                        lep_list, dirpath, TRUE);
3167                         if (item_list) {
3168                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3169                                 no_select = cur_item->no_select;
3170                                 no_sub = cur_item->no_sub;
3171                                 g_slist_free(item_list);
3172                         } 
3173                         mailimap_list_result_free(lep_list);
3174                 } else {
3175                         imap_handle_error(SESSION(session), NULL, r);
3176                 }
3177         }
3178
3179         new_item = folder_item_new(folder, new_name, dirpath);
3180         new_item->no_select = no_select;
3181         new_item->no_sub = no_sub;
3182         folder_item_append(parent, new_item);
3183         g_free(imap_path);
3184         g_free(dirpath);
3185
3186         dirpath = folder_item_get_path(new_item);
3187         if (!is_dir_exist(dirpath))
3188                 make_dir_hier(dirpath);
3189         g_free(dirpath);
3190
3191         if (exist) {
3192                 /* folder existed, scan it */
3193                 imap_scan_required(folder, new_item);
3194                 folder_item_scan_full(new_item, FALSE);
3195         }
3196
3197         return new_item;
3198 }
3199
3200 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3201                                const gchar *name)
3202 {
3203         gchar *dirpath;
3204         gchar *newpath;
3205         gchar *real_oldpath;
3206         gchar *real_newpath;
3207         gchar *paths[2];
3208         gchar *old_cache_dir;
3209         gchar *new_cache_dir;
3210         IMAPSession *session;
3211         gchar separator;
3212         gint ok = MAILIMAP_NO_ERROR;
3213         gint exists, recent, unseen;
3214         guint32 uid_validity;
3215
3216         g_return_val_if_fail(folder != NULL, -1);
3217         g_return_val_if_fail(item != NULL, -1);
3218         g_return_val_if_fail(item->path != NULL, -1);
3219         g_return_val_if_fail(name != NULL, -1);
3220
3221         debug_print("getting session...\n");
3222         session = imap_session_get(folder);
3223         if (!session) {
3224                 return -1;
3225         }
3226
3227         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3228                 is_fatal(ok)) {
3229                 g_warning(_("New folder name must not contain the namespace "
3230                             "path separator"));
3231                 return -1;
3232         }
3233
3234         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3235         if (is_fatal(ok)) {
3236                 g_free(real_oldpath);
3237                 return -1;
3238         }
3239
3240         g_free(session->mbox);
3241         session->mbox = NULL;
3242         session->exists = 0;
3243         session->recent = 0;
3244         session->expunge = 0;
3245         ok = imap_cmd_examine(session, "INBOX",
3246                               &exists, &recent, &unseen, &uid_validity, FALSE);
3247         if (ok != MAILIMAP_NO_ERROR) {
3248                 g_free(real_oldpath);
3249                 return -1;
3250         }
3251
3252         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3253         if (is_fatal(ok)) {
3254                 g_free(real_oldpath);
3255                 return -1;
3256         }
3257         if (strchr(item->path, G_DIR_SEPARATOR)) {
3258                 dirpath = g_path_get_dirname(item->path);
3259                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
3260                 g_free(dirpath);
3261         } else
3262                 newpath = g_strdup(name);
3263
3264         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3265         imap_path_separator_subst(real_newpath, separator);
3266
3267         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3268         if (ok != MAILIMAP_NO_ERROR) {
3269                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3270                             real_oldpath, real_newpath);
3271                 g_free(real_oldpath);
3272                 g_free(newpath);
3273                 g_free(real_newpath);
3274                 return -1;
3275         }
3276         g_free(item->name);
3277         item->name = g_strdup(name);
3278
3279         old_cache_dir = folder_item_get_path(item);
3280
3281         paths[0] = g_strdup(item->path);
3282         paths[1] = newpath;
3283         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3284                         imap_rename_folder_func, paths);
3285
3286         if (is_dir_exist(old_cache_dir)) {
3287                 new_cache_dir = folder_item_get_path(item);
3288                 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3289                         FILE_OP_ERROR(old_cache_dir, "rename");
3290                 }
3291                 g_free(new_cache_dir);
3292         }
3293
3294         g_free(old_cache_dir);
3295         g_free(paths[0]);
3296         g_free(newpath);
3297         g_free(real_oldpath);
3298         g_free(real_newpath);