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