Пример #1
0
/* Give the process appropriate permissions for a child process.
   This is like user_access, but you can't get back to make_access.  */
void
child_access (void)
{
#ifdef  GETLOADAVG_PRIVILEGED

  if (!access_inited)
    abort ();

  /* Set both the real and effective UID and GID to the user's.
     They cannot be changed back to make's.  */

#ifndef HAVE_SETREUID
  if (setuid (user_uid) < 0)
    pfatal_with_name ("child_access: setuid");
#else
  if (setreuid (user_uid, user_uid) < 0)
    pfatal_with_name ("child_access: setreuid");
#endif

#ifndef HAVE_SETREGID
  if (setgid (user_gid) < 0)
    pfatal_with_name ("child_access: setgid");
#else
  if (setregid (user_gid, user_gid) < 0)
    pfatal_with_name ("child_access: setregid");
#endif

  log_access (_("Child access"));

#endif  /* GETLOADAVG_PRIVILEGED */
}
Пример #2
0
/* Compile an entire file of output from cpp, named NAME.
   Write a file of assembly output and various debugging dumps.  */
static void compile_file(char *name)
{
  FILE *ifile;

#if !USE_CPPLIB
  /* Open input file.  */

  if (name == 0 || !strcmp (name, "-"))
    {
      ifile = stdin;
      name = "stdin";
    }
  else
    ifile = fopen (name, "r");
  if (ifile == 0)
    pfatal_with_name (name);

#ifdef IO_BUFFER_SIZE
  setvbuf(ifile, (char *) xmalloc (IO_BUFFER_SIZE), _IOFBF, IO_BUFFER_SIZE);
#endif
#endif /* !USE_CPPLIB */

  set_nomem_handler(outofmemory);

  set_input(ifile, name);
  init_lex(); /* needs to go before init_semantics, since inits
		 dummy_location */
  init_semantics();

  if (yyparse () != 0)
    {
      if (errorcount == 0)
	fprintf (stderr, "Errors detected in input file (your bison.simple is out of date)");
    }

  fclose (ifile);

  if (errorcount == 0)
    {
      /*if (flag_parse_only)
	{
	  fprintf(stderr, "\nDONE. Unparsing............\n\n");
	  unparse(stdout, the_program);
	}
      else
      exit(exec_cc1(the_program));*/

      if (the_program)
	{
	  parsed_file pf;

	  pf = ralloc(parse_region, struct parsed_file);
	  pf->name = name;
	  pf->program = the_program;
	  dd_add_last(parse_region, parsed_files, pf);

	  analyze(the_program);
	}
    }
}
Пример #3
0
/* Returns a file descriptor to a temporary file.  The file is automatically
   closed/deleted on exit.  Don't use a FILE* stream.  */
int
open_tmpfd ()
{
  int fd = -1;
  FILE *tfile = tmpfile ();

  if (! tfile)
    pfatal_with_name ("tmpfile");

  /* Create a duplicate so we can close the stream.  */
  fd = dup (fileno (tfile));
  if (fd < 0)
    pfatal_with_name ("dup");

  fclose (tfile);

  return fd;
}
Пример #4
0
static bool
sip (struct file_data *current, bool skip_test)
{
  /* If we have a nonexistent file at this stage, treat it as empty.  */
  if (current->desc < 0)
    {
      /* Leave room for a sentinel.  */
      current->bufsize = sizeof (word);
      current->buffer = xmalloc (current->bufsize);
    }
  else
    {
      current->bufsize = buffer_lcm (sizeof (word),
				     STAT_BLOCKSIZE (current->stat),
				     PTRDIFF_MAX - 2 * sizeof (word));
      current->buffer = xmalloc (current->bufsize);

#ifdef __KLIBC__
      /* Skip test if seek is not possible */
      skip_test = skip_test
		  || (lseek (current->desc, 0, SEEK_CUR) < 0
		      && errno == ESPIPE);
#endif

      if (! skip_test)
	{
	  /* Check first part of file to see if it's a binary file.  */

	  int prev_mode = set_binary_mode (current->desc, O_BINARY);
	  off_t buffered;
	  file_block_read (current, current->bufsize);
	  buffered = current->buffered;

	  if (prev_mode != O_BINARY)
	    {
	      /* Revert to text mode and seek back to the start to reread
		 the file.  Use relative seek, since file descriptors
		 like stdin might not start at offset zero.  */
	      if (lseek (current->desc, - buffered, SEEK_CUR) < 0)
		pfatal_with_name (current->name);
	      set_binary_mode (current->desc, prev_mode);
	      current->buffered = 0;
	      current->eof = false;
	    }

	  return binary_file_p (current->buffer, buffered);
	}
    }

  current->buffered = 0;
  current->eof = false;
  return false;
}
Пример #5
0
void
file_block_read (struct file_data *current, size_t size)
{
  if (size && ! current->eof)
    {
      size_t s = block_read (current->desc,
			     FILE_BUFFER (current) + current->buffered, size);
      if (s == SIZE_MAX)
	pfatal_with_name (current->name);
      current->buffered += s;
      current->eof = s < size;
    }
}
Пример #6
0
static bool
sip (struct file_data *current, bool skip_test)
{
  /* If we have a nonexistent file at this stage, treat it as empty.  */
  if (current->desc < 0)
    {
      /* Leave room for a sentinel.  */
      current->bufsize = sizeof (word);
      current->buffer = xmalloc (current->bufsize);
    }
  else
    {
      current->bufsize = buffer_lcm (sizeof (word),
				     STAT_BLOCKSIZE (current->stat),
				     PTRDIFF_MAX - 2 * sizeof (word));
      current->buffer = xmalloc (current->bufsize);

      if (! skip_test)
	{
	  /* Check first part of file to see if it's a binary file.  */

	  bool was_binary = set_binary_mode (current->desc, true);
	  off_t buffered;
	  file_block_read (current, current->bufsize);
	  buffered = current->buffered;

	  if (! was_binary)
	    {
	      /* Revert to text mode and seek back to the beginning to
		 reread the file.  Use relative seek, since file
		 descriptors like stdin might not start at offset
		 zero.  */

	      if (lseek (current->desc, - buffered, SEEK_CUR) == -1)
		pfatal_with_name (current->name);
	      set_binary_mode (current->desc, false);
	      current->buffered = 0;
	      current->eof = false;
	    }

	  return binary_file_p (current->buffer, buffered);
	}
    }

  current->buffered = 0;
  current->eof = false;
  return false;
}
Пример #7
0
static void
init_access (void)
{
#ifndef VMS
  user_uid = getuid ();
  user_gid = getgid ();

  make_uid = geteuid ();
  make_gid = getegid ();

  /* Do these ever fail?  */
  if (user_uid == -1 || user_gid == -1 || make_uid == -1 || make_gid == -1)
    pfatal_with_name ("get{e}[gu]id");

  log_access (_("Initialized access"));

  current_access = make;
#endif
}
Пример #8
0
/* Give the process appropriate permissions for access to
   make data (i.e., the load average).  */
