when a 'protocol error' is encountered disconnect from the server
[claws.git] / src / news.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 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 "defs.h"
25
26 #include <glib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <dirent.h>
31 #include <unistd.h>
32 #include <time.h>
33
34 #include "intl.h"
35 #include "news.h"
36 #include "nntp.h"
37 #include "socket.h"
38 #include "recv.h"
39 #include "procmsg.h"
40 #include "procheader.h"
41 #include "folder.h"
42 #include "session.h"
43 #include "statusbar.h"
44 #include "codeconv.h"
45 #include "utils.h"
46 #include "prefs_common.h"
47 #include "prefs_account.h"
48 #include "inputdialog.h"
49 #include "alertpanel.h"
50 #include "log.h"
51 #if USE_OPENSSL
52 #  include "ssl.h"
53 #endif
54
55 #define NNTP_PORT       119
56 #if USE_OPENSSL
57 #define NNTPS_PORT      563
58 #endif
59
60 static void news_folder_init             (Folder        *folder,
61                                           const gchar   *name,
62                                           const gchar   *path);
63
64 #if USE_OPENSSL
65 static Session *news_session_new         (const gchar   *server,
66                                           gushort        port,
67                                           const gchar   *userid,
68                                           const gchar   *passwd,
69                                           SSLType        ssl_type);
70 #else
71 static Session *news_session_new         (const gchar   *server,
72                                           gushort        port,
73                                           const gchar   *userid,
74                                           const gchar   *passwd);
75 #endif
76
77 static gint news_get_article_cmd         (NNTPSession   *session,
78                                           const gchar   *cmd,
79                                           gint           num,
80                                           gchar         *filename);
81 static gint news_get_article             (NNTPSession   *session,
82                                           gint           num,
83                                           gchar         *filename);
84
85 static gint news_select_group            (NNTPSession   *session,
86                                           const gchar   *group,
87                                           gint          *num,
88                                           gint          *first,
89                                           gint          *last);
90 static GSList *news_get_uncached_articles(NNTPSession   *session,
91                                           FolderItem    *item,
92                                           gint           cache_last,
93                                           gint          *rfirst,
94                                           gint          *rlast);
95 static MsgInfo *news_parse_xover         (const gchar   *xover_str);
96 static gchar *news_parse_xhdr            (const gchar   *xhdr_str,
97                                           MsgInfo       *msginfo);
98 static GSList *news_delete_old_articles  (GSList        *alist,
99                                           FolderItem    *item,
100                                           gint           first);
101 static void news_delete_all_articles     (FolderItem    *item);
102 static void news_delete_expired_caches   (GSList        *alist,
103                                           FolderItem    *item);
104
105 static gint news_remove_msg              (Folder        *folder, 
106                                           FolderItem    *item, 
107                                           gint           num);
108 gint news_get_num_list                   (Folder        *folder, 
109                                           FolderItem    *item,
110                                           GSList       **list);
111 MsgInfo *news_get_msginfo                (Folder        *folder, 
112                                           FolderItem    *item,
113                                           gint           num);
114 GSList *news_get_msginfos                (Folder        *folder,
115                                           FolderItem    *item,
116                                           GSList        *msgnum_list);
117
118 gint news_post_stream                    (Folder        *folder, 
119                                           FILE          *fp);
120
121 Folder *news_folder_new(const gchar *name, const gchar *path)
122 {
123         Folder *folder;
124
125         folder = (Folder *)g_new0(NewsFolder, 1);
126         news_folder_init(folder, name, path);
127
128         return folder;
129 }
130
131 void news_folder_destroy(Folder *folder)
132 {
133         gchar *dir;
134
135         dir = folder_get_path(folder);
136         if (is_dir_exist(dir))
137                 remove_dir_recursive(dir);
138         g_free(dir);
139
140         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
141 }
142
143 static void news_folder_init(Folder *folder, const gchar *name,
144                              const gchar *path)
145 {
146         folder->type = F_NEWS;
147
148         folder_remote_folder_init(folder, name, path);
149
150 /*
151         folder->get_msg_list = news_get_article_list;
152 */
153         folder->fetch_msg    = news_fetch_msg;
154 /*
155         folder->scan         = news_scan_group;
156 */
157         folder->destroy      = news_folder_destroy;
158         folder->remove_msg   = news_remove_msg;
159         folder->get_num_list = news_get_num_list;
160         folder->get_msginfo  = news_get_msginfo;
161         folder->get_msginfos = news_get_msginfos;
162 }
163
164 #if USE_OPENSSL
165 static Session *news_session_new(const gchar *server, gushort port,
166                                  const gchar *userid, const gchar *passwd,
167                                  SSLType ssl_type)
168 #else
169 static Session *news_session_new(const gchar *server, gushort port,
170                                  const gchar *userid, const gchar *passwd)
171 #endif
172 {
173         gchar buf[NNTPBUFSIZE];
174         NNTPSession *session;
175         NNTPSockInfo *nntp_sock;
176
177         g_return_val_if_fail(server != NULL, NULL);
178
179         log_message(_("creating NNTP connection to %s:%d ...\n"), server, port);
180
181 #if USE_OPENSSL
182         if (userid && passwd)
183                 nntp_sock = nntp_open_auth(server, port, buf, userid, passwd,
184                                            ssl_type);
185         else
186                 nntp_sock = nntp_open(server, port, buf, ssl_type);
187 #else
188         if (userid && passwd)
189                 nntp_sock = nntp_open_auth(server, port, buf, userid, passwd);
190         else
191                 nntp_sock = nntp_open(server, port, buf);
192 #endif
193
194         if (nntp_sock == NULL)
195                 return NULL;
196
197         session = g_new(NNTPSession, 1);
198         SESSION(session)->type             = SESSION_NEWS;
199         SESSION(session)->server           = g_strdup(server);
200         session->nntp_sock                 = nntp_sock;
201         SESSION(session)->sock             = nntp_sock->sock;
202         SESSION(session)->connected        = TRUE;
203         SESSION(session)->phase            = SESSION_READY;
204         SESSION(session)->last_access_time = time(NULL);
205         SESSION(session)->data             = NULL;
206
207         SESSION(session)->destroy          = news_session_destroy;
208
209         session->group = NULL;
210
211         return SESSION(session);
212 }
213
214 void news_session_destroy(Session *session)
215 {
216         nntp_close(NNTP_SESSION(session)->nntp_sock);
217         NNTP_SESSION(session)->nntp_sock = NULL;
218         session->sock = NULL;
219
220         g_free(NNTP_SESSION(session)->group);
221 }
222
223 static Session *news_session_new_for_folder(Folder *folder)
224 {
225         Session *session;
226         PrefsAccount *ac;
227         const gchar *userid = NULL;
228         gchar *passwd = NULL;
229         gushort port;
230         gchar buf[NNTPBUFSIZE];
231
232         g_return_val_if_fail(folder != NULL, NULL);
233         g_return_val_if_fail(folder->account != NULL, NULL);
234
235         ac = folder->account;
236         if (ac->use_nntp_auth && ac->userid && ac->userid[0]) {
237                 userid = ac->userid;
238                 if (ac->passwd && ac->passwd[0])
239                         passwd = g_strdup(ac->passwd);
240                 else
241                         passwd = input_dialog_query_password(ac->nntp_server,
242                                                              userid);
243         }
244
245 #if USE_OPENSSL
246         port = ac->set_nntpport ? ac->nntpport
247                 : ac->ssl_nntp ? NNTPS_PORT : NNTP_PORT;
248         session = news_session_new(ac->nntp_server, port, userid, passwd,
249                                    ac->ssl_nntp);
250 #else
251         port = ac->set_nntpport ? ac->nntpport : NNTP_PORT;
252         session = news_session_new(ac->nntp_server, port, userid, passwd);
253 #endif
254         if (ac->use_nntp_auth && ac->use_nntp_auth_onconnect)
255                 nntp_forceauth(NNTP_SESSION(session)->nntp_sock, buf, userid, passwd);
256
257         g_free(passwd);
258
259         return session;
260 }
261
262 NNTPSession *news_session_get(Folder *folder)
263 {
264         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
265
266         g_return_val_if_fail(folder != NULL, NULL);
267         g_return_val_if_fail(folder->type == F_NEWS, NULL);
268         g_return_val_if_fail(folder->account != NULL, NULL);
269
270         if (!rfolder->session) {
271                 rfolder->session = news_session_new_for_folder(folder);
272                 return NNTP_SESSION(rfolder->session);
273         }
274
275         if (time(NULL) - rfolder->session->last_access_time < SESSION_TIMEOUT) {
276                 rfolder->session->last_access_time = time(NULL);
277                 return NNTP_SESSION(rfolder->session);
278         }
279
280         if (nntp_mode(NNTP_SESSION(rfolder->session)->nntp_sock, FALSE)
281             != NN_SUCCESS) {
282                 log_warning("NNTP connection to %s:%d has been"
283                               " disconnected. Reconnecting...\n",
284                             folder->account->nntp_server,
285                             folder->account->set_nntpport ?
286                             folder->account->nntpport : NNTP_PORT);
287                 session_destroy(rfolder->session);
288                 rfolder->session = news_session_new_for_folder(folder);
289         }
290
291         if (rfolder->session)
292                 rfolder->session->last_access_time = time(NULL);
293         return NNTP_SESSION(rfolder->session);
294 }
295
296 GSList *news_get_article_list(Folder *folder, FolderItem *item,
297                               gboolean use_cache)
298 {
299         GSList *alist;
300         NNTPSession *session;
301
302         g_return_val_if_fail(folder != NULL, NULL);
303         g_return_val_if_fail(item != NULL, NULL);
304         g_return_val_if_fail(folder->type == F_NEWS, NULL);
305
306         session = news_session_get(folder);
307
308         if (!session) {
309                 alist = procmsg_read_cache(item, FALSE);
310                 item->last_num = procmsg_get_last_num_in_msg_list(alist);
311         } else if (use_cache) {
312                 GSList *newlist;
313                 gint cache_last;
314                 gint first, last;
315
316                 alist = procmsg_read_cache(item, FALSE);
317
318                 cache_last = procmsg_get_last_num_in_msg_list(alist);
319                 newlist = news_get_uncached_articles
320                         (session, item, cache_last, &first, &last);
321                 if (first == 0 && last == 0) {
322                         news_delete_all_articles(item);
323                         procmsg_msg_list_free(alist);
324                         alist = NULL;
325                 } else {
326                         alist = news_delete_old_articles(alist, item, first);
327                         news_delete_expired_caches(alist, item);
328                 }
329
330                 alist = g_slist_concat(alist, newlist);
331
332                 item->last_num = last;
333         } else {
334                 gint last;
335
336                 alist = news_get_uncached_articles
337                         (session, item, 0, NULL, &last);
338                 news_delete_all_articles(item);
339                 item->last_num = last;
340         }
341
342         procmsg_set_flags(alist, item);
343
344         return alist;
345 }
346
347 gchar *news_fetch_msg(Folder *folder, FolderItem *item, gint num)
348 {
349         gchar *path, *filename;
350         NNTPSession *session;
351         gint ok;
352
353         g_return_val_if_fail(folder != NULL, NULL);
354         g_return_val_if_fail(item != NULL, NULL);
355
356         path = folder_item_get_path(item);
357         if (!is_dir_exist(path))
358                 make_dir_hier(path);
359         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
360         g_free(path);
361
362         if (is_file_exist(filename)) {
363                 debug_print("article %d has been already cached.\n", num);
364                 return filename;
365         }
366
367         session = news_session_get(folder);
368         if (!session) {
369                 g_free(filename);
370                 return NULL;
371         }
372
373         ok = news_select_group(session, item->path, NULL, NULL, NULL);
374         if (ok != NN_SUCCESS) {
375                 g_warning("can't select group %s\n", item->path);
376                 g_free(filename);
377                 return NULL;
378         }
379
380         debug_print("getting article %d...\n", num);
381         ok = news_get_article(NNTP_SESSION(REMOTE_FOLDER(folder)->session),
382                               num, filename);
383         if (ok < 0) {
384                 g_warning("can't read article %d\n", num);
385                 session_destroy(SESSION(session));
386                 REMOTE_FOLDER(folder)->session = NULL;
387                 g_free(filename);
388                 return NULL;
389         }
390
391         return filename;
392 }
393
394 gint news_scan_group(Folder *folder, FolderItem *item)
395 {
396         NNTPSession *session;
397         gint num = 0, first = 0, last = 0;
398         gint ok;
399
400         g_return_val_if_fail(folder != NULL, -1);
401         g_return_val_if_fail(item != NULL, -1);
402
403         session = news_session_get(folder);
404         if (!session) return -1;
405
406         ok = news_select_group(session, item->path, &num, &first, &last);
407         if (ok != NN_SUCCESS) {
408                 log_warning("can't set group: %s\n", item->path);
409                 return -1;
410         }
411
412         if (num == 0) {
413                 item->new = item->unread = item->total = item->last_num = 0;
414                 return 0;
415         }
416
417 /*
418         path = folder_item_get_path(item);
419         if (path && is_dir_exist(path)) {
420                 procmsg_get_mark_sum(path, &new, &unread, &total, &min, &max,
421                                      first);
422         }
423         g_free(path);
424
425         if (max < first || last < min)
426                 new = unread = total = num;
427         else {
428                 if (min < first)
429                         min = first;
430
431                 if (last < max)
432                         max = last;
433                 else if (max < last) {
434                         new += last - max;
435                         unread += last - max;
436                 }
437
438                 if (new > num) new = num;
439                 if (unread > num) unread = num;
440         }
441
442         item->new = new;
443         item->unread = unread;
444         item->total = num;
445         item->last_num = last;
446 */
447         return 0;
448 }
449
450 static NewsGroupInfo *news_group_info_new(const gchar *name,
451                                           gint first, gint last, gchar type)
452 {
453         NewsGroupInfo *ginfo;
454
455         ginfo = g_new(NewsGroupInfo, 1);
456         ginfo->name = g_strdup(name);
457         ginfo->first = first;
458         ginfo->last = last;
459         ginfo->type = type;
460
461         return ginfo;
462 }
463
464 static void news_group_info_free(NewsGroupInfo *ginfo)
465 {
466         g_free(ginfo->name);
467         g_free(ginfo);
468 }
469
470 static gint news_group_info_compare(NewsGroupInfo *ginfo1,
471                                     NewsGroupInfo *ginfo2)
472 {
473         return g_strcasecmp(ginfo1->name, ginfo2->name);
474 }
475
476 GSList *news_get_group_list(Folder *folder)
477 {
478         gchar *path, *filename;
479         FILE *fp;
480         GSList *list = NULL;
481         GSList *last = NULL;
482         gchar buf[NNTPBUFSIZE];
483
484         g_return_val_if_fail(folder != NULL, NULL);
485         g_return_val_if_fail(folder->type == F_NEWS, NULL);
486
487         path = folder_item_get_path(FOLDER_ITEM(folder->node->data));
488         if (!is_dir_exist(path))
489                 make_dir_hier(path);
490         filename = g_strconcat(path, G_DIR_SEPARATOR_S, NEWSGROUP_LIST, NULL);
491         g_free(path);
492
493         if ((fp = fopen(filename, "rb")) == NULL) {
494                 NNTPSession *session;
495
496                 session = news_session_get(folder);
497                 if (!session) {
498                         g_free(filename);
499                         return NULL;
500                 }
501
502                 if (nntp_list(session->nntp_sock) != NN_SUCCESS) {
503                         g_free(filename);
504                         return NULL;
505                 }
506                 if (recv_write_to_file(SESSION(session)->sock, filename) < 0) {
507                         log_warning("can't retrieve newsgroup list\n");
508                         session_destroy(SESSION(session));
509                         REMOTE_FOLDER(folder)->session = NULL;
510                         g_free(filename);
511                         return NULL;
512                 }
513
514                 if ((fp = fopen(filename, "rb")) == NULL) {
515                         FILE_OP_ERROR(filename, "fopen");
516                         g_free(filename);
517                         return NULL;
518                 }
519         }
520
521         while (fgets(buf, sizeof(buf), fp) != NULL) {
522                 gchar *p = buf;
523                 gchar *name;
524                 gint last_num;
525                 gint first_num;
526                 gchar type;
527                 NewsGroupInfo *ginfo;
528
529                 p = strchr(p, ' ');
530                 if (!p) continue;
531                 *p = '\0';
532                 p++;
533                 name = buf;
534
535                 if (sscanf(p, "%d %d %c", &last_num, &first_num, &type) < 3)
536                         continue;
537
538                 ginfo = news_group_info_new(name, first_num, last_num, type);
539
540                 if (!last)
541                         last = list = g_slist_append(NULL, ginfo);
542                 else {
543                         last = g_slist_append(last, ginfo);
544                         last = last->next;
545                 }
546         }
547
548         fclose(fp);
549         g_free(filename);
550
551         list = g_slist_sort(list, (GCompareFunc)news_group_info_compare);
552
553         return list;
554 }
555
556 void news_group_list_free(GSList *group_list)
557 {
558         GSList *cur;
559
560         if (!group_list) return;
561
562         for (cur = group_list; cur != NULL; cur = cur->next)
563                 news_group_info_free((NewsGroupInfo *)cur->data);
564         g_slist_free(group_list);
565 }
566
567 void news_remove_group_list_cache(Folder *folder)
568 {
569         gchar *path, *filename;
570
571         g_return_if_fail(folder != NULL);
572         g_return_if_fail(folder->type == F_NEWS);
573
574         path = folder_item_get_path(FOLDER_ITEM(folder->node->data));
575         filename = g_strconcat(path, G_DIR_SEPARATOR_S, NEWSGROUP_LIST, NULL);
576         g_free(path);
577
578         if (is_file_exist(filename)) {
579                 if (remove(filename) < 0)
580                         FILE_OP_ERROR(filename, "remove");
581         }
582         g_free(filename);
583 }
584
585 gint news_post(Folder *folder, const gchar *file)
586 {
587         FILE *fp;
588         gint ok;
589
590         g_return_val_if_fail(folder != NULL, -1);
591         g_return_val_if_fail(folder->type == F_NEWS, -1);
592         g_return_val_if_fail(file != NULL, -1);
593
594         if ((fp = fopen(file, "rb")) == NULL) {
595                 FILE_OP_ERROR(file, "fopen");
596                 return -1;
597         }
598
599         ok = news_post_stream(folder, fp);
600
601         fclose(fp);
602
603         return ok;
604 }
605
606 gint news_post_stream(Folder *folder, FILE *fp)
607 {
608         NNTPSession *session;
609         gint ok;
610
611         g_return_val_if_fail(folder != NULL, -1);
612         g_return_val_if_fail(folder->type == F_NEWS, -1);
613         g_return_val_if_fail(fp != NULL, -1);
614
615         session = news_session_get(folder);
616         if (!session) return -1;
617
618         ok = nntp_post(session->nntp_sock, fp);
619         if (ok != NN_SUCCESS) {
620                 log_warning("can't post article.\n");
621                 return -1;
622         }
623
624         return 0;
625 }
626
627 static gint news_get_article_cmd(NNTPSession *session, const gchar *cmd,
628                                  gint num, gchar *filename)
629 {
630         gchar *msgid;
631
632         if (nntp_get_article(session->nntp_sock, cmd, num, &msgid)
633             != NN_SUCCESS)
634                 return -1;
635
636         debug_print("Message-Id = %s, num = %d\n", msgid, num);
637         g_free(msgid);
638
639         if (recv_write_to_file(session->nntp_sock->sock, filename) < 0) {
640                 log_warning("can't retrieve article %d\n", num);
641                 return -1;
642         }
643
644         return 0;
645 }
646
647 static gint news_remove_msg(Folder *folder, FolderItem *item, gint num)
648 {
649         gchar * dir;
650         gint r;
651
652         dir = folder_item_get_path(item);
653         debug_print("news_remove_msg: removing msg %d in %s\n",num,dir);
654         r = remove_numbered_files(dir, num, num);
655         g_free(dir);
656
657         return r;
658 }
659
660 static gint news_get_article(NNTPSession *session, gint num, gchar *filename)
661 {
662         return news_get_article_cmd(session, "ARTICLE", num, filename);
663 }
664
665 /**
666  * news_select_group:
667  * @session: Active NNTP session.
668  * @group: Newsgroup name.
669  * @num: Estimated number of articles.
670  * @first: First article number.
671  * @last: Last article number.
672  *
673  * Select newsgroup @group with the GROUP command if it is not already
674  * selected in @session, or article numbers need to be returned.
675  *
676  * Return value: NNTP result code.
677  **/
678 static gint news_select_group(NNTPSession *session, const gchar *group,
679                               gint *num, gint *first, gint *last)
680 {
681         gint ok;
682         gint num_, first_, last_;
683
684         if (!num || !first || !last) {
685                 if (session->group && g_strcasecmp(session->group, group) == 0)
686                         return NN_SUCCESS;
687                 num = &num_;
688                 first = &first_;
689                 last = &last_;
690         }
691
692         g_free(session->group);
693         session->group = NULL;
694
695         ok = nntp_group(session->nntp_sock, group, num, first, last);
696         if (ok == NN_SUCCESS)
697                 session->group = g_strdup(group);
698
699         return ok;
700 }
701
702 static GSList *news_get_uncached_articles(NNTPSession *session,
703                                           FolderItem *item, gint cache_last,
704                                           gint *rfirst, gint *rlast)
705 {
706         gint ok;
707         gint num = 0, first = 0, last = 0, begin = 0, end = 0;
708         gchar buf[NNTPBUFSIZE];
709         GSList *newlist = NULL;
710         GSList *llast = NULL;
711         MsgInfo *msginfo;
712
713         if (rfirst) *rfirst = -1;
714         if (rlast)  *rlast  = -1;
715
716         g_return_val_if_fail(session != NULL, NULL);
717         g_return_val_if_fail(item != NULL, NULL);
718         g_return_val_if_fail(item->folder != NULL, NULL);
719         g_return_val_if_fail(item->folder->type == F_NEWS, NULL);
720
721         ok = news_select_group(session, item->path, &num, &first, &last);
722         if (ok != NN_SUCCESS) {
723                 log_warning("can't set group: %s\n", item->path);
724                 return NULL;
725         }
726
727         /* calculate getting overview range */
728         if (first > last) {
729                 log_warning("invalid article range: %d - %d\n",
730                             first, last);
731                 return NULL;
732         }
733
734         if (rfirst) *rfirst = first;
735         if (rlast)  *rlast  = last;
736
737         if (cache_last < first)
738                 begin = first;
739         else if (last < cache_last)
740                 begin = first;
741         else if (last == cache_last) {
742                 debug_print("no new articles.\n");
743                 return NULL;
744         } else
745                 begin = cache_last + 1;
746         end = last;
747
748         if (prefs_common.max_articles > 0 &&
749             end - begin + 1 > prefs_common.max_articles)
750                 begin = end - prefs_common.max_articles + 1;
751
752         log_message(_("getting xover %d - %d in %s...\n"),
753                     begin, end, item->path);
754         if (nntp_xover(session->nntp_sock, begin, end) != NN_SUCCESS) {
755                 log_warning("can't get xover\n");
756                 return NULL;
757         }
758
759         for (;;) {
760                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
761                         log_warning("error occurred while getting xover.\n");
762                         return newlist;
763                 }
764
765                 if (buf[0] == '.' && buf[1] == '\r') break;
766
767                 msginfo = news_parse_xover(buf);
768                 if (!msginfo) {
769                         log_warning("invalid xover line: %s\n", buf);
770                         continue;
771                 }
772
773                 msginfo->folder = item;
774                 msginfo->flags.perm_flags = MSG_NEW|MSG_UNREAD;
775                 msginfo->flags.tmp_flags = MSG_NEWS;
776                 msginfo->newsgroups = g_strdup(item->path);
777
778                 if (!newlist)
779                         llast = newlist = g_slist_append(newlist, msginfo);
780                 else {
781                         llast = g_slist_append(llast, msginfo);
782                         llast = llast->next;
783                 }
784         }
785
786         if (nntp_xhdr(session->nntp_sock, "to", begin, end) != NN_SUCCESS) {
787                 log_warning("can't get xhdr\n");
788                 return newlist;
789         }
790
791         llast = newlist;
792
793         for (;;) {
794                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
795                         log_warning("error occurred while getting xhdr.\n");
796                         return newlist;
797                 }
798
799                 if (buf[0] == '.' && buf[1] == '\r') break;
800                 if (!llast) {
801                         g_warning("llast == NULL\n");
802                         continue;
803                 }
804
805                 msginfo = (MsgInfo *)llast->data;
806                 msginfo->to = news_parse_xhdr(buf, msginfo);
807
808                 llast = llast->next;
809         }
810
811         if (nntp_xhdr(session->nntp_sock, "cc", begin, end) != NN_SUCCESS) {
812                 log_warning("can't get xhdr\n");
813                 return newlist;
814         }
815
816         llast = newlist;
817
818         for (;;) {
819                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
820                         log_warning("error occurred while getting xhdr.\n");
821                         return newlist;
822                 }
823
824                 if (buf[0] == '.' && buf[1] == '\r') break;
825                 if (!llast) {
826                         g_warning("llast == NULL\n");
827                         continue;
828                 }
829
830                 msginfo = (MsgInfo *)llast->data;
831                 msginfo->cc = news_parse_xhdr(buf, msginfo);
832
833                 llast = llast->next;
834         }
835
836         return newlist;
837 }
838
839 #define PARSE_ONE_PARAM(p, srcp) \
840 { \
841         p = strchr(srcp, '\t'); \
842         if (!p) return NULL; \
843         else \
844                 *p++ = '\0'; \
845 }
846
847 static MsgInfo *news_parse_xover(const gchar *xover_str)
848 {
849         MsgInfo *msginfo;
850         gchar buf[NNTPBUFSIZE];
851         gchar *subject, *sender, *size, *line, *date, *msgid, *ref, *tmp, *xref;
852         gchar *p;
853         gint num, size_int, line_int;
854         gchar *xover_buf;
855
856         Xstrdup_a(xover_buf, xover_str, return NULL);
857
858         PARSE_ONE_PARAM(subject, xover_buf);
859         PARSE_ONE_PARAM(sender, subject);
860         PARSE_ONE_PARAM(date, sender);
861         PARSE_ONE_PARAM(msgid, date);
862         PARSE_ONE_PARAM(ref, msgid);
863         PARSE_ONE_PARAM(size, ref);
864         PARSE_ONE_PARAM(line, size);
865         PARSE_ONE_PARAM(xref, line);
866
867         tmp = strchr(xref, '\t');
868         if (!tmp) tmp = strchr(line, '\r');
869         if (!tmp) tmp = strchr(line, '\n');
870         if (tmp) *tmp = '\0';
871
872         num = atoi(xover_str);
873         size_int = atoi(size);
874         line_int = atoi(line);
875
876         /* set MsgInfo */
877         msginfo = procmsg_msginfo_new();
878         msginfo->msgnum = num;
879         msginfo->size = size_int;
880
881         msginfo->date = g_strdup(date);
882         msginfo->date_t = procheader_date_parse(NULL, date, 0);
883
884         conv_unmime_header(buf, sizeof(buf), sender, NULL);
885         msginfo->from = g_strdup(buf);
886         msginfo->fromname = procheader_get_fromname(buf);
887
888         conv_unmime_header(buf, sizeof(buf), subject, NULL);
889         msginfo->subject = g_strdup(buf);
890
891         extract_parenthesis(msgid, '<', '>');
892         remove_space(msgid);
893         if (*msgid != '\0')
894                 msginfo->msgid = g_strdup(msgid);
895
896         msginfo->references = g_strdup(ref);
897         eliminate_parenthesis(ref, '(', ')');
898         if ((p = strrchr(ref, '<')) != NULL) {
899                 extract_parenthesis(p, '<', '>');
900                 remove_space(p);
901                 if (*p != '\0')
902                         msginfo->inreplyto = g_strdup(p);
903         }
904
905         msginfo->xref = g_strdup(xref);
906         p = msginfo->xref+strlen(msginfo->xref) - 1;
907         while (*p == '\r' || *p == '\n') {
908                 *p = '\0';
909                 p--;
910         }
911
912         return msginfo;
913 }
914
915 static gchar *news_parse_xhdr(const gchar *xhdr_str, MsgInfo *msginfo)
916 {
917         gchar *p;
918         gchar *tmp;
919         gint num;
920
921         p = strchr(xhdr_str, ' ');
922         if (!p)
923                 return NULL;
924         else
925                 p++;
926
927         num = atoi(xhdr_str);
928         if (msginfo->msgnum != num) return NULL;
929
930         tmp = strchr(p, '\r');
931         if (!tmp) tmp = strchr(p, '\n');
932
933         if (tmp)
934                 return g_strndup(p, tmp - p);
935         else
936                 return g_strdup(p);
937 }
938
939 static GSList *news_delete_old_articles(GSList *alist, FolderItem *item,
940                                         gint first)
941 {
942         GSList *cur, *next;
943         MsgInfo *msginfo;
944         gchar *dir;
945
946         g_return_val_if_fail(item != NULL, alist);
947         g_return_val_if_fail(item->folder != NULL, alist);
948         g_return_val_if_fail(item->folder->type == F_NEWS, alist);
949
950         if (first < 2) return alist;
951
952         debug_print("Deleting cached articles 1 - %d ...\n", first - 1);
953
954         dir = folder_item_get_path(item);
955         remove_numbered_files(dir, 1, first - 1);
956         g_free(dir);
957
958         for (cur = alist; cur != NULL; ) {
959                 next = cur->next;
960
961                 msginfo = (MsgInfo *)cur->data;
962                 if (msginfo && msginfo->msgnum < first) {
963                         procmsg_msginfo_free(msginfo);
964                         alist = g_slist_remove(alist, msginfo);
965                 }
966
967                 cur = next;
968         }
969
970         return alist;
971 }
972
973 static void news_delete_all_articles(FolderItem *item)
974 {
975         gchar *dir;
976
977         g_return_if_fail(item != NULL);
978         g_return_if_fail(item->folder != NULL);
979         g_return_if_fail(item->folder->type == F_NEWS);
980
981         debug_print("Deleting all cached articles...\n");
982
983         dir = folder_item_get_path(item);
984         remove_all_numbered_files(dir);
985         g_free(dir);
986 }
987
988 static void news_delete_expired_caches(GSList *alist, FolderItem *item)
989 {
990         gchar *dir;
991
992         g_return_if_fail(item != NULL);
993         g_return_if_fail(item->folder != NULL);
994         g_return_if_fail(item->folder->type == F_NEWS);
995
996         debug_print("Deleting expired cached articles...\n");
997
998         dir = folder_item_get_path(item);
999         remove_expired_files(dir, 24 * 7);
1000         g_free(dir);
1001 }
1002
1003 gint news_cancel_article(Folder * folder, MsgInfo * msginfo)
1004 {
1005         gchar * tmp;
1006         FILE * tmpfp;
1007         gchar buf[BUFFSIZE];
1008
1009         tmp = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
1010                               G_DIR_SEPARATOR, (gint)msginfo);
1011         if (tmp == NULL)
1012                 return -1;
1013
1014         if ((tmpfp = fopen(tmp, "wb")) == NULL) {
1015                 FILE_OP_ERROR(tmp, "fopen");
1016                 return -1;
1017         }
1018         if (change_file_mode_rw(tmpfp, tmp) < 0) {
1019                 FILE_OP_ERROR(tmp, "chmod");
1020                 g_warning("can't change file mode\n");
1021         }
1022         
1023         fprintf(tmpfp, "From: %s\r\n", msginfo->from);
1024         fprintf(tmpfp, "Newsgroups: %s\r\n", msginfo->newsgroups);
1025         fprintf(tmpfp, "Subject: cmsg cancel <%s>\r\n", msginfo->msgid);
1026         fprintf(tmpfp, "Control: cancel <%s>\r\n", msginfo->msgid);
1027         fprintf(tmpfp, "Approved: %s\r\n", msginfo->from);
1028         fprintf(tmpfp, "X-Cancelled-by: %s\r\n", msginfo->from);
1029         get_rfc822_date(buf, sizeof(buf));
1030         fprintf(tmpfp, "Date: %s\r\n", buf);
1031         fprintf(tmpfp, "\r\n");
1032         fprintf(tmpfp, "removed with sylpheed\r\n");
1033
1034         fclose(tmpfp);
1035
1036         news_post(folder, tmp);
1037         remove(tmp);
1038
1039         g_free(tmp);
1040
1041         return 0;
1042 }
1043
1044 gint news_get_num_list(Folder *folder, FolderItem *item, GSList **msgnum_list)
1045 {
1046         NNTPSession *session;
1047         gint i, ok, num, first, last, nummsgs = 0;
1048         gchar *dir;
1049
1050         g_return_val_if_fail(item != NULL, -1);
1051         g_return_val_if_fail(item->folder != NULL, -1);
1052         g_return_val_if_fail(item->folder->type == F_NEWS, -1);
1053
1054         session = news_session_get(folder);
1055         g_return_val_if_fail(session != NULL, -1);
1056
1057         ok = news_select_group(session, item->path, &num, &first, &last);
1058         if (ok != NN_SUCCESS) {
1059                 log_warning(_("can't set group: %s\n"), item->path);
1060                 return -1;
1061         }
1062
1063         if(last < first) {
1064                 log_warning(_("invalid article range: %d - %d\n"),
1065                             first, last);
1066                 return 0;
1067         }
1068
1069         for(i = first; i <= last; i++) {
1070                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(i));
1071                 nummsgs++;
1072         }
1073
1074         dir = folder_item_get_path(item);
1075         debug_print("removing old messages from %d to %d in %s\n", first, last, dir);
1076         remove_numbered_files(dir, 1, first - 1);
1077         g_free(dir);
1078
1079         return nummsgs;
1080 }
1081
1082 #define READ_TO_LISTEND(hdr) \
1083         while (!(buf[0] == '.' && buf[1] == '\r')) { \
1084                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) { \
1085                         log_warning(_("error occurred while getting %s.\n"), hdr); \
1086                         return msginfo; \
1087                 } \
1088         }
1089
1090 MsgInfo *news_get_msginfo(Folder *folder, FolderItem *item, gint num)
1091 {
1092         NNTPSession *session;
1093         MsgInfo *msginfo = NULL;
1094         gchar buf[NNTPBUFSIZE];
1095
1096         session = news_session_get(folder);
1097         g_return_val_if_fail(session != NULL, NULL);
1098         g_return_val_if_fail(item != NULL, NULL);
1099         g_return_val_if_fail(item->folder != NULL, NULL);
1100         g_return_val_if_fail(item->folder->type == F_NEWS, NULL);
1101
1102         log_message(_("getting xover %d in %s...\n"),
1103                     num, item->path);
1104         if (nntp_xover(session->nntp_sock, num, num) != NN_SUCCESS) {
1105                 log_warning(_("can't get xover\n"));
1106                 return NULL;
1107         }
1108         
1109         if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1110                 log_warning(_("error occurred while getting xover.\n"));
1111                 return NULL;
1112         }
1113         
1114         msginfo = news_parse_xover(buf);
1115         if (!msginfo) {
1116                 log_warning(_("invalid xover line: %s\n"), buf);
1117         }
1118
1119         READ_TO_LISTEND("xover");
1120
1121         if(!msginfo)
1122                 return NULL;
1123         
1124         msginfo->folder = item;
1125         msginfo->flags.perm_flags = MSG_NEW|MSG_UNREAD;
1126         msginfo->flags.tmp_flags = MSG_NEWS;
1127         msginfo->newsgroups = g_strdup(item->path);
1128
1129         if (nntp_xhdr(session->nntp_sock, "to", num, num) != NN_SUCCESS) {
1130                 log_warning(_("can't get xhdr\n"));
1131                 return msginfo;
1132         }
1133
1134         if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1135                 log_warning(_("error occurred while getting xhdr.\n"));
1136                 return msginfo;
1137         }
1138
1139         msginfo->to = news_parse_xhdr(buf, msginfo);
1140
1141         READ_TO_LISTEND("xhdr (to)");
1142
1143         if (nntp_xhdr(session->nntp_sock, "cc", num, num) != NN_SUCCESS) {
1144                 log_warning(_("can't get xhdr\n"));
1145                 return msginfo;
1146         }
1147
1148         if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1149                 log_warning(_("error occurred while getting xhdr.\n"));
1150                 return msginfo;
1151         }
1152
1153         msginfo->cc = news_parse_xhdr(buf, msginfo);
1154
1155         READ_TO_LISTEND("xhdr (cc)");
1156
1157         return msginfo;
1158 }
1159
1160 static GSList *news_get_msginfos_for_range(NNTPSession *session, FolderItem *item, guint begin, guint end)
1161 {
1162         gchar buf[NNTPBUFSIZE];
1163         GSList *newlist = NULL;
1164         GSList *llast = NULL;
1165         MsgInfo *msginfo;
1166
1167         g_return_val_if_fail(session != NULL, NULL);
1168         g_return_val_if_fail(item != NULL, NULL);
1169
1170         log_message(_("getting xover %d - %d in %s...\n"),
1171                     begin, end, item->path);
1172         if (nntp_xover(session->nntp_sock, begin, end) != NN_SUCCESS) {
1173                 log_warning(_("can't get xover\n"));
1174                 return NULL;
1175         }
1176
1177         for (;;) {
1178                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1179                         log_warning(_("error occurred while getting xover.\n"));
1180                         return newlist;
1181                 }
1182
1183                 if (buf[0] == '.' && buf[1] == '\r') break;
1184
1185                 msginfo = news_parse_xover(buf);
1186                 if (!msginfo) {
1187                         log_warning(_("invalid xover line: %s\n"), buf);
1188                         continue;
1189                 }
1190
1191                 msginfo->folder = item;
1192                 msginfo->flags.perm_flags = MSG_NEW|MSG_UNREAD;
1193                 msginfo->flags.tmp_flags = MSG_NEWS;
1194                 msginfo->newsgroups = g_strdup(item->path);
1195
1196                 if (!newlist)
1197                         llast = newlist = g_slist_append(newlist, msginfo);
1198                 else {
1199                         llast = g_slist_append(llast, msginfo);
1200                         llast = llast->next;
1201                 }
1202         }
1203
1204         if (nntp_xhdr(session->nntp_sock, "to", begin, end) != NN_SUCCESS) {
1205                 log_warning(_("can't get xhdr\n"));
1206                 return newlist;
1207         }
1208
1209         llast = newlist;
1210
1211         for (;;) {
1212                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1213                         log_warning(_("error occurred while getting xhdr.\n"));
1214                         return newlist;
1215                 }
1216
1217                 if (buf[0] == '.' && buf[1] == '\r') break;
1218                 if (!llast) {
1219                         g_warning("llast == NULL\n");
1220                         continue;
1221                 }
1222
1223                 msginfo = (MsgInfo *)llast->data;
1224                 msginfo->to = news_parse_xhdr(buf, msginfo);
1225
1226                 llast = llast->next;
1227         }
1228
1229         if (nntp_xhdr(session->nntp_sock, "cc", begin, end) != NN_SUCCESS) {
1230                 log_warning(_("can't get xhdr\n"));
1231                 return newlist;
1232         }
1233
1234         llast = newlist;
1235
1236         for (;;) {
1237                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
1238                         log_warning(_("error occurred while getting xhdr.\n"));
1239                         return newlist;
1240                 }
1241
1242                 if (buf[0] == '.' && buf[1] == '\r') break;
1243                 if (!llast) {
1244                         g_warning("llast == NULL\n");
1245                         continue;
1246                 }
1247
1248                 msginfo = (MsgInfo *)llast->data;
1249                 msginfo->cc = news_parse_xhdr(buf, msginfo);
1250
1251                 llast = llast->next;
1252         }
1253
1254         return newlist;
1255 }
1256
1257 gint news_fetch_msgnum_sort(gconstpointer a, gconstpointer b)
1258 {
1259         return (GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b));
1260 }
1261
1262 GSList *news_get_msginfos(Folder *folder, FolderItem *item, GSList *msgnum_list)
1263 {
1264         NNTPSession *session;
1265         GSList *elem, *msginfo_list = NULL, *tmp_msgnum_list, *tmp_msginfo_list;
1266         guint first, last, next;
1267         
1268         g_return_val_if_fail(folder != NULL, NULL);
1269         g_return_val_if_fail(folder->type == F_NEWS, NULL);
1270         g_return_val_if_fail(msgnum_list != NULL, NULL);
1271         g_return_val_if_fail(item != NULL, NULL);
1272         
1273         session = news_session_get(folder);
1274         g_return_val_if_fail(session != NULL, NULL);
1275
1276         tmp_msgnum_list = g_slist_copy(msgnum_list);
1277         tmp_msgnum_list = g_slist_sort(tmp_msgnum_list, news_fetch_msgnum_sort);
1278
1279         first = GPOINTER_TO_INT(tmp_msgnum_list->data);
1280         last = first;
1281         for(elem = g_slist_next(tmp_msgnum_list); elem != NULL; elem = g_slist_next(elem)) {
1282                 next = GPOINTER_TO_INT(elem->data);
1283                 if(next != (last + 1)) {
1284                         tmp_msginfo_list = news_get_msginfos_for_range(session, item, first, last);
1285                         msginfo_list = g_slist_concat(msginfo_list, tmp_msginfo_list);
1286                         first = next;
1287                 }
1288                 last = next;
1289         }
1290         tmp_msginfo_list = news_get_msginfos_for_range(session, item, first, last);
1291         msginfo_list = g_slist_concat(msginfo_list, tmp_msginfo_list);
1292
1293         g_slist_free(tmp_msgnum_list);
1294         
1295         return msginfo_list;
1296 }