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