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