exec.c 13.7 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * exec.c
4 5
 *		Functions for finding and validating executable files
 *
6
 *
P
 
PostgreSQL Daemon 已提交
7
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9 10 11
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
12
 *	  $PostgreSQL: pgsql/src/port/exec.c,v 1.39 2005/10/15 02:49:51 momjian Exp $
13 14 15
 *
 *-------------------------------------------------------------------------
 */
16 17

#ifndef FRONTEND
18
#include "postgres.h"
19 20 21
#else
#include "postgres_fe.h"
#endif
22

23 24
#include <grp.h>
#include <pwd.h>
B
Bruce Momjian 已提交
25
#include <sys/stat.h>
26
#include <sys/wait.h>
27
#ifndef WIN32_CLIENT_ONLY
28
#include <unistd.h>
29
#endif
30

31 32 33 34 35 36 37 38 39 40
#ifndef S_IRUSR					/* XXX [TRH] should be in a header */
#define S_IRUSR		 S_IREAD
#define S_IWUSR		 S_IWRITE
#define S_IXUSR		 S_IEXEC
#define S_IRGRP		 ((S_IRUSR)>>3)
#define S_IWGRP		 ((S_IWUSR)>>3)
#define S_IXGRP		 ((S_IXUSR)>>3)
#define S_IROTH		 ((S_IRUSR)>>6)
#define S_IWOTH		 ((S_IWUSR)>>6)
#define S_IXOTH		 ((S_IXUSR)>>6)
41 42
#endif

43 44
#ifndef FRONTEND
/* We use only 3-parameter elog calls in this file, for simplicity */
45
/* NOTE: caller must provide gettext call around str! */
46
#define log_error(str, param)	elog(LOG, str, param)
47
#else
48
#define log_error(str, param)	(fprintf(stderr, str, param), fputc('\n', stderr))
49 50
#endif

51 52 53 54 55 56 57 58
#ifdef WIN32_CLIENT_ONLY
#define getcwd(cwd,len)  GetCurrentDirectory(len, cwd)
#endif

static int	validate_exec(const char *path);
static int	resolve_symlinks(char *path);
static char *pipe_read_line(char *cmd, char *line, int maxsize);

59

60
/*
61
 * validate_exec -- validate "path" as an executable file
62 63
 *
 * returns 0 if the file is found and no error is encountered.
64 65
 *		  -1 if the regular file "path" does not exist or cannot be executed.
 *		  -2 if the file is otherwise valid but cannot be read.
66
 */
