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