fe-connect.c 77.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * fe-connect.c
4
 *	  functions related to setting up a connection to the backend
5
 *
6
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/interfaces/libpq/fe-connect.c,v 1.306 2005/05/05 16:40:42 momjian Exp $
12 13 14 15
 *
 *-------------------------------------------------------------------------
 */

16
#include "postgres_fe.h"
17

18
#include <sys/types.h>
19
#include <sys/stat.h>
20 21
#include <fcntl.h>
#include <ctype.h>
Bruce Momjian's avatar
Bruce Momjian committed
22
#include <time.h>
23
#ifndef WIN32_CLIENT_ONLY
24
#include <unistd.h>
25
#endif
26

27 28 29 30
#ifndef HAVE_STRDUP
#include "strdup.h"
#endif

31 32 33
#include "libpq-fe.h"
#include "libpq-int.h"
#include "fe-auth.h"
34
#include "pg_config_paths.h"
35

Bruce Momjian's avatar
Bruce Momjian committed
36 37
#ifdef WIN32
#include "win32.h"
38 39 40
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
41
#define _WIN32_IE 0x0500
42 43 44 45
#ifdef near
#undef near
#endif
#define near
46
#include <shlobj.h>
Bruce Momjian's avatar
Bruce Momjian committed
47
#else
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
48
#include <sys/socket.h>
49
#include <netdb.h>
50
#include <netinet/in.h>
51
#ifdef HAVE_NETINET_TCP_H
52
#include <netinet/tcp.h>
53
#endif
54
#include <arpa/inet.h>
Bruce Momjian's avatar
Bruce Momjian committed
55
#endif
56

57 58 59 60
#ifdef ENABLE_THREAD_SAFETY
#include <pthread.h>
#endif

61
#include "libpq/ip.h"
62
#include "mb/pg_wchar.h"
63

64 65 66 67 68
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif


69
#ifndef WIN32
70
#define PGPASSFILE ".pgpass"
71
#else
72
#define PGPASSFILE "pgpass.conf"
73
#endif
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
74

75 76 77 78 79 80 81
/* fall back options if they are not specified by arguments or defined
   by environment variables */
#define DefaultHost		"localhost"
#define DefaultTty		""
#define DefaultOption	""
#define DefaultAuthtype		  ""
#define DefaultPassword		  ""
82 83 84 85 86
#ifdef USE_SSL
#define DefaultSSLMode	"prefer"
#else
#define DefaultSSLMode	"disable"
#endif
87

88
/* ----------
89
 * Definition of the conninfo parameters and their fallback resources.
90
 *
91 92 93 94
 * 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.
 *
95
 * The value for the username is treated specially in conninfo_parse.
96
 * If the Compiled-in resource is specified as a NULL value, the
97
 * user is determined by fe_getauthname().
98 99 100 101
 *
 * 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:
102 103 104 105 106 107
 *		""		Normal input field
 *		"*"		Password field - hide value
 *		"D"		Debug option - don't show by default
 *
 * PQconninfoOptions[] is a constant static array that we use to initialize
 * a dynamically allocated working copy.  All the "val" fields in
108
 * PQconninfoOptions[] *must* be NULL.	In a working copy, non-null "val"
109 110
 * fields point to malloc'd strings that should be freed when the working
 * array is freed (see PQconninfoFree).
111 112
 * ----------
 */
113
static const PQconninfoOption PQconninfoOptions[] = {
114 115 116 117
	/*
	 * "authtype" is no longer used, so mark it "don't show".  We keep it
	 * in the array so as not to reject conninfo strings from old apps
	 * that might still try to set it.
118
	 */
119
	{"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
120
	"Database-Authtype", "D", 20},
121

Bruce Momjian's avatar
TNS:  
Bruce Momjian committed
122
	{"service", "PGSERVICE", NULL, NULL,
123
	"Database-Service", "", 20},
Bruce Momjian's avatar
TNS:  
Bruce Momjian committed
124

125 126
	{"user", "PGUSER", NULL, NULL,
	"Database-User", "", 20},
127

128
	{"password", "PGPASSWORD", NULL, NULL,
129
	"Database-Password", "*", 20},
130

131
	{"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
132
	"Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
133

134 135
	{"dbname", "PGDATABASE", NULL, NULL,
	"Database-Name", "", 20},
136

137
	{"host", "PGHOST", NULL, NULL,
138
	"Database-Host", "", 40},
139

140
	{"hostaddr", "PGHOSTADDR", NULL, NULL,
141
	"Database-Host-IP-Address", "", 45},
142

143
	{"port", "PGPORT", DEF_PGPORT_STR, NULL,
144
	"Database-Port", "", 6},
145

146 147 148 149
	/*
	 * "tty" is no longer used either, but keep it present for backwards
	 * compatibility.
	 */
150 151
	{"tty", "PGTTY", DefaultTty, NULL,
	"Backend-Debug-TTY", "D", 40},
152

153 154
	{"options", "PGOPTIONS", DefaultOption, NULL,
	"Backend-Debug-Options", "D", 40},
155

Bruce Momjian's avatar
Bruce Momjian committed
156
#ifdef USE_SSL
Bruce Momjian's avatar
Bruce Momjian committed
157

158
	/*
Bruce Momjian's avatar
Bruce Momjian committed
159 160
	 * "requiressl" is deprecated, its purpose having been taken over by
	 * "sslmode". It remains for backwards compatibility.
161
	 */
Bruce Momjian's avatar
Bruce Momjian committed
162
	{"requiressl", "PGREQUIRESSL", "0", NULL,
163
	"Require-SSL", "D", 1},
Bruce Momjian's avatar
Bruce Momjian committed
164 165
#endif

166
	/*
Bruce Momjian's avatar
Bruce Momjian committed
167 168
	 * "sslmode" option is allowed even without client SSL support because
	 * the client can still handle SSL modes "disable" and "allow".
169 170
	 */
	{"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
Bruce Momjian's avatar
Bruce Momjian committed
171
	"SSL-Mode", "", 8},			/* sizeof("disable") == 8 */
172

173
	/* Terminating entry --- MUST BE LAST */
174 175
	{NULL, NULL, NULL, NULL,
	NULL, NULL, 0}
176 177
};

178
static const PQEnvironmentOption EnvironmentOptions[] =
179
{
180
	/* common user-interface settings */
181 182 183 184 185 186
	{
		"PGDATESTYLE", "datestyle"
	},
	{
		"PGTZ", "timezone"
	},
187 188 189
	{
		"PGCLIENTENCODING", "client_encoding"
	},
190
	/* internal performance-related settings */
191 192 193 194
	{
		"PGGEQO", "geqo"
	},
	{
Bruce Momjian's avatar
Bruce Momjian committed
195
		NULL, NULL
196
	}
197 198
};

199

200 201
static bool connectOptions1(PGconn *conn, const char *conninfo);
static bool connectOptions2(PGconn *conn);
202 203
static int	connectDBStart(PGconn *conn);
static int	connectDBComplete(PGconn *conn);
204 205 206 207
static PGconn *makeEmptyPGconn(void);
static void freePGconn(PGconn *conn);
static void closePGconn(PGconn *conn);
static PQconninfoOption *conninfo_parse(const char *conninfo,
208
			   PQExpBuffer errorMessage);
209
static char *conninfo_getval(PQconninfoOption *connOptions,
210
				const char *keyword);
211
static void defaultNoticeReceiver(void *arg, const PGresult *res);
212
static void defaultNoticeProcessor(void *arg, const char *message);
213 214
static int parseServiceInfo(PQconninfoOption *options,
				 PQExpBuffer errorMessage);
215 216
static char *pwdfMatchesString(char *buf, char *token);
static char *PasswordFromFile(char *hostname, char *port, char *dbname,
Bruce Momjian's avatar
Bruce Momjian committed
217
				 char *username);
218 219 220 221 222
static void default_threadlock(int acquire);


/* global variable because fe-auth.c needs to access it */
pgthreadlock_t pg_g_threadlock = default_threadlock;
223

224

225
/*
226
 *		Connecting to a Database
227 228 229 230 231 232 233 234 235 236
 *
 * 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.
 *
237
 * To connect in an asynchronous (non-blocking) manner, use the functions
238 239 240 241 242 243
 * PQconnectStart, and PQconnectPoll.
 *
 * Internally, the static functions connectDBStart, connectDBComplete
 * are part of the connection procedure.
 */

244
/*
245 246
 *		PQconnectdb
 *
247
 * establishes a connection to a postgres backend through the postmaster
248 249
 * using connection information in a string.
 *
250
 * The conninfo string is a white-separated list of
251
 *
252
 *	   option = value
253
 *
254 255 256
 * 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 \'
257
 *
258 259 260 261 262 263 264
 * 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.
265
 */
266
PGconn *
267
PQconnectdb(const char *conninfo)
268
{
269
	PGconn	   *conn = PQconnectStart(conninfo);
270 271 272

	if (conn && conn->status != CONNECTION_BAD)
		(void) connectDBComplete(conn);
273 274 275 276

	return conn;
}

277
/*
278 279 280 281 282 283 284 285
 *		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
286
 * you should not attempt to proceed with this connection.	If the status
287 288 289 290 291 292 293 294
 * 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.
295
 */
296 297
PGconn *
PQconnectStart(const char *conninfo)
298
{
299
	PGconn	   *conn;
300

301
	/*
302 303
	 * Allocate memory for the conn structure
	 */
Bruce Momjian's avatar
Bruce Momjian committed
304
	conn = makeEmptyPGconn();
305
	if (conn == NULL)
306
		return NULL;
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
	/*
	 * Parse the conninfo string
	 */
	if (!connectOptions1(conn, conninfo))
		return conn;

	/*
	 * Compute derived options
	 */
	if (!connectOptions2(conn))
		return conn;

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

	return conn;
}

/*
 *		connectOptions1
 *
 * Internal subroutine to set up connection parameters given an already-
 * created PGconn and a conninfo string.  Derived settings should be
 * processed by calling connectOptions2 next.  (We split them because
 * PQsetdbLogin overrides defaults in between.)
 *
 * Returns true if OK, false if trouble (in which case errorMessage is set
 * and so is conn->status).
 */
static bool
connectOptions1(PGconn *conn, const char *conninfo)
{
	PQconninfoOption *connOptions;
	char	   *tmp;

349
	/*
350
	 * Parse the conninfo string
351
	 */
352 353
	connOptions = conninfo_parse(conninfo, &conn->errorMessage);
	if (connOptions == NULL)
354 355
	{
		conn->status = CONNECTION_BAD;
356
		/* errorMessage is already set */
357
		return false;
358
	}
359 360 361

	/*
	 * Move option values into conn structure
362 363 364
	 *
	 * Don't put anything cute here --- intelligence should be in
	 * connectOptions2 ...
365 366
	 */
	tmp = conninfo_getval(connOptions, "hostaddr");
367
	conn->pghostaddr = tmp ? strdup(tmp) : NULL;
368
	tmp = conninfo_getval(connOptions, "host");
369
	conn->pghost = tmp ? strdup(tmp) : NULL;
370
	tmp = conninfo_getval(connOptions, "port");
371
	conn->pgport = tmp ? strdup(tmp) : NULL;
372
	tmp = conninfo_getval(connOptions, "tty");
373
	conn->pgtty = tmp ? strdup(tmp) : NULL;
374
	tmp = conninfo_getval(connOptions, "options");
375
	conn->pgoptions = tmp ? strdup(tmp) : NULL;
376
	tmp = conninfo_getval(connOptions, "dbname");
Bruce Momjian's avatar
Bruce Momjian committed
377
	conn->dbName = tmp ? strdup(tmp) : NULL;
378
	tmp = conninfo_getval(connOptions, "user");
379
	conn->pguser = tmp ? strdup(tmp) : NULL;
380
	tmp = conninfo_getval(connOptions, "password");
381
	conn->pgpass = tmp ? strdup(tmp) : NULL;
382 383
	tmp = conninfo_getval(connOptions, "connect_timeout");
	conn->connect_timeout = tmp ? strdup(tmp) : NULL;
384 385
	tmp = conninfo_getval(connOptions, "sslmode");
	conn->sslmode = tmp ? strdup(tmp) : NULL;
Bruce Momjian's avatar
Bruce Momjian committed
386 387
#ifdef USE_SSL
	tmp = conninfo_getval(connOptions, "requiressl");
388
	if (tmp && tmp[0] == '1')
389 390 391 392
	{
		/* here warn that the requiressl option is deprecated? */
		if (conn->sslmode)
			free(conn->sslmode);
393
		conn->sslmode = strdup("require");
394
	}
Bruce Momjian's avatar
Bruce Momjian committed
395
#endif
396

397
	/*
398
	 * Free the option info - all is in conn now
399
	 */
400
	PQconninfoFree(connOptions);
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415
	return true;
}

/*
 *		connectOptions2
 *
 * Compute derived connection options after absorbing all user-supplied info.
 *
 * Returns true if OK, false if trouble (in which case errorMessage is set
 * and so is conn->status).
 */
static bool
connectOptions2(PGconn *conn)
{
416 417 418 419 420 421 422 423 424 425 426
	/*
	 * If database name was not given, default it to equal user name
	 */
	if ((conn->dbName == NULL || conn->dbName[0] == '\0')
		&& conn->pguser != NULL)
	{
		if (conn->dbName)
			free(conn->dbName);
		conn->dbName = strdup(conn->pguser);
	}

427 428 429 430 431 432 433 434 435 436 437 438 439
	/*
	 * Supply default password if none given
	 */
	if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
	{
		if (conn->pgpass)
			free(conn->pgpass);
		conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
										conn->dbName, conn->pguser);
		if (conn->pgpass == NULL)
			conn->pgpass = strdup(DefaultPassword);
	}

440
	/*
441 442
	 * Allow unix socket specification in the host name
	 */
443
	if (conn->pghost && is_absolute_path(conn->pghost))
444 445 446 447 448 449 450
	{
		if (conn->pgunixsocket)
			free(conn->pgunixsocket);
		conn->pgunixsocket = conn->pghost;
		conn->pghost = NULL;
	}

451
#ifdef NOT_USED
Bruce Momjian's avatar
Bruce Momjian committed
452

453
	/*
454
	 * parse dbName to get all additional info in it, if any
455
	 */
456
	if (update_db_info(conn) != 0)
457 458
	{
		conn->status = CONNECTION_BAD;
459 460
		/* errorMessage is already set */
		return false;
461
	}
462
#endif
463

464 465 466 467 468 469 470 471 472 473 474 475
	/*
	 * validate sslmode option
	 */
	if (conn->sslmode)
	{
		if (strcmp(conn->sslmode, "disable") != 0
			&& strcmp(conn->sslmode, "allow") != 0
			&& strcmp(conn->sslmode, "prefer") != 0
			&& strcmp(conn->sslmode, "require") != 0)
		{
			conn->status = CONNECTION_BAD;
			printfPQExpBuffer(&conn->errorMessage,
Bruce Momjian's avatar
Bruce Momjian committed
476
						libpq_gettext("invalid sslmode value: \"%s\"\n"),
477 478 479 480 481
							  conn->sslmode);
			return false;
		}

#ifndef USE_SSL
Bruce Momjian's avatar
Bruce Momjian committed
482 483 484 485 486
		switch (conn->sslmode[0])
		{
			case 'a':			/* "allow" */
			case 'p':			/* "prefer" */

487 488 489 490 491 492
				/*
				 * warn user that an SSL connection will never be
				 * negotiated since SSL was not compiled in?
				 */
				break;

Bruce Momjian's avatar
Bruce Momjian committed
493
			case 'r':			/* "require" */
494 495
				conn->status = CONNECTION_BAD;
				printfPQExpBuffer(&conn->errorMessage,
496
								  libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
497 498 499 500 501 502
								  conn->sslmode);
				return false;
		}
#endif
	}
	else
503
		conn->sslmode = strdup(DefaultSSLMode);
504

505
	return true;
506 507
}

