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