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