muttlib.c 46.7 KB
Newer Older
1
/*
2
 * Copyright (C) 1996-2000,2007,2010,2013 Michael R. Elkins <me@mutt.org>
3
 * Copyright (C) 1999-2008 Thomas Roessler <roessler@does-not-exist.org>
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * 
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 * 
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with this program; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */ 

#if HAVE_CONFIG_H
# include "config.h"
#endif
23 24

#include "mutt.h"
25
#include "mutt_curses.h"
26 27
#include "mime.h"
#include "mailbox.h"
28 29
#include "mx.h"
#include "url.h"
30

31
#ifdef USE_IMAP
32
#include "imap.h"
33 34
#endif

35
#include "mutt_crypt.h"
36

37 38 39 40 41 42 43 44 45 46 47
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <sys/types.h>
#include <utime.h>
48

49
BODY *mutt_new_body (void)
50
{
51 52
  BODY *p = (BODY *) safe_calloc (1, sizeof (BODY));
    
53
  p->disposition = DISPATTACH;
54 55
  p->use_disp = 1;
  return (p);
56 57 58 59
}


/* Modified by blong to accept a "suggestion" for file name.  If
60
 * that file exists, then construct one with unique name but 
61 62 63 64
 * keep any extension.  This might fail, I guess.
 * Renamed to mutt_adv_mktemp so I only have to change where it's
 * called, and not all possible cases.
 */
65
void mutt_adv_mktemp (char *s, size_t l)
66
{
67
  char prefix[_POSIX_PATH_MAX];
68
  char *suffix;
69
  struct stat sb;
70

71 72
  if (s[0] == '\0')
  {
73
    mutt_mktemp (s, l);
74 75 76
  }
  else
  {
77 78 79 80
    strfcpy (prefix, s, sizeof (prefix));
    mutt_sanitize_filename (prefix, 1);
    snprintf (s, l, "%s/%s", NONULL (Tempdir), prefix);
    if (lstat (s, &sb) == -1 && errno == ENOENT)
81
      return;
82

83
    if ((suffix = strrchr (prefix, '.')) != NULL)
84
    {
85 86
      *suffix = 0;
      ++suffix;
87
    }
88
    mutt_mktemp_pfx_sfx (s, l, prefix, suffix);
89 90 91 92
  }
}

/* create a send-mode duplicate from a receive-mode body */
93

94 95
int mutt_copy_body (FILE *fp, BODY **tgt, BODY *src)
{
96
  char tmp[_POSIX_PATH_MAX];
97
  BODY *b;
98

99 100 101
  PARAMETER *par, **ppar;
  
  short use_disp;
102 103 104

  if (src->filename)
  {
105 106
    use_disp = 1;
    strfcpy (tmp, src->filename, sizeof (tmp));
107 108 109
  }
  else
  {
110
    use_disp = 0;
111 112 113
    tmp[0] = '\0';
  }

114 115
  mutt_adv_mktemp (tmp, sizeof (tmp));
  if (mutt_save_attachment (fp, src, tmp, 0, NULL) == -1)
116
    return -1;
117 118
      
  *tgt = mutt_new_body ();
119 120
  b = *tgt;

121
  memcpy (b, src, sizeof (BODY));
122
  b->parts = NULL;
123
  b->next  = NULL;
124

125
  b->filename = safe_strdup (tmp);
126
  b->use_disp = use_disp;
127
  b->unlink = 1;
128

129 130
  if (mutt_is_text_part (b))
    b->noconv = 1;
131

132 133 134 135
  b->xtype = safe_strdup (b->xtype);
  b->subtype = safe_strdup (b->subtype);
  b->form_name = safe_strdup (b->form_name);
  b->d_filename = safe_strdup (b->d_filename);
136 137 138
  /* mutt_adv_mktemp() will mangle the filename in tmp,
   * so preserve it in d_filename */
  if (!b->d_filename && use_disp)
139 140
    b->d_filename = safe_strdup (src->filename);
  b->description = safe_strdup (b->description);
141

142 143
  /* 
   * we don't seem to need the HEADER structure currently.
144 145 146
   * XXX - this may change in the future
   */

147 148
  if (b->hdr) b->hdr = NULL;
  
149 150 151
  /* copy parameters */
  for (par = b->parameter, ppar = &b->parameter; par; ppar = &(*ppar)->next, par = par->next)
  {
152 153 154
    *ppar = mutt_new_parameter ();
    (*ppar)->attribute = safe_strdup (par->attribute);
    (*ppar)->value = safe_strdup (par->value);
155 156
  }

157 158
  mutt_stamp_attachment (b);
  
159 160 161 162
  return 0;
}


163 164

void mutt_free_body (BODY **p)
165
{
166
  BODY *a = *p, *b;
167 168 169 170

  while (a)
  {
    b = a;
171
    a = a->next; 
172 173

    if (b->parameter)
174
      mutt_free_parameter (&b->parameter);
175
    if (b->filename)
176
    {
177
      if (b->unlink)
178 179 180
	unlink (b->filename);
      dprint (1, (debugfile, "mutt_free_body: %sunlinking %s.\n",
	    b->unlink ? "" : "not ", b->filename));
181 182
    }

183 184 185 186 187 188 189 190
    FREE (&b->filename);
    FREE (&b->d_filename);
    FREE (&b->charset);
    FREE (&b->content);
    FREE (&b->xtype);
    FREE (&b->subtype);
    FREE (&b->description);
    FREE (&b->form_name);
191 192 193 194 195 196 197 198 199

    if (b->hdr)
    {
      /* Don't free twice (b->hdr->content = b->parts) */
      b->hdr->content = NULL;
      mutt_free_header(&b->hdr);
    }

    if (b->parts)
200
      mutt_free_body (&b->parts);
201

202
    FREE (&b);
203 204 205 206 207
  }

  *p = 0;
}

