PostgreSQL Source Code  git master
exec.c File Reference
#include "postgres.h"
#include <signal.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
Include dependency graph for exec.c:

Go to the source code of this file.

Macros

#define log_error(errcodefn, ...)   ereport(LOG, (errcodefn, errmsg_internal(__VA_ARGS__)))
 

Functions

static int validate_exec (const char *path)
 
static int resolve_symlinks (char *path)
 
static char * pipe_read_line (char *cmd, char *line, int maxsize)
 
int find_my_exec (const char *argv0, char *retpath)
 
int find_other_exec (const char *argv0, const char *target, const char *versionstr, char *retpath)
 
int pclose_check (FILE *stream)
 
void set_pglocale_pgservice (const char *argv0, const char *app)
 

Macro Definition Documentation

◆ log_error

#define log_error (   errcodefn,
  ... 
)    ereport(LOG, (errcodefn, errmsg_internal(__VA_ARGS__)))

Function Documentation

◆ find_my_exec()

int find_my_exec ( const char *  argv0,
char *  retpath 
)

Definition at line 129 of file exec.c.

References _, canonicalize_path(), errcode(), errcode_for_file_access(), first_dir_separator(), first_path_var_separator(), is_absolute_path, join_path_components(), log_error, MAXPGPATH, Min, resolve_symlinks(), StrNCpy, and validate_exec().

Referenced by do_kill(), find_other_exec(), find_other_exec_or_die(), getInstallationPaths(), InitStandaloneProcess(), main(), process_psqlrc(), set_pglocale_pgservice(), setup(), and setup_bin_paths().

130 {
131  char cwd[MAXPGPATH],
132  test_path[MAXPGPATH];
133  char *path;
134 
135  if (!getcwd(cwd, MAXPGPATH))
136  {
138  _("could not identify current directory: %m"));
139  return -1;
140  }
141 
142  /*
143  * If argv0 contains a separator, then PATH wasn't used.
144  */
145  if (first_dir_separator(argv0) != NULL)
146  {
147  if (is_absolute_path(argv0))
148  StrNCpy(retpath, argv0, MAXPGPATH);
149  else
150  join_path_components(retpath, cwd, argv0);
151  canonicalize_path(retpath);
152 
153  if (validate_exec(retpath) == 0)
154  return resolve_symlinks(retpath);
155 
156  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
157  _("invalid binary \"%s\""), retpath);
158  return -1;
159  }
160 
161 #ifdef WIN32
162  /* Win32 checks the current directory first for names without slashes */
163  join_path_components(retpath, cwd, argv0);
164  if (validate_exec(retpath) == 0)
165  return resolve_symlinks(retpath);
166 #endif
167 
168  /*
169  * Since no explicit path was supplied, the user must have been relying on
170  * PATH. We'll search the same PATH.
171  */
172  if ((path = getenv("PATH")) && *path)
173  {
174  char *startp = NULL,
175  *endp = NULL;
176 
177  do
178  {
179  if (!startp)
180  startp = path;
181  else
182  startp = endp + 1;
183 
184  endp = first_path_var_separator(startp);
185  if (!endp)
186  endp = startp + strlen(startp); /* point to end */
187 
188  StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
189 
190  if (is_absolute_path(test_path))
191  join_path_components(retpath, test_path, argv0);
192  else
193  {
194  join_path_components(retpath, cwd, test_path);
195  join_path_components(retpath, retpath, argv0);
196  }
197  canonicalize_path(retpath);
198 
199  switch (validate_exec(retpath))
200  {
201  case 0: /* found ok */
202  return resolve_symlinks(retpath);
203  case -1: /* wasn't even a candidate, keep looking */
204  break;
205  case -2: /* found but disqualified */
206  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
207  _("could not read binary \"%s\""),
208  retpath);
209  break;
210  }
211  } while (*endp);
212  }
213 
214  log_error(errcode(ERRCODE_UNDEFINED_FILE),
215  _("could not find a \"%s\" to execute"), argv0);
216  return -1;
217 }
static char * argv0
Definition: pg_ctl.c:97
static int resolve_symlinks(char *path)
Definition: exec.c:232
#define Min(x, y)
Definition: c.h:904
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:570
#define log_error(errcodefn,...)
Definition: exec.c:41
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:68
int errcode_for_file_access(void)
Definition: elog.c:593
#define is_absolute_path(filename)
Definition: port.h:86
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define StrNCpy(dst, src, len)
Definition: c.h:928
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
#define _(x)
Definition: elog.c:84
char * first_path_var_separator(const char *pathlist)
Definition: path.c:120

◆ find_other_exec()

int find_other_exec ( const char *  argv0,
const char *  target,
const char *  versionstr,
char *  retpath 
)

Definition at line 324 of file exec.c.