void
make_access (void)
{
#ifdef  GETLOADAVG_PRIVILEGED

  if (!access_inited)
    init_access ();

  if (current_access == make)
    return;

  /* See comments in user_access, above.  */

#ifdef  HAVE_SETEUID
  if (seteuid (make_uid) < 0)
    pfatal_with_name ("make_access: seteuid");
#else
#ifndef HAVE_SETREUID
  if (setuid (make_uid) < 0)
    pfatal_with_name ("make_access: setuid");
#else
  if (setreuid (user_uid, make_uid) < 0)
    pfatal_with_name ("make_access: setreuid");
#endif
#endif

#ifdef  HAVE_SETEGID
  if (setegid (make_gid) < 0)
    pfatal_with_name ("make_access: setegid");
#else
#ifndef HAVE_SETREGID
  if (setgid (make_gid) < 0)
    pfatal_with_name ("make_access: setgid");
#else
  if (setregid (user_gid, make_gid) < 0)
    pfatal_with_name ("make_access: setregid");
#endif
#endif

  current_access = make;

  log_access (_("Make access"));

#endif  /* GETLOADAVG_PRIVILEGED */
}
Пример #9
0
int
child_execute_job (char *argv, struct child *child)
{
  int i;
  static struct dsc$descriptor_s cmddsc;
  static struct dsc$descriptor_s pnamedsc;
  static struct dsc$descriptor_s ifiledsc;
  static struct dsc$descriptor_s ofiledsc;
  static struct dsc$descriptor_s efiledsc;
  int have_redirection = 0;
  int have_append = 0;
  int have_newline = 0;

  int spflags = CLI$M_NOWAIT;
  int status;
  char *cmd = alloca (strlen (argv) + 512), *p, *q;
  char ifile[256], ofile[256], efile[256];
  int comnamelen;
  char procname[100];
  int in_string;

  /* Parse IO redirection.  */

  ifile[0] = 0;
  ofile[0] = 0;
  efile[0] = 0;
  child->comname = NULL;

  DB (DB_JOBS, ("child_execute_job (%s)\n", argv));

  while (isspace ((unsigned char)*argv))
    argv++;

  if (*argv == 0)
    return 0;

  sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
  pnamedsc.dsc$w_length = strlen(procname);
  pnamedsc.dsc$a_pointer = procname;
  pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
  pnamedsc.dsc$b_class = DSC$K_CLASS_S;

  in_string = 0;
  /* Handle comments and redirection. */
  for (p = argv, q = cmd; *p; p++, q++)
    {
      if (*p == '"')
        in_string = !in_string;
      if (in_string)
        {
          *q = *p;
          continue;
        }
      switch (*p)
        {
        case '#':
          *p-- = 0;
          *q-- = 0;
          break;
        case '\\':
          p++;
          if (*p == '\n')
            p++;
          if (isspace ((unsigned char)*p))
            {
              do { p++; } while (isspace ((unsigned char)*p));
              p--;
            }
          *q = *p;
          break;
        case '<':
          p = vms_redirect (&ifiledsc, ifile, p);
          *q = ' ';
          have_redirection = 1;
          break;
        case '>':
          have_redirection = 1;
          if (*(p-1) == '2')
            {
              q--;
              if (strncmp (p, ">&1", 3) == 0)
                {
                  p += 3;
                  strcpy (efile, "sys$output");
                  efiledsc.dsc$w_length = strlen(efile);
                  efiledsc.dsc$a_pointer = efile;
                  efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
                  efiledsc.dsc$b_class = DSC$K_CLASS_S;
                }
              else
                  p = vms_redirect (&efiledsc, efile, p);
            }
          else
            {
              if (*(p+1) == '>')
                {
                  have_append = 1;
                  p += 1;
                }
              p = vms_redirect (&ofiledsc, ofile, p);
            }
          *q = ' ';
          break;
        case '\n':
          have_newline = 1;
        default:
          *q = *p;
          break;
        }
    }
  *q = *p;
  while (isspace ((unsigned char)*--q))
    *q = '\0';

  if (strncmp (cmd, "builtin_", 8) == 0)
    {
      child->pid = 270163;
      child->efn = 0;
      child->cstatus = 1;

      DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));

      p = cmd + 8;

      if ((*(p) == 'c')
          && (*(p+1) == 'd')
          && ((*(p+2) == ' ') || (*(p+2) == '\t')))
        {
          p += 3;
          while ((*p == ' ') || (*p == '\t'))
            p++;
          DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
          if (chdir (p))
            return 0;
          else
            return 1;
        }
      else if ((*(p) == 'r')
               && (*(p+1) == 'm')
               && ((*(p+2) == ' ') || (*(p+2) == '\t')))
        {
          int in_arg;

          /* rm  */
          p += 3;
          while ((*p == ' ') || (*p == '\t'))
            p++;
          in_arg = 1;

          DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
          while (*p)
            {
              switch (*p)
                {
                case ' ':
                case '\t':
                  if (in_arg)
                    {
                      *p++ = ';';
                      in_arg = 0;
                    }
                  break;
                default:
                  break;
                }
              p++;
            }
        }
      else
        {
          printf (_("Unknown builtin command '%s'\n"), cmd);
          fflush (stdout);
          return 0;
        }
    }

  /* Create a *.com file if either the command is too long for
     lib$spawn, or the command contains a newline, or if redirection
     is desired. Forcing commands with newlines into DCLs allows to
     store search lists on user mode logicals.  */

  if (strlen (cmd) > MAXCMDLEN
      || (have_redirection != 0)
      || (have_newline != 0))
    {
      FILE *outfile;
      char c;
      char *sep;
      int alevel = 0;   /* apostrophe level */

      if (strlen (cmd) == 0)
        {
          printf (_("Error, empty command\n"));
          fflush (stdout);
          return 0;
        }

      outfile = output_tmpfile (&child->comname, "sys$scratch:CMDXXXXXX.COM");
      if (outfile == 0)
        pfatal_with_name (_("fopen (temporary file)"));
      comnamelen = strlen (child->comname);

      if (ifile[0])
        {
          fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
          DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
          ifiledsc.dsc$w_length = 0;
        }

      if (efile[0])
        {
          fprintf (outfile, "$ define sys$error %s\n", efile);
          DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
          efiledsc.dsc$w_length = 0;
        }

      if (ofile[0])
        if (have_append)
          {
            fprintf (outfile, "$ set noon\n");
            fprintf (outfile, "$ define sys$output %.*s\n", comnamelen-3, child->comname);
            DB (DB_JOBS, (_("Append output to %s\n"), ofile));
            ofiledsc.dsc$w_length = 0;
          }
        else
          {
            fprintf (outfile, "$ define sys$output %s\n", ofile);
            DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
            ofiledsc.dsc$w_length = 0;
          }

      p = sep = q = cmd;
      for (c = '\n'; c; c = *q++)
        {
          switch (c)
            {
            case '\n':
              /* At a newline, skip any whitespace around a leading $
                 from the command and issue exactly one $ into the DCL. */
              while (isspace ((unsigned char)*p))
                p++;
              if (*p == '$')
                p++;
              while (isspace ((unsigned char)*p))
                p++;
              fwrite (p, 1, q - p, outfile);
              fputc ('$', outfile);
              fputc (' ', outfile);
              /* Reset variables. */
              p = sep = q;
              break;

              /* Nice places for line breaks are after strings, after
                 comma or space and before slash. */
            case '"':
              q = vms_handle_apos (q);
              sep = q;
              break;
            case ',':
            case ' ':
              sep = q;
              break;
            case '/':
            case '\0':
              sep = q - 1;
              break;
            default:
              break;
            }
          if (sep - p > 78)
            {
              /* Enough stuff for a line. */
              fwrite (p, 1, sep - p, outfile);
              p = sep;
              if (*sep)
                {
                  /* The command continues.  */
                  fputc ('-', outfile);
                }
              fputc ('\n', outfile);
            }
        }

      if (*p)
        {
          fwrite (p, 1, --q - p, outfile);
          fputc ('\n', outfile);
        }

      if (have_append)
        {
          fprintf (outfile, "$ deassign sys$output ! 'f$verify(0)\n");
          fprintf (outfile, "$ append:=append\n");
          fprintf (outfile, "$ delete:=delete\n");
          fprintf (outfile, "$ append/new %.*s %s\n", comnamelen-3, child->comname, ofile);
          fprintf (outfile, "$ delete %.*s;*\n", comnamelen-3, child->comname);
          DB (DB_JOBS, (_("Append %.*s and cleanup\n"), comnamelen-3, child->comname));
        }

      fclose (outfile);

      sprintf (cmd, "$ @%s", child->comname);

      DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
    }

  cmddsc.dsc$w_length = strlen(cmd);
  cmddsc.dsc$a_pointer = cmd;
  cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
  cmddsc.dsc$b_class = DSC$K_CLASS_S;

  child->efn = 0;
  while (child->efn < 32 || child->efn > 63)
    {
      status = lib$get_ef ((unsigned long *)&child->efn);
      if (!(status & 1))
        {
          if (child->comname)
            {
              if (!ISDB (DB_JOBS))
                unlink (child->comname);
              free (child->comname);
            }
          return 0;
        }
    }

  sys$clref (child->efn);

  vms_jobsefnmask |= (1 << (child->efn - 32));

  /*
    LIB$SPAWN  [command-string]
    [,input-file]
    [,output-file]
    [,flags]
    [,process-name]
    [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
    [,AST-address] [,varying-AST-argument]
    [,prompt-string] [,cli] [,table]
  */

