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       case '^':
460       {
461         strfcpy (p, NONULL(CurrentFolder), sizeof (p));
462         tail = s + 1;
463       }
464       break;
465  
466       default:
467       {
468         *p = '\0';
469         tail = s;
470       }
471     }
472
473     if (rx && *p && !recurse)
474     {
475       mutt_rx_sanitize_string (q, sizeof (q), p);
476       snprintf (tmp, sizeof (tmp), "%s%s", q, tail);
477     }
478     else
479       snprintf (tmp, sizeof (tmp), "%s%s", p, tail);
480     
481     strfcpy (s, tmp, slen);
482   }
483   while (recurse);
484
485 #ifdef USE_IMAP
486   /* Rewrite IMAP path in canonical form - aids in string comparisons of
487    * folders. May possibly fail, in which case s should be the same. */
488   if (mx_is_imap (s))
489     imap_expand_path (s, slen);
490 #endif
491
492   return (s);
493 }
494
495 /* Extract the real name from /etc/passwd's GECOS field.
496  * When set, honor the regular expression in GecosMask,
497  * otherwise assume that the GECOS field is a 
498  * comma-separated list.
499  * Replace "&" by a capitalized version of the user's login
500  * name.
501  */
502
503 char *mutt_gecos_name (char *dest, size_t destlen, struct passwd *pw)
504 {
505   regmatch_t pat_match[1];
506   size_t pwnl;
507   int idx;
508   char *p;
509   
510   if (!pw || !pw->pw_gecos) 
511     return NULL;
512
513   memset (dest, 0, destlen);
514   
515   if (GecosMask.rx)
516   {
517     if (regexec (GecosMask.rx, pw->pw_gecos, 1, pat_match, 0) == 0)
518       strfcpy (dest, pw->pw_gecos + pat_match[0].rm_so, 
519                MIN (pat_match[0].rm_eo - pat_match[0].rm_so + 1, destlen));
520   }
521   else if ((p = strchr (pw->pw_gecos, ',')))
522     strfcpy (dest, pw->pw_gecos, MIN (destlen, p - pw->pw_gecos + 1));
523   else
524     strfcpy (dest, pw->pw_gecos, destlen);
525
526   pwnl = strlen (pw->pw_name);
527
528   for (idx = 0; dest[idx]; idx++)
529   {
530     if (dest[idx] == '&')
531     {
532       memmove (&dest[idx + pwnl], &dest[idx + 1],
533                MAX(destlen - idx - pwnl - 1, 0));
534       memcpy (&dest[idx], pw->pw_name, MIN(destlen - idx - 1, pwnl));
535       dest[idx] = toupper ((unsigned char) dest[idx]);
536     }
537   }
538       
539   return dest;
540 }
541   
542
543 char *mutt_get_parameter (const char *s, PARAMETER *p)
544 {
545   for (; p; p = p->next)
546     if (ascii_strcasecmp (s, p->attribute) == 0)
547       return (p->value);
548
549   return NULL;
550 }
551
552 void mutt_set_parameter (const char *attribute, const char *value, PARAMETER **p)
553 {
554   PARAMETER *q;
555
556   if (!value)
557   {
558     mutt_delete_parameter (attribute, p);
559     return;
560   }
561   
562   for(q = *p; q; q = q->next)
563   {
564     if (ascii_strcasecmp (attribute, q->attribute) == 0)
565     {
566       mutt_str_replace (&q->value, value);
567       return;
568     }
569   }
570   
571   q = mutt_new_parameter();
572   q->attribute = safe_strdup(attribute);
573   q->value = safe_strdup(value);
574   q->next = *p;
575   *p = q;
576 }
577
578 void mutt_delete_parameter (const char *attribute, PARAMETER **p)
579 {
580   PARAMETER *q;
581   
582   for (q = *p; q; p = &q->next, q = q->next)
583   {
584     if (ascii_strcasecmp (attribute, q->attribute) == 0)
585     {
586       *p = q->next;
587       q->next = NULL;
588       mutt_free_parameter (&q);
589       return;
590     }
591   }
592 }
593
594 /* returns 1 if Mutt can't display this type of data, 0 otherwise */
595 int mutt_needs_mailcap (BODY *m)
596 {
597   switch (m->type)
598   {
599     case TYPETEXT:
600
601       if (!ascii_strcasecmp ("plain", m->subtype) ||
602           !ascii_strcasecmp ("rfc822-headers", m->subtype) ||
603           !ascii_strcasecmp ("enriched", m->subtype))
604         return 0;
605       break;
606
607     case TYPEAPPLICATION:
608       if((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp(m))
609         return 0;
610       if((WithCrypto & APPLICATION_SMIME) && mutt_is_application_smime(m))
611         return 0;
612       break;
613
614     case TYPEMULTIPART:
615     case TYPEMESSAGE:
616       return 0;
617   }
618
619   return 1;
620 }
621
622 int mutt_is_text_part (BODY *b)
623 {
624   int t = b->type;
625   char *s = b->subtype;
626   
627   if ((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp (b))
628     return 0;
629
630   if (t == TYPETEXT)
631     return 1;
632
633   if (t == TYPEMESSAGE)
634   {
635     if (!ascii_strcasecmp ("delivery-status", s))
636       return 1;
637   }
638
639   if ((WithCrypto & APPLICATION_PGP) && t == TYPEAPPLICATION)
640   {
641     if (!ascii_strcasecmp ("pgp-keys", s))
642       return 1;
643   }
644
645   return 0;
646 }
647
648 void mutt_free_envelope (ENVELOPE **p)
649 {
650   if (!*p) return;
651   rfc822_free_address (&(*p)->return_path);
652   rfc822_free_address (&(*p)->from);
653   rfc822_free_address (&(*p)->to);
654   rfc822_free_address (&(*p)->cc);
655   rfc822_free_address (&(*p)->bcc);
656   rfc822_free_address (&(*p)->sender);
657   rfc822_free_address (&(*p)->reply_to);
658   rfc822_free_address (&(*p)->mail_followup_to);
659
660   FREE (&(*p)->list_post);
661   FREE (&(*p)->subject);
662   /* real_subj is just an offset to subject and shouldn't be freed */
663   FREE (&(*p)->message_id);
664   FREE (&(*p)->supersedes);
665   FREE (&(*p)->date);
666   FREE (&(*p)->x_label);
667   FREE (&(*p)->organization);
668 #ifdef USE_NNTP
669   FREE (&(*p)->newsgroups);
670   FREE (&(*p)->xref);
671   FREE (&(*p)->followup_to);
672   FREE (&(*p)->x_comment_to);
673 #endif
674
675   mutt_buffer_free (&(*p)->spam);
676   mutt_free_list (&(*p)->references);
677   mutt_free_list (&(*p)->in_reply_to);
678   mutt_free_list (&(*p)->userhdrs);
679   FREE (p);
680 }
681
682 void _mutt_mktemp (char *s, const char *src, int line)
683 {
684   snprintf (s, _POSIX_PATH_MAX, "%s/mutt-%s-%d-%d-%d", NONULL (Tempdir), NONULL(Hostname), (int) getuid(), (int) getpid (), Counter++);
685   dprint (1, (debugfile, "%s:%d: mutt_mktemp returns \"%s\".\n", src, line, s));
686   unlink (s);
687 }
688
689 void mutt_free_alias (ALIAS **p)
690 {
691   ALIAS *t;
692
693   while (*p)
694   {
695     t = *p;
696     *p = (*p)->next;
697     FREE (&t->name);
698     rfc822_free_address (&t->addr);
699     FREE (&t);
700   }
701 }
702
703 /* collapse the pathname using ~ or = when possible */
704 void mutt_pretty_mailbox (char *s)
705 {
706   char *p = s, *q = s;
707   size_t len;
708   url_scheme_t scheme;
709
710   scheme = url_check_scheme (s);
711
712 #ifdef USE_IMAP
713   if (scheme == U_IMAP || scheme == U_IMAPS)
714   {
715     imap_pretty_mailbox (s);
716     return;
717   }
718 #endif
719
720   /* if s is an url, only collapse path component */
721   if (scheme != U_UNKNOWN)
722   {
723     p = strchr(s, ':')+1;
724     if (!strncmp (p, "//", 2))
725       q = strchr (p+2, '/');
726     if (!q)
727       q = strchr (p, '\0');
728     p = q;
729   }
730   
731   /* first attempt to collapse the pathname */
732   while (*p)
733   {
734     if (*p == '/' && p[1] == '/')
735     {
736       *q++ = '/';
737       p += 2;
738     }
739     else if (p[0] == '/' && p[1] == '.' && p[2] == '/')
740     {
741       *q++ = '/';
742       p += 3;
743     }
744     else
745       *q++ = *p++;
746   }
747   *q = 0;
748
749   if (mutt_strncmp (s, Maildir, (len = mutt_strlen (Maildir))) == 0 &&
750       s[len] == '/')
751   {
752     *s++ = '=';
753     memmove (s, s + len, mutt_strlen (s + len) + 1);
754   }
755   else if (mutt_strncmp (s, Homedir, (len = mutt_strlen (Homedir))) == 0 &&
756            s[len] == '/')
757   {
758     *s++ = '~';
759     memmove (s, s + len - 1, mutt_strlen (s + len - 1) + 1);
760   }
761 }
762
763 void mutt_pretty_size (char *s, size_t len, long n)
764 {
765   if (n == 0)
766     strfcpy (s, "0K", len);
767   else if (n < 10189) /* 0.1K - 9.9K */
768     snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
769   else if (n < 1023949) /* 10K - 999K */
770   {
771     /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
772     snprintf (s, len, "%ldK", (n + 51) / 1024);
773   }
774   else if (n < 10433332) /* 1.0M - 9.9M */
775     snprintf (s, len, "%3.1fM", n / 1048576.0);
776   else /* 10M+ */
777   {
778     /* (10433332 + 52428) / 1048576 = 10 */
779     snprintf (s, len, "%ldM", (n + 52428) / 1048576);
780   }
781 }
782
783 void mutt_expand_file_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
784 {
785   char tmp[LONG_STRING];
786   
787   mutt_quote_filename (tmp, sizeof (tmp), src);
788   mutt_expand_fmt (dest, destlen, fmt, tmp);
789 }
790
791 void mutt_expand_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
792 {
793   const char *p;
794   char *d;
795   size_t slen;
796   int found = 0;
797
798   slen = mutt_strlen (src);
799   destlen--;
800   
801   for (p = fmt, d = dest; destlen && *p; p++)
802   {
803     if (*p == '%') 
804     {
805       switch (p[1])
806       {
807         case '%':
808           *d++ = *p++;
809           destlen--;
810           break;
811         case 's':
812           found = 1;
813           strfcpy (d, src, destlen + 1);
814           d       += destlen > slen ? slen : destlen;
815           destlen -= destlen > slen ? slen : destlen;
816           p++;
817           break;
818         default:
819           *d++ = *p; 
820           destlen--;
821           break;
822       }
823     }
824     else
825     {
826       *d++ = *p;
827       destlen--;
828     }
829   }
830   
831   *d = '\0';
832   
833   if (!found && destlen > 0)
834   {
835     safe_strcat (dest, destlen, " ");
836     safe_strcat (dest, destlen, src);
837   }
838   
839 }
840
841 /* return 0 on success, -1 on abort, 1 on error */
842 int mutt_check_overwrite (const char *attname, const char *path,
843                                 char *fname, size_t flen, int *append, char **directory) 
844 {
845   int rc = 0;
846   char tmp[_POSIX_PATH_MAX];
847   struct stat st;
848
849   strfcpy (fname, path, flen);
850   if (access (fname, F_OK) != 0)
851     return 0;
852   if (stat (fname, &st) != 0)
853     return -1;
854   if (S_ISDIR (st.st_mode))
855   {
856     if (directory)
857     {
858       switch (mutt_multi_choice
859               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"), _("yna")))
860       {
861         case 3:         /* all */
862           mutt_str_replace (directory, fname);
863           break;
864         case 1:         /* yes */
865           FREE (directory);
866           break;
867         case -1:        /* abort */
868           FREE (directory); 
869           return -1;
870         case  2:        /* no */
871           FREE (directory);
872           return 1;
873       }
874     }
875     else if ((rc = mutt_yesorno (_("File is a directory, save under it?"), M_YES)) != M_YES)
876       return (rc == M_NO) ? 1 : -1;
877
878     if (!attname || !attname[0])
879     {
880       tmp[0] = 0;
881       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
882                                       M_FILE | M_CLEAR) != 0 || !tmp[0])
883         return (-1);
884       mutt_concat_path (fname, path, tmp, flen);
885     }
886     else
887       mutt_concat_path (fname, path, mutt_basename (attname), flen);
888   }
889   
890   if (*append == 0 && access (fname, F_OK) == 0)
891   {
892     switch (mutt_multi_choice
893             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
894     {
895       case -1: /* abort */
896         return -1;
897       case 3:  /* cancel */
898         return 1;
899
900       case 2: /* append */
901         *append = M_SAVE_APPEND;
902         break;
903       case 1: /* overwrite */
904         *append = M_SAVE_OVERWRITE;
905         break;
906     }
907   }
908   return 0;
909 }
910
911 void mutt_save_path (char *d, size_t dsize, ADDRESS *a)
912 {
913   if (a && a->mailbox)
914   {
915     strfcpy (d, a->mailbox, dsize);
916     if (!option (OPTSAVEADDRESS))
917     {
918       char *p;
919
920       if ((p = strpbrk (d, "%@")))
921         *p = 0;
922     }
923     mutt_strlower (d);
924   }
925   else
926     *d = 0;
927 }
928
929 void mutt_safe_path (char *s, size_t l, ADDRESS *a)
930 {
931   char *p;
932
933   mutt_save_path (s, l, a);
934   for (p = s; *p; p++)
935     if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
936       *p = '_';
937 }
938
939 /* counts how many characters in s can be skipped while none of the
940  * characters of c appears */
941 int mutt_skipchars (const char* s, const char* c) {
942   int ret = 0;
943   const char* p = s;
944   while (s && *s) {
945     register const char* t = c;
946     while (t && *t) {
947       if (*t == *s)
948         return (ret);
949       t++;
950     }
951     ret++;
952     s++;
953   }
954   return (mutt_strlen (p));
955 }
956
957 void mutt_FormatString (char *dest,             /* output buffer */
958                         size_t destlen,         /* output buffer len */
959                         const char *src,        /* template string */
960                         format_t *callback,     /* callback for processing */
961                         unsigned long data,     /* callback data */
962                         format_flag flags)      /* callback flags */
963 {
964   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
965   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
966   size_t wlen, count, len, col, wid;
967
968   prefix[0] = '\0';
969   destlen--; /* save room for the terminal \0 */
970   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
971   col = wlen;
972     
973   while (*src && wlen < destlen)
974   {
975     if (*src == '%')
976     {
977       if (*++src == '%')
978       {
979         *wptr++ = '%';
980         wlen++;
981         col++;
982         src++;
983         continue;
984       }
985
986       if (*src == '?')
987       {
988         flags |= M_FORMAT_OPTIONAL;
989         src++;
990       }
991       else
992       {
993         flags &= ~M_FORMAT_OPTIONAL;
994
995         /* eat the format string */
996         cp = prefix;
997         count = 0;
998         while (count < sizeof (prefix) &&
999                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
1000         {
1001           *cp++ = *src++;
1002           count++;
1003         }
1004         *cp = 0;
1005       }
1006
1007       if (!*src)
1008         break; /* bad format */
1009
1010       ch = *src++; /* save the character to switch on */
1011
1012       if (flags & M_FORMAT_OPTIONAL)
1013       {
1014         if (*src != '?')
1015           break; /* bad format */
1016         src++;
1017
1018         /* eat the `if' part of the string */
1019         cp = ifstring;
1020         count = 0;
1021         while (count < sizeof (ifstring) && *src && *src != '?' && *src != '&')
1022         {
1023           *cp++ = *src++;
1024           count++;
1025         }
1026         *cp = 0;
1027
1028         /* eat the `else' part of the string (optional) */
1029         if (*src == '&')
1030           src++; /* skip the & */
1031         cp = elsestring;
1032         count = 0;
1033         while (count < sizeof (elsestring) && *src && *src != '?')
1034         {
1035           *cp++ = *src++;
1036           count++;
1037         }
1038         *cp = 0;
1039
1040         if (!*src)
1041           break; /* bad format */
1042
1043         src++; /* move past the trailing `?' */
1044       }
1045
1046       /* handle generic cases first */
1047       if (ch == '>')
1048       {
1049         /* right justify to EOL */
1050         ch = *src++; /* pad char */
1051         /* calculate space left on line.  if we've already written more data
1052            than will fit on the line, ignore the rest of the line */
1053         if ( DrawFullLine  || option(OPTSTATUSONTOP))
1054           count = (COLS < destlen ? COLS : destlen);
1055         else
1056           count = ((COLS-SidebarWidth) < destlen ? (COLS - SidebarWidth) : destlen);
1057         if (count > col)
1058         {
1059           count -= col; /* how many columns left on this line */
1060           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
1061           wid = mutt_strlen (buf);
1062           if (count > wid)
1063           {
1064             count -= wid; /* how many chars to pad */
1065             memset (wptr, ch, count);
1066             wptr += count;
1067             col += count;
1068           }
1069           if (wid + wlen > destlen)
1070             len = destlen - wlen;
1071     else
1072       len = wid;
1073           memcpy (wptr, buf, len);
1074           wptr += len;
1075           wlen += len;
1076           col += mutt_strwidth (buf);
1077         }
1078         break; /* skip rest of input */
1079       }
1080       else if (ch == '|')
1081       {
1082         /* pad to EOL */
1083         ch = *src++;
1084         if (destlen > COLS)
1085           destlen = COLS;
1086         if (destlen > wlen)
1087         {
1088           count = destlen - wlen;
1089           memset (wptr, ch, count);
1090           wptr += count;
1091         }
1092         break; /* skip rest of input */
1093       }
1094       else
1095       {
1096         short tolower =  0;
1097         short nodots  = 0;
1098         
1099         while (ch == '_' || ch == ':') 
1100         {
1101           if (ch == '_')
1102             tolower = 1;
1103           else if (ch == ':') 
1104             nodots = 1;
1105           
1106           ch = *src++;
1107         }
1108         
1109         /* use callback function to handle this case */
1110         src = callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring, data, flags);
1111
1112         if (tolower)
1113           mutt_strlower (buf);
1114         if (nodots) 
1115         {
1116           char *p = buf;
1117           for (; *p; p++)
1118             if (*p == '.')
1119                 *p = '_';
1120         }
1121         
1122         if ((len = mutt_strlen (buf)) + wlen > destlen)
1123           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
1124
1125         memcpy (wptr, buf, len);
1126         wptr += len;
1127         wlen += len;
1128         col += mutt_strwidth (buf);
1129       }
1130     }
1131     else if (*src == '\\')
1132     {
1133       if (!*++src)
1134         break;
1135       switch (*src)
1136       {
1137         case 'n':
1138           *wptr = '\n';
1139           break;
1140         case 't':
1141           *wptr = '\t';
1142           break;
1143         case 'r':
1144           *wptr = '\r';
1145           break;
1146         case 'f':
1147           *wptr = '\f';
1148           break;
1149         case 'v':
1150           *wptr = '\v';
1151           break;
1152         default:
1153           *wptr = *src;
1154           break;
1155       }
1156       src++;
1157       wptr++;
1158       wlen++;
1159       col++;
1160     }
1161     else
1162     {
1163       unsigned int bar = mutt_skipchars (src, "%\\");
1164       char* bar2 = safe_malloc (bar+1);
1165       strfcpy (bar2, src, bar+1);
1166       while (bar--) {
1167         *wptr++ = *src++;
1168         wlen++;
1169       }
1170       col += mutt_strwidth (bar2);
1171       FREE(&bar2);
1172     }
1173   }
1174   *wptr = 0;
1175
1176 #if 0
1177   if (flags & M_FORMAT_MAKEPRINT)
1178   {
1179     /* Make sure that the string is printable by changing all non-printable
1180        chars to dots, or spaces for non-printable whitespace */
1181     for (cp = dest ; *cp ; cp++)
1182       if (!IsPrint (*cp) &&
1183           !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
1184         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
1185   }
1186 #endif
1187 }
1188
1189 /* This function allows the user to specify a command to read stdout from in
1190    place of a normal file.  If the last character in the string is a pipe (|),
1191    then we assume it is a commmand to run instead of a normal file. */
1192 FILE *mutt_open_read (const char *path, pid_t *thepid)
1193 {
1194   FILE *f;
1195   struct stat s;
1196
1197   int len = mutt_strlen (path);
1198
1199   if (path[len - 1] == '|')
1200   {
1201     /* read from a pipe */
1202
1203     char *s = safe_strdup (path);
1204
1205     s[len - 1] = 0;
1206     mutt_endwin (NULL);
1207     *thepid = mutt_create_filter (s, NULL, &f, NULL);
1208     FREE (&s);
1209   }
1210   else
1211   {
1212     if (stat (path, &s) < 0)
1213       return (NULL);
1214     if (S_ISDIR (s.st_mode))
1215     {
1216       errno = EINVAL;
1217       return (NULL);
1218     }
1219     f = fopen (path, "r");
1220     *thepid = -1;
1221   }
1222   return (f);
1223 }
1224
1225 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1226 int mutt_save_confirm (const char *s, struct stat *st)
1227 {
1228   char tmp[_POSIX_PATH_MAX];
1229   int ret = 0;
1230   int rc;
1231   int magic = 0;
1232
1233   magic = mx_get_magic (s);
1234
1235 #ifdef USE_POP
1236   if (magic == M_POP)
1237   {
1238     mutt_error _("Can't save message to POP mailbox.");
1239     return 1;
1240   }
1241 #endif
1242
1243 #ifdef USE_NNTP
1244   if (magic == M_NNTP)
1245   {
1246     mutt_error _("Can't save message to newsserver.");
1247     return 0;
1248   }
1249 #endif
1250
1251   if (stat (s, st) != -1)
1252   {
1253     if (magic == -1)
1254     {
1255       mutt_error (_("%s is not a mailbox!"), s);
1256       return 1;
1257     }
1258
1259     if (option (OPTCONFIRMAPPEND) &&
1260         (!TrashPath || (mutt_strcmp (s, TrashPath) != 0)))
1261       /* if we're appending to the trash, there's no point in asking */
1262     {
1263       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1264       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1265         ret = 1;
1266       else if (rc == -1)
1267         ret = -1;
1268     }
1269   }
1270   else
1271   {
1272 #ifdef USE_IMAP
1273     if (magic != M_IMAP)
1274 #endif /* execute the block unconditionally if we don't use imap */
1275     {
1276       st->st_mtime = 0;
1277       st->st_atime = 0;
1278
1279       if (errno == ENOENT)
1280       {
1281         if (option (OPTCONFIRMCREATE))
1282         {
1283           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1284           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1285             ret = 1;
1286           else if (rc == -1)
1287             ret = -1;
1288         }
1289       }
1290       else
1291       {
1292         mutt_perror (s);
1293         return 1;
1294       }
1295     }
1296   }
1297
1298   CLEARLINE (LINES-1);
1299   return (ret);
1300 }
1301
1302 void state_prefix_putc (char c, STATE *s)
1303 {
1304   if (s->flags & M_PENDINGPREFIX)
1305   {
1306     int i;
1307
1308     i = strlen (Quotebuf);
1309     Quotebuf[i++] = c;
1310     Quotebuf[i] = '\0';
1311     if (i == sizeof (Quotebuf) - 1 || c == '\n')
1312     {
1313       char buf[2 * SHORT_STRING];
1314       int j = 0, offset = 0;
1315       regmatch_t pmatch[1];
1316
1317       state_reset_prefix (s);
1318       while (regexec ((regex_t *) QuoteRegexp.rx, &Quotebuf[offset], 1, pmatch, 0) == 0)
1319         offset += pmatch->rm_eo;
1320
1321       if (!option (OPTQUOTEEMPTY) && Quotebuf[offset] == '\n') {
1322         buf[0] = '\n';
1323         buf[1] = '\0';
1324       }
1325       else if (option (OPTQUOTEQUOTED) && offset)
1326       {
1327         for (i = 0; i < offset; i++)
1328           if (Quotebuf[i] != ' ')
1329             j = i;
1330         strncpy (buf, Quotebuf, j + 1);
1331         strcpy (buf + j + 1, Quotebuf + j);
1332       }
1333       else
1334         snprintf (buf, sizeof (buf), "%s%s", NONULL(s->prefix), Quotebuf);
1335
1336       state_puts (buf, s);
1337     }
1338   }
1339   else
1340     state_putc (c, s);
1341
1342   if (c == '\n')
1343   {
1344     state_set_prefix (s);
1345     Quotebuf[0] = '\0';
1346   }
1347 }
1348
1349 int state_printf (STATE *s, const char *fmt, ...)
1350 {
1351   int rv;
1352   va_list ap;
1353
1354   va_start (ap, fmt);
1355   rv = vfprintf (s->fpout, fmt, ap);
1356   va_end (ap);
1357   
1358   return rv;
1359 }
1360
1361 void state_mark_attach (STATE *s)
1362 {
1363   if ((s->flags & M_DISPLAY) && !mutt_strcmp (Pager, "builtin"))
1364     state_puts (AttachmentMarker, s);
1365 }
1366
1367 void state_attach_puts (const char *t, STATE *s)
1368 {
1369   if (*t != '\n') state_mark_attach (s);
1370   while (*t)
1371   {
1372     state_putc (*t, s);
1373     if (*t++ == '\n' && *t)
1374       if (*t != '\n') state_mark_attach (s);
1375   }
1376 }
1377
1378 void mutt_display_sanitize (char *s)
1379 {
1380   for (; *s; s++)
1381   {
1382     if (!IsPrint (*s))
1383       *s = '?';
1384   }
1385 }
1386       
1387 void mutt_sleep (short s)
1388 {
1389   if (SleepTime > s)
1390     sleep (SleepTime);
1391   else if (s)
1392     sleep (s);
1393 }
1394
1395 /*
1396  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1397  * just initializes. Frees anything already in the buffer.
1398  *
1399  * Disregards the 'destroy' flag, which seems reserved for caller.
1400  * This is bad, but there's no apparent protocol for it.
1401  */
1402 BUFFER * mutt_buffer_init(BUFFER *b)
1403 {
1404   if (!b)
1405   {
1406     b = safe_malloc(sizeof(BUFFER));
1407     if (!b)
1408       return NULL;
1409   }
1410   else
1411   {
1412     safe_free(b->data);
1413   }
1414   memset(b, 0, sizeof(BUFFER));
1415   return b;
1416 }
1417
1418 /*
1419  * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1420  * just initializes. Frees anything already in the buffer. Copies in
1421  * the seed string.
1422  *
1423  * Disregards the 'destroy' flag, which seems reserved for caller.
1424  * This is bad, but there's no apparent protocol for it.
1425  */
1426 BUFFER * mutt_buffer_from(BUFFER *b, char *seed)
1427 {
1428   if (!seed)
1429     return NULL;
1430
1431   b = mutt_buffer_init(b);
1432   b->data = safe_strdup (seed);
1433   b->dsize = mutt_strlen (seed);
1434   b->dptr = (char *) b->data + b->dsize;
1435   return b;
1436 }
1437
1438 void mutt_buffer_addstr (BUFFER* buf, const char* s)
1439 {
1440   mutt_buffer_add (buf, s, mutt_strlen (s));
1441 }
1442
1443 void mutt_buffer_addch (BUFFER* buf, char c)
1444 {
1445   mutt_buffer_add (buf, &c, 1);
1446 }
1447
1448 void mutt_buffer_free (BUFFER **p)
1449 {
1450   if (!p || !*p) 
1451     return;
1452
1453    FREE(&(*p)->data);
1454    /* dptr is just an offset to data and shouldn't be freed */
1455    FREE(p);
1456 }
1457
1458 /* dynamically grows a BUFFER to accomodate s, in increments of 128 bytes.
1459  * Always one byte bigger than necessary for the null terminator, and
1460  * the buffer is always null-terminated */
1461 void mutt_buffer_add (BUFFER* buf, const char* s, size_t len)
1462 {
1463   size_t offset;
1464
1465   if (buf->dptr + len + 1 > buf->data + buf->dsize)
1466   {
1467     offset = buf->dptr - buf->data;
1468     buf->dsize += len < 128 ? 128 : len + 1;
1469     safe_realloc ((void**) &buf->data, buf->dsize);
1470     buf->dptr = buf->data + offset;
1471   }
1472   memcpy (buf->dptr, s, len);
1473   buf->dptr += len;
1474   *(buf->dptr) = '\0';
1475 }
1476
1477 /* Decrease a file's modification time by 1 second */
1478
1479 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1480 {
1481   struct utimbuf utim;
1482   struct stat _st;
1483   time_t mtime;
1484   
1485   if (!st)
1486   {
1487     if (stat (f, &_st) == -1)
1488       return -1;
1489     st = &_st;
1490   }
1491
1492   if ((mtime = st->st_mtime) == time (NULL))
1493   {
1494     mtime -= 1;
1495     utim.actime = mtime;
1496     utim.modtime = mtime;
1497     utime (f, &utim);
1498   }
1499   
1500   return mtime;
1501 }
1502
1503 const char *mutt_make_version (void)
1504 {
1505   static char vstring[STRING];
1506   snprintf (vstring, sizeof (vstring), "Mutt-ng %s (%s)",
1507             MUTT_VERSION, ReleaseDate);
1508   return vstring;
1509 }
1510
1511 REGEXP *mutt_compile_regexp (const char *s, int flags)
1512 {
1513   REGEXP *pp = safe_calloc (sizeof (REGEXP), 1);
1514   pp->pattern = safe_strdup (s);
1515   pp->rx = safe_calloc (sizeof (regex_t), 1);
1516   if (REGCOMP (pp->rx, NONULL(s), flags) != 0)
1517     mutt_free_regexp (&pp);
1518
1519   return pp;
1520 }
1521
1522 void mutt_free_regexp (REGEXP **pp)
1523 {
1524   FREE (&(*pp)->pattern);
1525   regfree ((*pp)->rx);
1526   FREE (&(*pp)->rx);
1527   FREE (pp);
1528 }
1529
1530 void mutt_free_rx_list (RX_LIST **list)
1531 {
1532   RX_LIST *p;
1533   
1534   if (!list) return;
1535   while (*list)
1536   {
1537     p = *list;
1538     *list = (*list)->next;
1539     mutt_free_regexp (&p->rx);
1540     FREE (&p);
1541   }
1542 }
1543
1544 void mutt_free_spam_list (SPAM_LIST **list)
1545 {
1546   SPAM_LIST *p;
1547   
1548   if (!list) return;
1549   while (*list)
1550   {
1551     p = *list;
1552     *list = (*list)->next;
1553     mutt_free_regexp (&p->rx);
1554     safe_free(&p->template);
1555     FREE (&p);
1556   }
1557 }
1558
1559 int mutt_match_rx_list (const char *s, RX_LIST *l)
1560 {
1561   if (!s)  return 0;
1562   
1563   for (; l; l = l->next)
1564   {
1565     if (regexec (l->rx->rx, s, (size_t) 0, (regmatch_t *) 0, (int) 0) == 0)
1566     {
1567       dprint (5, (debugfile, "mutt_match_rx_list: %s matches %s\n", s, l->rx->pattern));
1568       return 1;
1569     }
1570   }
1571
1572   return 0;
1573 }
1574
1575 int mutt_match_spam_list (const char *s, SPAM_LIST *l, char *text, int x)
1576 {
1577   static regmatch_t *pmatch = NULL;
1578   static int nmatch = 0;
1579   int i, n, tlen;
1580   char *p;
1581
1582   if (!s)  return 0;
1583
1584   tlen = 0;
1585
1586   for (; l; l = l->next)
1587   {
1588     /* If this pattern needs more matches, expand pmatch. */
1589     if (l->nmatch > nmatch)
1590     {
1591       safe_realloc (&pmatch, l->nmatch * sizeof(regmatch_t));
1592       nmatch = l->nmatch;
1593     }
1594
1595     /* Does this pattern match? */
1596     if (regexec (l->rx->rx, s, (size_t) l->nmatch, (regmatch_t *) pmatch, (int) 0) == 0)
1597     {
1598       dprint (5, (debugfile, "mutt_match_spam_list: %s matches %s\n", s, l->rx->pattern));
1599       dprint (5, (debugfile, "mutt_match_spam_list: %d subs\n", l->rx->rx->re_nsub));
1600
1601       /* Copy template into text, with substitutions. */
1602       for (p = l->template; *p;)
1603       {
1604         if (*p == '%')
1605         {
1606           n = atoi(++p);                        /* find pmatch index */
1607           while (isdigit(*p))
1608             ++p;                                /* skip subst token */
1609           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
1610             text[tlen++] = s[i];
1611         }
1612         else
1613         {
1614           text[tlen++] = *p++;
1615         }
1616       }
1617       text[tlen] = '\0';
1618       dprint (5, (debugfile, "mutt_match_spam_list: \"%s\"\n", text));
1619       return 1;
1620     }
1621   }
1622
1623   return 0;
1624 }