References canonicalize_path(), EXE, find_my_exec(), last_dir_separator(), MAXPGPATH, pipe_read_line(), snprintf, and validate_exec().

Referenced by do_kill(), find_other_exec_or_die(), getInstallationPaths(), isolation_start_test(), main(), and setup_bin_paths().

326 {
327  char cmd[MAXPGPATH];
328  char line[MAXPGPATH];
329 
330  if (find_my_exec(argv0, retpath) < 0)
331  return -1;
332 
333  /* Trim off program name and keep just directory */
334  *last_dir_separator(retpath) = '\0';
335  canonicalize_path(retpath);
336 
337  /* Now append the other program's name */
338  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
339  "/%s%s", target, EXE);
340 
341  if (validate_exec(retpath) != 0)
342  return -1;
343 
344  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
345 
346  if (!pipe_read_line(cmd, line, sizeof(line)))
347  return -1;
348 
349  if (strcmp(line, versionstr) != 0)
350  return -2;
351 
352  return 0;
353 }
static char * argv0
Definition: pg_ctl.c:97
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:68
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define EXE
Definition: port.h:117
#define snprintf
Definition: port.h:192
static char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:365

◆ pclose_check()

int pclose_check ( FILE *  stream)

Definition at line 527 of file exec.c.

References _, errcode(), log_error, pfree(), and wait_result_to_str().

Referenced by pipe_read_line().

528 {
529  int exitstatus;
530  char *reason;
531 
532  exitstatus = pclose(stream);
533 
534  if (exitstatus == 0)
535  return 0; /* all is well */
536 
537  if (exitstatus == -1)
538  {
539  /* pclose() itself failed, and hopefully set errno */
540  log_error(errcode(ERRCODE_SYSTEM_ERROR),
541  _("pclose failed: %m"));
542  }
543  else
544  {
545  reason = wait_result_to_str(exitstatus);
546  log_error(errcode(ERRCODE_SYSTEM_ERROR),
547  "%s", reason);
548  pfree(reason);
549  }
550  return exitstatus;
551 }
int errcode(int sqlerrcode)
Definition: elog.c:570
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
void pfree(void *pointer)
Definition: mcxt.c:1031
#define log_error(errcodefn,...)
Definition: exec.c:41
#define _(x)
Definition: elog.c:84

◆ pipe_read_line()

static char * pipe_read_line ( char *  cmd,
char *  line,
int  maxsize 
)
static

Definition at line 365 of file exec.c.

References FALSE, fprintf, pclose_check(), generate_unaccent_rules::stdout, and TRUE.

Referenced by find_other_exec().

366 {
367 #ifndef WIN32
368  FILE *pgver;
369 
370  /* flush output buffers in case popen does not... */
371  fflush(stdout);
372  fflush(stderr);
373 
374  errno = 0;
375  if ((pgver = popen(cmd, "r")) == NULL)
376  {
377  perror("popen failure");
378  return NULL;
379  }
380 
381  errno = 0;
382  if (fgets(line, maxsize, pgver) == NULL)
383  {
384  if (feof(pgver))
385  fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
386  else
387  perror("fgets failure");
388  pclose(pgver); /* no error checking */
389  return NULL;
390  }
391 
392  if (pclose_check(pgver))
393  return NULL;
394 
395  return line;
396 #else /* WIN32 */
397 
398  SECURITY_ATTRIBUTES sattr;
399  HANDLE childstdoutrd,
400  childstdoutwr,
401  childstdoutrddup;
402  PROCESS_INFORMATION pi;
403  STARTUPINFO si;
404  char *retval = NULL;
405 
406  sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
407  sattr.bInheritHandle = TRUE;
408  sattr.lpSecurityDescriptor = NULL;
409 
410  if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
411  return NULL;
412 
413  if (!DuplicateHandle(GetCurrentProcess(),
414  childstdoutrd,
415  GetCurrentProcess(),
416  &childstdoutrddup,
417  0,
418  FALSE,
419  DUPLICATE_SAME_ACCESS))
420  {
421  CloseHandle(childstdoutrd);
422  CloseHandle(childstdoutwr);
423  return NULL;
424  }
425 
426  CloseHandle(childstdoutrd);
427 
428  ZeroMemory(&pi, sizeof(pi));
429  ZeroMemory(&si, sizeof(si));
430  si.cb = sizeof(si);
431  si.dwFlags = STARTF_USESTDHANDLES;
432  si.hStdError = childstdoutwr;
433  si.hStdOutput = childstdoutwr;
434  si.hStdInput = INVALID_HANDLE_VALUE;
435 
436  if (CreateProcess(NULL,
437  cmd,
438  NULL,
439  NULL,
440  TRUE,
441  0,
442  NULL,
443  NULL,
444  &si,
445  &pi))
446  {
447  /* Successfully started the process */
448  char *lineptr;
449 
450  ZeroMemory(line, maxsize);
451 
452  /* Try to read at least one line from the pipe */
453  /* This may require more than one wait/read attempt */
454  for (lineptr = line; lineptr < line + maxsize - 1;)
455  {
456  DWORD bytesread = 0;
457 
458  /* Let's see if we can read */
459  if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
460  break; /* Timeout, but perhaps we got a line already */
461 
462  if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
463  &bytesread, NULL))
464  break; /* Error, but perhaps we got a line already */
465 
466  lineptr += strlen(lineptr);
467 
468  if (!bytesread)
469  break; /* EOF */
470 
471  if (strchr(line, '\n'))
472  break; /* One or more lines read */
473  }
474 
475  if (lineptr != line)
476  {
477  /* OK, we read some data */
478  int len;
479 
480  /* If we got more than one line, cut off after the first \n */
481  lineptr = strchr(line, '\n');
482  if (lineptr)
483  *(lineptr + 1) = '\0';
484 
485  len = strlen(line);
486 
487  /*
488  * If EOL is \r\n, convert to just \n. Because stdout is a
489  * text-mode stream, the \n output by the child process is
490  * received as \r\n, so we convert it to \n. The server main.c
491  * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
492  * disabling \n to \r\n expansion for stdout.
493  */
494  if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
495  {
496  line[len - 2] = '\n';
497  line[len - 1] = '\0';
498  len--;
499  }
500 
501  /*
502  * We emulate fgets() behaviour. So if there is no newline at the
503  * end, we add one...
504  */
505  if (len == 0 || line[len - 1] != '\n')
506  strcat(line, "\n");
507 
508  retval = line;
509  }
510 
511  CloseHandle(pi.hProcess);
512  CloseHandle(pi.hThread);
513  }
514 
515  CloseHandle(childstdoutwr);
516  CloseHandle(childstdoutrddup);
517 
518  return retval;
519 #endif /* WIN32 */
520 }
#define TRUE
Definition: ecpglib.h:35
#define FALSE
Definition: ecpglib.h:39
#define fprintf
Definition: port.h:196
int pclose_check(FILE *stream)
Definition: exec.c:527

