fe-connect.c 55.0 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
T
Tatsuo Ishii 已提交
10
 *	  $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.110 2000/01/15 05:37:21 ishii Exp $
11 12 13 14
 *
 *-------------------------------------------------------------------------
 */

15 16
#include <sys/types.h>
#include <sys/socket.h>
17 18 19 20 21
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>

#include "postgres.h"
M
 
Marc G. Fournier 已提交
22 23 24 25
#include "libpq-fe.h"
#include "libpq-int.h"
#include "fe-auth.h"

B
Bruce Momjian 已提交
26 27 28
#ifdef WIN32
#include "win32.h"
#else
29
#include <unistd.h>
30
#include <netdb.h>
31
#include <netinet/tcp.h>
32
#include <arpa/inet.h>
B
Bruce Momjian 已提交
33
#endif
34

35
#ifndef HAVE_STRDUP
36 37
#include "strdup.h"
#endif
38 39 40
#ifdef HAVE_CRYPT_H
#include <crypt.h>
#endif
41

M
 
Marc G. Fournier 已提交
42
#ifdef MULTIBYTE
M
 
Marc G. Fournier 已提交
43 44
#include "mb/pg_wchar.h"
#endif
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/* ----------
 *     pg_setenv_state
 * A struct used when polling a setenv request. This is referred to externally
 * using a PGsetenvHandle.
 * ----------
 */
struct pg_setenv_state
{
	enum
	{
		SETENV_STATE_OPTION_SEND,    /* About to send an Environment Option */
		SETENV_STATE_OPTION_WAIT,    /* Waiting for above send to complete  */
#ifdef MULTIBYTE
		SETENV_STATE_ENCODINGS_SEND, /* About to send an "encodings" query  */
		SETENV_STATE_ENCODINGS_WAIT, /* Waiting for query to complete       */
#endif
		SETENV_STATE_OK,
		SETENV_STATE_FAILED
	} state;
	PGconn *conn;
	PGresult *res;
	struct EnvironmentOptions *eo;
} ;

static int connectDBStart(PGconn *conn);
static int connectDBComplete(PGconn *conn);

73 74 75 76
#ifdef USE_SSL
static SSL_CTX *SSL_context = NULL;
#endif

B
Bruce Momjian 已提交
77
static PGconn *makeEmptyPGconn(void);
78 79
static void freePGconn(PGconn *conn);
static void closePGconn(PGconn *conn);
80
static int	conninfo_parse(const char *conninfo, PQExpBuffer errorMessage);
81
static char *conninfo_getval(char *keyword);
82
static void conninfo_free(void);
83 84
static void defaultNoticeProcessor(void *arg, const char *message);

85 86 87
#define NOTIFYLIST_INITIAL_SIZE 10
#define NOTIFYLIST_GROWBY 10

M
Marc G. Fournier 已提交
88 89

/* ----------
90
 * Definition of the conninfo parameters and their fallback resources.
M
Marc G. Fournier 已提交
91 92 93 94 95 96 97 98 99 100 101 102
 * 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:
103
 *	   ""		Normal input field
M
Marc G. Fournier 已提交
104 105 106
 * ----------
 */
static PQconninfoOption PQconninfoOptions[] = {
107 108 109 110
/* ----------------------------------------------------------------- */
/*	  Option-name		Environment-Var Compiled-in		Current value	*/
/*						Label							Disp-Char		*/
/* ----------------- --------------- --------------- --------------- */
111
	/* "authtype" is ignored as it is no longer used. */
112 113
	{"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
	"Database-Authtype", "", 20},
114

115 116
	{"user", "PGUSER", NULL, NULL,
	"Database-User", "", 20},
M
Marc G. Fournier 已提交
117

118 119
	{"password", "PGPASSWORD", DefaultPassword, NULL,
	"Database-Password", "", 20},
120

121 122
	{"dbname", "PGDATABASE", NULL, NULL,
	"Database-Name", "", 20},
M
Marc G. Fournier 已提交
123

124
	{"host", "PGHOST", NULL, NULL,
125
	"Database-Host", "", 40},
M
Marc G. Fournier 已提交
126

127 128 129
	{"hostaddr", "PGHOSTADDR", NULL, NULL,
	 "Database-Host-IPv4-Address", "", 15}, /* Room for abc.def.ghi.jkl */

130 131
	{"port", "PGPORT", DEF_PGPORT, NULL,
	"Database-Port", "", 6},
M
Marc G. Fournier 已提交
132

133 134
	{"tty", "PGTTY", DefaultTty, NULL,
	"Backend-Debug-TTY", "D", 40},
M
Marc G. Fournier 已提交
135

136 137 138 139 140
	{"options", "PGOPTIONS", DefaultOption, NULL,
	"Backend-Debug-Options", "D", 40},
/* ----------------- --------------- --------------- --------------- */
	{NULL, NULL, NULL, NULL,
	NULL, NULL, 0}
M
Marc G. Fournier 已提交
141 142
};

M
 
Marc G. Fournier 已提交
143
static struct EnvironmentOptions
144
{
145 146 147
	const char *envName,
			   *pgName;
}			EnvironmentOptions[] =
148 149