208
void mutt_free_parameter (PARAMETER **p)
209
{
210 211
  PARAMETER *t = *p;
  PARAMETER *o;
212 213 214

  while (t)
  {
215 216
    FREE (&t->attribute);
    FREE (&t->value);
217 218
    o = t;
    t = t->next;
219
    FREE (&o);
220 221 222 223
  }
  *p = 0;
}

224
LIST *mutt_add_list (LIST *head, const char *data)
225
{
226
  size_t len = mutt_strlen (data);
227

228
  return mutt_add_list_n (head, data, len ? len + 1 : 0);
229 230
}

231
LIST *mutt_add_list_n (LIST *head, const void *data, size_t len)
232
{
233 234
  LIST *tmp;
  
235 236 237 238
  for (tmp = head; tmp && tmp->next; tmp = tmp->next)
    ;
  if (tmp)
  {
239
    tmp->next = safe_malloc (sizeof (LIST));
240 241 242
    tmp = tmp->next;
  }
  else
243 244 245
    head = tmp = safe_malloc (sizeof (LIST));
  
  tmp->data = safe_malloc (len);
246
  if (len)
247
    memcpy (tmp->data, data, len);
248 249 250 251
  tmp->next = NULL;
  return head;
}

252
LIST *mutt_find_list (LIST *l, const char *data)
253
{
254
  LIST *p = l;
255 256 257 258 259

  while (p)
  {
    if (data == p->data)
      return p;
260
    if (data && p->data && mutt_strcmp (p->data, data) == 0)
261 262 263 264 265 266
      return p;
    p = p->next;
  }
  return NULL;
}

267
int mutt_remove_from_rx_list (RX_LIST **l, const char *str)
268
{
269
  RX_LIST *p, *last = NULL;
270 271
  int rv = -1;

272
  if (mutt_strcmp ("*", str) == 0)
273
  {
274
    mutt_free_rx_list (l);    /* ``unCMD *'' means delete all current entries */
275 276 277 278 279 280 281 282
    rv = 0;
  }
  else
  {
    p = *l;
    last = NULL;
    while (p)
    {
283
      if (ascii_strcasecmp (str, p->rx->pattern) == 0)
284
      {
285 286 287 288 289 290 291
	mutt_free_regexp (&p->rx);
	if (last)
	  last->next = p->next;
	else
	  (*l) = p->next;
	FREE (&p);
	rv = 0;
292 293 294
      }
      else
      {
295 296
	last = p;
	p = p->next;
297 298 299
      }
    }
  }
300
  return (rv);
301 302
}

303
void mutt_free_list (LIST **list)
304
{
305 306 307
  LIST *p;
  
  if (!list) return;
308 309 310 311
  while (*list)
  {
    p = *list;
    *list = (*list)->next;
312 313
    FREE (&p->data);
    FREE (&p);
314 315 316
  }
}

317
LIST *mutt_copy_list (LIST *p)
318
{
319
  LIST *t, *r=NULL, *l=NULL;
320 321 322

  for (; p; p = p->next)
  {
323 324
    t = (LIST *) safe_malloc (sizeof (LIST));
    t->data = safe_strdup (p->data);
325 326
    t->next = NULL;
    if (l)
327
    { 
328 329 330 331 332 333
      r->next = t;
      r = r->next;
    }
    else
      l = r = t;
  }
334
  return (l);
335 336
}

337
HEADER *mutt_dup_header(HEADER *h)
338
{
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
  HEADER *hnew;

  hnew = mutt_new_header();
  memcpy(hnew, h, sizeof (HEADER));
  return hnew;
}

void mutt_free_header (HEADER **h)
{
  if(!h || !*h) return;
  mutt_free_envelope (&(*h)->env);
  mutt_free_body (&(*h)->content);
  FREE (&(*h)->maildir_flags);
  FREE (&(*h)->tree);
  FREE (&(*h)->path);
354
#ifdef MIXMASTER
355
  mutt_free_list (&(*h)->chain);
356
#endif
357 358
#if defined USE_POP || defined USE_IMAP
  FREE (&(*h)->data);
359
#endif
360
  FREE (h);		/* __FREE_CHECKED__ */
361 362 363
}

/* returns true if the header contained in "s" is in list "t" */
364
int mutt_matches_ignore (const char *s, LIST *t)
365 366 367
{
  for (; t; t = t->next)
  {
368 369
    if (!ascii_strncasecmp (s, t->data, mutt_strlen (t->data)) || *t->data == '*')
      return 1;
370
  }
371
  return 0;
372 373
}

