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