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