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