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