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