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