1 /*-------------------------------------------------------------------------
4 * Functions for finding and validating executable files
7 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
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");
361 pclose(pgver); /* no error checking */
365 if (pclose_check(pgver))
371 SECURITY_ATTRIBUTES sattr;
372 HANDLE childstdoutrd,
375 PROCESS_INFORMATION pi;
379 sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
380 sattr.bInheritHandle = TRUE;
381 sattr.lpSecurityDescriptor = NULL;
383 if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
386 if (!DuplicateHandle(GetCurrentProcess(),
392 DUPLICATE_SAME_ACCESS))
394 CloseHandle(childstdoutrd);
395 CloseHandle(childstdoutwr);
399 CloseHandle(childstdoutrd);
401 ZeroMemory(&pi, sizeof(pi));
402 ZeroMemory(&si, sizeof(si));
404 si.dwFlags = STARTF_USESTDHANDLES;
405 si.hStdError = childstdoutwr;
406 si.hStdOutput = childstdoutwr;
407 si.hStdInput = INVALID_HANDLE_VALUE;
409 if (CreateProcess(NULL,
420 /* Successfully started the process */
423 ZeroMemory(line, maxsize);
425 /* Try to read at least one line from the pipe */
426 /* This may require more than one wait/read attempt */
427 for (lineptr = line; lineptr < line + maxsize - 1;)
431 /* Let's see if we can read */
432 if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
433 break; /* Timeout, but perhaps we got a line already */
435 if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
437 break; /* Error, but perhaps we got a line already */
439 lineptr += strlen(lineptr);
444 if (strchr(line, '\n'))
445 break; /* One or more lines read */
450 /* OK, we read some data */
453 /* If we got more than one line, cut off after the first \n */
454 lineptr = strchr(line, '\n');
456 *(lineptr + 1) = '\0';
461 * If EOL is \r\n, convert to just \n. Because stdout is a
462 * text-mode stream, the \n output by the child process is
463 * received as \r\n, so we convert it to \n. The server main.c
464 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
465 * disabling \n to \r\n expansion for stdout.
467 if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
469 line[len - 2] = '\n';
470 line[len - 1] = '\0';
475 * We emulate fgets() behaviour. So if there is no newline at the
478 if (len == 0 || line[len - 1] != '\n')
484 CloseHandle(pi.hProcess);
485 CloseHandle(pi.hThread);
488 CloseHandle(childstdoutwr);
489 CloseHandle(childstdoutrddup);
497 * pclose() plus useful error reporting
498 * Is this necessary? bjm 2004-05-11
499 * It is better here because pipe.c has win32 backend linkage.
502 pclose_check(FILE *stream)
506 exitstatus = pclose(stream);
509 return 0; /* all is well */
511 if (exitstatus == -1)
513 /* pclose() itself failed, and hopefully set errno */
514 perror("pclose failed");
516 else if (WIFEXITED(exitstatus))
517 log_error(_("child process exited with exit code %d"),
518 WEXITSTATUS(exitstatus));
519 else if (WIFSIGNALED(exitstatus))
521 log_error(_("child process was terminated by exception 0x%X"),
522 WTERMSIG(exitstatus));
523 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
527 snprintf(str, sizeof(str), "%d: %s", WTERMSIG(exitstatus),
528 WTERMSIG(exitstatus) < NSIG ?
529 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)");
530 log_error(_("child process was terminated by signal %s"), str);
533 log_error(_("child process was terminated by signal %d"),
534 WTERMSIG(exitstatus));
537 log_error(_("child process exited with unrecognized status %d"),
545 * set_pglocale_pgservice
547 * Set application-specific locale and service directory
549 * This function takes the value of argv[0] rather than a full path.
551 * (You may be wondering why this is in exec.c. It requires this module's
552 * services and doesn't introduce any new dependencies, so this seems as
556 set_pglocale_pgservice(const char *argv0, const char *app)
558 char path[MAXPGPATH];
559 char my_exec_path[MAXPGPATH];
560 char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
563 /* don't set LC_ALL in the backend */
564 if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
565 setlocale(LC_ALL, "");
567 if (find_my_exec(argv0, my_exec_path) < 0)
571 get_locale_path(my_exec_path, path);
572 bindtextdomain(app, path);
575 if (getenv("PGLOCALEDIR") == NULL)
577 /* set for libpq to use */
578 snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
579 canonicalize_path(env_path + 12);
580 putenv(strdup(env_path));
584 if (getenv("PGSYSCONFDIR") == NULL)
586 get_etc_path(my_exec_path, path);
588 /* set for libpq to use */
589 snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
590 canonicalize_path(env_path + 13);
591 putenv(strdup(env_path));
598 * AddUserToTokenDacl(HANDLE hToken)
600 * This function adds the current user account to the restricted
601 * token used when we create a restricted process.
603 * This is required because of some security changes in Windows
604 * that appeared in patches to XP/2K3 and in Vista/2008.
606 * On these machines, the Administrator account is not included in
607 * the default DACL - you just get Administrators + System. For
608 * regular users you get User + System. Because we strip Administrators
609 * when we create the restricted token, we are left with only System
610 * in the DACL which leads to access denied errors for later CreatePipe()
611 * and CreateProcess() calls when running as Administrator.
613 * This function fixes this problem by modifying the DACL of the
614 * token the process will use, and explicitly re-adding the current
615 * user account. This is still secure because the Administrator account
616 * inherits its privileges from the Administrators group - it doesn't
617 * have any of its own.
620 AddUserToTokenDacl(HANDLE hToken)
623 ACL_SIZE_INFORMATION asi;
624 ACCESS_ALLOWED_ACE *pace;
627 DWORD dwTokenInfoLength = 0;
629 PTOKEN_USER pTokenUser = NULL;
630 TOKEN_DEFAULT_DACL tddNew;
631 TOKEN_DEFAULT_DACL *ptdd = NULL;
632 TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
635 /* Figure out the buffer size for the DACL info */
636 if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
638 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
640 ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
643 log_error("could not allocate %lu bytes of memory", dwSize);
647 if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
649 log_error("could not get token information: %lu", GetLastError());
655 log_error("could not get token information buffer size: %lu", GetLastError());
660 /* Get the ACL info */
661 if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) &asi,
662 (DWORD) sizeof(ACL_SIZE_INFORMATION),
665 log_error("could not get ACL information: %lu", GetLastError());
670 * Get the user token for the current user, which provides us with the SID
671 * that is needed for creating the ACL.
673 if (!GetTokenUser(hToken, &pTokenUser))
675 log_error("could not get user token: %lu", GetLastError());
679 /* Figure out the size of the new ACL */
680 dwNewAclSize = asi.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) +
681 GetLengthSid(pTokenUser->User.Sid) -sizeof(DWORD);
683 /* Allocate the ACL buffer & initialize it */
684 pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
687 log_error("could not allocate %lu bytes of memory", dwNewAclSize);
691 if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
693 log_error("could not initialize ACL: %lu", GetLastError());
697 /* Loop through the existing ACEs, and build the new ACL */
698 for (i = 0; i < (int) asi.AceCount; i++)
700 if (!GetAce(ptdd->DefaultDacl, i, (LPVOID *) &pace))
702 log_error("could not get ACE: %lu", GetLastError());
706 if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
708 log_error("could not add ACE: %lu", GetLastError());
713 /* Add the new ACE for the current user */
714 if (!AddAccessAllowedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE, GENERIC_ALL, pTokenUser->User.Sid))
716 log_error("could not add access allowed ACE: %lu", GetLastError());
720 /* Set the new DACL in the token */
721 tddNew.DefaultDacl = pacl;
723 if (!SetTokenInformation(hToken, tic, (LPVOID) &tddNew, dwNewAclSize))
725 log_error("could not set token information: %lu", GetLastError());
733 LocalFree((HLOCAL) pTokenUser);
736 LocalFree((HLOCAL) pacl);
739 LocalFree((HLOCAL) ptdd);
745 * GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
747 * Get the users token information from a process token.
749 * The caller of this function is responsible for calling LocalFree() on the
750 * returned TOKEN_USER memory.
753 GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
759 if (!GetTokenInformation(hToken,
765 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
767 *ppTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwLength);
769 if (*ppTokenUser == NULL)
771 log_error("could not allocate %lu bytes of memory", dwLength);
777 log_error("could not get token information buffer size: %lu", GetLastError());
782 if (!GetTokenInformation(hToken,
788 LocalFree(*ppTokenUser);
791 log_error("could not get token information: %lu", GetLastError());
795 /* Memory in *ppTokenUser is LocalFree():d by the caller */