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