2 * Sandbox helper for CUPS.
4 * Copyright 2007-2014 by Apple Inc.
6 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
10 * cups-exec /path/to/profile [-u UID] [-g GID] [-n NICE] /path/to/program argv0 argv1 ... argvN
14 * Include necessary headers...
17 #include <cups/string-private.h>
18 #include <cups/file.h>
25 # ifndef SANDBOX_NAMED_EXTERNAL
26 # define SANDBOX_NAMED_EXTERNAL 0x0003
27 # endif /* !SANDBOX_NAMED_EXTERNAL */
28 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
29 #endif /* HAVE_SANDBOX_H */
36 static void usage(void) _CUPS_NORETURN;
40 * 'main()' - Apply sandbox profile and execute program.
43 int /* O - Exit status */
44 main(int argc, /* I - Number of command-line args */
45 char *argv[]) /* I - Command-line arguments */
47 int i; /* Looping var */
48 const char *opt; /* Current option character */
49 uid_t uid = getuid(); /* UID */
50 gid_t gid = getgid(); /* GID */
51 int niceval = 0; /* Nice value */
53 char *sandbox_error = NULL; /* Sandbox error, if any */
54 #endif /* HAVE_SANDBOX_H */
58 * Parse command-line...
61 for (i = 1; i < argc; i ++)
63 if (argv[i][0] == '-')
65 for (opt = argv[i] + 1; *opt; opt ++)
69 case 'g' : /* -g gid */
74 gid = (gid_t)atoi(argv[i]);
77 case 'n' : /* -n nice-value */
82 niceval = atoi(argv[i]);
85 case 'u' : /* -g gid */
90 uid = (uid_t)atoi(argv[i]);
94 fprintf(stderr, "cups-exec: Unknown option '-%c'.\n", *opt);
104 * Check that we have enough arguments...
109 fputs("cups-exec: Insufficient arguments.\n", stderr);
114 * Make sure side and back channel FDs are non-blocking...
117 fcntl(3, F_SETFL, O_NDELAY);
118 fcntl(4, F_SETFL, O_NDELAY);
121 * Change UID, GID, and nice value...
132 if (setgroups(1, &gid))
135 if (uid && setuid(uid))
141 #ifdef HAVE_SANDBOX_H
143 * Run in a separate security profile...
146 if (strcmp(argv[i], "none") &&
147 sandbox_init(argv[i], SANDBOX_NAMED_EXTERNAL, &sandbox_error))
149 cups_file_t *fp; /* File */
150 char line[1024]; /* Line from file */
151 int linenum = 0; /* Line number in file */
153 fprintf(stderr, "DEBUG: sandbox_init failed: %s (%s)\n", sandbox_error,
155 sandbox_free_error(sandbox_error);
157 if ((fp = cupsFileOpen(argv[i], "r")) != NULL)
159 while (cupsFileGets(fp, line, sizeof(line)))
162 fprintf(stderr, "DEBUG: %4d %s\n", linenum, line);
167 return (100 + EINVAL);
169 #endif /* HAVE_SANDBOX_H */
172 * Execute the program...
175 execv(argv[i + 1], argv + i + 2);
178 * If we get here, execv() failed...
181 fprintf(stderr, "DEBUG: execv failed: %s\n", strerror(errno));
182 return (errno + 100);
187 * 'usage()' - Show program usage.
193 fputs("Usage: cups-exec [-g gid] [-n nice-value] [-u uid] /path/to/profile /path/to/program argv0 argv1 ... argvN\n", stderr);