fe-connect.c 26.3 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * fe-connect.c--
4
 *	  functions related to setting up a connection to the backend
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.49 1997/12/01 22:02:46 momjian Exp $
11 12 13 14 15 16 17 18 19 20
 *
 *-------------------------------------------------------------------------
 */

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
21
#include <ctype.h>
22 23
#include <string.h>
#include <netdb.h>
24
#include <netinet/tcp.h>
25
#include <errno.h>
26
#include <signal.h>
27
#include <ctype.h>				/* for isspace() */
28 29

#include "postgres.h"
30 31
#include "libpq/pqcomm.h"		/* for decls of MsgType, PacketBuf,
								 * StartupInfo */
32
#include "fe-auth.h"
33
#include "fe-connect.h"
34 35
#include "libpq-fe.h"

36
#ifndef HAVE_STRDUP
37 38
#include "strdup.h"
#endif
39

40 41

/* use a local version instead of the one found in pqpacket.c */
42
static ConnStatusType connectDB(PGconn *conn);
43

44 45 46
static void startup2PacketBuf(StartupInfo *s, PacketBuf *res);
static void freePGconn(PGconn *conn);
static void closePGconn(PGconn *conn);
47 48 49
static int	conninfo_parse(const char *conninfo, char *errorMessage);
static char *conninfo_getval(char *keyword);
static void conninfo_free(void);
50
void PQsetenv(PGconn *conn);
51 52 53 54

#define NOTIFYLIST_INITIAL_SIZE 10
#define NOTIFYLIST_GROWBY 10

55 56

/* ----------
57
 * Definition of the conninfo parameters and their fallback resources.
58 59 60 61 62 63 64 65 66 67 68 69
 * If Environment-Var and Compiled-in are specified as NULL, no
 * fallback is available. If after all no value can be determined
 * for an option, an error is returned.
 *
 * The values for dbname and user are treated special in conninfo_parse.
 * If the Compiled-in resource is specified as a NULL value, the
 * user is determined by fe_getauthname() and for dbname the user
 * name is copied.
 *
 * The Label and Disp-Char entries are provided for applications that
 * want to use PQconndefaults() to create a generic database connection
 * dialog. Disp-Char is defined as follows:
70
 *	   ""		Normal input field
71 72 73
 * ----------
 */
static PQconninfoOption PQconninfoOptions[] = {
74 75 76 77 78 79
/* ----------------------------------------------------------------- */
/*	  Option-name		Environment-Var Compiled-in		Current value	*/
/*						Label							Disp-Char		*/
/* ----------------- --------------- --------------- --------------- */
	{"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
	"Database-Authtype", "", 20},
80

81 82
	{"user", "PGUSER", NULL, NULL,
	"Database-User", "", 20},
83

84 85
	{"password", "PGPASSWORD", DefaultPassword, NULL,
	"Database-Password", "", 20},
86

87 88
	{"dbname", "PGDATABASE", NULL, NULL,
	"Database-Name", "", 20},
89

90
	{"host", "PGHOST", NULL, NULL,
91
	"Database-Host", "", 40},
92

93 94
	{"port", "PGPORT", DEF_PGPORT, NULL,
	"Database-Port", "", 6},
95

96 97
	{"tty", "PGTTY", DefaultTty, NULL,
	"Backend-Debug-TTY", "D", 40},
98

99 100 101 102 103
	{"options", "PGOPTIONS", DefaultOption, NULL,
	"Backend-Debug-Options", "D", 40},
/* ----------------- --------------- --------------- --------------- */
	{NULL, NULL, NULL, NULL,
	NULL, NULL, 0}
104 105
};

106
struct EnvironmentOptions
107
{
108 109 110
	const char *envName,
			   *pgName;
}			EnvironmentOptions[] =
111 112

{
113 114 115 116 117 118 119 120 121
	/* common user-interface settings */
	{	"PGDATESTYLE",	"datestyle" },
	{	"PGTZ",			"timezone" },

	/* internal performance-related settings */
	{	"PGCOSTHEAP",	"cost_heap" },
	{	"PGCOSTINDEX",	"cost_index" },
	{	"PGRPLANS",		"r_plans" },
	{	"PGGEQO",		"geqo" },
122
	{	NULL }
123 124
};

125
/* ----------------
126 127
 *		PQconnectdb
 *
128
 * establishes a connection to a postgres backend through the postmaster
129 130 131 132
 * using connection information in a string.
 *
 * The conninfo string is a list of
 *
133
 *	   option = value
134 135 136 137 138 139 140
 *
 * definitions. Value might be a single value containing no whitespaces
 * or a single quoted string. If a single quote should appear everywhere
 * in the value, it must be escaped with a backslash like \'
 *
 * Returns a PGconn* which is needed for all subsequent libpq calls
 * if the status field of the connection returned is CONNECTION_BAD,
141
 * then some fields may be null'ed out instead of having valid values
142 143
 * ----------------
 */
