Rewritten account passwords handling.
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include "imap.h"
32 #include "imap_gtk.h"
33 #include "inc.h"
34 #include "xml.h"
35 #include "alertpanel.h"
36
37 #ifdef HAVE_LIBETPAN
38
39 #include <stdlib.h>
40 #include <dirent.h>
41 #include <unistd.h>
42 #include <ctype.h>
43 #include <time.h>
44 #include <errno.h>
45 #if HAVE_ICONV
46 #  include <iconv.h>
47 #endif
48
49 #ifdef USE_GNUTLS
50 #  include "ssl.h"
51 #endif
52
53 #include "folder.h"
54 #include "session.h"
55 #include "procmsg.h"
56 #include "socket.h"
57 #include "recv.h"
58 #include "procheader.h"
59 #include "prefs_account.h"
60 #include "codeconv.h"
61 #include "md5.h"
62 #include "utils.h"
63 #include "prefs_common.h"
64 #include "inputdialog.h"
65 #include "log.h"
66 #include "remotefolder.h"
67 #include "claws.h"
68 #include "statusbar.h"
69 #include "msgcache.h"
70 #include "imap-thread.h"
71 #include "account.h"
72 #include "tags.h"
73 #include "main.h"
74 #include "password.h"
75
76 typedef struct _IMAPFolder      IMAPFolder;
77 typedef struct _IMAPSession     IMAPSession;
78 typedef struct _IMAPNameSpace   IMAPNameSpace;
79 typedef struct _IMAPFolderItem  IMAPFolderItem;
80
81 #include "prefs_account.h"
82
83 #define IMAP_FOLDER(obj)        ((IMAPFolder *)obj)
84 #define IMAP_FOLDER_ITEM(obj)   ((IMAPFolderItem *)obj)
85 #define IMAP_SESSION(obj)       ((IMAPSession *)obj)
86
87 struct _IMAPFolder
88 {
89         RemoteFolder rfolder;
90
91         /* list of IMAPNameSpace */
92         GList *ns_personal;
93         GList *ns_others;
94         GList *ns_shared;
95         gchar last_seen_separator;
96         guint refcnt;
97         guint max_set_size;
98         gchar *search_charset;
99         gboolean search_charset_supported;
100 };
101
102 struct _IMAPSession
103 {
104         Session session;
105
106         gboolean authenticated;
107
108         GSList *capability;
109         gboolean uidplus;
110
111         gchar *mbox;
112         guint cmd_count;
113
114         /* CLAWS */
115         gboolean folder_content_changed;
116         guint exists;
117         guint recent;
118         guint expunge;
119         guint unseen;
120         guint uid_validity;
121         guint uid_next;
122
123         Folder * folder;
124         gboolean busy;
125         gboolean cancelled;
126         gboolean sens_update_block;
127         gboolean do_destroy;
128 };
129
130 struct _IMAPNameSpace
131 {
132         gchar *name;
133         gchar separator;
134 };
135
136 #define IMAPBUFSIZE     8192
137
138 #define IMAP_IS_SEEN(flags)     ((flags & IMAP_FLAG_SEEN) != 0)
139 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
140 #define IMAP_IS_FLAGGED(flags)  ((flags & IMAP_FLAG_FLAGGED) != 0)
141 #define IMAP_IS_DELETED(flags)  ((flags & IMAP_FLAG_DELETED) != 0)
142 #define IMAP_IS_DRAFT(flags)    ((flags & IMAP_FLAG_DRAFT) != 0)
143 #define IMAP_IS_FORWARDED(flags)        ((flags & IMAP_FLAG_FORWARDED) != 0)
144 #define IMAP_IS_SPAM(flags)     ((flags & IMAP_FLAG_SPAM) != 0)
145 #define IMAP_IS_HAM(flags)      ((flags & IMAP_FLAG_HAM) != 0)
146
147
148 #define IMAP4_PORT      143
149 #ifdef USE_GNUTLS
150 #define IMAPS_PORT      993
151 #endif
152
153 #define IMAP_CMD_LIMIT  1000
154
155 enum {
156         ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
157         ITEM_CAN_CREATE_FLAGS,
158         ITEM_CANNOT_CREATE_FLAGS
159 };
160
161 struct _IMAPFolderItem
162 {
163         FolderItem item;
164
165         guint lastuid;
166         guint uid_next;
167         GSList *uid_list;
168         gboolean batching;
169
170         GHashTable *flags_set_table;
171         GHashTable *flags_unset_table;
172         guint32 last_change;
173         guint32 last_sync;
174         gboolean should_update;
175         gboolean should_trash_cache;
176         gint can_create_flags;
177
178         GHashTable *tags_set_table;
179         GHashTable *tags_unset_table;
180         GSList *ok_flags;
181
182 };
183
184 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
185 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
186
187 static void imap_folder_init            (Folder         *folder,
188                                          const gchar    *name,
189                                          const gchar    *path);
190
191 static Folder   *imap_folder_new        (const gchar    *name,
192                                          const gchar    *path);
193 static void      imap_folder_destroy    (Folder         *folder);
194
195 static IMAPSession *imap_session_new    (Folder         *folder,
196                                          const PrefsAccount     *account);
197 static gint     imap_session_authenticate(IMAPSession   *session,
198                                           PrefsAccount  *account);
199 static void     imap_session_destroy    (Session        *session);
200
201 static gchar   *imap_fetch_msg          (Folder         *folder, 
202                                          FolderItem     *item, 
203                                          gint            uid);
204 static gchar   *imap_fetch_msg_full     (Folder         *folder, 
205                                          FolderItem     *item, 
206                                          gint            uid,
207                                          gboolean        headers,
208                                          gboolean        body);
209 static void     imap_remove_cached_msg  (Folder         *folder, 
210                                          FolderItem     *item, 
211                                          MsgInfo        *msginfo);
212 static gint     imap_add_msg            (Folder         *folder,
213                                          FolderItem     *dest,
214                                          const gchar    *file, 
215                                          MsgFlags       *flags);
216 static gint     imap_add_msgs           (Folder         *folder, 
217                                          FolderItem     *dest,
218                                          GSList         *file_list,
219                                          GHashTable     *relation);
220
221 static gint     imap_copy_msg           (Folder         *folder,
222                                          FolderItem     *dest, 
223                                          MsgInfo        *msginfo);
224 static gint     imap_copy_msgs          (Folder         *folder, 
225                                          FolderItem     *dest, 
226                                          MsgInfoList    *msglist, 
227                                          GHashTable     *relation);
228
229 static gint     search_msgs             (Folder                 *folder,
230                                          FolderItem             *container,
231                                          MsgNumberList          **msgs,
232                                          gboolean               *on_server,
233                                          MatcherList            *predicate,
234                                          SearchProgressNotify   progress_cb,
235                                          gpointer               progress_data);
236
237 static gint     imap_remove_msg         (Folder         *folder, 
238                                          FolderItem     *item, 
239                                          gint            uid);
240 static gint     imap_remove_msgs        (Folder         *folder, 
241                                          FolderItem     *dest, 
242                                          MsgInfoList    *msglist, 
243                                          GHashTable     *relation);
244 static gint     imap_expunge            (Folder         *folder, 
245                                          FolderItem     *dest);
246 static gint     imap_remove_all_msg     (Folder         *folder, 
247                                          FolderItem     *item);
248
249 static gboolean imap_is_msg_changed     (Folder         *folder,
250                                          FolderItem     *item, 
251                                          MsgInfo        *msginfo);
252
253 static gint     imap_close              (Folder         *folder, 
254                                          FolderItem     *item);
255
256 static gint     imap_scan_tree          (Folder         *folder);
257
258 static gint     imap_create_tree        (Folder         *folder);
259
260 static FolderItem *imap_create_folder   (Folder         *folder,
261                                          FolderItem     *parent,
262                                          const gchar    *name);
263 static gint     imap_rename_folder      (Folder         *folder,
264                                          FolderItem     *item, 
265                                          const gchar    *name);
266 static gint     imap_remove_folder      (Folder         *folder, 
267                                          FolderItem     *item);
268
269 static FolderItem *imap_folder_item_new (Folder         *folder);
270 static void imap_folder_item_destroy    (Folder         *folder,
271                                          FolderItem     *item);
272
273 static IMAPSession *imap_session_get    (Folder         *folder);
274
275 static gint imap_auth                   (IMAPSession    *session,
276                                          const gchar    *user,
277                                          const gchar    *pass,
278                                          IMAPAuthType    type);
279
280 static gint imap_scan_tree_recursive    (IMAPSession    *session,
281                                          FolderItem     *item,
282                                          gboolean        subs_only);
283
284 static void imap_create_missing_folders (Folder         *folder);
285 static FolderItem *imap_create_special_folder
286                                         (Folder                 *folder,
287                                          SpecialFolderItemType   stype,
288                                          const gchar            *name);
289
290 static gint imap_do_copy_msgs           (Folder         *folder,
291                                          FolderItem     *dest,
292                                          MsgInfoList    *msglist,
293                                          GHashTable     *relation,
294                                          gboolean        same_dest_ok);
295
296 static gint imap_do_remove_msgs         (Folder         *folder,
297                                          FolderItem     *dest,
298                                          MsgInfoList    *msglist,
299                                          GHashTable     *relation);
300
301 static void imap_delete_all_cached_messages     (FolderItem     *item);
302 static void imap_set_batch              (Folder         *folder,
303                                          FolderItem     *item,
304                                          gboolean        batch);
305 static gint imap_set_message_flags      (IMAPSession    *session,
306                                          IMAPFolderItem *item,
307                                          MsgNumberList  *numlist,
308                                          IMAPFlags       flags,
309                                          GSList         *tags,
310                                          gboolean        is_set);
311 static gint imap_select                 (IMAPSession    *session,
312                                          IMAPFolder     *folder,
313                                          FolderItem     *item,
314                                          gint           *exists,
315                                          gint           *recent,
316                                          gint           *unseen,
317                                          guint32        *uid_validity,
318                                          gint           *can_create_flags,
319                                          gboolean        block);
320 static gint imap_status                 (IMAPSession    *session,
321                                          IMAPFolder     *folder,
322                                          const gchar    *path,
323                                          IMAPFolderItem *item,
324                                          gint           *messages,
325                                          guint32        *uid_next,
326                                          guint32        *uid_validity,
327                                          gint           *unseen,
328                                          gboolean        block);
329 static void     imap_commit_tags        (FolderItem     *item, 
330                                          MsgInfo        *msginfo,
331                                          GSList         *set_tags,
332                                          GSList         *unset_tags);
333
334 static gchar imap_get_path_separator            (IMAPSession    *session,
335                                                  IMAPFolder     *folder,
336                                                  const gchar    *path,
337                                                  gint           *ok);
338 static gchar *imap_get_real_path                (IMAPSession    *session,
339                                                  IMAPFolder     *folder,
340                                                  const gchar    *path,
341                                                  gint           *ok);
342 #ifdef HAVE_LIBETPAN
343 static void imap_synchronise            (FolderItem     *item, gint days);
344 #endif
345 static gboolean imap_is_busy            (Folder *folder);
346
347 static void imap_free_capabilities      (IMAPSession    *session);
348
349 /* low-level IMAP4rev1 commands */
350 static gint imap_cmd_login      (IMAPSession    *session,
351                                  const gchar    *user,
352                                  const gchar    *pass,
353                                  const gchar    *type);
354 static gint imap_cmd_noop       (IMAPSession    *session);
355 #ifdef USE_GNUTLS
356 static gint imap_cmd_starttls   (IMAPSession    *session);
357 #endif
358 static gint imap_cmd_select     (IMAPSession    *session,
359                                  const gchar    *folder,
360                                  gint           *exists,
361                                  gint           *recent,
362                                  gint           *unseen,
363                                  guint32        *uid_validity,
364                                  gint           *can_create_flags,
365                                  GSList         **ok_flags,
366                                  gboolean        block);
367 static gint imap_cmd_close      (IMAPSession    *session);
368 static gint imap_cmd_examine    (IMAPSession    *session,
369                                  const gchar    *folder,
370                                  gint           *exists,
371                                  gint           *recent,
372                                  gint           *unseen,
373                                  guint32        *uid_validity,
374                                  gboolean        block);
375 static gint imap_cmd_create     (IMAPSession    *sock,
376                                  const gchar    *folder);
377 static gint imap_cmd_rename     (IMAPSession    *sock,
378                                  const gchar    *oldfolder,
379                                  const gchar    *newfolder);
380 static gint imap_cmd_delete     (IMAPSession    *session,
381                                  const gchar    *folder);
382 static gint imap_cmd_fetch      (IMAPSession    *sock,
383                                  guint32         uid,
384                                  const gchar    *filename,
385                                  gboolean        headers,
386                                  gboolean        body);
387 static gint imap_cmd_append     (IMAPSession    *session,
388                                  IMAPFolderItem *item,
389                                  const gchar    *destfolder,
390                                  const gchar    *file,
391                                  IMAPFlags       flags,
392                                  guint32        *new_uid);
393 static gint imap_cmd_copy       (IMAPSession *session,
394                                  struct mailimap_set * set,
395                                  const gchar *destfolder,
396                                  struct mailimap_set ** source,
397                                  struct mailimap_set ** dest);
398 static gint imap_cmd_store      (IMAPSession    *session,
399                                  IMAPFolderItem *item,
400                                  struct mailimap_set * set,
401                                  IMAPFlags flags,
402                                  GSList *tags,
403                                  int do_add);
404 static gint imap_cmd_expunge    (IMAPSession    *session, gboolean force);
405
406 static void imap_path_separator_subst           (gchar          *str,
407                                                  gchar           separator);
408
409 static gboolean imap_rename_folder_func         (GNode          *node,
410                                                  gpointer        data);
411 static gint imap_get_num_list                   (Folder         *folder,
412                                                  FolderItem     *item,
413                                                  GSList        **list,
414                                                  gboolean       *old_uids_valid);
415 static GSList *imap_get_msginfos                (Folder         *folder,
416                                                  FolderItem     *item,
417                                                  GSList         *msgnum_list);
418 static MsgInfo *imap_get_msginfo                (Folder         *folder,
419                                                  FolderItem     *item,
420                                                  gint            num);
421 static gboolean imap_scan_required              (Folder         *folder,
422                                                  FolderItem     *item);
423 static void imap_change_flags                   (Folder         *folder,
424                                                  FolderItem     *item,
425                                                  MsgInfo        *msginfo,
426                                                  MsgPermFlags    newflags);
427 static gint imap_get_flags                      (Folder         *folder,
428                                                  FolderItem     *item,
429                                                  MsgInfoList    *msglist,
430                                                  GHashTable     *msgflags);
431 static gchar *imap_folder_get_path              (Folder         *folder);
432 static gchar *imap_item_get_path                (Folder         *folder,
433                                                  FolderItem     *item);
434 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
435
436
437 /* data types conversion libetpan <-> claws */
438 static GSList * imap_list_from_lep(IMAPFolder * folder,
439                                    clist * list, const gchar * real_path, gboolean all);
440 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
441 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
442 static GSList * imap_uid_list_from_lep(clist * list, gint* length);
443 static GSList * imap_uid_list_from_lep_tab(carray * list);
444 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
445                                                    GHashTable * hash,
446                                                    GHashTable *tags_hash);
447 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
448                                        FolderItem *item);
449 static void imap_lep_set_free(GSList *seq_list);
450 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
451
452 typedef struct _hashtable_data {
453         GSList *msglist;
454         IMAPFolderItem *item;
455 } hashtable_data;
456
457 static FolderClass imap_class;
458
459 FolderClass *imap_get_class(void)
460 {
461         if (imap_class.idstr == NULL) {
462                 imap_class.type = F_IMAP;
463                 imap_class.idstr = "imap";
464                 imap_class.uistr = "IMAP4";
465                 imap_class.supports_server_search = TRUE;
466
467                 /* Folder functions */
468                 imap_class.new_folder = imap_folder_new;
469                 imap_class.destroy_folder = imap_folder_destroy;
470                 imap_class.scan_tree = imap_scan_tree;
471                 imap_class.create_tree = imap_create_tree;
472
473                 /* FolderItem functions */
474                 imap_class.item_new = imap_folder_item_new;
475                 imap_class.item_destroy = imap_folder_item_destroy;
476                 imap_class.item_get_path = imap_item_get_path;
477                 imap_class.create_folder = imap_create_folder;
478                 imap_class.rename_folder = imap_rename_folder;
479                 imap_class.remove_folder = imap_remove_folder;
480                 imap_class.close = imap_close;
481                 imap_class.get_num_list = imap_get_num_list;
482                 imap_class.scan_required = imap_scan_required;
483                 imap_class.set_xml = folder_set_xml;
484                 imap_class.get_xml = folder_get_xml;
485                 imap_class.item_set_xml = imap_item_set_xml;
486                 imap_class.item_get_xml = imap_item_get_xml;
487
488                 /* Message functions */
489                 imap_class.get_msginfo = imap_get_msginfo;
490                 imap_class.get_msginfos = imap_get_msginfos;
491                 imap_class.fetch_msg = imap_fetch_msg;
492                 imap_class.fetch_msg_full = imap_fetch_msg_full;
493                 imap_class.add_msg = imap_add_msg;
494                 imap_class.add_msgs = imap_add_msgs;
495                 imap_class.copy_msg = imap_copy_msg;
496                 imap_class.copy_msgs = imap_copy_msgs;
497                 imap_class.search_msgs = search_msgs;
498                 imap_class.remove_msg = imap_remove_msg;
499                 imap_class.remove_msgs = imap_remove_msgs;
500                 imap_class.expunge = imap_expunge;
501                 imap_class.remove_all_msg = imap_remove_all_msg;
502                 imap_class.is_msg_changed = imap_is_msg_changed;
503                 imap_class.change_flags = imap_change_flags;
504                 imap_class.get_flags = imap_get_flags;
505                 imap_class.set_batch = imap_set_batch;
506                 imap_class.synchronise = imap_synchronise;
507                 imap_class.remove_cached_msg = imap_remove_cached_msg;
508                 imap_class.commit_tags = imap_commit_tags;
509 #ifdef USE_PTREAD
510                 pthread_mutex_init(&imap_mutex, NULL);
511 #endif
512         }
513         
514         return &imap_class;
515 }
516
517 static void imap_refresh_sensitivity (IMAPSession *session)
518 {
519         MainWindow *mainwin;
520
521         if (session->sens_update_block)
522                 return;
523         mainwin = mainwindow_get_mainwindow();
524         if (mainwin) {
525                 toolbar_main_set_sensitive(mainwin);
526                 main_window_set_menu_sensitive(mainwin);
527         }
528 }
529
530 static void lock_session(IMAPSession *session)
531 {
532         if (session) {
533                 debug_print("locking session %p (%d)\n", session, session->busy);
534                 if (session->busy)
535                         debug_print("         SESSION WAS LOCKED !!      \n");
536                 session->busy = TRUE;
537                 imap_refresh_sensitivity(session);
538         } else {
539                 debug_print("can't lock null session\n");
540         }
541 }
542
543 static void unlock_session(IMAPSession *session)
544 {
545         if (session) {
546                 debug_print("unlocking session %p\n", session);
547                 session->busy = FALSE;
548                 imap_refresh_sensitivity(session);
549         } else {
550                 debug_print("can't unlock null session\n");
551         }
552 }
553
554 static gboolean imap_ping(gpointer data)
555 {
556         Session *session = (Session *)data;
557         IMAPSession *imap_session = IMAP_SESSION(session);
558         int r;
559
560         if (session->state != SESSION_READY)
561                 return FALSE;
562         if (imap_session->busy || !imap_session->authenticated)
563                 return TRUE;
564         
565         lock_session(imap_session);
566         r = imap_cmd_noop(imap_session);
567         unlock_session(imap_session);
568
569         return r == MAILIMAP_NO_ERROR;
570 }
571
572 static void imap_disc_session_destroy(IMAPSession *session)
573 {
574         RemoteFolder *rfolder = NULL;
575
576         if (session == NULL)
577                 return;
578
579         rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
580         
581         if (rfolder == NULL)
582                 return;
583         log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
584         SESSION(session)->state = SESSION_DISCONNECTED;
585         SESSION(session)->sock = NULL;
586 }
587
588 static void imap_safe_destroy(IMAPSession *session)
589 {
590         if (!session->busy)
591                 session_destroy(SESSION(session));
592         else
593                 session->do_destroy = TRUE;
594 }
595
596 static gboolean is_fatal(int libetpan_errcode)
597 {
598         switch(libetpan_errcode) {
599         case MAILIMAP_ERROR_STREAM:
600         case MAILIMAP_ERROR_PROTOCOL:
601         case MAILIMAP_ERROR_PARSE:
602         case MAILIMAP_ERROR_BAD_STATE:
603                 return TRUE;
604         default:
605                 return FALSE;
606         }
607 }
608
609 static void imap_handle_error(Session *session, const gchar *server, int libetpan_errcode)
610 {
611         const gchar *session_server = (session ? session->server : NULL);
612
613         if (session_server == NULL)
614                 session_server = server;
615         if (session_server == NULL)
616                 session_server = "(null)";
617
618         switch(libetpan_errcode) {
619         case MAILIMAP_NO_ERROR:
620                 return;
621         case MAILIMAP_NO_ERROR_AUTHENTICATED:
622                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" authenticated\n"), NULL), session_server);
623                 break;
624         case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
625                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" not authenticated\n"), NULL), session_server);
626                 break;
627         case MAILIMAP_ERROR_BAD_STATE:
628                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" bad state\n"), NULL), session_server);
629                 break;
630         case MAILIMAP_ERROR_STREAM:
631                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" stream error\n"), NULL), session_server);
632                 break;
633         case MAILIMAP_ERROR_PARSE:
634                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" parse error "
635                                             "(very probably non-RFC compliance from the server)\n"), NULL), session_server);
636                 break;
637         case MAILIMAP_ERROR_CONNECTION_REFUSED:
638                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" connection refused\n"), NULL), session_server);
639                 break;
640         case MAILIMAP_ERROR_MEMORY:
641                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" memory error\n"), NULL), session_server);
642                 break;
643         case MAILIMAP_ERROR_FATAL:
644                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" fatal error\n"), NULL), session_server);
645                 break;
646         case MAILIMAP_ERROR_PROTOCOL:
647                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" protocol error "
648                                             "(very probably non-RFC compliance from the server)\n"), NULL), session_server);
649                 break;
650         case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
651                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" connection not accepted\n"), NULL), session_server);
652                 break;
653         case MAILIMAP_ERROR_APPEND:
654                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" APPEND error\n"), NULL), session_server);
655                 break;
656         case MAILIMAP_ERROR_NOOP:
657                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" NOOP error\n"), NULL), session_server);
658                 break;
659         case MAILIMAP_ERROR_LOGOUT:
660                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" LOGOUT error\n"), NULL), session_server);
661                 break;
662         case MAILIMAP_ERROR_CAPABILITY:
663                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" CAPABILITY error\n"), NULL), session_server);
664                 break;
665         case MAILIMAP_ERROR_CHECK:
666                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" CHECK error\n"), NULL), session_server);
667                 break;
668         case MAILIMAP_ERROR_CLOSE:
669                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" CLOSE error\n"), NULL), session_server);
670                 break;
671         case MAILIMAP_ERROR_EXPUNGE:
672                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" EXPUNGE error\n"), NULL), session_server);
673                 break;
674         case MAILIMAP_ERROR_COPY:
675                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" COPY error\n"), NULL), session_server);
676                 break;
677         case MAILIMAP_ERROR_UID_COPY:
678                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" UID COPY error\n"), NULL), session_server);
679                 break;
680         case MAILIMAP_ERROR_CREATE:
681                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" CREATE error\n"), NULL), session_server);
682                 break;
683         case MAILIMAP_ERROR_DELETE:
684                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" DELETE error\n"), NULL), session_server);
685                 break;
686         case MAILIMAP_ERROR_EXAMINE:
687                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" EXAMINE error\n"), NULL), session_server);
688                 break;
689         case MAILIMAP_ERROR_FETCH:
690                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" FETCH error\n"), NULL), session_server);
691                 break;
692         case MAILIMAP_ERROR_UID_FETCH:
693                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" UID FETCH error\n"), NULL), session_server);
694                 break;
695         case MAILIMAP_ERROR_LIST:
696                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" LIST error\n"), NULL), session_server);
697                 break;
698         case MAILIMAP_ERROR_LOGIN:
699                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" LOGIN error\n"), NULL), session_server);
700                 break;
701         case MAILIMAP_ERROR_LSUB:
702                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" LSUB error\n"), NULL), session_server);
703                 break;
704         case MAILIMAP_ERROR_RENAME:
705                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" RENAME error\n"), NULL), session_server);
706                 break;
707         case MAILIMAP_ERROR_SEARCH:
708                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" SEARCH error\n"), NULL), session_server);
709                 break;
710         case MAILIMAP_ERROR_UID_SEARCH:
711                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" UID SEARCH error\n"), NULL), session_server);
712                 break;
713         case MAILIMAP_ERROR_SELECT:
714                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" SELECT error\n"), NULL), session_server);
715                 break;
716         case MAILIMAP_ERROR_STATUS:
717                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" STATUS error\n"), NULL), session_server);
718                 break;
719         case MAILIMAP_ERROR_STORE:
720                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" STORE error\n"), NULL), session_server);
721                 break;
722         case MAILIMAP_ERROR_UID_STORE:
723                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" UID STORE error\n"), NULL), session_server);
724                 break;
725         case MAILIMAP_ERROR_SUBSCRIBE:
726                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" SUBSCRIBE error\n"), NULL), session_server);
727                 break;
728         case MAILIMAP_ERROR_UNSUBSCRIBE:
729                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" UNSUBSCRIBE error\n"), NULL), session_server);
730                 break;
731         case MAILIMAP_ERROR_STARTTLS:
732                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" STARTTLS error\n"), NULL), session_server);
733                 break;
734         case MAILIMAP_ERROR_INVAL:
735                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" INVAL error\n"), NULL), session_server);
736                 break;
737         case MAILIMAP_ERROR_EXTENSION:
738                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" EXTENSION error\n"), NULL), session_server);
739                 break;
740         case MAILIMAP_ERROR_SASL:
741                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" SASL error\n"), NULL), session_server);
742                 break;
743 #ifdef USE_GNUTLS
744         case MAILIMAP_ERROR_SSL:
745                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" SSL error\n"), NULL), session_server);
746                 break;
747 #endif
748         default:
749                 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"),_(" Unknown error [%d]\n"), NULL),
750                         session_server, libetpan_errcode);
751                 break;
752         }
753
754         if (session && is_fatal(libetpan_errcode)) {
755                 imap_disc_session_destroy(IMAP_SESSION(session));
756         } else if (session && !is_fatal(libetpan_errcode)) {
757                 if (IMAP_SESSION(session)->busy)
758                         unlock_session(IMAP_SESSION(session));
759         }
760 }
761
762 static Folder *imap_folder_new(const gchar *name, const gchar *path)
763 {
764         Folder *folder;
765
766         folder = (Folder *)g_new0(IMAPFolder, 1);
767         folder->klass = &imap_class;
768         imap_folder_init(folder, name, path);
769
770         return folder;
771 }
772
773 static void imap_folder_destroy(Folder *folder)
774 {
775         while (imap_folder_get_refcnt(folder) > 0)
776                 gtk_main_iteration();
777
778         g_free(IMAP_FOLDER(folder)->search_charset);
779
780         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
781         imap_done(folder);
782 }
783
784 static void imap_folder_init(Folder *folder, const gchar *name,
785                              const gchar *path)
786 {
787         folder_remote_folder_init((Folder *)folder, name, path);
788         IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
789         IMAP_FOLDER(folder)->search_charset_supported = TRUE;
790         IMAP_FOLDER(folder)->search_charset = g_strdup(conv_get_locale_charset_str_no_utf8());
791 }
792
793 static FolderItem *imap_folder_item_new(Folder *folder)
794 {
795         IMAPFolderItem *item;
796         
797         item = g_new0(IMAPFolderItem, 1);
798         item->lastuid = 0;
799         item->uid_next = 0;
800         item->uid_list = NULL;
801
802         return (FolderItem *)item;
803 }
804
805 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
806 {
807         IMAPFolderItem *item = (IMAPFolderItem *)_item;
808
809         g_return_if_fail(item != NULL);
810         g_slist_free(item->uid_list);
811
812         g_free(_item);
813 }
814
815 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
816 {
817         IMAPFolderItem *item = (IMAPFolderItem *)node->data;
818         
819         item->lastuid = 0;
820         g_slist_free(item->uid_list);
821         item->uid_list = NULL;
822         
823         return FALSE;
824 }
825
826 static void imap_reset_uid_lists(Folder *folder)
827 {
828         if(folder->node == NULL)
829                 return;
830         
831         /* Destroy all uid lists and rest last uid */
832         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
833 }
834
835 static int imap_get_capabilities(IMAPSession *session)
836 {
837         struct mailimap_capability_data *capabilities = NULL;
838         clistiter *cur;
839         int result;
840
841         if (session->capability != NULL)
842                 return MAILIMAP_NO_ERROR;
843
844         result = imap_threaded_capability(session->folder, &capabilities);
845
846         if (result != MAILIMAP_NO_ERROR) {
847                 return result;
848         }
849
850         if (capabilities == NULL || capabilities->cap_list == NULL) {
851                 return MAILIMAP_NO_ERROR;
852         }
853
854         for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
855             cur = clist_next(cur)) {
856                 struct mailimap_capability * cap = 
857                         clist_content(cur);
858                 if (!cap || cap->cap_data.cap_name == NULL)
859                         continue;
860                 session->capability = g_slist_append
861                                 (session->capability,
862                                  g_strdup(cap->cap_data.cap_name));
863                 debug_print("got capa %s\n", cap->cap_data.cap_name);
864         }
865         mailimap_capability_data_free(capabilities);
866         return MAILIMAP_NO_ERROR;
867 }
868
869 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
870 {
871         GSList *cur;
872         for (cur = session->capability; cur; cur = cur->next) {
873                 if (!g_ascii_strcasecmp(cur->data, cap))
874                         return TRUE;
875         }
876         return FALSE;
877 }
878
879 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
880                       IMAPAuthType type)
881 {
882         gint ok = MAILIMAP_ERROR_LOGIN;
883         static time_t last_login_err = 0;
884         gchar *ext_info = "";
885         int r;
886         gchar *server = NULL;
887         if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
888                 imap_handle_error(SESSION(session), NULL, r);
889                 return r;
890         }
891         server = g_strdup(SESSION(session)->server);
892         switch(type) {
893         case IMAP_AUTH_ANON:
894                 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
895                 break;
896         case IMAP_AUTH_CRAM_MD5:
897                 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
898                 break;
899         case IMAP_AUTH_DIGEST_MD5:
900                 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
901                 break;
902         case IMAP_AUTH_SCRAM_SHA1:
903                 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
904                 break;
905         case IMAP_AUTH_LOGIN:
906                 ok = imap_cmd_login(session, user, pass, "LOGIN");
907                 break;
908         case IMAP_AUTH_GSSAPI:
909                 ok = imap_cmd_login(session, user, pass, "GSSAPI");
910                 break;
911         default:
912                 debug_print("capabilities:\n"
913                                 "\t ANONYMOUS %d\n"
914                                 "\t CRAM-MD5 %d\n"
915                                 "\t DIGEST-MD5 %d\n"
916                                 "\t SCRAM-SHA-1 %d\n"
917                                 "\t LOGIN %d\n"
918                                 "\t GSSAPI %d\n", 
919                         imap_has_capability(session, "ANONYMOUS"),
920                         imap_has_capability(session, "CRAM-MD5"),
921                         imap_has_capability(session, "DIGEST-MD5"),
922                         imap_has_capability(session, "SCRAM-SHA-1"),
923                         imap_has_capability(session, "LOGIN"),
924                         imap_has_capability(session, "GSSAPI"));
925                 if (imap_has_capability(session, "CRAM-MD5"))
926                         ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
927                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
928                         ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
929                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-1"))
930                         ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
931                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
932                         ok = imap_cmd_login(session, user, pass, "GSSAPI");
933                 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
934                         ok = imap_cmd_login(session, user, pass, "LOGIN");
935         }
936
937         if (ok == MAILIMAP_NO_ERROR)
938                 session->authenticated = TRUE;
939         else {
940                 if (type == IMAP_AUTH_CRAM_MD5) {
941                         ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
942                                      "compiled with SASL support and the "
943                                      "CRAM-MD5 SASL plugin is installed.");
944                 } 
945
946                 if (type == IMAP_AUTH_DIGEST_MD5) {
947                         ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
948                                      "compiled with SASL support and the "
949                                      "DIGEST-MD5 SASL plugin is installed.");
950                 } 
951
952                 if (type == IMAP_AUTH_SCRAM_SHA1) {
953                         ext_info = _("\n\nSCRAM-SHA-1 logins only work if libetpan has been "
954                                      "compiled with SASL support and the "
955                                      "SCRAM SASL plugin is installed.");
956                 }
957
958                 if (time(NULL) - last_login_err > 10) {
959                         if (!prefs_common.no_recv_err_panel) {
960                                 alertpanel_error_log(_("Connection to %s failed: "
961                                         "login refused.%s"),
962                                         server, ext_info);
963                         } else {
964                                 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
965                                         "login refused.%s\n"),
966                                         server, ext_info);
967                         }
968                 }
969                 last_login_err = time(NULL);
970         }
971         g_free(server);
972         return ok;
973 }
974
975 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
976 {
977         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
978         /* Check if this is the first try to establish a
979            connection, if yes we don't try to reconnect */
980         debug_print("reconnecting\n");
981         if (rfolder->session == NULL) {
982                 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
983                             folder->account->recv_server);
984                 SESSION(session)->sock = NULL;
985                 imap_safe_destroy(session);
986                 session = NULL;
987         } else {
988                 rfolder->session = NULL;
989                 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
990                             " disconnected. Reconnecting...\n"),
991                             folder->account->recv_server);
992                 statusbar_print_all(_("IMAP4 connection to %s has been"
993                             " disconnected. Reconnecting...\n"),
994                             folder->account->recv_server);
995                 SESSION(session)->state = SESSION_DISCONNECTED;
996                 SESSION(session)->sock = NULL;
997                 imap_safe_destroy(session);
998                 /* Clear folders session to make imap_session_get create
999                    a new session, because of rfolder->session == NULL
1000                    it will not try to reconnect again and so avoid an
1001                    endless loop */
1002                 debug_print("getting session...\n");
1003                 session = imap_session_get(folder);
1004                 rfolder->session = SESSION(session);
1005                 statusbar_pop_all();
1006         }
1007         return session;
1008 }
1009
1010 static IMAPSession *imap_session_get(Folder *folder)
1011 {
1012         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1013         IMAPSession *session = NULL;
1014         gint r = MAILIMAP_NO_ERROR;
1015
1016         g_return_val_if_fail(folder != NULL, NULL);
1017         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
1018         g_return_val_if_fail(folder->account != NULL, NULL);
1019         
1020         if (prefs_common.work_offline && 
1021             !inc_offline_should_override(FALSE,
1022                 _("Claws Mail needs network access in order "
1023                   "to access the IMAP server."))) {
1024                 return NULL;
1025         }
1026
1027         /* check for deferred destroy */
1028         if (rfolder->session != NULL) {
1029                 session = IMAP_SESSION(rfolder->session);
1030                 if (!session->busy && session->do_destroy) {
1031                         rfolder->session = NULL;
1032                         imap_safe_destroy(session);
1033                         session = NULL;
1034                 }
1035         }
1036
1037         /* Make sure we have a session */
1038         if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
1039                 session = IMAP_SESSION(rfolder->session);
1040         } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
1041                 imap_safe_destroy(IMAP_SESSION(rfolder->session));
1042                 rfolder->session = NULL;
1043                 goto new_conn;
1044         } else if (rfolder->connecting) {
1045                 debug_print("already connecting\n");
1046                 return NULL;
1047         } else {
1048 new_conn:
1049                 imap_reset_uid_lists(folder);
1050                 if (time(NULL) - rfolder->last_failure <= 2)
1051                         return NULL;
1052                 rfolder->connecting = TRUE;
1053                 session = imap_session_new(folder, folder->account);
1054         }
1055         if(session == NULL) {
1056                 rfolder->last_failure = time(NULL);
1057                 rfolder->connecting = FALSE;
1058                 return NULL;
1059         }
1060
1061         /* Make sure session is authenticated */
1062         if (!IMAP_SESSION(session)->authenticated)
1063                 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
1064         
1065         if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
1066                 rfolder->session = NULL;
1067                 if (!is_fatal(r)) {
1068                         imap_threaded_disconnect(session->folder);
1069                 }
1070                 SESSION(session)->state = SESSION_DISCONNECTED;
1071                 SESSION(session)->sock = NULL;
1072                 imap_safe_destroy(session);
1073                 rfolder->last_failure = time(NULL);
1074                 rfolder->connecting = FALSE;
1075                 return NULL;
1076         }
1077
1078         /* I think the point of this code is to avoid sending a
1079          * keepalive if we've used the session recently and therefore
1080          * think it's still alive.  Unfortunately, most of the code
1081          * does not yet check for errors on the socket, and so if the
1082          * connection drops we don't notice until the timeout expires.
1083          * A better solution than sending a NOOP every time would be
1084          * for every command to be prepared to retry until it is
1085          * successfully sent. -- mbp */
1086         if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1087                 /* verify that the session is still alive */
1088                 r = imap_cmd_noop(session);
1089
1090                 if (r != MAILIMAP_NO_ERROR) {
1091                         debug_print("disconnected!\n");
1092                         if (!is_fatal(r))
1093                                 session = imap_reconnect_if_possible(folder, session);
1094                         else {
1095                                 rfolder->session = NULL;
1096                                 rfolder->connecting = FALSE;
1097                                 SESSION(session)->state = SESSION_DISCONNECTED;
1098                                 SESSION(session)->sock = NULL;
1099                                 imap_safe_destroy(session);
1100                                 session = imap_session_get(folder);
1101                         }
1102                 }
1103                 if (session)
1104                         session->cancelled = FALSE;
1105         }
1106
1107         rfolder->session = SESSION(session);
1108         rfolder->connecting = FALSE;
1109
1110         return IMAP_SESSION(session);
1111 }
1112
1113 static IMAPSession *imap_session_new(Folder * folder,
1114                                      const PrefsAccount *account)
1115 {
1116         IMAPSession *session;
1117         gushort port;
1118         int r;
1119         int authenticated = FALSE;
1120         gchar *buf;
1121
1122 #ifdef USE_GNUTLS
1123         /* FIXME: IMAP over SSL only... */ 
1124         SSLType ssl_type;
1125
1126         port = account->set_imapport ? account->imapport
1127                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1128         ssl_type = account->ssl_imap;   
1129 #else
1130         if (account->ssl_imap != SSL_NONE) {
1131                 if (alertpanel_full(_("Insecure connection"),
1132                         _("This connection is configured to be secured "
1133                           "using SSL, but SSL is not available in this "
1134                           "build of Claws Mail. \n\n"
1135                           "Do you want to continue connecting to this "
1136                           "server? The communication would not be "
1137                           "secure."),
1138                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1139                           NULL, FALSE, NULL, ALERT_WARNING,
1140                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1141                         return NULL;
1142         }
1143         port = account->set_imapport ? account->imapport
1144                 : IMAP4_PORT;
1145 #endif
1146
1147         imap_init(folder);
1148         buf = g_strdup_printf(_("Account '%s': Connecting to IMAP4 server: %s:%d..."),
1149                                 folder->account->account_name, folder->account->recv_server,
1150                                 port);
1151         statuswindow_print_all("%s", buf);
1152         log_message(LOG_PROTOCOL, "%s\n", buf);
1153         g_free(buf);
1154
1155 #ifndef G_OS_WIN32
1156         if (account->set_tunnelcmd) {
1157                 r = imap_threaded_connect_cmd(folder,
1158                                               account->tunnelcmd,
1159                                               account->recv_server,
1160                                               port);
1161         }
1162         else 
1163 #endif
1164         {
1165 #ifdef USE_GNUTLS
1166                 if (ssl_type == SSL_TUNNEL) {
1167                         r = imap_threaded_connect_ssl(folder,
1168                                                       account->recv_server,
1169                                                       port);
1170                 }
1171                 else 
1172 #endif
1173                 {
1174                         r = imap_threaded_connect(folder,
1175                                                   account->recv_server,
1176                                                   port);
1177                 }
1178         }
1179         
1180         statuswindow_pop_all();
1181         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1182                 authenticated = TRUE;
1183         }
1184         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1185                 authenticated = FALSE;
1186         }
1187         else {
1188 #ifdef USE_GNUTLS
1189                 if (r == MAILIMAP_ERROR_SSL)
1190                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1191                 else
1192 #endif
1193                         imap_handle_error(NULL, account->recv_server, r);
1194
1195                 if(!prefs_common.no_recv_err_panel) {
1196                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1197                                          account->recv_server, port);
1198                 } else {
1199                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1200                                          account->recv_server, port);
1201                 } 
1202                 
1203                 return NULL;
1204         }
1205         
1206         session = g_new0(IMAPSession, 1);
1207         session_init(SESSION(session), account, FALSE);
1208         SESSION(session)->type             = SESSION_IMAP;
1209         SESSION(session)->server           = g_strdup(account->recv_server);
1210         SESSION(session)->port             = port;
1211         SESSION(session)->sock             = NULL;
1212         
1213         SESSION(session)->destroy          = imap_session_destroy;
1214
1215         session->capability = NULL;
1216         
1217         session->authenticated = authenticated;
1218         session->mbox = NULL;
1219         session->exists = 0;
1220         session->recent = 0;
1221         session->expunge = 0;
1222         session->cmd_count = 0;
1223         session->folder = folder;
1224         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1225
1226 #ifdef USE_GNUTLS
1227         if (account->ssl_imap == SSL_STARTTLS) {
1228                 gint ok;
1229
1230                 ok = imap_cmd_starttls(session);
1231                 if (ok != MAILIMAP_NO_ERROR) {
1232                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1233                         if (!is_fatal(ok)) {
1234                                 SESSION(session)->sock = NULL;
1235                                 imap_safe_destroy(session);
1236                         }
1237                         return NULL;
1238                 }
1239
1240                 imap_free_capabilities(session);
1241                 session->authenticated = FALSE;
1242                 session->uidplus = FALSE;
1243                 session->cmd_count = 1;
1244         }
1245 #endif
1246         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1247                     (session->authenticated) ? "pre" : "un");
1248         
1249         session_register_ping(SESSION(session), imap_ping);
1250
1251         return session;
1252 }
1253
1254 static gint imap_session_authenticate(IMAPSession *session, 
1255                                       PrefsAccount *account)
1256 {
1257         gchar *pass, *acc_pass;
1258         gboolean failed = FALSE;
1259         gint ok = MAILIMAP_NO_ERROR;
1260         g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1261
1262         if (password_get(account->userid, account->recv_server, "imap",
1263                          SESSION(session)->port, &pass)) {
1264                 Xstrdup_a(acc_pass, pass, {g_free(pass); return MAILIMAP_NO_ERROR;});
1265                 g_free(pass);
1266         } else {
1267                 acc_pass = password_decrypt(account->passwd, NULL);
1268         }
1269 try_again:
1270         pass = acc_pass;
1271         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1272                 gchar *tmp_pass;
1273                 tmp_pass = input_dialog_query_password_keep(account->recv_server, 
1274                                                             account->userid,
1275                                                             &(account->session_passwd));
1276                 if (!tmp_pass) {
1277                         memset(acc_pass, 0, strlen(acc_pass));
1278                         g_free(acc_pass);
1279                         return MAILIMAP_NO_ERROR;
1280                 }
1281                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1282                 g_free(tmp_pass);
1283         } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1284                 pass = "";
1285         }
1286         if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1287                 
1288                 if (!failed && !is_fatal(ok)) {
1289                         memset(acc_pass, 0, strlen(acc_pass));
1290                         g_free(acc_pass);
1291                         acc_pass = NULL;
1292                         failed = TRUE;
1293                         if (account->session_passwd != NULL) {
1294                                 g_free(account->session_passwd);
1295                                 account->session_passwd = NULL;
1296                         }
1297                         goto try_again;
1298                 } else {
1299                         if (prefs_common.no_recv_err_panel) {
1300                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1301                                 mainwindow_show_error();
1302                         } else
1303                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1304                 }
1305
1306                 g_free(acc_pass);
1307                 memset(acc_pass, 0, strlen(acc_pass));
1308                 return ok;
1309         } 
1310
1311         memset(acc_pass, 0, strlen(acc_pass));
1312         g_free(acc_pass);
1313         statuswindow_pop_all();
1314         session->authenticated = TRUE;
1315         return MAILIMAP_NO_ERROR;
1316 }
1317
1318 static void imap_session_destroy(Session *session)
1319 {
1320         if (session->state != SESSION_DISCONNECTED)
1321                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1322         
1323         imap_free_capabilities(IMAP_SESSION(session));
1324         g_free(IMAP_SESSION(session)->mbox);
1325 }
1326
1327 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1328 {
1329         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1330 }
1331
1332 static guint get_file_size_with_crs(const gchar *filename) 
1333 {
1334         FILE *fp = NULL;
1335         guint cnt = 0;
1336         gchar buf[4096];
1337         
1338         if (filename == NULL)
1339                 return -1;
1340         
1341         fp = g_fopen(filename, "rb");
1342         if (!fp)
1343                 return -1;
1344         
1345         while (fgets(buf, sizeof (buf), fp) != NULL) {
1346                 cnt += strlen(buf);
1347                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1348                         cnt++;
1349         }
1350         
1351         fclose(fp);
1352         return cnt;
1353 }
1354
1355 static gchar *imap_get_cached_filename(FolderItem *item, guint msgnum)
1356 {
1357         gchar *path, *filename;
1358
1359         cm_return_val_if_fail(item != NULL, NULL);
1360
1361         path = folder_item_get_path(item);
1362
1363         if (!is_dir_exist(path)) {
1364                 g_free(path);
1365                 return NULL;
1366         }
1367
1368         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
1369
1370         if (is_dir_exist(filename)) {
1371                 g_free(filename);
1372                 filename = g_strconcat(path, G_DIR_SEPARATOR_S, ".", itos(msgnum), NULL);
1373         }
1374         g_free(path);
1375
1376         return filename;
1377 }
1378
1379 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1380 {
1381         gchar *filename;
1382
1383         filename = imap_get_cached_filename(item, msginfo->msgnum);
1384
1385         cm_return_if_fail(filename != NULL);
1386
1387         if (is_file_exist(filename)) {
1388                 claws_unlink(filename);
1389         }
1390         g_free(filename);
1391 }
1392
1393 typedef struct _TagsData {
1394         gchar *str;
1395         GSList *msglist;
1396         IMAPFolderItem *item;
1397 } TagsData;
1398
1399 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1400 {
1401         IMAPSession *session;
1402         gint ok, can_create_tags;
1403         Folder *folder = NULL;
1404         TagsData *ht_data = NULL;
1405         GSList *cur;
1406
1407         g_return_if_fail(item != NULL);
1408         g_return_if_fail(msginfo != NULL);
1409
1410         folder = item->folder;
1411         debug_print("getting session...\n");
1412         session = imap_session_get(folder);
1413         
1414         if (!session) {
1415                 debug_print("can't get session\n");
1416                 return;
1417         }
1418
1419         ok = imap_select(session, IMAP_FOLDER(folder), item,
1420                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1421
1422         if (ok != MAILIMAP_NO_ERROR) {
1423                 return;
1424         }
1425
1426         
1427         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1428                 return;
1429         
1430         if (IMAP_FOLDER_ITEM(item)->batching) {
1431                 /* instead of performing an UID STORE command for each message change,
1432                  * as a lot of them can change "together", we just fill in hashtables
1433                  * and defer the treatment so that we're able to send only one
1434                  * command.
1435                  */
1436                 debug_print("IMAP batch mode on, deferring tags change\n");
1437                 for (cur = tags_set; cur; cur = cur->next) {
1438                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1439                         if (cur_tag) {
1440                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1441                                         GINT_TO_POINTER(cur_tag));
1442                                 if (ht_data == NULL) {
1443                                         ht_data = g_new0(TagsData, 1);
1444                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1445                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1446                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1447                                                 GINT_TO_POINTER(cur_tag), ht_data);
1448                                 }
1449                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1450                         } 
1451                 }
1452                 for (cur = tags_unset; cur; cur = cur->next) {
1453                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1454                         if (cur_tag) {
1455                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1456                                         GINT_TO_POINTER(cur_tag));
1457                                 if (ht_data == NULL) {
1458                                         ht_data = g_new0(TagsData, 1);
1459                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1460                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1461                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1462                                                 GINT_TO_POINTER(cur_tag), ht_data);
1463                                 }
1464                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1465                         }
1466                 }
1467         } else {
1468                 GSList *list_set = NULL;
1469                 GSList *list_unset = NULL;
1470                 GSList numlist;
1471                 
1472                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1473                 numlist.next = NULL;
1474         
1475                 debug_print("IMAP changing tags NOW\n");
1476                 for (cur = tags_set; cur; cur = cur->next) {
1477                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1478                         const gchar *str = tags_get_tag(cur_tag);
1479                         if (IS_NOT_RESERVED_TAG(str))
1480                                 list_set = g_slist_prepend(list_set, g_strdup(str));
1481                 }
1482                 if (list_set) {
1483                         ok = imap_set_message_flags(session, 
1484                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1485                         slist_free_strings_full(list_set);
1486                         if (ok != MAILIMAP_NO_ERROR) {
1487                                 return;
1488                         }
1489                 }
1490
1491                 for (cur = tags_unset; cur; cur = cur->next) {
1492                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1493                         const gchar *str = tags_get_tag(cur_tag);
1494                         if (IS_NOT_RESERVED_TAG(str))
1495                                 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1496                 }
1497                 if (list_unset) {
1498                         ok = imap_set_message_flags(session, 
1499                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1500                         slist_free_strings_full(list_unset);
1501                         if (ok != MAILIMAP_NO_ERROR) {
1502                                 return;
1503                         }
1504                 }
1505         }
1506 }
1507
1508 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1509                                   gboolean headers, gboolean body)
1510 {
1511         gchar *path, *filename;
1512         IMAPSession *session;
1513         gint ok;
1514
1515         g_return_val_if_fail(folder != NULL, NULL);
1516         g_return_val_if_fail(item != NULL, NULL);
1517
1518         if (uid == 0)
1519                 return NULL;
1520
1521         path = folder_item_get_path(item);
1522         if (!is_dir_exist(path)) {
1523                 if(is_file_exist(path))
1524                         claws_unlink(path);
1525                 make_dir_hier(path);
1526         }
1527         g_free(path);
1528
1529         filename = imap_get_cached_filename(item, uid);
1530         debug_print("trying to fetch cached %s\n", filename);
1531
1532         if (is_file_exist(filename)) {
1533                 /* see whether the local file represents the whole message
1534                  * or not. As the IMAP server reports size with \r chars,
1535                  * we have to update the local file (UNIX \n only) size */
1536                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1537                 guint have_size = -1;
1538
1539                 if (cached)
1540                         debug_print("message %d has been already %scached.\n", uid,
1541                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1542                 
1543                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1544                         have_size = get_file_size_with_crs(filename);
1545                         if (cached && (cached->size <= have_size || !body)) {
1546                                 ok = file_strip_crs(filename);
1547                                 if (ok == 0 && cached && cached->size <= have_size) {
1548                                         /* we have it all and stripped */
1549                                         debug_print("...fully cached in fact (%u/%zd); setting flag.\n",
1550                                                         have_size, cached->size);
1551                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1552                                 }
1553                                 procmsg_msginfo_free(&cached);
1554                                 return filename;
1555                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1556                                 debug_print("message not cached and file recent, considering file complete\n");
1557                                 ok = file_strip_crs(filename);
1558                                 if (ok == 0)
1559                                         return filename;
1560                         } else {
1561                                 procmsg_msginfo_free(&cached);
1562                         }
1563                 }
1564                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1565                         procmsg_msginfo_free(&cached);
1566                         return filename;
1567                 }
1568         } else {
1569                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1570                 if (cached) {
1571                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1572                         procmsg_msginfo_free(&cached);
1573                 }
1574         }
1575
1576         debug_print("getting session...\n");
1577         session = imap_session_get(folder);
1578         
1579         if (!session) {
1580                 g_free(filename);
1581                 return NULL;
1582         }
1583         session_set_access_time(SESSION(session));
1584         lock_session(session); /* unlocked later in the function */
1585
1586         debug_print("IMAP fetching messages\n");
1587         ok = imap_select(session, IMAP_FOLDER(folder), item,
1588                          NULL, NULL, NULL, NULL, NULL, FALSE);
1589         if (ok != MAILIMAP_NO_ERROR) {
1590                 g_warning("can't select mailbox %s", item->path);
1591                 g_free(filename);
1592                 return NULL;
1593         }
1594
1595         session_set_access_time(SESSION(session));
1596
1597         debug_print("getting message %d...\n", uid);
1598         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1599
1600         if (ok != MAILIMAP_NO_ERROR) {
1601                 g_warning("can't fetch message %d", uid);
1602                 g_free(filename);
1603                 return NULL;
1604         }
1605
1606         session_set_access_time(SESSION(session));
1607         unlock_session(session);
1608
1609         ok = file_strip_crs(filename);
1610
1611         if (ok == 0 && headers && body) {
1612                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1613                 if (cached) {
1614                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1615                         procmsg_msginfo_free(&cached);
1616                 }
1617         } else if (ok == -1) {
1618                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1619                 if (cached) {
1620                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1621                         procmsg_msginfo_free(&cached);
1622                 }
1623         }
1624         return filename;
1625 }
1626
1627 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1628 {
1629         gchar *filename;
1630         guint size = 0;
1631         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1632         
1633         if (!cached)
1634                 return FALSE;
1635
1636         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1637                 procmsg_msginfo_free(&cached);
1638                 return TRUE;
1639         }
1640
1641         filename = imap_get_cached_filename(item, uid);
1642
1643         if (is_file_exist(filename)) {
1644                 if (cached && cached->total_size == cached->size) {
1645                         /* fast path */
1646                         g_free(filename);
1647                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1648                         return TRUE;
1649                 }
1650                 size = get_file_size_with_crs(filename);
1651         }
1652         g_free(filename);
1653         debug_print("msg %d cached, has size %d, full should be %zd.\n", uid, size, cached->size);
1654         if (cached && size >= cached->size) {
1655                 cached->total_size = cached->size;
1656                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1657                 procmsg_msginfo_free(&cached);
1658                 return TRUE;
1659         }
1660         if (cached)
1661                 procmsg_msginfo_free(&cached);
1662         return FALSE;   
1663 }
1664
1665 void imap_cache_msg(FolderItem *item, gint msgnum)
1666 {
1667         Folder *folder = NULL;
1668         
1669         if (!item)
1670                 return;
1671         folder = item->folder;
1672         
1673         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1674                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1675                 debug_print("fetched %s\n", tmp);
1676                 g_free(tmp);
1677         }
1678 }
1679
1680 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1681                          const gchar *file, MsgFlags *flags)
1682 {
1683         gint ret;
1684         GSList file_list;
1685         MsgFileInfo fileinfo;
1686
1687         g_return_val_if_fail(file != NULL, -1);
1688
1689         fileinfo.msginfo = NULL;
1690         fileinfo.file = (gchar *)file;
1691         fileinfo.flags = flags;
1692         file_list.data = &fileinfo;
1693         file_list.next = NULL;
1694
1695         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1696         return ret;
1697 }
1698
1699 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1700                    GHashTable *relation)
1701 {
1702         gchar *destdir;
1703         IMAPSession *session;
1704         guint32 last_uid = 0;
1705         GSList *cur;
1706         MsgFileInfo *fileinfo;
1707         gint ok = MAILIMAP_NO_ERROR;
1708         gint curnum = 0, total = 0;
1709         gboolean missing_uids = FALSE;
1710
1711         g_return_val_if_fail(folder != NULL, -1);
1712         g_return_val_if_fail(dest != NULL, -1);
1713         g_return_val_if_fail(file_list != NULL, -1);
1714         
1715         debug_print("getting session...\n");
1716         session = imap_session_get(folder);
1717         if (!session) {
1718                 return -1;
1719         }
1720         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1721         if (is_fatal(ok)) {
1722                 g_free(destdir);
1723                 return -1;
1724         }
1725         statusbar_print_all(_("Adding messages..."));
1726         total = g_slist_length(file_list);
1727         for (cur = file_list; cur != NULL; cur = cur->next) {
1728                 IMAPFlags iflags = 0;
1729                 guint32 new_uid = 0;
1730                 gchar *real_file = NULL;
1731                 fileinfo = (MsgFileInfo *)cur->data;
1732
1733                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1734                 curnum++;
1735
1736                 if (fileinfo->flags) {
1737                         if (MSG_IS_MARKED(*fileinfo->flags))
1738                                 iflags |= IMAP_FLAG_FLAGGED;
1739                         if (MSG_IS_REPLIED(*fileinfo->flags))
1740                                 iflags |= IMAP_FLAG_ANSWERED;
1741                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1742                                 iflags |= IMAP_FLAG_FORWARDED;
1743                         if (MSG_IS_SPAM(*fileinfo->flags))
1744                                 iflags |= IMAP_FLAG_SPAM;
1745                         else
1746                                 iflags |= IMAP_FLAG_HAM;
1747                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1748                                 iflags |= IMAP_FLAG_SEEN;
1749                         
1750                 }
1751                 
1752                 if (real_file == NULL)
1753                         real_file = g_strdup(fileinfo->file);
1754                 
1755                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1756                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1757                     folder_has_parent_of_type(dest, F_DRAFT) ||
1758                     folder_has_parent_of_type(dest, F_TRASH))
1759                         iflags |= IMAP_FLAG_SEEN;
1760
1761                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1762                                      &new_uid);
1763
1764                 if (ok != MAILIMAP_NO_ERROR) {
1765                         g_warning("can't append message %s", real_file);
1766                         g_free(real_file);
1767                         g_free(destdir);
1768                         statusbar_progress_all(0,0,0);
1769                         statusbar_pop_all();
1770                         return -1;
1771                 } else {
1772                         debug_print("appended new message as %d\n", new_uid);
1773                         /* put the local file in the imapcache, so that we don't
1774                          * have to fetch it back later. */
1775                         
1776                         if (new_uid == 0) {
1777                                 missing_uids = TRUE;
1778                                 debug_print("Missing UID (0)\n");
1779                         }
1780                         if (new_uid > 0) {
1781                                 gchar *cache_path = folder_item_get_path(dest);
1782                                 if (!is_dir_exist(cache_path))
1783                                         make_dir_hier(cache_path);
1784                                 if (is_dir_exist(cache_path)) {
1785                                         gchar *cache_file = g_strconcat(
1786                                                 cache_path, G_DIR_SEPARATOR_S, 
1787                                                 itos(new_uid), NULL);
1788                                         copy_file(real_file, cache_file, TRUE);
1789                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1790                                         g_free(cache_file);
1791                                 }
1792                                 g_free(cache_path);
1793                         }
1794                 }
1795
1796                 if (relation != NULL)
1797                         g_hash_table_insert(relation, fileinfo->msginfo != NULL ? 
1798                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1799                                           GINT_TO_POINTER(new_uid));
1800                 if (last_uid < new_uid) {
1801                         last_uid = new_uid;
1802                 }
1803
1804                 g_free(real_file);
1805         }
1806         
1807         statusbar_progress_all(0,0,0);
1808         statusbar_pop_all();
1809         
1810         
1811         g_free(destdir);
1812
1813         imap_scan_required(folder, dest);
1814
1815         session = imap_session_get(folder);
1816         if (!session) {
1817                 return -1;
1818         }
1819         if (missing_uids) {
1820                 gint a;
1821                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1822                          &a, NULL, NULL, NULL, NULL, FALSE);
1823         }
1824         return last_uid;
1825 }
1826
1827 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1828 {
1829         GSList *result = NULL;
1830         clistiter *list;
1831         guint32 start, end, t;
1832         GSList *cur;
1833
1834         if (!set || !set->set_list)
1835                 return NULL;
1836
1837         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1838                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1839                 start = item->set_first;
1840                 end = item->set_last;
1841                 if (start <= end) {
1842                         for (t = start; t <= end; t++) {
1843                                 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1844                         }
1845                 }
1846         }
1847         result = g_slist_reverse(result);
1848         if (debug_get_mode()) {
1849                 debug_print("flat imap set: ");
1850                 for (cur = result; cur; cur = cur->next) {
1851                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1852                 }
1853                 debug_print("\n");
1854         }
1855         
1856         return result;
1857 }
1858 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1859                               MsgInfoList *msglist, GHashTable *relation,
1860                               gboolean same_dest_ok)
1861 {
1862         FolderItem *src;
1863         gchar *destdir;
1864         GSList *seq_list, *cur;
1865         MsgInfo *msginfo;
1866         IMAPSession *session;
1867         gint ok = MAILIMAP_NO_ERROR;
1868         GHashTable *uid_hash;
1869         gint last_num = 0;
1870
1871         g_return_val_if_fail(folder != NULL, -1);
1872         g_return_val_if_fail(dest != NULL, -1);
1873         g_return_val_if_fail(msglist != NULL, -1);
1874         
1875         debug_print("getting session...\n");
1876         session = imap_session_get(folder);
1877         
1878         if (!session) {
1879                 return -1;
1880         }
1881
1882         msginfo = (MsgInfo *)msglist->data;
1883         src = msginfo->folder;
1884         if (!same_dest_ok && src == dest) {
1885                 g_warning("the src folder is identical to the dest.");
1886                 return -1;
1887         }
1888
1889         if (src->folder != dest->folder) {
1890                 GSList *infolist = NULL, *cur;
1891                 int res = -1;
1892                 for (cur = msglist; cur; cur = cur->next) {
1893                         msginfo = (MsgInfo *)cur->data;
1894                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1895                         fileinfo->file = procmsg_get_message_file(msginfo);
1896                         fileinfo->flags = &(msginfo->flags);
1897                         infolist = g_slist_prepend(infolist, fileinfo);
1898                 }
1899                 infolist = g_slist_reverse(infolist);
1900                 res = folder_item_add_msgs(dest, infolist, FALSE);
1901                 for (cur = infolist; cur; cur = cur->next) {
1902                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1903                         g_free(info->file);
1904                         g_free(info);
1905                 }
1906                 g_slist_free(infolist);
1907                 return res;
1908         } 
1909
1910         lock_session(session); /* unlocked later in the function */
1911
1912         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1913                          NULL, NULL, NULL, NULL, NULL, FALSE);
1914         if (ok != MAILIMAP_NO_ERROR) {
1915                 return ok;
1916         }
1917
1918         unlock_session(session);
1919
1920         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1921
1922         if (is_fatal(ok)) {
1923                 g_free(destdir);
1924                 return ok;
1925         }
1926
1927         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1928         uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
1929         
1930         statusbar_print_all(_("Copying messages..."));
1931         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1932                 struct mailimap_set * seq_set;
1933                 struct mailimap_set * source = NULL;
1934                 struct mailimap_set * dest = NULL;
1935                 seq_set = cur->data;
1936
1937                 debug_print("Copying messages from %s to %s ...\n",
1938                             src->path, destdir);
1939
1940                 lock_session(session); /* unlocked later in the function */
1941                 ok = imap_cmd_copy(session, seq_set, destdir,
1942                         &source, &dest);
1943                 
1944                 if (is_fatal(ok)) {
1945                         session = NULL;
1946                 }
1947
1948                 if (ok == MAILIMAP_NO_ERROR) {
1949                         unlock_session(session);
1950                         if (relation && source && dest) {
1951                                 GSList *s_list = flatten_mailimap_set(source);
1952                                 GSList *d_list = flatten_mailimap_set(dest);
1953                                 GSList *s_cur, *d_cur;
1954                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1955
1956                                         for (s_cur = s_list, d_cur = d_list; 
1957                                              s_cur && d_cur; 
1958                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1959                                                 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
1960                                         }
1961
1962                                 } else {
1963                                         debug_print("hhhmm, source list length != dest list length.\n");
1964                                 }
1965                                 g_slist_free(s_list);
1966                                 g_slist_free(d_list);
1967                         }
1968                 }
1969
1970
1971                 if (source)
1972                         mailimap_set_free(source);
1973                 if (dest)
1974                         mailimap_set_free(dest);
1975
1976                 if (ok != MAILIMAP_NO_ERROR) {
1977                         g_hash_table_destroy(uid_hash);
1978                         imap_lep_set_free(seq_list);
1979                         statusbar_pop_all();
1980                         return -1;
1981                 }
1982         }
1983
1984         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1985                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1986                 gpointer hashval;
1987
1988                 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
1989                 
1990                 if (hashval != NULL) {
1991                         gint num = GPOINTER_TO_INT(hashval);
1992                         g_hash_table_insert(relation, msginfo,
1993                                           GINT_TO_POINTER(num));
1994                         if (num > last_num)
1995                                 last_num = num;
1996                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1997                         /* put the local file in the imapcache, so that we don't
1998                          * have to fetch it back later. */
1999                         if (num > 0) {
2000                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
2001                                 gchar *real_file = g_strconcat(
2002                                         cache_path, G_DIR_SEPARATOR_S, 
2003                                         itos(msginfo->msgnum), NULL);
2004                                 gchar *cache_file = NULL;
2005                                 g_free(cache_path);
2006                                 cache_path = folder_item_get_path(dest);
2007                                 cache_file = g_strconcat(
2008                                         cache_path, G_DIR_SEPARATOR_S, 
2009                                         itos(num), NULL);
2010                                 if (!is_dir_exist(cache_path))
2011                                         make_dir_hier(cache_path);
2012                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
2013                                         if (copy_file(real_file, cache_file, TRUE) < 0)
2014                                                 debug_print("couldn't cache to %s: %s\n", cache_file,
2015                                                             strerror(errno));
2016                                         else
2017                                                 debug_print("copied to cache: %s\n", cache_file);
2018                                 }
2019                                 g_free(real_file);
2020                                 g_free(cache_file);
2021                                 g_free(cache_path);
2022                         }
2023                 } else
2024                         g_hash_table_insert(relation, msginfo,
2025                                           GINT_TO_POINTER(0));
2026         }
2027         statusbar_pop_all();
2028
2029         g_hash_table_destroy(uid_hash);
2030         imap_lep_set_free(seq_list);
2031
2032         g_free(destdir);
2033         
2034         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
2035         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
2036         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
2037         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
2038
2039         imap_scan_required(folder, dest);
2040         if (ok == MAILIMAP_NO_ERROR)
2041                 return last_num;
2042         else
2043                 return -1;
2044 }
2045
2046 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
2047 {
2048         GSList msglist;
2049
2050         g_return_val_if_fail(msginfo != NULL, -1);
2051
2052         msglist.data = msginfo;
2053         msglist.next = NULL;
2054
2055         return imap_copy_msgs(folder, dest, &msglist, NULL);
2056 }
2057
2058 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
2059                     MsgInfoList *msglist, GHashTable *relation)
2060 {
2061         MsgInfo *msginfo;
2062         gint ret;
2063
2064         g_return_val_if_fail(folder != NULL, -1);
2065         g_return_val_if_fail(dest != NULL, -1);
2066         g_return_val_if_fail(msglist != NULL, -1);
2067
2068         msginfo = (MsgInfo *)msglist->data;
2069         g_return_val_if_fail(msginfo->folder != NULL, -1);
2070
2071         ret = imap_do_copy_msgs(folder, dest, msglist, relation, FALSE);
2072         return ret;
2073 }
2074
2075 static gboolean imap_matcher_type_is_local(gint matchertype)
2076 {
2077         switch (matchertype) {
2078         case MATCHCRITERIA_FROM:
2079         case MATCHCRITERIA_TO:
2080         case MATCHCRITERIA_CC:
2081         case MATCHCRITERIA_TO_OR_CC:
2082         case MATCHCRITERIA_SUBJECT:
2083         case MATCHCRITERIA_REFERENCES:
2084         case MATCHCRITERIA_MESSAGEID:
2085         case MATCHCRITERIA_INREPLYTO:
2086         case MATCHCRITERIA_AGE_GREATER:
2087         case MATCHCRITERIA_AGE_LOWER:
2088         case MATCHCRITERIA_FORWARDED:
2089         case MATCHCRITERIA_SPAM:
2090         case MATCHCRITERIA_UNREAD:
2091         case MATCHCRITERIA_NEW:
2092         case MATCHCRITERIA_MARKED:
2093         case MATCHCRITERIA_REPLIED:
2094         case MATCHCRITERIA_DELETED:
2095         case MATCHCRITERIA_SIZE_GREATER:
2096         case MATCHCRITERIA_SIZE_SMALLER:
2097         case MATCHCRITERIA_SIZE_EQUAL:
2098                 return TRUE;
2099         }
2100         return FALSE;
2101 }
2102
2103 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2104 {
2105         if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2106                 IMAPSearchKey* result = NULL;
2107                 gboolean invert = FALSE;
2108                 gint matchertype = match->criteria;
2109
2110                 if (is_all) {
2111                         *is_all = FALSE;
2112                 }
2113
2114                 switch (matchertype) {
2115                 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2116                 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2117                 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2118                 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2119                 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2120                 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2121                 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2122                 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2123                 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2124                 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2125                 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2126                 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2127                 case MATCHCRITERIA_NOT_HEADERS_CONT: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_CONT; break;
2128                 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2129                 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2130                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2131                 case MATCHCRITERIA_NOT_MESSAGEID: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGEID; break;
2132                 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2133                 }
2134
2135                 /* 
2136                  * this aborts conversion even for predicates understood by the following code.
2137                  * while that might seem wasteful, claws local search for information listed below
2138                  * has proven faster than IMAP search plus network roundtrips. once this changes,
2139                  * consider removing these exceptions.
2140                  */
2141                 if (imap_matcher_type_is_local(matchertype))
2142                         return NULL;
2143
2144                 /* the Message-ID header is also cached */
2145                 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2146                         return NULL;
2147                 }
2148
2149                 switch (matchertype) {
2150                 case MATCHCRITERIA_FORWARDED:
2151                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2152                         break;
2153
2154                 case MATCHCRITERIA_SPAM:
2155                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2156                         break;
2157
2158                 case MATCHCRITERIA_MESSAGEID:
2159                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "Message-ID", match->expr, 0);
2160                         break;
2161
2162                 case MATCHCRITERIA_INREPLYTO:
2163                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2164                         break;
2165
2166                 case MATCHCRITERIA_REFERENCES:
2167                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2168                         break;
2169
2170                 case MATCHCRITERIA_TO_OR_CC:
2171                         result = imap_search_or(
2172                                         imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2173                                         imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2174                                         );
2175                         break;
2176
2177                 case MATCHCRITERIA_HEADERS_PART:
2178                 case MATCHCRITERIA_HEADERS_CONT:
2179                         result = imap_search_and(
2180                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2181                                         imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2182                                         );
2183                         break;
2184
2185                 case MATCHCRITERIA_SIZE_EQUAL:
2186                         result = imap_search_and(
2187                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2188                                         imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2189                                         );
2190                         break;
2191
2192                 case MATCHCRITERIA_NOT_UNREAD:
2193                         result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2194                         break;
2195
2196                 case MATCHCRITERIA_UNREAD:
2197                         result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2198                         break;
2199
2200                 case MATCHCRITERIA_NEW:
2201                         result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2202                         break;
2203
2204                 case MATCHCRITERIA_MARKED:
2205                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2206                         break;
2207
2208                 case MATCHCRITERIA_DELETED:
2209                         result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2210                         break;
2211
2212                 case MATCHCRITERIA_REPLIED:
2213                         result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2214                         break;
2215
2216                 case MATCHCRITERIA_TAG:
2217                         {
2218                                 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2219                                 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2220                                 g_free(tmp);
2221                         }
2222                         break;
2223
2224                 case MATCHCRITERIA_SUBJECT:
2225                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2226                         break;
2227
2228                 case MATCHCRITERIA_FROM:
2229                         result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2230                         break;
2231
2232                 case MATCHCRITERIA_TO:
2233                         result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2234                         break;
2235
2236                 case MATCHCRITERIA_CC:
2237                         result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2238                         break;
2239
2240                 case MATCHCRITERIA_AGE_GREATER:
2241                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2242                         break;
2243
2244                 case MATCHCRITERIA_AGE_LOWER:
2245                         result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2246                         break;
2247
2248                 case MATCHCRITERIA_BODY_PART:
2249                         result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2250                         break;
2251
2252                 case MATCHCRITERIA_MESSAGE:
2253                         result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2254                         break;
2255
2256                 case MATCHCRITERIA_HEADER:
2257                         result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2258                         break;
2259
2260                 case MATCHCRITERIA_SIZE_GREATER:
2261                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2262                         break;
2263
2264                 case MATCHCRITERIA_SIZE_SMALLER:
2265                         result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2266                         break;
2267
2268                 default:
2269                         result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2270                         if (is_all) {
2271                                 *is_all = TRUE;
2272                         }
2273                         break;
2274                 }
2275
2276                 if (invert) {
2277                         result = imap_search_not(result);
2278                         if (is_all && *is_all) {
2279                                 *is_all = FALSE;
2280                         }
2281                 }
2282
2283                 return result;
2284         }
2285
2286         return NULL;
2287 }
2288
2289 static void imap_change_search_charset(IMAPFolder *folder)
2290 {
2291         /* If server supports charset in searches, but the last used one failed,
2292          * changed to the next preferred charset. If none are still available,
2293          * disable charset searches.
2294          * Charsets are tried in the following order: 
2295          * UTF-8, locale's charset, UTF-7.
2296          */
2297
2298         if (folder->search_charset_supported) {
2299                 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2300                         folder->search_charset = "UTF-8";
2301                 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2302                         folder->search_charset = "UTF-7";
2303                 else {
2304                         folder->search_charset = NULL;
2305                         folder->search_charset_supported = FALSE;
2306                 }
2307         }
2308 }
2309
2310 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2311                                                   MatcherProp *utf8_prop,
2312                                                   gchar **charset)
2313 {
2314         /* If the match is going to be done locally, or the criteria is on
2315          * tag (special-cased to modified-UTF-7), or the expression searched
2316          * is ASCII, don't bother converting.
2317          */
2318         if (imap_matcher_type_is_local(utf8_prop->criteria)
2319          || utf8_prop->criteria == MATCHCRITERIA_TAG
2320          || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2321          || utf8_prop->expr == NULL
2322          || is_ascii_str(utf8_prop->expr))
2323                 return matcherprop_new(utf8_prop->criteria,
2324                                utf8_prop->header,
2325                                utf8_prop->matchtype,
2326                                utf8_prop->expr,
2327                                utf8_prop->value);
2328         else {
2329                 gchar *conv_expr = NULL;
2330
2331                 /* If the search is server-side and the server doesn't support
2332                  * searching with the charsets we handle, bail out.
2333                  */
2334                 if (folder->search_charset_supported == FALSE)
2335                         return NULL;
2336
2337                 /* Else, convert. */
2338                 if (*charset == NULL)
2339                         *charset = g_strdup(folder->search_charset);
2340
2341                 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2342
2343                 if (conv_expr == NULL)
2344                         conv_expr = g_strdup(utf8_prop->expr);
2345
2346                 return matcherprop_new(utf8_prop->criteria,
2347                                utf8_prop->header,
2348                                utf8_prop->matchtype,
2349                                conv_expr,
2350                                utf8_prop->value);
2351         }
2352 }
2353
2354 static gint     search_msgs             (Folder                 *folder,
2355                                          FolderItem             *container,
2356                                          MsgNumberList          **msgs,
2357                                          gboolean               *on_server,
2358                                          MatcherList            *predicate,
2359                                          SearchProgressNotify   progress_cb,
2360                                          gpointer               progress_data)
2361 {
2362         IMAPSearchKey* key = NULL;
2363         GSList* cur;
2364         int result = -1;
2365         clist* uidlist = NULL;
2366         gboolean server_filtering_useless = FALSE;
2367         IMAPSession *session;
2368         gchar *charset_to_use = NULL;
2369
2370         if (on_server == NULL || !*on_server) {
2371                 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2372                                 predicate, progress_cb, progress_data);
2373         }
2374
2375         for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2376                 IMAPSearchKey* matcherPart = NULL;
2377                 MatcherProp* prop = (MatcherProp*) cur->data;
2378                 gboolean is_all;
2379                 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2380
2381                 if (imap_prop == NULL) {
2382                         /* Couldn't convert matcherprop to IMAP - probably not ascii
2383                          * and server doesn't support the charsets we do. */
2384                          return -1;
2385                 }
2386
2387                 matcherPart = search_make_key(imap_prop, &is_all);
2388
2389                 matcherprop_free(imap_prop);
2390
2391                 if (on_server) {
2392                         *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2393                 }
2394
2395                 if (matcherPart) {
2396                         if (key == NULL) {
2397                                 key = matcherPart;
2398                                 server_filtering_useless = is_all;
2399                         } else if (predicate->bool_and) {
2400                                 key = imap_search_and(key, matcherPart);
2401                                 server_filtering_useless &= is_all;
2402                         } else {
2403                                 key = imap_search_or(key, matcherPart);
2404                                 server_filtering_useless |= is_all;
2405                         }
2406                 }
2407         }
2408
2409         if (server_filtering_useless) {
2410                 imap_search_free(key);
2411                 key = NULL;
2412         }
2413
2414         if (key == NULL && progress_cb != NULL) {
2415                 GSList* cur;
2416                 GSList* list;
2417                 int count = 0;
2418
2419                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2420                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2421
2422                 list = folder_item_get_msg_list(container);
2423                 for (cur = list; cur != NULL; cur = cur->next) {
2424                         *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2425                         count++;
2426                 }
2427                 procmsg_msg_list_free(list);
2428
2429                 *msgs = g_slist_reverse(*msgs);
2430
2431                 return count;
2432         }
2433
2434         session = imap_session_get(folder);
2435         if (!session) {
2436                 return -1;
2437         }
2438         result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2439                          NULL, NULL, NULL, NULL, NULL, TRUE);
2440         if (result != MAILIMAP_NO_ERROR)
2441                 return -1;
2442
2443         if (progress_cb)
2444                 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2445         result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2446         if (progress_cb)
2447                 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2448
2449         if (result == MAILIMAP_NO_ERROR) {
2450                 gint result = 0;
2451
2452                 *msgs = imap_uid_list_from_lep(uidlist, &result);
2453
2454                 mailimap_search_result_free(uidlist);
2455
2456                 if (charset_to_use != NULL)
2457                         g_free(charset_to_use);
2458
2459                 return result;
2460         } else if (charset_to_use != NULL) {
2461                 /* If search failed and was on an 8-bit string, try the next
2462                  * available charset to search if there still are some.
2463                  */
2464                 g_free(charset_to_use);
2465                 
2466                 imap_change_search_charset(IMAP_FOLDER(folder));
2467                 if (IMAP_FOLDER(folder)->search_charset_supported)
2468                         return search_msgs(folder, container, msgs, on_server, predicate,
2469                                    progress_cb, progress_data);
2470                 else
2471                         return -1;
2472         } else {
2473                 return -1;
2474         }
2475 }
2476
2477
2478 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
2479                                 MsgInfoList *msglist, GHashTable *relation)
2480 {
2481         gchar *destdir, *dir;
2482         GSList *numlist = NULL, *cur;
2483         MsgInfo *msginfo;
2484         IMAPSession *session;
2485         gint ok = MAILIMAP_NO_ERROR;
2486         
2487         g_return_val_if_fail(folder != NULL, -1);
2488         g_return_val_if_fail(dest != NULL, -1);
2489         g_return_val_if_fail(msglist != NULL, -1);
2490
2491         debug_print("getting session...\n");
2492         session = imap_session_get(folder);
2493         if (!session) {
2494                 return -1;
2495         }
2496
2497         lock_session(session); /* unlocked later in the function */
2498
2499         msginfo = (MsgInfo *)msglist->data;
2500
2501         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2502                          NULL, NULL, NULL, NULL, NULL, FALSE);
2503         if (ok != MAILIMAP_NO_ERROR) {
2504                 return ok;
2505         }
2506
2507         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2508         if (is_fatal(ok)) {
2509                 g_free(destdir);
2510                 return ok;
2511         }
2512         for (cur = msglist; cur; cur = cur->next) {
2513                 msginfo = (MsgInfo *)cur->data;
2514                 if (!MSG_IS_DELETED(msginfo->flags))
2515                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2516         }
2517         numlist = g_slist_reverse(numlist);
2518
2519         if (numlist != NULL) {
2520                 ok = imap_set_message_flags
2521                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2522                 if (ok != MAILIMAP_NO_ERROR) {
2523                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2524                         g_free(destdir);
2525                         return ok;
2526                 }
2527         } /* else we just need to expunge */
2528         ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
2529         if (ok != MAILIMAP_NO_ERROR) {
2530                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2531                 g_free(destdir);
2532                 return ok;
2533         }
2534         
2535         session->folder_content_changed = TRUE;
2536         unlock_session(session);
2537
2538         dir = folder_item_get_path(msginfo->folder);
2539         if (is_dir_exist(dir)) {
2540                 for (cur = msglist; cur; cur = cur->next) {
2541                         msginfo = (MsgInfo *)cur->data;
2542                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2543                 }
2544         }
2545         g_free(dir);
2546
2547         g_slist_free(numlist);
2548
2549         imap_scan_required(folder, dest);
2550
2551         g_free(destdir);
2552
2553         return 0;
2554 }
2555
2556 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2557                     MsgInfoList *msglist, GHashTable *relation)
2558 {
2559         MsgInfo *msginfo;
2560
2561         g_return_val_if_fail(folder != NULL, -1);
2562         g_return_val_if_fail(dest != NULL, -1);
2563         if (msglist == NULL)
2564                 return 0;
2565
2566         msginfo = (MsgInfo *)msglist->data;
2567         g_return_val_if_fail(msginfo->folder != NULL, -1);
2568
2569         return imap_do_remove_msgs(folder, dest, msglist, relation);
2570 }
2571
2572 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2573 {
2574         GSList *list = folder_item_get_msg_list(item);
2575         gint res = imap_remove_msgs(folder, item, list, NULL);
2576         procmsg_msg_list_free(list);
2577         return res;
2578 }
2579
2580 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2581                                     MsgInfo *msginfo)
2582 {
2583         /* TODO: properly implement this method */
2584         return FALSE;
2585 }
2586
2587 static gint imap_close(Folder *folder, FolderItem *item)
2588 {
2589         return 0;
2590 }
2591
2592 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2593 {
2594         FolderItem *item = NULL;
2595         IMAPSession *session;
2596         gchar *root_folder = NULL;
2597
2598         g_return_val_if_fail(folder != NULL, -1);
2599         g_return_val_if_fail(folder->account != NULL, -1);
2600
2601         debug_print("getting session...\n");
2602         session = imap_session_get(folder);
2603         if (!session) {
2604                 if (!folder->node) {
2605                         folder_tree_destroy(folder);
2606                         item = folder_item_new(folder, folder->name, NULL);
2607                         item->folder = folder;
2608                         folder->node = item->node = g_node_new(item);
2609                 }
2610                 return -1;
2611         }
2612
2613         if (folder->account->imap_dir && *folder->account->imap_dir) {
2614                 gchar *real_path;
2615                 int r = MAILIMAP_NO_ERROR;
2616                 clist * lep_list;
2617
2618                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2619                 extract_quote(root_folder, '"');
2620                 subst_char(root_folder,
2621                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2622                                                    root_folder, &r),
2623                            '/');
2624                 if (is_fatal(r))
2625                         return -1;
2626                 strtailchomp(root_folder, '/');
2627                 real_path = imap_get_real_path
2628                         (session, IMAP_FOLDER(folder), root_folder, &r);
2629                 if (is_fatal(r)) {
2630                         g_free(real_path);
2631                         return -1;
2632                 }
2633                 debug_print("IMAP root directory: %s\n", real_path);
2634
2635                 /* check if root directory exist */
2636
2637                 r = imap_threaded_list(session->folder, "", real_path,
2638                                        &lep_list);
2639
2640                 if (r != MAILIMAP_NO_ERROR)
2641                         imap_handle_error(SESSION(session), NULL, r);
2642
2643                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2644                         if (!folder->node) {
2645                                 item = folder_item_new(folder, folder->name, NULL);
2646                                 item->folder = folder;
2647                                 folder->node = item->node = g_node_new(item);
2648                         }
2649                         return -1;
2650                 }
2651                 mailimap_list_result_free(lep_list);
2652                                 
2653                 g_free(real_path);
2654         }
2655
2656         if (folder->node)
2657                 item = FOLDER_ITEM(folder->node->data);
2658                 
2659         if (item && !item->path && root_folder) {
2660                 item->path = g_strdup(root_folder);
2661         }
2662
2663         if (!item || ((item->path || root_folder) &&
2664                       strcmp2(item->path, root_folder) != 0)) {
2665                 folder_tree_destroy(folder);
2666                 item = folder_item_new(folder, folder->name, root_folder);
2667                 item->folder = folder;
2668                 folder->node = item->node = g_node_new(item);
2669         }
2670
2671         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2672         imap_create_missing_folders(folder);
2673
2674         return 0;
2675 }
2676
2677 static gint imap_scan_tree(Folder *folder)
2678 {
2679         gboolean subs_only = FALSE;
2680         if (folder->account) {
2681                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2682                 subs_only = folder->account->imap_subsonly;
2683         }
2684         return imap_scan_tree_real(folder, subs_only);
2685 }
2686
2687 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2688 {
2689         Folder *folder;
2690         IMAPFolder *imapfolder;
2691         FolderItem *new_item;
2692         GSList *item_list, *cur;
2693         GNode *node;
2694         gchar *real_path;
2695         gchar *wildcard_path;
2696         gchar separator;
2697         gchar wildcard[3];
2698         clist * lep_list;
2699         int r = MAILIMAP_NO_ERROR;
2700         
2701         g_return_val_if_fail(item != NULL, -1);
2702         g_return_val_if_fail(item->folder != NULL, -1);
2703         g_return_val_if_fail(item->no_sub == FALSE, -1);
2704
2705         folder = item->folder;
2706         imapfolder = IMAP_FOLDER(folder);
2707
2708         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2709         if (is_fatal(r))
2710                 return r;
2711
2712         if (folder->ui_func)
2713                 folder->ui_func(folder, item, folder->ui_func_data);
2714
2715         if (item->path) {
2716                 wildcard[0] = separator;
2717                 wildcard[1] = '%';
2718                 wildcard[2] = '\0';
2719                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2720                 if (is_fatal(r)) {
2721                         g_free(real_path);
2722                         return r;
2723                 }
2724         } else {
2725                 wildcard[0] = '%';
2726                 wildcard[1] = '\0';
2727                 real_path = g_strdup("");
2728         }
2729
2730         Xstrcat_a(wildcard_path, real_path, wildcard,
2731                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2732         lep_list = NULL;
2733         
2734         if (subs_only)
2735                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2736         else
2737                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2738
2739         if (r != MAILIMAP_NO_ERROR) {
2740                 imap_handle_error(SESSION(session), NULL, r);
2741                 item_list = NULL;
2742                 g_free(real_path);
2743                 return r;
2744         }
2745         else {
2746                 item_list = imap_list_from_lep(imapfolder,
2747                                                lep_list, real_path, FALSE);
2748                 mailimap_list_result_free(lep_list);
2749         }
2750         
2751         g_free(real_path);
2752
2753         node = item->node->children;
2754         while (node != NULL) {
2755                 FolderItem *old_item = FOLDER_ITEM(node->data);
2756                 GNode *next = node->next;
2757
2758                 new_item = NULL;
2759                 for (cur = item_list; cur != NULL; cur = cur->next) {
2760                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2761                         if (!strcmp2(old_item->path, cur_item->path)) {
2762                                 new_item = cur_item;
2763                                 break;
2764                         }
2765                 }
2766                 if (!new_item) {
2767                         if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2768                                 debug_print("not removing INBOX\n");
2769                         } else {
2770                                 debug_print("folder '%s' not found. removing...\n",
2771                                             old_item->path);
2772                                 folder_item_remove(old_item);
2773                         }
2774                 } else {
2775                         old_item->no_sub = new_item->no_sub;
2776                         old_item->no_select = new_item->no_select;
2777                         if (old_item->no_sub == TRUE && node->children) {
2778                                 debug_print("folder '%s' doesn't have "
2779                                             "subfolders. removing...\n",
2780                                             old_item->path);
2781                                 folder_item_remove_children(old_item);
2782                         }
2783                 }
2784
2785                 node = next;
2786         }
2787
2788         for (cur = item_list; cur != NULL; cur = cur->next) {
2789                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2790                 new_item = NULL;
2791
2792                 for (node = item->node->children; node != NULL;
2793                      node = node->next) {
2794                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2795                                      cur_item->path)) {
2796                                 new_item = FOLDER_ITEM(node->data);
2797                                 folder_item_destroy(cur_item);
2798                                 cur_item = NULL;
2799                                 break;
2800                         }
2801                 }
2802                 if (!new_item) {
2803                         new_item = cur_item;
2804                         debug_print("new folder '%s' found.\n", new_item->path);
2805                         folder_item_append(item, new_item);
2806                 }
2807
2808                 if (!strcasecmp(new_item->path, "INBOX")) {
2809                         new_item->stype = F_INBOX;
2810                         folder->inbox = new_item;
2811                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2812                         gchar *base;
2813
2814                         base = g_path_get_basename(new_item->path);
2815
2816                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2817                                 new_item->stype = F_OUTBOX;
2818                                 folder->outbox = new_item;
2819                         } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2820                                 new_item->stype = F_DRAFT;
2821                                 folder->draft = new_item;
2822                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2823                                 new_item->stype = F_QUEUE;
2824                                 folder->queue = new_item;
2825                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2826                                 new_item->stype = F_TRASH;
2827                                 folder->trash = new_item;
2828                         }
2829                         g_free(base);
2830                 }
2831
2832                 if (new_item->no_sub == FALSE)
2833                         imap_scan_tree_recursive(session, new_item, subs_only);
2834         }
2835
2836         g_slist_free(item_list);
2837
2838         return MAILIMAP_NO_ERROR;
2839 }
2840
2841 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2842 {
2843         IMAPSession *session = imap_session_get(folder);
2844         gchar *real_path;
2845         gchar *wildcard_path;
2846         gchar separator;
2847         gchar wildcard[3];
2848         clist * lep_list;
2849         GSList *item_list = NULL, *cur;
2850         GList *child_list = NULL, *tmplist = NULL;
2851         GSList *sub_list = NULL;
2852         int r = MAILIMAP_NO_ERROR;
2853
2854         if (!session)
2855                 return NULL;
2856
2857         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2858         if (is_fatal(r))
2859                 return NULL;
2860
2861         if (item->path) {
2862                 wildcard[0] = separator;
2863                 wildcard[1] = '%';
2864                 wildcard[2] = '\0';
2865                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2866                 if (is_fatal(r)) {
2867                         g_free(real_path);
2868                         return NULL;
2869                 }
2870         } else {
2871                 wildcard[0] = '%';
2872                 wildcard[1] = '\0';
2873                 real_path = g_strdup("");
2874         }
2875
2876         Xstrcat_a(wildcard_path, real_path, wildcard,
2877                   {g_free(real_path); return NULL;});
2878         lep_list = NULL;
2879         
2880         if (unsubs_only)
2881                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2882                                 item->path?item->path:item->name);
2883         else
2884                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2885                                 item->path?item->path:item->name);
2886
2887         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2888         if (r) {
2889                 g_free(real_path);
2890                 statusbar_pop_all();
2891                 return NULL;
2892         }
2893         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2894                                lep_list, real_path, FALSE);
2895         mailimap_list_result_free(lep_list);
2896
2897         for (cur = item_list; cur != NULL; cur = cur->next) {
2898                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2899                 if (recursive) {
2900                         tmplist = imap_scan_subtree(folder, cur_item, 
2901                                         unsubs_only, recursive);
2902                         if (tmplist)
2903                                 child_list = g_list_concat(child_list, tmplist);
2904                 }
2905                 child_list = g_list_prepend(child_list,
2906                                 imap_get_real_path(session, 
2907                                         IMAP_FOLDER(folder), cur_item->path, &r));
2908                 if (is_fatal(r)) {
2909                         g_free(real_path);
2910                         statusbar_pop_all();
2911                         return NULL;
2912                 }
2913                 folder_item_destroy(cur_item);
2914         }
2915         child_list = g_list_reverse(child_list);
2916         g_slist_free(item_list);
2917
2918         if (unsubs_only) {
2919                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2920                 if (r) {
2921                         g_free(real_path);
2922                         statusbar_pop_all();
2923                         return NULL;
2924                 }
2925                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2926                                        lep_list, real_path, FALSE);
2927                 mailimap_list_result_free(lep_list);
2928
2929                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2930                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2931                         GList *oldlitem = NULL;
2932                         gchar *tmp = imap_get_real_path(session, 
2933                                         IMAP_FOLDER(folder), cur_item->path, &r);
2934                         if (r) {
2935                                 g_free(real_path);
2936                                 statusbar_pop_all();
2937                                 g_free(tmp);
2938                                 return NULL;
2939                         }
2940                         folder_item_destroy(cur_item);
2941                         oldlitem = g_list_find_custom(
2942                                         child_list, tmp, (GCompareFunc)strcmp2);
2943                         if (oldlitem) {
2944                                 child_list = g_list_remove_link(child_list, oldlitem);
2945                                 g_free(oldlitem->data);
2946                                 g_list_free(oldlitem);
2947                         }
2948                         g_free(tmp);
2949                 }
2950         }
2951
2952         g_free(real_path);
2953         statusbar_pop_all();
2954
2955         return child_list;
2956 }
2957
2958 static gint imap_create_tree(Folder *folder)
2959 {
2960         g_return_val_if_fail(folder != NULL, -1);
2961         g_return_val_if_fail(folder->node != NULL, -1);
2962         g_return_val_if_fail(folder->node->data != NULL, -1);
2963         g_return_val_if_fail(folder->account != NULL, -1);
2964
2965         imap_scan_tree(folder);
2966         imap_create_missing_folders(folder);
2967
2968         return 0;
2969 }
2970
2971 static void imap_create_missing_folders(Folder *folder)
2972 {
2973         g_return_if_fail(folder != NULL);
2974
2975         if (!folder->inbox)
2976                 folder->inbox = imap_create_special_folder
2977                         (folder, F_INBOX, "INBOX");
2978         if (!folder->trash)
2979                 folder->trash = imap_create_special_folder
2980                         (folder, F_TRASH, "Trash");
2981         if (!folder->queue)
2982                 folder->queue = imap_create_special_folder
2983                         (folder, F_QUEUE, "Queue");
2984         if (!folder->outbox)
2985                 folder->outbox = imap_create_special_folder
2986                         (folder, F_OUTBOX, "Sent");
2987         if (!folder->draft)
2988                 folder->draft = imap_create_special_folder
2989                         (folder, F_DRAFT, "Drafts");
2990 }
2991
2992 static FolderItem *imap_create_special_folder(Folder *folder,
2993                                               SpecialFolderItemType stype,
2994                                               const gchar *name)
2995 {
2996         FolderItem *item;
2997         FolderItem *new_item;
2998
2999         g_return_val_if_fail(folder != NULL, NULL);
3000         g_return_val_if_fail(folder->node != NULL, NULL);
3001         g_return_val_if_fail(folder->node->data != NULL, NULL);
3002         g_return_val_if_fail(folder->account != NULL, NULL);
3003         g_return_val_if_fail(name != NULL, NULL);
3004
3005         item = FOLDER_ITEM(folder->node->data);
3006         new_item = imap_create_folder(folder, item, name);
3007
3008         if (!new_item) {
3009                 g_warning("Can't create '%s'", name);
3010                 if (!folder->inbox) return NULL;
3011
3012                 new_item = imap_create_folder(folder, folder->inbox, name);
3013                 if (!new_item)
3014                         g_warning("Can't create '%s' under INBOX", name);
3015                 else
3016                         new_item->stype = stype;
3017         } else
3018                 new_item->stype = stype;
3019
3020         return new_item;
3021 }
3022
3023 static gchar *imap_folder_get_path(Folder *folder)
3024 {
3025         gchar *folder_path;
3026
3027         g_return_val_if_fail(folder != NULL, NULL);
3028         g_return_val_if_fail(folder->account != NULL, NULL);
3029
3030 #ifdef G_OS_WIN32
3031         gchar *sanitized_dirname = g_strdup(folder->account->recv_server);
3032         g_strdelimit(sanitized_dirname, ":", ',');
3033 #endif
3034
3035         folder_path = g_strconcat(get_imap_cache_dir(),
3036                                   G_DIR_SEPARATOR_S,
3037 #ifdef G_OS_WIN32
3038                                                                                                                                         sanitized_dirname,
3039 #else
3040                                   folder->account->recv_server,
3041 #endif
3042                                   G_DIR_SEPARATOR_S,
3043                                   folder->account->userid,
3044                                   NULL);
3045
3046 #ifdef G_OS_WIN32
3047         g_free(sanitized_dirname);
3048 #endif
3049         return folder_path;
3050 }
3051
3052 #ifdef G_OS_WIN32
3053 static gchar *imap_encode_unsafe_chars(const gchar *str)
3054 {
3055         gchar *ret = NULL, *o_ret;
3056         gchar *i;
3057         if (!str) 
3058                 return NULL;
3059         ret = g_malloc(3*strlen(str)+1);
3060         o_ret = ret;
3061         for (i = (gchar *)str; *i; i++) {
3062                 switch(*i) {
3063                         case ':':
3064                         case '|':
3065                         case '<':
3066                         case '>':
3067                         case '*':
3068                         case '?':
3069                         case '#':
3070                                 *ret++ = '%';
3071                                 *ret++ = '0'+(*i/10);
3072                                 *ret++ = '0'+(*i%10);
3073                                 break;
3074                         default:
3075                                 *ret++ = *i;
3076                 }
3077         }
3078         *ret++ = '\0';
3079         return o_ret;
3080 }
3081 #endif
3082 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3083 {
3084         gchar *folder_path, *path;
3085         gchar *item_path = NULL;
3086         
3087         g_return_val_if_fail(folder != NULL, NULL);
3088         g_return_val_if_fail(item != NULL, NULL);
3089         folder_path = imap_folder_get_path(folder);
3090
3091         g_return_val_if_fail(folder_path != NULL, NULL);
3092
3093 #ifdef G_OS_UNIX
3094         item_path = g_strdup(item->path);
3095 #else
3096         item_path = imap_encode_unsafe_chars(item->path);
3097 #endif  
3098
3099         if (g_path_is_absolute(folder_path)) {
3100                 if (item_path)
3101                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3102                                            item_path, NULL);
3103                 else
3104                         path = g_strdup(folder_path);
3105         } else {
3106                 if (item_path)
3107                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3108                                            folder_path, G_DIR_SEPARATOR_S,
3109                                            item_path, NULL);
3110                 else
3111                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3112                                            folder_path, NULL);
3113         }
3114         g_free(folder_path);
3115         g_free(item_path);
3116 #ifdef G_OS_WIN32
3117         while (strchr(path, '/'))
3118                 *strchr(path, '/') = '\\';
3119 #endif
3120
3121         return path;
3122 }
3123
3124 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3125                                const gchar *name)
3126 {
3127         gchar *dirpath, *imap_path;
3128         IMAPSession *session;
3129         FolderItem *new_item;
3130         gchar separator;
3131         gchar *new_name;
3132         const gchar *p;
3133         gint ok = MAILIMAP_NO_ERROR;
3134         gboolean no_select = FALSE, no_sub = FALSE;
3135         gboolean exist = FALSE;
3136         
3137         g_return_val_if_fail(folder != NULL, NULL);
3138         g_return_val_if_fail(folder->account != NULL, NULL);
3139         g_return_val_if_fail(parent != NULL, NULL);
3140         g_return_val_if_fail(name != NULL, NULL);
3141
3142         if (to_number(name) > 0) {
3143                 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3144                 if (is_file_exist(cached_msg)) {
3145                         if (claws_unlink(cached_msg) != 0) {
3146                                 return NULL;
3147                         }
3148                 }
3149         }
3150
3151         debug_print("getting session...\n");
3152         session = imap_session_get(folder);
3153         if (!session) {
3154                 return NULL;
3155         }
3156
3157         if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3158                 dirpath = g_strdup(name);
3159         }else if (parent->path)
3160                 dirpath = g_strconcat(parent->path, "/", name, NULL);
3161         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3162                 dirpath = g_strdup(name);
3163         else if (folder->account->imap_dir && *folder->account->imap_dir) {
3164                 gchar *imap_dir;
3165
3166                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3167                 strtailchomp(imap_dir, '/');
3168                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3169         } else
3170                 dirpath = g_strdup(name);
3171                 
3172         
3173
3174         /* keep trailing directory separator to create a folder that contains
3175            sub folder */
3176         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3177
3178         strtailchomp(dirpath, '/');
3179         Xstrdup_a(new_name, name, {
3180                 g_free(dirpath); 
3181                 g_free(imap_path);
3182                 return NULL;});
3183
3184         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3185         if (is_fatal(ok)) {
3186                 g_free(imap_path);
3187                 return NULL;
3188         }
3189         imap_path_separator_subst(imap_path, separator);
3190         /* remove trailing / for display */
3191         strtailchomp(new_name, '/');
3192
3193         if (strcasecmp(dirpath, "INBOX") != 0) {
3194                 GPtrArray *argbuf;
3195                 int r;
3196                 clist * lep_list;
3197                 
3198                 argbuf = g_ptr_array_new();
3199                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3200                 if (r != MAILIMAP_NO_ERROR) {
3201                         imap_handle_error(SESSION(session), NULL, r);
3202                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3203                         g_free(imap_path);
3204                         g_free(dirpath);
3205                         ptr_array_free_strings(argbuf);
3206                         g_ptr_array_free(argbuf, TRUE);
3207                         return NULL;
3208                 }
3209                 
3210                 if (clist_count(lep_list) > 0)
3211                         exist = TRUE;
3212                 mailimap_list_result_free(lep_list);
3213                 lep_list = NULL;
3214                 if (!exist) {
3215                         ok = imap_cmd_create(session, imap_path);
3216                         if (ok != MAILIMAP_NO_ERROR) {
3217                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3218                                 g_free(imap_path);
3219                                 g_free(dirpath);
3220                                 return NULL;
3221                         }
3222                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
3223                         if (r == MAILIMAP_NO_ERROR) {
3224                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3225                                                lep_list, dirpath, TRUE);
3226                                 if (item_list) {
3227                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3228                                         no_select = cur_item->no_select;
3229                                         no_sub = cur_item->no_sub;
3230                                         g_slist_free(item_list);
3231                                 } 
3232                                 mailimap_list_result_free(lep_list);
3233                         } else {
3234                                 imap_handle_error(SESSION(session), NULL, r);
3235                         }
3236                 }
3237                 imap_threaded_subscribe(folder, imap_path, TRUE);
3238         } else {
3239                 clist *lep_list;
3240                 int r;
3241                 /* just get flags */
3242                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3243                 if (r == MAILIMAP_NO_ERROR) {
3244                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3245                                        lep_list, dirpath, TRUE);
3246                         if (item_list) {
3247                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3248                                 no_select = cur_item->no_select;
3249                                 no_sub = cur_item->no_sub;
3250                                 g_slist_free(item_list);
3251                         } 
3252                         mailimap_list_result_free(lep_list);
3253                 } else {
3254                         imap_handle_error(SESSION(session), NULL, r);
3255                 }
3256         }
3257
3258         new_item = folder_item_new(folder, new_name, dirpath);
3259         new_item->no_select = no_select;
3260         new_item->no_sub = no_sub;
3261         folder_item_append(parent, new_item);
3262         g_free(imap_path);
3263         g_free(dirpath);
3264
3265         dirpath = folder_item_get_path(new_item);
3266         if (!is_dir_exist(dirpath))
3267                 make_dir_hier(dirpath);
3268         g_free(dirpath);
3269
3270         if (exist) {
3271                 /* folder existed, scan it */
3272                 imap_scan_required(folder, new_item);
3273                 folder_item_scan_full(new_item, FALSE);
3274         }
3275
3276         return new_item;
3277 }
3278
3279 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3280                                const gchar *name)
3281 {
3282         gchar *dirpath;
3283         gchar *newpath;
3284         gchar *real_oldpath;
3285         gchar *real_newpath;
3286         gchar *paths[2];
3287         gchar *old_cache_dir;
3288         gchar *new_cache_dir;
3289         IMAPSession *session;
3290         gchar separator;
3291         gint ok = MAILIMAP_NO_ERROR;
3292         gint exists, recent, unseen;
3293         guint32 uid_validity;
3294
3295         g_return_val_if_fail(folder != NULL, -1);
3296         g_return_val_if_fail(item != NULL, -1);
3297         g_return_val_if_fail(item->path != NULL, -1);
3298         g_return_val_if_fail(name != NULL, -1);
3299
3300         debug_print("getting session...\n");
3301         session = imap_session_get(folder);
3302         if (!session) {
3303                 return -1;
3304         }
3305
3306         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3307                 is_fatal(ok)) {
3308                 g_warning("New folder name must not contain the namespace "
3309                             "path separator");
3310                 return -1;
3311         }
3312
3313         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3314         if (is_fatal(ok)) {
3315                 g_free(real_oldpath);
3316                 return -1;
3317         }
3318
3319         g_free(session->mbox);
3320         session->mbox = NULL;
3321         session->exists = 0;
3322         session->recent = 0;
3323         session->expunge = 0;
3324         ok = imap_cmd_examine(session, "INBOX",
3325                               &exists, &recent, &unseen, &uid_validity, FALSE);
3326         if (ok != MAILIMAP_NO_ERROR) {
3327                 g_free(real_oldpath);
3328                 return -1;
3329         }
3330
3331         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3332         if (is_fatal(ok)) {
3333                 g_free(real_oldpath);
3334                 return -1;
3335         }
3336         if (strchr(item->path, '/')) {
3337                 dirpath = g_path_get_dirname(item->path);
3338                 newpath = g_strconcat(dirpath, "/", name, NULL);
3339                 g_free(dirpath);
3340         } else
3341                 newpath = g_strdup(name);
3342
3343         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3344         imap_path_separator_subst(real_newpath, separator);
3345
3346         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3347         if (ok != MAILIMAP_NO_ERROR) {
3348                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3349                             real_oldpath, real_newpath);
3350                 g_free(real_oldpath);
3351                 g_free(newpath);
3352                 g_free(real_newpath);
3353                 return -1;
3354         }
3355         g_free(item->name);
3356         item->name = g_strdup(name);
3357
3358         old_cache_dir = folder_item_get_path(item);
3359
3360         paths[0] = g_strdup(item->path);
3361         paths[1] = newpath;
3362         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3363                         imap_rename_folder_func, paths);
3364
3365         if (is_dir_exist(old_cache_dir)) {
3366                 new_cache_dir = folder_item_get_path(item);
3367                 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3368                         FILE_OP_ERROR(old_cache_dir, "rename");
3369                 }
3370                 g_free(new_cache_dir);
3371         }
3372
3373         g_free(old_cache_dir);
3374         g_free(paths[0]);
3375         g_free(newpath);
3376         g_free(real_oldpath);
3377         g_free(real_newpath);
3378         return 0;
3379 }
3380
3381 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
3382 {
3383         gchar *path;
3384         gint r = MAILIMAP_NO_ERROR;
3385         IMAPSession *session;
3386         debug_print("getting session...\n");
3387
3388         session = imap_session_get(folder);
3389         if (!session) {
3390                 return -1;
3391         }
3392         if (item && item->path) {
3393                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3394                 if (!path)
3395                         return -1;
3396                 if (is_fatal(r)) {
3397                         g_free(path);
3398                         return -1;
3399                 }
3400                 if (!strcasecmp(path, "INBOX") && sub == FALSE) {
3401                         g_free(path);
3402                         return -1;
3403                 }
3404                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
3405                 r = imap_threaded_subscribe(folder, path, sub);
3406                 g_free(path);
3407         } else if (rpath) {
3408                 r = imap_threaded_subscribe(folder, rpath, sub);
3409         } else
3410                 return -1;
3411         return r;
3412 }
3413
3414 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
3415 {
3416         gint ok = MAILIMAP_NO_ERROR;
3417         IMAPSession *session;
3418         gchar *path;
3419         gchar *cache_dir;
3420         gboolean selected_folder;
3421
3422         g_return_val_if_fail(folder != NULL, -1);
3423         g_return_val_if_fail(item != NULL, -1);
3424         g_return_val_if_fail(item->path != NULL, -1);
3425
3426         debug_print("getting session...\n");
3427         session = imap_session_get(folder);
3428         if (!session) {
3429                 return -1;
3430         }
3431         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3432         if (is_fatal(ok)) {
3433                 g_free(path);
3434                 return -1;
3435         }
3436         imap_threaded_subscribe(folder, path, FALSE);
3437
3438         selected_folder = (session->mbox != NULL) &&
3439                           (!strcmp(session->mbox, item->path));
3440         if (selected_folder) {
3441                 ok = imap_cmd_close(session);
3442                 if (ok != MAILIMAP_NO_ERROR) {
3443                         debug_print("close err %d\n", ok);
3444                         return ok;
3445                 }
3446         }
3447         ok = imap_cmd_delete(session, path);
3448         if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
3449                 gchar *tmp = NULL;
3450                 
3451                 ok = MAILIMAP_NO_ERROR;
3452                 tmp = g_strdup_printf("%s%c", path, 
3453                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
3454                 g_free(path);
3455                 path = tmp;
3456                 if (!is_fatal(ok))
3457                         ok = imap_cmd_delete(session, path);
3458         }
3459
3460         if (ok != MAILIMAP_NO_ERROR) {
3461                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
3462                 g_free(path);
3463                 return -1;
3464         }
3465
3466         g_free(path);
3467         cache_dir = folder_item_get_path(item);
3468         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
3469                 g_warning("can't remove directory '%s'", cache_dir);
3470         g_free(cache_dir);
3471         folder_item_remove(item);
3472         return 0;
3473 }
3474
3475 static gint imap_remove_folder(Folder *folder, FolderItem *item)
3476 {
3477         GNode *node, *next;
3478
3479         g_return_val_if_fail(item != NULL, -1);
3480         g_return_val_if_fail(item->folder != NULL, -1);
3481         g_return_val_if_fail(item->node != NULL, -1);
3482
3483         node = item->node->children;
3484         while (node != NULL) {
3485                 next = node->next;
3486                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
3487                         return -1;
3488                 node = next;
3489         }
3490         debug_print("IMAP removing %s\n", item->path);
3491
3492         if (imap_remove_all_msg(folder, item) < 0)
3493                 return -1;
3494         return imap_remove_folder_real(folder, item);
3495 }
3496
3497 typedef struct _uncached_data {
3498         IMAPSession *session;
3499         FolderItem *item;
3500         MsgNumberList *numlist;
3501         guint cur;
3502         guint total;
3503         gboolean done;
3504         int ok;
3505 } uncached_data;
3506
3507 static void *imap_get_uncached_messages_thread(void *data)
3508 {
3509         uncached_data *stuff = (uncached_data *)data;
3510         IMAPSession *session = stuff->session;
3511         FolderItem *item = stuff->item;
3512         MsgNumberList *numlist = stuff->numlist;
3513         GSList *newlist = NULL;
3514         GSList *llast = NULL;
3515         GSList *seq_list, *cur;
3516         gboolean got_alien_tags = FALSE;
3517
3518         debug_print("uncached_messages\n");
3519         
3520         if (session == NULL || item == NULL || item->folder == NULL
3521             || FOLDER_CLASS(item->folder) != &imap_class) {
3522                 stuff->done = TRUE;
3523                 return NULL;
3524         }
3525         
3526         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
3527         debug_print("get msgs info\n");
3528         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3529                 struct mailimap_set * imapset;
3530                 unsigned int i;
3531                 int r;
3532                 carray * env_list;
3533                 int count;
3534                 
3535                 if (session->cancelled)
3536                         break;
3537                 
3538                 imapset = cur->data;
3539                 
3540                 r = imap_threaded_fetch_env(session->folder,
3541                                             imapset, &env_list);
3542                 if (r != MAILIMAP_NO_ERROR) {
3543                         imap_handle_error(SESSION(session), NULL, r);
3544                         if (is_fatal(r)) {
3545                                 stuff->ok = r;
3546                                 return NULL;
3547                         }
3548                         continue;
3549                 }
3550
3551                 session_set_access_time(SESSION(session));
3552
3553                 count = 0;
3554                 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3555                         struct imap_fetch_env_info * info;
3556                         MsgInfo * msginfo;
3557                         GSList *tags = NULL, *cur = NULL;
3558                         info = carray_get(env_list, i);
3559                         tags = carray_get(env_list, i+1);
3560                         msginfo = imap_envelope_from_lep(info, item);
3561                         if (msginfo == NULL) {
3562                                 slist_free_strings_full(tags);
3563                                 continue;
3564                         }
3565                         g_slist_free(msginfo->tags);
3566                         msginfo->tags = NULL;
3567
3568                         for (cur = tags; cur; cur = cur->next) {
3569                                 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3570                                 gint id = 0;
3571                                 id = tags_get_id_for_str(real_tag);
3572                                 if (id == -1) {
3573                                         id = tags_add_tag(real_tag);
3574                                         got_alien_tags = TRUE;
3575                                 }
3576                                 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3577                                         msginfo->tags = g_slist_prepend(
3578                                                         msginfo->tags,
3579                                                         GINT_TO_POINTER(id));
3580                                 }
3581                                 g_free(real_tag);
3582                         }
3583                         if (msginfo->tags)
3584                                 msginfo->tags = g_slist_reverse(msginfo->tags);
3585                         slist_free_strings_full(tags);
3586                         msginfo->folder = item;
3587                         if (!newlist)
3588                                 llast = newlist = g_slist_append(newlist, msginfo);
3589                         else {
3590                                 llast = g_slist_append(llast, msginfo);
3591                                 llast = llast->next;
3592                         }
3593                         count ++;
3594                 }
3595                 
3596                 imap_fetch_env_free(env_list);
3597         }
3598         
3599         if (got_alien_tags) {
3600                 tags_write_tags();
3601                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3602         }
3603
3604         imap_lep_set_free(seq_list);
3605         
3606         session_set_access_time(SESSION(session));
3607         stuff->done = TRUE;
3608         return newlist;
3609 }
3610
3611 #define MAX_MSG_NUM 50
3612
3613 static GSList *imap_get_uncached_messages(IMAPSession *session,
3614                                         FolderItem *item,
3615                                         MsgNumberList *numlist,
3616                                         int *r)
3617 {
3618         GSList *result = NULL;
3619         GSList * cur;
3620         uncached_data *data = g_new0(uncached_data, 1);
3621         
3622         cur = numlist;
3623         data->total = g_slist_length(numlist);
3624         data->ok = MAILIMAP_NO_ERROR;
3625         debug_print("messages list : %i\n", data->total);
3626
3627         while (cur != NULL) {
3628                 GSList * partial_result;
3629                 int count;
3630                 GSList * newlist;
3631                 GSList * llast;
3632                 
3633                 llast = NULL;
3634                 count = 0;
3635                 newlist = NULL;
3636                 while (count < MAX_MSG_NUM) {
3637                         void * p;
3638                         
3639                         p = cur->data;
3640                         
3641                         if (newlist == NULL)
3642                                 llast = newlist = g_slist_append(newlist, p);
3643                         else {
3644                                 llast = g_slist_append(llast, p);
3645                                 llast = llast->next;
3646                         }
3647                         count ++;
3648                         
3649                         cur = cur->next;
3650                         if (cur == NULL)
3651                                 break;
3652                 }
3653                 
3654                 data->done = FALSE;
3655                 data->session = session;
3656                 data->item = item;
3657                 data->numlist = newlist;
3658                 data->cur += count;
3659                 
3660                 if (prefs_common.work_offline && 
3661                     !inc_offline_should_override(FALSE,
3662                         _("Claws Mail needs network access in order "
3663                           "to access the IMAP server."))) {
3664                         g_free(data);
3665                         return NULL;
3666                 }
3667                 
3668                 partial_result =
3669                         (GSList *)imap_get_uncached_messages_thread(data);
3670                 *r = data->ok;
3671                 if (data->ok != MAILIMAP_NO_ERROR) {
3672                         goto bail;
3673                 }
3674                 statusbar_progress_all(data->cur,data->total, 1);
3675                 
3676                 g_slist_free(newlist);
3677                 
3678                 result = g_slist_concat(result, partial_result);
3679         }
3680 bail:
3681         g_free(data);
3682         
3683         statusbar_progress_all(0,0,0);
3684         statusbar_pop_all();
3685         
3686         return result;
3687 }
3688
3689 static void imap_delete_all_cached_messages(FolderItem *item)
3690 {
3691         gchar *dir;
3692
3693         g_return_if_fail(item != NULL);
3694         g_return_if_fail(item->folder != NULL);
3695         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3696
3697         debug_print("Deleting all cached messages...\n");
3698
3699         dir = folder_item_get_path(item);
3700         if (is_dir_exist(dir))
3701                 remove_all_numbered_files(dir);
3702         g_free(dir);
3703
3704         debug_print("done.\n");
3705 }
3706
3707 gchar imap_get_path_separator_for_item(FolderItem *item)
3708 {
3709         Folder *folder = NULL;
3710         IMAPFolder *imap_folder = NULL;
3711         IMAPSession *session = NULL;
3712         gchar result = '/';
3713         gint ok = MAILIMAP_NO_ERROR;
3714         if (!item)
3715                 return '/';
3716         folder = item->folder;
3717
3718         if (!folder)
3719                 return '/';
3720
3721         imap_folder = IMAP_FOLDER(folder);
3722
3723         debug_print("getting session...");
3724         session = imap_session_get(FOLDER(folder));
3725         result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3726         return result;
3727 }
3728
3729 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3730 {
3731         clist * lep_list;
3732         int r;
3733         gchar separator = '\0';
3734         
3735         g_return_val_if_fail(session != NULL, '/');
3736         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3737         
3738         if (r != MAILIMAP_NO_ERROR) {
3739                 imap_handle_error(SESSION(session), NULL, r);
3740                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3741                 *ok = r;
3742                 return '\0';
3743         }
3744
3745         if (lep_list != NULL && clist_count(lep_list) > 0) {
3746                 clistiter * iter = clist_begin(lep_list); 
3747                 struct mailimap_mailbox_list * mb;
3748                 mb = clist_content(iter);
3749
3750                 separator = mb->mb_delimiter;
3751                 debug_print("got separator: %c\n", folder->last_seen_separator);
3752         }
3753         *ok = MAILIMAP_NO_ERROR;
3754         mailimap_list_result_free(lep_list);
3755         return separator;
3756 }
3757
3758 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3759 {
3760         gchar separator = '/';
3761         *ok = MAILIMAP_NO_ERROR;
3762         if (folder->last_seen_separator == 0) {
3763                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3764         }
3765
3766         if (folder->last_seen_separator == 0) {
3767                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3768         }
3769
3770         if (folder->last_seen_separator != 0) {
3771                 debug_print("using separator: %c\n", folder->last_seen_separator);
3772                 return folder->last_seen_separator;
3773         }
3774
3775         return separator;
3776 }
3777
3778 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3779 {
3780         gchar *real_path = NULL;
3781         gchar separator;
3782         
3783         g_return_val_if_fail(folder != NULL, NULL);
3784         g_return_val_if_fail(path != NULL, NULL);
3785
3786         *ok = MAILIMAP_NO_ERROR;
3787         
3788         real_path = imap_utf8_to_modified_utf7(path, FALSE);
3789         separator = imap_get_path_separator(session, folder, path, ok);
3790         if (*ok == MAILIMAP_NO_ERROR)
3791                 imap_path_separator_subst(real_path, separator);
3792
3793         return real_path;
3794 }
3795
3796 static gint imap_set_message_flags(IMAPSession *session,
3797                                    IMAPFolderItem *item,
3798                                    MsgNumberList *numlist,
3799                                    IMAPFlags flags,
3800                                    GSList *tags,
3801                                    gboolean is_set)
3802 {
3803         gint ok = 0;
3804         GSList *seq_list;
3805         GSList * cur;
3806         gint total = 0;
3807         IMAPFolder *folder = NULL;
3808         GSList *sorted_list = NULL;
3809
3810         if (numlist == NULL || session == NULL)
3811                 return MAILIMAP_ERROR_BAD_STATE;
3812         
3813         folder = IMAP_FOLDER(session->folder);
3814         
3815         sorted_list = g_slist_copy(numlist);
3816         sorted_list = g_slist_sort(sorted_list, g_int_compare);
3817         
3818         cur = g_slist_last(sorted_list);
3819
3820         if (cur)
3821                 total = GPOINTER_TO_INT(cur->data);
3822         
3823         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3824
3825         statusbar_print_all(_("Flagging messages..."));
3826
3827         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3828                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3829                 struct mailimap_set_item *set_item = NULL;
3830                 
3831                 if (imapset->set_list)
3832                         set_item = clist_content(clist_begin(imapset->set_list));
3833                 else
3834                         continue;
3835
3836                 if (set_item == NULL)
3837                         continue;
3838
3839                 statusbar_progress_all(set_item->set_first, total, 1);
3840
3841                 ok = imap_cmd_store(session, item, imapset,
3842                                     flags, tags, is_set);
3843                 statusbar_progress_all(set_item->set_last, total, 1);
3844                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3845                         /* reduce max set size */
3846                         folder->max_set_size /= 2;
3847                 }
3848                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3849                         break;
3850                 }
3851         }
3852         
3853         g_slist_free(sorted_list);
3854
3855         statusbar_progress_all(0,0,0);
3856         statusbar_pop_all();
3857
3858         imap_lep_set_free(seq_list);
3859         
3860         return ok;
3861 }
3862
3863 typedef struct _select_data {
3864         IMAPSession *session;
3865         gchar *real_path;
3866         gint *exists;
3867         gint *recent;
3868         gint *unseen;
3869         guint32 *uid_validity;
3870         gboolean done;
3871 } select_data;
3872
3873 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3874                         FolderItem *item,
3875                         gint *exists, gint *recent, gint *unseen,
3876                         guint32 *uid_validity, gint *can_create_flags,
3877                         gboolean block)
3878 {
3879         gchar *real_path;
3880         gint ok = MAILIMAP_NO_ERROR;
3881         gint exists_, recent_, unseen_;
3882         guint32 uid_validity_;
3883         gint can_create_flags_;
3884         const gchar *path = item ? item->path:NULL;
3885
3886         if (!item) {
3887                 return MAILIMAP_ERROR_BAD_STATE;
3888         }
3889
3890         if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3891                 if (session->mbox && strcmp(session->mbox, path) == 0)
3892                         return MAILIMAP_NO_ERROR;
3893         }
3894         if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3895                 if (session->mbox && strcmp(session->mbox, path) == 0) {
3896                         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3897                                 return MAILIMAP_NO_ERROR;
3898                 }
3899         }
3900         if (!exists)
3901                 exists = &exists_;
3902         if (!recent)
3903                 recent = &recent_;
3904         if (!unseen)
3905                 unseen = &unseen_;
3906         if (!uid_validity)
3907                 uid_validity = &uid_validity_;
3908         if (!can_create_flags)
3909                 can_create_flags = &can_create_flags_;
3910
3911         g_free(session->mbox);
3912         session->mbox = NULL;
3913         session->exists = 0;
3914         session->recent = 0;
3915         session->expunge = 0;
3916
3917         real_path = imap_get_real_path(session, folder, path, &ok);
3918         if (is_fatal(ok)) {
3919                 g_free(real_path);
3920                 return ok;      
3921         }       
3922         g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3923         IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3924         ok = imap_cmd_select(session, real_path,
3925                              exists, recent, unseen, uid_validity, can_create_flags, 
3926                              &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3927         if (ok != MAILIMAP_NO_ERROR) {
3928                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3929         } else {
3930                 session->mbox = g_strdup(path);
3931                 session->folder_content_changed = FALSE;
3932                 session->exists = *exists;
3933                 session->recent = *recent;
3934                 session->expunge = 0;
3935                 session->unseen = *unseen;
3936                 session->uid_validity = *uid_validity;
3937                 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
3938                         session->exists, session->recent, session->expunge,
3939                         session->uid_validity, *can_create_flags);
3940         }
3941         if (*can_create_flags) {
3942                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3943         } else {
3944                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3945         }
3946         g_free(real_path);
3947
3948         return ok;
3949 }
3950
3951 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3952                         const gchar *path, IMAPFolderItem *item,
3953                         gint *messages,
3954                         guint32 *uid_next, guint32 *uid_validity,
3955                         gint *unseen, gboolean block)
3956 {
3957         int r = MAILIMAP_NO_ERROR;
3958         clistiter * iter;
3959         struct mailimap_mailbox_data_status * data_status;
3960         int got_values;
3961         gchar *real_path;
3962         guint mask = 0;
3963         
3964         real_path = imap_get_real_path(session, folder, path, &r);
3965         if (is_fatal(r)) {
3966                 g_free(real_path);
3967                 return r;
3968         }
3969         if (messages) {
3970                 mask |= 1 << 0;
3971                 *messages = 0;
3972         }
3973         if (uid_next) {
3974                 mask |= 1 << 2;
3975                 *uid_next = 0;
3976         }
3977         if (uid_validity) {
3978                 mask |= 1 << 3;
3979                 *uid_validity = 0;
3980         }
3981         if (unseen) {
3982                 mask |= 1 << 4;
3983                 *unseen = 0;
3984         }
3985         
3986         if (session->mbox != NULL &&
3987             !strcmp(session->mbox, item->item.path)) {
3988                 r = imap_cmd_close(session);
3989                 if (r != MAILIMAP_NO_ERROR) {
3990                         debug_print("close err %d\n", r);
3991                         g_free(real_path);
3992                         return r;
3993                 }
3994         }
3995         
3996         r = imap_threaded_status(FOLDER(folder), real_path, 
3997                 &data_status, mask);
3998
3999         g_free(real_path);
4000         if (r != MAILIMAP_NO_ERROR) {
4001                 imap_handle_error(SESSION(session), NULL, r);
4002                 debug_print("status err %d\n", r);
4003                 return r;
4004         }
4005         
4006         if (data_status == NULL || data_status->st_info_list == NULL) {
4007                 debug_print("data_status %p\n", data_status);
4008                 if (data_status) {
4009                         debug_print("data_status->st_info_list %p\n", data_status->st_info_list);
4010                         mailimap_mailbox_data_status_free(data_status);
4011                 }
4012                 return MAILIMAP_ERROR_BAD_STATE;
4013         }
4014         
4015         got_values = 0;
4016         if (data_status->st_info_list) {
4017                 for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
4018                     iter = clist_next(iter)) {
4019                         struct mailimap_status_info * info;             
4020
4021                         info = clist_content(iter);
4022                         switch (info->st_att) {
4023                         case MAILIMAP_STATUS_ATT_MESSAGES:
4024                                 if (messages) {
4025                                         * messages = info->st_value;
4026                                         got_values |= 1 << 0;
4027                                 }
4028                                 break;
4029
4030                         case MAILIMAP_STATUS_ATT_UIDNEXT:
4031                                 if (uid_next) {
4032                                         * uid_next = info->st_value;
4033                                         got_values |= 1 << 2;
4034                                 }
4035                                 break;
4036
4037                         case MAILIMAP_STATUS_ATT_UIDVALIDITY:
4038                                 if (uid_validity) {
4039                                         * uid_validity = info->st_value;
4040                                         got_values |= 1 << 3;
4041                                 }
4042                                 break;
4043
4044                         case MAILIMAP_STATUS_ATT_UNSEEN:
4045                                 if (unseen) {
4046                                         * unseen = info->st_value;
4047                                         got_values |= 1 << 4;
4048                                 }
4049                                 break;
4050                         }
4051                 }
4052         }
4053         mailimap_mailbox_data_status_free(data_status);
4054         
4055         if (got_values != mask) {
4056                 g_warning("status: incomplete values received (%d)", got_values);
4057         }
4058         return MAILIMAP_NO_ERROR;
4059 }
4060
4061 static void imap_free_capabilities(IMAPSession *session)
4062 {
4063         slist_free_strings_full(session->capability);
4064         session->capability = NULL;
4065 }
4066
4067 /* low-level IMAP4rev1 commands */
4068
4069 static gint imap_cmd_login(IMAPSession *session,
4070                            const gchar *user, const gchar *pass,
4071                            const gchar *type)
4072 {
4073         int r;
4074         gint ok;
4075
4076         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
4077                 gint ok = MAILIMAP_ERROR_BAD_STATE;
4078                 if (imap_has_capability(session, "STARTTLS")) {
4079 #ifdef USE_GNUTLS
4080                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
4081                         ok = imap_cmd_starttls(session);
4082                         if (ok != MAILIMAP_NO_ERROR) {
4083                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
4084                                 return ok;
4085                         } else {
4086                                 /* refresh capas */
4087                                 imap_free_capabilities(session);
4088                                 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
4089                                         imap_handle_error(SESSION(session), NULL, r);
4090                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
4091                                         return r;
4092                                 }
4093                         }
4094 #else           
4095                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
4096                                         "server requires TLS, but Claws Mail "
4097                                         "has been compiled without TLS "
4098                                         "support.\n"),
4099                                         SESSION(session)->server);
4100                         return MAILIMAP_ERROR_LOGIN;
4101 #endif
4102                 } else {
4103                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
4104                         return MAILIMAP_ERROR_LOGIN;
4105                 }
4106         }
4107
4108         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
4109                         user,
4110                         SESSION(session)->server,
4111                         type);
4112         r = imap_threaded_login(session->folder, user, pass, type);
4113         if (r != MAILIMAP_NO_ERROR) {
4114                 imap_handle_error(SESSION(session), NULL, r);
4115                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
4116                                 SESSION(session)->server);
4117                 ok = r;
4118         } else {
4119                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
4120                                 SESSION(session)->server);
4121                 ok = MAILIMAP_NO_ERROR;
4122         }
4123         return ok;
4124 }
4125
4126 static gint imap_cmd_noop(IMAPSession *session)
4127 {
4128         int r;
4129         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
4130         
4131         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
4132         if (r != MAILIMAP_NO_ERROR) {
4133                 imap_handle_error(SESSION(session), NULL, r);
4134                 debug_print("noop err %d\n", r);
4135                 return r;
4136         }
4137
4138         if ((exists && exists != session->exists)
4139          || (recent && recent != session->recent)
4140          || (expunge && expunge != session->expunge)
4141          || (unseen && unseen != session->unseen)) {
4142                 session->folder_content_changed = TRUE;
4143         }
4144         if (uidnext != 0 && uidnext != session->uid_next) {
4145                 session->uid_next = uidnext;
4146                 session->folder_content_changed = TRUE;
4147         }
4148         if (uidval != 0 && uidval != session->uid_validity) {
4149                 session->uid_validity = uidval;
4150                 session->folder_content_changed = TRUE;
4151         }
4152
4153         session->exists = exists;
4154         session->recent = recent;
4155         session->expunge = expunge;
4156         session->unseen = unseen;
4157
4158         session_set_access_time(SESSION(session));
4159
4160         return MAILIMAP_NO_ERROR;
4161 }
4162
4163 #ifdef USE_GNUTLS
4164 static gint imap_cmd_starttls(IMAPSession *session)
4165 {
4166         int r;
4167         
4168         r = imap_threaded_starttls(session->folder, 
4169                 SESSION(session)->server, SESSION(session)->port);
4170         if (r != MAILIMAP_NO_ERROR) {
4171                 imap_handle_error(SESSION(session), NULL, r);
4172                 debug_print("starttls err %d\n", r);
4173                 return r;
4174         }
4175         return MAILIMAP_NO_ERROR;
4176 }
4177 #endif
4178
4179 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
4180                             gint *exists, gint *recent, gint *unseen,
4181                             guint32 *uid_validity, gint *can_create_flags,
4182                             GSList **ok_flags, gboolean block)
4183 {
4184         int r;
4185
4186         r = imap_threaded_select(session->folder, folder,
4187                                  exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
4188         if (r != MAILIMAP_NO_ERROR) {
4189                 imap_handle_error(SESSION(session), NULL, r);
4190                 debug_print("select err %d\n", r);
4191                 return r;
4192         }
4193         return MAILIMAP_NO_ERROR;
4194 }
4195
4196 static gint imap_cmd_close(IMAPSession *session)
4197 {
4198         int r;
4199
4200         r = imap_threaded_close(session->folder);
4201         if (r != MAILIMAP_NO_ERROR) {
4202                 imap_handle_error(SESSION(session), NULL, r);
4203                 debug_print("close err %d\n", r);
4204                 return r;
4205         }
4206         g_free(session->mbox);
4207         session->mbox = NULL;
4208         session->exists = 0;
4209         session->recent = 0;
4210         session->expunge = 0;
4211         return MAILIMAP_NO_ERROR;
4212 }
4213
4214 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
4215                              gint *exists, gint *recent, gint *unseen,
4216                              guint32 *uid_validity, gboolean block)
4217 {
4218         int r;
4219
4220         r = imap_threaded_examine(session->folder, folder,
4221                                   exists, recent, unseen, uid_validity);
4222         if (r != MAILIMAP_NO_ERROR) {
4223                 imap_handle_error(SESSION(session), NULL, r);
4224                 debug_print("examine err %d\n", r);
4225                 
4226                 return r;
4227         }
4228         return MAILIMAP_NO_ERROR;
4229 }
4230
4231 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
4232 {
4233         int r;
4234
4235         r = imap_threaded_create(session->folder, folder);
4236         if (r != MAILIMAP_NO_ERROR) {
4237                 imap_handle_error(SESSION(session), NULL, r);
4238                 return r;
4239         }
4240
4241         return MAILIMAP_NO_ERROR;
4242 }
4243
4244 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
4245                             const gchar *new_folder)
4246 {
4247         int r;
4248
4249         r = imap_threaded_rename(session->folder, old_folder,
4250                                  new_folder);
4251         if (r != MAILIMAP_NO_ERROR) {
4252                 imap_handle_error(SESSION(session), NULL, r);
4253                 return r;
4254         }
4255
4256         return MAILIMAP_NO_ERROR;
4257 }
4258
4259 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
4260 {
4261         int r;
4262         
4263
4264         r = imap_threaded_delete(session->folder, folder);
4265         if (r != MAILIMAP_NO_ERROR) {
4266                 imap_handle_error(SESSION(session), NULL, r);
4267                 return r;
4268         }
4269
4270         return MAILIMAP_NO_ERROR;
4271 }
4272
4273 typedef struct _fetch_data {
4274         IMAPSession *session;
4275         guint32 uid;
4276         const gchar *filename;
4277         gboolean headers;
4278         gboolean body;
4279         gboolean done;
4280 } fetch_data;
4281
4282 static void *imap_cmd_fetch_thread(void *data)
4283 {
4284         fetch_data *stuff = (fetch_data *)data;
4285         IMAPSession *session = stuff->session;
4286         guint32 uid = stuff->uid;
4287         const gchar *filename = stuff->filename;
4288         int r;
4289         
4290         if (stuff->body) {
4291                 r = imap_threaded_fetch_content(session->folder,
4292                                                uid, 1, filename);
4293         }
4294         else {
4295                 r = imap_threaded_fetch_content(session->folder,
4296                                                 uid, 0, filename);
4297         }
4298         if (r != MAILIMAP_NO_ERROR) {
4299                 imap_handle_error(SESSION(session), NULL, r);
4300                 debug_print("fetch err %d\n", r);
4301                 return GINT_TO_POINTER(r);
4302         }
4303         return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
4304 }
4305
4306 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
4307                                 const gchar *filename, gboolean headers,
4308                                 gboolean body)
4309 {
4310         fetch_data *data = g_new0(fetch_data, 1);
4311         int result = 0;
4312         data->done = FALSE;
4313         data->session = session;
4314         data->uid = uid;
4315         data->filename = filename;
4316         data->headers = headers;
4317         data->body = body;
4318
4319         if (prefs_common.work_offline && 
4320             !inc_offline_should_override(FALSE,
4321                 _("Claws Mail needs network access in order "
4322                   "to access the IMAP server."))) {
4323                 g_free(data);
4324                 return -1;
4325         }
4326         statusbar_print_all(_("Fetching message..."));
4327         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
4328         statusbar_pop_all();
4329         g_free(data);
4330         return result;
4331 }
4332
4333
4334 static gint imap_cmd_append(IMAPSession *session, 
4335                             IMAPFolderItem *item,
4336                             const gchar *destfolder,
4337                             const gchar *file, IMAPFlags flags, 
4338                             guint32 *new_uid)
4339 {
4340         struct mailimap_flag_list * flag_list;
4341         int r;
4342         
4343         cm_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
4344
4345         flag_list = imap_flag_to_lep(item, flags, NULL);
4346         lock_session(session);
4347         r = imap_threaded_append(session->folder, destfolder,
4348                          file, flag_list, (int *)new_uid);
4349         mailimap_flag_list_free(flag_list);
4350
4351         if (r != MAILIMAP_NO_ERROR) {
4352                 imap_handle_error(SESSION(session), NULL, r);
4353                 debug_print("append err %d\n", r);
4354                 return r;
4355         }
4356
4357         unlock_session(session);
4358
4359         return MAILIMAP_NO_ERROR;
4360 }
4361
4362 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
4363                           const gchar *destfolder,
4364                           struct mailimap_set **source, struct mailimap_set **dest)
4365 {
4366         int r;
4367         
4368         g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
4369         g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
4370         g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
4371
4372         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
4373         if (r != MAILIMAP_NO_ERROR) {
4374                 imap_handle_error(SESSION(session), NULL, r);
4375                 return r;
4376         }
4377
4378         return MAILIMAP_NO_ERROR;
4379 }
4380
4381 static gint imap_cmd_store(IMAPSession *session, 
4382                            IMAPFolderItem *item,
4383                            struct mailimap_set * set,
4384                            IMAPFlags flags, GSList *tags, int do_add)
4385 {
4386         int r;
4387         struct mailimap_flag_list * flag_list = NULL;
4388         struct mailimap_store_att_flags * store_att_flags;
4389         
4390         flag_list = imap_flag_to_lep(item, flags, tags);
4391
4392         if (do_add)
4393                 store_att_flags =
4394                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
4395         else
4396                 store_att_flags =
4397                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
4398         
4399         r = imap_threaded_store(session->folder, set, store_att_flags);
4400         mailimap_store_att_flags_free(store_att_flags);
4401         if (r != MAILIMAP_NO_ERROR) {
4402                 imap_handle_error(SESSION(session), NULL, r);
4403                 return r;
4404         }
4405         
4406         return MAILIMAP_NO_ERROR;
4407 }
4408
4409 static gint imap_cmd_expunge(IMAPSession *session, gboolean do_expunge)
4410 {
4411         int r;
4412         
4413         if (!do_expunge)
4414                 return MAILIMAP_NO_ERROR;
4415
4416         if (prefs_common.work_offline && 
4417             !inc_offline_should_override(FALSE,
4418                 _("Claws Mail needs network access in order "
4419                   "to access the IMAP server."))) {
4420                 return -1;
4421         }
4422
4423         r = imap_threaded_expunge(session->folder);
4424         if (r != MAILIMAP_NO_ERROR) {
4425                 imap_handle_error(SESSION(session), NULL, r);
4426                 return r;
4427         }
4428
4429         return MAILIMAP_NO_ERROR;
4430 }
4431
4432 gint imap_expunge(Folder *folder, FolderItem *item)
4433 {
4434         IMAPSession *session = imap_session_get(folder);
4435         if (session == NULL)
4436                 return -1;
4437         
4438         return imap_cmd_expunge(session, TRUE);
4439 }
4440
4441 static void imap_path_separator_subst(gchar *str, gchar separator)
4442 {
4443         gchar *p;
4444         gboolean in_escape = FALSE;
4445
4446         if (!separator || separator == '/') return;
4447
4448         for (p = str; *p != '\0'; p++) {
4449                 if (*p == '/' && !in_escape)
4450                         *p = separator;
4451                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
4452                         in_escape = TRUE;
4453                 else if (*p == '-' && in_escape)
4454                         in_escape = FALSE;
4455         }
4456 }
4457
4458 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
4459 {
4460         FolderItem *item = node->data;
4461         gchar **paths = data;
4462         const gchar *oldpath = paths[0];
4463         const gchar *newpath = paths[1];
4464         gchar *real_oldpath, *real_newpath;
4465         gchar *base;
4466         gchar *new_itempath;
4467         gint oldpathlen;
4468         IMAPSession *session = imap_session_get(item->folder);
4469         gint ok = MAILIMAP_NO_ERROR;
4470         oldpathlen = strlen(oldpath);
4471         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
4472                 g_warning("path doesn't match: %s, %s", oldpath, item->path);
4473                 return TRUE;
4474         }
4475
4476         base = item->path + oldpathlen;
4477         while (*base == '/') base++;
4478         if (*base == '\0')
4479                 new_itempath = g_strdup(newpath);
4480         else
4481                 new_itempath = g_strconcat(newpath, "/", base,
4482                                            NULL);
4483
4484         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4485         g_free(item->path);
4486         item->path = new_itempath;
4487         
4488         real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4489         
4490         imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
4491         imap_threaded_subscribe(item->folder, real_newpath, TRUE);
4492
4493         g_free(real_oldpath);
4494         g_free(real_newpath);
4495         return FALSE;
4496 }
4497
4498 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
4499 {
4500         GSList *uidlist, *elem;
4501         int r = -1;
4502         clist * lep_uidlist;
4503         gint ok, nummsgs = 0;
4504
4505         if (session == NULL) {
4506                 return -1;
4507         }
4508
4509         ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
4510                          NULL, NULL, NULL, NULL, NULL, TRUE);
4511         if (ok != MAILIMAP_NO_ERROR) {
4512                 return -1;
4513         }
4514
4515         g_slist_free(item->uid_list);
4516         item->uid_list = NULL;
4517
4518         uidlist = NULL;
4519         
4520         if (folder->account && folder->account->low_bandwidth) {
4521                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE,
4522                                 NULL, NULL, NULL, &lep_uidlist);
4523         }
4524         
4525         if (r == MAILIMAP_NO_ERROR) {
4526                 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
4527                 mailimap_search_result_free(lep_uidlist);
4528         } else {
4529                 carray * lep_uidtab;
4530                 if (r != -1) { /* inited */
4531                         imap_handle_error(SESSION(session), NULL, r);
4532                         if (is_fatal(r))
4533                                 return -1;
4534                 }
4535                 r = imap_threaded_fetch_uid(folder, 1,
4536                                     &lep_uidtab);
4537                 if (r == MAILIMAP_NO_ERROR) {
4538                         uidlist = imap_uid_list_from_lep_tab(lep_uidtab);
4539                         imap_fetch_uid_list_free(lep_uidtab);
4540                 }
4541         }
4542         
4543         if (r != MAILIMAP_NO_ERROR) {
4544                 imap_handle_error(SESSION(session), NULL, r);
4545                 return -1;
4546         }
4547
4548         for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
4549                 guint msgnum;
4550
4551                 msgnum = GPOINTER_TO_INT(elem->data);
4552
4553                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
4554                 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
4555                 nummsgs++;
4556         }
4557         g_slist_free(uidlist);
4558
4559         return nummsgs;
4560
4561 }
4562
4563 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
4564 {
4565         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4566         IMAPSession *session;
4567         gint nummsgs;
4568         GSList *uidlist = NULL;
4569         gchar *dir;
4570         gint known_list_len = 0;
4571         gchar *path;
4572
4573         debug_print("get_num_list\n");
4574         
4575         g_return_val_if_fail(folder != NULL, -1);
4576         g_return_val_if_fail(item != NULL, -1);
4577         g_return_val_if_fail(item->item.path != NULL, -1);
4578         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4579         g_return_val_if_fail(folder->account != NULL, -1);
4580
4581         known_list_len = g_slist_length(item->uid_list);
4582         if (!item->should_update) {
4583                 debug_print("get_num_list: nothing to update\n");
4584                 *old_uids_valid = TRUE;
4585                 if (known_list_len == item->item.total_msgs
4586                  && known_list_len > 0) {
4587                         *msgnum_list = g_slist_copy(item->uid_list);
4588                         return known_list_len;
4589                 } else {
4590                         debug_print("don't know the list length...\n");
4591                 }
4592         }
4593
4594         if (prefs_common.work_offline && 
4595             !inc_offline_should_override(FALSE,
4596                 _("Claws Mail needs network access in order "
4597                   "to access the IMAP server."))) {
4598                 return -1;
4599         }
4600         
4601         path = folder_item_get_path(_item);
4602         if (!is_dir_exist(path)) {
4603                 if(is_file_exist(path))
4604                         claws_unlink(path);
4605                 make_dir_hier(path);
4606         }
4607         g_free(path);
4608
4609         debug_print("getting session...\n");
4610         session = imap_session_get(folder);
4611         g_return_val_if_fail(session != NULL, -1);
4612
4613         lock_session(session);
4614         if (FOLDER_ITEM(item)->path) 
4615                 statusbar_print_all(_("Scanning folder %s%c%s..."),
4616                                       FOLDER_ITEM(item)->folder->name, 
4617                                       '/',
4618                                       FOLDER_ITEM(item)->path);
4619         else
4620                 statusbar_print_all(_("Scanning folder %s..."),
4621                                       FOLDER_ITEM(item)->folder->name);
4622
4623         if (item->should_trash_cache) {
4624                 *old_uids_valid = FALSE;
4625                 debug_print("get_num_list: trashing num list\n");
4626                 debug_print("Freeing imap uid cache\n");
4627                 item->lastuid = 0;
4628                 g_slist_free(item->uid_list);
4629                 item->uid_list = NULL;
4630
4631                 imap_delete_all_cached_messages((FolderItem *)item);
4632         } else {
4633                 debug_print("get_num_list: updating num list\n");
4634                 *old_uids_valid = TRUE;
4635         }
4636
4637         nummsgs = get_list_of_uids(session, folder, item, &uidlist);
4638
4639         unlock_session(session);
4640
4641         /* session could be broken now, in case of fatal error */
4642
4643         debug_print("get_num_list: got %d msgs\n", nummsgs);
4644
4645         if (nummsgs < 0) {
4646                 statusbar_pop_all();
4647                 return -1;
4648         }
4649
4650         *msgnum_list = uidlist;
4651
4652         dir = folder_item_get_path((FolderItem *)item);
4653         debug_print("removing old messages from %s\n", dir);
4654         remove_numbered_files_not_in_list(dir, *msgnum_list);
4655         g_free(dir);
4656         
4657         debug_print("get_num_list - ok - %i\n", nummsgs);
4658         statusbar_pop_all();
4659         item->should_trash_cache = FALSE;
4660         item->should_update = FALSE;
4661         return nummsgs;
4662 }
4663
4664 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
4665 {
4666         MsgInfo *msginfo;
4667         MsgFlags flags;
4668
4669         flags.perm_flags = MSG_NEW|MSG_UNREAD;
4670         flags.tmp_flags = 0;
4671
4672         g_return_val_if_fail(item != NULL, NULL);
4673         g_return_val_if_fail(file != NULL, NULL);
4674
4675         if (folder_has_parent_of_type(item, F_QUEUE)) {
4676                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4677         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4678                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4679         }
4680
4681         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
4682         if (!msginfo) return NULL;
4683         
4684         msginfo->plaintext_file = g_strdup(file);
4685         msginfo->folder = item;
4686
4687         return msginfo;
4688 }
4689
4690 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
4691                           GSList *msgnum_list)
4692 {
4693         IMAPSession *session;
4694         MsgInfoList *ret = NULL;
4695         gint ok;
4696         
4697         debug_print("get_msginfos\n");
4698         
4699         g_return_val_if_fail(folder != NULL, NULL);
4700         g_return_val_if_fail(item != NULL, NULL);
4701         g_return_val_if_fail(msgnum_list != NULL, NULL);
4702
4703         debug_print("getting session...\n");
4704         session = imap_session_get(folder);
4705         g_return_val_if_fail(session != NULL, NULL);
4706
4707         lock_session(session); /* unlocked later in the function */
4708
4709         debug_print("IMAP getting msginfos\n");
4710         ok = imap_select(session, IMAP_FOLDER(folder), item,
4711                          NULL, NULL, NULL, NULL, NULL, FALSE);
4712         if (ok != MAILIMAP_NO_ERROR) {
4713                 return NULL;
4714         }
4715         if (!(folder_has_parent_of_type(item, F_DRAFT) || 
4716               folder_has_parent_of_type(item, F_QUEUE))) {
4717                 ret = g_slist_concat(ret,
4718                         imap_get_uncached_messages(session, item,
4719                                                    msgnum_list, &ok));
4720                 if (ok != MAILIMAP_NO_ERROR)
4721                         return NULL;
4722                 unlock_session(session);
4723         } else {
4724                 MsgNumberList *sorted_list, *elem, *llast = NULL;
4725                 gint startnum, lastnum;
4726         
4727                 unlock_session(session);
4728
4729                 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
4730
4731                 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
4732
4733                 llast = g_slist_last(ret);
4734                 for (elem = sorted_list;; elem = g_slist_next(elem)) {
4735                         guint num = 0;
4736
4737                         if (elem)
4738                                 num = GPOINTER_TO_INT(elem->data);
4739
4740                         if (num > lastnum + 1 || elem == NULL) {
4741                                 int i;
4742                                 for (i = startnum; i <= lastnum; ++i) {
4743                                         gchar *file;
4744                                         file = imap_fetch_msg(folder, item, i);
4745                                         if (file != NULL) {
4746                                                 MsgInfo *msginfo = imap_parse_msg(file, item);
4747                                                 if (msginfo != NULL) {
4748                                                         msginfo->msgnum = i;
4749                                                         if (llast == NULL)
4750                                                                 llast = ret = g_slist_append(ret, msginfo);
4751                                                         else {
4752                                                                 llast = g_slist_append(llast, msginfo);
4753                                                                 llast = llast->next;
4754                                                         }
4755                                                 }
4756                                                 g_free(file);
4757                                         }
4758                                 }
4759
4760                                 if (elem == NULL)
4761                                         break;
4762
4763                                 startnum = num;
4764                         }
4765                         lastnum = num;
4766                 }
4767
4768                 g_slist_free(sorted_list);
4769         }
4770         return ret;
4771 }
4772
4773 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4774 {
4775         MsgInfo *msginfo = NULL;
4776         MsgInfoList *msginfolist;
4777         MsgNumberList numlist;
4778
4779         numlist.next = NULL;
4780         numlist.data = GINT_TO_POINTER(uid);
4781
4782         msginfolist = imap_get_msginfos(folder, item, &numlist);
4783         if (msginfolist != NULL) {
4784                 msginfo = msginfolist->data;
4785                 g_slist_free(msginfolist);
4786         }
4787
4788         return msginfo;
4789 }
4790
4791 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4792 {
4793         IMAPSession *session;
4794         IMAPFolderItem *item = (IMAPFolderItem *)_item;
4795         gint ok, exists = 0, unseen = 0;
4796         guint32 uid_next = 0, uid_val = 0;
4797         gboolean selected_folder;
4798         
4799         g_return_val_if_fail(folder != NULL, FALSE);
4800         g_return_val_if_fail(item != NULL, FALSE);
4801         g_return_val_if_fail(item->item.folder != NULL, FALSE);
4802         g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4803
4804         if (item->item.path == NULL)
4805                 return FALSE;
4806
4807         if (item->should_update) {
4808                 debug_print("scan already required\n");
4809                 return TRUE;
4810         }
4811         debug_print("getting session...\n");
4812         session = imap_session_get(folder);
4813         
4814         g_return_val_if_fail(session != NULL, FALSE);
4815         lock_session(session); /* unlocked later in the function */
4816
4817         selected_folder = (session->mbox != NULL) &&
4818                           (!strcmp(session->mbox, item->item.path));
4819         if (selected_folder) {
4820                 if (!session->folder_content_changed) {
4821                         ok = imap_cmd_noop(session);
4822                         if (ok != MAILIMAP_NO_ERROR) {
4823                                 debug_print("disconnected!\n");
4824                                 if (!is_fatal(ok))
4825                                         session = imap_reconnect_if_possible(folder, session);
4826                                 else
4827                                         session = imap_session_get(folder);
4828                                 if (session == NULL)
4829                                         return FALSE;
4830                         }
4831
4832                         if (session->folder_content_changed) {
4833                                 debug_print("CHANGED (self-noop)! scan_required\n");
4834                                 item->should_update = TRUE;
4835                                 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4836                                         item->item.mtime = session->uid_validity;
4837                                         item->should_trash_cache = TRUE;
4838                                 }
4839                                 unlock_session(session);
4840                                 return TRUE;
4841                         }
4842                 } else {
4843                         debug_print("CHANGED (previous noop)! scan_required\n");
4844                         item->should_update = TRUE;
4845                         if (session->uid_validity && session->uid_validity != item->item.mtime) {
4846                                 item->item.mtime = session->uid_validity;
4847                                 item->should_trash_cache = TRUE;
4848                         }
4849                         unlock_session(session);
4850                         return TRUE;
4851                 }
4852         } else {
4853                 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4854                                  &exists, &uid_next, &uid_val, &unseen, FALSE);
4855                 if (ok != MAILIMAP_NO_ERROR) {
4856                         return FALSE;
4857                 }
4858                 
4859                 debug_print("exists %d, item->item.total_msgs %d\n"
4860                             "\tunseen %d, item->item.unread_msgs %d\n"
4861                             "\tuid_next %d, item->uid_next %d\n"
4862                             "\tuid_val %d, item->item.mtime %ld\n",
4863                             exists, item->item.total_msgs, unseen, item->item.unread_msgs,
4864                             uid_next, item->uid_next, uid_val, (long)(item->item.mtime));
4865                 if (exists != item->item.total_msgs
4866                     || unseen != item->item.unread_msgs 
4867                     || uid_next != item->uid_next
4868                     || uid_val != item->item.mtime) {
4869                         debug_print("CHANGED (status)! scan_required\n");
4870                         item->last_change = time(NULL);
4871                         item->should_update = TRUE;
4872                         item->uid_next = uid_next;
4873                         if (uid_val != item->item.mtime) {
4874                                 item->item.mtime = uid_val;
4875                                 item->should_trash_cache = TRUE;
4876                         }
4877                         unlock_session(session);
4878                         return TRUE;
4879                 }
4880         }
4881         unlock_session(session);
4882
4883         item->should_update = FALSE;
4884         return FALSE;
4885 }
4886
4887 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4888 {
4889         IMAPSession *session;
4890         IMAPFlags flags_set = 0, flags_unset = 0;
4891         gint ok = MAILIMAP_NO_ERROR;
4892         MsgNumberList numlist;
4893         hashtable_data *ht_data = NULL;
4894
4895         g_return_if_fail(folder != NULL);
4896         g_return_if_fail(folder->klass == &imap_class);
4897         g_return_if_fail(item != NULL);
4898         g_return_if_fail(item->folder == folder);
4899         g_return_if_fail(msginfo != NULL);
4900         g_return_if_fail(msginfo->folder == item);
4901
4902         if (!MSG_IS_MARKED(msginfo->flags) &&  (newflags & MSG_MARKED))
4903                 flags_set |= IMAP_FLAG_FLAGGED;
4904         if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4905                 flags_unset |= IMAP_FLAG_FLAGGED;
4906
4907         if (!MSG_IS_UNREAD(msginfo->flags) &&  (newflags & MSG_UNREAD))
4908                 flags_unset |= IMAP_FLAG_SEEN;
4909         if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4910                 flags_set |= IMAP_FLAG_SEEN;
4911
4912         if (!MSG_IS_REPLIED(msginfo->flags) &&  (newflags & MSG_REPLIED))
4913                 flags_set |= IMAP_FLAG_ANSWERED;
4914         if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4915                 flags_unset |= IMAP_FLAG_ANSWERED;
4916
4917         if (!MSG_IS_FORWARDED(msginfo->flags) &&  (newflags & MSG_FORWARDED))
4918                 flags_set |= IMAP_FLAG_FORWARDED;
4919         if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
4920                 flags_unset |= IMAP_FLAG_FORWARDED;
4921
4922         if (!MSG_IS_SPAM(msginfo->flags) &&  (newflags & MSG_SPAM)) {
4923                 flags_set |= IMAP_FLAG_SPAM;
4924                 flags_unset |= IMAP_FLAG_HAM;
4925         }
4926         if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
4927                 flags_set |= IMAP_FLAG_HAM;
4928                 flags_unset |= IMAP_FLAG_SPAM;
4929         }
4930         if (!MSG_IS_DELETED(msginfo->flags) &&  (newflags & MSG_DELETED))
4931                 flags_set |= IMAP_FLAG_DELETED;
4932         if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
4933                 flags_unset |= IMAP_FLAG_DELETED;
4934
4935         if (!flags_set && !flags_unset) {
4936                 /* the changed flags were not translatable to IMAP-speak.
4937                  * like MSG_POSTFILTERED, so just apply. */
4938                 msginfo->flags.perm_flags = newflags;
4939                 return;
4940         }
4941
4942         debug_print("getting session...\n");
4943         session = imap_session_get(folder);
4944         if (!session) {
4945                 return;
4946         }
4947
4948         if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
4949             NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
4950                 return;
4951         }
4952         numlist.next = NULL;
4953         numlist.data = GINT_TO_POINTER(msginfo->msgnum);
4954
4955         if (IMAP_FOLDER_ITEM(item)->batching) {
4956                 /* instead of performing an UID STORE command for each message change,
4957                  * as a lot of them can change "together", we just fill in hashtables
4958                  * and defer the treatment so that we're able to send only one
4959                  * command.
4960                  */
4961                 debug_print("IMAP batch mode on, deferring flags change\n");
4962                 if (flags_set) {
4963                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4964                                 GINT_TO_POINTER(flags_set));
4965                         if (ht_data == NULL) {
4966                                 ht_data = g_new0(hashtable_data, 1);
4967                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4968                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table, 
4969                                         GINT_TO_POINTER(flags_set), ht_data);
4970                         }
4971                         ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
4972                 } 
4973                 if (flags_unset) {
4974                         ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4975                                 GINT_TO_POINTER(flags_unset));
4976                         if (ht_data == NULL) {
4977                                 ht_data = g_new0(hashtable_data, 1);
4978                                 ht_data->item = IMAP_FOLDER_ITEM(item);
4979                                 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table, 
4980                                         GINT_TO_POINTER(flags_unset), ht_data);
4981                         }
4982                         ht_data->msglist = g_slist_prepend(ht_data->msglist, 
4983                                         GINT_TO_POINTER(msginfo->msgnum));              
4984                 }
4985         } else {
4986                 debug_print("IMAP changing flags\n");
4987                 if (flags_set) {
4988                         ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
4989                         if (ok != MAILIMAP_NO_ERROR) {
4990                                 return;
4991                         }
4992                 }
4993
4994                 if (flags_unset) {
4995                         ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
4996                         if (ok != MAILIMAP_NO_ERROR) {
4997                                 return;
4998                         }
4999                 }
5000         }
5001         msginfo->flags.perm_flags = newflags;
5002         return;
5003 }
5004
5005 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
5006 {
5007         gint ok;
5008         IMAPSession *session;
5009         gchar *dir;
5010         MsgNumberList numlist;
5011         
5012         g_return_val_if_fail(folder != NULL, -1);
5013         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
5014         g_return_val_if_fail(item != NULL, -1);
5015
5016         debug_print("getting session...\n");
5017         session = imap_session_get(folder);
5018         if (!session) return -1;
5019
5020         ok = imap_select(session, IMAP_FOLDER(folder), item,
5021                          NULL, NULL, NULL, NULL, NULL, FALSE);
5022         if (ok != MAILIMAP_NO_ERROR) {
5023                 return ok;
5024         }
5025         numlist.next = NULL;
5026         numlist.data = GINT_TO_POINTER(uid);
5027         
5028         ok = imap_set_message_flags
5029                 (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
5030         if (ok != MAILIMAP_NO_ERROR) {
5031                 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
5032                 return ok;
5033         }
5034
5035         ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
5036
5037         if (ok != MAILIMAP_NO_ERROR) {
5038                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
5039                 return ok;
5040         }
5041
5042         IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
5043             IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
5044         dir = folder_item_get_path(item);
5045         if (is_dir_exist(dir))
5046                 remove_numbered_files(dir, uid, uid);
5047         g_free(dir);
5048         return MAILIMAP_NO_ERROR;
5049 }
5050
5051 static gint compare_msginfo(gconstpointer a, gconstpointer b)
5052 {
5053         return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
5054 }
5055
5056 static guint gslist_find_next_num(MsgNumberList **list, guint num)
5057 {
5058         GSList *elem;
5059
5060         g_return_val_if_fail(list != NULL, -1);
5061
5062         for (elem = *list; elem != NULL; elem = g_slist_next(elem))
5063                 if (GPOINTER_TO_INT(elem->data) >= num)
5064                         break;
5065         *list = elem;
5066         return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
5067 }
5068
5069 static gboolean flag_ok(IMAPFolderItem *item, guint flag)
5070 {
5071         if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
5072                 debug_print("flag %d is OK\n", flag);
5073                 return TRUE;
5074         }
5075         if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
5076                 debug_print("creating flags is OK\n");
5077                 return TRUE;
5078         }
5079         return FALSE;
5080 }
5081
5082 /*
5083  * NEW and DELETED flags are not syncronized
5084  * - The NEW/RECENT flags in IMAP folders can not really be directly
5085  *   modified by Sylpheed
5086  * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
5087  *   meaning, in IMAP it always removes the messages from the FolderItem
5088  *   in Sylpheed it can mean to move the message to trash
5089  */
5090
5091 typedef struct _get_flags_data {
5092         Folder *folder;
5093         FolderItem *item;
5094         MsgInfoList *msginfo_list;
5095         GHashTable *msgflags;
5096         gboolean full_search;
5097         gboolean done;
5098 } get_flags_data;
5099
5100 static /*gint*/ void *imap_get_flags_thread(void *data)
5101 {
5102         get_flags_data *stuff = (get_flags_data *)data;
5103         Folder *folder = stuff->folder;
5104         FolderItem *fitem = (FolderItem *) stuff->item;
5105         MsgInfoList *msginfo_list = stuff->msginfo_list;
5106         GHashTable *msgflags = stuff->msgflags;
5107         GSList *elem;
5108         carray * lep_uidtab;
5109         IMAPSession *session;
5110         gint ok;
5111         int r = MAILIMAP_NO_ERROR;
5112         GHashTable *flags_hash = NULL;
5113         GHashTable *tags_hash = NULL;
5114         gboolean full_search = stuff->full_search;
5115         GSList *sorted_list = NULL;
5116         GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
5117         GSList *seq_list, *cur;
5118         gboolean reverse_seen = FALSE;
5119         gboolean selected_folder;
5120         gint exists_cnt, unseen_cnt;
5121         gboolean got_alien_tags = FALSE;
5122
5123         session = imap_session_get(folder);
5124
5125         if (session == NULL) {
5126                 stuff->done = TRUE;
5127                 return GINT_TO_POINTER(-1);
5128         }
5129         selected_folder = (session->mbox != NULL) &&
5130                           (!strcmp(session->mbox, fitem->path));
5131
5132         lock_session(session);
5133         if (!selected_folder) {
5134                 ok = imap_select(session, IMAP_FOLDER(folder), fitem,
5135                         &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
5136                 if (ok != MAILIMAP_NO_ERROR) {
5137                         stuff->done = TRUE;
5138                         return GINT_TO_POINTER(-1);
5139                 }
5140
5141                 if (unseen_cnt > exists_cnt / 2)
5142                         reverse_seen = TRUE;
5143         } 
5144         else {
5145                 if (fitem->unread_msgs > fitem->total_msgs / 2)
5146                         reverse_seen = TRUE;
5147         }
5148
5149         sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
5150         if (!full_search) {
5151                 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
5152         } else {
5153                 struct mailimap_set * set;
5154                 set = mailimap_set_new_interval(1, 0);
5155                 seq_list = g_slist_append(NULL, set);
5156         }
5157
5158         if (folder->account && folder->account->low_bandwidth) {
5159                 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
5160                         struct mailimap_set * imapset;
5161                         clist * lep_uidlist;
5162                         int r;
5163
5164                         imapset = cur->data;
5165                         if (reverse_seen) {
5166                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN, NULL,
5167                                                          NULL, full_search ? NULL:imapset, &lep_uidlist);
5168                         }
5169                         else {
5170                                 r = imap_threaded_search(folder,
5171                                                          IMAP_SEARCH_TYPE_UNSEEN, NULL,
5172                                                          NULL, full_search ? NULL:imapset, &lep_uidlist);
5173                         }
5174                         if (r == MAILIMAP_NO_ERROR) {
5175                                 GSList * uidlist;
5176
5177                                 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5178                                 mailimap_search_result_free(lep_uidlist);
5179
5180                                 unseen = g_slist_concat(unseen, uidlist);
5181                         } else {
5182                                 imap_handle_error(SESSION(session), NULL, r);
5183                                 goto bail;
5184                         }
5185
5186                         r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED, NULL,
5187                                                  NULL, full_search ? NULL:imapset, &lep_uidlist);
5188                         if (r == MAILIMAP_NO_ERROR) {
5189                                 GSList * uidlist;
5190
5191                                 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5192                                 mailimap_search_result_free(lep_uidlist);
5193
5194                                 flagged = g_slist_concat(flagged, uidlist);
5195                         } else {
5196                                 imap_handle_error(SESSION(session), NULL, r);
5197                                 goto bail;
5198                         }
5199
5200                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5201                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED, NULL,
5202                                                          NULL, full_search ? NULL:imapset, &lep_uidlist);
5203                                 if (r == MAILIMAP_NO_ERROR) {
5204                                         GSList * uidlist;
5205
5206                                         uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5207                                         mailimap_search_result_free(lep_uidlist);
5208
5209                                         answered = g_slist_concat(answered, uidlist);
5210                                 } else {
5211                                         imap_handle_error(SESSION(session), NULL, r);
5212                                         goto bail;
5213                                 }
5214
5215                                 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
5216                                         r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED, NULL,
5217                                                                  NULL, full_search ? NULL:imapset, &lep_uidlist);
5218                                         if (r == MAILIMAP_NO_ERROR) {
5219                                                 GSList * uidlist;
5220
5221                                                 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5222                                                 mailimap_search_result_free(lep_uidlist);
5223
5224                                                 forwarded = g_slist_concat(forwarded, uidlist);
5225                                         } else {
5226                                                 imap_handle_error(SESSION(session), NULL, r);
5227                                                 goto bail;
5228                                         }
5229                                 }
5230
5231                                 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
5232                                         r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM, NULL,
5233                                                                  NULL, full_search ? NULL:imapset, &lep_uidlist);
5234                                         if (r == MAILIMAP_NO_ERROR) {
5235                                                 GSList * uidlist;
5236
5237                                                 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5238                                                 mailimap_search_result_free(lep_uidlist);
5239
5240                                                 spam = g_slist_concat(spam, uidlist);
5241                                         } else {
5242                                                 imap_handle_error(SESSION(session), NULL, r);
5243                                                 goto bail;
5244                                         }
5245                                 }
5246
5247                                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED, NULL,
5248                                                          NULL, full_search ? NULL:imapset, &lep_uidlist);
5249                                 if (r == MAILIMAP_NO_ERROR) {
5250                                         GSList * uidlist;
5251
5252                                         uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5253                                         mailimap_search_result_free(lep_uidlist);
5254
5255                                         deleted = g_slist_concat(deleted, uidlist);
5256                                 } else {
5257                                         imap_handle_error(SESSION(session), NULL, r);
5258                                         goto bail;
5259                                 }
5260                         }
5261                 }
5262
5263         } else {
5264                 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
5265                 if (r == MAILIMAP_NO_ERROR) {
5266                         flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5267                         tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5268                         imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
5269                         imap_fetch_uid_flags_list_free(lep_uidtab);
5270                 } else {
5271                         imap_handle_error(SESSION(session), NULL, r);
5272                         goto bail;
5273                 }
5274         }
5275
5276 bail:
5277         if (r == MAILIMAP_NO_ERROR)
5278                 unlock_session(session);
5279         
5280         for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
5281                 MsgInfo *msginfo;
5282                 MsgPermFlags flags, oldflags;
5283                 gboolean wasnew;
5284
5285                 msginfo = (MsgInfo *) elem->data;
5286                 flags = msginfo->flags.perm_flags;
5287                 wasnew = (flags & MSG_NEW);
5288                 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
5289
5290                 if (folder->account && folder->account->low_bandwidth) {
5291                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5292                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
5293                         } else {
5294                                 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
5295                         }
5296                         if (reverse_seen)
5297                                 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5298                         if (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
5299                                 if (!reverse_seen) {
5300                                         flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5301                                 } else {
5302                                         flags &= ~(MSG_UNREAD | MSG_NEW);
5303                                 }
5304                         }
5305
5306                         if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
5307                                 flags |= MSG_MARKED;
5308                         else
5309                                 flags &= ~MSG_MARKED;
5310
5311                         if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5312                                 if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
5313                                         flags |= MSG_REPLIED;
5314                                 else
5315                                         flags &= ~MSG_REPLIED;
5316                                 if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
5317                                         flags |= MSG_FORWARDED;
5318                                 else
5319                                         flags &= ~MSG_FORWARDED;
5320                                 if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
5321                                         flags |= MSG_SPAM;
5322                                 else
5323                                         flags &= ~MSG_SPAM;
5324                                 if (gslist_find_next_num(&deleted, msginfo->msgnum) == msginfo->msgnum)
5325                                         flags |= MSG_DELETED;
5326                                 else
5327                                         flags &= ~MSG_DELETED;
5328                         }
5329                 } else {
5330                         if (flags_hash != NULL) {
5331
5332                                 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash, 
5333                                                 GINT_TO_POINTER(msginfo->msgnum)));
5334                         }
5335
5336                         if ((flags & MSG_UNREAD) == 0)
5337                                 flags &= ~MSG_NEW;
5338                         else if (wasnew)
5339                                 flags |= MSG_NEW;
5340                         flags |= oldflags;
5341                         
5342                         if (tags_hash != NULL) {
5343                                 GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
5344                                 GSList *cur;
5345
5346                                 g_slist_free(msginfo->tags);
5347                                 msginfo->tags = NULL;
5348
5349                                 for (cur = tags; cur; cur = cur->next) {
5350                                         gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
5351                                         gint id = 0;
5352                                         id = tags_get_id_for_str(real_tag);
5353                                         if (id == -1) {
5354                                                 id = tags_add_tag(real_tag);
5355                                                 got_alien_tags = TRUE;
5356                                         }
5357                                         msginfo->tags = g_slist_append(
5358                                                                 msginfo->tags,
5359                                                                 GINT_TO_POINTER(id));
5360                                         g_free(real_tag);
5361                                 }
5362                                 slist_free_strings_full(tags);
5363                         }
5364                 }
5365
5366                 g_hash_table_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
5367         }
5368         
5369         if (got_alien_tags) {
5370                 tags_write_tags();
5371                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
5372         }
5373
5374         if (flags_hash)
5375                 g_hash_table_destroy(flags_hash);
5376         if (tags_hash)
5377                 g_hash_table_destroy(tags_hash);
5378
5379         imap_lep_set_free(seq_list);
5380         g_slist_free(flagged);
5381         g_slist_free(deleted);
5382         g_slist_free(answered);
5383         g_slist_free(forwarded);
5384         g_slist_free(spam);
5385         g_slist_free(unseen);
5386         g_slist_free(sorted_list);
5387
5388         stuff->done = TRUE;
5389         return GINT_TO_POINTER(0);
5390 }
5391
5392 static gint imap_get_flags(Folder *folder, FolderItem *item,
5393                            MsgInfoList *msginfo_list, GHashTable *msgflags)
5394 {
5395         gint result;
5396         get_flags_data *data = g_new0(get_flags_data, 1);
5397         data->done = FALSE;
5398         data->folder = folder;
5399         data->item = item;
5400         data->msginfo_list = msginfo_list;
5401         data->msgflags = msgflags;
5402         data->full_search = FALSE;
5403
5404         GSList *tmp = NULL, *cur;
5405         
5406         if (prefs_common.work_offline && 
5407             !inc_offline_should_override(FALSE,
5408                 _("Claws Mail needs network access in order "
5409                   "to access the IMAP server."))) {
5410                 g_free(data);
5411                 return -1;
5412         }
5413
5414         tmp = folder_item_get_msg_list(item);
5415
5416         if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
5417                 data->full_search = TRUE;
5418         
5419         for (cur = tmp; cur; cur = cur->next)
5420                 procmsg_msginfo_free((MsgInfo **)&(cur->data));
5421         
5422         g_slist_free(tmp);
5423
5424         result = GPOINTER_TO_INT(imap_get_flags_thread(data));
5425         
5426         g_free(data);
5427         return result;
5428
5429 }
5430
5431 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
5432 {
5433         gboolean flags_set = GPOINTER_TO_INT(user_data);
5434         gint flags_value = GPOINTER_TO_INT(key);
5435         hashtable_data *data = (hashtable_data *)value;
5436         IMAPFolderItem *_item = data->item;
5437         FolderItem *item = (FolderItem *)_item;
5438         gint ok = MAILIMAP_ERROR_BAD_STATE;
5439         IMAPSession *session = NULL;
5440         
5441         debug_print("getting session...\n");
5442         session = imap_session_get(item->folder);
5443
5444         data->msglist = g_slist_reverse(data->msglist);
5445         
5446         debug_print("IMAP %ssetting flags to %d for %d messages\n",
5447                 flags_set?"":"un",
5448                 flags_value,
5449                 g_slist_length(data->msglist));
5450         
5451         lock_session(session);
5452         if (session) {
5453                 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5454                          NULL, NULL, NULL, NULL, NULL, FALSE);
5455         }
5456         if (ok == MAILIMAP_NO_ERROR) {
5457                 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5458                         data->msglist, flags_value, NULL, flags_set);
5459         } else {
5460                 g_warning("can't select mailbox %s", item->path);
5461         }
5462
5463         if (!is_fatal(ok))
5464                 unlock_session(session);
5465
5466         g_slist_free(data->msglist);    
5467         g_free(data);
5468         return TRUE;
5469 }
5470
5471 static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
5472 {
5473         gboolean tags_set = GPOINTER_TO_INT(user_data);
5474         TagsData *data = (TagsData *)value;
5475         IMAPFolderItem *_item = data->item;
5476         FolderItem *item = (FolderItem *)_item;
5477         gchar *str = data->str;
5478         gint ok = MAILIMAP_ERROR_BAD_STATE;
5479         IMAPSession *session = NULL;
5480         
5481         debug_print("getting session...\n");
5482         session = imap_session_get(item->folder);
5483
5484         data->msglist = g_slist_reverse(data->msglist);
5485         
5486         debug_print("IMAP %ssetting tags %s for %d messages\n",
5487                 tags_set?"":"un",
5488                 str,
5489                 g_slist_length(data->msglist));
5490         
5491         lock_session(session);
5492         if (session) {
5493                 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5494                          NULL, NULL, NULL, NULL, NULL, FALSE);
5495         }
5496         if (ok == MAILIMAP_NO_ERROR) {
5497                 GSList list;
5498                 list.data = str;
5499                 list.next = NULL;
5500                 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5501                         data->msglist, 0, &list, tags_set);
5502         } else {
5503                 g_warning("can't select mailbox %s", item->path);
5504         }
5505
5506         if (!is_fatal(ok))
5507                 unlock_session(session);
5508
5509         g_slist_free(data->msglist);    
5510         g_free(data->str);
5511         g_free(data);
5512         return TRUE;
5513 }
5514
5515 static void process_hashtable(IMAPFolderItem *item)
5516 {
5517         if (item->flags_set_table) {
5518                 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
5519                 g_hash_table_destroy(item->flags_set_table);
5520                 item->flags_set_table = NULL;
5521         }
5522         if (item->flags_unset_table) {
5523                 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
5524                 g_hash_table_destroy(item->flags_unset_table);
5525                 item->flags_unset_table = NULL;
5526         }
5527         if (item->tags_set_table) {
5528                 g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
5529                 g_hash_table_destroy(item->tags_set_table);
5530                 item->tags_set_table = NULL;
5531         }
5532         if (item->tags_unset_table) {
5533                 g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
5534                 g_hash_table_destroy(item->tags_unset_table);
5535                 item->tags_unset_table = NULL;
5536         }
5537         
5538 }
5539
5540 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
5541 {
5542         IMAPFolderItem *item = (IMAPFolderItem *)_item;
5543         IMAPSession *session;
5544
5545         g_return_if_fail(item != NULL);
5546         
5547         if (item->batching == batch)
5548                 return;
5549         
5550         if (batch) {
5551                 item->batching = TRUE;
5552                 debug_print("IMAP switching to batch mode\n");
5553                 if (!item->flags_set_table) {
5554                         item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
5555                 }
5556                 if (!item->flags_unset_table) {
5557                         item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5558                 }
5559                 if (!item->tags_set_table) {
5560                         item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
5561                 }
5562                 if (!item->tags_unset_table) {
5563                         item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5564                 }
5565                 session = imap_session_get(folder);
5566                 if (session) {
5567                         imap_refresh_sensitivity(session);
5568                         session->sens_update_block = TRUE;
5569                 }
5570         } else {
5571                 debug_print("IMAP switching away from batch mode\n");
5572                 /* process stuff */
5573                 process_hashtable(item);
5574                 item->batching = FALSE;
5575                 session = imap_session_get(folder);
5576                 if (session) {
5577                         session->sens_update_block = FALSE;
5578                         imap_refresh_sensitivity(session);
5579                 }
5580         }
5581 }
5582
5583
5584
5585 /* data types conversion libetpan <-> claws */
5586
5587
5588
5589 #define ETPAN_IMAP_MB_MARKED      1
5590 #define ETPAN_IMAP_MB_UNMARKED    2
5591 #define ETPAN_IMAP_MB_NOSELECT    4
5592 #define ETPAN_IMAP_MB_NOINFERIORS 8
5593
5594 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
5595 {
5596   int flags;
5597   clistiter * cur;
5598   
5599   flags = 0;
5600   if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
5601     switch (imap_flags->mbf_sflag) {
5602     case MAILIMAP_MBX_LIST_SFLAG_MARKED:
5603       flags |= ETPAN_IMAP_MB_MARKED;
5604       break;
5605     case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
5606       flags |= ETPAN_IMAP_MB_NOSELECT;
5607       break;
5608     case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
5609       flags |= ETPAN_IMAP_MB_UNMARKED;
5610       break;
5611     }
5612   }
5613   
5614   if (imap_flags->mbf_oflags) {
5615     for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
5616         cur = clist_next(cur)) {
5617       struct mailimap_mbx_list_oflag * oflag;
5618
5619       oflag = clist_content(cur);
5620
5621       switch (oflag->of_type) {
5622       case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
5623         flags |= ETPAN_IMAP_MB_NOINFERIORS;
5624         break;
5625       }
5626     }
5627   }  
5628   return flags;
5629 }
5630
5631 static GSList * imap_list_from_lep(IMAPFolder * folder,
5632                                    clist * list, const gchar * real_path, gboolean all)
5633 {
5634         clistiter * iter;
5635         GSList * item_list = NULL, *llast = NULL;
5636         
5637         if (list) {
5638                 for(iter = clist_begin(list) ; iter != NULL ;
5639                     iter = clist_next(iter)) {
5640                         struct mailimap_mailbox_list * mb;
5641                         int flags;
5642                         char delimiter;
5643                         char * name;
5644                         char * dup_name;
5645                         gchar * base;
5646                         gchar * loc_name;
5647                         gchar * loc_path;
5648                         FolderItem *new_item;
5649
5650                         mb = clist_content(iter);
5651
5652                         if (mb == NULL)
5653                                 continue;
5654
5655                         flags = 0;
5656                         if (mb->mb_flag != NULL)
5657                                 flags = imap_flags_to_flags(mb->mb_flag);
5658
5659                         delimiter = mb->mb_delimiter;
5660                         name = mb->mb_name;
5661
5662                         dup_name = strdup(name);                
5663                         if (delimiter != '\0')
5664                                 subst_char(dup_name, delimiter, '/');
5665
5666                         base = g_path_get_basename(dup_name);
5667                         if (base[0] == '.') {
5668                                 g_free(base);
5669                                 free(dup_name);
5670                                 continue;
5671                         }
5672                         if (!all && path_cmp(name, real_path) == 0) {
5673                                 g_free(base);
5674                                 free(dup_name);
5675                                 continue;
5676                         }
5677
5678                         if (!all && dup_name[strlen(dup_name)-1] == '/') {
5679                                 g_free(base);
5680                                 free(dup_name);
5681                                 continue;
5682                         }
5683
5684                         loc_name = imap_modified_utf7_to_utf8(base, FALSE);
5685                         loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
5686
5687                         new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
5688                         if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
5689                                 new_item->no_sub = TRUE;
5690                         if (strcasecmp(dup_name, "INBOX") != 0 &&
5691                             ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
5692                                 new_item->no_select = TRUE;
5693
5694                         if (item_list == NULL)
5695                                 llast = item_list = g_slist_append(item_list, new_item);
5696                         else {
5697                                 llast = g_slist_append(llast, new_item);
5698                                 llast = llast->next;
5699                         }
5700                         debug_print("folder '%s' found.\n", loc_path);
5701                         g_free(base);
5702                         g_free(loc_path);
5703                         g_free(loc_name);
5704
5705                         free(dup_name);
5706                 }
5707         }       
5708         return item_list;
5709 }
5710
5711 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
5712 {
5713         GSList *sorted_list, *cur;
5714         guint first, last, next;
5715         GSList *ret_list = NULL, *llast = NULL;
5716         struct mailimap_set * current_set;
5717         unsigned int item_count;
5718         
5719         if (numlist == NULL)
5720                 return NULL;
5721         
5722         current_set = mailimap_set_new_empty();
5723         
5724         sorted_list = g_slist_copy(numlist);
5725         sorted_list = g_slist_sort(sorted_list, g_int_compare);
5726
5727         first = GPOINTER_TO_INT(sorted_list->data);
5728         
5729         item_count = 0;
5730         for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
5731                 if (GPOINTER_TO_INT(cur->data) == 0)
5732                         continue;
5733                 
5734                 item_count ++;
5735
5736                 last = GPOINTER_TO_INT(cur->data);
5737                 if (cur->next)
5738                         next = GPOINTER_TO_INT(cur->next->data);
5739                 else
5740                         next = 0;
5741
5742                 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
5743
5744                         struct mailimap_set_item * item;
5745                         item = mailimap_set_item_new(first, last);
5746                         mailimap_set_add(current_set, item);
5747                         
5748                         first = next;
5749
5750                         if (item_count >= folder->max_set_size) {
5751                                 if (ret_list == NULL)
5752                                         llast = ret_list = g_slist_append(ret_list,
5753                                                           current_set);
5754                                 else {
5755                                         llast = g_slist_append(llast, current_set);
5756                                         llast = llast->next;
5757                                 }
5758
5759                                 current_set = mailimap_set_new_empty();
5760                                 item_count = 0;
5761                         }
5762                 } 
5763         }
5764         
5765         if (clist_count(current_set->set_list) > 0) {
5766                 ret_list = g_slist_append(ret_list,
5767                                           current_set);
5768         }
5769         
5770         g_slist_free(sorted_list);
5771
5772         return ret_list;
5773 }
5774
5775 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
5776 {
5777         MsgNumberList *numlist = NULL;
5778         GSList *seq_list;
5779
5780         numlist = procmsg_get_number_list_for_msgs(msglist);
5781
5782         seq_list = imap_get_lep_set_from_numlist(folder, numlist);
5783         g_slist_free(numlist);
5784
5785         return seq_list;
5786 }
5787
5788 static GSList * imap_uid_list_from_lep(clist * list, gint* length)
5789 {
5790         clistiter * iter;
5791         GSList * result;
5792         gint len = 0;
5793         
5794         result = NULL;
5795         
5796         if (list) {
5797                 for(iter = clist_begin(list) ; iter != NULL ;
5798                     iter = clist_next(iter)) {
5799                         uint32_t * puid;
5800
5801                         puid = clist_content(iter);
5802                         result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5803                         len++;
5804                 }
5805                 result = g_slist_reverse(result);
5806         }
5807         if (length)
5808                 *length = len;
5809         return result;
5810 }
5811
5812 static GSList * imap_uid_list_from_lep_tab(carray * list)
5813 {
5814         unsigned int i;
5815         GSList * result;
5816         
5817         result = NULL;
5818         
5819         for(i = 0 ; i < carray_count(list) ; i ++) {
5820                 uint32_t * puid;
5821                 
5822                 puid = carray_get(list, i);
5823                 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5824         }
5825         result = g_slist_reverse(result);
5826         return result;
5827 }
5828
5829 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
5830                                                    GHashTable * hash,
5831                                                    GHashTable * tags_hash)
5832 {
5833         unsigned int i;
5834         
5835         for(i = 0 ; i < carray_count(list) ; i += 3) {
5836                 uint32_t * puid;
5837                 int * pflags;
5838                 GSList *tags;
5839                 
5840                 puid = carray_get(list, i);
5841                 pflags = carray_get(list, i + 1);
5842                 tags = carray_get(list, i + 2);
5843                 
5844                 g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
5845                 g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
5846         }
5847 }
5848
5849 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
5850                                        FolderItem *item)
5851 {
5852         MsgInfo *msginfo = NULL;
5853         guint32 uid = 0;
5854         goffset size = 0;
5855         MsgFlags flags = {0, 0};
5856
5857         if (info->headers == NULL)
5858                 return NULL;
5859
5860         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
5861         if (folder_has_parent_of_type(item, F_QUEUE)) {
5862                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
5863         } else if (folder_has_parent_of_type(item, F_DRAFT)) {
5864                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
5865         }
5866         flags.perm_flags = info->flags;
5867
5868         uid = info->uid;
5869         size = (goffset) info->size;
5870         msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
5871
5872         if (msginfo) {
5873                 msginfo->msgnum = uid;
5874                 msginfo->size = size;
5875         }
5876
5877         return msginfo;
5878 }
5879
5880 static void imap_lep_set_free(GSList *seq_list)
5881 {
5882         GSList * cur;
5883         
5884         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
5885                 struct mailimap_set * imapset;
5886                 
5887                 imapset = cur->data;
5888                 mailimap_set_free(imapset);
5889         }
5890         g_slist_free(seq_list);
5891 }
5892
5893 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
5894 {
5895         struct mailimap_flag_list * flag_list;
5896         GSList *cur = tags;
5897
5898         flag_list = mailimap_flag_list_new_empty();
5899         
5900         if (IMAP_IS_SEEN(flags))
5901                 mailimap_flag_list_add(flag_list,
5902                                        mailimap_flag_new_seen());
5903         if (IMAP_IS_ANSWERED(flags))
5904                 mailimap_flag_list_add(flag_list,
5905                                        mailimap_flag_new_answered());
5906         if (IMAP_IS_FLAGGED(flags))
5907                 mailimap_flag_list_add(flag_list,
5908                                        mailimap_flag_new_flagged());
5909         if (IMAP_IS_DELETED(flags))
5910                 mailimap_flag_list_add(flag_list,
5911                                        mailimap_flag_new_deleted());
5912         if (IMAP_IS_DRAFT(flags))
5913                 mailimap_flag_list_add(flag_list,
5914                                        mailimap_flag_new_draft());
5915         if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
5916                 mailimap_flag_list_add(flag_list,
5917                                        mailimap_flag_new_flag_keyword(strdup(RTAG_FORWARDED)));
5918         if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
5919                 mailimap_flag_list_add(flag_list,
5920                                        mailimap_flag_new_flag_keyword(strdup(RTAG_JUNK)));
5921         else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
5922                 mailimap_flag_list_add(flag_list,
5923                                        mailimap_flag_new_flag_keyword(strdup(RTAG_NON_JUNK)));
5924         
5925         for (; cur; cur = cur->next) {
5926                 gchar *enc_str = 
5927                         imap_utf8_to_modified_utf7(cur->data, TRUE);
5928                 g_strstrip(enc_str);
5929         
5930                 mailimap_flag_list_add(flag_list,
5931                         mailimap_flag_new_flag_keyword(enc_str));
5932         }
5933
5934         return flag_list;
5935 }
5936
5937 guint imap_folder_get_refcnt(Folder *folder)
5938 {
5939         return ((IMAPFolder *)folder)->refcnt;
5940 }
5941
5942 void imap_folder_ref(Folder *folder)
5943 {
5944         ((IMAPFolder *)folder)->refcnt++;
5945 }
5946
5947 void imap_disconnect_all(gboolean have_connectivity)
5948 {
5949         GList *list;
5950         gboolean short_timeout;
5951 #ifdef HAVE_NETWORKMANAGER_SUPPORT
5952         GError *error = NULL;
5953
5954         short_timeout = !networkmanager_is_online(&error);
5955         if(error) {
5956                 short_timeout = TRUE;
5957                 g_error_free(error);
5958         }
5959 #else
5960         short_timeout = TRUE;
5961 #endif
5962
5963         if(short_timeout)
5964                 imap_main_set_timeout(1);
5965
5966         for (list = account_get_list(); list != NULL; list = list->next) {
5967                 PrefsAccount *account = list->data;
5968                 if (account->protocol == A_IMAP4) {
5969                         RemoteFolder *folder = (RemoteFolder *)account->folder;
5970                         if (folder && folder->session) {
5971                                 if (imap_is_busy(FOLDER(folder)))
5972                                         imap_threaded_cancel(FOLDER(folder));
5973
5974                                 IMAPSession *session = (IMAPSession *)folder->session;
5975                                 if (have_connectivity)
5976                                         imap_threaded_disconnect(FOLDER(folder));
5977                                 SESSION(session)->state = SESSION_DISCONNECTED;
5978                                 SESSION(session)->sock = NULL;
5979                                 imap_safe_destroy(session);
5980                                 folder->session = NULL;
5981                         }
5982                 }
5983         }
5984
5985         if(short_timeout)
5986                 imap_main_set_timeout(prefs_common.io_timeout_secs);
5987 }
5988
5989 void imap_folder_unref(Folder *folder)
5990 {
5991         if (((IMAPFolder *)folder)->refcnt > 0)
5992                 ((IMAPFolder *)folder)->refcnt--;
5993 }
5994
5995 void imap_cancel_all(void)
5996 {
5997         GList *folderlist;
5998         GList *cur;
5999         
6000         folderlist = folder_get_list();
6001         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6002                 Folder *folder = (Folder *) cur->data;
6003
6004                 if (folder->klass == &imap_class) {
6005                         if (imap_is_busy(folder)) {
6006                                 IMAPSession *imap_session;
6007                                 RemoteFolder *rfolder;
6008                                 
6009                                 g_printerr("cancelled\n");
6010                                 imap_threaded_cancel(folder);
6011                                 rfolder = (RemoteFolder *) folder;
6012                                 imap_session = (IMAPSession *) rfolder->session;
6013                                 if (imap_session)
6014                                         imap_session->cancelled = 1;
6015                         }
6016                 }
6017         }
6018 }
6019
6020 gboolean imap_cancel_all_enabled(void)
6021 {
6022         GList *folderlist;
6023         GList *cur;
6024         
6025         folderlist = folder_get_list();
6026         for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6027                 Folder *folder = (Folder *) cur->data;
6028
6029                 if (folder->klass == &imap_class) {
6030                         if (imap_is_busy(folder)) {
6031                                 return TRUE;
6032                         }
6033                 }
6034         }
6035         
6036         return FALSE;
6037 }
6038
6039 static gboolean imap_is_busy(Folder *folder)
6040 {
6041         IMAPSession *imap_session;
6042         RemoteFolder *rfolder;
6043         
6044         rfolder = (RemoteFolder *) folder;
6045         imap_session = (IMAPSession *) rfolder->session;
6046         if (imap_session == NULL)
6047                 return FALSE;
6048         
6049         return imap_session->busy;
6050 }
6051
6052 #else /* HAVE_LIBETPAN */
6053
6054 static FolderClass imap_class;
6055
6056 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
6057 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
6058
6059 static Folder   *imap_folder_new        (const gchar    *name,
6060                                          const gchar    *path)
6061 {
6062         static gboolean missing_imap_warning = TRUE;
6063         if (missing_imap_warning) {
6064                 missing_imap_warning = FALSE;
6065                 alertpanel_error(
6066                         _("You have one or more IMAP accounts "
6067                           "defined. However this version of "
6068                           "Claws Mail has been built without "
6069                           "IMAP support; your IMAP account(s) are "
6070                           "disabled.\n\n"
6071                           "You probably need to "
6072                           "install libetpan and recompile "
6073                           "Claws Mail."));
6074         }
6075         return NULL;
6076 }
6077 static gint     imap_create_tree        (Folder         *folder)
6078 {
6079         return -1;
6080 }
6081 static FolderItem *imap_create_folder   (Folder         *folder,
6082                                          FolderItem     *parent,
6083                                          const gchar    *name)
6084 {
6085         return NULL;
6086 }
6087 static gint     imap_rename_folder      (Folder         *folder,
6088                                          FolderItem     *item, 
6089                                          const gchar    *name)
6090 {
6091         return -1;
6092 }
6093
6094 gchar imap_get_path_separator_for_item(FolderItem *item)
6095 {
6096         return '/';
6097 }
6098
6099 FolderClass *imap_get_class(void)
6100 {
6101         if (imap_class.idstr == NULL) {
6102                 imap_class.type = F_IMAP;
6103                 imap_class.idstr = "imap";
6104                 imap_class.uistr = "IMAP4";
6105
6106                 imap_class.new_folder = imap_folder_new;
6107                 imap_class.create_tree = imap_create_tree;
6108                 imap_class.create_folder = imap_create_folder;
6109                 imap_class.rename_folder = imap_rename_folder;
6110
6111                 imap_class.set_xml = folder_set_xml;
6112                 imap_class.get_xml = folder_get_xml;
6113                 imap_class.item_set_xml = imap_item_set_xml;
6114                 imap_class.item_get_xml = imap_item_get_xml;
6115                 /* nothing implemented */
6116         }
6117
6118         return &imap_class;
6119 }
6120
6121 void imap_disconnect_all(gboolean have_connectivity)
6122 {
6123 }
6124
6125 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
6126 {
6127         return -1;
6128 }
6129
6130 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
6131 {
6132         return NULL;
6133 }
6134
6135 void imap_cache_msg(FolderItem *item, gint msgnum)
6136 {
6137 }
6138
6139 void imap_cancel_all(void)
6140 {
6141 }
6142
6143 gboolean imap_cancel_all_enabled(void)
6144 {
6145         return FALSE;
6146 }
6147
6148 #endif
6149
6150 #ifdef HAVE_LIBETPAN
6151 static void imap_synchronise(FolderItem *item, gint days) 
6152 {
6153         if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
6154                 debug_print("%s already synced\n", item->path?item->path:item->name);
6155                 return;
6156         }
6157         debug_print("syncing %s\n", item->path?item->path:item->name);
6158         imap_gtk_synchronise(item, days);
6159         IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
6160 }
6161 #endif
6162
6163 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
6164 {
6165 #ifdef HAVE_LIBETPAN
6166         GList *cur;
6167 #endif
6168         folder_item_set_xml(folder, item, tag);
6169         
6170 #ifdef HAVE_LIBETPAN
6171         for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
6172                 XMLAttr *attr = (XMLAttr *) cur->data;
6173
6174                 if (!attr || !attr->name || !attr->value) continue;
6175                 if (!strcmp(attr->name, "uidnext"))
6176                         IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
6177                 if (!strcmp(attr->name, "last_sync"))
6178                         IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
6179                 if (!strcmp(attr->name, "last_change"))
6180                         IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
6181         }
6182         if (IMAP_FOLDER_ITEM(item)->last_change == 0)
6183                 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
6184 #endif
6185 }
6186
6187 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
6188 {
6189         XMLTag *tag;
6190
6191         tag = folder_item_get_xml(folder, item);
6192
6193 #ifdef HAVE_LIBETPAN
6194         xml_tag_add_attr(tag, xml_attr_new_int("uidnext", 
6195                         IMAP_FOLDER_ITEM(item)->uid_next));
6196         xml_tag_add_attr(tag, xml_attr_new_int("last_sync", 
6197                         IMAP_FOLDER_ITEM(item)->last_sync));
6198         xml_tag_add_attr(tag, xml_attr_new_int("last_change", 
6199                         IMAP_FOLDER_ITEM(item)->last_change));
6200
6201 #endif
6202         return tag;
6203 }
6204
6205 /* ===================================================================
6206  * UTF-7 conversion routines as in RFC 2192
6207  * =================================================================== 
6208  * These two functions from: 
6209  * libimap library.
6210  * Copyright (C) 2003-2004 Pawel Salek. */
6211
6212 /* UTF7 modified base64 alphabet */
6213 static char base64chars[] =
6214   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
6215 #define UNDEFINED 64
6216
6217 /* UTF16 definitions */
6218 #define UTF16MASK       0x03FFUL
6219 #define UTF16SHIFT      10
6220 #define UTF16BASE       0x10000UL
6221 #define UTF16HIGHSTART  0xD800UL
6222 #define UTF16HIGHEND    0xDBFFUL
6223 #define UTF16LOSTART    0xDC00UL
6224 #define UTF16LOEND      0xDFFFUL
6225
6226
6227 /* Convert an IMAP mailbox to a UTF-8 string.
6228  *  dst needs to have roughly 4 times the storage space of src
6229  *    Hex encoding can triple the size of the input
6230  *    UTF-7 can be slightly denser than UTF-8
6231  *     (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
6232  */
6233 char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
6234 {
6235   unsigned c, i, bitcount;
6236   unsigned long ucs4, utf16, bitbuf;
6237   unsigned char base64[256];
6238   const char *src;
6239   char *dst, *res  = g_malloc(2*strlen(mbox)+1);
6240
6241   dst = res;
6242   src = mbox;
6243   if(!dst) return NULL;
6244   /* initialize modified base64 decoding table */
6245   memset(base64, UNDEFINED, sizeof (base64));
6246   for (i = 0; i < sizeof (base64chars); ++i) {
6247     base64[(unsigned)base64chars[i]] = i;
6248   }
6249
6250   /* loop until end of string */
6251   while (*src != '\0') {
6252     c = *src++;
6253     /* deal with literal characters and &- */
6254     if (c != '&' || *src == '-') {
6255       /* encode literally */
6256       if (change_spaces && c == '_')
6257         *dst++ = ' ';
6258       else
6259         *dst++ = c;
6260       /* skip over the '-' if this is an &- sequence */
6261       if (c == '&') ++src;
6262     } else {
6263       /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
6264       bitbuf = 0;
6265       bitcount = 0;
6266       ucs4 = 0;
6267       while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
6268         ++src;
6269         bitbuf = (bitbuf << 6) | c;
6270         bitcount += 6;
6271         /* enough bits for a UTF-16 character? */
6272         if (bitcount >= 16) {
6273           bitcount -= 16;
6274           utf16 = (bitcount ? bitbuf >> bitcount
6275                    : bitbuf) & 0xffff;
6276           /* convert UTF16 to UCS4 */
6277           if
6278             (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
6279             ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
6280             continue;
6281           } else if
6282             (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
6283             ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
6284           } else {
6285             ucs4 = utf16;
6286           }
6287
6288           /* convert UTF-16 range of UCS4 to UTF-8 */
6289           if (ucs4 <= 0x7fUL) {
6290             dst[0] = ucs4;
6291             dst += 1;
6292           } else if (ucs4 <= 0x7ffUL) {
6293             dst[0] = 0xc0 | (ucs4 >> 6);
6294             dst[1] = 0x80 | (ucs4 & 0x3f);
6295             dst += 2;
6296           } else if (ucs4 <= 0xffffUL) {
6297             dst[0] = 0xe0 | (ucs4 >> 12);
6298             dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
6299             dst[2] = 0x80 | (ucs4 & 0x3f);
6300             dst += 3;
6301           } else {
6302             dst[0] = 0xf0 | (ucs4 >> 18);
6303             dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
6304             dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
6305             dst[3] = 0x80 | (ucs4 & 0x3f);
6306             dst += 4;
6307           }
6308         }
6309       }
6310       /* skip over trailing '-' in modified UTF-7 encoding */
6311       if (*src == '-') ++src;
6312     }
6313   }
6314   /* terminate destination string */
6315   *dst = '\0';
6316   return res;
6317 }
6318
6319 /* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
6320  *  dst should be about twice the length of src to deal with non-hex
6321  *  coded URLs
6322  */
6323 char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
6324 {
6325   unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
6326   unsigned long ucs4 = 0, bitbuf = 0;
6327
6328   /* initialize hex lookup table */
6329   char *dst, *res;
6330
6331   if (!src) return NULL;
6332
6333   res = malloc(2*strlen(src)+1);
6334   dst = res;
6335   if(!dst) return NULL;
6336
6337   utf7mode = 0;
6338   utf8total = 0;
6339   bitstogo = 0;
6340   utf8pos = 0;
6341   while ((c = (unsigned char)*src) != '\0') {
6342     ++src;
6343     /* normal character? */
6344     if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
6345       /* switch out of UTF-7 mode */
6346       if (utf7mode) {
6347         if (bitstogo) {
6348           *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6349         }
6350         *dst++ = '-';
6351         utf7mode = 0;
6352         utf8pos  = 0;
6353         bitstogo = 0;
6354         utf8total= 0;
6355       }
6356       if (change_spaces && c == ' ')
6357         *dst++ = '_';
6358       else
6359         *dst++ = c;
6360       /* encode '&' as '&-' */
6361       if (c == '&') {
6362         *dst++ = '-';
6363       }
6364       continue;
6365     }
6366     /* switch to UTF-7 mode */
6367     if (!utf7mode) {
6368       *dst++ = '&';
6369       utf7mode = 1;
6370     }
6371     /* Encode US-ASCII characters as themselves */
6372     if (c < 0x80) {
6373       ucs4 = c;
6374     } else if (utf8total) {
6375       /* save UTF8 bits into UCS4 */
6376       ucs4 = (ucs4 << 6) | (c & 0x3FUL);
6377       if (++utf8pos < utf8total) {
6378         continue;
6379       }
6380     } else {
6381       utf8pos = 1;
6382       if (c < 0xE0) {
6383         utf8total = 2;
6384         ucs4 = c & 0x1F;
6385       } else if (c < 0xF0) {
6386         utf8total = 3;
6387         ucs4 = c & 0x0F;
6388       } else {
6389         /* NOTE: can't convert UTF8 sequences longer than 4 */
6390         utf8total = 4;
6391         ucs4 = c & 0x03;
6392       }
6393       continue;
6394     }
6395     /* loop to split ucs4 into two utf16 chars if necessary */
6396     utf8total = 0;
6397     do {
6398       if (ucs4 >= UTF16BASE) {
6399         ucs4 -= UTF16BASE;
6400         bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
6401                                    + UTF16HIGHSTART);
6402         ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
6403         utf16flag = 1;
6404       } else {
6405         bitbuf = (bitbuf << 16) | ucs4;
6406         utf16flag = 0;
6407       }
6408       bitstogo += 16;
6409       /* spew out base64 */
6410       while (bitstogo >= 6) {
6411         bitstogo -= 6;
6412         *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
6413                               : bitbuf)
6414                              & 0x3F];
6415       }
6416     } while (utf16flag);
6417   }
6418   /* if in UTF-7 mode, finish in ASCII */
6419   if (utf7mode) {
6420     if (bitstogo) {
6421       *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6422     }
6423     *dst++ = '-';
6424   }
6425   /* tie off string */
6426   *dst = '\0';
6427   return res;
6428 }