67
static int
68
validate_exec(const char *path)
69
{
70
	struct stat buf;
B
Bruce Momjian 已提交
71

72
#ifndef WIN32
73 74 75
	uid_t		euid;
	struct group *gp;
	struct passwd *pwp;
76 77
	int			i;
	int			in_grp = 0;
B
Bruce Momjian 已提交
78
#else
79
	char		path_exe[MAXPGPATH + sizeof(".exe") - 1];
80
#endif
81 82
	int			is_r = 0;
	int			is_x = 0;
83

84 85
#ifdef WIN32
	/* Win32 requires a .exe suffix for stat() */
86 87
	if (strlen(path) >= strlen(".exe") &&
		pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
88 89 90 91 92 93 94
	{
		strcpy(path_exe, path);
		strcat(path_exe, ".exe");
		path = path_exe;
	}
#endif

95 96 97
	/*
	 * Ensure that the file exists and is a regular file.
	 *
B
Bruce Momjian 已提交
98 99
	 * XXX if you have a broken system where stat() looks at the symlink instead
	 * of the underlying file, you lose.
100 101
	 */
	if (stat(path, &buf) < 0)
102
		return -1;
103 104

	if ((buf.st_mode & S_IFMT) != S_IFREG)
105
		return -1;
106 107

	/*
108
	 * Ensure that we are using an authorized executable.
109 110 111 112 113 114
	 */

	/*
	 * Ensure that the file is both executable and readable (required for
	 * dynamic loading).
	 */
115
#ifdef WIN32
B
Bruce Momjian 已提交
116 117 118
	is_r = buf.st_mode & S_IRUSR;
	is_x = buf.st_mode & S_IXUSR;
	return is_x ? (is_r ? 0 : -2) : -1;
119
#else
120
	euid = geteuid();
121 122

	/* If owned by us, just check owner bits */
123 124 125 126
	if (euid == buf.st_uid)
	{
		is_r = buf.st_mode & S_IRUSR;
		is_x = buf.st_mode & S_IXUSR;
127
		return is_x ? (is_r ? 0 : -2) : -1;
128
	}
129 130

	/* OK, check group bits */
B
Bruce Momjian 已提交
131 132

	pwp = getpwuid(euid);		/* not thread-safe */
133 134
	if (pwp)
	{
135
		if (pwp->pw_gid == buf.st_gid)	/* my primary group? */
136 137
			++in_grp;
		else if (pwp->pw_name &&
138
				 (gp = getgrgid(buf.st_gid)) != NULL && /* not thread-safe */
139
				 gp->gr_mem != NULL)
B
Bruce Momjian 已提交
140
		{						/* try list of member groups */
141 142 143 144 145 146 147 148 149 150 151 152 153
			for (i = 0; gp->gr_mem[i]; ++i)
			{
				if (!strcmp(gp->gr_mem[i], pwp->pw_name))
				{
					++in_grp;
					break;
				}
			}
		}
		if (in_grp)
		{
			is_r = buf.st_mode & S_IRGRP;
			is_x = buf.st_mode & S_IXGRP;
154
			return is_x ? (is_r ? 0 : -2) : -1;
155 156
		}
	}
157 158

	/* Check "other" bits */
159 160
	is_r = buf.st_mode & S_IROTH;
	is_x = buf.st_mode & S_IXOTH;
161
	return is_x ? (is_r ? 0 : -2) : -1;
162
#endif
163 164
}

165

166
/*
167
 * find_my_exec -- find an absolute path to a valid executable
168
 *
169 170 171 172
 *	argv0 is the name passed on the command line
 *	retpath is the output area (must be of size MAXPGPATH)
 *	Returns 0 if OK, -1 if error.
 *
173
 * The reason we have to work so hard to find an absolute path is that
174 175
 * on some platforms we can't do dynamic loading unless we know the
 * executable's location.  Also, we need a full path not a relative
176 177 178
 * path because we will later change working directory.  Finally, we want
 * a true path not a symlink location, so that we can locate other files
 * that are part of our installation relative to the executable.
179
 *
180
 * This function is not thread-safe because it calls validate_exec(),
B
Bruce Momjian 已提交
181
 * which calls getgrgid().	This function should be used only in
182
 * non-threaded binaries, not in library routines.
183 184
 */
int
B
Bruce Momjian 已提交
185
find_my_exec(const char *argv0, char *retpath)
186
{
B
Bruce Momjian 已提交
187 188 189
	char		cwd[MAXPGPATH],
				test_path[MAXPGPATH];
	char	   *path;
190

191
	if (!getcwd(cwd, MAXPGPATH))
192
	{
193
		log_error(_("could not identify current directory: %s"),
194 195 196
				  strerror(errno));
		return -1;
	}
197

198
	/*
199
	 * If argv0 contains a separator, then PATH wasn't used.
200
	 */
201
	if (first_dir_separator(argv0) != NULL)
202
	{
203
		if (is_absolute_path(argv0))
B
Bruce Momjian 已提交
204
			StrNCpy(retpath, argv0, MAXPGPATH);
205
		else
206
			join_path_components(retpath, cwd, argv0);
B
Bruce Momjian 已提交
207
		canonicalize_path(retpath);
208

B
Bruce Momjian 已提交
209
		if (validate_exec(retpath) == 0)
210
			return resolve_symlinks(retpath);
211

212
		log_error(_("invalid binary \"%s\""), retpath);
213
		return -1;
214
	}
215

216 217
#ifdef WIN32
	/* Win32 checks the current directory first for names without slashes */
218 219
	join_path_components(retpath, cwd, argv0);
	if (validate_exec(retpath) == 0)
220
		return resolve_symlinks(retpath);
221 222
#endif

223
	/*
B
Bruce Momjian 已提交
224 225
	 * Since no explicit path was supplied, the user must have been relying on
	 * PATH.  We'll search the same PATH.
226
	 */
227
	if ((path = getenv("PATH")) && *path)
228
	{
B
Bruce Momjian 已提交
229 230
		char	   *startp = NULL,
				   *endp = NULL;
231 232

		do
233
		{
234 235 236 237
			if (!startp)
				startp = path;
			else
				startp = endp + 1;
238

239
			endp = first_path_separator(startp);
240
			if (!endp)
B
Bruce Momjian 已提交
241
				endp = startp + strlen(startp); /* point to end */
242 243 244 245

			StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));

			if (is_absolute_path(test_path))
246
				join_path_components(retpath, test_path, argv0);
247
			else
248 249 250 251
			{
				join_path_components(retpath, cwd, test_path);
				join_path_components(retpath, retpath, argv0);
			}
B
Bruce Momjian 已提交
252
			canonicalize_path(retpath);
253

B
Bruce Momjian 已提交
254
			switch (validate_exec(retpath))
255
			{
B
Bruce Momjian 已提交
256
				case 0: /* found ok */
257
					return resolve_symlinks(retpath);
258
				case -1:		/* wasn't even a candidate, keep looking */
259
					break;
260
				case -2:		/* found but disqualified */
261
					log_error(_("could not read binary \"%s\""),
262
							  retpath);
263
					break;
264
			}
265
		} while (*endp);
266 267
	}

