1499ba84dd36b6078ac1cbe6efb688eb7b28df28
[apps/madmutt.git] / nntp / newsrc.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-2001 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
19 #include "mutt.h"
20 #include "sort.h"
21 #include "mx.h"
22 #include "nntp.h"
23
24 void nntp_add_to_list (NNTP_SERVER * s, NNTP_DATA * d)
25 {
26   string_list_t *l;
27
28   if (!s || !d)
29     return;
30
31   l = p_new(string_list_t, 1);
32   if (s->list)
33     s->tail->next = l;
34   else
35     s->list = l;
36   s->tail = l;
37   l->data = (void *) d;
38 }
39
40 static int nntp_parse_newsrc_line (NNTP_SERVER * news, char *line)
41 {
42   NNTP_DATA *data;
43   char group[LONG_STRING];
44   int x = 1;
45   char *p = line, *b, *h;
46   ssize_t len;
47
48   while (*p) {
49     if (*p++ == ',')
50       x++;
51   }
52
53   p = line;
54   while (*p && (*p != ':' && *p != '!'))
55     p++;
56   if (!*p)
57     return -1;
58   len = p + 1 - line;
59   if (len > sizeof (group))
60     len = sizeof (group);
61   m_strcpy(group, len, line);
62   if ((data = (NNTP_DATA *) hash_find (news->newsgroups, group)) == NULL) {
63     data = xmalloc(sizeof(NNTP_DATA) + m_strlen(group) + 1);
64     data->group = (char *) data + sizeof (NNTP_DATA);
65     strcpy (data->group, group);
66     data->nserv = news;
67     data->deleted = 1;
68     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
69       news->newsgroups =
70         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
71     hash_insert (news->newsgroups, data->group, data, 0);
72     nntp_add_to_list (news, data);
73   }
74   else
75     p_delete(&data->entries);
76
77   data->rc = 1;
78   data->entries = p_new(NEWSRC_ENTRY, x * 2);
79   data->max = x * 2;
80
81   if (*p == ':')
82     data->subscribed = 1;
83   else
84     data->subscribed = 0;
85
86   p++;
87   b = p;
88   x = 0;
89   while (*b) {
90     while (*p && *p != ',' && *p != '\n')
91       p++;
92     if (*p) {
93       *p = '\0';
94       p++;
95     }
96     if ((h = strchr (b, '-'))) {
97       *h = '\0';
98       h++;
99       data->entries[x].first = atoi (b);
100       data->entries[x].last = atoi (h);
101     }
102     else {
103       data->entries[x].first = atoi (b);
104       data->entries[x].last = data->entries[x].first;
105     }
106     b = p;
107     if (data->entries[x].last != 0)
108       x++;
109   }
110   if (x && !data->lastMessage)
111     data->lastMessage = data->entries[x - 1].last;
112   data->num = x;
113   mutt_newsgroup_stat (data);
114
115   return 0;
116 }
117
118 static int slurp_newsrc (NNTP_SERVER * news)
119 {
120   FILE *fp;
121   char *buf;
122   struct stat sb;
123
124   news->stat = stat (news->newsrc, &sb);
125   news->size = sb.st_size;
126   news->mtime = sb.st_mtime;
127
128   if ((fp = safe_fopen (news->newsrc, "r")) == NULL)
129     return -1;
130   /* hmm, should we use dotlock? */
131   if (mx_lock_file (news->newsrc, fileno (fp), 0, 0, 1)) {
132     fclose (fp);
133     return -1;
134   }
135
136   buf = p_new(char, sb.st_size + 1);
137   while (fgets (buf, sb.st_size + 1, fp))
138     nntp_parse_newsrc_line (news, buf);
139   p_delete(&buf);
140
141   mx_unlock_file (news->newsrc, fileno (fp), 0);
142   fclose (fp);
143   return 0;
144 }
145
146 void nntp_cache_expand (char *dst, const char *src)
147 {
148   snprintf (dst, _POSIX_PATH_MAX, "%s/%s", NewsCacheDir, src);
149   mutt_expand_path (dst, _POSIX_PATH_MAX);
150 }
151
152 /* Loads $news_cache_dir/.index into memory, loads newsserver data
153  * and newsgroup cache names */
154 static int nntp_parse_cacheindex (NNTP_SERVER * news)
155 {
156   struct stat st;
157   char buf[HUGE_STRING], *cp;
158   char dir[_POSIX_PATH_MAX], file[_POSIX_PATH_MAX];
159   FILE *idx;
160   NNTP_DATA *data;
161   int l, m, t;
162
163   /* check is server name defined or not */
164   if (!news || !news->conn || !news->conn->account.host)
165     return -1;
166   unset_option (OPTNEWSCACHE);
167   if (!NewsCacheDir || !*NewsCacheDir)
168     return 0;
169
170   m_strcpy(dir, sizeof(dir), NewsCacheDir);
171   mutt_expand_path (dir, sizeof (dir));
172
173   if (lstat (dir, &st) || (st.st_mode & S_IFDIR) == 0) {
174     snprintf (buf, sizeof (buf), _("Directory %s not exist. Create it?"),
175               dir);
176     if (mutt_yesorno (buf, M_YES) != M_YES
177         || mkdir (dir, (S_IRWXU + S_IRWXG + S_IRWXO))) {
178       mutt_error _("Cache directory not created!");
179
180       return -1;
181     }
182     mutt_clear_error ();
183   }
184
185   set_option (OPTNEWSCACHE);
186
187   p_delete(&news->cache);
188   snprintf (buf, sizeof (buf), "%s/.index", dir);
189   if (!(idx = safe_fopen (buf, "a+")))
190     return 0;
191   rewind (idx);
192   while (fgets (buf, sizeof (buf), idx)) {
193     buf[m_strlen(buf) - 1] = 0;  /* strip ending '\n' */
194     if (!m_strncmp(buf, "#: ", 3) &&
195         !m_strcasecmp(buf + 3, news->conn->account.host))
196       break;
197   }
198   while (fgets (buf, sizeof (buf), idx)) {
199     cp = buf;
200     while (*cp && *cp != ' ')
201       cp++;
202     if (!*cp)
203       continue;
204     cp[0] = 0;
205     if (!m_strcmp(buf, "#:"))
206       break;
207     sscanf (cp + 1, "%s %d %d", file, &l, &m);
208     if (!m_strcmp(buf, "ALL")) {
209       news->cache = m_strdup(file);
210       news->newgroups_time = m;
211     }
212     else if (news->newsgroups) {
213       if ((data = (NNTP_DATA *) hash_find (news->newsgroups, buf)) == NULL) {
214         data = xmalloc(sizeof(NNTP_DATA) + m_strlen(buf) + 1);
215         data->group = (char *) data + sizeof (NNTP_DATA);
216         strcpy (data->group, buf);
217         data->nserv = news;
218         data->deleted = 1;
219         if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
220           news->newsgroups =
221             hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
222         hash_insert (news->newsgroups, data->group, data, 0);
223         nntp_add_to_list (news, data);
224       }
225       data->cache = m_strdup(file);
226       t = 0;
227       if (!data->firstMessage || data->lastMessage < m)
228         t = 1;
229       if (!data->firstMessage)
230         data->firstMessage = l;
231       if (data->lastMessage < m)
232         data->lastMessage = m;
233       data->lastCached = m;
234       if (t || !data->unread)
235         mutt_newsgroup_stat (data);
236     }
237   }
238   fclose (idx);
239   return 0;
240 }
241
242 const char *nntp_format_str (char *dest, ssize_t destlen, char op,
243                              const char *src, const char *fmt,
244                              const char *ifstring, const char *elsestring,
245                              unsigned long data, format_flag flags)
246 {
247   char fn[SHORT_STRING], tmp[SHORT_STRING];
248
249   switch (op) {
250   case 's':
251     m_strcpy(fn, sizeof (fn), NewsServer);
252     m_strtolower(fn);
253     snprintf (tmp, sizeof (tmp), "%%%ss", fmt);
254     snprintf (dest, destlen, tmp, fn);
255     break;
256   }
257   return (src);
258 }
259
260 /* nntp_parse_url: given an NNPT URL, return host, port,
261  * username, password and newsgroup will recognise. */
262 int nntp_parse_url (const char *server, ACCOUNT * act,
263                     char *group, ssize_t group_len)
264 {
265   ciss_url_t url;
266   char *c;
267   int ret = -1;
268
269   /* Defaults */
270   act->flags = 0;
271   act->port = NNTP_PORT;
272   act->type = M_ACCT_TYPE_NNTP;
273
274   c = m_strdup(server);
275   url_parse_ciss (&url, c);
276
277   if (url.scheme == U_NNTP || url.scheme == U_NNTPS) {
278     if (url.scheme == U_NNTPS) {
279       act->flags |= M_ACCT_SSL;
280       act->port = NNTP_SSL_PORT;
281     }
282
283     *group = '\0';
284     if (url.path)
285       m_strcpy(group, group_len, url.path);
286
287     ret = mutt_account_fromurl (act, &url);
288   }
289
290   p_delete(&c);
291   return ret;
292 }
293
294 void nntp_expand_path (char *line, ssize_t len, ACCOUNT * act)
295 {
296   ciss_url_t url;
297
298   url.path = m_strdup(line);
299   mutt_account_tourl (act, &url);
300   url_ciss_tostring (&url, line, len, 0);
301   p_delete(&url.path);
302 }
303
304 /*
305  * Automatically loads a newsrc into memory, if necessary.
306  * Checks the size/mtime of a newsrc file, if it doesn't match, load
307  * again.  Hmm, if a system has broken mtimes, this might mean the file
308  * is reloaded every time, which we'd have to fix.
309  *
310  * a newsrc file is a line per newsgroup, with the newsgroup, then a 
311  * ':' denoting subscribed or '!' denoting unsubscribed, then a 
312  * comma separated list of article numbers and ranges.
313  */
314 NNTP_SERVER *mutt_select_newsserver (char *server)
315 {
316   char file[_POSIX_PATH_MAX];
317   char *buf, *p;
318   string_list_t *list;
319   ACCOUNT act;
320   NNTP_SERVER *serv;
321   CONNECTION *conn;
322
323   p_clear(&act, 1);
324
325   if (!server || !*server) {
326     mutt_error _("No newsserver defined!");
327
328     return NULL;
329   }
330
331   buf = p = p_new(char, m_strlen(server) + 10);
332   if (url_check_scheme (server) == U_UNKNOWN) {
333     strcpy (buf, "nntp://");
334     p = strchr (buf, '\0');
335   }
336   strcpy (p, server);
337
338   if ((nntp_parse_url (buf, &act, file, sizeof (file))) < 0 || *file) {
339     p_delete(&buf);
340     mutt_error (_("%s is an invalid newsserver specification!"), server);
341     return NULL;
342   }
343   p_delete(&buf);
344
345   conn = mutt_conn_find (NULL, &act);
346   if (!conn)
347     return NULL;
348
349   mutt_FormatString (file, sizeof (file), NONULL (NewsRc), nntp_format_str, 0,
350                      0);
351   mutt_expand_path (file, sizeof (file));
352
353   serv = (NNTP_SERVER *) conn->data;
354   if (serv) {
355     struct stat sb;
356
357     /* externally modified? */
358     if (serv->stat != stat (file, &sb) || (!serv->stat &&
359                                            (serv->size != sb.st_size
360                                             || serv->mtime != sb.st_mtime))) {
361       for (list = serv->list; list; list = list->next) {
362         NNTP_DATA *data = (NNTP_DATA *) list->data;
363
364         if (data) {
365           data->subscribed = 0;
366           data->rc = 0;
367           data->num = 0;
368         }
369       }
370       slurp_newsrc (serv);
371       nntp_clear_cacheindex (serv);
372     }
373
374     if (serv->status == NNTP_BYE)
375       serv->status = NNTP_NONE;
376     nntp_check_newgroups (serv, 0);
377     return serv;
378   }
379
380   /* New newsserver */
381   serv = p_new(NNTP_SERVER, 1);
382   serv->conn = conn;
383   serv->newsrc = m_strdup(file);
384   serv->newsgroups = hash_create (1009);
385   slurp_newsrc (serv);          /* load .newsrc */
386   nntp_parse_cacheindex (serv); /* load .index */
387   if (option (OPTNEWSCACHE) && serv->cache && nntp_get_cache_all (serv) >= 0)
388     nntp_check_newgroups (serv, 1);
389   else if (nntp_get_active (serv) < 0) {
390     hash_destroy (&serv->newsgroups, nntp_delete_data);
391     for (list = serv->list; list; list = list->next)
392       list->data = NULL;
393     string_list_wipe(&serv->list);
394     p_delete(&serv->newsrc);
395     p_delete(&serv->cache);
396     p_delete(&serv);
397     return NULL;
398   }
399   nntp_clear_cacheindex (serv);
400   conn->data = (void *) serv;
401
402   return serv;
403 }
404
405 /* 
406  * full status flags are not supported by nntp, but we can fake some
407  * of them.  This is how:
408  * Read = a read message number is in the .newsrc
409  * New = a message is new since we last read this newsgroup
410  * Old = anything else
411  * So, Read is marked as such in the newsrc, old is anything that is 
412  * "skipped" in the newsrc, and new is anything not in the newsrc nor
413  * in the cache. By skipped, I mean before the last unread message
414  */
415 void nntp_get_status (CONTEXT * ctx, HEADER * h, char *group, int article)
416 {
417   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
418   int x;
419
420   if (group)
421     data = (NNTP_DATA *) hash_find (data->nserv->newsgroups, group);
422
423   if (!data) {
424     return;
425   }
426
427   for (x = 0; x < data->num; x++) {
428     if ((article >= data->entries[x].first) &&
429         (article <= data->entries[x].last)) {
430       /* we cannot use mutt_set_flag() because mx_update_context()
431          didn't called yet */
432       h->read = 1;
433       return;
434     }
435   }
436   /* If article was not cached yet, it is new! :) */
437   if (!data->cache || article > data->lastCached)
438     return;
439   /* Old articles are articles which aren't read but an article after them
440    * has been cached */
441   if (option (OPTMARKOLD))
442     h->old = 1;
443 }
444
445 void mutt_newsgroup_stat (NNTP_DATA * data)
446 {
447   int i;
448   unsigned int first, last;
449
450   data->unread = 0;
451   if (data->lastMessage == 0 || data->firstMessage > data->lastMessage)
452     return;
453
454   data->unread = data->lastMessage - data->firstMessage + 1;
455   for (i = 0; i < data->num; i++) {
456     first = data->entries[i].first;
457     if (first < data->firstMessage)
458       first = data->firstMessage;
459     last = data->entries[i].last;
460     if (last > data->lastMessage)
461       last = data->lastMessage;
462     if (first <= last)
463       data->unread -= last - first + 1;
464   }
465 }
466
467 static int puti (char *line, int num)
468 {
469   char *p, s[32];
470
471   for (p = s; num;) {
472     *p++ = '0' + num % 10;
473     num /= 10;
474   }
475   while (p > s)
476     *line++ = *--p, num++;
477   *line = '\0';
478   return num;
479 }
480
481 static void nntp_create_newsrc_line (NNTP_DATA * data, char **buf,
482                                      char **pline, ssize_t * buflen)
483 {
484   char *line = *pline;
485   ssize_t len = *buflen - (*pline - *buf);
486   int x, i;
487
488   if (len < LONG_STRING * 10) {
489     len += *buflen;
490     *buflen *= 2;
491     line = *buf;
492     p_realloc(buf, *buflen);
493     line = *buf + (*pline - line);
494   }
495   strcpy (line, data->group);
496   len -= m_strlen(line) + 1;
497   line += m_strlen(line);
498   *line++ = data->subscribed ? ':' : '!';
499   *line++ = ' ';
500   *line = '\0';
501
502   for (x = 0; x < data->num; x++) {
503     if (len < LONG_STRING) {
504       len += *buflen;
505       *buflen *= 2;
506       *pline = line;
507       line = *buf;
508       p_realloc(buf, *buflen);
509       line = *buf + (*pline - line);
510     }
511     if (x) {
512       *line++ = ',';
513       len--;
514     }
515
516 #if 0
517     if (data->entries[x].first == data->entries[x].last)
518       snprintf (line, len, "%d%n", data->entries[x].first, &i);
519     else
520       snprintf (line, len, "%d-%d%n",
521                 data->entries[x].first, data->entries[x].last, &i);
522     len -= i;
523     line += i;
524 #else
525     i = puti (line, data->entries[x].first);
526     line += i;
527     len -= i;
528     if (data->entries[x].first != data->entries[x].last) {
529       *line++ = '-';
530       len--;
531       i = puti (line, data->entries[x].last);
532       line += i;
533       len -= i;
534     }
535 #endif
536   }
537   *line++ = '\n';
538   *line = '\0';
539   *pline = line;
540 }
541
542 void newsrc_gen_entries (CONTEXT * ctx)
543 {
544   NNTP_DATA *data = (NNTP_DATA *) ctx->data;
545   int series, x;
546   unsigned int last = 0, first = 1;
547   int save_sort = SORT_ORDER;
548
549   if (Sort != SORT_ORDER) {
550     save_sort = Sort;
551     Sort = SORT_ORDER;
552     mutt_sort_headers (ctx, 0);
553   }
554
555   if (!data->max) {
556     data->entries = p_new(NEWSRC_ENTRY, 5);
557     data->max = 5;
558   }
559
560   /*
561    * Set up to fake initial sequence from 1 to the article before the 
562    * first article in our list
563    */
564   data->num = 0;
565   series = 1;
566
567   for (x = 0; x < ctx->msgcount; x++) {
568     if (series) {               /* search for first unread */
569       /*
570        * We don't actually check sequential order, since we mark 
571        * "missing" entries as read/deleted
572        */
573       last = ctx->hdrs[x]->article_num;
574       if (last >= data->firstMessage && !ctx->hdrs[x]->deleted &&
575           !ctx->hdrs[x]->read) {
576         if (data->num >= data->max) {
577           data->max = data->max * 2;
578           p_realloc(&data->entries, data->max);
579         }
580         data->entries[data->num].first = first;
581         data->entries[data->num].last = last - 1;
582         data->num++;
583         series = 0;
584       }
585     }
586     else {                      /* search for first read */
587
588       if (ctx->hdrs[x]->deleted || ctx->hdrs[x]->read) {
589         first = last + 1;
590         series = 1;
591       }
592       last = ctx->hdrs[x]->article_num;
593     }
594   }
595   if (series && first <= data->lastLoaded) {
596     if (data->num >= data->max) {
597       data->max = data->max * 2;
598       p_realloc(&data->entries, data->max);
599     }
600     data->entries[data->num].first = first;
601     data->entries[data->num].last = data->lastLoaded;
602     data->num++;
603   }
604
605   if (save_sort != Sort) {
606     Sort = save_sort;
607     mutt_sort_headers (ctx, 0);
608   }
609 }
610
611 static int mutt_update_list_file (char *filename, char *section,
612                                   const char *key, char *line) {
613   FILE *ifp;
614   FILE *ofp;
615   char buf[HUGE_STRING];
616   char tmpfile[_POSIX_PATH_MAX], link[_POSIX_PATH_MAX];
617   char *c;
618   int ext = 0, done = 0, r = 0, l = 0;
619
620   /* if file not exist, create it */
621   if ((ifp = safe_fopen (filename, "a")))
622     fclose (ifp);
623   if (!(ifp = safe_fopen (filename, "r"))) {
624     mutt_error (_("Unable to open %s for reading"), filename);
625     return -1;
626   }
627   if (mx_lock_file (filename, fileno (ifp), 0, 0, 1)) {
628     fclose (ifp);
629     mutt_error (_("Unable to lock %s"), filename);
630     return -1;
631   }
632   /* use mutt_adv_mktemp() to get a tempfile in the same
633    * directory as filename is so that we can follow symlinks
634    * via rename(2); as dirname(2) may modify its argument,
635    * temporarily use buf as copy of it
636    */
637   m_strcpy(buf, sizeof(buf), filename);
638   m_strcpy(tmpfile, sizeof(tmpfile), basename(filename));
639   mutt_adv_mktemp ((const char*) dirname (buf), tmpfile, sizeof (tmpfile));
640   if (!(ofp = fopen (tmpfile, "w"))) {
641     fclose (ifp);
642     mutt_error (_("Unable to open %s for writing"), tmpfile);
643     return -1;
644   }
645
646   if (section) {
647     while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
648       r = fputs (buf, ofp);
649       c = buf;
650       while (*c && *c != '\n') c++;
651       c[0] = 0; /* strip EOL */
652       if (!strncmp (buf, "#: ", 3) && !m_strcasecmp(buf+3, section))
653         done++;
654     }
655     if (r != EOF && !done) {
656       snprintf (buf, sizeof(buf), "#: %s\n", section);
657       r = fputs (buf, ofp);
658     }
659     done = 0;
660   }
661
662   while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
663     if (ext) {
664       c = buf;
665       while (*c && (*c != '\r') && (*c != '\n')) c++;
666       c--;
667       if (*c != '\\') ext = 0;
668     } else if ((section && !strncmp (buf, "#: ", 3))) {
669       if (!done && line) {
670         fputs (line, ofp);
671         fputc ('\n', ofp);
672       }
673       r = fputs (buf, ofp);
674       done++;
675       break;
676     } else if (key && !strncmp (buf, key, strlen(key)) &&
677                (!*key || buf[strlen(key)] == ' ')) {
678       c = buf;
679       ext = 0;
680       while (*c && (*c != '\r') && (*c != '\n')) c++;
681       c--;
682       if (*c == '\\') ext = 1;
683       if (!done && line) {
684         r = fputs (line, ofp);
685         if (*key)
686           r = fputc ('\n', ofp);
687         done++;
688       }
689     } else {
690       r = fputs (buf, ofp);
691     }
692   }
693
694   while (r != EOF && fgets (buf, sizeof (buf), ifp))
695     r = fputs (buf, ofp);
696
697   /* If there wasn't a line to replace, put it on the end of the file */
698   if (r != EOF && !done && line) {
699     fputs (line, ofp);
700     r = fputc ('\n', ofp);
701   }
702   mx_unlock_file (filename, fileno (ifp), 0);
703   fclose (ofp);
704   fclose (ifp);
705   if (r == EOF) {
706     unlink (tmpfile);
707     mutt_error (_("Can't write %s"), tmpfile);
708     return -1;
709   }
710   link[0] = '\0';
711   if ((l = readlink (filename, link, sizeof (link)-1)) > 0)
712     link[l] = '\0';
713   if (rename (tmpfile, l > 0 ? link : filename) < 0) {
714     unlink (tmpfile);
715     mutt_error (_("Can't rename %s to %s"), tmpfile, l > 0 ? link : filename);
716     return -1;
717   }
718   return 0;
719 }
720
721 int mutt_newsrc_update (NNTP_SERVER * news)
722 {
723   char *buf, *line;
724   NNTP_DATA *data;
725   string_list_t *tmp;
726   int r = -1;
727   ssize_t len, llen;
728
729   if (!news)
730     return -1;
731   llen = len = 10 * LONG_STRING;
732   line = buf = p_new(char, len);
733   /* we will generate full newsrc here */
734   for (tmp = news->list; tmp; tmp = tmp->next) {
735     data = (NNTP_DATA *) tmp->data;
736     if (!data || !data->rc)
737       continue;
738     nntp_create_newsrc_line (data, &buf, &line, &llen);
739     line += m_strlen(line);
740   }
741   /* newrc being fully rewritten */
742   if (news->newsrc &&
743       (r = mutt_update_list_file(news->newsrc, NULL, "", buf)) == 0) {
744     struct stat st;
745
746     stat (news->newsrc, &st);
747     news->size = st.st_size;
748     news->mtime = st.st_mtime;
749   }
750   p_delete(&buf);
751   return r;
752 }
753
754 static FILE *mutt_mkname (char *s)
755 {
756   char buf[_POSIX_PATH_MAX], *pc;
757   int fd;
758   FILE *fp;
759
760   nntp_cache_expand (buf, s);
761   if ((fp = safe_fopen (buf, "w")))
762     return fp;
763
764   nntp_cache_expand (buf, "cache-XXXXXX");
765   pc = buf + m_strlen(buf) - 12; /* positioning to "cache-XXXXXX" */
766   if ((fd = mkstemp (buf)) == -1)
767     return NULL;
768   strcpy (s, pc);               /* generated name */
769   return fdopen (fd, "w");
770 }
771
772 /* Updates info into .index file: ALL or about selected newsgroup */
773 static int nntp_update_cacheindex (NNTP_SERVER * serv, NNTP_DATA * data)
774 {
775   char buf[LONG_STRING];
776   char file[_POSIX_PATH_MAX];
777   const char *key = "ALL";
778
779   if (!serv || !serv->conn || !serv->conn->account.host)
780     return -1;
781
782   if (data && data->group) {
783     key = data->group;
784     snprintf (buf, sizeof (buf), "%s %s %d %d", key, data->cache,
785               data->firstMessage, data->lastLoaded);
786   }
787   else {
788     m_strcpy(file, sizeof(file), serv->cache);
789     snprintf (buf, sizeof (buf), "ALL %s 0 %d", file,
790               (int) serv->newgroups_time);
791   }
792   nntp_cache_expand (file, ".index");
793   return mutt_update_list_file (file, serv->conn->account.host, key, buf);
794 }
795
796 /* Remove cache files of unsubscribed newsgroups */
797 void nntp_clear_cacheindex (NNTP_SERVER * news)
798 {
799   NNTP_DATA *data;
800   string_list_t *tmp;
801
802   if (option (OPTSAVEUNSUB) || !news)
803     return;
804
805   for (tmp = news->list; tmp; tmp = tmp->next) {
806     data = (NNTP_DATA *) tmp->data;
807     if (!data || data->subscribed || !data->cache)
808       continue;
809     nntp_delete_cache (data);
810   }
811   return;
812 }
813
814 int nntp_save_cache_index (NNTP_SERVER * news)
815 {
816   char buf[HUGE_STRING];
817   char file[_POSIX_PATH_MAX];
818   NNTP_DATA *d;
819   FILE *f;
820   string_list_t *l;
821
822   if (!news || !news->newsgroups)
823     return -1;
824   if (!option (OPTNEWSCACHE))
825     return 0;
826
827   if (news->cache) {
828     nntp_cache_expand (file, news->cache);
829     unlink (file);
830     f = safe_fopen (file, "w");
831   }
832   else {
833     m_strcpy(buf, sizeof(buf), news->conn->account.host);
834     f = mutt_mkname (buf);
835     news->cache = m_strdup(buf);
836     nntp_cache_expand (file, buf);
837   }
838   if (!f)
839     return -1;
840
841   for (l = news->list; l; l = l->next) {
842     if ((d = (NNTP_DATA *) l->data) && !d->deleted) {
843       if (d->desc)
844         snprintf (buf, sizeof (buf), "%s %d %d %c %s\n", d->group,
845                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n',
846                   d->desc);
847       else
848         snprintf (buf, sizeof (buf), "%s %d %d %c\n", d->group,
849                   d->lastMessage, d->firstMessage, d->allowed ? 'y' : 'n');
850       if (fputs (buf, f) == EOF) {
851         fclose (f);
852         unlink (file);
853         return -1;
854       }
855     }
856   }
857   fclose (f);
858
859   if (nntp_update_cacheindex (news, NULL)) {
860     unlink (file);
861     return -1;
862   }
863   return 0;
864 }
865
866 int nntp_save_cache_group (CONTEXT * ctx)
867 {
868   char buf[HUGE_STRING], addr[STRING];
869   char file[_POSIX_PATH_MAX];
870   FILE *f;
871   HEADER *h;
872   struct tm *tm;
873   int i = 0, save = SORT_ORDER;
874   int prev = 0;
875
876   if (!option (OPTNEWSCACHE))
877     return 0;
878   if (!ctx || !ctx->data || ctx->magic != M_NNTP)
879     return -1;
880
881   if (((NNTP_DATA *) ctx->data)->cache) {
882     nntp_cache_expand (file, ((NNTP_DATA *) ctx->data)->cache);
883     unlink (file);
884     f = safe_fopen (file, "w");
885   }
886   else {
887     snprintf (buf, sizeof (buf), "%s-%s",
888               ((NNTP_DATA *) ctx->data)->nserv->conn->account.host,
889               ((NNTP_DATA *) ctx->data)->group);
890     f = mutt_mkname (buf);
891     ((NNTP_DATA *) ctx->data)->cache = m_strdup(buf);
892     nntp_cache_expand (file, buf);
893   }
894   if (!f)
895     return -1;
896
897   if (Sort != SORT_ORDER) {
898     save = Sort;
899     Sort = SORT_ORDER;
900     mutt_sort_headers (ctx, 0);
901   }
902
903   /* Save only $nntp_context messages... */
904   ((NNTP_DATA *) ctx->data)->lastCached = 0;
905   if (NntpContext && ctx->msgcount > NntpContext)
906     i = ctx->msgcount - NntpContext;
907   for (; i < ctx->msgcount; i++) {
908     if (!ctx->hdrs[i]->deleted && ctx->hdrs[i]->article_num != prev) {
909       h = ctx->hdrs[i];
910       addr[0] = 0;
911       rfc822_write_address (addr, sizeof (addr), h->env->from, 0);
912       tm = gmtime (&h->date_sent);
913       snprintf (buf, sizeof (buf),
914                 "%d\t%s\t%s\t%d %s %d %02d:%02d:%02d GMT\t%s\t",
915                 h->article_num, h->env->subject, addr, tm->tm_mday,
916                 Months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour,
917                 tm->tm_min, tm->tm_sec, h->env->message_id);
918       fputs (buf, f);
919       if (h->env->references)
920         mutt_write_references (h->env->references, f);
921       snprintf (buf, sizeof (buf), "\t%zd\t%d\tXref: %s\n",
922                 h->content->length, h->lines, NONULL (h->env->xref));
923       if (fputs (buf, f) == EOF) {
924         fclose (f);
925         unlink (file);
926         return -1;
927       }
928     }
929     prev = ctx->hdrs[i]->article_num;
930   }
931
932   if (save != Sort) {
933     Sort = save;
934     mutt_sort_headers (ctx, 0);
935   }
936   fclose (f);
937
938   if (nntp_update_cacheindex (((NNTP_DATA *) ctx->data)->nserv,
939                               (NNTP_DATA *) ctx->data)) {
940     unlink (file);
941     return -1;
942   }
943   ((NNTP_DATA *) ctx->data)->lastCached =
944     ((NNTP_DATA *) ctx->data)->lastLoaded;
945   return 0;
946 }
947
948 void nntp_delete_cache (NNTP_DATA * data)
949 {
950   char buf[_POSIX_PATH_MAX];
951
952   if (!option (OPTNEWSCACHE) || !data || !data->cache || !data->nserv)
953     return;
954
955   nntp_cache_expand (buf, data->cache);
956   unlink (buf);
957   p_delete(&data->cache);
958   data->lastCached = 0;
959   nntp_cache_expand (buf, ".index");
960   mutt_update_list_file (buf, data->nserv->conn->account.host, data->group,
961                          NULL);
962 }
963
964 NNTP_DATA *mutt_newsgroup_subscribe (NNTP_SERVER * news, char *group)
965 {
966   NNTP_DATA *data;
967
968   if (!news || !news->newsgroups || !group || !*group)
969     return NULL;
970   if (!(data = (NNTP_DATA *) hash_find (news->newsgroups, group))) {
971     data = xmalloc(sizeof(NNTP_DATA) + m_strlen(group) + 1);
972     data->group = (char *) data + sizeof (NNTP_DATA);
973     strcpy (data->group, group);
974     data->nserv = news;
975     data->deleted = 1;
976     if (news->newsgroups->nelem < news->newsgroups->curnelem * 2)
977       news->newsgroups =
978         hash_resize (news->newsgroups, news->newsgroups->nelem * 2);
979     hash_insert (news->newsgroups, data->group, data, 0);
980     nntp_add_to_list (news, data);
981   }
982   if (!data->subscribed) {
983     data->subscribed = 1;
984     data->rc = 1;
985   }
986   return data;
987 }
988
989 NNTP_DATA *mutt_newsgroup_unsubscribe (NNTP_SERVER * news, char *group)
990 {
991   NNTP_DATA *data;
992
993   if (!news || !news->newsgroups || !group || !*group ||
994       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
995     return NULL;
996   if (data->subscribed) {
997     data->subscribed = 0;
998     if (!option (OPTSAVEUNSUB))
999       data->rc = 0;
1000   }
1001   return data;
1002 }
1003
1004 NNTP_DATA *mutt_newsgroup_catchup (NNTP_SERVER * news, char *group)
1005 {
1006   NNTP_DATA *data;
1007
1008   if (!news || !news->newsgroups || !group || !*group ||
1009       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
1010     return NULL;
1011   if (!data->max) {
1012     data->entries = p_new(NEWSRC_ENTRY, 5);
1013     data->max = 5;
1014   }
1015   data->num = 1;
1016   data->entries[0].first = 1;
1017   data->unread = 0;
1018   data->entries[0].last = data->lastMessage;
1019   if (Context && Context->data == data) {
1020     int x;
1021
1022     for (x = 0; x < Context->msgcount; x++)
1023       mutt_set_flag (Context, Context->hdrs[x], M_READ, 1);
1024   }
1025   return data;
1026 }
1027
1028 NNTP_DATA *mutt_newsgroup_uncatchup (NNTP_SERVER * news, char *group)
1029 {
1030   NNTP_DATA *data;
1031
1032   if (!news || !news->newsgroups || !group || !*group ||
1033       !(data = (NNTP_DATA *) hash_find (news->newsgroups, group)))
1034     return NULL;
1035   if (!data->max) {
1036     data->entries = p_new(NEWSRC_ENTRY, 5);
1037     data->max = 5;
1038   }
1039   data->num = 1;
1040   data->entries[0].first = 1;
1041   data->entries[0].last = data->firstMessage - 1;
1042   if (Context && Context->data == data) {
1043     int x;
1044
1045     data->unread = Context->msgcount;
1046     for (x = 0; x < Context->msgcount; x++)
1047       mutt_set_flag (Context, Context->hdrs[x], M_READ, 0);
1048   }
1049   else
1050     data->unread = data->lastMessage - data->entries[0].last;
1051   return data;
1052 }
1053
1054 /* this routine gives the first newsgroup with new messages */
1055 void nntp_buffy (char* dst, ssize_t dstlen) {
1056   string_list_t *list;
1057   int count = 0;
1058
1059   /* forward to current group */
1060   for (list = CurrentNewsSrv->list; list; list = list->next) {
1061     NNTP_DATA *data = (NNTP_DATA *) list->data;
1062     if (data && data->subscribed && data->unread && 
1063         Context && Context->magic == M_NNTP &&
1064         m_strcmp(data->group, ((NNTP_DATA *) Context->data)->group) == 0) {
1065       list = list->next;
1066       break;
1067     }
1068   }
1069
1070   *dst = '\0';
1071
1072   while (count < 2) {
1073
1074     if (!list)
1075       list = CurrentNewsSrv->list;
1076
1077     for (; list; list = list->next) {
1078       NNTP_DATA *data = (NNTP_DATA *) list->data;
1079
1080       if (data && data->subscribed && data->unread) {
1081         if (Context && Context->magic == M_NNTP &&
1082             !m_strcmp(data->group, ((NNTP_DATA *) Context->data)->group)) {
1083           unsigned int i, unread = 0;
1084
1085           for (i = 0; i < Context->msgcount; i++)
1086             if (!Context->hdrs[i]->read && !Context->hdrs[i]->deleted)
1087               unread++;
1088           if (!unread)
1089             continue;
1090         }
1091         m_strcpy(dst, dstlen, data->group);
1092         break;
1093       }
1094     }
1095     /* done if found */
1096     if (dst && *dst)
1097       return;
1098     count++;
1099   }
1100   *dst = '\0';
1101 }