◆ resolve_symlinks()

static int resolve_symlinks ( char *  path)
static

Definition at line 232 of file exec.c.

References _, canonicalize_path(), errcode_for_file_access(), join_path_components(), last_dir_separator(), log_error, lstat, MAXPGPATH, readlink, stat, and strlcpy().

Referenced by find_my_exec().

233 {
234 #ifdef HAVE_READLINK
235  struct stat buf;
236  char orig_wd[MAXPGPATH],
237  link_buf[MAXPGPATH];
238  char *fname;
239 
240  /*
241  * To resolve a symlink properly, we have to chdir into its directory and
242  * then chdir to where the symlink points; otherwise we may fail to
243  * resolve relative links correctly (consider cases involving mount
244  * points, for example). After following the final symlink, we use
245  * getcwd() to figure out where the heck we're at.
246  *
247  * One might think we could skip all this if path doesn't point to a
248  * symlink to start with, but that's wrong. We also want to get rid of
249  * any directory symlinks that are present in the given path. We expect
250  * getcwd() to give us an accurate, symlink-free path.
251  */
252  if (!getcwd(orig_wd, MAXPGPATH))
253  {
255  _("could not identify current directory: %m"));
256  return -1;
257  }
258 
259  for (;;)
260  {
261  char *lsep;
262  int rllen;
263 
264  lsep = last_dir_separator(path);
265  if (lsep)
266  {
267  *lsep = '\0';
268  if (chdir(path) == -1)
269  {
271  _("could not change directory to \"%s\": %m"), path);
272  return -1;
273  }
274  fname = lsep + 1;
275  }
276  else
277  fname = path;
278 
279  if (lstat(fname, &buf) < 0 ||
280  !S_ISLNK(buf.st_mode))
281  break;
282 
283  errno = 0;
284  rllen = readlink(fname, link_buf, sizeof(link_buf));
285  if (rllen < 0 || rllen >= sizeof(link_buf))
286  {
288  _("could not read symbolic link \"%s\": %m"), fname);
289  return -1;
290  }
291  link_buf[rllen] = '\0';
292  strcpy(path, link_buf);
293  }
294 
295  /* must copy final component out of 'path' temporarily */
296  strlcpy(link_buf, fname, sizeof(link_buf));
297 
298  if (!getcwd(path, MAXPGPATH))
299  {
301  _("could not identify current directory: %m"));
302  return -1;
303  }
304  join_path_components(path, path, link_buf);
305  canonicalize_path(path);
306 
307  if (chdir(orig_wd) == -1)
308  {
310  _("could not change directory to \"%s\": %m"), orig_wd);
311  return -1;
312  }
313 #endif /* HAVE_READLINK */
314 
315  return 0;
316 }
void canonicalize_path(char *path)
Definition: path.c:254
#define log_error(errcodefn,...)
Definition: exec.c:41
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:68
#define readlink(path, buf, size)
Definition: win32_port.h:231
int errcode_for_file_access(void)
Definition: elog.c:593
#define stat(a, b)
Definition: win32_port.h:264
char * last_dir_separator(const char *filename)
Definition: path.c:138
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
#define lstat(path, sb)
Definition: win32_port.h:253
#define _(x)
Definition: elog.c:84

