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