Suppress "variable may be used uninitialized" warning.
[pgsql.git] / src / common / exec.c
blob0bee19c1e539fea1186fe9847568caf6c96bbfba
1 /*-------------------------------------------------------------------------
3 * exec.c
4 * Functions for finding and validating executable files
7 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
11 * IDENTIFICATION
12 * src/common/exec.c
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
26 #ifndef FRONTEND
27 #include "postgres.h"
28 #else
29 #include "postgres_fe.h"
30 #endif
32 #include <signal.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <unistd.h>
37 #ifdef EXEC_BACKEND
38 #if defined(HAVE_SYS_PERSONALITY_H)
39 #include <sys/personality.h>
40 #elif defined(HAVE_SYS_PROCCTL_H)
41 #include <sys/procctl.h>
42 #endif
43 #endif
45 #include "common/string.h"
47 /* Inhibit mingw CRT's auto-globbing of command line arguments */
48 #if defined(WIN32) && !defined(_MSC_VER)
49 extern int _CRT_glob = 0; /* 0 turns off globbing; 1 turns it on */
50 #endif
53 * Hacky solution to allow expressing both frontend and backend error reports
54 * in one macro call. First argument of log_error is an errcode() call of
55 * some sort (ignored if FRONTEND); the rest are errmsg_internal() arguments,
56 * i.e. message string and any parameters for it.
58 * Caller must provide the gettext wrapper around the message string, if
59 * appropriate, so that it gets translated in the FRONTEND case; this
60 * motivates using errmsg_internal() not errmsg(). We handle appending a
61 * newline, if needed, inside the macro, so that there's only one translatable
62 * string per call not two.
64 #ifndef FRONTEND
65 #define log_error(errcodefn, ...) \
66 ereport(LOG, (errcodefn, errmsg_internal(__VA_ARGS__)))
67 #else
68 #define log_error(errcodefn, ...) \
69 (fprintf(stderr, __VA_ARGS__), fputc('\n', stderr))
70 #endif
72 static int normalize_exec_path(char *path);
73 static char *pg_realpath(const char *fname);
75 #ifdef WIN32
76 static BOOL GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser);
77 #endif
80 * validate_exec -- validate "path" as an executable file
82 * returns 0 if the file is found and no error is encountered.
83 * -1 if the regular file "path" does not exist or cannot be executed.
84 * -2 if the file is otherwise valid but cannot be read.
85 * in the failure cases, errno is set appropriately
87 int
88 validate_exec(const char *path)
90 struct stat buf;
91 int is_r;
92 int is_x;
94 #ifdef WIN32
95 char path_exe[MAXPGPATH + sizeof(".exe") - 1];
97 /* Win32 requires a .exe suffix for stat() */
98 if (strlen(path) < strlen(".exe") ||
99 pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
101 strlcpy(path_exe, path, sizeof(path_exe) - 4);
102 strcat(path_exe, ".exe");
103 path = path_exe;
105 #endif
108 * Ensure that the file exists and is a regular file.
110 * XXX if you have a broken system where stat() looks at the symlink
111 * instead of the underlying file, you lose.
113 if (stat(path, &buf) < 0)
114 return -1;
116 if (!S_ISREG(buf.st_mode))
119 * POSIX offers no errno code that's simply "not a regular file". If
120 * it's a directory we can use EISDIR. Otherwise, it's most likely a
121 * device special file, and EPERM (Operation not permitted) isn't too
122 * horribly off base.
124 errno = S_ISDIR(buf.st_mode) ? EISDIR : EPERM;
125 return -1;
129 * Ensure that the file is both executable and readable (required for
130 * dynamic loading).
132 #ifndef WIN32
133 is_r = (access(path, R_OK) == 0);
134 is_x = (access(path, X_OK) == 0);
135 /* access() will set errno if it returns -1 */
136 #else
137 is_r = buf.st_mode & S_IRUSR;
138 is_x = buf.st_mode & S_IXUSR;
139 errno = EACCES; /* appropriate thing if we return nonzero */
140 #endif
141 return is_x ? (is_r ? 0 : -2) : -1;
146 * find_my_exec -- find an absolute path to this program's executable
148 * argv0 is the name passed on the command line
149 * retpath is the output area (must be of size MAXPGPATH)
150 * Returns 0 if OK, -1 if error.
152 * The reason we have to work so hard to find an absolute path is that
153 * on some platforms we can't do dynamic loading unless we know the
154 * executable's location. Also, we need an absolute path not a relative
155 * path because we may later change working directory. Finally, we want
156 * a true path not a symlink location, so that we can locate other files
157 * that are part of our installation relative to the executable.
160 find_my_exec(const char *argv0, char *retpath)
162 char *path;
165 * If argv0 contains a separator, then PATH wasn't used.
167 strlcpy(retpath, argv0, MAXPGPATH);
168 if (first_dir_separator(retpath) != NULL)
170 if (validate_exec(retpath) == 0)
171 return normalize_exec_path(retpath);
173 log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
174 _("invalid binary \"%s\": %m"), retpath);
175 return -1;
178 #ifdef WIN32
179 /* Win32 checks the current directory first for names without slashes */
180 if (validate_exec(retpath) == 0)
181 return normalize_exec_path(retpath);
182 #endif
185 * Since no explicit path was supplied, the user must have been relying on
186 * PATH. We'll search the same PATH.
188 if ((path = getenv("PATH")) && *path)
190 char *startp = NULL,
191 *endp = NULL;
195 if (!startp)
196 startp = path;
197 else
198 startp = endp + 1;
200 endp = first_path_var_separator(startp);
201 if (!endp)
202 endp = startp + strlen(startp); /* point to end */
204 strlcpy(retpath, startp, Min(endp - startp + 1, MAXPGPATH));
206 join_path_components(retpath, retpath, argv0);
207 canonicalize_path(retpath);
209 switch (validate_exec(retpath))
211 case 0: /* found ok */
212 return normalize_exec_path(retpath);
213 case -1: /* wasn't even a candidate, keep looking */
214 break;
215 case -2: /* found but disqualified */
216 log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
217 _("could not read binary \"%s\": %m"),
218 retpath);
219 break;
221 } while (*endp);
224 log_error(errcode(ERRCODE_UNDEFINED_FILE),
225 _("could not find a \"%s\" to execute"), argv0);
226 return -1;
231 * normalize_exec_path - resolve symlinks and convert to absolute path
233 * Given a path that refers to an executable, chase through any symlinks
234 * to find the real file location; then convert that to an absolute path.
236 * On success, replaces the contents of "path" with the absolute path.
237 * ("path" is assumed to be of size MAXPGPATH.)
238 * Returns 0 if OK, -1 if error.
240 static int
241 normalize_exec_path(char *path)
244 * We used to do a lot of work ourselves here, but now we just let
245 * realpath(3) do all the heavy lifting.
247 char *abspath = pg_realpath(path);
249 if (abspath == NULL)
251 log_error(errcode_for_file_access(),
252 _("could not resolve path \"%s\" to absolute form: %m"),
253 path);
254 return -1;
256 strlcpy(path, abspath, MAXPGPATH);
257 free(abspath);
259 #ifdef WIN32
260 /* On Windows, be sure to convert '\' to '/' */
261 canonicalize_path(path);
262 #endif
264 return 0;
269 * pg_realpath() - realpath(3) with POSIX.1-2008 semantics
271 * This is equivalent to realpath(fname, NULL), in that it returns a
272 * malloc'd buffer containing the absolute path equivalent to fname.
273 * On error, returns NULL with errno set.
275 * On Windows, what you get is spelled per platform conventions,
276 * so you probably want to apply canonicalize_path() to the result.
278 * For now, this is needed only here so mark it static. If you choose to
279 * move it into its own file, move the _DARWIN_BETTER_REALPATH #define too!
281 static char *
282 pg_realpath(const char *fname)
284 char *path;
286 #ifndef WIN32
287 path = realpath(fname, NULL);
288 if (path == NULL && errno == EINVAL)
291 * Cope with old-POSIX systems that require a user-provided buffer.
292 * Assume MAXPGPATH is enough room on all such systems.
294 char *buf = malloc(MAXPGPATH);
296 if (buf == NULL)
297 return NULL; /* assume errno is set */
298 path = realpath(fname, buf);
299 if (path == NULL) /* don't leak memory */
301 int save_errno = errno;
303 free(buf);
304 errno = save_errno;
307 #else /* WIN32 */
310 * Microsoft is resolutely non-POSIX, but _fullpath() does the same thing.
311 * The documentation claims it reports errors by setting errno, which is a
312 * bit surprising for Microsoft, but we'll believe that until it's proven
313 * wrong. Clear errno first, though, so we can at least tell if a failure
314 * occurs and doesn't set it.
316 errno = 0;
317 path = _fullpath(NULL, fname, 0);
318 #endif
320 return path;
325 * Find another program in our binary's directory,
326 * then make sure it is the proper version.
329 find_other_exec(const char *argv0, const char *target,
330 const char *versionstr, char *retpath)
332 char cmd[MAXPGPATH];
333 char *line;
335 if (find_my_exec(argv0, retpath) < 0)
336 return -1;
338 /* Trim off program name and keep just directory */
339 *last_dir_separator(retpath) = '\0';
340 canonicalize_path(retpath);
342 /* Now append the other program's name */
343 snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
344 "/%s%s", target, EXE);
346 if (validate_exec(retpath) != 0)
347 return -1;
349 snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
351 if ((line = pipe_read_line(cmd)) == NULL)
352 return -1;
354 if (strcmp(line, versionstr) != 0)
356 pfree(line);
357 return -2;
360 pfree(line);
361 return 0;
366 * Execute a command in a pipe and read the first line from it. The returned
367 * string is palloc'd (malloc'd in frontend code), the caller is responsible
368 * for freeing.
370 char *
371 pipe_read_line(char *cmd)
373 FILE *pipe_cmd;
374 char *line;
376 fflush(NULL);
378 errno = 0;
379 if ((pipe_cmd = popen(cmd, "r")) == NULL)
381 log_error(errcode(ERRCODE_SYSTEM_ERROR),
382 _("could not execute command \"%s\": %m"), cmd);
383 return NULL;
386 /* Make sure popen() didn't change errno */
387 errno = 0;
388 line = pg_get_line(pipe_cmd, NULL);
390 if (line == NULL)
392 if (ferror(pipe_cmd))
393 log_error(errcode_for_file_access(),
394 _("could not read from command \"%s\": %m"), cmd);
395 else
396 log_error(errcode(ERRCODE_NO_DATA),
397 _("no data was returned by command \"%s\""), cmd);
400 (void) pclose_check(pipe_cmd);
402 return line;
407 * pclose() plus useful error reporting
410 pclose_check(FILE *stream)
412 int exitstatus;
413 char *reason;
415 exitstatus = pclose(stream);
417 if (exitstatus == 0)
418 return 0; /* all is well */
420 if (exitstatus == -1)
422 /* pclose() itself failed, and hopefully set errno */
423 log_error(errcode(ERRCODE_SYSTEM_ERROR),
424 _("%s() failed: %m"), "pclose");
426 else
428 reason = wait_result_to_str(exitstatus);
429 log_error(errcode(ERRCODE_SYSTEM_ERROR),
430 "%s", reason);
431 pfree(reason);
433 return exitstatus;
437 * set_pglocale_pgservice
439 * Set application-specific locale and service directory
441 * This function takes the value of argv[0] rather than a full path.
443 * (You may be wondering why this is in exec.c. It requires this module's
444 * services and doesn't introduce any new dependencies, so this seems as
445 * good as anyplace.)
447 void
448 set_pglocale_pgservice(const char *argv0, const char *app)
450 char path[MAXPGPATH];
451 char my_exec_path[MAXPGPATH];
453 /* don't set LC_ALL in the backend */
454 if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
456 setlocale(LC_ALL, "");
459 * One could make a case for reproducing here PostmasterMain()'s test
460 * for whether the process is multithreaded. Unlike the postmaster,
461 * no frontend program calls sigprocmask() or otherwise provides for
462 * mutual exclusion between signal handlers. While frontends using
463 * fork(), if multithreaded, are formally exposed to undefined
464 * behavior, we have not witnessed a concrete bug. Therefore,
465 * complaining about multithreading here may be mere pedantry.
469 if (find_my_exec(argv0, my_exec_path) < 0)
470 return;
472 #ifdef ENABLE_NLS
473 get_locale_path(my_exec_path, path);
474 bindtextdomain(app, path);
475 textdomain(app);
476 /* set for libpq to use, but don't override existing setting */
477 setenv("PGLOCALEDIR", path, 0);
478 #endif
480 if (getenv("PGSYSCONFDIR") == NULL)
482 get_etc_path(my_exec_path, path);
483 /* set for libpq to use */
484 setenv("PGSYSCONFDIR", path, 0);
488 #ifdef EXEC_BACKEND
490 * For the benefit of PostgreSQL developers testing EXEC_BACKEND on Unix
491 * systems (code paths normally exercised only on Windows), provide a way to
492 * disable address space layout randomization, if we know how on this platform.
493 * Otherwise, backends may fail to attach to shared memory at the fixed address
494 * chosen by the postmaster. (See also the macOS-specific hack in
495 * sysv_shmem.c.)
498 pg_disable_aslr(void)
500 #if defined(HAVE_SYS_PERSONALITY_H)
501 return personality(ADDR_NO_RANDOMIZE);
502 #elif defined(HAVE_SYS_PROCCTL_H) && defined(PROC_ASLR_FORCE_DISABLE)
503 int data = PROC_ASLR_FORCE_DISABLE;
505 return procctl(P_PID, 0, PROC_ASLR_CTL, &data);
506 #else
507 errno = ENOSYS;
508 return -1;
509 #endif
511 #endif
513 #ifdef WIN32
516 * AddUserToTokenDacl(HANDLE hToken)
518 * This function adds the current user account to the restricted
519 * token used when we create a restricted process.
521 * This is required because of some security changes in Windows
522 * that appeared in patches to XP/2K3 and in Vista/2008.
524 * On these machines, the Administrator account is not included in
525 * the default DACL - you just get Administrators + System. For
526 * regular users you get User + System. Because we strip Administrators
527 * when we create the restricted token, we are left with only System
528 * in the DACL which leads to access denied errors for later CreatePipe()
529 * and CreateProcess() calls when running as Administrator.
531 * This function fixes this problem by modifying the DACL of the
532 * token the process will use, and explicitly re-adding the current
533 * user account. This is still secure because the Administrator account
534 * inherits its privileges from the Administrators group - it doesn't
535 * have any of its own.
537 BOOL
538 AddUserToTokenDacl(HANDLE hToken)
540 int i;
541 ACL_SIZE_INFORMATION asi;
542 ACCESS_ALLOWED_ACE *pace;
543 DWORD dwNewAclSize;
544 DWORD dwSize = 0;
545 DWORD dwTokenInfoLength = 0;
546 PACL pacl = NULL;
547 PTOKEN_USER pTokenUser = NULL;
548 TOKEN_DEFAULT_DACL tddNew;
549 TOKEN_DEFAULT_DACL *ptdd = NULL;
550 TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
551 BOOL ret = FALSE;
553 /* Figure out the buffer size for the DACL info */
554 if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
556 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
558 ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
559 if (ptdd == NULL)
561 log_error(errcode(ERRCODE_OUT_OF_MEMORY),
562 _("out of memory"));
563 goto cleanup;
566 if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
568 log_error(errcode(ERRCODE_SYSTEM_ERROR),
569 "could not get token information: error code %lu",
570 GetLastError());
571 goto cleanup;
574 else
576 log_error(errcode(ERRCODE_SYSTEM_ERROR),
577 "could not get token information buffer size: error code %lu",
578 GetLastError());
579 goto cleanup;
583 /* Get the ACL info */
584 if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) &asi,
585 (DWORD) sizeof(ACL_SIZE_INFORMATION),
586 AclSizeInformation))
588 log_error(errcode(ERRCODE_SYSTEM_ERROR),
589 "could not get ACL information: error code %lu",
590 GetLastError());
591 goto cleanup;
594 /* Get the current user SID */
595 if (!GetTokenUser(hToken, &pTokenUser))
596 goto cleanup; /* callee printed a message */
598 /* Figure out the size of the new ACL */
599 dwNewAclSize = asi.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) +
600 GetLengthSid(pTokenUser->User.Sid) - sizeof(DWORD);
602 /* Allocate the ACL buffer & initialize it */
603 pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
604 if (pacl == NULL)
606 log_error(errcode(ERRCODE_OUT_OF_MEMORY),
607 _("out of memory"));
608 goto cleanup;
611 if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
613 log_error(errcode(ERRCODE_SYSTEM_ERROR),
614 "could not initialize ACL: error code %lu", GetLastError());
615 goto cleanup;
618 /* Loop through the existing ACEs, and build the new ACL */
619 for (i = 0; i < (int) asi.AceCount; i++)
621 if (!GetAce(ptdd->DefaultDacl, i, (LPVOID *) &pace))
623 log_error(errcode(ERRCODE_SYSTEM_ERROR),
624 "could not get ACE: error code %lu", GetLastError());
625 goto cleanup;
628 if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
630 log_error(errcode(ERRCODE_SYSTEM_ERROR),
631 "could not add ACE: error code %lu", GetLastError());
632 goto cleanup;
636 /* Add the new ACE for the current user */
637 if (!AddAccessAllowedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE, GENERIC_ALL, pTokenUser->User.Sid))
639 log_error(errcode(ERRCODE_SYSTEM_ERROR),
640 "could not add access allowed ACE: error code %lu",
641 GetLastError());
642 goto cleanup;
645 /* Set the new DACL in the token */
646 tddNew.DefaultDacl = pacl;
648 if (!SetTokenInformation(hToken, tic, (LPVOID) &tddNew, dwNewAclSize))
650 log_error(errcode(ERRCODE_SYSTEM_ERROR),
651 "could not set token information: error code %lu",
652 GetLastError());
653 goto cleanup;
656 ret = TRUE;
658 cleanup:
659 if (pTokenUser)
660 LocalFree((HLOCAL) pTokenUser);
662 if (pacl)
663 LocalFree((HLOCAL) pacl);
665 if (ptdd)
666 LocalFree((HLOCAL) ptdd);
668 return ret;
672 * GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
674 * Get the users token information from a process token.
676 * The caller of this function is responsible for calling LocalFree() on the
677 * returned TOKEN_USER memory.
679 static BOOL
680 GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
682 DWORD dwLength;
684 *ppTokenUser = NULL;
686 if (!GetTokenInformation(hToken,
687 TokenUser,
688 NULL,
690 &dwLength))
692 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
694 *ppTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwLength);
696 if (*ppTokenUser == NULL)
698 log_error(errcode(ERRCODE_OUT_OF_MEMORY),
699 _("out of memory"));
700 return FALSE;
703 else
705 log_error(errcode(ERRCODE_SYSTEM_ERROR),
706 "could not get token information buffer size: error code %lu",
707 GetLastError());
708 return FALSE;
712 if (!GetTokenInformation(hToken,
713 TokenUser,
714 *ppTokenUser,
715 dwLength,
716 &dwLength))
718 LocalFree(*ppTokenUser);
719 *ppTokenUser = NULL;
721 log_error(errcode(ERRCODE_SYSTEM_ERROR),
722 "could not get token information: error code %lu",
723 GetLastError());
724 return FALSE;
727 /* Memory in *ppTokenUser is LocalFree():d by the caller */
728 return TRUE;
731 #endif