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