{
150
	/* common user-interface settings */
151 152 153 154 155 156
	{
		"PGDATESTYLE", "datestyle"
	},
	{
		"PGTZ", "timezone"
	},
157
#ifdef MULTIBYTE
158 159 160 161
	{
		"PGCLIENTENCODING", "client_encoding"
	},
#endif
162
	/* internal performance-related settings */
163 164 165 166 167 168 169 170 171 172
	{
		"PGCOSTHEAP", "cost_heap"
	},
	{
		"PGCOSTINDEX", "cost_index"
	},
	{
		"PGGEQO", "geqo"
	},
	{
B
Bruce Momjian 已提交
173
		NULL, NULL
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

/* ----------------
 *      Connecting to a Database
 *
 * There are now four different ways a user of this API can connect to the
 * database.  Two are not recommended for use in new code, because of their
 * lack of extensibility with respect to the passing of options to the
 * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
 * to the latter).
 *
 * If it is desired to connect in a synchronous (blocking) manner, use the
 * function PQconnectdb.
 *
 * To connect in an asychronous (non-blocking) manner, use the functions
 * PQconnectStart, and PQconnectPoll.
 *
 * Internally, the static functions connectDBStart, connectDBComplete
 * are part of the connection procedure.
 * 
 * ----------------
 */

M
Marc G. Fournier 已提交
199
/* ----------------
200 201
 *		PQconnectdb
 *
202
 * establishes a connection to a postgres backend through the postmaster
M
Marc G. Fournier 已提交
203 204
 * using connection information in a string.
 *
205
 * The conninfo string is a white-separated list of
M
Marc G. Fournier 已提交
206
 *
207
 *	   option = value
M
Marc G. Fournier 已提交
208
 *
209 210 211
 * definitions. Value might be a single value containing no whitespaces or
 * a single quoted string. If a single quote should appear anywhere in
 * the value, it must be escaped with a backslash like \'
M
Marc G. Fournier 已提交
212
 *
213 214 215 216 217 218 219 220
 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
 * if a memory allocation failed.
 * If the status field of the connection returned is CONNECTION_BAD,
 * then some fields may be null'ed out instead of having valid values.
 *
 * You should call PQfinish (if conn is not NULL) regardless of whether this
 * call succeeded.
 *
221 222
 * ----------------
 */
223
PGconn *
M
Marc G. Fournier 已提交
224
PQconnectdb(const char *conninfo)
225 226
{
	PGconn *conn = PQconnectStart(conninfo);
227 228 229

	if (conn && conn->status != CONNECTION_BAD)
		(void) connectDBComplete(conn);
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

	return conn;
}

/* ----------------
 *		PQconnectStart
 *
 * Begins the establishment of a connection to a postgres backend through the
 * postmaster using connection information in a string.
 *
 * See comment for PQconnectdb for the definition of the string format.
 *
 * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
 * you should not attempt to proceed with this connection.  If the status
 * field of the connection returned is CONNECTION_BAD, an error has
 * occurred. In this case you should call PQfinish on the result, (perhaps
 * inspecting the error message first).  Other fields of the structure may not
 * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
 * this is necessary.
 *
 * See PQconnectPoll for more info.
 *
253 254
 * ----------------
 */
255 256
PGconn *
PQconnectStart(const char *conninfo)
M
Marc G. Fournier 已提交
257
{
258 259
	PGconn	   *conn;
	char	   *tmp;
260

261 262 263 264
	/* ----------
	 * Allocate memory for the conn structure
	 * ----------
	 */
265
	
B
Bruce Momjian 已提交
266
	conn = makeEmptyPGconn();
267 268
	if (conn == NULL)
		return (PGconn *) NULL;
M
Marc G. Fournier 已提交
269 270

	/* ----------
B
Bruce Momjian 已提交
271
	 * Parse the conninfo string and save settings in conn structure
M
Marc G. Fournier 已提交
272 273
	 * ----------
	 */
274
	if (conninfo_parse(conninfo, &conn->errorMessage) < 0)
275 276 277 278
	{
		conn->status = CONNECTION_BAD;
		conninfo_free();
		return conn;
M
Marc G. Fournier 已提交
279
	}
280 281
	tmp = conninfo_getval("hostaddr");
	conn->pghostaddr = tmp ? strdup(tmp) : NULL;
282 283 284 285 286
	tmp = conninfo_getval("host");
	conn->pghost = tmp ? strdup(tmp) : NULL;
	tmp = conninfo_getval("port");
	conn->pgport = tmp ? strdup(tmp) : NULL;
	tmp = conninfo_getval("tty");
287
	conn->pgtty = tmp ? strdup(tmp) : NULL;
288 289
	tmp = conninfo_getval("options");
	conn->pgoptions = tmp ? strdup(tmp) : NULL;
B
Bruce Momjian 已提交
290 291
	tmp = conninfo_getval("dbname");
	conn->dbName = tmp ? strdup(tmp) : NULL;
292 293 294 295
	tmp = conninfo_getval("user");
	conn->pguser = tmp ? strdup(tmp) : NULL;
	tmp = conninfo_getval("password");
	conn->pgpass = tmp ? strdup(tmp) : NULL;
296 297 298 299 300

	/* ----------
	 * Free the connection info - all is in conn now
	 * ----------
	 */
M
Marc G. Fournier 已提交
301
	conninfo_free();
302 303 304 305 306

	/* ----------
	 * Connect to the database
	 * ----------
	 */
307 308
	if (!connectDBStart(conn))
	{
309
		/* Just in case we failed to set it in connectDBStart */
310 311
		conn->status = CONNECTION_BAD;
	}
312

M
Marc G. Fournier 已提交
313 314 315 316
	return conn;
}

/* ----------------
317 318
 *		PQconndefaults
 *
M
Marc G. Fournier 已提交
319 320 321 322 323 324
 * 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.
 * ----------------
 */
325
PQconninfoOption *
326
PQconndefaults(void)
M
Marc G. Fournier 已提交
327
{
328
	PQExpBufferData  errorBuf;
M
Marc G. Fournier 已提交
329

330 331 332
	initPQExpBuffer(&errorBuf);
	conninfo_parse("", &errorBuf);
	termPQExpBuffer(&errorBuf);
333
	return PQconninfoOptions;
M
Marc G. Fournier 已提交
334 335
}

336
/* ----------------
337
 *		PQsetdbLogin
338
 *
339
 * establishes a connection to a postgres backend through the postmaster
340 341 342 343
 * 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,
344
 * then some fields may be null'ed out instead of having valid values
345
 *
346
 *	Uses these environment variables:
347
 *
348 349
 *	  PGHOST	   identifies host to which to connect if <pghost> argument
 *				   is NULL or a null string.
350
 *
351 352
 *	  PGPORT	   identifies TCP port to which to connect if <pgport> argument
 *				   is NULL or a null string.
353
 *
354 355
 *	  PGTTY		   identifies tty to which to send messages if <pgtty> argument
 *				   is NULL or a null string.
356
 *
357 358
 *	  PGOPTIONS    identifies connection options if <pgoptions> argument is
 *				   NULL or a null string.
359
 *
360
 *	  PGUSER	   Postgres username to associate with the connection.
361
 *
362
 *	  PGPASSWORD   The user's password.
363
 *
364 365
 *	  PGDATABASE   name of database to which to connect if <pgdatabase>
 *				   argument is NULL or a null string
366
 *
367
 *	  None of the above need be defined.  There are defaults for all of them.
368
 *
369 370 371 372 373
 * 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
 *
374 375
 * ----------------
 */
376
PGconn *
377 378 379
PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
			 const char *pgtty, const char *dbName, const char *login,
			 const char *pwd)
380
{
381
	PGconn	   *conn;
382 383
	char	   *tmp;	/* An error message from some service we call. */
	bool		error = FALSE;	/* We encountered an error. */
384
	int			i;
385

B
Bruce Momjian 已提交
386
	conn = makeEmptyPGconn();
387
	if (conn == NULL)
B
Bruce Momjian 已提交
388 389 390 391 392 393 394
		return (PGconn *) NULL;

	if ((pghost == NULL) || pghost[0] == '\0')
	{
		if ((tmp = getenv("PGHOST")) != NULL)
			conn->pghost = strdup(tmp);
	}
395
	else
B
Bruce Momjian 已提交
396 397 398
		conn->pghost = strdup(pghost);

	if ((pgport == NULL) || pgport[0] == '\0')
399
	{
B
Bruce Momjian 已提交
400 401 402 403 404 405
		if ((tmp = getenv("PGPORT")) == NULL)
			tmp = DEF_PGPORT;
		conn->pgport = strdup(tmp);
	}
	else
		conn->pgport = strdup(pgport);
406

B
Bruce Momjian 已提交
407 408 409 410 411 412 413 414
	if ((pgtty == NULL) || pgtty[0] == '\0')
	{
		if ((tmp = getenv("PGTTY")) == NULL)
			tmp = DefaultTty;
		conn->pgtty = strdup(tmp);
	}
	else
		conn->pgtty = strdup(pgtty);
415

B
Bruce Momjian 已提交
416 417 418 419 420 421 422 423
	if ((pgoptions == NULL) || pgoptions[0] == '\0')
	{
		if ((tmp = getenv("PGOPTIONS")) == NULL)
			tmp = DefaultOption;
		conn->pgoptions = strdup(tmp);
	}
	else
		conn->pgoptions = strdup(pgoptions);
424

B
Bruce Momjian 已提交
425 426 427 428 429
	if (login)
		conn->pguser = strdup(login);
	else if ((tmp = getenv("PGUSER")) != NULL)
		conn->pguser = strdup(tmp);
	else
430 431 432 433 434
	{
		/* fe-auth.c has not been fixed to support PQExpBuffers, so: */
		conn->pguser = fe_getauthname(conn->errorMessage.data);
		conn->errorMessage.len = strlen(conn->errorMessage.data);
	}
435

B
Bruce Momjian 已提交
436 437 438
	if (conn->pguser == NULL)
	{
		error = TRUE;
439 440
		printfPQExpBuffer(&conn->errorMessage,
						  "FATAL: PQsetdbLogin(): Unable to determine a Postgres username!\n");
B
Bruce Momjian 已提交
441
	}
442

B
Bruce Momjian 已提交
443 444 445 446 447 448
	if (pwd)
		conn->pgpass = strdup(pwd);
	else if ((tmp = getenv("PGPASSWORD")) != NULL)
		conn->pgpass = strdup(tmp);
	else
		conn->pgpass = strdup(DefaultPassword);
449

B
Bruce Momjian 已提交
450 451 452 453 454 455 456 457 458
	if ((dbName == NULL) || dbName[0] == '\0')
	{
		if ((tmp = getenv("PGDATABASE")) != NULL)
			conn->dbName = strdup(tmp);
		else if (conn->pguser)
			conn->dbName = strdup(conn->pguser);
	}
	else
		conn->dbName = strdup(dbName);
459

B
Bruce Momjian 已提交
460 461
	if (conn->dbName)
	{
462

B
Bruce Momjian 已提交
463
		/*
464 465
		 * if the database name is surrounded by double-quotes, then don't
		 * convert case
B
Bruce Momjian 已提交
466 467
		 */
		if (*conn->dbName == '"')
468
		{
B
Bruce Momjian 已提交
469 470
			strcpy(conn->dbName, conn->dbName + 1);
			conn->dbName[strlen(conn->dbName) - 1] = '\0';
471 472
		}
		else
B
Bruce Momjian 已提交
473
			for (i = 0; conn->dbName[i]; i++)
474 475
				if (isascii((unsigned char) conn->dbName[i]) &&
					isupper(conn->dbName[i]))
B
Bruce Momjian 已提交
476
					conn->dbName[i] = tolower(conn->dbName[i]);
477
	}
B
Bruce Momjian 已提交
478 479

	if (error)
480
	{
B
Bruce Momjian 已提交
481
		conn->status = CONNECTION_BAD;
482
	}
B
Bruce Momjian 已提交
483
	else
484
	{
485 486
		if (connectDBStart(conn))
			(void) connectDBComplete(conn);
487 488
	}
		
489
	return conn;
490 491
}

492

M
 
Marc G. Fournier 已提交
493 494 495 496 497 498 499 500
/*
 * update_db_info -
 * get all additional infos out of dbName
 *
 */
static int
update_db_info(PGconn *conn)
{
501 502 503
	char	   *tmp,
			   *old = conn->dbName;

M
 
Marc G. Fournier 已提交
504 505 506 507
	if (strchr(conn->dbName, '@') != NULL)
	{
		/* old style: dbname[@server][:port] */
		tmp = strrchr(conn->dbName, ':');
508
		if (tmp != NULL)		/* port number given */
M
 
Marc G. Fournier 已提交
509
		{
510
			conn->pgport = strdup(tmp + 1);
M
 
Marc G. Fournier 已提交
511 512
			*tmp = '\0';
		}
513

M
 
Marc G. Fournier 已提交
514
		tmp = strrchr(conn->dbName, '@');
515
		if (tmp != NULL)		/* host name given */
M
 
Marc G. Fournier 已提交
516
		{
517
			conn->pghost = strdup(tmp + 1);
M
 
Marc G. Fournier 已提交
518 519
			*tmp = '\0';
		}
520

M
 
Marc G. Fournier 已提交
521 522 523 524 525
		conn->dbName = strdup(old);
		free(old);
	}
	else
	{
526 527
		int			offset;

M
 
Marc G. Fournier 已提交
528
		/*
529 530
		 * only allow protocols tcp and unix
		 */
M
 
Marc G. Fournier 已提交
531 532 533 534
		if (strncmp(conn->dbName, "tcp:", 4) == 0)
			offset = 4;
		else if (strncmp(conn->dbName, "unix:", 5) == 0)
			offset = 5;
535 536 537
		else
			return 0;

M
 
Marc G. Fournier 已提交
538 539
		if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
		{
540 541 542 543 544

			/*
			 * new style:
			 * <tcp|unix>:postgresql://server[:port][/dbname][?options]
			 */
M
 
Marc G. Fournier 已提交
545
			offset += strlen("postgresql://");
546

M
 
Marc G. Fournier 已提交
547
			tmp = strrchr(conn->dbName + offset, '?');
548
			if (tmp != NULL)	/* options given */
M
 
Marc G. Fournier 已提交
549
			{
550
				conn->pgoptions = strdup(tmp + 1);
M
 
Marc G. Fournier 已提交
551 552
				*tmp = '\0';
			}
553

M
 
Marc G. Fournier 已提交
554
			tmp = strrchr(conn->dbName + offset, '/');
555
			if (tmp != NULL)	/* database name given */
M
 
Marc G. Fournier 已提交
556
			{
557
				conn->dbName = strdup(tmp + 1);
M
 
Marc G. Fournier 已提交
558 559 560 561 562 563 564 565 566
				*tmp = '\0';
			}
			else
			{
				if ((tmp = getenv("PGDATABASE")) != NULL)
					conn->dbName = strdup(tmp);
				else if (conn->pguser)
					conn->dbName = strdup(conn->pguser);
			}
567

M
 
Marc G. Fournier 已提交
568
			tmp = strrchr(old + offset, ':');
569
			if (tmp != NULL)	/* port number given */
M
 
Marc G. Fournier 已提交
570
			{
571
				conn->pgport = strdup(tmp + 1);
M
 
Marc G. Fournier 已提交
572 573
				*tmp = '\0';
			}
574

M
 
Marc G. Fournier 已提交
575 576 577 578 579
			if (strncmp(old, "unix:", 5) == 0)
			{
				conn->pghost = NULL;
				if (strcmp(old + offset, "localhost") != 0)
				{
580
					printfPQExpBuffer(&conn->errorMessage,
581 582 583
									  "connectDBStart() -- "
									  "non-tcp access only possible on "
									  "localhost\n");
584
					return 1;
M
 
Marc G. Fournier 已提交
585 586
				}
			}
587 588 589
			else
				conn->pghost = strdup(old + offset);

M
 
Marc G. Fournier 已提交
590 591 592
			free(old);
		}
	}
593

M
 
Marc G. Fournier 已提交
594 595 596
	return 0;
}

597 598 599 600 601 602

/* ----------
 * connectMakeNonblocking -
 * Make a connection non-blocking.
 * Returns 1 if successful, 0 if not.
 * ----------
603
 */
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
static int
connectMakeNonblocking(PGconn *conn)
{
#ifndef WIN32
	if (fcntl(conn->sock, F_SETFL, O_NONBLOCK) < 0)
#else
	if (ioctlsocket(conn->sock, FIONBIO, &on) != 0)
#endif
	{
		printfPQExpBuffer(&conn->errorMessage,
						  "connectMakeNonblocking -- fcntl() failed: errno=%d\n%s\n",
						  errno, strerror(errno));
		return 0;
	}

	return 1;
}

/* ----------
 * connectNoDelay -
 * Sets the TCP_NODELAY socket option.
 * Returns 1 if successful, 0 if not.
 * ----------
 */
static int
connectNoDelay(PGconn *conn)
{
	struct protoent *pe;
	int			on = 1;

	pe = getprotobyname("TCP");
	if (pe == NULL)
	{
		printfPQExpBuffer(&conn->errorMessage,
						  "connectNoDelay() -- "
						  "getprotobyname failed: errno=%d\n%s\n",
						  errno, strerror(errno));
		return 0;
	}
	if (setsockopt(conn->sock, pe->p_proto, TCP_NODELAY,
#ifdef WIN32
				   (char *)
#endif
				   &on,
				   sizeof(on)) < 0)
	{
		printfPQExpBuffer(&conn->errorMessage,
						  "connectNoDelay() -- setsockopt failed: errno=%d\n%s\n",
						  errno, strerror(errno));
#ifdef WIN32
		printf("Winsock error: %i\n", WSAGetLastError());
#endif
		return 0;
	}

	return 1;
}


/* ----------
 * connectDBStart -
 * Start to make a connection to the backend so it is ready to receive
 * queries.
 * Returns 1 if successful, 0 if not.
 * ----------
 */
static int
connectDBStart(PGconn *conn)
672
{
B
Bruce Momjian 已提交
673
	int			portno,
M
 
Marc G. Fournier 已提交
674
				family;
675 676 677 678
#ifdef USE_SSL
	StartupPacket           np; /* Used to negotiate SSL connection */
	char                    SSLok;
#endif
679

680 681
	if (!conn)
		return 0;
682 683 684
	/*
	 * parse dbName to get all additional info in it, if any
	 */
M
 
Marc G. Fournier 已提交
685 686
	if (update_db_info(conn) != 0)
		goto connect_errReturn;
687

688 689 690 691
	/* Ensure our buffers are empty */
	conn->inStart = conn->inCursor = conn->inEnd = 0;
	conn->outCount = 0;

692
	/*
693 694
	 * Set up the connection to postmaster/backend.
	 * Note that this supports IPv4 and UDP only.
695
	 */
696

697
	MemSet((char *) &conn->raddr, 0, sizeof(conn->raddr));
698

699 700 701 702 703
	if (conn->pghostaddr != NULL)
	{
		/* Using pghostaddr avoids a hostname lookup */
		/* Note that this supports IPv4 only */
		struct in_addr addr;
704

705 706 707 708 709 710 711
		if(!inet_aton(conn->pghostaddr, &addr))
		{
			printfPQExpBuffer(&conn->errorMessage,
							  "connectDBStart() -- "
							  "invalid host address: %s\n", conn->pghostaddr);
			goto connect_errReturn;
		}
712

713
		family = AF_INET;
714

715 716 717 718
		memmove((char *) &(conn->raddr.in.sin_addr),
				(char *) &addr, sizeof(addr));
	}
	else if (conn->pghost != NULL)
719
	{
720 721 722
		/* Using pghost, so we have to look-up the hostname */
		struct hostent *hp;

723 724 725
		hp = gethostbyname(conn->pghost);
		if ((hp == NULL) || (hp->h_addrtype != AF_INET))
		{
726
			printfPQExpBuffer(&conn->errorMessage,
727
							  "connectDBStart() --  unknown hostname: %s\n",
728
							  conn->pghost);
729 730
			goto connect_errReturn;
		}
B
Bruce Momjian 已提交
731
		family = AF_INET;
732 733 734 735

		memmove((char *) &(conn->raddr.in.sin_addr),
				(char *) hp->h_addr,
				hp->h_length);
736
	}
737 738
	else
	{
739
		/* pghostaddr and pghost are NULL, so use UDP */
B
Bruce Momjian 已提交
740 741
		family = AF_UNIX;
	}
742

743
	/* Set family */
744
	conn->raddr.sa.sa_family = family;
B
Bruce Momjian 已提交
745

746
	/* Set port number */
B
Bruce Momjian 已提交
747
	portno = atoi(conn->pgport);
748
	if (family == AF_INET)
B
Bruce Momjian 已提交
749
	{
750
		conn->raddr.in.sin_port = htons((unsigned short) (portno));
M
 
Marc G. Fournier 已提交
751
		conn->raddr_len = sizeof(struct sockaddr_in);
B
Bruce Momjian 已提交
752
	}
753
#if !defined(WIN32) && !defined(__CYGWIN32__)
754 755
		else
			conn->raddr_len = UNIXSOCK_PATH(conn->raddr.un, portno);
B
Hello!  
Bruce Momjian 已提交
756
#endif
757

B
Bruce Momjian 已提交
758

759
	/* Open a socket */
760
	if ((conn->sock = socket(family, SOCK_STREAM, 0)) < 0)
761
	{
762
		printfPQExpBuffer(&conn->errorMessage,
763 764
						  "connectDBStart() -- "
						  "socket() failed: errno=%d\n%s\n",
765
						  errno, strerror(errno));
766 767
		goto connect_errReturn;
	}
768 769 770 771 772 773 774 775

	/* ----------
	 * Set the right options. Normally, we need nonblocking I/O, and we don't
	 * want delay of outgoing data for AF_INET sockets.  If we are using SSL,
	 * then we need the blocking I/O (XXX Can this be fixed?).
	 * ---------- */

	if (family == AF_INET)
776
	{
777 778
		if (!connectNoDelay(conn))
			goto connect_errReturn;
779
	}
B
Bruce Momjian 已提交
780

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
	/* ----------
	 * Since I have no idea whether this is a valid thing to do under Windows
	 * before a connection is made, and since I have no way of testing it, I
	 * leave the code looking as below.  When someone decides that they want
	 * non-blocking connections under Windows, they can define
	 * WIN32_NON_BLOCKING_CONNECTIONS before compilation.  If it works, then
	 * this code can be cleaned up.
	 *
	 *   Ewan Mellor <eem21@cam.ac.uk>.
	 * ---------- */
#if (!defined(WIN32) || defined(WIN32_NON_BLOCKING_CONNECTIONS)) && !defined(USE_SSL)
	if (!connectMakeNonblocking(conn))
		goto connect_errReturn;
#endif	

#ifdef USE_SSL
797 798
	/* This needs to be done before we set into nonblocking, since SSL
	 * negotiation does not like that mode */
799 800

	/* Attempt to negotiate SSL usage */
801
	if (conn->allow_ssl_try) {
802 803 804 805 806 807 808 809 810
	  memset((char *)&np, 0, sizeof(np));
	  np.protoVersion = htonl(NEGOTIATE_SSL_CODE);
	  if (pqPacketSend(conn, (char *) &np, sizeof(StartupPacket)) != STATUS_OK)
	    {
	      sprintf(conn->errorMessage,
		      "connectDB() -- couldn't send SSL negotiation packet: errno=%d\n%s\n",
		      errno, strerror(errno));
	      goto connect_errReturn;
	    }
811
	  /* Now receive the postmasters response */
812
	  if (recv(conn->sock, &SSLok, 1, 0) != 1) {
813
	    sprintf(conn->errorMessage, "PQconnectDB() -- couldn't read postmaster response: errno=%d\n%s\n",
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
		    errno, strerror(errno));
	    goto connect_errReturn;
	  }
	  if (SSLok == 'S') {
	    if (!SSL_context) 
	      {
		SSL_load_error_strings();
		SSL_library_init();
		SSL_context = SSL_CTX_new(SSLv23_method());
		if (!SSL_context) {
		  sprintf(conn->errorMessage,
			  "connectDB() -- couldn't create SSL context: %s\n",
			  ERR_reason_error_string(ERR_get_error()));
		  goto connect_errReturn;
		}
	      }
	    if (!(conn->ssl = SSL_new(SSL_context)) ||
		!SSL_set_fd(conn->ssl, conn->sock) ||
		SSL_connect(conn->ssl) <= 0) 
	      {
		sprintf(conn->errorMessage,
			"connectDB() -- couldn't establish SSL connection: %s\n",
			ERR_reason_error_string(ERR_get_error()));
		goto connect_errReturn;
	      }
	    /* SSL connection finished. Continue to send startup packet */
	  }
	  else if (SSLok == 'E') {
	    /* Received error - probably protocol mismatch */
	    if (conn->Pfdebug)
844
	      fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-6.6.\n");
845
	    close(conn->sock);
846
	    conn->allow_ssl_try = FALSE;
847
	    return connectDBStart(conn);
848 849 850 851 852 853 854 855 856
	  }
	  else if (SSLok != 'N') {
	    strcpy(conn->errorMessage,
		   "Received invalid negotiation response.\n");
	    goto connect_errReturn;
	  }
	}
#endif

857 858 859 860 861 862 863 864 865 866
	/* ----------
     * Start / make connection.  We are hopefully in non-blocking mode
	 * now, but it is possible that:
	 *   1. Older systems will still block on connect, despite the
	 *      non-blocking flag. (Anyone know if this is true?)
	 *   2. We are running under Windows, and aren't even trying
	 *      to be non-blocking (see above).
	 *   3. We are using SSL.
	 * Thus, we have make arrangements for all eventualities.
	 * ----------
B
Bruce Momjian 已提交
867
	 */
868
	if (connect(conn->sock, &conn->raddr.sa, conn->raddr_len) < 0)
869
	{
870
		if (errno == EINPROGRESS)
871
		{
872 873 874
			/* This is fine - we're in non-blocking mode, and the
			 * connection is in progress. */
			conn->status = CONNECTION_STARTED;
875
		}
876
		else
877
		{
878
			/* Something's gone wrong */
879
			printfPQExpBuffer(&conn->errorMessage,
880
							  "connectDBStart() -- connect() failed: %s\n"
881 882
							  "\tIs the postmaster running%s at '%s'\n"
							  "\tand accepting connections on %s '%s'?\n",
883 884 885 886 887 888
							  strerror(errno),
							  (family == AF_INET) ? " (with -i)" : "",
							  conn->pghost ? conn->pghost : "localhost",
							  (family == AF_INET) ?
							  "TCP/IP port" : "Unix socket",
							  conn->pgport);
889 890 891
			goto connect_errReturn;
		}
	}
892
	else
893
	{
894 895
		/* We're connected already */
		conn->status = CONNECTION_MADE;
896 897
	}

898 899 900 901 902 903
	/* This makes the connection non-blocking, for all those cases which forced us
	   not to do it above. */
#if (defined(WIN32) && !defined(WIN32_NON_BLOCKING_CONNECTIONS)) || defined(USE_SSL)
	if (!connectMakeNonblocking(conn))
		goto connect_errReturn;
#endif	
904

905
	return 1;
906

907 908
connect_errReturn:
	if (conn->sock >= 0)
909
	{
910 911 912 913 914 915
#ifdef WIN32
		closesocket(conn->sock);
#else
		close(conn->sock);
#endif
		conn->sock = -1;
916
	}
917
	conn->status = CONNECTION_BAD;
918

919 920
	return 0;
}
921

922

923 924 925 926 927 928 929 930 931 932 933 934
/* ----------------
 *		connectDBComplete
 *
 * Block and complete a connection.
 *
 * Returns 1 on success, 0 on failure.
 * ----------------
 */
static int
connectDBComplete(PGconn *conn)
{
	PostgresPollingStatusType flag;
935

936 937 938
	for (;;) {
		flag = PQconnectPoll(conn);
		switch (flag)
939
		{
940
			case PGRES_POLLING_ACTIVE:
941
				break;
942 943

			case PGRES_POLLING_OK:
944
				return 1;		/* success! */
945 946
				
			case PGRES_POLLING_READING:
947 948 949 950 951
				if (pqWait(1, 0, conn))
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
952 953 954
				break;

			case PGRES_POLLING_WRITING:
955 956 957 958 959
				if (pqWait(0, 1, conn))
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
960 961 962 963 964 965
				break;

			default:
				/* Just in case we failed to set it in PQconnectPoll */
				conn->status = CONNECTION_BAD;
				return 0;
966
		}
967
	}
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
}

/* ----------------
 *		PQconnectPoll
 *
 * Poll an asynchronous connection.
 *
 * Returns a PostgresPollingStatusType.
 * Before calling this function, use select(2) to determine when data arrive.
 * 
 * You must call PQfinish whether or not this fails.
 *
 * This function and PQconnectStart are intended to allow connections to be
 * made without blocking the execution of your program on remote I/O. However,
 * there are a number of caveats:
 *
 *   o  If you call PQtrace, ensure that the stream object into which you trace
985
 *      will not block.
986 987
 *   o  If you do not supply an IP address for the remote host (i.e. you 
 *      supply a host name instead) then this function will block on
988 989
 *      gethostbyname.  You will be fine if using Unix sockets (i.e. by
 *      supplying neither a host name nor a host address).
990 991 992 993 994
 *   o  If your backend wants to use Kerberos authentication then you must
 *      supply both a host name and a host address, otherwise this function
 *      may block on gethostname.
 *   o  This function will block if compiled with USE_SSL.
 *
995 996
 * ----------------
 */
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
PostgresPollingStatusType
PQconnectPoll(PGconn *conn)
{
	PGresult   *res;

	if (conn == NULL)
		return PGRES_POLLING_FAILED;

	/* Get the new data */
	switch (conn->status)
	{
		/* We really shouldn't have been polled in these two cases, but
		   we can handle it. */
		case CONNECTION_BAD:
			return PGRES_POLLING_FAILED;
		case CONNECTION_OK:
			return PGRES_POLLING_OK;

		/* These are reading states */
		case CONNECTION_AWAITING_RESPONSE:
		case CONNECTION_AUTH_OK:
1018
		{
1019 1020 1021 1022 1023 1024 1025 1026 1027
			/* Load waiting data */
			int n = pqReadData(conn);
				
			if (n < 0)
				goto error_return;
			if (n == 0)
				return PGRES_POLLING_READING;

			break;
1028 1029
		}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
		/* These are writing states, so we just proceed. */
		case CONNECTION_STARTED:
		case CONNECTION_MADE:
		   break;

		case CONNECTION_SETENV:
			/* We allow PQsetenvPoll to decide whether to proceed */
			break;

		default:
			printfPQExpBuffer(&conn->errorMessage,
							  "PQconnectPoll() -- unknown connection state - "
							  "probably indicative of memory corruption!\n");
			goto error_return;
	}


 keep_going: /* We will come back to here until there is nothing left to
				parse. */
	switch(conn->status)
	{
		case CONNECTION_STARTED:
		{
			SOCKET_SIZE_TYPE laddrlen;
			int optval;
1055
			int optlen = sizeof(int);
1056 1057 1058 1059 1060 1061

			/* Write ready, since we've made it here, so the connection
			 * has been made. */

			/* Now check (using getsockopt) that there is not an error
			   state waiting for us on the socket. */
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
			if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
						   &optval, &optlen) == -1)
			{
				printfPQExpBuffer(&conn->errorMessage,
								  "PQconnectPoll() -- getsockopt() failed: "
								  "errno=%d\n%s\n",
								  errno, strerror(errno));
				goto error_return;
			}
			else if (optval != 0)
			{
1074 1075 1076 1077 1078
				/*
				 * When using a nonblocking connect, we will typically see
				 * connect failures at this point, so provide a friendly
				 * error message.
				 */
1079
				printfPQExpBuffer(&conn->errorMessage,
1080 1081 1082 1083 1084 1085 1086 1087 1088
								  "PQconnectPoll() -- connect() failed: %s\n"
								  "\tIs the postmaster running%s at '%s'\n"
								  "\tand accepting connections on %s '%s'?\n",
								  strerror(optval),
								  (conn->raddr.sa.sa_family == AF_INET) ? " (with -i)" : "",
								  conn->pghost ? conn->pghost : "localhost",
								  (conn->raddr.sa.sa_family == AF_INET) ?
								  "TCP/IP port" : "Unix socket",
								  conn->pgport);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
				goto error_return;
			}

			/* Fill in the client address */
			laddrlen = sizeof(conn->laddr);
			if (getsockname(conn->sock, &conn->laddr.sa, &laddrlen) < 0)
			{
				printfPQExpBuffer(&conn->errorMessage,
								  "PQconnectPoll() -- getsockname() failed: "
								  "errno=%d\n%s\n",
								  errno, strerror(errno));
				goto error_return;
			}

			conn->status = CONNECTION_MADE;
			return PGRES_POLLING_WRITING;
		}

		case CONNECTION_MADE:
1108
		{
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
			StartupPacket sp;
			
			/*
			 * Initialize the startup packet.
			 */

			MemSet((char *) &sp, 0, sizeof(StartupPacket));
	
			sp.protoVersion = (ProtocolVersion) htonl(PG_PROTOCOL_LIBPQ);
			
			strncpy(sp.user, conn->pguser, SM_USER);
			strncpy(sp.database, conn->dbName, SM_DATABASE);
			strncpy(sp.tty, conn->pgtty, SM_TTY);

			if (conn->pgoptions)
				strncpy(sp.options, conn->pgoptions, SM_OPTIONS);

1126 1127 1128 1129 1130
			/* Send the startup packet.
			 *
			 * Theoretically, this could block, but it really shouldn't
			 * since we only got here if the socket is write-ready.
			 */
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

			if (pqPacketSend(conn, (char *) &sp,
							 sizeof(StartupPacket)) != STATUS_OK)
			{
				printfPQExpBuffer(&conn->errorMessage,
								  "PQconnectPoll() --  "
								  "couldn't send startup packet: "
								  "errno=%d\n%s\n",
								  errno, strerror(errno));
				goto error_return;
			}

			conn->status = CONNECTION_AWAITING_RESPONSE;
			return PGRES_POLLING_READING;
B
Bruce Momjian 已提交
1145
		}
1146

1147
		/*
1148
		 * Handle the authentication exchange: wait for postmaster messages
1149 1150 1151 1152 1153
		 * and respond as necessary.
		 */
		case CONNECTION_AWAITING_RESPONSE:
		{
			char		beresp;
1154
			AuthRequest areq;
1155

1156 1157 1158 1159
			/* Scan the message from current point (note that if we find
			 * the message is incomplete, we will return without advancing
			 * inStart, and resume here next time).
			 */
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
			conn->inCursor = conn->inStart;

			if (pqGetc(&beresp, conn))
			{
				/* We'll come back when there are more data */
				return PGRES_POLLING_READING;
			}

			/* Handle errors. */
			if (beresp == 'E')
			{
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
				if (pqGets(&conn->errorMessage, conn))
				{
					/* We'll come back when there are more data */
					return PGRES_POLLING_READING;
				}
				/* OK, we read the message; mark data consumed */
				conn->inStart = conn->inCursor;
				/* The postmaster typically won't end its message with a
				 * newline, so add one to conform to libpq conventions.
				 */
				appendPQExpBufferChar(&conn->errorMessage, '\n');
				goto error_return;
1183 1184 1185 1186 1187 1188
			}

			/* Otherwise it should be an authentication request. */
			if (beresp != 'R')
			{
				printfPQExpBuffer(&conn->errorMessage,
1189 1190
								  "PQconnectPoll() -- expected "
								  "authentication request\n");
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
				goto error_return;
			}

			/* Get the type of request. */
			if (pqGetInt((int *) &areq, 4, conn))
			{
				/* We'll come back when there are more data */
				return PGRES_POLLING_READING;
			}

			/* Get the password salt if there is one. */
			if (areq == AUTH_REQ_CRYPT)
			{
				if (pqGetnchar(conn->salt, sizeof(conn->salt), conn))
				{
					/* We'll come back when there are more data */
					return PGRES_POLLING_READING;
				}
			}

			/* OK, we successfully read the message; mark data consumed */
			conn->inStart = conn->inCursor;

			/* Respond to the request if necessary. */
1215
			/* Note that conn->pghost must be non-NULL if we are going to
1216 1217 1218 1219 1220 1221 1222 1223
			 * avoid the Kerberos code doing a hostname look-up. */
			/* XXX fe-auth.c has not been fixed to support PQExpBuffers, so: */
			if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
							conn->errorMessage.data) != STATUS_OK)
			{
				conn->errorMessage.len = strlen(conn->errorMessage.data);
				goto error_return;
			}
