1/*-------------------------------------------------------------------------
4 * Functions for finding and validating executable files
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
14 *-------------------------------------------------------------------------
18 * On macOS, "man realpath" avers:
19 * Defining _DARWIN_C_SOURCE or _DARWIN_BETTER_REALPATH before including
20 * stdlib.h will cause the provided implementation of realpath() to use
21 * F_GETPATH from fcntl(2) to discover the path.
22 * This should be harmless everywhere else.
24 #define _DARWIN_BETTER_REALPATH
38#if defined(HAVE_SYS_PERSONALITY_H)
39#include <sys/personality.h>
40#elif defined(HAVE_SYS_PROCCTL_H)
41#include <sys/procctl.h>
47/* Inhibit mingw CRT's auto-globbing of command line arguments */
48#if defined(WIN32) && !defined(_MSC_VER)
50int _CRT_glob = 0;
/* 0 turns off globbing; 1 turns it on */
54 * Hacky solution to allow expressing both frontend and backend error reports
55 * in one macro call. First argument of log_error is an errcode() call of
56 * some sort (ignored if FRONTEND); the rest are errmsg_internal() arguments,
57 * i.e. message string and any parameters for it.
59 * Caller must provide the gettext wrapper around the message string, if
60 * appropriate, so that it gets translated in the FRONTEND case; this
61 * motivates using errmsg_internal() not errmsg(). We handle appending a
62 * newline, if needed, inside the macro, so that there's only one translatable
63 * string per call not two.
66 #define log_error(errcodefn, ...) \
67 ereport(LOG, (errcodefn, errmsg_internal(__VA_ARGS__)))
69#define log_error(errcodefn, ...) \
70 (fprintf(stderr, __VA_ARGS__), fputc('\n', stderr))
77static BOOL GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser);
81 * validate_exec -- validate "path" as an executable file
83 * returns 0 if the file is found and no error is encountered.
84 * -1 if the regular file "path" does not exist or cannot be executed.
85 * -2 if the file is otherwise valid but cannot be read.
86 * in the failure cases, errno is set appropriately
96 char path_exe[
MAXPGPATH +
sizeof(
".exe") - 1];
98 /* Win32 requires a .exe suffix for stat() */
99 if (strlen(path) < strlen(
".exe") ||
100 pg_strcasecmp(path + strlen(path) - strlen(
".exe"),
".exe") != 0)
102 strlcpy(path_exe, path,
sizeof(path_exe) - 4);
103 strcat(path_exe,
".exe");
109 * Ensure that the file exists and is a regular file.
111 * XXX if you have a broken system where stat() looks at the symlink
112 * instead of the underlying file, you lose.
120 * POSIX offers no errno code that's simply "not a regular file". If
121 * it's a directory we can use EISDIR. Otherwise, it's most likely a
122 * device special file, and EPERM (Operation not permitted) isn't too
125 errno =
S_ISDIR(
buf.st_mode) ? EISDIR : EPERM;
130 * Ensure that the file is both executable and readable (required for
134 is_r = (
access(path, R_OK) == 0);
135 is_x = (
access(path, X_OK) == 0);
136 /* access() will set errno if it returns -1 */
140 errno = EACCES;
/* appropriate thing if we return nonzero */
142 return is_x ? (is_r ? 0 : -2) : -1;
147 * find_my_exec -- find an absolute path to this program's executable
149 * argv0 is the name passed on the command line
150 * retpath is the output area (must be of size MAXPGPATH)
151 * Returns 0 if OK, -1 if error.
153 * The reason we have to work so hard to find an absolute path is that
154 * on some platforms we can't do dynamic loading unless we know the
155 * executable's location. Also, we need an absolute path not a relative
156 * path because we may later change working directory. Finally, we want
157 * a true path not a symlink location, so that we can locate other files
158 * that are part of our installation relative to the executable.
166 * If argv0 contains a separator, then PATH wasn't used.
175 _(
"invalid binary \"%s\": %m"), retpath);
180 /* Win32 checks the current directory first for names without slashes */
186 * Since no explicit path was supplied, the user must have been relying on
187 * PATH. We'll search the same PATH.
189 if ((path = getenv(
"PATH")) && *path)
203 endp = startp + strlen(startp);
/* point to end */
212 case 0:
/* found ok */
214 case -1:
/* wasn't even a candidate, keep looking */
216 case -2:
/* found but disqualified */
218 _(
"could not read binary \"%s\": %m"),
226 _(
"could not find a \"%s\" to execute"),
argv0);
232 * normalize_exec_path - resolve symlinks and convert to absolute path
234 * Given a path that refers to an executable, chase through any symlinks
235 * to find the real file location; then convert that to an absolute path.
237 * On success, replaces the contents of "path" with the absolute path.
238 * ("path" is assumed to be of size MAXPGPATH.)
239 * Returns 0 if OK, -1 if error.
245 * We used to do a lot of work ourselves here, but now we just let
246 * realpath(3) do all the heavy lifting.
253 _(
"could not resolve path \"%s\" to absolute form: %m"),
261 /* On Windows, be sure to convert '\' to '/' */
270 * pg_realpath() - realpath(3) with POSIX.1-2008 semantics
272 * This is equivalent to realpath(fname, NULL), in that it returns a
273 * malloc'd buffer containing the absolute path equivalent to fname.
274 * On error, returns NULL with errno set.
276 * On Windows, what you get is spelled per platform conventions,
277 * so you probably want to apply canonicalize_path() to the result.
279 * For now, this is needed only here so mark it static. If you choose to
280 * move it into its own file, move the _DARWIN_BETTER_REALPATH #define too!
288 path = realpath(fname, NULL);
292 * Microsoft is resolutely non-POSIX, but _fullpath() does the same thing.
293 * The documentation claims it reports errors by setting errno, which is a
294 * bit surprising for Microsoft, but we'll believe that until it's proven
295 * wrong. Clear errno first, though, so we can at least tell if a failure
296 * occurs and doesn't set it.
299 path = _fullpath(NULL, fname, 0);
307 * Find another program in our binary's directory,
308 * then make sure it is the proper version.
312 const char *versionstr,
char *retpath)
320 /* Trim off program name and keep just directory */
324 /* Now append the other program's name */
326 "/%s%s", target,
EXE);
331 snprintf(cmd,
sizeof(cmd),
"\"%s\" -V", retpath);
336 if (strcmp(line, versionstr) != 0)
348 * Execute a command in a pipe and read the first line from it. The returned
349 * string is palloc'd (malloc'd in frontend code), the caller is responsible
361 if ((pipe_cmd = popen(cmd,
"r")) == NULL)
364 _(
"could not execute command \"%s\": %m"), cmd);
368 /* Make sure popen() didn't change errno */
374 if (ferror(pipe_cmd))
376 _(
"could not read from command \"%s\": %m"), cmd);
379 _(
"no data was returned by command \"%s\""), cmd);
389 * pclose() plus useful error reporting
397 exitstatus = pclose(stream);
400 return 0;
/* all is well */
402 if (exitstatus == -1)
404 /* pclose() itself failed, and hopefully set errno */
406 _(
"%s() failed: %m"),
"pclose");
419 * set_pglocale_pgservice
421 * Set application-specific locale and service directory
423 * This function takes the value of argv[0] rather than a full path.
425 * (You may be wondering why this is in exec.c. It requires this module's
426 * services and doesn't introduce any new dependencies, so this seems as
435 /* don't set LC_ALL in the backend */
441 * One could make a case for reproducing here PostmasterMain()'s test
442 * for whether the process is multithreaded. Unlike the postmaster,
443 * no frontend program calls sigprocmask() or otherwise provides for
444 * mutual exclusion between signal handlers. While frontends using
445 * fork(), if multithreaded, are formally exposed to undefined
446 * behavior, we have not witnessed a concrete bug. Therefore,
447 * complaining about multithreading here may be mere pedantry.
456 bindtextdomain(app, path);
458 /* set for libpq to use, but don't override existing setting */
459 setenv(
"PGLOCALEDIR", path, 0);
462 if (getenv(
"PGSYSCONFDIR") == NULL)
465 /* set for libpq to use */
466 setenv(
"PGSYSCONFDIR", path, 0);
472 * For the benefit of PostgreSQL developers testing EXEC_BACKEND on Unix
473 * systems (code paths normally exercised only on Windows), provide a way to
474 * disable address space layout randomization, if we know how on this platform.
475 * Otherwise, backends may fail to attach to shared memory at the fixed address
476 * chosen by the postmaster. (See also the macOS-specific hack in
482#if defined(HAVE_SYS_PERSONALITY_H)
483 return personality(ADDR_NO_RANDOMIZE);
484#elif defined(HAVE_SYS_PROCCTL_H) && defined(PROC_ASLR_FORCE_DISABLE)
485 int data = PROC_ASLR_FORCE_DISABLE;
487 return procctl(P_PID, 0, PROC_ASLR_CTL, &
data);
498 * AddUserToTokenDacl(HANDLE hToken)
500 * This function adds the current user account to the restricted
501 * token used when we create a restricted process.
503 * This is required because of some security changes in Windows
504 * that appeared in patches to XP/2K3 and in Vista/2008.
506 * On these machines, the Administrator account is not included in
507 * the default DACL - you just get Administrators + System. For
508 * regular users you get User + System. Because we strip Administrators
509 * when we create the restricted token, we are left with only System
510 * in the DACL which leads to access denied errors for later CreatePipe()
511 * and CreateProcess() calls when running as Administrator.
513 * This function fixes this problem by modifying the DACL of the
514 * token the process will use, and explicitly re-adding the current
515 * user account. This is still secure because the Administrator account
516 * inherits its privileges from the Administrators group - it doesn't
517 * have any of its own.
523 ACL_SIZE_INFORMATION asi;
524 ACCESS_ALLOWED_ACE *pace;
527 DWORD dwTokenInfoLength = 0;
529 PTOKEN_USER pTokenUser = NULL;
530 TOKEN_DEFAULT_DACL tddNew;
531 TOKEN_DEFAULT_DACL *ptdd = NULL;
532 TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
535 /* Figure out the buffer size for the DACL info */
536 if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
538 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
540 ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
548 if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
551 "could not get token information: error code %lu",
559 "could not get token information buffer size: error code %lu",
565 /* Get the ACL info */
566 if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) &asi,
567 (DWORD)
sizeof(ACL_SIZE_INFORMATION),
571 "could not get ACL information: error code %lu",
576 /* Get the current user SID */
577 if (!GetTokenUser(hToken, &pTokenUser))
578 goto cleanup;
/* callee printed a message */
580 /* Figure out the size of the new ACL */
581 dwNewAclSize = asi.AclBytesInUse +
sizeof(ACCESS_ALLOWED_ACE) +
582 GetLengthSid(pTokenUser->User.Sid) -
sizeof(DWORD);
584 /* Allocate the ACL buffer & initialize it */
585 pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
593 if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
596 "could not initialize ACL: error code %lu", GetLastError());
600 /* Loop through the existing ACEs, and build the new ACL */
601 for (
i = 0;
i < (int) asi.AceCount;
i++)
603 if (!GetAce(ptdd->DefaultDacl,
i, (LPVOID *) &pace))
606 "could not get ACE: error code %lu", GetLastError());
610 if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
613 "could not add ACE: error code %lu", GetLastError());
618 /* Add the new ACE for the current user */
619 if (!AddAccessAllowedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE, GENERIC_ALL, pTokenUser->User.Sid))
622 "could not add access allowed ACE: error code %lu",
627 /* Set the new DACL in the token */
628 tddNew.DefaultDacl = pacl;
630 if (!SetTokenInformation(hToken, tic, (LPVOID) &tddNew, dwNewAclSize))
633 "could not set token information: error code %lu",
642 LocalFree((HLOCAL) pTokenUser);
645 LocalFree((HLOCAL) pacl);
648 LocalFree((HLOCAL) ptdd);
654 * GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
656 * Get the users token information from a process token.
658 * The caller of this function is responsible for calling LocalFree() on the
659 * returned TOKEN_USER memory.
662GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
668 if (!GetTokenInformation(hToken,
674 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
676 *ppTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwLength);
678 if (*ppTokenUser == NULL)
688 "could not get token information buffer size: error code %lu",
694 if (!GetTokenInformation(hToken,
700 LocalFree(*ppTokenUser);
704 "could not get token information: error code %lu",
709 /* Memory in *ppTokenUser is LocalFree():d by the caller */
static void cleanup(void)
#define PG_TEXTDOMAIN(domain)
int find_my_exec(const char *argv0, char *retpath)
#define log_error(errcodefn,...)
int validate_exec(const char *path)
char * pipe_read_line(char *cmd)
int pclose_check(FILE *stream)
void set_pglocale_pgservice(const char *argv0, const char *app)
static char * pg_realpath(const char *fname)
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
static int normalize_exec_path(char *path)
int errcode_for_file_access(void)
int errcode(int sqlerrcode)
char my_exec_path[MAXPGPATH]
void pfree(void *pointer)
char * pg_get_line(FILE *stream, PromptInterruptContext *prompt_ctx)
void get_locale_path(const char *my_exec_path, char *ret_path)
void join_path_components(char *ret_path, const char *head, const char *tail)
char * last_dir_separator(const char *filename)
int pg_strcasecmp(const char *s1, const char *s2)
char * first_path_var_separator(const char *pathlist)
void canonicalize_path(char *path)
void get_etc_path(const char *my_exec_path, char *ret_path)
char * first_dir_separator(const char *filename)
size_t strlcpy(char *dst, const char *src, size_t siz)
char * wait_result_to_str(int exitstatus)
BOOL AddUserToTokenDacl(HANDLE hToken)