mbox format completed
[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         if (strcmp(name, "INBOX") != 0) {
509                 ok = imap_create(SESSION(session)->sock, imappath);
510                 if (ok != IMAP_SUCCESS) {
511                         log_warning(_("can't create mailbox\n"));
512                         g_free(imappath);
513                         g_free(dirpath);
514                         return NULL;
515                 }
516         }
517
518         new_item = folder_item_new(name, dirpath);
519         folder_item_append(parent, new_item);
520         g_free(imappath);
521         g_free(dirpath);
522
523         return new_item;
524 }
525
526 gint imap_remove_folder(Folder *folder, FolderItem *item)
527 {
528         gint ok;
529         IMAPSession *session;
530
531         g_return_val_if_fail(folder != NULL, -1);
532         g_return_val_if_fail(item != NULL, -1);
533         g_return_val_if_fail(item->path != NULL, -1);
534
535         session = imap_session_connect_if_not(folder);
536         if (!session) return -1;
537
538         ok = imap_delete(SESSION(session)->sock, item->path);
539         if (ok != IMAP_SUCCESS) {
540                 log_warning(_("can't delete mailbox\n"));
541                 return -1;
542         }
543
544         folder_item_remove(item);
545
546         return 0;
547 }
548
549 static GSList *imap_get_uncached_messages(IMAPSession *session,
550                                           FolderItem *item,
551                                           gint first, gint last)
552 {
553         gchar buf[IMAPBUFSIZE];
554         GSList *newlist = NULL;
555         GSList *llast = NULL;
556         MsgInfo *msginfo;
557
558         g_return_val_if_fail(session != NULL, NULL);
559         g_return_val_if_fail(item != NULL, NULL);
560         g_return_val_if_fail(item->folder != NULL, NULL);
561         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
562         g_return_val_if_fail(first <= last, NULL);
563
564         if (imap_get_envelope(SESSION(session)->sock, first, last)
565             != IMAP_SUCCESS) {
566                 log_warning(_("can't get envelope\n"));
567                 return NULL;
568         }
569
570         for (;;) {
571                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
572                         log_warning(_("error occurred while getting envelope.\n"));
573                         return newlist;
574                 }
575                 strretchomp(buf);
576                 if (buf[0] != '*' || buf[1] != ' ') break;
577
578                 msginfo = imap_parse_envelope(SESSION(session)->sock, buf);
579                 if (!msginfo) {
580                         log_warning(_("can't parse envelope: %s\n"), buf);
581                         continue;
582                 }
583
584                 msginfo->folder = item;
585
586                 if (!newlist)
587                         llast = newlist = g_slist_append(newlist, msginfo);
588                 else {
589                         llast = g_slist_append(llast, msginfo);
590                         llast = llast->next;
591                 }
592         }
593
594         return newlist;
595 }
596
597 static GSList *imap_delete_messages(GSList *mlist, gint first, gint last)
598 {
599         GSList *cur, *next;
600         MsgInfo *msginfo;
601         gchar *cache_file;
602
603         for (cur = mlist; cur != NULL; ) {
604                 next = cur->next;
605
606                 msginfo = (MsgInfo *)cur->data;
607                 if ((msginfo) && 
608                     (first <= msginfo->msgnum ) &&
609                     (msginfo->msgnum <= last)) {
610                         debug_print(_("deleting message %d...\n"),
611                                     msginfo->msgnum);
612
613                         cache_file = procmsg_get_message_file_path(msginfo);
614                         if (is_file_exist(cache_file)) unlink(cache_file);
615                         g_free(cache_file);
616
617                         procmsg_msginfo_free(msginfo);
618                         mlist = g_slist_remove(mlist, msginfo);
619                 }
620
621                 cur = next;
622         }
623
624         return mlist;
625 }
626
627 static void imap_delete_all_messages(FolderItem *item)
628 {
629         DIR *dp;
630         struct dirent *d;
631         gchar *dir;
632         gchar *file;
633
634         g_return_if_fail(item != NULL);
635         g_return_if_fail(item->folder != NULL);
636         g_return_if_fail(item->folder->type == F_IMAP);
637
638         dir = folder_item_get_path(item);
639         if ((dp = opendir(dir)) == NULL) {
640                 FILE_OP_ERROR(dir, "opendir");
641                 g_free(dir);
642                 return;
643         }
644
645         debug_print(_("\tDeleting all cached messages... "));
646
647         while ((d = readdir(dp)) != NULL) {
648                 if (to_number(d->d_name) < 0) continue;
649
650                 file = g_strconcat(dir, G_DIR_SEPARATOR_S, d->d_name, NULL);
651
652                 if (is_file_exist(file)) {
653                         if (unlink(file) < 0)
654                                 FILE_OP_ERROR(file, "unlink");
655                 }
656
657                 g_free(file);
658         }
659
660         closedir(dp);
661         g_free(dir);
662
663         debug_print(_("done.\n"));
664 }
665
666
667 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf)
668 {
669         SockInfo *sock;
670
671         if ((sock = sock_connect(server, port)) == NULL) {
672                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
673                             server, port);
674                 return NULL;
675         }
676
677         imap_cmd_count = 0;
678
679         if (imap_noop(sock) != IMAP_SUCCESS) {
680                 sock_close(sock);
681                 return NULL;
682         }
683
684         return sock;
685 }
686
687 static gint imap_auth(SockInfo *sock, const gchar *user, const gchar *pass)
688 {
689         gint ok;
690         GPtrArray *argbuf;
691
692         imap_gen_send(sock, "LOGIN \"%s\" %s", user, pass);
693         argbuf = g_ptr_array_new();
694         ok = imap_ok(sock, argbuf);
695         if (ok != IMAP_SUCCESS) log_warning(_("IMAP4 login failed.\n"));
696         ptr_array_free_strings(argbuf);
697         g_ptr_array_free(argbuf, TRUE);
698
699         return ok;
700 }
701
702 static gint imap_logout(SockInfo *sock)
703 {
704         imap_gen_send(sock, "LOGOUT");
705         return imap_ok(sock, NULL);
706 }
707
708 static gint imap_noop(SockInfo *sock)
709 {
710         imap_gen_send(sock, "NOOP");
711         return imap_ok(sock, NULL);
712 }
713
714 static gint imap_select(SockInfo *sock, const gchar *folder,
715                         gint *exists, gint *recent, gint *unseen, gulong *uid)
716 {
717         gint ok;
718         gchar *resp_str;
719         GPtrArray *argbuf;
720         gchar *imappath;
721
722         *exists = *recent = *unseen = *uid = 0;
723         argbuf = g_ptr_array_new();
724
725         Xstrdup_a(imappath, folder, return -1);
726         /* imap_path_subst_slash_to_dot(imappath); */
727
728         imap_gen_send(sock, "SELECT \"%s\"", imappath);
729         if ((ok = imap_ok(sock, argbuf)) != IMAP_SUCCESS)
730                 goto bail;
731
732         resp_str = search_array_contain_str(argbuf, "EXISTS");
733         if (resp_str) {
734                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
735                         g_warning("imap_select(): invalid EXISTS line.\n");
736                         goto bail;
737                 }
738         }
739
740         resp_str = search_array_contain_str(argbuf, "RECENT");
741         if (resp_str) {
742                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
743                         g_warning("imap_select(): invalid RECENT line.\n");
744                         goto bail;
745                 }
746         }
747
748         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
749         if (resp_str) {
750                 if (sscanf(resp_str, "OK [UIDVALIDITY %lu] ", uid) != 1) {
751                         g_warning("imap_select(): invalid UIDVALIDITY line.\n");
752                         goto bail;
753                 }
754         }
755
756         resp_str = search_array_contain_str(argbuf, "UNSEEN");
757         if (resp_str) {
758                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
759                         g_warning("imap_select(): invalid UNSEEN line.\n");
760                         goto bail;
761                 }
762         }
763
764 bail:
765         ptr_array_free_strings(argbuf);
766         g_ptr_array_free(argbuf, TRUE);
767
768         return ok;
769 }
770
771 static gint imap_create(SockInfo *sock, const gchar *folder)
772 {
773         imap_gen_send(sock, "CREATE \"%s\"", folder);
774         return imap_ok(sock, NULL);
775 }
776
777 static gint imap_delete(SockInfo *sock, const gchar *folder)
778 {
779         imap_gen_send(sock, "DELETE \"%s\"", folder);
780         return imap_ok(sock, NULL);
781 }
782
783 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
784 {
785         gchar *tmp;
786
787         dest[0] = '\0';
788         tmp = strchr(src, ch);
789         if (!tmp || tmp == src)
790                 return NULL;
791
792         memcpy(dest, src, MIN(tmp - src, len - 1));
793         dest[MIN(tmp - src, len - 1)] = '\0';
794
795         return tmp + 1;
796 }
797
798 static gint imap_get_message(SockInfo *sock, gint num, const gchar *filename)
799 {
800         gint ok;
801         gchar buf[IMAPBUFSIZE];
802         gchar *cur_pos;
803         gchar size_str[32];
804         glong size_num;
805
806         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
807
808         imap_gen_send(sock, "FETCH %d BODY[]", num);
809
810         if (sock_gets(sock, buf, sizeof(buf)) < 0)
811                 return IMAP_ERROR;
812         strretchomp(buf);
813         if (buf[0] != '*' || buf[1] != ' ')
814                 return IMAP_ERROR;
815         log_print("IMAP4< %s\n", buf);
816
817         cur_pos = strchr(buf, '{');
818         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
819         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
820         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
821         size_num = atol(size_str);
822
823         if (*cur_pos != '\0') return IMAP_ERROR;
824
825         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
826                 return IMAP_ERROR;
827
828         if (imap_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
829                 return IMAP_ERROR;
830
831         if (buf[0] != ')')
832                 return IMAP_ERROR;
833
834         ok = imap_ok(sock, NULL);
835
836         return ok;
837 }
838
839 static gint imap_copy_message(SockInfo *sock, gint num, const gchar *destfolder)
840 {
841         gint ok;
842
843         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
844
845         imap_gen_send(sock, "COPY %d %s", num, destfolder);
846         ok = imap_ok(sock, NULL);
847         if (ok != IMAP_SUCCESS) {
848                 log_warning(_("can't copy %d to %s\n"), num, destfolder);
849                 return -1;
850         }
851
852         return ok;
853 }
854
855 static gchar *imap_parse_atom(SockInfo *sock, gchar *src, gchar *dest,
856                               gchar *orig_buf)
857 {
858         gchar *cur_pos = src;
859
860         while (*cur_pos == ' ') cur_pos++;
861
862         if (!strncmp(cur_pos, "NIL", 3)) {
863                 *dest = '\0';
864                 cur_pos += 3;
865         } else if (*cur_pos == '\"') {
866                 gchar *p;
867
868                 p = strchr_cpy(cur_pos + 1, '\"', dest, IMAPBUFSIZE);
869                 cur_pos = p ? p : cur_pos + 2;
870         } else if (*cur_pos == '{') {
871                 gchar buf[32];
872                 gint len;
873
874                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
875                 len = atoi(buf);
876
877                 g_return_val_if_fail(orig_buf != NULL, cur_pos);
878
879                 if (sock_gets(sock, orig_buf, IMAPBUFSIZE) < 0)
880                         return cur_pos;
881                 strretchomp(orig_buf);
882                 log_print("IMAP4< %s\n", orig_buf);
883                 memcpy(dest, orig_buf, len);
884                 dest[len] = '\0';
885                 cur_pos = orig_buf + len;
886         }
887
888         return cur_pos;
889 }
890
891 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
892                                      gchar *out_from_str,
893                                      gchar *out_fromname_str,
894                                      gchar *orig_buf)
895 {
896         gchar buf[IMAPBUFSIZE];
897         gchar *cur_pos = start;
898
899         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
900         conv_unmime_header(out_fromname_str, 256, buf, NULL);
901
902         if (out_fromname_str[0] != '\0') {
903                 strcat(out_from_str, "\"");
904                 strcat(out_from_str, out_fromname_str);
905                 strcat(out_from_str, "\"");
906         }
907
908         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
909
910         strcat(out_from_str, " <");
911
912         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
913         strcat(out_from_str, buf);
914
915         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
916         strcat(out_from_str, "@");
917         strcat(out_from_str, buf);
918         strcat(out_from_str, ">");
919
920         while (*cur_pos == ' ') cur_pos++;
921
922         g_return_val_if_fail(*cur_pos == ')', cur_pos + 1);
923
924         return cur_pos + 1;
925 }
926
927 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
928                                  gchar **out_from_str,
929                                  gchar **out_fromname_str,
930                                  gchar *orig_buf)
931 {
932         gchar buf[IMAPBUFSIZE];
933         gchar name_buf[IMAPBUFSIZE];
934         gchar *cur_pos = start;
935         gboolean first = TRUE;
936
937         if (out_from_str)     *out_from_str     = NULL;
938         if (out_fromname_str) *out_fromname_str = NULL;
939         buf[0] = name_buf[0] = '\0';
940
941         if (!strncmp(cur_pos, "NIL", 3)) {
942                 if (out_from_str)     *out_from_str     = g_strdup("");
943                 if (out_fromname_str) *out_fromname_str = g_strdup("");
944                 return cur_pos + 3;
945         }
946
947         g_return_val_if_fail(*cur_pos == '(', NULL);
948         cur_pos++;
949
950         for (;;) {
951                 gchar ch = *cur_pos++;
952                 if (ch == ')') break;
953                 if (ch == '(') {
954                         if (!first) strcat(buf, ", ");
955                         first = FALSE;
956                         cur_pos = imap_parse_one_address
957                                 (sock, cur_pos, buf, name_buf, orig_buf);
958                         if (!cur_pos) return NULL;
959                 }
960         }
961
962         if (out_from_str)     *out_from_str     = g_strdup(buf);
963         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
964
965         return cur_pos;
966 }
967
968 static MsgFlags imap_parse_flags(const gchar *flag_str)  
969 {
970         gchar buf[32];
971         const gchar *cur_pos = flag_str;
972         const gchar *last_pos;
973         MsgFlags flags;
974
975         flags = 0;
976         MSG_SET_FLAGS(flags, MSG_UNREAD|MSG_IMAP);
977
978         while (cur_pos != NULL) {
979                 cur_pos = strchr(cur_pos, '\\');
980                 if (cur_pos == NULL) break;
981
982                 last_pos = cur_pos + 1;
983                 cur_pos = strchr_cpy(last_pos, ' ', buf, sizeof(buf));
984                 if (cur_pos == NULL)
985                         strncpy2(buf, last_pos, sizeof(buf));
986
987                 if (g_strcasecmp(buf, "Recent") == 0) {
988                         MSG_SET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
989                 } else if (g_strcasecmp(buf, "Seen") == 0) {
990                         MSG_UNSET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
991                 } else if (g_strcasecmp(buf, "Deleted") == 0) {
992                         MSG_SET_FLAGS(flags, MSG_DELETED);
993                 } else if (g_strcasecmp(buf, "Flagged") == 0) {
994                         MSG_SET_FLAGS(flags, MSG_MARKED);
995                 }
996         }
997
998         return flags;
999 }
1000
1001 static MsgInfo *imap_parse_envelope(SockInfo *sock, gchar *line_str)
1002 {
1003         MsgInfo *msginfo;
1004         gchar buf[IMAPBUFSIZE];
1005         gchar tmp[IMAPBUFSIZE];
1006         gchar *cur_pos;
1007         gint msgnum;
1008         size_t size;
1009         gchar *date = NULL;
1010         time_t date_t;
1011         gchar *subject = NULL;
1012         gchar *tmp_from;
1013         gchar *tmp_fromname;
1014         gchar *from = NULL;
1015         gchar *fromname = NULL;
1016         gchar *tmp_to;
1017         gchar *to = NULL;
1018         gchar *inreplyto = NULL;
1019         gchar *msgid = NULL;
1020         MsgFlags flags;
1021
1022         log_print("IMAP4< %s\n", line_str);
1023
1024         g_return_val_if_fail(line_str != NULL, NULL);
1025         g_return_val_if_fail(line_str[0] == '*' && line_str[1] == ' ', NULL);
1026
1027         cur_pos = line_str + 2;
1028
1029 #define PARSE_ONE_ELEMENT(ch) \
1030 { \
1031         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1032         g_return_val_if_fail(cur_pos != NULL, NULL); \
1033 }
1034
1035         PARSE_ONE_ELEMENT(' ');
1036         msgnum = atoi(buf);
1037
1038         PARSE_ONE_ELEMENT(' ');
1039         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1040
1041         PARSE_ONE_ELEMENT(' ');
1042         g_return_val_if_fail(!strcmp(buf, "(FLAGS"), NULL);
1043
1044         PARSE_ONE_ELEMENT(')');
1045         g_return_val_if_fail(*buf == '(', NULL);
1046         flags = imap_parse_flags(buf + 1);
1047
1048         g_return_val_if_fail(*cur_pos == ' ', NULL);
1049         g_return_val_if_fail
1050                 ((cur_pos = strchr_cpy(cur_pos + 1, ' ', buf, sizeof(buf))),
1051                  NULL);
1052         g_return_val_if_fail(!strcmp(buf, "RFC822.SIZE"), NULL);
1053
1054         PARSE_ONE_ELEMENT(' ');
1055         size = atoi(buf);
1056
1057         PARSE_ONE_ELEMENT(' ');
1058         g_return_val_if_fail(!strcmp(buf, "ENVELOPE"), NULL);
1059
1060         g_return_val_if_fail(*cur_pos == '(', NULL);
1061         cur_pos = imap_parse_atom(sock, cur_pos + 1, buf, line_str);
1062         Xstrdup_a(date, buf, return NULL);
1063         date_t = procheader_date_parse(NULL, date, 0);
1064
1065         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1066         if (buf[0] != '\0') {
1067                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1068                 Xstrdup_a(subject, tmp, return NULL);
1069         }
1070
1071         g_return_val_if_fail(*cur_pos == ' ', NULL);
1072         cur_pos = imap_parse_address(sock, cur_pos + 1,
1073                                      &tmp_from, &tmp_fromname, line_str);
1074         Xstrdup_a(from, tmp_from,
1075                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1076         Xstrdup_a(fromname, tmp_fromname,
1077                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1078         g_free(tmp_from);
1079         g_free(tmp_fromname);
1080
1081 #define SKIP_ONE_ELEMENT() \
1082 { \
1083         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1084         cur_pos = imap_parse_address(sock, cur_pos + 1, \
1085                                      NULL, NULL, line_str); \
1086 }
1087
1088         /* skip sender and reply-to */
1089         SKIP_ONE_ELEMENT();
1090         SKIP_ONE_ELEMENT();
1091
1092         g_return_val_if_fail(*cur_pos == ' ', NULL);
1093         cur_pos = imap_parse_address(sock, cur_pos + 1, &tmp_to, NULL, line_str);
1094         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1095         g_free(tmp_to);
1096
1097         /* skip Cc and Bcc */
1098         SKIP_ONE_ELEMENT();
1099         SKIP_ONE_ELEMENT();
1100
1101 #undef SKIP_ONE_ELEMENT
1102
1103         g_return_val_if_fail(*cur_pos == ' ', NULL);
1104         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1105         if (buf[0] != '\0') {
1106                 eliminate_parenthesis(buf, '(', ')');
1107                 extract_parenthesis(buf, '<', '>');
1108                 remove_space(buf);
1109                 Xstrdup_a(inreplyto, buf, return NULL);
1110         }
1111
1112         g_return_val_if_fail(*cur_pos == ' ', NULL);
1113         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1114         if (buf[0] != '\0') {
1115                 extract_parenthesis(buf, '<', '>');
1116                 remove_space(buf);
1117                 Xstrdup_a(msgid, buf, return NULL);
1118         }
1119
1120         msginfo = g_new0(MsgInfo, 1);
1121         msginfo->msgnum = msgnum;
1122         msginfo->size = size;
1123         msginfo->date = g_strdup(date);
1124         msginfo->date_t = date_t;
1125         msginfo->subject = g_strdup(subject);
1126         msginfo->from = g_strdup(from);
1127         msginfo->fromname = g_strdup(fromname);
1128         msginfo->to = g_strdup(to);
1129         msginfo->inreplyto = g_strdup(inreplyto);
1130         msginfo->msgid = g_strdup(msgid);
1131         msginfo->flags = flags;
1132
1133         return msginfo;
1134 }
1135
1136 gint imap_get_envelope(SockInfo *sock, gint first, gint last)
1137 {
1138         imap_gen_send(sock, "FETCH %d:%d (FLAGS RFC822.SIZE ENVELOPE)",
1139                       first, last);
1140
1141         return IMAP_SUCCESS;
1142 }
1143
1144 static gint imap_store(SockInfo *sock, gint first, gint last, gchar *sub_cmd)
1145 {
1146         gint ok;
1147         GPtrArray *argbuf;
1148
1149         argbuf = g_ptr_array_new();
1150
1151         imap_gen_send(sock, "STORE %d:%d %s", first, last, sub_cmd);
1152         
1153         if ((ok = imap_ok(sock, argbuf)) != IMAP_SUCCESS) {
1154                 g_ptr_array_free(argbuf, TRUE);
1155                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
1156                             first, last, sub_cmd);
1157                 return ok;
1158         }
1159
1160         g_ptr_array_free(argbuf, TRUE);
1161
1162         return IMAP_SUCCESS;
1163 }
1164
1165 static gint imap_set_article_flags(IMAPSession *session,
1166                                    gint first,
1167                                    gint last,
1168                                    IMAPFlags flags,
1169                                    gboolean is_set)
1170 {
1171         GString *buf;
1172         gint ok;
1173
1174         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1175
1176         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1177         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1178         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1179         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1180         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1181
1182         if (buf->str[buf->len - 1] == ' ')
1183                 g_string_truncate(buf, buf->len - 1);
1184
1185         g_string_append_c(buf, ')');
1186
1187         ok = imap_store(SESSION(session)->sock, first, last, buf->str);
1188         g_string_free(buf, TRUE);
1189
1190         return ok;
1191 }
1192
1193 static gint imap_expunge(IMAPSession *session)
1194 {
1195         gint ok;
1196         GPtrArray *argbuf;
1197
1198         argbuf = g_ptr_array_new();
1199
1200         imap_gen_send(SESSION(session)->sock, "EXPUNGE");
1201
1202         if ((ok = imap_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS) {
1203                 log_warning(_("error while imap command: EXPUNGE\n"));
1204                 g_ptr_array_free(argbuf, TRUE);
1205                 return ok;
1206         }
1207
1208         g_ptr_array_free(argbuf, TRUE);
1209
1210         return IMAP_SUCCESS;
1211 }
1212
1213 static gint imap_ok(SockInfo *sock, GPtrArray *argbuf)
1214 {
1215         gint ok;
1216         gchar buf[IMAPBUFSIZE];
1217         gint cmd_num;
1218         gchar cmd_status[IMAPBUFSIZE];
1219
1220         while ((ok = imap_gen_recv(sock, buf, sizeof(buf))) == IMAP_SUCCESS) {
1221                 if (buf[0] == '*' && buf[1] == ' ') {
1222                         if (argbuf)
1223                                 g_ptr_array_add(argbuf, g_strdup(&buf[2]));
1224                 } else {
1225                         if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
1226                                 return IMAP_ERROR;
1227                         else if (cmd_num == imap_cmd_count &&
1228                                  !strcmp(cmd_status, "OK")) {
1229                                 if (argbuf)
1230                                         g_ptr_array_add(argbuf, g_strdup(buf));
1231                                 return IMAP_SUCCESS;
1232                         } else
1233                                 return IMAP_ERROR;
1234                 }
1235         }
1236
1237         return ok;
1238 }
1239
1240 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
1241 {
1242         gint i;
1243
1244         for (i = 0; i < array->len; i++) {
1245                 gchar *tmp;
1246
1247                 tmp = g_ptr_array_index(array, i);
1248                 if (strstr(tmp, str) != NULL)
1249                         return tmp;
1250         }
1251
1252         return NULL;
1253 }
1254
1255 static void imap_gen_send(SockInfo *sock, const gchar *format, ...)
1256 {
1257         gchar buf[IMAPBUFSIZE];
1258         gchar tmp[IMAPBUFSIZE];
1259         gchar *p;
1260         va_list args;
1261
1262         va_start(args, format);
1263         g_vsnprintf(tmp, sizeof(tmp), format, args);
1264         va_end(args);
1265
1266         imap_cmd_count++;
1267
1268         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
1269         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
1270                 *(p + 1) = '\0';
1271                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
1272         } else
1273                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
1274
1275         sock_write(sock, buf, strlen(buf));
1276 }
1277
1278 static gint imap_gen_recv(SockInfo *sock, gchar *buf, gint size)
1279 {
1280         if (sock_gets(sock, buf, size) == -1)
1281                 return IMAP_SOCKET;
1282
1283         strretchomp(buf);
1284
1285         log_print("IMAP4< %s\n", buf);
1286
1287         return IMAP_SUCCESS;
1288 }
1289
1290 static void imap_path_subst_slash_to_dot(gchar *str)
1291 {       
1292         subst_char(str, '/', '.');
1293 }