144
PGconn *
145 146
PQconnectdb(const char *conninfo)
{
147
	PGconn	   *conn;
148
	PQconninfoOption *option;
149
	char		errorMessage[ERROR_MSG_LENGTH];
150

151 152 153 154 155 156 157 158 159 160 161
	/* ----------
	 * Allocate memory for the conn structure
	 * ----------
	 */
	conn = (PGconn *) malloc(sizeof(PGconn));
	if (conn == NULL)
	{
		fprintf(stderr,
		   "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
		return (PGconn *) NULL;
	}
Bruce Momjian's avatar
Bruce Momjian committed
162
	MemSet((char *) conn, 0, sizeof(PGconn));
163 164

	/* ----------
165
	 * Parse the conninfo string and get the fallback resources
166 167
	 * ----------
	 */
168 169 170 171 172 173
	if (conninfo_parse(conninfo, errorMessage) < 0)
	{
		conn->status = CONNECTION_BAD;
		strcpy(conn->errorMessage, errorMessage);
		conninfo_free();
		return conn;
174
	}
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

	/* ----------
	 * Check that we have all connection parameters
	 * ----------
	 */
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (option->val != NULL)
			continue;			/* Value was in conninfo */

		/* ----------
		 * No value was found for this option. Return an error.
		 * ----------
		 */
		conn->status = CONNECTION_BAD;
		sprintf(conn->errorMessage,
				"ERROR: PQconnectdb(): Cannot determine a value for option '%s'.\n",
				option->keyword);
		strcat(conn->errorMessage,
			   "Option not specified in conninfo string");
		if (option->environ)
		{
			strcat(conn->errorMessage,
				   ", environment variable ");
			strcat(conn->errorMessage, option->environ);
			strcat(conn->errorMessage, "\nnot set");
		}
		strcat(conn->errorMessage, " and no compiled in default value.\n");
		conninfo_free();
		return conn;
	}

	/* ----------
	 * Setup the conn structure
	 * ----------
	 */
	conn->lobjfuncs = (PGlobjfuncs *) NULL;
	conn->Pfout = NULL;
	conn->Pfin = NULL;
	conn->Pfdebug = NULL;
	conn->port = NULL;
	conn->notifyList = DLNewList();

	conn->pghost = strdup(conninfo_getval("host"));
	conn->pgport = strdup(conninfo_getval("port"));
	conn->pgtty = strdup(conninfo_getval("tty"));
	conn->pgoptions = strdup(conninfo_getval("options"));
	conn->pguser = strdup(conninfo_getval("user"));
	conn->pgpass = strdup(conninfo_getval("password"));
	conn->pgauth = strdup(conninfo_getval("authtype"));
	conn->dbName = strdup(conninfo_getval("dbname"));

	/* ----------
	 * Free the connection info - all is in conn now
	 * ----------
	 */
231
	conninfo_free();
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

	/*
	 * try to set the auth service if one was specified
	 */
	if (conn->pgauth)
	{
		fe_setauthsvc(conn->pgauth, conn->errorMessage);
	}

	/* ----------
	 * Connect to the database
	 * ----------
	 */
	conn->status = connectDB(conn);
	if (conn->status == CONNECTION_OK)
	{
248
		PGresult   *res;
249 250 251 252 253 254 255 256 257 258 259 260 261 262

		/*
		 * Send a blank query to make sure everything works; in
		 * particular, that the database exists.
		 */
		res = PQexec(conn, " ");
		if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY)
		{
			/* PQexec has put error message in conn->errorMessage */
			closePGconn(conn);
		}
		PQclear(res);
	}

263 264
	PQsetenv(conn);

265 266 267 268
	return conn;
}

/* ----------------
269 270
 *		PQconndefaults
 *
271 272 273 274 275 276
 * Parse an empty string like PQconnectdb() would do and return the
 * address of the connection options structure. Using this function
 * an application might determine all possible options and their
 * current default values.
 * ----------------
 */
277
PQconninfoOption *
278
PQconndefaults(void)
279
{
280
	char		errorMessage[ERROR_MSG_LENGTH];
281

282 283
	conninfo_parse("", errorMessage);
	return PQconninfoOptions;
284 285
}

