1f30f10326bab5745079a70633f4c60e70c6bb60
[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         
968         if (info == NULL)
969                 return -1;
970         
971         fp = procmsg_open_message(info);
972         if (!fp)
973                 return -1;
974         
975         while (fgets(buf, sizeof (buf), fp) != NULL) {
976                 cnt += strlen(buf);
977                 if (!strstr(buf, "\r") && strstr(buf, "\n"))
978                         cnt++;
979         }
980         
981         fclose(fp);
982         return cnt;
983 }
984
985 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
986                                   gboolean headers, gboolean body)
987 {
988         gchar *path, *filename;
989         IMAPSession *session;
990         gint ok;
991
992         g_return_val_if_fail(folder != NULL, NULL);
993         g_return_val_if_fail(item != NULL, NULL);
994
995         if (uid == 0)
996                 return NULL;
997
998         path = folder_item_get_path(item);
999         if (!is_dir_exist(path))
1000                 make_dir_hier(path);
1001         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1002         g_free(path);
1003
1004         if (is_file_exist(filename)) {
1005                 /* see whether the local file represents the whole message
1006                  * or not. As the IMAP server reports size with \r chars,
1007                  * we have to update the local file (UNIX \n only) size */
1008                 MsgInfo *msginfo = imap_parse_msg(filename, item);
1009                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1010                 guint have_size = get_size_with_lfs(msginfo);
1011                 debug_print("message %d has been already %scached (%d/%d).\n", uid,
1012                                 have_size == cached->size ? "fully ":"",
1013                                 have_size, cached? (int)cached->size : -1);
1014                                 
1015                 if (cached && (cached->size == have_size || !body)) {
1016                         procmsg_msginfo_free(cached);
1017                         procmsg_msginfo_free(msginfo);
1018                         return filename;
1019                 } else {
1020                         procmsg_msginfo_free(cached);
1021                         procmsg_msginfo_free(msginfo);
1022                 }
1023         }
1024
1025         session = imap_session_get(folder);
1026         if (!session) {
1027                 g_free(filename);
1028                 return NULL;
1029         }
1030
1031         debug_print("IMAP fetching messages\n");
1032         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1033                          NULL, NULL, NULL, NULL, FALSE);
1034         if (ok != IMAP_SUCCESS) {
1035                 g_warning("can't select mailbox %s\n", item->path);
1036                 g_free(filename);
1037                 return NULL;
1038         }
1039
1040         debug_print("getting message %d...\n", uid);
1041         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1042
1043         if (ok != IMAP_SUCCESS) {
1044                 g_warning("can't fetch message %d\n", uid);
1045                 g_free(filename);
1046                 return NULL;
1047         }
1048
1049         return filename;
1050 }
1051
1052 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1053                          const gchar *file, MsgFlags *flags)
1054 {
1055         gint ret;
1056         GSList file_list;
1057         MsgFileInfo fileinfo;
1058
1059         g_return_val_if_fail(file != NULL, -1);
1060
1061         fileinfo.msginfo = NULL;
1062         fileinfo.file = (gchar *)file;
1063         fileinfo.flags = flags;
1064         file_list.data = &fileinfo;
1065         file_list.next = NULL;
1066
1067         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1068         return ret;
1069 }
1070
1071 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1072                    GRelation *relation)
1073 {
1074         gchar *destdir;
1075         IMAPSession *session;
1076         guint32 last_uid = 0;
1077         GSList *cur;
1078         MsgFileInfo *fileinfo;
1079         gint ok;
1080
1081         g_return_val_if_fail(folder != NULL, -1);
1082         g_return_val_if_fail(dest != NULL, -1);
1083         g_return_val_if_fail(file_list != NULL, -1);
1084
1085         session = imap_session_get(folder);
1086         if (!session) return -1;
1087
1088         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
1089
1090         for (cur = file_list; cur != NULL; cur = cur->next) {
1091                 IMAPFlags iflags = 0;
1092                 guint32 new_uid = 0;
1093
1094                 fileinfo = (MsgFileInfo *)cur->data;
1095
1096                 if (fileinfo->flags) {
1097                         if (MSG_IS_MARKED(*fileinfo->flags))
1098                                 iflags |= IMAP_FLAG_FLAGGED;
1099                         if (MSG_IS_REPLIED(*fileinfo->flags))
1100                                 iflags |= IMAP_FLAG_ANSWERED;
1101                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1102                                 iflags |= IMAP_FLAG_SEEN;
1103                 }
1104
1105                 if (dest->stype == F_OUTBOX ||
1106                     dest->stype == F_QUEUE  ||
1107                     dest->stype == F_DRAFT  ||
1108                     dest->stype == F_TRASH)
1109                         iflags |= IMAP_FLAG_SEEN;
1110
1111                 ok = imap_cmd_append(session, destdir, fileinfo->file, iflags, 
1112                                      &new_uid);
1113
1114                 if (ok != IMAP_SUCCESS) {
1115                         g_warning("can't append message %s\n", fileinfo->file);
1116                         g_free(destdir);
1117                         return -1;
1118                 }
1119
1120                 if (relation != NULL)
1121                         g_relation_insert(relation, fileinfo->msginfo != NULL ? 
1122                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1123                                           GINT_TO_POINTER(dest->last_num + 1));
1124                 if (last_uid < new_uid)
1125                         last_uid = new_uid;
1126         }
1127
1128         g_free(destdir);
1129
1130         return last_uid;
1131 }
1132
1133 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1134                               MsgInfoList *msglist, GRelation *relation)
1135 {
1136         FolderItem *src;
1137         gchar *destdir;
1138         GSList *seq_list, *cur;
1139         MsgInfo *msginfo;
1140         IMAPSession *session;
1141         gint ok = IMAP_SUCCESS;
1142         GRelation *uid_mapping;
1143         gint last_num = 0;
1144         
1145         g_return_val_if_fail(folder != NULL, -1);
1146         g_return_val_if_fail(dest != NULL, -1);
1147         g_return_val_if_fail(msglist != NULL, -1);
1148
1149         session = imap_session_get(folder);
1150         if (!session) {
1151                 return -1;
1152         }
1153         msginfo = (MsgInfo *)msglist->data;
1154
1155         src = msginfo->folder;
1156         if (src == dest) {
1157                 g_warning("the src folder is identical to the dest.\n");
1158                 return -1;
1159         }
1160
1161         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
1162                          NULL, NULL, NULL, NULL, FALSE);
1163         if (ok != IMAP_SUCCESS) {
1164                 return ok;
1165         }
1166
1167         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
1168         seq_list = imap_get_seq_set_from_msglist(msglist);
1169         uid_mapping = g_relation_new(2);
1170         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1171         
1172         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1173                 gchar *seq_set = (gchar *)cur->data;
1174
1175                 debug_print("Copying message %s%c[%s] to %s ...\n",
1176                             src->path, G_DIR_SEPARATOR,
1177                             seq_set, destdir);
1178
1179                 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping);
1180                 if (ok != IMAP_SUCCESS) {
1181                         g_relation_destroy(uid_mapping);
1182                         imap_seq_set_free(seq_list);
1183                         return -1;
1184                 }
1185         }
1186
1187         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1188                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1189                 GTuples *tuples;
1190
1191                 tuples = g_relation_select(uid_mapping, 
1192                                            GINT_TO_POINTER(msginfo->msgnum),
1193                                            0);
1194                 if (tuples->len > 0) {
1195                         gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1196                         g_relation_insert(relation, msginfo,
1197                                           GPOINTER_TO_INT(num));
1198                         if (num > last_num)
1199                                 last_num = num;
1200                 } else
1201                         g_relation_insert(relation, msginfo,
1202                                           GPOINTER_TO_INT(0));
1203                 g_tuples_destroy(tuples);
1204         }
1205
1206         g_relation_destroy(uid_mapping);
1207         imap_seq_set_free(seq_list);
1208
1209         g_free(destdir);
1210         
1211         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1212         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1213         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1214         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1215
1216         if (ok == IMAP_SUCCESS)
1217                 return last_num;
1218         else
1219                 return -1;
1220 }
1221
1222 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1223 {
1224         GSList msglist;
1225
1226         g_return_val_if_fail(msginfo != NULL, -1);
1227
1228         msglist.data = msginfo;
1229         msglist.next = NULL;
1230
1231         return imap_copy_msgs(folder, dest, &msglist, NULL);
1232 }
1233
1234 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1235                     MsgInfoList *msglist, GRelation *relation)
1236 {
1237         MsgInfo *msginfo;
1238         GSList *file_list;
1239         gint ret;
1240
1241         g_return_val_if_fail(folder != NULL, -1);
1242         g_return_val_if_fail(dest != NULL, -1);
1243         g_return_val_if_fail(msglist != NULL, -1);
1244
1245         msginfo = (MsgInfo *)msglist->data;
1246         g_return_val_if_fail(msginfo->folder != NULL, -1);
1247
1248         if (folder == msginfo->folder->folder)
1249                 return imap_do_copy_msgs(folder, dest, msglist, relation);
1250
1251         file_list = procmsg_get_message_file_list(msglist);
1252         g_return_val_if_fail(file_list != NULL, -1);
1253
1254         ret = imap_add_msgs(folder, dest, file_list, relation);
1255
1256         procmsg_message_file_list_free(file_list);
1257
1258         return ret;
1259 }
1260
1261
1262 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1263                                 MsgInfoList *msglist, GRelation *relation)
1264 {
1265         gchar *destdir;
1266         GSList *seq_list = NULL, *cur;
1267         MsgInfo *msginfo;
1268         IMAPSession *session;
1269         gint ok = IMAP_SUCCESS;
1270         GRelation *uid_mapping;
1271         
1272         g_return_val_if_fail(folder != NULL, -1);
1273         g_return_val_if_fail(dest != NULL, -1);
1274         g_return_val_if_fail(msglist != NULL, -1);
1275
1276         session = imap_session_get(folder);
1277         if (!session) {
1278                 return -1;
1279         }
1280         msginfo = (MsgInfo *)msglist->data;
1281
1282         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
1283                          NULL, NULL, NULL, NULL, FALSE);
1284         if (ok != IMAP_SUCCESS) {
1285                 return ok;
1286         }
1287
1288         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
1289         for (cur = msglist; cur; cur = cur->next) {
1290                 msginfo = (MsgInfo *)cur->data;
1291                 seq_list = g_slist_append(seq_list, GINT_TO_POINTER(msginfo->msgnum));
1292         }
1293
1294         uid_mapping = g_relation_new(2);
1295         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1296
1297         ok = imap_set_message_flags
1298                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
1299                 seq_list, IMAP_FLAG_DELETED, TRUE);
1300         if (ok != IMAP_SUCCESS) {
1301                 log_warning(_("can't set deleted flags\n"));
1302                 return ok;
1303         }
1304         ok = imap_cmd_expunge(session, NULL);
1305         if (ok != IMAP_SUCCESS) {
1306                 log_warning(_("can't expunge\n"));
1307                 return ok;
1308         }
1309         
1310         g_relation_destroy(uid_mapping);
1311         g_slist_free(seq_list);
1312
1313         g_free(destdir);
1314
1315         if (ok == IMAP_SUCCESS)
1316                 return 0;
1317         else
1318                 return -1;
1319 }
1320
1321 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
1322                     MsgInfoList *msglist, GRelation *relation)
1323 {
1324         MsgInfo *msginfo;
1325
1326         g_return_val_if_fail(folder != NULL, -1);
1327         g_return_val_if_fail(dest != NULL, -1);
1328         g_return_val_if_fail(msglist != NULL, -1);
1329
1330         msginfo = (MsgInfo *)msglist->data;
1331         g_return_val_if_fail(msginfo->folder != NULL, -1);
1332
1333         return imap_do_remove_msgs(folder, dest, msglist, relation);
1334 }
1335
1336 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1337 {
1338         GSList *list = folder_item_get_msg_list(item);
1339         gint res = imap_remove_msgs(folder, item, list, NULL);
1340         g_slist_free(list);
1341         return res;
1342 }
1343
1344 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
1345                                     MsgInfo *msginfo)
1346 {
1347         /* TODO: properly implement this method */
1348         return FALSE;
1349 }
1350
1351 static gint imap_close(Folder *folder, FolderItem *item)
1352 {
1353         gint ok;
1354         IMAPSession *session;
1355
1356         g_return_val_if_fail(folder != NULL, -1);
1357         g_return_val_if_fail(item != NULL, -1);
1358         g_return_val_if_fail(item->path != NULL, -1);
1359
1360         session = imap_session_get(folder);
1361         if (!session) return -1;
1362
1363         if (session->mbox) {
1364                 if (strcmp2(session->mbox, item->path) != 0) return -1;
1365
1366                 ok = imap_cmd_close(session);
1367                 if (ok != IMAP_SUCCESS)
1368                         log_warning(_("can't close folder\n"));
1369
1370                 g_free(session->mbox);
1371
1372                 session->mbox = NULL;
1373
1374                 return ok;
1375         }
1376
1377         return 0;
1378 }
1379
1380 static gint imap_scan_tree(Folder *folder)
1381 {
1382         FolderItem *item = NULL;
1383         IMAPSession *session;
1384         gchar *root_folder = NULL;
1385
1386         g_return_val_if_fail(folder != NULL, -1);
1387         g_return_val_if_fail(folder->account != NULL, -1);
1388
1389         session = imap_session_get(folder);
1390         if (!session) {
1391                 if (!folder->node) {
1392                         folder_tree_destroy(folder);
1393                         item = folder_item_new(folder, folder->name, NULL);
1394                         item->folder = folder;
1395                         folder->node = item->node = g_node_new(item);
1396                 }
1397                 return -1;
1398         }
1399
1400         if (folder->account->imap_dir && *folder->account->imap_dir) {
1401                 gchar *real_path;
1402                 GPtrArray *argbuf;
1403                 gint ok;
1404
1405                 Xstrdup_a(root_folder, folder->account->imap_dir, return -1);
1406                 extract_quote(root_folder, '"');
1407                 subst_char(root_folder,
1408                            imap_get_path_separator(IMAP_FOLDER(folder),
1409                                                    root_folder),
1410                            '/');
1411                 strtailchomp(root_folder, '/');
1412                 real_path = imap_get_real_path
1413                         (IMAP_FOLDER(folder), root_folder);
1414                 debug_print("IMAP root directory: %s\n", real_path);
1415
1416                 /* check if root directory exist */
1417                 argbuf = g_ptr_array_new();
1418                 ok = imap_cmd_list(session, NULL, real_path, argbuf);
1419                 if (ok != IMAP_SUCCESS ||
1420                     search_array_str(argbuf, "LIST ") == NULL) {
1421                         log_warning(_("root folder %s does not exist\n"), real_path);
1422                         g_ptr_array_free(argbuf, TRUE);
1423                         g_free(real_path);
1424
1425                         if (!folder->node) {
1426                                 item = folder_item_new(folder, folder->name, NULL);
1427                                 item->folder = folder;
1428                                 folder->node = item->node = g_node_new(item);
1429                         }
1430                         return -1;
1431                 }
1432                 g_ptr_array_free(argbuf, TRUE);
1433                 g_free(real_path);
1434         }
1435
1436         if (folder->node)
1437                 item = FOLDER_ITEM(folder->node->data);
1438         if (!item || ((item->path || root_folder) &&
1439                       strcmp2(item->path, root_folder) != 0)) {
1440                 folder_tree_destroy(folder);
1441                 item = folder_item_new(folder, folder->name, root_folder);
1442                 item->folder = folder;
1443                 folder->node = item->node = g_node_new(item);
1444         }
1445
1446         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data));
1447         imap_create_missing_folders(folder);
1448
1449         return 0;
1450 }
1451
1452 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
1453 {
1454         Folder *folder;
1455         IMAPFolder *imapfolder;
1456         FolderItem *new_item;
1457         GSList *item_list, *cur;
1458         GNode *node;
1459         gchar *real_path;
1460         gchar *wildcard_path;
1461         gchar separator;
1462         gchar wildcard[3];
1463
1464         g_return_val_if_fail(item != NULL, -1);
1465         g_return_val_if_fail(item->folder != NULL, -1);
1466         g_return_val_if_fail(item->no_sub == FALSE, -1);
1467
1468         folder = item->folder;
1469         imapfolder = IMAP_FOLDER(folder);
1470
1471         separator = imap_get_path_separator(imapfolder, item->path);
1472
1473         if (folder->ui_func)
1474                 folder->ui_func(folder, item, folder->ui_func_data);
1475
1476         if (item->path) {
1477                 wildcard[0] = separator;
1478                 wildcard[1] = '%';
1479                 wildcard[2] = '\0';
1480                 real_path = imap_get_real_path(imapfolder, item->path);
1481         } else {
1482                 wildcard[0] = '%';
1483                 wildcard[1] = '\0';
1484                 real_path = g_strdup("");
1485         }
1486
1487         Xstrcat_a(wildcard_path, real_path, wildcard,
1488                   {g_free(real_path); return IMAP_ERROR;});
1489         QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
1490
1491         imap_gen_send(session, "LIST \"\" %s",
1492                       wildcard_path);
1493
1494         strtailchomp(real_path, separator);
1495         item_list = imap_parse_list(imapfolder, session, real_path, NULL);
1496         g_free(real_path);
1497
1498         node = item->node->children;
1499         while (node != NULL) {
1500                 FolderItem *old_item = FOLDER_ITEM(node->data);
1501                 GNode *next = node->next;
1502
1503                 new_item = NULL;
1504                 for (cur = item_list; cur != NULL; cur = cur->next) {
1505                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
1506                         if (!strcmp2(old_item->path, cur_item->path)) {
1507                                 new_item = cur_item;
1508                                 break;
1509                         }
1510                 }
1511                 if (!new_item) {
1512                         debug_print("folder '%s' not found. removing...\n",
1513                                     old_item->path);
1514                         folder_item_remove(old_item);
1515                 } else {
1516                         old_item->no_sub = new_item->no_sub;
1517                         old_item->no_select = new_item->no_select;
1518                         if (old_item->no_sub == TRUE && node->children) {
1519                                 debug_print("folder '%s' doesn't have "
1520                                             "subfolders. removing...\n",
1521                                             old_item->path);
1522                                 folder_item_remove_children(old_item);
1523                         }
1524                 }
1525
1526                 node = next;
1527         }
1528
1529         for (cur = item_list; cur != NULL; cur = cur->next) {
1530                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
1531                 new_item = NULL;
1532                 for (node = item->node->children; node != NULL;
1533                      node = node->next) {
1534                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
1535                                      cur_item->path)) {
1536                                 new_item = FOLDER_ITEM(node->data);
1537                                 folder_item_destroy(cur_item);
1538                                 cur_item = NULL;
1539                                 break;
1540                         }
1541                 }
1542                 if (!new_item) {
1543                         new_item = cur_item;
1544                         debug_print("new folder '%s' found.\n", new_item->path);
1545                         folder_item_append(item, new_item);
1546                 }
1547
1548                 if (!strcmp(new_item->path, "INBOX")) {
1549                         new_item->stype = F_INBOX;
1550                         folder->inbox = new_item;
1551                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
1552                         gchar *base;
1553
1554                         base = g_path_get_basename(new_item->path);
1555
1556                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
1557                                 new_item->stype = F_OUTBOX;
1558                                 folder->outbox = new_item;
1559                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
1560                                 new_item->stype = F_DRAFT;
1561                                 folder->draft = new_item;
1562                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
1563                                 new_item->stype = F_QUEUE;
1564                                 folder->queue = new_item;
1565                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
1566                                 new_item->stype = F_TRASH;
1567                                 folder->trash = new_item;
1568                         }
1569                         g_free(base);
1570                 }
1571
1572                 if (new_item->no_sub == FALSE)
1573                         imap_scan_tree_recursive(session, new_item);
1574         }
1575
1576         g_slist_free(item_list);
1577
1578         return IMAP_SUCCESS;
1579 }
1580
1581 static GSList *imap_parse_list(IMAPFolder *folder, IMAPSession *session,
1582                                const gchar *real_path, gchar *separator)
1583 {
1584         gchar buf[IMAPBUFSIZE];
1585         gchar flags[256];
1586         gchar separator_str[16];
1587         gchar *p;
1588         gchar *base;
1589         gchar *loc_name, *loc_path;
1590         GSList *item_list = NULL;
1591         GString *str;
1592         FolderItem *new_item;
1593
1594         debug_print("getting list of %s ...\n",
1595                     *real_path ? real_path : "\"\"");
1596
1597         str = g_string_new(NULL);
1598
1599         for (;;) {
1600                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1601                         log_warning(_("error occurred while getting LIST.\n"));
1602                         break;
1603                 }
1604                 strretchomp(buf);
1605                 if (buf[0] != '*' || buf[1] != ' ') {
1606                         log_print("IMAP4< %s\n", buf);
1607                         if (sscanf(buf, "%*d %16s", buf) < 1 ||
1608                             strcmp(buf, "OK") != 0)
1609                                 log_warning(_("error occurred while getting LIST.\n"));
1610                                 
1611                         break;
1612                 }
1613                 debug_print("IMAP4< %s\n", buf);
1614
1615                 g_string_assign(str, buf);
1616                 p = str->str + 2;
1617                 if (strncmp(p, "LIST ", 5) != 0) continue;
1618                 p += 5;
1619
1620                 if (*p != '(') continue;
1621                 p++;
1622                 p = strchr_cpy(p, ')', flags, sizeof(flags));
1623                 if (!p) continue;
1624                 while (*p == ' ') p++;
1625
1626                 p = strchr_cpy(p, ' ', separator_str, sizeof(separator_str));
1627                 if (!p) continue;
1628                 extract_quote(separator_str, '"');
1629                 if (!strcmp(separator_str, "NIL"))
1630                         separator_str[0] = '\0';
1631                 if (separator)
1632                         *separator = separator_str[0];
1633
1634                 buf[0] = '\0';
1635                 while (*p == ' ') p++;
1636                 if (*p == '{' || *p == '"')
1637                         p = imap_parse_atom(SESSION(session)->sock, p,
1638                                             buf, sizeof(buf), str);
1639                 else
1640                         strncpy2(buf, p, sizeof(buf));
1641                 strtailchomp(buf, separator_str[0]);
1642                 if (buf[0] == '\0') continue;
1643                 if (!strcmp(buf, real_path)) continue;
1644
1645                 if (separator_str[0] != '\0')
1646                         subst_char(buf, separator_str[0], '/');
1647                 base = g_path_get_basename(buf);
1648                 if (base[0] == '.') continue;
1649
1650                 loc_name = imap_modified_utf7_to_utf8(base);
1651                 loc_path = imap_modified_utf7_to_utf8(buf);
1652                 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
1653                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1654                         new_item->no_sub = TRUE;
1655                 if (strcmp(buf, "INBOX") != 0 &&
1656                     strcasestr(flags, "\\Noselect") != NULL)
1657                         new_item->no_select = TRUE;
1658
1659                 item_list = g_slist_append(item_list, new_item);
1660
1661                 debug_print("folder '%s' found.\n", loc_path);
1662                 g_free(base);
1663                 g_free(loc_path);
1664                 g_free(loc_name);
1665         }
1666
1667         g_string_free(str, TRUE);
1668
1669         return item_list;
1670 }
1671
1672 static gint imap_create_tree(Folder *folder)
1673 {
1674         g_return_val_if_fail(folder != NULL, -1);
1675         g_return_val_if_fail(folder->node != NULL, -1);
1676         g_return_val_if_fail(folder->node->data != NULL, -1);
1677         g_return_val_if_fail(folder->account != NULL, -1);
1678
1679         imap_scan_tree(folder);
1680         imap_create_missing_folders(folder);
1681
1682         return 0;
1683 }
1684
1685 static void imap_create_missing_folders(Folder *folder)
1686 {
1687         g_return_if_fail(folder != NULL);
1688
1689         if (!folder->inbox)
1690                 folder->inbox = imap_create_special_folder
1691                         (folder, F_INBOX, "INBOX");
1692 #if 0
1693         if (!folder->outbox)
1694                 folder->outbox = imap_create_special_folder
1695                         (folder, F_OUTBOX, "Sent");
1696         if (!folder->draft)
1697                 folder->draft = imap_create_special_folder
1698                         (folder, F_DRAFT, "Drafts");
1699         if (!folder->queue)
1700                 folder->queue = imap_create_special_folder
1701                         (folder, F_QUEUE, "Queue");
1702 #endif
1703         if (!folder->trash)
1704                 folder->trash = imap_create_special_folder
1705                         (folder, F_TRASH, "Trash");
1706 }
1707
1708 static FolderItem *imap_create_special_folder(Folder *folder,
1709                                               SpecialFolderItemType stype,
1710                                               const gchar *name)
1711 {
1712         FolderItem *item;
1713         FolderItem *new_item;
1714
1715         g_return_val_if_fail(folder != NULL, NULL);
1716         g_return_val_if_fail(folder->node != NULL, NULL);
1717         g_return_val_if_fail(folder->node->data != NULL, NULL);
1718         g_return_val_if_fail(folder->account != NULL, NULL);
1719         g_return_val_if_fail(name != NULL, NULL);
1720
1721         item = FOLDER_ITEM(folder->node->data);
1722         new_item = imap_create_folder(folder, item, name);
1723
1724         if (!new_item) {
1725                 g_warning("Can't create '%s'\n", name);
1726                 if (!folder->inbox) return NULL;
1727
1728                 new_item = imap_create_folder(folder, folder->inbox, name);
1729                 if (!new_item)
1730                         g_warning("Can't create '%s' under INBOX\n", name);
1731                 else
1732                         new_item->stype = stype;
1733         } else
1734                 new_item->stype = stype;
1735
1736         return new_item;
1737 }
1738
1739 static gchar *imap_folder_get_path(Folder *folder)
1740 {
1741         gchar *folder_path;
1742
1743         g_return_val_if_fail(folder != NULL, NULL);
1744         g_return_val_if_fail(folder->account != NULL, NULL);
1745
1746         folder_path = g_strconcat(get_imap_cache_dir(),
1747                                   G_DIR_SEPARATOR_S,
1748                                   folder->account->recv_server,
1749                                   G_DIR_SEPARATOR_S,
1750                                   folder->account->userid,
1751                                   NULL);
1752
1753         return folder_path;
1754 }
1755
1756 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
1757 {
1758         gchar *folder_path, *path;
1759
1760         g_return_val_if_fail(folder != NULL, NULL);
1761         g_return_val_if_fail(item != NULL, NULL);
1762         folder_path = imap_folder_get_path(folder);
1763
1764         g_return_val_if_fail(folder_path != NULL, NULL);
1765         if (folder_path[0] == G_DIR_SEPARATOR) {
1766                 if (item->path)
1767                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
1768                                            item->path, NULL);
1769                 else
1770                         path = g_strdup(folder_path);
1771         } else {
1772                 if (item->path)
1773                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1774                                            folder_path, G_DIR_SEPARATOR_S,
1775                                            item->path, NULL);
1776                 else
1777                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1778                                            folder_path, NULL);
1779         }
1780         g_free(folder_path);
1781
1782         return path;
1783 }
1784
1785 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1786                                const gchar *name)
1787 {
1788         gchar *dirpath, *imap_path;
1789         IMAPSession *session;
1790         FolderItem *new_item;
1791         gchar separator;
1792         gchar *new_name;
1793         const gchar *p;
1794         gint ok;
1795
1796         g_return_val_if_fail(folder != NULL, NULL);
1797         g_return_val_if_fail(folder->account != NULL, NULL);
1798         g_return_val_if_fail(parent != NULL, NULL);
1799         g_return_val_if_fail(name != NULL, NULL);
1800
1801         session = imap_session_get(folder);
1802         if (!session) return NULL;
1803
1804         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0)
1805                 dirpath = g_strdup(name);
1806         else if (parent->path)
1807                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1808         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1809                 dirpath = g_strdup(name);
1810         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1811                 gchar *imap_dir;
1812
1813                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1814                 strtailchomp(imap_dir, '/');
1815                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1816         } else
1817                 dirpath = g_strdup(name);
1818
1819         /* keep trailing directory separator to create a folder that contains
1820            sub folder */
1821         imap_path = imap_utf8_to_modified_utf7(dirpath);
1822         strtailchomp(dirpath, '/');
1823         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1824         strtailchomp(new_name, '/');
1825         separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
1826         imap_path_separator_subst(imap_path, separator);
1827         subst_char(new_name, '/', separator);
1828
1829         if (strcmp(name, "INBOX") != 0) {
1830                 GPtrArray *argbuf;
1831                 gint i;
1832                 gboolean exist = FALSE;
1833
1834                 argbuf = g_ptr_array_new();
1835                 ok = imap_cmd_list(session, NULL, imap_path,
1836                                    argbuf);
1837                 if (ok != IMAP_SUCCESS) {
1838                         log_warning(_("can't create mailbox: LIST failed\n"));
1839                         g_free(imap_path);
1840                         g_free(dirpath);
1841                         ptr_array_free_strings(argbuf);
1842                         g_ptr_array_free(argbuf, TRUE);
1843                         return NULL;
1844                 }
1845
1846                 for (i = 0; i < argbuf->len; i++) {
1847                         gchar *str;
1848                         str = g_ptr_array_index(argbuf, i);
1849                         if (!strncmp(str, "LIST ", 5)) {
1850                                 exist = TRUE;
1851                                 break;
1852                         }
1853                 }
1854                 ptr_array_free_strings(argbuf);
1855                 g_ptr_array_free(argbuf, TRUE);
1856
1857                 if (!exist) {
1858                         ok = imap_cmd_create(session, imap_path);
1859                         if (ok != IMAP_SUCCESS) {
1860                                 log_warning(_("can't create mailbox\n"));
1861                                 g_free(imap_path);
1862                                 g_free(dirpath);
1863                                 return NULL;
1864                         }
1865                 }
1866         }
1867
1868         new_item = folder_item_new(folder, new_name, dirpath);
1869         folder_item_append(parent, new_item);
1870         g_free(imap_path);
1871         g_free(dirpath);
1872
1873         dirpath = folder_item_get_path(new_item);
1874         if (!is_dir_exist(dirpath))
1875                 make_dir_hier(dirpath);
1876         g_free(dirpath);
1877
1878         return new_item;
1879 }
1880
1881 static gint imap_rename_folder(Folder *folder, FolderItem *item,
1882                                const gchar *name)
1883 {
1884         gchar *dirpath;
1885         gchar *newpath;
1886         gchar *real_oldpath;
1887         gchar *real_newpath;
1888         gchar *paths[2];
1889         gchar *old_cache_dir;
1890         gchar *new_cache_dir;
1891         IMAPSession *session;
1892         gchar separator;
1893         gint ok;
1894         gint exists, recent, unseen;
1895         guint32 uid_validity;
1896
1897         g_return_val_if_fail(folder != NULL, -1);
1898         g_return_val_if_fail(item != NULL, -1);
1899         g_return_val_if_fail(item->path != NULL, -1);
1900         g_return_val_if_fail(name != NULL, -1);
1901
1902         if (strchr(name, imap_get_path_separator(IMAP_FOLDER(folder), item->path)) != NULL) {
1903                 g_warning(_("New folder name must not contain the namespace "
1904                             "path separator"));
1905                 return -1;
1906         }
1907
1908         session = imap_session_get(folder);
1909         if (!session) return -1;
1910
1911         real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1912
1913         g_free(session->mbox);
1914         session->mbox = NULL;
1915         ok = imap_cmd_examine(session, "INBOX",
1916                               &exists, &recent, &unseen, &uid_validity, FALSE);
1917         if (ok != IMAP_SUCCESS) {
1918                 g_free(real_oldpath);
1919                 return -1;
1920         }
1921
1922         separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
1923         if (strchr(item->path, G_DIR_SEPARATOR)) {
1924                 dirpath = g_path_get_dirname(item->path);
1925                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
1926                 g_free(dirpath);
1927         } else
1928                 newpath = g_strdup(name);
1929
1930         real_newpath = imap_utf8_to_modified_utf7(newpath);
1931         imap_path_separator_subst(real_newpath, separator);
1932
1933         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
1934         if (ok != IMAP_SUCCESS) {
1935                 log_warning(_("can't rename mailbox: %s to %s\n"),
1936                             real_oldpath, real_newpath);
1937                 g_free(real_oldpath);
1938                 g_free(newpath);
1939                 g_free(real_newpath);
1940                 return -1;
1941         }
1942
1943         g_free(item->name);
1944         item->name = g_strdup(name);
1945
1946         old_cache_dir = folder_item_get_path(item);
1947
1948         paths[0] = g_strdup(item->path);
1949         paths[1] = newpath;
1950         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1951                         imap_rename_folder_func, paths);
1952
1953         if (is_dir_exist(old_cache_dir)) {
1954                 new_cache_dir = folder_item_get_path(item);
1955                 if (rename(old_cache_dir, new_cache_dir) < 0) {
1956                         FILE_OP_ERROR(old_cache_dir, "rename");
1957                 }
1958                 g_free(new_cache_dir);
1959         }
1960
1961         g_free(old_cache_dir);
1962         g_free(paths[0]);
1963         g_free(newpath);
1964         g_free(real_oldpath);
1965         g_free(real_newpath);
1966
1967         return 0;
1968 }
1969
1970 static gint imap_remove_folder(Folder *folder, FolderItem *item)
1971 {
1972         gint ok;
1973         IMAPSession *session;
1974         gchar *path;
1975         gchar *cache_dir;
1976         gint exists, recent, unseen;
1977         guint32 uid_validity;
1978
1979         g_return_val_if_fail(folder != NULL, -1);
1980         g_return_val_if_fail(item != NULL, -1);
1981         g_return_val_if_fail(item->path != NULL, -1);
1982
1983         session = imap_session_get(folder);
1984         if (!session) return -1;
1985
1986         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1987
1988         ok = imap_cmd_examine(session, "INBOX",
1989                               &exists, &recent, &unseen, &uid_validity, FALSE);
1990         if (ok != IMAP_SUCCESS) {
1991                 g_free(path);
1992                 return -1;
1993         }
1994
1995         ok = imap_cmd_delete(session, path);
1996         if (ok != IMAP_SUCCESS) {
1997                 log_warning(_("can't delete mailbox\n"));
1998                 g_free(path);
1999                 return -1;
2000         }
2001
2002         g_free(path);
2003         cache_dir = folder_item_get_path(item);
2004         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2005                 g_warning("can't remove directory '%s'\n", cache_dir);
2006         g_free(cache_dir);
2007         folder_item_remove(item);
2008
2009         return 0;
2010 }
2011
2012 typedef struct _uncached_data {
2013         IMAPSession *session;
2014         FolderItem *item;
2015         MsgNumberList *numlist;
2016         guint cur;
2017         guint total;
2018         gboolean done;
2019 } uncached_data;
2020
2021 static void *imap_get_uncached_messages_thread(void *data)
2022 {
2023         uncached_data *stuff = (uncached_data *)data;
2024         IMAPSession *session = stuff->session;
2025         FolderItem *item = stuff->item;
2026         MsgNumberList *numlist = stuff->numlist;
2027
2028         gchar *tmp;
2029         GSList *newlist = NULL;
2030         GSList *llast = NULL;
2031         GString *str = NULL;
2032         MsgInfo *msginfo;
2033         GSList *seq_list, *cur;
2034         IMAPSet imapset;
2035         
2036         stuff->total = g_slist_length(numlist);
2037         stuff->cur = 0;
2038
2039         if (session == NULL || item == NULL || item->folder == NULL
2040             || FOLDER_CLASS(item->folder) != &imap_class) {
2041                 stuff->done = TRUE;
2042                 return NULL;
2043         }
2044
2045         seq_list = imap_get_seq_set_from_numlist(numlist);
2046         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2047                 imapset = cur->data;
2048
2049                 if (imap_cmd_envelope(session, imapset)
2050                     != IMAP_SUCCESS) {
2051                         log_warning(_("can't get envelope\n"));
2052                         continue;
2053                 }
2054
2055                 str = g_string_new(NULL);
2056
2057                 for (;;) {
2058                         if ((tmp =sock_getline(SESSION(session)->sock)) == NULL) {
2059                                 log_warning(_("error occurred while getting envelope.\n"));
2060                                 g_string_free(str, TRUE);
2061                                 str = NULL;
2062                                 break;
2063                         }
2064                         strretchomp(tmp);
2065                         if (tmp[0] != '*' || tmp[1] != ' ') {
2066                                 log_print("IMAP4< %s\n", tmp);
2067                                 g_free(tmp);
2068                                 break;
2069                         }
2070                         if (strstr(tmp, "FETCH") == NULL) {
2071                                 log_print("IMAP4< %s\n", tmp);
2072                                 g_free(tmp);
2073                                 continue;
2074                         }
2075                         log_print("IMAP4< %s\n", tmp);
2076                         g_string_assign(str, tmp);
2077                         g_free(tmp);
2078                         
2079                         stuff->cur++;
2080
2081                         msginfo = imap_parse_envelope
2082                                 (SESSION(session)->sock, item, str);
2083                         if (!msginfo) {
2084                                 log_warning(_("can't parse envelope: %s\n"), str->str);
2085                                 continue;
2086                         }
2087                         if (item->stype == F_QUEUE) {
2088                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
2089                         } else if (item->stype == F_DRAFT) {
2090                                 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
2091                         }
2092
2093                         msginfo->folder = item;
2094
2095                         if (!newlist)
2096                                 llast = newlist = g_slist_append(newlist, msginfo);
2097                         else {
2098                                 llast = g_slist_append(llast, msginfo);
2099                                 llast = llast->next;
2100                         }
2101                 }
2102                 if (str)
2103                         g_string_free(str, TRUE);
2104         }
2105         imap_seq_set_free(seq_list);
2106         
2107         session_set_access_time(SESSION(session));
2108         stuff->done = TRUE;
2109
2110         return newlist;
2111 }
2112
2113 static GSList *imap_get_uncached_messages(IMAPSession *session,
2114                                         FolderItem *item,
2115                                         MsgNumberList *numlist)
2116 {
2117         uncached_data *data = g_new0(uncached_data, 1);
2118         GSList *result = NULL;
2119         gint last_cur = 0;
2120 #ifdef USE_PTHREAD
2121         pthread_t pt;
2122 #endif
2123         data->done = FALSE;
2124         data->session = session;
2125         data->item = item;
2126         data->numlist = numlist;
2127         data->cur = 0;
2128         data->total = 0;
2129         
2130         if (prefs_common.work_offline && !imap_gtk_should_override()) {
2131                 g_free(data);
2132                 return NULL;
2133         }
2134
2135 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
2136         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
2137                         imap_get_uncached_messages_thread, data) != 0) {
2138                 result = (GSList *)imap_get_uncached_messages_thread(data);
2139                 g_free(data);
2140                 return result;
2141         }
2142         debug_print("+++waiting for imap_get_uncached_messages_thread...\n");
2143         statusbar_print_all(_("IMAP4 Fetching uncached short headers..."));
2144         while(!data->done) {
2145                 /* don't let the interface freeze while waiting */
2146                 sylpheed_do_idle();
2147                 if (data->total != 0 && last_cur != data->cur && data->cur % 10 == 0) {
2148                         gchar buf[32];
2149                         g_snprintf(buf, sizeof(buf), "%d / %d",
2150                                    data->cur, data->total);
2151                         gtk_progress_bar_set_text
2152                                 (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), buf);
2153                         gtk_progress_bar_set_fraction
2154                         (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar),
2155                          (gfloat)data->cur / (gfloat)data->total);
2156                         last_cur = data->cur;
2157                 }
2158         }
2159         gtk_progress_bar_set_fraction
2160                 (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), 0);
2161         gtk_progress_bar_set_text
2162                 (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), "");
2163         statusbar_pop_all();
2164
2165         debug_print("---imap_get_uncached_messages_thread done\n");
2166
2167         /* get the thread's return value and clean its resources */
2168         pthread_join(pt, (void *)&result);
2169 #else
2170         result = (GSList *)imap_get_uncached_messages_thread(data);
2171 #endif
2172         g_free(data);
2173         return result;
2174 }
2175
2176 static void imap_delete_all_cached_messages(FolderItem *item)
2177 {
2178         gchar *dir;
2179
2180         g_return_if_fail(item != NULL);
2181         g_return_if_fail(item->folder != NULL);
2182         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
2183
2184         debug_print("Deleting all cached messages...\n");
2185
2186         dir = folder_item_get_path(item);
2187         if (is_dir_exist(dir))
2188                 remove_all_numbered_files(dir);
2189         g_free(dir);
2190
2191         debug_print("done.\n");
2192 }
2193
2194 #if USE_OPENSSL
2195 static SockInfo *imap_open_tunnel(const gchar *server,
2196                            const gchar *tunnelcmd,
2197                            SSLType ssl_type)
2198 #else
2199 static SockInfo *imap_open_tunnel(const gchar *server,
2200                            const gchar *tunnelcmd)
2201 #endif
2202 {
2203         SockInfo *sock;
2204
2205         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL) {
2206                 log_warning(_("Can't establish IMAP4 session with: %s\n"),
2207                             server);
2208                 return NULL;
2209         }
2210 #if USE_OPENSSL
2211         return imap_init_sock(sock, ssl_type);
2212 #else
2213         return imap_init_sock(sock);
2214 #endif
2215 }
2216
2217 void *imap_open_thread(void *data)
2218 {
2219         SockInfo *sock = NULL;
2220         thread_data *td = (thread_data *)data;
2221         if ((sock = sock_connect(td->server, td->port)) == NULL) {
2222                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
2223                             td->server, td->port);
2224                 td->done = TRUE;
2225                 return NULL;
2226         }
2227
2228         td->done = TRUE;
2229         return sock;
2230 }
2231
2232 #if USE_OPENSSL
2233 static SockInfo *imap_open(const gchar *server, gushort port,
2234                            SSLType ssl_type)
2235 #else
2236 static SockInfo *imap_open(const gchar *server, gushort port)
2237 #endif
2238 {
2239         thread_data *td = g_new0(thread_data, 1);
2240 #if USE_PTHREAD
2241         pthread_t pt;
2242 #endif
2243         SockInfo *sock = NULL;
2244
2245 #if USE_OPENSSL
2246         td->ssl_type = ssl_type;
2247 #endif
2248         td->server = g_strdup(server);
2249         td->port = port;
2250         td->done = FALSE;
2251
2252         statusbar_print_all(_("Connecting to IMAP4 server: %s..."), server);
2253
2254 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
2255         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
2256                         imap_open_thread, td) != 0) {
2257                 statusbar_pop_all();
2258                 sock = imap_open_thread(td);
2259         } else {        
2260                 debug_print("+++waiting for imap_open_thread...\n");
2261                 while(!td->done) {
2262                         /* don't let the interface freeze while waiting */
2263                         sylpheed_do_idle();
2264                 }
2265
2266                 /* get the thread's return value and clean its resources */
2267                 pthread_join(pt, (void *)&sock);
2268         }
2269 #else
2270         sock = imap_open_thread(td);
2271 #endif
2272 #if USE_OPENSSL
2273         if (sock && td->ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
2274                 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
2275                             td->server, td->port);
2276                 sock_close(sock);
2277                 sock = NULL;
2278                 td->done = TRUE;
2279         }
2280 #endif
2281         g_free(td->server);
2282         g_free(td);
2283
2284         debug_print("---imap_open_thread returned %p\n", sock);
2285         statusbar_pop_all();
2286
2287         if(!sock && !prefs_common.no_recv_err_panel) {
2288                 alertpanel_error(_("Can't connect to IMAP4 server: %s:%d"),
2289                                  server, port);
2290         }
2291
2292         return sock;
2293 }
2294
2295 #if USE_OPENSSL
2296 static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type)
2297 #else
2298 static SockInfo *imap_init_sock(SockInfo *sock)
2299 #endif
2300 {
2301
2302         return sock;
2303 }
2304
2305 static GList *imap_parse_namespace_str(gchar *str)
2306 {
2307         guchar *p = str;
2308         gchar *name;
2309         gchar *separator;
2310         IMAPNameSpace *namespace;
2311         GList *ns_list = NULL;
2312
2313         while (*p != '\0') {
2314                 /* parse ("#foo" "/") */
2315
2316                 while (*p && *p != '(') p++;
2317                 if (*p == '\0') break;
2318                 p++;
2319
2320                 while (*p && *p != '"') p++;
2321                 if (*p == '\0') break;
2322                 p++;
2323                 name = p;
2324
2325                 while (*p && *p != '"') p++;
2326                 if (*p == '\0') break;
2327                 *p = '\0';
2328                 p++;
2329
2330                 while (*p && isspace(*p)) p++;
2331                 if (*p == '\0') break;
2332                 if (strncmp(p, "NIL", 3) == 0)
2333                         separator = NULL;
2334                 else if (*p == '"') {
2335                         p++;
2336                         separator = p;
2337                         while (*p && *p != '"') p++;
2338                         if (*p == '\0') break;
2339                         *p = '\0';
2340                         p++;
2341                 } else break;
2342
2343                 while (*p && *p != ')') p++;
2344                 if (*p == '\0') break;
2345                 p++;
2346
2347                 namespace = g_new(IMAPNameSpace, 1);
2348                 namespace->name = g_strdup(name);
2349                 namespace->separator = separator ? separator[0] : '\0';
2350                 ns_list = g_list_append(ns_list, namespace);
2351         }
2352
2353         return ns_list;
2354 }
2355
2356 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
2357 {
2358         gchar *ns_str;
2359         gchar **str_array;
2360
2361         g_return_if_fail(session != NULL);
2362         g_return_if_fail(folder != NULL);
2363
2364         if (folder->ns_personal != NULL ||
2365             folder->ns_others   != NULL ||
2366             folder->ns_shared   != NULL)
2367                 return;
2368
2369         if (!imap_has_capability(session, "NAMESPACE")) {
2370                 imap_get_namespace_by_list(session, folder);
2371                 return;
2372         }
2373         
2374         if (imap_cmd_namespace(session, &ns_str)
2375             != IMAP_SUCCESS) {
2376                 log_warning(_("can't get namespace\n"));
2377                 return;
2378         }
2379
2380         str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
2381         if (str_array == NULL) {
2382                 g_free(ns_str);
2383                 imap_get_namespace_by_list(session, folder);
2384                 return;
2385         }
2386         if (str_array[0])
2387                 folder->ns_personal = imap_parse_namespace_str(str_array[0]);
2388         if (str_array[0] && str_array[1])
2389                 folder->ns_others = imap_parse_namespace_str(str_array[1]);
2390         if (str_array[0] && str_array[1] && str_array[2])
2391                 folder->ns_shared = imap_parse_namespace_str(str_array[2]);
2392         g_strfreev(str_array);
2393         g_free(ns_str);
2394 }
2395
2396 static void imap_get_namespace_by_list(IMAPSession *session, IMAPFolder *folder)
2397 {
2398         GSList *item_list, *cur;
2399         gchar separator = '\0';
2400         IMAPNameSpace *namespace;
2401
2402         g_return_if_fail(session != NULL);
2403         g_return_if_fail(folder != NULL);
2404
2405         if (folder->ns_personal != NULL ||
2406             folder->ns_others   != NULL ||
2407             folder->ns_shared   != NULL)
2408                 return;
2409
2410         imap_gen_send(session, "LIST \"\" \"\"");
2411         item_list = imap_parse_list(folder, session, "", &separator);
2412         for (cur = item_list; cur != NULL; cur = cur->next)
2413                 folder_item_destroy(FOLDER_ITEM(cur->data));
2414         g_slist_free(item_list);
2415
2416         namespace = g_new(IMAPNameSpace, 1);
2417         namespace->name = g_strdup("");
2418         namespace->separator = separator;
2419         folder->ns_personal = g_list_append(NULL, namespace);
2420 }
2421
2422 static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
2423                                                     const gchar *path)
2424 {
2425         IMAPNameSpace *namespace = NULL;
2426         gchar *tmp_path, *name;
2427
2428         if (!path) path = "";
2429
2430         for (; ns_list != NULL; ns_list = ns_list->next) {
2431                 IMAPNameSpace *tmp_ns = ns_list->data;
2432
2433                 Xstrcat_a(tmp_path, path, "/", return namespace);
2434                 Xstrdup_a(name, tmp_ns->name, return namespace);
2435                 if (tmp_ns->separator && tmp_ns->separator != '/') {
2436                         subst_char(tmp_path, tmp_ns->separator, '/');
2437                         subst_char(name, tmp_ns->separator, '/');
2438                 }
2439                 if (strncmp(tmp_path, name, strlen(name)) == 0)
2440                         namespace = tmp_ns;
2441         }
2442
2443         return namespace;
2444 }
2445
2446 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
2447                                           const gchar *path)
2448 {
2449         IMAPNameSpace *namespace;
2450
2451         g_return_val_if_fail(folder != NULL, NULL);
2452
2453         namespace = imap_find_namespace_from_list(folder->ns_personal, path);
2454         if (namespace) return namespace;
2455         namespace = imap_find_namespace_from_list(folder->ns_others, path);
2456         if (namespace) return namespace;
2457         namespace = imap_find_namespace_from_list(folder->ns_shared, path);
2458         if (namespace) return namespace;
2459
2460         return NULL;
2461 }
2462
2463 static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
2464 {
2465         IMAPNameSpace *namespace;
2466         gchar separator = '/';
2467
2468         namespace = imap_find_namespace(folder, path);
2469         if (namespace && namespace->separator)
2470                 separator = namespace->separator;
2471
2472         return separator;
2473 }
2474
2475 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
2476 {
2477         gchar *real_path;
2478         gchar separator;
2479
2480         g_return_val_if_fail(folder != NULL, NULL);
2481         g_return_val_if_fail(path != NULL, NULL);
2482
2483         real_path = imap_utf8_to_modified_utf7(path);
2484         separator = imap_get_path_separator(folder, path);
2485         imap_path_separator_subst(real_path, separator);
2486
2487         return real_path;
2488 }
2489
2490 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
2491                               gchar *dest, gint dest_len, GString *str)
2492 {
2493         gchar *cur_pos = src;
2494         gchar *nextline;
2495
2496         g_return_val_if_fail(str != NULL, cur_pos);
2497
2498         /* read the next line if the current response buffer is empty */
2499         while (isspace(*(guchar *)cur_pos)) cur_pos++;
2500         while (*cur_pos == '\0') {
2501                 if ((nextline = imap_getline(sock)) == NULL)
2502                         return cur_pos;
2503                 g_string_assign(str, nextline);
2504                 cur_pos = str->str;
2505                 strretchomp(nextline);
2506                 /* log_print("IMAP4< %s\n", nextline); */
2507                 debug_print("IMAP4< %s\n", nextline);
2508                 g_free(nextline);
2509
2510                 while (isspace(*(guchar *)cur_pos)) cur_pos++;
2511         }
2512
2513         if (!strncmp(cur_pos, "NIL", 3)) {
2514                 *dest = '\0';
2515                 cur_pos += 3;
2516         } else if (*cur_pos == '\"') {
2517                 gchar *p;
2518
2519                 p = get_quoted(cur_pos, '\"', dest, dest_len);
2520                 cur_pos = p ? p : cur_pos + 2;
2521         } else if (*cur_pos == '{') {
2522                 gchar buf[32];
2523                 gint len;
2524                 gint line_len = 0;
2525
2526                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
2527                 len = atoi(buf);
2528                 g_return_val_if_fail(len >= 0, cur_pos);
2529
2530                 g_string_truncate(str, 0);
2531                 cur_pos = str->str;
2532
2533                 do {
2534                         if ((nextline = imap_getline(sock)) == NULL)
2535                                 return cur_pos;
2536                         line_len += strlen(nextline);
2537                         g_string_append(str, nextline);
2538                         cur_pos = str->str;
2539                         strretchomp(nextline);
2540                         /* log_print("IMAP4< %s\n", nextline); */
2541                         debug_print("IMAP4< %s\n", nextline);
2542                         g_free(nextline);
2543                 } while (line_len < len);
2544
2545                 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
2546                 dest[MIN(len, dest_len - 1)] = '\0';
2547                 cur_pos += len;
2548         }
2549
2550         return cur_pos;
2551 }
2552
2553 static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
2554                               GString *str)
2555 {
2556         gchar *nextline;
2557         gchar buf[32];
2558         gint len;
2559         gint block_len = 0;
2560
2561         *headers = NULL;
2562
2563         g_return_val_if_fail(str != NULL, cur_pos);
2564
2565         while (isspace(*(guchar *)cur_pos)) cur_pos++;
2566
2567         g_return_val_if_fail(*cur_pos == '{', cur_pos);
2568
2569         cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
2570         len = atoi(buf);
2571         g_return_val_if_fail(len >= 0, cur_pos);
2572
2573         g_string_truncate(str, 0);
2574         cur_pos = str->str;
2575
2576         do {
2577                 if ((nextline = sock_getline(sock)) == NULL) {
2578                         *headers = NULL;
2579                         return cur_pos;
2580                 }
2581                 block_len += strlen(nextline);
2582                 g_string_append(str, nextline);
2583                 cur_pos = str->str;
2584                 strretchomp(nextline);
2585                 /* debug_print("IMAP4< %s\n", nextline); */
2586                 g_free(nextline);
2587         } while (block_len < len);
2588
2589         debug_print("IMAP4< [contents of BODY.PEEK[HEADER_FIELDS (...)]\n");
2590
2591         *headers = g_strndup(cur_pos, len);
2592         cur_pos += len;
2593
2594         while (isspace(*(guchar *)cur_pos)) cur_pos++;
2595         while (*cur_pos == '\0') {
2596                 if ((nextline = sock_getline(sock)) == NULL)
2597                         return cur_pos;
2598                 g_string_assign(str, nextline);
2599                 cur_pos = str->str;
2600                 strretchomp(nextline);
2601                 debug_print("IMAP4< %s\n", nextline);
2602                 g_free(nextline);
2603
2604                 while (isspace(*(guchar *)cur_pos)) cur_pos++;
2605         }
2606
2607         return cur_pos;
2608 }
2609
2610 static MsgFlags imap_parse_flags(const gchar *flag_str)  
2611 {
2612         const gchar *p = flag_str;
2613         MsgFlags flags = {0, 0};
2614
2615         flags.perm_flags = MSG_UNREAD;
2616
2617         while ((p = strchr(p, '\\')) != NULL) {
2618                 p++;
2619
2620                 if (g_ascii_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
2621                         MSG_SET_PERM_FLAGS(flags, MSG_NEW);
2622                 } else if (g_ascii_strncasecmp(p, "Seen", 4) == 0) {
2623                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
2624                 } else if (g_ascii_strncasecmp(p, "Deleted", 7) == 0) {
2625                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
2626                 } else if (g_ascii_strncasecmp(p, "Flagged", 7) == 0) {
2627                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
2628                 } else if (g_ascii_strncasecmp(p, "Answered", 8) == 0) {
2629                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
2630                 }
2631         }
2632
2633         return flags;
2634 }
2635
2636 static MsgInfo *imap_parse_envelope(SockInfo *sock, FolderItem *item,
2637                                     GString *line_str)
2638 {
2639         gchar buf[IMAPBUFSIZE];
2640         MsgInfo *msginfo = NULL;
2641         gchar *cur_pos;
2642         gint msgnum;
2643         guint32 uid = 0;
2644         size_t size = 0;
2645         MsgFlags flags = {0, 0}, imap_flags = {0, 0};
2646
2647         g_return_val_if_fail(line_str != NULL, NULL);
2648         g_return_val_if_fail(line_str->str[0] == '*' &&
2649                              line_str->str[1] == ' ', NULL);
2650
2651         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
2652         if (item->stype == F_QUEUE) {
2653                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
2654         } else if (item->stype == F_DRAFT) {
2655                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
2656         }
2657
2658         cur_pos = line_str->str + 2;
2659
2660 #define PARSE_ONE_ELEMENT(ch)                                   \
2661 {                                                               \
2662         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));    \
2663         if (cur_pos == NULL) {                                  \
2664                 g_warning("cur_pos == NULL\n");                 \
2665                 procmsg_msginfo_free(msginfo);                  \
2666                 return NULL;                                    \
2667         }                                                       \
2668 }
2669
2670         PARSE_ONE_ELEMENT(' ');
2671         msgnum = atoi(buf);
2672
2673         PARSE_ONE_ELEMENT(' ');
2674         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
2675
2676         g_return_val_if_fail(*cur_pos == '(', NULL);
2677         cur_pos++;
2678
2679         while (*cur_pos != '\0' && *cur_pos != ')') {
2680                 while (*cur_pos == ' ') cur_pos++;
2681
2682                 if (!strncmp(cur_pos, "UID ", 4)) {
2683                         cur_pos += 4;
2684                         uid = strtoul(cur_pos, &cur_pos, 10);
2685                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
2686                         cur_pos += 6;
2687                         if (*cur_pos != '(') {
2688                                 g_warning("*cur_pos != '('\n");
2689                                 procmsg_msginfo_free(msginfo);
2690                                 return NULL;
2691                         }
2692                         cur_pos++;
2693                         PARSE_ONE_ELEMENT(')');
2694                         imap_flags = imap_parse_flags(buf);
2695                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
2696                         cur_pos += 12;
2697                         size = strtol(cur_pos, &cur_pos, 10);
2698                 } else if (!strncmp(cur_pos, "BODY[HEADER.FIELDS ", 19)) {
2699                         gchar *headers;
2700
2701                         cur_pos += 19;
2702                         if (*cur_pos != '(') {
2703                                 g_warning("*cur_pos != '('\n");
2704                                 procmsg_msginfo_free(msginfo);
2705                                 return NULL;
2706                         }
2707                         cur_pos++;
2708                         PARSE_ONE_ELEMENT(')');
2709                         if (*cur_pos != ']') {
2710                                 g_warning("*cur_pos != ']'\n");
2711                                 procmsg_msginfo_free(msginfo);
2712                                 return NULL;
2713                         }
2714                         cur_pos++;
2715                         cur_pos = imap_get_header(sock, cur_pos, &headers,
2716                                                   line_str);
2717                         msginfo = procheader_parse_str(headers, flags, FALSE, FALSE);
2718                         g_free(headers);
2719                 } else {
2720                         g_warning("invalid FETCH response: %s\n", cur_pos);
2721                         break;
2722                 }
2723         }
2724
2725         if (msginfo) {
2726                 msginfo->msgnum = uid;
2727                 msginfo->size = size;
2728                 msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
2729                 msginfo->flags.perm_flags = imap_flags.perm_flags;
2730         }
2731
2732         return msginfo;
2733 }
2734
2735 static gchar *imap_get_flag_str(IMAPFlags flags)
2736 {
2737         GString *str;
2738         gchar *ret;
2739
2740         str = g_string_new(NULL);
2741
2742         if (IMAP_IS_SEEN(flags))        g_string_append(str, "\\Seen ");
2743         if (IMAP_IS_ANSWERED(flags))    g_string_append(str, "\\Answered ");
2744         if (IMAP_IS_FLAGGED(flags))     g_string_append(str, "\\Flagged ");
2745         if (IMAP_IS_DELETED(flags))     g_string_append(str, "\\Deleted ");
2746         if (IMAP_IS_DRAFT(flags))       g_string_append(str, "\\Draft");
2747
2748         if (str->len > 0 && str->str[str->len - 1] == ' ')
2749                 g_string_truncate(str, str->len - 1);
2750
2751         ret = str->str;
2752         g_string_free(str, FALSE);
2753
2754         return ret;
2755 }
2756
2757 static gint imap_set_message_flags(IMAPSession *session,
2758                                    MsgNumberList *numlist,
2759                                    IMAPFlags flags,
2760                                    gboolean is_set)
2761 {
2762         gchar *cmd;
2763         gchar *flag_str;
2764         gint ok = 0;
2765         GSList *seq_list;
2766         IMAPSet imapset;
2767
2768         flag_str = imap_get_flag_str(flags);
2769         cmd = g_strconcat(is_set ? "+FLAGS.SILENT (" : "-FLAGS.SILENT (",
2770                           flag_str, ")", NULL);
2771         g_free(flag_str);
2772
2773         seq_list = imap_get_seq_set_from_numlist(numlist);
2774         imapset = get_seq_set_from_seq_list(seq_list);
2775
2776         ok = imap_cmd_store(session, imapset, cmd);
2777         
2778         g_free(imapset);
2779         imap_seq_set_free(seq_list);
2780         g_free(cmd);
2781
2782         return ok;
2783 }
2784
2785 typedef struct _select_data {
2786         IMAPSession *session;
2787         gchar *real_path;
2788         gint *exists;
2789         gint *recent;
2790         gint *unseen;
2791         guint32 *uid_validity;
2792         gboolean done;
2793 } select_data;
2794
2795 static void *imap_select_thread(void *data)
2796 {
2797         select_data *stuff = (select_data *)data;
2798         IMAPSession *session = stuff->session;
2799         gchar *real_path = stuff->real_path;
2800         gint *exists = stuff->exists;
2801         gint *recent = stuff->recent;
2802         gint *unseen = stuff->unseen;
2803         guint32 *uid_validity = stuff->uid_validity;
2804         gint ok;
2805         
2806         ok = imap_cmd_select(session, real_path,
2807                              exists, recent, unseen, uid_validity, TRUE);
2808         stuff->done = TRUE;
2809         return GINT_TO_POINTER(ok);
2810 }
2811                 
2812 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2813                         const gchar *path,
2814                         gint *exists, gint *recent, gint *unseen,
2815                         guint32 *uid_validity, gboolean block)
2816 {
2817         gchar *real_path;
2818         gint ok;
2819         gint exists_, recent_, unseen_;
2820         guint32 uid_validity_;
2821         
2822         if (!exists || !recent || !unseen || !uid_validity) {
2823                 if (session->mbox && strcmp(session->mbox, path) == 0)
2824                         return IMAP_SUCCESS;
2825                 exists = &exists_;
2826                 recent = &recent_;
2827                 unseen = &unseen_;
2828                 uid_validity = &uid_validity_;
2829         }
2830
2831         g_free(session->mbox);
2832         session->mbox = NULL;
2833
2834         real_path = imap_get_real_path(folder, path);
2835         
2836 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
2837         if (block == FALSE) {
2838                 select_data *data = g_new0(select_data, 1);
2839                 void *tmp;
2840                 pthread_t pt;
2841                 data->session = session;
2842                 data->real_path = real_path;
2843                 data->exists = exists;
2844                 data->recent = recent;
2845                 data->unseen = unseen;
2846                 data->uid_validity = uid_validity;
2847                 data->done = FALSE;
2848                 
2849                 if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
2850                                 imap_select_thread, data) != 0) {
2851                         ok = GPOINTER_TO_INT(imap_select_thread(data));
2852                         g_free(data);
2853                 } else {
2854                         debug_print("+++waiting for imap_select_thread...\n");
2855                         while(!data->done) {
2856                                 /* don't let the interface freeze while waiting */
2857                                 sylpheed_do_idle();
2858                         }
2859                         debug_print("---imap_select_thread done\n");
2860
2861                         /* get the thread's return value and clean its resources */
2862                         pthread_join(pt, &tmp);
2863                         ok = GPOINTER_TO_INT(tmp);
2864                         g_free(data);
2865                 }
2866         } else {
2867                 ok = imap_cmd_select(session, real_path,
2868                              exists, recent, unseen, uid_validity, block);
2869         }
2870 #else
2871         ok = imap_cmd_select(session, real_path,
2872                              exists, recent, unseen, uid_validity, block);
2873 #endif
2874         if (ok != IMAP_SUCCESS)
2875                 log_warning(_("can't select folder: %s\n"), real_path);
2876         else {
2877                 session->mbox = g_strdup(path);
2878                 session->folder_content_changed = FALSE;
2879         }
2880         g_free(real_path);
2881
2882         return ok;
2883 }
2884
2885 #define THROW(err) { ok = err; goto catch; }
2886
2887 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2888                         const gchar *path,
2889                         gint *messages, gint *recent,
2890                         guint32 *uid_next, guint32 *uid_validity,
2891                         gint *unseen, gboolean block)
2892 {
2893         gchar *real_path;
2894         gchar *real_path_;
2895         gint ok;
2896         GPtrArray *argbuf = NULL;
2897         gchar *str;
2898
2899         if (messages && recent && uid_next && uid_validity && unseen) {
2900                 *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
2901                 argbuf = g_ptr_array_new();
2902         }
2903
2904         real_path = imap_get_real_path(folder, path);
2905         QUOTE_IF_REQUIRED(real_path_, real_path);
2906         imap_gen_send(session, "STATUS %s "
2907                           "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
2908                           real_path_);
2909
2910         ok = imap_cmd_ok_with_block(session, argbuf, block);
2911         if (ok != IMAP_SUCCESS || !argbuf) THROW(ok);
2912
2913         str = search_array_str(argbuf, "STATUS");
2914         if (!str) THROW(IMAP_ERROR);
2915
2916         str = strchr(str, '(');
2917         if (!str) THROW(IMAP_ERROR);
2918         str++;
2919         while (*str != '\0' && *str != ')') {
2920                 while (*str == ' ') str++;
2921
2922                 if (!strncmp(str, "MESSAGES ", 9)) {
2923                         str += 9;
2924                         *messages = strtol(str, &str, 10);
2925                 } else if (!strncmp(str, "RECENT ", 7)) {
2926                         str += 7;
2927                         *recent = strtol(str, &str, 10);
2928                 } else if (!strncmp(str, "UIDNEXT ", 8)) {
2929                         str += 8;
2930                         *uid_next = strtoul(str, &str, 10);
2931                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2932                         str += 12;
2933                         *uid_validity = strtoul(str, &str, 10);
2934                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2935                         str += 7;
2936                         *unseen = strtol(str, &str, 10);
2937                 } else {
2938                         g_warning("invalid STATUS response: %s\n", str);
2939                         break;
2940                 }
2941         }
2942
2943 catch:
2944         g_free(real_path);
2945         if (argbuf) {
2946                 ptr_array_free_strings(argbuf);
2947                 g_ptr_array_free(argbuf, TRUE);
2948         }
2949
2950         return ok;
2951 }
2952
2953 #undef THROW
2954
2955 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
2956 {
2957         gchar **p;
2958         
2959         for (p = session->capability; *p != NULL; ++p) {
2960                 if (!g_ascii_strcasecmp(*p, cap))
2961                         return TRUE;
2962         }
2963
2964         return FALSE;
2965 }
2966
2967 static void imap_free_capabilities(IMAPSession *session)
2968 {
2969         g_strfreev(session->capability);
2970         session->capability = NULL;
2971 }
2972
2973 /* low-level IMAP4rev1 commands */
2974
2975 static gint imap_cmd_authenticate(IMAPSession *session, const gchar *user,
2976                                   const gchar *pass, IMAPAuthType type)
2977 {
2978         gchar *auth_type;
2979         gint ok;
2980         gchar *buf = NULL;
2981         gchar *challenge;
2982         gint challenge_len;
2983         gchar hexdigest[33];
2984         gchar *response;
2985         gchar *response64;
2986
2987         auth_type = "CRAM-MD5";
2988
2989         imap_gen_send(session, "AUTHENTICATE %s", auth_type);
2990         ok = imap_gen_recv(session, &buf);
2991         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2992                 g_free(buf);
2993                 return IMAP_ERROR;
2994         }
2995
2996         challenge = g_malloc(strlen(buf + 2) + 1);
2997         challenge_len = base64_decode(challenge, buf + 2, -1);
2998         challenge[challenge_len] = '\0';
2999         g_free(buf);
3000         log_print("IMAP< [Decoded: %s]\n", challenge);
3001
3002         md5_hex_hmac(hexdigest, challenge, challenge_len, pass, strlen(pass));
3003         g_free(challenge);
3004
3005         response = g_strdup_printf("%s %s", user, hexdigest);
3006         log_print("IMAP> [Encoded: %s]\n", response);
3007         response64 = g_malloc((strlen(response) + 3) * 2 + 1);
3008         base64_encode(response64, response, strlen(response));
3009         g_free(response);
3010
3011         log_print("IMAP> %s\n", response64);
3012         sock_puts(SESSION(session)->sock, response64);
3013         ok = imap_cmd_ok(session, NULL);
3014         if (ok != IMAP_SUCCESS)
3015                 log_warning(_("IMAP4 authentication failed.\n"));
3016
3017         return ok;
3018 }
3019
3020 static gint imap_cmd_login(IMAPSession *session,
3021                            const gchar *user, const gchar *pass)
3022 {
3023         gchar *ans;
3024         gint ok;
3025
3026         imap_gen_send(session, "LOGIN {%d}\r\n%s {%d}\r\n%s", 
3027                                 strlen(user), user, 
3028                                 strlen(pass), pass);
3029                                 
3030         ok = imap_gen_recv_with_block(session, &ans, TRUE);
3031         if (ok != IMAP_SUCCESS || ans[0] != '+' || ans[1] != ' ') {
3032                 g_free(ans);
3033                 return IMAP_ERROR;
3034         }
3035         g_free(ans);
3036         ok = imap_gen_recv_with_block(session, &ans, TRUE);
3037         if (ok != IMAP_SUCCESS || ans[0] != '+' || ans[1] != ' ') {
3038                 g_free(ans);
3039                 return IMAP_ERROR;
3040         }
3041         g_free(ans);
3042         ok = imap_cmd_ok(session, NULL);
3043         if (ok != IMAP_SUCCESS)
3044                 log_warning(_("IMAP4 login failed.\n"));
3045
3046         return ok;
3047 }
3048
3049 static gint imap_cmd_logout(IMAPSession *session)
3050 {
3051         imap_gen_send(session, "LOGOUT");
3052         return imap_cmd_ok(session, NULL);
3053 }
3054
3055 static gint imap_cmd_noop(IMAPSession *session)
3056 {
3057         imap_gen_send(session, "NOOP");
3058         return imap_cmd_ok(session, NULL);
3059 }
3060
3061 #if USE_OPENSSL
3062 static gint imap_cmd_starttls(IMAPSession *session)
3063 {
3064         imap_gen_send(session, "STARTTLS");
3065         return imap_cmd_ok(session, NULL);
3066 }
3067 #endif
3068
3069 #define THROW(err) { ok = err; goto catch; }
3070
3071 static gint imap_cmd_namespace(IMAPSession *session, gchar **ns_str)
3072 {
3073         gint ok;
3074         GPtrArray *argbuf;
3075         gchar *str;
3076
3077         argbuf = g_ptr_array_new();
3078
3079         imap_gen_send(session, "NAMESPACE");
3080         if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW(ok);
3081
3082         str = search_array_str(argbuf, "NAMESPACE");
3083         if (!str) THROW(IMAP_ERROR);
3084
3085         *ns_str = g_strdup(str);
3086
3087 catch:
3088         ptr_array_free_strings(argbuf);
3089         g_ptr_array_free(argbuf, TRUE);
3090
3091         return ok;
3092 }
3093
3094 #undef THROW
3095
3096 static gint imap_cmd_list(IMAPSession *session, const gchar *ref,
3097                           const gchar *mailbox, GPtrArray *argbuf)
3098 {
3099         gchar *ref_, *mailbox_;
3100
3101         if (!ref) ref = "\"\"";
3102         if (!mailbox) mailbox = "\"\"";
3103
3104         QUOTE_IF_REQUIRED(ref_, ref);
3105         QUOTE_IF_REQUIRED(mailbox_, mailbox);
3106         imap_gen_send(session, "LIST %s %s", ref_, mailbox_);
3107
3108         return imap_cmd_ok(session, argbuf);
3109 }
3110
3111 #define THROW goto catch
3112
3113 static gint imap_cmd_do_select(IMAPSession *session, const gchar *folder,
3114                                gboolean examine,
3115                                gint *exists, gint *recent, gint *unseen,
3116                                guint32 *uid_validity, gboolean block)
3117 {
3118         gint ok;
3119         gchar *resp_str;
3120         GPtrArray *argbuf;
3121         gchar *select_cmd;
3122         gchar *folder_;
3123         unsigned int uid_validity_;
3124
3125         *exists = *recent = *unseen = *uid_validity = 0;
3126         argbuf = g_ptr_array_new();
3127
3128         if (examine)
3129                 select_cmd = "EXAMINE";
3130         else
3131                 select_cmd = "SELECT";
3132
3133         QUOTE_IF_REQUIRED(folder_, folder);
3134         imap_gen_send(session, "%s %s", select_cmd, folder_);
3135
3136         if ((ok = imap_cmd_ok_with_block(session, argbuf, block)) != IMAP_SUCCESS) THROW;
3137
3138         resp_str = search_array_contain_str(argbuf, "EXISTS");
3139         if (resp_str) {
3140                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
3141                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
3142                         THROW;
3143                 }
3144         }
3145
3146         resp_str = search_array_contain_str(argbuf, "RECENT");
3147         if (resp_str) {
3148                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
3149                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
3150                         THROW;
3151                 }
3152         }
3153
3154         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
3155         if (resp_str) {
3156                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", &uid_validity_)
3157                     != 1) {
3158                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
3159                         THROW;
3160                 }
3161                 *uid_validity = uid_validity_;
3162         }
3163
3164         resp_str = search_array_contain_str(argbuf, "UNSEEN");
3165         if (resp_str) {
3166                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
3167                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
3168                         THROW;
3169                 }
3170         }
3171
3172 catch:
3173         ptr_array_free_strings(argbuf);
3174         g_ptr_array_free(argbuf, TRUE);
3175
3176         return ok;
3177 }
3178
3179 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3180                             gint *exists, gint *recent, gint *unseen,
3181                             guint32 *uid_validity, gboolean block)
3182 {
3183         return imap_cmd_do_select(session, folder, FALSE,
3184                                   exists, recent, unseen, uid_validity, block);
3185 }
3186
3187 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3188                              gint *exists, gint *recent, gint *unseen,
3189                              guint32 *uid_validity, gboolean block)
3190 {
3191         return imap_cmd_do_select(session, folder, TRUE,
3192                                   exists, recent, unseen, uid_validity, block);
3193 }
3194
3195 #undef THROW
3196
3197 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3198 {
3199         gchar *folder_;
3200
3201         QUOTE_IF_REQUIRED(folder_, folder);
3202         imap_gen_send(session, "CREATE %s", folder_);
3203
3204         return imap_cmd_ok(session, NULL);
3205 }
3206
3207 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3208                             const gchar *new_folder)
3209 {
3210         gchar *old_folder_, *new_folder_;
3211
3212         QUOTE_IF_REQUIRED(old_folder_, old_folder);
3213         QUOTE_IF_REQUIRED(new_folder_, new_folder);
3214         imap_gen_send(session, "RENAME %s %s", old_folder_, new_folder_);
3215
3216         return imap_cmd_ok(session, NULL);
3217 }
3218
3219 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3220 {
3221         gchar *folder_;
3222
3223         QUOTE_IF_REQUIRED(folder_, folder);
3224         imap_gen_send(session, "DELETE %s", folder_);
3225
3226         return imap_cmd_ok(session, NULL);
3227 }
3228
3229 static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, 
3230                             GSList **list, gboolean block)
3231 {
3232         gint ok;
3233         gchar *uidlist;
3234         GPtrArray *argbuf;
3235
3236         g_return_val_if_fail(criteria != NULL, IMAP_ERROR);
3237         g_return_val_if_fail(list != NULL, IMAP_ERROR);
3238
3239         *list = NULL;
3240         
3241         argbuf = g_ptr_array_new();
3242         imap_gen_send(session, "UID SEARCH %s", criteria);
3243
3244         ok = imap_cmd_ok_with_block(session, argbuf, block);
3245         if (ok != IMAP_SUCCESS) {
3246                 ptr_array_free_strings(argbuf);
3247                 g_ptr_array_free(argbuf, TRUE);
3248                 return ok;
3249         }
3250
3251         if ((uidlist = search_array_str(argbuf, "SEARCH ")) != NULL) {
3252                 gchar **strlist, **p;
3253
3254                 strlist = g_strsplit(uidlist + 7, " ", 0);
3255                 for (p = strlist; *p != NULL; ++p) {
3256                         guint msgnum;
3257
3258                         if (sscanf(*p, "%u", &msgnum) == 1)
3259                                 *list = g_slist_append(*list, GINT_TO_POINTER(msgnum));
3260                 }
3261                 g_strfreev(strlist);
3262         }
3263         ptr_array_free_strings(argbuf);
3264         g_ptr_array_free(argbuf, TRUE);
3265
3266         return IMAP_SUCCESS;
3267 }
3268
3269 typedef struct _fetch_data {
3270         IMAPSession *session;
3271         guint32 uid;
3272         const gchar *filename;
3273         gboolean headers;
3274         gboolean body;
3275         gboolean done;
3276 } fetch_data;
3277
3278 static void *imap_cmd_fetch_thread(void *data)
3279 {
3280         fetch_data *stuff = (fetch_data *)data;
3281         IMAPSession *session = stuff->session;
3282         guint32 uid = stuff->uid;
3283         const gchar *filename = stuff->filename;
3284         
3285         gint ok;
3286         gchar *buf = NULL;
3287         gchar *cur_pos;
3288         gchar size_str[32];
3289         glong size_num;
3290
3291         if (filename == NULL) {
3292                 stuff->done = TRUE;
3293                 return GINT_TO_POINTER(IMAP_ERROR);
3294         }
3295         
3296         if (stuff->body)
3297                 imap_gen_send(session, "UID FETCH %d BODY.PEEK[]", uid);
3298         else
3299                 imap_gen_send(session, "UID FETCH %d BODY.PEEK[HEADER]",
3300                                 uid);
3301         while ((ok = imap_gen_recv_block(session, &buf)) == IMAP_SUCCESS) {
3302                 if (buf[0] != '*' || buf[1] != ' ') {
3303                         g_free(buf);
3304                         stuff->done = TRUE;
3305                         return GINT_TO_POINTER(IMAP_ERROR);
3306                 }
3307                 if (strstr(buf, "FETCH") != NULL) break;
3308                 g_free(buf);
3309         }
3310         if (ok != IMAP_SUCCESS) {
3311                 g_free(buf);
3312                 stuff->done = TRUE;
3313                 return GINT_TO_POINTER(ok);
3314         }
3315
3316 #define RETURN_ERROR_IF_FAIL(cond)      \
3317         if (!(cond)) {                  \
3318                 g_free(buf);            \
3319                 stuff->done = TRUE;     \
3320                 return GINT_TO_POINTER(IMAP_ERROR);     \
3321         }
3322
3323         cur_pos = strchr(buf, '{');
3324         RETURN_ERROR_IF_FAIL(cur_pos != NULL);
3325         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
3326         RETURN_ERROR_IF_FAIL(cur_pos != NULL);
3327         size_num = atol(size_str);
3328         RETURN_ERROR_IF_FAIL(size_num >= 0);
3329
3330         RETURN_ERROR_IF_FAIL(*cur_pos == '\0');
3331
3332 #undef RETURN_ERROR_IF_FAIL
3333
3334         g_free(buf);
3335
3336         if (recv_bytes_write_to_file(SESSION(session)->sock,
3337                                      size_num, filename) != 0) {
3338                 stuff->done = TRUE;
3339                 return GINT_TO_POINTER(IMAP_ERROR);
3340         }
3341         if (imap_gen_recv_block(session, &buf) != IMAP_SUCCESS) {
3342                 g_free(buf);
3343                 stuff->done = TRUE;
3344                 return GINT_TO_POINTER(IMAP_ERROR);
3345         }
3346
3347         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')') {
3348                 g_free(buf);
3349                 stuff->done = TRUE;
3350                 return GINT_TO_POINTER(IMAP_ERROR);
3351         }
3352         g_free(buf);
3353
3354         ok = imap_cmd_ok_block(session, NULL);
3355
3356         stuff->done = TRUE;
3357         return GINT_TO_POINTER(ok);
3358 }
3359
3360 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3361                                 const gchar *filename, gboolean headers,
3362                                 gboolean body)
3363 {
3364         fetch_data *data = g_new0(fetch_data, 1);
3365         int result = 0;
3366 #ifdef USE_PTHREAD
3367         void *tmp;
3368         pthread_t pt;
3369 #endif
3370         data->done = FALSE;
3371         data->session = session;
3372         data->uid = uid;
3373         data->filename = filename;
3374         data->headers = headers;
3375         data->body = body;
3376
3377         if (prefs_common.work_offline && !imap_gtk_should_override()) {
3378                 g_free(data);
3379                 return -1;
3380         }
3381
3382 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
3383         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
3384                         imap_cmd_fetch_thread, data) != 0) {
3385                 result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3386                 g_free(data);
3387                 return result;
3388         }
3389         debug_print("+++waiting for imap_cmd_fetch_thread...\n");
3390         while(!data->done) {
3391                 /* don't let the interface freeze while waiting */
3392                 sylpheed_do_idle();
3393         }
3394         debug_print("---imap_cmd_fetch_thread done\n");
3395
3396         /* get the thread's return value and clean its resources */
3397         pthread_join(pt, &tmp);
3398         result = GPOINTER_TO_INT(tmp);
3399 #else
3400         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3401 #endif
3402         g_free(data);
3403         return result;
3404 }
3405
3406 static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
3407                             const gchar *file, IMAPFlags flags, 
3408                             guint32 *new_uid)
3409 {
3410         gint ok;
3411         gint size;
3412         gchar *destfolder_;
3413         gchar *flag_str;
3414         unsigned int new_uid_;
3415         gchar *ret = NULL;
3416         gchar buf[BUFFSIZE];
3417         FILE *fp;
3418         GPtrArray *argbuf;
3419         gchar *resp_str;
3420
3421         g_return_val_if_fail(file != NULL, IMAP_ERROR);
3422
3423         size = get_file_size_as_crlf(file);
3424         if ((fp = fopen(file, "rb")) == NULL) {
3425                 FILE_OP_ERROR(file, "fopen");
3426                 return -1;
3427         }
3428         QUOTE_IF_REQUIRED(destfolder_, destfolder);
3429         flag_str = imap_get_flag_str(flags);
3430         imap_gen_send(session, "APPEND %s (%s) {%d}", 
3431                       destfolder_, flag_str, size);
3432         g_free(flag_str);
3433
3434         ok = imap_gen_recv(session, &ret);
3435         if (ok != IMAP_SUCCESS || ret[0] != '+' || ret[1] != ' ') {
3436                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
3437                 g_free(ret);
3438                 fclose(fp);
3439                 return IMAP_ERROR;
3440         }
3441         g_free(ret);
3442
3443         log_print("IMAP4> %s\n", "(sending file...)");
3444
3445         while (fgets(buf, sizeof(buf), fp) != NULL) {
3446                 strretchomp(buf);
3447                 if (sock_puts(SESSION(session)->sock, buf) < 0) {
3448                         fclose(fp);
3449                         return -1;
3450                 }
3451         }
3452
3453         if (ferror(fp)) {
3454                 FILE_OP_ERROR(file, "fgets");
3455                 fclose(fp);
3456                 return -1;
3457         }
3458
3459         sock_puts(SESSION(session)->sock, "");
3460
3461         fclose(fp);
3462
3463         if (new_uid != NULL)
3464                 *new_uid = 0;
3465
3466         if (new_uid != NULL && session->uidplus) {
3467                 argbuf = g_ptr_array_new();
3468
3469                 ok = imap_cmd_ok(session, argbuf);
3470                 if ((ok == IMAP_SUCCESS) && (argbuf->len > 0)) {
3471                         resp_str = g_ptr_array_index(argbuf, argbuf->len - 1);
3472                         if (resp_str &&
3473                             sscanf(resp_str, "%*u OK [APPENDUID %*u %u]",
3474                                    &new_uid_) == 1) {
3475                                 *new_uid = new_uid_;
3476                         }
3477                 }
3478
3479                 ptr_array_free_strings(argbuf);
3480                 g_ptr_array_free(argbuf, TRUE);
3481         } else
3482                 ok = imap_cmd_ok(session, NULL);
3483
3484         if (ok != IMAP_SUCCESS)
3485                 log_warning(_("can't append message to %s\n"),
3486                             destfolder_);
3487
3488         return ok;
3489 }
3490
3491 static MsgNumberList *imapset_to_numlist(IMAPSet imapset)
3492 {
3493         gchar **ranges, **range;
3494         unsigned int low, high;
3495         MsgNumberList *uids = NULL;
3496         
3497         ranges = g_strsplit(imapset, ",", 0);
3498         for (range = ranges; *range != NULL; range++) {
3499                 if (sscanf(*range, "%u:%u", &low, &high) == 1)
3500                         uids = g_slist_prepend(uids, GINT_TO_POINTER(low));
3501                 else {
3502                         int i;
3503                         for (i = low; i <= high; i++)
3504                                 uids = g_slist_prepend(uids, GINT_TO_POINTER(i));
3505                 }
3506         }
3507         uids = g_slist_reverse(uids);
3508         g_strfreev(ranges);
3509
3510         return uids;
3511 }
3512
3513 static gint imap_cmd_copy(IMAPSession *session, const gchar *seq_set,
3514                           const gchar *destfolder, GRelation *uid_mapping)
3515 {
3516         gint ok;
3517         gchar *destfolder_;
3518         
3519         g_return_val_if_fail(session != NULL, IMAP_ERROR);
3520         g_return_val_if_fail(seq_set != NULL, IMAP_ERROR);
3521         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
3522
3523         QUOTE_IF_REQUIRED(destfolder_, destfolder);
3524         imap_gen_send(session, "UID COPY %s %s", seq_set, destfolder_);
3525
3526         if (uid_mapping != NULL && session->uidplus) {
3527                 GPtrArray *reply;               
3528                 gchar *resp_str = NULL, *olduids_str, *newuids_str;
3529                 MsgNumberList *olduids, *old_cur, *newuids, *new_cur;
3530
3531                 reply = g_ptr_array_new();
3532                 ok = imap_cmd_ok(session, reply);
3533                 if ((ok == IMAP_SUCCESS) && (reply->len > 0)) {
3534                         resp_str = g_ptr_array_index(reply, reply->len - 1);
3535                         if (resp_str) {
3536                                 olduids_str = g_new0(gchar, strlen(resp_str));
3537                                 newuids_str = g_new0(gchar, strlen(resp_str));
3538                                 if (sscanf(resp_str, "%*s OK [COPYUID %*u %[0-9,:] %[0-9,:]]",
3539                                            olduids_str, newuids_str) == 2) {
3540                                         olduids = imapset_to_numlist(olduids_str);
3541                                         newuids = imapset_to_numlist(newuids_str);
3542
3543                                         old_cur = olduids;
3544                                         new_cur = newuids;
3545                                         while(old_cur != NULL && new_cur != NULL) {
3546                                                 g_relation_insert(uid_mapping, 
3547                                                                   GPOINTER_TO_INT(old_cur->data),
3548                                                                   GPOINTER_TO_INT(new_cur->data));
3549                                                 old_cur = g_slist_next(old_cur);
3550                                                 new_cur = g_slist_next(new_cur);
3551                                         }
3552
3553                                         g_slist_free(olduids);
3554                                         g_slist_free(newuids);
3555                                 }
3556                                 g_free(olduids_str);
3557                                 g_free(newuids_str);
3558                         }
3559                 }
3560                 ptr_array_free_strings(reply);
3561                 g_ptr_array_free(reply, TRUE);
3562         } else
3563                 ok = imap_cmd_ok(session, NULL);
3564
3565         if (ok != IMAP_SUCCESS)
3566                 log_warning(_("can't copy %s to %s\n"), seq_set, destfolder_);
3567
3568         return ok;
3569 }
3570
3571 gint imap_cmd_envelope(IMAPSession *session, IMAPSet set)
3572 {
3573         static gchar *header_fields = 
3574                 "Date From To Cc Subject Message-ID References In-Reply-To" ;
3575
3576         imap_gen_send
3577                 (session, "UID FETCH %s (UID FLAGS RFC822.SIZE BODY.PEEK[HEADER.FIELDS (%s)])",
3578                  set, header_fields);
3579
3580         return IMAP_SUCCESS;
3581 }
3582
3583 static gint imap_cmd_store(IMAPSession *session, IMAPSet seq_set,
3584                            gchar *sub_cmd)
3585 {
3586         gint ok;
3587
3588         imap_gen_send(session, "UID STORE %s %s", seq_set, sub_cmd);
3589
3590         if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS) {
3591                 log_warning(_("error while imap command: STORE %s %s\n"),
3592                             seq_set, sub_cmd);
3593                 return ok;
3594         }
3595
3596         return IMAP_SUCCESS;
3597 }
3598
3599 typedef struct _expunge_data {
3600         IMAPSession *session;
3601         IMAPSet seq_set;
3602         gboolean done;
3603 } expunge_data;
3604
3605 static void *imap_cmd_expunge_thread(void *data)
3606 {
3607         expunge_data *stuff = (expunge_data *)data;
3608         IMAPSession *session = stuff->session;
3609         IMAPSet seq_set = stuff->seq_set;
3610
3611         gint ok;
3612
3613         if (seq_set && session->uidplus)
3614                 imap_gen_send(session, "UID EXPUNGE %s", seq_set);
3615         else    
3616                 imap_gen_send(session, "EXPUNGE");
3617         if ((ok = imap_cmd_ok_with_block(session, NULL, TRUE)) != IMAP_SUCCESS) {
3618                 log_warning(_("error while imap command: EXPUNGE\n"));
3619                 stuff->done = TRUE;
3620                 return GINT_TO_POINTER(ok);
3621         }
3622
3623         stuff->done = TRUE;
3624         return GINT_TO_POINTER(IMAP_SUCCESS);
3625 }
3626
3627 static gint imap_cmd_expunge(IMAPSession *session, IMAPSet seq_set)
3628 {
3629         expunge_data *data = g_new0(expunge_data, 1);
3630         int result;
3631 #ifdef USE_PTHREAD
3632         void *tmp;
3633         pthread_t pt;
3634 #endif
3635         data->done = FALSE;
3636         data->session = session;
3637         data->seq_set = seq_set;
3638
3639         if (prefs_common.work_offline && !imap_gtk_should_override()) {
3640                 g_free(data);
3641                 return -1;
3642         }
3643
3644 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
3645         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
3646                         imap_cmd_expunge_thread, data) != 0) {
3647                 result = GPOINTER_TO_INT(imap_cmd_expunge_thread(data));
3648                 g_free(data);
3649                 return result;
3650         }
3651         debug_print("+++waiting for imap_cmd_expunge_thread...\n");
3652         while(!data->done) {
3653                 /* don't let the interface freeze while waiting */
3654                 sylpheed_do_idle();
3655         }
3656         debug_print("---imap_cmd_expunge_thread done\n");
3657
3658         /* get the thread's return value and clean its resources */
3659         pthread_join(pt, &tmp);
3660         result = GPOINTER_TO_INT(tmp);
3661 #else
3662         result = GPOINTER_TO_INT(imap_cmd_expunge_thread(data));
3663 #endif
3664         g_free(data);
3665         return result;
3666 }
3667
3668 static gint imap_cmd_close(IMAPSession *session)
3669 {
3670         gint ok;
3671
3672         imap_gen_send(session, "CLOSE");
3673         if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS)
3674                 log_warning(_("error while imap command: CLOSE\n"));
3675
3676         return ok;
3677 }
3678
3679 static gint imap_cmd_ok_with_block(IMAPSession *session, GPtrArray *argbuf, gboolean block)
3680 {
3681         gint ok = IMAP_SUCCESS;
3682         gchar *buf;
3683         gint cmd_num;
3684         gchar *data;
3685
3686         while ((ok = imap_gen_recv_with_block(session, &buf, block))
3687                == IMAP_SUCCESS) {
3688                 /* make sure data is long enough for any substring of buf */
3689                 data = alloca(strlen(buf) + 1);
3690
3691                 /* untagged line read */
3692                 if (buf[0] == '*' && buf[1] == ' ') {
3693                         gint num;
3694                         if (argbuf)
3695                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
3696
3697                         if (sscanf(buf + 2, "%d %s", &num, data) >= 2) {
3698                                 if (!strcmp(data, "EXISTS")) {
3699                                         session->exists = num;
3700                                         session->folder_content_changed = TRUE;
3701                                 }
3702
3703                                 if(!strcmp(data, "EXPUNGE")) {
3704                                         session->exists--;
3705                                         session->folder_content_changed = TRUE;
3706                                 }
3707                         }
3708                 /* tagged line with correct tag and OK response found */
3709                 } else if ((sscanf(buf, "%d %s", &cmd_num, data) >= 2) &&
3710                            (cmd_num == session->cmd_count) &&
3711                            !strcmp(data, "OK")) {
3712                         if (argbuf)
3713                                 g_ptr_array_add(argbuf, g_strdup(buf));
3714                         break;
3715                 /* everything else */
3716                 } else {
3717                         ok = IMAP_ERROR;
3718                         break;
3719                 }
3720                 g_free(buf);
3721         }
3722         g_free(buf);
3723
3724         return ok;
3725 }
3726 static gint imap_cmd_ok(IMAPSession *session, GPtrArray *argbuf)
3727 {
3728         return imap_cmd_ok_with_block(session, argbuf, FALSE);
3729 }
3730 static gint imap_cmd_ok_block(IMAPSession *session, GPtrArray *argbuf)
3731 {
3732         return imap_cmd_ok_with_block(session, argbuf, TRUE);
3733 }
3734 static void imap_gen_send(IMAPSession *session, const gchar *format, ...)
3735 {
3736         gchar *buf;
3737         gchar *tmp;
3738         gchar *p;
3739         va_list args;
3740
3741         va_start(args, format);
3742         tmp = g_strdup_vprintf(format, args);
3743         va_end(args);
3744
3745         session->cmd_count++;
3746
3747         buf = g_strdup_printf("%d %s\r\n", session->cmd_count, tmp);
3748         if (!g_ascii_strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
3749                 *p = '\0';
3750                 log_print("IMAP4> %d %s ********\n", session->cmd_count, tmp);
3751         } else
3752                 log_print("IMAP4> %d %s\n", session->cmd_count, tmp);
3753
3754         sock_write_all(SESSION(session)->sock, buf, strlen(buf));
3755         g_free(tmp);
3756         g_free(buf);
3757 }
3758
3759 static gint imap_gen_recv_with_block(IMAPSession *session, gchar **ret, gboolean block)
3760 {
3761         if (!block) {
3762                 if ((*ret = imap_getline(SESSION(session)->sock)) == NULL)
3763                         return IMAP_SOCKET;
3764         } else {
3765                 if ((*ret = sock_getline(SESSION(session)->sock)) == NULL)
3766                         return IMAP_SOCKET;
3767         }
3768         strretchomp(*ret);
3769
3770         log_print("IMAP4< %s\n", *ret);
3771         
3772         session_set_access_time(SESSION(session));
3773
3774         return IMAP_SUCCESS;
3775 }
3776
3777 static gint imap_gen_recv_block(IMAPSession *session, gchar **ret)
3778 {
3779         return imap_gen_recv_with_block(session, ret, TRUE);
3780 }
3781
3782 static gint imap_gen_recv(IMAPSession *session, gchar **ret)
3783 {
3784         return imap_gen_recv_with_block(session, ret, FALSE);
3785 }
3786 /* misc utility functions */
3787
3788 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
3789 {
3790         gchar *tmp;
3791
3792         dest[0] = '\0';
3793         tmp = strchr(src, ch);
3794         if (!tmp)
3795                 return NULL;
3796
3797         memcpy(dest, src, MIN(tmp - src, len - 1));
3798         dest[MIN(tmp - src, len - 1)] = '\0';
3799
3800         return tmp + 1;
3801 }
3802
3803 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
3804 {
3805         const gchar *p = src;
3806         gint n = 0;
3807
3808         g_return_val_if_fail(*p == ch, NULL);
3809
3810         *dest = '\0';
3811         p++;
3812
3813         while (*p != '\0' && *p != ch) {
3814                 if (n < len - 1) {
3815                         if (*p == '\\' && *(p + 1) != '\0')
3816                                 p++;
3817                         *dest++ = *p++;
3818                 } else
3819                         p++;
3820                 n++;
3821         }
3822
3823         *dest = '\0';
3824         return (gchar *)(*p == ch ? p + 1 : p);
3825 }
3826
3827 static gchar *search_array_contain_str(GPtrArray *array, const gchar *str)
3828 {
3829         gint i;
3830
3831         for (i = 0; i < array->len; i++) {
3832                 gchar *tmp;
3833
3834                 tmp = g_ptr_array_index(array, i);
3835                 if (strstr(tmp, str) != NULL)
3836                         return tmp;
3837         }
3838
3839         return NULL;
3840 }
3841
3842 static gchar *search_array_str(GPtrArray *array, const gchar *str)
3843 {
3844         gint i;
3845         gint len;
3846
3847         len = strlen(str);
3848
3849         for (i = 0; i < array->len; i++) {
3850                 gchar *tmp;
3851
3852                 tmp = g_ptr_array_index(array, i);
3853                 if (!strncmp(tmp, str, len))
3854                         return tmp;
3855         }
3856
3857         return NULL;
3858 }
3859
3860 static void imap_path_separator_subst(gchar *str, gchar separator)
3861 {
3862         gchar *p;
3863         gboolean in_escape = FALSE;
3864
3865         if (!separator || separator == '/') return;
3866
3867         for (p = str; *p != '\0'; p++) {
3868                 if (*p == '/' && !in_escape)
3869                         *p = separator;
3870                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3871                         in_escape = TRUE;
3872                 else if (*p == '-' && in_escape)
3873                         in_escape = FALSE;
3874         }
3875 }
3876
3877 static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
3878 {
3879         static iconv_t cd = (iconv_t)-1;
3880         static gboolean iconv_ok = TRUE;
3881         GString *norm_utf7;
3882         gchar *norm_utf7_p;
3883         size_t norm_utf7_len;
3884         const gchar *p;
3885         gchar *to_str, *to_p;
3886         size_t to_len;
3887         gboolean in_escape = FALSE;
3888
3889         if (!iconv_ok) return g_strdup(mutf7_str);
3890
3891         if (cd == (iconv_t)-1) {
3892                 cd = iconv_open(CS_INTERNAL, CS_UTF_7);
3893                 if (cd == (iconv_t)-1) {
3894                         g_warning("iconv cannot convert UTF-7 to %s\n",
3895                                   CS_INTERNAL);
3896                         iconv_ok = FALSE;
3897                         return g_strdup(mutf7_str);
3898                 }
3899         }
3900
3901         /* modified UTF-7 to normal UTF-7 conversion */
3902         norm_utf7 = g_string_new(NULL);
3903
3904         for (p = mutf7_str; *p != '\0'; p++) {
3905                 /* replace: '&'  -> '+',
3906                             "&-" -> '&',
3907                             escaped ','  -> '/' */
3908                 if (!in_escape && *p == '&') {
3909                         if (*(p + 1) != '-') {
3910                                 g_string_append_c(norm_utf7, '+');
3911                                 in_escape = TRUE;
3912                         } else {
3913                                 g_string_append_c(norm_utf7, '&');
3914                                 p++;
3915                         }
3916                 } else if (in_escape && *p == ',') {
3917                         g_string_append_c(norm_utf7, '/');
3918                 } else if (in_escape && *p == '-') {
3919                         g_string_append_c(norm_utf7, '-');
3920                         in_escape = FALSE;
3921                 } else {
3922                         g_string_append_c(norm_utf7, *p);
3923                 }
3924         }
3925
3926         norm_utf7_p = norm_utf7->str;
3927         norm_utf7_len = norm_utf7->len;
3928         to_len = strlen(mutf7_str) * 5;
3929         to_p = to_str = g_malloc(to_len + 1);
3930
3931         if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
3932                   &to_p, &to_len) == -1) {
3933                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
3934                           conv_get_locale_charset_str());
3935                 g_string_free(norm_utf7, TRUE);
3936                 g_free(to_str);
3937                 return g_strdup(mutf7_str);
3938         }
3939
3940         /* second iconv() call for flushing */
3941         iconv(cd, NULL, NULL, &to_p, &to_len);
3942         g_string_free(norm_utf7, TRUE);
3943         *to_p = '\0';
3944
3945         return to_str;
3946 }
3947
3948 static gchar *imap_utf8_to_modified_utf7(const gchar *from)
3949 {
3950         static iconv_t cd = (iconv_t)-1;
3951         static gboolean iconv_ok = TRUE;
3952         gchar *norm_utf7, *norm_utf7_p;
3953         size_t from_len, norm_utf7_len;
3954         GString *to_str;
3955         gchar *from_tmp, *to, *p;
3956         gboolean in_escape = FALSE;
3957
3958         if (!iconv_ok) return g_strdup(from);
3959
3960         if (cd == (iconv_t)-1) {
3961                 cd = iconv_open(CS_UTF_7, CS_INTERNAL);
3962                 if (cd == (iconv_t)-1) {
3963                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
3964                                   CS_INTERNAL);
3965                         iconv_ok = FALSE;
3966                         return g_strdup(from);
3967                 }
3968         }
3969
3970         /* UTF-8 to normal UTF-7 conversion */
3971         Xstrdup_a(from_tmp, from, return g_strdup(from));
3972         from_len = strlen(from);
3973         norm_utf7_len = from_len * 5;
3974         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
3975         norm_utf7_p = norm_utf7;
3976
3977 #define IS_PRINT(ch) (isprint(ch) && IS_ASCII(ch))
3978
3979         while (from_len > 0) {
3980                 if (*from_tmp == '+') {
3981                         *norm_utf7_p++ = '+';
3982                         *norm_utf7_p++ = '-';
3983                         norm_utf7_len -= 2;
3984                         from_tmp++;
3985                         from_len--;
3986                 } else if (IS_PRINT(*(guchar *)from_tmp)) {
3987                         /* printable ascii char */
3988                         *norm_utf7_p = *from_tmp;
3989                         norm_utf7_p++;
3990                         norm_utf7_len--;
3991                         from_tmp++;
3992                         from_len--;
3993                 } else {
3994                         size_t conv_len = 0;
3995
3996                         /* unprintable char: convert to UTF-7 */
3997                         p = from_tmp;
3998                         while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
3999                                 conv_len += g_utf8_skip[*(guchar *)p];
4000                                 p += g_utf8_skip[*(guchar *)p];
4001                         }
4002
4003                         from_len -= conv_len;
4004                         if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
4005                                   &conv_len,
4006                                   &norm_utf7_p, &norm_utf7_len) == -1) {
4007                                 g_warning(_("iconv cannot convert UTF-8 to UTF-7\n"));
4008                                 return g_strdup(from);
4009                         }
4010
4011                         /* second iconv() call for flushing */
4012                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
4013                 }
4014         }
4015
4016 #undef IS_PRINT
4017
4018         *norm_utf7_p = '\0';
4019         to_str = g_string_new(NULL);
4020         for (p = norm_utf7; p < norm_utf7_p; p++) {
4021                 /* replace: '&' -> "&-",
4022                             '+' -> '&',
4023                             "+-" -> '+',
4024                             BASE64 '/' -> ',' */
4025                 if (!in_escape && *p == '&') {
4026                         g_string_append(to_str, "&-");
4027                 } else if (!in_escape && *p == '+') {
4028                         if (*(p + 1) == '-') {
4029                                 g_string_append_c(to_str, '+');
4030                                 p++;
4031                         } else {
4032                                 g_string_append_c(to_str, '&');
4033                                 in_escape = TRUE;
4034                         }
4035                 } else if (in_escape && *p == '/') {
4036                         g_string_append_c(to_str, ',');
4037                 } else if (in_escape && *p == '-') {
4038                         g_string_append_c(to_str, '-');
4039                         in_escape = FALSE;
4040                 } else {
4041                         g_string_append_c(to_str, *p);
4042                 }
4043         }
4044
4045         if (in_escape) {
4046                 in_escape = FALSE;
4047                 g_string_append_c(to_str, '-');
4048         }
4049
4050         to = to_str->str;
4051         g_string_free(to_str, FALSE);
4052
4053         return to;
4054 }
4055
4056 static GSList *imap_get_seq_set_from_numlist(MsgNumberList *numlist)
4057 {
4058         GString *str;
4059         GSList *sorted_list, *cur;
4060         guint first, last, next;
4061         gchar *ret_str;
4062         GSList *ret_list = NULL;
4063
4064         if (numlist == NULL)
4065                 return NULL;
4066
4067         str = g_string_sized_new(256);
4068
4069         sorted_list = g_slist_copy(numlist);
4070         sorted_list = g_slist_sort(sorted_list, g_int_compare);
4071
4072         first = GPOINTER_TO_INT(sorted_list->data);
4073
4074         for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
4075                 last = GPOINTER_TO_INT(cur->data);
4076                 if (cur->next)
4077                         next = GPOINTER_TO_INT(cur->next->data);
4078                 else
4079                 &