268
	log_error(_("could not find a \"%s\" to execute"), argv0);
269
	return -1;
270
}
271

272 273 274 275

/*
 * resolve_symlinks - resolve symlinks to the underlying file
 *
276
 * Replace "path" by the absolute path to the referenced file.
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
 *
 * Returns 0 if OK, -1 if error.
 *
 * Note: we are not particularly tense about producing nice error messages
 * because we are not really expecting error here; we just determined that
 * the symlink does point to a valid executable.
 */
static int
resolve_symlinks(char *path)
{
#ifdef HAVE_READLINK
	struct stat buf;
	char		orig_wd[MAXPGPATH],
				link_buf[MAXPGPATH];
	char	   *fname;

	/*
B
Bruce Momjian 已提交
294 295
	 * To resolve a symlink properly, we have to chdir into its directory and
	 * then chdir to where the symlink points; otherwise we may fail to
296 297 298
	 * resolve relative links correctly (consider cases involving mount
	 * points, for example).  After following the final symlink, we use
	 * getcwd() to figure out where the heck we're at.
299
	 *
B
Bruce Momjian 已提交
300 301 302 303
	 * One might think we could skip all this if path doesn't point to a symlink
	 * to start with, but that's wrong.  We also want to get rid of any
	 * directory symlinks that are present in the given path. We expect
	 * getcwd() to give us an accurate, symlink-free path.
304 305 306
	 */
	if (!getcwd(orig_wd, MAXPGPATH))
	{
307
		log_error(_("could not identify current directory: %s"),
308 309 310 311 312 313
				  strerror(errno));
		return -1;
	}

	for (;;)
	{
B
Bruce Momjian 已提交
314 315
		char	   *lsep;
		int			rllen;
316 317 318 319 320 321 322

		lsep = last_dir_separator(path);
		if (lsep)
		{
			*lsep = '\0';
			if (chdir(path) == -1)
			{
323
				log_error(_("could not change directory to \"%s\""), path);
324 325 326 327 328 329 330 331 332 333 334 335 336 337
				return -1;
			}
			fname = lsep + 1;
		}
		else
			fname = path;

		if (lstat(fname, &buf) < 0 ||
			(buf.st_mode & S_IFMT) != S_IFLNK)
			break;

		rllen = readlink(fname, link_buf, sizeof(link_buf));
		if (rllen < 0 || rllen >= sizeof(link_buf))
		{
338
			log_error(_("could not read symbolic link \"%s\""), fname);
339 340 341 342 343 344 345 346 347 348 349
			return -1;
		}
		link_buf[rllen] = '\0';
		strcpy(path, link_buf);
	}

	/* must copy final component out of 'path' temporarily */
	strcpy(link_buf, fname);

	if (!getcwd(path, MAXPGPATH))
	{
350
		log_error(_("could not identify current directory: %s"),
351 352 353 354 355 356 357 358
				  strerror(errno));
		return -1;
	}
	join_path_components(path, path, link_buf);
	canonicalize_path(path);

	if (chdir(orig_wd) == -1)
	{
359
		log_error(_("could not change directory to \"%s\""), orig_wd);
360 361
		return -1;
	}
B
Bruce Momjian 已提交
362
#endif   /* HAVE_READLINK */
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

	return 0;
}


