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