Deep rework of nntp_data_t (ex-NNTP_DATA) to make it list-able.
[apps/madmutt.git] / nntp.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-2002 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-ui/sidebar.h>
19 #include <lib-mx/mx.h>
20
21 #include "mutt.h"
22 #include "sort.h"
23 #include "nntp.h"
24 #include "buffy.h"
25 #include "crypt.h"
26
27 #define NNTP_PORT      119
28 #define NNTP_SSL_PORT  563
29
30 static int nntp_get_cache_all (NNTP_SERVER *);
31 static int nntp_check_newgroups (NNTP_SERVER *, int);
32 static void mutt_newsgroup_stat (nntp_data_t *);
33 static void nntp_delete_cache (nntp_data_t *);
34
35 /* newsrc {{{ */
36
37 static int nntp_parse_newsrc_line (NNTP_SERVER * news, char *line)
38 {
39   nntp_data_t *data;
40   char group[LONG_STRING];
41   int x = 1;
42   char *p, *b, *h;
43
44   for (p = line; p; p = strchr(p, ',')) {
45     x++;
46   }
47
48   p = strpbrk(line, ":!");
49   if (!p)
50     return -1;
51
52   m_strncpy(group, ssizeof(group), line, p - line);
53   if ((data = (nntp_data_t *) hash_find (news->newsgroups, group)) == NULL) {
54     data = xmalloc(sizeof(nntp_data_t) + m_strlen(group) + 1);
55     data->group = (char *) data + sizeof (nntp_data_t);
56     strcpy (data->group, group);
57     data->nserv = news;
58     data->deleted = 1;
59     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
60         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
61     hash_insert (news->newsgroups, data->group, data);
62     nntp_data_list_append(&news->list, data);
63   } else {
64     p_delete(&data->entries);
65   }
66
67   data->rc = 1;
68   data->entries = p_new(NEWSRC_ENTRY, x * 2);
69   data->max = x * 2;
70
71   data->subscribed = (*p++ == ':');
72
73   b = p;
74   x = 0;
75   while (*b) {
76     while (*p && *p != ',' && *p != '\n')
77       p++;
78     if (*p) {
79       *p = '\0';
80       p++;
81     }
82     if ((h = strchr (b, '-'))) {
83       *h = '\0';
84       h++;
85       data->entries[x].first = atoi (b);
86       data->entries[x].last = atoi (h);
87     }
88     else {
89       data->entries[x].first = atoi (b);
90       data->entries[x].last = data->entries[x].first;
91     }
92     b = p;
93     if (data->entries[x].last != 0)
94       x++;
95   }
96   if (x && !data->lastMessage)
97     data->lastMessage = data->entries[x - 1].last;
98   data->num = x;
99   mutt_newsgroup_stat (data);
100
101   return 0;
102 }
103
104 static int slurp_newsrc (NNTP_SERVER * news)
105 {
106   FILE *fp;
107   char *buf;
108   struct stat sb;
109
110   news->stat = stat (news->newsrc, &sb);
111   news->size = sb.st_size;
112   news->mtime = sb.st_mtime;
113
114   if ((fp = safe_fopen (news->newsrc, "r")) == NULL)
115     return -1;
116   /* hmm, should we use dotlock? */
117   if (mx_lock_file (news->newsrc, fileno (fp), 0, 0, 1)) {
118     m_fclose(&fp);
119     return -1;
120   }
121
122   buf = p_new(char, sb.st_size + 1);
123   while (fgets (buf, sb.st_size + 1, fp))
124     nntp_parse_newsrc_line (news, buf);
125   p_delete(&buf);
126
127   mx_unlock_file (news->newsrc, fileno (fp), 0);
128   m_fclose(&fp);
129   return 0;
130 }
131
132 static void nntp_cache_expand (char *dst, const char *src)
133 {
134   snprintf (dst, _POSIX_PATH_MAX, "%s/%s", NewsCacheDir, src);
135   mutt_expand_path (dst, _POSIX_PATH_MAX);
136 }
137
138 /* Loads $news_cache_dir/.index into memory, loads newsserver data
139  * and newsgroup cache names */
140 static int nntp_parse_cacheindex (NNTP_SERVER * news)
141 {
142   struct stat st;
143   char buf[HUGE_STRING], *cp;
144   char dir[_POSIX_PATH_MAX], file[_POSIX_PATH_MAX];
145   FILE *idx;
146   nntp_data_t *data;
147   int l, m, t;
148
149   /* check is server name defined or not */
150   if (!news || !news->conn || !news->conn->account.host)
151     return -1;
152   unset_option (OPTNEWSCACHE);
153   if (m_strisempty(NewsCacheDir))
154     return 0;
155
156   m_strcpy(dir, sizeof(dir), NewsCacheDir);
157   mutt_expand_path (dir, sizeof (dir));
158
159   if (lstat (dir, &st) || (st.st_mode & S_IFDIR) == 0) {
160     snprintf (buf, sizeof (buf), _("Directory %s not exist. Create it?"),
161               dir);
162     if (mutt_yesorno (buf, M_YES) != M_YES
163         || mkdir (dir, (S_IRWXU + S_IRWXG + S_IRWXO))) {
164       mutt_error _("Cache directory not created!");
165
166       return -1;
167     }
168     mutt_clear_error ();
169   }
170
171   set_option (OPTNEWSCACHE);
172
173   p_delete(&news->cache);
174   snprintf (buf, sizeof (buf), "%s/.index", dir);
175   if (!(idx = safe_fopen (buf, "a+")))
176     return 0;
177   rewind (idx);
178   while (fgets (buf, sizeof (buf), idx)) {
179     buf[m_strlen(buf) - 1] = 0;  /* strip ending '\n' */
180     if (!m_strncmp(buf, "#: ", 3) &&
181         !m_strcasecmp(buf + 3, news->conn->account.host))
182       break;
183   }
184   while (fgets (buf, sizeof (buf), idx)) {
185     cp = buf;
186     while (*cp && *cp != ' ')
187       cp++;
188     if (!*cp)
189       continue;
190     cp[0] = 0;
191     if (!m_strcmp(buf, "#:"))
192       break;
193     sscanf (cp + 1, "%s %d %d", file, &l, &m);
194     if (!m_strcmp(buf, "ALL")) {
195       news->cache = m_strdup(file);
196       news->newgroups_time = m;
197     }
198     else if (news->newsgroups) {
199       if ((data = (nntp_data_t *) hash_find (news->newsgroups, buf)) == NULL) {
200         data = xmalloc(sizeof(nntp_data_t) + m_strlen(buf) + 1);
201         data->group = (char *) data + sizeof (nntp_data_t);
202         strcpy (data->group, buf);
203         data->nserv = news;
204         data->deleted = 1;
205         if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
206             hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
207         hash_insert (news->newsgroups, data->group, data);
208         nntp_data_list_append(&news->list, data);
209       }
210       data->cache = m_strdup(file);
211       t = 0;
212       if (!data->firstMessage || data->lastMessage < m)
213         t = 1;
214       if (!data->firstMessage)
215         data->firstMessage = l;
216       if (data->lastMessage < m)
217         data->lastMessage = m;
218       data->lastCached = m;
219       if (t || !data->unread)
220         mutt_newsgroup_stat (data);
221     }
222   }
223   m_fclose(&idx);
224   return 0;
225 }
226
227 const char *nntp_format_str(char *dest, ssize_t destlen, char op,
228                             const char *src, const char *fmt,
229                             const char *ifstr __attribute__((unused)),
230                             const char *elstr __attribute__((unused)),
231                             anytype data __attribute__((unused)),
232                             format_flag flags __attribute__((unused)))
233 {
234   char fn[STRING], tmp[STRING];
235
236   switch (op) {
237   case 's':
238     m_strcpy(fn, sizeof (fn), NewsServer);
239     m_strtolower(fn);
240     snprintf (tmp, sizeof (tmp), "%%%ss", fmt);
241     snprintf (dest, destlen, tmp, fn);
242     break;
243   }
244   return (src);
245 }
246
247 /* nntp_parse_url: given an NNPT URL, return host, port,
248  * username, password and newsgroup will recognise. */
249 static int nntp_parse_url(const char *server, ACCOUNT * act, char *group,
250                           ssize_t group_len)
251 {
252   ciss_url_t url;
253   char *c;
254   int ret = -1;
255
256   /* Defaults */
257   act->flags = 0;
258   act->port = NNTP_PORT;
259   act->type = M_ACCT_TYPE_NNTP;
260
261   c = m_strdup(server);
262   url_parse_ciss (&url, c);
263
264   if (url.scheme == U_NNTP || url.scheme == U_NNTPS) {
265     if (url.scheme == U_NNTPS) {
266       act->has_ssl = 1;
267       act->port = NNTP_SSL_PORT;
268     }
269
270     *group = '\0';
271     if (url.path)
272       m_strcpy(group, group_len, url.path);
273
274     ret = mutt_account_fromurl (act, &url);
275   }
276
277   p_delete(&c);
278   return ret;
279 }
280
281 void nntp_expand_path (char *line, ssize_t len, ACCOUNT * act)
282 {
283   ciss_url_t url;
284
285   url.path = m_strdup(line);
286   mutt_account_tourl (act, &url);
287   url_ciss_tostring (&url, line, len, 0);
288   p_delete(&url.path);
289 }
290
291 /*
292  * Automatically loads a newsrc into memory, if necessary.
293  * Checks the size/mtime of a newsrc file, if it doesn't match, load
294  * again.  Hmm, if a system has broken mtimes, this might mean the file
295  * is reloaded every time, which we'd have to fix.
296  *
297  * a newsrc file is a line per newsgroup, with the newsgroup, then a 
298  * ':' denoting subscribed or '!' denoting unsubscribed, then a 
299  * comma separated list of article numbers and ranges.
300  */
301 NNTP_SERVER *mutt_select_newsserver (char *server)
302 {
303   char file[_POSIX_PATH_MAX];
304   char *buf, *p;
305   nntp_data_t *list;
306   ACCOUNT act;
307   NNTP_SERVER *serv;
308   CONNECTION *conn;
309
310   p_clear(&act, 1);
311
312   if (!server || !*server) {
313     mutt_error _("No newsserver defined!");
314
315     return NULL;
316   }
317
318   buf = p = p_new(char, m_strlen(server) + 10);
319   if (url_check_scheme (server) == U_UNKNOWN) {
320     strcpy (buf, "nntp://");
321     p = strchr (buf, '\0');
322   }
323   strcpy (p, server);
324
325   if ((nntp_parse_url (buf, &act, file, sizeof (file))) < 0 || *file) {
326     p_delete(&buf);
327     mutt_error (_("%s is an invalid newsserver specification!"), server);
328     return NULL;
329   }
330   p_delete(&buf);
331
332   conn = mutt_conn_find (NULL, &act);
333   if (!conn)
334     return NULL;
335
336   m_strformat(file, sizeof(file), 0, NewsRc, nntp_format_str, NULL, 0);
337   mutt_expand_path(file, sizeof(file));
338
339   serv = (NNTP_SERVER *) conn->data;
340   if (serv) {
341     struct stat sb;
342
343     /* externally modified? */
344     if (serv->stat != stat(file, &sb) || (!serv->stat &&
345                                            (serv->size != sb.st_size
346                                             || serv->mtime != sb.st_mtime)))
347     {
348       for (list = serv->list; list; list = list->next) {
349         list->subscribed = 0;
350         list->rc = 0;
351         list->num = 0;
352       }
353       slurp_newsrc (serv);
354       nntp_clear_cacheindex (serv);
355     }
356
357     if (serv->status == NNTP_BYE)
358       serv->status = NNTP_NONE;
359     nntp_check_newgroups (serv, 0);
360     return serv;
361   }
362
363   /* New newsserver */
364   serv = p_new(NNTP_SERVER, 1);
365   serv->conn = conn;
366   serv->newsrc = m_strdup(file);
367   serv->newsgroups = hash_new(1009, false);
368   slurp_newsrc (serv);          /* load .newsrc */
369   nntp_parse_cacheindex (serv); /* load .index */
370   if (option (OPTNEWSCACHE) && serv->cache && nntp_get_cache_all (serv) >= 0)
371     nntp_check_newgroups (serv, 1);
372   else if (nntp_get_active (serv) < 0) {
373     hash_delete(&serv->newsgroups, NULL);
374     nntp_data_list_wipe(&serv->list);
375     p_delete(&serv->newsrc);
376     p_delete(&serv->cache);
377     p_delete(&serv);
378     return NULL;
379   }
380   nntp_clear_cacheindex (serv);
381   conn->data = (void *) serv;
382
383   return serv;
384 }
385
386 /* 
387  * full status flags are not supported by nntp, but we can fake some
388  * of them.  This is how:
389  * Read = a read message number is in the .newsrc
390  * New = a message is new since we last read this newsgroup
391  * Old = anything else
392  * So, Read is marked as such in the newsrc, old is anything that is 
393  * "skipped" in the newsrc, and new is anything not in the newsrc nor
394  * in the cache. By skipped, I mean before the last unread message
395  */
396 static void nntp_get_status(CONTEXT *ctx, HEADER *h, char *group, int article)
397 {
398   nntp_data_t *data = (nntp_data_t *) ctx->data;
399   int x;
400
401   if (group)
402     data = (nntp_data_t *) hash_find (data->nserv->newsgroups, group);
403
404   if (!data) {
405     return;
406   }
407
408   for (x = 0; x < data->num; x++) {
409     if ((article >= data->entries[x].first) &&
410         (article <= data->entries[x].last)) {
411       /* we cannot use mutt_set_flag() because mx_update_context()
412          didn't called yet */
413       h->read = 1;
414       return;
415     }
416   }
417   /* If article was not cached yet, it is new! :) */
418   if (!data->cache || article > data->lastCached)
419     return;
420   /* Old articles are articles which aren't read but an article after them
421    * has been cached */
422   if (option (OPTMARKOLD))
423     h->old = 1;
424 }
425
426 static void mutt_newsgroup_stat (nntp_data_t * data)
427 {
428   int i, first, last;
429
430   data->unread = 0;
431   if (data->lastMessage == 0 || data->firstMessage > data->lastMessage)
432     return;
433
434   data->unread = data->lastMessage - data->firstMessage + 1;
435   for (i = 0; i < data->num; i++) {
436     first = data->entries[i].first;
437     if (first < data->firstMessage)
438       first = data->firstMessage;
439     last = data->entries[i].last;
440     if (last > data->lastMessage)
441       last = data->lastMessage;
442     if (first <= last)
443       data->unread -= last - first + 1;
444   }
445 }
446
447 static int puti (char *line, int num)
448 {
449   char *p, s[32];
450
451   for (p = s; num;) {
452     *p++ = '0' + num % 10;
453     num /= 10;
454   }
455   while (p > s)
456     *line++ = *--p, num++;
457   *line = '\0';
458   return num;
459 }
460
461 static void nntp_create_newsrc_line (nntp_data_t * data, char **buf,
462                                      char **pline, ssize_t * buflen)
463 {
464   char *line = *pline;
465   ssize_t len = *buflen - (*pline - *buf);
466   int x, i;
467
468   if (len < LONG_STRING * 10) {
469     len += *buflen;
470     *buflen *= 2;
471     line = *buf;
472     p_realloc(buf, *buflen);
473     line = *buf + (*pline - line);
474   }
475   strcpy (line, data->group);
476   len -= m_strlen(line) + 1;
477   line += m_strlen(line);
478   *line++ = data->subscribed ? ':' : '!';
479   *line++ = ' ';
480   *line = '\0';
481
482   for (x = 0; x < data->num; x++) {
483     if (len < LONG_STRING) {
484       len += *buflen;
485       *buflen *= 2;
486       *pline = line;
487       line = *buf;
488       p_realloc(buf, *buflen);
489       line = *buf + (*pline - line);
490     }
491     if (x) {
492       *line++ = ',';
493       len--;
494     }
495
496     i = puti (line, data->entries[x].first);
497     line += i;
498     len -= i;
499     if (data->entries[x].first != data->entries[x].last) {
500       *line++ = '-';
501       len--;
502       i = puti (line, data->entries[x].last);
503       line += i;
504       len -= i;
505     }
506   }
507   *line++ = '\n';
508   *line = '\0';
509   *pline = line;
510 }
511
512 static void newsrc_gen_entries (CONTEXT * ctx)
513 {
514   nntp_data_t *data = (nntp_data_t *) ctx->data;
515   int series, x;
516   int last = 0, first = 1;
517   int save_sort = SORT_ORDER;
518
519   if (Sort != SORT_ORDER) {
520     save_sort = Sort;
521     Sort = SORT_ORDER;
522     mutt_sort_headers (ctx, 0);
523   }
524
525   if (!data->max) {
526     data->entries = p_new(NEWSRC_ENTRY, 5);
527     data->max = 5;
528   }
529
530   /*
531    * Set up to fake initial sequence from 1 to the article before the 
532    * first article in our list
533    */
534   data->num = 0;
535   series = 1;
536
537   for (x = 0; x < ctx->msgcount; x++) {
538     if (series) {               /* search for first unread */
539       /*
540        * We don't actually check sequential order, since we mark 
541        * "missing" entries as read/deleted
542        */
543       last = ctx->hdrs[x]->article_num;
544       if (last >= data->firstMessage && !ctx->hdrs[x]->deleted &&
545           !ctx->hdrs[x]->read) {
546         if (data->num >= data->max) {
547           data->max = data->max * 2;
548           p_realloc(&data->entries, data->max);
549         }
550         data->entries[data->num].first = first;
551         data->entries[data->num].last = last - 1;
552         data->num++;
553         series = 0;
554       }
555     }
556     else {                      /* search for first read */
557
558       if (ctx->hdrs[x]->deleted || ctx->hdrs[x]->read) {
559         first = last + 1;
560         series = 1;
561       }
562       last = ctx->hdrs[x]->article_num;
563     }
564   }
565   if (series && first <= data->lastLoaded) {
566     if (data->num >= data->max) {
567       data->max = data->max * 2;
568       p_realloc(&data->entries, data->max);
569     }
570     data->entries[data->num].first = first;
571     data->entries[data->num].last = data->lastLoaded;
572     data->num++;
573   }
574
575   if (save_sort != Sort) {
576     Sort = save_sort;
577     mutt_sort_headers (ctx, 0);
578   }
579 }
580
581 static int mutt_update_list_file (char *filename, char *section,
582                                   const char *key, char *line) {
583   FILE *ifp;
584   FILE *ofp;
585   char buf[HUGE_STRING];
586   char tmpf[_POSIX_PATH_MAX], lnk[_POSIX_PATH_MAX];
587   char *c;
588   int ext = 0, done = 0, r = 0, l = 0;
589
590   /* if file not exist, create it */
591   if ((ifp = safe_fopen (filename, "a")))
592     m_fclose(&ifp);
593   if (!(ifp = safe_fopen (filename, "r"))) {
594     mutt_error (_("Unable to open %s for reading"), filename);
595     return -1;
596   }
597   if (mx_lock_file (filename, fileno (ifp), 0, 0, 1)) {
598     m_fclose(&ifp);
599     mutt_error (_("Unable to lock %s"), filename);
600     return -1;
601   }
602
603   /* use m_tempfile() to get a tempfile in the same
604    * directory as filename is so that we can follow symlinks
605    * via rename(2); as dirname(2) may modify its argument,
606    * temporarily use buf as copy of it
607    */
608   m_strcpy(buf, sizeof(buf), filename);
609   ofp = m_tempfile(tmpf, sizeof(tmpf), dirname(buf), filename);
610   if (!ofp) {
611     m_fclose(&ifp);
612     mutt_error (_("Unable to open %s for writing"), tmpf);
613     return -1;
614   }
615
616   if (section) {
617     while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
618       r = fputs (buf, ofp);
619       c = buf;
620       while (*c && *c != '\n') c++;
621       c[0] = 0; /* strip EOL */
622       if (!strncmp (buf, "#: ", 3) && !m_strcasecmp(buf+3, section))
623         done++;
624     }
625     if (r != EOF && !done) {
626       snprintf (buf, sizeof(buf), "#: %s\n", section);
627       r = fputs (buf, ofp);
628     }
629     done = 0;
630   }
631
632   while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
633     if (ext) {
634       c = buf;
635       while (*c && (*c != '\r') && (*c != '\n')) c++;
636       c--;
637       if (*c != '\\') ext = 0;
638     } else if ((section && !strncmp (buf, "#: ", 3))) {
639       if (!done && line) {
640         fputs (line, ofp);
641         fputc ('\n', ofp);
642       }
643       r = fputs (buf, ofp);
644       done++;
645       break;
646     } else if (key && !strncmp (buf, key, strlen(key)) &&
647                (!*key || buf[strlen(key)] == ' ')) {
648       c = buf;
649       ext = 0;
650       while (*c && (*c != '\r') && (*c != '\n')) c++;
651       c--;
652       if (*c == '\\') ext = 1;
653       if (!done && line) {
654         r = fputs (line, ofp);
655         if (*key)
656           r = fputc ('\n', ofp);
657         done++;
658       }
659     } else {
660       r = fputs (buf, ofp);
661     }
662   }
663
664   while (r != EOF && fgets (buf, sizeof (buf), ifp))
665     r = fputs (buf, ofp);
666
667   /* If there wasn't a line to replace, put it on the end of the file */
668   if (r != EOF && !done && line) {
669     fputs (line, ofp);
670     r = fputc ('\n', ofp);
671   }
672   mx_unlock_file (filename, fileno (ifp), 0);
673   m_fclose(&ofp);
674   m_fclose(&ifp);
675   if (r == EOF) {
676     unlink (tmpf);
677     mutt_error (_("Can't write %s"), tmpf);
678     return -1;
679   }
680   lnk[0] = '\0';
681   if ((l = readlink (filename, lnk, sizeof(lnk)-1)) > 0)
682     lnk[l] = '\0';
683   if (rename (tmpf, l > 0 ? lnk : filename) < 0) {
684     unlink (tmpf);
685     mutt_error (_("Can't rename %s to %s"), tmpf, l > 0 ? lnk : filename);
686     return -1;
687   }
688   return 0;
689 }
690
691 int mutt_newsrc_update (NNTP_SERVER * news)
692 {
693   char *buf, *line;
694   nntp_data_t *data;
695   int r = -1;
696   ssize_t len, llen;
697
698   if (!news)
699     return -1;
700   llen = len = 10 * LONG_STRING;
701   line = buf = p_new(char, len);
702   /* we will generate full newsrc here */
703   for (data = news->list; data; data = data->next) {
704     if (!data || !data->rc)
705       continue;
706     nntp_create_newsrc_line (data, &buf, &line, &llen);
707     line += m_strlen(line);
708   }
709   /* newrc being fully rewritten */
710   if (news->newsrc &&
711       (r = mutt_update_list_file(news->newsrc, NULL, "", buf)) == 0) {
712     struct stat st;
713
714     stat (news->newsrc, &st);
715     news->size = st.st_size;
716     news->mtime = st.st_mtime;
717   }
718   p_delete(&buf);
719   return r;
720 }
721
722 static FILE *mutt_mkname (char *s)
723 {
724   char buf[_POSIX_PATH_MAX], *pc;
725   int fd;
726   FILE *fp;
727
728   nntp_cache_expand (buf, s);
729   if ((fp = safe_fopen (buf, "w")))
730     return fp;
731
732   nntp_cache_expand (buf, "cache-XXXXXX");
733   pc = buf + m_strlen(buf) - 12; /* positioning to "cache-XXXXXX" */
734   if ((fd = mkstemp (buf)) == -1)
735     return NULL;
736   strcpy (s, pc);               /* generated name */
737   return fdopen (fd, "w");
738 }
739
740 /* Updates info into .index file: ALL or about selected newsgroup */
741 static int nntp_update_cacheindex (NNTP_SERVER * serv, nntp_data_t * data)
742 {
743   char buf[LONG_STRING];
744   char file[_POSIX_PATH_MAX];
745   const char *key = "ALL";
746
747   if (!serv || !serv->conn || !serv->conn->account.host)
748     return -1;
749
750   if (data && data->group) {
751     key = data->group;
752     snprintf (buf, sizeof (buf), "%s %s %d %d", key, data->cache,
753               data->firstMessage, data->lastLoaded);
754   }
755   else {
756     m_strcpy(file, sizeof(file), serv->cache);
757     snprintf (buf, sizeof (buf), "ALL %s 0 %d", file,
758               (int) serv->newgroups_time);
759   }
760   nntp_cache_expand (file, ".index");
761   return mutt_update_list_file (file, serv->conn->account.host, key, buf);
762 }
763
764 /* Remove cache files of unsubscribed newsgroups */
765 void nntp_clear_cacheindex (NNTP_SERVER * news)
766 {
767   nntp_data_t *data;
768
769   if (option (OPTSAVEUNSUB) || !news)
770     return;
771
772   for (data = news->list; data; data = data->next) {
773     if (!data || data->subscribed || !data->cache)
774       continue;
775     nntp_delete_cache (data);
776   }
777   return;
778 }
779
780 static int nntp_save_cache_index (NNTP_SERVER * news)
781 {
782   char buf[HUGE_STRING];
783   char file[_POSIX_PATH_MAX];
784   nntp_data_t *d;
785   FILE *f;
786
787   if (!news || !news->newsgroups)
788     return -1;
789   if (!option (OPTNEWSCACHE))
790     return 0;
791
792   if (news->cache) {
793     nntp_cache_expand (file, news->cache);
794     unlink (file);
795     f = safe_fopen (file, "w");
796   }
797   else {
798     m_strcpy(buf, sizeof(buf), news->conn->account.host);
799     f = mutt_mkname (buf);
800     news->cache = m_strdup(buf);
801     nntp_cache_expand (file, buf);
802   }
803   if (!f)
804     return -1;
805
806   for (d = news->list; d; d = d->next) {
807     if (!d->deleted) {
808       if (d->desc)
809         snprintf (buf, sizeof (buf), "%s %d %d %c %s\n", d->group,
810                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n',
811                   d->desc);
812       else
813         snprintf (buf, sizeof (buf), "%s %d %d %c\n", d->group,
814                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n');
815       if (fputs (buf, f) == EOF) {
816         m_fclose(&f);
817         unlink (file);
818         return -1;
819       }
820     }
821   }
822   m_fclose(&f);
823
824   if (nntp_update_cacheindex (news, NULL)) {
825     unlink (file);
826     return -1;
827   }
828   return 0;
829 }
830
831 static int nntp_save_cache_group (CONTEXT * ctx)
832 {
833   char buf[HUGE_STRING], addr[STRING];
834   char file[_POSIX_PATH_MAX];
835   FILE *f;
836   HEADER *h;
837   struct tm *tm;
838   int i = 0, save = SORT_ORDER;
839   int prev = 0;
840
841   if (!option (OPTNEWSCACHE))
842     return 0;
843   if (!ctx || !ctx->data || ctx->magic != M_NNTP)
844     return -1;
845
846   if (((nntp_data_t *) ctx->data)->cache) {
847     nntp_cache_expand (file, ((nntp_data_t *) ctx->data)->cache);
848     unlink (file);
849     f = safe_fopen (file, "w");
850   }
851   else {
852     snprintf (buf, sizeof (buf), "%s-%s",
853               ((nntp_data_t *) ctx->data)->nserv->conn->account.host,
854               ((nntp_data_t *) ctx->data)->group);
855     f = mutt_mkname (buf);
856     ((nntp_data_t *) ctx->data)->cache = m_strdup(buf);
857     nntp_cache_expand (file, buf);
858   }
859   if (!f)
860     return -1;
861
862   if (Sort != SORT_ORDER) {
863     save = Sort;
864     Sort = SORT_ORDER;
865     mutt_sort_headers (ctx, 0);
866   }
867
868   /* Save only $nntp_context messages... */
869   ((nntp_data_t *) ctx->data)->lastCached = 0;
870   if (NntpContext && ctx->msgcount > NntpContext)
871     i = ctx->msgcount - NntpContext;
872   for (; i < ctx->msgcount; i++) {
873     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->article_num != prev) {
874       h = ctx->hdrs[i];
875       addr[0] = 0;
876       rfc822_addrcat(addr, sizeof(addr), h->env->from, 0);
877       tm = gmtime (&h->date_sent);
878       snprintf (buf, sizeof (buf),
879                 "%d\t%s\t%s\t%d %s %d %02d:%02d:%02d GMT\t%s\t",
880                 h->article_num, h->env->subject, addr, tm->tm_mday,
881                 Months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour,
882                 tm->tm_min, tm->tm_sec, h->env->message_id);
883       fputs (buf, f);
884       if (h->env->references)
885         mutt_write_references (h->env->references, f);
886       snprintf (buf, sizeof (buf), "\t%zd\t%d\tXref: %s\n",
887                 h->content->length, h->lines, NONULL (h->env->xref));
888       if (fputs (buf, f) == EOF) {
889         m_fclose(&f);
890         unlink (file);
891         return -1;
892       }
893     }
894     prev = ctx->hdrs[i]->article_num;
895   }
896
897   if (save != Sort) {
898     Sort = save;
899     mutt_sort_headers (ctx, 0);
900   }
901   m_fclose(&f);
902
903   if (nntp_update_cacheindex (((nntp_data_t *) ctx->data)->nserv,
904                               (nntp_data_t *) ctx->data)) {
905     unlink (file);
906     return -1;
907   }
908   ((nntp_data_t *) ctx->data)->lastCached =
909     ((nntp_data_t *) ctx->data)->lastLoaded;
910   return 0;
911 }
912
913 static void nntp_delete_cache (nntp_data_t * data)
914 {
915   char buf[_POSIX_PATH_MAX];
916
917   if (!option (OPTNEWSCACHE) || !data || !data->cache || !data->nserv)
918     return;
919
920   nntp_cache_expand (buf, data->cache);
921   unlink (buf);
922   p_delete(&data->cache);
923   data->lastCached = 0;
924   nntp_cache_expand (buf, ".index");
925   mutt_update_list_file (buf, data->nserv->conn->account.host, data->group,
926                          NULL);
927 }
928
929 nntp_data_t *mutt_newsgroup_subscribe (NNTP_SERVER * news, char *group)
930 {
931   nntp_data_t *data;
932
933   if (!news || !news->newsgroups || !group || !*group)
934     return NULL;
935   if (!(data = (nntp_data_t *) hash_find (news->newsgroups, group))) {
936     data = xmalloc(sizeof(nntp_data_t) + m_strlen(group) + 1);
937     data->group = (char *) data + sizeof (nntp_data_t);
938     strcpy (data->group, group);
939     data->nserv = news;
940     data->deleted = 1;
941     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
942         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
943     hash_insert (news->newsgroups, data->group, data);
944     nntp_data_list_append(&news->list, data);
945   }
946   if (!data->subscribed) {
947     data->subscribed = 1;
948     data->rc = 1;
949   }
950   return data;
951 }
952
953 nntp_data_t *mutt_newsgroup_unsubscribe (NNTP_SERVER * news, char *group)
954 {
955   nntp_data_t *data;
956
957   if (!news || !news->newsgroups || !group || !*group ||
958       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
959     return NULL;
960   if (data->subscribed) {
961     data->subscribed = 0;
962     if (!option (OPTSAVEUNSUB))
963       data->rc = 0;
964   }
965   return data;
966 }
967
968 nntp_data_t *mutt_newsgroup_catchup (NNTP_SERVER * news, char *group)
969 {
970   nntp_data_t *data;
971
972   if (!news || !news->newsgroups || !group || !*group ||
973       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
974     return NULL;
975   if (!data->max) {
976     data->entries = p_new(NEWSRC_ENTRY, 5);
977     data->max = 5;
978   }
979   data->num = 1;
980   data->entries[0].first = 1;
981   data->unread = 0;
982   data->entries[0].last = data->lastMessage;
983   if (Context && Context->data == data) {
984     int x;
985
986     for (x = 0; x < Context->msgcount; x++)
987       mutt_set_flag (Context, Context->hdrs[x], M_READ, 1);
988   }
989   return data;
990 }
991
992 nntp_data_t *mutt_newsgroup_uncatchup (NNTP_SERVER * news, char *group)
993 {
994   nntp_data_t *data;
995
996   if (!news || !news->newsgroups || !group || !*group ||
997       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
998     return NULL;
999   if (!data->max) {
1000     data->entries = p_new(NEWSRC_ENTRY, 5);
1001     data->max = 5;
1002   }
1003   data->num = 1;
1004   data->entries[0].first = 1;
1005   data->entries[0].last = data->firstMessage - 1;
1006   if (Context && Context->data == data) {
1007     int x;
1008
1009     data->unread = Context->msgcount;
1010     for (x = 0; x < Context->msgcount; x++)
1011       mutt_set_flag (Context, Context->hdrs[x], M_READ, 0);
1012   }
1013   else
1014     data->unread = data->lastMessage - data->entries[0].last;
1015   return data;
1016 }
1017
1018 /* this routine gives the first newsgroup with new messages */
1019 void nntp_buffy (char* dst, ssize_t dstlen) {
1020   nntp_data_t *list;
1021   int count = 0;
1022
1023   /* forward to current group */
1024   for (list = CurrentNewsSrv->list; list; list = list->next) {
1025     if (list->subscribed && list->unread
1026     &&  Context && Context->magic == M_NNTP
1027     &&  m_strcmp(list->group, ((nntp_data_t *)Context->data)->group) == 0)
1028     {
1029       list = list->next;
1030       break;
1031     }
1032   }
1033
1034   *dst = '\0';
1035
1036   while (count < 2) {
1037
1038     if (!list)
1039       list = CurrentNewsSrv->list;
1040
1041     for (; list; list = list->next) {
1042       if (list->subscribed && list->unread) {
1043         if (Context && Context->magic == M_NNTP &&
1044             !m_strcmp(list->group, ((nntp_data_t *)Context->data)->group)) {
1045           int i, unread = 0;
1046
1047           for (i = 0; i < Context->msgcount; i++)
1048             if (!Context->hdrs[i]->read && !Context->hdrs[i]->deleted)
1049               unread++;
1050           if (!unread)
1051             continue;
1052         }
1053         m_strcpy(dst, dstlen, list->group);
1054         break;
1055       }
1056     }
1057     /* done if found */
1058     if (dst && *dst)
1059       return;
1060     count++;
1061   }
1062   *dst = '\0';
1063 }
1064
1065 /* }}} */
1066 /* nntp protocol {{{ */
1067
1068 static unsigned int _checked = 0;
1069
1070 void nntp_sync_sidebar (nntp_data_t* data) {
1071   int i = 0;
1072   BUFFY* tmp = NULL;
1073   char buf[STRING];
1074
1075   if (!Incoming.len)
1076     return;
1077
1078   snprintf(buf, sizeof (buf), "nntp%s://%s%s%s%s/%s",
1079            data->nserv->conn->account.has_ssl ? "s" : "",
1080            NONULL(data->nserv->conn->account.user),
1081            *data->nserv->conn->account.pass ? ":" : "",
1082            *data->nserv->conn->account.pass ? data->nserv->conn->account.pass : "",
1083            data->nserv->conn->account.host,
1084            data->group);
1085
1086   /* bail out if group not found via mailboxes */
1087   if ((i = buffy_lookup (buf)) < 0)
1088     return;
1089
1090   tmp = Incoming.arr[i];
1091   /* copied from browser.c */
1092   if (option (OPTMARKOLD) &&
1093       data->lastCached >= data->firstMessage &&
1094       data->lastCached <= data->lastMessage)
1095     tmp->msg_unread = data->lastMessage - data->lastCached;
1096   else
1097     tmp->msg_unread = data->unread;
1098   tmp->new = data->unread > 0;
1099   /* this is closest to a "total" count we can get */
1100   tmp->msgcount = data->lastMessage - data->firstMessage;
1101 }
1102
1103 static int nntp_auth (NNTP_SERVER * serv)
1104 {
1105   CONNECTION *conn = serv->conn;
1106   char buf[STRING];
1107   unsigned char flags = conn->account.flags;
1108
1109   if (mutt_account_getuser(&conn->account) || !conn->account.user[0] ||
1110       mutt_account_getpass(&conn->account) || !conn->account.pass[0]) {
1111     conn->account.flags = flags;
1112     return -2;
1113   }
1114
1115   mutt_message _("Logging in...");
1116
1117   snprintf (buf, sizeof (buf), "AUTHINFO USER %s\r\n", conn->account.user);
1118   mutt_socket_write (conn, buf);
1119   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
1120     conn->account.flags = flags;
1121     return -1;
1122   }
1123
1124   snprintf (buf, sizeof (buf), "AUTHINFO PASS %s\r\n", conn->account.pass);
1125   mutt_socket_write(conn, buf);
1126   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
1127     conn->account.flags = flags;
1128     return -1;
1129   }
1130
1131   if (m_strncmp("281", buf, 3)) {
1132     conn->account.flags = flags;
1133     mutt_error _("Login failed.");
1134
1135     sleep (2);
1136     return -3;
1137   }
1138
1139   return 0;
1140 }
1141
1142 static int nntp_connect_error (NNTP_SERVER * serv)
1143 {
1144   serv->status = NNTP_NONE;
1145   mutt_socket_close (serv->conn);
1146   mutt_error _("Server closed connection!");
1147
1148   sleep (2);
1149   return -1;
1150 }
1151
1152 static int nntp_connect_and_auth (NNTP_SERVER * serv)
1153 {
1154   CONNECTION *conn = serv->conn;
1155   char buf[STRING];
1156   int rc;
1157
1158   serv->status = NNTP_NONE;
1159
1160   if (mutt_socket_open (conn) < 0)
1161     return -1;
1162
1163   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1164     return nntp_connect_error (serv);
1165
1166   if (!m_strncmp("200", buf, 3))
1167     mutt_message (_("Connected to %s. Posting ok."), conn->account.host);
1168   else if (!m_strncmp("201", buf, 3))
1169     mutt_message (_("Connected to %s. Posting NOT ok."), conn->account.host);
1170   else {
1171     mutt_socket_close(conn);
1172     m_strrtrim(buf);
1173     mutt_error("%s", buf);
1174     sleep (2);
1175     return -1;
1176   }
1177
1178   /* Tell INN to switch to mode reader if it isn't so. Ignore all
1179      returned codes and messages. */
1180   mutt_socket_write (conn, "MODE READER\r\n");
1181   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1182     return nntp_connect_error (serv);
1183
1184   mutt_socket_write (conn, "STAT\r\n");
1185   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1186     return nntp_connect_error (serv);
1187
1188   if (!conn->account.has_user && m_strncmp("480", buf, 3)) {
1189     serv->status = NNTP_OK;
1190     return 0;
1191   }
1192
1193   rc = nntp_auth (serv);
1194   if (rc == -1)
1195     return nntp_connect_error (serv);
1196   if (rc == -2) {
1197     mutt_socket_close (conn);
1198     serv->status = NNTP_BYE;
1199     return -1;
1200   }
1201   if (rc < 0) {
1202     mutt_socket_close (conn);
1203     mutt_error _("Login failed.");
1204
1205     sleep (2);
1206     return -1;
1207   }
1208   serv->status = NNTP_OK;
1209   return 0;
1210 }
1211
1212 static int nntp_attempt_features (NNTP_SERVER * serv)
1213 {
1214   char buf[LONG_STRING];
1215   CONNECTION *conn = serv->conn;
1216
1217   if (serv->feat_known)
1218       return 0;
1219
1220   mutt_socket_write (conn, "XOVER\r\n");
1221   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1222     return nntp_connect_error (serv);
1223   if (m_strncmp("500", buf, 3))
1224     serv->hasXOVER = 1;
1225
1226   mutt_socket_write (conn, "XPAT\r\n");
1227   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1228     return nntp_connect_error (serv);
1229   if (m_strncmp("500", buf, 3))
1230     serv->hasXPAT = 1;
1231
1232   mutt_socket_write (conn, "LISTGROUP\r\n");
1233   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1234     return (nntp_connect_error (serv));
1235   if (m_strncmp("500", buf, 3))
1236     serv->hasLISTGROUP = 1;
1237
1238   mutt_socket_write (conn, "XGTITLE +\r\n");
1239   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1240     return nntp_connect_error (serv);
1241   if (m_strncmp("500", buf, 3))
1242     serv->hasXGTITLE = 1;
1243
1244   if (!m_strncmp("282", buf, 3)) {
1245     do {
1246       if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1247         return nntp_connect_error (serv);
1248     } while (!(buf[0] == '.' && buf[1] == '\0'));
1249   }
1250
1251   serv->feat_known = 1;
1252   return 0;
1253 }
1254
1255 static int nntp_open_connection (NNTP_SERVER * serv)
1256 {
1257   if (serv->status == NNTP_OK)
1258     return 0;
1259   if (serv->status == NNTP_BYE)
1260     return -1;
1261   if (nntp_connect_and_auth (serv) < 0)
1262     return -1;
1263   if (nntp_attempt_features (serv) < 0)
1264     return -1;
1265   return 0;
1266 }
1267
1268 static int nntp_reconnect (NNTP_SERVER * serv)
1269 {
1270   char buf[STRING];
1271
1272   mutt_socket_close (serv->conn);
1273
1274   for (;;) {
1275     if (nntp_connect_and_auth (serv) == 0)
1276       return 0;
1277
1278     snprintf (buf, sizeof (buf), _("Connection to %s lost. Reconnect?"),
1279               serv->conn->account.host);
1280     if (query_quadoption (OPT_NNTPRECONNECT, buf) != M_YES) {
1281       serv->status = NNTP_BYE;
1282       return -1;
1283     }
1284   }
1285 }
1286
1287 /* Send data from line[LONG_STRING] and receive answer to same line */
1288 static int mutt_nntp_query (nntp_data_t * data, char *line, size_t linelen)
1289 {
1290   char buf[LONG_STRING];
1291   int done = TRUE;
1292
1293   if (data->nserv->status == NNTP_BYE)
1294     return -1;
1295
1296   do {
1297     if (*line) {
1298       mutt_socket_write (data->nserv->conn, line);
1299     }
1300     else if (data->group) {
1301       snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
1302       mutt_socket_write (data->nserv->conn, buf);
1303     }
1304
1305     done = TRUE;
1306     if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0) {
1307       if (nntp_reconnect (data->nserv) < 0)
1308         return -1;
1309
1310       if (data->group) {
1311         snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
1312         mutt_socket_write (data->nserv->conn, buf);
1313         if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0)
1314           return -1;
1315       }
1316       if (*line)
1317         done = FALSE;
1318     }
1319     else if ((!m_strncmp("480", buf, 3)) && nntp_auth (data->nserv) < 0)
1320       return -1;
1321   } while (!done);
1322
1323   m_strcpy(line, linelen, buf);
1324   return 0;
1325 }
1326
1327 /*
1328  * This function calls  funct(*line, *data)  for each received line,
1329  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
1330  * Returned codes:
1331  *  0 - successful,
1332  *  1 - correct but not performed (may be, have to be continued),
1333  * -1 - conection lost,
1334  * -2 - invalid command or execution error,
1335  * -3 - error in funct(*line, *data).
1336  */
1337 static int mutt_nntp_fetch (nntp_data_t * nntp_data, const char *query,
1338                             const char *msg, progress_t* bar,
1339                             int (*funct) (char *, void *),
1340                             void *data, int tagged)
1341 {
1342   char buf[LONG_STRING];
1343   char *inbuf, *p;
1344   int done = FALSE;
1345   int chunk, line;
1346   long pos = 0;
1347   size_t lenbuf = 0;
1348   int ret;
1349
1350   do {
1351     m_strcpy(buf, sizeof(buf), query);
1352     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0)
1353       return -1;
1354     if (buf[0] == '5')
1355       return -2;
1356     if (buf[0] != '2')
1357       return 1;
1358
1359     ret = 0;
1360     line = 0;
1361     inbuf = p_new(char, sizeof(buf));
1362
1363     for (;;) {
1364       chunk = mutt_socket_readln(buf, sizeof (buf), nntp_data->nserv->conn);
1365       if (chunk < 0)
1366         break;
1367
1368       p = buf;
1369       if (!lenbuf && buf[0] == '.') {
1370         if (buf[1] == '\0') {
1371           done = TRUE;
1372           break;
1373         }
1374         if (buf[1] == '.')
1375           p++;
1376       }
1377
1378       m_strcpy(inbuf + lenbuf, sizeof(buf), p);
1379       pos += chunk;
1380
1381       if (chunk >= ssizeof (buf)) {
1382         lenbuf += m_strlen(p);
1383       }
1384       else {
1385         if (bar) {
1386           mutt_progress_bar (bar, pos);
1387         } else if (msg) {
1388           line++;
1389           if (ReadInc && (line % ReadInc == 0)) {
1390             if (tagged)
1391               mutt_message (_("%s (tagged: %d) %d"), msg, tagged, line);
1392             else
1393               mutt_message ("%s %d", msg, line);
1394           }
1395         }
1396
1397         if (ret == 0 && funct (inbuf, data) < 0)
1398           ret = -3;
1399         lenbuf = 0;
1400       }
1401
1402       p_realloc(&inbuf, lenbuf + sizeof (buf));
1403     }
1404     p_delete(&inbuf);
1405     funct (NULL, data);
1406   }
1407   while (!done);
1408   return ret;
1409 }
1410
1411 static int nntp_read_tempfile (char *line, void *file)
1412 {
1413   FILE *f = (FILE *) file;
1414
1415   if (!line)
1416     rewind (f);
1417   else {
1418     fputs (line, f);
1419     if (fputc ('\n', f) == EOF)
1420       return -1;
1421   }
1422   return 0;
1423 }
1424
1425 static void nntp_parse_xref (CONTEXT * ctx, char *group, char *xref,
1426                              HEADER * h)
1427 {
1428   register char *p, *b;
1429   register char *colon = NULL;
1430
1431   b = p = xref;
1432   while (*p) {
1433     /* skip to next word */
1434     b = p;
1435     while (*b && ((*b == ' ') || (*b == '\t')))
1436       b++;
1437     p = b;
1438     colon = NULL;
1439     /* skip to end of word */
1440     while (*p && (*p != ' ') && (*p != '\t')) {
1441       if (*p == ':')
1442         colon = p;
1443       p++;
1444     }
1445     if (*p) {
1446       *p = '\0';
1447       p++;
1448     }
1449     if (colon) {
1450       *colon = '\0';
1451       colon++;
1452       nntp_get_status (ctx, h, b, atoi (colon));
1453       if (h && h->article_num == 0 && m_strcmp(group, b) == 0)
1454         h->article_num = atoi (colon);
1455     }
1456   }
1457 }
1458
1459 /*
1460  * returns:
1461  *  0 on success
1462  *  1 if article not found
1463  * -1 if read or write error on tempfile or socket
1464  */
1465 static int nntp_read_header (CONTEXT * ctx, const char *msgid,
1466                              int article_num)
1467 {
1468   nntp_data_t *nntp_data = ((nntp_data_t *) ctx->data);
1469   FILE *f;
1470   char buf[LONG_STRING];
1471   char tempfile[_POSIX_PATH_MAX];
1472   int ret;
1473   HEADER *h = ctx->hdrs[ctx->msgcount];
1474
1475   f = m_tempfile(tempfile, sizeof(tempfile), NONULL(mod_core.tmpdir), NULL);
1476   if (!f)
1477     return -1;
1478
1479   if (!msgid)
1480     snprintf (buf, sizeof (buf), "HEAD %d\r\n", article_num);
1481   else
1482     snprintf (buf, sizeof (buf), "HEAD %s\r\n", msgid);
1483
1484   ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, nntp_read_tempfile, f, 0);
1485   if (ret) {
1486     m_fclose(&f);
1487     unlink (tempfile);
1488     return (ret == -1 ? -1 : 1);
1489   }
1490
1491   h->article_num = article_num;
1492   h->env = mutt_read_rfc822_header (f, h, 0, 0);
1493   m_fclose(&f);
1494   unlink (tempfile);
1495
1496   if (h->env->xref != NULL)
1497     nntp_parse_xref (ctx, nntp_data->group, h->env->xref, h);
1498   else if (h->article_num == 0 && msgid) {
1499     snprintf (buf, sizeof (buf), "STAT %s\r\n", msgid);
1500     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) == 0)
1501       h->article_num = atoi (buf + 4);
1502   }
1503
1504   return 0;
1505 }
1506
1507 static int parse_description (char *line, void *n)
1508 {
1509   register char *d = line;
1510   nntp_data_t *data;
1511   NNTP_SERVER *news = n;
1512
1513   if (!line)
1514     return 0;
1515   while (*d && *d != '\t' && *d != ' ')
1516     d++;
1517   *d = 0;
1518   d++;
1519   while (*d && (*d == '\t' || *d == ' '))
1520     d++;
1521   if ((data = (nntp_data_t *) hash_find (news->newsgroups, line)) != NULL &&
1522       m_strcmp(d, data->desc)) {
1523     p_delete(&data->desc);
1524     data->desc = m_strdup(d);
1525   }
1526   return 0;
1527 }
1528
1529 static void nntp_get_desc (nntp_data_t * data, const char *mask, char *msg, progress_t* bar)
1530 {
1531   char buf[STRING];
1532
1533   if (!option (OPTLOADDESC) || !data || !data->nserv)
1534     return;
1535
1536   /* Get newsgroup description, if we can */
1537   if (data->nserv->hasXGTITLE)
1538     snprintf (buf, sizeof (buf), "XGTITLE %s\r\n", mask);
1539   else
1540     snprintf (buf, sizeof (buf), "LIST NEWSGROUPS %s\r\n", mask);
1541   if (mutt_nntp_fetch (data, buf, msg, bar, parse_description, data->nserv, 0) !=
1542       0) {
1543   }
1544 }
1545
1546 /*
1547  * XOVER returns a tab separated list of:
1548  * id|subject|from|date|Msgid|references|bytes|lines|xref
1549  *
1550  * This has to duplicate some of the functionality of 
1551  * mutt_read_rfc822_header(), since it replaces the call to that (albeit with
1552  * a limited number of headers which are "parsed" by placement in the list)
1553  */
1554 static int nntp_parse_xover (CONTEXT * ctx, char *buf, HEADER * hdr)
1555 {
1556   nntp_data_t *nntp_data = (nntp_data_t *) ctx->data;
1557   char *p, *b;
1558   int x, done = 0;
1559
1560   hdr->env = envelope_new();
1561   hdr->env->newsgroups = m_strdup(nntp_data->group);
1562   hdr->content = body_new();
1563   hdr->content->type = TYPETEXT;
1564   hdr->content->subtype = m_strdup("plain");
1565   hdr->content->encoding = ENC7BIT;
1566   hdr->content->disposition = DISPINLINE;
1567   hdr->content->length = -1;
1568   b = p = buf;
1569
1570   for (x = 0; !done && x < 9; x++) {
1571     /* if from file, need to skip newline character */
1572     while (*p && *p != '\n' && *p != '\t')
1573       p++;
1574     if (!*p)
1575       done++;
1576     *p = '\0';
1577     p++;
1578     switch (x) {
1579     case 0:
1580
1581       hdr->article_num = atoi (b);
1582       nntp_get_status (ctx, hdr, NULL, hdr->article_num);
1583       break;
1584     case 1:
1585       hdr->env->subject = m_strdup(b);
1586       break;
1587     case 2:
1588       address_list_wipe(&hdr->env->from);
1589       hdr->env->from = rfc822_parse_adrlist (hdr->env->from, b);
1590       /* same as for mutt_parse_rfc822_line():
1591        * don't leave from info NULL if there's an invalid address (or
1592        * whatever) in From: field; mutt would just display it as empty
1593        * and mark mail/(esp.) news article as your own. aaargh! this
1594        * bothered me for _years_ */
1595       if (!hdr->env->from) {
1596         hdr->env->from = address_new ();
1597         hdr->env->from->personal = m_strdup(b);
1598       }
1599       break;
1600     case 3:
1601       hdr->date_sent = mutt_parse_date (b, hdr);
1602       hdr->received = hdr->date_sent;
1603       break;
1604     case 4:
1605       p_delete(&hdr->env->message_id);
1606       hdr->env->message_id = m_strdup(b);
1607       break;
1608     case 5:
1609       string_list_wipe(&hdr->env->references);
1610       hdr->env->references = mutt_parse_references (b, 0);
1611       break;
1612     case 6:
1613       hdr->content->length = atoi (b);
1614       break;
1615     case 7:
1616       hdr->lines = atoi (b);
1617       break;
1618     case 8:
1619       if (!hdr->read)
1620         p_delete(&hdr->env->xref);
1621       b = b + 6;                /* skips the "Xref: " */
1622       hdr->env->xref = m_strdup(b);
1623       nntp_parse_xref (ctx, nntp_data->group, b, hdr);
1624     }
1625     rfc2047_decode_envelope(hdr->env);
1626     if (!*p)
1627       return -1;
1628     b = p;
1629   }
1630   return 0;
1631 }
1632
1633 typedef struct {
1634   CONTEXT *ctx;
1635   int   first;
1636   int   last;
1637   bits_t messages;
1638   const char *msg;
1639 } FETCH_CONTEXT;
1640
1641 static int nntp_fetch_numbers (char *line, void *c)
1642 {
1643     FETCH_CONTEXT *fc = c;
1644
1645     if (line) {
1646         int num = atoi(line);
1647         if (num < fc->first || num > fc->last)
1648             return 0;
1649
1650         bit_set(&fc->messages, num);
1651     }
1652     return 0;
1653 }
1654
1655 static int add_xover_line (char *line, void *c)
1656 {
1657   int num, total;
1658   FETCH_CONTEXT *fc = c;
1659   CONTEXT *ctx = fc->ctx;
1660   nntp_data_t *data = (nntp_data_t *) ctx->data;
1661
1662   if (!line)
1663     return 0;
1664
1665   if (ctx->msgcount >= ctx->hdrmax)
1666     mx_alloc_memory (ctx);
1667   ctx->hdrs[ctx->msgcount] = header_new();
1668   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
1669
1670   nntp_parse_xover (ctx, line, ctx->hdrs[ctx->msgcount]);
1671   num = ctx->hdrs[ctx->msgcount]->article_num;
1672
1673   if (num >= fc->first && num <= fc->last) {
1674     ctx->msgcount++;
1675     if (num > data->lastLoaded)
1676       data->lastLoaded = num;
1677     num = num - fc->first + 1;
1678     total = fc->last - fc->first + 1;
1679     if (!ctx->quiet && fc->msg && ReadInc && (num % ReadInc == 0))
1680       mutt_message ("%s %d/%d", fc->msg, num, total);
1681   } else {
1682     header_delete(&ctx->hdrs[ctx->msgcount]);       /* skip it */
1683   }
1684
1685   return 0;
1686 }
1687
1688
1689 static int nntp_fetch_headers(CONTEXT * ctx, int first, int last)
1690 {
1691   char buf[HUGE_STRING];
1692   const char *msg = _("Fetching message headers...");
1693   const char *msg2 = _("Fetching headers from cache...");
1694   nntp_data_t *nntp_data = ((nntp_data_t *) ctx->data);
1695   int ret, num, oldmsgcount, current;
1696   FILE *f;
1697   FETCH_CONTEXT fc;
1698
1699   /* if empty group or nothing to do */
1700   if (!last || first > last)
1701     return 0;
1702
1703   /* fetch list of articles */
1704   mutt_message _("Fetching list of articles...");
1705
1706   fc.ctx   = ctx;
1707   fc.first = first;
1708   fc.last  = last;
1709
1710   /* CACHE: must be loaded xover cache here */
1711   num = nntp_data->lastCached - first + 1;
1712   if (option (OPTNEWSCACHE) && nntp_data->cache && num > 0) {
1713   nntp_cache_expand (buf, nntp_data->cache);
1714   mutt_message (msg2);
1715
1716   if ((f = safe_fopen (buf, "r"))) {
1717     int r = 0, c = 0;
1718
1719     /* counting number of lines */
1720     while (fgets (buf, sizeof (buf), f) != NULL)
1721       r++;
1722     rewind (f);
1723     while (r > num && fgets (buf, sizeof (buf), f) != NULL)
1724       r--;
1725     oldmsgcount = ctx->msgcount;
1726     fc.first = first;
1727     fc.last = first + num - 1;
1728     fc.msg = NULL;
1729     while (fgets (buf, sizeof (buf), f) != NULL) {
1730       if (ReadInc && ((++c) % ReadInc == 0))
1731         mutt_message ("%s %d/%d", msg2, c, r);
1732       add_xover_line (buf, &fc);
1733     }
1734     m_fclose(&f);
1735     nntp_data->lastLoaded = fc.last;
1736     first = fc.last + 1;
1737     if (ctx->msgcount > oldmsgcount)
1738       mx_update_context (ctx, ctx->msgcount - oldmsgcount);
1739   }
1740   else
1741     nntp_delete_cache (nntp_data);
1742   }
1743   num = last - first + 1;
1744   if (num <= 0) {
1745     return 0;
1746   }
1747
1748   /*
1749   * Without XOVER, we have to fetch each article header and parse
1750   * it.  With XOVER, we ask for all of them
1751   */
1752   mutt_message (msg);
1753   if (nntp_data->nserv->hasXOVER) {
1754     oldmsgcount = ctx->msgcount;
1755     fc.first = first;
1756     fc.last = last;
1757     fc.msg = msg;
1758     snprintf (buf, sizeof (buf), "XOVER %d-%d\r\n", first, last);
1759     ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, add_xover_line, &fc, 0);
1760     if (ctx->msgcount > oldmsgcount)
1761       mx_update_context (ctx, ctx->msgcount - oldmsgcount);
1762     if (ret != 0) {
1763       mutt_error (_("XOVER command failed: %s"), buf);
1764       return -1;
1765     }
1766   } else {
1767     bits_init(&fc.messages);
1768
1769     if (nntp_data->nserv->hasLISTGROUP) {
1770       snprintf (buf, sizeof (buf), "LISTGROUP %s\r\n", nntp_data->group);
1771       if (mutt_nntp_fetch(nntp_data, buf, NULL, NULL,
1772                           nntp_fetch_numbers, &fc, 0))
1773       {
1774         mutt_error (_("LISTGROUP command failed: %s"), buf);
1775         sleep (2);
1776         bits_wipe(&fc.messages);
1777         return -1;
1778       }
1779     } else {
1780       for (num = first; num <= last; num++)
1781         bit_set(&fc.messages, num);
1782     }
1783
1784     for (current = first; current <= last; current++) {
1785       HEADER *h;
1786
1787       ret = current - first + 1;
1788       mutt_message ("%s %d/%d", msg, ret, num);
1789
1790       if (!bit_isset(&fc.messages, current))
1791         continue;
1792
1793       if (ctx->msgcount >= ctx->hdrmax)
1794         mx_alloc_memory (ctx);
1795       h = ctx->hdrs[ctx->msgcount] = header_new();
1796       h->index = ctx->msgcount;
1797
1798       ret = nntp_read_header (ctx, NULL, current);
1799       if (ret == 0) {           /* Got article. Fetch next header */
1800         nntp_get_status (ctx, h, NULL, h->article_num);
1801         ctx->msgcount++;
1802         mx_update_context (ctx, 1);
1803       }
1804       else
1805         header_delete(&h);  /* skip it */
1806       if (ret == -1) {
1807         bits_wipe(&fc.messages);
1808         return -1;
1809       }
1810
1811       if (current > nntp_data->lastLoaded)
1812         nntp_data->lastLoaded = current;
1813     }
1814     bits_wipe(&fc.messages);
1815   }
1816
1817   nntp_data->lastLoaded = last;
1818   mutt_clear_error ();
1819   return 0;
1820 }
1821
1822 /*
1823  * currently, nntp "mailbox" is "newsgroup"
1824  */
1825 static int nntp_open_mailbox (CONTEXT * ctx)
1826 {
1827   nntp_data_t *nntp_data;
1828   NNTP_SERVER *serv;
1829   char buf[HUGE_STRING];
1830   char server[LONG_STRING];
1831   int count = 0, first;
1832   ACCOUNT act;
1833
1834   p_clear(&act, 1);
1835
1836   if (nntp_parse_url (ctx->path, &act, buf, sizeof (buf)) < 0 || !*buf) {
1837     mutt_error (_("%s is an invalid newsgroup specification!"), ctx->path);
1838     mutt_sleep (2);
1839     return -1;
1840   }
1841
1842   server[0] = '\0';
1843   nntp_expand_path (server, sizeof (server), &act);
1844   if (!(serv = mutt_select_newsserver (server)) || serv->status != NNTP_OK)
1845     return -1;
1846
1847   CurrentNewsSrv = serv;
1848
1849   /* create NNTP-specific state struct if nof found in list */
1850   if ((nntp_data = (nntp_data_t *) hash_find (serv->newsgroups, buf)) == NULL) {
1851     nntp_data = xmalloc(sizeof(nntp_data_t) + m_strlen(buf) + 1);
1852     nntp_data->group = (char *) nntp_data + sizeof (nntp_data_t);
1853     strcpy (nntp_data->group, buf);
1854     hash_insert (serv->newsgroups, nntp_data->group, nntp_data);
1855     nntp_data_list_append(&serv->list, nntp_data);
1856   }
1857   ctx->data = nntp_data;
1858   nntp_data->nserv = serv;
1859
1860   mutt_message (_("Selecting %s..."), nntp_data->group);
1861
1862   if (!nntp_data->desc) {
1863     nntp_get_desc (nntp_data, nntp_data->group, NULL, NULL);
1864     if (nntp_data->desc)
1865       nntp_save_cache_index (serv);
1866   }
1867
1868   buf[0] = 0;
1869   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
1870     return -1;
1871   }
1872
1873   if (m_strncmp("211", buf, 3)) {
1874     nntp_data_t **l;
1875
1876     /* GROUP command failed */
1877     if (!m_strncmp("411", buf, 3)) {
1878       mutt_error (_("Newsgroup %s not found on server %s"),
1879                   nntp_data->group, serv->conn->account.host);
1880
1881       /* CACHE: delete cache and line from .index */
1882       nntp_delete_cache (nntp_data);
1883       hash_remove(serv->newsgroups, nntp_data->group, NULL, NULL);
1884       for (l = &serv->list; *l; l = &(*l)->next) {
1885           if ((*l) == nntp_data) {
1886               nntp_data_list_pop(l);
1887               nntp_data_delete(&nntp_data);
1888               break;
1889           }
1890       }
1891       nntp_data_delete(&nntp_data);
1892       sleep (2);
1893     }
1894
1895     return -1;
1896   }
1897
1898   sscanf (buf + 4, "%d %u %u %s", &count, &nntp_data->firstMessage,
1899           &nntp_data->lastMessage, buf);
1900
1901   nntp_data->deleted = 0;
1902
1903   time (&serv->check_time);
1904
1905   /*
1906    * Check for max adding context. If it is greater than $nntp_context,
1907    * strip off extra articles
1908    */
1909   first = nntp_data->firstMessage;
1910   if (NntpContext && nntp_data->lastMessage - first + 1 > NntpContext)
1911     first = nntp_data->lastMessage - NntpContext + 1;
1912   if (first)
1913     nntp_data->lastLoaded = first - 1;
1914   return nntp_fetch_headers (ctx, first, nntp_data->lastMessage);
1915 }
1916
1917 int nntp_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
1918 {
1919   char buf[LONG_STRING];
1920   char path[_POSIX_PATH_MAX];
1921   NNTP_CACHE *cache;
1922   int ret;
1923   progress_t bar;
1924
1925   /* see if we already have the message in our cache */
1926   cache =
1927     &((nntp_data_t *) ctx->data)->acache[ctx->hdrs[msgno]->index %
1928                                        NNTP_CACHE_LEN];
1929
1930   /* if everything is fine, assign msg->fp and return */
1931   if (cache->path && cache->index == ctx->hdrs[msgno]->index &&
1932       (msg->fp = fopen (cache->path, "r")))
1933     return 0;
1934
1935   /* clear the previous entry */
1936   unlink (cache->path);
1937   p_delete(&cache->path);
1938
1939   cache->index = ctx->hdrs[msgno]->index;
1940   msg->fp = m_tempfile(path, sizeof(path), NONULL(mod_core.tmpdir), NULL);
1941   if (!msg->fp) {
1942     return -1;
1943   }
1944   cache->path = m_strdup(path);
1945
1946   if (ctx->hdrs[msgno]->article_num == 0)
1947     snprintf (buf, sizeof (buf), "ARTICLE %s\r\n",
1948               ctx->hdrs[msgno]->env->message_id);
1949   else
1950     snprintf (buf, sizeof (buf), "ARTICLE %d\r\n",
1951               ctx->hdrs[msgno]->article_num);
1952
1953   bar.msg = _("Fetching message...");
1954   bar.size = 0;
1955   mutt_progress_bar (&bar, 0);
1956
1957   ret = mutt_nntp_fetch ((nntp_data_t *) ctx->data, buf, NULL, &bar, nntp_read_tempfile,
1958                          msg->fp, ctx->tagged);
1959   if (ret == 1) {
1960     mutt_error (_("Article %d not found on server"),
1961                 ctx->hdrs[msgno]->article_num);
1962   }
1963
1964   if (ret) {
1965     m_fclose(&msg->fp);
1966     unlink (path);
1967     p_delete(&cache->path);
1968     return -1;
1969   }
1970
1971   envelope_delete(&ctx->hdrs[msgno]->env);
1972   ctx->hdrs[msgno]->env =
1973     mutt_read_rfc822_header (msg->fp, ctx->hdrs[msgno], 0, 0);
1974   /* fix content length */
1975   fseeko (msg->fp, 0, SEEK_END);
1976   ctx->hdrs[msgno]->content->length = ftello (msg->fp) -
1977     ctx->hdrs[msgno]->content->offset;
1978
1979   /* this is called in mutt before the open which fetches the message, 
1980    * which is probably wrong, but we just call it again here to handle
1981    * the problem instead of fixing it.
1982    */
1983   mutt_parse_mime_message (ctx, ctx->hdrs[msgno]);
1984
1985   /* These would normally be updated in mx_update_context(), but the 
1986    * full headers aren't parsed with XOVER, so the information wasn't
1987    * available then.
1988    */
1989   ctx->hdrs[msgno]->security = crypt_query (ctx->hdrs[msgno]->content);
1990
1991   mutt_clear_error ();
1992   rewind (msg->fp);
1993
1994   return 0;
1995 }
1996
1997 /* Post article */
1998 int nntp_post (const char *msg)
1999 {
2000   char buf[LONG_STRING];
2001   size_t len;
2002   FILE *f;
2003   nntp_data_t *nntp_data;
2004
2005   if (Context && Context->magic == M_NNTP)
2006     nntp_data = (nntp_data_t *)Context->data;
2007   else {
2008     if (!(CurrentNewsSrv = mutt_select_newsserver(NewsServer)) ||
2009         !CurrentNewsSrv->list)
2010     {
2011       mutt_error (_("Can't post article. No connection to news server."));
2012       return -1;
2013     }
2014     nntp_data = CurrentNewsSrv->list;
2015   }
2016
2017   if (!(f = safe_fopen (msg, "r"))) {
2018     mutt_error (_("Can't post article. Unable to open %s"), msg);
2019     return -1;
2020   }
2021
2022   m_strcpy(buf, sizeof(buf), "POST\r\n");
2023   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2024     mutt_error (_("Can't post article. Connection to %s lost."),
2025                 nntp_data->nserv->conn->account.host);
2026     return -1;
2027   }
2028   if (buf[0] != '3') {
2029     mutt_error (_("Can't post article: %s"), buf);
2030     return -1;
2031   }
2032
2033   buf[0] = '.';
2034   buf[1] = '\0';
2035   while (fgets (buf + 1, sizeof (buf) - 2, f) != NULL) {
2036     len = m_strlen(buf);
2037     if (buf[len - 1] == '\n') {
2038       buf[len - 1] = '\r';
2039       buf[len] = '\n';
2040       len++;
2041       buf[len] = '\0';
2042     }
2043     if (buf[1] == '.')
2044       mutt_socket_write(nntp_data->nserv->conn, buf);
2045     else
2046       mutt_socket_write(nntp_data->nserv->conn, buf + 1);
2047   }
2048   m_fclose(&f);
2049
2050   if (buf[m_strlen(buf) - 1] != '\n')
2051     mutt_socket_write(nntp_data->nserv->conn, "\r\n");
2052   mutt_socket_write(nntp_data->nserv->conn, ".\r\n");
2053   if (mutt_socket_readln (buf, sizeof (buf), nntp_data->nserv->conn) < 0) {
2054     mutt_error (_("Can't post article. Connection to %s lost."),
2055                 nntp_data->nserv->conn->account.host);
2056     return -1;
2057   }
2058   if (buf[0] != '2') {
2059     mutt_error (_("Can't post article: %s"), buf);
2060     return -1;
2061   }
2062
2063   return 0;
2064 }
2065
2066 /* nntp_logout_all: close all open connections. */
2067 void nntp_logout_all (void)
2068 {
2069   char buf[LONG_STRING];
2070   CONNECTION *conn;
2071
2072   conn = mutt_socket_head ();
2073
2074   while (conn) {
2075     CONNECTION* next = conn->next;
2076     if (conn->account.type == M_ACCT_TYPE_NNTP) {
2077       mutt_message (_("Closing connection to %s..."), conn->account.host);
2078       mutt_socket_write (conn, "QUIT\r\n");
2079       mutt_socket_readln (buf, sizeof (buf), conn);
2080       mutt_clear_error ();
2081       mutt_socket_close (conn);
2082       mutt_socket_free (conn);
2083     }
2084     conn = next;
2085   }
2086 }
2087
2088 static void nntp_free_acache (nntp_data_t * data)
2089 {
2090   int i;
2091
2092   for (i = 0; i < NNTP_CACHE_LEN; i++) {
2093     if (data->acache[i].path) {
2094       unlink (data->acache[i].path);
2095       p_delete(&data->acache[i].path);
2096     }
2097   }
2098 }
2099
2100 void nntp_data_wipe(nntp_data_t *data)
2101 {
2102     p_delete(&data->entries);
2103     p_delete(&data->desc);
2104     p_delete(&data->cache);
2105     nntp_free_acache(data);
2106 }
2107
2108 static int nntp_sync_mailbox (CONTEXT * ctx, int unused1, int* unused2)
2109 {
2110   nntp_data_t *data = ctx->data;
2111
2112   /* CACHE: update cache and .index files */
2113   if ((option (OPTSAVEUNSUB) || data->subscribed))
2114     nntp_save_cache_group (ctx);
2115   nntp_free_acache (data);
2116
2117   data->nserv->check_time = 0;  /* next nntp_check_mailbox() will really check */
2118   return 0;
2119 }
2120
2121 static void nntp_fastclose_mailbox (CONTEXT * ctx)
2122 {
2123   nntp_data_t *data = (nntp_data_t *) ctx->data, *tmp;
2124
2125   if (!data)
2126     return;
2127   nntp_free_acache (data);
2128   if (!data->nserv || !data->nserv->newsgroups || !data->group)
2129     return;
2130   nntp_save_cache_index (data->nserv);
2131   if ((tmp = hash_find (data->nserv->newsgroups, data->group)) == NULL
2132       || tmp != data)
2133     nntp_data_delete(&data);
2134   else
2135     nntp_sync_sidebar (data);
2136 }
2137
2138 /* commit changes and terminate connection */
2139 int nntp_close_mailbox (CONTEXT * ctx)
2140 {
2141   if (!ctx)
2142     return -1;
2143   mutt_message _("Quitting newsgroup...");
2144
2145   if (ctx->data) {
2146     nntp_data_t *data = (nntp_data_t *) ctx->data;
2147     int ret;
2148
2149     if (data->nserv && data->nserv->conn && ctx->unread) {
2150       ret = query_quadoption (OPT_CATCHUP, _("Mark all articles read?"));
2151       if (ret == M_YES)
2152         mutt_newsgroup_catchup (data->nserv, data->group);
2153       else if (ret < 0)
2154         return -1;
2155     }
2156   }
2157   nntp_sync_mailbox (ctx, 0, NULL);
2158   if (ctx->data && ((nntp_data_t *) ctx->data)->nserv) {
2159     NNTP_SERVER *news;
2160
2161     news = ((nntp_data_t *) ctx->data)->nserv;
2162     newsrc_gen_entries (ctx);
2163     ((nntp_data_t *) ctx->data)->unread = ctx->unread;
2164     mutt_newsrc_update (news);
2165   }
2166   mutt_clear_error ();
2167   return 0;
2168 }
2169
2170 /* use the GROUP command to poll for new mail */
2171 static int _nntp_check_mailbox (CONTEXT * ctx, nntp_data_t * nntp_data)
2172 {
2173   char buf[LONG_STRING];
2174   int count = 0;
2175
2176   if (nntp_data->nserv->check_time + NewsPollTimeout > time (NULL))
2177     return 0;
2178
2179   buf[0] = 0;
2180   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2181     return -1;
2182   }
2183   if (m_strncmp("211", buf, 3)) {
2184     buf[0] = 0;
2185     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2186       return -1;
2187     }
2188   }
2189   if (!m_strncmp("211", buf, 3)) {
2190     int first;
2191     int last;
2192
2193     sscanf (buf + 4, "%d %d %d", &count, &first, &last);
2194     nntp_data->firstMessage = first;
2195     nntp_data->lastMessage = last;
2196     if (ctx && last > nntp_data->lastLoaded) {
2197       nntp_fetch_headers (ctx, nntp_data->lastLoaded + 1, last);
2198       time (&nntp_data->nserv->check_time);
2199       return 1;
2200     }
2201     if (!last || (!nntp_data->rc && !nntp_data->lastCached))
2202       nntp_data->unread = count;
2203     else
2204       mutt_newsgroup_stat (nntp_data);
2205     /* active was renumbered? */
2206     if (last < nntp_data->lastLoaded) {
2207       if (!nntp_data->max) {
2208         nntp_data->entries = p_new(NEWSRC_ENTRY, 5);
2209         nntp_data->max = 5;
2210       }
2211       nntp_data->lastCached = 0;
2212       nntp_data->num = 1;
2213       nntp_data->entries[0].first = 1;
2214       nntp_data->entries[0].last = 0;
2215     }
2216     nntp_sync_sidebar (nntp_data);
2217   }
2218
2219   time (&nntp_data->nserv->check_time);
2220   return 0;
2221 }
2222
2223 static int nntp_check_mailbox (CONTEXT * ctx, int* unused1, int unused2)
2224 {
2225   return _nntp_check_mailbox (ctx, (nntp_data_t *) ctx->data);
2226 }
2227
2228 static int add_group (char *buf, void *serv)
2229 {
2230   NNTP_SERVER *s = serv;
2231   char group[LONG_STRING], mod, desc[HUGE_STRING];
2232   int first, last;
2233   nntp_data_t *nntp_data;
2234   static int n = 0;
2235
2236   _checked = n;                 /* _checked have N, where N = number of groups */
2237   if (!buf)                     /* at EOF must be zerouth */
2238     n = 0;
2239
2240   if (!s || !buf)
2241     return 0;
2242
2243   *desc = 0;
2244   sscanf (buf, "%s %d %d %c %[^\n]", group, &last, &first, &mod, desc);
2245   if (!group)
2246     return 0;
2247   if ((nntp_data = (nntp_data_t *) hash_find (s->newsgroups, group)) == NULL) {
2248     n++;
2249     nntp_data = xmalloc(sizeof(nntp_data_t) + m_strlen(group) + 1);
2250     nntp_data->group = (char *) nntp_data + sizeof (nntp_data_t);
2251     strcpy (nntp_data->group, group);
2252     nntp_data->nserv = s;
2253     if (s->newsgroups->nelem < s->newsgroups->curnelem * 2)
2254       hash_resize (s->newsgroups, s->newsgroups->nelem * 2);
2255     hash_insert (s->newsgroups, nntp_data->group, nntp_data);
2256     nntp_data_list_append(&s->list, nntp_data);
2257   }
2258   nntp_data->deleted = 0;
2259   nntp_data->firstMessage = first;
2260   nntp_data->lastMessage = last;
2261   if (mod == 'y')
2262     nntp_data->allowed = 1;
2263   else
2264     nntp_data->allowed = 0;
2265   if (nntp_data->desc)
2266     p_delete(&nntp_data->desc);
2267   if (*desc)
2268     nntp_data->desc = m_strdup(desc);
2269   if (nntp_data->rc || nntp_data->lastCached)
2270     mutt_newsgroup_stat (nntp_data);
2271   else if (nntp_data->lastMessage &&
2272            nntp_data->firstMessage <= nntp_data->lastMessage)
2273     nntp_data->unread = nntp_data->lastMessage - nntp_data->firstMessage + 1;
2274   else
2275     nntp_data->unread = 0;
2276
2277   return 0;
2278 }
2279
2280 static int nntp_check_newgroups (NNTP_SERVER * serv, int force)
2281 {
2282   char buf[LONG_STRING];
2283   nntp_data_t nntp_data;
2284   nntp_data_t *l, **emp;
2285   time_t now;
2286   struct tm *t;
2287
2288   if (!serv || !serv->newgroups_time)
2289     return -1;
2290
2291   if (nntp_open_connection (serv) < 0)
2292     return -1;
2293
2294   /* check subscribed groups for new news */
2295   if (option (OPTSHOWNEWNEWS)) {
2296     mutt_message _("Checking for new messages...");
2297
2298     for (l = serv->list; l; l = l->next) {
2299       serv->check_time = 0;     /* really check! */
2300       if (l->subscribed)
2301         _nntp_check_mailbox (NULL, l);
2302     }
2303     sidebar_draw ();
2304   }
2305   else if (!force)
2306     return 0;
2307
2308   mutt_message _("Checking for new newsgroups...");
2309
2310   now = serv->newgroups_time;
2311   time (&serv->newgroups_time);
2312   t = gmtime (&now);
2313   snprintf (buf, sizeof (buf), "NEWGROUPS %02d%02d%02d %02d%02d%02d GMT\r\n",
2314             (t->tm_year % 100), t->tm_mon + 1, t->tm_mday, t->tm_hour,
2315             t->tm_min, t->tm_sec);
2316   nntp_data.nserv = serv;
2317   if (Context && Context->magic == M_NNTP)
2318     nntp_data.group = ((nntp_data_t *) Context->data)->group;
2319   else
2320     nntp_data.group = NULL;
2321
2322   emp = nntp_data_list_last(&serv->list);
2323   if (mutt_nntp_fetch (&nntp_data, buf, _("Adding new newsgroups..."), NULL,
2324                        add_group, serv, 0) != 0) {
2325     return -1;
2326   }
2327
2328   mutt_message _("Loading descriptions...");
2329
2330   for (l = *emp; l; l = l->next) {
2331     l->new = 1;
2332     nntp_get_desc(l, l->group, NULL, NULL);
2333   }
2334   if (*emp)
2335     nntp_save_cache_index(serv);
2336   mutt_clear_error();
2337   return _checked;
2338 }
2339
2340 /* Load list of all newsgroups from cache ALL */
2341 static int nntp_get_cache_all (NNTP_SERVER * serv)
2342 {
2343   char buf[HUGE_STRING];
2344   FILE *f;
2345
2346   nntp_cache_expand (buf, serv->cache);
2347   if ((f = safe_fopen (buf, "r"))) {
2348     int i = 0;
2349
2350     while (fgets (buf, sizeof (buf), f) != NULL) {
2351       if (ReadInc && (i % ReadInc == 0))
2352         mutt_message (_("Loading list from cache... %d"), i);
2353       add_group (buf, serv);
2354       i++;
2355     }
2356     add_group (NULL, NULL);
2357     m_fclose(&f);
2358     mutt_clear_error ();
2359     return 0;
2360   }
2361   else {
2362     p_delete(&serv->cache);
2363     return -1;
2364   }
2365 }
2366
2367 /* Load list of all newsgroups from active */
2368 int nntp_get_active (NNTP_SERVER * serv)
2369 {
2370   char msg[STRING];
2371   nntp_data_t nntp_data, **tmp = &serv->list;
2372
2373   if (nntp_open_connection (serv) < 0)
2374     return -1;
2375
2376   snprintf (msg, sizeof (msg),
2377             _("Loading list of all newsgroups on server %s..."),
2378             serv->conn->account.host);
2379   mutt_message (msg);
2380   time (&serv->newgroups_time);
2381   nntp_data.nserv = serv;
2382   nntp_data.group = NULL;
2383
2384   if (mutt_nntp_fetch (&nntp_data, "LIST\r\n", msg, NULL, add_group, serv, 0) < 0) {
2385     return -1;
2386   }
2387
2388   m_strcpy(msg, sizeof(msg), _("Loading descriptions..."));
2389   mutt_message (msg);
2390   nntp_get_desc (&nntp_data, "*", msg, NULL);
2391
2392   while (*tmp) {
2393     if ((*tmp)->deleted && !(*tmp)->rc) {
2394       nntp_data_t *d = nntp_data_list_pop(tmp);
2395       nntp_delete_cache(d);
2396       hash_remove(serv->newsgroups, d->group, NULL, NULL);
2397       nntp_data_delete(&d);
2398     } else {
2399       tmp = &(*tmp)->next;
2400     }
2401   }
2402   nntp_save_cache_index (serv);
2403
2404   mutt_clear_error ();
2405   return _checked;
2406 }
2407
2408 /*
2409  * returns -1 if error ocurred while retrieving header,
2410  * number of articles which ones exist in context on success.
2411  */
2412 int nntp_check_msgid (CONTEXT * ctx, const char *msgid)
2413 {
2414   int ret;
2415
2416   /* if msgid is already in context, don't reload them */
2417   if (hash_find (ctx->id_hash, msgid))
2418     return 1;
2419   if (ctx->msgcount == ctx->hdrmax)
2420     mx_alloc_memory (ctx);
2421   ctx->hdrs[ctx->msgcount] = header_new();
2422   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
2423
2424   mutt_message (_("Fetching %s from server..."), msgid);
2425   ret = nntp_read_header (ctx, msgid, 0);
2426   /* since nntp_read_header() may set read flag, we must reset it */
2427   ctx->hdrs[ctx->msgcount]->read = 0;
2428   if (ret != 0)
2429     header_delete(&ctx->hdrs[ctx->msgcount]);
2430   else {
2431     ctx->msgcount++;
2432     mx_update_context (ctx, 1);
2433     ctx->changed = 1;
2434   }
2435   return ret;
2436 }
2437
2438 typedef struct {
2439   CONTEXT *ctx;
2440   int num;
2441   int max;
2442   int *child;
2443 } CHILD_CONTEXT;
2444
2445 static int check_children (char *s, void *c)
2446 {
2447   CHILD_CONTEXT *cc = c;
2448   int i, n;
2449
2450   if (!s || (n = atoi (s)) == 0)
2451     return 0;
2452   for (i = 0; i < cc->ctx->msgcount; i++)
2453     if (cc->ctx->hdrs[i]->article_num == n)
2454       return 0;
2455   if (cc->num >= cc->max)
2456     p_realloc(&cc->child, cc->max += 25);
2457   cc->child[cc->num++] = n;
2458
2459   return 0;
2460 }
2461
2462 int nntp_check_children (CONTEXT * ctx, const char *msgid)
2463 {
2464   nntp_data_t *nntp_data = (nntp_data_t *) ctx->data;
2465   char buf[STRING];
2466   int i, ret = 0, tmp = 0;
2467   CHILD_CONTEXT cc = { ctx, 0, 0, NULL };
2468
2469   if (!nntp_data || !nntp_data->nserv || !nntp_data->nserv->conn ||
2470       !nntp_data->nserv->conn->account.host)
2471     return -1;
2472   if (nntp_data->firstMessage > nntp_data->lastLoaded)
2473     return 0;
2474   if (!nntp_data->nserv->hasXPAT) {
2475     mutt_error (_("Server %s does not support this operation!"),
2476                 nntp_data->nserv->conn->account.host);
2477     return -1;
2478   }
2479
2480   snprintf (buf, sizeof (buf), "XPAT References %d-%d *%s*\r\n",
2481             nntp_data->firstMessage, nntp_data->lastLoaded, msgid);
2482
2483   if (mutt_nntp_fetch (nntp_data, buf, NULL, NULL, check_children, &cc, 0)) {
2484     p_delete(&cc.child);
2485     return -1;
2486   }
2487
2488   /* dont try to read the xover cache. check_children() already
2489    * made sure that we dont have the article, so we need to visit
2490    * the server. Reading the cache at this point is also bad
2491    * because it would duplicate messages */
2492   if (option (OPTNEWSCACHE)) {
2493     tmp++;
2494     unset_option (OPTNEWSCACHE);
2495   }
2496   for (i = 0; i < cc.num; i++) {
2497     if ((ret = nntp_fetch_headers (ctx, cc.child[i], cc.child[i])))
2498       break;
2499     if (ctx->msgcount &&
2500         ctx->hdrs[ctx->msgcount - 1]->article_num == cc.child[i])
2501       ctx->hdrs[ctx->msgcount - 1]->read = 0;
2502   }
2503   if (tmp)
2504     set_option (OPTNEWSCACHE);
2505   p_delete(&cc.child);
2506   return ret;
2507 }
2508
2509 static int nntp_is_magic (const char* path, struct stat* st) {
2510   url_scheme_t s = url_check_scheme(NONULL(path));
2511   return s == U_NNTP || s == U_NNTPS ? M_NNTP : -1;
2512 }
2513
2514 static int acl_check_nntp (CONTEXT* ctx, int bit) {
2515   switch (bit) {
2516     case ACL_INSERT:    /* editing messages */
2517     case ACL_WRITE:     /* change importance */
2518       return (0);
2519     case ACL_DELETE:    /* (un)deletion */
2520     case ACL_SEEN:      /* mark as read */
2521       return (1);
2522     default:
2523       return (0);
2524   }
2525 }
2526
2527 mx_t const nntp_mx = {
2528     M_NNTP,
2529     0,
2530     nntp_is_magic,
2531     NULL,
2532     NULL,
2533     nntp_open_mailbox,
2534     NULL,
2535     acl_check_nntp,
2536     nntp_check_mailbox,
2537     nntp_fastclose_mailbox,
2538     nntp_sync_mailbox,
2539     NULL,
2540 };
2541
2542 /* }}} */