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