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