mutil.c 29.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 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 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2002, 2003,
   2005, 2006, 2007, 2009 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General
   Public License along with this library; 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

#include <errno.h>
#include <limits.h>
#include <netdb.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/select.h>

#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif

#include <mailutils/address.h>
#include <mailutils/assoc.h>
#include <mailutils/argcv.h>
#include <mailutils/error.h>
#include <mailutils/errno.h>
#include <mailutils/iterator.h>
#include <mailutils/mutil.h>
#include <mailutils/parse822.h>
#include <mailutils/mu_auth.h>
#include <mailutils/header.h>
#include <mailutils/message.h>
#include <mailutils/envelope.h>
#include <mailutils/nls.h>
#include <mailutils/stream.h>
#include <mailutils/filter.h>
#include <mailutils/sql.h>
#include <mailutils/url.h>
#include <mailutils/io.h>
#include <mailutils/cctype.h>
#include <mailutils/cstr.h>

#include <registrar0.h>

/* convert a sequence of hex characters into an integer */

unsigned long
mu_hex2ul (char hex)
{
  if (hex >= '0' && hex <= '9')
   return hex - '0';

  if (hex >= 'a' && hex <= 'z')
    return hex - 'a';

  if (hex >= 'A' && hex <= 'Z')
    return hex - 'A';

  return -1;
}

size_t
mu_hexstr2ul (unsigned long *ul, const char *hex, size_t len)
{
  size_t r;

  *ul = 0;

  for (r = 0; r < len; r++)
    {
      unsigned long v = mu_hex2ul (hex[r]);

      if (v == (unsigned long)-1)
	return r;

      *ul = *ul * 16 + v;
    }
  return r;
}


char *
mu_get_homedir (void)
{
  char *homedir = getenv ("HOME");
  if (homedir)
    homedir = strdup (homedir);
  else
    {
      struct mu_auth_data *auth = mu_get_auth_by_uid (geteuid ());
      if (!auth)
	return NULL;
      homedir = strdup (auth->dir);
      mu_auth_data_free (auth);
    }
  return homedir;
}

char *
mu_getcwd ()
{
  char *ret;
  unsigned path_max;
  char buf[128];

  errno = 0;
  ret = getcwd (buf, sizeof (buf));
  if (ret != NULL)
    return strdup (buf);

  if (errno != ERANGE)
    return NULL;

  path_max = 128;
  path_max += 2;                /* The getcwd docs say to do this. */

  for (;;)
    {
      char *cwd = (char *) malloc (path_max);

      errno = 0;
      ret = getcwd (cwd, path_max);
      if (ret != NULL)
        return ret;
      if (errno != ERANGE)
        {
          int save_errno = errno;
          free (cwd);
          errno = save_errno;
          return NULL;
        }

      free (cwd);

      path_max += path_max / 16;
      path_max += 32;
    }
  /* oops?  */
  return NULL;
}

char *
mu_get_full_path (const char *file)
{
  char *p = NULL;

  if (!file)
    p = mu_getcwd ();
  else if (*file != '/')
    {
      char *cwd = mu_getcwd ();
      if (cwd)
	{
	  p = calloc (strlen (cwd) + 1 + strlen (file) + 1, 1);
	  if (p)
	    sprintf (p, "%s/%s", cwd, file);
	  free (cwd);
	}
    }

  if (!p)
    p = strdup (file);
  return p;
}

