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