#ifndef DONTWAITFORCHILD
  /*
   * Code to make ctrl+c and ctrl+y working.
   * The problem starts with the synchronous case where after lib$spawn is
   * called any input will go to the child. But with input re-directed,
   * both control characters won't make it to any of the programs, neither
   * the spawning nor to the spawned one. Hence the caller needs to spawn
   * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
   * has to follow to simulate the wanted synchronous behaviour.
   * The next problem is ctrl+y which isn't caught by the crtl and
   * therefore isn't converted to SIGQUIT (for a signal handler which is
   * already established). The only way to catch ctrl+y, is an AST
   * assigned to the input channel. But ctrl+y handling of DCL needs to be
   * disabled, otherwise it will handle it. Not to mention the previous
   * ctrl+y handling of DCL needs to be re-established before make exits.
   * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
   * make it to the signal handler after the child "normally" terminates.
   * This isn't enough. It seems reasonable for simple command lines like
   * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
   * spawning make. Therefore we need to abort the process in the AST.
   *
   * Prior to the spawn it is checked if an AST is already set up for
   * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
   * this will work except if make is run in a batch environment, but there
   * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
   * is disabled and an exit handler is established to re-enable it.
   * If the user interrupts with ctrl+y, the assigned AST will fire, force
   * an abort to the subprocess and signal SIGQUIT, which will be caught by
   * the already established handler and will bring us back to common code.
   * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
   * enables the ctrl+y be delivered to this code. And the ctrl+c too,
   * which the crtl converts to SIGINT and which is caught by the common
   * signal handler. Because signals were blocked before entering this code
   * sys$waitfr will always complete and the SIGQUIT will be processed after
   * it (after termination of the current block, somewhere in common code).
   * And SIGINT too will be delayed. That is ctrl+c can only abort when the
   * current command completes. Anyway it's better than nothing :-)
   */

  if (!setupYAstTried)
    tryToSetupYAst();
  status = lib$spawn (&cmddsc,                                  /* cmd-string */
                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
                      &spflags,                                 /* flags */
                      &pnamedsc,                                /* proc name */
                      &child->pid, &child->cstatus, &child->efn,
                      0, 0,
                      0, 0, 0);
  if (status & 1)
    {
      status= sys$waitfr (child->efn);
      vmsHandleChildTerm(child);
    }
#else
  status = lib$spawn (&cmddsc,
                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
                      &spflags,
                      &pnamedsc,
                      &child->pid, &child->cstatus, &child->efn,
                      vmsHandleChildTerm, child,
                      0, 0, 0);
#endif

  if (!(status & 1))
    {
      printf (_("Error spawning, %d\n") ,status);
      fflush (stdout);
      switch (status)
        {
        case 0x1c:
          errno = EPROCLIM;
          break;
        default:
          errno = EFAIL;
        }
    }

  return (status & 1);
}
Пример #10
0
/* Give the process appropriate permissions for access to
   user data (i.e., to stat files, or to spawn a child process).  */