/* NOTE: Allocates Memory.  */
/* Expand: ~ --> /home/user and to ~guest --> /home/guest.  */
char *
mu_tilde_expansion (const char *ref, const char *delim, const char *homedir)
{
  char *base = strdup (ref);
  char *home = NULL;
  char *proto = NULL;
  size_t proto_len = 0;
  char *p;

  for (p = base; *p && isascii (*p) && isalnum (*p); p++)
    ;
  
  if (*p == ':')
    {
      p++;
      proto_len = p - base;
      proto = malloc (proto_len + 1);
      if (!proto)
	return NULL;
      memcpy (proto, base, proto_len);
      proto[proto_len] = 0;
      /* Allow for extra pair of slashes after the protocol specifier */
      if (*p == delim[0])
	p++;
      if (*p == delim[0])
	p++;
    }
  else
    p = base;
  
  if (*p == '~')
    {
      p++;
      if (*p == delim[0] || *p == '\0')
        {
	  char *s;
	  if (!homedir)
	    {
	      home = mu_get_homedir ();
	      if (!home)
		return base;
	      homedir = home;
	    }
	  s = calloc (proto_len + strlen (homedir) + strlen (p) + 1, 1);
	  if (proto_len)
	    strcpy (s, proto);
	  else
	    s[0] = 0;
          strcat (s, homedir);
          strcat (s, p);
          free (base);
          base = s;
        }
      else
        {
          struct mu_auth_data *auth;
          char *s = p;
          char *name;
          while (*s && *s != delim[0])
            s++;
          name = calloc (s - p + 1, 1);
          memcpy (name, p, s - p);
          name[s - p] = '\0';
	  
          auth = mu_get_auth_by_name (name);
          free (name);
          if (auth)
            {
              char *buf = calloc (proto_len + strlen (auth->dir)
				  + strlen (s) + 1, 1);
	      if (proto_len)
		strcpy (buf, proto);
	      else
		buf[0] = 0;
	      strcat (buf, auth->dir);
              strcat (buf, s);
              free (base);
              base = buf;
	      mu_auth_data_free (auth);
            }
        }
    }
  if (home)
    free (home);
  return base;
}

/* Smart strncpy that always add the null and returns the number of bytes
   written.  */
size_t
mu_cpystr (char *dst, const char *src, size_t size)
{
  size_t len = src ? strlen (src) : 0 ;
  if (dst == NULL || size == 0)
    return len;
  if (len >= size)
    len = size - 1;
  memcpy (dst, src, len);
  dst[len] = '\0';
  return len;
}

/* General retrieve stack support: */

void
mu_register_retriever (mu_list_t *pflist, mu_retrieve_fp fun)
{
  if (!*pflist && mu_list_create (pflist))
    return;
  mu_list_append (*pflist, fun);
}

void *
mu_retrieve (mu_list_t flist, void *data)
{
  void *p = NULL;
  mu_iterator_t itr;

  if (mu_list_get_iterator (flist, &itr) == 0)
    {
      mu_retrieve_fp fun;
      for (mu_iterator_first (itr); !p && !mu_iterator_is_done (itr);
	   mu_iterator_next (itr))
	{
	  mu_iterator_current (itr, (void **)&fun);
	  p = (*fun) (data);
	}

      mu_iterator_destroy (&itr);
    }
  return p;
}

int
mu_get_host_name (char **host)
{
  char hostname[MAXHOSTNAMELEN + 1];
  struct hostent *hp = NULL;
  char *domain = NULL;

  gethostname (hostname, sizeof hostname);
  hostname[sizeof (hostname) - 1] = 0;

  if ((hp = gethostbyname (hostname)))
    domain = hp->h_name;
  else
    domain = hostname;

  domain = strdup (domain);

  if (!domain)
    return ENOMEM;

  *host = domain;

  return 0;
}

/*
 * Functions used to convert unix mailbox/user names into RFC822 addr-specs.
 */

static char *mu_user_email = 0;

int
mu_set_user_email (const char *candidate)
{
  int err = 0;
  mu_address_t addr = NULL;
  size_t emailno = 0;
  char *email = NULL;
  const char *domain = NULL;
  
  if ((err = mu_address_create (&addr, candidate)) != 0)
    return err;

  if ((err = mu_address_get_email_count (addr, &emailno)) != 0)
    goto cleanup;

  if (emailno != 1)
    {
      errno = EINVAL;
      goto cleanup;
    }

  if ((err = mu_address_aget_email (addr, 1, &email)) != 0)
    goto cleanup;

  if (mu_user_email)
    free (mu_user_email);

  mu_user_email = email;

  if ((err = mu_address_sget_domain (addr, 1, &domain)) == 0)
    mu_set_user_email_domain (domain);
  
cleanup:
  mu_address_destroy (&addr);

  return err;
}

static char *mu_user_email_domain = 0;

int
mu_set_user_email_domain (const char *domain)
{
  char *d = NULL;
  
  if (!domain)
    return EINVAL;
  
  d = strdup (domain);

  if (!d)
    return ENOMEM;

  if (mu_user_email_domain)
    free (mu_user_email_domain);

  mu_user_email_domain = d;

  return 0;
}

/* FIXME: must be called _sget_ */
int
mu_get_user_email_domain (const char **domain)
{
  int err = 0;

  if (!mu_user_email_domain)
    {
      if ((err = mu_get_host_name (&mu_user_email_domain)))
	return err;
    }

  *domain = mu_user_email_domain;

  return 0;
}