1224
			conn->errorMessage.len = strlen(conn->errorMessage.data);
1225

1226 1227 1228 1229
			/* Just make sure that any data sent by fe_sendauth is flushed
			 * out.  Although this theoretically could block, it really
			 * shouldn't since we don't send large auth responses.
			 */
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
			if (pqFlush(conn))
				goto error_return;

			if (areq == AUTH_REQ_OK)
			{
				/* We are done with authentication exchange */
				conn->status = CONNECTION_AUTH_OK;
				/* Set asyncStatus so that PQsetResult will think that what
				 * comes back next is the result of a query.  See below.  */
				conn->asyncStatus = PGASYNC_BUSY;
			}

1242 1243
			/* Look to see if we have more data yet. */
			goto keep_going;
1244 1245
		}

1246 1247 1248 1249 1250 1251 1252 1253 1254
		case CONNECTION_AUTH_OK:
		{
			/* ----------
			 * Now we expect to hear from the backend. A ReadyForQuery
			 * message indicates that startup is successful, but we might
			 * also get an Error message indicating failure. (Notice
			 * messages indicating nonfatal warnings are also allowed by
			 * the protocol, as is a BackendKeyData message.) Easiest way
			 * to handle this is to let PQgetResult() read the messages. We
1255 1256
			 * just have to fake it out about the state of the connection,
			 * by setting asyncStatus = PGASYNC_BUSY (done above).
1257 1258
			 *----------
			 */
1259

1260
			if (PQisBusy(conn))
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
				return PGRES_POLLING_READING;
			
			res = PQgetResult(conn);
			/* NULL return indicating we have gone to
			   IDLE state is expected */
			if (res)
			{
				if (res->resultStatus != PGRES_FATAL_ERROR)
					printfPQExpBuffer(&conn->errorMessage,
									  "PQconnectPoll() -- unexpected message "
									  "during startup\n");
1272 1273 1274 1275 1276 1277 1278 1279
				/* if the resultStatus is FATAL, then conn->errorMessage
				 * already has a copy of the error; needn't copy it back.
				 * But add a newline if it's not there already, since
				 * postmaster error messages may not have one.
				 */
				if (conn->errorMessage.len <= 0 ||
					conn->errorMessage.data[conn->errorMessage.len-1] != '\n')
					appendPQExpBufferChar(&conn->errorMessage, '\n');
1280 1281 1282 1283 1284
				PQclear(res);
				goto error_return;
			}

			/*
1285 1286
			 * Post-connection housekeeping. Prepare to send environment
			 * variables to server.
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
			 */

			if ((conn->setenv_handle = PQsetenvStart(conn)) == NULL)
				goto error_return;

			conn->status = CONNECTION_SETENV;

			goto keep_going;
		}

		case CONNECTION_SETENV:
			/* We pretend that the connection is OK for the duration of
1299
			   these queries. */
