PostgreSQL Source Code  git master
exec.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * exec.c
4  * Functions for finding and validating executable files
5  *
6  *
7  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  * src/common/exec.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 
17 #ifndef FRONTEND
18 #include "postgres.h"
19 #else
20 #include "postgres_fe.h"
21 #endif
22 
23 #include <signal.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 
28 /*
29  * Hacky solution to allow expressing both frontend and backend error reports
30  * in one macro call. First argument of log_error is an errcode() call of
31  * some sort (ignored if FRONTEND); the rest are errmsg_internal() arguments,
32  * i.e. message string and any parameters for it.
33  *
34  * Caller must provide the gettext wrapper around the message string, if
35  * appropriate, so that it gets translated in the FRONTEND case; this
36  * motivates using errmsg_internal() not errmsg(). We handle appending a
37  * newline, if needed, inside the macro, so that there's only one translatable
38  * string per call not two.
39  */
40 #ifndef FRONTEND
41 #define log_error(errcodefn, ...) \
42  ereport(LOG, (errcodefn, errmsg_internal(__VA_ARGS__)))
43 #else
44 #define log_error(errcodefn, ...) \
45  (fprintf(stderr, __VA_ARGS__), fputc('\n', stderr))
46 #endif
47 
48 #ifdef _MSC_VER
49 #define getcwd(cwd,len) GetCurrentDirectory(len, cwd)
50 #endif
51 
52 static int resolve_symlinks(char *path);
53 
54 #ifdef WIN32
55 static BOOL GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser);
56 #endif
57 
58 /*
59  * validate_exec -- validate "path" as an executable file
60  *
61  * returns 0 if the file is found and no error is encountered.
62  * -1 if the regular file "path" does not exist or cannot be executed.
63  * -2 if the file is otherwise valid but cannot be read.
64  */
65 int
66 validate_exec(const char *path)
67 {
68  struct stat buf;
69  int is_r;
70  int is_x;
71 
72 #ifdef WIN32
73  char path_exe[MAXPGPATH + sizeof(".exe") - 1];
74 
75  /* Win32 requires a .exe suffix for stat() */
76  if (strlen(path) >= strlen(".exe") &&
77  pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
78  {
79  strlcpy(path_exe, path, sizeof(path_exe) - 4);
80  strcat(path_exe, ".exe");
81  path = path_exe;
82  }
83 #endif
84 
85  /*
86  * Ensure that the file exists and is a regular file.
87  *
88  * XXX if you have a broken system where stat() looks at the symlink
89  * instead of the underlying file, you lose.
90  */
91  if (stat(path, &buf) < 0)
92  return -1;
93 
94  if (!S_ISREG(buf.st_mode))
95  return -1;
96 
97  /*
98  * Ensure that the file is both executable and readable (required for
99  * dynamic loading).
100  */
101 #ifndef WIN32
102  is_r = (access(path, R_OK) == 0);
103  is_x = (access(path, X_OK) == 0);
104 #else
105  is_r = buf.st_mode & S_IRUSR;
106  is_x = buf.st_mode & S_IXUSR;
107 #endif
108  return is_x ? (is_r ? 0 : -2) : -1;
109 }
110 
111 
112 /*
113  * find_my_exec -- find an absolute path to a valid executable
114  *
115  * argv0 is the name passed on the command line
116  * retpath is the output area (must be of size MAXPGPATH)
117  * Returns 0 if OK, -1 if error.
118  *
119  * The reason we have to work so hard to find an absolute path is that
120  * on some platforms we can't do dynamic loading unless we know the
121  * executable's location. Also, we need a full path not a relative
122  * path because we will later change working directory. Finally, we want
123  * a true path not a symlink location, so that we can locate other files
124  * that are part of our installation relative to the executable.
125  */
126 int
127 find_my_exec(const char *argv0, char *retpath)
128 {
129  char cwd[MAXPGPATH],
130  test_path[MAXPGPATH];
131  char *path;
132 
133  if (!getcwd(cwd, MAXPGPATH))
134  {
136  _("could not identify current directory: %m"));
137  return -1;
138  }
139 
140  /*
141  * If argv0 contains a separator, then PATH wasn't used.
142  */
143  if (first_dir_separator(argv0) != NULL)
144  {
145  if (is_absolute_path(argv0))
146  strlcpy(retpath, argv0, MAXPGPATH);
147  else
148  join_path_components(retpath, cwd, argv0);
149  canonicalize_path(retpath);
150 
151  if (validate_exec(retpath) == 0)
152  return resolve_symlinks(retpath);
153 
154  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
155  _("invalid binary \"%s\""), retpath);
156  return -1;
157  }
158 
159 #ifdef WIN32
160  /* Win32 checks the current directory first for names without slashes */
161  join_path_components(retpath, cwd, argv0);
162  if (validate_exec(retpath) == 0)
163  return resolve_symlinks(retpath);
164 #endif
165 
166  /*
167  * Since no explicit path was supplied, the user must have been relying on
168  * PATH. We'll search the same PATH.
169  */
170  if ((path = getenv("PATH")) && *path)
171  {
172  char *startp = NULL,
173  *endp = NULL;
174 
175  do
176  {
177  if (!startp)
178  startp = path;
179  else
180  startp = endp + 1;
181 
182  endp = first_path_var_separator(startp);
183  if (!endp)
184  endp = startp + strlen(startp); /* point to end */
185 
186  strlcpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
187 
188  if (is_absolute_path(test_path))
189  join_path_components(retpath, test_path, argv0);
190  else
191  {
192  join_path_components(retpath, cwd, test_path);
193  join_path_components(retpath, retpath, argv0);
194  }
195  canonicalize_path(retpath);
196 
197  switch (validate_exec(retpath))
198  {
199  case 0: /* found ok */
200  return resolve_symlinks(retpath);
201  case -1: /* wasn't even a candidate, keep looking */
202  break;
203  case -2: /* found but disqualified */
204  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
205  _("could not read binary \"%s\""),
206  retpath);
207  break;
208  }
209  } while (*endp);
210  }
211 
212  log_error(errcode(ERRCODE_UNDEFINED_FILE),
213  _("could not find a \"%s\" to execute"), argv0);
214  return -1;
215 }
216 
217 
218 /*
219  * resolve_symlinks - resolve symlinks to the underlying file
220  *
221  * Replace "path" by the absolute path to the referenced file.
222  *
223  * Returns 0 if OK, -1 if error.
224  *
225  * Note: we are not particularly tense about producing nice error messages
226  * because we are not really expecting error here; we just determined that
227  * the symlink does point to a valid executable.
228  */
229 static int
230 resolve_symlinks(char *path)
231 {
232 #ifdef HAVE_READLINK
233  struct stat buf;
234  char orig_wd[MAXPGPATH],
235  link_buf[MAXPGPATH];
236  char *fname;
237 
238  /*
239  * To resolve a symlink properly, we have to chdir into its directory and
240  * then chdir to where the symlink points; otherwise we may fail to
241  * resolve relative links correctly (consider cases involving mount
242  * points, for example). After following the final symlink, we use
243  * getcwd() to figure out where the heck we're at.
244  *
245  * One might think we could skip all this if path doesn't point to a
246  * symlink to start with, but that's wrong. We also want to get rid of
247  * any directory symlinks that are present in the given path. We expect
248  * getcwd() to give us an accurate, symlink-free path.
249  */
250  if (!getcwd(orig_wd, MAXPGPATH))
251  {
253  _("could not identify current directory: %m"));
254  return -1;
255  }
256 
257  for (;;)
258  {
259  char *lsep;
260  int rllen;
261 
262  lsep = last_dir_separator(path);
263  if (lsep)
264  {
265  *lsep = '\0';
266  if (chdir(path) == -1)
267  {
269  _("could not change directory to \"%s\": %m"), path);
270  return -1;
271  }
272  fname = lsep + 1;
273  }
274  else
275  fname = path;
276 
277  if (lstat(fname, &buf) < 0 ||
278  !S_ISLNK(buf.st_mode))
279  break;
280 
281  errno = 0;
282  rllen = readlink(fname, link_buf, sizeof(link_buf));
283  if (rllen < 0 || rllen >= sizeof(link_buf))
284  {
286  _("could not read symbolic link \"%s\": %m"), fname);
287  return -1;
288  }
289  link_buf[rllen] = '\0';
290  strcpy(path, link_buf);
291  }
292 
293  /* must copy final component out of 'path' temporarily */
294  strlcpy(link_buf, fname, sizeof(link_buf));
295 
296  if (!getcwd(path, MAXPGPATH))
297  {
299  _("could not identify current directory: %m"));
300  return -1;
301  }
302  join_path_components(path, path, link_buf);
303  canonicalize_path(path);
304 
305  if (chdir(orig_wd) == -1)
306  {
308  _("could not change directory to \"%s\": %m"), orig_wd);
309  return -1;
310  }
311 #endif /* HAVE_READLINK */
312 
313  return 0;
314 }
315 
316 
317 /*
318  * Find another program in our binary's directory,
319  * then make sure it is the proper version.
320  */
321 int
322 find_other_exec(const char *argv0, const char *target,
323  const char *versionstr, char *retpath)
324 {
325  char cmd[MAXPGPATH];
326  char line[MAXPGPATH];
327 
328  if (find_my_exec(argv0, retpath) < 0)
329  return -1;
330 
331  /* Trim off program name and keep just directory */
332  *last_dir_separator(retpath) = '\0';
333  canonicalize_path(retpath);
334 
335  /* Now append the other program's name */
336  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
337  "/%s%s", target, EXE);
338 
339  if (validate_exec(retpath) != 0)
340  return -1;
341 
342  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
343 
344  if (!pipe_read_line(cmd, line, sizeof(line)))
345  return -1;
346 
347  if (strcmp(line, versionstr) != 0)
348  return -2;
349 
350  return 0;
351 }
352 
353 
354 /*
355  * Execute a command in a pipe and read the first line from it.
356  */
357 char *
358 pipe_read_line(char *cmd, char *line, int maxsize)
359 {
360  FILE *pgver;
361 
362  /* flush output buffers in case popen does not... */
363  fflush(stdout);
364  fflush(stderr);
365 
366  errno = 0;
367  if ((pgver = popen(cmd, "r")) == NULL)
368  {
369  perror("popen failure");
370  return NULL;
371  }
372 
373  errno = 0;
374  if (fgets(line, maxsize, pgver) == NULL)
375  {
376  if (feof(pgver))
377  fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
378  else
379  perror("fgets failure");
380  pclose(pgver); /* no error checking */
381  return NULL;
382  }
383 
384  if (pclose_check(pgver))
385  return NULL;
386 
387  return line;
388 }
389 
390 
391 /*
392  * pclose() plus useful error reporting
393  */
394 int
395 pclose_check(FILE *stream)
396 {
397  int exitstatus;
398  char *reason;
399 
400  exitstatus = pclose(stream);
401 
402  if (exitstatus == 0)
403  return 0; /* all is well */
404 
405  if (exitstatus == -1)
406  {
407  /* pclose() itself failed, and hopefully set errno */
408  log_error(errcode(ERRCODE_SYSTEM_ERROR),
409  _("%s() failed: %m"), "pclose");
410  }
411  else
412  {
413  reason = wait_result_to_str(exitstatus);
414  log_error(errcode(ERRCODE_SYSTEM_ERROR),
415  "%s", reason);
416  pfree(reason);
417  }
418  return exitstatus;
419 }
420 
421 /*
422  * set_pglocale_pgservice
423  *
424  * Set application-specific locale and service directory
425  *
426  * This function takes the value of argv[0] rather than a full path.
427  *
428  * (You may be wondering why this is in exec.c. It requires this module's
429  * services and doesn't introduce any new dependencies, so this seems as
430  * good as anyplace.)
431  */
432 void
433 set_pglocale_pgservice(const char *argv0, const char *app)
434 {
435  char path[MAXPGPATH];
436  char my_exec_path[MAXPGPATH];
437 
438  /* don't set LC_ALL in the backend */
439  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
440  {
441  setlocale(LC_ALL, "");
442 
443  /*
444  * One could make a case for reproducing here PostmasterMain()'s test
445  * for whether the process is multithreaded. Unlike the postmaster,
446  * no frontend program calls sigprocmask() or otherwise provides for
447  * mutual exclusion between signal handlers. While frontends using
448  * fork(), if multithreaded, are formally exposed to undefined
449  * behavior, we have not witnessed a concrete bug. Therefore,
450  * complaining about multithreading here may be mere pedantry.
451  */
452  }
453 
454  if (find_my_exec(argv0, my_exec_path) < 0)
455  return;
456 
457 #ifdef ENABLE_NLS
459  bindtextdomain(app, path);
460  textdomain(app);
461  /* set for libpq to use, but don't override existing setting */
462  setenv("PGLOCALEDIR", path, 0);
463 #endif
464 
465  if (getenv("PGSYSCONFDIR") == NULL)
466  {
467  get_etc_path(my_exec_path, path);
468  /* set for libpq to use */
469  setenv("PGSYSCONFDIR", path, 0);
470  }
471 }
472 
473 #ifdef WIN32
474 
475 /*
476  * AddUserToTokenDacl(HANDLE hToken)
477  *
478  * This function adds the current user account to the restricted
479  * token used when we create a restricted process.
480  *
481  * This is required because of some security changes in Windows
482  * that appeared in patches to XP/2K3 and in Vista/2008.
483  *
484  * On these machines, the Administrator account is not included in
485  * the default DACL - you just get Administrators + System. For
486  * regular users you get User + System. Because we strip Administrators
487  * when we create the restricted token, we are left with only System
488  * in the DACL which leads to access denied errors for later CreatePipe()
489  * and CreateProcess() calls when running as Administrator.
490  *
491  * This function fixes this problem by modifying the DACL of the
492  * token the process will use, and explicitly re-adding the current
493  * user account. This is still secure because the Administrator account
494  * inherits its privileges from the Administrators group - it doesn't
495  * have any of its own.
496  */
497 BOOL
498 AddUserToTokenDacl(HANDLE hToken)
499 {
500  int i;
501  ACL_SIZE_INFORMATION asi;
502  ACCESS_ALLOWED_ACE *pace;
503  DWORD dwNewAclSize;
504  DWORD dwSize = 0;
505  DWORD dwTokenInfoLength = 0;
506  PACL pacl = NULL;
507  PTOKEN_USER pTokenUser = NULL;
508  TOKEN_DEFAULT_DACL tddNew;
509  TOKEN_DEFAULT_DACL *ptdd = NULL;
510  TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
511  BOOL ret = FALSE;
512 
513  /* Figure out the buffer size for the DACL info */
514  if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
515  {
516  if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
517  {
518  ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
519  if (ptdd == NULL)
520  {
521  log_error(errcode(ERRCODE_OUT_OF_MEMORY),
522  _("out of memory"));
523  goto cleanup;
524  }
525 
526  if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
527  {
528  log_error(errcode(ERRCODE_SYSTEM_ERROR),
529  "could not get token information: error code %lu",
530  GetLastError());
531  goto cleanup;
532  }
533  }
534  else
535  {
536  log_error(errcode(ERRCODE_SYSTEM_ERROR),
537  "could not get token information buffer size: error code %lu",
538  GetLastError());
539  goto cleanup;
540  }
541  }
542 
543  /* Get the ACL info */
544  if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) &asi,
545  (DWORD) sizeof(ACL_SIZE_INFORMATION),
546  AclSizeInformation))
547  {
548  log_error(errcode(ERRCODE_SYSTEM_ERROR),
549  "could not get ACL information: error code %lu",
550  GetLastError());
551  goto cleanup;
552  }
553 
554  /* Get the current user SID */
555  if (!GetTokenUser(hToken, &pTokenUser))
556  goto cleanup; /* callee printed a message */
557 
558  /* Figure out the size of the new ACL */
559  dwNewAclSize = asi.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) +
560  GetLengthSid(pTokenUser->User.Sid) - sizeof(DWORD);
561 
562  /* Allocate the ACL buffer & initialize it */
563  pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
564  if (pacl == NULL)
565  {
566  log_error(errcode(ERRCODE_OUT_OF_MEMORY),
567  _("out of memory"));
568  goto cleanup;
569  }
570 
571  if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
572  {
573  log_error(errcode(ERRCODE_SYSTEM_ERROR),
574  "could not initialize ACL: error code %lu", GetLastError());
575  goto cleanup;
576  }
577 
578  /* Loop through the existing ACEs, and build the new ACL */
579  for (i = 0; i < (int) asi.AceCount; i++)
580  {
581  if (!GetAce(ptdd->DefaultDacl, i, (LPVOID *) &pace))
582  {
583  log_error(errcode(ERRCODE_SYSTEM_ERROR),
584  "could not get ACE: error code %lu", GetLastError());
585  goto cleanup;
586  }
587 
588  if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
589  {
590  log_error(errcode(ERRCODE_SYSTEM_ERROR),
591  "could not add ACE: error code %lu", GetLastError());
592  goto cleanup;
593  }
594  }
595 
596  /* Add the new ACE for the current user */
597  if (!AddAccessAllowedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE, GENERIC_ALL, pTokenUser->User.Sid))
598  {
599  log_error(errcode(ERRCODE_SYSTEM_ERROR),
600  "could not add access allowed ACE: error code %lu",
601  GetLastError());
602  goto cleanup;
603  }
604 
605  /* Set the new DACL in the token */
606  tddNew.DefaultDacl = pacl;
607 
608  if (!SetTokenInformation(hToken, tic, (LPVOID) &tddNew, dwNewAclSize))
609  {
610  log_error(errcode(ERRCODE_SYSTEM_ERROR),
611  "could not set token information: error code %lu",
612  GetLastError());
613  goto cleanup;
614  }
615 
616  ret = TRUE;
617 
618 cleanup:
619  if (pTokenUser)
620  LocalFree((HLOCAL) pTokenUser);
621 
622  if (pacl)
623  LocalFree((HLOCAL) pacl);
624 
625  if (ptdd)
626  LocalFree((HLOCAL) ptdd);
627 
628  return ret;
629 }
630 
631 /*
632  * GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
633  *
634  * Get the users token information from a process token.
635  *
636  * The caller of this function is responsible for calling LocalFree() on the
637  * returned TOKEN_USER memory.
638  */
639 static BOOL
640 GetTokenUser(HANDLE hToken, PTOKEN_USER *ppTokenUser)
641 {
642  DWORD dwLength;
643 
644  *ppTokenUser = NULL;
645 
646  if (!GetTokenInformation(hToken,
647  TokenUser,
648  NULL,
649  0,
650  &dwLength))
651  {
652  if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
653  {
654  *ppTokenUser = (PTOKEN_USER) LocalAlloc(LPTR, dwLength);
655 
656  if (*ppTokenUser == NULL)
657  {
658  log_error(errcode(ERRCODE_OUT_OF_MEMORY),
659  _("out of memory"));
660  return FALSE;
661  }
662  }
663  else
664  {
665  log_error(errcode(ERRCODE_SYSTEM_ERROR),
666  "could not get token information buffer size: error code %lu",
667  GetLastError());
668  return FALSE;
669  }
670  }
671 
672  if (!GetTokenInformation(hToken,
673  TokenUser,
674  *ppTokenUser,
675  dwLength,
676  &dwLength))
677  {
678  LocalFree(*ppTokenUser);
679  *ppTokenUser = NULL;
680 
681  log_error(errcode(ERRCODE_SYSTEM_ERROR),
682  "could not get token information: error code %lu",
683  GetLastError());
684  return FALSE;
685  }
686 
687  /* Memory in *ppTokenUser is LocalFree():d by the caller */
688  return TRUE;
689 }
690 
691 #endif
static void cleanup(void)
Definition: bootstrap.c:697
#define Min(x, y)
Definition: c.h:986
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
#define log_error(errcodefn,...)
Definition: exec.c:41
int validate_exec(const char *path)
Definition: exec.c:66
char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:358
int pclose_check(FILE *stream)
Definition: exec.c:395
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:433
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:322
static int resolve_symlinks(char *path)
Definition: exec.c:230
int errcode_for_file_access(void)
Definition: elog.c:721
int errcode(int sqlerrcode)
Definition: elog.c:698
#define _(x)
Definition: elog.c:89
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
int i
Definition: isn.c:73
static void const char fflush(stdout)
void pfree(void *pointer)
Definition: mcxt.c:1169
#define MAXPGPATH
static char * argv0
Definition: pg_ctl.c:97
static char * buf
Definition: pg_test_fsync.c:69
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define is_absolute_path(filename)
Definition: port.h:91
char * first_dir_separator(const char *filename)
Definition: path.c:103
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void canonicalize_path(char *path)
Definition: path.c:254
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:713
char * first_path_var_separator(const char *pathlist)
Definition: path.c:120
#define snprintf
Definition: port.h:222
#define fprintf
Definition: port.h:226
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define EXE
Definition: port.h:147
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
#define stat
Definition: win32_port.h:283
#define lstat(path, sb)
Definition: win32_port.h:284
BOOL AddUserToTokenDacl(HANDLE hToken)
#define S_IRUSR
Definition: win32_port.h:288
#define setenv(x, y, z)
Definition: win32_port.h:507
#define readlink(path, buf, size)
Definition: win32_port.h:236
#define S_ISREG(m)
Definition: win32_port.h:327
#define setlocale(a, b)
Definition: win32_port.h:446
#define S_IXUSR
Definition: win32_port.h:294