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