4 * Process management routines for the CUPS scheduler.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
17 * Include necessary headers...
24 #endif /* __APPLE__ */
25 #ifdef HAVE_POSIX_SPAWN
27 extern char **environ
;
28 #endif /* HAVE_POSIX_SPAWN */
32 * Process structure...
37 int pid
, /* Process ID */
38 job_id
; /* Job associated with process */
39 char name
[1]; /* Name of process */
47 static cups_array_t
*process_array
= NULL
;
54 static int compare_procs(cupsd_proc_t
*a
, cupsd_proc_t
*b
);
56 static char *cupsd_requote(char *dst
, const char *src
, size_t dstsize
);
57 #endif /* HAVE_SANDBOX_H */
61 * 'cupsdCreateProfile()' - Create an execution profile for a subprocess.
64 void * /* O - Profile or NULL on error */
65 cupsdCreateProfile(int job_id
, /* I - Job ID or 0 for none */
66 int allow_networking
)/* I - Allow networking off machine? */
69 cups_file_t
*fp
; /* File pointer */
70 char profile
[1024], /* File containing the profile */
71 bin
[1024], /* Quoted ServerBin */
72 cache
[1024], /* Quoted CacheDir */
73 domain
[1024], /* Domain socket, if any */
74 request
[1024], /* Quoted RequestRoot */
75 root
[1024], /* Quoted ServerRoot */
76 temp
[1024]; /* Quoted TempDir */
77 const char *nodebug
; /* " (with no-log)" for no debug */
78 cupsd_listener_t
*lis
; /* Current listening socket */
81 if (!UseSandboxing
|| Sandboxing
== CUPSD_SANDBOXING_OFF
)
84 * Only use sandbox profiles as root...
87 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id
, allow_networking
);
92 if ((fp
= cupsTempFile2(profile
, sizeof(profile
))) == NULL
)
94 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id
, allow_networking
);
95 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create security profile: %s",
100 fchown(cupsFileNumber(fp
), RunUser
, Group
);
101 fchmod(cupsFileNumber(fp
), 0640);
103 cupsd_requote(bin
, ServerBin
, sizeof(bin
));
104 cupsd_requote(cache
, CacheDir
, sizeof(cache
));
105 cupsd_requote(request
, RequestRoot
, sizeof(request
));
106 cupsd_requote(root
, ServerRoot
, sizeof(root
));
107 cupsd_requote(temp
, TempDir
, sizeof(temp
));
109 nodebug
= LogLevel
< CUPSD_LOG_DEBUG
? " (with no-log)" : "";
111 cupsFilePuts(fp
, "(version 1)\n");
112 if (Sandboxing
== CUPSD_SANDBOXING_STRICT
)
113 cupsFilePuts(fp
, "(deny default)\n");
115 cupsFilePuts(fp
, "(allow default)\n");
116 if (LogLevel
>= CUPSD_LOG_DEBUG
)
117 cupsFilePuts(fp
, "(debug deny)\n");
118 cupsFilePuts(fp
, "(import \"system.sb\")\n");
119 cupsFilePuts(fp
, "(system-network)\n");
120 cupsFilePuts(fp
, "(allow mach-per-user-lookup)\n");
121 cupsFilePuts(fp
, "(allow ipc-posix-sem)\n");
122 cupsFilePuts(fp
, "(allow ipc-posix-shm)\n");
123 cupsFilePuts(fp
, "(allow ipc-sysv-shm)\n");
124 cupsFilePuts(fp
, "(allow mach-lookup)\n");
126 "(deny file-write* file-read-data file-read-metadata\n"
128 " #\"^%s$\"" /* RequestRoot */
129 " #\"^%s/\"" /* RequestRoot/... */
131 request
, request
, nodebug
);
134 "(deny file-write* file-read-data file-read-metadata\n"
140 "(deny file-write*\n"
142 " #\"^%s$\"" /* ServerRoot */
143 " #\"^%s/\"" /* ServerRoot/... */
144 " #\"^/private/etc$\""
145 " #\"^/private/etc/\""
146 " #\"^/usr/local/etc$\""
147 " #\"^/usr/local/etc/\""
153 root
, root
, nodebug
);
154 /* Specifically allow applications to stat RequestRoot and some other system folders */
156 "(allow file-read-metadata\n"
159 " #\"^/usr$\"" /* /usr */
160 " #\"^/Library$\"" /* /Library */
161 " #\"^/Library/Printers$\"" /* /Library/Printers */
162 " #\"^%s$\"" /* RequestRoot */
165 /* Read and write TempDir, CacheDir, and other common folders */
167 "(allow file-write* file-read-data file-read-metadata\n"
169 " #\"^%s$\"" /* TempDir */
170 " #\"^%s/\"" /* TempDir/... */
171 " #\"^%s$\"" /* CacheDir */
172 " #\"^%s/\"" /* CacheDir/... */
173 " #\"^/private/var/db/\""
174 " #\"^/private/var/folders/\""
175 " #\"^/private/var/run/\""
176 " #\"^/Library/Application Support/\""
177 " #\"^/Library/Caches/\""
178 " #\"^/Library/Preferences/\""
179 " #\"^/Users/Shared/\""
181 temp
, temp
, cache
, cache
);
182 /* Read common folders */
184 "(allow file-read-data file-read-metadata\n"
186 " #\"^/AppleInternal$\""
187 " #\"^/AppleInternal/\""
188 " #\"^/bin$\"" /* /bin */
189 " #\"^/bin/\"" /* /bin/... */
191 " #\"^/private/etc/services$\""
192 " #\"^/private/var$\""
193 " #\"^/private/var/db$\""
194 " #\"^/private/var/spool$\""
195 " #\"^/usr/bin$\"" /* /usr/bin */
196 " #\"^/usr/bin/\"" /* /usr/bin/... */
197 " #\"^/usr/libexec/cups$\"" /* /usr/libexec/cups */
198 " #\"^/usr/libexec/cups/\"" /* /usr/libexec/cups/... */
199 " #\"^/usr/sbin$\"" /* /usr/sbin */
200 " #\"^/usr/sbin/\"" /* /usr/sbin/... */
201 " #\"^/Library/Caches$\""
202 " #\"^/Library/Fonts$\""
203 " #\"^/Library/Fonts/\""
204 " #\"^/Library/Keychains$\""
205 " #\"^/Library/Keychains/\""
206 " #\"^/Library/Printers$\""
207 " #\"^/Library/Printers/\""
208 " #\"^%s/Library$\"" /* RequestRoot/Library */
209 " #\"^%s/Library/\"" /* RequestRoot/Library/... */
210 " #\"^%s$\"" /* ServerBin */
211 " #\"^%s/\"" /* ServerBin/... */
212 " #\"^%s$\"" /* ServerRoot */
213 " #\"^%s/\"" /* ServerRoot/... */
215 request
, request
, bin
, bin
, root
, root
);
216 if (Sandboxing
== CUPSD_SANDBOXING_RELAXED
)
218 /* Limited write access to /Library/Printers/... */
220 "(allow file-write*\n"
222 " #\"^/Library/Printers/.*/\""
225 "(deny file-write*\n"
227 " #\"^/Library/Printers/PPDs$\""
228 " #\"^/Library/Printers/PPDs/\""
229 " #\"^/Library/Printers/PPD Plugins$\""
230 " #\"^/Library/Printers/PPD Plugins/\""
233 /* Allow execution of child processes */
234 cupsFilePuts(fp
, "(allow process-fork)\n");
236 "(allow process-exec\n"
238 " #\"^/bin/\"" /* /bin/... */
239 " #\"^/usr/bin/\"" /* /usr/bin/... */
240 " #\"^/usr/libexec/cups/\"" /* /usr/libexec/cups/... */
241 " #\"^/usr/sbin/\"" /* /usr/sbin/... */
242 " #\"^%s/\"" /* ServerBin/... */
243 " #\"^/Library/Printers/.*/\""
246 if (RunUser
&& getenv("CUPS_TESTROOT"))
248 /* Allow source directory access in "make test" environment */
249 char testroot
[1024]; /* Root directory of test files */
251 cupsd_requote(testroot
, getenv("CUPS_TESTROOT"), sizeof(testroot
));
254 "(allow file-write* file-read-data file-read-metadata\n"
256 " #\"^%s$\"" /* CUPS_TESTROOT */
257 " #\"^%s/\"" /* CUPS_TESTROOT/... */
261 "(allow process-exec\n"
263 " #\"^%s/\"" /* CUPS_TESTROOT/... */
269 /* Allow job filters to read the current job files... */
271 "(allow file-read-data file-read-metadata\n"
272 " (regex #\"^%s/([ac]%05d|d%05d-[0-9][0-9][0-9])$\"))\n",
273 request
, job_id
, job_id
);
277 /* Allow email notifications from notifiers... */
279 "(allow process-exec\n"
280 " (literal \"/usr/sbin/sendmail\")\n"
281 " (with no-sandbox))\n");
283 /* Allow outbound networking to local services */
284 cupsFilePuts(fp
, "(allow network-outbound"
285 "\n (regex #\"^/private/var/run/\")");
286 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
288 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
290 if (httpAddrFamily(&(lis
->address
)) == AF_LOCAL
)
292 httpAddrString(&(lis
->address
), domain
, sizeof(domain
));
293 cupsFilePrintf(fp
, "\n (literal \"%s\")", domain
);
296 if (allow_networking
)
298 /* Allow TCP and UDP networking off the machine... */
299 cupsFilePuts(fp
, "\n (remote tcp))\n");
300 cupsFilePuts(fp
, "(allow network*\n"
301 " (local udp \"*:*\")\n"
302 " (remote udp \"*:*\"))\n");
304 /* Also allow access to Bluetooth, USB, and SMB */
305 cupsFilePuts(fp
, "(allow iokit-open)\n");
306 cupsFilePuts(fp
, "(allow file-write* file-read-data file-read-metadata file-ioctl\n"
307 " (regex #\"^/dev/nsmb[0-9]+$\"))\n");
311 /* Only allow SNMP (UDP) off the machine... */
312 cupsFilePuts(fp
, ")\n");
313 cupsFilePuts(fp
, "(allow network-outbound\n"
314 " (remote udp \"*:161\"))\n");
315 cupsFilePuts(fp
, "(allow network-inbound\n"
316 " (local udp \"localhost:*\"))\n");
320 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCreateProfile(job_id=%d,allow_networking=%d) = \"%s\"", job_id
, allow_networking
, profile
);
321 return ((void *)strdup(profile
));
324 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id
, allow_networking
);
327 #endif /* HAVE_SANDBOX_H */
332 * 'cupsdDestroyProfile()' - Delete an execution profile.
336 cupsdDestroyProfile(void *profile
) /* I - Profile */
338 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdDeleteProfile(profile=\"%s\")",
339 profile
? (char *)profile
: "(null)");
341 #ifdef HAVE_SANDBOX_H
344 unlink((char *)profile
);
347 #endif /* HAVE_SANDBOX_H */
352 * 'cupsdEndProcess()' - End a process.
355 int /* O - 0 on success, -1 on failure */
356 cupsdEndProcess(int pid
, /* I - Process ID */
357 int force
) /* I - Force child to die */
359 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdEndProcess(pid=%d, force=%d)", pid
,
368 * When running as root, cupsd puts child processes in their own process
369 * group. Using "-pid" sends a signal to all processes in the group.
376 return (kill(pid
, SIGKILL
));
378 return (kill(pid
, SIGTERM
));
383 * 'cupsdFinishProcess()' - Finish a process and get its name.
386 const char * /* O - Process name */
387 cupsdFinishProcess(int pid
, /* I - Process ID */
388 char *name
, /* I - Name buffer */
389 size_t namelen
, /* I - Size of name buffer */
390 int *job_id
) /* O - Job ID pointer or NULL */
392 cupsd_proc_t key
, /* Search key */
393 *proc
; /* Matching process */
398 if ((proc
= (cupsd_proc_t
*)cupsArrayFind(process_array
, &key
)) != NULL
)
401 *job_id
= proc
->job_id
;
403 strlcpy(name
, proc
->name
, namelen
);
404 cupsArrayRemove(process_array
, proc
);
412 strlcpy(name
, "unknown", namelen
);
415 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
);
422 * 'cupsdStartProcess()' - Start a process.
425 int /* O - Process ID or 0 */
427 const char *command
, /* I - Full path to command */
428 char *argv
[], /* I - Command-line arguments */
429 char *envp
[], /* I - Environment */
430 int infd
, /* I - Standard input file descriptor */
431 int outfd
, /* I - Standard output file descriptor */
432 int errfd
, /* I - Standard error file descriptor */
433 int backfd
, /* I - Backchannel file descriptor */
434 int sidefd
, /* I - Sidechannel file descriptor */
435 int root
, /* I - Run as root? */
436 void *profile
, /* I - Security profile to use */
437 cupsd_job_t
*job
, /* I - Job associated with process */
438 int *pid
) /* O - Process ID */
440 int i
; /* Looping var */
441 const char *exec_path
= command
; /* Command to be exec'd */
442 char *real_argv
[110], /* Real command-line arguments */
443 cups_exec
[1024]; /* Path to "cups-exec" program */
444 uid_t user
; /* Command UID */
445 cupsd_proc_t
*proc
; /* New process record */
446 #ifdef HAVE_POSIX_SPAWN
447 posix_spawn_file_actions_t actions
; /* Spawn file actions */
448 posix_spawnattr_t attrs
; /* Spawn attributes */
449 char user_str
[16], /* User string */
450 group_str
[16], /* Group string */
451 nice_str
[16]; /* FilterNice string */
452 #elif defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
453 struct sigaction action
; /* POSIX signal handler */
454 #endif /* HAVE_POSIX_SPAWN */
455 #if defined(__APPLE__)
456 char processPath
[1024], /* CFProcessPath environment variable */
457 linkpath
[1024]; /* Link path for symlinks... */
458 int linkbytes
; /* Bytes for link path */
459 #endif /* __APPLE__ */
465 * Figure out the UID for the child process...
476 * Check the permissions of the command we are running...
479 if (_cupsFileCheck(command
, _CUPS_FILE_CHECK_PROGRAM
, !RunUser
,
480 cupsdLogFCMessage
, job
? job
->printer
: NULL
))
483 #if defined(__APPLE__)
487 * Add special voodoo magic for OS X - this allows OS X programs to access
488 * their bundle resources properly...
491 if ((linkbytes
= readlink(command
, linkpath
, sizeof(linkpath
) - 1)) > 0)
494 * Yes, this is a symlink to the actual program, nul-terminate and
498 linkpath
[linkbytes
] = '\0';
500 if (linkpath
[0] == '/')
501 snprintf(processPath
, sizeof(processPath
), "CFProcessPath=%s",
504 snprintf(processPath
, sizeof(processPath
), "CFProcessPath=%s/%s",
505 dirname((char *)command
), linkpath
);
508 snprintf(processPath
, sizeof(processPath
), "CFProcessPath=%s", command
);
510 envp
[0] = processPath
; /* Replace <CFProcessPath> string */
512 #endif /* __APPLE__ */
515 * Use helper program when we have a sandbox profile...
518 #ifndef HAVE_POSIX_SPAWN
520 #endif /* !HAVE_POSIX_SPAWN */
522 snprintf(cups_exec
, sizeof(cups_exec
), "%s/daemon/cups-exec", ServerBin
);
523 snprintf(user_str
, sizeof(user_str
), "%d", user
);
524 snprintf(group_str
, sizeof(group_str
), "%d", Group
);
525 snprintf(nice_str
, sizeof(nice_str
), "%d", FilterNice
);
527 real_argv
[0] = cups_exec
;
528 real_argv
[1] = (char *)"-g";
529 real_argv
[2] = group_str
;
530 real_argv
[3] = (char *)"-n";
531 real_argv
[4] = nice_str
;
532 real_argv
[5] = (char *)"-u";
533 real_argv
[6] = user_str
;
534 real_argv
[7] = profile
;
535 real_argv
[8] = (char *)command
;
538 i
< (int)(sizeof(real_argv
) / sizeof(real_argv
[0]) - 10) && argv
[i
];
540 real_argv
[i
+ 9] = argv
[i
];
542 real_argv
[i
+ 9] = NULL
;
545 exec_path
= cups_exec
;
548 if (LogLevel
== CUPSD_LOG_DEBUG2
)
550 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: Preparing to start \"%s\", arguments:", command
);
552 for (i
= 0; argv
[i
]; i
++)
553 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: argv[%d] = \"%s\"", i
, argv
[i
]);
556 #ifdef HAVE_POSIX_SPAWN
558 * Setup attributes and file actions for the spawn...
561 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: Setting spawn attributes.");
562 posix_spawnattr_init(&attrs
);
563 posix_spawnattr_setflags(&attrs
, POSIX_SPAWN_SETPGROUP
| POSIX_SPAWN_SETSIGDEF
);
565 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: Setting file actions.");
566 posix_spawn_file_actions_init(&actions
);
570 posix_spawn_file_actions_addopen(&actions
, 0, "/dev/null", O_WRONLY
, 0);
572 posix_spawn_file_actions_adddup2(&actions
, infd
, 0);
578 posix_spawn_file_actions_addopen(&actions
, 1, "/dev/null", O_WRONLY
, 0);
580 posix_spawn_file_actions_adddup2(&actions
, outfd
, 1);
586 posix_spawn_file_actions_addopen(&actions
, 2, "/dev/null", O_WRONLY
, 0);
588 posix_spawn_file_actions_adddup2(&actions
, errfd
, 2);
591 if (backfd
!= 3 && backfd
>= 0)
592 posix_spawn_file_actions_adddup2(&actions
, backfd
, 3);
594 if (sidefd
!= 4 && sidefd
>= 0)
595 posix_spawn_file_actions_adddup2(&actions
, sidefd
, 4);
597 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: Calling posix_spawn.");
599 if (posix_spawn(pid
, exec_path
, &actions
, &attrs
, argv
, envp
? envp
: environ
))
601 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork %s - %s.", command
, strerror(errno
));
606 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdStartProcess: pid=%d", (int)*pid
);
608 posix_spawn_file_actions_destroy(&actions
);
609 posix_spawnattr_destroy(&attrs
);
613 * Block signals before forking...
618 if ((*pid
= fork()) == 0)
621 * Child process goes here; update stderr as needed...
627 errfd
= open("/dev/null", O_WRONLY
);
637 * Put this process in its own process group so that we can kill any child
638 * processes it creates.
642 if (!RunUser
&& setpgid(0, 0))
645 if (!RunUser
&& setpgrp())
647 # endif /* HAVE_SETPGID */
650 * Update the remaining file descriptors as needed...
656 infd
= open("/dev/null", O_RDONLY
);
668 outfd
= open("/dev/null", O_WRONLY
);
677 if (backfd
!= 3 && backfd
>= 0)
681 fcntl(3, F_SETFL
, O_NDELAY
);
684 if (sidefd
!= 4 && sidefd
>= 0)
688 fcntl(4, F_SETFL
, O_NDELAY
);
692 * Change the priority of the process based on the FilterNice setting.
693 * (this is not done for root processes...)
700 * Reset group membership to just the main one we belong to.
703 if (!RunUser
&& setgid(Group
))
706 if (!RunUser
&& setgroups(1, &Group
))
710 * Change user to something "safe"...
713 if (!RunUser
&& user
&& setuid(user
))
717 * Change umask to restrict permissions on created files...
723 * Unblock signals before doing the exec...
727 sigset(SIGTERM
, SIG_DFL
);
728 sigset(SIGCHLD
, SIG_DFL
);
729 sigset(SIGPIPE
, SIG_DFL
);
730 # elif defined(HAVE_SIGACTION)
731 memset(&action
, 0, sizeof(action
));
733 sigemptyset(&action
.sa_mask
);
734 action
.sa_handler
= SIG_DFL
;
736 sigaction(SIGTERM
, &action
, NULL
);
737 sigaction(SIGCHLD
, &action
, NULL
);
738 sigaction(SIGPIPE
, &action
, NULL
);
740 signal(SIGTERM
, SIG_DFL
);
741 signal(SIGCHLD
, SIG_DFL
);
742 signal(SIGPIPE
, SIG_DFL
);
743 # endif /* HAVE_SIGSET */
745 cupsdReleaseSignals();
748 * Execute the command; if for some reason this doesn't work, log an error
749 * exit with a non-zero value...
753 execve(exec_path
, argv
, envp
);
755 execv(exec_path
, argv
);
762 * Error - couldn't fork a new process!
765 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork %s - %s.", command
,
771 cupsdReleaseSignals();
772 #endif /* HAVE_POSIX_SPAWN */
777 process_array
= cupsArrayNew((cups_array_func_t
)compare_procs
, NULL
);
781 if ((proc
= calloc(1, sizeof(cupsd_proc_t
) + strlen(command
))) != NULL
)
784 proc
->job_id
= job
? job
->id
: 0;
785 _cups_strcpy(proc
->name
, command
);
787 cupsArrayAdd(process_array
, proc
);
792 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
793 "cupsdStartProcess(command=\"%s\", argv=%p, envp=%p, "
794 "infd=%d, outfd=%d, errfd=%d, backfd=%d, sidefd=%d, root=%d, "
795 "profile=%p, job=%p(%d), pid=%p) = %d",
796 command
, argv
, envp
, infd
, outfd
, errfd
, backfd
, sidefd
,
797 root
, profile
, job
, job
? job
->id
: 0, pid
, *pid
);
804 * 'compare_procs()' - Compare two processes.
807 static int /* O - Result of comparison */
808 compare_procs(cupsd_proc_t
*a
, /* I - First process */
809 cupsd_proc_t
*b
) /* I - Second process */
811 return (a
->pid
- b
->pid
);
815 #ifdef HAVE_SANDBOX_H
817 * 'cupsd_requote()' - Make a regular-expression version of a string.
820 static char * /* O - Quoted string */
821 cupsd_requote(char *dst
, /* I - Destination buffer */
822 const char *src
, /* I - Source string */
823 size_t dstsize
) /* I - Size of destination buffer */
825 int ch
; /* Current character */
826 char *dstptr
, /* Current position in buffer */
827 *dstend
; /* End of destination buffer */
831 dstend
= dst
+ dstsize
- 2;
833 while (*src
&& dstptr
< dstend
)
837 if (ch
== '/' && !*src
)
838 break; /* Don't add trailing slash */
840 if (strchr(".?*()[]^$\\", ch
))
843 *dstptr
++ = (char)ch
;
850 #endif /* HAVE_SANDBOX_H */