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