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