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