1300 1301
			conn->status = CONNECTION_OK;

T
Tatsuo Ishii 已提交
1302
			switch (PQsetenvPoll(conn))
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
			{
				case PGRES_POLLING_OK: /* Success */
					conn->status = CONNECTION_OK;
					return PGRES_POLLING_OK;

				case PGRES_POLLING_READING: /* Still going */
					conn->status = CONNECTION_SETENV;
					return PGRES_POLLING_READING;

				case PGRES_POLLING_WRITING: /* Still going */
					conn->status = CONNECTION_SETENV;
					return PGRES_POLLING_WRITING;

				default:
					conn->status = CONNECTION_SETENV;
					goto error_return;
			}
			/* Unreachable */

		default:
1323
			printfPQExpBuffer(&conn->errorMessage,
1324
							  "PQconnectPoll() -- unknown connection state - "
1325
							  "probably indicative of memory corruption!\n");
1326
			goto error_return;
B
Bruce Momjian 已提交
1327
	}
1328

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
	/* Unreachable */

error_return:
	/* ----------
	 * We used to close the socket at this point, but that makes it awkward
	 * for those above us if they wish to remove this socket from their
	 * own records (an fd_set for example).  We'll just have this socket
	 * closed when PQfinish is called (which is compulsory even after an
	 * error, since the connection structure must be freed).
	 * ----------
B
Bruce Momjian 已提交
1339
	 */
