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