Rocco Rutte:
[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 /* counts how many characters in s can be skipped while none of the
933  * characters of c appears */
934 int mutt_skipchars (const char* s, const char* c) {
935   int ret = 0;
936   const char* p = s;
937   while (s && *s) {
938     register const char* t = c;
939     while (t && *t) {
940       if (*t == *s)
941         return (ret);
942       t++;
943     }
944     ret++;
945     s++;
946   }
947   return (mutt_strlen (p));
948 }
949
950 void mutt_FormatString (char *dest,             /* output buffer */
951                         size_t destlen,         /* output buffer len */
952                         const char *src,        /* template string */
953                         format_t *callback,     /* callback for processing */
954                         unsigned long data,     /* callback data */
955                         format_flag flags)      /* callback flags */
956 {
957   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
958   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
959   size_t wlen, count, len, col, wid;
960
961   prefix[0] = '\0';
962   destlen--; /* save room for the terminal \0 */
963   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
964   col = wlen;
965     
966   while (*src && wlen < destlen)
967   {
968     if (*src == '%')
969     {
970       if (*++src == '%')
971       {
972         *wptr++ = '%';
973         wlen++;
974         col++;
975         src++;
976         continue;
977       }
978
979       if (*src == '?')
980       {
981         flags |= M_FORMAT_OPTIONAL;
982         src++;
983       }
984       else
985       {
986         flags &= ~M_FORMAT_OPTIONAL;
987
988         /* eat the format string */
989         cp = prefix;
990         count = 0;
991         while (count < sizeof (prefix) &&
992                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
993         {
994           *cp++ = *src++;
995           count++;
996         }
997         *cp = 0;
998       }
999
1000       if (!*src)
1001         break; /* bad format */
1002
1003       ch = *src++; /* save the character to switch on */
1004
1005       if (flags & M_FORMAT_OPTIONAL)
1006       {
1007         if (*src != '?')
1008           break; /* bad format */
1009         src++;
1010
1011         /* eat the `if' part of the string */
1012         cp = ifstring;
1013         count = 0;
1014         while (count < sizeof (ifstring) && *src && *src != '?' && *src != '&')
1015         {
1016           *cp++ = *src++;
1017           count++;
1018         }
1019         *cp = 0;
1020
1021         /* eat the `else' part of the string (optional) */
1022         if (*src == '&')
1023           src++; /* skip the & */
1024         cp = elsestring;
1025         count = 0;
1026         while (count < sizeof (elsestring) && *src && *src != '?')
1027         {
1028           *cp++ = *src++;
1029           count++;
1030         }
1031         *cp = 0;
1032
1033         if (!*src)
1034           break; /* bad format */
1035
1036         src++; /* move past the trailing `?' */
1037       }
1038
1039       /* handle generic cases first */
1040       if (ch == '>')
1041       {
1042         /* right justify to EOL */
1043         ch = *src++; /* pad char */
1044         /* calculate space left on line.  if we've already written more data
1045            than will fit on the line, ignore the rest of the line */
1046         if ( DrawFullLine  || option(OPTSTATUSONTOP))
1047           count = (COLS < destlen ? COLS : destlen);
1048         else
1049           count = ((COLS-SidebarWidth) < destlen ? (COLS - SidebarWidth) : destlen);
1050         if (count > col)
1051         {
1052           count -= col; /* how many columns left on this line */
1053           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
1054           wid = mutt_strlen (buf);
1055           if (count > wid)
1056           {
1057             count -= wid; /* how many chars to pad */
1058             memset (wptr, ch, count);
1059             wptr += count;
1060             col += count;
1061           }
1062           if (wid + wlen > destlen)
1063             len = destlen - wlen;
1064     else
1065       len = wid;
1066           memcpy (wptr, buf, len);
1067           wptr += len;
1068           wlen += len;
1069           col += mutt_strwidth (buf);
1070         }
1071         break; /* skip rest of input */
1072       }
1073       else if (ch == '|')
1074       {
1075         /* pad to EOL */
1076         ch = *src++;
1077         if (destlen > COLS)
1078           destlen = COLS;
1079         if (destlen > wlen)
1080         {
1081           count = destlen - wlen;
1082           memset (wptr, ch, count);
1083           wptr += count;
1084         }
1085         break; /* skip rest of input */
1086       }
1087       else
1088       {
1089         short tolower =  0;
1090         short nodots  = 0;
1091         
1092         while (ch == '_' || ch == ':') 
1093         {
1094           if (ch == '_')
1095             tolower = 1;
1096           else if (ch == ':') 
1097             nodots = 1;
1098           
1099           ch = *src++;
1100         }
1101         
1102         /* use callback function to handle this case */
1103         src = callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring, data, flags);
1104
1105         if (tolower)
1106           mutt_strlower (buf);
1107         if (nodots) 
1108         {
1109           char *p = buf;
1110           for (; *p; p++)
1111             if (*p == '.')
1112                 *p = '_';
1113         }
1114         
1115         if ((len = mutt_strlen (buf)) + wlen > destlen)
1116           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
1117
1118         memcpy (wptr, buf, len);
1119         wptr += len;
1120         wlen += len;
1121         col += mutt_strwidth (buf);
1122       }
1123     }
1124     else if (*src == '\\')
1125     {
1126       if (!*++src)
1127         break;
1128       switch (*src)
1129       {
1130         case 'n':
1131           *wptr = '\n';
1132           break;
1133         case 't':
1134           *wptr = '\t';
1135           break;
1136         case 'r':
1137           *wptr = '\r';
1138           break;
1139         case 'f':
1140           *wptr = '\f';
1141           break;
1142         case 'v':
1143           *wptr = '\v';
1144           break;
1145         default:
1146           *wptr = *src;
1147           break;
1148       }
1149       src++;
1150       wptr++;
1151       wlen++;
1152       col++;
1153     }
1154     else
1155     {
1156       unsigned int bar = mutt_skipchars (src, "%\\");
1157       char* bar2 = safe_malloc (bar+1);
1158       strfcpy (bar2, src, bar+1);
1159       while (bar--) {
1160         *wptr++ = *src++;
1161         wlen++;
1162       }
1163       col += mutt_strwidth (bar2);
1164       FREE(&bar2);
1165     }
1166   }
1167   *wptr = 0;
1168
1169 #if 0
1170   if (flags & M_FORMAT_MAKEPRINT)
1171   {
1172     /* Make sure that the string is printable by changing all non-printable
1173        chars to dots, or spaces for non-printable whitespace */
1174     for (cp = dest ; *cp ; cp++)
1175       if (!IsPrint (*cp) &&
1176           !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
1177         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
1178   }
1179 #endif
1180 }
1181
1182 /* This function allows the user to specify a command to read stdout from in
1183    place of a normal file.  If the last character in the string is a pipe (|),
1184    then we assume it is a commmand to run instead of a normal file. */
1185 FILE *mutt_open_read (const char *path, pid_t *thepid)
1186 {
1187   FILE *f;
1188   struct stat s;
1189
1190   int len = mutt_strlen (path);
1191
1192   if (path[len - 1] == '|')
1193   {
1194     /* read from a pipe */
1195
1196     char *s = safe_strdup (path);
1197
1198     s[len - 1] = 0;
1199     mutt_endwin (NULL);
1200     *thepid = mutt_create_filter (s, NULL, &f, NULL);
1201     FREE (&s);
1202   }
1203   else
1204   {
1205     if (stat (path, &s) < 0)
1206       return (NULL);
1207     if (S_ISDIR (s.st_mode))
1208     {
1209       errno = EINVAL;
1210       return (NULL);
1211     }
1212     f = fopen (path, "r");
1213     *thepid = -1;
1214   }
1215   return (f);
1216 }
1217
1218 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1219 int mutt_save_confirm (const char *s, struct stat *st)
1220 {
1221   char tmp[_POSIX_PATH_MAX];
1222   int ret = 0;
1223   int rc;
1224   int magic = 0;
1225
1226   magic = mx_get_magic (s);
1227
1228 #ifdef USE_POP
1229   if (magic == M_POP)
1230   {
1231     mutt_error _("Can't save message to POP mailbox.");
1232     return 1;
1233   }
1234 #endif
1235
1236 #ifdef USE_NNTP
1237   if (magic == M_NNTP)
1238   {
1239     mutt_error _("Can't save message to newsserver.");
1240     return 0;
1241   }
1242 #endif
1243
1244   if (stat (s, st) != -1)
1245   {
1246     if (magic == -1)
1247     {
1248       mutt_error (_("%s is not a mailbox!"), s);
1249       return 1;
1250     }
1251
1252     if (option (OPTCONFIRMAPPEND) &&
1253         (!TrashPath || (mutt_strcmp (s, TrashPath) != 0)))
1254       /* if we're appending to the trash, there's no point in asking */
1255     {
1256       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1257       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1258         ret = 1;
1259       else if (rc == -1)
1260         ret = -1;
1261     }
1262   }
1263   else
1264   {
1265 #ifdef USE_IMAP
1266     if (magic != M_IMAP)
1267 #endif /* execute the block unconditionally if we don't use imap */
1268     {
1269       st->st_mtime = 0;
1270       st->st_atime = 0;
1271
1272       if (errno == ENOENT)
1273       {
1274         if (option (OPTCONFIRMCREATE))
1275         {
1276           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1277           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1278             ret = 1;
1279           else if (rc == -1)
1280             ret = -1;
1281         }
1282       }
1283       else
1284       {
1285         mutt_perror (s);
1286         return 1;
1287       }
1288     }
1289   }
1290
1291   CLEARLINE (LINES-1);
1292   return (ret);
1293 }
1294
1295 void state_prefix_putc (char c, STATE *s)
1296 {
1297   if (s->flags & M_PENDINGPREFIX)
1298   {
1299     int i;
1300
1301     i = strlen (Quotebuf);
1302     Quotebuf[i++] = c;
1303     Quotebuf[i] = '\0';
1304     if (i == sizeof (Quotebuf) - 1 || c == '\n')
1305     {
1306       char buf[2 * SHORT_STRING];
1307       int j = 0, offset = 0;
1308       regmatch_t pmatch[1];
1309
1310       state_reset_prefix (s);
1311       while (regexec ((regex_t *) QuoteRegexp.rx, &Quotebuf[offset], 1, pmatch, 0) == 0)
1312         offset += pmatch->rm_eo;
1313
1314       if (!option (OPTQUOTEEMPTY) && Quotebuf[0] == '\n')
1315         strcpy (buf, Quotebuf);
1316       else if (option (OPTQUOTEQUOTED) && offset)
1317       {
1318         for (i = 0; i < offset; i++)
1319           if (Quotebuf[i] != ' ')
1320             j = i;
1321         strncpy (buf, Quotebuf, j + 1);
1322         strcpy (buf + j + 1, Quotebuf + j);
1323       }
1324       else
1325         snprintf (buf, sizeof (buf), "%s%s", NONULL(s->prefix), Quotebuf);
1326
1327       state_puts (buf, s);
1328     }
1329   }
1330   else
1331     state_putc (c, s);
1332
1333   if (c == '\n')
1334   {
1335     state_set_prefix (s);
1336     Quotebuf[0] = '\0';
1337   }
1338 }
1339
1340 int state_printf (STATE *s, const char *fmt, ...)
1341 {
1342   int rv;
1343   va_list ap;
1344
1345   va_start (ap, fmt);
1346   rv = vfprintf (s->fpout, fmt, ap);
1347   va_end (ap);
1348   
1349   return rv;
1350 }
1351
1352 void state_mark_attach (STATE *s)
1353 {
1354   if ((s->flags & M_DISPLAY) && !mutt_strcmp (Pager, "builtin"))
1355     state_puts (AttachmentMarker, s);
1356 }
1357
1358 void state_attach_puts (const char *t, STATE *s)
1359 {
1360   if (*t != '\n') state_mark_attach (s);
1361   while (*t)
1362   {
1363     state_putc (*t, s);
1364     if (*t++ == '\n' && *t)
1365       if (*t != '\n') state_mark_attach (s);
1366   }
1367 }
1368
1369 void mutt_display_sanitize (char *s)
1370 {
1371   for (; *s; s++)
1372   {
1373     if (!IsPrint (*s))
1374       *s = '?';
1375   }
1376 }
1377       
1378 void mutt_sleep (short s)
1379 {
1380   if (SleepTime > s)
1381     sleep (SleepTime);
1382   else if (s)
1383     sleep (s);
1384 }
1385
1386 /*
1387  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1388  * just initializes. Frees anything already in the buffer.
1389  *
1390  * Disregards the 'destroy' flag, which seems reserved for caller.
1391  * This is bad, but there's no apparent protocol for it.
1392  */
1393 BUFFER * mutt_buffer_init(BUFFER *b)
1394 {
1395   if (!b)
1396   {
1397     b = safe_malloc(sizeof(BUFFER));
1398     if (!b)
1399       return NULL;
1400   }
1401   else
1402   {
1403     safe_free(b->data);
1404   }
1405   memset(b, 0, sizeof(BUFFER));
1406   return b;
1407 }
1408
1409 /*
1410  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1411  * just initializes. Frees anything already in the buffer. Copies in
1412  * the seed string.
1413  *
1414  * Disregards the 'destroy' flag, which seems reserved for caller.
1415  * This is bad, but there's no apparent protocol for it.
1416  */
1417 BUFFER * mutt_buffer_from(BUFFER *b, char *seed)
1418 {
1419   if (!seed)
1420     return NULL;
1421
1422   b = mutt_buffer_init(b);
1423   b->data = safe_strdup (seed);
1424   b->dsize = mutt_strlen (seed);
1425   b->dptr = (char *) b->data + b->dsize;
1426   return b;
1427 }
1428
1429 void mutt_buffer_addstr (BUFFER* buf, const char* s)
1430 {
1431   mutt_buffer_add (buf, s, mutt_strlen (s));
1432 }
1433
1434 void mutt_buffer_addch (BUFFER* buf, char c)
1435 {
1436   mutt_buffer_add (buf, &c, 1);
1437 }
1438
1439 void mutt_buffer_free (BUFFER **p)
1440 {
1441   if (!p || !*p) 
1442     return;
1443
1444    FREE(&(*p)->data);
1445    /* dptr is just an offset to data and shouldn't be freed */
1446    FREE(p);
1447 }
1448
1449 /* dynamically grows a BUFFER to accomodate s, in increments of 128 bytes.
1450  * Always one byte bigger than necessary for the null terminator, and
1451  * the buffer is always null-terminated */
1452 void mutt_buffer_add (BUFFER* buf, const char* s, size_t len)
1453 {
1454   size_t offset;
1455
1456   if (buf->dptr + len + 1 > buf->data + buf->dsize)
1457   {
1458     offset = buf->dptr - buf->data;
1459     buf->dsize += len < 128 ? 128 : len + 1;
1460     safe_realloc ((void**) &buf->data, buf->dsize);
1461     buf->dptr = buf->data + offset;
1462   }
1463   memcpy (buf->dptr, s, len);
1464   buf->dptr += len;
1465   *(buf->dptr) = '\0';
1466 }
1467
1468 /* Decrease a file's modification time by 1 second */
1469
1470 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1471 {
1472   struct utimbuf utim;
1473   struct stat _st;
1474   time_t mtime;
1475   
1476   if (!st)
1477   {
1478     if (stat (f, &_st) == -1)
1479       return -1;
1480     st = &_st;
1481   }
1482
1483   if ((mtime = st->st_mtime) == time (NULL))
1484   {
1485     mtime -= 1;
1486     utim.actime = mtime;
1487     utim.modtime = mtime;
1488     utime (f, &utim);
1489   }
1490   
1491   return mtime;
1492 }
1493
1494 const char *mutt_make_version (void)
1495 {
1496   static char vstring[STRING];
1497   snprintf (vstring, sizeof (vstring), "Mutt-ng %s (%s)",
1498             MUTT_VERSION, ReleaseDate);
1499   return vstring;
1500 }
1501
1502 REGEXP *mutt_compile_regexp (const char *s, int flags)
1503 {
1504   REGEXP *pp = safe_calloc (sizeof (REGEXP), 1);
1505   pp->pattern = safe_strdup (s);
1506   pp->rx = safe_calloc (sizeof (regex_t), 1);
1507   if (REGCOMP (pp->rx, NONULL(s), flags) != 0)
1508     mutt_free_regexp (&pp);
1509
1510   return pp;
1511 }
1512
1513 void mutt_free_regexp (REGEXP **pp)
1514 {
1515   FREE (&(*pp)->pattern);
1516   regfree ((*pp)->rx);
1517   FREE (&(*pp)->rx);
1518   FREE (pp);
1519 }
1520
1521 void mutt_free_rx_list (RX_LIST **list)
1522 {
1523   RX_LIST *p;
1524   
1525   if (!list) return;
1526   while (*list)
1527   {
1528     p = *list;
1529     *list = (*list)->next;
1530     mutt_free_regexp (&p->rx);
1531     FREE (&p);
1532   }
1533 }
1534
1535 void mutt_free_spam_list (SPAM_LIST **list)
1536 {
1537   SPAM_LIST *p;
1538   
1539   if (!list) return;
1540   while (*list)
1541   {
1542     p = *list;
1543     *list = (*list)->next;
1544     mutt_free_regexp (&p->rx);
1545     safe_free(&p->template);
1546     FREE (&p);
1547   }
1548 }
1549
1550 int mutt_match_rx_list (const char *s, RX_LIST *l)
1551 {
1552   if (!s)  return 0;
1553   
1554   for (; l; l = l->next)
1555   {
1556     if (regexec (l->rx->rx, s, (size_t) 0, (regmatch_t *) 0, (int) 0) == 0)
1557     {
1558       dprint (5, (debugfile, "mutt_match_rx_list: %s matches %s\n", s, l->rx->pattern));
1559       return 1;
1560     }
1561   }
1562
1563   return 0;
1564 }
1565
1566 int mutt_match_spam_list (const char *s, SPAM_LIST *l, char *text, int x)
1567 {
1568   static regmatch_t *pmatch = NULL;
1569   static int nmatch = 0;
1570   int i, n, tlen;
1571   char *p;
1572
1573   if (!s)  return 0;
1574
1575   tlen = 0;
1576
1577   for (; l; l = l->next)
1578   {
1579     /* If this pattern needs more matches, expand pmatch. */
1580     if (l->nmatch > nmatch)
1581     {
1582       safe_realloc (&pmatch, l->nmatch * sizeof(regmatch_t));
1583       nmatch = l->nmatch;
1584     }
1585
1586     /* Does this pattern match? */
1587     if (regexec (l->rx->rx, s, (size_t) l->nmatch, (regmatch_t *) pmatch, (int) 0) == 0)
1588     {
1589       dprint (5, (debugfile, "mutt_match_spam_list: %s matches %s\n", s, l->rx->pattern));
1590       dprint (5, (debugfile, "mutt_match_spam_list: %d subs\n", l->rx->rx->re_nsub));
1591
1592       /* Copy template into text, with substitutions. */
1593       for (p = l->template; *p;)
1594       {
1595         if (*p == '%')
1596         {
1597           n = atoi(++p);                        /* find pmatch index */
1598           while (isdigit(*p))
1599             ++p;                                /* skip subst token */
1600           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
1601             text[tlen++] = s[i];
1602         }
1603         else
1604         {
1605           text[tlen++] = *p++;
1606         }
1607       }
1608       text[tlen] = '\0';
1609       dprint (5, (debugfile, "mutt_match_spam_list: \"%s\"\n", text));
1610       return 1;
1611     }
1612   }
1613
1614   return 0;
1615 }