mutil.c 15.8 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
/* Copyright (C) 2001 Free Software Foundation, Inc.
   A wrapper for mktime function allowing to specify the timezone.

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

   The GNU C 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with the GNU C Library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.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 <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

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

#include <mailutils/error.h>
#include <mailutils/iterator.h>
#include <mailutils/mutil.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;
}

/* Convert struct tm into time_t, taking into account timezone offset.

 mktime() always treats tm as if it was localtime, so convert it
 to UTC, then adjust by the tm's real timezone, if it is known.

 NOTE: 1. mktime converts localtime struct tm to *time_t in UTC*
       2. adding mu_utc_offset() compensates for the localtime
          corrections in mktime(), i.e. it yields the time_t in
	  the current zone of struct tm.
       3. finally, subtracting TZ offset yields the UTC.
*/
time_t
mu_tm2time (struct tm *timeptr, mu_timezone* tz)
{
  int offset = tz ? tz->utc_offset : 0;

  return mktime (timeptr) + mu_utc_offset () - offset;
}

/* Convert time 0 at UTC to our localtime, that tells us the offset
   of our current timezone from UTC. */
time_t
mu_utc_offset (void)
{
  time_t t = 0;
  struct tm* tm = gmtime (&t);

  return - mktime (tm);
}

static const char *months[] =
{
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
};

static const char *wdays[] =
{
  "Sun", "Mon", "Teu", "Wed", "Thr", "Fri", "Sat", NULL
};

int
mu_parse_imap_date_time (const char **p, struct tm *tm, mu_timezone *tz)
{
  int year, mon, day, hour, min, sec;
  char zone[6] = "+0000";	/* ( "+" / "-" ) hhmm */
  char month[5] = "";
  int hh = 0;
  int mm = 0;
  int sign = 1;
  int scanned = 0, scanned3;
  int i;
  int tzoffset;

  day = mon = year = hour = min = sec = 0;

  memset (tm, 0, sizeof (*tm));

  switch (sscanf (*p,
		  "%2d-%3s-%4d%n %2d:%2d:%2d %5s%n",
		  &day, month, &year, &scanned3, &hour, &min, &sec, zone,
		  &scanned))
    {
    case 3:
      scanned = scanned3;
      break;
    case 7:
      break;
    default:
      return -1;
    }

  tm->tm_sec = sec;
  tm->tm_min = min;
  tm->tm_hour = hour;
  tm->tm_mday = day;

  for (i = 0; i < 12; i++)
    {
      if (strncasecmp (month, months[i], 3) == 0)
	{
	  mon = i;
	  break;
	}
    }
  tm->tm_mon = mon;
  tm->tm_year = (year > 1900) ? year - 1900 : year;
  tm->tm_yday = 0;		/* unknown. */
  tm->tm_wday = 0;		/* unknown. */
#if HAVE_TM_ISDST
  tm->tm_isdst = -1;		/* unknown. */
#endif

  hh = (zone[1] - '0') * 10 + (zone[2] - '0');
  mm = (zone[3] - '0') * 10 + (zone[4] - '0');
  sign = (zone[0] == '-') ? -1 : +1;
  tzoffset = sign * (hh * 60 * 60 + mm * 60);

#if HAVE_TM_GMTOFFSET
  tm->tm_gmtoffset = tzoffset;
#endif

  if (tz)
    {
      tz->utc_offset = tzoffset;
      tz->tz_name = NULL;
    }

  *p += scanned;

  return 0;
}

/* "ctime" format is: Thu Jul 01 15:58:27 1999, with no trailing \n.  */
int
mu_parse_ctime_date_time (const char **p, struct tm *tm, mu_timezone * tz)
{
  int wday = 0;
  int year = 0;
  int mon = 0;
  int day = 0;
  int hour = 0;
  int min = 0;
  int sec = 0;
  int n = 0;
  int i;
  char weekday[5] = "";
  char month[5] = "";

  if (sscanf (*p, "%3s %3s %2d %2d:%2d:%2d %d%n\n",
	weekday, month, &day, &hour, &min, &sec, &year, &n) != 7)
    return -1;

  *p += n;

  for (i = 0; i < 7; i++)
    {
      if (strncasecmp (weekday, wdays[i], 3) == 0)
	{
	  wday = i;
	  break;
	}
    }

  for (i = 0; i < 12; i++)
    {
      if (strncasecmp (month, months[i], 3) == 0)
	{
	  mon = i;
	  break;
	}
    }

  if (tm)
    {
      memset (tm, 0, sizeof (struct tm));

      tm->tm_sec = sec;
      tm->tm_min = min;
      tm->tm_hour = hour;
      tm->tm_mday = day;
      tm->tm_wday = wday;
      tm->tm_mon = mon;
      tm->tm_year = (year > 1900) ? year - 1900 : year;
#ifdef HAVE_TM_ISDST
      tm->tm_isdst = -1;	/* unknown. */
#endif
    }

  /* ctime has no timezone information, set tz to UTC if they ask. */
  if (tz)
    memset (tz, 0, sizeof (struct mu_timezone));

  return 0;
}

