VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/process-creation-posix.cpp@ 62477

Last change on this file since 62477 was 62477, checked in by vboxsync, 9 years ago

(C) 2016

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 33.2 KB
Line 
1/* $Id: process-creation-posix.cpp 62477 2016-07-22 18:27:37Z vboxsync $ */
2/** @file
3 * IPRT - Process Creation, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP RTLOGGROUP_PROCESS
32#include <iprt/cdefs.h>
33
34#include <unistd.h>
35#include <stdlib.h>
36#include <errno.h>
37#include <sys/types.h>
38#include <sys/stat.h>
39#include <sys/wait.h>
40#include <fcntl.h>
41#include <signal.h>
42#include <grp.h>
43#include <pwd.h>
44#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
45# include <crypt.h>
46# include <shadow.h>
47#endif
48
49#if defined(RT_OS_LINUX) || defined(RT_OS_OS2)
50/* While Solaris has posix_spawn() of course we don't want to use it as
51 * we need to have the child in a different process contract, no matter
52 * whether it is started detached or not. */
53# define HAVE_POSIX_SPAWN 1
54#endif
55#if defined(RT_OS_DARWIN) && defined(MAC_OS_X_VERSION_MIN_REQUIRED)
56# if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
57# define HAVE_POSIX_SPAWN 1
58# endif
59#endif
60#ifdef HAVE_POSIX_SPAWN
61# include <spawn.h>
62#endif
63
64#ifdef RT_OS_DARWIN
65# include <mach-o/dyld.h>
66#endif
67#ifdef RT_OS_SOLARIS
68# include <limits.h>
69# include <sys/ctfs.h>
70# include <sys/contract/process.h>
71# include <libcontract.h>
72#endif
73
74#ifndef RT_OS_SOLARIS
75# include <paths.h>
76#else
77# define _PATH_MAILDIR "/var/mail"
78# define _PATH_DEFPATH "/usr/bin:/bin"
79# define _PATH_STDPATH "/sbin:/usr/sbin:/bin:/usr/bin"
80#endif
81
82
83#include <iprt/process.h>
84#include "internal/iprt.h"
85
86#include <iprt/assert.h>
87#include <iprt/env.h>
88#include <iprt/err.h>
89#include <iprt/file.h>
90#include <iprt/path.h>
91#include <iprt/pipe.h>
92#include <iprt/socket.h>
93#include <iprt/string.h>
94#include <iprt/mem.h>
95#include "internal/process.h"
96
97
98/**
99 * Check the credentials and return the gid/uid of user.
100 *
101 * @param pszUser username
102 * @param pszPasswd password
103 * @param gid where to store the GID of the user
104 * @param uid where to store the UID of the user
105 * @returns IPRT status code
106 */
107static int rtCheckCredentials(const char *pszUser, const char *pszPasswd, gid_t *pGid, uid_t *pUid)
108{
109#if defined(RT_OS_LINUX)
110 struct passwd *pw;
111
112 pw = getpwnam(pszUser);
113 if (!pw)
114 return VERR_AUTHENTICATION_FAILURE;
115
116 if (!pszPasswd)
117 pszPasswd = "";
118
119 struct spwd *spwd;
120 /* works only if /etc/shadow is accessible */
121 spwd = getspnam(pszUser);
122 if (spwd)
123 pw->pw_passwd = spwd->sp_pwdp;
124
125 /* Default fCorrect=true if no password specified. In that case, pw->pw_passwd
126 * must be NULL (no password set for this user). Fail if a password is specified
127 * but the user does not have one assigned. */
128 int fCorrect = !pszPasswd || !*pszPasswd;
129 if (pw->pw_passwd && *pw->pw_passwd)
130 {
131 struct crypt_data *data = (struct crypt_data*)RTMemTmpAllocZ(sizeof(*data));
132 /* be reentrant */
133 char *pszEncPasswd = crypt_r(pszPasswd, pw->pw_passwd, data);
134 fCorrect = pszEncPasswd && !strcmp(pszEncPasswd, pw->pw_passwd);
135 RTMemTmpFree(data);
136 }
137 if (!fCorrect)
138 return VERR_AUTHENTICATION_FAILURE;
139
140 *pGid = pw->pw_gid;
141 *pUid = pw->pw_uid;
142 return VINF_SUCCESS;
143
144#elif defined(RT_OS_SOLARIS)
145 struct passwd *ppw, pw;
146 char szBuf[1024];
147
148 if (getpwnam_r(pszUser, &pw, szBuf, sizeof(szBuf), &ppw) != 0 || ppw == NULL)
149 return VERR_AUTHENTICATION_FAILURE;
150
151 if (!pszPasswd)
152 pszPasswd = "";
153
154 struct spwd spwd;
155 char szPwdBuf[1024];
156 /* works only if /etc/shadow is accessible */
157 if (getspnam_r(pszUser, &spwd, szPwdBuf, sizeof(szPwdBuf)) != NULL)
158 ppw->pw_passwd = spwd.sp_pwdp;
159
160 char *pszEncPasswd = crypt(pszPasswd, ppw->pw_passwd);
161 if (strcmp(pszEncPasswd, ppw->pw_passwd))
162 return VERR_AUTHENTICATION_FAILURE;
163
164 *pGid = ppw->pw_gid;
165 *pUid = ppw->pw_uid;
166 return VINF_SUCCESS;
167
168#else
169 NOREF(pszUser); NOREF(pszPasswd); NOREF(pGid); NOREF(pUid);
170 return VERR_AUTHENTICATION_FAILURE;
171#endif
172}
173
174
175#ifdef RT_OS_SOLARIS
176/** @todo the error reporting of the Solaris process contract code could be
177 * a lot better, but essentially it is not meant to run into errors after
178 * the debugging phase. */
179static int rtSolarisContractPreFork(void)
180{
181 int templateFd = open64(CTFS_ROOT "/process/template", O_RDWR);
182 if (templateFd < 0)
183 return -1;
184
185 /* Set template parameters and event sets. */
186 if (ct_pr_tmpl_set_param(templateFd, CT_PR_PGRPONLY))
187 {
188 close(templateFd);
189 return -1;
190 }
191 if (ct_pr_tmpl_set_fatal(templateFd, CT_PR_EV_HWERR))
192 {
193 close(templateFd);
194 return -1;
195 }
196 if (ct_tmpl_set_critical(templateFd, 0))
197 {
198 close(templateFd);
199 return -1;
200 }
201 if (ct_tmpl_set_informative(templateFd, CT_PR_EV_HWERR))
202 {
203 close(templateFd);
204 return -1;
205 }
206
207 /* Make this the active template for the process. */
208 if (ct_tmpl_activate(templateFd))
209 {
210 close(templateFd);
211 return -1;
212 }
213
214 return templateFd;
215}
216
217static void rtSolarisContractPostForkChild(int templateFd)
218{
219 if (templateFd == -1)
220 return;
221
222 /* Clear the active template. */
223 ct_tmpl_clear(templateFd);
224 close(templateFd);
225}
226
227static void rtSolarisContractPostForkParent(int templateFd, pid_t pid)
228{
229 if (templateFd == -1)
230 return;
231
232 /* Clear the active template. */
233 int cleared = ct_tmpl_clear(templateFd);
234 close(templateFd);
235
236 /* If the clearing failed or the fork failed there's nothing more to do. */
237 if (cleared || pid <= 0)
238 return;
239
240 /* Look up the contract which was created by this thread. */
241 int statFd = open64(CTFS_ROOT "/process/latest", O_RDONLY);
242 if (statFd == -1)
243 return;
244 ct_stathdl_t statHdl;
245 if (ct_status_read(statFd, CTD_COMMON, &statHdl))
246 {
247 close(statFd);
248 return;
249 }
250 ctid_t ctId = ct_status_get_id(statHdl);
251 ct_status_free(statHdl);
252 close(statFd);
253 if (ctId < 0)
254 return;
255
256 /* Abandon this contract we just created. */
257 char ctlPath[PATH_MAX];
258 size_t len = snprintf(ctlPath, sizeof(ctlPath),
259 CTFS_ROOT "/process/%ld/ctl", (long)ctId);
260 if (len >= sizeof(ctlPath))
261 return;
262 int ctlFd = open64(ctlPath, O_WRONLY);
263 if (statFd == -1)
264 return;
265 if (ct_ctl_abandon(ctlFd) < 0)
266 {
267 close(ctlFd);
268 return;
269 }
270 close(ctlFd);
271}
272
273#endif /* RT_OS_SOLARIS */
274
275
276RTR3DECL(int) RTProcCreate(const char *pszExec, const char * const *papszArgs, RTENV Env, unsigned fFlags, PRTPROCESS pProcess)
277{
278 return RTProcCreateEx(pszExec, papszArgs, Env, fFlags,
279 NULL, NULL, NULL, /* standard handles */
280 NULL /*pszAsUser*/, NULL /* pszPassword*/,
281 pProcess);
282}
283
284
285/**
286 * Adjust the profile environment after forking the child process and changing
287 * the UID.
288 *
289 * @returns IRPT status code.
290 * @param hEnvToUse The environment we're going to use with execve.
291 * @param fFlags The process creation flags.
292 * @param hEnv The environment passed in by the user.
293 */
294static int rtProcPosixAdjustProfileEnvFromChild(RTENV hEnvToUse, uint32_t fFlags, RTENV hEnv)
295{
296 int rc = VINF_SUCCESS;
297#ifdef RT_OS_DARWIN
298 if ( RT_SUCCESS(rc)
299 && (!(fFlags & RTPROC_FLAGS_ENV_CHANGE_RECORD) || RTEnvExistEx(hEnv, "TMPDIR")) )
300 {
301 char szValue[_4K];
302 size_t cbNeeded = confstr(_CS_DARWIN_USER_TEMP_DIR, szValue, sizeof(szValue));
303 if (cbNeeded > 0 && cbNeeded < sizeof(szValue))
304 {
305 char *pszTmp;
306 rc = RTStrCurrentCPToUtf8(&pszTmp, szValue);
307 if (RT_SUCCESS(rc))
308 {
309 rc = RTEnvSetEx(hEnvToUse, "TMPDIR", pszTmp);
310 RTStrFree(pszTmp);
311 }
312 }
313 else
314 rc = VERR_BUFFER_OVERFLOW;
315 }
316#endif
317 return rc;
318}
319
320
321/**
322 * Create a very very basic environment for a user.
323 *
324 * @returns IPRT status code.
325 * @param phEnvToUse Where to return the created environment.
326 * @param pszUser The user name for the profile.
327 */
328static int rtProcPosixCreateProfileEnv(PRTENV phEnvToUse, const char *pszUser)
329{
330 struct passwd Pwd;
331 struct passwd *pPwd = NULL;
332 char achBuf[_4K];
333 int rc;
334 errno = 0;
335 if (pszUser)
336 rc = getpwnam_r(pszUser, &Pwd, achBuf, sizeof(achBuf), &pPwd);
337 else
338 rc = getpwuid_r(getuid(), &Pwd, achBuf, sizeof(achBuf), &pPwd);
339 if (rc == 0 && pPwd)
340 {
341 char *pszDir;
342 rc = RTStrCurrentCPToUtf8(&pszDir, pPwd->pw_dir);
343 if (RT_SUCCESS(rc))
344 {
345 char *pszShell;
346 rc = RTStrCurrentCPToUtf8(&pszShell, pPwd->pw_shell);
347 if (RT_SUCCESS(rc))
348 {
349 char *pszUserFree = NULL;
350 if (!pszUser)
351 {
352 rc = RTStrCurrentCPToUtf8(&pszUserFree, pPwd->pw_name);
353 if (RT_SUCCESS(rc))
354 pszUser = pszUserFree;
355 }
356 if (RT_SUCCESS(rc))
357 {
358 rc = RTEnvCreate(phEnvToUse);
359 if (RT_SUCCESS(rc))
360 {
361 RTENV hEnvToUse = *phEnvToUse;
362
363 rc = RTEnvSetEx(hEnvToUse, "HOME", pszDir);
364 if (RT_SUCCESS(rc))
365 rc = RTEnvSetEx(hEnvToUse, "SHELL", pszShell);
366 if (RT_SUCCESS(rc))
367 rc = RTEnvSetEx(hEnvToUse, "USER", pszUser);
368 if (RT_SUCCESS(rc))
369 rc = RTEnvSetEx(hEnvToUse, "LOGNAME", pszUser);
370
371 if (RT_SUCCESS(rc))
372 rc = RTEnvSetEx(hEnvToUse, "PATH", pPwd->pw_uid == 0 ? _PATH_STDPATH : _PATH_DEFPATH);
373
374 if (RT_SUCCESS(rc))
375 {
376 RTStrPrintf(achBuf, sizeof(achBuf), "%s/%s", _PATH_MAILDIR, pszUser);
377 rc = RTEnvSetEx(hEnvToUse, "MAIL", achBuf);
378 }
379
380#ifdef RT_OS_DARWIN
381 if (RT_SUCCESS(rc) && !pszUserFree)
382 {
383 size_t cbNeeded = confstr(_CS_DARWIN_USER_TEMP_DIR, achBuf, sizeof(achBuf));
384 if (cbNeeded > 0 && cbNeeded < sizeof(achBuf))
385 {
386 char *pszTmp;
387 rc = RTStrCurrentCPToUtf8(&pszTmp, achBuf);
388 if (RT_SUCCESS(rc))
389 {
390 rc = RTEnvSetEx(hEnvToUse, "TMPDIR", pszTmp);
391 RTStrFree(pszTmp);
392 }
393 }
394 else
395 rc = VERR_BUFFER_OVERFLOW;
396 }
397#endif
398
399 /** @todo load /etc/environment, /etc/profile.env and ~/.pam_environment? */
400
401 if (RT_FAILURE(rc))
402 RTEnvDestroy(hEnvToUse);
403 }
404 RTStrFree(pszUserFree);
405 }
406 RTStrFree(pszShell);
407 }
408 RTStrFree(pszDir);
409 }
410 }
411 else
412 rc = errno ? RTErrConvertFromErrno(errno) : VERR_ACCESS_DENIED;
413 return rc;
414}
415
416
417/**
418 * RTPathTraverseList callback used by RTProcCreateEx to locate the executable.
419 */
420static DECLCALLBACK(int) rtPathFindExec(char const *pchPath, size_t cchPath, void *pvUser1, void *pvUser2)
421{
422 const char *pszExec = (const char *)pvUser1;
423 char *pszRealExec = (char *)pvUser2;
424 int rc = RTPathJoinEx(pszRealExec, RTPATH_MAX, pchPath, cchPath, pszExec, RTSTR_MAX);
425 if (RT_FAILURE(rc))
426 return rc;
427 if (!access(pszRealExec, X_OK))
428 return VINF_SUCCESS;
429 if ( errno == EACCES
430 || errno == EPERM)
431 return RTErrConvertFromErrno(errno);
432 return VERR_TRY_AGAIN;
433}
434
435/**
436 * Cleans up the environment on the way out.
437 */
438static int rtProcPosixCreateReturn(int rc, RTENV hEnvToUse, RTENV hEnv)
439{
440 if (hEnvToUse != hEnv)
441 RTEnvDestroy(hEnvToUse);
442 return rc;
443}
444
445
446RTR3DECL(int) RTProcCreateEx(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
447 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
448 const char *pszPassword, PRTPROCESS phProcess)
449{
450 int rc;
451
452 /*
453 * Input validation
454 */
455 AssertPtrReturn(pszExec, VERR_INVALID_POINTER);
456 AssertReturn(*pszExec, VERR_INVALID_PARAMETER);
457 AssertReturn(!(fFlags & ~RTPROC_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER);
458 AssertReturn(!(fFlags & RTPROC_FLAGS_DETACHED) || !phProcess, VERR_INVALID_PARAMETER);
459 AssertReturn(hEnv != NIL_RTENV, VERR_INVALID_PARAMETER);
460 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
461 AssertPtrNullReturn(pszAsUser, VERR_INVALID_POINTER);
462 AssertReturn(!pszAsUser || *pszAsUser, VERR_INVALID_PARAMETER);
463 AssertReturn(!pszPassword || pszAsUser, VERR_INVALID_PARAMETER);
464 AssertPtrNullReturn(pszPassword, VERR_INVALID_POINTER);
465#if defined(RT_OS_OS2)
466 if (fFlags & RTPROC_FLAGS_DETACHED)
467 return VERR_PROC_DETACH_NOT_SUPPORTED;
468#endif
469
470 /*
471 * Get the file descriptors for the handles we've been passed.
472 */
473 PCRTHANDLE paHandles[3] = { phStdIn, phStdOut, phStdErr };
474 int aStdFds[3] = { -1, -1, -1 };
475 for (int i = 0; i < 3; i++)
476 {
477 if (paHandles[i])
478 {
479 AssertPtrReturn(paHandles[i], VERR_INVALID_POINTER);
480 switch (paHandles[i]->enmType)
481 {
482 case RTHANDLETYPE_FILE:
483 aStdFds[i] = paHandles[i]->u.hFile != NIL_RTFILE
484 ? (int)RTFileToNative(paHandles[i]->u.hFile)
485 : -2 /* close it */;
486 break;
487
488 case RTHANDLETYPE_PIPE:
489 aStdFds[i] = paHandles[i]->u.hPipe != NIL_RTPIPE
490 ? (int)RTPipeToNative(paHandles[i]->u.hPipe)
491 : -2 /* close it */;
492 break;
493
494 case RTHANDLETYPE_SOCKET:
495 aStdFds[i] = paHandles[i]->u.hSocket != NIL_RTSOCKET
496 ? (int)RTSocketToNative(paHandles[i]->u.hSocket)
497 : -2 /* close it */;
498 break;
499
500 default:
501 AssertMsgFailedReturn(("%d: %d\n", i, paHandles[i]->enmType), VERR_INVALID_PARAMETER);
502 }
503 /** @todo check the close-on-execness of these handles? */
504 }
505 }
506
507 for (int i = 0; i < 3; i++)
508 if (aStdFds[i] == i)
509 aStdFds[i] = -1;
510
511 for (int i = 0; i < 3; i++)
512 AssertMsgReturn(aStdFds[i] < 0 || aStdFds[i] > i,
513 ("%i := %i not possible because we're lazy\n", i, aStdFds[i]),
514 VERR_NOT_SUPPORTED);
515
516 /*
517 * Resolve the user id if specified.
518 */
519 uid_t uid = ~(uid_t)0;
520 gid_t gid = ~(gid_t)0;
521 if (pszAsUser)
522 {
523 rc = rtCheckCredentials(pszAsUser, pszPassword, &gid, &uid);
524 if (RT_FAILURE(rc))
525 return rc;
526 }
527
528 /*
529 * Create the child environment if either RTPROC_FLAGS_PROFILE or
530 * RTPROC_FLAGS_ENV_CHANGE_RECORD are in effect.
531 */
532 RTENV hEnvToUse = hEnv;
533 if ( (fFlags & (RTPROC_FLAGS_ENV_CHANGE_RECORD | RTPROC_FLAGS_PROFILE))
534 && ( (fFlags & RTPROC_FLAGS_ENV_CHANGE_RECORD)
535 || hEnv == RTENV_DEFAULT) )
536 {
537 if (fFlags & RTPROC_FLAGS_PROFILE)
538 rc = rtProcPosixCreateProfileEnv(&hEnvToUse, pszAsUser);
539 else
540 rc = RTEnvClone(&hEnvToUse, RTENV_DEFAULT);
541 if (RT_SUCCESS(rc))
542 {
543 if ((fFlags & RTPROC_FLAGS_ENV_CHANGE_RECORD) && hEnv != RTENV_DEFAULT)
544 rc = RTEnvApplyChanges(hEnvToUse, hEnv);
545 if (RT_FAILURE(rc))
546 RTEnvDestroy(hEnvToUse);
547 }
548 if (RT_FAILURE(rc))
549 return rc;
550 }
551
552 /*
553 * Check for execute access to the file.
554 */
555 char szRealExec[RTPATH_MAX];
556 if (access(pszExec, X_OK))
557 {
558 rc = errno;
559 if ( !(fFlags & RTPROC_FLAGS_SEARCH_PATH)
560 || rc != ENOENT
561 || RTPathHavePath(pszExec) )
562 rc = RTErrConvertFromErrno(rc);
563 else
564 {
565 /* search */
566 char *pszPath = RTEnvDupEx(hEnvToUse, "PATH");
567 rc = RTPathTraverseList(pszPath, ':', rtPathFindExec, (void *)pszExec, &szRealExec[0]);
568 RTStrFree(pszPath);
569 if (RT_SUCCESS(rc))
570 pszExec = szRealExec;
571 else
572 rc = rc == VERR_END_OF_STRING ? VERR_FILE_NOT_FOUND : rc;
573 }
574
575 if (RT_FAILURE(rc))
576 return rtProcPosixCreateReturn(rc, hEnvToUse, hEnv);
577 }
578
579 pid_t pid = -1;
580 const char * const *papszEnv = RTEnvGetExecEnvP(hEnvToUse);
581 AssertPtrReturn(papszEnv, rtProcPosixCreateReturn(VERR_INVALID_HANDLE, hEnvToUse, hEnv));
582
583
584 /*
585 * Take care of detaching the process.
586 *
587 * HACK ALERT! Put the process into a new process group with pgid = pid
588 * to make sure it differs from that of the parent process to ensure that
589 * the IPRT waitpid call doesn't race anyone (read XPCOM) doing group wide
590 * waits. setsid() includes the setpgid() functionality.
591 * 2010-10-11 XPCOM no longer waits for anything, but it cannot hurt.
592 */
593#ifndef RT_OS_OS2
594 if (fFlags & RTPROC_FLAGS_DETACHED)
595 {
596# ifdef RT_OS_SOLARIS
597 int templateFd = -1;
598 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
599 {
600 templateFd = rtSolarisContractPreFork();
601 if (templateFd == -1)
602 return rtProcPosixCreateReturn(VERR_OPEN_FAILED, hEnvToUse, hEnv);
603 }
604# endif /* RT_OS_SOLARIS */
605 pid = fork();
606 if (!pid)
607 {
608# ifdef RT_OS_SOLARIS
609 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
610 rtSolarisContractPostForkChild(templateFd);
611# endif
612 setsid(); /* see comment above */
613
614 pid = -1;
615 /* Child falls through to the actual spawn code below. */
616 }
617 else
618 {
619# ifdef RT_OS_SOLARIS
620 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
621 rtSolarisContractPostForkParent(templateFd, pid);
622# endif
623 if (pid > 0)
624 {
625 /* Must wait for the temporary process to avoid a zombie. */
626 int status = 0;
627 pid_t pidChild = 0;
628
629 /* Restart if we get interrupted. */
630 do
631 {
632 pidChild = waitpid(pid, &status, 0);
633 } while ( pidChild == -1
634 && errno == EINTR);
635
636 /* Assume that something wasn't found. No detailed info. */
637 if (status)
638 return rtProcPosixCreateReturn(VERR_PROCESS_NOT_FOUND, hEnvToUse, hEnv);
639 if (phProcess)
640 *phProcess = 0;
641 return rtProcPosixCreateReturn(VINF_SUCCESS, hEnvToUse, hEnv);
642 }
643 return rtProcPosixCreateReturn(RTErrConvertFromErrno(errno), hEnvToUse, hEnv);
644 }
645 }
646#endif
647
648 /*
649 * Spawn the child.
650 *
651 * Any spawn code MUST not execute any atexit functions if it is for a
652 * detached process. It would lead to running the atexit functions which
653 * make only sense for the parent. libORBit e.g. gets confused by multiple
654 * execution. Remember, there was only a fork() so far, and until exec()
655 * is successfully run there is nothing which would prevent doing anything
656 * silly with the (duplicated) file descriptors.
657 */
658#ifdef HAVE_POSIX_SPAWN
659 /** @todo OS/2: implement DETACHED (BACKGROUND stuff), see VbglR3Daemonize. */
660 if ( uid == ~(uid_t)0
661 && gid == ~(gid_t)0)
662 {
663 /* Spawn attributes. */
664 posix_spawnattr_t Attr;
665 rc = posix_spawnattr_init(&Attr);
666 if (!rc)
667 {
668 /* Indicate that process group and signal mask are to be changed,
669 and that the child should use default signal actions. */
670 rc = posix_spawnattr_setflags(&Attr, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);
671 Assert(rc == 0);
672
673 /* The child starts in its own process group. */
674 if (!rc)
675 {
676 rc = posix_spawnattr_setpgroup(&Attr, 0 /* pg == child pid */);
677 Assert(rc == 0);
678 }
679
680 /* Unmask all signals. */
681 if (!rc)
682 {
683 sigset_t SigMask;
684 sigemptyset(&SigMask);
685 rc = posix_spawnattr_setsigmask(&Attr, &SigMask); Assert(rc == 0);
686 }
687
688 /* File changes. */
689 posix_spawn_file_actions_t FileActions;
690 posix_spawn_file_actions_t *pFileActions = NULL;
691 if ((aStdFds[0] != -1 || aStdFds[1] != -1 || aStdFds[2] != -1) && !rc)
692 {
693 rc = posix_spawn_file_actions_init(&FileActions);
694 if (!rc)
695 {
696 pFileActions = &FileActions;
697 for (int i = 0; i < 3; i++)
698 {
699 int fd = aStdFds[i];
700 if (fd == -2)
701 rc = posix_spawn_file_actions_addclose(&FileActions, i);
702 else if (fd >= 0 && fd != i)
703 {
704 rc = posix_spawn_file_actions_adddup2(&FileActions, fd, i);
705 if (!rc)
706 {
707 for (int j = i + 1; j < 3; j++)
708 if (aStdFds[j] == fd)
709 {
710 fd = -1;
711 break;
712 }
713 if (fd >= 0)
714 rc = posix_spawn_file_actions_addclose(&FileActions, fd);
715 }
716 }
717 if (rc)
718 break;
719 }
720 }
721 }
722
723 if (!rc)
724 rc = posix_spawn(&pid, pszExec, pFileActions, &Attr, (char * const *)papszArgs,
725 (char * const *)papszEnv);
726
727 /* cleanup */
728 int rc2 = posix_spawnattr_destroy(&Attr); Assert(rc2 == 0); NOREF(rc2);
729 if (pFileActions)
730 {
731 rc2 = posix_spawn_file_actions_destroy(pFileActions);
732 Assert(rc2 == 0);
733 }
734
735 /* return on success.*/
736 if (!rc)
737 {
738 /* For a detached process this happens in the temp process, so
739 * it's not worth doing anything as this process must exit. */
740 if (fFlags & RTPROC_FLAGS_DETACHED)
741 _Exit(0);
742 if (phProcess)
743 *phProcess = pid;
744 return rtProcPosixCreateReturn(VINF_SUCCESS, hEnvToUse, hEnv);
745 }
746 }
747 /* For a detached process this happens in the temp process, so
748 * it's not worth doing anything as this process must exit. */
749 if (fFlags & RTPROC_FLAGS_DETACHED)
750 _Exit(124);
751 }
752 else
753#endif
754 {
755#ifdef RT_OS_SOLARIS
756 int templateFd = -1;
757 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
758 {
759 templateFd = rtSolarisContractPreFork();
760 if (templateFd == -1)
761 return rtProcPosixCreateReturn(VERR_OPEN_FAILED, hEnvToUse, hEnv);
762 }
763#endif /* RT_OS_SOLARIS */
764 pid = fork();
765 if (!pid)
766 {
767#ifdef RT_OS_SOLARIS
768 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
769 rtSolarisContractPostForkChild(templateFd);
770#endif /* RT_OS_SOLARIS */
771 if (!(fFlags & RTPROC_FLAGS_DETACHED))
772 setpgid(0, 0); /* see comment above */
773
774 /*
775 * Change group and user if requested.
776 */
777#if 1 /** @todo This needs more work, see suplib/hardening. */
778 if (pszAsUser)
779 {
780 int ret = initgroups(pszAsUser, gid);
781 if (ret)
782 {
783 if (fFlags & RTPROC_FLAGS_DETACHED)
784 _Exit(126);
785 else
786 exit(126);
787 }
788 }
789 if (gid != ~(gid_t)0)
790 {
791 if (setgid(gid))
792 {
793 if (fFlags & RTPROC_FLAGS_DETACHED)
794 _Exit(126);
795 else
796 exit(126);
797 }
798 }
799
800 if (uid != ~(uid_t)0)
801 {
802 if (setuid(uid))
803 {
804 if (fFlags & RTPROC_FLAGS_DETACHED)
805 _Exit(126);
806 else
807 exit(126);
808 }
809 }
810#endif
811
812 /*
813 * Some final profile environment tweaks, if running as user.
814 */
815 if ( (fFlags & RTPROC_FLAGS_PROFILE)
816 && pszAsUser
817 && ( (fFlags & RTPROC_FLAGS_ENV_CHANGE_RECORD)
818 || hEnv == RTENV_DEFAULT) )
819 {
820 rc = rtProcPosixAdjustProfileEnvFromChild(hEnvToUse, fFlags, hEnv);
821 papszEnv = RTEnvGetExecEnvP(hEnvToUse);
822 if (RT_FAILURE(rc) || !papszEnv)
823 {
824 if (fFlags & RTPROC_FLAGS_DETACHED)
825 _Exit(126);
826 else
827 exit(126);
828 }
829 }
830
831 /*
832 * Unset the signal mask.
833 */
834 sigset_t SigMask;
835 sigemptyset(&SigMask);
836 rc = sigprocmask(SIG_SETMASK, &SigMask, NULL);
837 Assert(rc == 0);
838
839 /*
840 * Apply changes to the standard file descriptor and stuff.
841 */
842 for (int i = 0; i < 3; i++)
843 {
844 int fd = aStdFds[i];
845 if (fd == -2)
846 close(i);
847 else if (fd >= 0)
848 {
849 int rc2 = dup2(fd, i);
850 if (rc2 != i)
851 {
852 if (fFlags & RTPROC_FLAGS_DETACHED)
853 _Exit(125);
854 else
855 exit(125);
856 }
857 for (int j = i + 1; j < 3; j++)
858 if (aStdFds[j] == fd)
859 {
860 fd = -1;
861 break;
862 }
863 if (fd >= 0)
864 close(fd);
865 }
866 }
867
868 /*
869 * Finally, execute the requested program.
870 */
871 rc = execve(pszExec, (char * const *)papszArgs, (char * const *)papszEnv);
872 if (errno == ENOEXEC)
873 {
874 /* This can happen when trying to start a shell script without the magic #!/bin/sh */
875 RTAssertMsg2Weak("Cannot execute this binary format!\n");
876 }
877 else
878 RTAssertMsg2Weak("execve returns %d errno=%d\n", rc, errno);
879 RTAssertReleasePanic();
880 if (fFlags & RTPROC_FLAGS_DETACHED)
881 _Exit(127);
882 else
883 exit(127);
884 }
885#ifdef RT_OS_SOLARIS
886 if (!(fFlags & RTPROC_FLAGS_SAME_CONTRACT))
887 rtSolarisContractPostForkParent(templateFd, pid);
888#endif /* RT_OS_SOLARIS */
889 if (pid > 0)
890 {
891 /* For a detached process this happens in the temp process, so
892 * it's not worth doing anything as this process must exit. */
893 if (fFlags & RTPROC_FLAGS_DETACHED)
894 _Exit(0);
895 if (phProcess)
896 *phProcess = pid;
897 return rtProcPosixCreateReturn(VINF_SUCCESS, hEnvToUse, hEnv);
898 }
899 /* For a detached process this happens in the temp process, so
900 * it's not worth doing anything as this process must exit. */
901 if (fFlags & RTPROC_FLAGS_DETACHED)
902 _Exit(124);
903 return rtProcPosixCreateReturn(RTErrConvertFromErrno(errno), hEnvToUse, hEnv);
904 }
905
906 return rtProcPosixCreateReturn(VERR_NOT_IMPLEMENTED, hEnvToUse, hEnv);
907}
908
909
910RTR3DECL(int) RTProcDaemonizeUsingFork(bool fNoChDir, bool fNoClose, const char *pszPidfile)
911{
912 /*
913 * Fork the child process in a new session and quit the parent.
914 *
915 * - fork once and create a new session (setsid). This will detach us
916 * from the controlling tty meaning that we won't receive the SIGHUP
917 * (or any other signal) sent to that session.
918 * - The SIGHUP signal is ignored because the session/parent may throw
919 * us one before we get to the setsid.
920 * - When the parent exit(0) we will become an orphan and re-parented to
921 * the init process.
922 * - Because of the sometimes unexpected semantics of assigning the
923 * controlling tty automagically when a session leader first opens a tty,
924 * we will fork() once more to get rid of the session leadership role.
925 */
926
927 /* We start off by opening the pidfile, so that we can fail straight away
928 * if it already exists. */
929 int fdPidfile = -1;
930 if (pszPidfile != NULL)
931 {
932 /* @note the exclusive create is not guaranteed on all file
933 * systems (e.g. NFSv2) */
934 if ((fdPidfile = open(pszPidfile, O_RDWR | O_CREAT | O_EXCL, 0644)) == -1)
935 return RTErrConvertFromErrno(errno);
936 }
937
938 /* Ignore SIGHUP straight away. */
939 struct sigaction OldSigAct;
940 struct sigaction SigAct;
941 memset(&SigAct, 0, sizeof(SigAct));
942 SigAct.sa_handler = SIG_IGN;
943 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
944
945 /* First fork, to become independent process. */
946 pid_t pid = fork();
947 if (pid == -1)
948 {
949 if (fdPidfile != -1)
950 close(fdPidfile);
951 return RTErrConvertFromErrno(errno);
952 }
953 if (pid != 0)
954 {
955 /* Parent exits, no longer necessary. The child gets reparented
956 * to the init process. */
957 exit(0);
958 }
959
960 /* Create new session, fix up the standard file descriptors and the
961 * current working directory. */
962 /** @todo r=klaus the webservice uses this function and assumes that the
963 * contract id of the daemon is the same as that of the original process.
964 * Whenever this code is changed this must still remain possible. */
965 pid_t newpgid = setsid();
966 int SavedErrno = errno;
967 if (rcSigAct != -1)
968 sigaction(SIGHUP, &OldSigAct, NULL);
969 if (newpgid == -1)
970 {
971 if (fdPidfile != -1)
972 close(fdPidfile);
973 return RTErrConvertFromErrno(SavedErrno);
974 }
975
976 if (!fNoClose)
977 {
978 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
979 int fd = open("/dev/null", O_RDWR);
980 if (fd == -1) /* paranoia */
981 {
982 close(STDIN_FILENO);
983 close(STDOUT_FILENO);
984 close(STDERR_FILENO);
985 fd = open("/dev/null", O_RDWR);
986 }
987 if (fd != -1)
988 {
989 dup2(fd, STDIN_FILENO);
990 dup2(fd, STDOUT_FILENO);
991 dup2(fd, STDERR_FILENO);
992 if (fd > 2)
993 close(fd);
994 }
995 }
996
997 if (!fNoChDir)
998 {
999 int rcIgnored = chdir("/");
1000 NOREF(rcIgnored);
1001 }
1002
1003 /* Second fork to lose session leader status. */
1004 pid = fork();
1005 if (pid == -1)
1006 {
1007 if (fdPidfile != -1)
1008 close(fdPidfile);
1009 return RTErrConvertFromErrno(errno);
1010 }
1011
1012 if (pid != 0)
1013 {
1014 /* Write the pid file, this is done in the parent, before exiting. */
1015 if (fdPidfile != -1)
1016 {
1017 char szBuf[256];
1018 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n", pid);
1019 ssize_t cbIgnored = write(fdPidfile, szBuf, cbPid); NOREF(cbIgnored);
1020 close(fdPidfile);
1021 }
1022 exit(0);
1023 }
1024
1025 if (fdPidfile != -1)
1026 close(fdPidfile);
1027
1028 return VINF_SUCCESS;
1029}
1030
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette