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