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