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