Return Receipt
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999,2000 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
31 #include "intl.h"
32 #include "imap.h"
33 #include "socket.h"
34 #include "recv.h"
35 #include "procmsg.h"
36 #include "procheader.h"
37 #include "folder.h"
38 #include "statusbar.h"
39 #include "prefs_account.h"
40 #include "codeconv.h"
41 #include "utils.h"
42
43 static GList *session_list = NULL;
44
45 static gint imap_cmd_count = 0;
46
47 static GSList *imap_get_uncached_messages(IMAPSession   *session,
48                                           FolderItem    *item,
49                                           gint          first,
50                                           gint          last);
51 static GSList *imap_delete_messages      (GSList        *mlist,
52                                           gint          first,
53                                           gint          last);
54 static void imap_delete_all_messages     (FolderItem    *item);
55
56 static SockInfo *imap_open      (const gchar    *server,
57                                  gushort         port,
58                                  gchar          *buf);
59 static gint imap_auth           (SockInfo       *sock,
60                                  const gchar    *user,
61                                  const gchar    *pass);
62 static gint imap_logout         (SockInfo       *sock);
63 static gint imap_noop           (SockInfo       *sock);
64 static gint imap_select         (SockInfo       *sock,
65                                  const gchar    *folder,
66                                  gint           *exists,
67                                  gint           *recent,
68                                  gint           *unseen,
69                                  gulong         *uid);
70 static gint imap_create         (SockInfo       *sock,
71                                  const gchar    *folder);
72 static gint imap_delete         (SockInfo       *sock,
73                                  const gchar    *folder);
74 static gint imap_get_envelope   (SockInfo       *sock,
75                                  gint            first,
76                                  gint            last);
77 #if 0
78 static gint imap_search         (SockInfo       *sock,
79                                  GSList         *numlist);
80 #endif
81 static gint imap_get_message    (SockInfo       *sock,
82                                  gint            num,
83                                  const gchar    *filename);
84 static gint imap_copy_message   (SockInfo       *sock,
85                                  gint            num,
86                                  const gchar    *destfolder);
87 static gint imap_store          (SockInfo       *sock,
88                                  gint            first,
89                                  gint            last,
90                                  gchar          *sub_cmd);
91
92 static gint imap_set_article_flags      (IMAPSession    *session,
93                                          gint            first,
94                                          gint            last,
95                                          IMAPFlags       flag,
96                                          gboolean        is_set);
97 static gint imap_expunge                (IMAPSession    *session);
98
99 static gchar *imap_parse_atom           (SockInfo *sock,
100                                          gchar    *src,
101                                          gchar    *dest,
102                                          gchar    *orig_buf);
103 static gchar *imap_parse_one_address    (SockInfo *sock,
104                                          gchar    *start,
105                                          gchar    *out_from_str,
106                                          gchar    *out_fromname_str,
107                                          gchar    *orig_buf);
108 static gchar *imap_parse_address        (SockInfo *sock,
109                                          gchar    *start,
110                                          gchar   **out_from_str,
111                                          gchar   **out_fromname_str,
112                                          gchar    *orig_buf);
113 static MsgFlags imap_parse_flags        (const gchar    *flag_str);
114 static MsgInfo *imap_parse_envelope     (SockInfo *sock,
115                                          gchar    *line_str);
116
117 static gint imap_ok             (SockInfo       *sock,
118                                  GPtrArray      *argbuf);
119 static void imap_gen_send       (SockInfo       *sock,
120                                  const gchar    *format, ...);
121 static gint imap_gen_recv       (SockInfo       *sock,
122                                  gchar          *buf,
123                                  gint            size);
124
125 static gchar *search_array_contain_str  (GPtrArray      *array,
126                                          gchar          *str);
127 static void imap_path_subst_slash_to_dot(gchar *str);
128
129
130 static IMAPSession *imap_session_connect_if_not(Folder *folder)
131 {
132         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
133
134         g_return_val_if_fail(folder != NULL, NULL);
135         g_return_val_if_fail(folder->type == F_IMAP, NULL);
136         g_return_val_if_fail(folder->account != NULL, NULL);
137
138         if (!rfolder->session) {
139                 rfolder->session =
140                         imap_session_new(folder->account->recv_server, 143,
141                                          folder->account->userid,
142                                          folder->account->passwd);
143         } else {
144                 if (imap_noop(rfolder->session->sock) != IMAP_SUCCESS) {
145                         log_warning(_("IMAP4 connection to %s:%d has been"
146                                       " disconnected. Reconnecting...\n"),
147                                     folder->account->recv_server, 143);
148                         session_destroy(rfolder->session);
149                         rfolder->session =
150                                 imap_session_new(folder->account->recv_server,
151                                                  143, folder->account->userid,
152                                                  folder->account->passwd);
153                 }
154         }
155
156         return IMAP_SESSION(rfolder->session);
157 }
158
159 Session *imap_session_new(const gchar *server, gushort port,
160                           const gchar *user, const gchar *pass)
161 {
162         gchar buf[IMAPBUFSIZE];
163         IMAPSession *session;
164         SockInfo *imap_sock;
165
166         g_return_val_if_fail(server != NULL, NULL);
167
168         log_message(_("creating IMAP4 connection to %s:%d ...\n"),
169                     server, port);
170
171         if ((imap_sock = imap_open(server, port, buf)) == NULL)
172                 return NULL;
173         if (imap_auth(imap_sock, user, pass) != IMAP_SUCCESS) {
174                 imap_logout(imap_sock);
175                 sock_close(imap_sock);
176                 return NULL;
177         }
178
179         session = g_new(IMAPSession, 1);
180         SESSION(session)->type      = SESSION_IMAP;
181         SESSION(session)->server    = g_strdup(server);
182         SESSION(session)->sock      = imap_sock;
183         SESSION(session)->connected = TRUE;
184         SESSION(session)->phase     = SESSION_READY;
185         SESSION(session)->data      = NULL;
186         session->mbox = NULL;
187
188         session_list = g_list_append(session_list, session);
189
190         return SESSION(session);
191 }
192
193 void imap_session_destroy(IMAPSession *session)
194 {
195         sock_close(SESSION(session)->sock);
196         SESSION(session)->sock = NULL;
197
198         g_free(session->mbox);
199
200         session_list = g_list_remove(session_list, session);
201 }
202
203 void imap_session_destroy_all(void)
204 {
205         while (session_list != NULL) {
206                 IMAPSession *session = (IMAPSession *)session_list->data;
207
208                 imap_logout(SESSION(session)->sock);
209                 imap_session_destroy(session);
210         }
211 }
212
213 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
214 {
215         GSList *mlist = NULL;
216         IMAPSession *session;
217
218         g_return_val_if_fail(folder != NULL, NULL);
219         g_return_val_if_fail(item != NULL, NULL);
220         g_return_val_if_fail(folder->type == F_IMAP, NULL);
221         g_return_val_if_fail(folder->account != NULL, NULL);
222
223         session = imap_session_connect_if_not(folder);
224
225         if (!session) {
226                 mlist = procmsg_read_cache(item, FALSE);
227                 item->last_num = procmsg_get_last_num_in_cache(mlist);
228                 procmsg_set_flags(mlist, item);
229         } else {
230                 gint ok, exists = 0, recent = 0, unseen = 0, begin = 1;
231                 gulong uid = 0, last_uid = item->mtime;
232
233                 ok = imap_select(SESSION(session)->sock, item->path,
234                                         &exists, &recent, &unseen, &uid);
235                 if (ok != IMAP_SUCCESS) {
236                         log_warning(_("can't select folder: %s\n"), item->path);
237                         return NULL;
238                 }
239
240                 if (use_cache) {
241                         gint cache_last;
242
243                         mlist = procmsg_read_cache(item, FALSE);
244                         procmsg_set_flags(mlist, item);
245                         cache_last = procmsg_get_last_num_in_cache(mlist);
246
247                         /* calculating the range of envelope to get */
248                         if (exists < cache_last) {
249                                 /* some messages are deleted (get all) */
250                                 begin = 1;
251                         } else if (exists == cache_last) {
252                                 if (last_uid != 0 && last_uid != uid) {
253                                         /* some recent but deleted (get all) */
254                                         begin = 1;
255                                 } else {
256                                         /* mailbox unchanged (get none)*/
257                                         begin = -1;
258                                 }
259                         } else {
260                                 if (exists == cache_last + recent) {
261                                         /* some recent */
262                                         begin = cache_last + 1;
263                                 } else {
264                                         /* some recent but deleted (get all) */
265                                         begin = 1;
266                                 }
267                         }
268
269                         item->mtime = uid;
270                 }
271
272                 if (1 < begin && begin <= exists) {
273                         GSList *newlist;
274
275                         newlist = imap_get_uncached_messages
276                                 (session, item, begin, exists);
277                         imap_delete_messages(mlist, begin, INT_MAX);
278                         mlist = g_slist_concat(mlist, newlist);
279                 } else if (begin == 1) {
280                         mlist = imap_get_uncached_messages 
281                                         (session, item, 1, exists);
282                         imap_delete_all_messages(item);
283                 }
284
285                 item->last_num = exists;
286         }
287
288         statusbar_pop_all();
289
290         return mlist;
291 }
292
293 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint num)
294 {
295         gchar *path, *filename;
296         IMAPSession *session;
297         gint ok;
298
299         g_return_val_if_fail(folder != NULL, NULL);
300         g_return_val_if_fail(item != NULL, NULL);
301
302         session = imap_session_connect_if_not(folder);
303
304         path = folder_item_get_path(item);
305         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
306         g_free(path);
307  
308         if (is_file_exist(filename)) {
309                 debug_print(_("message %d has been already cached.\n"), num);
310                 return filename;
311         }
312
313         if (!session) {
314                 g_free(filename);
315                 return NULL;
316         }
317
318         debug_print(_("getting message %d...\n"), num);
319         ok = imap_get_message(SESSION(session)->sock, num, filename);
320
321         statusbar_pop_all();
322
323         if (ok != IMAP_SUCCESS) {
324                 g_warning(_("can't fetch message %d\n"), num);
325                 g_free(filename);
326                 return NULL;
327         }
328
329         return filename;
330 }
331
332 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
333 {
334         gchar *destdir;
335         IMAPSession *session;
336
337         g_return_val_if_fail(folder != NULL, -1);
338         g_return_val_if_fail(dest != NULL, -1);
339         g_return_val_if_fail(msginfo != NULL, -1);
340
341         session = imap_session_connect_if_not(folder);
342         if (!session) return -1;
343
344         if (msginfo->folder == dest) {
345                 g_warning(_("the src folder is identical to the dest.\n"));
346                 return -1;
347         }
348
349         Xstrdup_a(destdir, dest->path, return -1);
350         /* imap_path_subst_slash_to_dot(destdir); */
351
352         imap_copy_message(SESSION(session)->sock, msginfo->msgnum, destdir);
353         imap_set_article_flags(session, msginfo->msgnum, msginfo->msgnum,
354                                IMAP_FLAG_DELETED, TRUE);
355         debug_print(_("Moving message %s%c%d to %s ...\n"),
356                     msginfo->folder->path, G_DIR_SEPARATOR,
357                     msginfo->msgnum, dest->path);
358
359         imap_expunge(session);
360
361         return IMAP_SUCCESS;
362 }
363
364 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
365                               GSList *msglist)
366 {
367         gchar *destdir;
368         GSList *cur;
369         MsgInfo *msginfo;
370         IMAPSession *session;
371
372         g_return_val_if_fail(folder != NULL, -1);
373         g_return_val_if_fail(dest != NULL, -1);
374         g_return_val_if_fail(msglist != NULL, -1);
375
376         session = imap_session_connect_if_not(folder);
377         if (!session) return -1;
378
379         Xstrdup_a(destdir, dest->path, return -1);
380         /* imap_path_subst_slash_to_dot(destdir); */
381
382         for (cur = msglist; cur != NULL; cur = cur->next) {
383                 msginfo = (MsgInfo *)cur->data;
384
385                 if (msginfo->folder == dest) {
386                         g_warning(_("the src folder is identical to the dest.\n"));
387                         continue;
388                 }
389                 imap_copy_message(SESSION(session)->sock,
390                                   msginfo->msgnum, destdir);
391                 imap_set_article_flags
392                         (session, msginfo->msgnum, msginfo->msgnum,
393                          IMAP_FLAG_DELETED, TRUE);
394
395                 debug_print(_("Moving message %s%c%d to %s ...\n"),
396                             msginfo->folder->path, G_DIR_SEPARATOR,
397                             msginfo->msgnum, dest->path);
398                 
399         }
400
401         imap_expunge(session);
402
403         return IMAP_SUCCESS;
404
405 }
406
407 gint imap_remove_msg(Folder *folder, FolderItem *item, gint num)
408 {
409         gint exists, recent, unseen;
410         gulong uid;
411         gint ok;
412         IMAPSession *session;
413
414         g_return_val_if_fail(folder != NULL, -1);
415         g_return_val_if_fail(item != NULL, -1);
416         g_return_val_if_fail(num > 0 && num <= item->last_num, -1);
417
418         session = imap_session_connect_if_not(folder);
419         if (!session) return -1;
420
421         ok = imap_select(SESSION(session)->sock, item->path,
422                          &exists, &recent, &unseen, &uid);
423         if (ok != IMAP_SUCCESS) {
424                 log_warning(_("can't select folder: %s\n"), item->path);
425                 return ok;
426         }
427
428         ok = imap_set_article_flags(IMAP_SESSION(REMOTE_FOLDER(folder)->session),
429                                     num, num, IMAP_FLAG_DELETED, TRUE);
430         if (ok != IMAP_SUCCESS) {
431                 log_warning(_("can't set deleted flags: %d\n"), num);
432                 return ok;
433         }
434
435         ok = imap_expunge(session);
436         if (ok != IMAP_SUCCESS) {
437                 log_warning(_("can't expunge\n"));
438                 return ok;
439         }
440
441         return IMAP_SUCCESS;
442 }
443
444 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
445 {
446         gint exists, recent, unseen;
447         gulong uid;
448         gint ok;
449         IMAPSession *session;
450
451         g_return_val_if_fail(folder != NULL, -1);
452         g_return_val_if_fail(item != NULL, -1);
453
454         session = imap_session_connect_if_not(folder);
455         if (!session) return -1;
456
457         ok = imap_select(SESSION(session)->sock, item->path,
458                          &exists, &recent, &unseen, &uid);
459         if (ok != IMAP_SUCCESS) {
460                 log_warning(_("can't select folder: %s\n"), item->path);
461                 return ok;
462         }
463
464         ok = imap_set_article_flags(session, 1, exists,
465                                     IMAP_FLAG_DELETED, TRUE);
466         if (ok != IMAP_SUCCESS) {
467                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
468                 return ok;
469         }
470
471         ok = imap_expunge(session);
472         if (ok != IMAP_SUCCESS) {
473                 log_warning(_("can't expunge\n"));
474                 return ok;
475         }
476
477         return IMAP_SUCCESS;
478 }
479
480 void imap_scan_folder(Folder *folder, FolderItem *item)
481 {
482 }
483
484 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
485                                const gchar *name)
486 {
487         gint ok;
488         gchar *dirpath, *imappath;
489         IMAPSession *session;
490         FolderItem *new_item;
491
492         g_return_val_if_fail(folder != NULL, NULL);
493         g_return_val_if_fail(parent != NULL, NULL);
494         g_return_val_if_fail(name != NULL, NULL);
495
496         session = imap_session_connect_if_not(folder);
497         if (!session) return NULL;
498
499         if (parent->path)
500                 dirpath = g_strconcat(parent->path, G_DIR_SEPARATOR_S, name,
501                                       NULL);
502         else
503                 dirpath = g_strdup(name);
504
505         imappath = g_strdup(dirpath);
506         /* imap_path_subst_slash_to_dot(imappath); */
507
508         ok = imap_create(SESSION(session)->sock, imappath);
509         if (ok != IMAP_SUCCESS) {
510                 log_warning(_("can't create mailbox\n"));
511                 g_free(imappath);
512                 g_free(dirpath);
513                 return NULL;
514         }
515
516         new_item = folder_item_new(name, dirpath);
517         folder_item_append(parent, new_item);
518         g_free(imappath);
519         g_free(dirpath);
520
521         return new_item;
522 }
523
524 gint imap_remove_folder(Folder *folder, FolderItem *item)
525 {
526         gint ok;
527         IMAPSession *session;
528
529         g_return_val_if_fail(folder != NULL, -1);
530         g_return_val_if_fail(item != NULL, -1);
531         g_return_val_if_fail(item->path != NULL, -1);
532
533         session = imap_session_connect_if_not(folder);
534         if (!session) return -1;
535
536         ok = imap_delete(SESSION(session)->sock, item->path);
537         if (ok != IMAP_SUCCESS) {
538                 log_warning(_("can't delete mailbox\n"));
539                 return -1;
540         }
541
542         folder_item_remove(item);
543
544         return 0;
545 }
546
547 static GSList *imap_get_uncached_messages(IMAPSession *session,
548                                           FolderItem *item,
549                                           gint first, gint last)
550 {
551         gchar buf[IMAPBUFSIZE];
552         GSList *newlist = NULL;
553         GSList *llast = NULL;
554         MsgInfo *msginfo;
555
556         g_return_val_if_fail(session != NULL, NULL);
557         g_return_val_if_fail(item != NULL, NULL);
558         g_return_val_if_fail(item->folder != NULL, NULL);
559         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
560         g_return_val_if_fail(first <= last, NULL);
561
562         if (imap_get_envelope(SESSION(session)->sock, first, last)
563             != IMAP_SUCCESS) {
564                 log_warning(_("can't get envelope\n"));
565                 return NULL;
566         }
567
568         for (;;) {
569                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
570                         log_warning(_("error occurred while getting envelope.\n"));
571                         return newlist;
572                 }
573                 strretchomp(buf);
574                 if (buf[0] != '*' || buf[1] != ' ') break;
575
576                 msginfo = imap_parse_envelope(SESSION(session)->sock, buf);
577                 if (!msginfo) {
578                         log_warning(_("can't parse envelope: %s\n"), buf);
579                         continue;
580                 }
581
582                 msginfo->folder = item;
583
584                 if (!newlist)
585                         llast = newlist = g_slist_append(newlist, msginfo);
586                 else {
587                         llast = g_slist_append(llast, msginfo);
588                         llast = llast->next;
589                 }
590         }
591
592         return newlist;
593 }
594
595 static GSList *imap_delete_messages(GSList *mlist, gint first, gint last)
596 {
597         GSList *cur, *next;
598         MsgInfo *msginfo;
599         gchar *cache_file;
600
601         for (cur = mlist; cur != NULL; ) {
602                 next = cur->next;
603
604                 msginfo = (MsgInfo *)cur->data;
605                 if ((msginfo) && 
606                     (first <= msginfo->msgnum ) &&
607                     (msginfo->msgnum <= last)) {
608                         debug_print(_("deleting message %d...\n"),
609                                     msginfo->msgnum);
610
611                         cache_file = procmsg_get_message_file_path(msginfo);
612                         if (is_file_exist(cache_file)) unlink(cache_file);
613                         g_free(cache_file);
614
615                         procmsg_msginfo_free(msginfo);
616                         mlist = g_slist_remove(mlist, msginfo);
617                 }
618
619                 cur = next;
620         }
621
622         return mlist;
623 }
624
625 static void imap_delete_all_messages(FolderItem *item)
626 {
627         DIR *dp;
628         struct dirent *d;
629         gchar *dir;
630         gchar *file;
631
632         g_return_if_fail(item != NULL);
633         g_return_if_fail(item->folder != NULL);
634         g_return_if_fail(item->folder->type == F_IMAP);
635
636         dir = folder_item_get_path(item);
637         if ((dp = opendir(dir)) == NULL) {
638                 FILE_OP_ERROR(dir, "opendir");
639                 g_free(dir);
640                 return;
641         }
642
643         debug_print(_("\tDeleting all cached messages... "));
644
645         while ((d = readdir(dp)) != NULL) {
646                 if (to_number(d->d_name) < 0) continue;
647
648                 file = g_strconcat(dir, G_DIR_SEPARATOR_S, d->d_name, NULL);
649
650                 if (is_file_exist(file)) {
651                         if (unlink(file) < 0)
652                                 FILE_OP_ERROR(file, "unlink");
653                 }
654
655                 g_free(file);
656         }
657
658         closedir(dp);
659         g_free(dir);
660
661         debug_print(_("done.\n"));
662 }
663
664
665 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf)
666 {
667         SockInfo *sock;
668
669         if ((sock = sock_connect(server, port)) == NULL) {
670                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
671                             server, port);
672                 return NULL;
673         }
674
675         imap_cmd_count = 0;
676
677         if (imap_noop(sock) != IMAP_SUCCESS) {
678                 sock_close(sock);
679                 return NULL;
680         }
681
682         return sock;
683 }
684
685 static gint imap_auth(SockInfo *sock, const gchar *user, const gchar *pass)
686 {
687         gint ok;
688         GPtrArray *argbuf;
689
690         imap_gen_send(sock, "LOGIN \"%s\" %s", user, pass);
691         argbuf = g_ptr_array_new();
692         ok = imap_ok(sock, argbuf);
693         if (ok != IMAP_SUCCESS) log_warning(_("IMAP4 login failed.\n"));
694         ptr_array_free_strings(argbuf);
695         g_ptr_array_free(argbuf, TRUE);
696
697         return ok;
698 }
699
700 static gint imap_logout(SockInfo *sock)
701 {
702         imap_gen_send(sock, "LOGOUT");
703         return imap_ok(sock, NULL);
704 }
705
706 static gint imap_noop(SockInfo *sock)
707 {
708         imap_gen_send(sock, "NOOP");
709         return imap_ok(sock, NULL);
710 }
711
712 static gint imap_select(SockInfo *sock, const gchar *folder,
713                         gint *exists, gint *recent, gint *unseen, gulong *uid)
714 {
715         gint ok;
716         gchar *resp_str;
717         GPtrArray *argbuf;
718         gchar *imappath;
719
720         *exists = *recent = *unseen = *uid = 0;
721         argbuf = g_ptr_array_new();
722
723         Xstrdup_a(imappath, folder, return -1);
724         /* imap_path_subst_slash_to_dot(imappath); */
725
726         imap_gen_send(sock, "SELECT \"%s\"", imappath);
727         if ((ok = imap_ok(sock, argbuf)) != IMAP_SUCCESS)
728                 goto bail;
729
730         resp_str = search_array_contain_str(argbuf, "EXISTS");
731         if (resp_str) {
732                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
733                         g_warning("imap_select(): invalid EXISTS line.\n");
734                         goto bail;
735                 }
736         }
737
738         resp_str = search_array_contain_str(argbuf, "RECENT");
739         if (resp_str) {
740                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
741                         g_warning("imap_select(): invalid RECENT line.\n");
742                         goto bail;
743                 }
744         }
745
746         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
747         if (resp_str) {
748                 if (sscanf(resp_str, "OK [UIDVALIDITY %lu] ", uid) != 1) {
749                         g_warning("imap_select(): invalid UIDVALIDITY line.\n");
750                         goto bail;
751                 }
752         }
753
754         resp_str = search_array_contain_str(argbuf, "UNSEEN");
755         if (resp_str) {
756                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
757                         g_warning("imap_select(): invalid UNSEEN line.\n");
758                         goto bail;
759                 }
760         }
761
762 bail:
763         ptr_array_free_strings(argbuf);
764         g_ptr_array_free(argbuf, TRUE);
765
766         return ok;
767 }
768
769 static gint imap_create(SockInfo *sock, const gchar *folder)
770 {
771         imap_gen_send(sock, "CREATE \"%s\"", folder);
772         return imap_ok(sock, NULL);
773 }
774
775 static gint imap_delete(SockInfo *sock, const gchar *folder)
776 {
777         imap_gen_send(sock, "DELETE \"%s\"", folder);
778         return imap_ok(sock, NULL);
779 }
780
781 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
782 {
783         gchar *tmp;
784
785         dest[0] = '\0';
786         tmp = strchr(src, ch);
787         if (!tmp || tmp == src)
788                 return NULL;
789
790         memcpy(dest, src, MIN(tmp - src, len - 1));
791         dest[MIN(tmp - src, len - 1)] = '\0';
792
793         return tmp + 1;
794 }
795
796 static gint imap_get_message(SockInfo *sock, gint num, const gchar *filename)
797 {
798         gint ok;
799         gchar buf[IMAPBUFSIZE];
800         gchar *cur_pos;
801         gchar size_str[32];
802         glong size_num;
803
804         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
805
806         imap_gen_send(sock, "FETCH %d BODY[]", num);
807
808         if (sock_gets(sock, buf, sizeof(buf)) < 0)
809                 return IMAP_ERROR;
810         strretchomp(buf);
811         if (buf[0] != '*' || buf[1] != ' ')
812                 return IMAP_ERROR;
813         log_print("IMAP4< %s\n", buf);
814
815         cur_pos = strchr(buf, '{');
816         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
817         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
818         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
819         size_num = atol(size_str);
820
821         if (*cur_pos != '\0') return IMAP_ERROR;
822
823         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
824                 return IMAP_ERROR;
825
826         if (imap_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
827                 return IMAP_ERROR;
828
829         if (buf[0] != ')')
830                 return IMAP_ERROR;
831
832         ok = imap_ok(sock, NULL);
833
834         return ok;
835 }
836
837 static gint imap_copy_message(SockInfo *sock, gint num, const gchar *destfolder)
838 {
839         gint ok;
840
841         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
842
843         imap_gen_send(sock, "COPY %d %s", num, destfolder);
844         ok = imap_ok(sock, NULL);
845         if (ok != IMAP_SUCCESS) {
846                 log_warning(_("can't copy %d to %s\n"), num, destfolder);
847                 return -1;
848         }
849
850         return ok;
851 }
852
853 static gchar *imap_parse_atom(SockInfo *sock, gchar *src, gchar *dest,
854                               gchar *orig_buf)
855 {
856         gchar *cur_pos = src;
857
858         while (*cur_pos == ' ') cur_pos++;
859
860         if (!strncmp(cur_pos, "NIL", 3)) {
861                 *dest = '\0';
862                 cur_pos += 3;
863         } else if (*cur_pos == '\"') {
864                 gchar *p;
865
866                 p = strchr_cpy(cur_pos + 1, '\"', dest, IMAPBUFSIZE);
867                 cur_pos = p ? p : cur_pos + 2;
868         } else if (*cur_pos == '{') {
869                 gchar buf[32];
870                 gint len;
871
872                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
873                 len = atoi(buf);
874
875                 g_return_val_if_fail(orig_buf != NULL, cur_pos);
876
877                 if (sock_gets(sock, orig_buf, IMAPBUFSIZE) < 0)
878                         return cur_pos;
879                 strretchomp(orig_buf);
880                 log_print("IMAP4< %s\n", orig_buf);
881                 memcpy(dest, orig_buf, len);
882                 dest[len] = '\0';
883                 cur_pos = orig_buf + len;
884         }
885
886         return cur_pos;
887 }
888
889 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
890                                      gchar *out_from_str,
891                                      gchar *out_fromname_str,
892                                      gchar *orig_buf)
893 {
894         gchar buf[IMAPBUFSIZE];
895         gchar *cur_pos = start;
896
897         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
898         conv_unmime_header(out_fromname_str, 256, buf, NULL);
899
900         if (out_fromname_str[0] != '\0') {
901                 strcat(out_from_str, "\"");
902                 strcat(out_from_str, out_fromname_str);
903                 strcat(out_from_str, "\"");
904         }
905
906         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
907
908         strcat(out_from_str, " <");
909
910         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
911         strcat(out_from_str, buf);
912
913         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
914         strcat(out_from_str, "@");
915         strcat(out_from_str, buf);
916         strcat(out_from_str, ">");
917
918         while (*cur_pos == ' ') cur_pos++;
919
920         g_return_val_if_fail(*cur_pos == ')', cur_pos + 1);
921
922         return cur_pos + 1;
923 }
924
925 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
926                                  gchar **out_from_str,
927                                  gchar **out_fromname_str,
928                                  gchar *orig_buf)
929 {
930         gchar buf[IMAPBUFSIZE];
931         gchar name_buf[IMAPBUFSIZE];
932         gchar *cur_pos = start;
933         gboolean first = TRUE;
934
935         if (out_from_str)     *out_from_str     = NULL;
936         if (out_fromname_str) *out_fromname_str = NULL;
937         buf[0] = name_buf[0] = '\0';
938
939         if (!strncmp(cur_pos, "NIL", 3)) {
940                 if (out_from_str)     *out_from_str     = g_strdup("");
941                 if (out_fromname_str) *out_fromname_str = g_strdup("");
942                 return cur_pos + 3;
943         }
944
945         g_return_val_if_fail(*cur_pos == '(', NULL);
946         cur_pos++;
947
948         for (;;) {
949                 gchar ch = *cur_pos++;
950                 if (ch == ')') break;
951                 if (ch == '(') {
952                         if (!first) strcat(buf, ", ");
953                         first = FALSE;
954                         cur_pos = imap_parse_one_address
955                                 (sock, cur_pos, buf, name_buf, orig_buf);
956                         if (!cur_pos) return NULL;
957                 }
958         }
959
960         if (out_from_str)     *out_from_str     = g_strdup(buf);
961         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
962
963         return cur_pos;
964 }
965
966 static MsgFlags imap_parse_flags(const gchar *flag_str)  
967 {
968         gchar buf[32];
969         const gchar *cur_pos = flag_str;
970         const gchar *last_pos;
971         MsgFlags flags;
972
973         flags = 0;
974         MSG_SET_FLAGS(flags, MSG_UNREAD|MSG_IMAP);
975
976         while (cur_pos != NULL) {
977                 cur_pos = strchr(cur_pos, '\\');
978                 if (cur_pos == NULL) break;
979
980                 last_pos = cur_pos + 1;
981                 cur_pos = strchr_cpy(last_pos, ' ', buf, sizeof(buf));
982                 if (cur_pos == NULL)
983                         strncpy2(buf, last_pos, sizeof(buf));
984
985                 if (g_strcasecmp(buf, "Recent") == 0) {
986                         MSG_SET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
987                 } else if (g_strcasecmp(buf, "Seen") == 0) {
988                         MSG_UNSET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
989                 } else if (g_strcasecmp(buf, "Deleted") == 0) {
990                         MSG_SET_FLAGS(flags, MSG_DELETED);
991                 } else if (g_strcasecmp(buf, "Flagged") == 0) {
992                         MSG_SET_FLAGS(flags, MSG_MARKED);
993                 }
994         }
995
996         return flags;
997 }
998
999 static MsgInfo *imap_parse_envelope(SockInfo *sock, gchar *line_str)
1000 {
1001         MsgInfo *msginfo;
1002         gchar buf[IMAPBUFSIZE];
1003         gchar tmp[IMAPBUFSIZE];
1004         gchar *cur_pos;
1005         gint msgnum;
1006         size_t size;
1007         gchar *date = NULL;
1008         time_t date_t;
1009         gchar *subject = NULL;
1010         gchar *tmp_from;
1011         gchar *tmp_fromname;
1012         gchar *from = NULL;
1013         gchar *fromname = NULL;
1014         gchar *tmp_to;
1015         gchar *to = NULL;
1016         gchar *inreplyto = NULL;
1017         gchar *msgid = NULL;
1018         MsgFlags flags;
1019
1020         log_print("IMAP4< %s\n", line_str);
1021
1022         g_return_val_if_fail(line_str != NULL, NULL);
1023         g_return_val_if_fail(line_str[0] == '*' && line_str[1] == ' ', NULL);
1024
1025         cur_pos = line_str + 2;
1026
1027 #define PARSE_ONE_ELEMENT(ch) \
1028 { \
1029         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1030         g_return_val_if_fail(cur_pos != NULL, NULL); \
1031 }
1032
1033         PARSE_ONE_ELEMENT(' ');
1034         msgnum = atoi(buf);
1035
1036         PARSE_ONE_ELEMENT(' ');
1037         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1038
1039         PARSE_ONE_ELEMENT(' ');
1040         g_return_val_if_fail(!strcmp(buf, "(FLAGS"), NULL);
1041
1042         PARSE_ONE_ELEMENT(')');
1043         g_return_val_if_fail(*buf == '(', NULL);
1044         flags = imap_parse_flags(buf + 1);
1045
1046         g_return_val_if_fail(*cur_pos == ' ', NULL);
1047         g_return_val_if_fail
1048                 ((cur_pos = strchr_cpy(cur_pos + 1, ' ', buf, sizeof(buf))),
1049                  NULL);
1050         g_return_val_if_fail(!strcmp(buf, "RFC822.SIZE"), NULL);
1051
1052         PARSE_ONE_ELEMENT(' ');
1053         size = atoi(buf);
1054
1055         PARSE_ONE_ELEMENT(' ');
1056         g_return_val_if_fail(!strcmp(buf, "ENVELOPE"), NULL);
1057
1058         g_return_val_if_fail(*cur_pos == '(', NULL);
1059         cur_pos = imap_parse_atom(sock, cur_pos + 1, buf, line_str);
1060         Xstrdup_a(date, buf, return NULL);
1061         date_t = procheader_date_parse(NULL, date, 0);
1062
1063         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1064         if (buf[0] != '\0') {
1065                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1066                 Xstrdup_a(subject, tmp, return NULL);
1067         }
1068
1069         g_return_val_if_fail(*cur_pos == ' ', NULL);
1070         cur_pos = imap_parse_address(sock, cur_pos + 1,
1071                                      &tmp_from, &tmp_fromname, line_str);
1072         Xstrdup_a(from, tmp_from,
1073                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1074         Xstrdup_a(fromname, tmp_fromname,
1075                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1076         g_free(tmp_from);
1077         g_free(tmp_fromname);
1078
1079 #define SKIP_ONE_ELEMENT() \
1080 { \
1081         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1082         cur_pos = imap_parse_address(sock, cur_pos + 1, \
1083                                      NULL, NULL, line_str); \
1084 }
1085
1086         /* skip sender and reply-to */
1087         SKIP_ONE_ELEMENT();
1088         SKIP_ONE_ELEMENT();
1089
1090         g_return_val_if_fail(*cur_pos == ' ', NULL);
1091         cur_pos = imap_parse_address(sock, cur_pos + 1, &tmp_to, NULL, line_str);
1092         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1093         g_free(tmp_to);
1094
1095         /* skip Cc and Bcc */
1096         SKIP_ONE_ELEMENT();
1097         SKIP_ONE_ELEMENT();
1098
1099 #undef SKIP_ONE_ELEMENT
1100
1101         g_return_val_if_fail(*cur_pos == ' ', NULL);
1102         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1103         if (buf[0] != '\0') {
1104                 eliminate_parenthesis(buf, '(', ')');
1105                 extract_parenthesis(buf, '<', '>');
1106                 remove_space(buf);
1107                 Xstrdup_a(inreplyto, buf, return NULL);
1108         }
1109
1110         g_return_val_if_fail(*cur_pos == ' ', NULL);
1111         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1112         if (buf[0] != '\0') {
1113                 extract_parenthesis(buf, '<', '>');
1114                 remove_space(buf);
1115                 Xstrdup_a(msgid, buf, return NULL);
1116         }
1117
1118         msginfo = g_new0(MsgInfo, 1);
1119         msginfo->msgnum = msgnum;
1120         msginfo->size = size;
1121         msginfo->date = g_strdup(date);
1122         msginfo->date_t = date_t;
1123         msginfo->subject = g_strdup(subject);
1124         msginfo->from = g_strdup(from);
1125         msginfo->fromname = g_strdup(fromname);
1126         msginfo->to = g_strdup(to);
1127         msginfo->inreplyto = g_strdup(inreplyto);
1128         msginfo->msgid = g_strdup(msgid);
1129         msginfo->flags = flags;
1130
1131         return msginfo;
1132 }
1133
1134 gint imap_get_envelope(SockInfo *sock, gint first, gint last)
1135 {
1136         imap_gen_send(sock, "FETCH %d:%d (FLAGS RFC822.SIZE ENVELOPE)",
1137                       first, last);
1138
1139         return IMAP_SUCCESS;
1140 }
1141
1142 static gint imap_store(SockInfo *sock, gint first, gint last, gchar *sub_cmd)
1143 {
1144         gint ok;
1145         GPtrArray *argbuf;
1146
1147         argbuf = g_ptr_array_new();
1148
1149         imap_gen_send(sock, "STORE %d:%d %s", first, last, sub_cmd);
1150         
1151         if ((ok = imap_ok(sock, argbuf)) != IMAP_SUCCESS) {
1152                 g_ptr_array_free(argbuf, TRUE);
1153                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
1154                             first, last, sub_cmd);
1155                 return ok;
1156         }
1157
1158         g_ptr_array_free(argbuf, TRUE);
1159
1160         return IMAP_SUCCESS;
1161 }
1162
1163 static gint imap_set_article_flags(IMAPSession *session,
1164                                    gint first,
1165                                    gint last,
1166                                    IMAPFlags flags,
1167                                    gboolean is_set)
1168 {
1169         GString *buf;
1170         gint ok;
1171
1172         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1173
1174         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1175         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1176         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1177         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1178         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1179
1180         if (buf->str[buf->len - 1] == ' ')
1181                 g_string_truncate(buf, buf->len - 1);
1182
1183         g_string_append_c(buf, ')');
1184
1185         ok = imap_store(SESSION(session)->sock, first, last, buf->str);
1186         g_string_free(buf, TRUE);
1187
1188         return ok;
1189 }
1190
1191 static gint imap_expunge(IMAPSession *session)
1192 {
1193         gint ok;
1194         GPtrArray *argbuf;
1195
1196         argbuf = g_ptr_array_new();
1197
1198         imap_gen_send(SESSION(session)->sock, "EXPUNGE");
1199
1200         if ((ok = imap_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS) {
1201                 log_warning(_("error while imap command: EXPUNGE\n"));
1202                 g_ptr_array_free(argbuf, TRUE);
1203                 return ok;
1204         }
1205
1206         g_ptr_array_free(argbuf, TRUE);
1207
1208         return IMAP_SUCCESS;
1209 }
1210
1211 static gint imap_ok(SockInfo *sock, GPtrArray *argbuf)
1212 {
1213         gint ok;
1214         gchar buf[IMAPBUFSIZE];
1215         gint cmd_num;
1216         gchar cmd_status[IMAPBUFSIZE];
1217
1218         while ((ok = imap_gen_recv(sock, buf, sizeof(buf))) == IMAP_SUCCESS) {
1219                 if (buf[0] == '*' && buf[1] == ' ') {
1220                         if (argbuf)
1221                                 g_ptr_array_add(argbuf, g_strdup(&buf[2]));
1222                 } else {
1223                         if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
1224                                 return IMAP_ERROR;
1225                         else if (cmd_num == imap_cmd_count &&
1226                                  !strcmp(cmd_status, "OK")) {
1227                                 if (argbuf)
1228                                         g_ptr_array_add(argbuf, g_strdup(buf));
1229                                 return IMAP_SUCCESS;
1230                         } else
1231                                 return IMAP_ERROR;
1232                 }
1233         }
1234
1235         return ok;
1236 }
1237
1238 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
1239 {
1240         gint i;
1241
1242         for (i = 0; i < array->len; i++) {
1243                 gchar *tmp;
1244
1245                 tmp = g_ptr_array_index(array, i);
1246                 if (strstr(tmp, str) != NULL)
1247                         return tmp;
1248         }
1249
1250         return NULL;
1251 }
1252
1253 static void imap_gen_send(SockInfo *sock, const gchar *format, ...)
1254 {
1255         gchar buf[IMAPBUFSIZE];
1256         gchar tmp[IMAPBUFSIZE];
1257         gchar *p;
1258         va_list args;
1259
1260         va_start(args, format);
1261         g_vsnprintf(tmp, sizeof(tmp), format, args);
1262         va_end(args);
1263
1264         imap_cmd_count++;
1265
1266         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
1267         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
1268                 *(p + 1) = '\0';
1269                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
1270         } else
1271                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
1272
1273         sock_write(sock, buf, strlen(buf));
1274 }
1275
1276 static gint imap_gen_recv(SockInfo *sock, gchar *buf, gint size)
1277 {
1278         if (sock_gets(sock, buf, size) == -1)
1279                 return IMAP_SOCKET;
1280
1281         strretchomp(buf);
1282
1283         log_print("IMAP4< %s\n", buf);
1284
1285         return IMAP_SUCCESS;
1286 }
1287
1288 static void imap_path_subst_slash_to_dot(gchar *str)
1289 {       
1290         subst_char(str, '/', '.');
1291 }