374 375
/* prepend the path part of *path to *link */
void mutt_expand_link (char *newpath, const char *path, const char *link)
376
{
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  const char *lb = NULL;
  size_t len;

  /* link is full path */
  if (*link == '/')
  {
    strfcpy (newpath, link, _POSIX_PATH_MAX);
    return;
  }

  if ((lb = strrchr (path, '/')) == NULL)
  {
    /* no path in link */
    strfcpy (newpath, link, _POSIX_PATH_MAX);
    return;
  }

  len = lb - path + 1;
  memcpy (newpath, path, len);
  strfcpy (newpath + len, link, _POSIX_PATH_MAX - len);
397 398
}

399
char *mutt_expand_path (char *s, size_t slen)
400
{
401
  return _mutt_expand_path (s, slen, 0);
402 403
}

404
char *_mutt_expand_path (char *s, size_t slen, int rx)
405 406 407 408
{
  char p[_POSIX_PATH_MAX] = "";
  char q[_POSIX_PATH_MAX] = "";
  char tmp[_POSIX_PATH_MAX];
409
  char *t;
410

411
  char *tail = ""; 
412 413

  int recurse = 0;
414 415
  
  do 
416 417 418 419 420 421 422
  {
    recurse = 0;

    switch (*s)
    {
      case '~':
      {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
	if (*(s + 1) == '/' || *(s + 1) == 0)
	{
	  strfcpy (p, NONULL(Homedir), sizeof (p));
	  tail = s + 1;
	}
	else
	{
	  struct passwd *pw;
	  if ((t = strchr (s + 1, '/'))) 
	    *t = 0;

	  if ((pw = getpwnam (s + 1)))
	  {
	    strfcpy (p, pw->pw_dir, sizeof (p));
	    if (t)
	    {
	      *t = '/';
	      tail = t;
	    }
	    else
	      tail = "";
	  }
	  else
	  {
	    /* user not found! */
	    if (t)
	      *t = '/';
	    *p = '\0';
	    tail = s;
	  }
	}
454 455
      }
      break;
456
      
457
      case '=':
458
      case '+':    
459 460
      {
#ifdef USE_IMAP
461 462 463 464 465 466
	/* if folder = {host} or imap[s]://host/: don't append slash */
	if (mx_is_imap (NONULL (Maildir)) &&
	    (Maildir[strlen (Maildir) - 1] == '}' ||
	     Maildir[strlen (Maildir) - 1] == '/'))
	  strfcpy (p, NONULL (Maildir), sizeof (p));
	else
467
#endif
468 469 470 471 472 473
	if (Maildir && *Maildir && Maildir[strlen (Maildir) - 1] == '/')
	  strfcpy (p, NONULL (Maildir), sizeof (p));
	else
	  snprintf (p, sizeof (p), "%s/", NONULL (Maildir));
	
	tail = s + 1;
474 475
      }
      break;
476
      
477
      /* elm compatibility, @ expands alias to user name */
478
    
479 480
      case '@':
      {
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	HEADER *h;
	ADDRESS *alias;
	
	if ((alias = mutt_lookup_alias (s + 1)))
	{
	  h = mutt_new_header();
	  h->env = mutt_new_envelope();
	  h->env->from = h->env->to = alias;
	  mutt_default_save (p, sizeof (p), h);
	  h->env->from = h->env->to = NULL;
	  mutt_free_header (&h);
	  /* Avoid infinite recursion if the resulting folder starts with '@' */
	  if (*p != '@')
	    recurse = 1;
	  
	  tail = "";
	}
498 499
      }
      break;
500
      
501 502
      case '>':
      {
503 504
	strfcpy (p, NONULL(Inbox), sizeof (p));
	tail = s + 1;
505 506
      }
      break;
507
      
508 509
      case '<':
      {
510 511
	strfcpy (p, NONULL(Outbox), sizeof (p));
	tail = s + 1;
512 513
      }
      break;
514
      
515 516
      case '!':
      {
517 518 519 520 521 522 523 524 525 526
	if (*(s+1) == '!')
	{
	  strfcpy (p, NONULL(LastFolder), sizeof (p));
	  tail = s + 2;
	}
	else 
	{
	  strfcpy (p, NONULL(Spoolfile), sizeof (p));
	  tail = s + 1;
	}
527 528
      }
      break;
529
      
530 531
      case '-':
      {
532 533
	strfcpy (p, NONULL(LastFolder), sizeof (p));
	tail = s + 1;
534 535
      }
      break;
536 537
      
      case '^':        
538
      {
539 540
	strfcpy (p, NONULL(CurrentFolder), sizeof (p));
	tail = s + 1;
541 542 543 544 545
      }
      break;

      default:
      {
546 547
	*p = '\0';
	tail = s;
548 549 550 551 552
      }
    }

    if (rx && *p && !recurse)
    {
553 554
      mutt_rx_sanitize_string (q, sizeof (q), p);
      snprintf (tmp, sizeof (tmp), "%s%s", q, tail);
555 556
    }
    else
557 558 559 560 561
      snprintf (tmp, sizeof (tmp), "%s%s", p, tail);
    
    strfcpy (s, tmp, slen);
  }
  while (recurse);
562 563 564 565

#ifdef USE_IMAP
  /* Rewrite IMAP path in canonical form - aids in string comparisons of
   * folders. May possibly fail, in which case s should be the same. */
566 567
  if (mx_is_imap (s))
    imap_expand_path (s, slen);
568 569
#endif

570
  return (s);
571 572 573 574
}

