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