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