1340 1341
	return PGRES_POLLING_FAILED;
}
B
Bruce Momjian 已提交
1342 1343


1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
/* ----------------
 *		PQsetenvStart
 *
 * Starts the process of passing the values of a standard set of environment
 * variables to the backend.
 *
 * ---------------- */
PGsetenvHandle
PQsetenvStart(PGconn *conn)
{
	struct pg_setenv_state *handle;
1355

1356
	if ((handle = malloc(sizeof(struct pg_setenv_state))) == NULL)
B
Bruce Momjian 已提交
1357
	{
1358 1359 1360 1361
		printfPQExpBuffer(&conn->errorMessage,
						  "PQsetenvStart() -- malloc error - %s\n",
						  strerror(errno));
		return NULL;
B
Bruce Momjian 已提交
1362
	}
1363

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
	handle->conn = conn;
	handle->res = NULL;
	handle->eo = EnvironmentOptions;

#ifdef MULTIBYTE
	handle->state = SETENV_STATE_ENCODINGS_SEND;
#else
	handle->state = SETENV_STATE_OPTION_SEND;
#endif
	
	return handle; /* Note that a struct pg_setenv_state * is the same as a
					  PGsetenvHandle */
1376 1377
}

1378 1379 1380 1381 1382 1383
/* ----------------
 *		PQsetenvPoll
 *
 * Polls the process of passing the values of a standard set of environment
 * variables to the backend.
 *
1384 1385
 * ----------------
 */
