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