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