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