add printf-like primitive to the buffers.
[apps/madmutt.git] / 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 <libgen.h>
15
16 #include <lib-mime/mime.h>
17 #include <lib-ui/curses.h>
18 #include <lib-ui/sidebar.h>
19 #include <lib-mx/mx.h>
20
21 #include "mutt.h"
22 #include "sort.h"
23 #include "nntp.h"
24 #include "buffy.h"
25 #include "crypt.h"
26
27 #define NNTP_PORT      119
28 #define NNTP_SSL_PORT  563
29
30 static int nntp_get_cache_all (NNTP_SERVER *);
31 static int nntp_check_newgroups (NNTP_SERVER *, int);
32 static void mutt_newsgroup_stat (nntp_data_t *);
33 static void nntp_delete_cache (nntp_data_t *);
34
35 /* newsrc {{{ */
36
37 static int nntp_parse_newsrc_line (NNTP_SERVER * news, char *line)
38 {
39   nntp_data_t *data;
40   char group[LONG_STRING];
41   int x = 1;
42   char *p, *b, *h;
43
44   for (p = line; p; p = strchr(p, ',')) {
45     x++;
46   }
47
48   p = strpbrk(line, ":!");
49   if (!p)
50     return -1;
51
52   m_strncpy(group, ssizeof(group), line, p - line);
53   if ((data = hash_find(news->newsgroups, group)) == NULL) {
54     data = nntp_data_new();
55     data->group = m_strdup(group);
56     data->nserv = news;
57     data->deleted = 1;
58     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
59         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
60     hash_insert(news->newsgroups, data->group, data);
61     nntp_data_list_append(&news->list, data);
62   } else {
63     p_delete(&data->entries);
64   }
65
66   data->rc = 1;
67   data->entries = p_new(NEWSRC_ENTRY, x * 2);
68   data->max = x * 2;
69
70   data->subscribed = (*p++ == ':');
71
72   b = p;
73   x = 0;
74   while (*b) {
75     while (*p && *p != ',' && *p != '\n')
76       p++;
77     if (*p) {
78       *p = '\0';
79       p++;
80     }
81     if ((h = strchr (b, '-'))) {
82       *h = '\0';
83       h++;
84       data->entries[x].first = atoi (b);
85       data->entries[x].last = atoi (h);
86     }
87     else {
88       data->entries[x].first = atoi (b);
89       data->entries[x].last = data->entries[x].first;
90     }
91     b = p;
92     if (data->entries[x].last != 0)
93       x++;
94   }
95   if (x && !data->lastMessage)
96     data->lastMessage = data->entries[x - 1].last;
97   data->num = x;
98   mutt_newsgroup_stat (data);
99
100   return 0;
101 }
102
103 static int slurp_newsrc (NNTP_SERVER * news)
104 {
105   FILE *fp;
106   char *buf;
107   struct stat sb;
108
109   news->stat = stat (news->newsrc, &sb);
110   news->size = sb.st_size;
111   news->mtime = sb.st_mtime;
112
113   if ((fp = safe_fopen (news->newsrc, "r")) == NULL)
114     return -1;
115   /* hmm, should we use dotlock? */
116   if (mx_lock_file (news->newsrc, fileno (fp), 0, 0, 1)) {
117     m_fclose(&fp);
118     return -1;
119   }
120
121   buf = p_new(char, sb.st_size + 1);
122   while (fgets (buf, sb.st_size + 1, fp))
123     nntp_parse_newsrc_line (news, buf);
124   p_delete(&buf);
125
126   mx_unlock_file (news->newsrc, fileno (fp), 0);
127   m_fclose(&fp);
128   return 0;
129 }
130
131 static void nntp_cache_expand (char *dst, const char *src)
132 {
133   snprintf (dst, _POSIX_PATH_MAX, "%s/%s", NewsCacheDir, src);
134   mutt_expand_path (dst, _POSIX_PATH_MAX);
135 }
136
137 /* Loads $news_cache_dir/.index into memory, loads newsserver data
138  * and newsgroup cache names */
139 static int nntp_parse_cacheindex (NNTP_SERVER * news)
140 {
141   struct stat st;
142   char buf[HUGE_STRING], *cp;
143   char dir[_POSIX_PATH_MAX], file[_POSIX_PATH_MAX];
144   FILE *idx;
145   nntp_data_t *data;
146   int l, m, t;
147
148   /* check is server name defined or not */
149   if (!news || !news->conn || !news->conn->account.host)
150     return -1;
151   unset_option (OPTNEWSCACHE);
152   if (m_strisempty(NewsCacheDir))
153     return 0;
154
155   m_strcpy(dir, sizeof(dir), NewsCacheDir);
156   mutt_expand_path (dir, sizeof (dir));
157
158   if (lstat (dir, &st) || (st.st_mode & S_IFDIR) == 0) {
159     snprintf (buf, sizeof (buf), _("Directory %s not exist. Create it?"),
160               dir);
161     if (mutt_yesorno (buf, M_YES) != M_YES
162         || mkdir (dir, (S_IRWXU + S_IRWXG + S_IRWXO))) {
163       mutt_error _("Cache directory not created!");
164
165       return -1;
166     }
167     mutt_clear_error ();
168   }
169
170   set_option (OPTNEWSCACHE);
171
172   p_delete(&news->cache);
173   snprintf (buf, sizeof (buf), "%s/.index", dir);
174   if (!(idx = safe_fopen (buf, "a+")))
175     return 0;
176   rewind (idx);
177   while (fgets (buf, sizeof (buf), idx)) {
178     buf[m_strlen(buf) - 1] = 0;  /* strip ending '\n' */
179     if (!m_strncmp(buf, "#: ", 3) &&
180         !m_strcasecmp(buf + 3, news->conn->account.host))
181       break;
182   }
183   while (fgets (buf, sizeof (buf), idx)) {
184     cp = buf;
185     while (*cp && *cp != ' ')
186       cp++;
187     if (!*cp)
188       continue;
189     cp[0] = 0;
190     if (!m_strcmp(buf, "#:"))
191       break;
192     sscanf (cp + 1, "%s %d %d", file, &l, &m);
193     if (!m_strcmp(buf, "ALL")) {
194       news->cache = m_strdup(file);
195       news->newgroups_time = m;
196     }
197     else if (news->newsgroups) {
198       if ((data = hash_find (news->newsgroups, buf)) == NULL) {
199         data = nntp_data_new();
200         data->group = m_strdup(buf);
201         data->nserv = news;
202         data->deleted = 1;
203         if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
204             hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
205         hash_insert (news->newsgroups, data->group, data);
206         nntp_data_list_append(&news->list, data);
207       }
208       data->cache = m_strdup(file);
209       t = 0;
210       if (!data->firstMessage || data->lastMessage < m)
211         t = 1;
212       if (!data->firstMessage)
213         data->firstMessage = l;
214       if (data->lastMessage < m)
215         data->lastMessage = m;
216       data->lastCached = m;
217       if (t || !data->unread)
218         mutt_newsgroup_stat (data);
219     }
220   }
221   m_fclose(&idx);
222   return 0;
223 }
224
225 const char *nntp_format_str(char *dest, ssize_t destlen, char op,
226                             const char *src, const char *fmt,
227                             const char *ifstr __attribute__((unused)),
228                             const char *elstr __attribute__((unused)),
229                             anytype data __attribute__((unused)),
230                             format_flag flags __attribute__((unused)))
231 {
232   char fn[STRING], tmp[STRING];
233
234   switch (op) {
235   case 's':
236     m_strcpy(fn, sizeof (fn), NewsServer);
237     m_strtolower(fn);
238     snprintf (tmp, sizeof (tmp), "%%%ss", fmt);
239     snprintf (dest, destlen, tmp, fn);
240     break;
241   }
242   return (src);
243 }
244
245 /* nntp_parse_url: given an NNPT URL, return host, port,
246  * username, password and newsgroup will recognise. */
247 static int nntp_parse_url(const char *server, ACCOUNT * act, char *group,
248                           ssize_t group_len)
249 {
250   ciss_url_t url;
251   char *c;
252   int ret = -1;
253
254   /* Defaults */
255   act->flags = 0;
256   act->port = NNTP_PORT;
257   act->type = M_ACCT_TYPE_NNTP;
258
259   c = m_strdup(server);
260   url_parse_ciss (&url, c);
261
262   if (url.scheme == U_NNTP || url.scheme == U_NNTPS) {
263     if (url.scheme == U_NNTPS) {
264       act->has_ssl = 1;
265       act->port = NNTP_SSL_PORT;
266     }
267
268     *group = '\0';
269     if (url.path)
270       m_strcpy(group, group_len, url.path);
271
272     ret = mutt_account_fromurl (act, &url);
273   }
274
275   p_delete(&c);
276   return ret;
277 }
278
279 void nntp_expand_path (char *line, ssize_t len, ACCOUNT * act)
280 {
281   ciss_url_t url;
282
283   url.path = m_strdup(line);
284   mutt_account_tourl (act, &url);
285   url_ciss_tostring (&url, line, len, 0);
286   p_delete(&url.path);
287 }
288
289 /*
290  * Automatically loads a newsrc into memory, if necessary.
291  * Checks the size/mtime of a newsrc file, if it doesn't match, load
292  * again.  Hmm, if a system has broken mtimes, this might mean the file
293  * is reloaded every time, which we'd have to fix.
294  *
295  * a newsrc file is a line per newsgroup, with the newsgroup, then a 
296  * ':' denoting subscribed or '!' denoting unsubscribed, then a 
297  * comma separated list of article numbers and ranges.
298  */
299 NNTP_SERVER *mutt_select_newsserver (char *server)
300 {
301   char file[_POSIX_PATH_MAX];
302   char *buf, *p;
303   nntp_data_t *list;
304   ACCOUNT act;
305   NNTP_SERVER *serv;
306   CONNECTION *conn;
307
308   p_clear(&act, 1);
309
310   if (!server || !*server) {
311     mutt_error _("No newsserver defined!");
312
313     return NULL;
314   }
315
316   buf = p = p_new(char, m_strlen(server) + 10);
317   if (url_check_scheme (server) == U_UNKNOWN) {
318     strcpy (buf, "nntp://");
319     p = strchr (buf, '\0');
320   }
321   strcpy (p, server);
322
323   if ((nntp_parse_url (buf, &act, file, sizeof (file))) < 0 || *file) {
324     p_delete(&buf);
325     mutt_error (_("%s is an invalid newsserver specification!"), server);
326     return NULL;
327   }
328   p_delete(&buf);
329
330   conn = mutt_conn_find (NULL, &act);
331   if (!conn)
332     return NULL;
333
334   m_strformat(file, sizeof(file), 0, NewsRc, nntp_format_str, NULL, 0);
335   mutt_expand_path(file, sizeof(file));
336
337   serv = (NNTP_SERVER *) conn->data;
338   if (serv) {
339     struct stat sb;
340
341     /* externally modified? */
342     if (serv->stat != stat(file, &sb) || (!serv->stat &&
343                                            (serv->size != sb.st_size
344                                             || serv->mtime != sb.st_mtime)))
345     {
346       for (list = serv->list; list; list = list->next) {
347         list->subscribed = 0;
348         list->rc = 0;
349         list->num = 0;
350       }
351       slurp_newsrc (serv);
352       nntp_clear_cacheindex (serv);
353     }
354
355     if (serv->status == NNTP_BYE)
356       serv->status = NNTP_NONE;
357     nntp_check_newgroups (serv, 0);
358     return serv;
359   }
360
361   /* New newsserver */
362   serv = p_new(NNTP_SERVER, 1);
363   serv->conn = conn;
364   serv->newsrc = m_strdup(file);
365   serv->newsgroups = hash_new(1009, false);
366   slurp_newsrc (serv);          /* load .newsrc */
367   nntp_parse_cacheindex (serv); /* load .index */
368   if (option (OPTNEWSCACHE) && serv->cache && nntp_get_cache_all (serv) >= 0)
369     nntp_check_newgroups (serv, 1);
370   else if (nntp_get_active (serv) < 0) {
371     hash_delete(&serv->newsgroups, NULL);
372     nntp_data_list_wipe(&serv->list);
373     p_delete(&serv->newsrc);
374     p_delete(&serv->cache);
375     p_delete(&serv);
376     return NULL;
377   }
378   nntp_clear_cacheindex (serv);
379   conn->data = (void *) serv;
380
381   return serv;
382 }
383
384 /* 
385  * full status flags are not supported by nntp, but we can fake some
386  * of them.  This is how:
387  * Read = a read message number is in the .newsrc
388  * New = a message is new since we last read this newsgroup
389  * Old = anything else
390  * So, Read is marked as such in the newsrc, old is anything that is 
391  * "skipped" in the newsrc, and new is anything not in the newsrc nor
392  * in the cache. By skipped, I mean before the last unread message
393  */
394 static void nntp_get_status(CONTEXT *ctx, HEADER *h, char *group, int article)
395 {
396   nntp_data_t *data = (nntp_data_t *) ctx->data;
397   int x;
398
399   if (group)
400     data = (nntp_data_t *) hash_find (data->nserv->newsgroups, group);
401
402   if (!data) {
403     return;
404   }
405
406   for (x = 0; x < data->num; x++) {
407     if ((article >= data->entries[x].first) &&
408         (article <= data->entries[x].last)) {
409       /* we cannot use mutt_set_flag() because mx_update_context()
410          didn't called yet */
411       h->read = 1;
412       return;
413     }
414   }
415   /* If article was not cached yet, it is new! :) */
416   if (!data->cache || article > data->lastCached)
417     return;
418   /* Old articles are articles which aren't read but an article after them
419    * has been cached */
420   if (option (OPTMARKOLD))
421     h->old = 1;
422 }
423
424 static void mutt_newsgroup_stat (nntp_data_t * data)
425 {
426   int i, first, last;
427
428   data->unread = 0;
429   if (data->lastMessage == 0 || data->firstMessage > data->lastMessage)
430     return;
431
432   data->unread = data->lastMessage - data->firstMessage + 1;
433   for (i = 0; i < data->num; i++) {
434     first = data->entries[i].first;
435     if (first < data->firstMessage)
436       first = data->firstMessage;
437     last = data->entries[i].last;
438     if (last > data->lastMessage)
439       last = data->lastMessage;
440     if (first <= last)
441       data->unread -= last - first + 1;
442   }
443 }
444
445 static int puti (char *line, int num)
446 {
447   char *p, s[32];
448
449   for (p = s; num;) {
450     *p++ = '0' + num % 10;
451     num /= 10;
452   }
453   while (p > s)
454     *line++ = *--p, num++;
455   *line = '\0';
456   return num;
457 }
458
459 static void nntp_create_newsrc_line (nntp_data_t * data, char **buf,
460                                      char **pline, ssize_t * buflen)
461 {
462   char *line = *pline;
463   ssize_t len = *buflen - (*pline - *buf);
464   int x, i;
465
466   if (len < LONG_STRING * 10) {
467     len += *buflen;
468     *buflen *= 2;
469     line = *buf;
470     p_realloc(buf, *buflen);
471     line = *buf + (*pline - line);
472   }
473   strcpy (line, data->group);
474   len -= m_strlen(line) + 1;
475   line += m_strlen(line);
476   *line++ = data->subscribed ? ':' : '!';
477   *line++ = ' ';
478   *line = '\0';
479
480   for (x = 0; x < data->num; x++) {
481     if (len < LONG_STRING) {
482       len += *buflen;
483       *buflen *= 2;
484       *pline = line;
485       line = *buf;
486       p_realloc(buf, *buflen);
487       line = *buf + (*pline - line);
488     }
489     if (x) {
490       *line++ = ',';
491       len--;
492     }
493
494     i = puti (line, data->entries[x].first);
495     line += i;
496     len -= i;
497     if (data->entries[x].first != data->entries[x].last) {
498       *line++ = '-';
499       len--;
500       i = puti (line, data->entries[x].last);
501       line += i;
502       len -= i;
503     }
504   }
505   *line++ = '\n';
506   *line = '\0';
507   *pline = line;
508 }
509
510 static void newsrc_gen_entries (CONTEXT * ctx)
511 {
512   nntp_data_t *data = (nntp_data_t *) ctx->data;
513   int series, x;
514   int last = 0, first = 1;
515   int save_sort = SORT_ORDER;
516
517   if (Sort != SORT_ORDER) {
518     save_sort = Sort;
519     Sort = SORT_ORDER;
520     mutt_sort_headers (ctx, 0);
521   }
522
523   if (!data->max) {
524     data->entries = p_new(NEWSRC_ENTRY, 5);
525     data->max = 5;
526   }
527
528   /*
529    * Set up to fake initial sequence from 1 to the article before the 
530    * first article in our list
531    */
532   data->num = 0;
533   series = 1;
534
535   for (x = 0; x < ctx->msgcount; x++) {
536     if (series) {               /* search for first unread */
537       /*
538        * We don't actually check sequential order, since we mark 
539        * "missing" entries as read/deleted
540        */
541       last = ctx->hdrs[x]->article_num;
542       if (last >= data->firstMessage && !ctx->hdrs[x]->deleted &&
543           !ctx->hdrs[x]->read) {
544         if (data->num >= data->max) {
545           data->max = data->max * 2;
546           p_realloc(&data->entries, data->max);
547         }
548         data->entries[data->num].first = first;
549         data->entries[data->num].last = last - 1;
550         data->num++;
551         series = 0;
552       }
553     }
554     else {                      /* search for first read */
555
556       if (ctx->hdrs[x]->deleted || ctx->hdrs[x]->read) {
557         first = last + 1;
558         series = 1;
559       }
560       last = ctx->hdrs[x]->article_num;
561     }
562   }
563   if (series && first <= data->lastLoaded) {
564     if (data->num >= data->max) {
565       data->max = data->max * 2;
566       p_realloc(&data->entries, data->max);
567     }
568     data->entries[data->num].first = first;
569     data->entries[data->num].last = data->lastLoaded;
570     data->num++;
571   }
572
573   if (save_sort != Sort) {
574     Sort = save_sort;
575     mutt_sort_headers (ctx, 0);
576   }
577 }
578
579 static int mutt_update_list_file (char *filename, char *section,
580                                   const char *key, char *line) {
581   FILE *ifp;
582   FILE *ofp;
583   char buf[HUGE_STRING];
584   char tmpf[_POSIX_PATH_MAX], lnk[_POSIX_PATH_MAX];
585   char *c;
586   int ext = 0, done = 0, r = 0, l = 0;
587
588   /* if file not exist, create it */
589   if ((ifp = safe_fopen (filename, "a")))
590     m_fclose(&ifp);
591   if (!(ifp = safe_fopen (filename, "r"))) {
592     mutt_error (_("Unable to open %s for reading"), filename);
593     return -1;
594   }
595   if (mx_lock_file (filename, fileno (ifp), 0, 0, 1)) {
596     m_fclose(&ifp);
597     mutt_error (_("Unable to lock %s"), filename);
598     return -1;
599   }
600
601   /* use m_tempfile() to get a tempfile in the same
602    * directory as filename is so that we can follow symlinks
603    * via rename(2); as dirname(2) may modify its argument,
604    * temporarily use buf as copy of it
605    */
606   m_strcpy(buf, sizeof(buf), filename);
607   ofp = m_tempfile(tmpf, sizeof(tmpf), dirname(buf), filename);
608   if (!ofp) {
609     m_fclose(&ifp);
610     mutt_error (_("Unable to open %s for writing"), tmpf);
611     return -1;
612   }
613
614   if (section) {
615     while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
616       r = fputs (buf, ofp);
617       c = buf;
618       while (*c && *c != '\n') c++;
619       c[0] = 0; /* strip EOL */
620       if (!strncmp (buf, "#: ", 3) && !m_strcasecmp(buf+3, section))
621         done++;
622     }
623     if (r != EOF && !done) {
624       snprintf (buf, sizeof(buf), "#: %s\n", section);
625       r = fputs (buf, ofp);
626     }
627     done = 0;
628   }
629
630   while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
631     if (ext) {
632       c = buf;
633       while (*c && (*c != '\r') && (*c != '\n')) c++;
634       c--;
635       if (*c != '\\') ext = 0;
636     } else if ((section && !strncmp (buf, "#: ", 3))) {
637       if (!done && line) {
638         fputs (line, ofp);
639         fputc ('\n', ofp);
640       }
641       r = fputs (buf, ofp);
642       done++;
643       break;
644     } else if (key && !strncmp (buf, key, strlen(key)) &&
645                (!*key || buf[strlen(key)] == ' ')) {
646       c = buf;
647       ext = 0;
648       while (*c && (*c != '\r') && (*c != '\n')) c++;
649       c--;
650       if (*c == '\\') ext = 1;
651       if (!done && line) {
652         r = fputs (line, ofp);
653         if (*key)
654           r = fputc ('\n', ofp);
655         done++;
656       }
657     } else {
658       r = fputs (buf, ofp);
659     }
660   }
661
662   while (r != EOF && fgets (buf, sizeof (buf), ifp))
663     r = fputs (buf, ofp);
664
665   /* If there wasn't a line to replace, put it on the end of the file */
666   if (r != EOF && !done && line) {
667     fputs (line, ofp);
668     r = fputc ('\n', ofp);
669   }
670   mx_unlock_file (filename, fileno (ifp), 0);
671   m_fclose(&ofp);
672   m_fclose(&ifp);
673   if (r == EOF) {
674     unlink (tmpf);
675     mutt_error (_("Can't write %s"), tmpf);
676     return -1;
677   }
678   lnk[0] = '\0';
679   if ((l = readlink (filename, lnk, sizeof(lnk)-1)) > 0)
680     lnk[l] = '\0';
681   if (rename (tmpf, l > 0 ? lnk : filename) < 0) {
682     unlink (tmpf);
683     mutt_error (_("Can't rename %s to %s"), tmpf, l > 0 ? lnk : filename);
684     return -1;
685   }
686   return 0;
687 }
688
689 int mutt_newsrc_update (NNTP_SERVER * news)
690 {
691   char *buf, *line;
692   nntp_data_t *data;
693   int r = -1;
694   ssize_t len, llen;
695
696   if (!news)
697     return -1;
698   llen = len = 10 * LONG_STRING;
699   line = buf = p_new(char, len);
700   /* we will generate full newsrc here */
701   for (data = news->list; data; data = data->next) {
702     if (!data || !data->rc)
703       continue;
704     nntp_create_newsrc_line (data, &buf, &line, &llen);
705     line += m_strlen(line);
706   }
707   /* newrc being fully rewritten */
708   if (news->newsrc &&
709       (r = mutt_update_list_file(news->newsrc, NULL, "", buf)) == 0) {
710     struct stat st;
711
712     stat (news->newsrc, &st);
713     news->size = st.st_size;
714     news->mtime = st.st_mtime;
715   }
716   p_delete(&buf);
717   return r;
718 }
719
720 static FILE *mutt_mkname (char *s)
721 {
722   char buf[_POSIX_PATH_MAX], *pc;
723   int fd;
724   FILE *fp;
725
726   nntp_cache_expand (buf, s);
727   if ((fp = safe_fopen (buf, "w")))
728     return fp;
729
730   nntp_cache_expand (buf, "cache-XXXXXX");
731   pc = buf + m_strlen(buf) - 12; /* positioning to "cache-XXXXXX" */
732   if ((fd = mkstemp (buf)) == -1)
733     return NULL;
734   strcpy (s, pc);               /* generated name */
735   return fdopen (fd, "w");
736 }
737
738 /* Updates info into .index file: ALL or about selected newsgroup */
739 static int nntp_update_cacheindex (NNTP_SERVER * serv, nntp_data_t * data)
740 {
741   char buf[LONG_STRING];
742   char file[_POSIX_PATH_MAX];
743   const char *key = "ALL";
744
745   if (!serv || !serv->conn || !serv->conn->account.host)
746     return -1;
747
748   if (data && data->group) {
749     key = data->group;
750     snprintf (buf, sizeof (buf), "%s %s %d %d", key, data->cache,
751               data->firstMessage, data->lastLoaded);
752   }
753   else {
754     m_strcpy(file, sizeof(file), serv->cache);
755     snprintf (buf, sizeof (buf), "ALL %s 0 %d", file,
756               (int) serv->newgroups_time);
757   }
758   nntp_cache_expand (file, ".index");
759   return mutt_update_list_file (file, serv->conn->account.host, key, buf);
760 }
761
762 /* Remove cache files of unsubscribed newsgroups */
763 void nntp_clear_cacheindex (NNTP_SERVER * news)
764 {
765   nntp_data_t *data;
766
767   if (option (OPTSAVEUNSUB) || !news)
768     return;
769
770   for (data = news->list; data; data = data->next) {
771     if (!data || data->subscribed || !data->cache)
772       continue;
773     nntp_delete_cache (data);
774   }
775   return;
776 }
777
778 static int nntp_save_cache_index (NNTP_SERVER * news)
779 {
780   char buf[HUGE_STRING];
781   char file[_POSIX_PATH_MAX];
782   nntp_data_t *d;
783   FILE *f;
784
785   if (!news || !news->newsgroups)
786     return -1;
787   if (!option (OPTNEWSCACHE))
788     return 0;
789
790   if (news->cache) {
791     nntp_cache_expand (file, news->cache);
792     unlink (file);
793     f = safe_fopen (file, "w");
794   }
795   else {
796     m_strcpy(buf, sizeof(buf), news->conn->account.host);
797     f = mutt_mkname (buf);
798     news->cache = m_strdup(buf);
799     nntp_cache_expand (file, buf);
800   }
801   if (!f)
802     return -1;
803
804   for (d = news->list; d; d = d->next) {
805     if (!d->deleted) {
806       if (d->desc)
807         snprintf (buf, sizeof (buf), "%s %d %d %c %s\n", d->group,
808                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n',
809                   d->desc);
810       else
811         snprintf (buf, sizeof (buf), "%s %d %d %c\n", d->group,
812                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n');
813       if (fputs (buf, f) == EOF) {
814         m_fclose(&f);
815         unlink (file);
816         return -1;
817       }
818     }
819   }
820   m_fclose(&f);
821
822   if (nntp_update_cacheindex (news, NULL)) {
823     unlink (file);
824     return -1;
825   }
826   return 0;
827 }
828
829 static int nntp_save_cache_group (CONTEXT * ctx)
830 {
831   char buf[HUGE_STRING], addr[STRING];
832   char file[_POSIX_PATH_MAX];
833   FILE *f;
834   HEADER *h;
835   struct tm *tm;
836   int i = 0, save = SORT_ORDER;
837   int prev = 0;
838
839   if (!option (OPTNEWSCACHE))
840     return 0;
841   if (!ctx || !ctx->data || ctx->magic != M_NNTP)
842     return -1;
843
844   if (((nntp_data_t *) ctx->data)->cache) {
845     nntp_cache_expand (file, ((nntp_data_t *) ctx->data)->cache);
846     unlink (file);
847     f = safe_fopen (file, "w");
848   }
849   else {
850     snprintf (buf, sizeof (buf), "%s-%s",
851               ((nntp_data_t *) ctx->data)->nserv->conn->account.host,
852               ((nntp_data_t *) ctx->data)->group);
853     f = mutt_mkname (buf);
854     ((nntp_data_t *) ctx->data)->cache = m_strdup(buf);
855     nntp_cache_expand (file, buf);
856   }
857   if (!f)
858     return -1;
859
860   if (Sort != SORT_ORDER) {
861     save = Sort;
862     Sort = SORT_ORDER;
863     mutt_sort_headers (ctx, 0);
864   }
865
866   /* Save only $nntp_context messages... */
867   ((nntp_data_t *) ctx->data)->lastCached = 0;
868   if (NntpContext && ctx->msgcount > NntpContext)
869     i = ctx->msgcount - NntpContext;
870   for (; i < ctx->msgcount; i++) {
871     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->article_num != prev) {
872       h = ctx->hdrs[i];
873       addr[0] = 0;
874       rfc822_addrcat(addr, sizeof(addr), h->env->from, 0);
875       tm = gmtime (&h->date_sent);
876       snprintf (buf, sizeof (buf),
877                 "%d\t%s\t%s\t%d %s %d %02d:%02d:%02d GMT\t%s\t",
878                 h->article_num, h->env->subject, addr, tm->tm_mday,
879                 Months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour,
880                 tm->tm_min, tm->tm_sec, h->env->message_id);
881       fputs (buf, f);
882       if (h->env->references)
883         mutt_write_references (h->env->references, f);
884       snprintf (buf, sizeof (buf), "\t%zd\t%d\tXref: %s\n",
885                 h->content->length, h->lines, NONULL (h->env->xref));
886       if (fputs (buf, f) == EOF) {
887         m_fclose(&f);
888         unlink (file);
889         return -1;
890       }
891     }
892     prev = ctx->hdrs[i]->article_num;
893   }
894
895   if (save != Sort) {
896     Sort = save;
897     mutt_sort_headers (ctx, 0);
898   }
899   m_fclose(&f);
900
901   if (nntp_update_cacheindex (((nntp_data_t *) ctx->data)->nserv,
902                               (nntp_data_t *) ctx->data)) {
903     unlink (file);
904     return -1;
905   }
906   ((nntp_data_t *) ctx->data)->lastCached =
907     ((nntp_data_t *) ctx->data)->lastLoaded;
908   return 0;
909 }
910
911 static void nntp_delete_cache (nntp_data_t * data)
912 {
913   char buf[_POSIX_PATH_MAX];
914
915   if (!option (OPTNEWSCACHE) || !data || !data->cache || !data->nserv)
916     return;
917
918   nntp_cache_expand (buf, data->cache);
919   unlink (buf);
920   p_delete(&data->cache);
921   data->lastCached = 0;
922   nntp_cache_expand (buf, ".index");
923   mutt_update_list_file (buf, data->nserv->conn->account.host, data->group,
924                          NULL);
925 }
926
927 nntp_data_t *mutt_newsgroup_subscribe (NNTP_SERVER * news, char *group)
928 {
929   nntp_data_t *data;
930
931   if (!news || !news->newsgroups || !group || !*group)
932     return NULL;
933   if (!(data = (nntp_data_t *) hash_find (news->newsgroups, group))) {
934     data = nntp_data_new();
935     data->group = m_strdup(group);
936     data->nserv = news;
937     data->deleted = 1;
938     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
939         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
940     hash_insert (news->newsgroups, data->group, data);
941     nntp_data_list_append(&news->list, data);
942   }
943   if (!data->subscribed) {
944     data->subscribed = 1;
945     data->rc = 1;
946   }
947   return data;
948 }
949
950 nntp_data_t *mutt_newsgroup_unsubscribe (NNTP_SERVER * news, char *group)
951 {
952   nntp_data_t *data;
953
954   if (!news || !news->newsgroups || !group || !*group ||
955       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
956     return NULL;
957   if (data->subscribed) {
958     data->subscribed = 0;
959     if (!option (OPTSAVEUNSUB))
960       data->rc = 0;
961   }
962   return data;
963 }
964
965 nntp_data_t *mutt_newsgroup_catchup (NNTP_SERVER * news, char *group)
966 {
967   nntp_data_t *data;
968
969   if (!news || !news->newsgroups || !group || !*group ||
970       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
971     return NULL;
972   if (!data->max) {
973     data->entries = p_new(NEWSRC_ENTRY, 5);
974     data->max = 5;
975   }
976   data->num = 1;
977   data->entries[0].first = 1;
978   data->unread = 0;
979   data->entries[0].last = data->lastMessage;
980   if (Context && Context->data == data) {
981     int x;
982
983     for (x = 0; x < Context->msgcount; x++)
984       mutt_set_flag (Context, Context->hdrs[x], M_READ, 1);
985   }
986   return data;
987 }
988
989 nntp_data_t *mutt_newsgroup_uncatchup (NNTP_SERVER * news, char *group)
990 {
991   nntp_data_t *data;
992
993   if (!news || !news->newsgroups || !group || !*group ||
994       !(data = (nntp_data_t *) hash_find (news->newsgroups, group)))
995     return NULL;
996   if (!data->max) {
997     data->entries = p_new(NEWSRC_ENTRY, 5);
998     data->max = 5;
999   }
1000   data->num = 1;
1001   data->entries[0].first = 1;
1002   data->entries[0].last = data->firstMessage - 1;
1003   if (Context && Context->data == data) {
1004     int x;
1005
1006     data->unread = Context->msgcount;
1007     for (x = 0; x < Context->msgcount; x++)
1008       mutt_set_flag (Context, Context->hdrs[x], M_READ, 0);
1009   }
1010   else
1011     data->unread = data->lastMessage - data->entries[0].last;
1012   return data;
1013 }
1014
1015 /* this routine gives the first newsgroup with new messages */
1016 void nntp_buffy (char* dst, ssize_t dstlen) {
1017   nntp_data_t *list;
1018   int count = 0;
1019
1020   /* forward to current group */
1021   for (list = CurrentNewsSrv->list; list; list = list->next) {
1022     if (list->subscribed && list->unread
1023     &&  Context && Context->magic == M_NNTP
1024     &&  m_strcmp(list->group, ((nntp_data_t *)Context->data)->group) == 0)
1025     {
1026       list = list->next;
1027       break;
1028     }
1029   }
1030
1031   *dst = '\0';
1032
1033   while (count < 2) {
1034
1035     if (!list)
1036       list = CurrentNewsSrv->list;
1037
1038     for (; list; list = list->next) {
1039       if (list->subscribed && list->unread) {
1040         if (Context && Context->magic == M_NNTP &&
1041             !m_strcmp(list->group, ((nntp_data_t *)Context->data)->group)) {
1042           int i, unread = 0;
1043
1044           for (i = 0; i < Context->msgcount; i++)
1045             if (!Context->hdrs[i]->read && !Context->hdrs[i]->deleted)
1046               unread++;
1047           if (!unread)
1048             continue;
1049         }
1050         m_strcpy(dst, dstlen, list->group);
1051         break;
1052       }
1053     }
1054     /* done if found */
1055     if (dst && *dst)
1056       return;
1057     count++;
1058   }
1059   *dst = '\0';
1060 }
1061
1062 /* }}} */
1063 /* nntp protocol {{{ */
1064
1065 static unsigned int _checked = 0;
1066
1067 void nntp_sync_sidebar (nntp_data_t* data) {
1068   int i = 0;
1069   BUFFY* tmp = NULL;
1070   char buf[STRING];
1071
1072   if (!Incoming.len)
1073     return;
1074
1075   snprintf(buf, sizeof (buf), "nntp%s://%s%s%s%s/%s",
1076            data->nserv->conn->account.has_ssl ? "s" : "",
1077            NONULL(data->nserv->conn->account.user),
1078            *data->nserv->conn->account.pass ? ":" : "",
1079            *data->nserv->conn->account.pass ? data->nserv->conn->account.pass : "",
1080            data->nserv->conn->account.host,
1081            data->group);
1082
1083   /* bail out if group not found via mailboxes */
1084   if ((i = buffy_lookup (buf)) < 0)
1085     return;
1086
1087   tmp = Incoming.arr[i];
1088   /* copied from browser.c */
1089   if (option (OPTMARKOLD) &&
1090       data->lastCached >= data->firstMessage &&
1091       data->lastCached <= data->lastMessage)
1092     tmp->msg_unread = data->lastMessage - data->lastCached;
1093   else
1094     tmp->msg_unread = data->unread;
1095   tmp->new = data->unread > 0;
1096   /* this is closest to a "total" count we can get */
1097   tmp->msgcount = data->lastMessage - data->firstMessage;
1098 }
1099
1100 static int nntp_auth (NNTP_SERVER * serv)
1101 {
1102   CONNECTION *conn = serv->conn;
1103   char buf[STRING];
1104   unsigned char flags = conn->account.flags;
1105
1106   if (mutt_account_getuser(&conn->account) || !conn->account.user[0] ||
1107       mutt_account_getpass(&conn->account) || !conn->account.pass[0]) {
1108     conn->account.flags = flags;
1109     return -2;
1110   }
1111
1112   mutt_message _("Logging in...");
1113
1114   snprintf (buf, sizeof (buf), "AUTHINFO USER %s\r\n", conn->account.user);
1115   mutt_socket_write (conn, buf);
1116   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
1117     conn->account.flags = flags;
1118     return -1;
1119   }
1120
1121   snprintf (buf, sizeof (buf), "AUTHINFO PASS %s\r\n", conn->account.pass);
1122   mutt_socket_write(conn, buf);
1123   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0) {
1124     conn->account.flags = flags;
1125     return -1;
1126   }
1127
1128   if (m_strncmp("281", buf, 3)) {
1129     conn->account.flags = flags;
1130     mutt_error _("Login failed.");
1131
1132     sleep (2);
1133     return -3;
1134   }
1135
1136   return 0;
1137 }
1138
1139 static int nntp_connect_error (NNTP_SERVER * serv)
1140 {
1141   serv->status = NNTP_NONE;
1142   mutt_socket_close (serv->conn);
1143   mutt_error _("Server closed connection!");
1144
1145   sleep (2);
1146   return -1;
1147 }
1148
1149 static int nntp_connect_and_auth (NNTP_SERVER * serv)
1150 {
1151   CONNECTION *conn = serv->conn;
1152   char buf[STRING];
1153   int rc;
1154
1155   serv->status = NNTP_NONE;
1156
1157   if (mutt_socket_open (conn) < 0)
1158     return -1;
1159
1160   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1161     return nntp_connect_error (serv);
1162
1163   if (!m_strncmp("200", buf, 3))
1164     mutt_message (_("Connected to %s. Posting ok."), conn->account.host);
1165   else if (!m_strncmp("201", buf, 3))
1166     mutt_message (_("Connected to %s. Posting NOT ok."), conn->account.host);
1167   else {
1168     mutt_socket_close(conn);
1169     m_strrtrim(buf);
1170     mutt_error("%s", buf);
1171     sleep (2);
1172     return -1;
1173   }
1174
1175   /* Tell INN to switch to mode reader if it isn't so. Ignore all
1176      returned codes and messages. */
1177   mutt_socket_write (conn, "MODE READER\r\n");
1178   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1179     return nntp_connect_error (serv);
1180
1181   mutt_socket_write (conn, "STAT\r\n");
1182   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1183     return nntp_connect_error (serv);
1184
1185   if (!conn->account.has_user && m_strncmp("480", buf, 3)) {
1186     serv->status = NNTP_OK;
1187     return 0;
1188   }
1189
1190   rc = nntp_auth (serv);
1191   if (rc == -1)
1192     return nntp_connect_error (serv);
1193   if (rc == -2) {
1194     mutt_socket_close (conn);
1195     serv->status = NNTP_BYE;
1196     return -1;
1197   }
1198   if (rc < 0) {
1199     mutt_socket_close (conn);
1200     mutt_error _("Login failed.");
1201
1202     sleep (2);
1203     return -1;
1204   }
1205   serv->status = NNTP_OK;
1206   return 0;
1207 }
1208
1209 static int nntp_attempt_features (NNTP_SERVER * serv)
1210 {
1211   char buf[LONG_STRING];
1212   CONNECTION *conn = serv->conn;
1213
1214   if (serv->feat_known)
1215       return 0;
1216
1217   mutt_socket_write (conn, "XOVER\r\n");
1218   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1219     return nntp_connect_error (serv);
1220   if (m_strncmp("500", buf, 3))
1221     serv->hasXOVER = 1;
1222
1223   mutt_socket_write (conn, "XPAT\r\n");
1224   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1225     return nntp_connect_error (serv);
1226   if (m_strncmp("500", buf, 3))
1227     serv->hasXPAT = 1;
1228
1229   mutt_socket_write (conn, "LISTGROUP\r\n");
1230   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1231     return (nntp_connect_error (serv));
1232   if (m_strncmp("500", buf, 3))
1233     serv->hasLISTGROUP = 1;
1234
1235   mutt_socket_write (conn, "XGTITLE +\r\n");
1236   if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1237     return nntp_connect_error (serv);
1238   if (m_strncmp("500", buf, 3))
1239     serv->hasXGTITLE = 1;
1240
1241   if (!m_strncmp("282", buf, 3)) {
1242     do {
1243       if (mutt_socket_readln (buf, sizeof (buf), conn) < 0)
1244         return nntp_connect_error (serv);
1245     } while (!(buf[0] == '.' && buf[1] == '\0'));
1246   }
1247
1248   serv->feat_known = 1;
1249   return 0;
1250 }
1251
1252 static int nntp_open_connection (NNTP_SERVER * serv)
1253 {
1254   if (serv->status == NNTP_OK)
1255     return 0;
1256   if (serv->status == NNTP_BYE)
1257     return -1;
1258   if (nntp_connect_and_auth (serv) < 0)
1259     return -1;
1260   if (nntp_attempt_features (serv) < 0)
1261     return -1;
1262   return 0;
1263 }
1264
1265 static int nntp_reconnect (NNTP_SERVER * serv)
1266 {
1267   char buf[STRING];
1268
1269   mutt_socket_close (serv->conn);
1270
1271   for (;;) {
1272     if (nntp_connect_and_auth (serv) == 0)
1273       return 0;
1274
1275     snprintf (buf, sizeof (buf), _("Connection to %s lost. Reconnect?"),
1276               serv->conn->account.host);
1277     if (query_quadoption (OPT_NNTPRECONNECT, buf) != M_YES) {
1278       serv->status = NNTP_BYE;
1279       return -1;
1280     }
1281   }
1282 }
1283
1284 /* Send data from line[LONG_STRING] and receive answer to same line */
1285 static int mutt_nntp_query (nntp_data_t * data, char *line, size_t linelen)
1286 {
1287   char buf[LONG_STRING];
1288   int done = TRUE;
1289
1290   if (data->nserv->status == NNTP_BYE)
1291     return -1;
1292
1293   do {
1294     if (*line) {
1295       mutt_socket_write (data->nserv->conn, line);
1296     }
1297     else if (data->group) {
1298       snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
1299       mutt_socket_write (data->nserv->conn, buf);
1300     }
1301
1302     done = TRUE;
1303     if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0) {
1304       if (nntp_reconnect (data->nserv) < 0)
1305         return -1;
1306
1307       if (data->group) {
1308         snprintf (buf, sizeof (buf), "GROUP %s\r\n", data->group);
1309         mutt_socket_write (data->nserv->conn, buf);
1310         if (mutt_socket_readln (buf, sizeof (buf), data->nserv->conn) < 0)
1311           return -1;
1312       }
1313       if (*line)
1314         done = FALSE;
1315     }
1316     else if ((!m_strncmp("480", buf, 3)) && nntp_auth (data->nserv) < 0)
1317       return -1;
1318   } while (!done);
1319
1320   m_strcpy(line, linelen, buf);
1321   return 0;
1322 }
1323
1324 /*
1325  * This function calls  funct(*line, *data)  for each received line,
1326  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
1327  * Returned codes:
1328  *  0 - successful,
1329  *  1 - correct but not performed (may be, have to be continued),
1330  * -1 - conection lost,
1331  * -2 - invalid command or execution error,
1332  * -3 - error in funct(*line, *data).
1333  */
1334 static int mutt_nntp_fetch (nntp_data_t * nntp_data, const char *query,
1335                             const char *msg, progress_t* bar,
1336                             int (*funct) (char *, void *),
1337                             void *data, int tagged)
1338 {
1339   char buf[LONG_STRING];
1340   char *inbuf, *p;
1341   int done = FALSE;
1342   int chunk, line;
1343   long pos = 0;
1344   size_t lenbuf = 0;
1345   int ret;
1346
1347   do {
1348     m_strcpy(buf, sizeof(buf), query);
1349     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0)
1350       return -1;
1351     if (buf[0] == '5')
1352       return -2;
1353     if (buf[0] != '2')
1354       return 1;
1355
1356     ret = 0;
1357     line = 0;
1358     inbuf = p_new(char, sizeof(buf));
1359
1360     for (;;) {
1361       chunk = mutt_socket_readln(buf, sizeof (buf), nntp_data->nserv->conn);
1362       if (chunk < 0)
1363         break;
1364
1365       p = buf;
1366       if (!lenbuf && buf[0] == '.') {
1367         if (buf[1] == '\0') {
1368           done = TRUE;
1369           break;
1370         }
1371         if (buf[1] == '.')
1372           p++;
1373       }
1374
1375       m_strcpy(inbuf + lenbuf, sizeof(buf), p);
1376       pos += chunk;
1377
1378       if (chunk >= ssizeof (buf)) {
1379         lenbuf += m_strlen(p);
1380       }
1381       else {
1382         if (bar) {
1383           mutt_progress_bar (bar, pos);
1384         } else if (msg) {
1385           line++;
1386           if (ReadInc && (line % ReadInc == 0)) {
1387             if (tagged)
1388               mutt_message (_("%s (tagged: %d) %d"), msg, tagged, line);
1389             else
1390               mutt_message ("%s %d", msg, line);
1391           }
1392         }
1393
1394         if (ret == 0 && funct (inbuf, data) < 0)
1395           ret = -3;
1396         lenbuf = 0;
1397       }
1398
1399       p_realloc(&inbuf, lenbuf + sizeof (buf));
1400     }
1401     p_delete(&inbuf);
1402     funct (NULL, data);
1403   }
1404   while (!done);
1405   return ret;
1406 }
1407
1408 static int nntp_read_tempfile (char *line, void *file)
1409 {
1410   FILE *f = (FILE *) file;
1411
1412   if (!line)
1413     rewind (f);
1414   else {
1415     fputs (line, f);
1416     if (fputc ('\n', f) == EOF)
1417       return -1;
1418   }
1419   return 0;
1420 }
1421
1422 static void nntp_parse_xref (CONTEXT * ctx, char *group, char *xref,
1423                              HEADER * h)
1424 {
1425   register char *p, *b;
1426   register char *colon = NULL;
1427
1428   b = p = xref;
1429   while (*p) {
1430     /* skip to next word */
1431     b = p;
1432     while (*b && ((*b == ' ') || (*b == '\t')))
1433       b++;
1434     p = b;
1435     colon = NULL;
1436     /* skip to end of word */
1437     while (*p && (*p != ' ') && (*p != '\t')) {
1438       if (*p == ':')
1439         colon = p;
1440       p++;
1441     }
1442     if (*p) {
1443       *p = '\0';
1444       p++;
1445     }
1446     if (colon) {
1447       *colon = '\0';
1448       colon++;
1449       nntp_get_status (ctx, h, b, atoi (colon));
1450       if (h && h->article_num == 0 && m_strcmp(group, b) == 0)
1451         h->article_num = atoi (colon);
1452     }
1453   }
1454 }
1455
1456 /*
1457  * returns:
1458  *  0 on success
1459  *  1 if article not found
1460  * -1 if read or write error on tempfile or socket
1461  */
1462 static int nntp_read_header (CONTEXT * ctx, const char *msgid,
1463                              int article_num)
1464 {
1465   nntp_data_t *nntp_data = ((nntp_data_t *) ctx->data);
1466   FILE *f;
1467   char buf[LONG_STRING];
1468   char tempfile[_POSIX_PATH_MAX];
1469   int ret;
1470   HEADER *h = ctx->hdrs[ctx->msgcount];
1471
1472   f = m_tempfile(tempfile, sizeof(tempfile), NONULL(mod_core.tmpdir), NULL);
1473   if (!f)
1474     return -1;
1475
1476   if (!msgid)
1477     snprintf (buf, sizeof (buf), "HEAD %d\r\n", article_num);
1478   else
1479     snprintf (buf, sizeof (buf), "HEAD %s\r\n", msgid);
1480
1481   ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, nntp_read_tempfile, f, 0);
1482   if (ret) {
1483     m_fclose(&f);
1484     unlink (tempfile);
1485     return (ret == -1 ? -1 : 1);
1486   }
1487
1488   h->article_num = article_num;
1489   h->env = mutt_read_rfc822_header (f, h, 0, 0);
1490   m_fclose(&f);
1491   unlink (tempfile);
1492
1493   if (h->env->xref != NULL)
1494     nntp_parse_xref (ctx, nntp_data->group, h->env->xref, h);
1495   else if (h->article_num == 0 && msgid) {
1496     snprintf (buf, sizeof (buf), "STAT %s\r\n", msgid);
1497     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) == 0)
1498       h->article_num = atoi (buf + 4);
1499   }
1500
1501   return 0;
1502 }
1503
1504 static int parse_description (char *line, void *n)
1505 {
1506   register char *d = line;
1507   nntp_data_t *data;
1508   NNTP_SERVER *news = n;
1509
1510   if (!line)
1511     return 0;
1512   while (*d && *d != '\t' && *d != ' ')
1513     d++;
1514   *d = 0;
1515   d++;
1516   while (*d && (*d == '\t' || *d == ' '))
1517     d++;
1518   if ((data = (nntp_data_t *) hash_find (news->newsgroups, line)) != NULL &&
1519       m_strcmp(d, data->desc)) {
1520     p_delete(&data->desc);
1521     data->desc = m_strdup(d);
1522   }
1523   return 0;
1524 }
1525
1526 static void nntp_get_desc (nntp_data_t * data, const char *mask, char *msg, progress_t* bar)
1527 {
1528   char buf[STRING];
1529
1530   if (!option (OPTLOADDESC) || !data || !data->nserv)
1531     return;
1532
1533   /* Get newsgroup description, if we can */
1534   if (data->nserv->hasXGTITLE)
1535     snprintf (buf, sizeof (buf), "XGTITLE %s\r\n", mask);
1536   else
1537     snprintf (buf, sizeof (buf), "LIST NEWSGROUPS %s\r\n", mask);
1538   if (mutt_nntp_fetch (data, buf, msg, bar, parse_description, data->nserv, 0) !=
1539       0) {
1540   }
1541 }
1542
1543 /*
1544  * XOVER returns a tab separated list of:
1545  * id|subject|from|date|Msgid|references|bytes|lines|xref
1546  *
1547  * This has to duplicate some of the functionality of 
1548  * mutt_read_rfc822_header(), since it replaces the call to that (albeit with
1549  * a limited number of headers which are "parsed" by placement in the list)
1550  */
1551 static int nntp_parse_xover (CONTEXT * ctx, char *buf, HEADER * hdr)
1552 {
1553   nntp_data_t *nntp_data = (nntp_data_t *) ctx->data;
1554   char *p, *b;
1555   int x, done = 0;
1556
1557   hdr->env = envelope_new();
1558   hdr->env->newsgroups = m_strdup(nntp_data->group);
1559   hdr->content = body_new();
1560   hdr->content->type = TYPETEXT;
1561   hdr->content->subtype = m_strdup("plain");
1562   hdr->content->encoding = ENC7BIT;
1563   hdr->content->disposition = DISPINLINE;
1564   hdr->content->length = -1;
1565   b = p = buf;
1566
1567   for (x = 0; !done && x < 9; x++) {
1568     /* if from file, need to skip newline character */
1569     while (*p && *p != '\n' && *p != '\t')
1570       p++;
1571     if (!*p)
1572       done++;
1573     *p = '\0';
1574     p++;
1575     switch (x) {
1576     case 0:
1577
1578       hdr->article_num = atoi (b);
1579       nntp_get_status (ctx, hdr, NULL, hdr->article_num);
1580       break;
1581     case 1:
1582       hdr->env->subject = m_strdup(b);
1583       break;
1584     case 2:
1585       address_list_wipe(&hdr->env->from);
1586       hdr->env->from = rfc822_parse_adrlist (hdr->env->from, b);
1587       /* same as for mutt_parse_rfc822_line():
1588        * don't leave from info NULL if there's an invalid address (or
1589        * whatever) in From: field; mutt would just display it as empty
1590        * and mark mail/(esp.) news article as your own. aaargh! this
1591        * bothered me for _years_ */
1592       if (!hdr->env->from) {
1593         hdr->env->from = address_new ();
1594         hdr->env->from->personal = m_strdup(b);
1595       }
1596       break;
1597     case 3:
1598       hdr->date_sent = mutt_parse_date (b, hdr);
1599       hdr->received = hdr->date_sent;
1600       break;
1601     case 4:
1602       p_delete(&hdr->env->message_id);
1603       hdr->env->message_id = m_strdup(b);
1604       break;
1605     case 5:
1606       string_list_wipe(&hdr->env->references);
1607       hdr->env->references = mutt_parse_references (b, 0);
1608       break;
1609     case 6:
1610       hdr->content->length = atoi (b);
1611       break;
1612     case 7:
1613       hdr->lines = atoi (b);
1614       break;
1615     case 8:
1616       if (!hdr->read)
1617         p_delete(&hdr->env->xref);
1618       b = b + 6;                /* skips the "Xref: " */
1619       hdr->env->xref = m_strdup(b);
1620       nntp_parse_xref (ctx, nntp_data->group, b, hdr);
1621     }
1622     rfc2047_decode_envelope(hdr->env);
1623     if (!*p)
1624       return -1;
1625     b = p;
1626   }
1627   return 0;
1628 }
1629
1630 typedef struct {
1631   CONTEXT *ctx;
1632   int   first;
1633   int   last;
1634   bits_t messages;
1635   const char *msg;
1636 } FETCH_CONTEXT;
1637
1638 static int nntp_fetch_numbers (char *line, void *c)
1639 {
1640     FETCH_CONTEXT *fc = c;
1641
1642     if (line) {
1643         int num = atoi(line);
1644         if (num < fc->first || num > fc->last)
1645             return 0;
1646
1647         bit_set(&fc->messages, num);
1648     }
1649     return 0;
1650 }
1651
1652 static int add_xover_line (char *line, void *c)
1653 {
1654   int num, total;
1655   FETCH_CONTEXT *fc = c;
1656   CONTEXT *ctx = fc->ctx;
1657   nntp_data_t *data = (nntp_data_t *) ctx->data;
1658
1659   if (!line)
1660     return 0;
1661
1662   if (ctx->msgcount >= ctx->hdrmax)
1663     mx_alloc_memory (ctx);
1664   ctx->hdrs[ctx->msgcount] = header_new();
1665   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
1666
1667   nntp_parse_xover (ctx, line, ctx->hdrs[ctx->msgcount]);
1668   num = ctx->hdrs[ctx->msgcount]->article_num;
1669
1670   if (num >= fc->first && num <= fc->last) {
1671     ctx->msgcount++;
1672     if (num > data->lastLoaded)
1673       data->lastLoaded = num;
1674     num = num - fc->first + 1;
1675     total = fc->last - fc->first + 1;
1676     if (!ctx->quiet && fc->msg && ReadInc && (num % ReadInc == 0))
1677       mutt_message ("%s %d/%d", fc->msg, num, total);
1678   } else {
1679     header_delete(&ctx->hdrs[ctx->msgcount]);       /* skip it */
1680   }
1681
1682   return 0;
1683 }
1684
1685
1686 static int nntp_fetch_headers(CONTEXT * ctx, int first, int last)
1687 {
1688   char buf[HUGE_STRING];
1689   const char *msg = _("Fetching message headers...");
1690   const char *msg2 = _("Fetching headers from cache...");
1691   nntp_data_t *nntp_data = ((nntp_data_t *) ctx->data);
1692   int ret, num, oldmsgcount, current;
1693   FILE *f;
1694   FETCH_CONTEXT fc;
1695
1696   /* if empty group or nothing to do */
1697   if (!last || first > last)
1698     return 0;
1699
1700   /* fetch list of articles */
1701   mutt_message _("Fetching list of articles...");
1702
1703   fc.ctx   = ctx;
1704   fc.first = first;
1705   fc.last  = last;
1706
1707   /* CACHE: must be loaded xover cache here */
1708   num = nntp_data->lastCached - first + 1;
1709   if (option (OPTNEWSCACHE) && nntp_data->cache && num > 0) {
1710   nntp_cache_expand (buf, nntp_data->cache);
1711   mutt_message (msg2);
1712
1713   if ((f = safe_fopen (buf, "r"))) {
1714     int r = 0, c = 0;
1715
1716     /* counting number of lines */
1717     while (fgets (buf, sizeof (buf), f) != NULL)
1718       r++;
1719     rewind (f);
1720     while (r > num && fgets (buf, sizeof (buf), f) != NULL)
1721       r--;
1722     oldmsgcount = ctx->msgcount;
1723     fc.first = first;
1724     fc.last = first + num - 1;
1725     fc.msg = NULL;
1726     while (fgets (buf, sizeof (buf), f) != NULL) {
1727       if (ReadInc && ((++c) % ReadInc == 0))
1728         mutt_message ("%s %d/%d", msg2, c, r);
1729       add_xover_line (buf, &fc);
1730     }
1731     m_fclose(&f);
1732     nntp_data->lastLoaded = fc.last;
1733     first = fc.last + 1;
1734     if (ctx->msgcount > oldmsgcount)
1735       mx_update_context (ctx, ctx->msgcount - oldmsgcount);
1736   }
1737   else
1738     nntp_delete_cache (nntp_data);
1739   }
1740   num = last - first + 1;
1741   if (num <= 0) {
1742     return 0;
1743   }
1744
1745   /*
1746   * Without XOVER, we have to fetch each article header and parse
1747   * it.  With XOVER, we ask for all of them
1748   */
1749   mutt_message (msg);
1750   if (nntp_data->nserv->hasXOVER) {
1751     oldmsgcount = ctx->msgcount;
1752     fc.first = first;
1753     fc.last = last;
1754     fc.msg = msg;
1755     snprintf (buf, sizeof (buf), "XOVER %d-%d\r\n", first, last);
1756     ret = mutt_nntp_fetch (nntp_data, buf, NULL, NULL, add_xover_line, &fc, 0);
1757     if (ctx->msgcount > oldmsgcount)
1758       mx_update_context (ctx, ctx->msgcount - oldmsgcount);
1759     if (ret != 0) {
1760       mutt_error (_("XOVER command failed: %s"), buf);
1761       return -1;
1762     }
1763   } else {
1764     bits_init(&fc.messages);
1765
1766     if (nntp_data->nserv->hasLISTGROUP) {
1767       snprintf (buf, sizeof (buf), "LISTGROUP %s\r\n", nntp_data->group);
1768       if (mutt_nntp_fetch(nntp_data, buf, NULL, NULL,
1769                           nntp_fetch_numbers, &fc, 0))
1770       {
1771         mutt_error (_("LISTGROUP command failed: %s"), buf);
1772         sleep (2);
1773         bits_wipe(&fc.messages);
1774         return -1;
1775       }
1776     } else {
1777       for (num = first; num <= last; num++)
1778         bit_set(&fc.messages, num);
1779     }
1780
1781     for (current = first; current <= last; current++) {
1782       HEADER *h;
1783
1784       ret = current - first + 1;
1785       mutt_message ("%s %d/%d", msg, ret, num);
1786
1787       if (!bit_isset(&fc.messages, current))
1788         continue;
1789
1790       if (ctx->msgcount >= ctx->hdrmax)
1791         mx_alloc_memory (ctx);
1792       h = ctx->hdrs[ctx->msgcount] = header_new();
1793       h->index = ctx->msgcount;
1794
1795       ret = nntp_read_header (ctx, NULL, current);
1796       if (ret == 0) {           /* Got article. Fetch next header */
1797         nntp_get_status (ctx, h, NULL, h->article_num);
1798         ctx->msgcount++;
1799         mx_update_context (ctx, 1);
1800       }
1801       else
1802         header_delete(&h);  /* skip it */
1803       if (ret == -1) {
1804         bits_wipe(&fc.messages);
1805         return -1;
1806       }
1807
1808       if (current > nntp_data->lastLoaded)
1809         nntp_data->lastLoaded = current;
1810     }
1811     bits_wipe(&fc.messages);
1812   }
1813
1814   nntp_data->lastLoaded = last;
1815   mutt_clear_error ();
1816   return 0;
1817 }
1818
1819 /*
1820  * currently, nntp "mailbox" is "newsgroup"
1821  */
1822 static int nntp_open_mailbox (CONTEXT * ctx)
1823 {
1824   nntp_data_t *nntp_data;
1825   NNTP_SERVER *serv;
1826   char buf[HUGE_STRING];
1827   char server[LONG_STRING];
1828   int count = 0, first;
1829   ACCOUNT act;
1830
1831   p_clear(&act, 1);
1832
1833   if (nntp_parse_url (ctx->path, &act, buf, sizeof (buf)) < 0 || !*buf) {
1834     mutt_error (_("%s is an invalid newsgroup specification!"), ctx->path);
1835     mutt_sleep (2);
1836     return -1;
1837   }
1838
1839   server[0] = '\0';
1840   nntp_expand_path (server, sizeof (server), &act);
1841   if (!(serv = mutt_select_newsserver (server)) || serv->status != NNTP_OK)
1842     return -1;
1843
1844   CurrentNewsSrv = serv;
1845
1846   /* create NNTP-specific state struct if nof found in list */
1847   if ((nntp_data = hash_find(serv->newsgroups, buf)) == NULL) {
1848     nntp_data = nntp_data_new();
1849     nntp_data->group = m_strdup(buf);
1850     hash_insert(serv->newsgroups, nntp_data->group, nntp_data);
1851     nntp_data_list_append(&serv->list, nntp_data);
1852   }
1853   ctx->data = nntp_data;
1854   nntp_data->nserv = serv;
1855
1856   mutt_message (_("Selecting %s..."), nntp_data->group);
1857
1858   if (!nntp_data->desc) {
1859     nntp_get_desc (nntp_data, nntp_data->group, NULL, NULL);
1860     if (nntp_data->desc)
1861       nntp_save_cache_index (serv);
1862   }
1863
1864   buf[0] = 0;
1865   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
1866     return -1;
1867   }
1868
1869   if (m_strncmp("211", buf, 3)) {
1870     nntp_data_t **l;
1871
1872     /* GROUP command failed */
1873     if (!m_strncmp("411", buf, 3)) {
1874       mutt_error (_("Newsgroup %s not found on server %s"),
1875                   nntp_data->group, serv->conn->account.host);
1876
1877       /* CACHE: delete cache and line from .index */
1878       nntp_delete_cache (nntp_data);
1879       hash_remove(serv->newsgroups, nntp_data->group, NULL, NULL);
1880       for (l = &serv->list; *l; l = &(*l)->next) {
1881           if ((*l) == nntp_data) {
1882               nntp_data_list_pop(l);
1883               nntp_data_delete(&nntp_data);
1884               break;
1885           }
1886       }
1887       nntp_data_delete(&nntp_data);
1888       sleep (2);
1889     }
1890
1891     return -1;
1892   }
1893
1894   sscanf (buf + 4, "%d %u %u %s", &count, &nntp_data->firstMessage,
1895           &nntp_data->lastMessage, buf);
1896
1897   nntp_data->deleted = 0;
1898
1899   time (&serv->check_time);
1900
1901   /*
1902    * Check for max adding context. If it is greater than $nntp_context,
1903    * strip off extra articles
1904    */
1905   first = nntp_data->firstMessage;
1906   if (NntpContext && nntp_data->lastMessage - first + 1 > NntpContext)
1907     first = nntp_data->lastMessage - NntpContext + 1;
1908   if (first)
1909     nntp_data->lastLoaded = first - 1;
1910   return nntp_fetch_headers (ctx, first, nntp_data->lastMessage);
1911 }
1912
1913 int nntp_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
1914 {
1915   char buf[LONG_STRING];
1916   char path[_POSIX_PATH_MAX];
1917   NNTP_CACHE *cache;
1918   int ret;
1919   progress_t bar;
1920
1921   /* see if we already have the message in our cache */
1922   cache =
1923     &((nntp_data_t *) ctx->data)->acache[ctx->hdrs[msgno]->index %
1924                                        NNTP_CACHE_LEN];
1925
1926   /* if everything is fine, assign msg->fp and return */
1927   if (cache->path && cache->index == ctx->hdrs[msgno]->index &&
1928       (msg->fp = fopen (cache->path, "r")))
1929     return 0;
1930
1931   /* clear the previous entry */
1932   unlink (cache->path);
1933   p_delete(&cache->path);
1934
1935   cache->index = ctx->hdrs[msgno]->index;
1936   msg->fp = m_tempfile(path, sizeof(path), NONULL(mod_core.tmpdir), NULL);
1937   if (!msg->fp) {
1938     return -1;
1939   }
1940   cache->path = m_strdup(path);
1941
1942   if (ctx->hdrs[msgno]->article_num == 0)
1943     snprintf (buf, sizeof (buf), "ARTICLE %s\r\n",
1944               ctx->hdrs[msgno]->env->message_id);
1945   else
1946     snprintf (buf, sizeof (buf), "ARTICLE %d\r\n",
1947               ctx->hdrs[msgno]->article_num);
1948
1949   bar.msg = _("Fetching message...");
1950   bar.size = 0;
1951   mutt_progress_bar (&bar, 0);
1952
1953   ret = mutt_nntp_fetch ((nntp_data_t *) ctx->data, buf, NULL, &bar, nntp_read_tempfile,
1954                          msg->fp, ctx->tagged);
1955   if (ret == 1) {
1956     mutt_error (_("Article %d not found on server"),
1957                 ctx->hdrs[msgno]->article_num);
1958   }
1959
1960   if (ret) {
1961     m_fclose(&msg->fp);
1962     unlink (path);
1963     p_delete(&cache->path);
1964     return -1;
1965   }
1966
1967   envelope_delete(&ctx->hdrs[msgno]->env);
1968   ctx->hdrs[msgno]->env =
1969     mutt_read_rfc822_header (msg->fp, ctx->hdrs[msgno], 0, 0);
1970   /* fix content length */
1971   fseeko (msg->fp, 0, SEEK_END);
1972   ctx->hdrs[msgno]->content->length = ftello (msg->fp) -
1973     ctx->hdrs[msgno]->content->offset;
1974
1975   /* this is called in mutt before the open which fetches the message, 
1976    * which is probably wrong, but we just call it again here to handle
1977    * the problem instead of fixing it.
1978    */
1979   mutt_parse_mime_message (ctx, ctx->hdrs[msgno]);
1980
1981   /* These would normally be updated in mx_update_context(), but the 
1982    * full headers aren't parsed with XOVER, so the information wasn't
1983    * available then.
1984    */
1985   ctx->hdrs[msgno]->security = crypt_query (ctx->hdrs[msgno]->content);
1986
1987   mutt_clear_error ();
1988   rewind (msg->fp);
1989
1990   return 0;
1991 }
1992
1993 /* Post article */
1994 int nntp_post (const char *msg)
1995 {
1996   char buf[LONG_STRING];
1997   size_t len;
1998   FILE *f;
1999   nntp_data_t *nntp_data;
2000
2001   if (Context && Context->magic == M_NNTP)
2002     nntp_data = (nntp_data_t *)Context->data;
2003   else {
2004     if (!(CurrentNewsSrv = mutt_select_newsserver(NewsServer)) ||
2005         !CurrentNewsSrv->list)
2006     {
2007       mutt_error (_("Can't post article. No connection to news server."));
2008       return -1;
2009     }
2010     nntp_data = CurrentNewsSrv->list;
2011   }
2012
2013   if (!(f = safe_fopen (msg, "r"))) {
2014     mutt_error (_("Can't post article. Unable to open %s"), msg);
2015     return -1;
2016   }
2017
2018   m_strcpy(buf, sizeof(buf), "POST\r\n");
2019   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2020     mutt_error (_("Can't post article. Connection to %s lost."),
2021                 nntp_data->nserv->conn->account.host);
2022     return -1;
2023   }
2024   if (buf[0] != '3') {
2025     mutt_error (_("Can't post article: %s"), buf);
2026     return -1;
2027   }
2028
2029   buf[0] = '.';
2030   buf[1] = '\0';
2031   while (fgets (buf + 1, sizeof (buf) - 2, f) != NULL) {
2032     len = m_strlen(buf);
2033     if (buf[len - 1] == '\n') {
2034       buf[len - 1] = '\r';
2035       buf[len] = '\n';
2036       len++;
2037       buf[len] = '\0';
2038     }
2039     if (buf[1] == '.')
2040       mutt_socket_write(nntp_data->nserv->conn, buf);
2041     else
2042       mutt_socket_write(nntp_data->nserv->conn, buf + 1);
2043   }
2044   m_fclose(&f);
2045
2046   if (buf[m_strlen(buf) - 1] != '\n')
2047     mutt_socket_write(nntp_data->nserv->conn, "\r\n");
2048   mutt_socket_write(nntp_data->nserv->conn, ".\r\n");
2049   if (mutt_socket_readln (buf, sizeof (buf), nntp_data->nserv->conn) < 0) {
2050     mutt_error (_("Can't post article. Connection to %s lost."),
2051                 nntp_data->nserv->conn->account.host);
2052     return -1;
2053   }
2054   if (buf[0] != '2') {
2055     mutt_error (_("Can't post article: %s"), buf);
2056     return -1;
2057   }
2058
2059   return 0;
2060 }
2061
2062 /* nntp_logout_all: close all open connections. */
2063 void nntp_logout_all (void)
2064 {
2065   char buf[LONG_STRING];
2066   CONNECTION *conn;
2067
2068   conn = mutt_socket_head ();
2069
2070   while (conn) {
2071     CONNECTION* next = conn->next;
2072     if (conn->account.type == M_ACCT_TYPE_NNTP) {
2073       mutt_message (_("Closing connection to %s..."), conn->account.host);
2074       mutt_socket_write (conn, "QUIT\r\n");
2075       mutt_socket_readln (buf, sizeof (buf), conn);
2076       mutt_clear_error ();
2077       mutt_socket_close (conn);
2078       mutt_socket_free (conn);
2079     }
2080     conn = next;
2081   }
2082 }
2083
2084 static void nntp_free_acache (nntp_data_t * data)
2085 {
2086   int i;
2087
2088   for (i = 0; i < NNTP_CACHE_LEN; i++) {
2089     if (data->acache[i].path) {
2090       unlink (data->acache[i].path);
2091       p_delete(&data->acache[i].path);
2092     }
2093   }
2094 }
2095
2096 void nntp_data_wipe(nntp_data_t *data)
2097 {
2098     p_delete(&data->entries);
2099     p_delete(&data->desc);
2100     p_delete(&data->cache);
2101     p_delete(&data->group);
2102     nntp_free_acache(data);
2103 }
2104
2105 static int nntp_sync_mailbox (CONTEXT * ctx, int unused1, int* unused2)
2106 {
2107   nntp_data_t *data = ctx->data;
2108
2109   /* CACHE: update cache and .index files */
2110   if ((option (OPTSAVEUNSUB) || data->subscribed))
2111     nntp_save_cache_group (ctx);
2112   nntp_free_acache (data);
2113
2114   data->nserv->check_time = 0;  /* next nntp_check_mailbox() will really check */
2115   return 0;
2116 }
2117
2118 static void nntp_fastclose_mailbox (CONTEXT * ctx)
2119 {
2120   nntp_data_t *data = (nntp_data_t *) ctx->data, *tmp;
2121
2122   if (!data)
2123     return;
2124   nntp_free_acache (data);
2125   if (!data->nserv || !data->nserv->newsgroups || !data->group)
2126     return;
2127   nntp_save_cache_index (data->nserv);
2128   if ((tmp = hash_find (data->nserv->newsgroups, data->group)) == NULL
2129       || tmp != data)
2130     nntp_data_delete(&data);
2131   else
2132     nntp_sync_sidebar (data);
2133 }
2134
2135 /* commit changes and terminate connection */
2136 int nntp_close_mailbox (CONTEXT * ctx)
2137 {
2138   if (!ctx)
2139     return -1;
2140   mutt_message _("Quitting newsgroup...");
2141
2142   if (ctx->data) {
2143     nntp_data_t *data = (nntp_data_t *) ctx->data;
2144     int ret;
2145
2146     if (data->nserv && data->nserv->conn && ctx->unread) {
2147       ret = query_quadoption (OPT_CATCHUP, _("Mark all articles read?"));
2148       if (ret == M_YES)
2149         mutt_newsgroup_catchup (data->nserv, data->group);
2150       else if (ret < 0)
2151         return -1;
2152     }
2153   }
2154   nntp_sync_mailbox (ctx, 0, NULL);
2155   if (ctx->data && ((nntp_data_t *) ctx->data)->nserv) {
2156     NNTP_SERVER *news;
2157
2158     news = ((nntp_data_t *) ctx->data)->nserv;
2159     newsrc_gen_entries (ctx);
2160     ((nntp_data_t *) ctx->data)->unread = ctx->unread;
2161     mutt_newsrc_update (news);
2162   }
2163   mutt_clear_error ();
2164   return 0;
2165 }
2166
2167 /* use the GROUP command to poll for new mail */
2168 static int _nntp_check_mailbox (CONTEXT * ctx, nntp_data_t * nntp_data)
2169 {
2170   char buf[LONG_STRING];
2171   int count = 0;
2172
2173   if (nntp_data->nserv->check_time + NewsPollTimeout > time (NULL))
2174     return 0;
2175
2176   buf[0] = 0;
2177   if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2178     return -1;
2179   }
2180   if (m_strncmp("211", buf, 3)) {
2181     buf[0] = 0;
2182     if (mutt_nntp_query (nntp_data, buf, sizeof (buf)) < 0) {
2183       return -1;
2184     }
2185   }
2186   if (!m_strncmp("211", buf, 3)) {
2187     int first;
2188     int last;
2189
2190     sscanf (buf + 4, "%d %d %d", &count, &first, &last);
2191     nntp_data->firstMessage = first;
2192     nntp_data->lastMessage = last;
2193     if (ctx && last > nntp_data->lastLoaded) {
2194       nntp_fetch_headers (ctx, nntp_data->lastLoaded + 1, last);
2195       time (&nntp_data->nserv->check_time);
2196       return 1;
2197     }
2198     if (!last || (!nntp_data->rc && !nntp_data->lastCached))
2199       nntp_data->unread = count;
2200     else
2201       mutt_newsgroup_stat (nntp_data);
2202     /* active was renumbered? */
2203     if (last < nntp_data->lastLoaded) {
2204       if (!nntp_data->max) {
2205         nntp_data->entries = p_new(NEWSRC_ENTRY, 5);
2206         nntp_data->max = 5;
2207       }
2208       nntp_data->lastCached = 0;
2209       nntp_data->num = 1;
2210       nntp_data->entries[0].first = 1;
2211       nntp_data->entries[0].last = 0;
2212     }
2213     nntp_sync_sidebar (nntp_data);
2214   }
2215
2216   time (&nntp_data->nserv->check_time);
2217   return 0;
2218 }
2219
2220 static int nntp_check_mailbox (CONTEXT * ctx, int* unused1, int unused2)
2221 {
2222   return _nntp_check_mailbox (ctx, (nntp_data_t *) ctx->data);
2223 }
2224
2225 static int add_group (char *buf, void *serv)
2226 {
2227   NNTP_SERVER *s = serv;
2228   char group[LONG_STRING], mod, desc[HUGE_STRING];
2229   int first, last;
2230   nntp_data_t *nntp_data;
2231   static int n = 0;
2232
2233   _checked = n;                 /* _checked have N, where N = number of groups */
2234   if (!buf)                     /* at EOF must be zerouth */
2235     n = 0;
2236
2237   if (!s || !buf)
2238     return 0;
2239
2240   *desc = 0;
2241   sscanf (buf, "%s %d %d %c %[^\n]", group, &last, &first, &mod, desc);
2242   if (!group)
2243     return 0;
2244   if ((nntp_data = hash_find(s->newsgroups, group)) == NULL) {
2245     n++;
2246     nntp_data = nntp_data_new();
2247     nntp_data->group = m_strdup(group);
2248     nntp_data->nserv = s;
2249     if (s->newsgroups->nelem < s->newsgroups->curnelem * 2)
2250       hash_resize (s->newsgroups, s->newsgroups->nelem * 2);
2251     hash_insert(s->newsgroups, nntp_data->group, nntp_data);
2252     nntp_data_list_append(&s->list, nntp_data);
2253   }
2254   nntp_data->deleted = 0;
2255   nntp_data->firstMessage = first;
2256   nntp_data->lastMessage = last;
2257   if (mod == 'y')
2258     nntp_data->allowed = 1;
2259   else
2260     nntp_data->allowed = 0;
2261   if (nntp_data->desc)
2262     p_delete(&nntp_data->desc);
2263   if (*desc)
2264     nntp_data->desc = m_strdup(desc);
2265   if (nntp_data->rc || nntp_data->lastCached)
2266     mutt_newsgroup_stat (nntp_data);
2267   else if (nntp_data->lastMessage &&
2268            nntp_data->firstMessage <= nntp_data->lastMessage)
2269     nntp_data->unread = nntp_data->lastMessage - nntp_data->firstMessage + 1;
2270   else
2271     nntp_data->unread = 0;
2272
2273   return 0;
2274 }
2275
2276 static int nntp_check_newgroups (NNTP_SERVER * serv, int force)
2277 {
2278   char buf[LONG_STRING];
2279   nntp_data_t nntp_data;
2280   nntp_data_t *l, **emp;
2281   time_t now;
2282   struct tm *t;
2283
2284   if (!serv || !serv->newgroups_time)
2285     return -1;
2286
2287   if (nntp_open_connection (serv) < 0)
2288     return -1;
2289
2290   /* check subscribed groups for new news */
2291   if (option (OPTSHOWNEWNEWS)) {
2292     mutt_message _("Checking for new messages...");
2293
2294     for (l = serv->list; l; l = l->next) {
2295       serv->check_time = 0;     /* really check! */
2296       if (l->subscribed)
2297         _nntp_check_mailbox (NULL, l);
2298     }
2299     sidebar_draw ();
2300   }
2301   else if (!force)
2302     return 0;
2303
2304   mutt_message _("Checking for new newsgroups...");
2305
2306   now = serv->newgroups_time;
2307   time (&serv->newgroups_time);
2308   t = gmtime (&now);
2309   snprintf (buf, sizeof (buf), "NEWGROUPS %02d%02d%02d %02d%02d%02d GMT\r\n",
2310             (t->tm_year % 100), t->tm_mon + 1, t->tm_mday, t->tm_hour,
2311             t->tm_min, t->tm_sec);
2312   nntp_data.nserv = serv;
2313   if (Context && Context->magic == M_NNTP)
2314     nntp_data.group = ((nntp_data_t *) Context->data)->group;
2315   else
2316     nntp_data.group = NULL;
2317
2318   emp = nntp_data_list_last(&serv->list);
2319   if (mutt_nntp_fetch (&nntp_data, buf, _("Adding new newsgroups..."), NULL,
2320                        add_group, serv, 0) != 0) {
2321     return -1;
2322   }
2323
2324   mutt_message _("Loading descriptions...");
2325
2326   for (l = *emp; l; l = l->next) {
2327     l->new = 1;
2328     nntp_get_desc(l, l->group, NULL, NULL);
2329   }
2330   if (*emp)
2331     nntp_save_cache_index(serv);
2332   mutt_clear_error();
2333   return _checked;
2334 }
2335
2336 /* Load list of all newsgroups from cache ALL */
2337 static int nntp_get_cache_all (NNTP_SERVER * serv)
2338 {
2339   char buf[HUGE_STRING];
2340   FILE *f;
2341
2342   nntp_cache_expand (buf, serv->cache);
2343   if ((f = safe_fopen (buf, "r"))) {
2344     int i = 0;
2345
2346     while (fgets (buf, sizeof (buf), f) != NULL) {
2347       if (ReadInc && (i % ReadInc == 0))
2348         mutt_message (_("Loading list from cache... %d"), i);
2349       add_group (buf, serv);
2350       i++;
2351     }
2352     add_group (NULL, NULL);
2353     m_fclose(&f);
2354     mutt_clear_error ();
2355     return 0;
2356   }
2357   else {
2358     p_delete(&serv->cache);
2359     return -1;
2360   }
2361 }
2362
2363 /* Load list of all newsgroups from active */
2364 int nntp_get_active (NNTP_SERVER * serv)
2365 {
2366   char msg[STRING];
2367   nntp_data_t nntp_data, **tmp = &serv->list;
2368
2369   if (nntp_open_connection (serv) < 0)
2370     return -1;
2371
2372   snprintf (msg, sizeof (msg),
2373             _("Loading list of all newsgroups on server %s..."),
2374             serv->conn->account.host);
2375   mutt_message (msg);
2376   time (&serv->newgroups_time);
2377   nntp_data.nserv = serv;
2378   nntp_data.group = NULL;
2379
2380   if (mutt_nntp_fetch (&nntp_data, "LIST\r\n", msg, NULL, add_group, serv, 0) < 0) {
2381     return -1;
2382   }
2383
2384   m_strcpy(msg, sizeof(msg), _("Loading descriptions..."));
2385   mutt_message (msg);
2386   nntp_get_desc (&nntp_data, "*", msg, NULL);
2387
2388   while (*tmp) {
2389     if ((*tmp)->deleted && !(*tmp)->rc) {
2390       nntp_data_t *d = nntp_data_list_pop(tmp);
2391       nntp_delete_cache(d);
2392       hash_remove(serv->newsgroups, d->group, NULL, NULL);
2393       nntp_data_delete(&d);
2394     } else {
2395       tmp = &(*tmp)->next;
2396     }
2397   }
2398   nntp_save_cache_index (serv);
2399
2400   mutt_clear_error ();
2401   return _checked;
2402 }
2403
2404 /*
2405  * returns -1 if error ocurred while retrieving header,
2406  * number of articles which ones exist in context on success.
2407  */
2408 int nntp_check_msgid (CONTEXT * ctx, const char *msgid)
2409 {
2410   int ret;
2411
2412   /* if msgid is already in context, don't reload them */
2413   if (hash_find (ctx->id_hash, msgid))
2414     return 1;
2415   if (ctx->msgcount == ctx->hdrmax)
2416     mx_alloc_memory (ctx);
2417   ctx->hdrs[ctx->msgcount] = header_new();
2418   ctx->hdrs[ctx->msgcount]->index = ctx->msgcount;
2419
2420   mutt_message (_("Fetching %s from server..."), msgid);
2421   ret = nntp_read_header (ctx, msgid, 0);
2422   /* since nntp_read_header() may set read flag, we must reset it */
2423   ctx->hdrs[ctx->msgcount]->read = 0;
2424   if (ret != 0)
2425     header_delete(&ctx->hdrs[ctx->msgcount]);
2426   else {
2427     ctx->msgcount++;
2428     mx_update_context (ctx, 1);
2429     ctx->changed = 1;
2430   }
2431   return ret;
2432 }
2433
2434 typedef struct {
2435   CONTEXT *ctx;
2436   int num;
2437   int max;
2438   int *child;
2439 } CHILD_CONTEXT;
2440
2441 static int check_children (char *s, void *c)
2442 {
2443   CHILD_CONTEXT *cc = c;
2444   int i, n;
2445
2446   if (!s || (n = atoi (s)) == 0)
2447     return 0;
2448   for (i = 0; i < cc->ctx->msgcount; i++)
2449     if (cc->ctx->hdrs[i]->article_num == n)
2450       return 0;
2451   if (cc->num >= cc->max)
2452     p_realloc(&cc->child, cc->max += 25);
2453   cc->child[cc->num++] = n;
2454
2455   return 0;
2456 }
2457
2458 int nntp_check_children (CONTEXT * ctx, const char *msgid)
2459 {
2460   nntp_data_t *nntp_data = (nntp_data_t *) ctx->data;
2461   char buf[STRING];
2462   int i, ret = 0, tmp = 0;
2463   CHILD_CONTEXT cc = { ctx, 0, 0, NULL };
2464
2465   if (!nntp_data || !nntp_data->nserv || !nntp_data->nserv->conn ||
2466       !nntp_data->nserv->conn->account.host)
2467     return -1;
2468   if (nntp_data->firstMessage > nntp_data->lastLoaded)
2469     return 0;
2470   if (!nntp_data->nserv->hasXPAT) {
2471     mutt_error (_("Server %s does not support this operation!"),
2472                 nntp_data->nserv->conn->account.host);
2473     return -1;
2474   }
2475
2476   snprintf (buf, sizeof (buf), "XPAT References %d-%d *%s*\r\n",
2477             nntp_data->firstMessage, nntp_data->lastLoaded, msgid);
2478
2479   if (mutt_nntp_fetch (nntp_data, buf, NULL, NULL, check_children, &cc, 0)) {
2480     p_delete(&cc.child);
2481     return -1;
2482   }
2483
2484   /* dont try to read the xover cache. check_children() already
2485    * made sure that we dont have the article, so we need to visit
2486    * the server. Reading the cache at this point is also bad
2487    * because it would duplicate messages */
2488   if (option (OPTNEWSCACHE)) {
2489     tmp++;
2490     unset_option (OPTNEWSCACHE);
2491   }
2492   for (i = 0; i < cc.num; i++) {
2493     if ((ret = nntp_fetch_headers (ctx, cc.child[i], cc.child[i])))
2494       break;
2495     if (ctx->msgcount &&
2496         ctx->hdrs[ctx->msgcount - 1]->article_num == cc.child[i])
2497       ctx->hdrs[ctx->msgcount - 1]->read = 0;
2498   }
2499   if (tmp)
2500     set_option (OPTNEWSCACHE);
2501   p_delete(&cc.child);
2502   return ret;
2503 }
2504
2505 static int nntp_is_magic (const char* path, struct stat* st) {
2506   url_scheme_t s = url_check_scheme(NONULL(path));
2507   return s == U_NNTP || s == U_NNTPS ? M_NNTP : -1;
2508 }
2509
2510 static int acl_check_nntp (CONTEXT* ctx, int bit) {
2511   switch (bit) {
2512     case ACL_INSERT:    /* editing messages */
2513     case ACL_WRITE:     /* change importance */
2514       return (0);
2515     case ACL_DELETE:    /* (un)deletion */
2516     case ACL_SEEN:      /* mark as read */
2517       return (1);
2518     default:
2519       return (0);
2520   }
2521 }
2522
2523 mx_t const nntp_mx = {
2524     M_NNTP,
2525     0,
2526     nntp_is_magic,
2527     NULL,
2528     NULL,
2529     nntp_open_mailbox,
2530     NULL,
2531     acl_check_nntp,
2532     nntp_check_mailbox,
2533     nntp_fastclose_mailbox,
2534     nntp_sync_mailbox,
2535     NULL,
2536 };
2537
2538 /* }}} */