void
user_access (void)
{
#ifdef  GETLOADAVG_PRIVILEGED

  if (!access_inited)
    init_access ();

  if (current_access == user)
    return;

  /* We are in "make access" mode.  This means that the effective user and
     group IDs are those of make (if it was installed setuid or setgid).
     We now want to set the effective user and group IDs to the real IDs,
     which are the IDs of the process that exec'd make.  */

#ifdef  HAVE_SETEUID

  /* Modern systems have the seteuid/setegid calls which set only the
     effective IDs, which is ideal.  */

  if (seteuid (user_uid) < 0)
    pfatal_with_name ("user_access: seteuid");

#else   /* Not HAVE_SETEUID.  */

#ifndef HAVE_SETREUID

  /* System V has only the setuid/setgid calls to set user/group IDs.
     There is an effective ID, which can be set by setuid/setgid.
     It can be set (unless you are root) only to either what it already is
     (returned by geteuid/getegid, now in make_uid/make_gid),
     the real ID (return by getuid/getgid, now in user_uid/user_gid),
     or the saved set ID (what the effective ID was before this set-ID
     executable (make) was exec'd).  */

  if (setuid (user_uid) < 0)
    pfatal_with_name ("user_access: setuid");

#else   /* HAVE_SETREUID.  */

  /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
     They may be set to themselves or each other.  So you have two alternatives
     at any one time.  If you use setuid/setgid, the effective will be set to
     the real, leaving only one alternative.  Using setreuid/setregid, however,
     you can toggle between your two alternatives by swapping the values in a
     single setreuid or setregid call.  */

  if (setreuid (make_uid, user_uid) < 0)
    pfatal_with_name ("user_access: setreuid");

#endif  /* Not HAVE_SETREUID.  */
#endif  /* HAVE_SETEUID.  */

#ifdef  HAVE_SETEGID
  if (setegid (user_gid) < 0)
    pfatal_with_name ("user_access: setegid");
#else
#ifndef HAVE_SETREGID
  if (setgid (user_gid) < 0)
    pfatal_with_name ("user_access: setgid");
#else
  if (setregid (make_gid, user_gid) < 0)
    pfatal_with_name ("user_access: setregid");
#endif
#endif

  current_access = user;

  log_access (_("User access"));

#endif  /* GETLOADAVG_PRIVILEGED */
}
Пример #11
0
int
main (int argc, char **argv)
{
  char *inname, *outname;
  int indesc, outdesc;
  ssize_t nread;
  int wait_status;
  int c, preserve_mail = 0;

#ifndef MAIL_USE_SYSTEM_LOCK
  struct stat st;
  int tem;
  char *lockname;
  char *tempname;
  size_t inname_len, inname_dirlen;
  int desc;
#endif /* not MAIL_USE_SYSTEM_LOCK */

#ifdef MAIL_USE_MAILLOCK
  char *spool_name;
#endif

#ifdef MAIL_USE_POP
  int pop_reverse_order = 0;
# define ARGSTR "pr"
#else /* ! MAIL_USE_POP */
# define ARGSTR "p"
#endif /* MAIL_USE_POP */

  uid_t real_gid = getgid ();
  uid_t priv_gid = getegid ();

#ifdef WINDOWSNT
  /* Ensure all file i/o is in binary mode. */
  _fmode = _O_BINARY;
#endif

  delete_lockname = 0;

  while ((c = getopt (argc, argv, ARGSTR)) != EOF)
    {
      switch (c) {
#ifdef MAIL_USE_POP
      case 'r':
	pop_reverse_order = 1;
	break;
#endif
      case 'p':
	preserve_mail++;
	break;
      default:
	exit (EXIT_FAILURE);
      }
    }

  if (
#ifdef MAIL_USE_POP
      (argc - optind < 2) || (argc - optind > 3)
#else
      (argc - optind != 2)
#endif
      )
    {
#ifdef MAIL_USE_POP
      fprintf (stderr, "Usage: movemail [-p] [-r] inbox destfile%s\n",
	       " [POP-password]");
#else
      fprintf (stderr, "Usage: movemail [-p] inbox destfile%s\n", "");
#endif
      exit (EXIT_FAILURE);
    }

  inname = argv[optind];
  outname = argv[optind+1];

#ifdef MAIL_USE_MMDF
  mmdf_init (argv[0]);
#endif

  if (*outname == 0)
    fatal ("Destination file name is empty", 0, 0);

#ifdef MAIL_USE_POP
  if (!strncmp (inname, "po:", 3))
    {
      int status;

      status = popmail (inname + 3, outname, preserve_mail,
			(argc - optind == 3) ? argv[optind+2] : NULL,
			pop_reverse_order);
      exit (status);
    }

  if (setuid (getuid ()) < 0)
    fatal ("Failed to drop privileges", 0, 0);

#endif /* MAIL_USE_POP */

#ifndef DISABLE_DIRECT_ACCESS
#ifndef MAIL_USE_MMDF
#ifndef MAIL_USE_SYSTEM_LOCK
#ifdef MAIL_USE_MAILLOCK
  spool_name = mail_spool_name (inname);
  if (spool_name)
    {
#ifdef lint
      lockname = 0;
#endif
    }
  else
#endif
    {
      /* Use a lock file named after our first argument with .lock appended:
	 If it exists, the mail file is locked.  */
      /* Note: this locking mechanism is *required* by the mailer
	 (on systems which use it) to prevent loss of mail.

	 On systems that use a lock file, extracting the mail without locking
	 WILL occasionally cause loss of mail due to timing errors!

	 So, if creation of the lock file fails due to access
	 permission on the mail spool directory, you simply MUST
	 change the permission and/or make movemail a setgid program
	 so it can create lock files properly.

	 You might also wish to verify that your system is one which
	 uses lock files for this purpose.  Some systems use other methods.  */

      inname_len = strlen (inname);
      lockname = xmalloc (inname_len + sizeof ".lock");
      strcpy (lockname, inname);
      strcpy (lockname + inname_len, ".lock");
      for (inname_dirlen = inname_len;
	   inname_dirlen && !IS_DIRECTORY_SEP (inname[inname_dirlen - 1]);
	   inname_dirlen--)
	continue;
      tempname = xmalloc (inname_dirlen + sizeof "EXXXXXX");

      while (1)
	{
	  /* Create the lock file, but not under the lock file name.  */
	  /* Give up if cannot do that.  */

	  memcpy (tempname, inname, inname_dirlen);
	  strcpy (tempname + inname_dirlen, "EXXXXXX");
#ifdef HAVE_MKSTEMP
	  desc = mkstemp (tempname);
#else
	  mktemp (tempname);
	  if (!*tempname)
	    desc = -1;
	  else
	    {
	      unlink (tempname);
	      desc = open (tempname, O_WRONLY | O_CREAT | O_EXCL, 0600);
	    }
#endif
	  if (desc < 0)
	    {
	      int mkstemp_errno = errno;
	      error ("error while creating what would become the lock file",
		     0, 0);
	      errno = mkstemp_errno;
	      pfatal_with_name (tempname);
	    }
	  close (desc);

	  tem = link (tempname, lockname);

#ifdef EPERM
	  if (tem < 0 && errno == EPERM)
	    fatal ("Unable to create hard link between %s and %s",
		   tempname, lockname);
#endif

	  unlink (tempname);
	  if (tem >= 0)
	    break;
	  sleep (1);

	  /* If lock file is five minutes old, unlock it.
	     Five minutes should be good enough to cope with crashes
	     and wedgitude, and long enough to avoid being fooled
	     by time differences between machines.  */
	  if (stat (lockname, &st) >= 0)
	    {
	      time_t now = time (0);
	      if (st.st_ctime < now - 300)
		unlink (lockname);
	    }
	}

      delete_lockname = lockname;
    }
#endif /* not MAIL_USE_SYSTEM_LOCK */
#endif /* not MAIL_USE_MMDF */

  if (fork () == 0)
    {
      int lockcount = 0;
      int status = 0;
#if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
      time_t touched_lock;
# ifdef lint
      touched_lock = 0;
# endif
#endif

      if (setuid (getuid ()) < 0 || setregid (-1, real_gid) < 0)
	fatal ("Failed to drop privileges", 0, 0);

#ifndef MAIL_USE_MMDF
#ifdef MAIL_USE_SYSTEM_LOCK
      indesc = open (inname, O_RDWR);
#else  /* if not MAIL_USE_SYSTEM_LOCK */
      indesc = open (inname, O_RDONLY);
#endif /* not MAIL_USE_SYSTEM_LOCK */
#else  /* MAIL_USE_MMDF */
      indesc = lk_open (inname, O_RDONLY, 0, 0, 10);
#endif /* MAIL_USE_MMDF */

      if (indesc < 0)
	pfatal_with_name (inname);

#ifdef BSD_SYSTEM
      /* In case movemail is setuid to root, make sure the user can
	 read the output file.  */
      /* This is desirable for all systems
	 but I don't want to assume all have the umask system call */
      umask (umask (0) & 0333);
#endif /* BSD_SYSTEM */
      outdesc = open (outname, O_WRONLY | O_CREAT | O_EXCL, 0666);
      if (outdesc < 0)
	pfatal_with_name (outname);

      if (setregid (-1, priv_gid) < 0)
	fatal ("Failed to regain privileges", 0, 0);

      /* This label exists so we can retry locking
	 after a delay, if it got EAGAIN or EBUSY.  */
    retry_lock:

      /* Try to lock it.  */
#ifdef MAIL_USE_MAILLOCK
      if (spool_name)
	{
	  /* The "0 - " is to make it a negative number if maillock returns
	     non-zero. */
	  status = 0 - maillock (spool_name, 1);
#ifdef HAVE_TOUCHLOCK
	  touched_lock = time (0);
#endif
	  lockcount = 5;
	}
      else
#endif /* MAIL_USE_MAILLOCK */
	{
#ifdef MAIL_USE_SYSTEM_LOCK
#ifdef MAIL_USE_LOCKF
	  status = lockf (indesc, F_LOCK, 0);
#else /* not MAIL_USE_LOCKF */
#ifdef WINDOWSNT
	  status = locking (indesc, LK_RLCK, -1L);
#else
	  status = flock (indesc, LOCK_EX);
#endif
#endif /* not MAIL_USE_LOCKF */
#endif /* MAIL_USE_SYSTEM_LOCK */
	}

      /* If it fails, retry up to 5 times
	 for certain failure codes.  */
      if (status < 0)
	{
	  if (++lockcount <= 5)
	    {
#ifdef EAGAIN
	      if (errno == EAGAIN)
		{
		  sleep (1);
		  goto retry_lock;
		}
#endif
#ifdef EBUSY
	      if (errno == EBUSY)
		{
		  sleep (1);
		  goto retry_lock;
		}
#endif
	    }

	  pfatal_with_name (inname);
	}

      {
	char buf[1024];

	while (1)
	  {
	    nread = read (indesc, buf, sizeof buf);
	    if (nread < 0)
	      pfatal_with_name (inname);
	    if (nread != write (outdesc, buf, nread))
	      {
		int saved_errno = errno;
		unlink (outname);
		errno = saved_errno;
		pfatal_with_name (outname);
	      }
	    if (nread < sizeof buf)
	      break;
#if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
	    if (spool_name)
	      {
		time_t now = time (0);
		if (now - touched_lock > 60)
		  {
		    touchlock ();
		    touched_lock = now;
		  }
	      }
#endif /* MAIL_USE_MAILLOCK */
	  }
      }

#ifdef BSD_SYSTEM
      if (fsync (outdesc) < 0)
	pfatal_and_delete (outname);
#endif

      /* Prevent symlink attacks truncating other users' mailboxes */
      if (setregid (-1, real_gid) < 0)
	fatal ("Failed to drop privileges", 0, 0);

      /* Check to make sure no errors before we zap the inbox.  */
      if (close (outdesc) != 0)
	pfatal_and_delete (outname);

#ifdef MAIL_USE_SYSTEM_LOCK
      if (! preserve_mail)
	{
	  if (ftruncate (indesc, 0L) != 0)
	    pfatal_with_name (inname);
	}
#endif /* MAIL_USE_SYSTEM_LOCK */

#ifdef MAIL_USE_MMDF
      lk_close (indesc, 0, 0, 0);
#else
      close (indesc);
#endif

#ifndef MAIL_USE_SYSTEM_LOCK
      if (! preserve_mail)
	{
	  /* Delete the input file; if we can't, at least get rid of its
	     contents.  */
#ifdef MAIL_UNLINK_SPOOL
	  /* This is generally bad to do, because it destroys the permissions
	     that were set on the file.  Better to just empty the file.  */
	  if (unlink (inname) < 0 && errno != ENOENT)
#endif /* MAIL_UNLINK_SPOOL */
	    creat (inname, 0600);
	}
#endif /* not MAIL_USE_SYSTEM_LOCK */

      /* End of mailbox truncation */
      if (setregid (-1, priv_gid) < 0)
	fatal ("Failed to regain privileges", 0, 0);

#ifdef MAIL_USE_MAILLOCK
      /* This has to occur in the child, i.e., in the process that
         acquired the lock! */
      if (spool_name)
	mailunlock ();
#endif
      exit (EXIT_SUCCESS);
    }

  wait (&wait_status);
  if (!WIFEXITED (wait_status))
    exit (EXIT_FAILURE);
  else if (WEXITSTATUS (wait_status) != 0)
    exit (WEXITSTATUS (wait_status));

#if !defined (MAIL_USE_MMDF) && !defined (MAIL_USE_SYSTEM_LOCK)
#ifdef MAIL_USE_MAILLOCK
  if (! spool_name)
#endif /* MAIL_USE_MAILLOCK */
    unlink (lockname);
#endif /* not MAIL_USE_MMDF and not MAIL_USE_SYSTEM_LOCK */

#endif /* ! DISABLE_DIRECT_ACCESS */

  return EXIT_SUCCESS;
}
Пример #12
0
RETSIGTYPE
fatal_error_signal (int sig)
{
#ifdef __MSDOS__
    extern int dos_status, dos_command_running;

    if (dos_command_running)
    {
        /* That was the child who got the signal, not us.  */
        dos_status |= (sig << 8);
        return;
    }
    remove_intermediates (1);
    exit (EXIT_FAILURE);
#else /* not __MSDOS__ */
#ifdef _AMIGA
    remove_intermediates (1);
    if (sig == SIGINT)
        fputs (_("*** Break.\n"), stderr);

    exit (10);
#else /* not Amiga */
#ifdef WINDOWS32
    extern HANDLE main_thread;

    /* Windows creates a sperate thread for handling Ctrl+C, so we need
       to suspend the main thread, or else we will have race conditions
       when both threads call reap_children.  */
    if (main_thread)
    {
        DWORD susp_count = SuspendThread (main_thread);

        if (susp_count != 0)
            fprintf (stderr, "SuspendThread: suspend count = %ld\n", susp_count);
        else if (susp_count == (DWORD)-1)
        {
            DWORD ierr = GetLastError ();

            fprintf (stderr, "SuspendThread: error %ld: %s\n",
                     ierr, map_windows32_error_to_string (ierr));
        }
    }
#endif
    handling_fatal_signal = 1;

    /* Set the handling for this signal to the default.
       It is blocked now while we run this handler.  */
    signal (sig, SIG_DFL);

    /* A termination signal won't be sent to the entire
       process group, but it means we want to kill the children.  */

    if (sig == SIGTERM)
    {
        struct child *c;
        for (c = children; c != 0; c = c->next)
            if (!c->remote)
                (void) kill (c->pid, SIGTERM);
    }

    /* If we got a signal that means the user
       wanted to kill make, remove pending targets.  */

    if (sig == SIGTERM || sig == SIGINT
#ifdef SIGHUP
            || sig == SIGHUP
#endif
#ifdef SIGQUIT
            || sig == SIGQUIT
#endif
       )
    {
        struct child *c;

        /* Remote children won't automatically get signals sent
        to the process group, so we must send them.  */
        for (c = children; c != 0; c = c->next)
            if (c->remote)
                (void) remote_kill (c->pid, sig);

        for (c = children; c != 0; c = c->next)
            delete_child_targets (c);

        /* Clean up the children.  We don't just use the call below because
        we don't want to print the "Waiting for children" message.  */
        while (job_slots_used > 0)
            reap_children (1, 0);
    }
    else
        /* Wait for our children to die.  */
        while (job_slots_used > 0)
            reap_children (1, 1);

    /* Delete any non-precious intermediate files that were made.  */

    remove_intermediates (1);

#ifdef SIGQUIT
    if (sig == SIGQUIT)
        /* We don't want to send ourselves SIGQUIT, because it will
           cause a core dump.  Just exit instead.  */
        exit (EXIT_FAILURE);
#endif

#ifdef WINDOWS32
    if (main_thread)
        CloseHandle (main_thread);
    /* Cannot call W32_kill with a pid (it needs a handle).  The exit
       status of 130 emulates what happens in Bash.  */
    exit (130);
#else
    /* Signal the same code; this time it will really be fatal.  The signal
       will be unblocked when we return and arrive then to kill us.  */
    if (kill (getpid (), sig) < 0)
        pfatal_with_name ("kill");
#endif /* not WINDOWS32 */
#endif /* not Amiga */
#endif /* not __MSDOS__  */
}
Пример #13
0
int
child_execute_job (char *argv, struct child *child)
{
  int i;
  static struct dsc$descriptor_s cmddsc;
  static struct dsc$descriptor_s pnamedsc;
  static struct dsc$descriptor_s ifiledsc;
  static struct dsc$descriptor_s ofiledsc;
  static struct dsc$descriptor_s efiledsc;
  int have_redirection = 0;
  int have_append = 0;
  int have_newline = 0;

  int spflags = CLI$M_NOWAIT;
  int status;
  char *cmd = alloca (strlen (argv) + 512), *p, *q;
  char ifile[256], ofile[256], efile[256];
  int comnamelen;
  char procname[100];
  int in_string;

  /* Parse IO redirection.  */

  ifile[0] = 0;
  ofile[0] = 0;
  efile[0] = 0;
  child->comname = NULL;

  DB (DB_JOBS, ("child_execute_job (%s)\n", argv));

  while (isspace ((unsigned char)*argv))
    argv++;

  if (*argv == 0)
    return 0;

  sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
  pnamedsc.dsc$w_length = strlen(procname);
  pnamedsc.dsc$a_pointer = procname;
  pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
  pnamedsc.dsc$b_class = DSC$K_CLASS_S;

  in_string = 0;
  /* Handle comments and redirection.
     For ONESHELL, the redirection must be on the first line. Any other
     redirection token is handled by DCL, that is, the pipe command with
     redirection can be used, but it should not be used on the first line
     for ONESHELL. */
  for (p = argv, q = cmd; *p; p++, q++)
    {
      if (*p == '"')
        in_string = !in_string;
      if (in_string)
        {
          *q = *p;
          continue;
        }
      switch (*p)
        {
        case '#':
          *p-- = 0;
          *q-- = 0;
          break;
        case '\\':
          p++;
          if (*p == '\n')
            p++;
          if (isspace ((unsigned char)*p))
            {
              do { p++; } while (isspace ((unsigned char)*p));
              p--;
            }
          *q = *p;
          break;
        case '<':
          if (have_newline==0)
            {
              p = vms_redirect (&ifiledsc, ifile, p);
              *q = ' ';
              have_redirection = 1;
            }
          else
            *q = *p;
          break;
        case '>':
          if (have_newline==0)
            {
              have_redirection = 1;
              if (*(p-1) == '2')
                {
                  q--;
                  if (strncmp (p, ">&1", 3) == 0)
                    {
                      p += 2;
                      strcpy (efile, "sys$output");
                      efiledsc.dsc$w_length = strlen(efile);
                      efiledsc.dsc$a_pointer = efile;
                      efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
                      efiledsc.dsc$b_class = DSC$K_CLASS_S;
                    }
                  else
                    p = vms_redirect (&efiledsc, efile, p);
                }
              else
                {
                  if (*(p+1) == '>')
                    {
                      have_append = 1;
                      p += 1;
                    }
                  p = vms_redirect (&ofiledsc, ofile, p);
                }
              *q = ' ';
            }
          else
            *q = *p;
          break;
        case '\n':
          have_newline++;
        default:
          *q = *p;
          break;
        }
    }
  *q = *p;
  while (isspace ((unsigned char)*--q))
    *q = '\0';


#define VMS_EMPTY_ECHO "write sys$output \"\""
  if (have_newline == 0)
    {
      /* multiple shells */
      if (strncmp(cmd, "builtin_", 8) == 0)
        {
          child->pid = 270163;
          child->efn = 0;
          child->cstatus = 1;

          DB(DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd + 8));

          p = cmd + 8;

          if ((*(p) == 'c') && (*(p + 1) == 'd')
              && ((*(p + 2) == ' ') || (*(p + 2) == '\t')))
            {
              p += 3;
              while ((*p == ' ') || (*p == '\t'))
                p++;
              DB(DB_JOBS, (_("BUILTIN CD %s\n"), p));
              if (chdir(p))
                return 0;
              else
                return 1;
            }
          else if ((*(p) == 'e')
              && (*(p+1) == 'c')
              && (*(p+2) == 'h')
              && (*(p+3) == 'o')
              && ((*(p+4) == ' ') || (*(p+4) == '\t') || (*(p+4) == '\0')))
            {
              /* This is not a real builtin, it is a built in pre-processing
                 for the VMS/DCL echo (write sys$output) to ensure the to be echoed
                 string is correctly quoted (with the DCL quote character '"'). */
              char *vms_echo;
              p += 4;
              if (*p == '\0')
                cmd = VMS_EMPTY_ECHO;
              else
                {
                  p++;
                  while ((*p == ' ') || (*p == '\t'))
                    p++;
                  if (*p == '\0')
                    cmd = VMS_EMPTY_ECHO;
                  else
                    {
                      vms_echo = alloca(strlen(p) + sizeof VMS_EMPTY_ECHO);
                      strcpy(vms_echo, VMS_EMPTY_ECHO);
                      vms_echo[sizeof VMS_EMPTY_ECHO - 2] = '\0';
                      strcat(vms_echo, p);
                      strcat(vms_echo, "\"");
                      cmd = vms_echo;
                    }
                }
              DB (DB_JOBS, (_("BUILTIN ECHO %s->%s\n"), p, cmd));
            }
          else
            {
              printf(_("Unknown builtin command '%s'\n"), cmd);
              fflush(stdout);
              return 0;
            }
        }
      /* expand ':' aka 'do nothing' builtin for bash and friends */
      else if (cmd[0]==':' && cmd[1]=='\0')
        {
          cmd = "continue";
        }
    }
  else
    {
      /* todo: expand ':' aka 'do nothing' builtin for bash and friends */
      /* For 'one shell' expand all the
           builtin_echo
         to
           write sys$output ""
         where one is  ......7 bytes longer.
         At the same time ensure that the echo string is properly terminated.
         For that, allocate a command buffer big enough for all possible expansions
         (have_newline is the count), then expand, copy and terminate. */
      char *tmp_cmd;
      int nloff = 0;
      int vlen = 0;
      int clen = 0;
      int inecho;

      tmp_cmd = alloca(strlen(cmd) + (have_newline + 1) * 7 + 1);
      tmp_cmd[0] = '\0';
      inecho = 0;
      while (cmd[nloff])
        {
          if (inecho)
            {
              if (clen < nloff - 1)
                {
                  memcpy(&tmp_cmd[vlen], &cmd[clen], nloff - clen - 1);
                  vlen += nloff - clen - 1;
                  clen = nloff;
                }
              inecho = 0;
              tmp_cmd[vlen] = '"';
              vlen++;
              tmp_cmd[vlen] = '\n';
              vlen++;
            }
          if (strncmp(&cmd[nloff], "builtin_", 8) == 0)
            {
              /* ??? */
              child->pid = 270163;
              child->efn = 0;
              child->cstatus = 1;

              DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), &cmd[nloff], &cmd[nloff+8]));
              p = &cmd[nloff + 8];
              if ((*(p) ==        'e')
                  && (*(p + 1) == 'c')
                  && (*(p + 2) == 'h')
                  && (*(p + 3) == 'o')
                  && ((*(p + 4) == ' ') || (*(p + 4) == '\t') || (*(p + 4) == '\0')))
                {
                  if (clen < nloff - 1)
                    {
                      memcpy(&tmp_cmd[vlen], &cmd[clen], nloff - clen - 1);
                      vlen += nloff - clen - 1;
                      clen = nloff;
                      if (inecho)
                        {
                          inecho = 0;
                          tmp_cmd[vlen] = '"';
                          vlen++;
                        }
                      tmp_cmd[vlen] = '\n';
                      vlen++;
                    }
                  inecho = 1;
                  p += 4;
                  while ((*p == ' ') || (*p == '\t'))
                    p++;
                  clen = p - cmd;
                  memcpy(&tmp_cmd[vlen], VMS_EMPTY_ECHO,
                      sizeof VMS_EMPTY_ECHO - 2);
                  vlen += sizeof VMS_EMPTY_ECHO - 2;
                }
              else
                {
                  printf (_("Builtin command is unknown or unsupported in .ONESHELL: '%s'\n"), &cmd[nloff]);
                  fflush(stdout);
                  return 0;
                }
            }
          nloff = nextnl(cmd, nloff + 1);
        }
      if (clen < nloff)
        {
          memcpy(&tmp_cmd[vlen], &cmd[clen], nloff - clen);
          vlen += nloff - clen;
          clen = nloff;
          if (inecho)
            {
              inecho = 0;
              tmp_cmd[vlen] = '"';
              vlen++;
            }
        }

      tmp_cmd[vlen] = '\0';

      cmd = tmp_cmd;
    }