286
/* ----------------
287 288
 *		PQsetdb
 *
289
 * establishes a connection to a postgres backend through the postmaster
290 291 292 293
 * at the specified host and port.
 *
 * returns a PGconn* which is needed for all subsequent libpq calls
 * if the status field of the connection returned is CONNECTION_BAD,
294
 * then some fields may be null'ed out instead of having valid values
295
 *
296
 *	Uses these environment variables:
297
 *
298 299
 *	  PGHOST	   identifies host to which to connect if <pghost> argument
 *				   is NULL or a null string.
300
 *
301 302
 *	  PGPORT	   identifies TCP port to which to connect if <pgport> argument
 *				   is NULL or a null string.
303
 *
304 305
 *	  PGTTY		   identifies tty to which to send messages if <pgtty> argument
 *				   is NULL or a null string.
306
 *
307 308
 *	  PGOPTIONS    identifies connection options if <pgoptions> argument is
 *				   NULL or a null string.
309
 *
310
 *	  PGUSER	   Postgres username to associate with the connection.
311
 *
312
 *	  PGPASSWORD   The user's password.
313
 *
314 315
 *	  PGDATABASE   name of database to which to connect if <pgdatabase>
 *				   argument is NULL or a null string
316
 *
317
 *	  None of the above need be defined.  There are defaults for all of them.
318
 *
319 320 321 322 323
 * To support "delimited identifiers" for database names, only convert
 * the database name to lower case if it is not surrounded by double quotes.
 * Otherwise, strip the double quotes but leave the reset of the string intact.
 * - thomas 1997-11-08
 *
324 325
 * ----------------
 */
