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