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