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