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