/* Extract the real name from /etc/passwd's GECOS field.
 * When set, honor the regular expression in GecosMask,
575
 * otherwise assume that the GECOS field is a 
576 577 578 579
 * comma-separated list.
 * Replace "&" by a capitalized version of the user's login
 * name.
 */
580 581

char *mutt_gecos_name (char *dest, size_t destlen, struct passwd *pw)
582 583 584
{
  regmatch_t pat_match[1];
  size_t pwnl;
585 586 587 588
  int idx;
  char *p;
  
  if (!pw || !pw->pw_gecos) 
589 590
    return NULL;

591 592
  memset (dest, 0, destlen);
  
593 594
  if (GecosMask.rx)
  {
595 596 597
    if (regexec (GecosMask.rx, pw->pw_gecos, 1, pat_match, 0) == 0)
      strfcpy (dest, pw->pw_gecos + pat_match[0].rm_so, 
	       MIN (pat_match[0].rm_eo - pat_match[0].rm_so + 1, destlen));
598
  }
599 600
  else if ((p = strchr (pw->pw_gecos, ',')))
    strfcpy (dest, pw->pw_gecos, MIN (destlen, p - pw->pw_gecos + 1));
601
  else
602
    strfcpy (dest, pw->pw_gecos, destlen);
603

604
  pwnl = strlen (pw->pw_name);
605

606
  for (idx = 0; dest[idx]; idx++)
607 608 609
  {
    if (dest[idx] == '&')
    {
610 611 612 613
      memmove (&dest[idx + pwnl], &dest[idx + 1],
	       MAX((ssize_t)(destlen - idx - pwnl - 1), 0));
      memcpy (&dest[idx], pw->pw_name, MIN(destlen - idx - 1, pwnl));
      dest[idx] = toupper ((unsigned char) dest[idx]);
614 615
    }
  }
616
      
617 618
  return dest;
}
619
  
620

621
char *mutt_get_parameter (const char *s, PARAMETER *p)
622 623
{
  for (; p; p = p->next)
624 625
    if (ascii_strcasecmp (s, p->attribute) == 0)
      return (p->value);
626 627 628 629

  return NULL;
}

630
void mutt_set_parameter (const char *attribute, const char *value, PARAMETER **p)
631
{
632
  PARAMETER *q;
633 634 635

  if (!value)
  {
636
    mutt_delete_parameter (attribute, p);
637 638
    return;
  }
639 640
  
  for(q = *p; q; q = q->next)
641
  {
642
    if (ascii_strcasecmp (attribute, q->attribute) == 0)
643
    {
644
      mutt_str_replace (&q->value, value);
645 646 647
      return;
    }
  }
648
  
649 650 651 652 653 654 655
  q = mutt_new_parameter();
  q->attribute = safe_strdup(attribute);
  q->value = safe_strdup(value);
  q->next = *p;
  *p = q;
}

656
void mutt_delete_parameter (const char *attribute, PARAMETER **p)
657
{
658 659
  PARAMETER *q;
  
660 661
  for (q = *p; q; p = &q->next, q = q->next)
  {
662
    if (ascii_strcasecmp (attribute, q->attribute) == 0)
663 664 665
    {
      *p = q->next;
      q->next = NULL;
666
      mutt_free_parameter (&q);
667 668 669 670 671 672
      return;
    }
  }
}

