27b73f287857188ef8d692493ab9abf35c76c98d
[apps/madmutt.git] / muttlib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #if HAVE_CONFIG_H
12 # include "config.h"
13 #endif
14
15 #include "mutt.h"
16 #include "mutt_curses.h"
17 #include "mime.h"
18 #include "mx.h"
19 #include "url.h"
20
21 #include "reldate.h"
22
23 #ifdef USE_IMAP
24 #include "imap.h"
25 #include "imap/mx_imap.h"
26 #endif
27
28 #include "mutt_crypt.h"
29
30 #include "lib/mem.h"
31 #include "lib/intl.h"
32 #include "lib/str.h"
33 #include "lib/debug.h"
34
35 #include <string.h>
36 #include <ctype.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <sys/wait.h>
40 #include <errno.h>
41 #include <sys/stat.h>
42 #include <fcntl.h>
43 #include <time.h>
44 #include <sys/types.h>
45 #include <utime.h>
46
47 BODY *mutt_new_body (void)
48 {
49   BODY *p = (BODY *) safe_calloc (1, sizeof (BODY));
50
51   p->disposition = DISPATTACH;
52   p->use_disp = 1;
53   return (p);
54 }
55
56
57 /* Modified by blong to accept a "suggestion" for file name.  If
58  * that file exists, then construct one with unique name but 
59  * keep any extension.  This might fail, I guess.
60  * Renamed to mutt_adv_mktemp so I only have to change where it's
61  * called, and not all possible cases.
62  */
63 void mutt_adv_mktemp (char *s, size_t l)
64 {
65   char buf[_POSIX_PATH_MAX];
66   char tmp[_POSIX_PATH_MAX];
67   char *period;
68   size_t sl;
69   struct stat sb;
70
71   strfcpy (buf, NONULL (Tempdir), sizeof (buf));
72   mutt_expand_path (buf, sizeof (buf));
73   if (s[0] == '\0') {
74     snprintf (s, l, "%s/muttXXXXXX", buf);
75     mktemp (s);
76   }
77   else {
78     strfcpy (tmp, s, sizeof (tmp));
79     mutt_sanitize_filename (tmp, 1);
80     snprintf (s, l, "%s/%s", buf, tmp);
81     if (lstat (s, &sb) == -1 && errno == ENOENT)
82       return;
83     if ((period = strrchr (tmp, '.')) != NULL)
84       *period = 0;
85     snprintf (s, l, "%s/%s.XXXXXX", buf, tmp);
86     mktemp (s);
87     if (period != NULL) {
88       *period = '.';
89       sl = safe_strlen (s);
90       strfcpy (s + sl, period, l - sl);
91     }
92   }
93 }
94
95 /* create a send-mode duplicate from a receive-mode body */
96
97 int mutt_copy_body (FILE * fp, BODY ** tgt, BODY * src)
98 {
99   char tmp[_POSIX_PATH_MAX];
100   BODY *b;
101
102   PARAMETER *par, **ppar;
103
104   short use_disp;
105
106   if (src->filename) {
107     use_disp = 1;
108     strfcpy (tmp, src->filename, sizeof (tmp));
109   }
110   else {
111     use_disp = 0;
112     tmp[0] = '\0';
113   }
114
115   mutt_adv_mktemp (tmp, sizeof (tmp));
116   if (mutt_save_attachment (fp, src, tmp, 0, NULL) == -1)
117     return -1;
118
119   *tgt = mutt_new_body ();
120   b = *tgt;
121
122   memcpy (b, src, sizeof (BODY));
123   b->parts = NULL;
124   b->next = NULL;
125
126   b->filename = safe_strdup (tmp);
127   b->use_disp = use_disp;
128   b->unlink = 1;
129
130   if (mutt_is_text_part (b))
131     b->noconv = 1;
132
133   b->xtype = safe_strdup (b->xtype);
134   b->subtype = safe_strdup (b->subtype);
135   b->form_name = safe_strdup (b->form_name);
136   b->filename = safe_strdup (b->filename);
137   b->d_filename = safe_strdup (b->d_filename);
138   b->description = safe_strdup (b->description);
139
140   /* 
141    * we don't seem to need the HEADER structure currently.
142    * XXX - this may change in the future
143    */
144
145   if (b->hdr)
146     b->hdr = NULL;
147
148   /* copy parameters */
149   for (par = b->parameter, ppar = &b->parameter; par;
150        ppar = &(*ppar)->next, par = par->next) {
151     *ppar = mutt_new_parameter ();
152     (*ppar)->attribute = safe_strdup (par->attribute);
153     (*ppar)->value = safe_strdup (par->value);
154   }
155
156   mutt_stamp_attachment (b);
157
158   return 0;
159 }
160
161
162
163 void mutt_free_body (BODY ** p)
164 {
165   BODY *a = *p, *b;
166
167   while (a) {
168     b = a;
169     a = a->next;
170
171     if (b->parameter)
172       mutt_free_parameter (&b->parameter);
173     if (b->unlink && b->filename) {
174       debug_print (1, ("unlinking %s.\n", b->filename));
175       unlink (b->filename);
176     }
177     else if (b->filename)
178       debug_print (1, ("not unlinking %s.\n", b->filename));
179
180     FREE (&b->filename);
181     FREE (&b->content);
182     FREE (&b->xtype);
183     FREE (&b->subtype);
184     FREE (&b->description);
185     FREE (&b->form_name);
186
187     if (b->hdr) {
188       /* Don't free twice (b->hdr->content = b->parts) */
189       b->hdr->content = NULL;
190       mutt_free_header (&b->hdr);
191     }
192
193     if (b->parts)
194       mutt_free_body (&b->parts);
195
196     FREE (&b);
197   }
198
199   *p = 0;
200 }
201
202 void mutt_free_parameter (PARAMETER ** p)
203 {
204   PARAMETER *t = *p;
205   PARAMETER *o;
206
207   while (t) {
208     FREE (&t->attribute);
209     FREE (&t->value);
210     o = t;
211     t = t->next;
212     FREE (&o);
213   }
214   *p = 0;
215 }
216
217 LIST *mutt_add_list (LIST * head, const char *data)
218 {
219   LIST *tmp;
220
221   for (tmp = head; tmp && tmp->next; tmp = tmp->next);
222   if (tmp) {
223     tmp->next = safe_malloc (sizeof (LIST));
224     tmp = tmp->next;
225   }
226   else
227     head = tmp = safe_malloc (sizeof (LIST));
228
229   tmp->data = safe_strdup (data);
230   tmp->next = NULL;
231   return head;
232 }
233
234 void mutt_free_list (LIST ** list)
235 {
236   LIST *p;
237
238   if (!list)
239     return;
240   while (*list) {
241     p = *list;
242     *list = (*list)->next;
243     FREE (&p->data);
244     FREE (&p);
245   }
246 }
247
248 HEADER *mutt_dup_header (HEADER * h)
249 {
250   HEADER *hnew;
251
252   hnew = mutt_new_header ();
253   memcpy (hnew, h, sizeof (HEADER));
254   return hnew;
255 }
256
257 void mutt_free_header (HEADER ** h)
258 {
259   if (!h || !*h)
260     return;
261   mutt_free_envelope (&(*h)->env);
262   mutt_free_body (&(*h)->content);
263   FREE (&(*h)->maildir_flags);
264   FREE (&(*h)->tree);
265   FREE (&(*h)->path);
266 #ifdef MIXMASTER
267   mutt_free_list (&(*h)->chain);
268 #endif
269 #if defined USE_POP || defined USE_IMAP || defined USE_NNTP
270   FREE (&(*h)->data);
271 #endif
272   FREE (h);
273 }
274
275 /* returns true if the header contained in "s" is in list "t" */
276 int mutt_matches_ignore (const char *s, LIST * t)
277 {
278   for (; t; t = t->next) {
279     if (!ascii_strncasecmp (s, t->data, safe_strlen (t->data))
280         || *t->data == '*')
281       return 1;
282   }
283   return 0;
284 }
285
286 /* prepend the path part of *path to *link */
287 void mutt_expand_link (char *newpath, const char *path, const char *link)
288 {
289   const char *lb = NULL;
290   size_t len;
291
292   /* link is full path */
293   if (*link == '/') {
294     strfcpy (newpath, link, _POSIX_PATH_MAX);
295     return;
296   }
297
298   if ((lb = strrchr (path, '/')) == NULL) {
299     /* no path in link */
300     strfcpy (newpath, link, _POSIX_PATH_MAX);
301     return;
302   }
303
304   len = lb - path + 1;
305   memcpy (newpath, path, len);
306   strfcpy (newpath + len, link, _POSIX_PATH_MAX - len);
307 }
308
309 char *mutt_expand_path (char *s, size_t slen)
310 {
311   return _mutt_expand_path (s, slen, 0);
312 }
313
314 char *_mutt_expand_path (char *s, size_t slen, int rx)
315 {
316   char p[_POSIX_PATH_MAX] = "";
317   char q[_POSIX_PATH_MAX] = "";
318   char tmp[_POSIX_PATH_MAX];
319   char *t;
320
321   char *tail = "";
322
323   int recurse = 0;
324
325   do {
326     recurse = 0;
327
328     switch (*s) {
329     case '~':
330       {
331         if (*(s + 1) == '/' || *(s + 1) == 0) {
332           strfcpy (p, NONULL (Homedir), sizeof (p));
333           tail = s + 1;
334         }
335         else {
336           struct passwd *pw;
337
338           if ((t = strchr (s + 1, '/')))
339             *t = 0;
340
341           if ((pw = getpwnam (s + 1))) {
342             strfcpy (p, pw->pw_dir, sizeof (p));
343             if (t) {
344               *t = '/';
345               tail = t;
346             }
347             else
348               tail = "";
349           }
350           else {
351             /* user not found! */
352             if (t)
353               *t = '/';
354             *p = '\0';
355             tail = s;
356           }
357         }
358       }
359       break;
360
361     case '=':
362     case '+':
363       {
364 #ifdef USE_IMAP
365         /* if folder = {host} or imap[s]://host/: don't append slash */
366         if (imap_is_magic (NONULL (Maildir), NULL) == M_IMAP &&
367             (Maildir[safe_strlen (Maildir) - 1] == '}' ||
368              Maildir[safe_strlen (Maildir) - 1] == '/'))
369           strfcpy (p, NONULL (Maildir), sizeof (p));
370         else
371 #endif
372           snprintf (p, sizeof (p), "%s/", NONULL (Maildir));
373
374         tail = s + 1;
375       }
376       break;
377
378       /* elm compatibility, @ expands alias to user name */
379
380     case '@':
381       {
382         HEADER *h;
383         ADDRESS *alias;
384
385         if ((alias = mutt_lookup_alias (s + 1))) {
386           h = mutt_new_header ();
387           h->env = mutt_new_envelope ();
388           h->env->from = h->env->to = alias;
389           mutt_default_save (p, sizeof (p), h);
390           h->env->from = h->env->to = NULL;
391           mutt_free_header (&h);
392           /* Avoid infinite recursion if the resulting folder starts with '@' */
393           if (*p != '@')
394             recurse = 1;
395
396           tail = "";
397         }
398       }
399       break;
400
401     case '>':
402       {
403         strfcpy (p, NONULL (Inbox), sizeof (p));
404         tail = s + 1;
405       }
406       break;
407
408     case '<':
409       {
410         strfcpy (p, NONULL (Outbox), sizeof (p));
411         tail = s + 1;
412       }
413       break;
414
415     case '!':
416       {
417         if (*(s + 1) == '!') {
418           strfcpy (p, NONULL (LastFolder), sizeof (p));
419           tail = s + 2;
420         }
421         else {
422           strfcpy (p, NONULL (Spoolfile), sizeof (p));
423           tail = s + 1;
424         }
425       }
426       break;
427
428     case '-':
429       {
430         strfcpy (p, NONULL (LastFolder), sizeof (p));
431         tail = s + 1;
432       }
433       break;
434
435     case '^':
436       {
437         strfcpy (p, NONULL (CurrentFolder), sizeof (p));
438         tail = s + 1;
439       }
440       break;
441
442     default:
443       {
444         *p = '\0';
445         tail = s;
446       }
447     }
448
449     if (rx && *p && !recurse) {
450       mutt_rx_sanitize_string (q, sizeof (q), p);
451       snprintf (tmp, sizeof (tmp), "%s%s", q, tail);
452     }
453     else
454       snprintf (tmp, sizeof (tmp), "%s%s", p, tail);
455
456     strfcpy (s, tmp, slen);
457   }
458   while (recurse);
459
460 #ifdef USE_IMAP
461   /* Rewrite IMAP path in canonical form - aids in string comparisons of
462    * folders. May possibly fail, in which case s should be the same. */
463   if (imap_is_magic (s, NULL) == M_IMAP)
464     imap_expand_path (s, slen);
465 #endif
466
467   return (s);
468 }
469
470 /* Extract the real name from /etc/passwd's GECOS field.
471  * When set, honor the regular expression in GecosMask,
472  * otherwise assume that the GECOS field is a 
473  * comma-separated list.
474  * Replace "&" by a capitalized version of the user's login
475  * name.
476  */
477
478 char *mutt_gecos_name (char *dest, size_t destlen, struct passwd *pw)
479 {
480   regmatch_t pat_match[1];
481   size_t pwnl;
482   int idx;
483   char *p;
484
485   if (!pw || !pw->pw_gecos)
486     return NULL;
487
488   memset (dest, 0, destlen);
489
490   if (GecosMask.rx) {
491     if (regexec (GecosMask.rx, pw->pw_gecos, 1, pat_match, 0) == 0)
492       strfcpy (dest, pw->pw_gecos + pat_match[0].rm_so,
493                MIN (pat_match[0].rm_eo - pat_match[0].rm_so + 1, destlen));
494   }
495   else if ((p = strchr (pw->pw_gecos, ',')))
496     strfcpy (dest, pw->pw_gecos, MIN (destlen, p - pw->pw_gecos + 1));
497   else
498     strfcpy (dest, pw->pw_gecos, destlen);
499
500   pwnl = safe_strlen (pw->pw_name);
501
502   for (idx = 0; dest[idx]; idx++) {
503     if (dest[idx] == '&') {
504       memmove (&dest[idx + pwnl], &dest[idx + 1],
505                MAX (destlen - idx - pwnl - 1, 0));
506       memcpy (&dest[idx], pw->pw_name, MIN (destlen - idx - 1, pwnl));
507       dest[idx] = toupper ((unsigned char) dest[idx]);
508     }
509   }
510
511   return dest;
512 }
513
514
515 char *mutt_get_parameter (const char *s, PARAMETER * p)
516 {
517   for (; p; p = p->next)
518     if (ascii_strcasecmp (s, p->attribute) == 0)
519       return (p->value);
520
521   return NULL;
522 }
523
524 void mutt_set_parameter (const char *attribute, const char *value,
525                          PARAMETER ** p)
526 {
527   PARAMETER *q;
528
529   if (!value) {
530     mutt_delete_parameter (attribute, p);
531     return;
532   }
533
534   for (q = *p; q; q = q->next) {
535     if (ascii_strcasecmp (attribute, q->attribute) == 0) {
536       str_replace (&q->value, value);
537       return;
538     }
539   }
540
541   q = mutt_new_parameter ();
542   q->attribute = safe_strdup (attribute);
543   q->value = safe_strdup (value);
544   q->next = *p;
545   *p = q;
546 }
547
548 void mutt_delete_parameter (const char *attribute, PARAMETER ** p)
549 {
550   PARAMETER *q;
551
552   for (q = *p; q; p = &q->next, q = q->next) {
553     if (ascii_strcasecmp (attribute, q->attribute) == 0) {
554       *p = q->next;
555       q->next = NULL;
556       mutt_free_parameter (&q);
557       return;
558     }
559   }
560 }
561
562 /* returns 1 if Mutt can't display this type of data, 0 otherwise */
563 int mutt_needs_mailcap (BODY * m)
564 {
565   switch (m->type) {
566   case TYPETEXT:
567
568     if (!ascii_strcasecmp ("plain", m->subtype) ||
569         !ascii_strcasecmp ("rfc822-headers", m->subtype) ||
570         !ascii_strcasecmp ("enriched", m->subtype))
571       return 0;
572     break;
573
574   case TYPEAPPLICATION:
575     if ((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp (m))
576       return 0;
577     if ((WithCrypto & APPLICATION_SMIME) && mutt_is_application_smime (m))
578       return 0;
579     break;
580
581   case TYPEMULTIPART:
582   case TYPEMESSAGE:
583     return 0;
584   }
585
586   return 1;
587 }
588
589 int mutt_is_text_part (BODY * b)
590 {
591   int t = b->type;
592   char *s = b->subtype;
593
594   if ((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp (b))
595     return 0;
596
597   if (t == TYPETEXT)
598     return 1;
599
600   if (t == TYPEMESSAGE) {
601     if (!ascii_strcasecmp ("delivery-status", s))
602       return 1;
603   }
604
605   if ((WithCrypto & APPLICATION_PGP) && t == TYPEAPPLICATION) {
606     if (!ascii_strcasecmp ("pgp-keys", s))
607       return 1;
608   }
609
610   return 0;
611 }
612
613 void mutt_free_envelope (ENVELOPE ** p)
614 {
615   if (!*p)
616     return;
617   rfc822_free_address (&(*p)->return_path);
618   rfc822_free_address (&(*p)->from);
619   rfc822_free_address (&(*p)->to);
620   rfc822_free_address (&(*p)->cc);
621   rfc822_free_address (&(*p)->bcc);
622   rfc822_free_address (&(*p)->sender);
623   rfc822_free_address (&(*p)->reply_to);
624   rfc822_free_address (&(*p)->mail_followup_to);
625
626   FREE (&(*p)->list_post);
627   FREE (&(*p)->subject);
628   /* real_subj is just an offset to subject and shouldn't be freed */
629   FREE (&(*p)->message_id);
630   FREE (&(*p)->supersedes);
631   FREE (&(*p)->date);
632   FREE (&(*p)->x_label);
633   FREE (&(*p)->organization);
634 #ifdef USE_NNTP
635   FREE (&(*p)->newsgroups);
636   FREE (&(*p)->xref);
637   FREE (&(*p)->followup_to);
638   FREE (&(*p)->x_comment_to);
639 #endif
640
641   mutt_buffer_free (&(*p)->spam);
642   mutt_free_list (&(*p)->references);
643   mutt_free_list (&(*p)->in_reply_to);
644   mutt_free_list (&(*p)->userhdrs);
645   FREE (p);
646 }
647
648 void _mutt_mktemp (char *s, const char *src, int line)
649 {
650
651   snprintf (s, _POSIX_PATH_MAX, "%s/muttng-%s-%d-%d-%d-%x%x", NONULL (Tempdir),
652             NONULL (Hostname), (int) getuid (), (int) getpid (), Counter++, 
653             (unsigned int) rand(), (unsigned int) rand());
654   debug_print (1, ("%s:%d: mutt_mktemp returns \"%s\".\n", src, line, s));
655   unlink (s);
656 }
657
658 void mutt_free_alias (ALIAS ** p)
659 {
660   ALIAS *t;
661
662   while (*p) {
663     t = *p;
664     *p = (*p)->next;
665     FREE (&t->name);
666     rfc822_free_address (&t->addr);
667     FREE (&t);
668   }
669 }
670
671 /* collapse the pathname using ~ or = when possible */
672 void mutt_pretty_mailbox (char *s)
673 {
674   char *p = s, *q = s;
675   size_t len;
676   url_scheme_t scheme;
677
678   scheme = url_check_scheme (s);
679
680 #ifdef USE_IMAP
681   if (scheme == U_IMAP || scheme == U_IMAPS) {
682     imap_pretty_mailbox (s);
683     return;
684   }
685 #endif
686
687   /* if s is an url, only collapse path component */
688   if (scheme != U_UNKNOWN) {
689     p = strchr (s, ':') + 1;
690     if (!strncmp (p, "//", 2))
691       q = strchr (p + 2, '/');
692     if (!q)
693       q = strchr (p, '\0');
694     p = q;
695   }
696
697   /* first attempt to collapse the pathname */
698   while (*p) {
699     if (*p == '/' && p[1] == '/') {
700       *q++ = '/';
701       p += 2;
702     }
703     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
704       *q++ = '/';
705       p += 3;
706     }
707     else
708       *q++ = *p++;
709   }
710   *q = 0;
711
712   if (safe_strncmp (s, Maildir, (len = safe_strlen (Maildir))) == 0 &&
713       s[len] == '/') {
714     *s++ = '=';
715     memmove (s, s + len, safe_strlen (s + len) + 1);
716   }
717   else if (safe_strncmp (s, Homedir, (len = safe_strlen (Homedir))) == 0 &&
718            s[len] == '/') {
719     *s++ = '~';
720     memmove (s, s + len - 1, safe_strlen (s + len - 1) + 1);
721   }
722 }
723
724 void mutt_pretty_size (char *s, size_t len, long n)
725 {
726   if (n == 0)
727     strfcpy (s, "0K", len);
728   else if (n < 10189)           /* 0.1K - 9.9K */
729     snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
730   else if (n < 1023949) {       /* 10K - 999K */
731     /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
732     snprintf (s, len, "%ldK", (n + 51) / 1024);
733   }
734   else if (n < 10433332)        /* 1.0M - 9.9M */
735     snprintf (s, len, "%3.1fM", n / 1048576.0);
736   else {                        /* 10M+ */
737
738     /* (10433332 + 52428) / 1048576 = 10 */
739     snprintf (s, len, "%ldM", (n + 52428) / 1048576);
740   }
741 }
742
743 void mutt_expand_file_fmt (char *dest, size_t destlen, const char *fmt,
744                            const char *src)
745 {
746   char tmp[LONG_STRING];
747
748   mutt_quote_filename (tmp, sizeof (tmp), src);
749   mutt_expand_fmt (dest, destlen, fmt, tmp);
750 }
751
752 void mutt_expand_fmt (char *dest, size_t destlen, const char *fmt,
753                       const char *src)
754 {
755   const char *p;
756   char *d;
757   size_t slen;
758   int found = 0;
759
760   slen = safe_strlen (src);
761   destlen--;
762
763   for (p = fmt, d = dest; destlen && *p; p++) {
764     if (*p == '%') {
765       switch (p[1]) {
766       case '%':
767         *d++ = *p++;
768         destlen--;
769         break;
770       case 's':
771         found = 1;
772         strfcpy (d, src, destlen + 1);
773         d += destlen > slen ? slen : destlen;
774         destlen -= destlen > slen ? slen : destlen;
775         p++;
776         break;
777       default:
778         *d++ = *p;
779         destlen--;
780         break;
781       }
782     }
783     else {
784       *d++ = *p;
785       destlen--;
786     }
787   }
788
789   *d = '\0';
790
791   if (!found && destlen > 0) {
792     safe_strcat (dest, destlen, " ");
793     safe_strcat (dest, destlen, src);
794   }
795
796 }
797
798 /* return 0 on success, -1 on abort, 1 on error */
799 int mutt_check_overwrite (const char *attname, const char *path,
800                           char *fname, size_t flen, int *append,
801                           char **directory)
802 {
803   int rc = 0;
804   char tmp[_POSIX_PATH_MAX];
805   struct stat st;
806
807   strfcpy (fname, path, flen);
808   if (access (fname, F_OK) != 0)
809     return 0;
810   if (stat (fname, &st) != 0)
811     return -1;
812   if (S_ISDIR (st.st_mode)) {
813     if (directory) {
814       switch (mutt_multi_choice
815               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
816                _("yna"))) {
817       case 3:                  /* all */
818         str_replace (directory, fname);
819         break;
820       case 1:                  /* yes */
821         FREE (directory);
822         break;
823       case -1:                 /* abort */
824         FREE (directory);
825         return -1;
826       case 2:                  /* no */
827         FREE (directory);
828         return 1;
829       }
830     }
831     else
832       if ((rc =
833            mutt_yesorno (_("File is a directory, save under it?"),
834                          M_YES)) != M_YES)
835       return (rc == M_NO) ? 1 : -1;
836
837     if (!attname || !attname[0]) {
838       tmp[0] = 0;
839       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
840                           M_FILE | M_CLEAR) != 0 || !tmp[0])
841         return (-1);
842       mutt_concat_path (fname, path, tmp, flen);
843     }
844     else
845       mutt_concat_path (fname, path, mutt_basename (attname), flen);
846   }
847
848   if (*append == 0 && access (fname, F_OK) == 0) {
849     switch (mutt_multi_choice
850             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
851     {
852     case -1:                   /* abort */
853       return -1;
854     case 3:                    /* cancel */
855       return 1;
856
857     case 2:                    /* append */
858       *append = M_SAVE_APPEND;
859       break;
860     case 1:                    /* overwrite */
861       *append = M_SAVE_OVERWRITE;
862       break;
863     }
864   }
865   return 0;
866 }
867
868 void mutt_save_path (char *d, size_t dsize, ADDRESS * a)
869 {
870   if (a && a->mailbox) {
871     strfcpy (d, a->mailbox, dsize);
872     if (!option (OPTSAVEADDRESS)) {
873       char *p;
874
875       if ((p = strpbrk (d, "%@")))
876         *p = 0;
877     }
878     str_tolower (d);
879   }
880   else
881     *d = 0;
882 }
883
884 void mutt_safe_path (char *s, size_t l, ADDRESS * a)
885 {
886   char *p;
887
888   mutt_save_path (s, l, a);
889   for (p = s; *p; p++)
890     if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
891       *p = '_';
892 }
893
894 /* counts how many characters in s can be skipped while none of the
895  * characters of c appears */
896 int mutt_skipchars (const char *s, const char *c)
897 {
898   int ret = 0;
899   const char *p = s;
900
901   while (s && *s) {
902     register const char *t = c;
903
904     while (t && *t) {
905       if (*t == *s)
906         return (ret);
907       t++;
908     }
909     ret++;
910     s++;
911   }
912   return (safe_strlen (p));
913 }
914
915 void mutt_FormatString (char *dest,     /* output buffer */
916                         size_t destlen, /* output buffer len */
917                         const char *src,        /* template string */
918                         format_t * callback,    /* callback for processing */
919                         unsigned long data,     /* callback data */
920                         format_flag flags)
921 {                               /* callback flags */
922   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
923   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
924   size_t wlen, count, len, col, wid;
925
926   prefix[0] = '\0';
927   destlen--;                    /* save room for the terminal \0 */
928   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
929   col = wlen;
930
931   while (*src && wlen < destlen) {
932     if (*src == '%') {
933       if (*++src == '%') {
934         *wptr++ = '%';
935         wlen++;
936         col++;
937         src++;
938         continue;
939       }
940
941       if (*src == '?') {
942         flags |= M_FORMAT_OPTIONAL;
943         src++;
944       }
945       else {
946         flags &= ~M_FORMAT_OPTIONAL;
947
948         /* eat the format string */
949         cp = prefix;
950         count = 0;
951         while (count < sizeof (prefix) &&
952                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
953         {
954           *cp++ = *src++;
955           count++;
956         }
957         *cp = 0;
958       }
959
960       if (!*src)
961         break;                  /* bad format */
962
963       ch = *src++;              /* save the character to switch on */
964
965       if (flags & M_FORMAT_OPTIONAL) {
966         if (*src != '?')
967           break;                /* bad format */
968         src++;
969
970         /* eat the `if' part of the string */
971         cp = ifstring;
972         count = 0;
973         while (count < sizeof (ifstring) && *src && *src != '?'
974                && *src != '&') {
975           *cp++ = *src++;
976           count++;
977         }
978         *cp = 0;
979
980         /* eat the `else' part of the string (optional) */
981         if (*src == '&')
982           src++;                /* skip the & */
983         cp = elsestring;
984         count = 0;
985         while (count < sizeof (elsestring) && *src && *src != '?') {
986           *cp++ = *src++;
987           count++;
988         }
989         *cp = 0;
990
991         if (!*src)
992           break;                /* bad format */
993
994         src++;                  /* move past the trailing `?' */
995       }
996
997       /* handle generic cases first */
998       if (ch == '>') {
999         /* right justify to EOL */
1000         ch = *src++;            /* pad char */
1001         /* calculate space left on line.  if we've already written more data
1002            than will fit on the line, ignore the rest of the line */
1003         if (DrawFullLine || option (OPTSTATUSONTOP))
1004           count = (COLS < destlen ? COLS : destlen);
1005         else
1006           count =
1007             ((COLS - SidebarWidth) <
1008              destlen ? (COLS - SidebarWidth) : destlen);
1009         if (count > col) {
1010           count -= col;         /* how many columns left on this line */
1011           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
1012           wid = safe_strlen (buf);
1013           if (count > wid) {
1014             count -= wid;       /* how many chars to pad */
1015             memset (wptr, ch, count);
1016             wptr += count;
1017             col += count;
1018           }
1019           if (wid + wlen > destlen)
1020             len = destlen - wlen;
1021           else
1022             len = wid;
1023           memcpy (wptr, buf, len);
1024           wptr += len;
1025           wlen += len;
1026           col += mutt_strwidth (buf);
1027         }
1028         break;                  /* skip rest of input */
1029       }
1030       else if (ch == '|') {
1031         /* pad to EOL */
1032         ch = *src++;
1033         if (destlen > COLS)
1034           destlen = COLS;
1035         if (destlen > wlen) {
1036           count = destlen - wlen;
1037           memset (wptr, ch, count);
1038           wptr += count;
1039         }
1040         break;                  /* skip rest of input */
1041       }
1042       else {
1043         short tolower = 0;
1044         short nodots = 0;
1045
1046         while (ch == '_' || ch == ':') {
1047           if (ch == '_')
1048             tolower = 1;
1049           else if (ch == ':')
1050             nodots = 1;
1051
1052           ch = *src++;
1053         }
1054
1055         /* use callback function to handle this case */
1056         src =
1057           callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
1058                     data, flags);
1059
1060         if (tolower)
1061           str_tolower (buf);
1062         if (nodots) {
1063           char *p = buf;
1064
1065           for (; *p; p++)
1066             if (*p == '.')
1067               *p = '_';
1068         }
1069
1070         if ((len = safe_strlen (buf)) + wlen > destlen)
1071           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
1072
1073         memcpy (wptr, buf, len);
1074         wptr += len;
1075         wlen += len;
1076         col += mutt_strwidth (buf);
1077       }
1078     }
1079     else if (*src == '\\') {
1080       if (!*++src)
1081         break;
1082       switch (*src) {
1083       case 'n':
1084         *wptr = '\n';
1085         break;
1086       case 't':
1087         *wptr = '\t';
1088         break;
1089       case 'r':
1090         *wptr = '\r';
1091         break;
1092       case 'f':
1093         *wptr = '\f';
1094         break;
1095       case 'v':
1096         *wptr = '\v';
1097         break;
1098       default:
1099         *wptr = *src;
1100         break;
1101       }
1102       src++;
1103       wptr++;
1104       wlen++;
1105       col++;
1106     }
1107     else {
1108       unsigned int bar = mutt_skipchars (src, "%\\");
1109       char *bar2 = safe_malloc (bar + 1);
1110
1111       strfcpy (bar2, src, bar + 1);
1112       while (bar--) {
1113         *wptr++ = *src++;
1114         wlen++;
1115       }
1116       col += mutt_strwidth (bar2);
1117       FREE (&bar2);
1118     }
1119   }
1120   *wptr = 0;
1121
1122 #if 0
1123   if (flags & M_FORMAT_MAKEPRINT) {
1124     /* Make sure that the string is printable by changing all non-printable
1125        chars to dots, or spaces for non-printable whitespace */
1126     for (cp = dest; *cp; cp++)
1127       if (!IsPrint (*cp) && !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
1128         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
1129   }
1130 #endif
1131 }
1132
1133 /* This function allows the user to specify a command to read stdout from in
1134    place of a normal file.  If the last character in the string is a pipe (|),
1135    then we assume it is a commmand to run instead of a normal file. */
1136 FILE *mutt_open_read (const char *path, pid_t * thepid)
1137 {
1138   FILE *f;
1139   struct stat s;
1140
1141   int len = safe_strlen (path);
1142
1143   if (path[len - 1] == '|') {
1144     /* read from a pipe */
1145
1146     char *s = safe_strdup (path);
1147
1148     s[len - 1] = 0;
1149     mutt_endwin (NULL);
1150     *thepid = mutt_create_filter (s, NULL, &f, NULL);
1151     FREE (&s);
1152   }
1153   else {
1154     if (stat (path, &s) < 0)
1155       return (NULL);
1156     if (S_ISDIR (s.st_mode)) {
1157       errno = EINVAL;
1158       return (NULL);
1159     }
1160     f = fopen (path, "r");
1161     *thepid = -1;
1162   }
1163   return (f);
1164 }
1165
1166 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1167 int mutt_save_confirm (const char *s, struct stat *st)
1168 {
1169   char tmp[_POSIX_PATH_MAX];
1170   int ret = 0;
1171   int rc;
1172   int magic = 0;
1173
1174   magic = mx_get_magic (s);
1175
1176 #ifdef USE_POP
1177   if (magic == M_POP) {
1178     mutt_error _("Can't save message to POP mailbox.");
1179
1180     return 1;
1181   }
1182 #endif
1183
1184 #ifdef USE_NNTP
1185   if (magic == M_NNTP) {
1186     mutt_error _("Can't save message to newsserver.");
1187
1188     return 0;
1189   }
1190 #endif
1191
1192   if (stat (s, st) != -1) {
1193     if (magic == -1) {
1194       mutt_error (_("%s is not a mailbox!"), s);
1195       return 1;
1196     }
1197
1198     if (option (OPTCONFIRMAPPEND) &&
1199         (!TrashPath || (safe_strcmp (s, TrashPath) != 0)))
1200       /* if we're appending to the trash, there's no point in asking */
1201     {
1202       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1203       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1204         ret = 1;
1205       else if (rc == -1)
1206         ret = -1;
1207     }
1208   }
1209   else {
1210 #ifdef USE_IMAP
1211     if (magic != M_IMAP)
1212 #endif /* execute the block unconditionally if we don't use imap */
1213     {
1214       st->st_mtime = 0;
1215       st->st_atime = 0;
1216
1217       if (errno == ENOENT) {
1218         if (option (OPTCONFIRMCREATE)) {
1219           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1220           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1221             ret = 1;
1222           else if (rc == -1)
1223             ret = -1;
1224         }
1225       }
1226       else {
1227         mutt_perror (s);
1228         return 1;
1229       }
1230     }
1231   }
1232
1233   CLEARLINE (LINES - 1);
1234   return (ret);
1235 }
1236
1237 void state_prefix_putc (char c, STATE * s)
1238 {
1239   if (s->flags & M_PENDINGPREFIX) {
1240     int i;
1241
1242     i = safe_strlen (Quotebuf);
1243     Quotebuf[i++] = c;
1244     Quotebuf[i] = '\0';
1245     if (i == sizeof (Quotebuf) - 1 || c == '\n') {
1246       char buf[2 * SHORT_STRING];
1247       int j = 0, offset = 0;
1248       regmatch_t pmatch[1];
1249
1250       state_reset_prefix (s);
1251       while (regexec
1252              ((regex_t *) QuoteRegexp.rx, &Quotebuf[offset], 1, pmatch,
1253               0) == 0)
1254         offset += pmatch->rm_eo;
1255
1256       if (!option (OPTQUOTEEMPTY) && Quotebuf[offset] == '\n') {
1257         buf[0] = '\n';
1258         buf[1] = '\0';
1259       }
1260       else if (option (OPTQUOTEQUOTED) && offset) {
1261         for (i = 0; i < offset; i++)
1262           if (Quotebuf[i] != ' ')
1263             j = i;
1264         strncpy (buf, Quotebuf, j + 1);
1265         strcpy (buf + j + 1, Quotebuf + j);
1266       }
1267       else
1268         snprintf (buf, sizeof (buf), "%s%s", NONULL (s->prefix), Quotebuf);
1269
1270       state_puts (buf, s);
1271     }
1272   }
1273   else
1274     state_putc (c, s);
1275
1276   if (c == '\n') {
1277     state_set_prefix (s);
1278     Quotebuf[0] = '\0';
1279   }
1280 }
1281
1282 int state_printf (STATE * s, const char *fmt, ...)
1283 {
1284   int rv;
1285   va_list ap;
1286
1287   va_start (ap, fmt);
1288   rv = vfprintf (s->fpout, fmt, ap);
1289   va_end (ap);
1290
1291   return rv;
1292 }
1293
1294 void state_mark_attach (STATE * s)
1295 {
1296   if ((s->flags & M_DISPLAY) && !safe_strcmp (Pager, "builtin"))
1297     state_puts (AttachmentMarker, s);
1298 }
1299
1300 void state_attach_puts (const char *t, STATE * s)
1301 {
1302   if (*t != '\n')
1303     state_mark_attach (s);
1304   while (*t) {
1305     state_putc (*t, s);
1306     if (*t++ == '\n' && *t)
1307       if (*t != '\n')
1308         state_mark_attach (s);
1309   }
1310 }
1311
1312 void mutt_display_sanitize (char *s)
1313 {
1314   for (; *s; s++) {
1315     if (!IsPrint (*s))
1316       *s = '?';
1317   }
1318 }
1319
1320 void mutt_sleep (short s)
1321 {
1322   if (SleepTime > s)
1323     sleep (SleepTime);
1324   else if (s)
1325     sleep (s);
1326 }
1327
1328 /*
1329  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1330  * just initializes. Frees anything already in the buffer.
1331  *
1332  * Disregards the 'destroy' flag, which seems reserved for caller.
1333  * This is bad, but there's no apparent protocol for it.
1334  */
1335 BUFFER *mutt_buffer_init (BUFFER * b)
1336 {
1337   if (!b) {
1338     b = safe_malloc (sizeof (BUFFER));
1339     if (!b)
1340       return NULL;
1341   }
1342   else {
1343     FREE(&b->data);
1344   }
1345   memset (b, 0, sizeof (BUFFER));
1346   return b;
1347 }
1348
1349 /*
1350  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1351  * just initializes. Frees anything already in the buffer. Copies in
1352  * the seed string.
1353  *
1354  * Disregards the 'destroy' flag, which seems reserved for caller.
1355  * This is bad, but there's no apparent protocol for it.
1356  */
1357 BUFFER *mutt_buffer_from (BUFFER * b, char *seed)
1358 {
1359   if (!seed)
1360     return NULL;
1361
1362   b = mutt_buffer_init (b);
1363   b->data = safe_strdup (seed);
1364   b->dsize = safe_strlen (seed);
1365   b->dptr = (char *) b->data + b->dsize;
1366   return b;
1367 }
1368
1369 void mutt_buffer_addstr (BUFFER * buf, const char *s)
1370 {
1371   mutt_buffer_add (buf, s, safe_strlen (s));
1372 }
1373
1374 void mutt_buffer_addch (BUFFER * buf, char c)
1375 {
1376   mutt_buffer_add (buf, &c, 1);
1377 }
1378
1379 void mutt_buffer_free (BUFFER ** p)
1380 {
1381   if (!p || !*p)
1382     return;
1383
1384   FREE (&(*p)->data);
1385   /* dptr is just an offset to data and shouldn't be freed */
1386   FREE (p);
1387 }
1388
1389 /* dynamically grows a BUFFER to accomodate s, in increments of 128 bytes.
1390  * Always one byte bigger than necessary for the null terminator, and
1391  * the buffer is always null-terminated */
1392 void mutt_buffer_add (BUFFER * buf, const char *s, size_t len)
1393 {
1394   size_t offset;
1395
1396   if (buf->dptr + len + 1 > buf->data + buf->dsize) {
1397     offset = buf->dptr - buf->data;
1398     buf->dsize += len < 128 ? 128 : len + 1;
1399     safe_realloc ((void **) &buf->data, buf->dsize);
1400     buf->dptr = buf->data + offset;
1401   }
1402   memcpy (buf->dptr, s, len);
1403   buf->dptr += len;
1404   *(buf->dptr) = '\0';
1405 }
1406
1407 /* Decrease a file's modification time by 1 second */
1408
1409 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1410 {
1411   struct utimbuf utim;
1412   struct stat _st;
1413   time_t mtime;
1414
1415   if (!st) {
1416     if (stat (f, &_st) == -1)
1417       return -1;
1418     st = &_st;
1419   }
1420
1421   if ((mtime = st->st_mtime) == time (NULL)) {
1422     mtime -= 1;
1423     utim.actime = mtime;
1424     utim.modtime = mtime;
1425     utime (f, &utim);
1426   }
1427
1428   return mtime;
1429 }
1430
1431 const char *mutt_make_version (void)
1432 {
1433   static char vstring[STRING];
1434
1435   snprintf (vstring, sizeof (vstring), "Mutt-ng %s (%s) based on Mutt 1.5.9",
1436             MUTT_VERSION, ReleaseDate);
1437   return vstring;
1438 }
1439
1440 void mutt_free_spam_list (SPAM_LIST ** list)
1441 {
1442   SPAM_LIST *p;
1443
1444   if (!list)
1445     return;
1446   while (*list) {
1447     p = *list;
1448     *list = (*list)->next;
1449     rx_free (&p->rx);
1450     FREE(&p->template);
1451     FREE(&p);
1452   }
1453 }
1454
1455 int mutt_match_spam_list (const char *s, SPAM_LIST * l, char *text, int x)
1456 {
1457   static regmatch_t *pmatch = NULL;
1458   static int nmatch = 0;
1459   int i, n, tlen;
1460   char *p;
1461
1462   if (!s)
1463     return 0;
1464
1465   tlen = 0;
1466
1467   for (; l; l = l->next) {
1468     /* If this pattern needs more matches, expand pmatch. */
1469     if (l->nmatch > nmatch) {
1470       safe_realloc (&pmatch, l->nmatch * sizeof (regmatch_t));
1471       nmatch = l->nmatch;
1472     }
1473
1474     /* Does this pattern match? */
1475     if (regexec
1476         (l->rx->rx, s, (size_t) l->nmatch, (regmatch_t *) pmatch,
1477          (int) 0) == 0) {
1478       debug_print (5, ("%s matches %s\n%d subst", s, l->rx->pattern, l->rx->rx->re_nsub));
1479
1480       /* Copy template into text, with substitutions. */
1481       for (p = l->template; *p;) {
1482         if (*p == '%') {
1483           n = atoi (++p);       /* find pmatch index */
1484           while (isdigit (*p))
1485             ++p;                /* skip subst token */
1486           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
1487             text[tlen++] = s[i];
1488         }
1489         else {
1490           text[tlen++] = *p++;
1491         }
1492       }
1493       text[tlen] = '\0';
1494       debug_print (5, ("\"%s\"\n", text));
1495       return 1;
1496     }
1497   }
1498
1499   return 0;
1500 }