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