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