Nico Golde:
[apps/madmutt.git] / newsrc.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1998 Brandon Long <blong@fiction.net>
4  * Copyright (C) 1999 Andrej Gritsenko <andrej@lucky.net>
5  * Copyright (C) 2000-2001 Vsevolod Volkov <vvv@mutt.org.ua>
6  *
7  * This file is part of mutt-ng, see http://www.muttng.org/.
8  * It's licensed under the GNU General Public License,
9  * please see the file GPL in the top level source directory.
10  */
11
12 #ifdef HAVE_CONFIG_H
13 #include <config.h>
14 #endif
15
16 #include "mutt.h"
17 #include "mutt_curses.h"
18 #include "sort.h"
19 #include "mx.h"
20 #include "mime.h"
21 #include "mailbox.h"
22 #include "nntp.h"
23 #include "rfc822.h"
24 #include "rfc1524.h"
25 #include "rfc2047.h"
26
27 #include <unistd.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <stdlib.h>
31 #include <sys/stat.h>
32
33 void nntp_add_to_list (NNTP_SERVER * s, NNTP_DATA * d)
34 {
35   LIST *l;
36
37   if (!s || !d)
38     return;
39
40   l = safe_calloc (1, sizeof (LIST));
41   if (s->list)
42     s->tail->next = l;
43   else
44     s->list = l;
45   s->tail = l;
46   l->data = (void *) d;
47 }
48
49 static int nntp_parse_newsrc_line (NNTP_SERVER * news, char *line)
50 {
51   NNTP_DATA *data;
52   char group[LONG_STRING];
53   int x = 1;
54   char *p = line, *b, *h;
55   size_t len;
56
57   while (*p) {
58     if (*p++ == ',')
59       x++;
60   }
61
62   p = line;
63   while (*p && (*p != ':' && *p != '!'))
64     p++;
65   if (!*p)
66     return -1;
67   len = p + 1 - line;
68   if (len > sizeof (group))
69     len = sizeof (group);
70   strfcpy (group, line, len);
71   if ((data = (NNTP_DATA *) hash_find (news->newsgroups, group)) == NULL) {
72     data =
73       (NNTP_DATA *) safe_calloc (1, sizeof (NNTP_DATA) + strlen (group) + 1);
74     data->group = (char *) data + sizeof (NNTP_DATA);
75     strcpy (data->group, group);
76     data->nserv = news;
77     data->deleted = 1;
78     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
79       news->newsgroups =
80         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
81     hash_insert (news->newsgroups, data->group, data, 0);
82     nntp_add_to_list (news, data);
83   }
84   else
85     FREE ((void **) &data->entries);
86
87   data->rc = 1;
88   data->entries = safe_calloc (x * 2, sizeof (NEWSRC_ENTRY));
89   data->max = x * 2;
90
91   if (*p == ':')
92     data->subscribed = 1;
93   else
94     data->subscribed = 0;
95
96   p++;
97   b = p;
98   x = 0;
99   while (*b) {
100     while (*p && *p != ',' && *p != '\n')
101       p++;
102     if (*p) {
103       *p = '\0';
104       p++;
105     }
106     if ((h = strchr (b, '-'))) {
107       *h = '\0';
108       h++;
109       data->entries[x].first = atoi (b);
110       data->entries[x].last = atoi (h);
111     }
112     else {
113       data->entries[x].first = atoi (b);
114       data->entries[x].last = data->entries[x].first;
115     }
116     b = p;
117     if (data->entries[x].last != 0)
118       x++;
119   }
120   if (x && !data->lastMessage)
121     data->lastMessage = data->entries[x - 1].last;
122   data->num = x;
123   mutt_newsgroup_stat (data);
124   dprint (2, (debugfile, "parse_line: Newsgroup %s\n", data->group));
125
126   return 0;
127 }
128
129 static int slurp_newsrc (NNTP_SERVER * news)
130 {
131   FILE *fp;
132   char *buf;
133   struct stat sb;
134
135   news->stat = stat (news->newsrc, &sb);
136   news->size = sb.st_size;
137   news->mtime = sb.st_mtime;
138
139   if ((fp = safe_fopen (news->newsrc, "r")) == NULL)
140     return -1;
141   /* hmm, should we use dotlock? */
142   if (mx_lock_file (news->newsrc, fileno (fp), 0, 0, 1)) {
143     fclose (fp);
144     return -1;
145   }
146
147   buf = safe_malloc (sb.st_size + 1);
148   while (fgets (buf, sb.st_size + 1, fp))
149     nntp_parse_newsrc_line (news, buf);
150   FREE (&buf);
151
152   mx_unlock_file (news->newsrc, fileno (fp), 0);
153   fclose (fp);
154   return 0;
155 }
156
157 void nntp_cache_expand (char *dst, const char *src)
158 {
159   snprintf (dst, _POSIX_PATH_MAX, "%s/%s", NewsCacheDir, src);
160   mutt_expand_path (dst, _POSIX_PATH_MAX);
161 }
162
163 /* Loads $news_cache_dir/.index into memory, loads newsserver data
164  * and newsgroup cache names */
165 static int nntp_parse_cacheindex (NNTP_SERVER * news)
166 {
167   struct stat st;
168   char buf[HUGE_STRING], *cp;
169   char dir[_POSIX_PATH_MAX], file[_POSIX_PATH_MAX];
170   FILE *index;
171   NNTP_DATA *data;
172   int l, m, t;
173
174   /* check is server name defined or not */
175   if (!news || !news->conn || !news->conn->account.host)
176     return -1;
177   unset_option (OPTNEWSCACHE);
178   if (!NewsCacheDir || !*NewsCacheDir)
179     return 0;
180
181   strfcpy (dir, NewsCacheDir, sizeof (dir));
182   mutt_expand_path (dir, sizeof (dir));
183
184   if (lstat (dir, &st) || (st.st_mode & S_IFDIR) == 0) {
185     snprintf (buf, sizeof (buf), _("Directory %s not exist. Create it?"),
186               dir);
187     if (mutt_yesorno (buf, M_YES) != M_YES
188         || mkdir (dir, (S_IRWXU + S_IRWXG + S_IRWXO))) {
189       mutt_error _("Cache directory not created!");
190
191       return -1;
192     }
193     mutt_clear_error ();
194   }
195
196   set_option (OPTNEWSCACHE);
197
198   FREE (&news->cache);
199   snprintf (buf, sizeof (buf), "%s/.index", dir);
200   if (!(index = safe_fopen (buf, "a+")))
201     return 0;
202   rewind (index);
203   while (fgets (buf, sizeof (buf), index)) {
204     buf[strlen (buf) - 1] = 0;  /* strip ending '\n' */
205     if (!mutt_strncmp (buf, "#: ", 3) &&
206         !mutt_strcasecmp (buf + 3, news->conn->account.host))
207       break;
208   }
209   while (fgets (buf, sizeof (buf), index)) {
210     cp = buf;
211     while (*cp && *cp != ' ')
212       cp++;
213     if (!*cp)
214       continue;
215     cp[0] = 0;
216     if (!mutt_strcmp (buf, "#:"))
217       break;
218     sscanf (cp + 1, "%s %d %d", file, &l, &m);
219     if (!mutt_strcmp (buf, "ALL")) {
220       news->cache = safe_strdup (file);
221       news->newgroups_time = m;
222     }
223     else if (news->newsgroups) {
224       if ((data = (NNTP_DATA *) hash_find (news->newsgroups, buf)) == NULL) {
225         data =
226           (NNTP_DATA *) safe_calloc (1,
227                                      sizeof (NNTP_DATA) + strlen (buf) + 1);
228         data->group = (char *) data + sizeof (NNTP_DATA);
229         strcpy (data->group, buf);
230         data->nserv = news;
231         data->deleted = 1;
232         if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
233           news->newsgroups =
234             hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
235         hash_insert (news->newsgroups, data->group, data, 0);
236         nntp_add_to_list (news, data);
237       }
238       data->cache = safe_strdup (file);
239       t = 0;
240       if (!data->firstMessage || data->lastMessage < m)
241         t = 1;
242       if (!data->firstMessage)
243         data->firstMessage = l;
244       if (data->lastMessage < m)
245         data->lastMessage = m;
246       data->lastCached = m;
247       if (t || !data->unread)
248         mutt_newsgroup_stat (data);
249     }
250   }
251   fclose (index);
252   return 0;
253 }
254
255 const char *nntp_format_str (char *dest, size_t destlen, char op,
256                              const char *src, const char *fmt,
257                              const char *ifstring, const char *elsestring,
258                              unsigned long data, format_flag flags)
259 {
260   char fn[SHORT_STRING], tmp[SHORT_STRING];
261
262   switch (op) {
263   case 's':
264     strncpy (fn, NewsServer, sizeof (fn) - 1);
265     mutt_strlower (fn);
266     snprintf (tmp, sizeof (tmp), "%%%ss", fmt);
267     snprintf (dest, destlen, tmp, fn);
268     break;
269   }
270   return (src);
271 }
272
273 /* nntp_parse_url: given an NNPT URL, return host, port,
274  * username, password and newsgroup will recognise. */
275 int nntp_parse_url (const char *server, ACCOUNT * acct,
276                     char *group, size_t group_len)
277 {
278   ciss_url_t url;
279   char *c;
280   int ret = -1;
281
282   /* Defaults */
283   acct->flags = 0;
284   acct->port = NNTP_PORT;
285   acct->type = M_ACCT_TYPE_NNTP;
286
287   c = safe_strdup (server);
288   url_parse_ciss (&url, c);
289
290   if (url.scheme == U_NNTP || url.scheme == U_NNTPS) {
291     if (url.scheme == U_NNTPS) {
292       acct->flags |= M_ACCT_SSL;
293       acct->port = NNTP_SSL_PORT;
294     }
295
296     *group = '\0';
297     if (url.path)
298       strfcpy (group, url.path, group_len);
299
300     ret = mutt_account_fromurl (acct, &url);
301   }
302
303   FREE (&c);
304   return ret;
305 }
306
307 void nntp_expand_path (char *line, size_t len, ACCOUNT * acct)
308 {
309   ciss_url_t url;
310
311   url.path = safe_strdup (line);
312   mutt_account_tourl (acct, &url);
313   url_ciss_tostring (&url, line, len, 0);
314   FREE (&url.path);
315 }
316
317 /*
318  * Automatically loads a newsrc into memory, if necessary.
319  * Checks the size/mtime of a newsrc file, if it doesn't match, load
320  * again.  Hmm, if a system has broken mtimes, this might mean the file
321  * is reloaded every time, which we'd have to fix.
322  *
323  * a newsrc file is a line per newsgroup, with the newsgroup, then a 
324  * ':' denoting subscribed or '!' denoting unsubscribed, then a 
325  * comma separated list of article numbers and ranges.
326  */
327 NNTP_SERVER *mutt_select_newsserver (char *server)
328 {
329   char file[_POSIX_PATH_MAX];
330   char *buf, *p;
331   LIST *list;
332   ACCOUNT acct;
333   NNTP_SERVER *serv;
334   CONNECTION *conn;
335
336   if (!server || !*server) {
337     mutt_error _("No newsserver defined!");
338
339     return NULL;
340   }
341
342   buf = p = safe_calloc (strlen (server) + 10, sizeof (char));
343   if (url_check_scheme (server) == U_UNKNOWN) {
344     strcpy (buf, "nntp://");
345     p = strchr (buf, '\0');
346   }
347   strcpy (p, server);
348
349   if ((nntp_parse_url (buf, &acct, file, sizeof (file))) < 0 || *file) {
350     FREE (&buf);
351     mutt_error (_("%s is an invalid newsserver specification!"), server);
352     return NULL;
353   }
354   FREE (&buf);
355
356   conn = mutt_conn_find (NULL, &acct);
357   if (!conn)
358     return NULL;
359
360   mutt_FormatString (file, sizeof (file), NONULL (NewsRc), nntp_format_str, 0,
361                      0);
362   mutt_expand_path (file, sizeof (file));
363
364   serv = (NNTP_SERVER *) conn->data;
365   if (serv) {
366     struct stat sb;
367
368     /* externally modified? */
369     if (serv->stat != stat (file, &sb) || (!serv->stat &&
370                                            (serv->size != sb.st_size
371                                             || serv->mtime != sb.st_mtime))) {
372       for (list = serv->list; list; list = list->next) {
373         NNTP_DATA *data = (NNTP_DATA *) list->data;
374
375         if (data) {
376           data->subscribed = 0;
377           data->rc = 0;
378           data->num = 0;
379         }
380       }
381       slurp_newsrc (serv);
382       nntp_clear_cacheindex (serv);
383     }
384
385     if (serv->status == NNTP_BYE)
386       serv->status = NNTP_NONE;
387     nntp_check_newgroups (serv, 0);
388     return serv;
389   }
390
391   /* New newsserver */
392   serv = safe_calloc (1, sizeof (NNTP_SERVER));
393   serv->conn = conn;
394   serv->newsrc = safe_strdup (file);
395   serv->newsgroups = hash_create (1009);
396   slurp_newsrc (serv);          /* load .newsrc */
397   nntp_parse_cacheindex (serv); /* load .index */
398   if (option (OPTNEWSCACHE) && serv->cache && nntp_get_cache_all (serv) >= 0)
399     nntp_check_newgroups (serv, 1);
400   else if (nntp_get_active (serv) < 0) {
401     hash_destroy (&serv->newsgroups, nntp_delete_data);
402     for (list = serv->list; list; list = list->next)
403       list->data = NULL;
404     mutt_free_list (&serv->list);
405     FREE (&serv->newsrc);
406     FREE (&serv->cache);
407     FREE (&serv);
408     return NULL;
409   }
410   nntp_clear_cacheindex (serv);
411   conn->data = (void *) serv;
412
413   return serv;
414 }
415
416 /* 
417  * full status flags are not supported by nntp, but we can fake some
418  * of them.  This is how:
419  * Read = a read message number is in the .newsrc
420  * New = a message is new since we last read this newsgroup
421  * Old = anything else
422  * So, Read is marked as such in the newsrc, old is anything that is 
423  * "skipped" in the newsrc, and new is anything not in the newsrc nor
424  * in the cache. By skipped, I mean before the last unread message
425  */
426 void nntp_get_status (CONTEXT * ctx, HEADER * h, char *group, int article)
427 {
428   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
429   int x;
430
431   if (group)
432     data = (NNTP_DATA *) hash_find (data->nserv->newsgroups, group);
433
434   if (!data) {
435 #ifdef DEBUG
436     if (group)
437       dprint (3, (debugfile, "newsgroup %s not found\n", group));
438 #endif
439     return;
440   }
441
442   for (x = 0; x < data->num; x++) {
443     if ((article >= data->entries[x].first) &&
444         (article <= data->entries[x].last)) {
445       /* we cannot use mutt_set_flag() because mx_update_context()
446          didn't called yet */
447       h->read = 1;
448       return;
449     }
450   }
451   /* If article was not cached yet, it is new! :) */
452   if (!data->cache || article > data->lastCached)
453     return;
454   /* Old articles are articles which aren't read but an article after them
455    * has been cached */
456   if (option (OPTMARKOLD))
457     h->old = 1;
458 }
459
460 void mutt_newsgroup_stat (NNTP_DATA * data)
461 {
462   int i;
463   unsigned int first, last;
464
465   data->unread = 0;
466   if (data->lastMessage == 0 || data->firstMessage > data->lastMessage)
467     return;
468
469   data->unread = data->lastMessage - data->firstMessage + 1;
470   for (i = 0; i < data->num; i++) {
471     first = data->entries[i].first;
472     if (first < data->firstMessage)
473       first = data->firstMessage;
474     last = data->entries[i].last;
475     if (last > data->lastMessage)
476       last = data->lastMessage;
477     if (first <= last)
478       data->unread -= last - first + 1;
479   }
480 }
481
482 static int puti (char *line, int num)
483 {
484   char *p, s[32];
485
486   for (p = s; num;) {
487     *p++ = '0' + num % 10;
488     num /= 10;
489   }
490   while (p > s)
491     *line++ = *--p, num++;
492   *line = '\0';
493   return num;
494 }
495
496 static void nntp_create_newsrc_line (NNTP_DATA * data, char **buf,
497                                      char **pline, size_t * buflen)
498 {
499   char *line = *pline;
500   size_t len = *buflen - (*pline - *buf);
501   int x, i;
502
503   if (len < LONG_STRING * 10) {
504     len += *buflen;
505     *buflen *= 2;
506     line = *buf;
507     safe_realloc (buf, *buflen);
508     line = *buf + (*pline - line);
509   }
510   strcpy (line, data->group);
511   len -= strlen (line) + 1;
512   line += strlen (line);
513   *line++ = data->subscribed ? ':' : '!';
514   *line++ = ' ';
515   *line = '\0';
516
517   for (x = 0; x < data->num; x++) {
518     if (len < LONG_STRING) {
519       len += *buflen;
520       *buflen *= 2;
521       *pline = line;
522       line = *buf;
523       safe_realloc (buf, *buflen);
524       line = *buf + (*pline - line);
525     }
526     if (x) {
527       *line++ = ',';
528       len--;
529     }
530
531 #if 0
532     if (data->entries[x].first == data->entries[x].last)
533       snprintf (line, len, "%d%n", data->entries[x].first, &i);
534     else
535       snprintf (line, len, "%d-%d%n",
536                 data->entries[x].first, data->entries[x].last, &i);
537     len -= i;
538     line += i;
539 #else
540     i = puti (line, data->entries[x].first);
541     line += i;
542     len -= i;
543     if (data->entries[x].first != data->entries[x].last) {
544       *line++ = '-';
545       len--;
546       i = puti (line, data->entries[x].last);
547       line += i;
548       len -= i;
549     }
550 #endif
551   }
552   *line++ = '\n';
553   *line = '\0';
554   *pline = line;
555 }
556
557 void newsrc_gen_entries (CONTEXT * ctx)
558 {
559   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
560   int series, x;
561   unsigned int last = 0, first = 1;
562   int save_sort = SORT_ORDER;
563
564   if (Sort != SORT_ORDER) {
565     save_sort = Sort;
566     Sort = SORT_ORDER;
567     mutt_sort_headers (ctx, 0);
568   }
569
570   if (!data->max) {
571     data->entries = safe_calloc (5, sizeof (NEWSRC_ENTRY));
572     data->max = 5;
573   }
574
575   /*
576    * Set up to fake initial sequence from 1 to the article before the 
577    * first article in our list
578    */
579   data->num = 0;
580   series = 1;
581
582   for (x = 0; x < ctx->msgcount; x++) {
583     if (series) {               /* search for first unread */
584       /*
585        * We don't actually check sequential order, since we mark 
586        * "missing" entries as read/deleted
587        */
588       last = ctx->hdrs[x]->article_num;
589       if (last >= data->firstMessage && !ctx->hdrs[x]->deleted &&
590           !ctx->hdrs[x]->read) {
591         if (data->num >= data->max) {
592           data->max = data->max * 2;
593           safe_realloc (&data->entries, data->max * sizeof (NEWSRC_ENTRY));
594         }
595         data->entries[data->num].first = first;
596         data->entries[data->num].last = last - 1;
597         data->num++;
598         series = 0;
599       }
600     }
601     else {                      /* search for first read */
602
603       if (ctx->hdrs[x]->deleted || ctx->hdrs[x]->read) {
604         first = last + 1;
605         series = 1;
606       }
607       last = ctx->hdrs[x]->article_num;
608     }
609   }
610   if (series && first <= data->lastLoaded) {
611     if (data->num >= data->max) {
612       data->max = data->max * 2;
613       safe_realloc (&data->entries, data->max * sizeof (NEWSRC_ENTRY));
614     }
615     data->entries[data->num].first = first;
616     data->entries[data->num].last = data->lastLoaded;
617     data->num++;
618   }
619
620   if (save_sort != Sort) {
621     Sort = save_sort;
622     mutt_sort_headers (ctx, 0);
623   }
624 }
625
626 int mutt_newsrc_update (NNTP_SERVER * news)
627 {
628   char *buf, *line;
629   NNTP_DATA *data;
630   LIST *tmp;
631   int r = -1;
632   size_t len, llen;
633
634   if (!news)
635     return -1;
636   llen = len = 10 * LONG_STRING;
637   line = buf = safe_calloc (1, len);
638   /* we will generate full newsrc here */
639   for (tmp = news->list; tmp; tmp = tmp->next) {
640     data = (NNTP_DATA *) tmp->data;
641     if (!data || !data->rc)
642       continue;
643     nntp_create_newsrc_line (data, &buf, &line, &llen);
644     dprint (2, (debugfile, "Added to newsrc: %s", line));
645     line += strlen (line);
646   }
647   /* newrc being fully rewritten */
648   if (news->newsrc &&
649       (r = mutt_update_list_file (news->newsrc, NULL, "", buf)) == 0) {
650     struct stat st;
651
652     stat (news->newsrc, &st);
653     news->size = st.st_size;
654     news->mtime = st.st_mtime;
655   }
656   FREE (&buf);
657   return r;
658 }
659
660 static FILE *mutt_mkname (char *s)
661 {
662   char buf[_POSIX_PATH_MAX], *pc;
663   int fd;
664   FILE *fp;
665
666   nntp_cache_expand (buf, s);
667   if ((fp = safe_fopen (buf, "w")))
668     return fp;
669
670   nntp_cache_expand (buf, "cache-XXXXXX");
671   pc = buf + strlen (buf) - 12; /* positioning to "cache-XXXXXX" */
672   if ((fd = mkstemp (buf)) == -1)
673     return NULL;
674   strcpy (s, pc);               /* generated name */
675   return fdopen (fd, "w");
676 }
677
678 /* Updates info into .index file: ALL or about selected newsgroup */
679 static int nntp_update_cacheindex (NNTP_SERVER * serv, NNTP_DATA * data)
680 {
681   char buf[LONG_STRING], *key = "ALL";
682   char file[_POSIX_PATH_MAX];
683
684   if (!serv || !serv->conn || !serv->conn->account.host)
685     return -1;
686
687   if (data && data->group) {
688     key = data->group;
689     snprintf (buf, sizeof (buf), "%s %s %d %d", key, data->cache,
690               data->firstMessage, data->lastLoaded);
691   }
692   else {
693     strfcpy (file, serv->cache, sizeof (file));
694     snprintf (buf, sizeof (buf), "ALL %s 0 %d", file,
695               (int) serv->newgroups_time);
696   }
697   nntp_cache_expand (file, ".index");
698   return mutt_update_list_file (file, serv->conn->account.host, key, buf);
699 }
700
701 /* Remove cache files of unsubscribed newsgroups */
702 void nntp_clear_cacheindex (NNTP_SERVER * news)
703 {
704   NNTP_DATA *data;
705   LIST *tmp;
706
707   if (option (OPTSAVEUNSUB) || !news)
708     return;
709
710   for (tmp = news->list; tmp; tmp = tmp->next) {
711     data = (NNTP_DATA *) tmp->data;
712     if (!data || data->subscribed || !data->cache)
713       continue;
714     nntp_delete_cache (data);
715     dprint (2, (debugfile, "Removed from .index: %s\n", data->group));
716   }
717   return;
718 }
719
720 int nntp_save_cache_index (NNTP_SERVER * news)
721 {
722   char buf[HUGE_STRING];
723   char file[_POSIX_PATH_MAX];
724   NNTP_DATA *d;
725   FILE *f;
726   LIST *l;
727
728   if (!news || !news->newsgroups)
729     return -1;
730   if (!option (OPTNEWSCACHE))
731     return 0;
732
733   if (news->cache) {
734     nntp_cache_expand (file, news->cache);
735     unlink (file);
736     f = safe_fopen (file, "w");
737   }
738   else {
739     strfcpy (buf, news->conn->account.host, sizeof (buf));
740     f = mutt_mkname (buf);
741     news->cache = safe_strdup (buf);
742     nntp_cache_expand (file, buf);
743   }
744   if (!f)
745     return -1;
746
747   for (l = news->list; l; l = l->next) {
748     if ((d = (NNTP_DATA *) l->data) && !d->deleted) {
749       if (d->desc)
750         snprintf (buf, sizeof (buf), "%s %d %d %c %s\n", d->group,
751                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n',
752                   d->desc);
753       else
754         snprintf (buf, sizeof (buf), "%s %d %d %c\n", d->group,
755                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n');
756       if (fputs (buf, f) == EOF) {
757         fclose (f);
758         unlink (file);
759         return -1;
760       }
761     }
762   }
763   fclose (f);
764
765   if (nntp_update_cacheindex (news, NULL)) {
766     unlink (file);
767     return -1;
768   }
769   return 0;
770 }
771
772 int nntp_save_cache_group (CONTEXT * ctx)
773 {
774   char buf[HUGE_STRING], addr[STRING];
775   char file[_POSIX_PATH_MAX];
776   FILE *f;
777   HEADER *h;
778   struct tm *tm;
779   int i = 0, save = SORT_ORDER;
780   int prev = 0;
781
782   if (!option (OPTNEWSCACHE))
783     return 0;
784   if (!ctx || !ctx->data || ctx->magic != M_NNTP)
785     return -1;
786
787   if (((NNTP_DATA *) ctx->data)->cache) {
788     nntp_cache_expand (file, ((NNTP_DATA *) ctx->data)->cache);
789     unlink (file);
790     f = safe_fopen (file, "w");
791   }
792   else {
793     snprintf (buf, sizeof (buf), "%s-%s",
794               ((NNTP_DATA *) ctx->data)->nserv->conn->account.host,
795               ((NNTP_DATA *) ctx->data)->group);
796     f = mutt_mkname (buf);
797     ((NNTP_DATA *) ctx->data)->cache = safe_strdup (buf);
798     nntp_cache_expand (file, buf);
799   }
800   if (!f)
801     return -1;
802
803   if (Sort != SORT_ORDER) {
804     save = Sort;
805     Sort = SORT_ORDER;
806     mutt_sort_headers (ctx, 0);
807   }
808
809   /* Save only $nntp_context messages... */
810   ((NNTP_DATA *) ctx->data)->lastCached = 0;
811   if (NntpContext && ctx->msgcount > NntpContext)
812     i = ctx->msgcount - NntpContext;
813   for (; i < ctx->msgcount; i++) {
814     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->article_num != prev) {
815       h = ctx->hdrs[i];
816       addr[0] = 0;
817       rfc822_write_address (addr, sizeof (addr), h->env->from, 0);
818       tm = gmtime (&h->date_sent);
819       snprintf (buf, sizeof (buf),
820                 "%d\t%s\t%s\t%d %s %d %02d:%02d:%02d GMT\t%s\t",
821                 h->article_num, h->env->subject, addr, tm->tm_mday,
822                 Months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour,
823                 tm->tm_min, tm->tm_sec, h->env->message_id);
824       fputs (buf, f);
825       if (h->env->references)
826         mutt_write_references (h->env->references, f);
827       snprintf (buf, sizeof (buf), "\t%ld\t%d\tXref: %s\n",
828                 h->content->length, h->lines, NONULL (h->env->xref));
829       if (fputs (buf, f) == EOF) {
830         fclose (f);
831         unlink (file);
832         return -1;
833       }
834     }
835     prev = ctx->hdrs[i]->article_num;
836   }
837
838   if (save != Sort) {
839     Sort = save;
840     mutt_sort_headers (ctx, 0);
841   }
842   fclose (f);
843
844   if (nntp_update_cacheindex (((NNTP_DATA *) ctx->data)->nserv,
845                               (NNTP_DATA *) ctx->data)) {
846     unlink (file);
847     return -1;
848   }
849   ((NNTP_DATA *) ctx->data)->lastCached =
850     ((NNTP_DATA *) ctx->data)->lastLoaded;
851   return 0;
852 }
853
854 void nntp_delete_cache (NNTP_DATA * data)
855 {
856   char buf[_POSIX_PATH_MAX];
857
858   if (!option (OPTNEWSCACHE) || !data || !data->cache || !data->nserv)
859     return;
860
861   nntp_cache_expand (buf, data->cache);
862   unlink (buf);
863   FREE (&data->cache);
864   data->lastCached = 0;
865   nntp_cache_expand (buf, ".index");
866   mutt_update_list_file (buf, data->nserv->conn->account.host, data->group,
867                          NULL);
868 }
869
870 NNTP_DATA *mutt_newsgroup_subscribe (NNTP_SERVER * news, char *group)
871 {
872   NNTP_DATA *data;
873
874   if (!news || !news->newsgroups || !group || !*group)
875     return NULL;
876   if (!(data = (NNTP_DATA *) hash_find (news->newsgroups, group))) {
877     data =
878       (NNTP_DATA *) safe_calloc (1, sizeof (NNTP_DATA) + strlen (group) + 1);
879     data->group = (char *) data + sizeof (NNTP_DATA);
880     strcpy (data->group, group);
881     data->nserv = news;
882     data->deleted = 1;
883     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
884       news->newsgroups =
885         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
886     hash_insert (news->newsgroups, data->group, data, 0);
887     nntp_add_to_list (news, data);
888   }
889   if (!data->subscribed) {
890     data->subscribed = 1;
891     data->rc = 1;
892   }
893   return data;
894 }
895
896 NNTP_DATA *mutt_newsgroup_unsubscribe (NNTP_SERVER * news, char *group)
897 {
898   NNTP_DATA *data;
899
900   if (!news || !news->newsgroups || !group || !*group ||
901       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
902     return NULL;
903   if (data->subscribed) {
904     data->subscribed = 0;
905     if (!option (OPTSAVEUNSUB))
906       data->rc = 0;
907   }
908   return data;
909 }
910
911 NNTP_DATA *mutt_newsgroup_catchup (NNTP_SERVER * news, char *group)
912 {
913   NNTP_DATA *data;
914
915   if (!news || !news->newsgroups || !group || !*group ||
916       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
917     return NULL;
918   if (!data->max) {
919     data->entries = safe_calloc (5, sizeof (NEWSRC_ENTRY));
920     data->max = 5;
921   }
922   data->num = 1;
923   data->entries[0].first = 1;
924   data->unread = 0;
925   data->entries[0].last = data->lastMessage;
926   if (Context && Context->data == data) {
927     int x;
928
929     for (x = 0; x < Context->msgcount; x++)
930       mutt_set_flag (Context, Context->hdrs[x], M_READ, 1);
931   }
932   return data;
933 }
934
935 NNTP_DATA *mutt_newsgroup_uncatchup (NNTP_SERVER * news, char *group)
936 {
937   NNTP_DATA *data;
938
939   if (!news || !news->newsgroups || !group || !*group ||
940       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
941     return NULL;
942   if (!data->max) {
943     data->entries = safe_calloc (5, sizeof (NEWSRC_ENTRY));
944     data->max = 5;
945   }
946   data->num = 1;
947   data->entries[0].first = 1;
948   data->entries[0].last = data->firstMessage - 1;
949   if (Context && Context->data == data) {
950     int x;
951
952     data->unread = Context->msgcount;
953     for (x = 0; x < Context->msgcount; x++)
954       mutt_set_flag (Context, Context->hdrs[x], M_READ, 0);
955   }
956   else
957     data->unread = data->lastMessage - data->entries[0].last;
958   return data;
959 }
960
961 /* this routine gives the first newsgroup with new messages */
962 void nntp_buffy (char *s)
963 {
964   LIST *list;
965
966   for (list = CurrentNewsSrv->list; list; list = list->next) {
967     NNTP_DATA *data = (NNTP_DATA *) list->data;
968
969     if (data && data->subscribed && data->unread) {
970       if (Context && Context->magic == M_NNTP &&
971           !mutt_strcmp (data->group, ((NNTP_DATA *) Context->data)->group)) {
972         unsigned int i, unread = 0;
973
974         for (i = 0; i < Context->msgcount; i++)
975           if (!Context->hdrs[i]->read && !Context->hdrs[i]->deleted)
976             unread++;
977         if (!unread)
978           continue;
979       }
980       strcpy (s, data->group);
981       break;
982     }
983   }
984 }