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