int
mu_aget_user_email_domain (char **pdomain)
{
  const char *domain;
  int status = mu_get_user_email_domain (&domain);
  if (status)
    return status;
  if (domain == NULL)
    *pdomain = NULL;
  else
    {
      *pdomain = strdup (domain);
      if (*pdomain == NULL)
	return ENOMEM;
    }
  return 0;
}

/* Note: allocates memory */
char *
mu_get_user_email (const char *name)
{
  int status = 0;
  char *localpart = NULL;
  const char *domainpart = NULL;
  char *email = NULL;
  char *tmpname = NULL;

  if (!name && mu_user_email)
    {
      email = strdup (mu_user_email);
      if (!email)
	errno = ENOMEM;
      return email;
    }

  if (!name)
    {
      struct mu_auth_data *auth = mu_get_auth_by_uid (getuid ());
      if (!auth)
	{
	  errno = EINVAL;
	  return NULL;
	}
      name = tmpname = strdup(auth->name);
      if (auth)
	mu_auth_data_free (auth);
    }

  status = mu_get_user_email_domain (&domainpart);

  if (status)
    {
      free(tmpname);
      errno = status;
      return NULL;
    }

  if ((status = mu_parse822_quote_local_part (&localpart, name)))
    {
      free(tmpname);
      errno = status;
      return NULL;
    }


  email = malloc (strlen (localpart) + 1
		  + strlen (domainpart) + 1);
  if (!email)
    errno = ENOMEM;
  else
    sprintf (email, "%s@%s", localpart, domainpart);

  free(tmpname);
  free (localpart);

  return email;
}

/* mu_normalize_path: convert pathname containig relative paths specs (../)
   into an equivalent absolute path. Strip trailing delimiter if present,
   unless it is the only character left. E.g.:

         /home/user/../smith   -->   /home/smith
	 /home/user/../..      -->   /

*/
char *
mu_normalize_path (char *path)
{
  int len;
  char *p;

  if (!path)
    return path;

  len = strlen (path);

  /* Empty string is returned as is */
  if (len == 0)
    return path;

  /* delete trailing delimiter if any */
  if (len && path[len-1] == '/')
    path[len-1] = 0;

  /* Eliminate any /../ */
  for (p = strchr (path, '.'); p; p = strchr (p, '.'))
    {
      if (p > path && p[-1] == '/')
	{
	  if (p[1] == '.' && (p[2] == 0 || p[2] == '/'))
	    /* found */
	    {
	      char *q, *s;

	      /* Find previous delimiter */
	      for (q = p-2; *q != '/' && q >= path; q--)
		;

	      if (q < path)
		break;
	      /* Copy stuff */
	      s = p + 2;
	      p = q;
	      while ((*q++ = *s++))
		;
	      continue;
	    }
	}

      p++;
    }

  if (path[0] == 0)
    {
      path[0] = '/';
      path[1] = 0;
    }

  return path;
}

/* Create and open a temporary file. Be very careful about it, since we
   may be running with extra privilege i.e setgid().
   Returns file descriptor of the open file.
   If namep is not NULL, the pointer to the malloced file name will
   be stored there. Otherwise, the file is unlinked right after open,
   i.e. it will disappear after close(fd). */

#ifndef P_tmpdir
# define P_tmpdir "/tmp"
#endif

int
mu_tempfile (const char *tmpdir, char **namep)
{
  char *filename;
  int fd;

  if (!tmpdir)
    tmpdir = (getenv ("TMPDIR")) ? getenv ("TMPDIR") : P_tmpdir;

  filename = malloc (strlen (tmpdir) + /*'/'*/1 + /* "muXXXXXX" */8 + 1);
  if (!filename)
    return -1;
  sprintf (filename, "%s/muXXXXXX", tmpdir);

#ifdef HAVE_MKSTEMP
  {
    int save_mask = umask (077);
    fd = mkstemp (filename);
    umask (save_mask);
  }
#else
  if (mktemp (filename))
    fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
  else
    fd = -1;
#endif

  if (fd == -1)
    {
      mu_error (_("cannot open temporary file: %s"), mu_strerror (errno));
      free (filename);
      return -1;
    }

  if (namep)
    *namep = filename;
  else
    {
      unlink (filename);
      free (filename);
    }

  return fd;
}