#ifdef USE_DCL_COM_FILE
  /* Enforce the creation of a command file.
     Then all the make environment variables are written as DCL symbol
     assignments into the command file as well, so that they are visible
     in the sub-process but do not affect the current process.
     Further, this way DCL reads the input stream and therefore does
     'forced' symbol substitution, which it doesn't do for one-liners when
     they are 'lib$spawn'ed. */
#else
  /* Create a *.com file if either the command is too long for
     lib$spawn, or the command contains a newline, or if redirection
     is desired. Forcing commands with newlines into DCLs allows to
     store search lists on user mode logicals.  */
  if (strlen (cmd) > MAXCMDLEN
      || (have_redirection != 0)
      || (have_newline != 0))
#endif
    {
      FILE *outfile;
      char c;
      char *sep;
      int alevel = 0;   /* apostrophe level */
      int tmpstrlen;
      char *tmpstr;
      if (strlen (cmd) == 0)
        {
          printf (_("Error, empty command\n"));
          fflush (stdout);
          return 0;
        }

      outfile = output_tmpfile (&child->comname, "sys$scratch:CMDXXXXXX.COM");
      /*                                          012345678901234567890 */
#define TMP_OFFSET 12
#define TMP_LEN 9
      if (outfile == 0)
        pfatal_with_name (_("fopen (temporary file)"));
      comnamelen = strlen (child->comname);
      tmpstr = &child->comname[TMP_OFFSET];
      tmpstrlen = TMP_LEN;
      /* The whole DCL "script" is executed as one action, and it behaves as
         any DCL "script", that is errors stop it but warnings do not. Usually
         the command on the last line, defines the exit code.  However, with
         redirections there is a prolog and possibly an epilog to implement
         the redirection.  Both are part of the script which is actually
         executed. So if the redirection encounters an error in the prolog,
         the user actions will not run; if in the epilog, the user actions
         ran, but output is not captured. In both error cases, the error of
         redirection is passed back and not the exit code of the actions. The
         user should be able to enable DCL "script" verification with "set
         verify". However, the prolog and epilog commands are not shown. Also,
         if output redirection is used, the verification output is redirected
         into that file as well. */
      fprintf (outfile, "$ %.*s_1 = \"''f$verify(0)'\"\n", tmpstrlen, tmpstr);
      if (ifile[0])
        {
          fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
          DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
          ifiledsc.dsc$w_length = 0;
        }

      if (efile[0])
        {
          fprintf (outfile, "$ define sys$error %s\n", efile);
          DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
          efiledsc.dsc$w_length = 0;
        }

      if (ofile[0])
        if (have_append)
          {
            fprintf (outfile, "$ define sys$output %.*s\n", comnamelen-3, child->comname);
            fprintf (outfile, "$ on error then $ goto %.*s\n", tmpstrlen, tmpstr);
            DB (DB_JOBS, (_("Append output to %s\n"), ofile));
            ofiledsc.dsc$w_length = 0;
          }
        else
          {
            fprintf (outfile, "$ define sys$output %s\n", ofile);
            DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
            ofiledsc.dsc$w_length = 0;
          }
#ifdef USE_DCL_COM_FILE
      /* Export the child environment into DCL symbols */
      if (child->environment != 0)
        {
          char **ep = child->environment;
          char *valstr;
          while (*ep != 0)
            {
              valstr = strchr(*ep, '=');
              if (valstr == NULL)
                continue;
              fprintf(outfile, "$ %.*s=\"%s\"\n", valstr - *ep, *ep,
                  valstr + 1);
              ep++;
            }
        }
#endif
      fprintf (outfile, "$ %.*s_ = f$verify(%.*s_1)\n", tmpstrlen, tmpstr, tmpstrlen, tmpstr);

      /* TODO: give 78 a name! Whether 78 is a good number is another question.
         Trim, split and write the command lines.
         Splitting of a command is done after 78 output characters at an
         appropriate place (after strings, after comma or space and
         before slash): appending a hyphen indicates that the DCL command
         is being continued.
         Trimming is to skip any whitespace around - including - a
         leading $ from the command to ensure writing exactly one "$ "
         at the beginning of the line of the output file. Trimming is
         done when a new command is seen, indicated by a '\n' (outside
         of a string).
         The buffer so far is written and reset, when a new command is
         seen, when a split was done and at the end of the command.
         Only for ONESHELL there will be several commands separated by
         '\n'. But there can always be multiple continuation lines. */
      p = sep = q = cmd;
      for (c = '\n'; c; c = *q++)
        {
          switch (c)
          {
          case '\n':
            if (q > p)
              {
                fwrite(p, 1, q - p, outfile);
                p = q;
              }
            fputc('$', outfile);
            fputc(' ', outfile);
            while (isspace((unsigned char) *p))
              p++;
            if (*p == '$')
              p++;
            while (isspace((unsigned char) *p))
              p++;
            q = sep = p;
            break;
          case '"':
            q = vms_handle_apos(q);
            sep = q;
            break;
          case ',':
          case ' ':
            sep = q;
            break;
          case '/':
          case '\0':
            sep = q - 1;
            break;
          default:
            break;
          }
          if (sep - p > 78)
            {
              /* Enough stuff for a line. */
              fwrite(p, 1, sep - p, outfile);
              p = sep;
              if (*sep)
                {
                  /* The command continues.  */
                  fputc('-', outfile);
                }
              fputc('\n', outfile);
            }
        }

      if (*p)
        {
          fwrite(p, 1, --q - p, outfile);
          fputc('\n', outfile);
        }

      if (have_append)
        {
          fprintf (outfile, "$ %.*s: ! 'f$verify(0)\n", tmpstrlen, tmpstr);
          fprintf (outfile, "$ %.*s_2 = $status\n", tmpstrlen, tmpstr);
          fprintf (outfile, "$ on error then $ exit\n");
          fprintf (outfile, "$ deassign sys$output\n");
          if (efile[0])
            fprintf (outfile, "$ deassign sys$error\n");
          fprintf (outfile, "$ append:=append\n");
          fprintf (outfile, "$ delete:=delete\n");
          fprintf (outfile, "$ append/new %.*s %s\n", comnamelen-3, child->comname, ofile);
          fprintf (outfile, "$ delete %.*s;*\n", comnamelen-3, child->comname);
          fprintf (outfile, "$ exit '%.*s_2 + (0*f$verify(%.*s_1))\n", tmpstrlen, tmpstr, tmpstrlen, tmpstr);
          DB (DB_JOBS, (_("Append %.*s and cleanup\n"), comnamelen-3, child->comname));
        }

      fclose (outfile);

      sprintf (cmd, "$ @%s", child->comname);

      DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
    }

  cmddsc.dsc$w_length = strlen(cmd);
  cmddsc.dsc$a_pointer = cmd;
  cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
  cmddsc.dsc$b_class = DSC$K_CLASS_S;

  child->efn = 0;
  while (child->efn < 32 || child->efn > 63)
    {
      status = lib$get_ef ((unsigned long *)&child->efn);
      if (!(status & 1))
        {
          if (child->comname)
            {
              if (!ISDB (DB_JOBS))
                unlink (child->comname);
              free (child->comname);
            }
          return 0;
        }
    }

  sys$clref (child->efn);

  vms_jobsefnmask |= (1 << (child->efn - 32));

  /*
    LIB$SPAWN  [command-string]
    [,input-file]
    [,output-file]
    [,flags]
    [,process-name]
    [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
    [,AST-address] [,varying-AST-argument]
    [,prompt-string] [,cli] [,table]
  */

