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