/* Create a unique temporary file name in tmpdir. The function
   creates an empty file with this name to avoid possible race
   conditions. Returns a pointer to the malloc'ed file name.
   If tmpdir is NULL, the value of the environment variable
   TMPDIR or the hardcoded P_tmpdir is used, whichever is defined. */

char *
mu_tempname (const char *tmpdir)
{
  char *filename = NULL;
  int fd = mu_tempfile (tmpdir, &filename);
  close (fd);
  return filename;
}

/* See Advanced Programming in the UNIX Environment, Stevens,
 * program  10.20 for the rational for the signal handling. I
 * had to look it up, so if somebody else is curious, thats where
 * to find it.
 */
int 
mu_spawnvp (const char *prog, char *av[], int *stat)
{
  pid_t pid;
  int err = 0;
  int progstat;
  struct sigaction ignore;
  struct sigaction saveintr;
  struct sigaction savequit;
  sigset_t chldmask;
  sigset_t savemask;

  if (!prog || !av)
    return EINVAL;

  ignore.sa_handler = SIG_IGN;	/* ignore SIGINT and SIGQUIT */
  ignore.sa_flags = 0;
  sigemptyset (&ignore.sa_mask);

  if (sigaction (SIGINT, &ignore, &saveintr) < 0)
    return errno;
  if (sigaction (SIGQUIT, &ignore, &savequit) < 0)
    {
      sigaction (SIGINT, &saveintr, NULL);
      return errno;
    }

  sigemptyset (&chldmask);	/* now block SIGCHLD */
  sigaddset (&chldmask, SIGCHLD);

  if (sigprocmask (SIG_BLOCK, &chldmask, &savemask) < 0)
    {
      sigaction (SIGINT, &saveintr, NULL);
      sigaction (SIGQUIT, &savequit, NULL);
      return errno;
    }

#ifdef HAVE_VFORK
  pid = vfork ();
#else
  pid = fork ();
#endif

  if (pid < 0)
    {
      err = errno;
    }
  else if (pid == 0)
    {				/* child */
      /* restore previous signal actions & reset signal mask */
      sigaction (SIGINT, &saveintr, NULL);
      sigaction (SIGQUIT, &savequit, NULL);
      sigprocmask (SIG_SETMASK, &savemask, NULL);

      execvp (prog, av);
#ifdef HAVE__EXIT      
      _exit (127);		/* exec error */
#else
      exit (127);
#endif
    }
  else
    {				/* parent */
      while (waitpid (pid, &progstat, 0) < 0)
	if (errno != EINTR)
	  {
	    err = errno;	/* error other than EINTR from waitpid() */
	    break;
	  }
      if (err == 0 && stat)
	*stat = progstat;
    }

  /* restore previous signal actions & reset signal mask */
  /* preserve first error number, but still try and reset the signals */
  if (sigaction (SIGINT, &saveintr, NULL) < 0)
    err = err ? err : errno;
  if (sigaction (SIGQUIT, &savequit, NULL) < 0)
    err = err ? err : errno;
  if (sigprocmask (SIG_SETMASK, &savemask, NULL) < 0)
    err = err ? err : errno;

  return err;
}

/* The result of readlink() may be a path relative to that link, 
 * qualify it if necessary.
 */
static void
mu_qualify_link (const char *path, const char *link, char *qualified)
{
  const char *lb = NULL;
  size_t len;

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

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

  len = lb - path + 1;
  memcpy (qualified, path, len);
  mu_cpystr (qualified + len, link, _POSIX_PATH_MAX - len);
}

#ifndef _POSIX_SYMLOOP_MAX
# define _POSIX_SYMLOOP_MAX 255
#endif

int
mu_unroll_symlink (char *out, size_t outsz, const char *in)
{
  char path[_POSIX_PATH_MAX];
  int symloops = 0;

  while (symloops++ < _POSIX_SYMLOOP_MAX)
    {
      struct stat s;
      char link[_POSIX_PATH_MAX];
      char qualified[_POSIX_PATH_MAX];
      int len;

      if (lstat (in, &s) == -1)
	return errno;

      if (!S_ISLNK (s.st_mode))
	{
	  mu_cpystr (path, in, sizeof (path));
	  break;
	}

      if ((len = readlink (in, link, sizeof (link))) == -1)
	return errno;

      link[(len >= sizeof (link)) ? (sizeof (link) - 1) : len] = '\0';

      mu_qualify_link (in, link, qualified);

      mu_cpystr (path, qualified, sizeof (path));

      in = path;
    }

  mu_cpystr (out, path, outsz);

  return 0;
}

