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