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