char *
mu_get_homedir (void)
{
  char *homedir = getenv ("HOME");
  if (!homedir)
    {
      struct passwd *pwd;

      pwd = mu_getpwuid (getuid ());
      if (!pwd)
	return NULL;
      homedir = pwd->pw_dir;
    }
  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 *p = strdup (ref);

  if (*p == '~')
    {
      p++;
      if (*p == delim[0] || *p == '\0')
        {
	  char *s;
	  if (!homedir)
	    {
	      homedir = mu_get_homedir ();
	      if (!homedir)
		return NULL;
	    }
	  s = calloc (strlen (homedir) + strlen (p) + 1, 1);
          strcpy (s, homedir);
          strcat (s, p);
          free (--p);
          p = s;
        }
      else
        {
          struct passwd *pw;
          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';
          pw = mu_getpwnam (name);
          free (name);
          if (pw)
            {
              char *buf = calloc (strlen (pw->pw_dir) + strlen (s) + 1, 1);
              strcpy (buf, pw->pw_dir);
              strcat (buf, s);
              free (--p);
              p = buf;
            }
          else
            p--;
        }
    }
  return p;
}

/* 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 (list_t *pflist, mu_retrieve_fp fun)
{
  if (!*pflist && list_create (pflist))
    return;
  list_append (*pflist, fun);
}

void *
mu_retrieve (list_t flist, void *data)
{
  void *p = NULL;
  iterator_t itr;

  if (iterator_create (&itr, flist) == 0)
    {
      mu_retrieve_fp fun;
      for (iterator_first (itr); !p && !iterator_is_done (itr);
	   iterator_next (itr))
	{
	  iterator_current (itr, (void **)&fun);
	  p = (*fun) (data);
	}

      iterator_destroy (&itr);
    }
  return p;
}

/* getpwd support: */

static list_t _app_getpwnam = NULL;

void
mu_register_getpwnam (struct passwd *(*fun) __P((const char *)))
{
  mu_register_retriever (&_app_getpwnam, (mu_retrieve_fp)fun);
}

struct passwd *
mu_getpwnam (const char *name)
{
  struct passwd *p = getpwnam (name);
  return p ? p : mu_retrieve (_app_getpwnam, (void*) name);
}

/* getpwuid support: */

static list_t _app_getpwuid = NULL;

void
mu_register_getpwuid (struct passwd *(*fun) __P((uid_t)))
{
  mu_register_retriever (&_app_getpwuid, (mu_retrieve_fp)fun);
}

struct passwd *
mu_getpwuid (uid_t uid)
{
  struct passwd *p = getpwuid (uid);
  return p ? p : mu_retrieve (_app_getpwuid, &uid);
}

/* Virtual domains */

int mu_virtual_domain;

#ifdef USE_VIRTUAL_DOMAINS

struct passwd *
getpwnam_virtual (const char *u)
{
  struct passwd *pw = NULL;
  FILE *pfile;
  size_t i = 0, len = strlen (u), delim = 0;
  char *filename;

  mu_virtual_domain = 0;
  for (i = 0; i < len && delim == 0; i++)
    if (u[i] == '!' || u[i] == ':' || u[i] == '@')
      delim = i;

  if (delim == 0)
    return NULL;

  filename = malloc (strlen (SITE_VIRTUAL_PWDDIR) +
		     strlen (&u[delim + 1]) + 2 /* slash and null byte */);
  if (filename == NULL)
    return NULL;

  sprintf (filename, "%s/%s", SITE_VIRTUAL_PWDDIR, &u[delim + 1]);
  pfile = fopen (filename, "r");
  free (filename);

  if (pfile)
    while ((pw = fgetpwent (pfile)) != NULL)
      {
	if (strlen (pw->pw_name) == delim && !strncmp (u, pw->pw_name, delim))
	  {
	    mu_virtual_domain = 1;
	    break;
	  }
      }

  return pw;
}

#endif

char *
mu_get_user_email (char *name)
{
  char hostname[256];
  struct hostent *hp;
  char *domainpart;
  char *email;

  if (!name)
    {
      struct passwd *pw = getpwuid (getuid ());
      if (!pw)
	{
	  errno = EINVAL;
	  return NULL;
	}
      name = pw->pw_name;
    }

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

  if ((hp = gethostbyname (hostname)))
    domainpart = hp->h_name;
  else
    domainpart = hostname;
  email = malloc (strlen (name) + strlen (domainpart) + 2);
  if (!email)
    {
      errno = ENOMEM;
      return NULL;
    }
  sprintf (email, "%s@%s", name, domainpart);
  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/../..      -->   /

   FIXME: delim is superfluous. The function deals with unix filesystem
   paths, so delim should be always "/" */
char *
mu_normalize_path (char *path, const char *delim)
{
  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] == delim[0])
    path[len-1] = 0;

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

	      /* Find previous delimiter */
	      for (q = p-2; *q != delim[0] && 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] = delim[0];
      path[1] = 0;
    }

  return path;
}

char *
mu_normalize_maildir (const char *dir)
{
  int len = strlen (dir);
  if (dir[len-1] == '/')
    return strdup (dir);
  else if (strncasecmp (dir, "mbox:", 5) == 0 && dir[len-1] == '=')
    {
      if (len > 5 && strcmp (dir + len - 5, "user=") == 0)
	return strdup (dir);
      else
	return NULL;
    }
  else
    {
      char *p = malloc (strlen (dir) + 2);
      strcat (strcpy (p, dir), "/");
      return p;
    }
}

/* Create and open a temporary file. Be vary 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 ("Can not open temporary file: %s", strerror(errno));
      free (filename);
      return -1;
    }

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

  return fd;
}

/* 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, const char* const 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;
  char** av = (char**) av_;

  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)
    return errno;

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

  if (sigprocmask (SIG_BLOCK, &chldmask, &savemask) < 0)
    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 (av[0], 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;
}