/*
 * Find another program in our binary's directory,
 * then make sure it is the proper version.
 */
int
find_other_exec(const char *argv0, const char *target,
				const char *versionstr, char *retpath)
{
	char		cmd[MAXPGPATH];
	char		line[100];

	if (find_my_exec(argv0, retpath) < 0)
		return -1;

	/* Trim off program name and keep just directory */
	*last_dir_separator(retpath) = '\0';
	canonicalize_path(retpath);

	/* Now append the other program's name */
	snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
			 "/%s%s", target, EXE);

	if (validate_exec(retpath) != 0)
		return -1;

	snprintf(cmd, sizeof(cmd), "\"%s\" -V 2>%s", retpath, DEVNULL);

	if (!pipe_read_line(cmd, line, sizeof(line)))
		return -1;

	if (strcmp(line, versionstr) != 0)
		return -2;

	return 0;
}


405
/*
406
 * The runtime library's popen() on win32 does not work when being
407 408 409 410 411 412
 * called from a service when running on windows <= 2000, because
 * there is no stdin/stdout/stderr.
 *
 * Executing a command in a pipe and reading the first line from it
 * is all we need.
 */
B
Bruce Momjian 已提交
413 414
static char *
pipe_read_line(char *cmd, char *line, int maxsize)
415 416
{
#ifndef WIN32
B
Bruce Momjian 已提交
417
	FILE	   *pgver;
418 419 420 421 422 423 424

	/* flush output buffers in case popen does not... */
	fflush(stdout);
	fflush(stderr);

	if ((pgver = popen(cmd, "r")) == NULL)
		return NULL;
B
Bruce Momjian 已提交
425

426 427 428 429 430 431 432 433
	if (fgets(line, maxsize, pgver) == NULL)
	{
		perror("fgets failure");
		return NULL;
	}

	if (pclose_check(pgver))
		return NULL;
B
Bruce Momjian 已提交
434

435
	return line;
B
Bruce Momjian 已提交
436
#else							/* WIN32 */
437

438
	SECURITY_ATTRIBUTES sattr;
B
Bruce Momjian 已提交
439 440 441
	HANDLE		childstdoutrd,
				childstdoutwr,
				childstdoutrddup;
442 443
	PROCESS_INFORMATION pi;
	STARTUPINFO si;
B
Bruce Momjian 已提交
444
	char	   *retval = NULL;
445 446 447 448 449 450 451

	sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
	sattr.bInheritHandle = TRUE;
	sattr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
		return NULL;
B
Bruce Momjian 已提交
452

453 454 455 456 457 458 459 460 461 462 463 464 465 466
	if (!DuplicateHandle(GetCurrentProcess(),
						 childstdoutrd,
						 GetCurrentProcess(),
						 &childstdoutrddup,
						 0,
						 FALSE,
						 DUPLICATE_SAME_ACCESS))
	{
		CloseHandle(childstdoutrd);
		CloseHandle(childstdoutwr);
		return NULL;
	}

	CloseHandle(childstdoutrd);
B
Bruce Momjian 已提交
467 468 469

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
470 471 472 473 474
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdError = childstdoutwr;
	si.hStdOutput = childstdoutwr;
	si.hStdInput = INVALID_HANDLE_VALUE;
B
Bruce Momjian 已提交
475

476 477 478 479 480 481 482 483 484 485 486 487
	if (CreateProcess(NULL,
					  cmd,
					  NULL,
					  NULL,
					  TRUE,
					  0,
					  NULL,
					  NULL,
					  &si,
					  &pi))
	{
		/* Successfully started the process */
B
Bruce Momjian 已提交
488
		char	   *lineptr;
489

B
Bruce Momjian 已提交
490 491
		ZeroMemory(line, maxsize);

492 493
		/* Try to read at least one line from the pipe */
		/* This may require more than one wait/read attempt */
B
Bruce Momjian 已提交
494
		for (lineptr = line; lineptr < line + maxsize - 1;)
495
		{
496 497 498 499
			DWORD		bytesread = 0;

			/* Let's see if we can read */
			if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
B
Bruce Momjian 已提交
500
				break;			/* Timeout, but perhaps we got a line already */
501

B
Bruce Momjian 已提交
502
			if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
503
						  &bytesread, NULL))
B
Bruce Momjian 已提交
504
				break;			/* Error, but perhaps we got a line already */
505 506 507 508

			lineptr += strlen(lineptr);

			if (!bytesread)
B
Bruce Momjian 已提交
509
				break;			/* EOF */
510 511

			if (strchr(line, '\n'))
B
Bruce Momjian 已提交
512
				break;			/* One or more lines read */
513
		}
