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