/* returns 1 if Mutt can't display this type of data, 0 otherwise */
673
int mutt_needs_mailcap (BODY *m)
674 675 676 677
{
  switch (m->type)
  {
    case TYPETEXT:
678 679
      /* we can display any text, overridable by auto_view */
      return 0;
680
      break;
681

682
    case TYPEAPPLICATION:
683 684 685 686
      if((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp(m))
	return 0;
      if((WithCrypto & APPLICATION_SMIME) && mutt_is_application_smime(m))
	return 0;
687 688 689 690
      break;

    case TYPEMULTIPART:
    case TYPEMESSAGE:
691
      return 0;
692 693
  }

694
  return 1;
695 696
}

697
int mutt_is_text_part (BODY *b)
698 699 700
{
  int t = b->type;
  char *s = b->subtype;
701 702 703
  
  if ((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp (b))
    return 0;
704 705

  if (t == TYPETEXT)
706
    return 1;
707 708 709

  if (t == TYPEMESSAGE)
  {
710 711
    if (!ascii_strcasecmp ("delivery-status", s))
      return 1;
712 713 714 715
  }

  if ((WithCrypto & APPLICATION_PGP) && t == TYPEAPPLICATION)
  {
716 717
    if (!ascii_strcasecmp ("pgp-keys", s))
      return 1;
718 719
  }

720
  return 0;
721 722
}

723
void mutt_free_envelope (ENVELOPE **p)
724
{
725 726 727 728 729 730 731 732 733 734 735 736
  if (!*p) return;
  rfc822_free_address (&(*p)->return_path);
  rfc822_free_address (&(*p)->from);
  rfc822_free_address (&(*p)->to);
  rfc822_free_address (&(*p)->cc);
  rfc822_free_address (&(*p)->bcc);
  rfc822_free_address (&(*p)->sender);
  rfc822_free_address (&(*p)->reply_to);
  rfc822_free_address (&(*p)->mail_followup_to);

  FREE (&(*p)->list_post);
  FREE (&(*p)->subject);
737
  /* real_subj is just an offset to subject and shouldn't be freed */
738 739 740 741 742
  FREE (&(*p)->disp_subj);
  FREE (&(*p)->message_id);
  FREE (&(*p)->supersedes);
  FREE (&(*p)->date);
  FREE (&(*p)->x_label);
743

744
  mutt_buffer_free (&(*p)->spam);
745

746 747 748 749
  mutt_free_list (&(*p)->references);
  mutt_free_list (&(*p)->in_reply_to);
  mutt_free_list (&(*p)->userhdrs);
  FREE (p);		/* __FREE_CHECKED__ */
750 751 752
}

/* move all the headers from extra not present in base into base */
753
void mutt_merge_envelopes(ENVELOPE* base, ENVELOPE** extra)
754
{
755
  /* copies each existing element if necessary, and sets the element
756 757
  * to NULL in the source so that mutt_free_envelope doesn't leave us
  * with dangling pointers. */
758
#define MOVE_ELEM(h) if (!base->h) { base->h = (*extra)->h; (*extra)->h = NULL; }
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
  MOVE_ELEM(return_path);
  MOVE_ELEM(from);
  MOVE_ELEM(to);
  MOVE_ELEM(cc);
  MOVE_ELEM(bcc);
  MOVE_ELEM(sender);
  MOVE_ELEM(reply_to);
  MOVE_ELEM(mail_followup_to);
  MOVE_ELEM(list_post);
  MOVE_ELEM(message_id);
  MOVE_ELEM(supersedes);
  MOVE_ELEM(date);
  MOVE_ELEM(x_label);
  if (!base->refs_changed)
  {
    MOVE_ELEM(references);
  }
  if (!base->irt_changed)
  {
    MOVE_ELEM(in_reply_to);
  }
780
  
781 782 783 784 785
  /* real_subj is subordinate to subject */
  if (!base->subject)
  {
    base->subject = (*extra)->subject;
    base->real_subj = (*extra)->real_subj;
786
    base->disp_subj = (*extra)->disp_subj;
787 788
    (*extra)->subject = NULL;
    (*extra)->real_subj = NULL;
789
    (*extra)->disp_subj = NULL;
790 791 792
  }
  /* spam and user headers should never be hashed, and the new envelope may
    * have better values. Use new versions regardless. */
793 794
  mutt_buffer_free (&base->spam);
  mutt_free_list (&base->userhdrs);
795 796 797
  MOVE_ELEM(spam);
  MOVE_ELEM(userhdrs);
#undef MOVE_ELEM
798
  
799 800 801
  mutt_free_envelope(extra);
}

802 803
void _mutt_mktemp (char *s, size_t slen, const char *prefix, const char *suffix,
                   const char *src, int line)
804
{
805 806 807 808
  size_t n = snprintf (s, slen, "%s/%s-%s-%d-%d-%ld%ld%s%s",
      NONULL (Tempdir), NONULL (prefix), NONULL (Hostname),
      (int) getuid (), (int) getpid (), random (), random (),
      suffix ? "." : "", NONULL (suffix));
809
  if (n >= slen)
810 811 812 813 814
    dprint (1, (debugfile, "%s:%d: ERROR: insufficient buffer space to hold temporary filename! slen=%zu but need %zu\n",
	    src, line, slen, n));
  dprint (3, (debugfile, "%s:%d: mutt_mktemp returns \"%s\".\n", src, line, s));
  if (unlink (s) && errno != ENOENT)
    dprint (1, (debugfile, "%s:%d: ERROR: unlink(\"%s\"): %s (errno %d)\n", src, line, s, strerror (errno), errno));
815 816
}

817
void mutt_free_alias (ALIAS **p)
818
{
819
  ALIAS *t;
820 821 822 823 824

  while (*p)
  {
    t = *p;
    *p = (*p)->next;
825 826 827 828
    mutt_alias_delete_reverse (t);
    FREE (&t->name);
    rfc822_free_address (&t->addr);
    FREE (&t);
829 830 831 832
  }
}

/* collapse the pathname using ~ or = when possible */
833
void mutt_pretty_mailbox (char *s, size_t buflen)
834 835 836 837
{
  char *p = s, *q = s;
  size_t len;
  url_scheme_t scheme;
838
  char tmp[PATH_MAX];
839

840
  scheme = url_check_scheme (s);
841 842 843 844

#ifdef USE_IMAP
  if (scheme == U_IMAP || scheme == U_IMAPS)
  {
845
    imap_pretty_mailbox (s);
846 847 848 849 850 851 852
    return;
  }
#endif

  /* if s is an url, only collapse path component */
  if (scheme != U_UNKNOWN)
  {
853 854 855
    p = strchr(s, ':')+1;
    if (!strncmp (p, "//", 2))
      q = strchr (p+2, '/');
856
    if (!q)
857
      q = strchr (p, '\0');
858 859
    p = q;
  }
860 861

  /* cleanup path */
862
  if (strstr (p, "//") || strstr (p, "/./"))
863
  {
864 865 866 867
    /* first attempt to collapse the pathname, this is more
     * lightweight than realpath() and doesn't resolve links
     */
    while (*p)
868
    {
869 870
      if (*p == '/' && p[1] == '/')
      {
871 872
	*q++ = '/';
	p += 2;
873 874 875
      }
      else if (p[0] == '/' && p[1] == '.' && p[2] == '/')
      {
876 877
	*q++ = '/';
	p += 3;
878 879
      }
      else
880
	*q++ = *p++;
881
    }
882
    *q = 0;
883
  }
884 885 886 887
  else if (strstr (p, "..") && 
	   (scheme == U_UNKNOWN || scheme == U_FILE) &&
	   realpath (p, tmp))
    strfcpy (p, tmp, buflen - (p - s));
888

889 890
  if (mutt_strncmp (s, Maildir, (len = mutt_strlen (Maildir))) == 0 &&
      s[len] == '/')
891 892
  {
    *s++ = '=';
893
    memmove (s, s + len, mutt_strlen (s + len) + 1);
894
  }
895 896
  else if (mutt_strncmp (s, Homedir, (len = mutt_strlen (Homedir))) == 0 &&
	   s[len] == '/')
897 898
  {
    *s++ = '~';
899
    memmove (s, s + len - 1, mutt_strlen (s + len - 1) + 1);
900 901 902
  }
}

903
void mutt_pretty_size (char *s, size_t len, LOFF_T n)
904
{
905 906 907 908 909 910
  if (n == 0)
    strfcpy (s, "0K", len);
  /* Change in format released in 1.10.0, but reverted after feedback:
   * if (n < 1000)
   *  snprintf (s, len, "%d", (int)n);
   */
911
  else if (n < 10189) /* 0.1K - 9.9K */
912
    snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
913 914 915
  else if (n < 1023949) /* 10K - 999K */
  {
    /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
916
    snprintf (s, len, OFF_T_FMT "K", (n + 51) / 1024);
917 918
  }
  else if (n < 10433332) /* 1.0M - 9.9M */
919
    snprintf (s, len, "%3.1fM", n / 1048576.0);
920 921 922
  else /* 10M+ */
  {
    /* (10433332 + 52428) / 1048576 = 10 */
923
    snprintf (s, len, OFF_T_FMT "M", (n + 52428) / 1048576);
924 925 926
  }
}

927
void mutt_expand_file_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
928 929
{
  char tmp[LONG_STRING];
930 931 932
  
  mutt_quote_filename (tmp, sizeof (tmp), src);
  mutt_expand_fmt (dest, destlen, fmt, tmp);
933 934
}

935
void mutt_expand_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
936
{
937 938
  const char *p;
  char *d;
939 940 941
  size_t slen;
  int found = 0;

942
  slen = mutt_strlen (src);
943
  destlen--;
944
  
945 946
  for (p = fmt, d = dest; destlen && *p; p++)
  {
947
    if (*p == '%') 
948 949 950
    {
      switch (p[1])
      {
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
	case '%':
	  *d++ = *p++;
	  destlen--;
	  break;
	case 's':
	  found = 1;
	  strfcpy (d, src, destlen + 1);
	  d       += destlen > slen ? slen : destlen;
	  destlen -= destlen > slen ? slen : destlen;
	  p++;
	  break;
	default:
	  *d++ = *p; 
	  destlen--;
	  break;
966 967 968 969 970 971 972 973
      }
    }
    else
    {
      *d++ = *p;
      destlen--;
    }
  }
974
  
975
  *d = '\0';
976
  
977 978
  if (!found && destlen > 0)
  {
979 980
    safe_strcat (dest, destlen, " ");
    safe_strcat (dest, destlen, src);
981
  }
982
  
983 984 985
}

/* return 0 on success, -1 on abort, 1 on error */
986 987
int mutt_check_overwrite (const char *attname, const char *path,
				char *fname, size_t flen, int *append, char **directory) 
988 989 990 991 992
{
  int rc = 0;
  char tmp[_POSIX_PATH_MAX];
  struct stat st;

993 994
  strfcpy (fname, path, flen);
  if (access (fname, F_OK) != 0)
995
    return 0;
996
  if (stat (fname, &st) != 0)
997
    return -1;
998
  if (S_ISDIR (st.st_mode))
999 1000 1001 1002
  {
    if (directory)
    {
      switch (mutt_multi_choice
1003
      /* L10N:
1004 1005
         Means "The path you specified as the destination file is a directory."
         See the msgid "Save to file: " (alias.c, recvattach.c) */
1006
	      (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"), _("yna")))
1007
      {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	case 3:		/* all */
	  mutt_str_replace (directory, fname);
	  break;
	case 1:		/* yes */
	  FREE (directory);		/* __FREE_CHECKED__ */
	  break;
	case -1:	/* abort */
	  FREE (directory); 		/* __FREE_CHECKED__ */
	  return -1;
	case  2:	/* no */
	  FREE (directory);		/* __FREE_CHECKED__ */
	  return 1;
1020 1021
      }
    }
1022 1023 1024
    /* L10N:
       Means "The path you specified as the destination file is a directory."
       See the msgid "Save to file: " (alias.c, recvattach.c) */
1025
    else if ((rc = mutt_yesorno (_("File is a directory, save under it?"), MUTT_YES)) != MUTT_YES)
1026
      return (rc == MUTT_NO) ? 1 : -1;
1027

1028 1029 1030 1031 1032
    strfcpy (tmp, mutt_basename (NONULL (attname)), sizeof (tmp));
    if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
                                    MUTT_FILE | MUTT_CLEAR) != 0 || !tmp[0])
      return (-1);
    mutt_concat_path (fname, path, tmp, flen);
1033
  }
1034 1035
  
  if (*append == 0 && access (fname, F_OK) == 0)
1036
  {
1037 1038
    switch (mutt_multi_choice
	    (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
1039 1040 1041
    {
      case -1: /* abort */
        return -1;
1042 1043
      case 3:  /* cancel */
	return 1;
1044 1045

      case 2: /* append */
1046
        *append = MUTT_SAVE_APPEND;
1047 1048
        break;
      case 1: /* overwrite */
1049
        *append = MUTT_SAVE_OVERWRITE;
1050 1051 1052 1053 1054 1055
        break;
    }
  }
  return 0;
}

1056
void mutt_save_path (char *d, size_t dsize, ADDRESS *a)
1057 1058 1059
{
  if (a && a->mailbox)
  {
1060 1061
    strfcpy (d, a->mailbox, dsize);
    if (!option (OPTSAVEADDRESS))
1062
    {
1063
      char *p;
1064

1065 1066
      if ((p = strpbrk (d, "%@")))
	*p = 0;
1067
    }
1068
    mutt_strlower (d);
1069 1070 1071 1072 1073
  }
  else
    *d = 0;
}

1074
void mutt_safe_path (char *s, size_t l, ADDRESS *a)
1075
{
1076
  char *p;
1077

1078
  mutt_save_path (s, l, a);
1079
  for (p = s; *p; p++)
1080
    if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
1081 1082 1083
      *p = '_';
}

1084 1085
/* Note this function uses a fixed size buffer of LONG_STRING and so
 * should only be used for visual modifications, such as disp_subj. */
1086
char *mutt_apply_replace (char *dbuf, size_t dlen, char *sbuf, REPLACE_LIST *rlist)
1087
{
1088
  REPLACE_LIST *l;
1089 1090 1091 1092
  static regmatch_t *pmatch = NULL;
  static int nmatch = 0;
  static char twinbuf[2][LONG_STRING];
  int switcher = 0;
1093
  char *p;
1094 1095
  int i, n;
  size_t cpysize, tlen;
1096
  char *src, *dst;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

  if (dbuf && dlen)
    dbuf[0] = '\0';

  if (sbuf == NULL || *sbuf == '\0' || (dbuf && !dlen))
    return dbuf;

  twinbuf[0][0] = '\0';
  twinbuf[1][0] = '\0';
  src = twinbuf[switcher];
  dst = src;

  strfcpy(src, sbuf, LONG_STRING);

  for (l = rlist; l; l = l->next)
  {
    /* If this pattern needs more matches, expand pmatch. */
    if (l->nmatch > nmatch)
    {
1116
      safe_realloc (&pmatch, l->nmatch * sizeof(regmatch_t));
1117 1118 1119
      nmatch = l->nmatch;
    }

1120
    if (regexec (l->rx->rx, src, l->nmatch, pmatch, 0) == 0)
1121 1122 1123 1124 1125
    {
      tlen = 0;
      switcher ^= 1;
      dst = twinbuf[switcher];

1126
      dprint (5, (debugfile, "mutt_apply_replace: %s matches %s\n", src, l->rx->pattern));
1127 1128 1129 1130

      /* Copy into other twinbuf with substitutions */
      if (l->template)
      {
1131
        for (p = l->template; *p && (tlen < LONG_STRING - 1); )
1132
        {
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	  if (*p == '%')
	  {
	    p++;
	    if (*p == 'L')
	    {
	      p++;
              cpysize = MIN (pmatch[0].rm_so, LONG_STRING - tlen - 1);
	      strncpy(&dst[tlen], src, cpysize);
	      tlen += cpysize;
	    }
	    else if (*p == 'R')
	    {
	      p++;
              cpysize = MIN (strlen (src) - pmatch[0].rm_eo, LONG_STRING - tlen - 1);
	      strncpy(&dst[tlen], &src[pmatch[0].rm_eo], cpysize);
	      tlen += cpysize;
	    }
	    else
	    {
	      n = strtoul(p, &p, 10);               /* get subst number */
	      while (isdigit((unsigned char)*p))    /* skip subst token */
1154
                ++p;
1155 1156 1157 1158 1159 1160
	      for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < LONG_STRING-1); i++)
	        dst[tlen++] = src[i];
	    }
	  }
	  else
	    dst[tlen++] = *p++;
1161 1162 1163
        }
      }
      dst[tlen] = '\0';
1164
      dprint (5, (debugfile, "mutt_apply_replace: subst %s\n", dst));
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    }
    src = dst;
  }

  if (dbuf)
    strfcpy(dbuf, dst, dlen);
  else
    dbuf = safe_strdup(dst);
  return dbuf;
}

1176

1177 1178 1179 1180 1181 1182 1183 1184
void mutt_FormatString (char *dest,		/* output buffer */
			size_t destlen,		/* output buffer len */
			size_t col,		/* starting column (nonzero when called recursively) */
                        int cols,               /* maximum columns */
			const char *src,	/* template string */
			format_t *callback,	/* callback for processing */
			unsigned long data,	/* callback data */
			format_flag flags)	/* callback flags */
1185
{
1186
  char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
1187 1188 1189
  char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
  size_t wlen, count, len, wid;
  pid_t pid;
1190
  FILE *filter;
1191
  int n;
1192
  char *recycler;
1193 1194 1195

  prefix[0] = '\0';
  destlen--; /* save room for the terminal \0 */
1196
  wlen = ((flags & MUTT_FORMAT_ARROWCURSOR) && option (OPTARROWCURSOR)) ? 3 : 0;
1197 1198
  col += wlen;

1199
  if ((flags & MUTT_FORMAT_NOFILTER) == 0)
1200 1201 1202 1203 1204
  {
    int off = -1;

    /* Do not consider filters if no pipe at end */
    n = mutt_strlen(src);
1205
    if (n > 1 && src[n-1] == '|')
1206 1207 1208
    {
      /* Scan backwards for backslashes */
      off = n;
1209
      while (off > 0 && src[off-2] == '\\')
1210 1211 1212 1213 1214
        off--;
    }

    /* If number of backslashes is even, the pipe is real. */
    /* n-off is the number of backslashes. */
1215
    if (off > 0 && ((n-off) % 2) == 0)
1216
    {
1217 1218
      BUFFER *srcbuf, *word, *command;
      char    srccopy[LONG_STRING];
1219
#ifdef DEBUG
1220
      int     i = 0;
1221 1222
#endif

1223
      dprint(3, (debugfile, "fmtpipe = %s\n", src));
1224 1225

      strncpy(srccopy, src, n);
1226
      srccopy[n-1] = '\0';
1227 1228

      /* prepare BUFFERs */
1229
      srcbuf = mutt_buffer_from (srccopy);
1230
      srcbuf->dptr = srcbuf->data;
1231 1232
      word = mutt_buffer_new ();
      command = mutt_buffer_new ();
1233 1234

      /* Iterate expansions across successive arguments */
1235 1236
      do {
        char *p;
1237 1238

        /* Extract the command name and copy to command line */
1239
        dprint(3, (debugfile, "fmtpipe +++: %s\n", srcbuf->dptr));
1240 1241 1242
        if (word->data)
          *word->data = '\0';
        mutt_extract_token(word, srcbuf, 0);
1243
        dprint(3, (debugfile, "fmtpipe %2d: %s\n", i++, word->data));
1244
        mutt_buffer_addch(command, '\'');
1245 1246
        mutt_FormatString(buf, sizeof(buf), 0, cols, word->data, callback, data,
                          flags | MUTT_FORMAT_NOFILTER);
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        for (p = buf; p && *p; p++)
        {
          if (*p == '\'')
            /* shell quoting doesn't permit escaping a single quote within
             * single-quoted material.  double-quoting instead will lead
             * shell variable expansions, so break out of the single-quoted
             * span, insert a double-quoted single quote, and resume. */
            mutt_buffer_addstr(command, "'\"'\"'");
          else
            mutt_buffer_addch(command, *p);
        }
        mutt_buffer_addch(command, '\'');
        mutt_buffer_addch(command, ' ');
      } while (MoreArgs(srcbuf));

1262
      dprint(3, (debugfile, "fmtpipe > %s\n", command->data));
1263

1264 1265 1266
      col -= wlen;	/* reset to passed in value */
      wptr = dest;      /* reset write ptr */
      wlen = ((flags & MUTT_FORMAT_ARROWCURSOR) && option (OPTARROWCURSOR)) ? 3 : 0;
1267
      if ((pid = mutt_create_filter(command->data, NULL, &filter, NULL)) != -1)
1268
      {
1269
	int rc;
1270

1271
        n = fread(dest, 1, destlen /* already decremented */, filter);
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        safe_fclose (&filter);
	rc = mutt_wait_filter(pid);
	if (rc != 0)
	  dprint(1, (debugfile, "format pipe command exited code %d\n", rc));
	if (n > 0) {
	  dest[n] = 0;
	  while ((n > 0) && (dest[n-1] == '\n' || dest[n-1] == '\r'))
	    dest[--n] = '\0';
	  dprint(3, (debugfile, "fmtpipe < %s\n", dest));

	  /* If the result ends with '%', this indicates that the filter
	   * generated %-tokens that mutt can expand.  Eliminate the '%'
	   * marker and recycle the string through mutt_FormatString().
	   * To literally end with "%", use "%%". */
	  if ((n > 0) && dest[n-1] == '%')
	  {
	    --n;
	    dest[n] = '\0';               /* remove '%' */
	    if ((n > 0) && dest[n-1] != '%')
	    {
	      recycler = safe_strdup(dest);
	      if (recycler)
	      {
		/* destlen is decremented at the start of this function
		 * to save space for the terminal nul char.  We can add
		 * it back for the recursive call since the expansion of
		 * format pipes does not try to append a nul itself.
		 */
		mutt_FormatString(dest, destlen+1, col, cols, recycler, callback, data, flags);
		FREE(&recycler);
	      }
	    }
	  }
	}
	else
	{
	  /* read error */
	  dprint(1, (debugfile, "error reading from fmtpipe: %s (errno=%d)\n", strerror(errno), errno));
	  *wptr = 0;
	}
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
      }
      else
      {
        /* Filter failed; erase write buffer */
        *wptr =