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