326
PGconn	   *
327
PQsetdb(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName)
328
{
329 330 331
	PGconn	   *conn;
	char	   *tmp;
	char		errorMessage[ERROR_MSG_LENGTH];
332 333

	/* An error message from some service we call. */
334
	bool		error;
335 336

	/* We encountered an error that prevents successful completion */
337
	int			i;
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

	conn = (PGconn *) malloc(sizeof(PGconn));

	if (conn == NULL)
		fprintf(stderr,
		   "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
	else
	{
		conn->lobjfuncs = (PGlobjfuncs *) NULL;
		conn->Pfout = NULL;
		conn->Pfin = NULL;
		conn->Pfdebug = NULL;
		conn->port = NULL;
		conn->notifyList = DLNewList();

353
		if ((pghost == NULL) || pghost[0] == '\0')
354
		{
Bruce Momjian's avatar
Bruce Momjian committed
355
			conn->pghost = NULL;
356
			if ((tmp = getenv("PGHOST")) != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
357
				conn->pghost = strdup(tmp);
358 359 360 361
		}
		else
			conn->pghost = strdup(pghost);

362
		if ((pgport == NULL) || pgport[0] == '\0')
363
		{
364
			if ((tmp = getenv("PGPORT")) == NULL)
365 366 367 368 369 370
				tmp = DEF_PGPORT;
			conn->pgport = strdup(tmp);
		}
		else
			conn->pgport = strdup(pgport);

371
		if ((pgtty == NULL) || pgtty[0] == '\0')
372
		{
373
			if ((tmp = getenv("PGTTY")) == NULL)
374 375 376 377 378 379
				tmp = DefaultTty;
			conn->pgtty = strdup(tmp);
		}
		else
			conn->pgtty = strdup(pgtty);

380
		if ((pgoptions == NULL) || pgoptions[0] == '\0')
381
		{
382
			if ((tmp = getenv("PGOPTIONS")) == NULL)
383 384 385 386 387 388
				tmp = DefaultOption;
			conn->pgoptions = strdup(tmp);
		}
		else
			conn->pgoptions = strdup(pgoptions);

389
		if ((tmp = getenv("PGUSER")) != NULL)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
		{
			error = FALSE;
			conn->pguser = strdup(tmp);
		}
		else
		{
			tmp = fe_getauthname(errorMessage);
			if (tmp == 0)
			{
				error = TRUE;
				sprintf(conn->errorMessage,
						"FATAL: PQsetdb: Unable to determine a Postgres username!\n");
			}
			else
			{
				error = FALSE;
				conn->pguser = tmp;
			}
		}

410
		if ((tmp = getenv("PGPASSWORD")) != NULL)
411 412 413 414 415 416
			conn->pgpass = strdup(tmp);
		else
			conn->pgpass = 0;

		if (!error)
		{
417 418
			if ((((tmp = (char *) dbName) != NULL) && (dbName[0] != '\0'))
				|| ((tmp = getenv("PGDATABASE"))))
419 420 421
				conn->dbName = strdup(tmp);
			else
				conn->dbName = strdup(conn->pguser);
Bruce Momjian's avatar
Bruce Momjian committed
422 423

			/*
424 425
			 * if the database name is surrounded by double-quotes,
			 *  then don't convert case
Bruce Momjian's avatar
Bruce Momjian committed
426 427 428 429 430 431 432
			 */
			if (*conn->dbName == '"')
			{
				strcpy(conn->dbName, conn->dbName + 1);
				*(conn->dbName + strlen(conn->dbName) - 1) = '\0';
			}
			else
433
				for (i = strlen(conn->dbName); i >= 0; i--)
Bruce Momjian's avatar
Bruce Momjian committed
434 435
					if (isupper(conn->dbName[i]))
						conn->dbName[i] = tolower(conn->dbName[i]);
436 437 438 439 440 441 442 443 444 445 446 447
		}
		else
			conn->dbName = NULL;

		if (error)
			conn->status = CONNECTION_BAD;
		else
		{
			conn->status = connectDB(conn);
			/* Puts message in conn->errorMessage */
			if (conn->status == CONNECTION_OK)
			{
448
				PGresult   *res;
449 450 451 452 453 454 455 456 457 458 459 460 461

				/*
				 * Send a blank query to make sure everything works; in
				 * particular, that the database exists.
				 */
				res = PQexec(conn, " ");
				if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY)
				{
					/* PQexec has put error message in conn->errorMessage */
					closePGconn(conn);
				}
				PQclear(res);
			}
462
			PQsetenv(conn);
463 464 465
		}
	}
	return conn;
466 467
}

468

469 470
/*
 * connectDB -
471
 * make a connection to the backend so it is ready to receive queries.
Marc G. Fournier's avatar
Marc G. Fournier committed
472
 * return CONNECTION_OK if successful, CONNECTION_BAD if not.
473 474
 *
 */
475
static ConnStatusType
476
connectDB(PGconn *conn)
477
{
478 479
	struct hostent *hp;

480 481 482 483 484 485
	StartupInfo startup;
	PacketBuf	pacBuf;
	int			status;
	MsgType		msgtype;
	int			laddrlen = sizeof(struct sockaddr);
	Port	   *port = conn->port;
Bruce Momjian's avatar
Bruce Momjian committed
486 487 488
	int			portno,
				family,
				len;
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

	/*
	 * Initialize the startup packet.
	 *
	 * This data structure is used for the seq-packet protocol.  It describes
	 * the frontend-backend connection.
	 *
	 *
	 */
	strncpy(startup.user, conn->pguser, sizeof(startup.user));
	strncpy(startup.database, conn->dbName, sizeof(startup.database));
	strncpy(startup.tty, conn->pgtty, sizeof(startup.tty));
	if (conn->pgoptions)
	{
		strncpy(startup.options, conn->pgoptions, sizeof(startup.options));
	}
	else
		startup.options[0] = '\0';
	startup.execFile[0] = '\0'; /* not used */

	/*
	 * Open a connection to postmaster/backend.
	 *
	 */
	port = (Port *) malloc(sizeof(Port));
Bruce Momjian's avatar
Bruce Momjian committed
514
	MemSet((char *) port, 0, sizeof(Port));
515

516
	if (conn->pghost != NULL)
517
	{
518 519 520 521 522 523 524 525 526 527 528 529
		hp = gethostbyname(conn->pghost);
		if ((hp == NULL) || (hp->h_addrtype != AF_INET))
		{
			(void) sprintf(conn->errorMessage,
						   "connectDB() --  unknown hostname: %s\n",
						   conn->pghost);
			goto connect_errReturn;
		}
	} else
		hp = NULL;

#if FALSE
Bruce Momjian's avatar
Bruce Momjian committed
530
	MemSet((char *) &port->raddr, 0, sizeof(port->raddr));
531
#endif
532
	portno = atoi(conn->pgport);
533 534
	family = (conn->pghost != NULL) ? AF_INET : AF_UNIX;
	port->raddr.in.sin_family = family;
535
	if (family == AF_INET)
Bruce Momjian's avatar
Bruce Momjian committed
536 537 538 539 540 541 542
	{
		memmove((char *) &(port->raddr.in.sin_addr),
				(char *) hp->h_addr,
				hp->h_length);
		port->raddr.in.sin_port = htons((unsigned short) (portno));
		len = sizeof(struct sockaddr_in);
	}
543
	else
Bruce Momjian's avatar
Bruce Momjian committed
544 545 546
	{
		len = UNIXSOCK_PATH(port->raddr.un, portno);
	}
547
	/* connect to the server  */
548
	if ((port->sock = socket(family, SOCK_STREAM, 0)) < 0)
549 550 551 552 553 554
	{
		(void) sprintf(conn->errorMessage,
					   "connectDB() -- socket() failed: errno=%d\n%s\n",
					   errno, strerror(errno));
		goto connect_errReturn;
	}
Bruce Momjian's avatar
Bruce Momjian committed
555
	if (connect(port->sock, (struct sockaddr *) & port->raddr, len) < 0)
556 557
	{
		(void) sprintf(conn->errorMessage,
Bruce Momjian's avatar
Bruce Momjian committed
558 559 560
					   "connectDB() failed: Is the postmaster running at '%s' on port '%s'?\n",
					   conn->pghost ? conn->pghost : "UNIX Socket",
					   conn->pgport);
561 562
		goto connect_errReturn;
	}
563
	if (family == AF_INET)
564 565
	{
		struct protoent *pe;
566
		int			on = 1;
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

		pe = getprotobyname("TCP");
		if (pe == NULL)
		{
			(void) sprintf(conn->errorMessage,
						   "connectDB(): getprotobyname failed\n");
			goto connect_errReturn;
		}
		if (setsockopt(port->sock, pe->p_proto, TCP_NODELAY,
					   &on, sizeof(on)) < 0)
		{
			(void) sprintf(conn->errorMessage,
						   "connectDB(): setsockopt failed\n");
			goto connect_errReturn;
		}
	}

	/* fill in the client address */
	if (getsockname(port->sock, (struct sockaddr *) & port->laddr,
					&laddrlen) < 0)
	{
		(void) sprintf(conn->errorMessage,
				   "connectDB() -- getsockname() failed: errno=%d\n%s\n",
					   errno, strerror(errno));
		goto connect_errReturn;
	}

	/* by this point, connection has been opened */
	msgtype = fe_getauthsvc(conn->errorMessage);

/*	  pacBuf = startup2PacketBuf(&startup);*/
	startup2PacketBuf(&startup, &pacBuf);
	pacBuf.msgtype = (MsgType) htonl(msgtype);
	status = packetSend(port, &pacBuf, sizeof(PacketBuf), BLOCKING);

	if (status == STATUS_ERROR)
	{
		sprintf(conn->errorMessage,
				"connectDB() --  couldn't send complete packet: errno=%d\n%s\n", errno, strerror(errno));
		goto connect_errReturn;
607
	}
608 609 610 611 612 613 614 615 616 617

	/* authenticate as required */
	if (fe_sendauth(msgtype, port, conn->pghost,
					conn->pguser, conn->pgpass,
					conn->errorMessage) != STATUS_OK)
	{
		(void) sprintf(conn->errorMessage,
					   "connectDB() --  authentication failed with %s\n",
					   conn->pghost);
		goto connect_errReturn;
618
	}
619 620

	/* free the password so it's not hanging out in memory forever */
621
	if (conn->pgpass != NULL)
622
	{
623
		free(conn->pgpass);
624 625
	}

626 627 628
	/* set up the socket file descriptors */
	conn->Pfout = fdopen(port->sock, "w");
	conn->Pfin = fdopen(dup(port->sock), "r");
629
	if ((conn->Pfout == NULL) || (conn->Pfin == NULL))
630 631 632 633 634 635 636 637 638 639
	{
		(void) sprintf(conn->errorMessage,
					   "connectDB() -- fdopen() failed: errno=%d\n%s\n",
					   errno, strerror(errno));
		goto connect_errReturn;
	}

	conn->port = port;

	return CONNECTION_OK;
640 641

connect_errReturn:
642

643 644 645 646 647 648 649 650
	/*
	 * Igor/6/3/97 - We need to free it here...otherwise the function
	 * returns without setting conn->port to port. Because of that any way
	 * of referencing this variable will be lost and it's allocated memory
	 * will not be freed.
	 */
	free(port);					/* PURIFY */
	return CONNECTION_BAD;
651 652 653

}

654 655 656 657 658 659 660 661 662 663 664 665 666 667
void
PQsetenv(PGconn *conn)
{
	struct EnvironmentOptions *eo;
	char setQuery[80];		/* mjl: size okay? XXX */

	for (eo = EnvironmentOptions; eo->envName; eo++)
	{
		const char *val;

		if ((val = getenv(eo->envName)))
		{
			PGresult   *res;

668 669 670 671
			if (strcasecmp(val, "default") == 0)
				sprintf(setQuery, "SET %s = %.60s", eo->pgName, val);
			else
				sprintf(setQuery, "SET %s = '%.60s'", eo->pgName, val);
672 673 674 675 676 677 678 679 680
#ifdef CONNECTDEBUG
printf("Use environment variable %s to send %s\n", eo->envName, setQuery);
#endif
			res = PQexec(conn, setQuery);
			PQclear(res);	/* Don't care? */
		}
	}
} /* PQsetenv() */

681 682
/*
 * freePGconn
683
 *	 - free the PGconn data structure
684 685
 *
 */
686
static void
687
freePGconn(PGconn *conn)
688
{
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	if (!conn)
		return;
	if (conn->pghost)
		free(conn->pghost);
	if (conn->pgtty)
		free(conn->pgtty);
	if (conn->pgoptions)
		free(conn->pgoptions);
	if (conn->pgport)
		free(conn->pgport);
	if (conn->dbName)
		free(conn->dbName);
	if (conn->pguser)
		free(conn->pguser);
	if (conn->notifyList)
		DLFreeList(conn->notifyList);
	if (conn->port)
		free(conn->port);
	free(conn);
708 709 710 711
}

/*
   closePGconn
712
	 - properly close a connection to the backend
713 714
*/
static void
715
closePGconn(PGconn *conn)
716
{
717 718
/* GH: What to do for !USE_POSIX_SIGNALS ? */
#if defined(USE_POSIX_SIGNALS)
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
	struct sigaction ignore_action;

	/*
	 * This is used as a constant, but not declared as such because the
	 * sigaction structure is defined differently on different systems
	 */
	struct sigaction oldaction;

	/*
	 * If connection is already gone, that's cool.  No reason for kernel
	 * to kill us when we try to write to it.  So ignore SIGPIPE signals.
	 */
	ignore_action.sa_handler = SIG_IGN;
	sigemptyset(&ignore_action.sa_mask);
	ignore_action.sa_flags = 0;
	sigaction(SIGPIPE, (struct sigaction *) & ignore_action, &oldaction);

	fputs("X\0", conn->Pfout);
	fflush(conn->Pfout);
	sigaction(SIGPIPE, &oldaction, NULL);
739
#else
740
				signal(SIGPIPE, SIG_IGN);
741 742 743
	fputs("X\0", conn->Pfout);
	fflush(conn->Pfout);
	signal(SIGPIPE, SIG_DFL);
744
#endif
745 746 747 748 749 750 751 752
	if (conn->Pfout)
		fclose(conn->Pfout);
	if (conn->Pfin)
		fclose(conn->Pfin);
	if (conn->Pfdebug)
		fclose(conn->Pfdebug);
	conn->status = CONNECTION_BAD;		/* Well, not really _bad_ - just
										 * absent */
753 754 755 756
}

/*
   PQfinish:
757 758 759
	  properly close a connection to the backend
	  also frees the PGconn data structure so it shouldn't be re-used
	  after this
760 761
*/
void
762
PQfinish(PGconn *conn)
763
{
764 765 766 767 768 769 770 771 772 773
	if (!conn)
	{
		fprintf(stderr, "PQfinish() -- pointer to PGconn is null\n");
	}
	else
	{
		if (conn->status == CONNECTION_OK)
			closePGconn(conn);
		freePGconn(conn);
	}
774 775 776 777
}

/* PQreset :
   resets the connection to the backend
778
   closes the existing connection and makes a new one
779 780
*/
void
781
PQreset(PGconn *conn)
782
{
783 784 785 786 787 788 789 790 791
	if (!conn)
	{
		fprintf(stderr, "PQreset() -- pointer to PGconn is null\n");
	}
	else
	{
		closePGconn(conn);
		conn->status = connectDB(conn);
	}
792 793 794 795 796 797 798 799 800 801 802 803
}

/*
 * PacketSend()
 *
 this is just like PacketSend(), defined in backend/libpq/pqpacket.c
 but we define it here to avoid linking in all of libpq.a

 * packetSend -- send a single-packet message.
 *
 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
 * SIDE_EFFECTS: may block.
804 805
 * NOTES: Non-blocking writes would significantly complicate
 *		buffer management.	For now, we're not going to do it.
806 807
 *
*/
808
int
809 810
packetSend(Port *port,
		   PacketBuf *buf,
811 812
		   PacketLen len,
		   bool nonBlocking)
813
{
Bruce Momjian's avatar
Bruce Momjian committed
814 815
	PacketLen	doneLen = write(port->sock, buf, len);

816
	if (doneLen < len)
817 818 819 820
	{
		return (STATUS_ERROR);
	}
	return (STATUS_OK);
821 822 823 824 825 826 827
}

/*
 * startup2PacketBuf()
 *
 * this is just like StartupInfo2Packet(), defined in backend/libpq/pqpacket.c
 * but we repeat it here so we don't have to link in libpq.a
828
 *
829 830 831
 * converts a StartupInfo structure to a PacketBuf
 */
static void
832
startup2PacketBuf(StartupInfo *s, PacketBuf *res)
833
{
834
	char	   *tmp;
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

/*	res = (PacketBuf*)malloc(sizeof(PacketBuf)); */
	res->len = htonl(sizeof(PacketBuf));
	/* use \n to delimit the strings */
	res->data[0] = '\0';

	tmp = res->data;

	strncpy(tmp, s->database, sizeof(s->database));
	tmp += sizeof(s->database);
	strncpy(tmp, s->user, sizeof(s->user));
	tmp += sizeof(s->user);
	strncpy(tmp, s->options, sizeof(s->options));
	tmp += sizeof(s->options);
	strncpy(tmp, s->execFile, sizeof(s->execFile));
	tmp += sizeof(s->execFile);
	strncpy(tmp, s->tty, sizeof(s->tty));
852 853
}

854 855 856 857
/* ----------------
 * Conninfo parser routine
 * ----------------
 */
858 859
static int
conninfo_parse(const char *conninfo, char *errorMessage)
860
{
861 862 863 864 865 866
	char	   *pname;
	char	   *pval;
	char	   *buf;
	char	   *tmp;
	char	   *cp;
	char	   *cp2;
867
	PQconninfoOption *option;
868
	char		errortmp[ERROR_MSG_LENGTH];
869 870 871 872 873 874 875 876

	conninfo_free();

	if ((buf = strdup(conninfo)) == NULL)
	{
		strcpy(errorMessage,
		  "FATAL: cannot allocate memory for copy of conninfo string\n");
		return -1;
877
	}
878
	cp = buf;
879

880 881 882 883 884 885 886
	while (*cp)
	{
		/* Skip blanks before the parameter name */
		if (isspace(*cp))
		{
			cp++;
			continue;
887 888
		}

889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
		/* Get the parameter name */
		pname = cp;
		while (*cp)
		{
			if (*cp == '=')
			{
				break;
			}
			if (isspace(*cp))
			{
				*cp++ = '\0';
				while (*cp)
				{
					if (!isspace(*cp))
					{
						break;
					}
					cp++;
				}
				break;
			}
			cp++;
		}
912

913 914 915 916 917 918 919 920 921 922
		/* Check that there is a following '=' */
		if (*cp != '=')
		{
			sprintf(errorMessage,
			"ERROR: PQconnectdb() - Missing '=' after '%s' in conninfo\n",
					pname);
			free(buf);
			return -1;
		}
		*cp++ = '\0';
923

924 925 926 927 928 929 930 931
		/* Skip blanks after the '=' */
		while (*cp)
		{
			if (!isspace(*cp))
			{
				break;
			}
			cp++;
932
		}
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

		pval = cp;

		if (*cp != '\'')
		{
			cp2 = pval;
			while (*cp)
			{
				if (isspace(*cp))
				{
					*cp++ = '\0';
					break;
				}
				if (*cp == '\\')
				{
					cp++;
					if (*cp != '\0')
					{
						*cp2++ = *cp++;
					}
				}
				else
				{
					*cp2++ = *cp++;
				}
			}
			*cp2 = '\0';
960
		}
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
		else
		{
			cp2 = pval;
			cp++;
			for (;;)
			{
				if (*cp == '\0')
				{
					sprintf(errorMessage,
							"ERROR: PQconnectdb() - unterminated quoted string in conninfo\n");
					free(buf);
					return -1;
				}
				if (*cp == '\\')
				{
					cp++;
					if (*cp != '\0')
					{
						*cp2++ = *cp++;
					}
					continue;
				}
				if (*cp == '\'')
				{
					*cp2 = '\0';
					cp++;
					break;
				}
				*cp2++ = *cp++;
			}
991
		}
992 993 994 995 996 997 998 999 1000 1001 1002 1003

		/* ----------
		 * Now we have the name and the value. Search
		 * for the param record.
		 * ----------
		 */
		for (option = PQconninfoOptions; option->keyword != NULL; option++)
		{
			if (!strcmp(option->keyword, pname))
			{
				break;
			}
1004
		}
1005 1006 1007 1008 1009 1010 1011
		if (option->keyword == NULL)
		{
			sprintf(errorMessage,
					"ERROR: PQconnectdb() - unknown option '%s'\n",
					pname);
			free(buf);
			return -1;
1012 1013
		}

1014 1015 1016 1017 1018
		/* ----------
		 * Store the value
		 * ----------
		 */
		option->val = strdup(pval);
1019 1020
	}

1021
	free(buf);
1022 1023

	/* ----------
1024 1025
	 * Get the fallback resources for parameters not specified
	 * in the conninfo string.
1026 1027
	 * ----------
	 */
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (option->val != NULL)
			continue;			/* Value was in conninfo */

		/* ----------
		 * Try to get the environment variable fallback
		 * ----------
		 */
		if (option->environ != NULL)
		{
			if ((tmp = getenv(option->environ)) != NULL)
			{
				option->val = strdup(tmp);
				continue;
			}
		}
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		/* ----------
		 * No environment variable specified or this one isn't set -
		 * try compiled in
		 * ----------
		 */
		if (option->compiled != NULL)
		{
			option->val = strdup(option->compiled);
			continue;
		}
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
		/* ----------
		 * Special handling for user
		 * ----------
		 */
		if (!strcmp(option->keyword, "user"))
		{
			tmp = fe_getauthname(errortmp);
			if (tmp)
			{
				option->val = strdup(tmp);
			}
		}
1069

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
		/* ----------
		 * Special handling for dbname
		 * ----------
		 */
		if (!strcmp(option->keyword, "dbname"))
		{
			tmp = conninfo_getval("user");
			if (tmp)
			{
				option->val = strdup(tmp);
			}
		}
1082 1083
	}

1084
	return 0;
1085 1086 1087
}


