various fixes, remove an adv_mktemp
[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 *ifstring, const char *elsestring,
243                              unsigned long data, format_flag flags)
244 {
245   char fn[SHORT_STRING], tmp[SHORT_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->flags |= M_ACCT_SSL;
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   mutt_FormatString (file, sizeof (file), NONULL (NewsRc), nntp_format_str, 0,
348                      0);
349   mutt_expand_path (file, sizeof (file));
350
351   serv = (NNTP_SERVER *) conn->data;
352   if (serv) {
353     struct stat sb;
354
355     /* externally modified? */
356     if (serv->stat != stat (file, &sb) || (!serv->stat &&
357                                            (serv->size != sb.st_size
358                                             || serv->mtime != sb.st_mtime))) {
359       for (list = serv->list; list; list = list->next) {
360         NNTP_DATA *data = (NNTP_DATA *) list->data;
361
362         if (data) {
363           data->subscribed = 0;
364           data->rc = 0;
365           data->num = 0;
366         }
367       }
368       slurp_newsrc (serv);
369       nntp_clear_cacheindex (serv);
370     }
371
372     if (serv->status == NNTP_BYE)
373       serv->status = NNTP_NONE;
374     nntp_check_newgroups (serv, 0);
375     return serv;
376   }
377
378   /* New newsserver */
379   serv = p_new(NNTP_SERVER, 1);
380   serv->conn = conn;
381   serv->newsrc = m_strdup(file);
382   serv->newsgroups = hash_create (1009);
383   slurp_newsrc (serv);          /* load .newsrc */
384   nntp_parse_cacheindex (serv); /* load .index */
385   if (option (OPTNEWSCACHE) && serv->cache && nntp_get_cache_all (serv) >= 0)
386     nntp_check_newgroups (serv, 1);
387   else if (nntp_get_active (serv) < 0) {
388     hash_destroy (&serv->newsgroups, nntp_delete_data);
389     for (list = serv->list; list; list = list->next)
390       list->data = NULL;
391     string_list_wipe(&serv->list);
392     p_delete(&serv->newsrc);
393     p_delete(&serv->cache);
394     p_delete(&serv);
395     return NULL;
396   }
397   nntp_clear_cacheindex (serv);
398   conn->data = (void *) serv;
399
400   return serv;
401 }
402
403 /* 
404  * full status flags are not supported by nntp, but we can fake some
405  * of them.  This is how:
406  * Read = a read message number is in the .newsrc
407  * New = a message is new since we last read this newsgroup
408  * Old = anything else
409  * So, Read is marked as such in the newsrc, old is anything that is 
410  * "skipped" in the newsrc, and new is anything not in the newsrc nor
411  * in the cache. By skipped, I mean before the last unread message
412  */
413 void nntp_get_status (CONTEXT * ctx, HEADER * h, char *group, int article)
414 {
415   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
416   int x;
417
418   if (group)
419     data = (NNTP_DATA *) hash_find (data->nserv->newsgroups, group);
420
421   if (!data) {
422     return;
423   }
424
425   for (x = 0; x < data->num; x++) {
426     if ((article >= data->entries[x].first) &&
427         (article <= data->entries[x].last)) {
428       /* we cannot use mutt_set_flag() because mx_update_context()
429          didn't called yet */
430       h->read = 1;
431       return;
432     }
433   }
434   /* If article was not cached yet, it is new! :) */
435   if (!data->cache || article > data->lastCached)
436     return;
437   /* Old articles are articles which aren't read but an article after them
438    * has been cached */
439   if (option (OPTMARKOLD))
440     h->old = 1;
441 }
442
443 void mutt_newsgroup_stat (NNTP_DATA * data)
444 {
445   int i;
446   unsigned int first, last;
447
448   data->unread = 0;
449   if (data->lastMessage == 0 || data->firstMessage > data->lastMessage)
450     return;
451
452   data->unread = data->lastMessage - data->firstMessage + 1;
453   for (i = 0; i < data->num; i++) {
454     first = data->entries[i].first;
455     if (first < data->firstMessage)
456       first = data->firstMessage;
457     last = data->entries[i].last;
458     if (last > data->lastMessage)
459       last = data->lastMessage;
460     if (first <= last)
461       data->unread -= last - first + 1;
462   }
463 }
464
465 static int puti (char *line, int num)
466 {
467   char *p, s[32];
468
469   for (p = s; num;) {
470     *p++ = '0' + num % 10;
471     num /= 10;
472   }
473   while (p > s)
474     *line++ = *--p, num++;
475   *line = '\0';
476   return num;
477 }
478
479 static void nntp_create_newsrc_line (NNTP_DATA * data, char **buf,
480                                      char **pline, ssize_t * buflen)
481 {
482   char *line = *pline;
483   ssize_t len = *buflen - (*pline - *buf);
484   int x, i;
485
486   if (len < LONG_STRING * 10) {
487     len += *buflen;
488     *buflen *= 2;
489     line = *buf;
490     p_realloc(buf, *buflen);
491     line = *buf + (*pline - line);
492   }
493   strcpy (line, data->group);
494   len -= m_strlen(line) + 1;
495   line += m_strlen(line);
496   *line++ = data->subscribed ? ':' : '!';
497   *line++ = ' ';
498   *line = '\0';
499
500   for (x = 0; x < data->num; x++) {
501     if (len < LONG_STRING) {
502       len += *buflen;
503       *buflen *= 2;
504       *pline = line;
505       line = *buf;
506       p_realloc(buf, *buflen);
507       line = *buf + (*pline - line);
508     }
509     if (x) {
510       *line++ = ',';
511       len--;
512     }
513
514 #if 0
515     if (data->entries[x].first == data->entries[x].last)
516       snprintf (line, len, "%d%n", data->entries[x].first, &i);
517     else
518       snprintf (line, len, "%d-%d%n",
519                 data->entries[x].first, data->entries[x].last, &i);
520     len -= i;
521     line += i;
522 #else
523     i = puti (line, data->entries[x].first);
524     line += i;
525     len -= i;
526     if (data->entries[x].first != data->entries[x].last) {
527       *line++ = '-';
528       len--;
529       i = puti (line, data->entries[x].last);
530       line += i;
531       len -= i;
532     }
533 #endif
534   }
535   *line++ = '\n';
536   *line = '\0';
537   *pline = line;
538 }
539
540 void newsrc_gen_entries (CONTEXT * ctx)
541 {
542   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
543   int series, x;
544   unsigned int last = 0, first = 1;
545   int save_sort = SORT_ORDER;
546
547   if (Sort != SORT_ORDER) {
548     save_sort = Sort;
549     Sort = SORT_ORDER;
550     mutt_sort_headers (ctx, 0);
551   }
552
553   if (!data->max) {
554     data->entries = p_new(NEWSRC_ENTRY, 5);
555     data->max = 5;
556   }
557
558   /*
559    * Set up to fake initial sequence from 1 to the article before the 
560    * first article in our list
561    */
562   data->num = 0;
563   series = 1;
564
565   for (x = 0; x < ctx->msgcount; x++) {
566     if (series) {               /* search for first unread */
567       /*
568        * We don't actually check sequential order, since we mark 
569        * "missing" entries as read/deleted
570        */
571       last = ctx->hdrs[x]->article_num;
572       if (last >= data->firstMessage && !ctx->hdrs[x]->deleted &&
573           !ctx->hdrs[x]->read) {
574         if (data->num >= data->max) {
575           data->max = data->max * 2;
576           p_realloc(&data->entries, data->max);
577         }
578         data->entries[data->num].first = first;
579         data->entries[data->num].last = last - 1;
580         data->num++;
581         series = 0;
582       }
583     }
584     else {                      /* search for first read */
585
586       if (ctx->hdrs[x]->deleted || ctx->hdrs[x]->read) {
587         first = last + 1;
588         series = 1;
589       }
590       last = ctx->hdrs[x]->article_num;
591     }
592   }
593   if (series && first <= data->lastLoaded) {
594     if (data->num >= data->max) {
595       data->max = data->max * 2;
596       p_realloc(&data->entries, data->max);
597     }
598     data->entries[data->num].first = first;
599     data->entries[data->num].last = data->lastLoaded;
600     data->num++;
601   }
602
603   if (save_sort != Sort) {
604     Sort = save_sort;
605     mutt_sort_headers (ctx, 0);
606   }
607 }
608
609 static int mutt_update_list_file (char *filename, char *section,
610                                   const char *key, char *line) {
611   FILE *ifp;
612   FILE *ofp;
613   char buf[HUGE_STRING];
614   char tmpf[_POSIX_PATH_MAX], lnk[_POSIX_PATH_MAX];
615   char *c;
616   int ext = 0, done = 0, r = 0, l = 0;
617
618   /* if file not exist, create it */
619   if ((ifp = safe_fopen (filename, "a")))
620     m_fclose(&ifp);
621   if (!(ifp = safe_fopen (filename, "r"))) {
622     mutt_error (_("Unable to open %s for reading"), filename);
623     return -1;
624   }
625   if (mx_lock_file (filename, fileno (ifp), 0, 0, 1)) {
626     m_fclose(&ifp);
627     mutt_error (_("Unable to lock %s"), filename);
628     return -1;
629   }
630
631   /* use m_tempfile() to get a tempfile in the same
632    * directory as filename is so that we can follow symlinks
633    * via rename(2); as dirname(2) may modify its argument,
634    * temporarily use buf as copy of it
635    */
636   m_strcpy(buf, sizeof(buf), filename);
637   ofp = m_tempfile(tmpf, sizeof(tmpf), dirname(buf), filename);
638   if (!ofp) {
639     m_fclose(&ifp);
640     mutt_error (_("Unable to open %s for writing"), tmpf);
641     return -1;
642   }
643
644   if (section) {
645     while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
646       r = fputs (buf, ofp);
647       c = buf;
648       while (*c && *c != '\n') c++;
649       c[0] = 0; /* strip EOL */
650       if (!strncmp (buf, "#: ", 3) && !m_strcasecmp(buf+3, section))
651         done++;
652     }
653     if (r != EOF && !done) {
654       snprintf (buf, sizeof(buf), "#: %s\n", section);
655       r = fputs (buf, ofp);
656     }
657     done = 0;
658   }
659
660   while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
661     if (ext) {
662       c = buf;
663       while (*c && (*c != '\r') && (*c != '\n')) c++;
664       c--;
665       if (*c != '\\') ext = 0;
666     } else if ((section && !strncmp (buf, "#: ", 3))) {
667       if (!done && line) {
668         fputs (line, ofp);
669         fputc ('\n', ofp);
670       }
671       r = fputs (buf, ofp);
672       done++;
673       break;
674     } else if (key && !strncmp (buf, key, strlen(key)) &&
675                (!*key || buf[strlen(key)] == ' ')) {
676       c = buf;
677       ext = 0;
678       while (*c && (*c != '\r') && (*c != '\n')) c++;
679       c--;
680       if (*c == '\\') ext = 1;
681       if (!done && line) {
682         r = fputs (line, ofp);
683         if (*key)
684           r = fputc ('\n', ofp);
685         done++;
686       }
687     } else {
688       r = fputs (buf, ofp);
689     }
690   }
691
692   while (r != EOF && fgets (buf, sizeof (buf), ifp))
693     r = fputs (buf, ofp);
694
695   /* If there wasn't a line to replace, put it on the end of the file */
696   if (r != EOF && !done && line) {
697     fputs (line, ofp);
698     r = fputc ('\n', ofp);
699   }
700   mx_unlock_file (filename, fileno (ifp), 0);
701   m_fclose(&ofp);
702   m_fclose(&ifp);
703   if (r == EOF) {
704     unlink (tmpf);
705     mutt_error (_("Can't write %s"), tmpf);
706     return -1;
707   }
708   lnk[0] = '\0';
709   if ((l = readlink (filename, lnk, sizeof(lnk)-1)) > 0)
710     lnk[l] = '\0';
711   if (rename (tmpf, l > 0 ? lnk : filename) < 0) {
712     unlink (tmpf);
713     mutt_error (_("Can't rename %s to %s"), tmpf, l > 0 ? lnk : filename);
714     return -1;
715   }
716   return 0;
717 }
718
719 int mutt_newsrc_update (NNTP_SERVER * news)
720 {
721   char *buf, *line;
722   NNTP_DATA *data;
723   string_list_t *tmp;
724   int r = -1;
725   ssize_t len, llen;
726
727   if (!news)
728     return -1;
729   llen = len = 10 * LONG_STRING;
730   line = buf = p_new(char, len);
731   /* we will generate full newsrc here */
732   for (tmp = news->list; tmp; tmp = tmp->next) {
733     data = (NNTP_DATA *) tmp->data;
734     if (!data || !data->rc)
735       continue;
736     nntp_create_newsrc_line (data, &buf, &line, &llen);
737     line += m_strlen(line);
738   }
739   /* newrc being fully rewritten */
740   if (news->newsrc &&
741       (r = mutt_update_list_file(news->newsrc, NULL, "", buf)) == 0) {
742     struct stat st;
743
744     stat (news->newsrc, &st);
745     news->size = st.st_size;
746     news->mtime = st.st_mtime;
747   }
748   p_delete(&buf);
749   return r;
750 }
751
752 static FILE *mutt_mkname (char *s)
753 {
754   char buf[_POSIX_PATH_MAX], *pc;
755   int fd;
756   FILE *fp;
757
758   nntp_cache_expand (buf, s);
759   if ((fp = safe_fopen (buf, "w")))
760     return fp;
761
762   nntp_cache_expand (buf, "cache-XXXXXX");
763   pc = buf + m_strlen(buf) - 12; /* positioning to "cache-XXXXXX" */
764   if ((fd = mkstemp (buf)) == -1)
765     return NULL;
766   strcpy (s, pc);               /* generated name */
767   return fdopen (fd, "w");
768 }
769
770 /* Updates info into .index file: ALL or about selected newsgroup */
771 static int nntp_update_cacheindex (NNTP_SERVER * serv, NNTP_DATA * data)
772 {
773   char buf[LONG_STRING];
774   char file[_POSIX_PATH_MAX];
775   const char *key = "ALL";
776
777   if (!serv || !serv->conn || !serv->conn->account.host)
778     return -1;
779
780   if (data && data->group) {
781     key = data->group;
782     snprintf (buf, sizeof (buf), "%s %s %d %d", key, data->cache,
783               data->firstMessage, data->lastLoaded);
784   }
785   else {
786     m_strcpy(file, sizeof(file), serv->cache);
787     snprintf (buf, sizeof (buf), "ALL %s 0 %d", file,
788               (int) serv->newgroups_time);
789   }
790   nntp_cache_expand (file, ".index");
791   return mutt_update_list_file (file, serv->conn->account.host, key, buf);
792 }
793
794 /* Remove cache files of unsubscribed newsgroups */
795 void nntp_clear_cacheindex (NNTP_SERVER * news)
796 {
797   NNTP_DATA *data;
798   string_list_t *tmp;
799
800   if (option (OPTSAVEUNSUB) || !news)
801     return;
802
803   for (tmp = news->list; tmp; tmp = tmp->next) {
804     data = (NNTP_DATA *) tmp->data;
805     if (!data || data->subscribed || !data->cache)
806       continue;
807     nntp_delete_cache (data);
808   }
809   return;
810 }
811
812 int nntp_save_cache_index (NNTP_SERVER * news)
813 {
814   char buf[HUGE_STRING];
815   char file[_POSIX_PATH_MAX];
816   NNTP_DATA *d;
817   FILE *f;
818   string_list_t *l;
819
820   if (!news || !news->newsgroups)
821     return -1;
822   if (!option (OPTNEWSCACHE))
823     return 0;
824
825   if (news->cache) {
826     nntp_cache_expand (file, news->cache);
827     unlink (file);
828     f = safe_fopen (file, "w");
829   }
830   else {
831     m_strcpy(buf, sizeof(buf), news->conn->account.host);
832     f = mutt_mkname (buf);
833     news->cache = m_strdup(buf);
834     nntp_cache_expand (file, buf);
835   }
836   if (!f)
837     return -1;
838
839   for (l = news->list; l; l = l->next) {
840     if ((d = (NNTP_DATA *) l->data) && !d->deleted) {
841       if (d->desc)
842         snprintf (buf, sizeof (buf), "%s %d %d %c %s\n", d->group,
843                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n',
844                   d->desc);
845       else
846         snprintf (buf, sizeof (buf), "%s %d %d %c\n", d->group,
847                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n');
848       if (fputs (buf, f) == EOF) {
849         m_fclose(&f);
850         unlink (file);
851         return -1;
852       }
853     }
854   }
855   m_fclose(&f);
856
857   if (nntp_update_cacheindex (news, NULL)) {
858     unlink (file);
859     return -1;
860   }
861   return 0;
862 }
863
864 int nntp_save_cache_group (CONTEXT * ctx)
865 {
866   char buf[HUGE_STRING], addr[STRING];
867   char file[_POSIX_PATH_MAX];
868   FILE *f;
869   HEADER *h;
870   struct tm *tm;
871   int i = 0, save = SORT_ORDER;
872   int prev = 0;
873
874   if (!option (OPTNEWSCACHE))
875     return 0;
876   if (!ctx || !ctx->data || ctx->magic != M_NNTP)
877     return -1;
878
879   if (((NNTP_DATA *) ctx->data)->cache) {
880     nntp_cache_expand (file, ((NNTP_DATA *) ctx->data)->cache);
881     unlink (file);
882     f = safe_fopen (file, "w");
883   }
884   else {
885     snprintf (buf, sizeof (buf), "%s-%s",
886               ((NNTP_DATA *) ctx->data)->nserv->conn->account.host,
887               ((NNTP_DATA *) ctx->data)->group);
888     f = mutt_mkname (buf);
889     ((NNTP_DATA *) ctx->data)->cache = m_strdup(buf);
890     nntp_cache_expand (file, buf);
891   }
892   if (!f)
893     return -1;
894
895   if (Sort != SORT_ORDER) {
896     save = Sort;
897     Sort = SORT_ORDER;
898     mutt_sort_headers (ctx, 0);
899   }
900
901   /* Save only $nntp_context messages... */
902   ((NNTP_DATA *) ctx->data)->lastCached = 0;
903   if (NntpContext && ctx->msgcount > NntpContext)
904     i = ctx->msgcount - NntpContext;
905   for (; i < ctx->msgcount; i++) {
906     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->article_num != prev) {
907       h = ctx->hdrs[i];
908       addr[0] = 0;
909       rfc822_write_address (addr, sizeof (addr), h->env->from, 0);
910       tm = gmtime (&h->date_sent);
911       snprintf (buf, sizeof (buf),
912                 "%d\t%s\t%s\t%d %s %d %02d:%02d:%02d GMT\t%s\t",
913                 h->article_num, h->env->subject, addr, tm->tm_mday,
914                 Months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour,
915                 tm->tm_min, tm->tm_sec, h->env->message_id);
916       fputs (buf, f);
917       if (h->env->references)
918         mutt_write_references (h->env->references, f);
919       snprintf (buf, sizeof (buf), "\t%zd\t%d\tXref: %s\n",
920                 h->content->length, h->lines, NONULL (h->env->xref));
921       if (fputs (buf, f) == EOF) {
922         m_fclose(&f);
923         unlink (file);
924         return -1;
925       }
926     }
927     prev = ctx->hdrs[i]->article_num;
928   }
929
930   if (save != Sort) {
931     Sort = save;
932     mutt_sort_headers (ctx, 0);
933   }
934   m_fclose(&f);
935
936   if (nntp_update_cacheindex (((NNTP_DATA *) ctx->data)->nserv,
937                               (NNTP_DATA *) ctx->data)) {
938     unlink (file);
939     return -1;
940   }
941   ((NNTP_DATA *) ctx->data)->lastCached =
942     ((NNTP_DATA *) ctx->data)->lastLoaded;
943   return 0;
944 }
945
946 void nntp_delete_cache (NNTP_DATA * data)
947 {
948   char buf[_POSIX_PATH_MAX];
949
950   if (!option (OPTNEWSCACHE) || !data || !data->cache || !data->nserv)
951     return;
952
953   nntp_cache_expand (buf, data->cache);
954   unlink (buf);
955   p_delete(&data->cache);
956   data->lastCached = 0;
957   nntp_cache_expand (buf, ".index");
958   mutt_update_list_file (buf, data->nserv->conn->account.host, data->group,
959                          NULL);
960 }
961
962 NNTP_DATA *mutt_newsgroup_subscribe (NNTP_SERVER * news, char *group)
963 {
964   NNTP_DATA *data;
965
966   if (!news || !news->newsgroups || !group || !*group)
967     return NULL;
968   if (!(data = (NNTP_DATA *) hash_find (news->newsgroups, group))) {
969     data = xmalloc(sizeof(NNTP_DATA) + m_strlen(group) + 1);
970     data->group = (char *) data + sizeof (NNTP_DATA);
971     strcpy (data->group, group);
972     data->nserv = news;
973     data->deleted = 1;
974     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
975       news->newsgroups =
976         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
977     hash_insert (news->newsgroups, data->group, data, 0);
978     nntp_add_to_list (news, data);
979   }
980   if (!data->subscribed) {
981     data->subscribed = 1;
982     data->rc = 1;
983   }
984   return data;
985 }
986
987 NNTP_DATA *mutt_newsgroup_unsubscribe (NNTP_SERVER * news, char *group)
988 {
989   NNTP_DATA *data;
990
991   if (!news || !news->newsgroups || !group || !*group ||
992       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
993     return NULL;
994   if (data->subscribed) {
995     data->subscribed = 0;
996     if (!option (OPTSAVEUNSUB))
997       data->rc = 0;
998   }
999   return data;
1000 }
1001
1002 NNTP_DATA *mutt_newsgroup_catchup (NNTP_SERVER * news, char *group)
1003 {
1004   NNTP_DATA *data;
1005
1006   if (!news || !news->newsgroups || !group || !*group ||
1007       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
1008     return NULL;
1009   if (!data->max) {
1010     data->entries = p_new(NEWSRC_ENTRY, 5);
1011     data->max = 5;
1012   }
1013   data->num = 1;
1014   data->entries[0].first = 1;
1015   data->unread = 0;
1016   data->entries[0].last = data->lastMessage;
1017   if (Context && Context->data == data) {
1018     int x;
1019
1020     for (x = 0; x < Context->msgcount; x++)
1021       mutt_set_flag (Context, Context->hdrs[x], M_READ, 1);
1022   }
1023   return data;
1024 }
1025
1026 NNTP_DATA *mutt_newsgroup_uncatchup (NNTP_SERVER * news, char *group)
1027 {
1028   NNTP_DATA *data;
1029
1030   if (!news || !news->newsgroups || !group || !*group ||
1031       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
1032     return NULL;
1033   if (!data->max) {
1034     data->entries = p_new(NEWSRC_ENTRY, 5);
1035     data->max = 5;
1036   }
1037   data->num = 1;
1038   data->entries[0].first = 1;
1039   data->entries[0].last = data->firstMessage - 1;
1040   if (Context && Context->data == data) {
1041     int x;
1042
1043     data->unread = Context->msgcount;
1044     for (x = 0; x < Context->msgcount; x++)
1045       mutt_set_flag (Context, Context->hdrs[x], M_READ, 0);
1046   }
1047   else
1048     data->unread = data->lastMessage - data->entries[0].last;
1049   return data;
1050 }
1051
1052 /* this routine gives the first newsgroup with new messages */
1053 void nntp_buffy (char* dst, ssize_t dstlen) {
1054   string_list_t *list;
1055   int count = 0;
1056
1057   /* forward to current group */
1058   for (list = CurrentNewsSrv->list; list; list = list->next) {
1059     NNTP_DATA *data = (NNTP_DATA *) list->data;
1060     if (data && data->subscribed && data->unread && 
1061         Context && Context->magic == M_NNTP &&
1062         m_strcmp(data->group, ((NNTP_DATA *) Context->data)->group) == 0) {
1063       list = list->next;
1064       break;
1065     }
1066   }
1067
1068   *dst = '\0';
1069
1070   while (count < 2) {
1071
1072     if (!list)
1073       list = CurrentNewsSrv->list;
1074
1075     for (; list; list = list->next) {
1076       NNTP_DATA *data = (NNTP_DATA *) list->data;
1077
1078       if (data && data->subscribed && data->unread) {
1079         if (Context && Context->magic == M_NNTP &&
1080             !m_strcmp(data->group, ((NNTP_DATA *) Context->data)->group)) {
1081           unsigned int i, unread = 0;
1082
1083           for (i = 0; i < Context->msgcount; i++)
1084             if (!Context->hdrs[i]->read && !Context->hdrs[i]->deleted)
1085               unread++;
1086           if (!unread)
1087             continue;
1088         }
1089         m_strcpy(dst, dstlen, data->group);
1090         break;
1091       }
1092     }
1093     /* done if found */
1094     if (dst && *dst)
1095       return;
1096     count++;
1097   }
1098   *dst = '\0';
1099 }