◆ set_pglocale_pgservice()

void set_pglocale_pgservice ( const char *  argv0,
const char *  app 
)

Definition at line 565 of file exec.c.

References _, AddUserToTokenDacl(), canonicalize_path(), cleanup(), errcode(), FALSE, find_my_exec(), get_etc_path(), get_locale_path(), i, log_error, MAXPGPATH, my_exec_path, PG_TEXTDOMAIN, putenv, setlocale, snprintf, and TRUE.

Referenced by main(), and regression_main().

566 {
567  char path[MAXPGPATH];
568  char my_exec_path[MAXPGPATH];
569  char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
570  * PGLOCALEDIR */
571  char *dup_path;
572 
573  /* don't set LC_ALL in the backend */
574  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
575  {
576  setlocale(LC_ALL, "");
577 
578  /*
579  * One could make a case for reproducing here PostmasterMain()'s test
580  * for whether the process is multithreaded. Unlike the postmaster,
581  * no frontend program calls sigprocmask() or otherwise provides for
582  * mutual exclusion between signal handlers. While frontends using
583  * fork(), if multithreaded, are formally exposed to undefined
584  * behavior, we have not witnessed a concrete bug. Therefore,
585  * complaining about multithreading here may be mere pedantry.
586  */
587  }
588 
589  if (find_my_exec(argv0, my_exec_path) < 0)
590  return;
591 
592 #ifdef ENABLE_NLS
593  get_locale_path(my_exec_path, path);
594  bindtextdomain(app, path);
595  textdomain(app);
596 
597  if (getenv("PGLOCALEDIR") == NULL)
598  {
599  /* set for libpq to use */
600  snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
601  canonicalize_path(env_path + 12);
602  dup_path = strdup(env_path);
603  if (dup_path)
604  putenv(dup_path);
605  }
606 #endif
607 
608  if (getenv("PGSYSCONFDIR") == NULL)
609  {
610  get_etc_path(my_exec_path, path);
611 
612  /* set for libpq to use */
613  snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
614  canonicalize_path(env_path + 13);
615  dup_path = strdup(env_path);
616  if (dup_path)
617  putenv(dup_path);
618  }
619 }
static char * argv0
Definition: pg_ctl.c:97
#define setlocale(a, b)
Definition: win32_port.h:417
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1135
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:713
#define putenv(x)
Definition: win32_port.h:483
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
#define snprintf
Definition: port.h:192

◆ validate_exec()

static int validate_exec ( const char *  path)
static

Definition at line 68 of file exec.c.

References MAXPGPATH, pg_strcasecmp(), S_IRUSR, S_ISREG, S_IXUSR, stat, and strlcpy().

Referenced by find_my_exec(), and find_other_exec().

69 {
70  struct stat buf;
71  int is_r;
72  int is_x;
73 
74 #ifdef WIN32
75  char path_exe[MAXPGPATH + sizeof(".exe") - 1];
76 
77  /* Win32 requires a .exe suffix for stat() */
78  if (strlen(path) >= strlen(".exe") &&
79  pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
80  {
81  strlcpy(path_exe, path, sizeof(path_exe) - 4);
82  strcat(path_exe, ".exe");
83  path = path_exe;
84  }
85 #endif
86 
87  /*
88  * Ensure that the file exists and is a regular file.
89  *
90  * XXX if you have a broken system where stat() looks at the symlink
91  * instead of the underlying file, you lose.
92  */
93  if (stat(path, &buf) < 0)
94  return -1;
95 
96  if (!S_ISREG(buf.st_mode))
97  return -1;
98 
99  /*
100  * Ensure that the file is both executable and readable (required for
101  * dynamic loading).
102  */
103 #ifndef WIN32
104  is_r = (access(path, R_OK) == 0);
105  is_x = (access(path, X_OK) == 0);
106 #else
107  is_r = buf.st_mode & S_IRUSR;
108  is_x = buf.st_mode & S_IXUSR;
109 #endif
110  return is_x ? (is_r ? 0 : -2) : -1;
111 }
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define S_IXUSR
Definition: win32_port.h:275
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:68
#define S_ISREG(m)
Definition: win32_port.h:308
#define stat(a, b)
Definition: win32_port.h:264
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define S_IRUSR
Definition: win32_port.h:269