#ifndef DONTWAITFORCHILD
  /*
   * Code to make ctrl+c and ctrl+y working.
   * The problem starts with the synchronous case where after lib$spawn is
   * called any input will go to the child. But with input re-directed,
   * both control characters won't make it to any of the programs, neither
   * the spawning nor to the spawned one. Hence the caller needs to spawn
   * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
   * has to follow to simulate the wanted synchronous behaviour.
   * The next problem is ctrl+y which isn't caught by the crtl and
   * therefore isn't converted to SIGQUIT (for a signal handler which is
   * already established). The only way to catch ctrl+y, is an AST
   * assigned to the input channel. But ctrl+y handling of DCL needs to be
   * disabled, otherwise it will handle it. Not to mention the previous
   * ctrl+y handling of DCL needs to be re-established before make exits.
   * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
   * make it to the signal handler after the child "normally" terminates.
   * This isn't enough. It seems reasonable for simple command lines like
   * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
   * spawning make. Therefore we need to abort the process in the AST.
   *
   * Prior to the spawn it is checked if an AST is already set up for
   * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
   * this will work except if make is run in a batch environment, but there
   * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
   * is disabled and an exit handler is established to re-enable it.
   * If the user interrupts with ctrl+y, the assigned AST will fire, force
   * an abort to the subprocess and signal SIGQUIT, which will be caught by
   * the already established handler and will bring us back to common code.
   * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
   * enables the ctrl+y be delivered to this code. And the ctrl+c too,
   * which the crtl converts to SIGINT and which is caught by the common
   * signal handler. Because signals were blocked before entering this code
   * sys$waitfr will always complete and the SIGQUIT will be processed after
   * it (after termination of the current block, somewhere in common code).
   * And SIGINT too will be delayed. That is ctrl+c can only abort when the
   * current command completes. Anyway it's better than nothing :-)
   */

  if (!setupYAstTried)
    tryToSetupYAst();
  status = lib$spawn (&cmddsc,                                  /* cmd-string */
                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
                      &spflags,                                 /* flags */
                      &pnamedsc,                                /* proc name */
                      &child->pid, &child->cstatus, &child->efn,
                      0, 0,
                      0, 0, 0);
  if (status & 1)
    {
      status= sys$waitfr (child->efn);
      vmsHandleChildTerm(child);
    }
#else
  status = lib$spawn (&cmddsc,
                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
                      &spflags,
                      &pnamedsc,
                      &child->pid, &child->cstatus, &child->efn,
                      vmsHandleChildTerm, child,
                      0, 0, 0);
#endif

  if (!(status & 1))
    {
      printf (_("Error spawning, %d\n") ,status);
      fflush (stdout);
      switch (status)
        {
        case 0x1c:
          errno = EPROCLIM;
          break;
        default:
          errno = EFAIL;
        }
    }

  return (status & 1);
}