/* Expand a PATTERN to the pathname. PATTERN may contain the following
   macro-notations:
   ---------+------------ 
   notation |  expands to
   ---------+------------
   %u         user name
   %h         user's home dir
   ~          Likewise
   ---------+------------

   Allocates memory. 
*/
char *
mu_expand_path_pattern (const char *pattern, const char *username)
{
  const char *p;
  char *q;
  char *path;
  size_t len = 0;
  struct mu_auth_data *auth = NULL;
  
  for (p = pattern; *p; p++)
    {
      if (*p == '~')
        {
          if (!auth)
            {
              auth = mu_get_auth_by_name (username);
              if (!auth)
                return NULL;
            }
          len += strlen (auth->dir);
        }
      else if (*p == '%')
	switch (*++p)
	  {
	  case 'u':
	    len += strlen (username);
	    break;
	    
	  case 'h':
	    if (!auth)
	      {
		auth = mu_get_auth_by_name (username);
		if (!auth)
		  return NULL;
	      }
	    len += strlen (auth->dir);
	    break;
	    
	  case '%':
	    len++;
	    break;
	    
	  default:
	    len += 2;
	  }
      else
	len++;
    }
  
  path = malloc (len + 1);
  if (!path)
    return NULL;

  p = pattern;
  q = path;
  while (*p)
    {
      size_t off = strcspn (p, "~%");
      memcpy (q, p, off);
      q += off;
      p += off;
      if (*p == '~')
	{
	  strcpy (q, auth->dir);
	  q += strlen (auth->dir);
	  p++;
	}
      else if (*p == '%')
	{
	  switch (*++p)
	    {
	    case 'u':
	      strcpy (q, username);
	      q += strlen (username);
	      break;
	    
	    case 'h':
	      strcpy (q, auth->dir);
	      q += strlen (auth->dir);
	      break;
	  
	    case '%':
	      *q++ = '%';
	      break;
	  
	    default:
	      *q++ = '%';
	      *q++ = *p;
	    }
	  p++;
	}
    }

  *q = 0;
  if (auth)
    mu_auth_data_free (auth);
  return path;
}

#define ST_INIT  0
#define ST_MSGID 1

static int
strip_message_id (char *msgid, char **pval)
{
  char *p, *q;
  int state;
  
  *pval = strdup (msgid);
  if (!*pval)
    return ENOMEM;
  state = ST_INIT;
  for (p = q = *pval; *p; p++)
    {
      switch (state)
	{
	case ST_INIT:
	  if (*p == '<')
	    {
	      *q++ = *p;
	      state = ST_MSGID;
	    }
	  else if (isspace (*p))
	    *q++ = *p;
	  break;

	case ST_MSGID:
	  *q++ = *p;
	  if (*p == '>')
	    state = ST_INIT;
	  break;
	}
    }
  *q = 0;
  return 0;
}

int
get_msgid_header (mu_header_t hdr, const char *name, char **val)
{
  char *p;
  int status = mu_header_aget_value (hdr, name, &p);
  if (status)
    return status;
  status = strip_message_id (p, val);
  free (p);
  return status;
}

static char *
concat (const char *s1, const char *s2)
{
  int len = (s1 ? strlen (s1) : 0) + (s2 ? strlen (s2) : 0) + 2;
  char *s = malloc (len);
  if (s)
    {
      char *p = s;
      
      if (s1)
	{
	  strcpy (p, s1);
	  p += strlen (s1);
	  *p++ = ' ';
	}
      if (s2)
	strcpy (p, s2);
    }
  return s;
}

/* rfc2822:
   
   The "References:" field will contain the contents of the parent's
   "References:" field (if any) followed by the contents of the parent's
   "Message-ID:" field (if any).  If the parent message does not contain
   a "References:" field but does have an "In-Reply-To:" field
   containing a single message identifier, then the "References:" field
   will contain the contents of the parent's "In-Reply-To:" field
   followed by the contents of the parent's "Message-ID:" field (if
   any).  If the parent has none of the "References:", "In-Reply-To:",
   or "Message-ID:" fields, then the new message will have no
   References:" field. */

