71e316a078f5f868cac568b3c526693ca76fb8d9
[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 (defined(USE_OPENSSL) || defined (USE_GNUTLS))
49 #  include "ssl.h"
50 #endif
51
52 #include "folder.h"
53 #include "session.h"
54 #include "procmsg.h"
55 #include "socket.h"
56 #include "recv.h"
57 #include "procheader.h"
58 #include "prefs_account.h"
59 #include "codeconv.h"
60 #include "md5.h"
61 #include "base64.h"
62 #include "utils.h"
63 #include "prefs_common.h"
64 #include "inputdialog.h"
65 #include "log.h"
66 #include "remotefolder.h"
67 #include "claws.h"
68 #include "statusbar.h"
69 #include "msgcache.h"
70 #include "imap-thread.h"
71 #include "account.h"
72 #include "tags.h"
73 #include "main.h"
74
75 typedef struct _IMAPFolder      IMAPFolder;
76 typedef struct _IMAPSession     IMAPSession;
77 typedef struct _IMAPNameSpace   IMAPNameSpace;
78 typedef struct _IMAPFolderItem  IMAPFolderItem;
79
80 #include "prefs_account.h"
81
82 #define IMAP_FOLDER(obj)        ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj)   ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj)       ((IMAPSession *)obj)
85
86 struct _IMAPFolder
87 {
88         RemoteFolder rfolder;
89
90         /* list of IMAPNameSpace */
91         GList *ns_personal;
92         GList *ns_others;
93         GList *ns_shared;
94         gchar last_seen_separator;
95         guint refcnt;
96         guint max_set_size;
97 };
98
99 struct _IMAPSession
100 {
101         Session session;
102
103         gboolean authenticated;
104
105         GSList *capability;
106         gboolean uidplus;
107
108         gchar *mbox;
109         guint cmd_count;
110
111         /* CLAWS */
112         gboolean folder_content_changed;
113         guint exists;
114         guint recent;
115         guint expunge;
116         guint unseen;
117         guint uid_validity;
118         guint uid_next;
119
120         Folder * folder;
121         gboolean busy;
122         gboolean cancelled;
123         gboolean sens_update_block;
124 };
125
126 struct _IMAPNameSpace
127 {
128         gchar *name;
129         gchar separator;
130 };
131
132 #define IMAPBUFSIZE     8192
133
134 #define IMAP_IS_SEEN(flags)     ((flags & IMAP_FLAG_SEEN) != 0)
135 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
136 #define IMAP_IS_FLAGGED(flags)  ((flags & IMAP_FLAG_FLAGGED) != 0)
137 #define IMAP_IS_DELETED(flags)  ((flags & IMAP_FLAG_DELETED) != 0)
138 #define IMAP_IS_DRAFT(flags)    ((flags & IMAP_FLAG_DRAFT) != 0)
139 #define IMAP_IS_FORWARDED(flags)        ((flags & IMAP_FLAG_FORWARDED) != 0)
140 #define IMAP_IS_SPAM(flags)     ((flags & IMAP_FLAG_SPAM) != 0)
141 #define IMAP_IS_HAM(flags)      ((flags & IMAP_FLAG_HAM) != 0)
142
143
144 #define IMAP4_PORT      143
145 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
146 #define IMAPS_PORT      993
147 #endif
148
149 #define IMAP_CMD_LIMIT  1000
150
151 enum {
152         ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
153         ITEM_CAN_CREATE_FLAGS,
154         ITEM_CANNOT_CREATE_FLAGS
155 };
156
157 struct _IMAPFolderItem
158 {
159         FolderItem item;
160
161         guint lastuid;
162         guint uid_next;
163         GSList *uid_list;
164         gboolean batching;
165
166         GHashTable *flags_set_table;
167         GHashTable *flags_unset_table;
168         guint32 last_change;
169         guint32 last_sync;
170         gboolean should_update;
171         gboolean should_trash_cache;
172         gint can_create_flags;
173
174         GHashTable *tags_set_table;
175         GHashTable *tags_unset_table;
176         GSList *ok_flags;
177
178 };
179
180 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
181 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
182
183 static void imap_folder_init            (Folder         *folder,
184                                          const gchar    *name,
185                                          const gchar    *path);
186
187 static Folder   *imap_folder_new        (const gchar    *name,
188                                          const gchar    *path);
189 static void      imap_folder_destroy    (Folder         *folder);
190
191 static IMAPSession *imap_session_new    (Folder         *folder,
192                                          const PrefsAccount     *account);
193 static gint     imap_session_authenticate(IMAPSession   *session,
194                                           PrefsAccount  *account);
195 static void     imap_session_destroy    (Session        *session);
196
197 static gchar   *imap_fetch_msg          (Folder         *folder, 
198                                          FolderItem     *item, 
199                                          gint            uid);
200 static gchar   *imap_fetch_msg_full     (Folder         *folder, 
201                                          FolderItem     *item, 
202                                          gint            uid,
203                                          gboolean        headers,
204                                          gboolean        body);
205 static void     imap_remove_cached_msg  (Folder         *folder, 
206                                          FolderItem     *item, 
207                                          MsgInfo        *msginfo);
208 static gint     imap_add_msg            (Folder         *folder,
209                                          FolderItem     *dest,
210                                          const gchar    *file, 
211                                          MsgFlags       *flags);
212 static gint     imap_add_msgs           (Folder         *folder, 
213                                          FolderItem     *dest,
214                                          GSList         *file_list,
215                                          GRelation      *relation);
216
217 static gint     imap_copy_msg           (Folder         *folder,
218                                          FolderItem     *dest, 
219                                          MsgInfo        *msginfo);
220 static gint     imap_copy_msgs          (Folder         *folder, 
221                                          FolderItem     *dest, 
222                                          MsgInfoList    *msglist, 
223                                          GRelation      *relation);
224
225 static gint     imap_remove_msg         (Folder         *folder, 
226                                          FolderItem     *item, 
227                                          gint            uid);
228 static gint     imap_remove_msgs        (Folder         *folder, 
229                                          FolderItem     *dest, 
230                                          MsgInfoList    *msglist, 
231                                          GRelation      *relation);
232 static gint     imap_remove_all_msg     (Folder         *folder, 
233                                          FolderItem     *item);
234
235 static gboolean imap_is_msg_changed     (Folder         *folder,
236                                          FolderItem     *item, 
237                                          MsgInfo        *msginfo);
238
239 static gint     imap_close              (Folder         *folder, 
240                                          FolderItem     *item);
241
242 static gint     imap_scan_tree          (Folder         *folder);
243
244 static gint     imap_create_tree        (Folder         *folder);
245
246 static FolderItem *imap_create_folder   (Folder         *folder,
247                                          FolderItem     *parent,
248                                          const gchar    *name);
249 static gint     imap_rename_folder      (Folder         *folder,
250                                          FolderItem     *item, 
251                                          const gchar    *name);
252 static gint     imap_remove_folder      (Folder         *folder, 
253                                          FolderItem     *item);
254
255 static FolderItem *imap_folder_item_new (Folder         *folder);
256 static void imap_folder_item_destroy    (Folder         *folder,
257                                          FolderItem     *item);
258
259 static IMAPSession *imap_session_get    (Folder         *folder);
260
261 static gint imap_auth                   (IMAPSession    *session,
262                                          const gchar    *user,
263                                          const gchar    *pass,
264                                          IMAPAuthType    type);
265
266 static gint imap_scan_tree_recursive    (IMAPSession    *session,
267                                          FolderItem     *item,
268                                          gboolean        subs_only);
269
270 static void imap_create_missing_folders (Folder         *folder);
271 static FolderItem *imap_create_special_folder
272                                         (Folder                 *folder,
273                                          SpecialFolderItemType   stype,
274                                          const gchar            *name);
275
276 static gint imap_do_copy_msgs           (Folder         *folder,
277                                          FolderItem     *dest,
278                                          MsgInfoList    *msglist,
279                                          GRelation      *relation);
280
281 static void imap_delete_all_cached_messages     (FolderItem     *item);
282 static void imap_set_batch              (Folder         *folder,
283                                          FolderItem     *item,
284                                          gboolean        batch);
285 static gint imap_set_message_flags      (IMAPSession    *session,
286                                          IMAPFolderItem *item,
287                                          MsgNumberList  *numlist,
288                                          IMAPFlags       flags,
289                                          GSList         *tags,
290                                          gboolean        is_set);
291 static gint imap_select                 (IMAPSession    *session,
292                                          IMAPFolder     *folder,
293                                          FolderItem     *item,
294                                          gint           *exists,
295                                          gint           *recent,
296                                          gint           *unseen,
297                                          guint32        *uid_validity,
298                                          gint           *can_create_flags,
299                                          gboolean        block);
300 static gint imap_status                 (IMAPSession    *session,
301                                          IMAPFolder     *folder,
302                                          const gchar    *path,
303                                          IMAPFolderItem *item,
304                                          gint           *messages,
305                                          guint32        *uid_next,
306                                          guint32        *uid_validity,
307                                          gint           *unseen,
308                                          gboolean        block);
309 static void     imap_commit_tags        (FolderItem     *item, 
310                                          MsgInfo        *msginfo,
311                                          GSList         *set_tags,
312                                          GSList         *unset_tags);
313
314 static gchar imap_get_path_separator            (IMAPSession    *session,
315                                                  IMAPFolder     *folder,
316                                                  const gchar    *path,
317                                                  gint           *ok);
318 static gchar *imap_get_real_path                (IMAPSession    *session,
319                                                  IMAPFolder     *folder,
320                                                  const gchar    *path,
321                                                  gint           *ok);
322 #ifdef HAVE_LIBETPAN
323 static void imap_synchronise            (FolderItem     *item, gint days);
324 #endif
325 static gboolean imap_is_busy            (Folder *folder);
326
327 static void imap_free_capabilities      (IMAPSession    *session);
328
329 /* low-level IMAP4rev1 commands */
330 static gint imap_cmd_login      (IMAPSession    *session,
331                                  const gchar    *user,
332                                  const gchar    *pass,
333                                  const gchar    *type);
334 static gint imap_cmd_noop       (IMAPSession    *session);
335 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
336 static gint imap_cmd_starttls   (IMAPSession    *session);
337 #endif
338 static gint imap_cmd_select     (IMAPSession    *session,
339                                  const gchar    *folder,
340                                  gint           *exists,
341                                  gint           *recent,
342                                  gint           *unseen,
343                                  guint32        *uid_validity,
344                                  gint           *can_create_flags,
345                                  GSList         **ok_flags,
346                                  gboolean        block);
347 static gint imap_cmd_close      (IMAPSession    *session);
348 static gint imap_cmd_examine    (IMAPSession    *session,
349                                  const gchar    *folder,
350                                  gint           *exists,
351                                  gint           *recent,
352                                  gint           *unseen,
353                                  guint32        *uid_validity,
354                                  gboolean        block);
355 static gint imap_cmd_create     (IMAPSession    *sock,
356                                  const gchar    *folder);
357 static gint imap_cmd_rename     (IMAPSession    *sock,
358                                  const gchar    *oldfolder,
359                                  const gchar    *newfolder);
360 static gint imap_cmd_delete     (IMAPSession    *session,
361                                  const gchar    *folder);
362 static gint imap_cmd_fetch      (IMAPSession    *sock,
363                                  guint32         uid,
364                                  const gchar    *filename,
365                                  gboolean        headers,
366                                  gboolean        body);
367 static gint imap_cmd_append     (IMAPSession    *session,
368                                  IMAPFolderItem *item,
369                                  const gchar    *destfolder,
370                                  const gchar    *file,
371                                  IMAPFlags       flags,
372                                  guint32        *new_uid);
373 static gint imap_cmd_copy       (IMAPSession *session,
374                                  struct mailimap_set * set,
375                                  const gchar *destfolder,
376                                  GRelation *uid_mapping,
377                                  struct mailimap_set ** source,
378                                  struct mailimap_set ** dest);
379 static gint imap_cmd_store      (IMAPSession    *session,
380                                  IMAPFolderItem *item,
381                                  struct mailimap_set * set,
382                                  IMAPFlags flags,
383                                  GSList *tags,
384                                  int do_add);
385 static gint imap_cmd_expunge    (IMAPSession    *session);
386
387 static void imap_path_separator_subst           (gchar          *str,
388                                                  gchar           separator);
389
390 static gboolean imap_rename_folder_func         (GNode          *node,
391                                                  gpointer        data);
392 static gint imap_get_num_list                   (Folder         *folder,
393                                                  FolderItem     *item,
394                                                  GSList        **list,
395                                                  gboolean       *old_uids_valid);
396 static GSList *imap_get_msginfos                (Folder         *folder,
397                                                  FolderItem     *item,
398                                                  GSList         *msgnum_list);
399 static MsgInfo *imap_get_msginfo                (Folder         *folder,
400                                                  FolderItem     *item,
401                                                  gint            num);
402 static gboolean imap_scan_required              (Folder         *folder,
403                                                  FolderItem     *item);
404 static void imap_change_flags                   (Folder         *folder,
405                                                  FolderItem     *item,
406                                                  MsgInfo        *msginfo,
407                                                  MsgPermFlags    newflags);
408 static gint imap_get_flags                      (Folder         *folder,
409                                                  FolderItem     *item,
410                                                  MsgInfoList    *msglist,
411                                                  GRelation      *msgflags);
412 static gchar *imap_folder_get_path              (Folder         *folder);
413 static gchar *imap_item_get_path                (Folder         *folder,
414                                                  FolderItem     *item);
415 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
416
417
418 /* data types conversion libetpan <-> claws */
419 static GSList * imap_list_from_lep(IMAPFolder * folder,
420                                    clist * list, const gchar * real_path, gboolean all);
421 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
422 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
423 static GSList * imap_uid_list_from_lep(clist * list);
424 static GSList * imap_uid_list_from_lep_tab(carray * list);
425 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
426                                                    GHashTable * hash,
427                                                    GHashTable *tags_hash);
428 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
429                                        FolderItem *item);
430 static void imap_lep_set_free(GSList *seq_list);
431 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
432
433 typedef struct _hashtable_data {
434         GSList *msglist;
435         IMAPFolderItem *item;
436 } hashtable_data;
437
438 static FolderClass imap_class;
439
440 FolderClass *imap_get_class(void)
441 {
442         if (imap_class.idstr == NULL) {
443                 imap_class.type = F_IMAP;
444                 imap_class.idstr = "imap";
445                 imap_class.uistr = "IMAP4";
446
447                 /* Folder functions */
448                 imap_class.new_folder = imap_folder_new;
449                 imap_class.destroy_folder = imap_folder_destroy;
450                 imap_class.scan_tree = imap_scan_tree;
451                 imap_class.create_tree = imap_create_tree;
452
453                 /* FolderItem functions */
454                 imap_class.item_new = imap_folder_item_new;
455                 imap_class.item_destroy = imap_folder_item_destroy;
456                 imap_class.item_get_path = imap_item_get_path;
457                 imap_class.create_folder = imap_create_folder;
458                 imap_class.rename_folder = imap_rename_folder;
459                 imap_class.remove_folder = imap_remove_folder;
460                 imap_class.close = imap_close;
461                 imap_class.get_num_list = imap_get_num_list;
462                 imap_class.scan_required = imap_scan_required;
463                 imap_class.set_xml = folder_set_xml;
464                 imap_class.get_xml = folder_get_xml;
465                 imap_class.item_set_xml = imap_item_set_xml;
466                 imap_class.item_get_xml = imap_item_get_xml;
467
468                 /* Message functions */
469                 imap_class.get_msginfo = imap_get_msginfo;
470                 imap_class.get_msginfos = imap_get_msginfos;
471                 imap_class.fetch_msg = imap_fetch_msg;
472                 imap_class.fetch_msg_full = imap_fetch_msg_full;
473                 imap_class.add_msg = imap_add_msg;
474                 imap_class.add_msgs = imap_add_msgs;
475                 imap_class.copy_msg = imap_copy_msg;
476                 imap_class.copy_msgs = imap_copy_msgs;
477                 imap_class.remove_msg = imap_remove_msg;
478                 imap_class.remove_msgs = imap_remove_msgs;
479                 imap_class.remove_all_msg = imap_remove_all_msg;
480                 imap_class.is_msg_changed = imap_is_msg_changed;
481                 imap_class.change_flags = imap_change_flags;
482                 imap_class.get_flags = imap_get_flags;
483                 imap_class.set_batch = imap_set_batch;
484                 imap_class.synchronise = imap_synchronise;
485                 imap_class.remove_cached_msg = imap_remove_cached_msg;
486                 imap_class.commit_tags = imap_commit_tags;
487 #ifdef USE_PTREAD
488                 pthread_mutex_init(&imap_mutex, NULL);
489 #endif
490         }
491         
492         return &imap_class;
493 }
494
495 static void imap_refresh_sensitivity (IMAPSession *session)
496 {
497         MainWindow *mainwin;
498
499         if (session->sens_update_block)
500                 return;
501         mainwin = mainwindow_get_mainwindow();
502         if (mainwin) {
503                 toolbar_main_set_sensitive(mainwin);
504                 main_window_set_menu_sensitive(mainwin);
505         }
506 }
507
508 static void lock_session(IMAPSession *session)
509 {
510         if (session) {
511                 debug_print("locking session %p (%d)\n", session, session->busy);
512                 if (session->busy)
513                         debug_print("         SESSION WAS LOCKED !!      \n");
514                 session->busy = TRUE;
515                 imap_refresh_sensitivity(session);
516         } else {
517                 debug_print("can't lock null session\n");
518         }
519 }
520
521 static void unlock_session(IMAPSession *session)
522 {
523         if (session) {
524                 debug_print("unlocking session %p\n", session);
525                 session->busy = FALSE;
526                 imap_refresh_sensitivity(session);
527         } else {
528                 debug_print("can't unlock null session\n");
529         }
530 }
531
532 static void imap_disc_session_destroy(IMAPSession *session)
533 {
534         RemoteFolder *rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
535         
536         if (!rfolder)
537                 return;
538         if (!session)
539                 return;
540         log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
541         SESSION(session)->state = SESSION_DISCONNECTED;
542         SESSION(session)->sock = NULL;
543 }
544
545 static gboolean is_fatal(int libetpan_errcode)
546 {
547         switch(libetpan_errcode) {
548         case MAILIMAP_ERROR_STREAM:
549         case MAILIMAP_ERROR_PROTOCOL:
550         case MAILIMAP_ERROR_PARSE:
551         case MAILIMAP_ERROR_BAD_STATE:
552                 return TRUE;
553         default:
554                 return FALSE;
555         }
556 }
557
558 static void imap_handle_error(Session *session, int libetpan_errcode)
559 {
560         switch(libetpan_errcode) {
561         case MAILIMAP_NO_ERROR:
562                 return;
563         case MAILIMAP_NO_ERROR_AUTHENTICATED:
564                 log_warning(LOG_PROTOCOL, _("IMAP error: authenticated\n"));
565                 break;
566         case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
567                 log_warning(LOG_PROTOCOL, _("IMAP error: not authenticated\n"));
568                 break;
569         case MAILIMAP_ERROR_BAD_STATE:
570                 log_warning(LOG_PROTOCOL, _("IMAP error: bad state\n"));
571                 break;
572         case MAILIMAP_ERROR_STREAM:
573                 log_warning(LOG_PROTOCOL, _("IMAP error: stream error\n"));
574                 break;
575         case MAILIMAP_ERROR_PARSE:
576                 log_warning(LOG_PROTOCOL, _("IMAP error: parse error "
577                                             "(very probably non-RFC compliance from the server)\n"));
578                 break;
579         case MAILIMAP_ERROR_CONNECTION_REFUSED:
580                 log_warning(LOG_PROTOCOL, _("IMAP error: connection refused\n"));
581                 break;
582         case MAILIMAP_ERROR_MEMORY:
583                 log_warning(LOG_PROTOCOL, _("IMAP error: memory error\n"));
584                 break;
585         case MAILIMAP_ERROR_FATAL:
586                 log_warning(LOG_PROTOCOL, _("IMAP error: fatal error\n"));
587                 break;
588         case MAILIMAP_ERROR_PROTOCOL:
589                 log_warning(LOG_PROTOCOL, _("IMAP error: protocol error"
590                                             "(very probably non-RFC compliance from the server)\n"));
591                 break;
592         case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
593                 log_warning(LOG_PROTOCOL, _("IMAP error: connection not accepted\n"));
594                 break;
595         case MAILIMAP_ERROR_APPEND:
596                 log_warning(LOG_PROTOCOL, _("IMAP error: APPEND error\n"));
597                 break;
598         case MAILIMAP_ERROR_NOOP:
599                 log_warning(LOG_PROTOCOL, _("IMAP error: NOOP error\n"));
600                 break;
601         case MAILIMAP_ERROR_LOGOUT:
602                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGOUT error\n"));
603                 break;
604         case MAILIMAP_ERROR_CAPABILITY:
605                 log_warning(LOG_PROTOCOL, _("IMAP error: CAPABILITY error\n"));
606                 break;
607         case MAILIMAP_ERROR_CHECK:
608                 log_warning(LOG_PROTOCOL, _("IMAP error: CHECK error\n"));
609                 break;
610         case MAILIMAP_ERROR_CLOSE:
611                 log_warning(LOG_PROTOCOL, _("IMAP error: CLOSE error\n"));
612                 break;
613         case MAILIMAP_ERROR_EXPUNGE:
614                 log_warning(LOG_PROTOCOL, _("IMAP error: EXPUNGE error\n"));
615                 break;
616         case MAILIMAP_ERROR_COPY:
617                 log_warning(LOG_PROTOCOL, _("IMAP error: COPY error\n"));
618                 break;
619         case MAILIMAP_ERROR_UID_COPY:
620                 log_warning(LOG_PROTOCOL, _("IMAP error: UID COPY error\n"));
621                 break;
622         case MAILIMAP_ERROR_CREATE:
623                 log_warning(LOG_PROTOCOL, _("IMAP error: CREATE error\n"));
624                 break;
625         case MAILIMAP_ERROR_DELETE:
626                 log_warning(LOG_PROTOCOL, _("IMAP error: DELETE error\n"));
627                 break;
628         case MAILIMAP_ERROR_EXAMINE:
629                 log_warning(LOG_PROTOCOL, _("IMAP error: EXAMINE error\n"));
630                 break;
631         case MAILIMAP_ERROR_FETCH:
632                 log_warning(LOG_PROTOCOL, _("IMAP error: FETCH error\n"));
633                 break;
634         case MAILIMAP_ERROR_UID_FETCH:
635                 log_warning(LOG_PROTOCOL, _("IMAP error: UID FETCH error\n"));
636                 break;
637         case MAILIMAP_ERROR_LIST:
638                 log_warning(LOG_PROTOCOL, _("IMAP error: LIST error\n"));
639                 break;
640         case MAILIMAP_ERROR_LOGIN:
641                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGIN error\n"));
642                 break;
643         case MAILIMAP_ERROR_LSUB:
644                 log_warning(LOG_PROTOCOL, _("IMAP error: LSUB error\n"));
645                 break;
646         case MAILIMAP_ERROR_RENAME:
647                 log_warning(LOG_PROTOCOL, _("IMAP error: RENAME error\n"));
648                 break;
649         case MAILIMAP_ERROR_SEARCH:
650                 log_warning(LOG_PROTOCOL, _("IMAP error: SEARCH error\n"));
651                 break;
652         case MAILIMAP_ERROR_UID_SEARCH:
653                 log_warning(LOG_PROTOCOL, _("IMAP error: UID SEARCH error\n"));
654                 break;
655         case MAILIMAP_ERROR_SELECT:
656                 log_warning(LOG_PROTOCOL, _("IMAP error: SELECT error\n"));
657                 break;
658         case MAILIMAP_ERROR_STATUS:
659                 log_warning(LOG_PROTOCOL, _("IMAP error: STATUS error\n"));
660                 break;
661         case MAILIMAP_ERROR_STORE:
662                 log_warning(LOG_PROTOCOL, _("IMAP error: STORE error\n"));
663                 break;
664         case MAILIMAP_ERROR_UID_STORE:
665                 log_warning(LOG_PROTOCOL, _("IMAP error: UID STORE error\n"));
666                 break;
667         case MAILIMAP_ERROR_SUBSCRIBE:
668                 log_warning(LOG_PROTOCOL, _("IMAP error: SUBSCRIBE error\n"));
669                 break;
670         case MAILIMAP_ERROR_UNSUBSCRIBE:
671                 log_warning(LOG_PROTOCOL, _("IMAP error: UNSUBSCRIBE error\n"));
672                 break;
673         case MAILIMAP_ERROR_STARTTLS:
674                 log_warning(LOG_PROTOCOL, _("IMAP error: STARTTLS error\n"));
675                 break;
676         case MAILIMAP_ERROR_INVAL:
677                 log_warning(LOG_PROTOCOL, _("IMAP error: INVAL error\n"));
678                 break;
679         case MAILIMAP_ERROR_EXTENSION:
680                 log_warning(LOG_PROTOCOL, _("IMAP error: EXTENSION error\n"));
681                 break;
682         case MAILIMAP_ERROR_SASL:
683                 log_warning(LOG_PROTOCOL, _("IMAP error: SASL error\n"));
684                 break;
685 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
686         case MAILIMAP_ERROR_SSL:
687                 log_warning(LOG_PROTOCOL, _("IMAP error: SSL error\n"));
688                 break;
689 #endif
690         default:
691                 log_warning(LOG_PROTOCOL, _("IMAP error: Unknown error [%d]\n"),
692                         libetpan_errcode);
693                 break;
694         }
695
696         if (session && is_fatal(libetpan_errcode)) {
697                 imap_disc_session_destroy(IMAP_SESSION(session));
698         } else if (session && !is_fatal(libetpan_errcode)) {
699                 if (IMAP_SESSION(session)->busy)
700                         unlock_session(IMAP_SESSION(session));
701         }
702 }
703
704 static Folder *imap_folder_new(const gchar *name, const gchar *path)
705 {
706         Folder *folder;
707
708         folder = (Folder *)g_new0(IMAPFolder, 1);
709         folder->klass = &imap_class;
710         imap_folder_init(folder, name, path);
711
712         return folder;
713 }
714
715 static void imap_folder_destroy(Folder *folder)
716 {
717         while (imap_folder_get_refcnt(folder) > 0)
718                 gtk_main_iteration();
719         
720         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
721         imap_done(folder);
722 }
723
724 static void imap_folder_init(Folder *folder, const gchar *name,
725                              const gchar *path)
726 {
727         folder_remote_folder_init((Folder *)folder, name, path);
728         IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
729 }
730
731 static FolderItem *imap_folder_item_new(Folder *folder)
732 {
733         IMAPFolderItem *item;
734         
735         item = g_new0(IMAPFolderItem, 1);
736         item->lastuid = 0;
737         item->uid_next = 0;
738         item->uid_list = NULL;
739
740         return (FolderItem *)item;
741 }
742
743 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
744 {
745         IMAPFolderItem *item = (IMAPFolderItem *)_item;
746
747         g_return_if_fail(item != NULL);
748         g_slist_free(item->uid_list);
749
750         g_free(_item);
751 }
752
753 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
754 {
755         IMAPFolderItem *item = (IMAPFolderItem *)node->data;
756         
757         item->lastuid = 0;
758         g_slist_free(item->uid_list);
759         item->uid_list = NULL;
760         
761         return FALSE;
762 }
763
764 static void imap_reset_uid_lists(Folder *folder)
765 {
766         if(folder->node == NULL)
767                 return;
768         
769         /* Destroy all uid lists and rest last uid */
770         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
771 }
772
773 static int imap_get_capabilities(IMAPSession *session)
774 {
775         struct mailimap_capability_data *capabilities = NULL;
776         clistiter *cur;
777         int result = -1;
778
779         if (session->capability != NULL)
780                 return MAILIMAP_NO_ERROR;
781
782         capabilities = imap_threaded_capability(session->folder, &result);
783
784         if (result != MAILIMAP_NO_ERROR) {
785                 return result;
786         }
787
788         if (capabilities == NULL) {
789                 return MAILIMAP_NO_ERROR;
790         }
791
792         for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
793             cur = clist_next(cur)) {
794                 struct mailimap_capability * cap = 
795                         clist_content(cur);
796                 if (!cap || cap->cap_data.cap_name == NULL)
797                         continue;
798                 session->capability = g_slist_append
799                                 (session->capability,
800                                  g_strdup(cap->cap_data.cap_name));
801                 debug_print("got capa %s\n", cap->cap_data.cap_name);
802         }
803         mailimap_capability_data_free(capabilities);
804         return MAILIMAP_NO_ERROR;
805 }
806
807 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
808 {
809         GSList *cur;
810         for (cur = session->capability; cur; cur = cur->next) {
811                 if (!g_ascii_strcasecmp(cur->data, cap))
812                         return TRUE;
813         }
814         return FALSE;
815 }
816
817 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
818                       IMAPAuthType type)
819 {
820         gint ok = MAILIMAP_ERROR_LOGIN;
821         static time_t last_login_err = 0;
822         gchar *ext_info = "";
823         int r;
824         gchar *server = NULL;
825         if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
826                 imap_handle_error(SESSION(session), r);
827                 return r;
828         }
829         server = g_strdup(SESSION(session)->server);
830         switch(type) {
831         case IMAP_AUTH_ANON:
832                 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
833                 break;
834         case IMAP_AUTH_CRAM_MD5:
835                 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
836                 break;
837         case IMAP_AUTH_DIGEST_MD5:
838                 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
839                 break;
840         case IMAP_AUTH_LOGIN:
841                 ok = imap_cmd_login(session, user, pass, "LOGIN");
842                 break;
843         case IMAP_AUTH_GSSAPI:
844                 ok = imap_cmd_login(session, user, pass, "GSSAPI");
845                 break;
846         default:
847                 debug_print("capabilities:\n"
848                                 "\t ANONYMOUS %d\n"
849                                 "\t CRAM-MD5 %d\n"
850                                 "\t DIGEST-MD5 %d\n"
851                                 "\t LOGIN %d\n"
852                                 "\t GSSAPI %d\n", 
853                         imap_has_capability(session, "ANONYMOUS"),
854                         imap_has_capability(session, "CRAM-MD5"),
855                         imap_has_capability(session, "DIGEST-MD5"),
856                         imap_has_capability(session, "LOGIN"),
857                         imap_has_capability(session, "GSSAPI"));
858                 if (imap_has_capability(session, "CRAM-MD5"))
859                         ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
860                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
861                         ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
862                 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
863                         ok = imap_cmd_login(session, user, pass, "GSSAPI");
864                 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
865                         ok = imap_cmd_login(session, user, pass, "LOGIN");
866         }
867
868         if (ok == MAILIMAP_NO_ERROR)
869                 session->authenticated = TRUE;
870         else {
871                 if (type == IMAP_AUTH_CRAM_MD5) {
872                         ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
873                                      "compiled with SASL support and the "
874                                      "CRAM-MD5 SASL plugin is installed.");
875                 } 
876
877                 if (type == IMAP_AUTH_DIGEST_MD5) {
878                         ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
879                                      "compiled with SASL support and the "
880                                      "DIGEST-MD5 SASL plugin is installed.");
881                 } 
882
883                 if (time(NULL) - last_login_err > 10) {
884                         if (!prefs_common.no_recv_err_panel) {
885                                 alertpanel_error_log(_("Connection to %s failed: "
886                                         "login refused.%s"),
887                                         server, ext_info);
888                         } else {
889                                 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
890                                         "login refused.%s\n"),
891                                         server, ext_info);
892                         }
893                 }
894                 last_login_err = time(NULL);
895         }
896         g_free(server);
897         return ok;
898 }
899
900 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
901 {
902         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
903         /* Check if this is the first try to establish a
904            connection, if yes we don't try to reconnect */
905         debug_print("reconnecting\n");
906         if (rfolder->session == NULL) {
907                 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
908                             folder->account->recv_server);
909                 SESSION(session)->sock = NULL;
910                 session_destroy(SESSION(session));
911                 session = NULL;
912         } else {
913                 rfolder->session = NULL;
914                 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
915                             " disconnected. Reconnecting...\n"),
916                             folder->account->recv_server);
917                 statusbar_print_all(_("IMAP4 connection to %s has been"
918                             " disconnected. Reconnecting...\n"),
919                             folder->account->recv_server);
920                 SESSION(session)->state = SESSION_DISCONNECTED;
921                 SESSION(session)->sock = NULL;
922                 session_destroy(SESSION(session));
923                 /* Clear folders session to make imap_session_get create
924                    a new session, because of rfolder->session == NULL
925                    it will not try to reconnect again and so avoid an
926                    endless loop */
927                 debug_print("getting session...\n");
928                 session = imap_session_get(folder);
929                 rfolder->session = SESSION(session);
930                 statusbar_pop_all();
931         }
932         return session;
933 }
934
935 static IMAPSession *imap_session_get(Folder *folder)
936 {
937         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
938         IMAPSession *session = NULL;
939         gint r = MAILIMAP_NO_ERROR;
940
941         g_return_val_if_fail(folder != NULL, NULL);
942         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
943         g_return_val_if_fail(folder->account != NULL, NULL);
944         
945         if (prefs_common.work_offline && 
946             !inc_offline_should_override(FALSE,
947                 _("Claws Mail needs network access in order "
948                   "to access the IMAP server."))) {
949                 return NULL;
950         }
951
952         /* Make sure we have a session */
953         if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
954                 session = IMAP_SESSION(rfolder->session);
955         } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
956                 session_destroy(SESSION(rfolder->session));
957                 rfolder->session = NULL;
958                 goto new_conn;
959         } else if (rfolder->connecting) {
960                 debug_print("already connecting\n");
961                 return NULL;
962         } else {
963 new_conn:
964                 imap_reset_uid_lists(folder);
965                 if (time(NULL) - rfolder->last_failure <= 2)
966                         return NULL;
967                 rfolder->connecting = TRUE;
968                 session = imap_session_new(folder, folder->account);
969         }
970         if(session == NULL) {
971                 rfolder->last_failure = time(NULL);
972                 rfolder->connecting = FALSE;
973                 return NULL;
974         }
975
976         /* Make sure session is authenticated */
977         if (!IMAP_SESSION(session)->authenticated)
978                 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
979         
980         if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
981                 rfolder->session = NULL;
982                 if (!is_fatal(r)) {
983                         imap_threaded_disconnect(session->folder);
984                         SESSION(session)->state = SESSION_DISCONNECTED;
985                         SESSION(session)->sock = NULL;
986                         session_destroy(SESSION(session));
987                 }
988                 rfolder->last_failure = time(NULL);
989                 rfolder->connecting = FALSE;
990                 return NULL;
991         }
992
993         /* I think the point of this code is to avoid sending a
994          * keepalive if we've used the session recently and therefore
995          * think it's still alive.  Unfortunately, most of the code
996          * does not yet check for errors on the socket, and so if the
997          * connection drops we don't notice until the timeout expires.
998          * A better solution than sending a NOOP every time would be
999          * for every command to be prepared to retry until it is
1000          * successfully sent. -- mbp */
1001         if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1002                 /* verify that the session is still alive */
1003                 if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
1004                         debug_print("disconnected!\n");
1005                         if (!is_fatal(r))
1006                                 session = imap_reconnect_if_possible(folder, session);
1007                         else {
1008                                 rfolder->session = NULL;
1009                                 rfolder->connecting = FALSE;
1010                                 session = imap_session_get(folder);
1011                         }
1012                 }
1013                 if (session)
1014                         session->cancelled = FALSE;
1015         }
1016
1017         rfolder->session = SESSION(session);
1018         rfolder->connecting = FALSE;
1019
1020         return IMAP_SESSION(session);
1021 }
1022
1023 static IMAPSession *imap_session_new(Folder * folder,
1024                                      const PrefsAccount *account)
1025 {
1026         IMAPSession *session;
1027         gushort port;
1028         int r;
1029         int authenticated = FALSE;
1030         
1031 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1032         /* FIXME: IMAP over SSL only... */ 
1033         SSLType ssl_type;
1034
1035         port = account->set_imapport ? account->imapport
1036                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1037         ssl_type = account->ssl_imap;   
1038 #else
1039         if (account->ssl_imap != SSL_NONE) {
1040                 if (alertpanel_full(_("Insecure connection"),
1041                         _("This connection is configured to be secured "
1042                           "using SSL, but SSL is not available in this "
1043                           "build of Claws Mail. \n\n"
1044                           "Do you want to continue connecting to this "
1045                           "server? The communication would not be "
1046                           "secure."),
1047                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1048                           NULL, FALSE, NULL, ALERT_WARNING,
1049                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1050                         return NULL;
1051         }
1052         port = account->set_imapport ? account->imapport
1053                 : IMAP4_PORT;
1054 #endif
1055
1056         imap_init(folder);
1057         statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
1058 #ifndef G_OS_WIN32
1059         if (account->set_tunnelcmd) {
1060                 r = imap_threaded_connect_cmd(folder,
1061                                               account->tunnelcmd,
1062                                               account->recv_server,
1063                                               port);
1064         }
1065         else 
1066 #endif
1067         {
1068 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1069                 if (ssl_type == SSL_TUNNEL) {
1070                         r = imap_threaded_connect_ssl(folder,
1071                                                       account->recv_server,
1072                                                       port);
1073                 }
1074                 else 
1075 #endif
1076                 {
1077                         r = imap_threaded_connect(folder,
1078                                                   account->recv_server,
1079                                                   port);
1080                 }
1081         }
1082         
1083         statuswindow_pop_all();
1084         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1085                 authenticated = TRUE;
1086         }
1087         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1088                 authenticated = FALSE;
1089         }
1090         else {
1091 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1092                 if (r == MAILIMAP_ERROR_SSL)
1093                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1094                 else
1095 #endif
1096                         imap_handle_error(NULL, r);
1097
1098                 if(!prefs_common.no_recv_err_panel) {
1099                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1100                                          account->recv_server, port);
1101                 } else {
1102                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1103                                          account->recv_server, port);
1104                 } 
1105                 
1106                 return NULL;
1107         }
1108         
1109         session = g_new0(IMAPSession, 1);
1110         session_init(SESSION(session), account, FALSE);
1111         SESSION(session)->type             = SESSION_IMAP;
1112         SESSION(session)->server           = g_strdup(account->recv_server);
1113         SESSION(session)->port             = port;
1114         SESSION(session)->sock             = NULL;
1115         
1116         SESSION(session)->destroy          = imap_session_destroy;
1117
1118         session->capability = NULL;
1119         
1120         session->authenticated = authenticated;
1121         session->mbox = NULL;
1122         session->exists = 0;
1123         session->recent = 0;
1124         session->expunge = 0;
1125         session->cmd_count = 0;
1126         session->folder = folder;
1127         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1128
1129 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1130         if (account->ssl_imap == SSL_STARTTLS) {
1131                 gint ok;
1132
1133                 ok = imap_cmd_starttls(session);
1134                 if (ok != MAILIMAP_NO_ERROR) {
1135                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1136                         if (!is_fatal(ok)) {
1137                                 SESSION(session)->sock = NULL;
1138                                 session_destroy(SESSION(session));
1139                         }
1140                         return NULL;
1141                 }
1142
1143                 imap_free_capabilities(session);
1144                 session->authenticated = FALSE;
1145                 session->uidplus = FALSE;
1146                 session->cmd_count = 1;
1147         }
1148 #endif
1149         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1150                     (session->authenticated) ? "pre" : "un");
1151         
1152         return session;
1153 }
1154
1155 static gint imap_session_authenticate(IMAPSession *session, 
1156                                       PrefsAccount *account)
1157 {
1158         gchar *pass, *acc_pass;
1159         gboolean failed = FALSE;
1160         gint ok = MAILIMAP_NO_ERROR;
1161         g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1162         acc_pass = account->passwd;
1163 try_again:
1164         pass = acc_pass;
1165         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON) {
1166                 gchar *tmp_pass;
1167                 tmp_pass = input_dialog_query_password_keep(account->recv_server, 
1168                                                             account->userid,
1169                                                             &(account->session_passwd));
1170                 if (!tmp_pass)
1171                         return MAILIMAP_NO_ERROR;
1172                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1173                 g_free(tmp_pass);
1174         } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
1175                 pass = "";
1176         }
1177         statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
1178                                 account->recv_server);
1179         if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1180                 statusbar_pop_all();
1181                 
1182                 if (!failed && !is_fatal(ok)) {
1183                         acc_pass = NULL;
1184                         failed = TRUE;
1185                         if (account->session_passwd != NULL) {
1186                                 g_free(account->session_passwd);
1187                                 account->session_passwd = NULL;
1188                         }
1189                         goto try_again;
1190                 } else {
1191                         if (prefs_common.no_recv_err_panel) {
1192                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1193                                 mainwindow_show_error();
1194                         } else
1195                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1196                 }               
1197
1198                 return ok;
1199         } 
1200
1201         statuswindow_pop_all();
1202         session->authenticated = TRUE;
1203         return MAILIMAP_NO_ERROR;
1204 }
1205
1206 static void imap_session_destroy(Session *session)
1207 {
1208         if (session->state != SESSION_DISCONNECTED)
1209                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1210         
1211         imap_free_capabilities(IMAP_SESSION(session));
1212         g_free(IMAP_SESSION(session)->mbox);
1213 }
1214
1215 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1216 {
1217         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1218 }
1219
1220 static guint get_file_size_with_crs(const gchar *filename) 
1221 {
1222         FILE *fp = NULL;
1223         guint cnt = 0;
1224         gchar buf[4096];
1225         
1226         if (filename == NULL)
1227                 return -1;
1228         
1229         fp = fopen(filename, "rb");
1230         if (!fp)
1231                 return -1;
1232         
1233         while (fgets(buf, sizeof (buf), fp) != NULL) {
1234                 cnt += strlen(buf);
1235                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1236                         cnt++;
1237         }
1238         
1239         fclose(fp);
1240         return cnt;
1241 }
1242
1243 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1244 {
1245         gchar *path, *filename;
1246
1247         path = folder_item_get_path(item);
1248
1249         if (!is_dir_exist(path)) {
1250                 g_free(path);
1251                 return;
1252         }
1253
1254         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1255         g_free(path);
1256
1257         if (is_file_exist(filename)) {
1258                 claws_unlink(filename);
1259         }
1260         g_free(filename);
1261 }
1262
1263 typedef struct _TagsData {
1264         gchar *str;
1265         GSList *msglist;
1266         IMAPFolderItem *item;
1267 } TagsData;
1268
1269 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1270 {
1271         IMAPSession *session;
1272         gint ok, can_create_tags;
1273         Folder *folder = NULL;
1274         TagsData *ht_data = NULL;
1275         GSList *cur;
1276
1277         g_return_if_fail(item != NULL);
1278         g_return_if_fail(msginfo != NULL);
1279
1280         folder = item->folder;
1281         debug_print("getting session...\n");
1282         session = imap_session_get(folder);
1283         
1284         if (!session) {
1285                 debug_print("can't get session\n");
1286                 return;
1287         }
1288
1289         ok = imap_select(session, IMAP_FOLDER(folder), item,
1290                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1291
1292         if (ok != MAILIMAP_NO_ERROR) {
1293                 return;
1294         }
1295
1296         
1297         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1298                 return;
1299         
1300         if (IMAP_FOLDER_ITEM(item)->batching) {
1301                 /* instead of performing an UID STORE command for each message change,
1302                  * as a lot of them can change "together", we just fill in hashtables
1303                  * and defer the treatment so that we're able to send only one
1304                  * command.
1305                  */
1306                 debug_print("IMAP batch mode on, deferring tags change\n");
1307                 for (cur = tags_set; cur; cur = cur->next) {
1308                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1309                         if (cur_tag) {
1310                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1311                                         GINT_TO_POINTER(cur_tag));
1312                                 if (ht_data == NULL) {
1313                                         ht_data = g_new0(TagsData, 1);
1314                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1315                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1316                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1317                                                 GINT_TO_POINTER(cur_tag), ht_data);
1318                                 }
1319                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1320                         } 
1321                 }
1322                 for (cur = tags_unset; cur; cur = cur->next) {
1323                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1324                         if (cur_tag) {
1325                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1326                                         GINT_TO_POINTER(cur_tag));
1327                                 if (ht_data == NULL) {
1328                                         ht_data = g_new0(TagsData, 1);
1329                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1330                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1331                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1332                                                 GINT_TO_POINTER(cur_tag), ht_data);
1333                                 }
1334                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1335                         }
1336                 }
1337         } else {
1338                 GSList *list_set = NULL;
1339                 GSList *list_unset = NULL;
1340                 GSList numlist;
1341                 
1342                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1343                 numlist.next = NULL;
1344         
1345                 debug_print("IMAP changing tags NOW\n");
1346                 for (cur = tags_set; cur; cur = cur->next) {
1347                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1348                         const gchar *str = tags_get_tag(cur_tag);
1349                         if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1350                                 list_set = g_slist_prepend(list_set, g_strdup(str));
1351                 }
1352                 if (list_set) {
1353                         ok = imap_set_message_flags(session, 
1354                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1355                         slist_free_strings(list_set);
1356                         g_slist_free(list_set);
1357                         if (ok != MAILIMAP_NO_ERROR) {
1358                                 return;
1359                         }
1360                 }
1361
1362                 for (cur = tags_unset; cur; cur = cur->next) {
1363                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1364                         const gchar *str = tags_get_tag(cur_tag);
1365                         if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1366                                 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1367                 }
1368                 if (list_unset) {
1369                         ok = imap_set_message_flags(session, 
1370                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1371                         slist_free_strings(list_unset);
1372                         g_slist_free(list_unset);
1373                         if (ok != MAILIMAP_NO_ERROR) {
1374                                 return;
1375                         }
1376                 }
1377         }
1378 }
1379
1380 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1381                                   gboolean headers, gboolean body)
1382 {
1383         gchar *path, *filename;
1384         IMAPSession *session;
1385         gint ok;
1386
1387         g_return_val_if_fail(folder != NULL, NULL);
1388         g_return_val_if_fail(item != NULL, NULL);
1389
1390         if (uid == 0)
1391                 return NULL;
1392
1393         path = folder_item_get_path(item);
1394         if (!is_dir_exist(path))
1395                 make_dir_hier(path);
1396         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1397         g_free(path);
1398         debug_print("trying to fetch cached %s\n", filename);
1399         if (is_file_exist(filename)) {
1400                 /* see whether the local file represents the whole message
1401                  * or not. As the IMAP server reports size with \r chars,
1402                  * we have to update the local file (UNIX \n only) size */
1403                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1404                 guint have_size = -1;
1405
1406                 if (cached)
1407                         debug_print("message %d has been already %scached.\n", uid,
1408                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1409                 
1410                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1411                         have_size = get_file_size_with_crs(filename);
1412                         if (cached && (cached->size <= have_size || !body)) {
1413                                 procmsg_msginfo_free(cached);
1414                                 ok = file_strip_crs(filename);
1415                                 if (ok == 0 && cached && cached->size <= have_size) {
1416                                         /* we have it all and stripped */
1417                                         debug_print("...fully cached in fact; setting flag.\n");
1418                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1419                                 }
1420                                 return filename;
1421                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1422                                 debug_print("message not cached and file recent, considering file complete\n");
1423                                 ok = file_strip_crs(filename);
1424                                 if (ok == 0)
1425                                         return filename;
1426                         } else {
1427                                 procmsg_msginfo_free(cached);
1428                         }
1429                 }
1430                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1431                         procmsg_msginfo_free(cached);
1432                         return filename;
1433                 }
1434         } else {
1435                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1436                 if (cached) {
1437                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1438                         procmsg_msginfo_free(cached);
1439                 }
1440         }
1441
1442         debug_print("getting session...\n");
1443         session = imap_session_get(folder);
1444         
1445         if (!session) {
1446                 g_free(filename);
1447                 return NULL;
1448         }
1449         session_set_access_time(SESSION(session));
1450         lock_session(session); /* unlocked later in the function */
1451
1452         debug_print("IMAP fetching messages\n");
1453         ok = imap_select(session, IMAP_FOLDER(folder), item,
1454                          NULL, NULL, NULL, NULL, NULL, FALSE);
1455         if (ok != MAILIMAP_NO_ERROR) {
1456                 g_warning("can't select mailbox %s\n", item->path);
1457                 g_free(filename);
1458                 return NULL;
1459         }
1460
1461         session_set_access_time(SESSION(session));
1462
1463         debug_print("getting message %d...\n", uid);
1464         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1465
1466         if (ok != MAILIMAP_NO_ERROR) {
1467                 g_warning("can't fetch message %d\n", uid);
1468                 g_free(filename);
1469                 return NULL;
1470         }
1471
1472         session_set_access_time(SESSION(session));
1473         unlock_session(session);
1474
1475         ok = file_strip_crs(filename);
1476
1477         if (ok == 0 && headers && body) {
1478                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1479                 if (cached) {
1480                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1481                         procmsg_msginfo_free(cached);
1482                 }
1483         } else if (ok == -1) {
1484                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1485                 if (cached) {
1486                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1487                         procmsg_msginfo_free(cached);
1488                 }
1489         }
1490         return filename;
1491 }
1492
1493 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1494 {
1495         gchar *path, *filename;
1496         guint size = 0;
1497         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1498         
1499         if (!cached)
1500                 return FALSE;
1501
1502         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1503                 procmsg_msginfo_free(cached);
1504                 return TRUE;
1505         }
1506         path = folder_item_get_path(item);
1507         if (!is_dir_exist(path))
1508                 return FALSE;
1509
1510         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1511         g_free(path);
1512         if (is_file_exist(filename)) {
1513                 if (cached && cached->total_size == cached->size) {
1514                         /* fast path */
1515                         g_free(filename);
1516                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1517                         return TRUE;
1518                 }
1519                 size = get_file_size_with_crs(filename);
1520                 g_free(filename);
1521         }
1522         if (cached && size >= cached->size) {
1523                 cached->total_size = cached->size;
1524                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1525                 procmsg_msginfo_free(cached);
1526                 return TRUE;
1527         }
1528         if (cached)
1529                 procmsg_msginfo_free(cached);
1530         return FALSE;   
1531 }
1532
1533 void imap_cache_msg(FolderItem *item, gint msgnum)
1534 {
1535         Folder *folder = NULL;
1536         
1537         if (!item)
1538                 return;
1539         folder = item->folder;
1540         
1541         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1542                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1543                 debug_print("fetched %s\n", tmp);
1544                 g_free(tmp);
1545         }
1546 }
1547
1548 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1549                          const gchar *file, MsgFlags *flags)
1550 {
1551         gint ret;
1552         GSList file_list;
1553         MsgFileInfo fileinfo;
1554
1555         g_return_val_if_fail(file != NULL, -1);
1556
1557         fileinfo.msginfo = NULL;
1558         fileinfo.file = (gchar *)file;
1559         fileinfo.flags = flags;
1560         file_list.data = &fileinfo;
1561         file_list.next = NULL;
1562
1563         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1564         return ret;
1565 }
1566
1567 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1568                    GRelation *relation)
1569 {
1570         gchar *destdir;
1571         IMAPSession *session;
1572         guint32 last_uid = 0;
1573         GSList *cur;
1574         MsgFileInfo *fileinfo;
1575         gint ok = MAILIMAP_NO_ERROR;
1576         gint curnum = 0, total = 0;
1577         gboolean missing_uids = FALSE;
1578
1579         g_return_val_if_fail(folder != NULL, -1);
1580         g_return_val_if_fail(dest != NULL, -1);
1581         g_return_val_if_fail(file_list != NULL, -1);
1582         
1583         debug_print("getting session...\n");
1584         session = imap_session_get(folder);
1585         if (!session) {
1586                 return -1;
1587         }
1588         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1589         if (is_fatal(ok))
1590                 return -1;
1591         statusbar_print_all(_("Adding messages..."));
1592         total = g_slist_length(file_list);
1593         for (cur = file_list; cur != NULL; cur = cur->next) {
1594                 IMAPFlags iflags = 0;
1595                 guint32 new_uid = 0;
1596                 gchar *real_file = NULL;
1597                 fileinfo = (MsgFileInfo *)cur->data;
1598
1599                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1600                 curnum++;
1601
1602                 if (fileinfo->flags) {
1603                         if (MSG_IS_MARKED(*fileinfo->flags))
1604                                 iflags |= IMAP_FLAG_FLAGGED;
1605                         if (MSG_IS_REPLIED(*fileinfo->flags))
1606                                 iflags |= IMAP_FLAG_ANSWERED;
1607                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1608                                 iflags |= IMAP_FLAG_FORWARDED;
1609                         if (MSG_IS_SPAM(*fileinfo->flags))
1610                                 iflags |= IMAP_FLAG_SPAM;
1611                         else
1612                                 iflags |= IMAP_FLAG_HAM;
1613                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1614                                 iflags |= IMAP_FLAG_SEEN;
1615                         
1616                 }
1617                 
1618                 if (real_file == NULL)
1619                         real_file = g_strdup(fileinfo->file);
1620                 
1621                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1622                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1623                     folder_has_parent_of_type(dest, F_DRAFT) ||
1624                     folder_has_parent_of_type(dest, F_TRASH))
1625                         iflags |= IMAP_FLAG_SEEN;
1626
1627                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1628                                      &new_uid);
1629
1630                 if (ok != MAILIMAP_NO_ERROR) {
1631                         g_warning("can't append message %s\n", real_file);
1632                         g_free(real_file);
1633                         g_free(destdir);
1634                         statusbar_progress_all(0,0,0);
1635                         statusbar_pop_all();
1636                         return -1;
1637                 } else {
1638                         debug_print("appended new message as %d\n", new_uid);
1639                         /* put the local file in the imapcache, so that we don't
1640                          * have to fetch it back later. */
1641                         
1642                         if (new_uid == 0) {
1643                                 missing_uids = TRUE;
1644                                 debug_print("Missing UID (0)\n");
1645                         }
1646                         if (new_uid > 0) {
1647                                 gchar *cache_path = folder_item_get_path(dest);
1648                                 if (!is_dir_exist(cache_path))
1649                                         make_dir_hier(cache_path);
1650                                 if (is_dir_exist(cache_path)) {
1651                                         gchar *cache_file = g_strconcat(
1652                                                 cache_path, G_DIR_SEPARATOR_S, 
1653                                                 itos(new_uid), NULL);
1654                                         copy_file(real_file, cache_file, TRUE);
1655                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1656                                         g_free(cache_file);
1657                                 }
1658                                 g_free(cache_path);
1659                         }
1660                 }
1661
1662                 if (relation != NULL)
1663                         g_relation_insert(relation, fileinfo->msginfo != NULL ? 
1664                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1665                                           GINT_TO_POINTER(new_uid));
1666                 if (last_uid < new_uid) {
1667                         last_uid = new_uid;
1668                 }
1669
1670                 g_free(real_file);
1671         }
1672         
1673         statusbar_progress_all(0,0,0);
1674         statusbar_pop_all();
1675         
1676         
1677         g_free(destdir);
1678
1679         imap_scan_required(folder, dest);
1680
1681         session = imap_session_get(folder);
1682         if (!session) {
1683                 return -1;
1684         }
1685         if (missing_uids) {
1686                 gint a;
1687                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1688                          &a, NULL, NULL, NULL, NULL, FALSE);
1689         }
1690         return last_uid;
1691 }
1692
1693 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1694 {
1695         GSList *result = NULL;
1696         clistiter *list;
1697         int start, end, t;
1698         GSList *cur;
1699
1700         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1701                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1702                 start = item->set_first;
1703                 end = item->set_last;
1704                 for (t = start; t <= end; t++) {
1705                         result = g_slist_prepend(result, GINT_TO_POINTER(t));
1706                 }
1707         }
1708         result = g_slist_reverse(result);
1709         if (debug_get_mode()) {
1710                 debug_print("flat imap set: ");
1711                 for (cur = result; cur; cur = cur->next) {
1712                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1713                 }
1714                 debug_print("\n");
1715         }
1716         
1717         return result;
1718 }
1719 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1720                               MsgInfoList *msglist, GRelation *relation)
1721 {
1722         FolderItem *src;
1723         gchar *destdir;
1724         GSList *seq_list, *cur;
1725         MsgInfo *msginfo;
1726         IMAPSession *session;
1727         gint ok = MAILIMAP_NO_ERROR;
1728         GRelation *uid_mapping;
1729         gint last_num = 0;
1730         gboolean single = FALSE;
1731
1732         g_return_val_if_fail(folder != NULL, -1);
1733         g_return_val_if_fail(dest != NULL, -1);
1734         g_return_val_if_fail(msglist != NULL, -1);
1735         
1736         debug_print("getting session...\n");
1737         session = imap_session_get(folder);
1738         
1739         if (!session) {
1740                 return -1;
1741         }
1742
1743         msginfo = (MsgInfo *)msglist->data;
1744         if (msglist->next == NULL)
1745                 single = TRUE;
1746         src = msginfo->folder;
1747         if (src == dest) {
1748                 g_warning("the src folder is identical to the dest.\n");
1749                 return -1;
1750         }
1751
1752         if (src->folder != dest->folder) {
1753                 GSList *infolist = NULL, *cur;
1754                 int res = -1;
1755                 for (cur = msglist; cur; cur = cur->next) {
1756                         msginfo = (MsgInfo *)cur->data;
1757                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1758                         fileinfo->file = procmsg_get_message_file(msginfo);
1759                         fileinfo->flags = &(msginfo->flags);
1760                         infolist = g_slist_prepend(infolist, fileinfo);
1761                 }
1762                 infolist = g_slist_reverse(infolist);
1763                 res = folder_item_add_msgs(dest, infolist, FALSE);
1764                 for (cur = infolist; cur; cur = cur->next) {
1765                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1766                         g_free(info->file);
1767                         g_free(info);
1768                 }
1769                 g_slist_free(infolist);
1770                 return res;
1771         } 
1772
1773         lock_session(session); /* unlocked later in the function */
1774
1775         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1776                          NULL, NULL, NULL, NULL, NULL, FALSE);
1777         if (ok != MAILIMAP_NO_ERROR) {
1778                 return ok;
1779         }
1780
1781         unlock_session(session);
1782
1783         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1784
1785         if (is_fatal(ok))
1786                 return ok;
1787
1788         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1789         uid_mapping = g_relation_new(2);
1790         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1791         
1792         statusbar_print_all(_("Copying messages..."));
1793         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1794                 struct mailimap_set * seq_set;
1795                 struct mailimap_set * source = NULL;
1796                 struct mailimap_set * dest = NULL;
1797                 seq_set = cur->data;
1798
1799                 debug_print("Copying messages from %s to %s ...\n",
1800                             src->path, destdir);
1801
1802                 lock_session(session); /* unlocked later in the function */
1803                 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
1804                         &source, &dest);
1805                 
1806                 if (is_fatal(ok)) {
1807                         session = NULL;
1808                 }
1809
1810                 if (ok == MAILIMAP_NO_ERROR) {
1811                         unlock_session(session);
1812                         if (relation && source && dest) {
1813                                 GSList *s_list = flatten_mailimap_set(source);
1814                                 GSList *d_list = flatten_mailimap_set(dest);
1815                                 GSList *s_cur, *d_cur;
1816                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1817
1818                                         for (s_cur = s_list, d_cur = d_list; 
1819                                              s_cur && d_cur; 
1820                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1821                                                 g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
1822                                         }
1823
1824                                 } else {
1825                                         debug_print("hhhmm, source list length != dest list length.\n");
1826                                 }
1827                                 g_slist_free(s_list);
1828                                 g_slist_free(d_list);
1829                         }
1830                 }
1831
1832
1833                 if (source)
1834                         mailimap_set_free(source);
1835                 if (dest)
1836                         mailimap_set_free(dest);
1837
1838                 if (ok != MAILIMAP_NO_ERROR) {
1839                         g_relation_destroy(uid_mapping);
1840                         imap_lep_set_free(seq_list);
1841                         statusbar_pop_all();
1842                         return -1;
1843                 }
1844         }
1845
1846         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1847                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1848                 GTuples *tuples;
1849
1850                 tuples = g_relation_select(uid_mapping, 
1851                                            GINT_TO_POINTER(msginfo->msgnum),
1852                                            0);
1853                 if (tuples->len > 0) {
1854                         gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1855                         g_relation_insert(relation, msginfo,
1856                                           GINT_TO_POINTER(num));
1857                         if (num > last_num)
1858                                 last_num = num;
1859                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1860                         /* put the local file in the imapcache, so that we don't
1861                          * have to fetch it back later. */
1862                         if (num > 0) {
1863                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1864                                 gchar *real_file = g_strconcat(
1865                                         cache_path, G_DIR_SEPARATOR_S, 
1866                                         itos(msginfo->msgnum), NULL);
1867                                 gchar *cache_file = NULL;
1868                                 g_free(cache_path);
1869                                 cache_path = folder_item_get_path(dest);
1870                                 cache_file = g_strconcat(
1871                                         cache_path, G_DIR_SEPARATOR_S, 
1872                                         itos(num), NULL);
1873                                 if (!is_dir_exist(cache_path))
1874                                         make_dir_hier(cache_path);
1875                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1876                                         copy_file(real_file, cache_file, TRUE);
1877                                         debug_print("copied to cache: %s\n", cache_file);
1878                                 }
1879                                 g_free(real_file);
1880                                 g_free(cache_file);
1881                                 g_free(cache_path);
1882                         }
1883                 } else
1884                         g_relation_insert(relation, msginfo,
1885                                           GINT_TO_POINTER(0));
1886                 g_tuples_destroy(tuples);
1887         }
1888         statusbar_pop_all();
1889
1890         g_relation_destroy(uid_mapping);
1891         imap_lep_set_free(seq_list);
1892
1893         g_free(destdir);
1894         
1895         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1896         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1897         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1898         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1899
1900         imap_scan_required(folder, dest);
1901         if (ok == MAILIMAP_NO_ERROR)
1902                 return last_num;
1903         else
1904                 return -1;
1905 }
1906
1907 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1908 {
1909         GSList msglist;
1910
1911         g_return_val_if_fail(msginfo != NULL, -1);
1912
1913         msglist.data = msginfo;
1914         msglist.next = NULL;
1915
1916         return imap_copy_msgs(folder, dest, &msglist, NULL);
1917 }
1918
1919 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1920                     MsgInfoList *msglist, GRelation *relation)
1921 {
1922         MsgInfo *msginfo;
1923         gint ret;
1924
1925         g_return_val_if_fail(folder != NULL, -1);
1926         g_return_val_if_fail(dest != NULL, -1);
1927         g_return_val_if_fail(msglist != NULL, -1);
1928
1929         msginfo = (MsgInfo *)msglist->data;
1930         g_return_val_if_fail(msginfo->folder != NULL, -1);
1931
1932         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1933         return ret;
1934 }
1935
1936
1937 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1938                                 MsgInfoList *msglist, GRelation *relation)
1939 {
1940         gchar *destdir, *dir;
1941         GSList *numlist = NULL, *cur;
1942         MsgInfo *msginfo;
1943         IMAPSession *session;
1944         gint ok = MAILIMAP_NO_ERROR;
1945         GRelation *uid_mapping;
1946         
1947         g_return_val_if_fail(folder != NULL, -1);
1948         g_return_val_if_fail(dest != NULL, -1);
1949         g_return_val_if_fail(msglist != NULL, -1);
1950
1951         debug_print("getting session...\n");
1952         session = imap_session_get(folder);
1953         if (!session) {
1954                 return -1;
1955         }
1956
1957         lock_session(session); /* unlocked later in the function */
1958
1959         msginfo = (MsgInfo *)msglist->data;
1960
1961         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1962                          NULL, NULL, NULL, NULL, NULL, FALSE);
1963         if (ok != MAILIMAP_NO_ERROR) {
1964                 return ok;
1965         }
1966
1967         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1968         if (is_fatal(ok))
1969                 return ok;
1970         for (cur = msglist; cur; cur = cur->next) {
1971                 msginfo = (MsgInfo *)cur->data;
1972                 if (!MSG_IS_DELETED(msginfo->flags))
1973                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1974         }
1975         numlist = g_slist_reverse(numlist);
1976
1977         uid_mapping = g_relation_new(2);
1978         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1979
1980         if (numlist != NULL) {
1981                 ok = imap_set_message_flags
1982                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
1983                 if (ok != MAILIMAP_NO_ERROR) {
1984                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1985                         return ok;
1986                 }
1987         } /* else we just need to expunge */
1988         ok = imap_cmd_expunge(session);
1989         if (ok != MAILIMAP_NO_ERROR) {
1990                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1991                 return ok;
1992         }
1993         
1994         session->folder_content_changed = TRUE;
1995         unlock_session(session);
1996
1997         dir = folder_item_get_path(msginfo->folder);
1998         if (is_dir_exist(dir)) {
1999                 for (cur = msglist; cur; cur = cur->next) {
2000                         msginfo = (MsgInfo *)cur->data;
2001                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2002                 }
2003         }
2004         g_free(dir);
2005
2006         g_relation_destroy(uid_mapping);
2007         g_slist_free(numlist);
2008
2009         imap_scan_required(folder, dest);
2010
2011         g_free(destdir);
2012         if (ok == MAILIMAP_NO_ERROR)
2013                 return 0;
2014         else
2015                 return -1;
2016 }
2017
2018 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
2019                     MsgInfoList *msglist, GRelation *relation)
2020 {
2021         MsgInfo *msginfo;
2022
2023         g_return_val_if_fail(folder != NULL, -1);
2024         g_return_val_if_fail(dest != NULL, -1);
2025         if (msglist == NULL)
2026                 return 0;
2027
2028         msginfo = (MsgInfo *)msglist->data;
2029         g_return_val_if_fail(msginfo->folder != NULL, -1);
2030
2031         return imap_do_remove_msgs(folder, dest, msglist, relation);
2032 }
2033
2034 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2035 {
2036         GSList *list = folder_item_get_msg_list(item);
2037         gint res = imap_remove_msgs(folder, item, list, NULL);
2038         procmsg_msg_list_free(list);
2039         return res;
2040 }
2041
2042 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2043                                     MsgInfo *msginfo)
2044 {
2045         /* TODO: properly implement this method */
2046         return FALSE;
2047 }
2048
2049 static gint imap_close(Folder *folder, FolderItem *item)
2050 {
2051         return 0;
2052 }
2053
2054 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2055 {
2056         FolderItem *item = NULL;
2057         IMAPSession *session;
2058         gchar *root_folder = NULL;
2059
2060         g_return_val_if_fail(folder != NULL, -1);
2061         g_return_val_if_fail(folder->account != NULL, -1);
2062
2063         debug_print("getting session...\n");
2064         session = imap_session_get(folder);
2065         if (!session) {
2066                 if (!folder->node) {
2067                         folder_tree_destroy(folder);
2068                         item = folder_item_new(folder, folder->name, NULL);
2069                         item->folder = folder;
2070                         folder->node = item->node = g_node_new(item);
2071                 }
2072                 return -1;
2073         }
2074
2075         if (folder->account->imap_dir && *folder->account->imap_dir) {
2076                 gchar *real_path;
2077                 int r;
2078                 clist * lep_list;
2079
2080                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2081                 extract_quote(root_folder, '"');
2082                 subst_char(root_folder,
2083                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2084                                                    root_folder, &r),
2085                            '/');
2086                 if (is_fatal(r))
2087                         return -1;
2088                 strtailchomp(root_folder, '/');
2089                 real_path = imap_get_real_path
2090                         (session, IMAP_FOLDER(folder), root_folder, &r);
2091                 if (is_fatal(r))
2092                         return -1;
2093                 debug_print("IMAP root directory: %s\n", real_path);
2094
2095                 /* check if root directory exist */
2096
2097                 r = imap_threaded_list(session->folder, "", real_path,
2098                                        &lep_list);
2099
2100                 if (r != MAILIMAP_NO_ERROR)
2101                         imap_handle_error(SESSION(session), r);
2102
2103                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2104                         if (!folder->node) {
2105                                 item = folder_item_new(folder, folder->name, NULL);
2106                                 item->folder = folder;
2107                                 folder->node = item->node = g_node_new(item);
2108                         }
2109                         return -1;
2110                 }
2111                 mailimap_list_result_free(lep_list);
2112                                 
2113                 g_free(real_path);
2114         }
2115
2116         if (folder->node)
2117                 item = FOLDER_ITEM(folder->node->data);
2118                 
2119         if (item && !item->path && root_folder) {
2120                 item->path = g_strdup(root_folder);
2121         }
2122
2123         if (!item || ((item->path || root_folder) &&
2124                       strcmp2(item->path, root_folder) != 0)) {
2125                 folder_tree_destroy(folder);
2126                 item = folder_item_new(folder, folder->name, root_folder);
2127                 item->folder = folder;
2128                 folder->node = item->node = g_node_new(item);
2129         }
2130
2131         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2132         imap_create_missing_folders(folder);
2133
2134         return 0;
2135 }
2136
2137 static gint imap_scan_tree(Folder *folder)
2138 {
2139         gboolean subs_only = FALSE;
2140         if (folder->account) {
2141                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2142                 subs_only = folder->account->imap_subsonly;
2143         }
2144         return imap_scan_tree_real(folder, subs_only);
2145 }
2146
2147 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2148 {
2149         Folder *folder;
2150         IMAPFolder *imapfolder;
2151         FolderItem *new_item;
2152         GSList *item_list, *cur;
2153         GNode *node;
2154         gchar *real_path;
2155         gchar *wildcard_path;
2156         gchar separator;
2157         gchar wildcard[3];
2158         clist * lep_list;
2159         int r;
2160         
2161         g_return_val_if_fail(item != NULL, -1);
2162         g_return_val_if_fail(item->folder != NULL, -1);
2163         g_return_val_if_fail(item->no_sub == FALSE, -1);
2164
2165         folder = item->folder;
2166         imapfolder = IMAP_FOLDER(folder);
2167
2168         separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2169         if (is_fatal(r))
2170                 return r;
2171
2172         if (folder->ui_func)
2173                 folder->ui_func(folder, item, folder->ui_func_data);
2174
2175         if (item->path) {
2176                 wildcard[0] = separator;
2177                 wildcard[1] = '%';
2178                 wildcard[2] = '\0';
2179                 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2180                 if (is_fatal(r))
2181                         return r;
2182         } else {
2183                 wildcard[0] = '%';
2184                 wildcard[1] = '\0';
2185                 real_path = g_strdup("");
2186         }
2187
2188         Xstrcat_a(wildcard_path, real_path, wildcard,
2189                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2190         lep_list = NULL;
2191         
2192         if (subs_only)
2193                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2194         else
2195                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2196
2197         if (r != MAILIMAP_NO_ERROR) {
2198                 imap_handle_error(SESSION(session), r);
2199                 item_list = NULL;
2200                 return r;
2201         }
2202         else {
2203                 item_list = imap_list_from_lep(imapfolder,
2204                                                lep_list, real_path, FALSE);
2205                 mailimap_list_result_free(lep_list);
2206         }
2207         
2208         g_free(real_path);
2209
2210         node = item->node->children;
2211         while (node != NULL) {
2212                 FolderItem *old_item = FOLDER_ITEM(node->data);
2213                 GNode *next = node->next;
2214
2215                 new_item = NULL;
2216                 for (cur = item_list; cur != NULL; cur = cur->next) {
2217                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2218                         if (!strcmp2(old_item->path, cur_item->path)) {
2219                                 new_item = cur_item;
2220                                 break;
2221                         }
2222                 }
2223                 if (!new_item) {
2224                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2225                                 debug_print("not removing INBOX\n");
2226                         } else {
2227                                 debug_print("folder '%s' not found. removing...\n",
2228                                             old_item->path);
2229                                 folder_item_remove(old_item);
2230                         }
2231                 } else {
2232                         old_item->no_sub = new_item->no_sub;
2233                         old_item->no_select = new_item->no_select;
2234                         if (old_item->no_sub == TRUE && node->children) {
2235                                 debug_print("folder '%s' doesn't have "
2236                                             "subfolders. removing...\n",
2237                                             old_item->path);
2238                                 folder_item_remove_children(old_item);
2239                         }
2240                 }
2241
2242                 node = next;
2243         }
2244
2245         for (cur = item_list; cur != NULL; cur = cur->next) {
2246                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2247                 new_item = NULL;
2248
2249                 for (node = item->node->children; node != NULL;
2250                      node = node->next) {
2251                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2252                                      cur_item->path)) {
2253                                 new_item = FOLDER_ITEM(node->data);
2254                                 folder_item_destroy(cur_item);
2255                                 cur_item = NULL;
2256                                 break;
2257                         }
2258                 }
2259                 if (!new_item) {
2260                         new_item = cur_item;
2261                         debug_print("new folder '%s' found.\n", new_item->path);
2262                         folder_item_append(item, new_item);
2263                 }
2264
2265                 if (!strcmp(new_item->path, "INBOX")) {
2266                         new_item->stype = F_INBOX;
2267                         folder->inbox = new_item;
2268                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2269                         gchar *base;
2270
2271                         base = g_path_get_basename(new_item->path);
2272
2273                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2274                                 new_item->stype = F_OUTBOX;
2275                                 folder->outbox = new_item;
2276                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2277                                 new_item->stype = F_DRAFT;
2278                                 folder->draft = new_item;
2279                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2280                                 new_item->stype = F_QUEUE;
2281                                 folder->queue = new_item;
2282                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2283                                 new_item->stype = F_TRASH;
2284                                 folder->trash = new_item;
2285                         }
2286                         g_free(base);
2287                 }
2288
2289                 if (new_item->no_sub == FALSE)
2290                         imap_scan_tree_recursive(session, new_item, subs_only);
2291         }
2292
2293         g_slist_free(item_list);
2294
2295         return MAILIMAP_NO_ERROR;
2296 }
2297
2298 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2299 {
2300         IMAPSession *session = imap_session_get(folder);
2301         gchar *real_path;
2302         gchar *wildcard_path;
2303         gchar separator;
2304         gchar wildcard[3];
2305         clist * lep_list;
2306         GSList *item_list = NULL, *cur;
2307         GList *child_list = NULL, *tmplist = NULL;
2308         GSList *sub_list = NULL;
2309         int r;
2310
2311         if (!session)
2312                 return NULL;
2313
2314         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2315         if (is_fatal(r))
2316                 return NULL;
2317
2318         if (item->path) {
2319                 wildcard[0] = separator;
2320                 wildcard[1] = '%';
2321                 wildcard[2] = '\0';
2322                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2323                 if (is_fatal(r))
2324                         return NULL;
2325         } else {
2326                 wildcard[0] = '%';
2327                 wildcard[1] = '\0';
2328                 real_path = g_strdup("");
2329         }
2330
2331         Xstrcat_a(wildcard_path, real_path, wildcard,
2332                   {g_free(real_path); return NULL;});
2333         lep_list = NULL;
2334         
2335         if (unsubs_only)
2336                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2337                                 item->path?item->path:item->name);
2338         else
2339                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2340                                 item->path?item->path:item->name);
2341
2342         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2343         if (r) {
2344                 statusbar_pop_all();
2345                 return NULL;
2346         }
2347         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2348                                lep_list, real_path, FALSE);
2349         mailimap_list_result_free(lep_list);
2350
2351         for (cur = item_list; cur != NULL; cur = cur->next) {
2352                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2353                 if (recursive) {
2354                         tmplist = imap_scan_subtree(folder, cur_item, 
2355                                         unsubs_only, recursive);
2356                         if (tmplist)
2357                                 child_list = g_list_concat(child_list, tmplist);
2358                 }
2359                 child_list = g_list_prepend(child_list,
2360                                 imap_get_real_path(session, 
2361                                         IMAP_FOLDER(folder), cur_item->path, &r));
2362                 if (is_fatal(r)) {
2363                         statusbar_pop_all();
2364                         return NULL;
2365                 }
2366                 folder_item_destroy(cur_item);
2367         }
2368         child_list = g_list_reverse(child_list);
2369         g_slist_free(item_list);
2370
2371         if (unsubs_only) {
2372                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2373                 if (r) {
2374                         statusbar_pop_all();
2375                         return NULL;
2376                 }
2377                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2378                                        lep_list, real_path, FALSE);
2379                 mailimap_list_result_free(lep_list);
2380
2381                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2382                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2383                         GList *oldlitem = NULL;
2384                         gchar *tmp = imap_get_real_path(session, 
2385                                         IMAP_FOLDER(folder), cur_item->path, &r);
2386                         if (r) {
2387                                 statusbar_pop_all();
2388                                 return NULL;
2389                         }
2390                         folder_item_destroy(cur_item);
2391                         oldlitem = g_list_find_custom(
2392                                         child_list, tmp, (GCompareFunc)strcmp2);
2393                         if (oldlitem) {
2394                                 child_list = g_list_remove_link(child_list, oldlitem);
2395                                 g_free(oldlitem->data);
2396                                 g_list_free(oldlitem);
2397                         }
2398                         g_free(tmp);
2399                 }
2400         }
2401
2402         statusbar_pop_all();
2403
2404         return child_list;
2405 }
2406
2407 static gint imap_create_tree(Folder *folder)
2408 {
2409         g_return_val_if_fail(folder != NULL, -1);
2410         g_return_val_if_fail(folder->node != NULL, -1);
2411         g_return_val_if_fail(folder->node->data != NULL, -1);
2412         g_return_val_if_fail(folder->account != NULL, -1);
2413
2414         imap_scan_tree(folder);
2415         imap_create_missing_folders(folder);
2416
2417         return 0;
2418 }
2419
2420 static void imap_create_missing_folders(Folder *folder)
2421 {
2422         g_return_if_fail(folder != NULL);
2423
2424         if (!folder->inbox)
2425                 folder->inbox = imap_create_special_folder
2426                         (folder, F_INBOX, "INBOX");
2427         if (!folder->trash)
2428                 folder->trash = imap_create_special_folder
2429                         (folder, F_TRASH, "Trash");
2430         if (!folder->queue)
2431                 folder->queue = imap_create_special_folder
2432                         (folder, F_QUEUE, "Queue");
2433         if (!folder->outbox)
2434                 folder->outbox = imap_create_special_folder
2435                         (folder, F_OUTBOX, "Sent");
2436         if (!folder->draft)
2437                 folder->draft = imap_create_special_folder
2438                         (folder, F_DRAFT, "Drafts");
2439 }
2440
2441 static FolderItem *imap_create_special_folder(Folder *folder,
2442                                               SpecialFolderItemType stype,
2443                                               const gchar *name)
2444 {
2445         FolderItem *item;
2446         FolderItem *new_item;
2447
2448         g_return_val_if_fail(folder != NULL, NULL);
2449         g_return_val_if_fail(folder->node != NULL, NULL);
2450         g_return_val_if_fail(folder->node->data != NULL, NULL);
2451         g_return_val_if_fail(folder->account != NULL, NULL);
2452         g_return_val_if_fail(name != NULL, NULL);
2453
2454         item = FOLDER_ITEM(folder->node->data);
2455         new_item = imap_create_folder(folder, item, name);
2456
2457         if (!new_item) {
2458                 g_warning("Can't create '%s'\n", name);
2459                 if (!folder->inbox) return NULL;
2460
2461                 new_item = imap_create_folder(folder, folder->inbox, name);
2462                 if (!new_item)
2463                         g_warning("Can't create '%s' under INBOX\n", name);
2464                 else
2465                         new_item->stype = stype;
2466         } else
2467                 new_item->stype = stype;
2468
2469         return new_item;
2470 }
2471
2472 static gchar *imap_folder_get_path(Folder *folder)
2473 {
2474         gchar *folder_path;
2475
2476         g_return_val_if_fail(folder != NULL, NULL);
2477         g_return_val_if_fail(folder->account != NULL, NULL);
2478
2479         folder_path = g_strconcat(get_imap_cache_dir(),
2480                                   G_DIR_SEPARATOR_S,
2481                                   folder->account->recv_server,
2482                                   G_DIR_SEPARATOR_S,
2483                                   folder->account->userid,
2484                                   NULL);
2485
2486         return folder_path;
2487 }
2488
2489 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2490 {
2491         gchar *folder_path, *path;
2492
2493         g_return_val_if_fail(folder != NULL, NULL);
2494         g_return_val_if_fail(item != NULL, NULL);
2495         folder_path = imap_folder_get_path(folder);
2496
2497         g_return_val_if_fail(folder_path != NULL, NULL);
2498         if (folder_path[0] == G_DIR_SEPARATOR) {
2499                 if (item->path)
2500                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2501                                            item->path, NULL);
2502                 else
2503                         path = g_strdup(folder_path);
2504         } else {
2505                 if (item->path)
2506                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2507                                            folder_path, G_DIR_SEPARATOR_S,
2508                                            item->path, NULL);
2509                 else
2510                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2511                                            folder_path, NULL);
2512         }
2513         g_free(folder_path);
2514
2515         return path;
2516 }
2517
2518 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2519                                const gchar *name)
2520 {
2521         gchar *dirpath, *imap_path;
2522         IMAPSession *session;
2523         FolderItem *new_item;
2524         gchar separator;
2525         gchar *new_name;
2526         const gchar *p;
2527         gint ok;
2528         gboolean no_select = FALSE, no_sub = FALSE;
2529         gboolean exist = FALSE;
2530         
2531         g_return_val_if_fail(folder != NULL, NULL);
2532         g_return_val_if_fail(folder->account != NULL, NULL);
2533         g_return_val_if_fail(parent != NULL, NULL);
2534         g_return_val_if_fail(name != NULL, NULL);
2535
2536         debug_print("getting session...\n");
2537         session = imap_session_get(folder);
2538         if (!session) {
2539                 return NULL;
2540         }
2541
2542         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2543                 dirpath = g_strdup(name);
2544         }else if (parent->path)
2545                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2546         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2547                 dirpath = g_strdup(name);
2548         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2549                 gchar *imap_dir;
2550
2551                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2552                 strtailchomp(imap_dir, '/');
2553                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2554         } else
2555                 dirpath = g_strdup(name);
2556                 
2557         
2558
2559         /* keep trailing directory separator to create a folder that contains
2560            sub folder */
2561         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
2562
2563         strtailchomp(dirpath, '/');
2564         Xstrdup_a(new_name, name, {
2565                 g_free(dirpath); 
2566                 return NULL;});
2567
2568         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
2569         if (is_fatal(ok))
2570                 return NULL;
2571         imap_path_separator_subst(imap_path, separator);
2572         /* remove trailing / for display */
2573         strtailchomp(new_name, '/');
2574
2575         if (strcmp(dirpath, "INBOX") != 0) {
2576                 GPtrArray *argbuf;
2577                 int r;
2578                 clist * lep_list;
2579                 
2580                 argbuf = g_ptr_array_new();
2581                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2582                 if (r != MAILIMAP_NO_ERROR) {
2583                         imap_handle_error(SESSION(session), r);
2584                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2585                         g_free(imap_path);
2586                         g_free(dirpath);
2587                         ptr_array_free_strings(argbuf);
2588                         g_ptr_array_free(argbuf, TRUE);
2589                         return NULL;
2590                 }
2591                 
2592                 if (clist_count(lep_list) > 0)
2593                         exist = TRUE;
2594                 mailimap_list_result_free(lep_list);
2595                 lep_list = NULL;
2596                 if (!exist) {
2597                         ok = imap_cmd_create(session, imap_path);
2598                         if (ok != MAILIMAP_NO_ERROR) {
2599                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2600                                 g_free(imap_path);
2601                                 g_free(dirpath);
2602                                 return NULL;
2603                         }
2604                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2605                         if (r == MAILIMAP_NO_ERROR) {
2606                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2607                                                lep_list, dirpath, TRUE);
2608                                 if (item_list) {
2609                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2610                                         no_select = cur_item->no_select;
2611                                         no_sub = cur_item->no_sub;
2612                                         g_slist_free(item_list);
2613                                 } 
2614                                 mailimap_list_result_free(lep_list);
2615                         } else {
2616                                 imap_handle_error(SESSION(session), r);
2617                         }
2618                 }
2619                 imap_threaded_subscribe(folder, imap_path, TRUE);
2620         } else {
2621                 clist *lep_list;
2622                 int r;
2623                 /* just get flags */
2624                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2625                 if (r == MAILIMAP_NO_ERROR) {
2626                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2627                                        lep_list, dirpath, TRUE);
2628                         if (item_list) {
2629                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2630                                 no_select = cur_item->no_select;
2631                                 no_sub = cur_item->no_sub;
2632                                 g_slist_free(item_list);
2633                         } 
2634                         mailimap_list_result_free(lep_list);
2635                 } else {
2636                         imap_handle_error(SESSION(session), r);
2637                 }
2638         }
2639
2640         new_item = folder_item_new(folder, new_name, dirpath);
2641         new_item->no_select = no_select;
2642         new_item->no_sub = no_sub;
2643         folder_item_append(parent, new_item);
2644         g_free(imap_path);
2645         g_free(dirpath);
2646
2647         dirpath = folder_item_get_path(new_item);
2648         if (!is_dir_exist(dirpath))
2649                 make_dir_hier(dirpath);
2650         g_free(dirpath);
2651
2652         if (exist) {
2653                 /* folder existed, scan it */
2654                 imap_scan_required(folder, new_item);
2655                 folder_item_scan_full(new_item, FALSE);
2656         }
2657
2658         return new_item;
2659 }
2660
2661 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2662                                const gchar *name)
2663 {
2664         gchar *dirpath;
2665         gchar *newpath;
2666         gchar *real_oldpath;
2667         gchar *real_newpath;
2668         gchar *paths[2];
2669         gchar *old_cache_dir;
2670         gchar *new_cache_dir;
2671         IMAPSession *session;
2672         gchar separator;
2673         gint ok;
2674         gint exists, recent, unseen;
2675         guint32 uid_validity;
2676
2677         g_return_val_if_fail(folder != NULL, -1);
2678         g_return_val_if_fail(item != NULL, -1);
2679         g_return_val_if_fail(item->path != NULL, -1);
2680         g_return_val_if_fail(name != NULL, -1);
2681
2682         debug_print("getting session...\n");
2683         session = imap_session_get(folder);
2684         if (!session) {
2685                 return -1;
2686         }
2687
2688         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
2689                 is_fatal(ok)) {
2690                 g_warning(_("New folder name must not contain the namespace "
2691                             "path separator"));
2692                 return -1;
2693         }
2694
2695         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2696         if (is_fatal(ok)) {
2697                 return -1;
2698         }
2699
2700         g_free(session->mbox);
2701         session->mbox = NULL;
2702         session->exists = 0;
2703         session->recent = 0;
2704         session->expunge = 0;
2705         ok = imap_cmd_examine(session, "INBOX",
2706                               &exists, &recent, &unseen, &uid_validity, FALSE);
2707         if (ok != MAILIMAP_NO_ERROR) {
2708                 g_free(real_oldpath);
2709                 return -1;
2710         }
2711
2712         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
2713         if (is_fatal(ok))
2714                 return -1;
2715         if (strchr(item->path, G_DIR_SEPARATOR)) {
2716                 dirpath = g_path_get_dirname(item->path);
2717                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2718                 g_free(dirpath);
2719         } else
2720                 newpath = g_strdup(name);
2721
2722         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
2723         imap_path_separator_subst(real_newpath, separator);
2724
2725         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2726         if (ok != MAILIMAP_NO_ERROR) {
2727                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2728                             real_oldpath, real_newpath);
2729                 g_free(real_oldpath);
2730                 g_free(newpath);
2731                 g_free(real_newpath);
2732                 return -1;
2733         }
2734         g_free(item->name);
2735         item->name = g_strdup(name);
2736
2737         old_cache_dir = folder_item_get_path(item);
2738
2739         paths[0] = g_strdup(item->path);
2740         paths[1] = newpath;
2741         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2742                         imap_rename_folder_func, paths);
2743
2744         if (is_dir_exist(old_cache_dir)) {
2745                 new_cache_dir = folder_item_get_path(item);
2746                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2747                         FILE_OP_ERROR(old_cache_dir, "rename");
2748                 }
2749                 g_free(new_cache_dir);
2750         }
2751
2752         g_free(old_cache_dir);
2753         g_free(paths[0]);
2754         g_free(newpath);
2755         g_free(real_oldpath);
2756         g_free(real_newpath);
2757         return 0;
2758 }
2759
2760 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2761 {
2762         gchar *path;
2763         gint r = -1;
2764         IMAPSession *session;
2765         debug_print("getting session...\n");
2766
2767         session = imap_session_get(folder);
2768         if (!session) {
2769                 return -1;
2770         }
2771         if (item && item->path) {
2772                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2773                 if (!path || is_fatal(r))
2774                         return -1;
2775                 if (!strcmp(path, "INBOX") && sub == FALSE)
2776                         return -1;
2777                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2778                 r = imap_threaded_subscribe(folder, path, sub);
2779                 g_free(path);
2780         } else if (rpath) {
2781                 r = imap_threaded_subscribe(folder, rpath, sub);
2782         } else
2783                 return -1;
2784         return r;
2785 }
2786
2787 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2788 {
2789         gint ok;
2790         IMAPSession *session;
2791         gchar *path;
2792         gchar *cache_dir;
2793         gboolean selected_folder;
2794
2795         g_return_val_if_fail(folder != NULL, -1);
2796         g_return_val_if_fail(item != NULL, -1);
2797         g_return_val_if_fail(item->path != NULL, -1);
2798
2799         debug_print("getting session...\n");
2800         session = imap_session_get(folder);
2801         if (!session) {
2802                 return -1;
2803         }
2804         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2805         if (is_fatal(ok))
2806                 return -1;
2807
2808         imap_threaded_subscribe(folder, path, FALSE);
2809
2810         selected_folder = (session->mbox != NULL) &&
2811                           (!strcmp(session->mbox, item->path));
2812         if (selected_folder) {
2813                 ok = imap_cmd_close(session);
2814                 if (ok != MAILIMAP_NO_ERROR) {
2815                         debug_print("close err %d\n", ok);
2816                         return ok;
2817                 }
2818         }
2819         ok = imap_cmd_delete(session, path);
2820         if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
2821                 gchar *tmp = g_strdup_printf("%s%c", path, 
2822                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
2823                 g_free(path);
2824                 path = tmp;
2825                 if (!is_fatal(ok))
2826                         ok = imap_cmd_delete(session, path);
2827         }
2828
2829         if (ok != MAILIMAP_NO_ERROR) {
2830                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2831                 g_free(path);
2832                 return -1;
2833         }
2834
2835         g_free(path);
2836         cache_dir = folder_item_get_path(item);
2837         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2838                 g_warning("can't remove directory '%s'\n", cache_dir);
2839         g_free(cache_dir);
2840         folder_item_remove(item);
2841         return 0;
2842 }
2843
2844 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2845 {
2846         GNode *node, *next;
2847
2848         g_return_val_if_fail(item != NULL, -1);
2849         g_return_val_if_fail(item->folder != NULL, -1);
2850         g_return_val_if_fail(item->node != NULL, -1);
2851
2852         node = item->node->children;
2853         while (node != NULL) {
2854                 next = node->next;
2855                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2856                         return -1;
2857                 node = next;
2858         }
2859         debug_print("IMAP removing %s\n", item->path);
2860
2861         if (imap_remove_all_msg(folder, item) < 0)
2862                 return -1;
2863         return imap_remove_folder_real(folder, item);
2864 }
2865
2866 typedef struct _uncached_data {
2867         IMAPSession *session;
2868         FolderItem *item;
2869         MsgNumberList *numlist;
2870         guint cur;
2871         guint total;
2872         gboolean done;
2873         int ok;
2874 } uncached_data;
2875
2876 static void *imap_get_uncached_messages_thread(void *data)
2877 {
2878         uncached_data *stuff = (uncached_data *)data;
2879         IMAPSession *session = stuff->session;
2880         FolderItem *item = stuff->item;
2881         MsgNumberList *numlist = stuff->numlist;
2882         GSList *newlist = NULL;
2883         GSList *llast = NULL;
2884         GSList *seq_list, *cur;
2885         gboolean got_alien_tags = FALSE;
2886
2887         debug_print("uncached_messages\n");
2888         
2889         if (session == NULL || item == NULL || item->folder == NULL
2890             || FOLDER_CLASS(item->folder) != &imap_class) {
2891                 stuff->done = TRUE;
2892                 return NULL;
2893         }
2894         
2895         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2896         debug_print("get msgs info\n");
2897         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2898                 struct mailimap_set * imapset;
2899                 unsigned int i;
2900                 int r;
2901                 carray * env_list;
2902                 int count;
2903                 
2904                 if (session->cancelled)
2905                         break;
2906                 
2907                 imapset = cur->data;
2908                 
2909                 r = imap_threaded_fetch_env(session->folder,
2910                                             imapset, &env_list);
2911                 if (r != MAILIMAP_NO_ERROR) {
2912                         imap_handle_error(SESSION(session), r);
2913                         if (is_fatal(r)) {
2914                                 stuff->ok = r;
2915                                 return NULL;
2916                         }
2917                         continue;
2918                 }
2919
2920                 session_set_access_time(SESSION(session));
2921
2922                 count = 0;
2923                 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
2924                         struct imap_fetch_env_info * info;
2925                         MsgInfo * msginfo;
2926                         GSList *tags = NULL, *cur = NULL;
2927                         info = carray_get(env_list, i);
2928                         tags = carray_get(env_list, i+1);
2929                         msginfo = imap_envelope_from_lep(info, item);
2930                         if (msginfo == NULL) {
2931                                 slist_free_strings(tags);
2932                                 g_slist_free(tags);
2933                                 continue;
2934                         }
2935                         if (tags != NULL) {
2936                                 g_slist_free(msginfo->tags);
2937                                 msginfo->tags = NULL;
2938                         }
2939                         for (cur = tags; cur; cur = cur->next) {
2940                                 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
2941                                 gint id = 0;
2942                                 id = tags_get_id_for_str(real_tag);
2943                                 if (id == -1) {
2944                                         id = tags_add_tag(real_tag);
2945                                         got_alien_tags = TRUE;
2946                                 }
2947                                 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
2948                                         msginfo->tags = g_slist_append(
2949                                                         msginfo->tags,
2950                                                         GINT_TO_POINTER(id));
2951                                 }
2952                                 g_free(real_tag);
2953                         }
2954                         slist_free_strings(tags);
2955                         g_slist_free(tags);
2956                         msginfo->folder = item;
2957                         if (!newlist)
2958                                 llast = newlist = g_slist_append(newlist, msginfo);
2959                         else {
2960                                 llast = g_slist_append(llast, msginfo);
2961                                 llast = llast->next;
2962                         }
2963                         count ++;
2964                 }
2965                 
2966                 imap_fetch_env_free(env_list);
2967         }
2968         
2969         if (got_alien_tags) {
2970                 tags_write_tags();
2971                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
2972         }
2973
2974         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2975                 struct mailimap_set * imapset;
2976                 
2977                 imapset = cur->data;
2978                 mailimap_set_free(imapset);
2979         }
2980         
2981         session_set_access_time(SESSION(session));
2982         stuff->done = TRUE;
2983         return newlist;
2984 }
2985
2986 #define MAX_MSG_NUM 50
2987
2988 static GSList *imap_get_uncached_messages(IMAPSession *session,
2989                                         FolderItem *item,
2990                                         MsgNumberList *numlist,
2991                                         int *r)
2992 {
2993         GSList *result = NULL;
2994         GSList * cur;
2995         uncached_data *data = g_new0(uncached_data, 1);
2996         int finished;
2997         
2998         finished = 0;
2999         cur = numlist;
3000         data->total = g_slist_length(numlist);
3001         data->ok = MAILIMAP_NO_ERROR;
3002         debug_print("messages list : %i\n", data->total);
3003
3004         while (cur != NULL) {
3005                 GSList * partial_result;
3006                 int count;
3007                 GSList * newlist;
3008                 GSList * llast;
3009                 
3010                 llast = NULL;
3011                 count = 0;
3012                 newlist = NULL;
3013                 while (count < MAX_MSG_NUM) {
3014                         void * p;
3015                         
3016                         p = cur->data;
3017                         
3018                         if (newlist == NULL)
3019                                 llast = newlist = g_slist_append(newlist, p);
3020                         else {
3021                                 llast = g_slist_append(llast, p);
3022                                 llast = llast->next;
3023                         }
3024                         count ++;
3025                         
3026                         cur = cur->next;
3027                         if (cur == NULL)
3028                                 break;
3029                 }
3030                 
3031                 data->done = FALSE;
3032                 data->session = session;
3033                 data->item = item;
3034                 data->numlist = newlist;
3035                 data->cur += count;
3036                 
3037                 if (prefs_common.work_offline && 
3038                     !inc_offline_should_override(FALSE,
3039                         _("Claws Mail needs network access in order "
3040                           "to access the IMAP server."))) {
3041                         g_free(data);
3042                         return NULL;
3043                 }
3044                 
3045                 partial_result =
3046                         (GSList *)imap_get_uncached_messages_thread(data);
3047                 *r = data->ok;
3048                 if (data->ok != MAILIMAP_NO_ERROR) {
3049                         goto bail;
3050                 }
3051                 statusbar_progress_all(data->cur,data->total, 1);
3052                 
3053                 g_slist_free(newlist);
3054                 
3055                 result = g_slist_concat(result, partial_result);
3056         }
3057 bail:
3058         g_free(data);
3059         
3060         statusbar_progress_all(0,0,0);
3061         statusbar_pop_all();
3062         
3063         return result;
3064 }
3065
3066 static void imap_delete_all_cached_messages(FolderItem *item)
3067 {
3068         gchar *dir;
3069
3070         g_return_if_fail(item != NULL);
3071         g_return_if_fail(item->folder != NULL);
3072         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3073
3074         debug_print("Deleting all cached messages...\n");
3075
3076         dir = folder_item_get_path(item);
3077         if (is_dir_exist(dir))
3078                 remove_all_numbered_files(dir);
3079         g_free(dir);
3080
3081         debug_print("done.\n");
3082 }
3083
3084 gchar imap_get_path_separator_for_item(FolderItem *item)
3085 {
3086         Folder *folder = NULL;
3087         IMAPFolder *imap_folder = NULL;
3088         IMAPSession *session = NULL;
3089         gchar result = '/';
3090         gint ok;
3091         if (!item)
3092                 return '/';
3093         folder = item->folder;
3094         
3095         if (!folder)
3096                 return '/';
3097         
3098         imap_folder = IMAP_FOLDER(folder);
3099         
3100         if (!imap_folder)
3101                 return '/';
3102         
3103         debug_print("getting session...");
3104         session = imap_session_get(FOLDER(folder));
3105         result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3106         return result;
3107 }
3108
3109 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3110 {
3111         clist * lep_list;
3112         int r;
3113         gchar separator = '\0';
3114         
3115         g_return_val_if_fail(session != NULL, '/');
3116         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3117         
3118         if (r != MAILIMAP_NO_ERROR) {
3119                 imap_handle_error(SESSION(session), r);
3120                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3121                 *ok = r;
3122                 return '\0';
3123         }
3124
3125         if (clist_count(lep_list) > 0) {
3126                 clistiter * iter = clist_begin(lep_list); 
3127                 struct mailimap_mailbox_list * mb;
3128                 mb = clist_content(iter);
3129
3130                 separator = mb->mb_delimiter;
3131                 debug_print("got separator: %c\n", folder->last_seen_separator);
3132         }
3133         *ok = MAILIMAP_NO_ERROR;
3134         mailimap_list_result_free(lep_list);
3135         return separator;
3136 }
3137
3138 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3139 {
3140         gchar separator = '/';
3141
3142         if (folder->last_seen_separator == 0) {
3143                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3144         }
3145
3146         if (folder->last_seen_separator == 0) {
3147                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3148         }
3149
3150         if (folder->last_seen_separator != 0) {
3151                 debug_print("using separator: %c\n", folder->last_seen_separator);
3152                 return folder->last_seen_separator;
3153         }
3154
3155         return separator;
3156 }
3157
3158 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3159 {
3160         gchar *real_path;
3161         gchar separator;
3162
3163         g_return_val_if_fail(folder != NULL, NULL);
3164         g_return_val_if_fail(path != NULL, NULL);
3165
3166         real_path = imap_utf8_to_modified_utf7(path, FALSE);
3167         separator = imap_get_path_separator(session, folder, path, ok);
3168         imap_path_separator_subst(real_path, separator);
3169
3170         return real_path;
3171 }
3172
3173 static gint imap_set_message_flags(IMAPSession *session,
3174                                    IMAPFolderItem *item,
3175                                    MsgNumberList *numlist,
3176                                    IMAPFlags flags,
3177                                    GSList *tags,
3178                                    gboolean is_set)
3179 {
3180         gint ok = 0;
3181         GSList *seq_list;
3182         GSList * cur;
3183         gint total = 0;
3184         IMAPFolder *folder = NULL;
3185         GSList *sorted_list = NULL;
3186
3187         if (numlist == NULL || session == NULL)
3188                 return MAILIMAP_ERROR_BAD_STATE;
3189         
3190         folder = IMAP_FOLDER(session->folder);
3191         
3192         sorted_list = g_slist_copy(numlist);
3193         sorted_list = g_slist_sort(sorted_list, g_int_compare);
3194         
3195         cur = g_slist_last(sorted_list);
3196
3197         if (cur)
3198                 total = GPOINTER_TO_INT(cur->data);
3199         
3200         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3201
3202         statusbar_print_all(_("Flagging messages..."));
3203
3204         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3205                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3206                 struct mailimap_set_item *set_item = clist_content(
3207                                                         clist_begin(imapset->set_list));
3208
3209                 statusbar_progress_all(set_item->set_first, total, 1);
3210
3211                 ok = imap_cmd_store(session, item, imapset,
3212                                     flags, tags, is_set);
3213                 statusbar_progress_all(set_item->set_last, total, 1);
3214                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3215                         /* reduce max set size */
3216                         folder->max_set_size /= 2;
3217                 }
3218                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3219                         break;
3220                 }
3221         }
3222         
3223         g_slist_free(sorted_list);
3224
3225         statusbar_progress_all(0,0,0);
3226         statusbar_pop_all();
3227
3228         imap_lep_set_free(seq_list);
3229         
3230         return ok;
3231 }
3232
3233 typedef struct _select_data {
3234         IMAPSession *session;
3235         gchar *real_path;
3236         gint *exists;
3237         gint *recent;
3238         gint *unseen;
3239         guint32 *uid_validity;
3240         gboolean done;
3241 } select_data;
3242
3243 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3244                         FolderItem *item,
3245                         gint *exists, gint *recent, gint *unseen,
3246                         guint32 *uid_validity, gint *can_create_flags,
3247                         gboolean block)
3248 {
3249         gchar *real_path;
3250         gint ok;
3251         gint exists_, recent_, unseen_;
3252         guint32 uid_validity_;
3253         gint can_create_flags_;
3254         const gchar *path = item ? item->path:NULL;
3255
3256         if (!item) {
3257                 return MAILIMAP_ERROR_BAD_STATE;
3258         }
3259
3260         if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3261                 if (session->mbox && strcmp(session->mbox, path) == 0)
3262                         return MAILIMAP_NO_ERROR;
3263         }
3264         if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3265                 if (session->mbox && strcmp(session->mbox, path) == 0) {
3266                         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3267                                 return MAILIMAP_NO_ERROR;
3268                 }
3269         }
3270         if (!exists)
3271                 exists = &exists_;
3272         if (!recent)
3273                 recent = &recent_;
3274         if (!unseen)
3275                 unseen = &unseen_;
3276         if (!uid_validity)
3277                 uid_validity = &uid_validity_;
3278         if (!can_create_flags)
3279                 can_create_flags = &can_create_flags_;
3280
3281         g_free(session->mbox);
3282         session->mbox = NULL;
3283         session->exists = 0;
3284         session->recent = 0;
3285         session->expunge = 0;
3286
3287         real_path = imap_get_real_path(session, folder, path, &ok);
3288         if (is_fatal(ok))
3289                 return ok;              
3290         g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3291         IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3292         ok = imap_cmd_select(session, real_path,
3293                              exists, recent, unseen, uid_validity, can_create_flags, 
3294                              &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3295         if (ok != MAILIMAP_NO_ERROR) {
3296                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3297         } else {
3298                 session->mbox = g_strdup(path);
3299                 session->folder_content_changed = FALSE;
3300                 session->exists = *exists;
3301                 session->recent = *recent;
3302                 session->expunge = 0;
3303                 session->unseen = *unseen;
3304                 session->uid_validity = *uid_validity;
3305                 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
3306                         session->exists, session->recent, session->expunge,
3307                         session->uid_validity, *can_create_flags);
3308         }
3309         if (*can_create_flags) {
3310                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3311         } else {
3312                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3313         }
3314         g_free(real_path);
3315
3316         return ok;
3317 }
3318
3319 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3320                         const gchar *path, IMAPFolderItem *item,
3321                         gint *messages,
3322                         guint32 *uid_next, guint32 *uid_validity,
3323                         gint *unseen, gboolean block)
3324 {
3325         int r;
3326         clistiter * iter;
3327         struct mailimap_mailbox_data_status * data_status;
3328         int got_values;
3329         gchar *real_path;
3330         guint mask = 0;
3331         
3332         real_path = imap_get_real_path(session, folder, path, &r);
3333         if (is_fatal(r))
3334                 return r;
3335
3336         if (messages) {
3337                 mask |= 1 << 0;
3338                 *messages = 0;
3339         }
3340         if (uid_next) {
3341                 mask |= 1 << 2;
3342                 *uid_next = 0;
3343         }
3344         if (uid_validity) {
3345                 mask |= 1 << 3;
3346                 *uid_validity = 0;
3347         }
3348         if (unseen) {
3349                 mask |= 1 << 4;
3350                 *unseen = 0;
3351         }
3352         
3353         if (session->mbox != NULL &&
3354             !strcmp(session->mbox, item->item.path)) {
3355                 r = imap_cmd_close(session);
3356                 if (r != MAILIMAP_NO_ERROR) {
3357                         debug_print("close err %d\n", r);
3358                         return r;
3359                 }
3360         }
3361         
3362         r = imap_threaded_status(FOLDER(folder), real_path, 
3363                 &data_status, mask);
3364
3365         g_free(real_path);
3366         if (r != MAILIMAP_NO_ERROR) {
3367                 imap_handle_error(SESSION(session), r);
3368                 debug_print("status err %d\n", r);
3369                 return r;
3370         }
3371         
3372         if (data_status->st_info_list == NULL) {
3373                 mailimap_mailbox_data_status_free(data_status);
3374                 debug_print("status->st_info_list == NULL\n");
3375                 return MAILIMAP_ERROR_BAD_STATE;
3376         }
3377         
3378         got_values = 0;
3379         for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
3380             iter = clist_next(iter)) {
3381                 struct mailimap_status_info * info;             
3382                 
3383                 info = clist_content(iter);
3384                 switch (info->st_att) {
3385                 case MAILIMAP_STATUS_ATT_MESSAGES:
3386                         if (messages) {
3387                                 * messages = info->st_value;
3388                                 got_values |= 1 << 0;
3389                         }
3390                         break;
3391                         
3392                 case MAILIMAP_STATUS_ATT_UIDNEXT:
3393                         if (uid_next) {
3394                                 * uid_next = info->st_value;
3395                                 got_values |= 1 << 2;
3396                         }
3397                         break;
3398                         
3399                 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
3400                         if (uid_validity) {
3401                                 * uid_validity = info->st_value;
3402                                 got_values |= 1 << 3;
3403                         }
3404                         break;
3405                         
3406                 case MAILIMAP_STATUS_ATT_UNSEEN:
3407                         if (unseen) {
3408                                 * unseen = info->st_value;
3409                                 got_values |= 1 << 4;
3410                         }
3411                         break;
3412                 }
3413         }
3414         mailimap_mailbox_data_status_free(data_status);
3415         
3416         if (got_values != mask) {
3417                 g_warning("status: incomplete values received (%d)\n", got_values);
3418         }
3419         return MAILIMAP_NO_ERROR;
3420 }
3421
3422 static void imap_free_capabilities(IMAPSession *session)
3423 {
3424         slist_free_strings(session->capability);
3425         g_slist_free(session->capability);
3426         session->capability = NULL;
3427 }
3428
3429 /* low-level IMAP4rev1 commands */
3430
3431 static gint imap_cmd_login(IMAPSession *session,
3432                            const gchar *user, const gchar *pass,
3433                            const gchar *type)
3434 {
3435         int r;
3436         gint ok;
3437
3438         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
3439                 gint ok = MAILIMAP_ERROR_BAD_STATE;
3440                 if (imap_has_capability(session, "STARTTLS")) {
3441 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3442                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
3443                         ok = imap_cmd_starttls(session);
3444                         if (ok != MAILIMAP_NO_ERROR) {
3445                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
3446                                 return ok;
3447                         } else {
3448                                 /* refresh capas */
3449                                 imap_free_capabilities(session);
3450                                 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
3451                                         imap_handle_error(SESSION(session), r);
3452                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
3453                                         return r;
3454                                 }
3455                         }
3456 #else           
3457                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
3458                                         "server requires TLS, but Claws Mail "
3459                                         "has been compiled without OpenSSL "
3460                                         "support.\n"),
3461                                         SESSION(session)->server);
3462                         return MAILIMAP_ERROR_LOGIN;
3463 #endif
3464                 } else {
3465                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
3466                         return MAILIMAP_ERROR_LOGIN;
3467                 }
3468         }
3469
3470         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
3471                         user,
3472                         SESSION(session)->server,
3473                         type);
3474         r = imap_threaded_login(session->folder, user, pass, type);
3475         if (r != MAILIMAP_NO_ERROR) {
3476                 imap_handle_error(SESSION(session), r);
3477                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
3478                                 SESSION(session)->server);
3479                 ok = r;
3480         } else {
3481                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
3482                                 SESSION(session)->server);
3483                 ok = MAILIMAP_NO_ERROR;
3484         }
3485         return ok;
3486 }
3487
3488 static gint imap_cmd_noop(IMAPSession *session)
3489 {
3490         int r;
3491         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
3492         
3493         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
3494         if (r != MAILIMAP_NO_ERROR) {
3495                 imap_handle_error(SESSION(session), r);
3496                 debug_print("noop err %d\n", r);
3497                 return r;
3498         }
3499
3500         session->folder_content_changed = FALSE;
3501
3502         if ((exists && exists != session->exists)
3503          || (recent && recent != session->recent)
3504          || (expunge && expunge != session->expunge)
3505          || (unseen && unseen != session->unseen)) {
3506                 session->folder_content_changed = TRUE;
3507         }
3508         if (uidnext != 0 && uidnext != session->uid_next) {
3509                 session->uid_next = uidnext;
3510                 session->folder_content_changed = TRUE;
3511         }
3512         if (uidval != 0 && uidval != session->uid_validity) {
3513                 session->uid_validity = uidval;
3514                 session->folder_content_changed = TRUE;
3515         }
3516
3517         session->exists = exists;
3518         session->recent = recent;
3519         session->expunge = expunge;
3520         session->unseen = unseen;
3521
3522         session_set_access_time(SESSION(session));
3523
3524         return MAILIMAP_NO_ERROR;
3525 }
3526
3527 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3528 static gint imap_cmd_starttls(IMAPSession *session)
3529 {
3530         int r;
3531         
3532         r = imap_threaded_starttls(session->folder, 
3533                 SESSION(session)->server, SESSION(session)->port);
3534         if (r != MAILIMAP_NO_ERROR) {
3535                 imap_handle_error(SESSION(session), r);
3536                 debug_print("starttls err %d\n", r);
3537                 return r;
3538         }
3539         return MAILIMAP_NO_ERROR;
3540 }
3541 #endif
3542
3543 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3544                             gint *exists, gint *recent, gint *unseen,
3545                             guint32 *uid_validity, gint *can_create_flags,
3546                             GSList **ok_flags, gboolean block)
3547 {
3548         int r;
3549
3550         r = imap_threaded_select(session->folder, folder,
3551                                  exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
3552         if (r != MAILIMAP_NO_ERROR) {
3553                 imap_handle_error(SESSION(session), r);
3554                 debug_print("select err %d\n", r);
3555                 return r;
3556         }
3557         return MAILIMAP_NO_ERROR;
3558 }
3559
3560 static gint imap_cmd_close(IMAPSession *session)
3561 {
3562         int r;
3563
3564         r = imap_threaded_close(session->folder);
3565         if (r != MAILIMAP_NO_ERROR) {
3566                 imap_handle_error(SESSION(session), r);
3567                 debug_print("close err %d\n", r);
3568                 return r;
3569         }
3570         g_free(session->mbox);
3571         session->mbox = NULL;
3572         session->exists = 0;
3573         session->recent = 0;
3574         session->expunge = 0;
3575         return MAILIMAP_NO_ERROR;
3576 }
3577
3578 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3579                              gint *exists, gint *recent, gint *unseen,
3580                              guint32 *uid_validity, gboolean block)
3581 {
3582         int r;
3583
3584         r = imap_threaded_examine(session->folder, folder,
3585                                   exists, recent, unseen, uid_validity);
3586         if (r != MAILIMAP_NO_ERROR) {
3587                 imap_handle_error(SESSION(session), r);
3588                 debug_print("examine err %d\n", r);
3589                 
3590                 return r;
3591         }
3592         return MAILIMAP_NO_ERROR;
3593 }
3594
3595 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3596 {
3597         int r;
3598
3599         r = imap_threaded_create(session->folder, folder);
3600         if (r != MAILIMAP_NO_ERROR) {
3601                 imap_handle_error(SESSION(session), r);
3602                 return r;
3603         }
3604
3605         return MAILIMAP_NO_ERROR;
3606 }
3607
3608 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3609                             const gchar *new_folder)
3610 {
3611         int r;
3612
3613         r = imap_threaded_rename(session->folder, old_folder,
3614                                  new_folder);
3615         if (r != MAILIMAP_NO_ERROR) {
3616                 imap_handle_error(SESSION(session), r);
3617                 return r;
3618         }
3619
3620         return MAILIMAP_NO_ERROR;
3621 }
3622
3623 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3624 {
3625         int r;
3626         
3627
3628         r = imap_threaded_delete(session->folder, folder);
3629         if (r != MAILIMAP_NO_ERROR) {
3630                 imap_handle_error(SESSION(session), r);
3631                 return r;
3632         }
3633
3634         return MAILIMAP_NO_ERROR;
3635 }
3636
3637 typedef struct _fetch_data {
3638         IMAPSession *session;
3639         guint32 uid;
3640         const gchar *filename;
3641         gboolean headers;
3642         gboolean body;
3643         gboolean done;
3644 } fetch_data;
3645
3646 static void *imap_cmd_fetch_thread(void *data)
3647 {
3648         fetch_data *stuff = (fetch_data *)data;
3649         IMAPSession *session = stuff->session;
3650         guint32 uid = stuff->uid;
3651         const gchar *filename = stuff->filename;
3652         int r;
3653         
3654         if (stuff->body) {
3655                 r = imap_threaded_fetch_content(session->folder,
3656                                                uid, 1, filename);
3657         }
3658         else {
3659                 r = imap_threaded_fetch_content(session->folder,
3660                                                 uid, 0, filename);
3661         }
3662         if (r != MAILIMAP_NO_ERROR) {
3663                 imap_handle_error(SESSION(session), r);
3664                 debug_print("fetch err %d\n", r);
3665                 return GINT_TO_POINTER(r);
3666         }
3667         return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
3668 }
3669
3670 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3671                                 const gchar *filename, gboolean headers,
3672                                 gboolean body)
3673 {
3674         fetch_data *data = g_new0(fetch_data, 1);
3675         int result = 0;
3676         data->done = FALSE;
3677         data->session = session;
3678         data->uid = uid;
3679         data->filename = filename;
3680         data->headers = headers;
3681         data->body = body;
3682
3683         if (prefs_common.work_offline && 
3684             !inc_offline_should_override(FALSE,
3685                 _("Claws Mail needs network access in order "
3686                   "to access the IMAP server."))) {
3687                 g_free(data);
3688                 return -1;
3689         }
3690         statusbar_print_all(_("Fetching message..."));
3691         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3692         statusbar_pop_all();
3693         g_free(data);
3694         return result;
3695 }
3696
3697
3698 static gint imap_cmd_append(IMAPSession *session, 
3699                             IMAPFolderItem *item,
3700                             const gchar *destfolder,
3701                             const gchar *file, IMAPFlags flags, 
3702                             guint32 *new_uid)
3703 {
3704         struct mailimap_flag_list * flag_list;
3705         int r;
3706         
3707         g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
3708
3709         flag_list = imap_flag_to_lep(item, flags, NULL);
3710         lock_session(session);
3711         r = imap_threaded_append(session->folder, destfolder,
3712                          file, flag_list, (int *)new_uid);
3713         mailimap_flag_list_free(flag_list);
3714
3715         if (r != MAILIMAP_NO_ERROR) {
3716                 imap_handle_error(SESSION(session), r);
3717                 debug_print("append err %d\n", r);
3718                 return r;
3719         }
3720
3721         unlock_session(session);
3722
3723         return MAILIMAP_NO_ERROR;
3724 }
3725
3726 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3727                           const gchar *destfolder, GRelation *uid_mapping,
3728                           struct mailimap_set **source, struct mailimap_set **dest)
3729 {
3730         int r;
3731         
3732         g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
3733         g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
3734         g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
3735
3736         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3737         if (r != MAILIMAP_NO_ERROR) {
3738                 imap_handle_error(SESSION(session), r);
3739                 return r;
3740         }
3741
3742         return MAILIMAP_NO_ERROR;
3743 }
3744
3745 static gint imap_cmd_store(IMAPSession *session, 
3746                            IMAPFolderItem *item,
3747                            struct mailimap_set * set,
3748                            IMAPFlags flags, GSList *tags, int do_add)
3749 {
3750         int r;
3751         struct mailimap_flag_list * flag_list = NULL;
3752         struct mailimap_store_att_flags * store_att_flags;
3753         
3754         flag_list = imap_flag_to_lep(item, flags, tags);
3755
3756         if (do_add)
3757                 store_att_flags =
3758                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
3759         else
3760                 store_att_flags =
3761                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3762         
3763         r = imap_threaded_store(session->folder, set, store_att_flags);
3764         mailimap_store_att_flags_free(store_att_flags);
3765         if (r != MAILIMAP_NO_ERROR) {
3766                 imap_handle_error(SESSION(session), r);
3767                 return r;
3768         }
3769         
3770         return MAILIMAP_NO_ERROR;
3771 }
3772
3773 static gint imap_cmd_expunge(IMAPSession *session)
3774 {
3775         int r;
3776         
3777         if (prefs_common.work_offline && 
3778             !inc_offline_should_override(FALSE,
3779                 _("Claws Mail needs network access in order "
3780                   "to access the IMAP server."))) {
3781                 return -1;
3782         }
3783
3784         r = imap_threaded_expunge(session->folder);
3785         if (r != MAILIMAP_NO_ERROR) {
3786                 imap_handle_error(SESSION(session), r);
3787                 return r;
3788         }
3789
3790         return MAILIMAP_NO_ERROR;
3791 }
3792
3793 static void imap_path_separator_subst(gchar *str, gchar separator)
3794 {
3795         gchar *p;
3796         gboolean in_escape = FALSE;
3797
3798         if (!separator || separator == '/') return;
3799
3800         for (p = str; *p != '\0'; p++) {
3801                 if (*p == '/' && !in_escape)
3802                         *p = separator;
3803                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3804                         in_escape = TRUE;
3805                 else if (*p == '-' && in_escape)
3806                         in_escape = FALSE;
3807         }
3808 }
3809
3810 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3811 {
3812         FolderItem *item = node->data;
3813         gchar **paths = data;
3814         const gchar *oldpath = paths[0];
3815         const gchar *newpath = paths[1];
3816         gchar *real_oldpath, *real_newpath;
3817         gchar *base;
3818         gchar *new_itempath;
3819         gint oldpathlen;
3820         IMAPSession *session = imap_session_get(item->folder);
3821         gint ok;
3822         oldpathlen = strlen(oldpath);
3823         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3824                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3825                 return TRUE;
3826         }
3827
3828         base = item->path + oldpathlen;
3829         while (*base == G_DIR_SEPARATOR) base++;
3830         if (*base == '\0')
3831                 new_itempath = g_strdup(newpath);
3832         else
3833                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3834                                            NULL);
3835
3836         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
3837         g_free(item->path);
3838         item->path = new_itempath;
3839         
3840         real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
3841         
3842         imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
3843         imap_threaded_subscribe(item->folder, real_newpath, TRUE);
3844
3845         g_free(real_oldpath);
3846         g_free(real_newpath);
3847         return FALSE;
3848 }
3849
3850 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
3851 {
3852         GSList *uidlist, *elem;
3853         int r = -1;
3854         clist * lep_uidlist;
3855         gint ok, nummsgs = 0, lastuid_old;
3856
3857         if (session == NULL) {
3858                 return -1;
3859         }
3860
3861         ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
3862                          NULL, NULL, NULL, NULL, NULL, TRUE);
3863         if (ok != MAILIMAP_NO_ERROR) {
3864                 return -1;
3865         }
3866
3867         g_slist_free(item->uid_list);
3868         item->uid_list = NULL;
3869
3870         uidlist = NULL;
3871         
3872         if (folder->account && folder->account->low_bandwidth) {
3873                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
3874                                  &lep_uidlist);
3875         }
3876         
3877         if (r == MAILIMAP_NO_ERROR) {
3878                 GSList * fetchuid_list =
3879                         imap_uid_list_from_lep(lep_uidlist);
3880                 mailimap_search_result_free(lep_uidlist);
3881                 
3882                 uidlist = g_slist_concat(fetchuid_list, uidlist);
3883         } else {
3884                 carray * lep_uidtab;
3885                 if (r != -1) { /* inited */
3886                         imap_handle_error(SESSION(session), r);
3887                         if (is_fatal(r))
3888                                 return -1;
3889                 }
3890                 r = imap_threaded_fetch_uid(folder, 1,
3891                                     &lep_uidtab);
3892                 if (r == MAILIMAP_NO_ERROR) {
3893                         GSList * fetchuid_list =
3894                                 imap_uid_list_from_lep_tab(lep_uidtab);
3895                         imap_fetch_uid_list_free(lep_uidtab);
3896                         uidlist = g_slist_concat(fetchuid_list, uidlist);
3897                 }
3898         }
3899         
3900         if (r != MAILIMAP_NO_ERROR) {
3901                 imap_handle_error(SESSION(session), r);
3902                 return -1;
3903         }
3904
3905         lastuid_old = item->lastuid;
3906
3907         for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
3908                 guint msgnum;
3909
3910                 msgnum = GPOINTER_TO_INT(elem->data);
3911
3912                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
3913                 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
3914                 nummsgs++;
3915         }
3916         g_slist_free(uidlist);
3917
3918         unlock_session(session); /* locked from imap_get_num_list */
3919
3920         return nummsgs;
3921
3922 }
3923
3924 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)