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