1 /*-------------------------------------------------------------------------
4 * Functions for finding and validating executable files
7 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/port/exec.c,v 1.68 2010/02/26 02:01:38 momjian Exp $
14 *-------------------------------------------------------------------------
20 #include "postgres_fe.h"
29 /* We use only 3-parameter elog calls in this file, for simplicity */
30 /* NOTE: caller must provide gettext call around str! */
31 #define log_error(str, param) elog(LOG, str, param)
33 #define log_error(str, param) (fprintf(stderr, str, param), fputc('\n', stderr))
36 #ifdef WIN32_ONLY_COMPILER
37 #define getcwd(cwd,len) GetCurrentDirectory(len, cwd)
40 static int validate_exec(const char *path);
41 static int resolve_symlinks(char *path);
42 static char *pipe_read_line(char *cmd, char *line, int maxsize);
45 static BOOL GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser);
49 * validate_exec -- validate "path" as an executable file
51 * returns 0 if the file is found and no error is encountered.
52 * -1 if the regular file "path" does not exist or cannot be executed.
53 * -2 if the file is otherwise valid but cannot be read.
56 validate_exec(const char *path)
63 char path_exe[MAXPGPATH + sizeof(".exe") - 1];
65 /* Win32 requires a .exe suffix for stat() */
66 if (strlen(path) >= strlen(".exe") &&
67 pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
69 strcpy(path_exe, path);
70 strcat(path_exe, ".exe");
76 * Ensure that the file exists and is a regular file.
78 * XXX if you have a broken system where stat() looks at the symlink
79 * instead of the underlying file, you lose.
81 if (stat(path, &buf) < 0)
84 if (!S_ISREG(buf.st_mode))
88 * Ensure that the file is both executable and readable (required for
92 is_r = (access(path, R_OK) == 0);
93 is_x = (access(path, X_OK) == 0);
95 is_r = buf.st_mode & S_IRUSR;
96 is_x = buf.st_mode & S_IXUSR;
98 return is_x ? (is_r ? 0 : -2) : -1;
103 * find_my_exec -- find an absolute path to a valid executable
105 * argv0 is the name passed on the command line
106 * retpath is the output area (must be of size MAXPGPATH)
107 * Returns 0 if OK, -1 if error.
109 * The reason we have to work so hard to find an absolute path is that
110 * on some platforms we can't do dynamic loading unless we know the
111 * executable's location. Also, we need a full path not a relative
112 * path because we will later change working directory. Finally, we want
113 * a true path not a symlink location, so that we can locate other files
114 * that are part of our installation relative to the executable.
117 find_my_exec(const char *argv0, char *retpath)
120 test_path[MAXPGPATH];
123 if (!getcwd(cwd, MAXPGPATH))
125 log_error(_("could not identify current directory: %s"),
131 * If argv0 contains a separator, then PATH wasn't used.
133 if (first_dir_separator(argv0) != NULL)
135 if (is_absolute_path(argv0))
136 StrNCpy(retpath, argv0, MAXPGPATH);
138 join_path_components(retpath, cwd, argv0);
139 canonicalize_path(retpath);
141 if (validate_exec(retpath) == 0)
142 return resolve_symlinks(retpath);
144 log_error(_("invalid binary \"%s\""), retpath);
149 /* Win32 checks the current directory first for names without slashes */
150 join_path_components(retpath, cwd, argv0);
151 if (validate_exec(retpath) == 0)
152 return resolve_symlinks(retpath);
156 * Since no explicit path was supplied, the user must have been relying on
157 * PATH. We'll search the same PATH.
159 if ((path = getenv("PATH")) && *path)
171 endp = first_path_separator(startp);
173 endp = startp + strlen(startp); /* point to end */
175 StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
177 if (is_absolute_path(test_path))
178 join_path_components(retpath, test_path, argv0);
181 join_path_components(retpath, cwd, test_path);
182 join_path_components(retpath, retpath, argv0);
184 canonicalize_path(retpath);
186 switch (validate_exec(retpath))
188 case 0: /* found ok */
189 return resolve_symlinks(retpath);
190 case -1: /* wasn't even a candidate, keep looking */
192 case -2: /* found but disqualified */
193 log_error(_("could not read binary \"%s\""),
200 log_error(_("could not find a \"%s\" to execute"), argv0);
206 * resolve_symlinks - resolve symlinks to the underlying file
208 * Replace "path" by the absolute path to the referenced file.
210 * Returns 0 if OK, -1 if error.
212 * Note: we are not particularly tense about producing nice error messages
213 * because we are not really expecting error here; we just determined that
214 * the symlink does point to a valid executable.
217 resolve_symlinks(char *path)
221 char orig_wd[MAXPGPATH],
226 * To resolve a symlink properly, we have to chdir into its directory and
227 * then chdir to where the symlink points; otherwise we may fail to
228 * resolve relative links correctly (consider cases involving mount
229 * points, for example). After following the final symlink, we use
230 * getcwd() to figure out where the heck we're at.
232 * One might think we could skip all this if path doesn't point to a
233 * symlink to start with, but that's wrong. We also want to get rid of
234 * any directory symlinks that are present in the given path. We expect
235 * getcwd() to give us an accurate, symlink-free path.
237 if (!getcwd(orig_wd, MAXPGPATH))
239 log_error(_("could not identify current directory: %s"),
249 lsep = last_dir_separator(path);
253 if (chdir(path) == -1)
255 log_error(_("could not change directory to \"%s\""), path);
263 if (lstat(fname, &buf) < 0 ||
264 !S_ISLNK(buf.st_mode))
267 rllen = readlink(fname, link_buf, sizeof(link_buf));
268 if (rllen < 0 || rllen >= sizeof(link_buf))
270 log_error(_("could not read symbolic link \"%s\""), fname);
273 link_buf[rllen] = '\0';
274 strcpy(path, link_buf);
277 /* must copy final component out of 'path' temporarily */
278 strcpy(link_buf, fname);
280 if (!getcwd(path, MAXPGPATH))
282 log_error(_("could not identify current directory: %s"),
286 join_path_components(path, path, link_buf);
287 canonicalize_path(path);
289 if (chdir(orig_wd) == -1)
291 log_error(_("could not change directory to \"%s\""), orig_wd);
294 #endif /* HAVE_READLINK */
301 * Find another program in our binary's directory,
302 * then make sure it is the proper version.
305 find_other_exec(const char *argv0, const char *target,
306 const char *versionstr, char *retpath)
311 if (find_my_exec(argv0, retpath) < 0)
314 /* Trim off program name and keep just directory */
315 *last_dir_separator(retpath) = '\0';
316 canonicalize_path(retpath);
318 /* Now append the other program's name */
319 snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
320 "/%s%s", target, EXE);
322 if (validate_exec(retpath) != 0)
325 snprintf(cmd, sizeof(cmd), "\"%s\" -V 2>%s", retpath, DEVNULL);
327 if (!pipe_read_line(cmd, line, sizeof(line)))
330 if (strcmp(line, versionstr) != 0)
338 * The runtime library's popen() on win32 does not work when being
339 * called from a service when running on windows <= 2000, because
340 * there is no stdin/stdout/stderr.
342 * Executing a command in a pipe and reading the first line from it
346 pipe_read_line(char *cmd, char *line, int maxsize)
351 /* flush output buffers in case popen does not... */
355 if ((pgver = popen(cmd, "r")) == NULL)
358 if (fgets(line, maxsize, pgver) == NULL)
360 perror("fgets failure");
364 if (pclose_check(pgver))
370 SECURITY_ATTRIBUTES sattr;
371 HANDLE childstdoutrd,
374 PROCESS_INFORMATION pi;
378 sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
379 sattr.bInheritHandle = TRUE;
380 sattr.lpSecurityDescriptor = NULL;
382 if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
385 if (!DuplicateHandle(GetCurrentProcess(),
391 DUPLICATE_SAME_ACCESS))
393 CloseHandle(childstdoutrd);
394 CloseHandle(childstdoutwr);
398 CloseHandle(childstdoutrd);
400 ZeroMemory(&pi, sizeof(pi));
401 ZeroMemory(&si, sizeof(si));
403 si.dwFlags = STARTF_USESTDHANDLES;
404 si.hStdError = childstdoutwr;
405 si.hStdOutput = childstdoutwr;
406 si.hStdInput = INVALID_HANDLE_VALUE;
408 if (CreateProcess(NULL,
419 /* Successfully started the process */
422 ZeroMemory(line, maxsize);
424 /* Try to read at least one line from the pipe */
425 /* This may require more than one wait/read attempt */
426 for (lineptr = line; lineptr < line + maxsize - 1;)
430 /* Let's see if we can read */
431 if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
432 break; /* Timeout, but perhaps we got a line already */
434 if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
436 break; /* Error, but perhaps we got a line already */
438 lineptr += strlen(lineptr);
443 if (strchr(line, '\n'))
444 break; /* One or more lines read */
449 /* OK, we read some data */
452 /* If we got more than one line, cut off after the first \n */
453 lineptr = strchr(line, '\n');
455 *(lineptr + 1) = '\0';
460 * If EOL is \r\n, convert to just \n. Because stdout is a
461 * text-mode stream, the \n output by the child process is
462 * received as \r\n, so we convert it to \n. The server main.c
463 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
464 * disabling \n to \r\n expansion for stdout.
466 if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
468 line[len - 2] = '\n';
469 line[len - 1] = '\0';
474 * We emulate fgets() behaviour. So if there is no newline at the
477 if (len == 0 || line[len - 1] != '\n')
483 CloseHandle(pi.hProcess);
484 CloseHandle(pi.hThread);
487 CloseHandle(childstdoutwr);
488 CloseHandle(childstdoutrddup);
496 * pclose() plus useful error reporting
497 * Is this necessary? bjm 2004-05-11
498 * It is better here because pipe.c has win32 backend linkage.
501 pclose_check(FILE *stream)
505 exitstatus = pclose(stream);
508 return 0; /* all is well */
510 if (exitstatus == -1)
512 /* pclose() itself failed, and hopefully set errno */
513 perror("pclose failed");
515 else if (WIFEXITED(exitstatus))
516 log_error(_("child process exited with exit code %d"),
517 WEXITSTATUS(exitstatus));
518 else if (WIFSIGNALED(exitstatus))
520 log_error(_("child process was terminated by exception 0x%X"),
521 WTERMSIG(exitstatus));
522 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
526 snprintf(str, sizeof(str), "%d: %s", WTERMSIG(exitstatus),
527 WTERMSIG(exitstatus) < NSIG ?
528 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)");
529 log_error(_("child process was terminated by signal %s"), str);
532 log_error(_("child process was terminated by signal %d"),
533 WTERMSIG(exitstatus));
536 log_error(_("child process exited with unrecognized status %d"),
544 * set_pglocale_pgservice
546 * Set application-specific locale and service directory
548 * This function takes the value of argv[0] rather than a full path.
550 * (You may be wondering why this is in exec.c. It requires this module's
551 * services and doesn't introduce any new dependencies, so this seems as
555 set_pglocale_pgservice(const char *argv0, const char *app)
557 char path[MAXPGPATH];
558 char my_exec_path[MAXPGPATH];
559 char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
562 /* don't set LC_ALL in the backend */
563 if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
564 setlocale(LC_ALL, "");
566 if (find_my_exec(argv0, my_exec_path) < 0)
570 get_locale_path(my_exec_path, path);
571 bindtextdomain(app, path);
574 if (getenv("PGLOCALEDIR") == NULL)
576 /* set for libpq to use */
577 snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
578 canonicalize_path(env_path + 12);
579 putenv(strdup(env_path));
583 if (getenv("PGSYSCONFDIR") == NULL)
585 get_etc_path(my_exec_path, path);
587 /* set for libpq to use */
588 snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
589 canonicalize_path(env_path + 13);
590 putenv(strdup(env_path));
597 * AddUserToTokenDacl(HANDLE hToken)
599 * This function adds the current user account to the restricted
600 * token used when we create a restricted process.
602 * This is required because of some security changes in Windows
603 * that appeared in patches to XP/2K3 and in Vista/2008.
605 * On these machines, the Administrator account is not included in
606 * the default DACL - you just get Administrators + System. For
607 * regular users you get User + System. Because we strip Administrators
608 * when we create the restricted token, we are left with only System
609 * in the DACL which leads to access denied errors for later CreatePipe()
610 * and CreateProcess() calls when running as Administrator.
612 * This function fixes this problem by modifying the DACL of the
613 * token the process will use, and explicitly re-adding the current
614 * user account. This is still secure because the Administrator account
615 * inherits its privileges from the Administrators group - it doesn't
616 * have any of its own.
619 AddUserToTokenDacl(HANDLE hToken)
622 ACL_SIZE_INFORMATION asi;
623 ACCESS_ALLOWED_ACE *pace;
626 DWORD dwTokenInfoLength = 0;
628 PTOKEN_USER pTokenUser = NULL;
629 TOKEN_DEFAULT_DACL tddNew;
630 TOKEN_DEFAULT_DACL *ptdd = NULL;
631 TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
634 /* Figure out the buffer size for the DACL info */
635 if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
637 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
639 ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
642 log_error("could not allocate %lu bytes of memory", dwSize);
646 if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
648 log_error("could not get token information: %lu", GetLastError());
654 log_error("could not get token information buffer size: %lu", GetLastError());
659 /* Get the ACL info */
660 if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) &asi,
661 (DWORD) sizeof(ACL_SIZE_INFORMATION),
664 log_error("could not get ACL information: %lu", GetLastError());
669 * Get the user token for the current user, which provides us with the SID
670 * that is needed for creating the ACL.
672 if (!GetTokenUser(hToken, &pTokenUser))
674 log_error("could not get user token: %lu", GetLastError());
678 /* Figure out the size of the new ACL */
679 dwNewAclSize = asi.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) +
680 GetLengthSid(pTokenUser->User.Sid) -sizeof(DWORD);
682 /* Allocate the ACL buffer & initialize it */
683 pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
686 log_error("could not allocate %lu bytes of memory", dwNewAclSize);
690 if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
692 log_error("could not initialize ACL: %lu", GetLastError());
696 /* Loop through the existing ACEs, and build the new ACL */
697 for (i = 0; i < (int) asi.AceCount; i++)
699 if (!GetAce(ptdd->DefaultDacl, i, (LPVOID *) &pace))
701 log_error("could not get ACE: %lu", GetLastError());
705 if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
707 log_error("could not add ACE: %lu", GetLastError());
712 /* Add the new ACE for the current user */
713 if (!AddAccessAllowedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE, GENERIC_ALL, pTokenUser->User.Sid))
715 log_error("could not add access allowed ACE: %lu", GetLastError());
719 /* Set the new DACL in the token */
720 tddNew.DefaultDacl = pacl;
722 if (!SetTokenInformation(hToken, tic, (LPVOID) &tddNew, dwNewAclSize))
724 log_error("could not set token information: %lu", GetLastError());
732 LocalFree((HLOCAL) pTokenUser);
735 LocalFree((HLOCAL) pacl);
738 LocalFree((HLOCAL) ptdd);
744 * GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
746 * Get the users token information from a process token.
748 * The caller of this function is responsible for calling LocalFree() on the
749 * returned TOKEN_USER memory.
752 GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
758 if (!GetTokenInformation(hToken,
764 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
766 *ppTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwLength);
768 if (*ppTokenUser == NULL)
770 log_error("could not allocate %lu bytes of memory", dwLength);
776 log_error("could not get token information buffer size: %lu", GetLastError());
781 if (!GetTokenInformation(hToken,
787 LocalFree(*ppTokenUser);
790 log_error("could not get token information: %lu", GetLastError());
794 /* Memory in *ppTokenUser is LocalFree():d by the caller */