sync with sylpheed 0.5.0pre3
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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 <glib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <dirent.h>
29 #include <unistd.h>
30 #include <ctype.h>
31
32 #include "intl.h"
33 #include "imap.h"
34 #include "socket.h"
35 #include "recv.h"
36 #include "procmsg.h"
37 #include "procheader.h"
38 #include "folder.h"
39 #include "statusbar.h"
40 #include "prefs_account.h"
41 #include "codeconv.h"
42 #include "utils.h"
43 #include "inputdialog.h"
44
45 #define IMAP4_PORT      143
46
47 static GList *session_list = NULL;
48
49 static gint imap_cmd_count = 0;
50
51 static IMAPSession *imap_session_get    (Folder         *folder);
52 static gchar *imap_query_password       (const gchar    *server,
53                                          const gchar    *user);
54
55 static gint imap_do_copy                (Folder         *folder,
56                                          FolderItem     *dest,
57                                          MsgInfo        *msginfo,
58                                          gboolean        remove_source);
59 static gint imap_do_copy_msgs_with_dest (Folder         *folder,
60                                          FolderItem     *dest, 
61                                          GSList         *msglist,
62                                          gboolean        remove_source);
63
64 static GSList *imap_get_uncached_messages       (IMAPSession    *session,
65                                                  FolderItem     *item,
66                                                  guint32         first_uid,
67                                                  guint32         last_uid);
68 static GSList *imap_delete_cached_messages      (GSList         *mlist,
69                                                  FolderItem     *item,
70                                                  guint32         first_uid,
71                                                  guint32         last_uid);
72 static void imap_delete_all_cached_messages     (FolderItem     *item);
73
74 static SockInfo *imap_open              (const gchar    *server,
75                                          gushort         port,
76                                          gchar          *buf);
77
78 static gint imap_set_message_flags      (IMAPSession    *session,
79                                          guint32         first_uid,
80                                          guint32         last_uid,
81                                          IMAPFlags       flag,
82                                          gboolean        is_set);
83 static gint imap_select                 (IMAPSession    *session,
84                                          IMAPFolder     *folder,
85                                          const gchar    *path,
86                                          gint           *exists,
87                                          gint           *recent,
88                                          gint           *unseen,
89                                          guint32        *uid_validity);
90 static gint imap_get_uid                (IMAPSession    *session,
91                                          gint            msgnum,
92                                          guint32        *uid);
93 #if 0
94 static gint imap_status_uidnext         (IMAPSession    *session,
95                                          IMAPFolder     *folder,
96                                          const gchar    *path,
97                                          guint32        *uid_next);
98 #endif
99
100 static void imap_parse_namespace                (IMAPSession    *session,
101                                                  IMAPFolder     *folder);
102 static IMAPNameSpace *imap_find_namespace       (IMAPFolder     *folder,
103                                                  const gchar    *path);
104
105 static gchar *imap_parse_atom           (SockInfo       *sock,
106                                          gchar          *src,
107                                          gchar          *dest,
108                                          gchar          *orig_buf);
109 static gchar *imap_parse_one_address    (SockInfo       *sock,
110                                          gchar          *start,
111                                          gchar          *out_from_str,
112                                          gchar          *out_fromname_str,
113                                          gchar          *orig_buf);
114 static gchar *imap_parse_address        (SockInfo       *sock,
115                                          gchar          *start,
116                                          gchar         **out_from_str,
117                                          gchar         **out_fromname_str,
118                                          gchar          *orig_buf);
119 static MsgFlags imap_parse_flags        (const gchar    *flag_str);
120 static MsgInfo *imap_parse_envelope     (SockInfo       *sock,
121                                          gchar          *line_str);
122
123 /* low-level IMAP4rev1 commands */
124 static gint imap_cmd_login      (SockInfo       *sock,
125                                  const gchar    *user,
126                                  const gchar    *pass);
127 static gint imap_cmd_logout     (SockInfo       *sock);
128 static gint imap_cmd_noop       (SockInfo       *sock);
129 static gint imap_cmd_namespace  (SockInfo       *sock,
130                                  gchar         **ns_str);
131 static gint imap_cmd_list       (SockInfo       *sock,
132                                  const gchar    *ref,
133                                  const gchar    *mailbox,
134                                  GPtrArray      *argbuf);
135 static gint imap_cmd_select     (SockInfo       *sock,
136                                  const gchar    *folder,
137                                  gint           *exists,
138                                  gint           *recent,
139                                  gint           *unseen,
140                                  guint32        *uid_validity);
141 #if 0
142 static gint imap_cmd_status     (SockInfo       *sock,
143                                  const gchar    *folder,
144                                  const gchar    *status,
145                                  gint           *value);
146 #endif
147 static gint imap_cmd_create     (SockInfo       *sock,
148                                  const gchar    *folder);
149 static gint imap_cmd_delete     (SockInfo       *sock,
150                                  const gchar    *folder);
151 static gint imap_cmd_envelope   (SockInfo       *sock,
152                                  guint32         first_uid,
153                                  guint32         last_uid);
154 #if 0
155 static gint imap_cmd_search     (SockInfo       *sock,
156                                  GSList         *numlist);
157 #endif
158 static gint imap_cmd_fetch      (SockInfo       *sock,
159                                  guint32         uid,
160                                  const gchar    *filename);
161 static gint imap_cmd_append     (SockInfo       *sock,
162                                  const gchar    *destfolder,
163                                  const gchar    *file);
164 static gint imap_cmd_copy       (SockInfo       *sock,
165                                  guint32         uid,
166                                  const gchar    *destfolder);
167 static gint imap_cmd_store      (SockInfo       *sock,
168                                  guint32         first_uid,
169                                  guint32         last_uid,
170                                  gchar          *sub_cmd);
171 static gint imap_cmd_expunge    (SockInfo       *sock);
172
173 static gint imap_cmd_ok         (SockInfo       *sock,
174                                  GPtrArray      *argbuf);
175 static void imap_cmd_gen_send   (SockInfo       *sock,
176                                  const gchar    *format, ...);
177 static gint imap_cmd_gen_recv   (SockInfo       *sock,
178                                  gchar          *buf,
179                                  gint            size);
180
181 /* misc utility functions */
182 static gchar *strchr_cpy                        (const gchar    *src,
183                                                  gchar           ch,
184                                                  gchar          *dest,
185                                                  gint            len);
186 static gchar *search_array_contain_str          (GPtrArray      *array,
187                                                  gchar          *str);
188 static void imap_path_separator_subst           (gchar          *str,
189                                                  gchar           separator);
190
191 static IMAPSession *imap_session_get(Folder *folder)
192 {
193         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
194
195         g_return_val_if_fail(folder != NULL, NULL);
196         g_return_val_if_fail(folder->type == F_IMAP, NULL);
197         g_return_val_if_fail(folder->account != NULL, NULL);
198
199         if (!rfolder->session) {
200                 rfolder->session =
201                         imap_session_new(folder->account->recv_server,
202                                          IMAP4_PORT,
203                                          folder->account->userid,
204                                          folder->account->passwd);
205                 if (rfolder->session)
206                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
207                                              IMAP_FOLDER(folder));
208                 statusbar_pop_all();
209                 return IMAP_SESSION(rfolder->session);
210         }
211
212         if (imap_cmd_noop(rfolder->session->sock) != IMAP_SUCCESS) {
213                 log_warning(_("IMAP4 connection to %s:%d has been"
214                               " disconnected. Reconnecting...\n"),
215                             folder->account->recv_server, IMAP4_PORT);
216                 session_destroy(rfolder->session);
217                 rfolder->session =
218                         imap_session_new(folder->account->recv_server,
219                                          IMAP4_PORT, folder->account->userid,
220                                          folder->account->passwd);
221                 if (rfolder->session)
222                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
223                                              IMAP_FOLDER(folder));
224         }
225
226         statusbar_pop_all();
227         return IMAP_SESSION(rfolder->session);
228 }
229
230 static gchar *imap_query_password(const gchar *server, const gchar *user)
231 {
232         gchar *message;
233         gchar *pass;
234
235         message = g_strdup_printf(_("Input password for %s on %s:"),
236                                   user, server);
237         pass = input_dialog_with_invisible(_("Input password"), message, NULL);
238         g_free(message);
239
240         return pass;
241 }
242
243 Session *imap_session_new(const gchar *server, gushort port,
244                           const gchar *user, const gchar *pass)
245 {
246         gchar buf[IMAPBUFSIZE];
247         IMAPSession *session;
248         SockInfo *imap_sock;
249
250         g_return_val_if_fail(server != NULL, NULL);
251         g_return_val_if_fail(user != NULL, NULL);
252
253         if (!pass) {
254                 gchar *tmp_pass;
255                 tmp_pass = imap_query_password(server, user);
256                 if (!tmp_pass)
257                         return NULL;
258                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return NULL;});
259                 g_free(tmp_pass);
260         }
261
262         log_message(_("creating IMAP4 connection to %s:%d ...\n"),
263                     server, port);
264
265         if ((imap_sock = imap_open(server, port, buf)) == NULL)
266                 return NULL;
267         if (imap_cmd_login(imap_sock, user, pass) != IMAP_SUCCESS) {
268                 imap_cmd_logout(imap_sock);
269                 sock_close(imap_sock);
270                 return NULL;
271         }
272
273         session = g_new(IMAPSession, 1);
274         SESSION(session)->type      = SESSION_IMAP;
275         SESSION(session)->server    = g_strdup(server);
276         SESSION(session)->sock      = imap_sock;
277         SESSION(session)->connected = TRUE;
278         SESSION(session)->phase     = SESSION_READY;
279         SESSION(session)->data      = NULL;
280         session->mbox = NULL;
281
282         session_list = g_list_append(session_list, session);
283
284         return SESSION(session);
285 }
286
287 void imap_session_destroy(IMAPSession *session)
288 {
289         sock_close(SESSION(session)->sock);
290         SESSION(session)->sock = NULL;
291
292         g_free(session->mbox);
293
294         session_list = g_list_remove(session_list, session);
295 }
296
297 void imap_session_destroy_all(void)
298 {
299         while (session_list != NULL) {
300                 IMAPSession *session = (IMAPSession *)session_list->data;
301
302                 imap_cmd_logout(SESSION(session)->sock);
303                 imap_session_destroy(session);
304         }
305 }
306
307 #define THROW goto catch
308
309 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
310 {
311         GSList *mlist = NULL;
312         IMAPSession *session;
313         gint ok, exists = 0, recent = 0, unseen = 0;
314         guint32 uid_validity = 0;
315         guint32 first_uid = 0, last_uid = 0, begin;
316
317         g_return_val_if_fail(folder != NULL, NULL);
318         g_return_val_if_fail(item != NULL, NULL);
319         g_return_val_if_fail(folder->type == F_IMAP, NULL);
320         g_return_val_if_fail(folder->account != NULL, NULL);
321
322         session = imap_session_get(folder);
323
324         if (!session) {
325                 mlist = procmsg_read_cache(item, FALSE);
326                 item->last_num = procmsg_get_last_num_in_cache(mlist);
327                 procmsg_set_flags(mlist, item);
328                 statusbar_pop_all();
329                 return mlist;
330         }
331
332         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
333                          &exists, &recent, &unseen, &uid_validity);
334         if (ok != IMAP_SUCCESS) THROW;
335         if (exists > 0) {
336                 ok = imap_get_uid(session, 1, &first_uid);
337                 if (ok != IMAP_SUCCESS) THROW;
338                 if (1 != exists) {
339                         ok = imap_get_uid(session, exists, &last_uid);
340                         if (ok != IMAP_SUCCESS) THROW;
341                 } else
342                         last_uid = first_uid;
343         } else {
344                 imap_delete_all_cached_messages(item);
345                 statusbar_pop_all();
346                 return NULL;
347         }
348
349         if (use_cache) {
350                 guint32 cache_last;
351
352                 mlist = procmsg_read_cache(item, FALSE);
353                 procmsg_set_flags(mlist, item);
354                 cache_last = procmsg_get_last_num_in_cache(mlist);
355
356                 /* calculating the range of envelope to get */
357                 if (item->mtime != uid_validity) {
358                         /* mailbox is changed (get all) */
359                         begin = first_uid;
360                 } else if (last_uid < cache_last) {
361                         /* mailbox is changed (get all) */
362                         begin = first_uid;
363                 } else if (last_uid == cache_last) {
364                         /* mailbox unchanged (get none)*/
365                         begin = 0;
366                 } else {
367                         begin = cache_last + 1;
368                 }
369
370                 item->mtime = uid_validity;
371
372                 if (first_uid > 0 && last_uid > 0) {
373                         mlist = imap_delete_cached_messages(mlist, item,
374                                                             0, first_uid - 1);
375                         mlist = imap_delete_cached_messages(mlist, item,
376                                                             last_uid + 1,
377                                                             UINT_MAX);
378                 }
379                 if (begin > 0)
380                         mlist = imap_delete_cached_messages(mlist, item,
381                                                             begin, UINT_MAX);
382         } else {
383                 imap_delete_all_cached_messages(item);
384                 begin = first_uid;
385         }
386
387         if (begin > 0 && begin <= last_uid) {
388                 GSList *newlist;
389                 newlist = imap_get_uncached_messages(session, item,
390                                                      begin, last_uid);
391                 mlist = g_slist_concat(mlist, newlist);
392         }
393
394         item->last_num = last_uid;
395
396 catch:
397         statusbar_pop_all();
398         return mlist;
399 }
400
401 #undef THROW
402
403 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
404 {
405         gchar *path, *filename;
406         IMAPSession *session;
407         gint ok;
408
409         g_return_val_if_fail(folder != NULL, NULL);
410         g_return_val_if_fail(item != NULL, NULL);
411
412         path = folder_item_get_path(item);
413         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
414         g_free(path);
415  
416         if (is_file_exist(filename)) {
417                 debug_print(_("message %d has been already cached.\n"), uid);
418                 return filename;
419         }
420
421         session = imap_session_get(folder);
422         if (!session) {
423                 g_free(filename);
424                 return NULL;
425         }
426
427         debug_print(_("getting message %d...\n"), uid);
428         ok = imap_cmd_fetch(SESSION(session)->sock, (guint32)uid, filename);
429
430         statusbar_pop_all();
431
432         if (ok != IMAP_SUCCESS) {
433                 g_warning(_("can't fetch message %d\n"), uid);
434                 g_free(filename);
435                 return NULL;
436         }
437
438         return filename;
439 }
440
441 gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
442                   gboolean remove_source)
443 {
444         IMAPSession *session;
445         gint ok;
446
447         g_return_val_if_fail(folder != NULL, -1);
448         g_return_val_if_fail(dest != NULL, -1);
449         g_return_val_if_fail(file != NULL, -1);
450
451         session = imap_session_get(folder);
452         if (!session)
453                 return -1;
454
455         if (dest->last_num < 0) {
456                 imap_scan_folder(folder, dest);
457                 if (dest->last_num < 0) return -1;
458         }
459
460         ok = imap_cmd_append(SESSION(session)->sock, dest->path, file);
461         if (ok != IMAP_SUCCESS) {
462                 g_warning(_("can't append message %s\n"), file);
463                 return -1;
464         }
465
466         if (remove_source) {
467                 if (unlink(file) < 0)
468                         FILE_OP_ERROR(file, "unlink");
469         }
470
471         return dest->last_num;
472 }
473
474 static gint imap_do_copy(Folder *folder, FolderItem *dest, MsgInfo *msginfo,
475                          gboolean remove_source)
476 {
477         gchar *destdir;
478         IMAPSession *session;
479         IMAPNameSpace *namespace;
480         gint ok;
481
482         g_return_val_if_fail(folder != NULL, -1);
483         g_return_val_if_fail(folder->type == F_IMAP, -1);
484         g_return_val_if_fail(dest != NULL, -1);
485         g_return_val_if_fail(msginfo != NULL, -1);
486
487         session = imap_session_get(folder);
488         if (!session) return -1;
489
490         if (msginfo->folder == dest) {
491                 g_warning(_("the src folder is identical to the dest.\n"));
492                 return -1;
493         }
494
495         Xstrdup_a(destdir, dest->path, return -1);
496         namespace = imap_find_namespace(IMAP_FOLDER(folder), destdir);
497         if (namespace && namespace->separator)
498                 imap_path_separator_subst(destdir, namespace->separator);
499
500         if (remove_source)
501                 debug_print(_("Moving message %s%c%d to %s ...\n"),
502                             msginfo->folder->path, G_DIR_SEPARATOR,
503                             msginfo->msgnum, destdir);
504         else
505                 debug_print(_("Copying message %s%c%d to %s ...\n"),
506                             msginfo->folder->path, G_DIR_SEPARATOR,
507                             msginfo->msgnum, destdir);
508
509         ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum, destdir);
510
511         if (ok == IMAP_SUCCESS && remove_source) {
512                 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
513                                        IMAP_FLAG_DELETED, TRUE);
514                 imap_cmd_expunge(SESSION(session)->sock);
515         }
516
517         statusbar_pop_all();
518         return ok;
519 }
520
521 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
522                                         GSList *msglist,
523                                         gboolean remove_source)
524 {
525         gchar *destdir;
526         GSList *cur;
527         MsgInfo *msginfo;
528         IMAPSession *session;
529         IMAPNameSpace *namespace;
530         gint ok;
531
532         g_return_val_if_fail(folder != NULL, -1);
533         g_return_val_if_fail(dest != NULL, -1);
534         g_return_val_if_fail(msglist != NULL, -1);
535
536         session = imap_session_get(folder);
537         if (!session) return -1;
538
539         Xstrdup_a(destdir, dest->path, return -1);
540         namespace = imap_find_namespace(IMAP_FOLDER(folder), destdir);
541         if (namespace && namespace->separator)
542                 imap_path_separator_subst(destdir, namespace->separator);
543
544         for (cur = msglist; cur != NULL; cur = cur->next) {
545                 msginfo = (MsgInfo *)cur->data;
546
547                 if (msginfo->folder == dest) {
548                         g_warning(_("the src folder is identical to the dest.\n"));
549                         continue;
550                 }
551
552                 if (remove_source)
553                         debug_print(_("Moving message %s%c%d to %s ...\n"),
554                                     msginfo->folder->path, G_DIR_SEPARATOR,
555                                     msginfo->msgnum, destdir);
556                 else
557                         debug_print(_("Copying message %s%c%d to %s ...\n"),
558                                     msginfo->folder->path, G_DIR_SEPARATOR,
559                                     msginfo->msgnum, destdir);
560
561                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
562                                    destdir);
563
564                 if (ok == IMAP_SUCCESS && remove_source) {
565                         imap_set_message_flags
566                                 (session, msginfo->msgnum, msginfo->msgnum,
567                                  IMAP_FLAG_DELETED, TRUE);
568                 }
569         }
570
571         if (remove_source)
572                 imap_cmd_expunge(SESSION(session)->sock);
573
574         statusbar_pop_all();
575         return IMAP_SUCCESS;
576 }
577
578 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
579 {
580         return imap_do_copy(folder, dest, msginfo, TRUE);
581 }
582
583 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
584                               GSList *msglist)
585 {
586         return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
587 }
588
589 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
590 {
591         return imap_do_copy(folder, dest, msginfo, FALSE);
592 }
593
594 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
595                               GSList *msglist)
596 {
597         return imap_do_copy_msgs_with_dest(folder, dest, msglist, FALSE);
598 }
599
600 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
601 {
602         gint exists, recent, unseen;
603         guint32 uid_validity;
604         gint ok;
605         IMAPSession *session;
606
607         g_return_val_if_fail(folder != NULL, -1);
608         g_return_val_if_fail(folder->type == F_IMAP, -1);
609         g_return_val_if_fail(item != NULL, -1);
610
611         session = imap_session_get(folder);
612         if (!session) return -1;
613
614         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
615                          &exists, &recent, &unseen, &uid_validity);
616         statusbar_pop_all();
617         if (ok != IMAP_SUCCESS)
618                 return ok;
619
620         ok = imap_set_message_flags
621                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
622                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
623         statusbar_pop_all();
624         if (ok != IMAP_SUCCESS) {
625                 log_warning(_("can't set deleted flags: %d\n"), uid);
626                 return ok;
627         }
628
629         ok = imap_cmd_expunge(SESSION(session)->sock);
630         statusbar_pop_all();
631         if (ok != IMAP_SUCCESS) {
632                 log_warning(_("can't expunge\n"));
633                 return ok;
634         }
635
636         return IMAP_SUCCESS;
637 }
638
639 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
640 {
641         gint exists, recent, unseen;
642         guint32 uid_validity;
643         gint ok;
644         IMAPSession *session;
645
646         g_return_val_if_fail(folder != NULL, -1);
647         g_return_val_if_fail(item != NULL, -1);
648
649         session = imap_session_get(folder);
650         if (!session) return -1;
651
652         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
653                          &exists, &recent, &unseen, &uid_validity);
654         statusbar_pop_all();
655         if (ok != IMAP_SUCCESS)
656                 return ok;
657         if (exists == 0)
658                 return IMAP_SUCCESS;
659
660         ok = imap_set_message_flags(session, 1, exists,
661                                     IMAP_FLAG_DELETED, TRUE);
662         statusbar_pop_all();
663         if (ok != IMAP_SUCCESS) {
664                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
665                 return ok;
666         }
667
668         ok = imap_cmd_expunge(SESSION(session)->sock);
669         statusbar_pop_all();
670         if (ok != IMAP_SUCCESS) {
671                 log_warning(_("can't expunge\n"));
672                 return ok;
673         }
674
675         return IMAP_SUCCESS;
676 }
677
678 void imap_scan_folder(Folder *folder, FolderItem *item)
679 {
680 }
681
682 gint imap_create_tree(Folder *folder)
683 {
684         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
685         FolderItem *item;
686         FolderItem *new_item;
687         gchar *trash_path;
688
689         g_return_val_if_fail(folder != NULL, -1);
690         g_return_val_if_fail(folder->node != NULL, -1);
691         g_return_val_if_fail(folder->node->data != NULL, -1);
692
693         imap_session_get(folder);
694
695         item = FOLDER_ITEM(folder->node->data);
696
697         new_item = folder_item_new("INBOX", "INBOX");
698         new_item->stype = F_INBOX;
699         folder_item_append(item, new_item);
700         folder->inbox = new_item;
701
702         if (imapfolder->namespace && imapfolder->namespace->data) {
703                 IMAPNameSpace *namespace;
704
705                 namespace = (IMAPNameSpace *)imapfolder->namespace->data;
706                 if (*namespace->name == '\0')
707                         trash_path = g_strdup("trash");
708                 else {
709                         gchar *name;
710
711                         Xstrdup_a(name, namespace->name, return -1);
712                         strtailchomp(name, namespace->separator);
713                         subst_char(name, namespace->separator,
714                                    G_DIR_SEPARATOR);
715                         trash_path = g_strconcat(name, G_DIR_SEPARATOR_S,
716                                                  "trash", NULL);
717                 }
718         } else
719                 trash_path = g_strdup("trash");
720
721         new_item = imap_create_folder(folder, item, trash_path);
722
723         if (!new_item) {
724                 new_item = folder_item_new("Trash", trash_path);
725                 folder_item_append(item, new_item);
726         } else {
727                 g_free(new_item->name);
728                 new_item->name = g_strdup("Trash");
729         }
730         new_item->stype = F_TRASH;
731         folder->trash = new_item;
732
733         g_free(trash_path);
734         return 0;
735 }
736
737 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
738                                const gchar *name)
739 {
740         gchar *dirpath, *imappath;
741         IMAPSession *session;
742         IMAPNameSpace *namespace;
743         FolderItem *new_item;
744         gchar *new_name;
745         gint ok;
746
747         g_return_val_if_fail(folder != NULL, NULL);
748         g_return_val_if_fail(parent != NULL, NULL);
749         g_return_val_if_fail(name != NULL, NULL);
750
751         session = imap_session_get(folder);
752         if (!session) return NULL;
753
754         if (parent->path)
755                 dirpath = g_strconcat(parent->path, G_DIR_SEPARATOR_S, name,
756                                       NULL);
757         else
758                 dirpath = g_strdup(name);
759
760         Xstrdup_a(imappath, dirpath, {g_free(dirpath); return NULL;});
761         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
762         namespace = imap_find_namespace(IMAP_FOLDER(folder), imappath);
763         if (namespace && namespace->separator) {
764                 imap_path_separator_subst(imappath, namespace->separator);
765                 imap_path_separator_subst(new_name, namespace->separator);
766                 strtailchomp(dirpath, '/');
767                 strtailchomp(new_name, namespace->separator);
768         }
769
770         if (strcmp(name, "INBOX") != 0) {
771                 GPtrArray *argbuf;
772                 gint i;
773                 gboolean exist = FALSE;
774
775                 argbuf = g_ptr_array_new();
776                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imappath,
777                                    argbuf);
778                 statusbar_pop_all();
779                 if (ok != IMAP_SUCCESS) {
780                         log_warning(_("can't create mailbox: LIST failed\n"));
781                         g_free(dirpath);
782                         g_ptr_array_free(argbuf, TRUE);
783                         return NULL;
784                 }
785
786                 for (i = 0; i < argbuf->len; i++) {
787                         gchar *str;
788                         str = g_ptr_array_index(argbuf, i);
789                         if (!strncmp(str, "LIST ", 5)) {
790                                 exist = TRUE;
791                                 break;
792                         }
793                 }
794                 g_ptr_array_free(argbuf, TRUE);
795
796                 if (!exist) {
797                         ok = imap_cmd_create(SESSION(session)->sock, imappath);
798                         statusbar_pop_all();
799                         if (ok != IMAP_SUCCESS) {
800                                 log_warning(_("can't create mailbox\n"));
801                                 g_free(dirpath);
802                                 return NULL;
803                         }
804                 }
805         }
806
807         new_item = folder_item_new(new_name, dirpath);
808         folder_item_append(parent, new_item);
809         g_free(dirpath);
810
811         return new_item;
812 }
813
814 gint imap_remove_folder(Folder *folder, FolderItem *item)
815 {
816         gint ok;
817         IMAPSession *session;
818         IMAPNameSpace *namespace;
819         gchar *path;
820
821         g_return_val_if_fail(folder != NULL, -1);
822         g_return_val_if_fail(item != NULL, -1);
823         g_return_val_if_fail(item->path != NULL, -1);
824
825         session = imap_session_get(folder);
826         if (!session) return -1;
827
828         Xstrdup_a(path, item->path, return -1);
829         namespace = imap_find_namespace(IMAP_FOLDER(folder), path);
830         if (namespace && namespace->separator)
831                 imap_path_separator_subst(path, namespace->separator);
832
833         ok = imap_cmd_delete(SESSION(session)->sock, path);
834         statusbar_pop_all();
835         if (ok != IMAP_SUCCESS) {
836                 log_warning(_("can't delete mailbox\n"));
837                 return -1;
838         }
839
840         folder_item_remove(item);
841
842         return 0;
843 }
844
845 static GSList *imap_get_uncached_messages(IMAPSession *session,
846                                           FolderItem *item,
847                                           guint32 first_uid, guint32 last_uid)
848 {
849         gchar buf[IMAPBUFSIZE];
850         GSList *newlist = NULL;
851         GSList *llast = NULL;
852         MsgInfo *msginfo;
853
854         g_return_val_if_fail(session != NULL, NULL);
855         g_return_val_if_fail(item != NULL, NULL);
856         g_return_val_if_fail(item->folder != NULL, NULL);
857         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
858         g_return_val_if_fail(first_uid <= last_uid, NULL);
859
860         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
861             != IMAP_SUCCESS) {
862                 log_warning(_("can't get envelope\n"));
863                 return NULL;
864         }
865
866         for (;;) {
867                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
868                         log_warning(_("error occurred while getting envelope.\n"));
869                         return newlist;
870                 }
871                 strretchomp(buf);
872                 log_print("IMAP4< %s\n", buf);
873                 if (buf[0] != '*' || buf[1] != ' ') break;
874
875                 msginfo = imap_parse_envelope(SESSION(session)->sock, buf);
876                 if (!msginfo) {
877                         log_warning(_("can't parse envelope: %s\n"), buf);
878                         continue;
879                 }
880
881                 msginfo->folder = item;
882
883                 if (!newlist)
884                         llast = newlist = g_slist_append(newlist, msginfo);
885                 else {
886                         llast = g_slist_append(llast, msginfo);
887                         llast = llast->next;
888                 }
889         }
890
891         return newlist;
892 }
893
894 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
895                                            guint32 first_uid, guint32 last_uid)
896 {
897         GSList *cur, *next;
898         MsgInfo *msginfo;
899         gchar *dir;
900
901         g_return_val_if_fail(item != NULL, mlist);
902         g_return_val_if_fail(item->folder != NULL, mlist);
903         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
904
905         debug_print(_("Deleting cached messages %d - %d ... "),
906                     first_uid, last_uid);
907
908         dir = folder_item_get_path(item);
909         remove_numbered_files(dir, first_uid, last_uid);
910         g_free(dir);
911
912         for (cur = mlist; cur != NULL; ) {
913                 next = cur->next;
914
915                 msginfo = (MsgInfo *)cur->data;
916                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
917                     msginfo->msgnum <= last_uid) {
918                         procmsg_msginfo_free(msginfo);
919                         mlist = g_slist_remove(mlist, msginfo);
920                 }
921
922                 cur = next;
923         }
924
925         debug_print(_("done.\n"));
926
927         return mlist;
928 }
929
930 static void imap_delete_all_cached_messages(FolderItem *item)
931 {
932         gchar *dir;
933
934         g_return_if_fail(item != NULL);
935         g_return_if_fail(item->folder != NULL);
936         g_return_if_fail(item->folder->type == F_IMAP);
937
938         debug_print(_("Deleting all cached messages... "));
939
940         dir = folder_item_get_path(item);
941         remove_all_numbered_files(dir);
942         g_free(dir);
943
944         debug_print(_("done.\n"));
945 }
946
947 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf)
948 {
949         SockInfo *sock;
950
951         if ((sock = sock_connect(server, port)) == NULL) {
952                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
953                             server, port);
954                 return NULL;
955         }
956
957         imap_cmd_count = 0;
958
959         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
960                 sock_close(sock);
961                 return NULL;
962         }
963
964         return sock;
965 }
966
967 #define THROW goto catch
968
969 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
970 {
971         gchar *ns_str;
972         gchar *name;
973         gchar *separator;
974         gchar *p;
975         IMAPNameSpace *namespace;
976         GList *ns_list = NULL;
977
978         g_return_if_fail(session != NULL);
979         g_return_if_fail(folder != NULL);
980
981         if (folder->namespace != NULL) return;
982
983         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
984             != IMAP_SUCCESS) {
985                 log_warning(_("can't get namespace\n"));
986                 return;
987         }
988
989         /* get the first element */
990         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
991         g_strstrip(ns_str);
992         p = ns_str;
993
994         while (*p != '\0') {
995                 /* parse ("#foo" "/") */
996
997                 while (*p && *p != '(') p++;
998                 if (*p == '\0') THROW;
999                 p++;
1000
1001                 while (*p && *p != '"') p++;
1002                 if (*p == '\0') THROW;
1003                 p++;
1004                 name = p;
1005
1006                 while (*p && *p != '"') p++;
1007                 if (*p == '\0') THROW;
1008                 *p = '\0';
1009                 p++;
1010
1011                 while (*p && isspace(*p)) p++;
1012                 if (*p == '\0') THROW;
1013                 if (strncmp(p, "NIL", 3) == 0)
1014                         separator = NULL;
1015                 else if (*p == '"') {
1016                         p++;
1017                         separator = p;
1018                         while (*p && *p != '"') p++;
1019                         if (*p == '\0') THROW;
1020                         *p = '\0';
1021                         p++;
1022                 } else THROW;
1023
1024                 while (*p && *p != ')') p++;
1025                 if (*p == '\0') THROW;
1026                 p++;
1027
1028                 namespace = g_new(IMAPNameSpace, 1);
1029                 namespace->name = g_strdup(name);
1030                 namespace->separator = separator ? separator[0] : '\0';
1031                 ns_list = g_list_append(ns_list, namespace);
1032                 IMAP_FOLDER(folder)->namespace = ns_list;
1033         }
1034
1035 catch:
1036         g_free(ns_str);
1037         return;
1038 }
1039
1040 #undef THROW
1041
1042 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1043                                           const gchar *path)
1044 {
1045         IMAPNameSpace *namespace = NULL;
1046         GList *ns_list;
1047         gchar *name;
1048
1049         g_return_val_if_fail(folder != NULL, NULL);
1050         g_return_val_if_fail(path != NULL, NULL);
1051
1052         ns_list = folder->namespace;
1053
1054         for (; ns_list != NULL; ns_list = ns_list->next) {
1055                 IMAPNameSpace *tmp_ns = ns_list->data;
1056
1057                 Xstrdup_a(name, tmp_ns->name, return namespace);
1058                 if (tmp_ns->separator && tmp_ns->separator != '/')
1059                         subst_char(name, tmp_ns->separator, '/');
1060                 if (strncmp(path, name, strlen(name)) == 0)
1061                         namespace = tmp_ns;
1062         }
1063
1064         return namespace;
1065 }
1066
1067 static gchar *imap_parse_atom(SockInfo *sock, gchar *src, gchar *dest,
1068                               gchar *orig_buf)
1069 {
1070         gchar *cur_pos = src;
1071
1072         while (*cur_pos == ' ') cur_pos++;
1073
1074         if (!strncmp(cur_pos, "NIL", 3)) {
1075                 *dest = '\0';
1076                 cur_pos += 3;
1077         } else if (*cur_pos == '\"') {
1078                 gchar *p;
1079
1080                 p = strchr_cpy(cur_pos + 1, '\"', dest, IMAPBUFSIZE);
1081                 cur_pos = p ? p : cur_pos + 2;
1082         } else if (*cur_pos == '{') {
1083                 gchar buf[32];
1084                 gint len;
1085
1086                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1087                 len = atoi(buf);
1088
1089                 g_return_val_if_fail(orig_buf != NULL, cur_pos);
1090
1091                 if (sock_gets(sock, orig_buf, IMAPBUFSIZE) < 0)
1092                         return cur_pos;
1093                 strretchomp(orig_buf);
1094                 log_print("IMAP4< %s\n", orig_buf);
1095                 memcpy(dest, orig_buf, len);
1096                 dest[len] = '\0';
1097                 cur_pos = orig_buf + len;
1098         }
1099
1100         return cur_pos;
1101 }
1102
1103 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1104                                      gchar *out_from_str,
1105                                      gchar *out_fromname_str,
1106                                      gchar *orig_buf)
1107 {
1108         gchar buf[IMAPBUFSIZE];
1109         gchar *userid;
1110         gchar *domain;
1111         gchar *cur_pos = start;
1112
1113         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1114         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1115
1116         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1117
1118         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1119         Xstrdup_a(userid, buf, return cur_pos + 1);
1120
1121         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1122         Xstrdup_a(domain, buf, return cur_pos + 1);
1123
1124         if (out_fromname_str[0] != '\0') {
1125                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1126                            out_fromname_str, userid, domain);
1127         } else {
1128                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1129                            userid, domain);
1130                 strcpy(out_fromname_str, out_from_str);
1131         }
1132
1133         while (*cur_pos == ' ') cur_pos++;
1134
1135         g_return_val_if_fail(*cur_pos == ')', cur_pos + 1);
1136
1137         return cur_pos + 1;
1138 }
1139
1140 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1141                                  gchar **out_from_str,
1142                                  gchar **out_fromname_str,
1143                                  gchar *orig_buf)
1144 {
1145         gchar buf[IMAPBUFSIZE];
1146         gchar name_buf[IMAPBUFSIZE];
1147         gchar *cur_pos = start;
1148         gboolean first = TRUE;
1149
1150         if (out_from_str)     *out_from_str     = NULL;
1151         if (out_fromname_str) *out_fromname_str = NULL;
1152         buf[0] = name_buf[0] = '\0';
1153
1154         if (!strncmp(cur_pos, "NIL", 3)) {
1155                 if (out_from_str)     *out_from_str     = g_strdup("");
1156                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1157                 return cur_pos + 3;
1158         }
1159
1160         g_return_val_if_fail(*cur_pos == '(', NULL);
1161         cur_pos++;
1162
1163         for (;;) {
1164                 gchar ch = *cur_pos++;
1165                 if (ch == ')') break;
1166                 if (ch == '(') {
1167                         if (!first) strcat(buf, ", ");
1168                         first = FALSE;
1169                         cur_pos = imap_parse_one_address
1170                                 (sock, cur_pos, buf, name_buf, orig_buf);
1171                         if (!cur_pos) return NULL;
1172                 }
1173         }
1174
1175         if (out_from_str)     *out_from_str     = g_strdup(buf);
1176         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1177
1178         return cur_pos;
1179 }
1180
1181 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1182 {
1183         const gchar *p = flag_str;
1184         MsgFlags flags;
1185
1186         flags = 0;
1187         MSG_SET_FLAGS(flags, MSG_UNREAD|MSG_IMAP);
1188
1189         while ((p = strchr(p, '\\')) != NULL) {
1190                 p++;
1191
1192                 if (g_strncasecmp(p, "Recent", 6) == 0) {
1193                         MSG_SET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1194                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1195                         MSG_UNSET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1196                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1197                         MSG_SET_FLAGS(flags, MSG_DELETED);
1198                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1199                         MSG_SET_FLAGS(flags, MSG_MARKED);
1200                 }
1201         }
1202
1203         return flags;
1204 }
1205
1206 static MsgInfo *imap_parse_envelope(SockInfo *sock, gchar *line_str)
1207 {
1208         MsgInfo *msginfo;
1209         gchar buf[IMAPBUFSIZE];
1210         gchar tmp[IMAPBUFSIZE];
1211         gchar *cur_pos;
1212         gint msgnum;
1213         guint32 uid = 0;
1214         size_t size = 0;
1215         gchar *date = NULL;
1216         time_t date_t = 0;
1217         gchar *subject = NULL;
1218         gchar *tmp_from;
1219         gchar *tmp_fromname;
1220         gchar *from = NULL;
1221         gchar *fromname = NULL;
1222         gchar *tmp_to;
1223         gchar *to = NULL;
1224         gchar *inreplyto = NULL;
1225         gchar *msgid = NULL;
1226         MsgFlags flags = 0;
1227         gint n_element = 0;
1228
1229         g_return_val_if_fail(line_str != NULL, NULL);
1230         g_return_val_if_fail(line_str[0] == '*' && line_str[1] == ' ', NULL);
1231
1232         cur_pos = line_str + 2;
1233
1234 #define PARSE_ONE_ELEMENT(ch) \
1235 { \
1236         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1237         g_return_val_if_fail(cur_pos != NULL, NULL); \
1238 }
1239
1240         PARSE_ONE_ELEMENT(' ');
1241         msgnum = atoi(buf);
1242
1243         PARSE_ONE_ELEMENT(' ');
1244         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1245
1246         g_return_val_if_fail(*cur_pos == '(', NULL);
1247         cur_pos++;
1248
1249         while (n_element < 4) {
1250                 while (*cur_pos == ' ') cur_pos++;
1251
1252                 if (!strncmp(cur_pos, "UID ", 4)) {
1253                         cur_pos += 4;
1254                         uid = strtoul(cur_pos, &cur_pos, 10);
1255                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
1256                         cur_pos += 6;
1257                         g_return_val_if_fail(*cur_pos == '(', NULL);
1258                         cur_pos++;
1259                         PARSE_ONE_ELEMENT(')');
1260                         flags = imap_parse_flags(buf);
1261                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
1262                         cur_pos += 12;
1263                         size = strtol(cur_pos, &cur_pos, 10);
1264                 } else if (!strncmp(cur_pos, "ENVELOPE ", 9)) {
1265                         cur_pos += 9;
1266                         g_return_val_if_fail(*cur_pos == '(', NULL);
1267                         cur_pos = imap_parse_atom
1268                                 (sock, cur_pos + 1, buf, line_str);
1269                         Xstrdup_a(date, buf, return NULL);
1270                         date_t = procheader_date_parse(NULL, date, 0);
1271
1272                         cur_pos = imap_parse_atom
1273                                 (sock, cur_pos, buf, line_str);
1274                         if (buf[0] != '\0') {
1275                                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1276                                 Xstrdup_a(subject, tmp, return NULL);
1277                         }
1278
1279                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1280                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1281                                                      &tmp_from, &tmp_fromname,
1282                                                      line_str);
1283                         Xstrdup_a(from, tmp_from,
1284                                   {g_free(tmp_from); g_free(tmp_fromname);
1285                                    return NULL;});
1286                         Xstrdup_a(fromname, tmp_fromname,
1287                                   {g_free(tmp_from); g_free(tmp_fromname);
1288                                    return NULL;});
1289                         g_free(tmp_from);
1290                         g_free(tmp_fromname);
1291
1292 #define SKIP_ONE_ELEMENT() \
1293 { \
1294         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1295         cur_pos = imap_parse_address(sock, cur_pos + 1, NULL, NULL, \
1296                                      line_str); \
1297 }
1298
1299                         /* skip sender and reply-to */
1300                         SKIP_ONE_ELEMENT();
1301                         SKIP_ONE_ELEMENT();
1302
1303                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1304                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1305                                                      &tmp_to, NULL, line_str);
1306                         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1307                         g_free(tmp_to);
1308
1309                         /* skip Cc and Bcc */
1310                         SKIP_ONE_ELEMENT();
1311                         SKIP_ONE_ELEMENT();
1312
1313 #undef SKIP_ONE_ELEMENT
1314
1315                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1316                         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1317                         if (buf[0] != '\0') {
1318                                 eliminate_parenthesis(buf, '(', ')');
1319                                 extract_parenthesis(buf, '<', '>');
1320                                 remove_space(buf);
1321                                 Xstrdup_a(inreplyto, buf, return NULL);
1322                         }
1323
1324                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1325                         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1326                         if (buf[0] != '\0') {
1327                                 extract_parenthesis(buf, '<', '>');
1328                                 remove_space(buf);
1329                                 Xstrdup_a(msgid, buf, return NULL);
1330                         }
1331
1332                         g_return_val_if_fail(*cur_pos == ')', NULL);
1333                         cur_pos++;
1334                 } else {
1335                         g_warning("invalid FETCH response: %s\n", cur_pos);
1336                         break;
1337                 }
1338
1339                 if (*cur_pos == '\0' || *cur_pos == ')') break;
1340                 n_element++;
1341         }
1342
1343         msginfo = g_new0(MsgInfo, 1);
1344         msginfo->msgnum = uid;
1345         msginfo->size = size;
1346         msginfo->date = g_strdup(date);
1347         msginfo->date_t = date_t;
1348         msginfo->subject = g_strdup(subject);
1349         msginfo->from = g_strdup(from);
1350         msginfo->fromname = g_strdup(fromname);
1351         msginfo->to = g_strdup(to);
1352         msginfo->inreplyto = g_strdup(inreplyto);
1353         msginfo->msgid = g_strdup(msgid);
1354         msginfo->flags = flags;
1355
1356         return msginfo;
1357 }
1358
1359 static gint imap_set_message_flags(IMAPSession *session,
1360                                    guint32 first_uid,
1361                                    guint32 last_uid,
1362                                    IMAPFlags flags,
1363                                    gboolean is_set)
1364 {
1365         GString *buf;
1366         gint ok;
1367
1368         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1369
1370         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1371         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1372         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1373         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1374         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1375
1376         if (buf->str[buf->len - 1] == ' ')
1377                 g_string_truncate(buf, buf->len - 1);
1378
1379         g_string_append_c(buf, ')');
1380
1381         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
1382                             buf->str);
1383         g_string_free(buf, TRUE);
1384
1385         return ok;
1386 }
1387
1388 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
1389                         const gchar *path,
1390                         gint *exists, gint *recent, gint *unseen,
1391                         guint32 *uid_validity)
1392 {
1393         gchar *real_path;
1394         IMAPNameSpace *namespace;
1395         gint ok;
1396
1397         Xstrdup_a(real_path, path, return -1);
1398         namespace = imap_find_namespace(folder, path);
1399         if (namespace && namespace->separator)
1400                 imap_path_separator_subst(real_path, namespace->separator);
1401
1402         ok = imap_cmd_select(SESSION(session)->sock, real_path,
1403                              exists, recent, unseen, uid_validity);
1404         if (ok != IMAP_SUCCESS)
1405                 log_warning(_("can't select folder: %s\n"), real_path);
1406
1407         return ok;
1408 }
1409
1410 #define THROW(err) { ok = err; goto catch; }
1411
1412 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
1413 {
1414         gint ok;
1415         GPtrArray *argbuf;
1416         gchar *str;
1417         gint num;
1418
1419         *uid = 0;
1420         argbuf = g_ptr_array_new();
1421
1422         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
1423         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
1424                 THROW(ok);
1425
1426         str = search_array_contain_str(argbuf, "FETCH");
1427         if (!str) THROW(IMAP_ERROR);
1428
1429         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
1430             num != msgnum) {
1431                 g_warning("imap_get_uid(): invalid FETCH line.\n");
1432                 THROW(IMAP_ERROR);
1433         }
1434
1435 catch:
1436         ptr_array_free_strings(argbuf);
1437         g_ptr_array_free(argbuf, TRUE);
1438
1439         return ok;
1440 }
1441
1442 #undef THROW
1443
1444 #if 0
1445 static gint imap_status_uidnext(IMAPSession *session, IMAPFolder *folder,
1446                                 const gchar *path, guint32 *uid_next)
1447 {
1448         gchar *real_path;
1449         IMAPNameSpace *namespace;
1450         gint ok;
1451
1452         Xstrdup_a(real_path, path, return -1);
1453         namespace = imap_find_namespace(folder, path);
1454         if (namespace && namespace->separator)
1455                 imap_path_separator_subst(real_path, namespace->separator);
1456
1457         ok = imap_cmd_status(SESSION(session)->sock, real_path,
1458                              "UIDNEXT", uid_next);
1459         if (ok != IMAP_SUCCESS)
1460                 log_warning(_("can't get the next uid of folder: %s\n"),
1461                             real_path);
1462
1463         return ok;
1464 }
1465 #endif
1466
1467
1468 /* low-level IMAP4rev1 commands */
1469
1470 static gint imap_cmd_login(SockInfo *sock,
1471                            const gchar *user, const gchar *pass)
1472 {
1473         gint ok;
1474
1475         if (strchr(user, ' ') != NULL)
1476                 imap_cmd_gen_send(sock, "LOGIN \"%s\" %s", user, pass);
1477         else
1478                 imap_cmd_gen_send(sock, "LOGIN %s %s", user, pass);
1479
1480         ok = imap_cmd_ok(sock, NULL);
1481         if (ok != IMAP_SUCCESS)
1482                 log_warning(_("IMAP4 login failed.\n"));
1483
1484         return ok;
1485 }
1486
1487 static gint imap_cmd_logout(SockInfo *sock)
1488 {
1489         imap_cmd_gen_send(sock, "LOGOUT");
1490         return imap_cmd_ok(sock, NULL);
1491 }
1492
1493 static gint imap_cmd_noop(SockInfo *sock)
1494 {
1495         imap_cmd_gen_send(sock, "NOOP");
1496         return imap_cmd_ok(sock, NULL);
1497 }
1498
1499 #define THROW(err) { ok = err; goto catch; }
1500
1501 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
1502 {
1503         gint ok;
1504         GPtrArray *argbuf;
1505         gchar *str;
1506
1507         argbuf = g_ptr_array_new();
1508
1509         imap_cmd_gen_send(sock, "NAMESPACE");
1510         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
1511
1512         str = search_array_contain_str(argbuf, "NAMESPACE");
1513         if (!str) THROW(IMAP_ERROR);
1514
1515         *ns_str = g_strdup(str);
1516
1517 catch:
1518         ptr_array_free_strings(argbuf);
1519         g_ptr_array_free(argbuf, TRUE);
1520
1521         return ok;
1522 }
1523
1524 #undef THROW
1525
1526 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
1527                           const gchar *mailbox, GPtrArray *argbuf)
1528 {
1529         gchar *new_ref;
1530         gchar *new_mailbox;
1531
1532         if (!ref) ref = "\"\"";
1533         if (!mailbox) mailbox = "\"\"";
1534
1535         if (*ref != '"' && strchr(ref, ' ') != NULL)
1536                 new_ref = g_strdup_printf("\"%s\"", ref);
1537         else
1538                 new_ref = g_strdup(ref);
1539         if (*mailbox != '"' && strchr(mailbox, ' ') != NULL)
1540                 new_mailbox = g_strdup_printf("\"%s\"", mailbox);
1541         else
1542                 new_mailbox = g_strdup(mailbox);
1543
1544         imap_cmd_gen_send(sock, "LIST %s %s", new_ref, new_mailbox);
1545
1546         g_free(new_ref);
1547         g_free(new_mailbox);
1548
1549         return imap_cmd_ok(sock, argbuf);
1550 }
1551
1552 #define THROW goto catch
1553
1554 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
1555                             gint *exists, gint *recent, gint *unseen,
1556                             guint32 *uid_validity)
1557 {
1558         gint ok;
1559         gchar *resp_str;
1560         GPtrArray *argbuf;
1561
1562         *exists = *recent = *unseen = *uid_validity = 0;
1563         argbuf = g_ptr_array_new();
1564
1565         if (strchr(folder, ' ') != NULL)
1566                 imap_cmd_gen_send(sock, "SELECT \"%s\"", folder);
1567         else
1568                 imap_cmd_gen_send(sock, "SELECT %s", folder);
1569
1570         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
1571
1572         resp_str = search_array_contain_str(argbuf, "EXISTS");
1573         if (resp_str) {
1574                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
1575                         g_warning("imap_select(): invalid EXISTS line.\n");
1576                         THROW;
1577                 }
1578         }
1579
1580         resp_str = search_array_contain_str(argbuf, "RECENT");
1581         if (resp_str) {
1582                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
1583                         g_warning("imap_select(): invalid RECENT line.\n");
1584                         THROW;
1585                 }
1586         }
1587
1588         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
1589         if (resp_str) {
1590                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
1591                     != 1) {
1592                         g_warning("imap_select(): invalid UIDVALIDITY line.\n");
1593                         THROW;
1594                 }
1595         }
1596
1597         resp_str = search_array_contain_str(argbuf, "UNSEEN");
1598         if (resp_str) {
1599                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
1600                         g_warning("imap_select(): invalid UNSEEN line.\n");
1601                         THROW;
1602                 }
1603         }
1604
1605 catch:
1606         ptr_array_free_strings(argbuf);
1607         g_ptr_array_free(argbuf, TRUE);
1608
1609         return ok;
1610 }
1611
1612 #if 0
1613 static gint imap_cmd_status(SockInfo *sock, const gchar *folder,
1614                             const gchar *status, gint *value)
1615 {
1616         gint ok;
1617         GPtrArray *argbuf;
1618         gchar *str;
1619
1620         if (value) *value = 0;
1621         argbuf = g_ptr_array_new();
1622
1623         if (strchr(folder, ' ') != NULL)
1624                 imap_cmd_gen_send(sock, "STATUS \"%s\" (%s)", folder, status);
1625         else
1626                 imap_cmd_gen_send(sock, "STATUS %s (%s)", folder, status);
1627
1628         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
1629
1630         str = search_array_contain_str(argbuf, "STATUS");
1631         if (!str) THROW;
1632         str = strchr(str, '(');
1633         if (!str) THROW;
1634         str++;
1635         if (strncmp(str, status, strlen(status)) != 0) THROW;
1636         str += strlen(status);
1637         if (*str != ' ') THROW;
1638         str++;
1639         if (value) *value = atoi(str);
1640
1641 catch:
1642         ptr_array_free_strings(argbuf);
1643         g_ptr_array_free(argbuf, TRUE);
1644
1645         return ok;
1646 }
1647 #endif
1648
1649 #undef THROW
1650
1651 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
1652 {
1653         if (strchr(folder, ' ') != NULL)
1654                 imap_cmd_gen_send(sock, "CREATE \"%s\"", folder);
1655         else
1656                 imap_cmd_gen_send(sock, "CREATE %s", folder);
1657
1658         return imap_cmd_ok(sock, NULL);
1659 }
1660
1661 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
1662 {
1663         if (strchr(folder, ' ') != NULL)
1664                 imap_cmd_gen_send(sock, "DELETE \"%s\"", folder);
1665         else
1666                 imap_cmd_gen_send(sock, "DELETE %s", folder);
1667
1668         return imap_cmd_ok(sock, NULL);
1669 }
1670
1671 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
1672 {
1673         gint ok;
1674         gchar buf[IMAPBUFSIZE];
1675         gchar *cur_pos;
1676         gchar size_str[32];
1677         glong size_num;
1678
1679         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
1680
1681         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
1682
1683         if (sock_gets(sock, buf, sizeof(buf)) < 0)
1684                 return IMAP_ERROR;
1685         strretchomp(buf);
1686         if (buf[0] != '*' || buf[1] != ' ')
1687                 return IMAP_ERROR;
1688         log_print("IMAP4< %s\n", buf);
1689
1690         cur_pos = strchr(buf, '{');
1691         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
1692         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
1693         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
1694         size_num = atol(size_str);
1695
1696         if (*cur_pos != '\0') return IMAP_ERROR;
1697
1698         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
1699                 return IMAP_ERROR;
1700
1701         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
1702                 return IMAP_ERROR;
1703
1704         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
1705                 return IMAP_ERROR;
1706
1707         ok = imap_cmd_ok(sock, NULL);
1708
1709         return ok;
1710 }
1711
1712 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
1713                             const gchar *file)
1714 {
1715         gint ok;
1716         gint size;
1717
1718         g_return_val_if_fail(file != NULL, IMAP_ERROR);
1719
1720         size = get_file_size(file);
1721         imap_cmd_gen_send(sock, "APPEND %s {%d}", destfolder, size);
1722         ok = imap_cmd_ok(sock, NULL);
1723         if (ok != IMAP_SUCCESS) {
1724                 log_warning(_("can't append %s to %s\n"), file, destfolder);
1725                 return -1;
1726         }
1727
1728         return ok;
1729 }
1730
1731 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
1732 {
1733         gint ok;
1734
1735         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
1736
1737         if (strchr(destfolder, ' ') != NULL)
1738                 imap_cmd_gen_send(sock, "UID COPY %d \"%s\"", uid, destfolder);
1739         else
1740                 imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder);
1741
1742         ok = imap_cmd_ok(sock, NULL);
1743         if (ok != IMAP_SUCCESS) {
1744                 log_warning(_("can't copy %d to %s\n"), uid, destfolder);
1745                 return -1;
1746         }
1747
1748         return ok;
1749 }
1750
1751 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
1752 {
1753         imap_cmd_gen_send
1754                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
1755                  first_uid, last_uid);
1756
1757         return IMAP_SUCCESS;
1758 }
1759
1760 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
1761                            gchar *sub_cmd)
1762 {
1763         gint ok;
1764
1765         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
1766                           first_uid, last_uid, sub_cmd);
1767
1768         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
1769                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
1770                             first_uid, last_uid, sub_cmd);
1771                 return ok;
1772         }
1773
1774         return IMAP_SUCCESS;
1775 }
1776
1777 static gint imap_cmd_expunge(SockInfo *sock)
1778 {
1779         gint ok;
1780
1781         imap_cmd_gen_send(sock, "EXPUNGE");
1782         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
1783                 log_warning(_("error while imap command: EXPUNGE\n"));
1784                 return ok;
1785         }
1786
1787         return IMAP_SUCCESS;
1788 }
1789
1790 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
1791 {
1792         gint ok;
1793         gchar buf[IMAPBUFSIZE];
1794         gint cmd_num;
1795         gchar cmd_status[IMAPBUFSIZE];
1796
1797         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
1798                == IMAP_SUCCESS) {
1799                 if (buf[0] == '*' && buf[1] == ' ') {
1800                         if (argbuf)
1801                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
1802                         continue;
1803                 }
1804
1805                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
1806                         return IMAP_ERROR;
1807                 else if (cmd_num == imap_cmd_count &&
1808                          !strcmp(cmd_status, "OK")) {
1809                         if (argbuf)
1810                                 g_ptr_array_add(argbuf, g_strdup(buf));
1811                         return IMAP_SUCCESS;
1812                 } else
1813                         return IMAP_ERROR;
1814         }
1815
1816         return ok;
1817 }
1818
1819 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
1820 {
1821         gchar buf[IMAPBUFSIZE];
1822         gchar tmp[IMAPBUFSIZE];
1823         gchar *p;
1824         va_list args;
1825
1826         va_start(args, format);
1827         g_vsnprintf(tmp, sizeof(tmp), format, args);
1828         va_end(args);
1829
1830         imap_cmd_count++;
1831
1832         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
1833         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
1834                 *p = '\0';
1835                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
1836         } else
1837                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
1838
1839         sock_write(sock, buf, strlen(buf));
1840 }
1841
1842 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
1843 {
1844         if (sock_gets(sock, buf, size) == -1)
1845                 return IMAP_SOCKET;
1846
1847         strretchomp(buf);
1848
1849         log_print("IMAP4< %s\n", buf);
1850
1851         return IMAP_SUCCESS;
1852 }
1853
1854
1855 /* misc utility functions */
1856
1857 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
1858 {
1859         gchar *tmp;
1860
1861         dest[0] = '\0';
1862         tmp = strchr(src, ch);
1863         if (!tmp)
1864                 return NULL;
1865
1866         memcpy(dest, src, MIN(tmp - src, len - 1));
1867         dest[MIN(tmp - src, len - 1)] = '\0';
1868
1869         return tmp + 1;
1870 }
1871
1872 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
1873 {
1874         gint i;
1875
1876         for (i = 0; i < array->len; i++) {
1877                 gchar *tmp;
1878
1879                 tmp = g_ptr_array_index(array, i);
1880                 if (strstr(tmp, str) != NULL)
1881                         return tmp;
1882         }
1883
1884         return NULL;
1885 }
1886
1887 static void imap_path_separator_subst(gchar *str, gchar separator)
1888 {
1889         if (separator && separator != '/')
1890                 subst_char(str, '/', separator);
1891 }