1386
PostgresPollingStatusType
T
Tatsuo Ishii 已提交
1387
PQsetenvPoll(PGconn *conn)
1388
{
T
Tatsuo Ishii 已提交
1389
	PGsetenvHandle handle = conn->setenv_handle;
M
 
Marc G. Fournier 已提交
1390
#ifdef MULTIBYTE
1391
	static const char envname[] = "PGCLIENTENCODING";
1392 1393 1394 1395
#endif

	if (!handle || handle->state == SETENV_STATE_FAILED)
		return PGRES_POLLING_FAILED;
M
 
Marc G. Fournier 已提交
1396

1397 1398
	/* Check whether there are any data for us */
	switch (handle->state)
1399
	{
1400 1401 1402 1403 1404
		/* These are reading states */
#ifdef MULTIBYTE
		case SETENV_STATE_ENCODINGS_WAIT:
#endif
		case SETENV_STATE_OPTION_WAIT:
1405
		{
1406 1407 1408 1409 1410 1411 1412
			/* Load waiting data */
			int n = pqReadData(handle->conn);
				
			if (n < 0)
				goto error_return;
			if (n == 0)
				return PGRES_POLLING_READING;
1413

1414
			break;
1415
		}
1416 1417 1418 1419

		/* These are writing states, so we just proceed. */
#ifdef MULTIBYTE
		case SETENV_STATE_ENCODINGS_SEND:
M
 
Marc G. Fournier 已提交
1420
#endif
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
		case SETENV_STATE_OPTION_SEND:
			break;
		   
		default:
			printfPQExpBuffer(&handle->conn->errorMessage,
							  "PQsetenvPoll() -- unknown state - "
							  "probably indicative of memory corruption!\n");
			goto error_return;
	}

1431

1432 1433 1434
 keep_going: /* We will come back to here until there is nothing left to
				parse. */
	switch(handle->state)
1435
	{
1436 1437 1438

#ifdef MULTIBYTE
		case SETENV_STATE_ENCODINGS_SEND:
1439
		{
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
			const char *env;
			
			/* query server encoding */
			env = getenv(envname);
			if (!env || *env == '\0')
			{
				if (!PQsendQuery(handle->conn,
								 "select getdatabaseencoding()"))
					goto error_return;

				handle->state = SETENV_STATE_ENCODINGS_WAIT;
				return PGRES_POLLING_READING;
			}
		}

		case SETENV_STATE_ENCODINGS_WAIT:
		{
			const char *encoding = 0;

			if (PQisBusy(handle->conn))
				return PGRES_POLLING_READING;
			
			handle->res = PQgetResult(handle->conn);

			if (handle->res)
			{
				if (PQresultStatus(handle->res) != PGRES_TUPLES_OK)
				{
					PQclear(handle->res);
					goto error_return;
				}

				encoding = PQgetvalue(handle->res, 0, 0);
				if (!encoding)			/* this should not happen */
T
Tatsuo Ishii 已提交
1474
					encoding = SQL_ASCII;
1475 1476 1477

				if (encoding)
				{
T
Tatsuo Ishii 已提交
1478 1479
					/* set client encoding to pg_conn struct */
					conn->client_encoding = atoi(encoding);
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
				}
				PQclear(handle->res);
				/* We have to keep going in order to clear up the query */
				goto keep_going;
			}

			/* NULL result indicates that the query is finished */

			/* Move on to setting the environment options */
			handle->state = SETENV_STATE_OPTION_SEND;
			goto keep_going;
		}
#endif

		case SETENV_STATE_OPTION_SEND:
		{
			/* Send an Environment Option */
			char		setQuery[100];	/* note length limits in sprintf's below */

			if (handle->eo->envName)
			{
				const char *val;

				if ((val = getenv(handle->eo->envName)))
				{
					if (strcasecmp(val, "default") == 0)
						sprintf(setQuery, "SET %s = %.60s",
								handle->eo->pgName, val);
					else
						sprintf(setQuery, "SET %s = '%.60s'",
								handle->eo->pgName, val);
1511
#ifdef CONNECTDEBUG
1512 1513
					printf("Use environment variable %s to send %s\n",
						   handle->eo->envName, setQuery);
1514
#endif
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
					if (!PQsendQuery(handle->conn, setQuery))
						goto error_return;

					handle->state = SETENV_STATE_OPTION_WAIT;
				}
				else
				{
					handle->eo++;
				}
			}
			else
			{
				/* No option to send, so we are done. */
				handle->state = SETENV_STATE_OK;
			}

			goto keep_going;
1532
		}
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590

		case SETENV_STATE_OPTION_WAIT:
		{
			if (PQisBusy(handle->conn))
				return PGRES_POLLING_READING;
			
			handle->res = PQgetResult(handle->conn);

			if (handle->res)
			{
				if (PQresultStatus(handle->res) != PGRES_COMMAND_OK)
				{
					PQclear(handle->res);
					goto error_return;
				}
				/* Don't need the result */
				PQclear(handle->res);
				/* We have to keep going in order to clear up the query */
				goto keep_going;
			}

			/* NULL result indicates that the query is finished */

			/* Send the next option */
			handle->eo++;
			handle->state = SETENV_STATE_OPTION_SEND;
			goto keep_going;
		}

		case SETENV_STATE_OK:
			/* Tidy up */
			free(handle);
			return PGRES_POLLING_OK;

		default:
			printfPQExpBuffer(&handle->conn->errorMessage,
							  "PQsetenvPoll() -- unknown state - "
							  "probably indicative of memory corruption!\n");
			goto error_return;
	}

	/* Unreachable */

 error_return:
	handle->state = SETENV_STATE_FAILED; /* This may protect us even if we
										  * are called after the handle
										  * has been freed.             */
	free(handle);
	return PGRES_POLLING_FAILED;
}


/* ----------------
 *		PQsetenvAbort
 *
 * Aborts the process of passing the values of a standard set of environment
 * variables to the backend.
 *
1591 1592
 * ----------------
 */
1593 1594 1595 1596 1597 1598 1599 1600 1601
void
PQsetenvAbort(PGsetenvHandle handle)
{
	/* We should not have been called in the FAILED state, but we can cope by
	 * not freeing the handle (it has probably been freed by now anyway). */
	if (handle->state != SETENV_STATE_FAILED)
	{
		handle->state = SETENV_STATE_FAILED;
		free(handle);
1602
	}
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
}


/* ----------------
 *		PQsetenv
 *
 * Passes the values of a standard set of environment variables to the
 * backend.
 *
 * Returns 1 on success, 0 on failure.
 *
 * This function used to return void.  I don't think that there should be
 * compatibility problems caused by giving it a return value, especially as
 * this function has not been documented previously.
 *
1618 1619
 * ----------------
 */
1620 1621 1622 1623
int
PQsetenv(PGconn *conn)
{
	PGsetenvHandle handle;
1624
	PostgresPollingStatusType flag;
1625

1626 1627
	if ((handle = PQsetenvStart(conn)) == NULL)
		return 0;
1628

1629
	for (;;) {
T
Tatsuo Ishii 已提交
1630
		flag = PQsetenvPoll(conn);
1631
		switch (flag)
1632 1633
		{
			case PGRES_POLLING_ACTIVE:
1634
				break;
1635 1636

			case PGRES_POLLING_OK:
1637
				return 1;		/* success! */
1638 1639
				
			case PGRES_POLLING_READING:
1640 1641 1642 1643 1644
				if (pqWait(1, 0, conn))
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
1645
				break;
1646

1647
			case PGRES_POLLING_WRITING:
1648 1649 1650 1651 1652
				if (pqWait(0, 1, conn))
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
1653
				break;
1654 1655 1656 1657

			default:
				/* Just in case we failed to set it in PQconnectPoll */
				conn->status = CONNECTION_BAD;
1658 1659
				return 0;
		}
1660
	}
1661 1662
}

B
Bruce Momjian 已提交
1663 1664
/*
 * makeEmptyPGconn
1665
 *	 - create a PGconn data structure with (as yet) no interesting data
B
Bruce Momjian 已提交
1666 1667 1668 1669
 */
static PGconn *
makeEmptyPGconn(void)
{
1670 1671
	PGconn	   *conn = (PGconn *) malloc(sizeof(PGconn));

B
Bruce Momjian 已提交
1672 1673 1674
	if (conn == NULL)
		return conn;

1675
	/* Zero all pointers and booleans */
B
Bruce Momjian 已提交
1676 1677
	MemSet((char *) conn, 0, sizeof(PGconn));

B
 
Bruce Momjian 已提交
1678
	conn->noticeHook = defaultNoticeProcessor;
B
Bruce Momjian 已提交
1679 1680 1681 1682
	conn->status = CONNECTION_BAD;
	conn->asyncStatus = PGASYNC_IDLE;
	conn->notifyList = DLNewList();
	conn->sock = -1;
1683 1684 1685 1686
#ifdef USE_SSL
	conn->allow_ssl_try = TRUE;
#endif

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
	/*
	 * The output buffer size is set to 8K, which is the usual size of pipe
	 * buffers on Unix systems.  That way, when we are sending a large
	 * amount of data, we avoid incurring extra kernel context swaps for
	 * partial bufferloads.  Note that we currently don't ever enlarge
	 * the output buffer.
	 *
	 * With the same goal of minimizing context swaps, the input buffer will
	 * be enlarged anytime it has less than 8K free, so we initially allocate
	 * twice that.
	 */
	conn->inBufSize = 16 * 1024;
B
Bruce Momjian 已提交
1699
	conn->inBuffer = (char *) malloc(conn->inBufSize);
1700
	conn->outBufSize = 8 * 1024;
B
Bruce Momjian 已提交
1701
	conn->outBuffer = (char *) malloc(conn->outBufSize);
1702 1703 1704 1705 1706 1707
	initPQExpBuffer(&conn->errorMessage);
	initPQExpBuffer(&conn->workBuffer);
	if (conn->inBuffer == NULL ||
		conn->outBuffer == NULL ||
		conn->errorMessage.data == NULL ||
		conn->workBuffer.data == NULL)
B
Bruce Momjian 已提交
1708
	{
1709
		/* out of memory already :-( */
B
Bruce Momjian 已提交
1710 1711 1712 1713 1714 1715
		freePGconn(conn);
		conn = NULL;
	}
	return conn;
}

1716 1717
/*
 * freePGconn
1718
 *	 - free the PGconn data structure
1719 1720
 *
 */
1721
static void
1722
freePGconn(PGconn *conn)
1723
{
1724 1725
	if (!conn)
		return;
M
 
Marc G. Fournier 已提交
1726
	pqClearAsyncResult(conn);	/* deallocate result and curTuple */
1727 1728 1729 1730
#ifdef USE_SSL
	if (conn->ssl)
	  SSL_free(conn->ssl);
#endif
B
Bruce Momjian 已提交
1731
	if (conn->sock >= 0)
B
Hello!  
Bruce Momjian 已提交
1732 1733 1734 1735 1736
#ifdef WIN32
		closesocket(conn->sock);
#else
		close(conn->sock);
#endif
1737 1738
	if (conn->pghost)
		free(conn->pghost);
1739 1740
	if (conn->pghostaddr)
		free(conn->pghostaddr);
B
Bruce Momjian 已提交
1741 1742
	if (conn->pgport)
		free(conn->pgport);
1743 1744 1745 1746 1747 1748 1749 1750
	if (conn->pgtty)
		free(conn->pgtty);
	if (conn->pgoptions)
		free(conn->pgoptions);
	if (conn->dbName)
		free(conn->dbName);
	if (conn->pguser)
		free(conn->pguser);
1751 1752
	if (conn->pgpass)
		free(conn->pgpass);
B
Bruce Momjian 已提交
1753
	/* Note that conn->Pfdebug is not ours to close or free */
1754 1755
	if (conn->notifyList)
		DLFreeList(conn->notifyList);
B
Bruce Momjian 已提交
1756 1757 1758 1759 1760 1761
	if (conn->lobjfuncs)
		free(conn->lobjfuncs);
	if (conn->inBuffer)
		free(conn->inBuffer);
	if (conn->outBuffer)
		free(conn->outBuffer);
1762 1763
	termPQExpBuffer(&conn->errorMessage);
	termPQExpBuffer(&conn->workBuffer);
1764
	free(conn);
1765 1766 1767 1768
}

