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