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