1088
static char *
1089 1090
conninfo_getval(char *keyword)
{
1091
	PQconninfoOption *option;
1092

1093 1094 1095 1096 1097 1098
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (!strcmp(option->keyword, keyword))
		{
			return option->val;
		}
1099 1100
	}

1101
	return NULL;
1102 1103 1104 1105 1106 1107
}


static void
conninfo_free()
{
1108
	PQconninfoOption *option;
1109

1110 1111 1112 1113 1114 1115 1116
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (option->val != NULL)
		{
			free(option->val);
			option->val = NULL;
		}
1117 1118 1119
	}
}

1120
/* =========== accessor functions for PGconn ========= */
1121
char	   *
1122
PQdb(PGconn *conn)
1123
{
1124 1125 1126 1127 1128 1129
	if (!conn)
	{
		fprintf(stderr, "PQdb() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->dbName;
1130 1131
}

1132
char	   *
1133
PQuser(PGconn *conn)
1134
{
1135 1136 1137 1138 1139 1140
	if (!conn)
	{
		fprintf(stderr, "PQuser() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->pguser;
1141 1142
}

1143
char	   *
1144
PQhost(PGconn *conn)
1145
{
1146 1147 1148 1149 1150
	if (!conn)
	{
		fprintf(stderr, "PQhost() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
1151

1152
	return conn->pghost;
1153 1154
}

1155
char	   *
1156
PQoptions(PGconn *conn)
1157
{
1158 1159 1160 1161 1162 1163
	if (!conn)
	{
		fprintf(stderr, "PQoptions() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->pgoptions;
1164 1165
}

1166
char	   *
1167
PQtty(PGconn *conn)
1168
{
1169 1170 1171 1172 1173 1174
	if (!conn)
	{
		fprintf(stderr, "PQtty() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->pgtty;
1175 1176
}

1177
char	   *
1178
PQport(PGconn *conn)
1179
{
1180 1181 1182 1183 1184 1185
	if (!conn)
	{
		fprintf(stderr, "PQport() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->pgport;
1186 1187 1188
}

ConnStatusType
1189
PQstatus(PGconn *conn)
1190
{
1191 1192 1193 1194 1195 1196
	if (!conn)
	{
		fprintf(stderr, "PQstatus() -- pointer to PGconn is null\n");
		return CONNECTION_BAD;
	}
	return conn->status;
1197 1198
}

1199
char	   *
1200
PQerrorMessage(PGconn *conn)
1201
{
1202 1203 1204 1205 1206 1207
	if (!conn)
	{
		fprintf(stderr, "PQerrorMessage() -- pointer to PGconn is null\n");
		return (char *) NULL;
	}
	return conn->errorMessage;
1208 1209 1210
}

void
1211
PQtrace(PGconn *conn, FILE *debug_port)
1212
{
1213 1214 1215 1216 1217 1218 1219
	if (conn == NULL ||
		conn->status == CONNECTION_BAD)
	{
		return;
	}
	PQuntrace(conn);
	conn->Pfdebug = debug_port;
1220 1221
}

1222
void
1223
PQuntrace(PGconn *conn)
1224
{
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	if (conn == NULL ||
		conn->status == CONNECTION_BAD)
	{
		return;
	}
	if (conn->Pfdebug)
	{
		fflush(conn->Pfdebug);
		fclose(conn->Pfdebug);
		conn->Pfdebug = NULL;
	}
1236
}