int
mu_rfc2822_references (mu_message_t msg, char **pstr)
{
  char *ref = NULL, *msgid = NULL;
  mu_header_t hdr;
  int rc;
  
  rc = mu_message_get_header (msg, &hdr);
  if (rc)
    return rc;
  get_msgid_header (hdr, MU_HEADER_MESSAGE_ID, &msgid);
  if (get_msgid_header (hdr, MU_HEADER_REFERENCES, &ref))
    get_msgid_header (hdr, MU_HEADER_IN_REPLY_TO, &ref);

  if (ref || msgid)
    {
      *pstr = concat (ref, msgid);
      free (ref);
      free (msgid);
      return 0;
    }
  return MU_ERR_FAILURE;
}

int
mu_rfc2822_msg_id (int subpart, char **pval)
{
  char date[4+2+2+2+2+2+1];
  time_t t = time (NULL);
  struct tm *tm = localtime (&t);
  char *host;
  char *p;
	  
  mu_strftime (date, sizeof date, "%Y%m%d%H%M%S", tm);
  mu_get_host_name (&host);

  if (subpart)
    {
      struct timeval tv;
      gettimeofday (&tv, NULL);
      mu_asprintf (&p, "<%s.%lu.%d@%s>",
		   date,
		   (unsigned long) getpid (),
		   subpart,
		   host);
    }
  else
    mu_asprintf (&p, "<%s.%lu@%s>", date, (unsigned long) getpid (), host);
  free (host);
  *pval = p;
  return 0;
}

#define DATEBUFSIZE 128
#define COMMENT "Your message of "

/*
   The "In-Reply-To:" field will contain the contents of the "Message-
   ID:" field of the message to which this one is a reply (the "parent
   message").  If there is more than one parent message, then the "In-
   Reply-To:" field will contain the contents of all of the parents'
   "Message-ID:" fields.  If there is no "Message-ID:" field in any of
   the parent messages, then the new message will have no "In-Reply-To:"
   field.
*/
int
mu_rfc2822_in_reply_to (mu_message_t msg, char **pstr)
{
  const char *value = NULL;
  char *s1 = NULL, *s2 = NULL;
  mu_header_t hdr;
  int rc;
  
  rc = mu_message_get_header (msg, &hdr);
  if (rc)
    return rc;
  
  if (mu_header_sget_value (hdr, MU_HEADER_DATE, &value))
    {
      mu_envelope_t envelope = NULL;
      mu_message_get_envelope (msg, &envelope);
      mu_envelope_sget_date (envelope, &value);
    }

  if (value)
    {
      s1 = malloc (sizeof (COMMENT) + strlen (value));
      if (!s1)
	return ENOMEM;
      strcat (strcpy (s1, COMMENT), value);
    }
  
  if (mu_header_sget_value (hdr, MU_HEADER_MESSAGE_ID, &value) == 0)
    {
      s2 = malloc (strlen (value) + 3);
      if (!s2)
	{
	  free (s1);
	  return ENOMEM;
	}
      strcat (strcpy (s2, "\n\t"), value);
    }

  if (s1 || s2)
    {
      *pstr = concat (s1, s2);
      free (s1);
      free (s2);
      return 0;
    }
  return MU_ERR_FAILURE;
}

/* Based on strstr from GNU libc (Stephen R. van den Berg,
   berg@pool.informatik.rwth-aachen.de) */

char *
mu_strcasestr (const char *a_haystack, const char *a_needle)
{
  register const unsigned char *haystack = (unsigned char*) a_haystack,
    *needle = (unsigned char*) a_needle;
  register unsigned int b, c;

#define U(c) mu_toupper (c)
  if ((b = U (*needle)))
    {
      haystack--;		
      do
	{
	  if (!(c = *++haystack))
	    goto ret0;
	}
      while (U (c) != b);

      if (!(c = *++needle))
	goto foundneedle;

      c = U (c);
      ++needle;
      goto jin;

      for (;;)
        { 
          register unsigned int a;
	  register const unsigned char *rhaystack, *rneedle;

	  do
	    {
	      if (!(a = *++haystack))
		goto ret0;
	      if (U (a) == b)
		break;
	      if (!(a = *++haystack))
		goto ret0;
shloop:       ;
            }
          while (U (a) != b);
	  
jin:     if (!(a = *++haystack))
	    goto ret0;

	  if (U (a) != c)
	    goto shloop;

	  if (U (*(rhaystack = haystack-- + 1)) ==
	      (a = U (*(rneedle = needle))))
	    do
	      {
		if (!a)
		  goto foundneedle;
		if (U (*++rhaystack) != (a = U (*++needle)))
		  break;
		if (!a)
		  goto foundneedle;
	      }
	    while (U (*++rhaystack) == (a = U (*++needle)));

	  needle = rneedle;

	  if (!a)
	    break;
        }
    }
foundneedle:
  return (char*)haystack;
ret0:
  return NULL;

#undef U
}  