508
/*
509 510
 *		PQconndefaults
 *
511
 * Parse an empty string like PQconnectdb() would do and return the
512 513 514 515 516 517
 * working connection options array.
 *
 * Using this function, an application may determine all possible options
 * and their current default values.
 *
 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
518
 * and should be freed when no longer needed via PQconninfoFree().	(In prior
519 520 521
 * versions, the returned array was static, but that's not thread-safe.)
 * Pre-7.0 applications that use this function will see a small memory leak
 * until they are updated to call PQconninfoFree.
522
 */
523
PQconninfoOption *
524
PQconndefaults(void)
525
{
526
	PQExpBufferData errorBuf;
527
	PQconninfoOption *connOptions;
528

529
	initPQExpBuffer(&errorBuf);
530
	connOptions = conninfo_parse("", &errorBuf);
531
	termPQExpBuffer(&errorBuf);
532
	return connOptions;
533 534
}

535
/* ----------------
536
 *		PQsetdbLogin
537
 *
538
 * establishes a connection to a postgres backend through the postmaster
539 540 541
 * at the specified host and port.
 *
 * returns a PGconn* which is needed for all subsequent libpq calls
542
 *
543 544
 * if the status field of the connection returned is CONNECTION_BAD,
 * then only the errorMessage is likely to be useful.
545 546
 * ----------------
 */
547
PGconn *
548 549 550
PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
			 const char *pgtty, const char *dbName, const char *login,
			 const char *pwd)