514

515
		if (lineptr != line)
516
		{
517 518 519 520
			/* OK, we read some data */
			int			len;

			/* If we got more than one line, cut off after the first \n */
B
Bruce Momjian 已提交
521
			lineptr = strchr(line, '\n');
522
			if (lineptr)
B
Bruce Momjian 已提交
523
				*(lineptr + 1) = '\0';
524 525

			len = strlen(line);
526

527
			/*
B
Bruce Momjian 已提交
528 529
			 * If EOL is \r\n, convert to just \n. Because stdout is a
			 * text-mode stream, the \n output by the child process is
B
Bruce Momjian 已提交
530 531 532
			 * received as \r\n, so we convert it to \n.  The server main.c
			 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
			 * disabling \n to \r\n expansion for stdout.
533
			 */
B
Bruce Momjian 已提交
534
			if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
535
			{
B
Bruce Momjian 已提交
536 537
				line[len - 2] = '\n';
				line[len - 1] = '\0';
538
				len--;
539 540
			}

B
Bruce Momjian 已提交
541
			/*
B
Bruce Momjian 已提交
542 543
			 * We emulate fgets() behaviour. So if there is no newline at the
			 * end, we add one...
B
Bruce Momjian 已提交
544
			 */
B
Bruce Momjian 已提交
545 546
			if (len == 0 || line[len - 1] != '\n')
				strcat(line, "\n");
547 548

			retval = line;
549 550 551 552 553
		}

		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	}
B
Bruce Momjian 已提交
554

555 556 557 558
	CloseHandle(childstdoutwr);
	CloseHandle(childstdoutrddup);

	return retval;
B
Bruce Momjian 已提交
559
#endif   /* WIN32 */
560 561 562
}


563 564 565 566 567 568 569 570
/*
 * pclose() plus useful error reporting
 * Is this necessary?  bjm 2004-05-11
 * It is better here because pipe.c has win32 backend linkage.
 */
int
pclose_check(FILE *stream)
{
B
Bruce Momjian 已提交
571
	int			exitstatus;
572 573 574 575

	exitstatus = pclose(stream);

	if (exitstatus == 0)
B
Bruce Momjian 已提交
576
		return 0;				/* all is well */
577 578 579 580 581 582 583

	if (exitstatus == -1)
	{
		/* pclose() itself failed, and hopefully set errno */
		perror("pclose failed");
	}
	else if (WIFEXITED(exitstatus))
584
		log_error(_("child process exited with exit code %d"),
B
Bruce Momjian 已提交
585
				  WEXITSTATUS(exitstatus));
586
	else if (WIFSIGNALED(exitstatus))
587
		log_error(_("child process was terminated by signal %d"),
B
Bruce Momjian 已提交
588
				  WTERMSIG(exitstatus));
589
	else
590
		log_error(_("child process exited with unrecognized status %d"),
B
Bruce Momjian 已提交
591
				  exitstatus);
592 593 594

	return -1;
}