• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Process management routines for the CUPS scheduler.
3  *
4  * Copyright 2007-2017 by Apple Inc.
5  * Copyright 1997-2007 by Easy Software Products, all rights reserved.
6  *
7  * Licensed under Apache License v2.0.  See the file "LICENSE" for more information.
8  */
9 
10 /*
11  * Include necessary headers...
12  */
13 
14 #include "cupsd.h"
15 #include <grp.h>
16 #ifdef __APPLE__
17 #  include <libgen.h>
18 #endif /* __APPLE__ */
19 #ifdef HAVE_POSIX_SPAWN
20 #  include <spawn.h>
21 extern char **environ;
22 /* Don't use posix_spawn on systems with bugs in their implementations... */
23 #  if defined(OpenBSD) && OpenBSD < 201505
24 #    define USE_POSIX_SPAWN 0
25 #  elif defined(__UCLIBC__) && __UCLIBC_MAJOR__ == 1 && __UCLIBC_MINOR__ == 0 && __UCLIBC_SUBLEVEL__ < 27
26 #    define USE_POSIX_SPAWN 0
27 #  elif defined(__UCLIBC__) && __UCLIBC_MAJOR__ < 1
28 #    define USE_POSIX_SPAWN 0
29 #  else /* All other platforms */
30 #    define USE_POSIX_SPAWN 1
31 #  endif /* ... */
32 #else
33 #  define USE_POSIX_SPAWN 0
34 #endif /* HAVE_POSIX_SPAWN */
35 
36 
37 /*
38  * Process structure...
39  */
40 
41 typedef struct
42 {
43   int	pid,				/* Process ID */
44 	job_id;				/* Job associated with process */
45   char	name[1];			/* Name of process */
46 } cupsd_proc_t;
47 
48 
49 /*
50  * Local globals...
51  */
52 
53 static cups_array_t	*process_array = NULL;
54 
55 
56 /*
57  * Local functions...
58  */
59 
60 static int	compare_procs(cupsd_proc_t *a, cupsd_proc_t *b);
61 #ifdef HAVE_SANDBOX_H
62 static char	*cupsd_requote(char *dst, const char *src, size_t dstsize);
63 #endif /* HAVE_SANDBOX_H */
64 
65 
66 /*
67  * 'cupsdCreateProfile()' - Create an execution profile for a subprocess.
68  */
69 
70 void *					/* O - Profile or NULL on error */
cupsdCreateProfile(int job_id,int allow_networking)71 cupsdCreateProfile(int job_id,		/* I - Job ID or 0 for none */
72                    int allow_networking)/* I - Allow networking off machine? */
73 {
74 #ifdef HAVE_SANDBOX_H
75   cups_file_t		*fp;		/* File pointer */
76   char			profile[1024],	/* File containing the profile */
77 			bin[1024],	/* Quoted ServerBin */
78 			cache[1024],	/* Quoted CacheDir */
79 			domain[1024],	/* Domain socket, if any */
80 			request[1024],	/* Quoted RequestRoot */
81 			root[1024],	/* Quoted ServerRoot */
82 			state[1024],	/* Quoted StateDir */
83 			temp[1024];	/* Quoted TempDir */
84   const char		*nodebug;	/* " (with no-log)" for no debug */
85   cupsd_listener_t	*lis;		/* Current listening socket */
86 
87 
88   if (!UseSandboxing || Sandboxing == CUPSD_SANDBOXING_OFF)
89   {
90    /*
91     * Only use sandbox profiles as root...
92     */
93 
94     cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);
95 
96     return (NULL);
97   }
98 
99   if ((fp = cupsTempFile2(profile, sizeof(profile))) == NULL)
100   {
101    /*
102     * This should never happen, and is fatal when sandboxing is enabled.
103     */
104 
105     cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);
106     cupsdLogMessage(CUPSD_LOG_EMERG, "Unable to create security profile: %s", strerror(errno));
107     kill(getpid(), SIGTERM);
108     return (NULL);
109   }
110 
111   fchown(cupsFileNumber(fp), RunUser, Group);
112   fchmod(cupsFileNumber(fp), 0640);
113 
114   cupsd_requote(bin, ServerBin, sizeof(bin));
115   cupsd_requote(cache, CacheDir, sizeof(cache));
116   cupsd_requote(request, RequestRoot, sizeof(request));
117   cupsd_requote(root, ServerRoot, sizeof(root));
118   cupsd_requote(state, StateDir, sizeof(state));
119   cupsd_requote(temp, TempDir, sizeof(temp));
120 
121   nodebug = LogLevel < CUPSD_LOG_DEBUG ? " (with no-log)" : "";
122 
123   cupsFilePuts(fp, "(version 1)\n");
124   if (Sandboxing == CUPSD_SANDBOXING_STRICT)
125     cupsFilePuts(fp, "(deny default)\n");
126   else
127     cupsFilePuts(fp, "(allow default)\n");
128   if (LogLevel >= CUPSD_LOG_DEBUG)
129     cupsFilePuts(fp, "(debug deny)\n");
130   cupsFilePuts(fp, "(import \"system.sb\")\n");
131   cupsFilePuts(fp, "(import \"com.apple.corefoundation.sb\")\n");
132   cupsFilePuts(fp, "(system-network)\n");
133   cupsFilePuts(fp, "(allow mach-per-user-lookup)\n");
134   cupsFilePuts(fp, "(allow ipc-posix-sem)\n");
135   cupsFilePuts(fp, "(allow ipc-posix-shm)\n");
136   cupsFilePuts(fp, "(allow ipc-sysv-shm)\n");
137   cupsFilePuts(fp, "(allow mach-lookup)\n");
138   if (!RunUser)
139     cupsFilePrintf(fp,
140 		   "(deny file-write* file-read-data file-read-metadata\n"
141 		   "  (regex"
142 		   " #\"^/Users$\""
143 		   " #\"^/Users/\""
144 		   ")%s)\n", nodebug);
145   cupsFilePrintf(fp,
146                  "(deny file-write*\n"
147                  "  (regex"
148 		 " #\"^%s$\""		/* ServerRoot */
149 		 " #\"^%s/\""		/* ServerRoot/... */
150 		 " #\"^/private/etc$\""
151 		 " #\"^/private/etc/\""
152 		 " #\"^/usr/local/etc$\""
153 		 " #\"^/usr/local/etc/\""
154 		 " #\"^/Library$\""
155 		 " #\"^/Library/\""
156 		 " #\"^/System$\""
157 		 " #\"^/System/\""
158 		 ")%s)\n",
159 		 root, root, nodebug);
160   /* Specifically allow applications to stat RequestRoot and some other system folders */
161   cupsFilePrintf(fp,
162                  "(allow file-read-metadata\n"
163                  "  (regex"
164 		 " #\"^/$\""		/* / */
165 		 " #\"^/usr$\""		/* /usr */
166 		 " #\"^/Library$\""	/* /Library */
167 		 " #\"^/Library/Printers$\""	/* /Library/Printers */
168 		 " #\"^%s$\""		/* RequestRoot */
169 		 "))\n",
170 		 request);
171   /* Read and write TempDir, CacheDir, and other common folders */
172   cupsFilePuts(fp,
173 	       "(allow file-write* file-read-data file-read-metadata\n"
174 	       "  (regex"
175 	       " #\"^/private/var/db/\""
176 	       " #\"^/private/var/folders/\""
177 	       " #\"^/private/var/lib/\""
178 	       " #\"^/private/var/log/\""
179 	       " #\"^/private/var/mysql/\""
180 	       " #\"^/private/var/run/\""
181 	       " #\"^/private/var/spool/\""
182 	       " #\"^/Library/Application Support/\""
183 	       " #\"^/Library/Caches/\""
184 	       " #\"^/Library/Logs/\""
185 	       " #\"^/Library/Preferences/\""
186 	       " #\"^/Library/WebServer/\""
187 	       " #\"^/Users/Shared/\""
188 	       "))\n");
189   cupsFilePrintf(fp,
190 		 "(deny file-write*\n"
191 		 "       (regex #\"^%s$\")%s)\n",
192 		 request, nodebug);
193   cupsFilePrintf(fp,
194 		 "(deny file-write* file-read-data file-read-metadata\n"
195 		 "       (regex #\"^%s/\")%s)\n",
196 		 request, nodebug);
197   cupsFilePrintf(fp,
198                  "(allow file-write* file-read-data file-read-metadata\n"
199                  "  (regex"
200 		 " #\"^%s$\""		/* TempDir */
201 		 " #\"^%s/\""		/* TempDir/... */
202 		 " #\"^%s$\""		/* CacheDir */
203 		 " #\"^%s/\""		/* CacheDir/... */
204 		 "))\n",
205 		 temp, temp, cache, cache);
206   /* Read common folders */
207   cupsFilePrintf(fp,
208                  "(allow file-read-data file-read-metadata\n"
209                  "  (regex"
210                  " #\"^/AppleInternal$\""
211                  " #\"^/AppleInternal/\""
212                  " #\"^/bin$\""		/* /bin */
213                  " #\"^/bin/\""		/* /bin/... */
214                  " #\"^/private$\""
215                  " #\"^/private/etc$\""
216                  " #\"^/private/etc/\""
217                  " #\"^/private/tmp$\""
218                  " #\"^/private/tmp/\""
219                  " #\"^/private/var$\""
220                  " #\"^/private/var/db$\""
221                  " #\"^/private/var/folders$\""
222                  " #\"^/private/var/lib$\""
223                  " #\"^/private/var/log$\""
224                  " #\"^/private/var/mysql$\""
225                  " #\"^/private/var/run$\""
226                  " #\"^/private/var/spool$\""
227                  " #\"^/private/var/tmp$\""
228                  " #\"^/private/var/tmp/\""
229                  " #\"^/usr/bin$\""	/* /usr/bin */
230                  " #\"^/usr/bin/\""	/* /usr/bin/... */
231                  " #\"^/usr/libexec/cups$\""	/* /usr/libexec/cups */
232                  " #\"^/usr/libexec/cups/\""	/* /usr/libexec/cups/... */
233                  " #\"^/usr/libexec/fax$\""	/* /usr/libexec/fax */
234                  " #\"^/usr/libexec/fax/\""	/* /usr/libexec/fax/... */
235                  " #\"^/usr/sbin$\""	/* /usr/sbin */
236                  " #\"^/usr/sbin/\""	/* /usr/sbin/... */
237 		 " #\"^/Library$\""	/* /Library */
238 		 " #\"^/Library/\""	/* /Library/... */
239 		 " #\"^/System$\""	/* /System */
240 		 " #\"^/System/\""	/* /System/... */
241 		 " #\"^%s/Library$\""	/* RequestRoot/Library */
242 		 " #\"^%s/Library/\""	/* RequestRoot/Library/... */
243 		 " #\"^%s$\""		/* ServerBin */
244 		 " #\"^%s/\""		/* ServerBin/... */
245 		 " #\"^%s$\""		/* ServerRoot */
246 		 " #\"^%s/\""		/* ServerRoot/... */
247 		 " #\"^%s$\""		/* StateDir */
248 		 " #\"^%s/\""		/* StateDir/... */
249 		 "))\n",
250 		 request, request, bin, bin, root, root, state, state);
251   if (Sandboxing == CUPSD_SANDBOXING_RELAXED)
252   {
253     /* Limited write access to /Library/Printers/... */
254     cupsFilePuts(fp,
255 		 "(allow file-write*\n"
256 		 "  (regex"
257 		 " #\"^/Library/Printers/.*/\""
258 		 "))\n");
259     cupsFilePrintf(fp,
260 		   "(deny file-write*\n"
261 		   "  (regex"
262 		   " #\"^/Library/Printers/PPDs$\""
263 		   " #\"^/Library/Printers/PPDs/\""
264 		   " #\"^/Library/Printers/PPD Plugins$\""
265 		   " #\"^/Library/Printers/PPD Plugins/\""
266 		   ")%s)\n", nodebug);
267   }
268   /* Allow execution of child processes as long as the programs are not in a user directory */
269   cupsFilePuts(fp, "(allow process*)\n");
270   cupsFilePuts(fp, "(deny process-exec (regex #\"^/Users/\"))\n");
271   if (RunUser && getenv("CUPS_TESTROOT"))
272   {
273     /* Allow source directory access in "make test" environment */
274     char	testroot[1024];		/* Root directory of test files */
275 
276     cupsd_requote(testroot, getenv("CUPS_TESTROOT"), sizeof(testroot));
277 
278     cupsFilePrintf(fp,
279 		   "(allow file-write* file-read-data file-read-metadata\n"
280 		   "  (regex"
281 		   " #\"^%s$\""		/* CUPS_TESTROOT */
282 		   " #\"^%s/\""		/* CUPS_TESTROOT/... */
283 		   "))\n",
284 		   testroot, testroot);
285     cupsFilePrintf(fp,
286 		   "(allow process-exec\n"
287 		   "  (regex"
288 		   " #\"^%s/\""		/* CUPS_TESTROOT/... */
289 		   "))\n",
290 		   testroot);
291     cupsFilePrintf(fp, "(allow sysctl*)\n");
292   }
293   if (job_id)
294   {
295     /* Allow job filters to read the current job files... */
296     cupsFilePrintf(fp,
297                    "(allow file-read-data file-read-metadata\n"
298                    "       (regex #\"^%s/([ac]%05d|d%05d-[0-9][0-9][0-9])$\"))\n",
299 		   request, job_id, job_id);
300   }
301   else
302   {
303     /* Allow email notifications from notifiers... */
304     cupsFilePuts(fp,
305 		 "(allow process-exec\n"
306 		 "  (literal \"/usr/sbin/sendmail\")\n"
307 		 "  (with no-sandbox))\n");
308   }
309   /* Allow access to Bluetooth, USB, and notify_post. */
310   cupsFilePuts(fp, "(allow iokit*)\n");
311   cupsFilePuts(fp, "(allow distributed-notification-post)\n");
312   /* Allow outbound networking to local services */
313   cupsFilePuts(fp, "(allow network-outbound"
314 		   "\n       (regex #\"^/private/var/run/\" #\"^/private/tmp/\" #\"^/private/var/tmp/\")");
315   for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
316        lis;
317        lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
318   {
319     if (httpAddrFamily(&(lis->address)) == AF_LOCAL)
320     {
321       httpAddrString(&(lis->address), domain, sizeof(domain));
322       cupsFilePrintf(fp, "\n       (literal \"%s\")", domain);
323     }
324   }
325   if (allow_networking)
326   {
327     /* Allow TCP and UDP networking off the machine... */
328     cupsFilePuts(fp, "\n       (remote tcp))\n");
329     cupsFilePuts(fp, "(allow network-bind)\n"); /* for LPD resvport */
330     cupsFilePuts(fp, "(allow network*\n"
331 		     "       (local udp \"*:*\")\n"
332 		     "       (remote udp \"*:*\"))\n");
333 
334     /* Also allow access to device files... */
335     cupsFilePuts(fp, "(allow file-write* file-read-data file-read-metadata file-ioctl\n"
336                      "       (regex #\"^/dev/\"))\n");
337 
338     /* And allow kernel extensions to be loaded, e.g., SMB */
339     cupsFilePuts(fp, "(allow system-kext-load)\n");
340   }
341   else
342   {
343     /* Only allow SNMP (UDP) and LPD (TCP) off the machine... */
344     cupsFilePuts(fp, ")\n");
345     cupsFilePuts(fp, "(allow network-outbound\n"
346 		     "       (remote udp \"*:161\")\n"
347 		     "       (remote tcp \"*:515\"))\n");
348     cupsFilePuts(fp, "(allow network-inbound\n"
349 		     "       (local udp \"localhost:*\"))\n");
350   }
351   cupsFileClose(fp);
352 
353   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d,allow_networking=%d) = \"%s\"", job_id, allow_networking, profile);
354   return ((void *)strdup(profile));
355 
356 #else
357   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);
358 
359   return (NULL);
360 #endif /* HAVE_SANDBOX_H */
361 }
362 
363 
364 /*
365  * 'cupsdDestroyProfile()' - Delete an execution profile.
366  */
367 
368 void
cupsdDestroyProfile(void * profile)369 cupsdDestroyProfile(void *profile)	/* I - Profile */
370 {
371   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdDeleteProfile(profile=\"%s\")",
372 		  profile ? (char *)profile : "(null)");
373 
374 #ifdef HAVE_SANDBOX_H
375   if (profile)
376   {
377     unlink((char *)profile);
378     free(profile);
379   }
380 #endif /* HAVE_SANDBOX_H */
381 }
382 
383 
384 /*
385  * 'cupsdEndProcess()' - End a process.
386  */
387 
388 int					/* O - 0 on success, -1 on failure */
cupsdEndProcess(int pid,int force)389 cupsdEndProcess(int pid,		/* I - Process ID */
390                 int force)		/* I - Force child to die */
391 {
392   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdEndProcess(pid=%d, force=%d)", pid,
393                   force);
394 
395   if (!pid)
396     return (0);
397 
398   if (!RunUser)
399   {
400    /*
401     * When running as root, cupsd puts child processes in their own process
402     * group.  Using "-pid" sends a signal to all processes in the group.
403     */
404 
405     pid = -pid;
406   }
407 
408   if (force)
409     return (kill(pid, SIGKILL));
410   else
411     return (kill(pid, SIGTERM));
412 }
413 
414 
415 /*
416  * 'cupsdFinishProcess()' - Finish a process and get its name.
417  */
418 
419 const char *				/* O - Process name */
cupsdFinishProcess(int pid,char * name,size_t namelen,int * job_id)420 cupsdFinishProcess(int    pid,		/* I - Process ID */
421                    char   *name,	/* I - Name buffer */
422 		   size_t namelen,	/* I - Size of name buffer */
423 		   int    *job_id)	/* O - Job ID pointer or NULL */
424 {
425   cupsd_proc_t	key,			/* Search key */
426 		*proc;			/* Matching process */
427 
428 
429   key.pid = pid;
430 
431   if ((proc = (cupsd_proc_t *)cupsArrayFind(process_array, &key)) != NULL)
432   {
433     if (job_id)
434       *job_id = proc->job_id;
435 
436     strlcpy(name, proc->name, namelen);
437     cupsArrayRemove(process_array, proc);
438     free(proc);
439   }
440   else
441   {
442     if (job_id)
443       *job_id = 0;
444 
445     strlcpy(name, "unknown", namelen);
446   }
447 
448   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFinishProcess(pid=%d, name=%p, namelen=" CUPS_LLFMT ", job_id=%p(%d)) = \"%s\"", pid, name, CUPS_LLCAST namelen, job_id, job_id ? *job_id : 0, name);
449 
450   return (name);
451 }
452 
453 
454 /*
455  * 'cupsdStartProcess()' - Start a process.
456  */
457 
458 int					/* O - Process ID or 0 */
cupsdStartProcess(const char * command,char * argv[],char * envp[],int infd,int outfd,int errfd,int backfd,int sidefd,int root,void * profile,cupsd_job_t * job,int * pid)459 cupsdStartProcess(
460     const char  *command,		/* I - Full path to command */
461     char        *argv[],		/* I - Command-line arguments */
462     char        *envp[],		/* I - Environment */
463     int         infd,			/* I - Standard input file descriptor */
464     int         outfd,			/* I - Standard output file descriptor */
465     int         errfd,			/* I - Standard error file descriptor */
466     int         backfd,			/* I - Backchannel file descriptor */
467     int         sidefd,			/* I - Sidechannel file descriptor */
468     int         root,			/* I - Run as root? */
469     void        *profile,		/* I - Security profile to use */
470     cupsd_job_t *job,			/* I - Job associated with process */
471     int         *pid)			/* O - Process ID */
472 {
473   int		i;			/* Looping var */
474   const char	*exec_path = command;	/* Command to be exec'd */
475   char		*real_argv[110],	/* Real command-line arguments */
476 		cups_exec[1024],	/* Path to "cups-exec" program */
477 		user_str[16],		/* User string */
478 		group_str[16],		/* Group string */
479 		nice_str[16];		/* FilterNice string */
480   uid_t		user;			/* Command UID */
481   cupsd_proc_t	*proc;			/* New process record */
482 #if USE_POSIX_SPAWN
483   posix_spawn_file_actions_t actions;	/* Spawn file actions */
484   posix_spawnattr_t attrs;		/* Spawn attributes */
485   sigset_t	defsignals;		/* Default signals */
486 #elif defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
487   struct sigaction action;		/* POSIX signal handler */
488 #endif /* USE_POSIX_SPAWN */
489 #if defined(__APPLE__)
490   char		processPath[1024],	/* CFProcessPath environment variable */
491 		linkpath[1024];		/* Link path for symlinks... */
492   int		linkbytes;		/* Bytes for link path */
493 #endif /* __APPLE__ */
494 
495 
496   *pid = 0;
497 
498  /*
499   * Figure out the UID for the child process...
500   */
501 
502   if (RunUser)
503     user = RunUser;
504   else if (root)
505     user = 0;
506   else
507     user = User;
508 
509  /*
510   * Check the permissions of the command we are running...
511   */
512 
513   if (_cupsFileCheck(command, _CUPS_FILE_CHECK_PROGRAM, !RunUser,
514                      cupsdLogFCMessage, job ? job->printer : NULL))
515     return (0);
516 
517 #if defined(__APPLE__)
518   if (envp)
519   {
520    /*
521     * Add special voodoo magic for macOS - this allows macOS programs to access
522     * their bundle resources properly...
523     */
524 
525     if ((linkbytes = readlink(command, linkpath, sizeof(linkpath) - 1)) > 0)
526     {
527      /*
528       * Yes, this is a symlink to the actual program, nul-terminate and
529       * use it...
530       */
531 
532       linkpath[linkbytes] = '\0';
533 
534       if (linkpath[0] == '/')
535 	snprintf(processPath, sizeof(processPath), "CFProcessPath=%s",
536 		 linkpath);
537       else
538 	snprintf(processPath, sizeof(processPath), "CFProcessPath=%s/%s",
539 		 dirname((char *)command), linkpath);
540     }
541     else
542       snprintf(processPath, sizeof(processPath), "CFProcessPath=%s", command);
543 
544     envp[0] = processPath;		/* Replace <CFProcessPath> string */
545   }
546 #endif	/* __APPLE__ */
547 
548  /*
549   * Use helper program when we have a sandbox profile...
550   */
551 
552 #if !USE_POSIX_SPAWN
553   if (profile)
554 #endif /* !USE_POSIX_SPAWN */
555   {
556     snprintf(cups_exec, sizeof(cups_exec), "%s/daemon/cups-exec", ServerBin);
557     snprintf(user_str, sizeof(user_str), "%d", user);
558     snprintf(group_str, sizeof(group_str), "%d", Group);
559     snprintf(nice_str, sizeof(nice_str), "%d", FilterNice);
560 
561     real_argv[0] = cups_exec;
562     real_argv[1] = (char *)"-g";
563     real_argv[2] = group_str;
564     real_argv[3] = (char *)"-n";
565     real_argv[4] = nice_str;
566     real_argv[5] = (char *)"-u";
567     real_argv[6] = user_str;
568     real_argv[7] = profile ? profile : "none";
569     real_argv[8] = (char *)command;
570 
571     for (i = 0;
572          i < (int)(sizeof(real_argv) / sizeof(real_argv[0]) - 10) && argv[i];
573 	 i ++)
574       real_argv[i + 9] = argv[i];
575 
576     real_argv[i + 9] = NULL;
577 
578     argv      = real_argv;
579     exec_path = cups_exec;
580   }
581 
582   if (LogLevel == CUPSD_LOG_DEBUG2)
583   {
584     cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Preparing to start \"%s\", arguments:", command);
585 
586     for (i = 0; argv[i]; i ++)
587       cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: argv[%d] = \"%s\"", i, argv[i]);
588   }
589 
590 #if USE_POSIX_SPAWN
591  /*
592   * Setup attributes and file actions for the spawn...
593   */
594 
595   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Setting spawn attributes.");
596   sigemptyset(&defsignals);
597   sigaddset(&defsignals, SIGTERM);
598   sigaddset(&defsignals, SIGCHLD);
599   sigaddset(&defsignals, SIGPIPE);
600 
601   posix_spawnattr_init(&attrs);
602   posix_spawnattr_setflags(&attrs, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGDEF);
603   posix_spawnattr_setpgroup(&attrs, 0);
604   posix_spawnattr_setsigdefault(&attrs, &defsignals);
605 
606   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Setting file actions.");
607   posix_spawn_file_actions_init(&actions);
608   if (infd != 0)
609   {
610     if (infd < 0)
611       posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);
612     else
613       posix_spawn_file_actions_adddup2(&actions, infd, 0);
614   }
615 
616   if (outfd != 1)
617   {
618     if (outfd < 0)
619       posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0);
620     else
621       posix_spawn_file_actions_adddup2(&actions, outfd, 1);
622   }
623 
624   if (errfd != 2)
625   {
626     if (errfd < 0)
627       posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
628     else
629       posix_spawn_file_actions_adddup2(&actions, errfd, 2);
630   }
631 
632   if (backfd != 3 && backfd >= 0)
633     posix_spawn_file_actions_adddup2(&actions, backfd, 3);
634 
635   if (sidefd != 4 && sidefd >= 0)
636     posix_spawn_file_actions_adddup2(&actions, sidefd, 4);
637 
638   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: Calling posix_spawn.");
639 
640   if (posix_spawn(pid, exec_path, &actions, &attrs, argv, envp ? envp : environ))
641   {
642     cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork %s - %s.", command, strerror(errno));
643 
644     *pid = 0;
645   }
646   else
647     cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartProcess: pid=%d", (int)*pid);
648 
649   posix_spawn_file_actions_destroy(&actions);
650   posix_spawnattr_destroy(&attrs);
651 
652 #else
653  /*
654   * Block signals before forking...
655   */
656 
657   cupsdHoldSignals();
658 
659   if ((*pid = fork()) == 0)
660   {
661    /*
662     * Child process goes here; update stderr as needed...
663     */
664 
665     if (errfd != 2)
666     {
667       if (errfd < 0)
668         errfd = open("/dev/null", O_WRONLY);
669 
670       if (errfd != 2)
671       {
672         dup2(errfd, 2);
673 	close(errfd);
674       }
675     }
676 
677    /*
678     * Put this process in its own process group so that we can kill any child
679     * processes it creates.
680     */
681 
682 #  ifdef HAVE_SETPGID
683     if (!RunUser && setpgid(0, 0))
684       exit(errno + 100);
685 #  else
686     if (!RunUser && setpgrp())
687       exit(errno + 100);
688 #  endif /* HAVE_SETPGID */
689 
690    /*
691     * Update the remaining file descriptors as needed...
692     */
693 
694     if (infd != 0)
695     {
696       if (infd < 0)
697         infd = open("/dev/null", O_RDONLY);
698 
699       if (infd != 0)
700       {
701         dup2(infd, 0);
702 	close(infd);
703       }
704     }
705 
706     if (outfd != 1)
707     {
708       if (outfd < 0)
709         outfd = open("/dev/null", O_WRONLY);
710 
711       if (outfd != 1)
712       {
713         dup2(outfd, 1);
714 	close(outfd);
715       }
716     }
717 
718     if (backfd != 3 && backfd >= 0)
719     {
720       dup2(backfd, 3);
721       close(backfd);
722       fcntl(3, F_SETFL, O_NDELAY);
723     }
724 
725     if (sidefd != 4 && sidefd >= 0)
726     {
727       dup2(sidefd, 4);
728       close(sidefd);
729       fcntl(4, F_SETFL, O_NDELAY);
730     }
731 
732    /*
733     * Change the priority of the process based on the FilterNice setting.
734     * (this is not done for root processes...)
735     */
736 
737     if (!root)
738       nice(FilterNice);
739 
740    /*
741     * Reset group membership to just the main one we belong to.
742     */
743 
744     if (!RunUser && setgid(Group))
745       exit(errno + 100);
746 
747     if (!RunUser && setgroups(1, &Group))
748       exit(errno + 100);
749 
750    /*
751     * Change user to something "safe"...
752     */
753 
754     if (!RunUser && user && setuid(user))
755       exit(errno + 100);
756 
757    /*
758     * Change umask to restrict permissions on created files...
759     */
760 
761     umask(077);
762 
763    /*
764     * Unblock signals before doing the exec...
765     */
766 
767 #  ifdef HAVE_SIGSET
768     sigset(SIGTERM, SIG_DFL);
769     sigset(SIGCHLD, SIG_DFL);
770     sigset(SIGPIPE, SIG_DFL);
771 #  elif defined(HAVE_SIGACTION)
772     memset(&action, 0, sizeof(action));
773 
774     sigemptyset(&action.sa_mask);
775     action.sa_handler = SIG_DFL;
776 
777     sigaction(SIGTERM, &action, NULL);
778     sigaction(SIGCHLD, &action, NULL);
779     sigaction(SIGPIPE, &action, NULL);
780 #  else
781     signal(SIGTERM, SIG_DFL);
782     signal(SIGCHLD, SIG_DFL);
783     signal(SIGPIPE, SIG_DFL);
784 #  endif /* HAVE_SIGSET */
785 
786     cupsdReleaseSignals();
787 
788    /*
789     * Execute the command; if for some reason this doesn't work, log an error
790     * exit with a non-zero value...
791     */
792 
793     if (envp)
794       execve(exec_path, argv, envp);
795     else
796       execv(exec_path, argv);
797 
798     exit(errno + 100);
799   }
800   else if (*pid < 0)
801   {
802    /*
803     * Error - couldn't fork a new process!
804     */
805 
806     cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to fork %s - %s.", command,
807                     strerror(errno));
808 
809     *pid = 0;
810   }
811 
812   cupsdReleaseSignals();
813 #endif /* USE_POSIX_SPAWN */
814 
815   if (*pid)
816   {
817     if (!process_array)
818       process_array = cupsArrayNew((cups_array_func_t)compare_procs, NULL);
819 
820     if (process_array)
821     {
822       if ((proc = calloc(1, sizeof(cupsd_proc_t) + strlen(command))) != NULL)
823       {
824         proc->pid    = *pid;
825 	proc->job_id = job ? job->id : 0;
826 	_cups_strcpy(proc->name, command);
827 
828 	cupsArrayAdd(process_array, proc);
829       }
830     }
831   }
832 
833   cupsdLogMessage(CUPSD_LOG_DEBUG2,
834 		  "cupsdStartProcess(command=\"%s\", argv=%p, envp=%p, "
835 		  "infd=%d, outfd=%d, errfd=%d, backfd=%d, sidefd=%d, root=%d, "
836 		  "profile=%p, job=%p(%d), pid=%p) = %d",
837 		  command, argv, envp, infd, outfd, errfd, backfd, sidefd,
838 		  root, profile, job, job ? job->id : 0, pid, *pid);
839 
840   return (*pid);
841 }
842 
843 
844 /*
845  * 'compare_procs()' - Compare two processes.
846  */
847 
848 static int				/* O - Result of comparison */
compare_procs(cupsd_proc_t * a,cupsd_proc_t * b)849 compare_procs(cupsd_proc_t *a,		/* I - First process */
850               cupsd_proc_t *b)		/* I - Second process */
851 {
852   return (a->pid - b->pid);
853 }
854 
855 
856 #ifdef HAVE_SANDBOX_H
857 /*
858  * 'cupsd_requote()' - Make a regular-expression version of a string.
859  */
860 
861 static char *				/* O - Quoted string */
cupsd_requote(char * dst,const char * src,size_t dstsize)862 cupsd_requote(char       *dst,		/* I - Destination buffer */
863               const char *src,		/* I - Source string */
864 	      size_t     dstsize)	/* I - Size of destination buffer */
865 {
866   int	ch;				/* Current character */
867   char	*dstptr,			/* Current position in buffer */
868 	*dstend;			/* End of destination buffer */
869 
870 
871   dstptr = dst;
872   dstend = dst + dstsize - 2;
873 
874   while (*src && dstptr < dstend)
875   {
876     ch = *src++;
877 
878     if (ch == '/' && !*src)
879       break;				/* Don't add trailing slash */
880 
881     if (strchr(".?*()[]^$\\\"", ch))
882       *dstptr++ = '\\';
883 
884     *dstptr++ = (char)ch;
885   }
886 
887   *dstptr = '\0';
888 
889   return (dst);
890 }
891 #endif /* HAVE_SANDBOX_H */
892