551
{
552
	PGconn	   *conn;
553

554 555 556
	/*
	 * Allocate memory for the conn structure
	 */
Bruce Momjian's avatar
Bruce Momjian committed
557
	conn = makeEmptyPGconn();
558
	if (conn == NULL)
559
		return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
560

561 562 563 564 565 566
	/*
	 * Parse an empty conninfo string in order to set up the same defaults
	 * that PQconnectdb() would use.
	 */
	if (!connectOptions1(conn, ""))
		return conn;
567

568
	/*
569
	 * Absorb specified options into conn structure, overriding defaults
570
	 */
571
	if (pghost && pghost[0] != '\0')
572
	{
573 574 575
		if (conn->pghost)
			free(conn->pghost);
		conn->pghost = strdup(pghost);
576
	}
577

578
	if (pgport && pgport[0] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
579
	{
580 581 582
		if (conn->pgport)
			free(conn->pgport);
		conn->pgport = strdup(pgport);
Bruce Momjian's avatar
Bruce Momjian committed
583
	}
584

585
	if (pgoptions && pgoptions[0] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
586
	{
587 588
		if (conn->pgoptions)
			free(conn->pgoptions);
Bruce Momjian's avatar
Bruce Momjian committed
589
		conn->pgoptions = strdup(pgoptions);
590
	}
591

592
	if (pgtty && pgtty[0] != '\0')
593
	{
594 595 596
		if (conn->pgtty)
			free(conn->pgtty);
		conn->pgtty = strdup(pgtty);
597
	}
598

599
	if (dbName && dbName[0] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
600
	{
601 602 603
		if (conn->dbName)
			free(conn->dbName);
		conn->dbName = strdup(dbName);
Bruce Momjian's avatar
Bruce Momjian committed
604
	}
605

606
	if (login && login[0] != '\0')
Bruce Momjian's avatar
Bruce Momjian committed
607
	{
608 609 610
		if (conn->pguser)
			free(conn->pguser);
		conn->pguser = strdup(login);
Bruce Momjian's avatar
Bruce Momjian committed
611
	}
612

613 614 615 616
	if (pwd && pwd[0] != '\0')
	{
		if (conn->pgpass)
			free(conn->pgpass);
617
		conn->pgpass = strdup(pwd);
618
	}
619

620 621 622 623 624
	/*
	 * Compute derived options
	 */
	if (!connectOptions2(conn))
		return conn;
Bruce Momjian's avatar
Bruce Momjian committed
625

626 627 628 629 630
	/*
	 * Connect to the database
	 */
	if (connectDBStart(conn))
		(void) connectDBComplete(conn);
631

632
	return conn;
633 634
}

635

636
#ifdef NOT_USED					/* because it's broken */
637 638
/*
 * update_db_info -
639
 * get all additional info out of dbName
640 641 642 643
 */
static int
update_db_info(PGconn *conn)
{
644 645
	char	   *tmp,
			   *tmp2,
646 647
			   *old = conn->dbName;

648 649 650 651
	if (strchr(conn->dbName, '@') != NULL)
	{
		/* old style: dbname[@server][:port] */
		tmp = strrchr(conn->dbName, ':');
652
		if (tmp != NULL)		/* port number given */
653
		{
654 655
			if (conn->pgport)
				free(conn->pgport);
656
			conn->pgport = strdup(tmp + 1);
657 658
			*tmp = '\0';
		}
659

660
		tmp = strrchr(conn->dbName, '@');
661
		if (tmp != NULL)		/* host name given */
662
		{
663 664
			if (conn->pghost)
				free(conn->pghost);
665
			conn->pghost = strdup(tmp + 1);
666 667
			*tmp = '\0';
		}
668

669 670 671 672 673
		conn->dbName = strdup(old);
		free(old);
	}
	else
	{
674 675
		int			offset;

676
		/*
677 678
		 * only allow protocols tcp and unix
		 */
679 680 681 682
		if (strncmp(conn->dbName, "tcp:", 4) == 0)
			offset = 4;
		else if (strncmp(conn->dbName, "unix:", 5) == 0)
			offset = 5;
683 684 685
		else
			return 0;

686 687
		if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
		{
688

689
			/*-------
690
			 * new style:
691
			 *	<tcp|unix>:postgresql://server[:port|:/unixsocket/path:]
692 693
			 *	[/db name][?options]
			 *-------
694
			 */
695
			offset += strlen("postgresql://");
696

697
			tmp = strrchr(conn->dbName + offset, '?');
698
			if (tmp != NULL)	/* options given */
699
			{
700 701
				if (conn->pgoptions)
					free(conn->pgoptions);
702
				conn->pgoptions = strdup(tmp + 1);
703 704
				*tmp = '\0';
			}
705

706
			tmp = last_dir_separator(conn->dbName + offset);
707
			if (tmp != NULL)	/* database name given */
708
			{
709 710
				if (conn->dbName)
					free(conn->dbName);
711
				conn->dbName = strdup(tmp + 1);
712 713 714 715
				*tmp = '\0';
			}
			else
			{
716 717 718 719
				/*
				 * Why do we default only this value from the environment
				 * again?
				 */
720
				if ((tmp = getenv("PGDATABASE")) != NULL)
721 722 723
				{
					if (conn->dbName)
						free(conn->dbName);
724
					conn->dbName = strdup(tmp);
725
				}
726
				else if (conn->pguser)
727 728 729
				{
					if (conn->dbName)
						free(conn->dbName);
730
					conn->dbName = strdup(conn->pguser);
731
				}
732
			}
733

734
			tmp = strrchr(old + offset, ':');
735
			if (tmp != NULL)	/* port number or Unix socket path given */
736 737
			{
				*tmp = '\0';
738 739 740 741 742
				if ((tmp2 = strchr(tmp + 1, ':')) != NULL)
				{
					if (strncmp(old, "unix:", 5) != 0)
					{
						printfPQExpBuffer(&conn->errorMessage,
743 744 745
										  libpq_gettext("connectDBStart() -- "
										  "socket name can only be specified with "
										  "non-TCP\n"));
746
						return 1;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
					}
					*tmp2 = '\0';
					if (conn->pgunixsocket)
						free(conn->pgunixsocket);
					conn->pgunixsocket = strdup(tmp + 1);
				}
				else
				{
					if (conn->pgport)
						free(conn->pgport);
					conn->pgport = strdup(tmp + 1);
					if (conn->pgunixsocket)
						free(conn->pgunixsocket);
					conn->pgunixsocket = NULL;
				}
762
			}
763

764 765
			if (strncmp(old, "unix:", 5) == 0)
			{
766 767
				if (conn->pghost)
					free(conn->pghost);
768 769 770
				conn->pghost = NULL;
				if (strcmp(old + offset, "localhost") != 0)
				{
771
					printfPQExpBuffer(&conn->errorMessage,
772
									  libpq_gettext("connectDBStart() -- "
773
									  "non-TCP access only possible on "
774
									  "localhost\n"));
775
					return 1;
776 777
				}
			}
778
			else
779 780 781
			{
				if (conn->pghost)
					free(conn->pghost);
782
				conn->pghost = strdup(old + offset);
783
			}
784 785 786
			free(old);
		}
	}
787

788 789
	return 0;
}
790
#endif   /* NOT_USED */
791

792

793 794 795 796 797 798 799 800 801
/* ----------
 * connectNoDelay -
 * Sets the TCP_NODELAY socket option.
 * Returns 1 if successful, 0 if not.
 * ----------
 */
static int
connectNoDelay(PGconn *conn)
{
Bruce Momjian's avatar
Bruce Momjian committed
802
#ifdef	TCP_NODELAY
803 804
	int			on = 1;

805
	if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
806
				   (char *) &on,
807 808
				   sizeof(on)) < 0)
	{
Bruce Momjian's avatar
Bruce Momjian committed
809
		char		sebuf[256];
810

811
		printfPQExpBuffer(&conn->errorMessage,
812
		libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
Bruce Momjian's avatar
Bruce Momjian committed
813
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
814 815
		return 0;
	}
Bruce Momjian's avatar
Bruce Momjian committed
816
#endif
817 818 819 820 821

	return 1;
}


822 823 824 825 826 827
/* ----------
 * connectFailureMessage -
 * create a friendly error message on connection failure.
 * ----------
 */
static void
828
connectFailureMessage(PGconn *conn, int errorno)
829
{
Bruce Momjian's avatar
Bruce Momjian committed
830
	char		sebuf[256];
Bruce Momjian's avatar
Bruce Momjian committed
831

832 833 834
#ifdef HAVE_UNIX_SOCKETS
	if (IS_AF_UNIX(conn->raddr.addr.ss_family))
	{
Bruce Momjian's avatar
Bruce Momjian committed
835
		char		service[NI_MAXHOST];
836 837 838 839 840

		getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
						NULL, 0,
						service, sizeof(service),
						NI_NUMERICSERV);
841
		printfPQExpBuffer(&conn->errorMessage,
842
						  libpq_gettext(
843 844 845 846
									  "could not connect to server: %s\n"
						"\tIs the server running locally and accepting\n"
						  "\tconnections on Unix domain socket \"%s\"?\n"
										),
847 848 849
						  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
						  service);
	}
850
	else
851 852
#endif   /* HAVE_UNIX_SOCKETS */
	{
853
		printfPQExpBuffer(&conn->errorMessage,
854
						  libpq_gettext(
855
									  "could not connect to server: %s\n"
Bruce Momjian's avatar
Bruce Momjian committed
856
				 "\tIs the server running on host \"%s\" and accepting\n"
857 858
									 "\tTCP/IP connections on port %s?\n"
										),
859
						  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
860 861 862 863
						  conn->pghostaddr
						  ? conn->pghostaddr
						  : (conn->pghost
							 ? conn->pghost
864
							 : "???"),
865
						  conn->pgport);
866
	}
867 868 869
}


870 871
/* ----------
 * connectDBStart -
872 873
 *		Begin the process of making a connection to the backend.
 *
874 875 876 877 878
 * Returns 1 if successful, 0 if not.
 * ----------
 */
static int
connectDBStart(PGconn *conn)
879
{
880
	int			portnum;
Bruce Momjian's avatar
Bruce Momjian committed
881 882 883
	char		portstr[128];
	struct addrinfo *addrs = NULL;
	struct addrinfo hint;
884
	const char *node;
885
	int			ret;
Bruce Momjian's avatar
Bruce Momjian committed
886

887 888
	if (!conn)
		return 0;
889

890 891 892 893
	/* Ensure our buffers are empty */
	conn->inStart = conn->inCursor = conn->inEnd = 0;
	conn->outCount = 0;

894
	/*
895
	 * Determine the parameters to pass to getaddrinfo_all.
896 897
	 */

898 899 900
	/* Initialize hint structure */
	MemSet(&hint, 0, sizeof(hint));
	hint.ai_socktype = SOCK_STREAM;
Bruce Momjian's avatar
Bruce Momjian committed
901
	hint.ai_family = AF_UNSPEC;
902

903
	/* Set up port number as a string */
904 905 906 907 908 909
	if (conn->pgport != NULL && conn->pgport[0] != '\0')
		portnum = atoi(conn->pgport);
	else
		portnum = DEF_PGPORT;
	snprintf(portstr, sizeof(portstr), "%d", portnum);

910 911
	if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
	{
912
		/* Using pghostaddr avoids a hostname lookup */
913 914
		node = conn->pghostaddr;
		hint.ai_family = AF_UNSPEC;
915
		hint.ai_flags = AI_NUMERICHOST;
916
	}
917 918
	else if (conn->pghost != NULL && conn->pghost[0] != '\0')
	{
919
		/* Using pghost, so we have to look-up the hostname */
920 921
		node = conn->pghost;
		hint.ai_family = AF_UNSPEC;
922
	}
923 924
	else
	{
925
#ifdef HAVE_UNIX_SOCKETS
926
		/* pghostaddr and pghost are NULL, so use Unix domain socket */
Bruce Momjian's avatar
Bruce Momjian committed
927
		node = NULL;
928
		hint.ai_family = AF_UNIX;
Bruce Momjian's avatar
Bruce Momjian committed
929
		UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
930 931 932 933
#else
		/* Without Unix sockets, default to localhost instead */
		node = "localhost";
		hint.ai_family = AF_UNSPEC;
Bruce Momjian's avatar
Bruce Momjian committed
934
#endif   /* HAVE_UNIX_SOCKETS */
935
	}
936

937 938 939
	/* Use getaddrinfo_all() to resolve the address */
	ret = getaddrinfo_all(node, portstr, &hint, &addrs);
	if (ret || !addrs)
940
	{
941 942
		if (node)
			printfPQExpBuffer(&conn->errorMessage,
943
							  libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
944 945 946
							  node, gai_strerror(ret));
		else
			printfPQExpBuffer(&conn->errorMessage,
947 948
							  libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
							  portstr, gai_strerror(ret));
949 950
		if (addrs)
			freeaddrinfo_all(hint.ai_family, addrs);
951 952 953
		goto connect_errReturn;
	}

954 955
#ifdef USE_SSL
	/* setup values based on SSL mode */
Bruce Momjian's avatar
Bruce Momjian committed
956
	if (conn->sslmode[0] == 'd')	/* "disable" */
957
		conn->allow_ssl_try = false;
Bruce Momjian's avatar
Bruce Momjian committed
958
	else if (conn->sslmode[0] == 'a')	/* "allow" */
959 960 961
		conn->wait_ssl_try = true;
#endif

962
	/*
963
	 * Set up to try to connect, with protocol 3.0 as the first attempt.
964
	 */
965 966
	conn->addrlist = addrs;
	conn->addr_cur = addrs;
967
	conn->addrlist_family = hint.ai_family;
Bruce Momjian's avatar
Bruce Momjian committed
968
	conn->pversion = PG_PROTOCOL(3, 0);
969
	conn->status = CONNECTION_NEEDED;
970 971

	/*
Bruce Momjian's avatar
Bruce Momjian committed
972 973 974 975 976 977
	 * The code for processing CONNECTION_NEEDED state is in
	 * PQconnectPoll(), so that it can easily be re-executed if needed
	 * again during the asynchronous startup process.  However, we must
	 * run it once here, because callers expect a success return from this
	 * routine to mean that we are in PGRES_POLLING_WRITING connection
	 * state.
978
	 */
979 980
	if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
		return 1;
981

982 983
connect_errReturn:
	if (conn->sock >= 0)
984
	{
985
		pqsecure_close(conn);
986 987
		closesocket(conn->sock);
		conn->sock = -1;
988
	}
989 990 991
	conn->status = CONNECTION_BAD;
	return 0;
}
992

993

994
/*
995 996 997 998 999 1000 1001 1002 1003
 *		connectDBComplete
 *
 * Block and complete a connection.
 *
 * Returns 1 on success, 0 on failure.
 */
static int
connectDBComplete(PGconn *conn)
{
1004
	PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1005
	time_t		finish_time = ((time_t) -1);
1006

1007 1008
	if (conn == NULL || conn->status == CONNECTION_BAD)
		return 0;
1009

Bruce Momjian's avatar
Bruce Momjian committed
1010
	/*
1011
	 * Set up a time limit, if connect_timeout isn't zero.
Bruce Momjian's avatar
Bruce Momjian committed
1012 1013
	 */
	if (conn->connect_timeout != NULL)
1014
	{
1015
		int			timeout = atoi(conn->connect_timeout);
1016

1017
		if (timeout > 0)
1018
		{
1019 1020 1021 1022
			/*
			 * Rounding could cause connection to fail; need at least 2
			 * secs
			 */
1023 1024 1025 1026
			if (timeout < 2)
				timeout = 2;
			/* calculate the finish time based on start + timeout */
			finish_time = time(NULL) + timeout;
1027 1028 1029
		}
	}

1030
	for (;;)
1031
	{
1032
		/*
1033 1034 1035
		 * Wait, if necessary.	Note that the initial state (just after
		 * PQconnectStart) is to wait for the socket to select for
		 * writing.
1036
		 */
1037
		switch (flag)
1038
		{
1039
			case PGRES_POLLING_OK:
1040
				return 1;		/* success! */
1041

1042
			case PGRES_POLLING_READING:
1043
				if (pqWaitTimed(1, 0, conn, finish_time))
1044 1045 1046 1047
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
1048 1049 1050
				break;

			case PGRES_POLLING_WRITING:
1051
				if (pqWaitTimed(0, 1, conn, finish_time))
1052 1053 1054 1055
				{
					conn->status = CONNECTION_BAD;
					return 0;
				}
1056 1057 1058 1059 1060 1061
				break;

			default:
				/* Just in case we failed to set it in PQconnectPoll */
				conn->status = CONNECTION_BAD;
				return 0;
1062
		}
1063

1064 1065 1066 1067
		/*
		 * Now try to advance the state machine.
		 */
		flag = PQconnectPoll(conn);
1068
	}
1069 1070 1071 1072 1073 1074 1075 1076
}

/* ----------------
 *		PQconnectPoll
 *
 * Poll an asynchronous connection.
 *
 * Returns a PostgresPollingStatusType.
1077 1078
 * Before calling this function, use select(2) to determine when data
 * has arrived..
1079
 *
1080 1081 1082 1083 1084 1085
 * 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:
 *
1086 1087 1088
 *	 o	If you call PQtrace, ensure that the stream object into which you trace
 *		will not block.
 *	 o	If you do not supply an IP address for the remote host (i.e. you
1089
 *		supply a host name instead) then PQconnectStart will block on
1090 1091 1092 1093 1094
 *		gethostbyname.	You will be fine if using Unix sockets (i.e. by
 *		supplying neither a host name nor a host address).
 *	 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.
1095
 *
1096 1097
 * ----------------
 */
1098 1099 1100 1101
PostgresPollingStatusType
PQconnectPoll(PGconn *conn)
{
	PGresult   *res;
1102
	char		sebuf[256];
1103

1104 1105 1106 1107 1108 1109
	if (conn == NULL)
		return PGRES_POLLING_FAILED;

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

1119
			/* These are reading states */
1120 1121
		case CONNECTION_AWAITING_RESPONSE:
		case CONNECTION_AUTH_OK:
1122 1123 1124
			{
				/* Load waiting data */
				int			n = pqReadData(conn);
1125

1126 1127 1128 1129 1130 1131 1132
				if (n < 0)
					goto error_return;
				if (n == 0)
					return PGRES_POLLING_READING;

				break;
			}
1133

1134
			/* These are writing states, so we just proceed. */
1135 1136
		case CONNECTION_STARTED:
		case CONNECTION_MADE:
1137
			break;
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147
			/* We allow pqSetenvPoll to decide whether to proceed. */
		case CONNECTION_SETENV:
			break;

			/* Special cases: proceed without waiting. */
		case CONNECTION_SSL_STARTUP:
		case CONNECTION_NEEDED:
			break;

1148 1149
		default:
			printfPQExpBuffer(&conn->errorMessage,
1150
							  libpq_gettext(
1151 1152 1153
											"invalid connection state, "
							 "probably indicative of memory corruption\n"
											));
1154 1155 1156 1157
			goto error_return;
	}


1158
keep_going:						/* We will come back to here until there
1159
								 * is nothing left to do. */
1160
	switch (conn->status)
1161
	{
1162 1163 1164 1165
		case CONNECTION_NEEDED:
			{
				/*
				 * Try to initiate a connection to one of the addresses
1166
				 * returned by getaddrinfo_all().  conn->addr_cur is the
1167
				 * next one to try.  We fail when we run out of addresses
Bruce Momjian's avatar
Bruce Momjian committed
1168 1169
				 * (reporting the error returned for the *last*
				 * alternative, which may not be what users expect :-().
1170 1171 1172 1173 1174 1175
				 */
				while (conn->addr_cur != NULL)
				{
					struct addrinfo *addr_cur = conn->addr_cur;

					/* Remember current address for possible error msg */
1176
					memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1177
						   addr_cur->ai_addrlen);
1178
					conn->raddr.salen = addr_cur->ai_addrlen;
1179 1180

					/* Open a socket */
1181
					conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1182 1183 1184
					if (conn->sock < 0)
					{
						/*
Bruce Momjian's avatar
Bruce Momjian committed
1185 1186
						 * ignore socket() failure if we have more
						 * addresses to try
1187 1188 1189 1190 1191 1192 1193
						 */
						if (addr_cur->ai_next != NULL)
						{
							conn->addr_cur = addr_cur->ai_next;
							continue;
						}
						printfPQExpBuffer(&conn->errorMessage,
Bruce Momjian's avatar
Bruce Momjian committed
1194 1195
						  libpq_gettext("could not create socket: %s\n"),
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1196 1197 1198 1199
						break;
					}

					/*
Bruce Momjian's avatar
Bruce Momjian committed
1200
					 * Select socket options: no delay of outgoing data
1201 1202
					 * for TCP sockets, nonblock mode, close-on-exec.
					 * Fail if any of this fails.
1203
					 */
Bruce Momjian's avatar
Bruce Momjian committed
1204
					if (!IS_AF_UNIX(addr_cur->ai_family))
1205 1206
					{
						if (!connectNoDelay(conn))
Bruce Momjian's avatar
Bruce Momjian committed
1207 1208 1209 1210 1211 1212
						{
							closesocket(conn->sock);
							conn->sock = -1;
							conn->addr_cur = addr_cur->ai_next;
							continue;
						}
1213
					}
1214
					if (!pg_set_noblock(conn->sock))
Bruce Momjian's avatar
Bruce Momjian committed
1215
					{
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
						printfPQExpBuffer(&conn->errorMessage,
										  libpq_gettext("could not set socket to non-blocking mode: %s\n"),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
						closesocket(conn->sock);
						conn->sock = -1;
						conn->addr_cur = addr_cur->ai_next;
						continue;
					}

#ifdef F_SETFD
					if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
					{
						printfPQExpBuffer(&conn->errorMessage,
										  libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
										  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
Bruce Momjian's avatar
Bruce Momjian committed
1231 1232 1233 1234 1235
						closesocket(conn->sock);
						conn->sock = -1;
						conn->addr_cur = addr_cur->ai_next;
						continue;
					}
1236
#endif /* F_SETFD */
Bruce Momjian's avatar
Bruce Momjian committed
1237

1238
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1239 1240 1241
					 * Start/make connection.  This should not block,
					 * since we are in nonblock mode.  If it does, well,
					 * too bad.
1242
					 */
Bruce Momjian's avatar
Bruce Momjian committed
1243
			retry_connect:
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
					if (connect(conn->sock, addr_cur->ai_addr,
								addr_cur->ai_addrlen) < 0)
					{
						if (SOCK_ERRNO == EINTR)
							/* Interrupted system call - just try again */
							goto retry_connect;
						if (SOCK_ERRNO == EINPROGRESS ||
							SOCK_ERRNO == EWOULDBLOCK ||
							SOCK_ERRNO == 0)
						{
							/*
							 * This is fine - we're in non-blocking mode,
							 * and the connection is in progress.  Tell
							 * caller to wait for write-ready on socket.
							 */
							conn->status = CONNECTION_STARTED;
							return PGRES_POLLING_WRITING;
						}
						/* otherwise, trouble */
					}
					else
					{
						/*
						 * Hm, we're connected already --- seems the
Bruce Momjian's avatar
Bruce Momjian committed
1268 1269
						 * "nonblock connection" wasn't.  Advance the
						 * state machine and go do the next stuff.
1270 1271 1272 1273
						 */
						conn->status = CONNECTION_STARTED;
						goto keep_going;
					}
Bruce Momjian's avatar
Bruce Momjian committed
1274

1275 1276 1277
					/*
					 * This connection failed --- set up error report,
					 * then close socket (do it this way in case close()
Bruce Momjian's avatar
Bruce Momjian committed
1278 1279 1280
					 * affects the value of errno...).	We will ignore the
					 * connect() failure and keep going if there are more
					 * addresses.
1281 1282 1283 1284 1285 1286 1287
					 */
					connectFailureMessage(conn, SOCK_ERRNO);
					if (conn->sock >= 0)
					{
						closesocket(conn->sock);
						conn->sock = -1;
					}
Bruce Momjian's avatar
Bruce Momjian committed
1288

1289 1290 1291 1292
					/*
					 * Try the next address, if any.
					 */
					conn->addr_cur = addr_cur->ai_next;
Bruce Momjian's avatar
Bruce Momjian committed
1293
				}				/* loop over addresses */
1294 1295 1296 1297 1298 1299 1300 1301

				/*
				 * Ooops, no more addresses.  An appropriate error message
				 * is already set up, so just set the right status.
				 */
				goto error_return;
			}

1302
		case CONNECTION_STARTED:
1303
			{
1304
				int			optval;
Bruce Momjian's avatar
Bruce Momjian committed
1305
				ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1306 1307 1308

				/*
				 * Write ready, since we've made it here, so the
1309
				 * connection has been made ... or has failed.
1310
				 */
1311

1312
				/*
1313 1314
				 * Now check (using getsockopt) that there is not an error
				 * state waiting for us on the socket.
1315
				 */
1316 1317

				if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1318
							   (char *) &optval, &optlen) == -1)
1319 1320
				{
					printfPQExpBuffer(&conn->errorMessage,
1321
									  libpq_gettext("could not get socket error status: %s\n"),
Bruce Momjian's avatar
Bruce Momjian committed
1322
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1323 1324 1325 1326 1327 1328 1329 1330 1331
					goto error_return;
				}
				else if (optval != 0)
				{
					/*
					 * When using a nonblocking connect, we will typically
					 * see connect failures at this point, so provide a
					 * friendly error message.
					 */
1332
					connectFailureMessage(conn, optval);
Bruce Momjian's avatar
Bruce Momjian committed
1333

1334 1335
					/*
					 * If more addresses remain, keep trying, just as in
Bruce Momjian's avatar
Bruce Momjian committed
1336 1337
					 * the case where connect() returned failure
					 * immediately.
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
					 */
					if (conn->addr_cur->ai_next != NULL)
					{
						if (conn->sock >= 0)
						{
							closesocket(conn->sock);
							conn->sock = -1;
						}
						conn->addr_cur = conn->addr_cur->ai_next;
						conn->status = CONNECTION_NEEDED;
						goto keep_going;
					}
1350 1351 1352 1353
					goto error_return;
				}

				/* Fill in the client address */
Bruce Momjian's avatar
Bruce Momjian committed
1354
				conn->laddr.salen = sizeof(conn->laddr.addr);
Bruce Momjian's avatar
Bruce Momjian committed
1355 1356 1357
				if (getsockname(conn->sock,
								(struct sockaddr *) & conn->laddr.addr,
								&conn->laddr.salen) < 0)
1358 1359
				{
					printfPQExpBuffer(&conn->errorMessage,
Bruce Momjian's avatar
Bruce Momjian committed
1360 1361
									  libpq_gettext("could not get client address from socket: %s\n"),
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1362 1363 1364
					goto error_return;
				}

1365 1366 1367
				/*
				 * Make sure we can write before advancing to next step.
				 */
1368 1369
				conn->status = CONNECTION_MADE;
				return PGRES_POLLING_WRITING;
1370 1371
			}

1372
		case CONNECTION_MADE:
1373
			{
Bruce Momjian's avatar
Bruce Momjian committed
1374 1375
				char	   *startpacket;
				int			packetlen;
1376

1377
#ifdef USE_SSL
Bruce Momjian's avatar
Bruce Momjian committed
1378

1379
				/*
Bruce Momjian's avatar
Bruce Momjian committed
1380 1381 1382
				 * If SSL is enabled and we haven't already got it
				 * running, request it instead of sending the startup
				 * message.
1383
				 */
1384
				if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1385 1386 1387 1388
				{
					/* Don't bother requesting SSL over a Unix socket */
					conn->allow_ssl_try = false;
				}
1389 1390
				if (conn->allow_ssl_try && !conn->wait_ssl_try &&
					conn->ssl == NULL)
1391 1392 1393 1394 1395 1396
				{
					ProtocolVersion pv;

					/*
					 * Send the SSL request packet.
					 *
Bruce Momjian's avatar
Bruce Momjian committed
1397 1398 1399
					 * Theoretically, this could block, but it really
					 * shouldn't since we only got here if the socket is
					 * write-ready.
1400 1401 1402 1403 1404 1405
					 */
					pv = htonl(NEGOTIATE_SSL_CODE);
					if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
					{
						printfPQExpBuffer(&conn->errorMessage,
										  libpq_gettext("could not send SSL negotiation packet: %s\n"),
Bruce Momjian's avatar
Bruce Momjian committed
1406
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1407 1408 1409 1410 1411 1412
						goto error_return;
					}
					/* Ok, wait for response */
					conn->status = CONNECTION_SSL_STARTUP;
					return PGRES_POLLING_READING;
				}
Bruce Momjian's avatar
Bruce Momjian committed
1413
#endif   /* USE_SSL */
1414

1415
				/*
1416
				 * Build the startup packet.
1417
				 */
1418 1419
				if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
					startpacket = pqBuildStartupPacket3(conn, &packetlen,
Bruce Momjian's avatar
Bruce Momjian committed
1420
													 EnvironmentOptions);
1421 1422
				else
					startpacket = pqBuildStartupPacket2(conn, &packetlen,
Bruce Momjian's avatar
Bruce Momjian committed
1423
													 EnvironmentOptions);
1424 1425 1426 1427 1428 1429
				if (!startpacket)
				{
					printfPQExpBuffer(&conn->errorMessage,
									  libpq_gettext("out of memory\n"));
					goto error_return;
				}
1430

1431 1432 1433 1434 1435 1436
				/*
				 * Send the startup packet.
				 *
				 * Theoretically, this could block, but it really shouldn't
				 * since we only got here if the socket is write-ready.
				 */
1437
				if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1438 1439
				{
					printfPQExpBuffer(&conn->errorMessage,
1440
					libpq_gettext("could not send startup packet: %s\n"),
Bruce Momjian's avatar
Bruce Momjian committed
1441
						SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1442
					free(startpacket);
1443 1444
					goto error_return;
				}
1445

1446 1447
				free(startpacket);

1448
				conn->status = CONNECTION_AWAITING_RESPONSE;
1449 1450 1451
				return PGRES_POLLING_READING;
			}

1452
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1453 1454
			 * Handle SSL negotiation: wait for postmaster messages and
			 * respond as necessary.
1455 1456 1457 1458 1459 1460 1461
			 */
		case CONNECTION_SSL_STARTUP:
			{
#ifdef USE_SSL
				PostgresPollingStatusType pollres;

				/*
Bruce Momjian's avatar
Bruce Momjian committed
1462
				 * On first time through, get the postmaster's response to
1463
				 * our SSL negotiation packet.
1464 1465 1466
				 */
				if (conn->ssl == NULL)
				{
1467 1468 1469 1470 1471
					/*
					 * We use pqReadData here since it has the logic to
					 * distinguish no-data-yet from connection closure.
					 * Since conn->ssl isn't set, a plain recv() will occur.
					 */
1472
					char		SSLok;
1473
					int			rdresult;
1474

1475 1476
					rdresult = pqReadData(conn);
					if (rdresult < 0)
1477
					{
1478
						/* errorMessage is already filled in */
1479 1480
						goto error_return;
					}
1481 1482
					if (rdresult == 0)
					{
1483 1484
						/* caller failed to wait for data */
						return PGRES_POLLING_READING;
1485 1486 1487 1488 1489 1490 1491 1492
					}
					if (pqGetc(&SSLok, conn) < 0)
					{
						/* should not happen really */
						return PGRES_POLLING_READING;
					}
					/* mark byte consumed */
					conn->inStart = conn->inCursor;
1493 1494 1495 1496 1497 1498 1499 1500
					if (SSLok == 'S')
					{
						/* Do one-time setup; this creates conn->ssl */
						if (pqsecure_initialize(conn) == -1)
							goto error_return;
					}
					else if (SSLok == 'N')
					{
Bruce Momjian's avatar
Bruce Momjian committed
1501
						if (conn->sslmode[0] == 'r')	/* "require" */
1502 1503 1504 1505 1506
						{
							/* Require SSL, but server does not want it */
							printfPQExpBuffer(&conn->errorMessage,
											  libpq_gettext("server does not support SSL, but SSL was required\n"));
							goto error_return;
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
						}
						/* Otherwise, proceed with normal startup */
						conn->allow_ssl_try = false;
						conn->status = CONNECTION_MADE;
						return PGRES_POLLING_WRITING;
					}
					else if (SSLok == 'E')
					{
						/* Received error - probably protocol mismatch */
						if (conn->Pfdebug)
1517
							fprintf(conn->Pfdebug, libpq_gettext("Postmaster reports error, attempting fallback to pre-7.0.\n"));
Bruce Momjian's avatar
Bruce Momjian committed
1518
						if (conn->sslmode[0] == 'r')	/* "require" */
1519 1520 1521 1522 1523
						{
							/* Require SSL, but server is too old */
							printfPQExpBuffer(&conn->errorMessage,
											  libpq_gettext("server does not support SSL, but SSL was required\n"));
							goto error_return;
1524 1525 1526 1527
						}
						/* Otherwise, try again without SSL */
						conn->allow_ssl_try = false;
						/* Assume it ain't gonna handle protocol 3, either */
Bruce Momjian's avatar
Bruce Momjian committed
1528
						conn->pversion = PG_PROTOCOL(2, 0);
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
						/* Must drop the old connection */
						closesocket(conn->sock);
						conn->sock = -1;
						conn->status = CONNECTION_NEEDED;
						goto keep_going;
					}
					else
					{
						printfPQExpBuffer(&conn->errorMessage,
										  libpq_gettext("received invalid response to SSL negotiation: %c\n"),
										  SSLok);
						goto error_return;
					}
				}
Bruce Momjian's avatar
Bruce Momjian committed
1543

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
				/*
				 * Begin or continue the SSL negotiation process.
				 */
				pollres = pqsecure_open_client(conn);
				if (pollres == PGRES_POLLING_OK)
				{
					/* SSL handshake done, ready to send startup packet */
					conn->status = CONNECTION_MADE;
					return PGRES_POLLING_WRITING;
				}
				return pollres;
Bruce Momjian's avatar
Bruce Momjian committed
1555
#else							/* !USE_SSL */
1556 1557
				/* can't get here */
				goto error_return;
Bruce Momjian's avatar
Bruce Momjian committed
1558
#endif   /* USE_SSL */
1559 1560 1561 1562
			}

			/*
			 * Handle authentication exchange: wait for postmaster
1563 1564 1565
			 * messages and respond as necessary.
			 */
		case CONNECTION_AWAITING_RESPONSE:
1566
			{
1567
				char		beresp;
1568 1569
				int			msgLength;
				int			avail;
1570 1571 1572 1573 1574 1575 1576 1577 1578
				AuthRequest areq;

				/*
				 * 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).
				 */
				conn->inCursor = conn->inStart;

1579
				/* Read type byte */
1580
				if (pqGetc(&beresp, conn))
1581
				{
1582
					/* We'll come back when there is more data */
1583 1584
					return PGRES_POLLING_READING;
				}
1585

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
				/*
				 * Validate message type: we expect only an authentication
				 * request or an error here.  Anything else probably means
				 * it's not Postgres on the other end at all.
				 */
				if (!(beresp == 'R' || beresp == 'E'))
				{
					printfPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(
								  "expected authentication request from "
Bruce Momjian's avatar
Bruce Momjian committed
1596
											"server, but received %c\n"),
1597 1598 1599 1600
									  beresp);
					goto error_return;
				}

1601
				if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1602
				{
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
					/* Read message length word */
					if (pqGetInt(&msgLength, 4, conn))
					{
						/* We'll come back when there is more data */
						return PGRES_POLLING_READING;
					}
				}
				else
				{
					/* Set phony message length to disable checks below */
					msgLength = 8;
1614 1615 1616 1617 1618
				}

				/*
				 * Try to validate message length before using it.
				 * Authentication requests can't be very large.  Errors
Bruce Momjian's avatar
Bruce Momjian committed
1619 1620 1621
				 * can be a little larger, but not huge.  If we see a
				 * large apparent length in an error, it means we're
				 * really talking to a pre-3.0-protocol server; cope.
1622 1623 1624 1625 1626 1627
				 */
				if (beresp == 'R' && (msgLength < 8 || msgLength > 100))
				{
					printfPQExpBuffer(&conn->errorMessage,
									  libpq_gettext(
								  "expected authentication request from "
Bruce Momjian's avatar
Bruce Momjian committed
1628
											"server, but received %c\n"),
1629 1630 1631 1632 1633
									  beresp);
					goto error_return;
				}

				if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1634
				{
1635
					/* Handle error from a pre-3.0 server */
Bruce Momjian's avatar
Bruce Momjian committed
1636
					conn->inCursor = conn->inStart + 1; /* reread data */
1637 1638
					if (pqGets(&conn->errorMessage, conn))
					{
1639
						/* We'll come back when there is more data */
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
						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');
1651 1652 1653 1654 1655 1656 1657

					/*
					 * If we tried to open the connection in 3.0 protocol,
					 * fall back to 2.0 protocol.
					 */
					if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
					{
Bruce Momjian's avatar
Bruce Momjian committed
1658
						conn->pversion = PG_PROTOCOL(2, 0);
1659 1660 1661 1662 1663 1664 1665 1666
						/* Must drop the old connection */
						pqsecure_close(conn);
						closesocket(conn->sock);
						conn->sock = -1;
						conn->status = CONNECTION_NEEDED;
						goto keep_going;
					}

1667 1668
					goto error_return;
				}
1669

1670 1671
				/*
				 * Can't process if message body isn't all here yet.
1672
				 *
Bruce Momjian's avatar
Bruce Momjian committed
1673 1674
				 * (In protocol 2.0 case, we are assuming messages carry at
				 * least 4 bytes of data.)
1675 1676 1677 1678
				 */
				msgLength -= 4;
				avail = conn->inEnd - conn->inCursor;
				if (avail < msgLength)
1679
				{
1680
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1681 1682
					 * Before returning, try to enlarge the input buffer
					 * if needed to hold the whole message; see notes in
1683
					 * pqParseInput3.
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
					 */
					if (pqCheckInBufferSpace(conn->inCursor + msgLength, conn))
						goto error_return;
					/* We'll come back when there is more data */
					return PGRES_POLLING_READING;
				}

				/* Handle errors. */
				if (beresp == 'E')
				{
1694
					if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1695
					{
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
						if (pqGetErrorNotice3(conn, true))
						{
							/* We'll come back when there is more data */
							return PGRES_POLLING_READING;
						}
					}
					else
					{
						if (pqGets(&conn->errorMessage, conn))
						{
							/* We'll come back when there is more data */
							return PGRES_POLLING_READING;
						}
1709 1710 1711
					}
					/* OK, we read the message; mark data consumed */
					conn->inStart = conn->inCursor;
1712 1713

#ifdef USE_SSL
Bruce Momjian's avatar
Bruce Momjian committed
1714

1715
					/*
1716
					 * if sslmode is "allow" and we haven't tried an SSL
Bruce Momjian's avatar
Bruce Momjian committed
1717 1718
					 * connection already, then retry with an SSL
					 * connection
1719
					 */
1720
					if (conn->sslmode[0] == 'a' /* "allow" */
1721
						&& conn->ssl == NULL
1722 1723
						&& conn->allow_ssl_try
						&& conn->wait_ssl_try)
1724
					{
1725
						/* only retry once */
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
						conn->wait_ssl_try = false;
						/* Must drop the old connection */
						closesocket(conn->sock);
						conn->sock = -1;
						conn->status = CONNECTION_NEEDED;
						goto keep_going;
					}

					/*
					 * if sslmode is "prefer" and we're in an SSL
1736
					 * connection, then do a non-SSL retry
1737
					 */
1738
					if (conn->sslmode[0] == 'p' /* "prefer" */
1739
						&& conn->ssl
Bruce Momjian's avatar
Bruce Momjian committed
1740 1741
						&& conn->allow_ssl_try	/* redundant? */
						&& !conn->wait_ssl_try) /* redundant? */
1742
					{
1743
						/* only retry once */
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
						conn->allow_ssl_try = false;
						/* Must drop the old connection */
						pqsecure_close(conn);
						closesocket(conn->sock);
						conn->sock = -1;
						conn->status = CONNECTION_NEEDED;
						goto keep_going;
					}
#endif

1754 1755
					goto error_return;
				}
1756

1757
				/* It is an authentication request. */
1758 1759
				/* Get the type of request. */
				if (pqGetInt((int *) &areq, 4, conn))
1760 1761 1762 1763 1764
				{
					/* We'll come back when there are more data */
					return PGRES_POLLING_READING;
				}

1765
				/* Get the password salt if there is one. */
Bruce Momjian's avatar
Bruce Momjian committed
1766
				if (areq == AUTH_REQ_MD5)
1767
				{
Bruce Momjian's avatar
Bruce Momjian committed
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
					if (pqGetnchar(conn->md5Salt,
								   sizeof(conn->md5Salt), conn))
					{
						/* We'll come back when there are more data */
						return PGRES_POLLING_READING;
					}
				}
				if (areq == AUTH_REQ_CRYPT)
				{
					if (pqGetnchar(conn->cryptSalt,
								   sizeof(conn->cryptSalt), conn))
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
					{
						/* 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;
1790

1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
				/* Respond to the request if necessary. */

				/*
				 * Note that conn->pghost must be non-NULL if we are going
				 * to 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;
				}
1808 1809
				conn->errorMessage.len = strlen(conn->errorMessage.data);

1810 1811 1812 1813 1814 1815 1816 1817
				/*
				 * 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.
				 */
				if (pqFlush(conn))
					goto error_return;
1818

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
				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;
				}
1831

1832 1833 1834
				/* Look to see if we have more data yet. */
				goto keep_going;
			}
1835

1836 1837
		case CONNECTION_AUTH_OK:
			{
1838
				/*
1839
				 * Now we expect to hear from the backend. A ReadyForQuery
1840 1841 1842
				 * message indicates that startup is successful, but we
				 * might also get an Error message indicating failure.
				 * (Notice messages indicating nonfatal warnings are also
1843 1844 1845
				 * allowed by the protocol, as are ParameterStatus and
				 * BackendKeyData messages.) Easiest way to handle this is
				 * to let PQgetResult() read the messages. We just have to
Bruce Momjian's avatar
Bruce Momjian committed
1846 1847
				 * fake it out about the state of the connection, by
				 * setting asyncStatus = PGASYNC_BUSY (done above).
1848
				 */
1849

1850 1851
				if (PQisBusy(conn))
					return PGRES_POLLING_READING;
1852

1853
				res = PQgetResult(conn);
1854

1855 1856 1857 1858 1859 1860 1861 1862
				/*
				 * NULL return indicating we have gone to IDLE state is
				 * expected
				 */
				if (res)
				{
					if (res->resultStatus != PGRES_FATAL_ERROR)
						printfPQExpBuffer(&conn->errorMessage,
1863
										  libpq_gettext("unexpected message from server during startup\n"));
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

					/*
					 * 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');
					PQclear(res);
					goto error_return;
				}

1879
				/* We can release the address list now. */
1880
				freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
				conn->addrlist = NULL;
				conn->addr_cur = NULL;

				/* Fire up post-connection housekeeping if needed */
				if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
				{
					conn->status = CONNECTION_SETENV;
					conn->setenv_state = SETENV_STATE_OPTION_SEND;
					conn->next_eo = EnvironmentOptions;
					return PGRES_POLLING_WRITING;
				}

				/* Otherwise, we are open for business! */
1894 1895
				conn->status = CONNECTION_OK;
				return PGRES_POLLING_OK;
1896 1897
			}

1898 1899 1900
		case CONNECTION_SETENV:

			/*
Bruce Momjian's avatar
Bruce Momjian committed
1901 1902
			 * Do post-connection housekeeping (only needed in protocol
			 * 2.0).
1903
			 *
Bruce Momjian's avatar
Bruce Momjian committed
1904 1905
			 * We pretend that the connection is OK for the duration of these
			 * queries.
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
			 */
			conn->status = CONNECTION_OK;

			switch (pqSetenvPoll(conn))
			{
				case PGRES_POLLING_OK:	/* Success */
					break;

				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:
					goto error_return;
			}

			/* We are open for business! */
			conn->status = CONNECTION_OK;
			return PGRES_POLLING_OK;

1930
		default:
1931
			printfPQExpBuffer(&conn->errorMessage,
1932
							  libpq_gettext(
1933 1934 1935
										  "invalid connection state %c, "
							 "probably indicative of memory corruption\n"
											),
1936
							  conn->status);
1937
			goto error_return;
Bruce Momjian's avatar
Bruce Momjian committed
1938
	}
1939

1940 1941 1942
	/* Unreachable */

error_return:
1943 1944 1945 1946 1947 1948 1949

	/*
	 * 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).
Bruce Momjian's avatar
Bruce Momjian committed
1950
	 */
1951
	conn->status = CONNECTION_BAD;
1952 1953
	return PGRES_POLLING_FAILED;
}
Bruce Momjian's avatar
Bruce Momjian committed
1954 1955 1956 1957


/*
 * makeEmptyPGconn
1958
 *	 - create a PGconn data structure with (as yet) no interesting data
Bruce Momjian's avatar
Bruce Momjian committed
1959 1960 1961 1962
 */
static PGconn *
makeEmptyPGconn(void)
{
1963
	PGconn	   *conn;
1964

1965
#ifdef WIN32
1966 1967 1968 1969 1970 1971
	/*
	 *	Make sure socket support is up and running.
	 *	Even though this is done in libpqdll.c, that is only for MSVC and
	 *	BCC builds and doesn't work for static builds at all, so we have
	 *	to do it in the main code too.
	 */
Bruce Momjian's avatar
Bruce Momjian committed
1972
	WSADATA		wsaData;
1973 1974

	if (WSAStartup(MAKEWORD(1, 1), &wsaData))
1975
		return NULL;
1976 1977 1978
	WSASetLastError(0);
#endif

1979 1980 1981 1982
	conn = (PGconn *) malloc(sizeof(PGconn));
	if (conn == NULL)
		return conn;

1983
	/* Zero all pointers and booleans */
1984
	MemSet(conn, 0, sizeof(PGconn));
Bruce Momjian's avatar
Bruce Momjian committed
1985

1986 1987
	conn->noticeHooks.noticeRec = defaultNoticeReceiver;
	conn->noticeHooks.noticeProc = defaultNoticeProcessor;
Bruce Momjian's avatar
Bruce Momjian committed
1988 1989
	conn->status = CONNECTION_BAD;
	conn->asyncStatus = PGASYNC_IDLE;
1990
	conn->xactStatus = PQTRANS_IDLE;
1991 1992
	conn->setenv_state = SETENV_STATE_IDLE;
	conn->client_encoding = PG_SQL_ASCII;
1993
	conn->verbosity = PQERRORS_DEFAULT;
Bruce Momjian's avatar
Bruce Momjian committed
1994
	conn->sock = -1;
1995
#ifdef USE_SSL
1996 1997
	conn->allow_ssl_try = true;
	conn->wait_ssl_try = false;
1998 1999
#endif

2000
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2001 2002
	 * We try to send at least 8K at a time, which is the usual size of
	 * pipe buffers on Unix systems.  That way, when we are sending a
2003
	 * large amount of data, we avoid incurring extra kernel context swaps
2004 2005
	 * for partial bufferloads.  The output buffer is initially made 16K
	 * in size, and we try to dump it after accumulating 8K.
2006 2007
	 *
	 * With the same goal of minimizing context swaps, the input buffer will
2008 2009
	 * be enlarged anytime it has less than 8K free, so we initially
	 * allocate twice that.
2010 2011
	 */
	conn->inBufSize = 16 * 1024;
Bruce Momjian's avatar
Bruce Momjian committed
2012
	conn->inBuffer = (char *) malloc(conn->inBufSize);
2013
	conn->outBufSize = 16 * 1024;
Bruce Momjian's avatar
Bruce Momjian committed
2014
	conn->outBuffer = (char *) malloc(conn->outBufSize);
2015
	conn->nonblocking = FALSE;
2016 2017
	initPQExpBuffer(&conn->errorMessage);
	initPQExpBuffer(&conn->workBuffer);
2018

2019 2020 2021 2022
	if (conn->inBuffer == NULL ||
		conn->outBuffer == NULL ||
		conn->errorMessage.data == NULL ||
		conn->workBuffer.data == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
2023
	{
2024
		/* out of memory already :-( */
Bruce Momjian's avatar
Bruce Momjian committed
2025 2026 2027
		freePGconn(conn);
		conn = NULL;
	}
2028

Bruce Momjian's avatar
Bruce Momjian committed
2029 2030 2031
	return conn;
}

2032 2033
/*
 * freePGconn
2034
 *	 - free the PGconn data structure
2035
 */
2036
static void
2037
freePGconn(PGconn *conn)
2038
{
2039
	PGnotify   *notify;
2040 2041
	pgParameterStatus *pstatus;

2042 2043 2044 2045
#ifdef WIN32
	WSACleanup();
#endif

2046 2047
	if (!conn)
		return;
2048

2049
	pqClearAsyncResult(conn);	/* deallocate result and curTuple */
Bruce Momjian's avatar
Bruce Momjian committed
2050
	if (conn->sock >= 0)
2051
	{
2052
		pqsecure_close(conn);
Bruce Momjian's avatar
Bruce Momjian committed
2053
		closesocket(conn->sock);
2054
	}
2055 2056
	if (conn->pghost)
		free(conn->pghost);
2057 2058
	if (conn->pghostaddr)
		free(conn->pghostaddr);
Bruce Momjian's avatar
Bruce Momjian committed
2059 2060
	if (conn->pgport)
		free(conn->pgport);
2061 2062
	if (conn->pgunixsocket)
		free(conn->pgunixsocket);
2063 2064
	if (conn->pgtty)
		free(conn->pgtty);
2065 2066
	if (conn->connect_timeout)
		free(conn->connect_timeout);
2067 2068 2069 2070 2071 2072
	if (conn->pgoptions)
		free(conn->pgoptions);
	if (conn->dbName)
		free(conn->dbName);
	if (conn->pguser)
		free(conn->pguser);
2073 2074
	if (conn->pgpass)
		free(conn->pgpass);
2075 2076
	if (conn->sslmode)
		free(conn->sslmode);
Bruce Momjian's avatar
Bruce Momjian committed
2077
	/* Note that conn->Pfdebug is not ours to close or free */
2078 2079 2080 2081 2082 2083 2084 2085
	notify = conn->notifyHead;
	while (notify != NULL)
	{
		PGnotify *prev = notify;

		notify = notify->next;
		free(prev);
	}
2086
	freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2087 2088 2089 2090 2091 2092 2093 2094
	pstatus = conn->pstatus;
	while (pstatus != NULL)
	{
		pgParameterStatus *prev = pstatus;

		pstatus = pstatus->next;
		free(prev);
	}
Bruce Momjian's avatar
Bruce Momjian committed
2095 2096 2097 2098 2099 2100
	if (conn->lobjfuncs)
		free(conn->lobjfuncs);
	if (conn->inBuffer)
		free(conn->inBuffer);
	if (conn->outBuffer)
		free(conn->outBuffer);
2101 2102
	termPQExpBuffer(&conn->errorMessage);
	termPQExpBuffer(&conn->workBuffer);
2103
	free(conn);
2104 2105 2106
}

/*
2107 2108 2109
 * closePGconn
 *	 - properly close a connection to the backend
 */
2110
static void
2111
closePGconn(PGconn *conn)
2112
{
2113 2114 2115 2116
	/*
	 * Note that the protocol doesn't allow us to send Terminate messages
	 * during the startup phase.
	 */
2117
	if (conn->sock >= 0 && conn->status == CONNECTION_OK)
Bruce Momjian's avatar
Bruce Momjian committed
2118 2119
	{
		/*
2120
		 * Try to send "close connection" message to backend. Ignore any
2121
		 * error.
Bruce Momjian's avatar
Bruce Momjian committed
2122
		 */
2123
		pqPutMsgStart('X', false, conn);
2124
		pqPutMsgEnd(conn);
2125
		pqFlush(conn);
Bruce Momjian's avatar
Bruce Momjian committed
2126 2127
	}

2128
	/*
2129 2130 2131 2132 2133 2134
	 * must reset the blocking status so a possible reconnect will work
	 * don't call PQsetnonblocking() because it will fail if it's unable
	 * to flush the connection.
	 */
	conn->nonblocking = FALSE;

Bruce Momjian's avatar
Bruce Momjian committed
2135 2136 2137 2138
	/*
	 * Close the connection, reset all transient state, flush I/O buffers.
	 */
	if (conn->sock >= 0)
2139
	{
2140
		pqsecure_close(conn);
Bruce Momjian's avatar
Bruce Momjian committed
2141
		closesocket(conn->sock);
2142
	}
Bruce Momjian's avatar
Bruce Momjian committed
2143
	conn->sock = -1;
2144 2145
	conn->status = CONNECTION_BAD;		/* Well, not really _bad_ - just
										 * absent */
Bruce Momjian's avatar
Bruce Momjian committed
2146
	conn->asyncStatus = PGASYNC_IDLE;
2147
	pqClearAsyncResult(conn);	/* deallocate result and curTuple */
Bruce Momjian's avatar
Bruce Momjian committed
2148 2149 2150 2151 2152
	if (conn->lobjfuncs)
		free(conn->lobjfuncs);
	conn->lobjfuncs = NULL;
	conn->inStart = conn->inCursor = conn->inEnd = 0;
	conn->outCount = 0;
2153 2154 2155 2156
}

/*
   PQfinish:
2157 2158 2159
	  properly close a connection to the backend
	  also frees the PGconn data structure so it shouldn't be re-used
	  after this
2160 2161
*/
void
2162
PQfinish(PGconn *conn)
2163
{
2164
	if (conn)
2165
	{
Bruce Momjian's avatar
Bruce Momjian committed
2166
		closePGconn(conn);
2167 2168
		freePGconn(conn);
	}
2169 2170 2171 2172
}

/* PQreset :
   resets the connection to the backend
2173
   closes the existing connection and makes a new one
2174 2175
*/
void
2176
PQreset(PGconn *conn)
2177
{
2178
	if (conn)
2179 2180
	{
		closePGconn(conn);
2181

2182 2183
		if (connectDBStart(conn))
			(void) connectDBComplete(conn);
2184
	}
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
}


/* 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);
	}

2203
	return 0;
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
}


/* 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;
2219 2220
}

2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
/*
 * PQcancelGet: get a PGcancel structure corresponding to a connection.
 *
 * A copy is needed to be able to cancel a running query from a different
 * thread. If the same structure is used all structure members would have
 * to be individually locked (if the entire structure was locked, it would
 * be impossible to cancel a synchronous query becuase the structure would
 * have to stay locked for the duration of the query).
 */
PGcancel *
PQgetCancel(PGconn *conn)
{
	PGcancel *cancel;

	if (!conn)
		return NULL;

	if (conn->sock < 0)
		return NULL;

	cancel = malloc(sizeof(PGcancel));
	if (cancel == NULL)
		return NULL;

	memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
	cancel->be_pid = conn->be_pid;
	cancel->be_key = conn->be_key;

	return cancel;
}

/* PQfreeCancel: free a cancel structure */
void
PQfreeCancel(PGcancel *cancel)
{
	if (cancel)
		free(cancel);
}

2260 2261

/*
2262 2263
 * PQcancel and PQrequestCancel: attempt to request cancellation of the
 * current operation.
2264 2265
 *
 * The return value is TRUE if the cancel request was successfully
2266
 * dispatched, FALSE if not (in which case an error message is available).
2267 2268 2269 2270 2271 2272 2273 2274 2275
 * Note: successful dispatch is no guarantee that there will be any effect at
 * the backend.  The application must read the operation result as usual.
 *
 * 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.
2276
 * We also save/restore errno in case the signal handler support doesn't.
2277
 *
2278 2279
 * internal_cancel() is an internal helper function to make code-sharing
 * between the two versions of the cancel function possible.
2280
 */
2281 2282 2283
static int
internal_cancel(SockAddr *raddr, int be_pid, int be_key,
				char *errbuf, int errbufsize)
2284
{
2285
	int			save_errno = SOCK_ERRNO;
2286
	int			tmpsock = -1;
2287
	char		sebuf[256];
2288
	int         maxlen;
2289 2290 2291 2292
	struct
	{
		uint32		packetlen;
		CancelRequestPacket cp;
2293 2294 2295
	}			crp;

	/*
2296 2297
	 * We need to open a temporary connection to the postmaster. Do
	 * this with only kernel calls.
2298
	 */
2299
	if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2300
	{
2301
		StrNCpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2302 2303
		goto cancel_errReturn;
	}
2304
retry3:
2305 2306
	if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
				raddr->salen) < 0)
2307
	{
2308 2309 2310
		if (SOCK_ERRNO == EINTR)
			/* Interrupted system call - we'll just try again */
			goto retry3;
2311
		StrNCpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2312 2313
		goto cancel_errReturn;
	}
2314

2315 2316 2317 2318 2319 2320 2321 2322
	/*
	 * 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);
2323 2324
	crp.cp.backendPID = htonl(be_pid);
	crp.cp.cancelAuthCode = htonl(be_key);
2325

2326
retry4:
2327
	if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2328
	{
2329 2330 2331
		if (SOCK_ERRNO == EINTR)
			/* Interrupted system call - we'll just try again */
			goto retry4;
2332
		StrNCpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2333 2334 2335
		goto cancel_errReturn;
	}

2336
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2337 2338 2339 2340 2341 2342
	 * Wait for the postmaster to close the connection, which indicates
	 * that it's processed the request.  Without this delay, we might
	 * issue another command only to find that our cancel zaps that
	 * command instead of the one we thought we were canceling.  Note we
	 * don't actually expect this read to obtain any data, we are just
	 * waiting for EOF to be signaled.
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
	 */
retry5:
	if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
	{
		if (SOCK_ERRNO == EINTR)
			/* Interrupted system call - we'll just try again */
			goto retry5;
		/* we ignore other error conditions */
	}

	/* All done */
2354
	closesocket(tmpsock);
2355
	SOCK_ERRNO_SET(save_errno);
2356 2357 2358
	return TRUE;

cancel_errReturn:
2359 2360 2361 2362 2363 2364
	/*
	 * Make sure we don't overflow the error buffer. Leave space for
	 * the \n at the end, and for the terminating zero.
	 */
	maxlen = errbufsize - strlen(errbuf) - 2;
	if (maxlen >= 0)
2365
	{
2366 2367 2368 2369 2370
		strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
				maxlen);
		strcat(errbuf, "\n");
	}
	if (tmpsock >= 0)
2371
		closesocket(tmpsock);
2372
	SOCK_ERRNO_SET(save_errno);
2373 2374 2375
	return FALSE;
}

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
/*
 * PQcancel: request query cancel
 *
 * Returns TRUE if able to send the cancel request, FALSE if not.
 *
 * On failure, an error message is stored in *errbuf, which must be of size
 * errbufsize (recommended size is 256 bytes).  *errbuf is not changed on
 * success return.
 */
int
PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
{
	if (!cancel)
	{
		StrNCpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
		return FALSE;
	}

	return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
						   errbuf, errbufsize);
}

/*
 * PQrequestCancel: old, not thread-safe function for requesting query cancel
 *
 * Returns TRUE if able to send the cancel request, FALSE if not.
 *
 * On failure, the error message is saved in conn->errorMessage; this means
 * that this can't be used when there might be other active operations on
 * the connection object.
 *
 * NOTE: error messages will be cut off at the current size of the
 * error message buffer, since we dare not try to expand conn->errorMessage!
 */
int
PQrequestCancel(PGconn *conn)
{
	int r;

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

	if (conn->sock < 0)
	{
		StrNCpy(conn->errorMessage.data,
				"PQrequestCancel() -- connection is not open\n",
				conn->errorMessage.maxlen);
		conn->errorMessage.len = strlen(conn->errorMessage.data);

		return FALSE;
	}

	r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
						conn->errorMessage.data, conn->errorMessage.maxlen);

	if (!r)
		conn->errorMessage.len = strlen(conn->errorMessage.data);

	return r;
}

2438

2439
/*
2440
 * pqPacketSend() -- convenience routine to send a message to server.
2441 2442 2443 2444 2445 2446
 *
 * pack_type: the single-byte message type code.  (Pass zero for startup
 * packets, which have no message type code.)
 *
 * buf, buf_len: contents of message.  The given length includes only what
 * is in buf; the message type and message length fields are added here.
2447 2448 2449
 *
 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
 * SIDE_EFFECTS: may block.
2450 2451 2452 2453
 *
 * Note: all messages sent with this routine have a length word, whether
 * it's protocol 2.0 or 3.0.
 */
2454
int
2455 2456
pqPacketSend(PGconn *conn, char pack_type,
			 const void *buf, size_t buf_len)
2457
{
2458
	/* Start the message. */
2459
	if (pqPutMsgStart(pack_type, true, conn))
2460
		return STATUS_ERROR;
2461

2462 2463
	/* Send the message body. */
	if (pqPutnchar(buf, buf_len, conn))
2464
		return STATUS_ERROR;
2465

2466 2467 2468 2469
	/* Finish the message. */
	if (pqPutMsgEnd(conn))
		return STATUS_ERROR;

2470
	/* Flush to ensure backend gets it. */
Bruce Momjian's avatar
Bruce Momjian committed
2471 2472
	if (pqFlush(conn))
		return STATUS_ERROR;
2473

2474
	return STATUS_OK;
2475 2476
}

2477 2478


2479 2480
#define MAXBUFSIZE 256

Tom Lane's avatar
Tom Lane committed
2481 2482 2483
static int
parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
{
2484
	char	   *service = conninfo_getval(options, "service");
2485
	char		serviceFile[MAXPGPATH];
2486
	bool		group_found = false;
2487 2488 2489
	int			linenr = 0,
				i;

2490 2491 2492 2493 2494 2495 2496 2497
	/*
	 * We have to special-case the environment variable PGSERVICE here,
	 * since this is and should be called before inserting environment
	 * defaults for other connection options.
	 */
	if (service == NULL)
		service = getenv("PGSERVICE");

2498
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2499 2500 2501
	 * This could be used by any application so we can't use the binary
	 * location to find our config files.
	 */
2502
	snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
Bruce Momjian's avatar
Bruce Momjian committed
2503
		   getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
2504

2505 2506 2507 2508 2509 2510 2511 2512 2513
	if (service != NULL)
	{
		FILE	   *f;
		char		buf[MAXBUFSIZE],
				   *line;

		f = fopen(serviceFile, "r");
		if (f == NULL)
		{
2514
			printfPQExpBuffer(errorMessage, libpq_gettext("ERROR: Service file '%s' not found\n"),
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
							  serviceFile);
			return 1;
		}

		while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
		{
			linenr++;

			if (strlen(line) >= MAXBUFSIZE - 2)
			{
				fclose(f);
				printfPQExpBuffer(errorMessage,
2527
						libpq_gettext("ERROR: line %d too long in service file '%s'\n"),
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
								  linenr,
								  serviceFile);
				return 2;
			}

			/* ignore EOL at end of line */
			if (strlen(line) && line[strlen(line) - 1] == '\n')
				line[strlen(line) - 1] = 0;

			/* ignore leading blanks */
			while (*line && isspace((unsigned char) line[0]))
				line++;

			/* ignore comments and empty lines */
			if (strlen(line) == 0 || line[0] == '#')
				continue;

			/* Check for right groupname */
			if (line[0] == '[')
			{
				if (group_found)
				{
					/* group info already read */
					fclose(f);
					return 0;
				}

				if (strncmp(line + 1, service, strlen(service)) == 0 &&
					line[strlen(service) + 1] == ']')
2557
					group_found = true;
2558
				else
2559
					group_found = false;
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
			}
			else
			{
				if (group_found)
				{
					/*
					 * Finally, we are in the right group and can parse
					 * the line
					 */
					char	   *key,
							   *val;
2571
					bool		found_keyword;
Bruce Momjian's avatar
TNS:  
Bruce Momjian committed
2572

2573 2574
					key = line;
					val = strchr(line, '=');
Bruce Momjian's avatar
Bruce Momjian committed
2575
					if (val == NULL)
2576 2577
					{
						printfPQExpBuffer(errorMessage,
2578
										  libpq_gettext("ERROR: syntax error in service file '%s', line %d\n"),
2579 2580 2581 2582 2583
										  serviceFile,
										  linenr);
						fclose(f);
						return 3;
					}
2584
					*val++ = '\0';
2585

2586 2587 2588 2589
					/*
					 * Set the parameter --- but don't override any
					 * previous explicit setting.
					 */
2590
					found_keyword = false;
2591 2592 2593 2594
					for (i = 0; options[i].keyword; i++)
					{
						if (strcmp(options[i].keyword, key) == 0)
						{
2595 2596
							if (options[i].val == NULL)
								options[i].val = strdup(val);
2597
							found_keyword = true;
2598
							break;
2599 2600 2601 2602 2603 2604
						}
					}

					if (!found_keyword)
					{
						printfPQExpBuffer(errorMessage,
2605
										  libpq_gettext("ERROR: syntax error in service file '%s', line %d\n"),
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
										  serviceFile,
										  linenr);
						fclose(f);
						return 3;
					}
				}
			}
		}

		fclose(f);
	}

	return 0;
Bruce Momjian's avatar
TNS:  
Bruce Momjian committed
2619 2620
}

2621

2622
/*
2623
 * Conninfo parser routine
2624 2625 2626 2627
 *
 * If successful, a malloc'd PQconninfoOption array is returned.
 * If not successful, NULL is returned and an error message is
 * left in errorMessage.
2628
 */
2629
static PQconninfoOption *
2630
conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2631
{
2632 2633 2634
	char	   *pname;
	char	   *pval;
	char	   *buf;
2635
	char	   *tmp;
2636 2637
	char	   *cp;
	char	   *cp2;
2638
	PQconninfoOption *options;
2639
	PQconninfoOption *option;
2640
	char		errortmp[PQERRORMSG_LENGTH];
2641

2642 2643 2644 2645 2646
	/* Make a working copy of PQconninfoOptions */
	options = malloc(sizeof(PQconninfoOptions));
	if (options == NULL)
	{
		printfPQExpBuffer(errorMessage,
2647
						  libpq_gettext("out of memory\n"));
2648 2649 2650
		return NULL;
	}
	memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2651

2652
	/* Need a modifiable copy of the input string */
2653 2654
	if ((buf = strdup(conninfo)) == NULL)
	{
2655
		printfPQExpBuffer(errorMessage,
2656
						  libpq_gettext("out of memory\n"));
2657 2658
		PQconninfoFree(options);
		return NULL;
2659
	}
2660
	cp = buf;
2661

2662 2663 2664
	while (*cp)
	{
		/* Skip blanks before the parameter name */
2665
		if (isspace((unsigned char) *cp))
2666 2667 2668
		{
			cp++;
			continue;
2669 2670
		}

2671 2672 2673 2674 2675 2676
		/* Get the parameter name */
		pname = cp;
		while (*cp)
		{
			if (*cp == '=')
				break;
2677
			if (isspace((unsigned char) *cp))
2678 2679 2680 2681
			{
				*cp++ = '\0';
				while (*cp)
				{
2682
					if (!isspace((unsigned char) *cp))
2683 2684 2685 2686 2687 2688 2689
						break;
					cp++;
				}
				break;
			}
			cp++;
		}
2690

2691 2692 2693
		/* Check that there is a following '=' */
		if (*cp != '=')
		{
2694
			printfPQExpBuffer(errorMessage,
2695
							  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2696
							  pname);
2697
			PQconninfoFree(options);
2698
			free(buf);
2699
			return NULL;
2700 2701
		}
		*cp++ = '\0';
2702

2703 2704 2705
		/* Skip blanks after the '=' */
		while (*cp)
		{
2706
			if (!isspace((unsigned char) *cp))
2707 2708
				break;
			cp++;
2709
		}
2710

2711
		/* Get the parameter value */
2712 2713 2714 2715 2716 2717 2718
		pval = cp;

		if (*cp != '\'')
		{
			cp2 = pval;
			while (*cp)
			{
2719
				if (isspace((unsigned char) *cp))
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
				{
					*cp++ = '\0';
					break;
				}
				if (*cp == '\\')
				{
					cp++;
					if (*cp != '\0')
						*cp2++ = *cp++;
				}
				else
					*cp2++ = *cp++;
			}
			*cp2 = '\0';
2734
		}
2735 2736 2737 2738 2739 2740 2741 2742
		else
		{
			cp2 = pval;
			cp++;
			for (;;)
			{
				if (*cp == '\0')
				{
2743
					printfPQExpBuffer(errorMessage,
2744
									  libpq_gettext("unterminated quoted string in connection info string\n"));
2745
					PQconninfoFree(options);
2746
					free(buf);
2747
					return NULL;
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
				}
				if (*cp == '\\')
				{
					cp++;
					if (*cp != '\0')
						*cp2++ = *cp++;
					continue;
				}
				if (*cp == '\'')
				{
					*cp2 = '\0';
					cp++;
					break;
				}
				*cp2++ = *cp++;
			}
2764
		}
2765

2766 2767 2768
		/*
		 * Now we have the name and the value. Search for the param
		 * record.
2769
		 */
2770
		for (option = options; option->keyword != NULL; option++)
2771
		{
2772
			if (strcmp(option->keyword, pname) == 0)
2773
				break;
2774
		}
2775 2776
		if (option->keyword == NULL)
		{
2777
			printfPQExpBuffer(errorMessage,
2778
					 libpq_gettext("invalid connection option \"%s\"\n"),
2779
							  pname);
2780
			PQconninfoFree(options);
2781
			free(buf);
2782
			return NULL;
2783 2784
		}

2785
		/*
2786 2787
		 * Store the value
		 */
2788 2789
		if (option->val)
			free(option->val);
2790
		option->val = strdup(pval);
Bruce Momjian's avatar
TNS:  
Bruce Momjian committed
2791 2792 2793

	}

2794 2795 2796
	/* Done with the modifiable input string */
	free(buf);

2797
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2798 2799
	 * If there's a service spec, use it to obtain any
	 * not-explicitly-given parameters.
2800
	 */
2801 2802 2803 2804
	if (parseServiceInfo(options, errorMessage))
	{
		PQconninfoFree(options);
		return NULL;
2805 2806
	}

2807 2808
	/*
	 * Get the fallback resources for parameters not specified in the
2809
	 * conninfo string nor the service.
2810
	 */
2811
	for (option = options; option->keyword != NULL; option++)
2812 2813
	{
		if (option->val != NULL)
2814
			continue;			/* Value was in conninfo or service */
2815

2816
		/*
2817 2818
		 * Try to get the environment variable fallback
		 */
Bruce Momjian's avatar
Bruce Momjian committed
2819
		if (option->envvar != NULL)
2820
		{
Bruce Momjian's avatar
Bruce Momjian committed
2821
			if ((tmp = getenv(option->envvar)) != NULL)
2822 2823 2824 2825 2826
			{
				option->val = strdup(tmp);
				continue;
			}
		}
2827

2828 2829 2830
		/*
		 * No environment variable specified or this one isn't set - try
		 * compiled in
2831 2832 2833 2834 2835 2836
		 */
		if (option->compiled != NULL)
		{
			option->val = strdup(option->compiled);
			continue;
		}
2837

2838
		/*
2839 2840
		 * Special handling for user
		 */
2841
		if (strcmp(option->keyword, "user") == 0)
2842
		{
2843
			option->val = fe_getauthname(errortmp);
2844
			/* note any error message is thrown away */
2845
			continue;
2846
		}
2847 2848
	}

2849
	return options;
2850 2851 2852
}


2853
static char *
2854 2855
conninfo_getval(PQconninfoOption *connOptions,
				const char *keyword)
2856
{
2857
	PQconninfoOption *option;
2858

2859
	for (option = connOptions; option->keyword != NULL; option++)
2860
	{
2861
		if (strcmp(option->keyword, keyword) == 0)
2862
			return option->val;
2863 2864
	}

2865
	return NULL;
2866 2867 2868
}


2869 2870
void
PQconninfoFree(PQconninfoOption *connOptions)
2871
{
2872
	PQconninfoOption *option;
2873

2874 2875 2876 2877
	if (connOptions == NULL)
		return;

	for (option = connOptions; option->keyword != NULL; option++)
2878 2879 2880
	{
		if (option->val != NULL)
			free(option->val);
2881
	}
2882
	free(connOptions);
2883 2884
}

2885

2886
/* =========== accessor functions for PGconn ========= */
2887
char *
Bruce Momjian's avatar
Bruce Momjian committed
2888
PQdb(const PGconn *conn)
2889
{
2890
	if (!conn)
2891
		return NULL;
2892
	return conn->dbName;
2893 2894
}

2895
char *
Bruce Momjian's avatar
Bruce Momjian committed
2896
PQuser(const PGconn *conn)
2897
{
2898
	if (!conn)
2899
		return NULL;
2900
	return conn->pguser;
2901 2902
}

2903
char *
Bruce Momjian's avatar
Bruce Momjian committed
2904
PQpass(const PGconn *conn)
2905 2906
{
	if (!conn)
2907
		return NULL;
2908 2909 2910
	return conn->pgpass;
}

2911
char *
Bruce Momjian's avatar
Bruce Momjian committed
2912
PQhost(const PGconn *conn)
2913
{
2914
	if (!conn)
2915
		return NULL;
2916
	return conn->pghost ? conn->pghost : conn->pgunixsocket;
2917 2918
}

2919
char *
Bruce Momjian's avatar
Bruce Momjian committed
2920
PQport(const PGconn *conn)
2921
{
2922
	if (!conn)
2923
		return NULL;
2924
	return conn->pgport;
2925 2926
}

2927
char *
Bruce Momjian's avatar
Bruce Momjian committed
2928
PQtty(const PGconn *conn)
2929
{
2930
	if (!conn)
2931
		return NULL;
2932
	return conn->pgtty;
2933 2934
}

2935
char *
Bruce Momjian's avatar
Bruce Momjian committed
2936
PQoptions(const PGconn *conn)
2937
{
2938
	if (!conn)
2939
		return NULL;
2940
	return conn->pgoptions;
2941 2942 2943
}

ConnStatusType
Bruce Momjian's avatar
Bruce Momjian committed
2944
PQstatus(const PGconn *conn)
2945
{
2946 2947 2948
	if (!conn)
		return CONNECTION_BAD;
	return conn->status;
2949 2950
}

2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
PGTransactionStatusType
PQtransactionStatus(const PGconn *conn)
{
	if (!conn || conn->status != CONNECTION_OK)
		return PQTRANS_UNKNOWN;
	if (conn->asyncStatus != PGASYNC_IDLE)
		return PQTRANS_ACTIVE;
	return conn->xactStatus;
}

const char *
PQparameterStatus(const PGconn *conn, const char *paramName)
{
	const pgParameterStatus *pstatus;

	if (!conn || !paramName)
		return NULL;
	for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
	{
		if (strcmp(pstatus->name, paramName) == 0)
			return pstatus->value;
	}
	return NULL;
}

int
PQprotocolVersion(const PGconn *conn)
{
	if (!conn)
		return 0;
	if (conn->status == CONNECTION_BAD)
		return 0;
	return PG_PROTOCOL_MAJOR(conn->pversion);
}

2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
int
PQserverVersion(const PGconn *conn)
{
	if (!conn)
		return 0;
	if (conn->status == CONNECTION_BAD)
		return 0;
	return conn->sversion;
}

2996
char *
Bruce Momjian's avatar
Bruce Momjian committed
2997
PQerrorMessage(const PGconn *conn)
2998
{
2999
	if (!conn)
3000
		return libpq_gettext("connection pointer is NULL\n");
3001

3002
	return conn->errorMessage.data;
3003 3004
}

Bruce Momjian's avatar
Bruce Momjian committed
3005
int
Bruce Momjian's avatar
Bruce Momjian committed
3006
PQsocket(const PGconn *conn)
Bruce Momjian's avatar
Bruce Momjian committed
3007 3008 3009 3010 3011 3012
{
	if (!conn)
		return -1;
	return conn->sock;
}

3013
int
Bruce Momjian's avatar
Bruce Momjian committed
3014
PQbackendPID(const PGconn *conn)
3015 3016 3017 3018 3019 3020
{
	if (!conn || conn->status != CONNECTION_OK)
		return 0;
	return conn->be_pid;
}

Tatsuo Ishii's avatar
Tatsuo Ishii committed
3021
int
3022
PQclientEncoding(const PGconn *conn)
Tatsuo Ishii's avatar
Tatsuo Ishii committed
3023 3024 3025 3026 3027 3028
{
	if (!conn || conn->status != CONNECTION_OK)
		return -1;
	return conn->client_encoding;
}

3029 3030 3031
int
PQsetClientEncoding(PGconn *conn, const char *encoding)
{
3032
	char		qbuf[128];
3033
	static const char query[] = "set client_encoding to '%s'";
3034 3035
	PGresult   *res;
	int			status;
3036 3037 3038 3039

	if (!conn || conn->status != CONNECTION_OK)
		return -1;

3040 3041 3042
	if (!encoding)
		return -1;

3043 3044 3045 3046 3047 3048 3049 3050
	/* check query buffer overflow */
	if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
		return -1;

	/* ok, now send a query */
	sprintf(qbuf, query, encoding);
	res = PQexec(conn, qbuf);

3051
	if (res == NULL)
3052 3053 3054 3055 3056 3057 3058
		return -1;
	if (res->resultStatus != PGRES_COMMAND_OK)
		status = -1;
	else
	{
		/* change libpq internal encoding */
		conn->client_encoding = pg_char_to_encoding(encoding);
3059
		status = 0;				/* everything is ok */
3060 3061
	}
	PQclear(res);
3062
	return (status);
3063
}
3064

3065 3066 3067
PGVerbosity
PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
{
Bruce Momjian's avatar
Bruce Momjian committed
3068
	PGVerbosity old;
3069 3070 3071 3072 3073 3074 3075 3076

	if (!conn)
		return PQERRORS_DEFAULT;
	old = conn->verbosity;
	conn->verbosity = verbosity;
	return old;
}

3077
void
3078
PQtrace(PGconn *conn, FILE *debug_port)
3079
{
3080
	if (conn == NULL)
3081 3082 3083
		return;
	PQuntrace(conn);
	conn->Pfdebug = debug_port;
3084 3085
}

3086
void
3087
PQuntrace(PGconn *conn)
3088
{
Bruce Momjian's avatar
Bruce Momjian committed
3089
	if (conn == NULL)
3090 3091 3092 3093 3094 3095
		return;
	if (conn->Pfdebug)
	{
		fflush(conn->Pfdebug);
		conn->Pfdebug = NULL;
	}
3096
}
3097

3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
PQnoticeReceiver
PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
{
	PQnoticeReceiver old;

	if (conn == NULL)
		return NULL;

	old = conn->noticeHooks.noticeRec;
	if (proc)
	{
		conn->noticeHooks.noticeRec = proc;
		conn->noticeHooks.noticeRecArg = arg;
	}
	return old;
}

3115
PQnoticeProcessor
3116
PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
3117
{
3118
	PQnoticeProcessor old;
3119

3120
	if (conn == NULL)
3121 3122
		return NULL;

3123
	old = conn->noticeHooks.noticeProc;
3124 3125
	if (proc)
	{
3126 3127
		conn->noticeHooks.noticeProc = proc;
		conn->noticeHooks.noticeProcArg = arg;
3128 3129
	}
	return old;
3130 3131 3132
}

/*
3133 3134 3135 3136 3137 3138 3139 3140 3141
 * The default notice message receiver just gets the standard notice text
 * and sends it to the notice processor.  This two-level setup exists
 * mostly for backwards compatibility; perhaps we should deprecate use of
 * PQsetNoticeProcessor?
 */
static void
defaultNoticeReceiver(void *arg, const PGresult *res)
{
	(void) arg;					/* not used */
3142 3143 3144
	if (res->noticeHooks.noticeProc != NULL)
		(*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
										PQresultErrorMessage(res));
3145 3146 3147 3148
}

/*
 * The default notice message processor just prints the
3149 3150 3151 3152 3153
 * 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
3154
defaultNoticeProcessor(void *arg, const char *message)
3155
{
3156
	(void) arg;					/* not used */
3157 3158 3159
	/* Note: we expect the supplied string to end with a newline already. */
	fprintf(stderr, "%s", message);
}
3160

