aa9d9150cf0718fab63c894d4a4c7410f9ea86ec
[apps/madmutt.git] / nntp / 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 #ifdef HAVE_CONFIG_H
13 #include <config.h>
14 #endif
15
16 #include <lib-lib/mem.h>
17 #include <lib-lib/str.h>
18 #include <lib-lib/file.h>
19 #include <lib-lib/macros.h>
20
21 #include <lib-mime/mime.h>
22
23 #include <lib-ui/curses.h>
24
25 #include "mutt.h"
26 #include "sort.h"
27 #include "mx.h"
28 #include "mx_nntp.h"
29 #include "rfc1524.h"
30 #include "nntp.h"
31 #include "sidebar.h"
32 #include "buffy.h"
33
34 #include <lib-crypt/crypt.h>
35
36
37 #include <unistd.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <stdlib.h>
41
42 #define WANT_LISTGROUP_COMMAND          0
43
44 static unsigned int _checked = 0;
45
46 void nntp_sync_sidebar (NNTP_DATA* data) {
47   int i = 0;
48   BUFFY* tmp = NULL;
49   char buf[STRING];
50
51   if (list_empty (Incoming))
52     return;
53
54   /* unfortunately, NNTP_DATA::group only is the plain
55    * group name, so for every single update, we need to
56    * compose the full string which must be defined via
57    * mailboxes command ;-((( FIXME
58    */
59   buf[0] = '\0';
60   snprintf (buf, sizeof (buf), "nntp%s://%s%s%s%s/%s",
61             (data->nserv->conn->account.flags & M_ACCT_SSL) ? "s" : "",
62             NONULL (data->nserv->conn->account.user),
63             *data->nserv->conn->account.pass ? ":" : "",
64             *data->nserv->conn->account.pass ? data->nserv->conn->account.pass : "",
65             data->nserv->conn->account.host,
66             data->group);
67
68   /* bail out if group not found via mailboxes */
69   if ((i = buffy_lookup (buf)) < 0)
70     return;
71
72   tmp = (BUFFY*) Incoming->data[i];
73   /* copied from browser.c */
74   if (option (OPTMARKOLD) &&
75       data->lastCached >= data->firstMessage &&
76       data->lastCached <= data->lastMessage)
77     tmp->msg_unread = data->lastMessage - data->lastCached;
78   else
79     tmp->msg_unread = data->unread;
80   tmp->new = data->unread > 0;
81   /* this is closest to a "total" count we can get */
82   tmp->msgcount = data->lastMessage - data->firstMessage;
83 }
84
85 static int nntp_auth (NNTP_SERVER * serv)
86 {
87   CONNECTION *conn = serv->conn;
88   char buf[STRING];
89   unsigned char flags = conn->account.flags;
90
91   if (mutt_account_getuser (&conn->account) || !conn->account.user[0] ||
92       mutt_account_getpass (&conn->account) || !conn->account.pass[0]) {
93     conn->account.flags = flags;
94     return -2;
95   }
96
97   mutt_message _("Logging in...");
98
99   snprintf (buf, sizeof (buf), "AUTHINFO USER %s\r\n", conn->account.user);
100   mutt_socket_write (conn, buf);
101   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
102     conn->account.flags = flags;
103     return -1;
104   }
105
106   snprintf (buf, sizeof (buf), "AUTHINFO PASS %s\r\n", conn->account.pass);
107   mutt_socket_write_d (conn, buf, M_SOCK_LOG_FULL);
108   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
109     conn->account.flags = flags;
110     return -1;
111   }
112
113   if (m_strncmp("281", buf, 3)) {
114     conn->account.flags = flags;
115     mutt_error _("Login failed.");
116
117     sleep (2);
118     return -3;
119   }
120
121   return 0;
122 }
123
124 static int nntp_connect_error (NNTP_SERVER * serv)
125 {
126   serv->status = NNTP_NONE;
127   mutt_socket_close (serv->conn);
128   mutt_error _("Server closed connection!");
129
130   sleep (2);
131   return -1;
132 }
133
134 static int nntp_connect_and_auth (NNTP_SERVER * serv)
135 {
136   CONNECTION *conn = serv->conn;
137   char buf[STRING];
138   int rc;
139
140   serv->status = NNTP_NONE;
141
142   if (mutt_socket_open (conn) < 0)
143     return -1;
144
145   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
146     return nntp_connect_error (serv);
147
148   if (!m_strncmp("200", buf, 3))
149     mutt_message (_("Connected to %s. Posting ok."), conn->account.host);
150   else if (!m_strncmp("201", buf, 3))
151     mutt_message (_("Connected to %s. Posting NOT ok."), conn->account.host);
152   else {
153     mutt_socket_close(conn);
154     m_strrtrim(buf);
155     mutt_error("%s", buf);
156     sleep (2);
157     return -1;
158   }
159
160   sleep (1);
161
162   /* Tell INN to switch to mode reader if it isn't so. Ignore all
163      returned codes and messages. */
164   mutt_socket_write (conn, "MODE READER\r\n");
165   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
166     return nntp_connect_error (serv);
167
168   mutt_socket_write (conn, "STAT\r\n");
169   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
170     return nntp_connect_error (serv);
171
172   if (!(conn->account.flags & M_ACCT_USER) && m_strncmp("480", buf, 3)) {
173     serv->status = NNTP_OK;
174     return 0;
175   }
176
177   rc = nntp_auth (serv);
178   if (rc == -1)
179     return nntp_connect_error (serv);
180   if (rc == -2) {
181     mutt_socket_close (conn);
182     serv->status = NNTP_BYE;
183     return -1;
184   }
185   if (rc < 0) {
186     mutt_socket_close (conn);
187     mutt_error _("Login failed.");
188
189     sleep (2);
190     return -1;
191   }
192   serv->status = NNTP_OK;
193   return 0;
194 }
195
196 static int nntp_attempt_features (NNTP_SERVER * serv)
197 {
198   char buf[LONG_STRING];
199   CONNECTION *conn = serv->conn;
200
201   mutt_socket_write (conn, "XOVER\r\n");
202   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
203     return nntp_connect_error (serv);
204   if (m_strncmp("500", buf, 3))
205     serv->hasXOVER = 1;
206
207   mutt_socket_write (conn, "XPAT\r\n");
208   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
209     return nntp_connect_error (serv);
210   if (m_strncmp("500", buf, 3))
211     serv->hasXPAT = 1;
212
213 #if WANT_LISTGROUP_COMMAND
214   mutt_socket_write (conn, "LISTGROUP\r\n");
215   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
216     return (nntp_connect_error (serv));
217   if (m_strncmp("500", buf, 3))
218     serv->hasLISTGROUP = 1;
219 #endif
220
221   mutt_socket_write (conn, "XGTITLE +\r\n");
222   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
223     return nntp_connect_error (serv);
224   if (m_strncmp("500", buf, 3))
225     serv->hasXGTITLE = 1;
226
227   if (!m_strncmp("282", buf, 3)) {
228     do {
229       if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
230         return nntp_connect_error (serv);
231     } while (!(buf[0] == '.' && buf[1] == '\0'));
232   }
233
234   return 0;
235 }
236
237 static int nntp_open_connection (NNTP_SERVER * serv)
238 {
239   if (serv->status == NNTP_OK)
240     return 0;
241   if (serv->status == NNTP_BYE)
242     return -1;
243   if (nntp_connect_and_auth (serv) < 0)
244     return -1;
245   if (nntp_attempt_features (serv) < 0)
246     return -1;
247   return 0;
248 }
249
250 static int nntp_reconnect (NNTP_SERVER * serv)
251 {
252   char buf[SHORT_STRING];
253
254   mutt_socket_close (serv->conn);
255
256   for (;;) {
257     if (nntp_connect_and_auth (serv) == 0)
258       return 0;
259
260     snprintf (buf, sizeof (buf), _("Connection to %s lost. Reconnect?"),
261               serv->conn->account.host);
262     if (query_quadoption (OPT_NNTPRECONNECT, buf) != M_YES) {
263       serv->status = NNTP_BYE;
264       return -1;
265     }
266   }
267 }
268
269 /* Send data from line[LONG_STRING] and receive answer to same line */
270 static int mutt_nntp_query (NNTP_DATA * data, char *line, size_t linelen)
271 {
272   char buf[LONG_STRING];
273   int done = TRUE;
274
275   if (data->nserv->status == NNTP_BYE)
276     return -1;
277
278   do {
279     if (*line) {
280       mutt_socket_write (data->nserv->conn, line);
281     }
282     else if (data->group) {
283       snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
284       mutt_socket_write (data->nserv->conn, buf);
285     }
286
287     done = TRUE;
288     if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0) {
289       if (nntp_reconnect (data->nserv) < 0)
290         return -1;
291
292       if (data->group) {
293         snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
294         mutt_socket_write (data->nserv->conn, buf);
295         if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0)
296           return -1;
297       }
298       if (*line)
299         done = FALSE;
300     }
301     else if ((!m_strncmp("480", buf, 3)) && nntp_auth (data->nserv) < 0)
302       return -1;
303   } while (!done);
304
305   m_strcpy(line, linelen, buf);
306   return 0;
307 }
308
309 /*
310  * This function calls  funct(*line, *data)  for each received line,
311  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
312  * Returned codes:
313  *  0 - successful,
314  *  1 - correct but not performed (may be, have to be continued),
315  * -1 - conection lost,
316  * -2 - invalid command or execution error,
317  * -3 - error in funct(*line, *data).
318  */
319 static int mutt_nntp_fetch (NNTP_DATA * nntp_data, const char *query, char *msg,
320                             progress_t* bar, int (*funct) (char *, void *),
321                             void *data, int tagged)
322 {
323   char buf[LONG_STRING];
324   char *inbuf, *p;
325   int done = FALSE;
326   int chunk, line;
327   long pos = 0;
328   size_t lenbuf = 0;
329   int ret;
330
331   do {
332     m_strcpy(buf, sizeof(buf), query);
333     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0)
334       return -1;
335     if (buf[0] == '5')
336       return -2;
337     if (buf[0] != '2')
338       return 1;
339
340     ret = 0;
341     line = 0;
342     inbuf = p_new(char, sizeof(buf));
343
344     for (;;) {
345       chunk = mutt_socket_readln_d (buf, sizeof (buf), nntp_data->nserv->conn,
346                                     M_SOCK_LOG_HDR);
347       if (chunk < 0)
348         break;
349
350       p = buf;
351       if (!lenbuf && buf[0] == '.') {
352         if (buf[1] == '\0') {
353           done = TRUE;
354           break;
355         }
356         if (buf[1] == '.')
357           p++;
358       }
359
360       m_strcpy(inbuf + lenbuf, sizeof(buf), p);
361       pos += chunk;
362
363       if (chunk >= ssizeof (buf)) {
364         lenbuf += m_strlen(p);
365       }
366       else {
367         if (bar) {
368           mutt_progress_bar (bar, pos);
369         } else if (msg) {
370           line++;
371           if (ReadInc && (line % ReadInc == 0)) {
372             if (tagged)
373               mutt_message (_("%s (tagged: %d) %d"), msg, tagged, line);
374             else
375               mutt_message ("%s %d", msg, line);
376           }
377         }
378
379         if (ret == 0 && funct (inbuf, data) < 0)
380           ret = -3;
381         lenbuf = 0;
382       }
383
384       p_realloc(&inbuf, lenbuf + sizeof (buf));
385     }
386     p_delete(&inbuf);
387     funct (NULL, data);
388   }
389   while (!done);
390   return ret;
391 }
392
393 static int nntp_read_tempfile (char *line, void *file)
394 {
395   FILE *f = (FILE *) file;
396
397   if (!line)
398     rewind (f);
399   else {
400     fputs (line, f);
401     if (fputc ('\n', f) == EOF)
402       return -1;
403   }
404   return 0;
405 }
406
407 static void nntp_parse_xref (CONTEXT * ctx, char *group, char *xref,
408                              HEADER * h)
409 {
410   register char *p, *b;
411   register char *colon = NULL;
412
413   b = p = xref;
414   while (*p) {
415     /* skip to next word */
416     b = p;
417     while (*b && ((*b == ' ') || (*b == '\t')))
418       b++;
419     p = b;
420     colon = NULL;
421     /* skip to end of word */
422     while (*p && (*p != ' ') && (*p != '\t')) {
423       if (*p == ':')
424         colon = p;
425       p++;
426     }
427     if (*p) {
428       *p = '\0';
429       p++;
430     }
431     if (colon) {
432       *colon = '\0';
433       colon++;
434       nntp_get_status (ctx, h, b, atoi (colon));
435       if (h && h->article_num == 0 && m_strcmp(group, b) == 0)
436         h->article_num = atoi (colon);
437     }
438   }
439 }
440
441 /*
442  * returns:
443  *  0 on success
444  *  1 if article not found
445  * -1 if read or write error on tempfile or socket
446  */
447 static int nntp_read_header (CONTEXT * ctx, const char *msgid,
448                              int article_num)
449 {
450   NNTP_DATA *nntp_data = ((NNTP_DATA *) ctx->data);
451   FILE *f;
452   char buf[LONG_STRING];
453   char tempfile[_POSIX_PATH_MAX];
454   int ret;
455   HEADER *h = ctx->hdrs[ctx->msgcount];
456
457   mutt_mktemp (tempfile);
458   if (!(f = safe_fopen (tempfile, "w+")))
459     return -1;
460
461   if (!msgid)
462     snprintf (buf, sizeof (buf), "HEAD %d\r\n", article_num);
463   else
464     snprintf (buf, sizeof (buf), "HEAD %s\r\n", msgid);
465
466   ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, nntp_read_tempfile, f, 0);
467   if (ret) {
468     fclose (f);
469     unlink (tempfile);
470     return (ret == -1 ? -1 : 1);
471   }
472
473   h->article_num = article_num;
474   h->env = mutt_read_rfc822_header (f, h, 0, 0);
475   fclose (f);
476   unlink (tempfile);
477
478   if (h->env->xref != NULL)
479     nntp_parse_xref (ctx, nntp_data->group, h->env->xref, h);
480   else if (h->article_num == 0 && msgid) {
481     snprintf (buf, sizeof (buf), "STAT %s\r\n", msgid);
482     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) == 0)
483       h->article_num = atoi (buf + 4);
484   }
485
486   return 0;
487 }
488
489 static int parse_description (char *line, void *n)
490 {
491 #define news ((NNTP_SERVER *) n)
492   register char *d = line;
493   NNTP_DATA *data;
494
495   if (!line)
496     return 0;
497   while (*d && *d != '\t' && *d != ' ')
498     d++;
499   *d = 0;
500   d++;
501   while (*d && (*d == '\t' || *d == ' '))
502     d++;
503   if ((data = (NNTP_DATA *) hash_find (news->newsgroups, line)) != NULL &&
504       m_strcmp(d, data->desc)) {
505     p_delete(&data->desc);
506     data->desc = m_strdup(d);
507   }
508   return 0;
509 #undef news
510 }
511
512 static void nntp_get_desc (NNTP_DATA * data, const char *mask, char *msg, progress_t* bar)
513 {
514   char buf[STRING];
515
516   if (!option (OPTLOADDESC) || !data || !data->nserv)
517     return;
518
519   /* Get newsgroup description, if we can */
520   if (data->nserv->hasXGTITLE)
521     snprintf (buf, sizeof (buf), "XGTITLE %s\r\n", mask);
522   else
523     snprintf (buf, sizeof (buf), "string_list_t NEWSGROUPS %s\r\n", mask);
524   if (mutt_nntp_fetch (data, buf, msg, bar, parse_description, data->nserv, 0) !=
525       0) {
526   }
527 }
528
529 /*
530  * XOVER returns a tab separated list of:
531  * id|subject|from|date|Msgid|references|bytes|lines|xref
532  *
533  * This has to duplicate some of the functionality of 
534  * mutt_read_rfc822_header(), since it replaces the call to that (albeit with
535  * a limited number of headers which are "parsed" by placement in the list)
536  */
537 static int nntp_parse_xover (CONTEXT * ctx, char *buf, HEADER * hdr)
538 {
539   NNTP_DATA *nntp_data = (NNTP_DATA *) ctx->data;
540   char *p, *b;
541   int x, done = 0;
542
543   hdr->env = envelope_new();
544   hdr->env->newsgroups = m_strdup(nntp_data->group);
545   hdr->content = mutt_new_body ();
546   hdr->content->type = TYPETEXT;
547   hdr->content->subtype = m_strdup("plain");
548   hdr->content->encoding = ENC7BIT;
549   hdr->content->disposition = DISPINLINE;
550   hdr->content->length = -1;
551   b = p = buf;
552
553   for (x = 0; !done && x < 9; x++) {
554     /* if from file, need to skip newline character */
555     while (*p && *p != '\n' && *p != '\t')
556       p++;
557     if (!*p)
558       done++;
559     *p = '\0';
560     p++;
561     switch (x) {
562     case 0:
563
564       hdr->article_num = atoi (b);
565       nntp_get_status (ctx, hdr, NULL, hdr->article_num);
566       break;
567     case 1:
568       hdr->env->subject = m_strdup(b);
569       break;
570     case 2:
571       address_list_wipe(&hdr->env->from);
572       hdr->env->from = rfc822_parse_adrlist (hdr->env->from, b);
573       /* same as for mutt_parse_rfc822_line():
574        * don't leave from info NULL if there's an invalid address (or
575        * whatever) in From: field; mutt would just display it as empty
576        * and mark mail/(esp.) news article as your own. aaargh! this
577        * bothered me for _years_ */
578       if (!hdr->env->from) {
579         hdr->env->from = address_new ();
580         hdr->env->from->personal = m_strdup(b);
581       }
582       break;
583     case 3:
584       hdr->date_sent = mutt_parse_date (b, hdr);
585       hdr->received = hdr->date_sent;
586       break;
587     case 4:
588       p_delete(&hdr->env->message_id);
589       hdr->env->message_id = m_strdup(b);
590       break;
591     case 5:
592       string_list_wipe(&hdr->env->references);
593       hdr->env->references = mutt_parse_references (b, 0);
594       break;
595     case 6:
596       hdr->content->length = atoi (b);
597       break;
598     case 7:
599       hdr->lines = atoi (b);
600       break;
601     case 8:
602       if (!hdr->read)
603         p_delete(&hdr->env->xref);
604       b = b + 6;                /* skips the "Xref: " */
605       hdr->env->xref = m_strdup(b);
606       nntp_parse_xref (ctx, nntp_data->group, b, hdr);
607     }
608     rfc2047_decode_envelope(hdr->env);
609     if (!*p)
610       return -1;
611     b = p;
612   }
613   return 0;
614 }
615
616 typedef struct {
617   CONTEXT *ctx;
618   unsigned int base;
619   unsigned int first;
620   unsigned int last;
621   unsigned short *messages;
622   char *msg;
623 } FETCH_CONTEXT;
624
625 #define fc ((FETCH_CONTEXT *) c)
626
627 #if WANT_LISTGROUP_COMMAND
628 static int _nntp_fetch_numbers (unsigned int num, void *c)
629 {
630   if (num < fc->base || num > fc->last)
631     return 0;
632   fc->messages[num - fc->base] = 1;
633   return 0;
634 }
635 static int nntp_fetch_numbers (char *line, void *c)
636 {
637   if (!line)
638     return 0;
639   return (_nntp_fetch_numbers ((unsigned int) atoi (line), c));
640 }
641 #endif
642
643 static int add_xover_line (char *line, void *c)
644 {
645   unsigned int num, total;
646   CONTEXT *ctx = fc->ctx;
647   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
648
649   if (!line)
650     return 0;
651
652   if (ctx->msgcount >= ctx->hdrmax)
653     mx_alloc_memory (ctx);
654   ctx->hdrs[ctx->msgcount] = header_new();
655   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
656
657   nntp_parse_xover (ctx, line, ctx->hdrs[ctx->msgcount]);
658   num = ctx->hdrs[ctx->msgcount]->article_num;
659
660   if (num >= fc->first && num <= fc->last && fc->messages[num - fc->base]) {
661     ctx->msgcount++;
662     if (num > data->lastLoaded)
663       data->lastLoaded = num;
664     num = num - fc->first + 1;
665     total = fc->last - fc->first + 1;
666     if (!ctx->quiet && fc->msg && ReadInc && (num % ReadInc == 0))
667       mutt_message ("%s %d/%d", fc->msg, num, total);
668   }
669   else
670     header_delete(&ctx->hdrs[ctx->msgcount]);       /* skip it */
671
672   return 0;
673 }
674
675 #undef fc
676
677 static int nntp_fetch_headers (CONTEXT * ctx, unsigned int first,
678                                unsigned int last)
679 {
680   char buf[HUGE_STRING];
681   char *msg = _("Fetching message headers...");
682   char *msg2 = _("Fetching headers from cache...");
683   NNTP_DATA *nntp_data = ((NNTP_DATA *) ctx->data);
684   int ret;
685   int num;
686   int oldmsgcount;
687   unsigned int current;
688   FILE *f;
689   FETCH_CONTEXT fc;
690
691   /* if empty group or nothing to do */
692   if (!last || first > last)
693     return 0;
694
695   /* fetch list of articles */
696   mutt_message _("Fetching list of articles...");
697
698   fc.ctx = ctx;
699   fc.base = first;
700   fc.last = last;
701   fc.messages = p_new(unsigned short, last - first + 1);
702 #if WANT_LISTGROUP_COMMAND
703   if (nntp_data->nserv->hasLISTGROUP) {
704     snprintf (buf, sizeof (buf), "LISTGROUP %s\r\n", nntp_data->group);
705     if (mutt_nntp_fetch (nntp_data, buf, NULL, NULL, nntp_fetch_numbers, &fc, 0) !=
706         0) {
707       mutt_error (_("LISTGROUP command failed: %s"), buf);
708       sleep (2);
709       p_delete(&fc.messages);
710       return -1;
711     }
712   }
713   else {
714 #endif
715     for (num = 0; num < last - first + 1; num++)
716       fc.messages[num] = 1;
717 #if WANT_LISTGROUP_COMMAND
718   }
719 #endif
720
721   /* CACHE: must be loaded xover cache here */
722   num = nntp_data->lastCached - first + 1;
723   if (option (OPTNEWSCACHE) && nntp_data->cache && num > 0) {
724     nntp_cache_expand (buf, nntp_data->cache);
725     mutt_message (msg2);
726
727     if ((f = safe_fopen (buf, "r"))) {
728       int r = 0, c = 0;
729
730       /* counting number of lines */
731       while (fgets (buf, sizeof (buf), f) != NULL)
732         r++;
733       rewind (f);
734       while (r > num && fgets (buf, sizeof (buf), f) != NULL)
735         r--;
736       oldmsgcount = ctx->msgcount;
737       fc.first = first;
738       fc.last = first + num - 1;
739       fc.msg = NULL;
740       while (fgets (buf, sizeof (buf), f) != NULL) {
741         if (ReadInc && ((++c) % ReadInc == 0))
742           mutt_message ("%s %d/%d", msg2, c, r);
743         add_xover_line (buf, &fc);
744       }
745       fclose (f);
746       nntp_data->lastLoaded = fc.last;
747       first = fc.last + 1;
748       if (ctx->msgcount > oldmsgcount)
749         mx_update_context (ctx, ctx->msgcount - oldmsgcount);
750     }
751     else
752       nntp_delete_cache (nntp_data);
753   }
754   num = last - first + 1;
755   if (num <= 0) {
756     p_delete(&fc.messages);
757     return 0;
758   }
759
760   /*
761    * Without XOVER, we have to fetch each article header and parse
762    * it.  With XOVER, we ask for all of them
763    */
764   mutt_message (msg);
765   if (nntp_data->nserv->hasXOVER) {
766     oldmsgcount = ctx->msgcount;
767     fc.first = first;
768     fc.last = last;
769     fc.msg = msg;
770     snprintf (buf, sizeof (buf), "XOVER %d-%d\r\n", first, last);
771     ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, add_xover_line, &fc, 0);
772     if (ctx->msgcount > oldmsgcount)
773       mx_update_context (ctx, ctx->msgcount - oldmsgcount);
774     if (ret != 0) {
775       mutt_error (_("XOVER command failed: %s"), buf);
776       p_delete(&fc.messages);
777       return -1;
778     }
779     /* fetched OK */
780   }
781   else
782     for (current = first; current <= last; current++) {
783       HEADER *h;
784
785       ret = current - first + 1;
786       mutt_message ("%s %d/%d", msg, ret, num);
787
788       if (!fc.messages[current - fc.base])
789         continue;
790
791       if (ctx->msgcount >= ctx->hdrmax)
792         mx_alloc_memory (ctx);
793       h = ctx->hdrs[ctx->msgcount] = header_new();
794       h->index = ctx->msgcount;
795
796       ret = nntp_read_header (ctx, NULL, current);
797       if (ret == 0) {           /* Got article. Fetch next header */
798         nntp_get_status (ctx, h, NULL, h->article_num);
799         ctx->msgcount++;
800         mx_update_context (ctx, 1);
801       }
802       else
803         header_delete(&h);  /* skip it */
804       if (ret == -1) {
805         p_delete(&fc.messages);
806         return -1;
807       }
808
809       if (current > nntp_data->lastLoaded)
810         nntp_data->lastLoaded = current;
811     }
812   p_delete(&fc.messages);
813   nntp_data->lastLoaded = last;
814   mutt_clear_error ();
815   return 0;
816 }
817
818 /* 
819  * currently, nntp "mailbox" is "newsgroup"
820  */
821 int nntp_open_mailbox (CONTEXT * ctx)
822 {
823   NNTP_DATA *nntp_data;
824   NNTP_SERVER *serv;
825   char buf[HUGE_STRING];
826   char server[LONG_STRING];
827   int count = 0;
828   unsigned int first;
829   ACCOUNT act;
830
831   p_clear(&act, 1);
832
833   if (nntp_parse_url (ctx->path, &act, buf, sizeof (buf)) < 0 || !*buf) {
834     mutt_error (_("%s is an invalid newsgroup specification!"), ctx->path);
835     mutt_sleep (2);
836     return -1;
837   }
838
839   server[0] = '\0';
840   nntp_expand_path (server, sizeof (server), &act);
841   if (!(serv = mutt_select_newsserver (server)) || serv->status != NNTP_OK)
842     return -1;
843
844   CurrentNewsSrv = serv;
845
846   /* create NNTP-specific state struct if nof found in list */
847   if ((nntp_data = (NNTP_DATA *) hash_find (serv->newsgroups, buf)) == NULL) {
848     nntp_data = xmalloc(sizeof(NNTP_DATA) + m_strlen(buf) + 1);
849     nntp_data->group = (char *) nntp_data + sizeof (NNTP_DATA);
850     strcpy (nntp_data->group, buf);
851     hash_insert (serv->newsgroups, nntp_data->group, nntp_data, 0);
852     nntp_add_to_list (serv, nntp_data);
853   }
854   ctx->data = nntp_data;
855   nntp_data->nserv = serv;
856
857   mutt_message (_("Selecting %s..."), nntp_data->group);
858
859   if (!nntp_data->desc) {
860     nntp_get_desc (nntp_data, nntp_data->group, NULL, NULL);
861     if (nntp_data->desc)
862       nntp_save_cache_index (serv);
863   }
864
865   buf[0] = 0;
866   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
867     return -1;
868   }
869
870   if (m_strncmp("211", buf, 3)) {
871     string_list_t *l = serv->list;
872
873     /* GROUP command failed */
874     if (!m_strncmp("411", buf, 3)) {
875       mutt_error (_("Newsgroup %s not found on server %s"),
876                   nntp_data->group, serv->conn->account.host);
877
878       /* CACHE: delete cache and line from .index */
879       nntp_delete_cache (nntp_data);
880       hash_delete (serv->newsgroups, nntp_data->group, NULL,
881                    nntp_delete_data);
882       while (l && l->data != (void *) nntp_data)
883         l = l->next;
884       if (l)
885         l->data = NULL;
886
887       sleep (2);
888     }
889
890     return -1;
891   }
892
893   sscanf (buf + 4, "%d %u %u %s", &count, &nntp_data->firstMessage,
894           &nntp_data->lastMessage, buf);
895
896   nntp_data->deleted = 0;
897
898   time (&serv->check_time);
899
900   /*
901    * Check for max adding context. If it is greater than $nntp_context,
902    * strip off extra articles
903    */
904   first = nntp_data->firstMessage;
905   if (NntpContext && nntp_data->lastMessage - first + 1 > NntpContext)
906     first = nntp_data->lastMessage - NntpContext + 1;
907   if (first)
908     nntp_data->lastLoaded = first - 1;
909   return nntp_fetch_headers (ctx, first, nntp_data->lastMessage);
910 }
911
912 int nntp_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
913 {
914   char buf[LONG_STRING];
915   char path[_POSIX_PATH_MAX];
916   NNTP_CACHE *cache;
917   int ret;
918   progress_t bar;
919
920   /* see if we already have the message in our cache */
921   cache =
922     &((NNTP_DATA *) ctx->data)->acache[ctx->hdrs[msgno]->index %
923                                        NNTP_CACHE_LEN];
924
925   /* if everything is fine, assign msg->fp and return */
926   if (cache->path && cache->index == ctx->hdrs[msgno]->index &&
927       (msg->fp = fopen (cache->path, "r")))
928     return 0;
929
930   /* clear the previous entry */
931   unlink (cache->path);
932   p_delete(&cache->path);
933
934   cache->index = ctx->hdrs[msgno]->index;
935   mutt_mktemp (path);
936   cache->path = m_strdup(path);
937   if (!(msg->fp = safe_fopen (path, "w+"))) {
938     p_delete(&cache->path);
939     return -1;
940   }
941
942   if (ctx->hdrs[msgno]->article_num == 0)
943     snprintf (buf, sizeof (buf), "ARTICLE %s\r\n",
944               ctx->hdrs[msgno]->env->message_id);
945   else
946     snprintf (buf, sizeof (buf), "ARTICLE %d\r\n",
947               ctx->hdrs[msgno]->article_num);
948
949   bar.msg = _("Fetching message...");
950   bar.size = 0;
951   mutt_progress_bar (&bar, 0);
952
953   ret = mutt_nntp_fetch ((NNTP_DATA *) ctx->data, buf, NULL, &bar, nntp_read_tempfile,
954                          msg->fp, ctx->tagged);
955   if (ret == 1) {
956     mutt_error (_("Article %d not found on server"),
957                 ctx->hdrs[msgno]->article_num);
958   }
959
960   if (ret) {
961     fclose (msg->fp);
962     unlink (path);
963     p_delete(&cache->path);
964     return -1;
965   }
966
967   envelope_delete(&ctx->hdrs[msgno]->env);
968   ctx->hdrs[msgno]->env =
969     mutt_read_rfc822_header (msg->fp, ctx->hdrs[msgno], 0, 0);
970   /* fix content length */
971   fseeko (msg->fp, 0, SEEK_END);
972   ctx->hdrs[msgno]->content->length = ftello (msg->fp) -
973     ctx->hdrs[msgno]->content->offset;
974
975   /* this is called in mutt before the open which fetches the message, 
976    * which is probably wrong, but we just call it again here to handle
977    * the problem instead of fixing it.
978    */
979   mutt_parse_mime_message (ctx, ctx->hdrs[msgno]);
980
981   /* These would normally be updated in mx_update_context(), but the 
982    * full headers aren't parsed with XOVER, so the information wasn't
983    * available then.
984    */
985   ctx->hdrs[msgno]->security = crypt_query (ctx->hdrs[msgno]->content);
986
987   mutt_clear_error ();
988   rewind (msg->fp);
989
990   return 0;
991 }
992
993 /* Post article */
994 int nntp_post (const char *msg)
995 {
996   char buf[LONG_STRING];
997   size_t len;
998   FILE *f;
999   NNTP_DATA *nntp_data;
1000
1001   if (Context && Context->magic == M_NNTP)
1002     nntp_data = (NNTP_DATA *) Context->data;
1003   else {
1004     if (!(CurrentNewsSrv = mutt_select_newsserver (NewsServer)) ||
1005         !CurrentNewsSrv->list || !CurrentNewsSrv->list->data) {
1006       mutt_error (_("Can't post article. No connection to news server."));
1007       return -1;
1008     }
1009     nntp_data = (NNTP_DATA *) CurrentNewsSrv->list->data;
1010   }
1011
1012   if (!(f = safe_fopen (msg, "r"))) {
1013     mutt_error (_("Can't post article. Unable to open %s"), msg);
1014     return -1;
1015   }
1016
1017   m_strcpy(buf, sizeof(buf), "POST\r\n");
1018   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
1019     mutt_error (_("Can't post article. Connection to %s lost."),
1020                 nntp_data->nserv->conn->account.host);
1021     return -1;
1022   }
1023   if (buf[0] != '3') {
1024     mutt_error (_("Can't post article: %s"), buf);
1025     return -1;
1026   }
1027
1028   buf[0] = '.';
1029   buf[1] = '\0';
1030   while (fgets (buf + 1, sizeof (buf) - 2, f) != NULL) {
1031     len = m_strlen(buf);
1032     if (buf[len - 1] == '\n') {
1033       buf[len - 1] = '\r';
1034       buf[len] = '\n';
1035       len++;
1036       buf[len] = '\0';
1037     }
1038     if (buf[1] == '.')
1039       mutt_socket_write_d (nntp_data->nserv->conn, buf, M_SOCK_LOG_HDR);
1040     else
1041       mutt_socket_write_d (nntp_data->nserv->conn, buf + 1, M_SOCK_LOG_HDR);
1042   }
1043   fclose (f);
1044
1045   if (buf[m_strlen(buf) - 1] != '\n')
1046     mutt_socket_write_d (nntp_data->nserv->conn, "\r\n", M_SOCK_LOG_HDR);
1047   mutt_socket_write_d (nntp_data->nserv->conn, ".\r\n", M_SOCK_LOG_HDR);
1048   if (mutt_socket_readln (buf, sizeof (buf), nntp_data->nserv->conn) < 0) {
1049     mutt_error (_("Can't post article. Connection to %s lost."),
1050                 nntp_data->nserv->conn->account.host);
1051     return -1;
1052   }
1053   if (buf[0] != '2') {
1054     mutt_error (_("Can't post article: %s"), buf);
1055     return -1;
1056   }
1057
1058   return 0;
1059 }
1060
1061 /* nntp_logout_all: close all open connections. */
1062 void nntp_logout_all (void)
1063 {
1064   char buf[LONG_STRING];
1065   CONNECTION *conn;
1066
1067   conn = mutt_socket_head ();
1068
1069   while (conn) {
1070     CONNECTION* next = conn->next;
1071     if (conn->account.type == M_ACCT_TYPE_NNTP) {
1072       mutt_message (_("Closing connection to %s..."), conn->account.host);
1073       mutt_socket_write (conn, "QUIT\r\n");
1074       mutt_socket_readln (buf, sizeof (buf), conn);
1075       mutt_clear_error ();
1076       mutt_socket_close (conn);
1077       mutt_socket_free (conn);
1078     }
1079     conn = next;
1080   }
1081 }
1082
1083 static void nntp_free_acache (NNTP_DATA * data)
1084 {
1085   int i;
1086
1087   for (i = 0; i < NNTP_CACHE_LEN; i++) {
1088     if (data->acache[i].path) {
1089       unlink (data->acache[i].path);
1090       p_delete(&data->acache[i].path);
1091     }
1092   }
1093 }
1094
1095 void nntp_delete_data (void *p)
1096 {
1097   NNTP_DATA *data = (NNTP_DATA *)p;
1098
1099   if (!p)
1100     return;
1101   p_delete(&data->entries);
1102   p_delete(&data->desc);
1103   p_delete(&data->cache);
1104   nntp_free_acache (data);
1105   p_delete(&data);
1106 }
1107
1108 int nntp_sync_mailbox (CONTEXT * ctx, int unused1, int* unused2)
1109 {
1110   NNTP_DATA *data = ctx->data;
1111
1112   /* CACHE: update cache and .index files */
1113   if ((option (OPTSAVEUNSUB) || data->subscribed))
1114     nntp_save_cache_group (ctx);
1115   nntp_free_acache (data);
1116
1117   data->nserv->check_time = 0;  /* next nntp_check_mailbox() will really check */
1118   return 0;
1119 }
1120
1121 void nntp_fastclose_mailbox (CONTEXT * ctx)
1122 {
1123   NNTP_DATA *data = (NNTP_DATA *) ctx->data, *tmp;
1124
1125   if (!data)
1126     return;
1127   nntp_free_acache (data);
1128   if (!data->nserv || !data->nserv->newsgroups || !data->group)
1129     return;
1130   nntp_save_cache_index (data->nserv);
1131   if ((tmp = hash_find (data->nserv->newsgroups, data->group)) == NULL
1132       || tmp != data)
1133     nntp_delete_data (data);
1134   else
1135     nntp_sync_sidebar (data);
1136 }
1137
1138 /* commit changes and terminate connection */
1139 int nntp_close_mailbox (CONTEXT * ctx)
1140 {
1141   if (!ctx)
1142     return -1;
1143   mutt_message _("Quitting newsgroup...");
1144
1145   if (ctx->data) {
1146     NNTP_DATA *data = (NNTP_DATA *) ctx->data;
1147     int ret;
1148
1149     if (data->nserv && data->nserv->conn && ctx->unread) {
1150       ret = query_quadoption (OPT_CATCHUP, _("Mark all articles read?"));
1151       if (ret == M_YES)
1152         mutt_newsgroup_catchup (data->nserv, data->group);
1153       else if (ret < 0)
1154         return -1;
1155     }
1156   }
1157   nntp_sync_mailbox (ctx, 0, NULL);
1158   if (ctx->data && ((NNTP_DATA *) ctx->data)->nserv) {
1159     NNTP_SERVER *news;
1160
1161     news = ((NNTP_DATA *) ctx->data)->nserv;
1162     newsrc_gen_entries (ctx);
1163     ((NNTP_DATA *) ctx->data)->unread = ctx->unread;
1164     mutt_newsrc_update (news);
1165   }
1166   mutt_clear_error ();
1167   return 0;
1168 }
1169
1170 /* use the GROUP command to poll for new mail */
1171 static int _nntp_check_mailbox (CONTEXT * ctx, NNTP_DATA * nntp_data)
1172 {
1173   char buf[LONG_STRING];
1174   int count = 0;
1175
1176   if (nntp_data->nserv->check_time + NewsPollTimeout > time (NULL))
1177     return 0;
1178
1179   buf[0] = 0;
1180   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
1181     return -1;
1182   }
1183   if (m_strncmp("211", buf, 3)) {
1184     buf[0] = 0;
1185     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
1186       return -1;
1187     }
1188   }
1189   if (!m_strncmp("211", buf, 3)) {
1190     int first;
1191     int last;
1192
1193     sscanf (buf + 4, "%d %d %d", &count, &first, &last);
1194     nntp_data->firstMessage = first;
1195     nntp_data->lastMessage = last;
1196     if (ctx && last > nntp_data->lastLoaded) {
1197       nntp_fetch_headers (ctx, nntp_data->lastLoaded + 1, last);
1198       time (&nntp_data->nserv->check_time);
1199       return 1;
1200     }
1201     if (!last || (!nntp_data->rc && !nntp_data->lastCached))
1202       nntp_data->unread = count;
1203     else
1204       mutt_newsgroup_stat (nntp_data);
1205     /* active was renumbered? */
1206     if (last < nntp_data->lastLoaded) {
1207       if (!nntp_data->max) {
1208         nntp_data->entries = p_new(NEWSRC_ENTRY, 5);
1209         nntp_data->max = 5;
1210       }
1211       nntp_data->lastCached = 0;
1212       nntp_data->num = 1;
1213       nntp_data->entries[0].first = 1;
1214       nntp_data->entries[0].last = 0;
1215     }
1216     nntp_sync_sidebar (nntp_data);
1217   }
1218
1219   time (&nntp_data->nserv->check_time);
1220   return 0;
1221 }
1222
1223 int nntp_check_mailbox (CONTEXT * ctx, int* unused1, int unused2)
1224 {
1225   return _nntp_check_mailbox (ctx, (NNTP_DATA *) ctx->data);
1226 }
1227
1228 static int add_group (char *buf, void *serv)
1229 {
1230 #define s ((NNTP_SERVER *) serv)
1231   char group[LONG_STRING], mod, desc[HUGE_STRING];
1232   int first, last;
1233   NNTP_DATA *nntp_data;
1234   static int n = 0;
1235
1236   _checked = n;                 /* _checked have N, where N = number of groups */
1237   if (!buf)                     /* at EOF must be zerouth */
1238     n = 0;
1239
1240   if (!s || !buf)
1241     return 0;
1242
1243   *desc = 0;
1244   sscanf (buf, "%s %d %d %c %[^\n]", group, &last, &first, &mod, desc);
1245   if (!group)
1246     return 0;
1247   if ((nntp_data = (NNTP_DATA *) hash_find (s->newsgroups, group)) == NULL) {
1248     n++;
1249     nntp_data = xmalloc(sizeof(NNTP_DATA) + m_strlen(group) + 1);
1250     nntp_data->group = (char *) nntp_data + sizeof (NNTP_DATA);
1251     strcpy (nntp_data->group, group);
1252     nntp_data->nserv = s;
1253     if (s->newsgroups->nelem < s->newsgroups->curnelem * 2)
1254       s->newsgroups = hash_resize (s->newsgroups, s->newsgroups->nelem * 2);
1255     hash_insert (s->newsgroups, nntp_data->group, nntp_data, 0);
1256     nntp_add_to_list (s, nntp_data);
1257   }
1258   nntp_data->deleted = 0;
1259   nntp_data->firstMessage = first;
1260   nntp_data->lastMessage = last;
1261   if (mod == 'y')
1262     nntp_data->allowed = 1;
1263   else
1264     nntp_data->allowed = 0;
1265   if (nntp_data->desc)
1266     p_delete(&nntp_data->desc);
1267   if (*desc)
1268     nntp_data->desc = m_strdup(desc);
1269   if (nntp_data->rc || nntp_data->lastCached)
1270     mutt_newsgroup_stat (nntp_data);
1271   else if (nntp_data->lastMessage &&
1272            nntp_data->firstMessage <= nntp_data->lastMessage)
1273     nntp_data->unread = nntp_data->lastMessage - nntp_data->firstMessage + 1;
1274   else
1275     nntp_data->unread = 0;
1276
1277   return 0;
1278 #undef s
1279 }
1280
1281 int nntp_check_newgroups (NNTP_SERVER * serv, int force)
1282 {
1283   char buf[LONG_STRING];
1284   NNTP_DATA nntp_data;
1285   string_list_t *l;
1286   string_list_t emp;
1287   time_t now;
1288   struct tm *t;
1289
1290   if (!serv || !serv->newgroups_time)
1291     return -1;
1292
1293   if (nntp_open_connection (serv) < 0)
1294     return -1;
1295
1296   /* check subscribed groups for new news */
1297   if (option (OPTSHOWNEWNEWS)) {
1298     mutt_message _("Checking for new messages...");
1299
1300     for (l = serv->list; l; l = l->next) {
1301       serv->check_time = 0;     /* really check! */
1302       if (l->data && ((NNTP_DATA *) l->data)->subscribed)
1303         _nntp_check_mailbox (NULL, (NNTP_DATA *) l->data);
1304     }
1305     sidebar_draw (CurrentMenu);
1306   }
1307   else if (!force)
1308     return 0;
1309
1310   mutt_message _("Checking for new newsgroups...");
1311
1312   now = serv->newgroups_time;
1313   time (&serv->newgroups_time);
1314   t = gmtime (&now);
1315   snprintf (buf, sizeof (buf), "NEWGROUPS %02d%02d%02d %02d%02d%02d GMT\r\n",
1316             (t->tm_year % 100), t->tm_mon + 1, t->tm_mday, t->tm_hour,
1317             t->tm_min, t->tm_sec);
1318   nntp_data.nserv = serv;
1319   if (Context && Context->magic == M_NNTP)
1320     nntp_data.group = ((NNTP_DATA *) Context->data)->group;
1321   else
1322     nntp_data.group = NULL;
1323   l = serv->tail;
1324   if (mutt_nntp_fetch (&nntp_data, buf, _("Adding new newsgroups..."), NULL,
1325                        add_group, serv, 0) != 0) {
1326     return -1;
1327   }
1328
1329   mutt_message _("Loading descriptions...");
1330
1331   if (l)
1332     emp.next = l->next;
1333   else
1334     emp.next = serv->list;
1335   l = &emp;
1336   while (l->next) {
1337     l = l->next;
1338     ((NNTP_DATA *) l->data)->new = 1;
1339     nntp_get_desc ((NNTP_DATA *) l->data, ((NNTP_DATA *) l->data)->group,
1340                    NULL, NULL);
1341   }
1342   if (emp.next)
1343     nntp_save_cache_index (serv);
1344   mutt_clear_error ();
1345   return _checked;
1346 }
1347
1348 /* Load list of all newsgroups from cache ALL */
1349 int nntp_get_cache_all (NNTP_SERVER * serv)
1350 {
1351   char buf[HUGE_STRING];
1352   FILE *f;
1353
1354   nntp_cache_expand (buf, serv->cache);
1355   if ((f = safe_fopen (buf, "r"))) {
1356     int i = 0;
1357
1358     while (fgets (buf, sizeof (buf), f) != NULL) {
1359       if (ReadInc && (i % ReadInc == 0))
1360         mutt_message (_("Loading list from cache... %d"), i);
1361       add_group (buf, serv);
1362       i++;
1363     }
1364     add_group (NULL, NULL);
1365     fclose (f);
1366     mutt_clear_error ();
1367     return 0;
1368   }
1369   else {
1370     p_delete(&serv->cache);
1371     return -1;
1372   }
1373 }
1374
1375 /* Load list of all newsgroups from active */
1376 int nntp_get_active (NNTP_SERVER * serv)
1377 {
1378   char msg[SHORT_STRING];
1379   NNTP_DATA nntp_data;
1380   string_list_t *tmp;
1381
1382   if (nntp_open_connection (serv) < 0)
1383     return -1;
1384
1385   snprintf (msg, sizeof (msg),
1386             _("Loading list of all newsgroups on server %s..."),
1387             serv->conn->account.host);
1388   mutt_message (msg);
1389   time (&serv->newgroups_time);
1390   nntp_data.nserv = serv;
1391   nntp_data.group = NULL;
1392
1393   if (mutt_nntp_fetch (&nntp_data, "string_list_t\r\n", msg, NULL, add_group, serv, 0) < 0) {
1394     return -1;
1395   }
1396
1397   m_strcpy(msg, sizeof(msg), _("Loading descriptions..."));
1398   mutt_message (msg);
1399   nntp_get_desc (&nntp_data, "*", msg, NULL);
1400
1401   for (tmp = serv->list; tmp; tmp = tmp->next) {
1402     NNTP_DATA *data = (NNTP_DATA *) tmp->data;
1403
1404     if (data && data->deleted && !data->rc) {
1405       nntp_delete_cache (data);
1406       hash_delete (serv->newsgroups, data->group, NULL, nntp_delete_data);
1407       tmp->data = NULL;
1408     }
1409   }
1410   nntp_save_cache_index (serv);
1411
1412   mutt_clear_error ();
1413   return _checked;
1414 }
1415
1416 /*
1417  * returns -1 if error ocurred while retrieving header,
1418  * number of articles which ones exist in context on success.
1419  */
1420 int nntp_check_msgid (CONTEXT * ctx, const char *msgid)
1421 {
1422   int ret;
1423
1424   /* if msgid is already in context, don't reload them */
1425   if (hash_find (ctx->id_hash, msgid))
1426     return 1;
1427   if (ctx->msgcount == ctx->hdrmax)
1428     mx_alloc_memory (ctx);
1429   ctx->hdrs[ctx->msgcount] = header_new();
1430   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
1431
1432   mutt_message (_("Fetching %s from server..."), msgid);
1433   ret = nntp_read_header (ctx, msgid, 0);
1434   /* since nntp_read_header() may set read flag, we must reset it */
1435   ctx->hdrs[ctx->msgcount]->read = 0;
1436   if (ret != 0)
1437     header_delete(&ctx->hdrs[ctx->msgcount]);
1438   else {
1439     ctx->msgcount++;
1440     mx_update_context (ctx, 1);
1441     ctx->changed = 1;
1442   }
1443   return ret;
1444 }
1445
1446 typedef struct {
1447   CONTEXT *ctx;
1448   unsigned int num;
1449   unsigned int max;
1450   unsigned int *child;
1451 } CHILD_CONTEXT;
1452
1453 static int check_children (char *s, void *c)
1454 {
1455 #define cc ((CHILD_CONTEXT *) c)
1456   unsigned int i, n;
1457
1458   if (!s || (n = atoi (s)) == 0)
1459     return 0;
1460   for (i = 0; i < cc->ctx->msgcount; i++)
1461     if (cc->ctx->hdrs[i]->article_num == n)
1462       return 0;
1463   if (cc->num >= cc->max)
1464     p_realloc(&cc->child, cc->max += 25);
1465   cc->child[cc->num++] = n;
1466
1467   return 0;
1468 #undef cc
1469 }
1470
1471 int nntp_check_children (CONTEXT * ctx, const char *msgid)
1472 {
1473   NNTP_DATA *nntp_data = (NNTP_DATA *) ctx->data;
1474   char buf[STRING];
1475   int i, ret = 0, tmp = 0;
1476   CHILD_CONTEXT cc;
1477
1478   if (!nntp_data || !nntp_data->nserv || !nntp_data->nserv->conn ||
1479       !nntp_data->nserv->conn->account.host)
1480     return -1;
1481   if (nntp_data->firstMessage > nntp_data->lastLoaded)
1482     return 0;
1483   if (!nntp_data->nserv->hasXPAT) {
1484     mutt_error (_("Server %s does not support this operation!"),
1485                 nntp_data->nserv->conn->account.host);
1486     return -1;
1487   }
1488
1489   snprintf (buf, sizeof (buf), "XPAT References %d-%d *%s*\r\n",
1490             nntp_data->firstMessage, nntp_data->lastLoaded, msgid);
1491
1492   cc.ctx = ctx;
1493   cc.num = 0;
1494   cc.max = 25;
1495   cc.child = p_new(unsigned int, 25);
1496   if (mutt_nntp_fetch (nntp_data, buf, NULL, NULL, check_children, &cc, 0)) {
1497     p_delete(&cc.child);
1498     return -1;
1499   }
1500   /* dont try to read the xover cache. check_children() already
1501    * made sure that we dont have the article, so we need to visit
1502    * the server. Reading the cache at this point is also bad
1503    * because it would duplicate messages */
1504   if (option (OPTNEWSCACHE)) {
1505     tmp++;
1506     unset_option (OPTNEWSCACHE);
1507   }
1508   for (i = 0; i < cc.num; i++) {
1509     if ((ret = nntp_fetch_headers (ctx, cc.child[i], cc.child[i])))
1510       break;
1511     if (ctx->msgcount &&
1512         ctx->hdrs[ctx->msgcount - 1]->article_num == cc.child[i])
1513       ctx->hdrs[ctx->msgcount - 1]->read = 0;
1514   }
1515   if (tmp)
1516     set_option (OPTNEWSCACHE);
1517   p_delete(&cc.child);
1518   return ret;
1519 }