/*
   closePGconn
1769
	 - properly close a connection to the backend
1770 1771
*/
static void
1772
closePGconn(PGconn *conn)
1773
{
1774 1775 1776 1777 1778 1779
	if (conn->status == CONNECTION_SETENV)
	{
		/* We have to abort the setenv process as well */
		PQsetenvAbort(conn->setenv_handle);
	}

B
Bruce Momjian 已提交
1780 1781
	if (conn->sock >= 0)
	{
1782

B
Bruce Momjian 已提交
1783
		/*
1784 1785 1786
		 * Try to send "close connection" message to backend. Ignore any
		 * error. Note: this routine used to go to substantial lengths to
		 * avoid getting SIGPIPE'd if the connection were already closed.
M
 
Marc G. Fournier 已提交
1787
		 * Now we rely on pqFlush to avoid the signal.
B
Bruce Momjian 已提交
1788
		 */
M
 
Marc G. Fournier 已提交
1789 1790
		(void) pqPuts("X", conn);
		(void) pqFlush(conn);
B
Bruce Momjian 已提交
1791 1792 1793 1794 1795 1796
	}

	/*
	 * Close the connection, reset all transient state, flush I/O buffers.
	 */
	if (conn->sock >= 0)
B
Hello!  
Bruce Momjian 已提交
1797 1798 1799
#ifdef WIN32
		closesocket(conn->sock);
#else
B
Bruce Momjian 已提交
1800
		close(conn->sock);
B
Hello!  
Bruce Momjian 已提交
1801
#endif
B
Bruce Momjian 已提交
1802
	conn->sock = -1;
1803 1804
	conn->status = CONNECTION_BAD;		/* Well, not really _bad_ - just
										 * absent */
B
Bruce Momjian 已提交
1805
	conn->asyncStatus = PGASYNC_IDLE;
M
 
Marc G. Fournier 已提交
1806
	pqClearAsyncResult(conn);	/* deallocate result and curTuple */
B
Bruce Momjian 已提交
1807 1808 1809 1810 1811 1812
	if (conn->lobjfuncs)
		free(conn->lobjfuncs);
	conn->lobjfuncs = NULL;
	conn->inStart = conn->inCursor = conn->inEnd = 0;
	conn->outCount = 0;

1813 1814 1815 1816
}

/*
   PQfinish:
1817 1818 1819
	  properly close a connection to the backend
	  also frees the PGconn data structure so it shouldn't be re-used
	  after this
1820 1821
*/
void
1822
PQfinish(PGconn *conn)
1823
{
B
 
Bruce Momjian 已提交
1824
	if (conn)
1825
	{
B
Bruce Momjian 已提交
1826
		closePGconn(conn);
1827 1828
		freePGconn(conn);
	}
1829 1830 1831 1832
}

/* PQreset :
   resets the connection to the backend
1833
   closes the existing connection and makes a new one
1834 1835
*/
void
1836
PQreset(PGconn *conn)
1837
{
B
 
Bruce Momjian 已提交
1838
	if (conn)
1839 1840
	{
		closePGconn(conn);
1841

1842 1843
		if (connectDBStart(conn))
			(void) connectDBComplete(conn);
1844
	}
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
}


/* PQresetStart :
   resets the connection to the backend
   closes the existing connection and makes a new one
   Returns 1 on success, 0 on failure.
*/
int
PQresetStart(PGconn *conn)
{
	if (conn)
	{
		closePGconn(conn);

		return connectDBStart(conn);
	}

1863
	return 0;
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
}


/* PQresetPoll :
   resets the connection to the backend
   closes the existing connection and makes a new one
*/

PostgresPollingStatusType
PQresetPoll(PGconn *conn)
{
	if (conn)
	{
		return PQconnectPoll(conn);
	}

	return PGRES_POLLING_FAILED;
1881 1882
}

M
 
Marc G. Fournier 已提交
1883 1884 1885 1886 1887

/*
 * PQrequestCancel: attempt to request cancellation of the current operation.
 *
 * The return value is TRUE if the cancel request was successfully
1888
 * dispatched, FALSE if not (in which case conn->errorMessage is set).
M
 
Marc G. Fournier 已提交
1889 1890 1891
 * Note: successful dispatch is no guarantee that there will be any effect at
 * the backend.  The application must read the operation result as usual.
 *
1892 1893 1894 1895
 * XXX it was a bad idea to have the error message returned in
 * conn->errorMessage, since it could overwrite a message already there.
 * Would be better to return it in a char array passed by the caller.
 *
M
 
Marc G. Fournier 已提交
1896 1897 1898 1899 1900 1901
 * CAUTION: we want this routine to be safely callable from a signal handler
 * (for example, an application might want to call it in a SIGINT handler).
 * This means we cannot use any C library routine that might be non-reentrant.
 * malloc/free are often non-reentrant, and anything that might call them is
 * just as dangerous.  We avoid sprintf here for that reason.  Building up
 * error messages with strcpy/strcat is tedious but should be quite safe.
1902 1903 1904 1905
 *
 * NOTE: this routine must not generate any error message longer than
 * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
 * expand conn->errorMessage!
M
 
Marc G. Fournier 已提交
1906 1907 1908 1909 1910 1911
 */