3161 3162 3163 3164 3165
/*
 * returns a pointer to the next token or NULL if the current
 * token doesn't match
 */
static char *
3166 3167
pwdfMatchesString(char *buf, char *token)
{
Bruce Momjian's avatar
Bruce Momjian committed
3168 3169 3170 3171
	char	   *tbuf,
			   *ttok;
	bool		bslash = false;

3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
	if (buf == NULL || token == NULL)
		return NULL;
	tbuf = buf;
	ttok = token;
	if (*tbuf == '*')
		return tbuf + 2;
	while (*tbuf != 0)
	{
		if (*tbuf == '\\' && !bslash)
		{
			tbuf++;
			bslash = true;
		}
		if (*tbuf == ':' && *ttok == 0 && !bslash)
Bruce Momjian's avatar
Bruce Momjian committed
3186
			return tbuf + 1;
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
		bslash = false;
		if (*ttok == 0)
			return NULL;
		if (*tbuf == *ttok)
		{
			tbuf++;
			ttok++;
		}
		else
			return NULL;
	}
	return NULL;
}

3201
/* Get a password from the password file. Return value is malloc'd. */
3202
static char *
3203
PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
3204
{
Bruce Momjian's avatar
Bruce Momjian committed
3205
	FILE	   *fp;
3206
	char		homedir[MAXPGPATH];
3207
	char		pgpassfile[MAXPGPATH];
3208
	struct stat stat_buf;
Bruce Momjian's avatar
Bruce Momjian committed
3209

3210
#define LINELEN NAMEDATALEN*5
Bruce Momjian's avatar
Bruce Momjian committed
3211
	char		buf[LINELEN];
3212

3213
	if (dbname == NULL || strlen(dbname) == 0)
3214 3215
		return NULL;

3216
	if (username == NULL || strlen(username) == 0)
3217 3218 3219 3220 3221 3222 3223 3224
		return NULL;

	if (hostname == NULL)
		hostname = DefaultHost;

	if (port == NULL)
		port = DEF_PGPORT_STR;

3225
	if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3226
		return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
3227

3228
	snprintf(pgpassfile, sizeof(pgpassfile), "%s/%s", homedir, PGPASSFILE);
3229

3230
	/* If password file cannot be opened, ignore it. */
3231
	if (stat(pgpassfile, &stat_buf) == -1)
3232 3233
		return NULL;

3234
#ifndef WIN32
3235 3236 3237 3238
	/* If password file is insecure, alert the user and ignore it. */
	if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
	{
		fprintf(stderr,
3239
				libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
3240
				pgpassfile);
3241 3242
		return NULL;
	}
3243
#endif
3244

3245
	fp = fopen(pgpassfile, "r");
3246 3247 3248
	if (fp == NULL)
		return NULL;

Bruce Momjian's avatar
Bruce Momjian committed
3249 3250 3251 3252
	while (!feof(fp))
	{
		char	   *t = buf,
				   *ret;
3253
		int			len;
Bruce Momjian's avatar
Bruce Momjian committed
3254

3255
		fgets(buf, LINELEN - 1, fp);
3256 3257 3258

		len = strlen(buf);
		if (len == 0)
3259 3260
			continue;

3261 3262 3263 3264
		/* Remove trailing newline */
		if (buf[len - 1] == '\n')
			buf[len - 1] = 0;

3265
		if ((t = pwdfMatchesString(t, hostname)) == NULL ||
Bruce Momjian's avatar
Bruce Momjian committed
3266 3267 3268
			(t = pwdfMatchesString(t, port)) == NULL ||
			(t = pwdfMatchesString(t, dbname)) == NULL ||
			(t = pwdfMatchesString(t, username)) == NULL)
3269
			continue;
3270
		ret = strdup(t);
3271 3272 3273
		fclose(fp);
		return ret;
	}
3274

3275 3276 3277 3278 3279
	fclose(fp);
	return NULL;

#undef LINELEN
}
3280

