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