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