3281 3282 3283
/*
 * Obtain user's home directory, return in given buffer
 *
3284 3285 3286
 * On Unix, this actually returns the user's home directory.  On Windows
 * it returns the PostgreSQL-specific application data folder.
 *
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
 * This is essentially the same as get_home_path(), but we don't use that
 * because we don't want to pull path.c into libpq (it pollutes application
 * namespace)
 */
bool
pqGetHomeDirectory(char *buf, int bufsize)
{
#ifndef WIN32
	char		pwdbuf[BUFSIZ];
	struct passwd pwdstr;
	struct passwd *pwd = NULL;

	if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
		return false;
	StrNCpy(buf, pwd->pw_dir, bufsize);
	return true;

#else
3305
	char		tmppath[MAX_PATH];
3306

3307
	ZeroMemory(tmppath, sizeof(tmppath));
3308
	if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
3309
		return false;
3310
	snprintf(buf, bufsize, "%s/postgresql", tmppath);
3311 3312 3313 3314
	return true;
#endif
}

3315 3316 3317 3318 3319 3320 3321 3322 3323
/*
 * To keep the API consistent, the locking stubs are always provided, even
 * if they are not required.
 */

static void
default_threadlock(int acquire)
{
#ifdef ENABLE_THREAD_SAFETY
3324
#ifndef WIN32
3325
	static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
Bruce Momjian's avatar
Bruce Momjian committed
3326

3327
#else
3328 3329 3330
	static pthread_mutex_t singlethread_lock = NULL;
	static long mutex_initlock = 0;

Bruce Momjian's avatar
Bruce Momjian committed
3331 3332 3333 3334
	if (singlethread_lock == NULL)
	{
		while (InterlockedExchange(&mutex_initlock, 1) == 1)
			 /* loop, another thread own the lock */ ;
3335 3336
		if (singlethread_lock == NULL)
			pthread_mutex_init(&singlethread_lock, NULL);
Bruce Momjian's avatar
Bruce Momjian committed
3337
		InterlockedExchange(&mutex_initlock, 0);
3338
	}
3339
#endif
3340 3341 3342 3343 3344 3345 3346
	if (acquire)
		pthread_mutex_lock(&singlethread_lock);
	else
		pthread_mutex_unlock(&singlethread_lock);
#endif
}

3347 3348
pgthreadlock_t
PQregisterThreadLock(pgthreadlock_t newhandler)
3349
{
3350
	pgthreadlock_t prev = pg_g_threadlock;
3351 3352

	if (newhandler)
3353
		pg_g_threadlock = newhandler;
3354
	else
3355 3356
		pg_g_threadlock = default_threadlock;

3357 3358
	return prev;
}