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