int
mu_string_unfold (char *text, size_t *plen)
{
  char *p, *q;
  enum uf_state { uf_init, uf_nl, uf_fold } state = uf_init;
#define ISSPACE(c) (c == '\r' || c == ' ' || c == '\t')
  
  if (!text)
    return EINVAL;
  
  for (p = q = text; *q; q++)
    {
      switch (state)
	{
	case uf_init:
	  if (*q == '\n')
	    state = uf_nl;
	  else
	    *p++ = *q;
	  break;

	case uf_nl:
	  if (ISSPACE (*q))
	    state = uf_fold;
	  else
	    {
	      state = uf_init;
	      *p++ = *q;
	    }
	  break;

	case uf_fold:
	  if (!ISSPACE (*q))
	    {
	      *p++ = ' ';
	      *p++ = *q;
	      state = uf_init;
	    }
	  break;
	}
    }
  
  *p++ = 0;
  if (plen)
    *plen = p - text;
  return 0;
}

int
mu_true_answer_p (const char *p)
{
  if (!p)
    return -1;

  while (*p && isspace (*p))
    p++;

  if (*p)
    {
      /* TRANSLATORS: This is a list of characters which start
	 an affirmative answer. Whenever possible, please preserve
	 'yY' in your translation, e.g., for Euskara:

	 msgstr "yYbB";
      */
      if (strchr (_("yY"), *p))
	return 1;

      /* TRANSLATORS: This is a list of characters which start
	 a negative answer. Whenever possible, please preserve
	 'nN' in your translation, e.g., for Euskara:

	 msgstr "nNeE";
      */
      else if (strchr (_("nN"), *p))
	return 0;
    }
  return -1;
}

/* Returns true if SCHEME represents a local (autodetect) mail folder.  */
int
mu_scheme_autodetect_p (mu_url_t url)
{
  if (mu_url_is_scheme (url, "file"))
    {
      mu_url_expand_path (url);
      return 1;
    }
  return 0;
}
    
int
mu_fd_wait (int fd, int *pflags, struct timeval *tvp)
{
  fd_set rdset, wrset, exset;
  int rc;

  FD_ZERO (&rdset);
  FD_ZERO (&wrset);
  FD_ZERO (&exset);
  if ((*pflags) & MU_STREAM_READY_RD)
    FD_SET (fd, &rdset);
  if ((*pflags) & MU_STREAM_READY_WR)
    FD_SET (fd, &wrset);
  if ((*pflags) & MU_STREAM_READY_EX)
    FD_SET (fd, &exset);
  
  do
    {
      if (tvp)
	{
	  struct timeval tv = *tvp; 
	  rc = select (fd + 1, &rdset, &wrset, &exset, &tv);
	}
      else
	rc = select (fd + 1, &rdset, &wrset, &exset, NULL);
    }
  while (rc == -1 && errno == EINTR);

  if (rc < 0)
    return errno;
  
  *pflags = 0;
  if (rc > 0)
    {
      if (FD_ISSET (fd, &rdset))
	*pflags |= MU_STREAM_READY_RD;
      if (FD_ISSET (fd, &wrset))
	*pflags |= MU_STREAM_READY_WR;
      if (FD_ISSET (fd, &exset))
	*pflags |= MU_STREAM_READY_EX;
    }
  return 0;
}

enum mu_iconv_fallback_mode mu_default_fallback_mode = mu_fallback_copy_octal;

int
mu_set_default_fallback (const char *str)
{
  if (strcmp (str, "none") == 0)
    mu_default_fallback_mode = mu_fallback_none;
  else if (strcmp (str, "copy-pass") == 0)
    mu_default_fallback_mode = mu_fallback_copy_pass;
  else if (strcmp (str, "copy-octal") == 0)
    mu_default_fallback_mode = mu_fallback_copy_octal;
  else
    return EINVAL;
  return 0;
}

