8f843388f9f8f738f51ecd94c015c548dc468be6
[claws.git] / src / news.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999,2000 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <dirent.h>
29 #include <unistd.h>
30
31 #include "defs.h"
32 #include "intl.h"
33 #include "news.h"
34 #include "nntp.h"
35 #include "socket.h"
36 #include "recv.h"
37 #include "procmsg.h"
38 #include "procheader.h"
39 #include "folder.h"
40 #include "session.h"
41 #include "statusbar.h"
42 #include "codeconv.h"
43 #include "utils.h"
44 #include "prefs_common.h"
45 #include "prefs_account.h"
46 #include "inputdialog.h"
47 #include "alertpanel.h"
48
49 static gint news_get_article_cmd         (NNTPSession   *session,
50                                           const gchar   *cmd,
51                                           gint           num,
52                                           gchar         *filename);
53 static gint news_get_article             (NNTPSession   *session,
54                                           gint           num,
55                                           gchar         *filename);
56 static gint news_get_header              (NNTPSession   *session,
57                                           gint           num,
58                                           gchar         *filename);
59
60 static GSList *news_get_uncached_articles(NNTPSession   *session,
61                                           FolderItem    *item,
62                                           gint           cache_last,
63                                           gint          *rfirst,
64                                           gint          *rlast);
65 static MsgInfo *news_parse_xover         (const gchar   *xover_str);
66 static GSList *news_delete_old_article   (GSList        *alist,
67                                           gint           first);
68 static void news_delete_all_article      (FolderItem    *item);
69
70
71 Session *news_session_new(const gchar *server, gushort port)
72 {
73         gchar buf[NNTPBUFSIZE];
74         NNTPSession *session;
75         gint nntp_sock;
76
77         g_return_val_if_fail(server != NULL, NULL);
78
79         log_message(_("creating NNTP connection to %s:%d ...\n"), server, port);
80
81         if ((nntp_sock = nntp_open(server, port, buf)) < 0)
82                 return NULL;
83
84         session = g_new(NNTPSession, 1);
85         SESSION(session)->type      = SESSION_NEWS;
86         SESSION(session)->server    = g_strdup(server);
87         SESSION(session)->sock      = nntp_sock;
88         SESSION(session)->connected = TRUE;
89         SESSION(session)->phase     = SESSION_READY;
90         SESSION(session)->data      = NULL;
91         session->group = NULL;
92
93         return SESSION(session);
94 }
95
96 void news_session_destroy(NNTPSession *session)
97 {
98         close(SESSION(session)->sock);
99
100         g_free(session->group);
101 }
102
103 NNTPSession *news_session_get(Folder *folder)
104 {
105         g_return_val_if_fail(folder != NULL, NULL);
106         g_return_val_if_fail(folder->type == F_NEWS, NULL);
107         g_return_val_if_fail(folder->account != NULL, NULL);
108
109         if (!REMOTE_FOLDER(folder)->session) {
110                 REMOTE_FOLDER(folder)->session =
111                         news_session_new(folder->account->nntp_server, 119);
112         } else {
113                 if (nntp_mode(REMOTE_FOLDER(folder)->session->sock, FALSE)
114                     != NN_SUCCESS) {
115                         log_warning(_("NNTP connection to %s:%d has been"
116                                       " disconnected. Reconnecting...\n"),
117                                     folder->account->nntp_server, 119);
118                         session_destroy(REMOTE_FOLDER(folder)->session);
119                         REMOTE_FOLDER(folder)->session =
120                                 news_session_new(folder->account->nntp_server,
121                                                  119);
122                 }
123         }
124
125         return NNTP_SESSION(REMOTE_FOLDER(folder)->session);
126 }
127
128 GSList *news_get_article_list(Folder *folder, FolderItem *item,
129                               gboolean use_cache)
130 {
131         GSList *alist;
132         NNTPSession *session;
133
134         g_return_val_if_fail(folder != NULL, NULL);
135         g_return_val_if_fail(item != NULL, NULL);
136         g_return_val_if_fail(folder->type == F_NEWS, NULL);
137
138         session = news_session_get(folder);
139
140         if (!session) {
141                 alist = procmsg_read_cache(item, FALSE);
142                 item->last_num = procmsg_get_last_num_in_cache(alist);
143         } else if (use_cache) {
144                 GSList *newlist;
145                 gint cache_last;
146                 gint first, last;
147
148                 alist = procmsg_read_cache(item, FALSE);
149
150                 cache_last = procmsg_get_last_num_in_cache(alist);
151                 newlist = news_get_uncached_articles
152                         (session, item, cache_last, &first, &last);
153                 alist = news_delete_old_article(alist, first);
154
155                 alist = g_slist_concat(alist, newlist);
156                 item->last_num = last;
157         } else {
158                 gint last;
159
160                 alist = news_get_uncached_articles
161                         (session, item, 0, NULL, &last);
162                 news_delete_all_article(item);
163                 item->last_num = last;
164         }
165
166         procmsg_set_flags(alist, item);
167
168         statusbar_pop_all();
169
170         return alist;
171 }
172
173 gchar *news_fetch_msg(Folder *folder, FolderItem *item, gint num)
174 {
175         gchar *path, *filename;
176         gint ok;
177
178         g_return_val_if_fail(folder != NULL, NULL);
179         g_return_val_if_fail(item != NULL, NULL);
180
181         path = folder_item_get_path(item);
182         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
183         g_free(path);
184
185         if (is_file_exist(filename)) {
186                 debug_print(_("article %d has been already cached.\n"), num);
187                 return filename;
188         }
189
190         if (!REMOTE_FOLDER(folder)->session) {
191                 g_free(filename);
192                 return NULL;
193         }
194
195         debug_print(_("getting article %d...\n"), num);
196         ok = news_get_article(NNTP_SESSION(REMOTE_FOLDER(folder)->session),
197                               num, filename);
198         statusbar_pop_all();
199         if (ok < 0) {
200                 g_warning(_("can't read article %d\n"), num);
201                 g_free(filename);
202                 return NULL;
203         }
204
205         return filename;
206 }
207
208 void news_scan_group(Folder *folder, FolderItem *item)
209 {
210 }
211
212 gint news_post(Folder *folder, const gchar *file)
213 {
214         NNTPSession *session;
215         FILE *fp;
216         gint ok;
217
218         g_return_val_if_fail(folder != NULL, -1);
219         g_return_val_if_fail(folder->type == F_NEWS, -1);
220         g_return_val_if_fail(file != NULL, -1);
221
222         session = news_session_get(folder);
223         if (!session) return -1;
224
225         if ((fp = fopen(file, "r")) == NULL) {
226                 FILE_OP_ERROR(file, "fopen");
227                 return -1;
228         }
229
230         ok = nntp_post(SESSION(session)->sock, fp);
231         if (ok != NN_SUCCESS) {
232                 log_warning(_("can't post article.\n"));
233                 return -1;
234         }
235
236         fclose(fp);
237
238         statusbar_pop_all();
239
240         return 0;
241 }
242
243 static gint news_get_article_cmd(NNTPSession *session, const gchar *cmd,
244                                  gint num, gchar *filename)
245 {
246         gchar *msgid;
247
248         if (nntp_get_article(SESSION(session)->sock, cmd, num, &msgid)
249             != NN_SUCCESS)
250                 return -1;
251
252         debug_print("Message-Id = %s, num = %d\n", msgid, num);
253         g_free(msgid);
254
255         if (recv_write_to_file(SESSION(session)->sock, filename) < 0) {
256                 log_warning(_("can't retrieve article %d\n"), num);
257                 return -1;
258         }
259
260         return 0;
261 }
262
263 static gint news_get_article(NNTPSession *session, gint num, gchar *filename)
264 {
265         return news_get_article_cmd(session, "ARTICLE", num, filename);
266 }
267
268 static gint news_get_header(NNTPSession *session, gint num, gchar *filename)
269 {
270         return news_get_article_cmd(session, "HEAD", num, filename);
271 }
272
273 static gchar *news_query_password(NNTPSession *session,
274                                   const gchar *user)
275 {
276         gchar *message;
277         gchar *pass;
278
279         message = g_strdup_printf
280                 (_("Input password for %s on %s:"),
281                  user,
282                  SESSION(session)->server);
283
284         pass = input_dialog_with_invisible(_("Input password"),
285                                            message, NULL);
286         g_free(message);
287 /*      manage_window_focus_in(inc_dialog->mainwin->window, */
288 /*                             NULL, NULL); */
289         return pass;
290 }
291
292 static gint news_authenticate(NNTPSession *session,
293                               FolderItem *item)
294 {
295         gint ok;
296         const gchar *user;
297         gchar *pass;
298         gboolean need_free_pass = FALSE;
299
300         debug_print(_("news server requested authentication\n"));
301         if (!item || !item->folder || !item->folder->account)
302                 return NN_ERROR;
303         user = item->folder->account->userid;
304         if (!user)
305                 return NN_ERROR;
306         ok = nntp_authinfo_user(SESSION(session)->sock, user);
307         if (ok == NN_AUTHCONT) {
308                 pass = item->folder->account->passwd;
309                 if (!pass || !pass[0]) {
310                         pass = news_query_password(session, user);
311                         need_free_pass = TRUE;
312                 }
313                 ok = nntp_authinfo_pass(SESSION(session)->sock, pass);
314                 if (need_free_pass)
315                         g_free(pass);
316         }
317         if (ok != NN_SUCCESS) {
318                 log_warning(_("NNTP authentication failed\n"));
319                 alertpanel_error(_("Authentication for %s on %s failed."),
320                                  user, SESSION(session)->server);
321         }
322         return ok;
323 }
324
325 static GSList *news_get_uncached_articles(NNTPSession *session,
326                                           FolderItem *item, gint cache_last,
327                                           gint *rfirst, gint *rlast)
328 {
329         gint ok;
330         gint num = 0, first = 0, last = 0, begin = 0, end = 0;
331         gchar buf[NNTPBUFSIZE];
332         GSList *newlist = NULL;
333         GSList *llast = NULL;
334         MsgInfo *msginfo;
335
336         if (rfirst) *rfirst = 0;
337         if (rlast)  *rlast  = 0;
338
339         g_return_val_if_fail(session != NULL, NULL);
340         g_return_val_if_fail(item != NULL, NULL);
341         g_return_val_if_fail(item->folder != NULL, NULL);
342         g_return_val_if_fail(item->folder->type == F_NEWS, NULL);
343
344         ok = nntp_group(SESSION(session)->sock, item->path,
345                         &num, &first, &last);
346         if (ok == NN_AUTHREQ) {
347                 ok = news_authenticate(session, item);
348                 if (ok != NN_SUCCESS)
349                         return NULL;
350                 ok = nntp_group(SESSION(session)->sock, item->path,
351                                 &num, &first, &last);
352         }
353         if (ok != NN_SUCCESS) {
354                 log_warning(_("can't set group: %s\n"), item->path);
355                 return NULL;
356         }
357
358         /* calculate getting overview range */
359         if (first > last) {
360                 log_warning(_("invalid article range: %d - %d\n"),
361                             first, last);
362                 return NULL;
363         }
364         if (cache_last < first)
365                 begin = first;
366         else if (last < cache_last)
367                 begin = first;
368         else if (last == cache_last) {
369                 debug_print(_("no new articles.\n"));
370                 return NULL;
371         } else
372                 begin = cache_last + 1;
373         end = last;
374
375         if (prefs_common.max_articles > 0 &&
376             end - begin + 1 > prefs_common.max_articles)
377                 begin = end - prefs_common.max_articles + 1;
378
379         log_message(_("getting xover %d - %d in %s...\n"),
380                     begin, end, item->path);
381         if (nntp_xover(SESSION(session)->sock, begin, end) != NN_SUCCESS) {
382                 log_warning(_("can't get xover\n"));
383                 return NULL;
384         }
385
386         for (;;) {
387                 if (sock_read(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
388                         log_warning(_("error occurred while getting xover.\n"));
389                         return newlist;
390                 }
391
392                 if (buf[0] == '.' && buf[1] == '\r') break;
393
394                 msginfo = news_parse_xover(buf);
395                 if (!msginfo) {
396                         log_warning(_("invalid xover line: %s\n"), buf);
397                         continue;
398                 }
399
400                 msginfo->folder = item;
401                 msginfo->flags = MSG_NEW|MSG_UNREAD|MSG_NEWS;
402
403                 if (!newlist)
404                         llast = newlist = g_slist_append(newlist, msginfo);
405                 else {
406                         llast = g_slist_append(llast, msginfo);
407                         llast = llast->next;
408                 }
409         }
410
411         if (rfirst) *rfirst = first;
412         if (rlast)  *rlast  = last;
413         return newlist;
414 }
415
416 #define PARSE_ONE_PARAM(p, srcp) \
417 { \
418         p = strchr(srcp, '\t'); \
419         if (!p) return NULL; \
420         else \
421                 *p++ = '\0'; \
422 }
423
424 static MsgInfo *news_parse_xover(const gchar *xover_str)
425 {
426         MsgInfo *msginfo;
427         gchar buf[NNTPBUFSIZE];
428         gchar *subject, *sender, *size, *line, *date, *msgid, *ref, *tmp;
429         gchar *p;
430         gint num, size_int, line_int;
431         gchar *xover_buf;
432
433         Xalloca(xover_buf, strlen(xover_str) + 1, return NULL);
434         strcpy(xover_buf, xover_str);
435
436         PARSE_ONE_PARAM(subject, xover_buf);
437         PARSE_ONE_PARAM(sender, subject);
438         PARSE_ONE_PARAM(date, sender);
439         PARSE_ONE_PARAM(msgid, date);
440         PARSE_ONE_PARAM(ref, msgid);
441         PARSE_ONE_PARAM(size, ref);
442         PARSE_ONE_PARAM(line, size);
443
444         tmp = strchr(line, '\t');
445         if (!tmp) tmp = strchr(line, '\r');
446         if (!tmp) tmp = strchr(line, '\n');
447         if (tmp) *tmp = '\0';
448
449         num = atoi(xover_str);
450         size_int = atoi(size);
451         line_int = atoi(line);
452
453         /* set MsgInfo */
454         msginfo = g_new0(MsgInfo, 1);
455         msginfo->msgnum = num;
456         msginfo->size = size_int;
457
458         msginfo->date = g_strdup(date);
459         msginfo->date_t = procheader_date_parse(NULL, date, 0);
460
461         conv_unmime_header(buf, sizeof(buf), sender, NULL);
462         msginfo->from = g_strdup(buf);
463         msginfo->fromname = procheader_get_fromname(buf);
464
465         conv_unmime_header(buf, sizeof(buf), subject, NULL);
466         msginfo->subject = g_strdup(buf);
467
468         extract_parenthesis(msgid, '<', '>');
469         remove_space(msgid);
470         if (*msgid != '\0')
471                 msginfo->msgid = g_strdup(msgid);
472
473         eliminate_parenthesis(ref, '(', ')');
474         if ((p = strrchr(ref, '<')) != NULL) {
475                 extract_parenthesis(p, '<', '>');
476                 remove_space(p);
477                 if (*p != '\0')
478                         msginfo->inreplyto = g_strdup(p);
479         }
480
481         return msginfo;
482 }
483
484 static GSList *news_delete_old_article(GSList *alist, gint first)
485 {
486         GSList *cur, *next;
487         MsgInfo *msginfo;
488         gchar *cache_file;
489
490         if (first < 2) return alist;
491
492         for (cur = alist; cur != NULL; ) {
493                 next = cur->next;
494
495                 msginfo = (MsgInfo *)cur->data;
496                 if (msginfo && msginfo->msgnum < first) {
497                         debug_print(_("deleting article %d...\n"),
498                                     msginfo->msgnum);
499
500                         cache_file = procmsg_get_message_file_path(msginfo);
501                         if (is_file_exist(cache_file)) unlink(cache_file);
502                         g_free(cache_file);
503
504                         procmsg_msginfo_free(msginfo);
505                         alist = g_slist_remove(alist, msginfo);
506                 }
507
508                 cur = next;
509         }
510
511         return alist;
512 }
513
514 static void news_delete_all_article(FolderItem *item)
515 {
516         DIR *dp;
517         struct dirent *d;
518         gchar *dir;
519         gchar *file;
520
521         dir = folder_item_get_path(item);
522         if ((dp = opendir(dir)) == NULL) {
523                 FILE_OP_ERROR(dir, "opendir");
524                 g_free(dir);
525                 return;
526         }
527
528         debug_print(_("\tDeleting all cached articles... "));
529
530         while ((d = readdir(dp)) != NULL) {
531                 if (to_number(d->d_name) < 0) continue;
532
533                 file = g_strconcat(dir, G_DIR_SEPARATOR_S, d->d_name, NULL);
534
535                 if (is_file_exist(file)) {
536                         if (unlink(file) < 0)
537                                 FILE_OP_ERROR(file, "unlink");
538                 }
539
540                 g_free(file);
541         }
542
543         closedir(dp);
544         g_free(dir);
545
546         debug_print(_("done.\n"));
547 }
548
549 /*
550   news_get_group_list returns a strings list.
551   These strings are the names of the newsgroups of a server.
552   item is the FolderItem of the news server.
553   The names of the newsgroups are cached into a file so that
554   when the function is called again, there is no need to make
555   a request to the server.
556  */
557
558 GSList * news_get_group_list(FolderItem *item)
559 {
560         gchar *path, *filename;
561         gint ok;
562         NNTPSession *session;
563         GSList * group_list = NULL;
564         FILE * f;
565         gchar buf[NNTPBUFSIZE];
566         int len;
567
568         if (item == NULL)
569           return NULL;
570
571         path = folder_item_get_path(item);
572
573         if (!is_dir_exist(path))
574                 make_dir_hier(path);
575
576         filename = g_strconcat(path, G_DIR_SEPARATOR_S, GROUPLIST_FILE, NULL);
577         g_free(path);
578
579         session = news_session_get(item->folder);
580
581         if (session == NULL)
582           return NULL;
583
584         if (is_file_exist(filename)) {
585                 debug_print(_("group list has been already cached.\n"));
586         }
587         else
588           {
589             ok = nntp_list(SESSION(session)->sock);
590             if (ok != NN_SUCCESS)
591               return NULL;
592             
593             if (recv_write_to_file(SESSION(session)->sock, filename)
594                 < 0) {
595               log_warning(_("can't retrieve group list\n"));
596               return NULL;
597             }
598           }
599
600         f = fopen(filename, "r");
601         while (fgets(buf, NNTPBUFSIZE, f))
602           {
603             char * s;
604
605             len = 0;
606             while ((buf[len] != 0) && (buf[len] != ' '))
607               len++;
608             buf[len] = 0;
609             s = g_strdup(buf);
610
611             group_list = g_slist_append(group_list, s);
612           }
613         fclose(f);
614         g_free(filename);
615
616         group_list = g_slist_sort(group_list, (GCompareFunc) g_strcasecmp);
617
618         return group_list;
619 }
620
621 /*
622   remove the cache file of the names of the newsgroups.
623  */
624
625 void news_reset_group_list(FolderItem *item)
626 {
627         gchar *path, *filename;
628
629         debug_print(_("\tDeleting cached group list... "));
630         path = folder_item_get_path(item);
631         filename = g_strconcat(path, G_DIR_SEPARATOR_S, GROUPLIST_FILE, NULL);
632         g_free(path);
633         if (remove(filename) != 0)
634           log_warning(_("can't delete cached group list %s\n"), filename);
635         g_free(filename);
636 }