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