int
mu_decode_filter (mu_stream_t *pfilter, mu_stream_t input,
		  const char *filter_type,
		  const char *fromcode, const char *tocode)
{
  mu_stream_t filter;
  
  int status = mu_filter_create (&filter, input, filter_type,
				 MU_FILTER_DECODE, MU_STREAM_READ);
  if (status)
    return status;

  if (fromcode && tocode && mu_c_strcasecmp (fromcode, tocode))
    {
      mu_stream_t cvt;
      status = mu_filter_iconv_create (&cvt, filter, fromcode, tocode,
				    MU_STREAM_NO_CLOSE,
				    mu_default_fallback_mode);
      if (status == 0)
	{
	  if (mu_stream_open (cvt))
	    mu_stream_destroy (&cvt, mu_stream_get_owner (cvt));
	  else
	    {
	      int flags;
	      mu_stream_get_flags (cvt, &flags);
	      flags &= ~MU_STREAM_NO_CLOSE;
	      mu_stream_set_flags (cvt, flags);
	      filter = cvt;
	    }
	}
    }
  *pfilter = filter;
  return 0;
}

int
mu_is_proto (const char *p)
{
  if (*p == '|')
    return 1;
  for (; *p && *p != '/'; p++)
    if (*p == ':')
      return 1;
  return 0;
}

int
mu_mh_delim (const char *str)
{
  if (str[0] == '-')
    {
      for (; *str == '-'; str++)
	;
      for (; *str == ' ' || *str == '\t'; str++)
	;
    }
  return str[0] == '\n';
}

char *
__argp_base_name (const char *arg)
{
  char *p = strrchr (arg, '/');
  return (char *)(p ? p + 1 : arg);
}

/* A locale-independent version of strftime */
size_t
mu_strftime (char *s, size_t max, const char *format, const struct tm *tm)
{
  size_t size;
  mu_set_locale ("C");
  size = strftime(s, max, format, tm);
  mu_restore_locale ();
  return size;
}
  

static void
assoc_str_free (void *data)
{
  free (data);
}

int
mutil_parse_field_map (const char *map, mu_assoc_t *passoc_tab, int *perr)
{
  int rc;
  int i;
  int argc;
  char **argv;
  mu_assoc_t assoc_tab = NULL;

  rc = mu_argcv_get (map, ":", NULL, &argc, &argv);
  if (rc)
    {
      mu_error (_("cannot split line `%s': %s"), map, mu_strerror (rc));
      return rc;
    }

  for (i = 0; i < argc; i += 2)
    {
      char *tok = argv[i];
      char *p = strchr (tok, '=');
      char *pptr;
      
      if (!p)
	{
	  rc = EINVAL;
	  break;
	}
      if (!assoc_tab)
	{
	  rc = mu_assoc_create (&assoc_tab, sizeof(char*), 0);
	  if (rc)
	    break;
	  mu_assoc_set_free (assoc_tab, assoc_str_free);
	  *passoc_tab = assoc_tab;
	}
      *p++ = 0;
      pptr = strdup (p);
      if (!pptr)
	{
	  rc = errno;
	  break;
	}
      rc = mu_assoc_install (assoc_tab, tok, &pptr);
      if (rc)
	{
	  free (p);
	  break;
	}
    }

  mu_argcv_free (argc, argv);
  if (rc && perr)
    *perr = i;
  return rc;
}

/* FIXME: should it be here? */
int
mu_sql_decode_password_type (const char *arg, enum mu_password_type *t)
{
  if (strcmp (arg, "plain") == 0)
    *t = password_plaintext;
  else if (strcmp (arg, "hash") == 0)
    *t = password_hash;
  else if (strcmp (arg, "scrambled") == 0)
    *t = password_scrambled;
  else
    return 1;
  return 0;
}

int
mu_stream_flags_to_mode (int flags, int isdir)
{
  int mode = 0;
  if (flags & MU_STREAM_IRGRP)
    mode |= S_IRGRP;
  if (flags & MU_STREAM_IWGRP)
    mode |= S_IWGRP;
  if (flags & MU_STREAM_IROTH)
    mode |= S_IROTH;
  if (flags & MU_STREAM_IWOTH)
    mode |= S_IWOTH;

  if (isdir)
    {
      if (mode & (S_IRGRP|S_IWGRP))
	mode |= S_IXGRP;
      if (mode & (S_IROTH|S_IWOTH))
	mode |= S_IXOTH;
    }
  
  return mode;
}