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