int
PQrequestCancel(PGconn *conn)
{
	int			tmpsock = -1;
1912 1913 1914 1915
	struct
	{
		uint32		packetlen;
		CancelRequestPacket cp;
M
 
Marc G. Fournier 已提交
1916 1917 1918 1919 1920 1921 1922 1923
	}			crp;

	/* Check we have an open connection */
	if (!conn)
		return FALSE;

	if (conn->sock < 0)
	{
1924
		strcpy(conn->errorMessage.data,
M
 
Marc G. Fournier 已提交
1925
			   "PQrequestCancel() -- connection is not open\n");
1926
		conn->errorMessage.len = strlen(conn->errorMessage.data);
M
 
Marc G. Fournier 已提交
1927 1928 1929 1930
		return FALSE;
	}

	/*
1931 1932
	 * We need to open a temporary connection to the postmaster. Use the
	 * information saved by connectDB to do this with only kernel calls.
M
 
Marc G. Fournier 已提交
1933 1934 1935
	 */
	if ((tmpsock = socket(conn->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
	{
1936 1937
		strcpy(conn->errorMessage.data,
			   "PQrequestCancel() -- socket() failed: ");
M
 
Marc G. Fournier 已提交
1938 1939 1940 1941
		goto cancel_errReturn;
	}
	if (connect(tmpsock, &conn->raddr.sa, conn->raddr_len) < 0)
	{
1942 1943
		strcpy(conn->errorMessage.data,
			   "PQrequestCancel() -- connect() failed: ");
M
 
Marc G. Fournier 已提交
1944 1945
		goto cancel_errReturn;
	}
1946

M
 
Marc G. Fournier 已提交
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
	/*
	 * We needn't set nonblocking I/O or NODELAY options here.
	 */

	/* Create and send the cancel request packet. */

	crp.packetlen = htonl((uint32) sizeof(crp));
	crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
	crp.cp.backendPID = htonl(conn->be_pid);
	crp.cp.cancelAuthCode = htonl(conn->be_key);

1958
	if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
M
 
Marc G. Fournier 已提交
1959
	{
1960 1961
		strcpy(conn->errorMessage.data,
			   "PQrequestCancel() -- send() failed: ");
M
 
Marc G. Fournier 已提交
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
		goto cancel_errReturn;
	}

	/* Sent it, done */
#ifdef WIN32
	closesocket(tmpsock);
#else
	close(tmpsock);
#endif

	return TRUE;

cancel_errReturn:
1975 1976 1977
	strcat(conn->errorMessage.data, strerror(errno));
	strcat(conn->errorMessage.data, "\n");
	conn->errorMessage.len = strlen(conn->errorMessage.data);
M
 
Marc G. Fournier 已提交
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
	if (tmpsock >= 0)
	{
#ifdef WIN32
		closesocket(tmpsock);
#else
		close(tmpsock);
#endif
	}
	return FALSE;
}


1990
/*
M
 
Marc G. Fournier 已提交
1991
 * pqPacketSend() -- send a single-packet message.
B
Bruce Momjian 已提交
1992
 * this is like PacketSend(), defined in backend/libpq/pqpacket.c
1993 1994 1995 1996
 *
 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
 * SIDE_EFFECTS: may block.
*/
1997
int
M
 
Marc G. Fournier 已提交
1998
pqPacketSend(PGconn *conn, const char *buf, size_t len)
1999
{
2000
	/* Send the total packet size. */
B
Bruce Momjian 已提交
2001

B
Bruce Momjian 已提交
2002
	if (pqPutInt(4 + len, 4, conn))
2003
		return STATUS_ERROR;
2004

2005
	/* Send the packet itself. */
2006

B
Bruce Momjian 已提交
2007
	if (pqPutnchar(buf, len, conn))
2008
		return STATUS_ERROR;
2009

B
Bruce Momjian 已提交
2010 2011
	if (pqFlush(conn))
		return STATUS_ERROR;
2012

2013
	return STATUS_OK;
2014 2015
}

2016

M
Marc G. Fournier 已提交
2017 2018 2019 2020
/* ----------------
 * Conninfo parser routine
 * ----------------
 */
2021
static int
2022
conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
M
Marc G. Fournier 已提交
2023
{
2024 2025 2026
	char	   *pname;
	char	   *pval;
	char	   *buf;
2027
	char	   *tmp;
2028 2029
	char	   *cp;
	char	   *cp2;
2030
	PQconninfoOption *option;
2031
	char		errortmp[INITIAL_EXPBUFFER_SIZE];
2032 2033 2034 2035 2036

	conninfo_free();

	if ((buf = strdup(conninfo)) == NULL)
	{
2037
		printfPQExpBuffer(errorMessage,
2038 2039
		  "FATAL: cannot allocate memory for copy of conninfo string\n");
		return -1;
M
Marc G. Fournier 已提交
2040
	}
2041
	cp = buf;
M
Marc G. Fournier 已提交
2042

2043 2044 2045 2046 2047 2048 2049
	while (*cp)
	{
		/* Skip blanks before the parameter name */
		if (isspace(*cp))
		{
			cp++;
			continue;
M
Marc G. Fournier 已提交
2050 2051
		}

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
		/* 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++;
		}
M
Marc G. Fournier 已提交
2071

2072 2073 2074
		/* Check that there is a following '=' */
		if (*cp != '=')
		{
2075 2076 2077
			printfPQExpBuffer(errorMessage,
				"ERROR: PQconnectdb() - Missing '=' after '%s' in conninfo\n",
							  pname);
2078 2079 2080 2081
			free(buf);
			return -1;
		}
		*cp++ = '\0';
M
Marc G. Fournier 已提交
2082

2083 2084 2085 2086 2087 2088
		/* Skip blanks after the '=' */
		while (*cp)
		{
			if (!isspace(*cp))
				break;
			cp++;
M
Marc G. Fournier 已提交
2089
		}
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112

		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';
M
Marc G. Fournier 已提交
2113
		}
2114 2115 2116 2117 2118 2119 2120 2121
		else
		{
			cp2 = pval;
			cp++;
			for (;;)
			{
				if (*cp == '\0')
				{
2122
					printfPQExpBuffer(errorMessage,
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
							"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++;
			}
M
Marc G. Fournier 已提交
2142
		}
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152

		/* ----------
		 * 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;
M
Marc G. Fournier 已提交
2153
		}
2154 2155
		if (option->keyword == NULL)
		{
2156 2157 2158
			printfPQExpBuffer(errorMessage,
							  "ERROR: PQconnectdb() - unknown option '%s'\n",
							  pname);
2159 2160
			free(buf);
			return -1;
M
Marc G. Fournier 已提交
2161 2162
		}

2163 2164 2165 2166 2167
		/* ----------
		 * Store the value
		 * ----------
		 */
		option->val = strdup(pval);
M
Marc G. Fournier 已提交
2168 2169
	}

2170
	free(buf);
M
Marc G. Fournier 已提交
2171 2172

	/* ----------
2173 2174
	 * Get the fallback resources for parameters not specified
	 * in the conninfo string.
M
Marc G. Fournier 已提交
2175 2176
	 * ----------
	 */
2177 2178 2179 2180 2181 2182 2183 2184 2185
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (option->val != NULL)
			continue;			/* Value was in conninfo */

		/* ----------
		 * Try to get the environment variable fallback
		 * ----------
		 */
B
Bruce Momjian 已提交
2186
		if (option->envvar != NULL)
2187
		{
B
Bruce Momjian 已提交
2188
			if ((tmp = getenv(option->envvar)) != NULL)
2189 2190 2191 2192 2193
			{
				option->val = strdup(tmp);
				continue;
			}
		}
M
Marc G. Fournier 已提交
2194

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
		/* ----------
		 * No environment variable specified or this one isn't set -
		 * try compiled in
		 * ----------
		 */
		if (option->compiled != NULL)
		{
			option->val = strdup(option->compiled);
			continue;
		}
M
Marc G. Fournier 已提交
2205

2206 2207 2208 2209 2210 2211
		/* ----------
		 * Special handling for user
		 * ----------
		 */
		if (!strcmp(option->keyword, "user"))
		{
B
Bruce Momjian 已提交
2212
			option->val = fe_getauthname(errortmp);
2213
			/* note any error message is thrown away */
B
Bruce Momjian 已提交
2214
			continue;
2215
		}
M
Marc G. Fournier 已提交
2216

2217 2218 2219 2220 2221 2222 2223 2224 2225
		/* ----------
		 * Special handling for dbname
		 * ----------
		 */
		if (!strcmp(option->keyword, "dbname"))
		{
			tmp = conninfo_getval("user");
			if (tmp)
				option->val = strdup(tmp);
B
Bruce Momjian 已提交
2226
			continue;
2227
		}
M
Marc G. Fournier 已提交
2228 2229
	}

2230
	return 0;
M
Marc G. Fournier 已提交
2231 2232 2233
}


2234 2235
static char *
conninfo_getval(char *keyword)
M
Marc G. Fournier 已提交
2236
{
2237
	PQconninfoOption *option;
M
Marc G. Fournier 已提交
2238

2239 2240 2241 2242
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (!strcmp(option->keyword, keyword))
			return option->val;
M
Marc G. Fournier 已提交
2243 2244
	}

2245
	return NULL;
M
Marc G. Fournier 已提交
2246 2247 2248 2249 2250 2251
}


static void
conninfo_free()
{
2252
	PQconninfoOption *option;
M
Marc G. Fournier 已提交
2253

2254 2255 2256 2257 2258 2259 2260
	for (option = PQconninfoOptions; option->keyword != NULL; option++)
	{
		if (option->val != NULL)
		{
			free(option->val);
			option->val = NULL;
		}
M
Marc G. Fournier 已提交
2261 2262 2263
	}
}

2264
/* =========== accessor functions for PGconn ========= */
B
Bruce Momjian 已提交
2265 2266
const char *
PQdb(const PGconn *conn)
2267
{
2268 2269 2270
	if (!conn)
		return (char *) NULL;
	return conn->dbName;
2271 2272
}

B
Bruce Momjian 已提交
2273 2274
const char *
PQuser(const PGconn *conn)
M
Marc G. Fournier 已提交
2275
{
2276 2277 2278
	if (!conn)
		return (char *) NULL;
	return conn->pguser;
M
Marc G. Fournier 已提交
2279 2280
}

B
Bruce Momjian 已提交
2281 2282
const char *
PQpass(const PGconn *conn)
2283 2284 2285 2286 2287 2288
{
	if (!conn)
		return (char *) NULL;
	return conn->pgpass;
}

B
Bruce Momjian 已提交
2289 2290
const char *
PQhost(const PGconn *conn)
2291
{
2292 2293 2294
	if (!conn)
		return (char *) NULL;
	return conn->pghost;
2295 2296
}

B
Bruce Momjian 已提交
2297 2298
const char *
PQport(const PGconn *conn)
2299
{
2300 2301
	if (!conn)
		return (char *) NULL;
2302
	return conn->pgport;
2303 2304
}

B
Bruce Momjian 已提交
2305 2306
const char *
PQtty(const PGconn *conn)
2307
{
2308 2309 2310
	if (!conn)
		return (char *) NULL;
	return conn->pgtty;
2311 2312
}

B
Bruce Momjian 已提交
2313 2314
const char *
PQoptions(const PGconn *conn)
2315
{
2316 2317
	if (!conn)
		return (char *) NULL;
2318
	return conn->pgoptions;
2319 2320 2321
}

ConnStatusType
B
Bruce Momjian 已提交
2322
PQstatus(const PGconn *conn)
2323
{
2324 2325 2326
	if (!conn)
		return CONNECTION_BAD;
	return conn->status;
2327 2328
}

B
Bruce Momjian 已提交
2329 2330
const char *
PQerrorMessage(const PGconn *conn)
2331
{
B
 
Bruce Momjian 已提交
2332
	static char noConn[] = "PQerrorMessage: conn pointer is NULL\n";
2333

2334
	if (!conn)
B
 
Bruce Momjian 已提交
2335
		return noConn;
2336
	return conn->errorMessage.data;
2337 2338
}

B
Bruce Momjian 已提交
2339
int
B
Bruce Momjian 已提交
2340
PQsocket(const PGconn *conn)
B
Bruce Momjian 已提交
2341 2342 2343 2344 2345 2346
{
	if (!conn)
		return -1;
	return conn->sock;
}

2347
int
B
Bruce Momjian 已提交
2348
PQbackendPID(const PGconn *conn)
2349 2350 2351 2352 2353 2354
{
	if (!conn || conn->status != CONNECTION_OK)
		return 0;
	return conn->be_pid;
}

T
Tatsuo Ishii 已提交
2355 2356 2357 2358 2359 2360 2361 2362
int
PQclientencoding(const PGconn *conn)
{
	if (!conn || conn->status != CONNECTION_OK)
		return -1;
	return conn->client_encoding;
}

2363
void
2364
PQtrace(PGconn *conn, FILE *debug_port)
2365
{
2366 2367 2368 2369 2370
	if (conn == NULL ||
		conn->status == CONNECTION_BAD)
		return;
	PQuntrace(conn);
	conn->Pfdebug = debug_port;
2371 2372
}

2373
void
2374
PQuntrace(PGconn *conn)
2375
{
B
Bruce Momjian 已提交
2376 2377
	/* note: better allow untrace even when connection bad */
	if (conn == NULL)
2378 2379 2380 2381 2382 2383
		return;
	if (conn->Pfdebug)
	{
		fflush(conn->Pfdebug);
		conn->Pfdebug = NULL;
	}
2384
}
B
 
Bruce Momjian 已提交
2385

2386
PQnoticeProcessor
2387
PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
B
 
Bruce Momjian 已提交
2388
{
2389
	PQnoticeProcessor old;
B
 
Bruce Momjian 已提交
2390
	if (conn == NULL)
2391 2392 2393 2394
		return NULL;

	old = conn->noticeHook;
	if (proc) {
B
 
Bruce Momjian 已提交
2395 2396
	conn->noticeHook = proc;
	conn->noticeArg = arg;
2397 2398
	}
	return old;
B
 
Bruce Momjian 已提交
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
}

/*
 * The default notice/error message processor just prints the
 * message on stderr.  Applications can override this if they
 * want the messages to go elsewhere (a window, for example).
 * Note that simply discarding notices is probably a bad idea.
 */

static void
2409
defaultNoticeProcessor(void *arg, const char *message)
B
 
Bruce Momjian 已提交
2410 2411 2412 2413
{
	/* Note: we expect the supplied string to end with a newline already. */
	fprintf(stderr, "%s", message);
}