1 /*-------------------------------------------------------------------------
2  *
3  * fe-connect.c
4  *	  functions related to setting up a connection to the backend
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/interfaces/libpq/fe-connect.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres_fe.h"
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <time.h>
23 #include <unistd.h>
24 
25 #include "libpq-fe.h"
26 #include "libpq-int.h"
27 #include "fe-auth.h"
28 #include "pg_config_paths.h"
29 
30 #ifdef WIN32
31 #include "win32.h"
32 #ifdef _WIN32_IE
33 #undef _WIN32_IE
34 #endif
35 #define _WIN32_IE 0x0500
36 #ifdef near
37 #undef near
38 #endif
39 #define near
40 #include <shlobj.h>
41 #ifdef WIN32_ONLY_COMPILER		/* mstcpip.h is missing on mingw */
42 #include <mstcpip.h>
43 #endif
44 #else
45 #include <sys/socket.h>
46 #include <netdb.h>
47 #include <netinet/in.h>
48 #ifdef HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
50 #endif
51 #include <arpa/inet.h>
52 #endif
53 
54 #ifdef ENABLE_THREAD_SAFETY
55 #ifdef WIN32
56 #include "pthread-win32.h"
57 #else
58 #include <pthread.h>
59 #endif
60 #endif
61 
62 #ifdef USE_LDAP
63 #ifdef WIN32
64 #include <winldap.h>
65 #else
66 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
67 #define LDAP_DEPRECATED 1
68 #include <ldap.h>
69 typedef struct timeval LDAP_TIMEVAL;
70 #endif
71 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
72 				  PQExpBuffer errorMessage);
73 #endif
74 
75 #include "libpq/ip.h"
76 #include "mb/pg_wchar.h"
77 
78 #ifndef FD_CLOEXEC
79 #define FD_CLOEXEC 1
80 #endif
81 
82 
83 #ifndef WIN32
84 #define PGPASSFILE ".pgpass"
85 #else
86 #define PGPASSFILE "pgpass.conf"
87 #endif
88 
89 /*
90  * Pre-9.0 servers will return this SQLSTATE if asked to set
91  * application_name in a startup packet.  We hard-wire the value rather
92  * than looking into errcodes.h since it reflects historical behavior
93  * rather than that of the current code.
94  */
95 #define ERRCODE_APPNAME_UNKNOWN "42704"
96 
97 /* This is part of the protocol so just define it */
98 #define ERRCODE_INVALID_PASSWORD "28P01"
99 /* This too */
100 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
101 
102 /*
103  * Cope with the various platform-specific ways to spell TCP keepalive socket
104  * options.  This doesn't cover Windows, which as usual does its own thing.
105  */
106 #if defined(TCP_KEEPIDLE)
107 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
108 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
109 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
110 #elif defined(TCP_KEEPALIVE_THRESHOLD)
111 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
112 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
113 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
114 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
115 /* TCP_KEEPALIVE is the name of this option on macOS */
116 /* Caution: Solaris has this symbol but it means something different */
117 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
118 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
119 #endif
120 
121 /*
122  * fall back options if they are not specified by arguments or defined
123  * by environment variables
124  */
125 #define DefaultHost		"localhost"
126 #define DefaultTty		""
127 #define DefaultOption	""
128 #define DefaultAuthtype		  ""
129 #define DefaultPassword		  ""
130 #ifdef USE_SSL
131 #define DefaultSSLMode "prefer"
132 #else
133 #define DefaultSSLMode	"disable"
134 #endif
135 
136 /* ----------
137  * Definition of the conninfo parameters and their fallback resources.
138  *
139  * If Environment-Var and Compiled-in are specified as NULL, no
140  * fallback is available. If after all no value can be determined
141  * for an option, an error is returned.
142  *
143  * The value for the username is treated specially in conninfo_add_defaults.
144  * If the value is not obtained any other way, the username is determined
145  * by pg_fe_getauthname().
146  *
147  * The Label and Disp-Char entries are provided for applications that
148  * want to use PQconndefaults() to create a generic database connection
149  * dialog. Disp-Char is defined as follows:
150  *		""		Normal input field
151  *		"*"		Password field - hide value
152  *		"D"		Debug option - don't show by default
153  *
154  * PQconninfoOptions[] is a constant static array that we use to initialize
155  * a dynamically allocated working copy.  All the "val" fields in
156  * PQconninfoOptions[] *must* be NULL.  In a working copy, non-null "val"
157  * fields point to malloc'd strings that should be freed when the working
158  * array is freed (see PQconninfoFree).
159  *
160  * The first part of each struct is identical to the one in libpq-fe.h,
161  * which is required since we memcpy() data between the two!
162  * ----------
163  */
164 typedef struct _internalPQconninfoOption
165 {
166 	char	   *keyword;		/* The keyword of the option			*/
167 	char	   *envvar;			/* Fallback environment variable name	*/
168 	char	   *compiled;		/* Fallback compiled in default value	*/
169 	char	   *val;			/* Option's current value, or NULL		 */
170 	char	   *label;			/* Label for field in connect dialog	*/
171 	char	   *dispchar;		/* Indicates how to display this field in a
172 								 * connect dialog. Values are: "" Display
173 								 * entered value as is "*" Password field -
174 								 * hide value "D"  Debug option - don't show
175 								 * by default */
176 	int			dispsize;		/* Field size in characters for dialog	*/
177 	/* ---
178 	 * Anything above this comment must be synchronized with
179 	 * PQconninfoOption in libpq-fe.h, since we memcpy() data
180 	 * between them!
181 	 * ---
182 	 */
183 	off_t		connofs;		/* Offset into PGconn struct, -1 if not there */
184 } internalPQconninfoOption;
185 
186 static const internalPQconninfoOption PQconninfoOptions[] = {
187 	/*
188 	 * "authtype" is no longer used, so mark it "don't show".  We keep it in
189 	 * the array so as not to reject conninfo strings from old apps that might
190 	 * still try to set it.
191 	 */
192 	{"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
193 	"Database-Authtype", "D", 20, -1},
194 
195 	{"service", "PGSERVICE", NULL, NULL,
196 	"Database-Service", "", 20, -1},
197 
198 	{"user", "PGUSER", NULL, NULL,
199 		"Database-User", "", 20,
200 	offsetof(struct pg_conn, pguser)},
201 
202 	{"password", "PGPASSWORD", NULL, NULL,
203 		"Database-Password", "*", 20,
204 	offsetof(struct pg_conn, pgpass)},
205 
206 	{"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
207 		"Connect-timeout", "", 10,		/* strlen(INT32_MAX) == 10 */
208 	offsetof(struct pg_conn, connect_timeout)},
209 
210 	{"dbname", "PGDATABASE", NULL, NULL,
211 		"Database-Name", "", 20,
212 	offsetof(struct pg_conn, dbName)},
213 
214 	{"host", "PGHOST", NULL, NULL,
215 		"Database-Host", "", 40,
216 	offsetof(struct pg_conn, pghost)},
217 
218 	{"hostaddr", "PGHOSTADDR", NULL, NULL,
219 		"Database-Host-IP-Address", "", 45,
220 	offsetof(struct pg_conn, pghostaddr)},
221 
222 	{"port", "PGPORT", DEF_PGPORT_STR, NULL,
223 		"Database-Port", "", 6,
224 	offsetof(struct pg_conn, pgport)},
225 
226 	{"client_encoding", "PGCLIENTENCODING", NULL, NULL,
227 		"Client-Encoding", "", 10,
228 	offsetof(struct pg_conn, client_encoding_initial)},
229 
230 	/*
231 	 * "tty" is no longer used either, but keep it present for backwards
232 	 * compatibility.
233 	 */
234 	{"tty", "PGTTY", DefaultTty, NULL,
235 		"Backend-Debug-TTY", "D", 40,
236 	offsetof(struct pg_conn, pgtty)},
237 
238 	{"options", "PGOPTIONS", DefaultOption, NULL,
239 		"Backend-Debug-Options", "D", 40,
240 	offsetof(struct pg_conn, pgoptions)},
241 
242 	{"application_name", "PGAPPNAME", NULL, NULL,
243 		"Application-Name", "", 64,
244 	offsetof(struct pg_conn, appname)},
245 
246 	{"fallback_application_name", NULL, NULL, NULL,
247 		"Fallback-Application-Name", "", 64,
248 	offsetof(struct pg_conn, fbappname)},
249 
250 	{"keepalives", NULL, NULL, NULL,
251 		"TCP-Keepalives", "", 1,	/* should be just '0' or '1' */
252 	offsetof(struct pg_conn, keepalives)},
253 
254 	{"keepalives_idle", NULL, NULL, NULL,
255 		"TCP-Keepalives-Idle", "", 10,	/* strlen(INT32_MAX) == 10 */
256 	offsetof(struct pg_conn, keepalives_idle)},
257 
258 	{"keepalives_interval", NULL, NULL, NULL,
259 		"TCP-Keepalives-Interval", "", 10,		/* strlen(INT32_MAX) == 10 */
260 	offsetof(struct pg_conn, keepalives_interval)},
261 
262 	{"keepalives_count", NULL, NULL, NULL,
263 		"TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
264 	offsetof(struct pg_conn, keepalives_count)},
265 
266 	/*
267 	 * ssl options are allowed even without client SSL support because the
268 	 * client can still handle SSL modes "disable" and "allow". Other
269 	 * parameters have no effect on non-SSL connections, so there is no reason
270 	 * to exclude them since none of them are mandatory.
271 	 */
272 	{"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
273 		"SSL-Mode", "", 12,		/* sizeof("verify-full") == 12 */
274 	offsetof(struct pg_conn, sslmode)},
275 
276 	{"sslcompression", "PGSSLCOMPRESSION", "1", NULL,
277 		"SSL-Compression", "", 1,
278 	offsetof(struct pg_conn, sslcompression)},
279 
280 	{"sslcert", "PGSSLCERT", NULL, NULL,
281 		"SSL-Client-Cert", "", 64,
282 	offsetof(struct pg_conn, sslcert)},
283 
284 	{"sslkey", "PGSSLKEY", NULL, NULL,
285 		"SSL-Client-Key", "", 64,
286 	offsetof(struct pg_conn, sslkey)},
287 
288 	{"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
289 		"SSL-Root-Certificate", "", 64,
290 	offsetof(struct pg_conn, sslrootcert)},
291 
292 	{"sslcrl", "PGSSLCRL", NULL, NULL,
293 		"SSL-Revocation-List", "", 64,
294 	offsetof(struct pg_conn, sslcrl)},
295 
296 	{"requirepeer", "PGREQUIREPEER", NULL, NULL,
297 		"Require-Peer", "", 10,
298 	offsetof(struct pg_conn, requirepeer)},
299 
300 	/*
301 	 * As with SSL, all GSS options are exposed even in builds that don't have
302 	 * support.
303 	 */
304 
305 	/* Kerberos and GSSAPI authentication support specifying the service name */
306 	{"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
307 		"Kerberos-service-name", "", 20,
308 	offsetof(struct pg_conn, krbsrvname)},
309 
310 	{"gsslib", "PGGSSLIB", NULL, NULL,
311 		"GSS-library", "", 7,	/* sizeof("gssapi") = 7 */
312 	offsetof(struct pg_conn, gsslib)},
313 
314 	{"replication", NULL, NULL, NULL,
315 		"Replication", "D", 5,
316 	offsetof(struct pg_conn, replication)},
317 
318 	/* Terminating entry --- MUST BE LAST */
319 	{NULL, NULL, NULL, NULL,
320 	NULL, NULL, 0}
321 };
322 
323 static const PQEnvironmentOption EnvironmentOptions[] =
324 {
325 	/* common user-interface settings */
326 	{
327 		"PGDATESTYLE", "datestyle"
328 	},
329 	{
330 		"PGTZ", "timezone"
331 	},
332 	/* internal performance-related settings */
333 	{
334 		"PGGEQO", "geqo"
335 	},
336 	{
337 		NULL, NULL
338 	}
339 };
340 
341 /* The connection URI must start with either of the following designators: */
342 static const char uri_designator[] = "postgresql://";
343 static const char short_uri_designator[] = "postgres://";
344 
345 static bool connectOptions1(PGconn *conn, const char *conninfo);
346 static bool connectOptions2(PGconn *conn);
347 static int	connectDBStart(PGconn *conn);
348 static int	connectDBComplete(PGconn *conn);
349 static PGPing internal_ping(PGconn *conn);
350 static PGconn *makeEmptyPGconn(void);
351 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
352 static void freePGconn(PGconn *conn);
353 static void closePGconn(PGconn *conn);
354 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
355 static PQconninfoOption *parse_connection_string(const char *conninfo,
356 						PQExpBuffer errorMessage, bool use_defaults);
357 static int	uri_prefix_length(const char *connstr);
358 static bool recognized_connection_string(const char *connstr);
359 static PQconninfoOption *conninfo_parse(const char *conninfo,
360 			   PQExpBuffer errorMessage, bool use_defaults);
361 static PQconninfoOption *conninfo_array_parse(const char *const * keywords,
362 					 const char *const * values, PQExpBuffer errorMessage,
363 					 bool use_defaults, int expand_dbname);
364 static bool conninfo_add_defaults(PQconninfoOption *options,
365 					  PQExpBuffer errorMessage);
366 static PQconninfoOption *conninfo_uri_parse(const char *uri,
367 				   PQExpBuffer errorMessage, bool use_defaults);
368 static bool conninfo_uri_parse_options(PQconninfoOption *options,
369 						   const char *uri, PQExpBuffer errorMessage);
370 static bool conninfo_uri_parse_params(char *params,
371 						  PQconninfoOption *connOptions,
372 						  PQExpBuffer errorMessage);
373 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
374 static bool get_hexdigit(char digit, int *value);
375 static const char *conninfo_getval(PQconninfoOption *connOptions,
376 				const char *keyword);
377 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
378 				  const char *keyword, const char *value,
379 			  PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
380 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
381 			  const char *keyword);
382 static void defaultNoticeReceiver(void *arg, const PGresult *res);
383 static void defaultNoticeProcessor(void *arg, const char *message);
384 static int parseServiceInfo(PQconninfoOption *options,
385 				 PQExpBuffer errorMessage);
386 static int parseServiceFile(const char *serviceFile,
387 				 const char *service,
388 				 PQconninfoOption *options,
389 				 PQExpBuffer errorMessage,
390 				 bool *group_found);
391 static char *pwdfMatchesString(char *buf, char *token);
392 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
393 				 char *username);
394 static bool getPgPassFilename(char *pgpassfile);
395 static void dot_pg_pass_warning(PGconn *conn);
396 static void default_threadlock(int acquire);
397 
398 
399 /* global variable because fe-auth.c needs to access it */
400 pgthreadlock_t pg_g_threadlock = default_threadlock;
401 
402 
403 /*
404  *		pqDropConnection
405  *
406  * Close any physical connection to the server, and reset associated
407  * state inside the connection object.  We don't release state that
408  * would be needed to reconnect, though, nor local state that might still
409  * be useful later.
410  *
411  * We can always flush the output buffer, since there's no longer any hope
412  * of sending that data.  However, unprocessed input data might still be
413  * valuable, so the caller must tell us whether to flush that or not.
414  */
415 void
pqDropConnection(PGconn * conn,bool flushInput)416 pqDropConnection(PGconn *conn, bool flushInput)
417 {
418 	/* Drop any SSL state */
419 	pqsecure_close(conn);
420 
421 	/* Close the socket itself */
422 	if (conn->sock != PGINVALID_SOCKET)
423 		closesocket(conn->sock);
424 	conn->sock = PGINVALID_SOCKET;
425 
426 	/* Optionally discard any unread data */
427 	if (flushInput)
428 		conn->inStart = conn->inCursor = conn->inEnd = 0;
429 
430 	/* Always discard any unsent data */
431 	conn->outCount = 0;
432 
433 	/* Free authentication state */
434 #ifdef ENABLE_GSS
435 	{
436 		OM_uint32	min_s;
437 
438 		if (conn->gctx)
439 			gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
440 		if (conn->gtarg_nam)
441 			gss_release_name(&min_s, &conn->gtarg_nam);
442 		if (conn->ginbuf.length)
443 			gss_release_buffer(&min_s, &conn->ginbuf);
444 		if (conn->goutbuf.length)
445 			gss_release_buffer(&min_s, &conn->goutbuf);
446 	}
447 #endif
448 #ifdef ENABLE_SSPI
449 	if (conn->ginbuf.length)
450 		free(conn->ginbuf.value);
451 	conn->ginbuf.length = 0;
452 	conn->ginbuf.value = NULL;
453 	if (conn->sspitarget)
454 		free(conn->sspitarget);
455 	conn->sspitarget = NULL;
456 	if (conn->sspicred)
457 	{
458 		FreeCredentialsHandle(conn->sspicred);
459 		free(conn->sspicred);
460 		conn->sspicred = NULL;
461 	}
462 	if (conn->sspictx)
463 	{
464 		DeleteSecurityContext(conn->sspictx);
465 		free(conn->sspictx);
466 		conn->sspictx = NULL;
467 	}
468 	conn->usesspi = 0;
469 #endif
470 }
471 
472 
473 /*
474  *		pqDropServerData
475  *
476  * Clear all connection state data that was received from (or deduced about)
477  * the server.  This is essential to do between connection attempts to
478  * different servers, else we may incorrectly hold over some data from the
479  * old server.
480  *
481  * It would be better to merge this into pqDropConnection, perhaps, but
482  * right now we cannot because that function is called immediately on
483  * detection of connection loss (cf. pqReadData, for instance).  This data
484  * should be kept until we are actually starting a new connection.
485  */
486 static void
pqDropServerData(PGconn * conn)487 pqDropServerData(PGconn *conn)
488 {
489 	PGnotify   *notify;
490 	pgParameterStatus *pstatus;
491 
492 	/* Forget pending notifies */
493 	notify = conn->notifyHead;
494 	while (notify != NULL)
495 	{
496 		PGnotify   *prev = notify;
497 
498 		notify = notify->next;
499 		free(prev);
500 	}
501 	conn->notifyHead = conn->notifyTail = NULL;
502 
503 	/* Reset ParameterStatus data, as well as variables deduced from it */
504 	pstatus = conn->pstatus;
505 	while (pstatus != NULL)
506 	{
507 		pgParameterStatus *prev = pstatus;
508 
509 		pstatus = pstatus->next;
510 		free(prev);
511 	}
512 	conn->pstatus = NULL;
513 	conn->client_encoding = PG_SQL_ASCII;
514 	conn->std_strings = false;
515 	conn->sversion = 0;
516 
517 	/* Drop large-object lookup data */
518 	if (conn->lobjfuncs)
519 		free(conn->lobjfuncs);
520 	conn->lobjfuncs = NULL;
521 
522 	/* Reset assorted other per-connection state */
523 	conn->last_sqlstate[0] = '\0';
524 	conn->auth_req_received = false;
525 	conn->password_needed = false;
526 	conn->be_pid = 0;
527 	conn->be_key = 0;
528 }
529 
530 
531 /*
532  *		Connecting to a Database
533  *
534  * There are now six different ways a user of this API can connect to the
535  * database.  Two are not recommended for use in new code, because of their
536  * lack of extensibility with respect to the passing of options to the
537  * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
538  * to the latter).
539  *
540  * If it is desired to connect in a synchronous (blocking) manner, use the
541  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
542  * option = value pairs (or a URI) which must be parsed; the latter takes two
543  * NULL terminated arrays instead.
544  *
545  * To connect in an asynchronous (non-blocking) manner, use the functions
546  * PQconnectStart or PQconnectStartParams (which differ in the same way as
547  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
548  *
549  * Internally, the static functions connectDBStart, connectDBComplete
550  * are part of the connection procedure.
551  */
552 
553 /*
554  *		PQconnectdbParams
555  *
556  * establishes a connection to a postgres backend through the postmaster
557  * using connection information in two arrays.
558  *
559  * The keywords array is defined as
560  *
561  *	   const char *params[] = {"option1", "option2", NULL}
562  *
563  * The values array is defined as
564  *
565  *	   const char *values[] = {"value1", "value2", NULL}
566  *
567  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
568  * if a memory allocation failed.
569  * If the status field of the connection returned is CONNECTION_BAD,
570  * then some fields may be null'ed out instead of having valid values.
571  *
572  * You should call PQfinish (if conn is not NULL) regardless of whether this
573  * call succeeded.
574  */
575 PGconn *
PQconnectdbParams(const char * const * keywords,const char * const * values,int expand_dbname)576 PQconnectdbParams(const char *const * keywords,
577 				  const char *const * values,
578 				  int expand_dbname)
579 {
580 	PGconn	   *conn = PQconnectStartParams(keywords, values, expand_dbname);
581 
582 	if (conn && conn->status != CONNECTION_BAD)
583 		(void) connectDBComplete(conn);
584 
585 	return conn;
586 
587 }
588 
589 /*
590  *		PQpingParams
591  *
592  * check server status, accepting parameters identical to PQconnectdbParams
593  */
594 PGPing
PQpingParams(const char * const * keywords,const char * const * values,int expand_dbname)595 PQpingParams(const char *const * keywords,
596 			 const char *const * values,
597 			 int expand_dbname)
598 {
599 	PGconn	   *conn = PQconnectStartParams(keywords, values, expand_dbname);
600 	PGPing		ret;
601 
602 	ret = internal_ping(conn);
603 	PQfinish(conn);
604 
605 	return ret;
606 }
607 
608 /*
609  *		PQconnectdb
610  *
611  * establishes a connection to a postgres backend through the postmaster
612  * using connection information in a string.
613  *
614  * The conninfo string is either a whitespace-separated list of
615  *
616  *	   option = value
617  *
618  * definitions or a URI (refer to the documentation for details.) Value
619  * might be a single value containing no whitespaces or a single quoted
620  * string. If a single quote should appear anywhere in the value, it must be
621  * escaped with a backslash like \'
622  *
623  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
624  * if a memory allocation failed.
625  * If the status field of the connection returned is CONNECTION_BAD,
626  * then some fields may be null'ed out instead of having valid values.
627  *
628  * You should call PQfinish (if conn is not NULL) regardless of whether this
629  * call succeeded.
630  */
631 PGconn *
PQconnectdb(const char * conninfo)632 PQconnectdb(const char *conninfo)
633 {
634 	PGconn	   *conn = PQconnectStart(conninfo);
635 
636 	if (conn && conn->status != CONNECTION_BAD)
637 		(void) connectDBComplete(conn);
638 
639 	return conn;
640 }
641 
642 /*
643  *		PQping
644  *
645  * check server status, accepting parameters identical to PQconnectdb
646  */
647 PGPing
PQping(const char * conninfo)648 PQping(const char *conninfo)
649 {
650 	PGconn	   *conn = PQconnectStart(conninfo);
651 	PGPing		ret;
652 
653 	ret = internal_ping(conn);
654 	PQfinish(conn);
655 
656 	return ret;
657 }
658 
659 /*
660  *		PQconnectStartParams
661  *
662  * Begins the establishment of a connection to a postgres backend through the
663  * postmaster using connection information in a struct.
664  *
665  * See comment for PQconnectdbParams for the definition of the string format.
666  *
667  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
668  * you should not attempt to proceed with this connection.  If the status
669  * field of the connection returned is CONNECTION_BAD, an error has
670  * occurred. In this case you should call PQfinish on the result, (perhaps
671  * inspecting the error message first).  Other fields of the structure may not
672  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
673  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
674  * this is necessary.
675  *
676  * See PQconnectPoll for more info.
677  */
678 PGconn *
PQconnectStartParams(const char * const * keywords,const char * const * values,int expand_dbname)679 PQconnectStartParams(const char *const * keywords,
680 					 const char *const * values,
681 					 int expand_dbname)
682 {
683 	PGconn	   *conn;
684 	PQconninfoOption *connOptions;
685 
686 	/*
687 	 * Allocate memory for the conn structure
688 	 */
689 	conn = makeEmptyPGconn();
690 	if (conn == NULL)
691 		return NULL;
692 
693 	/*
694 	 * Parse the conninfo arrays
695 	 */
696 	connOptions = conninfo_array_parse(keywords, values,
697 									   &conn->errorMessage,
698 									   true, expand_dbname);
699 	if (connOptions == NULL)
700 	{
701 		conn->status = CONNECTION_BAD;
702 		/* errorMessage is already set */
703 		return conn;
704 	}
705 
706 	/*
707 	 * Move option values into conn structure
708 	 */
709 	if (!fillPGconn(conn, connOptions))
710 	{
711 		PQconninfoFree(connOptions);
712 		return conn;
713 	}
714 
715 	/*
716 	 * Free the option info - all is in conn now
717 	 */
718 	PQconninfoFree(connOptions);
719 
720 	/*
721 	 * Compute derived options
722 	 */
723 	if (!connectOptions2(conn))
724 		return conn;
725 
726 	/*
727 	 * Connect to the database
728 	 */
729 	if (!connectDBStart(conn))
730 	{
731 		/* Just in case we failed to set it in connectDBStart */
732 		conn->status = CONNECTION_BAD;
733 	}
734 
735 	return conn;
736 }
737 
738 /*
739  *		PQconnectStart
740  *
741  * Begins the establishment of a connection to a postgres backend through the
742  * postmaster using connection information in a string.
743  *
744  * See comment for PQconnectdb for the definition of the string format.
745  *
746  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
747  * you should not attempt to proceed with this connection.  If the status
748  * field of the connection returned is CONNECTION_BAD, an error has
749  * occurred. In this case you should call PQfinish on the result, (perhaps
750  * inspecting the error message first).  Other fields of the structure may not
751  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
752  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
753  * this is necessary.
754  *
755  * See PQconnectPoll for more info.
756  */
757 PGconn *
PQconnectStart(const char * conninfo)758 PQconnectStart(const char *conninfo)
759 {
760 	PGconn	   *conn;
761 
762 	/*
763 	 * Allocate memory for the conn structure
764 	 */
765 	conn = makeEmptyPGconn();
766 	if (conn == NULL)
767 		return NULL;
768 
769 	/*
770 	 * Parse the conninfo string
771 	 */
772 	if (!connectOptions1(conn, conninfo))
773 		return conn;
774 
775 	/*
776 	 * Compute derived options
777 	 */
778 	if (!connectOptions2(conn))
779 		return conn;
780 
781 	/*
782 	 * Connect to the database
783 	 */
784 	if (!connectDBStart(conn))
785 	{
786 		/* Just in case we failed to set it in connectDBStart */
787 		conn->status = CONNECTION_BAD;
788 	}
789 
790 	return conn;
791 }
792 
793 /*
794  * Move option values into conn structure
795  *
796  * Don't put anything cute here --- intelligence should be in
797  * connectOptions2 ...
798  *
799  * Returns true on success. On failure, returns false and sets error message.
800  */
801 static bool
fillPGconn(PGconn * conn,PQconninfoOption * connOptions)802 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
803 {
804 	const internalPQconninfoOption *option;
805 
806 	for (option = PQconninfoOptions; option->keyword; option++)
807 	{
808 		if (option->connofs >= 0)
809 		{
810 			const char *tmp = conninfo_getval(connOptions, option->keyword);
811 
812 			if (tmp)
813 			{
814 				char	  **connmember = (char **) ((char *) conn + option->connofs);
815 
816 				if (*connmember)
817 					free(*connmember);
818 				*connmember = strdup(tmp);
819 				if (*connmember == NULL)
820 				{
821 					printfPQExpBuffer(&conn->errorMessage,
822 									  libpq_gettext("out of memory\n"));
823 					return false;
824 				}
825 			}
826 		}
827 	}
828 
829 	return true;
830 }
831 
832 /*
833  *		connectOptions1
834  *
835  * Internal subroutine to set up connection parameters given an already-
836  * created PGconn and a conninfo string.  Derived settings should be
837  * processed by calling connectOptions2 next.  (We split them because
838  * PQsetdbLogin overrides defaults in between.)
839  *
840  * Returns true if OK, false if trouble (in which case errorMessage is set
841  * and so is conn->status).
842  */
843 static bool
connectOptions1(PGconn * conn,const char * conninfo)844 connectOptions1(PGconn *conn, const char *conninfo)
845 {
846 	PQconninfoOption *connOptions;
847 
848 	/*
849 	 * Parse the conninfo string
850 	 */
851 	connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
852 	if (connOptions == NULL)
853 	{
854 		conn->status = CONNECTION_BAD;
855 		/* errorMessage is already set */
856 		return false;
857 	}
858 
859 	/*
860 	 * Move option values into conn structure
861 	 */
862 	if (!fillPGconn(conn, connOptions))
863 	{
864 		conn->status = CONNECTION_BAD;
865 		PQconninfoFree(connOptions);
866 		return false;
867 	}
868 
869 	/*
870 	 * Free the option info - all is in conn now
871 	 */
872 	PQconninfoFree(connOptions);
873 
874 	return true;
875 }
876 
877 /*
878  *		connectOptions2
879  *
880  * Compute derived connection options after absorbing all user-supplied info.
881  *
882  * Returns true if OK, false if trouble (in which case errorMessage is set
883  * and so is conn->status).
884  */
885 static bool
connectOptions2(PGconn * conn)886 connectOptions2(PGconn *conn)
887 {
888 	/*
889 	 * If user name was not given, fetch it.  (Most likely, the fetch will
890 	 * fail, since the only way we get here is if pg_fe_getauthname() failed
891 	 * during conninfo_add_defaults().  But now we want an error message.)
892 	 */
893 	if (conn->pguser == NULL || conn->pguser[0] == '\0')
894 	{
895 		if (conn->pguser)
896 			free(conn->pguser);
897 		conn->pguser = pg_fe_getauthname(&conn->errorMessage);
898 		if (!conn->pguser)
899 		{
900 			conn->status = CONNECTION_BAD;
901 			return false;
902 		}
903 	}
904 
905 	/*
906 	 * If database name was not given, default it to equal user name
907 	 */
908 	if (conn->dbName == NULL || conn->dbName[0] == '\0')
909 	{
910 		if (conn->dbName)
911 			free(conn->dbName);
912 		conn->dbName = strdup(conn->pguser);
913 		if (!conn->dbName)
914 			goto oom_error;
915 	}
916 
917 	/*
918 	 * Supply default password if none given
919 	 */
920 	if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
921 	{
922 		if (conn->pgpass)
923 			free(conn->pgpass);
924 		conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
925 										conn->dbName, conn->pguser);
926 		if (conn->pgpass == NULL)
927 		{
928 			conn->pgpass = strdup(DefaultPassword);
929 			if (!conn->pgpass)
930 				goto oom_error;
931 		}
932 		else
933 			conn->dot_pgpass_used = true;
934 	}
935 
936 	/*
937 	 * Allow unix socket specification in the host name
938 	 */
939 	if (conn->pghost && is_absolute_path(conn->pghost))
940 	{
941 		if (conn->pgunixsocket)
942 			free(conn->pgunixsocket);
943 		conn->pgunixsocket = conn->pghost;
944 		conn->pghost = NULL;
945 	}
946 
947 	/*
948 	 * validate sslmode option
949 	 */
950 	if (conn->sslmode)
951 	{
952 		if (strcmp(conn->sslmode, "disable") != 0
953 			&& strcmp(conn->sslmode, "allow") != 0
954 			&& strcmp(conn->sslmode, "prefer") != 0
955 			&& strcmp(conn->sslmode, "require") != 0
956 			&& strcmp(conn->sslmode, "verify-ca") != 0
957 			&& strcmp(conn->sslmode, "verify-full") != 0)
958 		{
959 			conn->status = CONNECTION_BAD;
960 			printfPQExpBuffer(&conn->errorMessage,
961 							libpq_gettext("invalid sslmode value: \"%s\"\n"),
962 							  conn->sslmode);
963 			return false;
964 		}
965 
966 #ifndef USE_SSL
967 		switch (conn->sslmode[0])
968 		{
969 			case 'a':			/* "allow" */
970 			case 'p':			/* "prefer" */
971 
972 				/*
973 				 * warn user that an SSL connection will never be negotiated
974 				 * since SSL was not compiled in?
975 				 */
976 				break;
977 
978 			case 'r':			/* "require" */
979 			case 'v':			/* "verify-ca" or "verify-full" */
980 				conn->status = CONNECTION_BAD;
981 				printfPQExpBuffer(&conn->errorMessage,
982 								  libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
983 								  conn->sslmode);
984 				return false;
985 		}
986 #endif
987 	}
988 	else
989 	{
990 		conn->sslmode = strdup(DefaultSSLMode);
991 		if (!conn->sslmode)
992 			goto oom_error;
993 	}
994 
995 	/*
996 	 * Resolve special "auto" client_encoding from the locale
997 	 */
998 	if (conn->client_encoding_initial &&
999 		strcmp(conn->client_encoding_initial, "auto") == 0)
1000 	{
1001 		free(conn->client_encoding_initial);
1002 		conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
1003 		if (!conn->client_encoding_initial)
1004 			goto oom_error;
1005 	}
1006 
1007 	/*
1008 	 * Only if we get this far is it appropriate to try to connect. (We need a
1009 	 * state flag, rather than just the boolean result of this function, in
1010 	 * case someone tries to PQreset() the PGconn.)
1011 	 */
1012 	conn->options_valid = true;
1013 
1014 	return true;
1015 
1016 oom_error:
1017 	conn->status = CONNECTION_BAD;
1018 	printfPQExpBuffer(&conn->errorMessage,
1019 					  libpq_gettext("out of memory\n"));
1020 	return false;
1021 }
1022 
1023 /*
1024  *		PQconndefaults
1025  *
1026  * Construct a default connection options array, which identifies all the
1027  * available options and shows any default values that are available from the
1028  * environment etc.  On error (eg out of memory), NULL is returned.
1029  *
1030  * Using this function, an application may determine all possible options
1031  * and their current default values.
1032  *
1033  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1034  * and should be freed when no longer needed via PQconninfoFree().  (In prior
1035  * versions, the returned array was static, but that's not thread-safe.)
1036  * Pre-7.0 applications that use this function will see a small memory leak
1037  * until they are updated to call PQconninfoFree.
1038  */
1039 PQconninfoOption *
PQconndefaults(void)1040 PQconndefaults(void)
1041 {
1042 	PQExpBufferData errorBuf;
1043 	PQconninfoOption *connOptions;
1044 
1045 	/* We don't actually report any errors here, but callees want a buffer */
1046 	initPQExpBuffer(&errorBuf);
1047 	if (PQExpBufferDataBroken(errorBuf))
1048 		return NULL;			/* out of memory already :-( */
1049 
1050 	connOptions = conninfo_init(&errorBuf);
1051 	if (connOptions != NULL)
1052 	{
1053 		/* pass NULL errorBuf to ignore errors */
1054 		if (!conninfo_add_defaults(connOptions, NULL))
1055 		{
1056 			PQconninfoFree(connOptions);
1057 			connOptions = NULL;
1058 		}
1059 	}
1060 
1061 	termPQExpBuffer(&errorBuf);
1062 	return connOptions;
1063 }
1064 
1065 /* ----------------
1066  *		PQsetdbLogin
1067  *
1068  * establishes a connection to a postgres backend through the postmaster
1069  * at the specified host and port.
1070  *
1071  * returns a PGconn* which is needed for all subsequent libpq calls
1072  *
1073  * if the status field of the connection returned is CONNECTION_BAD,
1074  * then only the errorMessage is likely to be useful.
1075  * ----------------
1076  */
1077 PGconn *
PQsetdbLogin(const char * pghost,const char * pgport,const char * pgoptions,const char * pgtty,const char * dbName,const char * login,const char * pwd)1078 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1079 			 const char *pgtty, const char *dbName, const char *login,
1080 			 const char *pwd)
1081 {
1082 	PGconn	   *conn;
1083 
1084 	/*
1085 	 * Allocate memory for the conn structure
1086 	 */
1087 	conn = makeEmptyPGconn();
1088 	if (conn == NULL)
1089 		return NULL;
1090 
1091 	/*
1092 	 * If the dbName parameter contains what looks like a connection string,
1093 	 * parse it into conn struct using connectOptions1.
1094 	 */
1095 	if (dbName && recognized_connection_string(dbName))
1096 	{
1097 		if (!connectOptions1(conn, dbName))
1098 			return conn;
1099 	}
1100 	else
1101 	{
1102 		/*
1103 		 * Old-style path: first, parse an empty conninfo string in order to
1104 		 * set up the same defaults that PQconnectdb() would use.
1105 		 */
1106 		if (!connectOptions1(conn, ""))
1107 			return conn;
1108 
1109 		/* Insert dbName parameter value into struct */
1110 		if (dbName && dbName[0] != '\0')
1111 		{
1112 			if (conn->dbName)
1113 				free(conn->dbName);
1114 			conn->dbName = strdup(dbName);
1115 			if (!conn->dbName)
1116 				goto oom_error;
1117 		}
1118 	}
1119 
1120 	/*
1121 	 * Insert remaining parameters into struct, overriding defaults (as well
1122 	 * as any conflicting data from dbName taken as a conninfo).
1123 	 */
1124 	if (pghost && pghost[0] != '\0')
1125 	{
1126 		if (conn->pghost)
1127 			free(conn->pghost);
1128 		conn->pghost = strdup(pghost);
1129 		if (!conn->pghost)
1130 			goto oom_error;
1131 	}
1132 
1133 	if (pgport && pgport[0] != '\0')
1134 	{
1135 		if (conn->pgport)
1136 			free(conn->pgport);
1137 		conn->pgport = strdup(pgport);
1138 		if (!conn->pgport)
1139 			goto oom_error;
1140 	}
1141 
1142 	if (pgoptions && pgoptions[0] != '\0')
1143 	{
1144 		if (conn->pgoptions)
1145 			free(conn->pgoptions);
1146 		conn->pgoptions = strdup(pgoptions);
1147 		if (!conn->pgoptions)
1148 			goto oom_error;
1149 	}
1150 
1151 	if (pgtty && pgtty[0] != '\0')
1152 	{
1153 		if (conn->pgtty)
1154 			free(conn->pgtty);
1155 		conn->pgtty = strdup(pgtty);
1156 		if (!conn->pgtty)
1157 			goto oom_error;
1158 	}
1159 
1160 	if (login && login[0] != '\0')
1161 	{
1162 		if (conn->pguser)
1163 			free(conn->pguser);
1164 		conn->pguser = strdup(login);
1165 		if (!conn->pguser)
1166 			goto oom_error;
1167 	}
1168 
1169 	if (pwd && pwd[0] != '\0')
1170 	{
1171 		if (conn->pgpass)
1172 			free(conn->pgpass);
1173 		conn->pgpass = strdup(pwd);
1174 		if (!conn->pgpass)
1175 			goto oom_error;
1176 	}
1177 
1178 	/*
1179 	 * Compute derived options
1180 	 */
1181 	if (!connectOptions2(conn))
1182 		return conn;
1183 
1184 	/*
1185 	 * Connect to the database
1186 	 */
1187 	if (connectDBStart(conn))
1188 		(void) connectDBComplete(conn);
1189 
1190 	return conn;
1191 
1192 oom_error:
1193 	conn->status = CONNECTION_BAD;
1194 	printfPQExpBuffer(&conn->errorMessage,
1195 					  libpq_gettext("out of memory\n"));
1196 	return conn;
1197 }
1198 
1199 
1200 /* ----------
1201  * connectNoDelay -
1202  * Sets the TCP_NODELAY socket option.
1203  * Returns 1 if successful, 0 if not.
1204  * ----------
1205  */
1206 static int
connectNoDelay(PGconn * conn)1207 connectNoDelay(PGconn *conn)
1208 {
1209 #ifdef	TCP_NODELAY
1210 	int			on = 1;
1211 
1212 	if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1213 				   (char *) &on,
1214 				   sizeof(on)) < 0)
1215 	{
1216 		char		sebuf[256];
1217 
1218 		appendPQExpBuffer(&conn->errorMessage,
1219 			libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1220 						  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1221 		return 0;
1222 	}
1223 #endif
1224 
1225 	return 1;
1226 }
1227 
1228 
1229 /* ----------
1230  * connectFailureMessage -
1231  * create a friendly error message on connection failure.
1232  * ----------
1233  */
1234 static void
connectFailureMessage(PGconn * conn,int errorno)1235 connectFailureMessage(PGconn *conn, int errorno)
1236 {
1237 	char		sebuf[256];
1238 
1239 #ifdef HAVE_UNIX_SOCKETS
1240 	if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1241 	{
1242 		char		service[NI_MAXHOST];
1243 
1244 		pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1245 						   NULL, 0,
1246 						   service, sizeof(service),
1247 						   NI_NUMERICSERV);
1248 		appendPQExpBuffer(&conn->errorMessage,
1249 						  libpq_gettext("could not connect to server: %s\n"
1250 							"\tIs the server running locally and accepting\n"
1251 							"\tconnections on Unix domain socket \"%s\"?\n"),
1252 						  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1253 						  service);
1254 	}
1255 	else
1256 #endif   /* HAVE_UNIX_SOCKETS */
1257 	{
1258 		char		host_addr[NI_MAXHOST];
1259 		const char *displayed_host;
1260 		struct sockaddr_storage *addr = &conn->raddr.addr;
1261 
1262 		/*
1263 		 * Optionally display the network address with the hostname. This is
1264 		 * useful to distinguish between IPv4 and IPv6 connections.
1265 		 */
1266 		if (conn->pghostaddr != NULL)
1267 			strlcpy(host_addr, conn->pghostaddr, NI_MAXHOST);
1268 		else if (addr->ss_family == AF_INET)
1269 		{
1270 			if (inet_net_ntop(AF_INET,
1271 							  &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1272 							  32,
1273 							  host_addr, sizeof(host_addr)) == NULL)
1274 				strcpy(host_addr, "???");
1275 		}
1276 #ifdef HAVE_IPV6
1277 		else if (addr->ss_family == AF_INET6)
1278 		{
1279 			if (inet_net_ntop(AF_INET6,
1280 						  &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1281 							  128,
1282 							  host_addr, sizeof(host_addr)) == NULL)
1283 				strcpy(host_addr, "???");
1284 		}
1285 #endif
1286 		else
1287 			strcpy(host_addr, "???");
1288 
1289 		if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1290 			displayed_host = conn->pghostaddr;
1291 		else if (conn->pghost && conn->pghost[0] != '\0')
1292 			displayed_host = conn->pghost;
1293 		else
1294 			displayed_host = DefaultHost;
1295 
1296 		/*
1297 		 * If the user did not supply an IP address using 'hostaddr', and
1298 		 * 'host' was missing or does not match our lookup, display the
1299 		 * looked-up IP address.
1300 		 */
1301 		if ((conn->pghostaddr == NULL) &&
1302 			(conn->pghost == NULL || strcmp(conn->pghost, host_addr) != 0))
1303 			appendPQExpBuffer(&conn->errorMessage,
1304 							libpq_gettext("could not connect to server: %s\n"
1305 				"\tIs the server running on host \"%s\" (%s) and accepting\n"
1306 									   "\tTCP/IP connections on port %s?\n"),
1307 							  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1308 							  displayed_host,
1309 							  host_addr,
1310 							  conn->pgport);
1311 		else
1312 			appendPQExpBuffer(&conn->errorMessage,
1313 							libpq_gettext("could not connect to server: %s\n"
1314 					 "\tIs the server running on host \"%s\" and accepting\n"
1315 									   "\tTCP/IP connections on port %s?\n"),
1316 							  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1317 							  displayed_host,
1318 							  conn->pgport);
1319 	}
1320 }
1321 
1322 /*
1323  * Should we use keepalives?  Returns 1 if yes, 0 if no, and -1 if
1324  * conn->keepalives is set to a value which is not parseable as an
1325  * integer.
1326  */
1327 static int
useKeepalives(PGconn * conn)1328 useKeepalives(PGconn *conn)
1329 {
1330 	char	   *ep;
1331 	int			val;
1332 
1333 	if (conn->keepalives == NULL)
1334 		return 1;
1335 	val = strtol(conn->keepalives, &ep, 10);
1336 	if (*ep)
1337 		return -1;
1338 	return val != 0 ? 1 : 0;
1339 }
1340 
1341 #ifndef WIN32
1342 /*
1343  * Set the keepalive idle timer.
1344  */
1345 static int
setKeepalivesIdle(PGconn * conn)1346 setKeepalivesIdle(PGconn *conn)
1347 {
1348 	int			idle;
1349 
1350 	if (conn->keepalives_idle == NULL)
1351 		return 1;
1352 
1353 	idle = atoi(conn->keepalives_idle);
1354 	if (idle < 0)
1355 		idle = 0;
1356 
1357 #ifdef PG_TCP_KEEPALIVE_IDLE
1358 	if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1359 				   (char *) &idle, sizeof(idle)) < 0)
1360 	{
1361 		char		sebuf[256];
1362 
1363 		appendPQExpBuffer(&conn->errorMessage,
1364 						  libpq_gettext("setsockopt(%s) failed: %s\n"),
1365 						  PG_TCP_KEEPALIVE_IDLE_STR,
1366 						  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1367 		return 0;
1368 	}
1369 #endif
1370 
1371 	return 1;
1372 }
1373 
1374 /*
1375  * Set the keepalive interval.
1376  */
1377 static int
setKeepalivesInterval(PGconn * conn)1378 setKeepalivesInterval(PGconn *conn)
1379 {
1380 	int			interval;
1381 
1382 	if (conn->keepalives_interval == NULL)
1383 		return 1;
1384 
1385 	interval = atoi(conn->keepalives_interval);
1386 	if (interval < 0)
1387 		interval = 0;
1388 
1389 #ifdef TCP_KEEPINTVL
1390 	if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1391 				   (char *) &interval, sizeof(interval)) < 0)
1392 	{
1393 		char		sebuf[256];
1394 
1395 		appendPQExpBuffer(&conn->errorMessage,
1396 						  libpq_gettext("setsockopt(%s) failed: %s\n"),
1397 						  "TCP_KEEPINTVL",
1398 						  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1399 		return 0;
1400 	}
1401 #endif
1402 
1403 	return 1;
1404 }
1405 
1406 /*
1407  * Set the count of lost keepalive packets that will trigger a connection
1408  * break.
1409  */
1410 static int
setKeepalivesCount(PGconn * conn)1411 setKeepalivesCount(PGconn *conn)
1412 {
1413 	int			count;
1414 
1415 	if (conn->keepalives_count == NULL)
1416 		return 1;
1417 
1418 	count = atoi(conn->keepalives_count);
1419 	if (count < 0)
1420 		count = 0;
1421 
1422 #ifdef TCP_KEEPCNT
1423 	if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1424 				   (char *) &count, sizeof(count)) < 0)
1425 	{
1426 		char		sebuf[256];
1427 
1428 		appendPQExpBuffer(&conn->errorMessage,
1429 						  libpq_gettext("setsockopt(%s) failed: %s\n"),
1430 						  "TCP_KEEPCNT",
1431 						  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1432 		return 0;
1433 	}
1434 #endif
1435 
1436 	return 1;
1437 }
1438 #else							/* WIN32 */
1439 #ifdef SIO_KEEPALIVE_VALS
1440 /*
1441  * Enable keepalives and set the keepalive values on Win32,
1442  * where they are always set in one batch.
1443  */
1444 static int
setKeepalivesWin32(PGconn * conn)1445 setKeepalivesWin32(PGconn *conn)
1446 {
1447 	struct tcp_keepalive ka;
1448 	DWORD		retsize;
1449 	int			idle = 0;
1450 	int			interval = 0;
1451 
1452 	if (conn->keepalives_idle)
1453 		idle = atoi(conn->keepalives_idle);
1454 	if (idle <= 0)
1455 		idle = 2 * 60 * 60;		/* 2 hours = default */
1456 
1457 	if (conn->keepalives_interval)
1458 		interval = atoi(conn->keepalives_interval);
1459 	if (interval <= 0)
1460 		interval = 1;			/* 1 second = default */
1461 
1462 	ka.onoff = 1;
1463 	ka.keepalivetime = idle * 1000;
1464 	ka.keepaliveinterval = interval * 1000;
1465 
1466 	if (WSAIoctl(conn->sock,
1467 				 SIO_KEEPALIVE_VALS,
1468 				 (LPVOID) &ka,
1469 				 sizeof(ka),
1470 				 NULL,
1471 				 0,
1472 				 &retsize,
1473 				 NULL,
1474 				 NULL)
1475 		!= 0)
1476 	{
1477 		appendPQExpBuffer(&conn->errorMessage,
1478 				 libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1479 						  WSAGetLastError());
1480 		return 0;
1481 	}
1482 	return 1;
1483 }
1484 #endif   /* SIO_KEEPALIVE_VALS */
1485 #endif   /* WIN32 */
1486 
1487 /* ----------
1488  * connectDBStart -
1489  *		Begin the process of making a connection to the backend.
1490  *
1491  * Returns 1 if successful, 0 if not.
1492  * ----------
1493  */
1494 static int
connectDBStart(PGconn * conn)1495 connectDBStart(PGconn *conn)
1496 {
1497 	int			portnum;
1498 	char		portstr[MAXPGPATH];
1499 	struct addrinfo *addrs = NULL;
1500 	struct addrinfo hint;
1501 	const char *node;
1502 	int			ret;
1503 
1504 	if (!conn)
1505 		return 0;
1506 
1507 	if (!conn->options_valid)
1508 		goto connect_errReturn;
1509 
1510 	/* Ensure our buffers are empty */
1511 	conn->inStart = conn->inCursor = conn->inEnd = 0;
1512 	conn->outCount = 0;
1513 
1514 	/*
1515 	 * Determine the parameters to pass to pg_getaddrinfo_all.
1516 	 */
1517 
1518 	/* Initialize hint structure */
1519 	MemSet(&hint, 0, sizeof(hint));
1520 	hint.ai_socktype = SOCK_STREAM;
1521 	hint.ai_family = AF_UNSPEC;
1522 
1523 	/* Set up port number as a string */
1524 	if (conn->pgport != NULL && conn->pgport[0] != '\0')
1525 	{
1526 		portnum = atoi(conn->pgport);
1527 		if (portnum < 1 || portnum > 65535)
1528 		{
1529 			appendPQExpBuffer(&conn->errorMessage,
1530 							  libpq_gettext("invalid port number: \"%s\"\n"),
1531 							  conn->pgport);
1532 			conn->options_valid = false;
1533 			goto connect_errReturn;
1534 		}
1535 	}
1536 	else
1537 		portnum = DEF_PGPORT;
1538 	snprintf(portstr, sizeof(portstr), "%d", portnum);
1539 
1540 	if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1541 	{
1542 		/* Using pghostaddr avoids a hostname lookup */
1543 		node = conn->pghostaddr;
1544 		hint.ai_family = AF_UNSPEC;
1545 		hint.ai_flags = AI_NUMERICHOST;
1546 	}
1547 	else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1548 	{
1549 		/* Using pghost, so we have to look-up the hostname */
1550 		node = conn->pghost;
1551 		hint.ai_family = AF_UNSPEC;
1552 	}
1553 	else
1554 	{
1555 #ifdef HAVE_UNIX_SOCKETS
1556 		/* pghostaddr and pghost are NULL, so use Unix domain socket */
1557 		node = NULL;
1558 		hint.ai_family = AF_UNIX;
1559 		UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1560 		if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
1561 		{
1562 			appendPQExpBuffer(&conn->errorMessage,
1563 							  libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
1564 							  portstr,
1565 							  (int) (UNIXSOCK_PATH_BUFLEN - 1));
1566 			conn->options_valid = false;
1567 			goto connect_errReturn;
1568 		}
1569 #else
1570 		/* Without Unix sockets, default to localhost instead */
1571 		node = DefaultHost;
1572 		hint.ai_family = AF_UNSPEC;
1573 #endif   /* HAVE_UNIX_SOCKETS */
1574 	}
1575 
1576 	/* Use pg_getaddrinfo_all() to resolve the address */
1577 	ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1578 	if (ret || !addrs)
1579 	{
1580 		if (node)
1581 			appendPQExpBuffer(&conn->errorMessage,
1582 							  libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1583 							  node, gai_strerror(ret));
1584 		else
1585 			appendPQExpBuffer(&conn->errorMessage,
1586 							  libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1587 							  portstr, gai_strerror(ret));
1588 		if (addrs)
1589 			pg_freeaddrinfo_all(hint.ai_family, addrs);
1590 		conn->options_valid = false;
1591 		goto connect_errReturn;
1592 	}
1593 
1594 	/*
1595 	 * Set up to try to connect to the first address.
1596 	 */
1597 	conn->addrlist = addrs;
1598 	conn->addr_cur = addrs;
1599 	conn->addrlist_family = hint.ai_family;
1600 	conn->try_next_addr = false;
1601 	conn->is_new_addr = true;
1602 	conn->status = CONNECTION_NEEDED;
1603 
1604 	/*
1605 	 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1606 	 * so that it can easily be re-executed if needed again during the
1607 	 * asynchronous startup process.  However, we must run it once here,
1608 	 * because callers expect a success return from this routine to mean that
1609 	 * we are in PGRES_POLLING_WRITING connection state.
1610 	 */
1611 	if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1612 		return 1;
1613 
1614 connect_errReturn:
1615 
1616 	/*
1617 	 * If we managed to open a socket, close it immediately rather than
1618 	 * waiting till PQfinish.  (The application cannot have gotten the socket
1619 	 * from PQsocket yet, so this doesn't risk breaking anything.)
1620 	 */
1621 	pqDropConnection(conn, true);
1622 	conn->status = CONNECTION_BAD;
1623 	return 0;
1624 }
1625 
1626 
1627 /*
1628  *		connectDBComplete
1629  *
1630  * Block and complete a connection.
1631  *
1632  * Returns 1 on success, 0 on failure.
1633  */
1634 static int
connectDBComplete(PGconn * conn)1635 connectDBComplete(PGconn *conn)
1636 {
1637 	PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1638 	time_t		finish_time = ((time_t) -1);
1639 
1640 	if (conn == NULL || conn->status == CONNECTION_BAD)
1641 		return 0;
1642 
1643 	/*
1644 	 * Set up a time limit, if connect_timeout isn't zero.
1645 	 */
1646 	if (conn->connect_timeout != NULL)
1647 	{
1648 		int			timeout = atoi(conn->connect_timeout);
1649 
1650 		if (timeout > 0)
1651 		{
1652 			/*
1653 			 * Rounding could cause connection to fail; need at least 2 secs
1654 			 */
1655 			if (timeout < 2)
1656 				timeout = 2;
1657 			/* calculate the finish time based on start + timeout */
1658 			finish_time = time(NULL) + timeout;
1659 		}
1660 	}
1661 
1662 	for (;;)
1663 	{
1664 		/*
1665 		 * Wait, if necessary.  Note that the initial state (just after
1666 		 * PQconnectStart) is to wait for the socket to select for writing.
1667 		 */
1668 		switch (flag)
1669 		{
1670 			case PGRES_POLLING_OK:
1671 
1672 				/*
1673 				 * Reset stored error messages since we now have a working
1674 				 * connection
1675 				 */
1676 				resetPQExpBuffer(&conn->errorMessage);
1677 				return 1;		/* success! */
1678 
1679 			case PGRES_POLLING_READING:
1680 				if (pqWaitTimed(1, 0, conn, finish_time))
1681 				{
1682 					/* hard failure, eg select() problem, aborts everything */
1683 					conn->status = CONNECTION_BAD;
1684 					return 0;
1685 				}
1686 				break;
1687 
1688 			case PGRES_POLLING_WRITING:
1689 				if (pqWaitTimed(0, 1, conn, finish_time))
1690 				{
1691 					/* hard failure, eg select() problem, aborts everything */
1692 					conn->status = CONNECTION_BAD;
1693 					return 0;
1694 				}
1695 				break;
1696 
1697 			default:
1698 				/* Just in case we failed to set it in PQconnectPoll */
1699 				conn->status = CONNECTION_BAD;
1700 				return 0;
1701 		}
1702 
1703 		/*
1704 		 * Now try to advance the state machine.
1705 		 */
1706 		flag = PQconnectPoll(conn);
1707 	}
1708 }
1709 
1710 /* ----------------
1711  *		PQconnectPoll
1712  *
1713  * Poll an asynchronous connection.
1714  *
1715  * Returns a PostgresPollingStatusType.
1716  * Before calling this function, use select(2) to determine when data
1717  * has arrived..
1718  *
1719  * You must call PQfinish whether or not this fails.
1720  *
1721  * This function and PQconnectStart are intended to allow connections to be
1722  * made without blocking the execution of your program on remote I/O. However,
1723  * there are a number of caveats:
1724  *
1725  *	 o	If you call PQtrace, ensure that the stream object into which you trace
1726  *		will not block.
1727  *	 o	If you do not supply an IP address for the remote host (i.e. you
1728  *		supply a host name instead) then PQconnectStart will block on
1729  *		gethostbyname.  You will be fine if using Unix sockets (i.e. by
1730  *		supplying neither a host name nor a host address).
1731  *	 o	If your backend wants to use Kerberos authentication then you must
1732  *		supply both a host name and a host address, otherwise this function
1733  *		may block on gethostname.
1734  *
1735  * ----------------
1736  */
1737 PostgresPollingStatusType
PQconnectPoll(PGconn * conn)1738 PQconnectPoll(PGconn *conn)
1739 {
1740 	bool		need_new_connection = false;
1741 	PGresult   *res;
1742 	char		sebuf[256];
1743 	int			optval;
1744 
1745 	if (conn == NULL)
1746 		return PGRES_POLLING_FAILED;
1747 
1748 	/* Get the new data */
1749 	switch (conn->status)
1750 	{
1751 			/*
1752 			 * We really shouldn't have been polled in these two cases, but we
1753 			 * can handle it.
1754 			 */
1755 		case CONNECTION_BAD:
1756 			return PGRES_POLLING_FAILED;
1757 		case CONNECTION_OK:
1758 			return PGRES_POLLING_OK;
1759 
1760 			/* These are reading states */
1761 		case CONNECTION_AWAITING_RESPONSE:
1762 		case CONNECTION_AUTH_OK:
1763 			{
1764 				/* Load waiting data */
1765 				int			n = pqReadData(conn);
1766 
1767 				if (n < 0)
1768 					goto error_return;
1769 				if (n == 0)
1770 					return PGRES_POLLING_READING;
1771 
1772 				break;
1773 			}
1774 
1775 			/* These are writing states, so we just proceed. */
1776 		case CONNECTION_STARTED:
1777 		case CONNECTION_MADE:
1778 			break;
1779 
1780 			/* We allow pqSetenvPoll to decide whether to proceed. */
1781 		case CONNECTION_SETENV:
1782 			break;
1783 
1784 			/* Special cases: proceed without waiting. */
1785 		case CONNECTION_SSL_STARTUP:
1786 		case CONNECTION_NEEDED:
1787 			break;
1788 
1789 		default:
1790 			appendPQExpBufferStr(&conn->errorMessage,
1791 								 libpq_gettext(
1792 											   "invalid connection state, "
1793 								 "probably indicative of memory corruption\n"
1794 											   ));
1795 			goto error_return;
1796 	}
1797 
1798 
1799 keep_going:						/* We will come back to here until there is
1800 								 * nothing left to do. */
1801 
1802 	/* Time to advance to next address? */
1803 	if (conn->try_next_addr)
1804 	{
1805 		if (conn->addr_cur && conn->addr_cur->ai_next)
1806 		{
1807 			conn->addr_cur = conn->addr_cur->ai_next;
1808 			conn->is_new_addr = true;
1809 		}
1810 		else
1811 		{
1812 			/*
1813 			 * Oops, no more addresses.  An appropriate error message is
1814 			 * already set up, so just set the right status.
1815 			 */
1816 			goto error_return;
1817 		}
1818 		conn->try_next_addr = false;
1819 	}
1820 
1821 	/* Reset connection state machine? */
1822 	if (conn->is_new_addr)
1823 	{
1824 		/*
1825 		 * (Re) initialize our connection control variables for a set of
1826 		 * connection attempts to a single server address.  These variables
1827 		 * must persist across individual connection attempts, but we must
1828 		 * reset them when we start to consider a new address (since it might
1829 		 * not be the same server).
1830 		 */
1831 		conn->pversion = PG_PROTOCOL(3, 0);
1832 		conn->send_appname = true;
1833 #ifdef USE_SSL
1834 		/* initialize these values based on SSL mode */
1835 		conn->allow_ssl_try = (conn->sslmode[0] != 'd');		/* "disable" */
1836 		conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
1837 #endif
1838 
1839 		conn->is_new_addr = false;
1840 		need_new_connection = true;
1841 	}
1842 
1843 	/* Force a new connection (perhaps to the same server as before)? */
1844 	if (need_new_connection)
1845 	{
1846 		/* Drop any existing connection */
1847 		pqDropConnection(conn, true);
1848 
1849 		/* Reset all state obtained from old server */
1850 		pqDropServerData(conn);
1851 
1852 		/* Drop any PGresult we might have, too */
1853 		conn->asyncStatus = PGASYNC_IDLE;
1854 		conn->xactStatus = PQTRANS_IDLE;
1855 		pqClearAsyncResult(conn);
1856 
1857 		/* Reset conn->status to put the state machine in the right state */
1858 		conn->status = CONNECTION_NEEDED;
1859 
1860 		need_new_connection = false;
1861 	}
1862 
1863 	/* Now try to advance the state machine for this connection */
1864 	switch (conn->status)
1865 	{
1866 		case CONNECTION_NEEDED:
1867 			{
1868 				/*
1869 				 * Try to initiate a connection to one of the addresses
1870 				 * returned by pg_getaddrinfo_all().  conn->addr_cur is the
1871 				 * next one to try.
1872 				 *
1873 				 * The extra level of braces here is historical.  It's not
1874 				 * worth reindenting this whole switch case to remove 'em.
1875 				 */
1876 				{
1877 					struct addrinfo *addr_cur = conn->addr_cur;
1878 
1879 					if (addr_cur == NULL)
1880 					{
1881 						/*
1882 						 * Ooops, no more addresses.  An appropriate error
1883 						 * message is already set up, so just set the right
1884 						 * status.
1885 						 */
1886 						goto error_return;
1887 					}
1888 
1889 					/* Remember current address for possible error msg */
1890 					memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1891 						   addr_cur->ai_addrlen);
1892 					conn->raddr.salen = addr_cur->ai_addrlen;
1893 
1894 					conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1895 					if (conn->sock == PGINVALID_SOCKET)
1896 					{
1897 						/*
1898 						 * Silently ignore socket() failure if we have more
1899 						 * addresses to try; this reduces useless chatter in
1900 						 * cases where the address list includes both IPv4 and
1901 						 * IPv6 but kernel only accepts one family.
1902 						 */
1903 						if (addr_cur->ai_next != NULL)
1904 						{
1905 							conn->try_next_addr = true;
1906 							goto keep_going;
1907 						}
1908 						appendPQExpBuffer(&conn->errorMessage,
1909 							  libpq_gettext("could not create socket: %s\n"),
1910 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1911 						goto error_return;
1912 					}
1913 
1914 					/*
1915 					 * Select socket options: no delay of outgoing data for
1916 					 * TCP sockets, nonblock mode, close-on-exec.  Try the
1917 					 * next address if any of this fails.
1918 					 */
1919 					if (!IS_AF_UNIX(addr_cur->ai_family))
1920 					{
1921 						if (!connectNoDelay(conn))
1922 						{
1923 							/* error message already created */
1924 							conn->try_next_addr = true;
1925 							goto keep_going;
1926 						}
1927 					}
1928 					if (!pg_set_noblock(conn->sock))
1929 					{
1930 						appendPQExpBuffer(&conn->errorMessage,
1931 										  libpq_gettext("could not set socket to nonblocking mode: %s\n"),
1932 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1933 						conn->try_next_addr = true;
1934 						goto keep_going;
1935 					}
1936 
1937 #ifdef F_SETFD
1938 					if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1939 					{
1940 						appendPQExpBuffer(&conn->errorMessage,
1941 										  libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1942 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1943 						conn->try_next_addr = true;
1944 						goto keep_going;
1945 					}
1946 #endif   /* F_SETFD */
1947 
1948 					if (!IS_AF_UNIX(addr_cur->ai_family))
1949 					{
1950 #ifndef WIN32
1951 						int			on = 1;
1952 #endif
1953 						int			usekeepalives = useKeepalives(conn);
1954 						int			err = 0;
1955 
1956 						if (usekeepalives < 0)
1957 						{
1958 							appendPQExpBufferStr(&conn->errorMessage,
1959 												 libpq_gettext("keepalives parameter must be an integer\n"));
1960 							err = 1;
1961 						}
1962 						else if (usekeepalives == 0)
1963 						{
1964 							/* Do nothing */
1965 						}
1966 #ifndef WIN32
1967 						else if (setsockopt(conn->sock,
1968 											SOL_SOCKET, SO_KEEPALIVE,
1969 											(char *) &on, sizeof(on)) < 0)
1970 						{
1971 							appendPQExpBuffer(&conn->errorMessage,
1972 											  libpq_gettext("setsockopt(%s) failed: %s\n"),
1973 											  "SO_KEEPALIVE",
1974 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1975 							err = 1;
1976 						}
1977 						else if (!setKeepalivesIdle(conn)
1978 								 || !setKeepalivesInterval(conn)
1979 								 || !setKeepalivesCount(conn))
1980 							err = 1;
1981 #else							/* WIN32 */
1982 #ifdef SIO_KEEPALIVE_VALS
1983 						else if (!setKeepalivesWin32(conn))
1984 							err = 1;
1985 #endif   /* SIO_KEEPALIVE_VALS */
1986 #endif   /* WIN32 */
1987 
1988 						if (err)
1989 						{
1990 							conn->try_next_addr = true;
1991 							goto keep_going;
1992 						}
1993 					}
1994 
1995 					/*----------
1996 					 * We have three methods of blocking SIGPIPE during
1997 					 * send() calls to this socket:
1998 					 *
1999 					 *	- setsockopt(sock, SO_NOSIGPIPE)
2000 					 *	- send(sock, ..., MSG_NOSIGNAL)
2001 					 *	- setting the signal mask to SIG_IGN during send()
2002 					 *
2003 					 * The third method requires three syscalls per send,
2004 					 * so we prefer either of the first two, but they are
2005 					 * less portable.  The state is tracked in the following
2006 					 * members of PGconn:
2007 					 *
2008 					 * conn->sigpipe_so		- we have set up SO_NOSIGPIPE
2009 					 * conn->sigpipe_flag	- we're specifying MSG_NOSIGNAL
2010 					 *
2011 					 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2012 					 * and we're done.  Otherwise, set sigpipe_flag so that
2013 					 * we will try MSG_NOSIGNAL on sends.  If we get an error
2014 					 * with MSG_NOSIGNAL, we'll clear that flag and revert to
2015 					 * signal masking.
2016 					 *----------
2017 					 */
2018 					conn->sigpipe_so = false;
2019 #ifdef MSG_NOSIGNAL
2020 					conn->sigpipe_flag = true;
2021 #else
2022 					conn->sigpipe_flag = false;
2023 #endif   /* MSG_NOSIGNAL */
2024 
2025 #ifdef SO_NOSIGPIPE
2026 					optval = 1;
2027 					if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2028 								   (char *) &optval, sizeof(optval)) == 0)
2029 					{
2030 						conn->sigpipe_so = true;
2031 						conn->sigpipe_flag = false;
2032 					}
2033 #endif   /* SO_NOSIGPIPE */
2034 
2035 					/*
2036 					 * Start/make connection.  This should not block, since we
2037 					 * are in nonblock mode.  If it does, well, too bad.
2038 					 */
2039 					if (connect(conn->sock, addr_cur->ai_addr,
2040 								addr_cur->ai_addrlen) < 0)
2041 					{
2042 						if (SOCK_ERRNO == EINPROGRESS ||
2043 #ifdef WIN32
2044 							SOCK_ERRNO == EWOULDBLOCK ||
2045 #endif
2046 							SOCK_ERRNO == EINTR)
2047 						{
2048 							/*
2049 							 * This is fine - we're in non-blocking mode, and
2050 							 * the connection is in progress.  Tell caller to
2051 							 * wait for write-ready on socket.
2052 							 */
2053 							conn->status = CONNECTION_STARTED;
2054 							return PGRES_POLLING_WRITING;
2055 						}
2056 						/* otherwise, trouble */
2057 					}
2058 					else
2059 					{
2060 						/*
2061 						 * Hm, we're connected already --- seems the "nonblock
2062 						 * connection" wasn't.  Advance the state machine and
2063 						 * go do the next stuff.
2064 						 */
2065 						conn->status = CONNECTION_STARTED;
2066 						goto keep_going;
2067 					}
2068 
2069 					/*
2070 					 * This connection failed.  Add the error report to
2071 					 * conn->errorMessage, then try the next address if any.
2072 					 */
2073 					connectFailureMessage(conn, SOCK_ERRNO);
2074 					conn->try_next_addr = true;
2075 					goto keep_going;
2076 				}
2077 			}
2078 
2079 		case CONNECTION_STARTED:
2080 			{
2081 				ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2082 
2083 				/*
2084 				 * Write ready, since we've made it here, so the connection
2085 				 * has been made ... or has failed.
2086 				 */
2087 
2088 				/*
2089 				 * Now check (using getsockopt) that there is not an error
2090 				 * state waiting for us on the socket.
2091 				 */
2092 
2093 				if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2094 							   (char *) &optval, &optlen) == -1)
2095 				{
2096 					appendPQExpBuffer(&conn->errorMessage,
2097 					libpq_gettext("could not get socket error status: %s\n"),
2098 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2099 					goto error_return;
2100 				}
2101 				else if (optval != 0)
2102 				{
2103 					/*
2104 					 * When using a nonblocking connect, we will typically see
2105 					 * connect failures at this point, so provide a friendly
2106 					 * error message.
2107 					 */
2108 					connectFailureMessage(conn, optval);
2109 
2110 					/*
2111 					 * Try the next address if any, just as in the case where
2112 					 * connect() returned failure immediately.
2113 					 */
2114 					conn->try_next_addr = true;
2115 					goto keep_going;
2116 				}
2117 
2118 				/* Fill in the client address */
2119 				conn->laddr.salen = sizeof(conn->laddr.addr);
2120 				if (getsockname(conn->sock,
2121 								(struct sockaddr *) & conn->laddr.addr,
2122 								&conn->laddr.salen) < 0)
2123 				{
2124 					appendPQExpBuffer(&conn->errorMessage,
2125 									  libpq_gettext("could not get client address from socket: %s\n"),
2126 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2127 					goto error_return;
2128 				}
2129 
2130 				/*
2131 				 * Make sure we can write before advancing to next step.
2132 				 */
2133 				conn->status = CONNECTION_MADE;
2134 				return PGRES_POLLING_WRITING;
2135 			}
2136 
2137 		case CONNECTION_MADE:
2138 			{
2139 				char	   *startpacket;
2140 				int			packetlen;
2141 
2142 #ifdef HAVE_UNIX_SOCKETS
2143 
2144 				/*
2145 				 * Implement requirepeer check, if requested and it's a
2146 				 * Unix-domain socket.
2147 				 */
2148 				if (conn->requirepeer && conn->requirepeer[0] &&
2149 					IS_AF_UNIX(conn->raddr.addr.ss_family))
2150 				{
2151 					char		pwdbuf[BUFSIZ];
2152 					struct passwd pass_buf;
2153 					struct passwd *pass;
2154 					int			passerr;
2155 					uid_t		uid;
2156 					gid_t		gid;
2157 
2158 					errno = 0;
2159 					if (getpeereid(conn->sock, &uid, &gid) != 0)
2160 					{
2161 						/*
2162 						 * Provide special error message if getpeereid is a
2163 						 * stub
2164 						 */
2165 						if (errno == ENOSYS)
2166 							appendPQExpBufferStr(&conn->errorMessage,
2167 												 libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2168 						else
2169 							appendPQExpBuffer(&conn->errorMessage,
2170 											  libpq_gettext("could not get peer credentials: %s\n"),
2171 									pqStrerror(errno, sebuf, sizeof(sebuf)));
2172 						goto error_return;
2173 					}
2174 
2175 					passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2176 					if (pass == NULL)
2177 					{
2178 						if (passerr != 0)
2179 							appendPQExpBuffer(&conn->errorMessage,
2180 											  libpq_gettext("could not look up local user ID %d: %s\n"),
2181 											  (int) uid,
2182 								  pqStrerror(passerr, sebuf, sizeof(sebuf)));
2183 						else
2184 							appendPQExpBuffer(&conn->errorMessage,
2185 											  libpq_gettext("local user with ID %d does not exist\n"),
2186 											  (int) uid);
2187 						goto error_return;
2188 					}
2189 
2190 					if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2191 					{
2192 						appendPQExpBuffer(&conn->errorMessage,
2193 										  libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2194 										  conn->requirepeer, pass->pw_name);
2195 						goto error_return;
2196 					}
2197 				}
2198 #endif   /* HAVE_UNIX_SOCKETS */
2199 
2200 #ifdef USE_SSL
2201 
2202 				/*
2203 				 * If SSL is enabled and we haven't already got it running,
2204 				 * request it instead of sending the startup message.
2205 				 */
2206 				if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2207 				{
2208 					/* Don't bother requesting SSL over a Unix socket */
2209 					conn->allow_ssl_try = false;
2210 				}
2211 				if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2212 					!conn->ssl_in_use)
2213 				{
2214 					ProtocolVersion pv;
2215 
2216 					/*
2217 					 * Send the SSL request packet.
2218 					 *
2219 					 * Theoretically, this could block, but it really
2220 					 * shouldn't since we only got here if the socket is
2221 					 * write-ready.
2222 					 */
2223 					pv = htonl(NEGOTIATE_SSL_CODE);
2224 					if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2225 					{
2226 						appendPQExpBuffer(&conn->errorMessage,
2227 										  libpq_gettext("could not send SSL negotiation packet: %s\n"),
2228 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2229 						goto error_return;
2230 					}
2231 					/* Ok, wait for response */
2232 					conn->status = CONNECTION_SSL_STARTUP;
2233 					return PGRES_POLLING_READING;
2234 				}
2235 #endif   /* USE_SSL */
2236 
2237 				/*
2238 				 * Build the startup packet.
2239 				 */
2240 				if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2241 					startpacket = pqBuildStartupPacket3(conn, &packetlen,
2242 														EnvironmentOptions);
2243 				else
2244 					startpacket = pqBuildStartupPacket2(conn, &packetlen,
2245 														EnvironmentOptions);
2246 				if (!startpacket)
2247 				{
2248 					/*
2249 					 * will not appendbuffer here, since it's likely to also
2250 					 * run out of memory
2251 					 */
2252 					printfPQExpBuffer(&conn->errorMessage,
2253 									  libpq_gettext("out of memory\n"));
2254 					goto error_return;
2255 				}
2256 
2257 				/*
2258 				 * Send the startup packet.
2259 				 *
2260 				 * Theoretically, this could block, but it really shouldn't
2261 				 * since we only got here if the socket is write-ready.
2262 				 */
2263 				if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2264 				{
2265 					appendPQExpBuffer(&conn->errorMessage,
2266 						libpq_gettext("could not send startup packet: %s\n"),
2267 							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2268 					free(startpacket);
2269 					goto error_return;
2270 				}
2271 
2272 				free(startpacket);
2273 
2274 				conn->status = CONNECTION_AWAITING_RESPONSE;
2275 				return PGRES_POLLING_READING;
2276 			}
2277 
2278 			/*
2279 			 * Handle SSL negotiation: wait for postmaster messages and
2280 			 * respond as necessary.
2281 			 */
2282 		case CONNECTION_SSL_STARTUP:
2283 			{
2284 #ifdef USE_SSL
2285 				PostgresPollingStatusType pollres;
2286 
2287 				/*
2288 				 * On first time through, get the postmaster's response to our
2289 				 * SSL negotiation packet.
2290 				 */
2291 				if (!conn->ssl_in_use)
2292 				{
2293 					/*
2294 					 * We use pqReadData here since it has the logic to
2295 					 * distinguish no-data-yet from connection closure. Since
2296 					 * conn->ssl isn't set, a plain recv() will occur.
2297 					 */
2298 					char		SSLok;
2299 					int			rdresult;
2300 
2301 					rdresult = pqReadData(conn);
2302 					if (rdresult < 0)
2303 					{
2304 						/* errorMessage is already filled in */
2305 						goto error_return;
2306 					}
2307 					if (rdresult == 0)
2308 					{
2309 						/* caller failed to wait for data */
2310 						return PGRES_POLLING_READING;
2311 					}
2312 					if (pqGetc(&SSLok, conn) < 0)
2313 					{
2314 						/* should not happen really */
2315 						return PGRES_POLLING_READING;
2316 					}
2317 					if (SSLok == 'S')
2318 					{
2319 						/* mark byte consumed */
2320 						conn->inStart = conn->inCursor;
2321 						/* Set up global SSL state if required */
2322 						if (pqsecure_initialize(conn) != 0)
2323 							goto error_return;
2324 					}
2325 					else if (SSLok == 'N')
2326 					{
2327 						/* mark byte consumed */
2328 						conn->inStart = conn->inCursor;
2329 						/* OK to do without SSL? */
2330 						if (conn->sslmode[0] == 'r' ||	/* "require" */
2331 							conn->sslmode[0] == 'v')	/* "verify-ca" or
2332 														 * "verify-full" */
2333 						{
2334 							/* Require SSL, but server does not want it */
2335 							appendPQExpBufferStr(&conn->errorMessage,
2336 												 libpq_gettext("server does not support SSL, but SSL was required\n"));
2337 							goto error_return;
2338 						}
2339 						/* Otherwise, proceed with normal startup */
2340 						conn->allow_ssl_try = false;
2341 						conn->status = CONNECTION_MADE;
2342 						return PGRES_POLLING_WRITING;
2343 					}
2344 					else if (SSLok == 'E')
2345 					{
2346 						/*
2347 						 * Server failure of some sort, such as failure to
2348 						 * fork a backend process.  We need to process and
2349 						 * report the error message, which might be formatted
2350 						 * according to either protocol 2 or protocol 3.
2351 						 * Rather than duplicate the code for that, we flip
2352 						 * into AWAITING_RESPONSE state and let the code there
2353 						 * deal with it.  Note we have *not* consumed the "E"
2354 						 * byte here.
2355 						 */
2356 						conn->status = CONNECTION_AWAITING_RESPONSE;
2357 						goto keep_going;
2358 					}
2359 					else
2360 					{
2361 						appendPQExpBuffer(&conn->errorMessage,
2362 										  libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2363 										  SSLok);
2364 						goto error_return;
2365 					}
2366 				}
2367 
2368 				/*
2369 				 * Begin or continue the SSL negotiation process.
2370 				 */
2371 				pollres = pqsecure_open_client(conn);
2372 				if (pollres == PGRES_POLLING_OK)
2373 				{
2374 					/*
2375 					 * At this point we should have no data already buffered.
2376 					 * If we do, it was received before we performed the SSL
2377 					 * handshake, so it wasn't encrypted and indeed may have
2378 					 * been injected by a man-in-the-middle.
2379 					 */
2380 					if (conn->inCursor != conn->inEnd)
2381 					{
2382 						appendPQExpBufferStr(&conn->errorMessage,
2383 											 libpq_gettext("received unencrypted data after SSL response\n"));
2384 						goto error_return;
2385 					}
2386 
2387 					/* SSL handshake done, ready to send startup packet */
2388 					conn->status = CONNECTION_MADE;
2389 					return PGRES_POLLING_WRITING;
2390 				}
2391 				if (pollres == PGRES_POLLING_FAILED)
2392 				{
2393 					/*
2394 					 * Failed ... if sslmode is "prefer" then do a non-SSL
2395 					 * retry
2396 					 */
2397 					if (conn->sslmode[0] == 'p' /* "prefer" */
2398 						&& conn->allow_ssl_try	/* redundant? */
2399 						&& !conn->wait_ssl_try) /* redundant? */
2400 					{
2401 						/* only retry once */
2402 						conn->allow_ssl_try = false;
2403 						need_new_connection = true;
2404 						goto keep_going;
2405 					}
2406 					/* Else it's a hard failure */
2407 					goto error_return;
2408 				}
2409 				/* Else, return POLLING_READING or POLLING_WRITING status */
2410 				return pollres;
2411 #else							/* !USE_SSL */
2412 				/* can't get here */
2413 				goto error_return;
2414 #endif   /* USE_SSL */
2415 			}
2416 
2417 			/*
2418 			 * Handle authentication exchange: wait for postmaster messages
2419 			 * and respond as necessary.
2420 			 */
2421 		case CONNECTION_AWAITING_RESPONSE:
2422 			{
2423 				char		beresp;
2424 				int			msgLength;
2425 				int			avail;
2426 				AuthRequest areq;
2427 
2428 				/*
2429 				 * Scan the message from current point (note that if we find
2430 				 * the message is incomplete, we will return without advancing
2431 				 * inStart, and resume here next time).
2432 				 */
2433 				conn->inCursor = conn->inStart;
2434 
2435 				/* Read type byte */
2436 				if (pqGetc(&beresp, conn))
2437 				{
2438 					/* We'll come back when there is more data */
2439 					return PGRES_POLLING_READING;
2440 				}
2441 
2442 				/*
2443 				 * Validate message type: we expect only an authentication
2444 				 * request or an error here.  Anything else probably means
2445 				 * it's not Postgres on the other end at all.
2446 				 */
2447 				if (!(beresp == 'R' || beresp == 'E'))
2448 				{
2449 					appendPQExpBuffer(&conn->errorMessage,
2450 									  libpq_gettext(
2451 									  "expected authentication request from "
2452 												"server, but received %c\n"),
2453 									  beresp);
2454 					goto error_return;
2455 				}
2456 
2457 				if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2458 				{
2459 					/* Read message length word */
2460 					if (pqGetInt(&msgLength, 4, conn))
2461 					{
2462 						/* We'll come back when there is more data */
2463 						return PGRES_POLLING_READING;
2464 					}
2465 				}
2466 				else
2467 				{
2468 					/* Set phony message length to disable checks below */
2469 					msgLength = 8;
2470 				}
2471 
2472 				/*
2473 				 * Try to validate message length before using it.
2474 				 * Authentication requests can't be very large, although GSS
2475 				 * auth requests may not be that small.  Errors can be a
2476 				 * little larger, but not huge.  If we see a large apparent
2477 				 * length in an error, it means we're really talking to a
2478 				 * pre-3.0-protocol server; cope.
2479 				 */
2480 				if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2481 				{
2482 					appendPQExpBuffer(&conn->errorMessage,
2483 									  libpq_gettext(
2484 									  "expected authentication request from "
2485 												"server, but received %c\n"),
2486 									  beresp);
2487 					goto error_return;
2488 				}
2489 
2490 				if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2491 				{
2492 					/* Handle error from a pre-3.0 server */
2493 					conn->inCursor = conn->inStart + 1; /* reread data */
2494 					if (pqGets_append(&conn->errorMessage, conn))
2495 					{
2496 						/* We'll come back when there is more data */
2497 						return PGRES_POLLING_READING;
2498 					}
2499 					/* OK, we read the message; mark data consumed */
2500 					conn->inStart = conn->inCursor;
2501 
2502 					/*
2503 					 * The postmaster typically won't end its message with a
2504 					 * newline, so add one to conform to libpq conventions.
2505 					 */
2506 					appendPQExpBufferChar(&conn->errorMessage, '\n');
2507 
2508 					/*
2509 					 * If we tried to open the connection in 3.0 protocol,
2510 					 * fall back to 2.0 protocol.
2511 					 */
2512 					if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2513 					{
2514 						conn->pversion = PG_PROTOCOL(2, 0);
2515 						need_new_connection = true;
2516 						goto keep_going;
2517 					}
2518 
2519 					goto error_return;
2520 				}
2521 
2522 				/*
2523 				 * Can't process if message body isn't all here yet.
2524 				 *
2525 				 * (In protocol 2.0 case, we are assuming messages carry at
2526 				 * least 4 bytes of data.)
2527 				 */
2528 				msgLength -= 4;
2529 				avail = conn->inEnd - conn->inCursor;
2530 				if (avail < msgLength)
2531 				{
2532 					/*
2533 					 * Before returning, try to enlarge the input buffer if
2534 					 * needed to hold the whole message; see notes in
2535 					 * pqParseInput3.
2536 					 */
2537 					if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2538 											 conn))
2539 						goto error_return;
2540 					/* We'll come back when there is more data */
2541 					return PGRES_POLLING_READING;
2542 				}
2543 
2544 				/* Handle errors. */
2545 				if (beresp == 'E')
2546 				{
2547 					if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2548 					{
2549 						if (pqGetErrorNotice3(conn, true))
2550 						{
2551 							/* We'll come back when there is more data */
2552 							return PGRES_POLLING_READING;
2553 						}
2554 					}
2555 					else
2556 					{
2557 						if (pqGets_append(&conn->errorMessage, conn))
2558 						{
2559 							/* We'll come back when there is more data */
2560 							return PGRES_POLLING_READING;
2561 						}
2562 					}
2563 					/* OK, we read the message; mark data consumed */
2564 					conn->inStart = conn->inCursor;
2565 
2566 					/* Check to see if we should mention pgpassfile */
2567 					dot_pg_pass_warning(conn);
2568 
2569 #ifdef USE_SSL
2570 
2571 					/*
2572 					 * if sslmode is "allow" and we haven't tried an SSL
2573 					 * connection already, then retry with an SSL connection
2574 					 */
2575 					if (conn->sslmode[0] == 'a' /* "allow" */
2576 						&& !conn->ssl_in_use
2577 						&& conn->allow_ssl_try
2578 						&& conn->wait_ssl_try)
2579 					{
2580 						/* only retry once */
2581 						conn->wait_ssl_try = false;
2582 						need_new_connection = true;
2583 						goto keep_going;
2584 					}
2585 
2586 					/*
2587 					 * if sslmode is "prefer" and we're in an SSL connection,
2588 					 * then do a non-SSL retry
2589 					 */
2590 					if (conn->sslmode[0] == 'p' /* "prefer" */
2591 						&& conn->ssl_in_use
2592 						&& conn->allow_ssl_try	/* redundant? */
2593 						&& !conn->wait_ssl_try) /* redundant? */
2594 					{
2595 						/* only retry once */
2596 						conn->allow_ssl_try = false;
2597 						need_new_connection = true;
2598 						goto keep_going;
2599 					}
2600 #endif
2601 
2602 					goto error_return;
2603 				}
2604 
2605 				/* It is an authentication request. */
2606 				conn->auth_req_received = true;
2607 
2608 				/* Get the type of request. */
2609 				if (pqGetInt((int *) &areq, 4, conn))
2610 				{
2611 					/* We'll come back when there are more data */
2612 					return PGRES_POLLING_READING;
2613 				}
2614 
2615 				/* Get the password salt if there is one. */
2616 				if (areq == AUTH_REQ_MD5)
2617 				{
2618 					if (pqGetnchar(conn->md5Salt,
2619 								   sizeof(conn->md5Salt), conn))
2620 					{
2621 						/* We'll come back when there are more data */
2622 						return PGRES_POLLING_READING;
2623 					}
2624 				}
2625 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2626 
2627 				/*
2628 				 * Continue GSSAPI/SSPI authentication
2629 				 */
2630 				if (areq == AUTH_REQ_GSS_CONT)
2631 				{
2632 					int			llen = msgLength - 4;
2633 
2634 					/*
2635 					 * We can be called repeatedly for the same buffer. Avoid
2636 					 * re-allocating the buffer in this case - just re-use the
2637 					 * old buffer.
2638 					 */
2639 					if (llen != conn->ginbuf.length)
2640 					{
2641 						if (conn->ginbuf.value)
2642 							free(conn->ginbuf.value);
2643 
2644 						conn->ginbuf.length = llen;
2645 						conn->ginbuf.value = malloc(llen);
2646 						if (!conn->ginbuf.value)
2647 						{
2648 							printfPQExpBuffer(&conn->errorMessage,
2649 											  libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2650 											  llen);
2651 							goto error_return;
2652 						}
2653 					}
2654 
2655 					if (pqGetnchar(conn->ginbuf.value, llen, conn))
2656 					{
2657 						/* We'll come back when there is more data. */
2658 						return PGRES_POLLING_READING;
2659 					}
2660 				}
2661 #endif
2662 
2663 				/*
2664 				 * OK, we successfully read the message; mark data consumed
2665 				 */
2666 				conn->inStart = conn->inCursor;
2667 
2668 				/* Respond to the request if necessary. */
2669 
2670 				/*
2671 				 * Note that conn->pghost must be non-NULL if we are going to
2672 				 * avoid the Kerberos code doing a hostname look-up.
2673 				 */
2674 
2675 				if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2676 				{
2677 					conn->errorMessage.len = strlen(conn->errorMessage.data);
2678 					goto error_return;
2679 				}
2680 				conn->errorMessage.len = strlen(conn->errorMessage.data);
2681 
2682 				/*
2683 				 * Just make sure that any data sent by pg_fe_sendauth is
2684 				 * flushed out.  Although this theoretically could block, it
2685 				 * really shouldn't since we don't send large auth responses.
2686 				 */
2687 				if (pqFlush(conn))
2688 					goto error_return;
2689 
2690 				if (areq == AUTH_REQ_OK)
2691 				{
2692 					/* We are done with authentication exchange */
2693 					conn->status = CONNECTION_AUTH_OK;
2694 
2695 					/*
2696 					 * Set asyncStatus so that PQgetResult will think that
2697 					 * what comes back next is the result of a query.  See
2698 					 * below.
2699 					 */
2700 					conn->asyncStatus = PGASYNC_BUSY;
2701 				}
2702 
2703 				/* Look to see if we have more data yet. */
2704 				goto keep_going;
2705 			}
2706 
2707 		case CONNECTION_AUTH_OK:
2708 			{
2709 				/*
2710 				 * Now we expect to hear from the backend. A ReadyForQuery
2711 				 * message indicates that startup is successful, but we might
2712 				 * also get an Error message indicating failure. (Notice
2713 				 * messages indicating nonfatal warnings are also allowed by
2714 				 * the protocol, as are ParameterStatus and BackendKeyData
2715 				 * messages.) Easiest way to handle this is to let
2716 				 * PQgetResult() read the messages. We just have to fake it
2717 				 * out about the state of the connection, by setting
2718 				 * asyncStatus = PGASYNC_BUSY (done above).
2719 				 */
2720 
2721 				if (PQisBusy(conn))
2722 					return PGRES_POLLING_READING;
2723 
2724 				res = PQgetResult(conn);
2725 
2726 				/*
2727 				 * NULL return indicating we have gone to IDLE state is
2728 				 * expected
2729 				 */
2730 				if (res)
2731 				{
2732 					if (res->resultStatus != PGRES_FATAL_ERROR)
2733 						appendPQExpBufferStr(&conn->errorMessage,
2734 											 libpq_gettext("unexpected message from server during startup\n"));
2735 					else if (conn->send_appname &&
2736 							 (conn->appname || conn->fbappname))
2737 					{
2738 						/*
2739 						 * If we tried to send application_name, check to see
2740 						 * if the error is about that --- pre-9.0 servers will
2741 						 * reject it at this stage of the process.  If so,
2742 						 * close the connection and retry without sending
2743 						 * application_name.  We could possibly get a false
2744 						 * SQLSTATE match here and retry uselessly, but there
2745 						 * seems no great harm in that; we'll just get the
2746 						 * same error again if it's unrelated.
2747 						 */
2748 						const char *sqlstate;
2749 
2750 						sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2751 						if (sqlstate &&
2752 							strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2753 						{
2754 							PQclear(res);
2755 							conn->send_appname = false;
2756 							need_new_connection = true;
2757 							goto keep_going;
2758 						}
2759 					}
2760 
2761 					/*
2762 					 * if the resultStatus is FATAL, then conn->errorMessage
2763 					 * already has a copy of the error; needn't copy it back.
2764 					 * But add a newline if it's not there already, since
2765 					 * postmaster error messages may not have one.
2766 					 */
2767 					if (conn->errorMessage.len <= 0 ||
2768 						conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2769 						appendPQExpBufferChar(&conn->errorMessage, '\n');
2770 					PQclear(res);
2771 					goto error_return;
2772 				}
2773 
2774 				/* We can release the address list now. */
2775 				pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2776 				conn->addrlist = NULL;
2777 				conn->addr_cur = NULL;
2778 
2779 				/* Fire up post-connection housekeeping if needed */
2780 				if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2781 				{
2782 					conn->status = CONNECTION_SETENV;
2783 					conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2784 					conn->next_eo = EnvironmentOptions;
2785 					return PGRES_POLLING_WRITING;
2786 				}
2787 
2788 				/* Otherwise, we are open for business! */
2789 				conn->status = CONNECTION_OK;
2790 				return PGRES_POLLING_OK;
2791 			}
2792 
2793 		case CONNECTION_SETENV:
2794 
2795 			/*
2796 			 * Do post-connection housekeeping (only needed in protocol 2.0).
2797 			 *
2798 			 * We pretend that the connection is OK for the duration of these
2799 			 * queries.
2800 			 */
2801 			conn->status = CONNECTION_OK;
2802 
2803 			switch (pqSetenvPoll(conn))
2804 			{
2805 				case PGRES_POLLING_OK:	/* Success */
2806 					break;
2807 
2808 				case PGRES_POLLING_READING:		/* Still going */
2809 					conn->status = CONNECTION_SETENV;
2810 					return PGRES_POLLING_READING;
2811 
2812 				case PGRES_POLLING_WRITING:		/* Still going */
2813 					conn->status = CONNECTION_SETENV;
2814 					return PGRES_POLLING_WRITING;
2815 
2816 				default:
2817 					goto error_return;
2818 			}
2819 
2820 			/* We are open for business! */
2821 			conn->status = CONNECTION_OK;
2822 			return PGRES_POLLING_OK;
2823 
2824 		default:
2825 			appendPQExpBuffer(&conn->errorMessage,
2826 							  libpq_gettext("invalid connection state %d, "
2827 							   "probably indicative of memory corruption\n"),
2828 							  conn->status);
2829 			goto error_return;
2830 	}
2831 
2832 	/* Unreachable */
2833 
2834 error_return:
2835 
2836 	/*
2837 	 * We used to close the socket at this point, but that makes it awkward
2838 	 * for those above us if they wish to remove this socket from their own
2839 	 * records (an fd_set for example).  We'll just have this socket closed
2840 	 * when PQfinish is called (which is compulsory even after an error, since
2841 	 * the connection structure must be freed).
2842 	 */
2843 	conn->status = CONNECTION_BAD;
2844 	return PGRES_POLLING_FAILED;
2845 }
2846 
2847 
2848 /*
2849  * internal_ping
2850  *		Determine if a server is running and if we can connect to it.
2851  *
2852  * The argument is a connection that's been started, but not completed.
2853  */
2854 static PGPing
internal_ping(PGconn * conn)2855 internal_ping(PGconn *conn)
2856 {
2857 	/* Say "no attempt" if we never got to PQconnectPoll */
2858 	if (!conn || !conn->options_valid)
2859 		return PQPING_NO_ATTEMPT;
2860 
2861 	/* Attempt to complete the connection */
2862 	if (conn->status != CONNECTION_BAD)
2863 		(void) connectDBComplete(conn);
2864 
2865 	/* Definitely OK if we succeeded */
2866 	if (conn->status != CONNECTION_BAD)
2867 		return PQPING_OK;
2868 
2869 	/*
2870 	 * Here begins the interesting part of "ping": determine the cause of the
2871 	 * failure in sufficient detail to decide what to return.  We do not want
2872 	 * to report that the server is not up just because we didn't have a valid
2873 	 * password, for example.  In fact, any sort of authentication request
2874 	 * implies the server is up.  (We need this check since the libpq side of
2875 	 * things might have pulled the plug on the connection before getting an
2876 	 * error as such from the postmaster.)
2877 	 */
2878 	if (conn->auth_req_received)
2879 		return PQPING_OK;
2880 
2881 	/*
2882 	 * If we failed to get any ERROR response from the postmaster, report
2883 	 * PQPING_NO_RESPONSE.  This result could be somewhat misleading for a
2884 	 * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2885 	 * out of support.  Another corner case where the server could return a
2886 	 * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2887 	 * totally unreasonable for that anyway.  We expect that every other
2888 	 * failure case in a modern server will produce a report with a SQLSTATE.
2889 	 *
2890 	 * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2891 	 * client-side errors, we should either not store those into
2892 	 * last_sqlstate, or add an extra flag so we can tell client-side errors
2893 	 * apart from server-side ones.
2894 	 */
2895 	if (strlen(conn->last_sqlstate) != 5)
2896 		return PQPING_NO_RESPONSE;
2897 
2898 	/*
2899 	 * Report PQPING_REJECT if server says it's not accepting connections. (We
2900 	 * distinguish this case mainly for the convenience of pg_ctl.)
2901 	 */
2902 	if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2903 		return PQPING_REJECT;
2904 
2905 	/*
2906 	 * Any other SQLSTATE can be taken to indicate that the server is up.
2907 	 * Presumably it didn't like our username, password, or database name; or
2908 	 * perhaps it had some transient failure, but that should not be taken as
2909 	 * meaning "it's down".
2910 	 */
2911 	return PQPING_OK;
2912 }
2913 
2914 
2915 /*
2916  * makeEmptyPGconn
2917  *	 - create a PGconn data structure with (as yet) no interesting data
2918  */
2919 static PGconn *
makeEmptyPGconn(void)2920 makeEmptyPGconn(void)
2921 {
2922 	PGconn	   *conn;
2923 
2924 #ifdef WIN32
2925 
2926 	/*
2927 	 * Make sure socket support is up and running in this process.
2928 	 *
2929 	 * Note: the Windows documentation says that we should eventually do a
2930 	 * matching WSACleanup() call, but experience suggests that that is at
2931 	 * least as likely to cause problems as fix them.  So we don't.
2932 	 */
2933 	static bool wsastartup_done = false;
2934 
2935 	if (!wsastartup_done)
2936 	{
2937 		WSADATA		wsaData;
2938 
2939 		if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
2940 			return NULL;
2941 		wsastartup_done = true;
2942 	}
2943 
2944 	/* Forget any earlier error */
2945 	WSASetLastError(0);
2946 #endif							/* WIN32 */
2947 
2948 	conn = (PGconn *) malloc(sizeof(PGconn));
2949 	if (conn == NULL)
2950 		return conn;
2951 
2952 	/* Zero all pointers and booleans */
2953 	MemSet(conn, 0, sizeof(PGconn));
2954 
2955 	/* install default notice hooks */
2956 	conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2957 	conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2958 
2959 	conn->status = CONNECTION_BAD;
2960 	conn->asyncStatus = PGASYNC_IDLE;
2961 	conn->xactStatus = PQTRANS_IDLE;
2962 	conn->options_valid = false;
2963 	conn->nonblocking = false;
2964 	conn->setenv_state = SETENV_STATE_IDLE;
2965 	conn->client_encoding = PG_SQL_ASCII;
2966 	conn->std_strings = false;	/* unless server says differently */
2967 	conn->verbosity = PQERRORS_DEFAULT;
2968 	conn->show_context = PQSHOW_CONTEXT_ERRORS;
2969 	conn->sock = PGINVALID_SOCKET;
2970 	conn->dot_pgpass_used = false;
2971 
2972 	/*
2973 	 * We try to send at least 8K at a time, which is the usual size of pipe
2974 	 * buffers on Unix systems.  That way, when we are sending a large amount
2975 	 * of data, we avoid incurring extra kernel context swaps for partial
2976 	 * bufferloads.  The output buffer is initially made 16K in size, and we
2977 	 * try to dump it after accumulating 8K.
2978 	 *
2979 	 * With the same goal of minimizing context swaps, the input buffer will
2980 	 * be enlarged anytime it has less than 8K free, so we initially allocate
2981 	 * twice that.
2982 	 */
2983 	conn->inBufSize = 16 * 1024;
2984 	conn->inBuffer = (char *) malloc(conn->inBufSize);
2985 	conn->outBufSize = 16 * 1024;
2986 	conn->outBuffer = (char *) malloc(conn->outBufSize);
2987 	conn->rowBufLen = 32;
2988 	conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
2989 	initPQExpBuffer(&conn->errorMessage);
2990 	initPQExpBuffer(&conn->workBuffer);
2991 
2992 	if (conn->inBuffer == NULL ||
2993 		conn->outBuffer == NULL ||
2994 		conn->rowBuf == NULL ||
2995 		PQExpBufferBroken(&conn->errorMessage) ||
2996 		PQExpBufferBroken(&conn->workBuffer))
2997 	{
2998 		/* out of memory already :-( */
2999 		freePGconn(conn);
3000 		conn = NULL;
3001 	}
3002 
3003 	return conn;
3004 }
3005 
3006 /*
3007  * freePGconn
3008  *	 - free an idle (closed) PGconn data structure
3009  *
3010  * NOTE: this should not overlap any functionality with closePGconn().
3011  * Clearing/resetting of transient state belongs there; what we do here is
3012  * release data that is to be held for the life of the PGconn structure.
3013  * If a value ought to be cleared/freed during PQreset(), do it there not here.
3014  */
3015 static void
freePGconn(PGconn * conn)3016 freePGconn(PGconn *conn)
3017 {
3018 	int			i;
3019 
3020 	/* let any event procs clean up their state data */
3021 	for (i = 0; i < conn->nEvents; i++)
3022 	{
3023 		PGEventConnDestroy evt;
3024 
3025 		evt.conn = conn;
3026 		(void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3027 									conn->events[i].passThrough);
3028 		free(conn->events[i].name);
3029 	}
3030 
3031 	if (conn->client_encoding_initial)
3032 		free(conn->client_encoding_initial);
3033 	if (conn->events)
3034 		free(conn->events);
3035 	if (conn->pghost)
3036 		free(conn->pghost);
3037 	if (conn->pghostaddr)
3038 		free(conn->pghostaddr);
3039 	if (conn->pgport)
3040 		free(conn->pgport);
3041 	if (conn->pgunixsocket)
3042 		free(conn->pgunixsocket);
3043 	if (conn->pgtty)
3044 		free(conn->pgtty);
3045 	if (conn->connect_timeout)
3046 		free(conn->connect_timeout);
3047 	if (conn->pgoptions)
3048 		free(conn->pgoptions);
3049 	if (conn->appname)
3050 		free(conn->appname);
3051 	if (conn->fbappname)
3052 		free(conn->fbappname);
3053 	if (conn->dbName)
3054 		free(conn->dbName);
3055 	if (conn->replication)
3056 		free(conn->replication);
3057 	if (conn->pguser)
3058 		free(conn->pguser);
3059 	if (conn->pgpass)
3060 		free(conn->pgpass);
3061 	if (conn->keepalives)
3062 		free(conn->keepalives);
3063 	if (conn->keepalives_idle)
3064 		free(conn->keepalives_idle);
3065 	if (conn->keepalives_interval)
3066 		free(conn->keepalives_interval);
3067 	if (conn->keepalives_count)
3068 		free(conn->keepalives_count);
3069 	if (conn->sslmode)
3070 		free(conn->sslmode);
3071 	if (conn->sslcert)
3072 		free(conn->sslcert);
3073 	if (conn->sslkey)
3074 		free(conn->sslkey);
3075 	if (conn->sslrootcert)
3076 		free(conn->sslrootcert);
3077 	if (conn->sslcrl)
3078 		free(conn->sslcrl);
3079 	if (conn->sslcompression)
3080 		free(conn->sslcompression);
3081 	if (conn->requirepeer)
3082 		free(conn->requirepeer);
3083 	if (conn->krbsrvname)
3084 		free(conn->krbsrvname);
3085 	if (conn->gsslib)
3086 		free(conn->gsslib);
3087 	/* Note that conn->Pfdebug is not ours to close or free */
3088 	if (conn->last_query)
3089 		free(conn->last_query);
3090 	if (conn->inBuffer)
3091 		free(conn->inBuffer);
3092 	if (conn->outBuffer)
3093 		free(conn->outBuffer);
3094 	if (conn->rowBuf)
3095 		free(conn->rowBuf);
3096 	termPQExpBuffer(&conn->errorMessage);
3097 	termPQExpBuffer(&conn->workBuffer);
3098 
3099 	free(conn);
3100 }
3101 
3102 /*
3103  * closePGconn
3104  *	 - properly close a connection to the backend
3105  *
3106  * This should reset or release all transient state, but NOT the connection
3107  * parameters.  On exit, the PGconn should be in condition to start a fresh
3108  * connection with the same parameters (see PQreset()).
3109  */
3110 static void
closePGconn(PGconn * conn)3111 closePGconn(PGconn *conn)
3112 {
3113 	/*
3114 	 * If possible, send Terminate message to close the connection politely.
3115 	 *
3116 	 * Note that the protocol doesn't allow us to send Terminate messages
3117 	 * during the startup phase.
3118 	 */
3119 	if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
3120 	{
3121 		/*
3122 		 * Try to send "close connection" message to backend. Ignore any
3123 		 * error.
3124 		 */
3125 		pqPutMsgStart('X', false, conn);
3126 		pqPutMsgEnd(conn);
3127 		(void) pqFlush(conn);
3128 	}
3129 
3130 	/*
3131 	 * Must reset the blocking status so a possible reconnect will work.
3132 	 *
3133 	 * Don't call PQsetnonblocking() because it will fail if it's unable to
3134 	 * flush the connection.
3135 	 */
3136 	conn->nonblocking = FALSE;
3137 
3138 	/*
3139 	 * Close the connection, reset all transient state, flush I/O buffers.
3140 	 */
3141 	pqDropConnection(conn, true);
3142 	conn->status = CONNECTION_BAD;		/* Well, not really _bad_ - just
3143 										 * absent */
3144 	conn->asyncStatus = PGASYNC_IDLE;
3145 	conn->xactStatus = PQTRANS_IDLE;
3146 	pqClearAsyncResult(conn);	/* deallocate result */
3147 	resetPQExpBuffer(&conn->errorMessage);
3148 	pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
3149 	conn->addrlist = NULL;
3150 	conn->addr_cur = NULL;
3151 
3152 	/* Reset all state obtained from server, too */
3153 	pqDropServerData(conn);
3154 }
3155 
3156 /*
3157  * PQfinish: properly close a connection to the backend. Also frees
3158  * the PGconn data structure so it shouldn't be re-used after this.
3159  */
3160 void
PQfinish(PGconn * conn)3161 PQfinish(PGconn *conn)
3162 {
3163 	if (conn)
3164 	{
3165 		closePGconn(conn);
3166 		freePGconn(conn);
3167 	}
3168 }
3169 
3170 /*
3171  * PQreset: resets the connection to the backend by closing the
3172  * existing connection and creating a new one.
3173  */
3174 void
PQreset(PGconn * conn)3175 PQreset(PGconn *conn)
3176 {
3177 	if (conn)
3178 	{
3179 		closePGconn(conn);
3180 
3181 		if (connectDBStart(conn) && connectDBComplete(conn))
3182 		{
3183 			/*
3184 			 * Notify event procs of successful reset.  We treat an event proc
3185 			 * failure as disabling the connection ... good idea?
3186 			 */
3187 			int			i;
3188 
3189 			for (i = 0; i < conn->nEvents; i++)
3190 			{
3191 				PGEventConnReset evt;
3192 
3193 				evt.conn = conn;
3194 				if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3195 										  conn->events[i].passThrough))
3196 				{
3197 					conn->status = CONNECTION_BAD;
3198 					printfPQExpBuffer(&conn->errorMessage,
3199 									  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3200 									  conn->events[i].name);
3201 					break;
3202 				}
3203 			}
3204 		}
3205 	}
3206 }
3207 
3208 
3209 /*
3210  * PQresetStart:
3211  * resets the connection to the backend
3212  * closes the existing connection and makes a new one
3213  * Returns 1 on success, 0 on failure.
3214  */
3215 int
PQresetStart(PGconn * conn)3216 PQresetStart(PGconn *conn)
3217 {
3218 	if (conn)
3219 	{
3220 		closePGconn(conn);
3221 
3222 		return connectDBStart(conn);
3223 	}
3224 
3225 	return 0;
3226 }
3227 
3228 
3229 /*
3230  * PQresetPoll:
3231  * resets the connection to the backend
3232  * closes the existing connection and makes a new one
3233  */
3234 PostgresPollingStatusType
PQresetPoll(PGconn * conn)3235 PQresetPoll(PGconn *conn)
3236 {
3237 	if (conn)
3238 	{
3239 		PostgresPollingStatusType status = PQconnectPoll(conn);
3240 
3241 		if (status == PGRES_POLLING_OK)
3242 		{
3243 			/*
3244 			 * Notify event procs of successful reset.  We treat an event proc
3245 			 * failure as disabling the connection ... good idea?
3246 			 */
3247 			int			i;
3248 
3249 			for (i = 0; i < conn->nEvents; i++)
3250 			{
3251 				PGEventConnReset evt;
3252 
3253 				evt.conn = conn;
3254 				if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3255 										  conn->events[i].passThrough))
3256 				{
3257 					conn->status = CONNECTION_BAD;
3258 					printfPQExpBuffer(&conn->errorMessage,
3259 									  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3260 									  conn->events[i].name);
3261 					return PGRES_POLLING_FAILED;
3262 				}
3263 			}
3264 		}
3265 
3266 		return status;
3267 	}
3268 
3269 	return PGRES_POLLING_FAILED;
3270 }
3271 
3272 /*
3273  * PQgetCancel: get a PGcancel structure corresponding to a connection.
3274  *
3275  * A copy is needed to be able to cancel a running query from a different
3276  * thread. If the same structure is used all structure members would have
3277  * to be individually locked (if the entire structure was locked, it would
3278  * be impossible to cancel a synchronous query because the structure would
3279  * have to stay locked for the duration of the query).
3280  */
3281 PGcancel *
PQgetCancel(PGconn * conn)3282 PQgetCancel(PGconn *conn)
3283 {
3284 	PGcancel   *cancel;
3285 
3286 	if (!conn)
3287 		return NULL;
3288 
3289 	if (conn->sock == PGINVALID_SOCKET)
3290 		return NULL;
3291 
3292 	cancel = malloc(sizeof(PGcancel));
3293 	if (cancel == NULL)
3294 		return NULL;
3295 
3296 	memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3297 	cancel->be_pid = conn->be_pid;
3298 	cancel->be_key = conn->be_key;
3299 
3300 	return cancel;
3301 }
3302 
3303 /* PQfreeCancel: free a cancel structure */
3304 void
PQfreeCancel(PGcancel * cancel)3305 PQfreeCancel(PGcancel *cancel)
3306 {
3307 	if (cancel)
3308 		free(cancel);
3309 }
3310 
3311 
3312 /*
3313  * PQcancel and PQrequestCancel: attempt to request cancellation of the
3314  * current operation.
3315  *
3316  * The return value is TRUE if the cancel request was successfully
3317  * dispatched, FALSE if not (in which case an error message is available).
3318  * Note: successful dispatch is no guarantee that there will be any effect at
3319  * the backend.  The application must read the operation result as usual.
3320  *
3321  * CAUTION: we want this routine to be safely callable from a signal handler
3322  * (for example, an application might want to call it in a SIGINT handler).
3323  * This means we cannot use any C library routine that might be non-reentrant.
3324  * malloc/free are often non-reentrant, and anything that might call them is
3325  * just as dangerous.  We avoid sprintf here for that reason.  Building up
3326  * error messages with strcpy/strcat is tedious but should be quite safe.
3327  * We also save/restore errno in case the signal handler support doesn't.
3328  *
3329  * internal_cancel() is an internal helper function to make code-sharing
3330  * between the two versions of the cancel function possible.
3331  */
3332 static int
internal_cancel(SockAddr * raddr,int be_pid,int be_key,char * errbuf,int errbufsize)3333 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3334 				char *errbuf, int errbufsize)
3335 {
3336 	int			save_errno = SOCK_ERRNO;
3337 	pgsocket	tmpsock = PGINVALID_SOCKET;
3338 	char		sebuf[256];
3339 	int			maxlen;
3340 	struct
3341 	{
3342 		uint32		packetlen;
3343 		CancelRequestPacket cp;
3344 	}			crp;
3345 
3346 	/*
3347 	 * We need to open a temporary connection to the postmaster. Do this with
3348 	 * only kernel calls.
3349 	 */
3350 	if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
3351 	{
3352 		strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3353 		goto cancel_errReturn;
3354 	}
3355 retry3:
3356 	if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
3357 				raddr->salen) < 0)
3358 	{
3359 		if (SOCK_ERRNO == EINTR)
3360 			/* Interrupted system call - we'll just try again */
3361 			goto retry3;
3362 		strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3363 		goto cancel_errReturn;
3364 	}
3365 
3366 	/*
3367 	 * We needn't set nonblocking I/O or NODELAY options here.
3368 	 */
3369 
3370 	/* Create and send the cancel request packet. */
3371 
3372 	crp.packetlen = htonl((uint32) sizeof(crp));
3373 	crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
3374 	crp.cp.backendPID = htonl(be_pid);
3375 	crp.cp.cancelAuthCode = htonl(be_key);
3376 
3377 retry4:
3378 	if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3379 	{
3380 		if (SOCK_ERRNO == EINTR)
3381 			/* Interrupted system call - we'll just try again */
3382 			goto retry4;
3383 		strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
3384 		goto cancel_errReturn;
3385 	}
3386 
3387 	/*
3388 	 * Wait for the postmaster to close the connection, which indicates that
3389 	 * it's processed the request.  Without this delay, we might issue another
3390 	 * command only to find that our cancel zaps that command instead of the
3391 	 * one we thought we were canceling.  Note we don't actually expect this
3392 	 * read to obtain any data, we are just waiting for EOF to be signaled.
3393 	 */
3394 retry5:
3395 	if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
3396 	{
3397 		if (SOCK_ERRNO == EINTR)
3398 			/* Interrupted system call - we'll just try again */
3399 			goto retry5;
3400 		/* we ignore other error conditions */
3401 	}
3402 
3403 	/* All done */
3404 	closesocket(tmpsock);
3405 	SOCK_ERRNO_SET(save_errno);
3406 	return TRUE;
3407 
3408 cancel_errReturn:
3409 
3410 	/*
3411 	 * Make sure we don't overflow the error buffer. Leave space for the \n at
3412 	 * the end, and for the terminating zero.
3413 	 */
3414 	maxlen = errbufsize - strlen(errbuf) - 2;
3415 	if (maxlen >= 0)
3416 	{
3417 		strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3418 				maxlen);
3419 		strcat(errbuf, "\n");
3420 	}
3421 	if (tmpsock != PGINVALID_SOCKET)
3422 		closesocket(tmpsock);
3423 	SOCK_ERRNO_SET(save_errno);
3424 	return FALSE;
3425 }
3426 
3427 /*
3428  * PQcancel: request query cancel
3429  *
3430  * Returns TRUE if able to send the cancel request, FALSE if not.
3431  *
3432  * On failure, an error message is stored in *errbuf, which must be of size
3433  * errbufsize (recommended size is 256 bytes).  *errbuf is not changed on
3434  * success return.
3435  */
3436 int
PQcancel(PGcancel * cancel,char * errbuf,int errbufsize)3437 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
3438 {
3439 	if (!cancel)
3440 	{
3441 		strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3442 		return FALSE;
3443 	}
3444 
3445 	return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3446 						   errbuf, errbufsize);
3447 }
3448 
3449 /*
3450  * PQrequestCancel: old, not thread-safe function for requesting query cancel
3451  *
3452  * Returns TRUE if able to send the cancel request, FALSE if not.
3453  *
3454  * On failure, the error message is saved in conn->errorMessage; this means
3455  * that this can't be used when there might be other active operations on
3456  * the connection object.
3457  *
3458  * NOTE: error messages will be cut off at the current size of the
3459  * error message buffer, since we dare not try to expand conn->errorMessage!
3460  */
3461 int
PQrequestCancel(PGconn * conn)3462 PQrequestCancel(PGconn *conn)
3463 {
3464 	int			r;
3465 
3466 	/* Check we have an open connection */
3467 	if (!conn)
3468 		return FALSE;
3469 
3470 	if (conn->sock == PGINVALID_SOCKET)
3471 	{
3472 		strlcpy(conn->errorMessage.data,
3473 				"PQrequestCancel() -- connection is not open\n",
3474 				conn->errorMessage.maxlen);
3475 		conn->errorMessage.len = strlen(conn->errorMessage.data);
3476 
3477 		return FALSE;
3478 	}
3479 
3480 	r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
3481 						conn->errorMessage.data, conn->errorMessage.maxlen);
3482 
3483 	if (!r)
3484 		conn->errorMessage.len = strlen(conn->errorMessage.data);
3485 
3486 	return r;
3487 }
3488 
3489 
3490 /*
3491  * pqPacketSend() -- convenience routine to send a message to server.
3492  *
3493  * pack_type: the single-byte message type code.  (Pass zero for startup
3494  * packets, which have no message type code.)
3495  *
3496  * buf, buf_len: contents of message.  The given length includes only what
3497  * is in buf; the message type and message length fields are added here.
3498  *
3499  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
3500  * SIDE_EFFECTS: may block.
3501  *
3502  * Note: all messages sent with this routine have a length word, whether
3503  * it's protocol 2.0 or 3.0.
3504  */
3505 int
pqPacketSend(PGconn * conn,char pack_type,const void * buf,size_t buf_len)3506 pqPacketSend(PGconn *conn, char pack_type,
3507 			 const void *buf, size_t buf_len)
3508 {
3509 	/* Start the message. */
3510 	if (pqPutMsgStart(pack_type, true, conn))
3511 		return STATUS_ERROR;
3512 
3513 	/* Send the message body. */
3514 	if (pqPutnchar(buf, buf_len, conn))
3515 		return STATUS_ERROR;
3516 
3517 	/* Finish the message. */
3518 	if (pqPutMsgEnd(conn))
3519 		return STATUS_ERROR;
3520 
3521 	/* Flush to ensure backend gets it. */
3522 	if (pqFlush(conn))
3523 		return STATUS_ERROR;
3524 
3525 	return STATUS_OK;
3526 }
3527 
3528 #ifdef USE_LDAP
3529 
3530 #define LDAP_URL	"ldap://"
3531 #define LDAP_DEF_PORT	389
3532 #define PGLDAP_TIMEOUT 2
3533 
3534 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
3535 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
3536 
3537 
3538 /*
3539  *		ldapServiceLookup
3540  *
3541  * Search the LDAP URL passed as first argument, treat the result as a
3542  * string of connection options that are parsed and added to the array of
3543  * options passed as second argument.
3544  *
3545  * LDAP URLs must conform to RFC 1959 without escape sequences.
3546  *	ldap://host:port/dn?attributes?scope?filter?extensions
3547  *
3548  * Returns
3549  *	0 if the lookup was successful,
3550  *	1 if the connection to the LDAP server could be established but
3551  *	  the search was unsuccessful,
3552  *	2 if a connection could not be established, and
3553  *	3 if a fatal error occurred.
3554  *
3555  * An error message is returned in the third argument for return codes 1 and 3.
3556  */
3557 static int
ldapServiceLookup(const char * purl,PQconninfoOption * options,PQExpBuffer errorMessage)3558 ldapServiceLookup(const char *purl, PQconninfoOption *options,
3559 				  PQExpBuffer errorMessage)
3560 {
3561 	int			port = LDAP_DEF_PORT,
3562 				scope,
3563 				rc,
3564 				size,
3565 				state,
3566 				oldstate,
3567 				i;
3568 #ifndef WIN32
3569 	int			msgid;
3570 #endif
3571 	bool		found_keyword;
3572 	char	   *url,
3573 			   *hostname,
3574 			   *portstr,
3575 			   *endptr,
3576 			   *dn,
3577 			   *scopestr,
3578 			   *filter,
3579 			   *result,
3580 			   *p,
3581 			   *p1 = NULL,
3582 			   *optname = NULL,
3583 			   *optval = NULL;
3584 	char	   *attrs[2] = {NULL, NULL};
3585 	LDAP	   *ld = NULL;
3586 	LDAPMessage *res,
3587 			   *entry;
3588 	struct berval **values;
3589 	LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
3590 
3591 	if ((url = strdup(purl)) == NULL)
3592 	{
3593 		printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
3594 		return 3;
3595 	}
3596 
3597 	/*
3598 	 * Parse URL components, check for correctness.  Basically, url has '\0'
3599 	 * placed at component boundaries and variables are pointed at each
3600 	 * component.
3601 	 */
3602 
3603 	if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
3604 	{
3605 		printfPQExpBuffer(errorMessage,
3606 						  libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
3607 		free(url);
3608 		return 3;
3609 	}
3610 
3611 	/* hostname */
3612 	hostname = url + strlen(LDAP_URL);
3613 	if (*hostname == '/')		/* no hostname? */
3614 		hostname = DefaultHost; /* the default */
3615 
3616 	/* dn, "distinguished name" */
3617 	p = strchr(url + strlen(LDAP_URL), '/');
3618 	if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3619 	{
3620 		printfPQExpBuffer(errorMessage, libpq_gettext(
3621 			 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
3622 		free(url);
3623 		return 3;
3624 	}
3625 	*p = '\0';					/* terminate hostname */
3626 	dn = p + 1;
3627 
3628 	/* attribute */
3629 	if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3630 	{
3631 		printfPQExpBuffer(errorMessage, libpq_gettext(
3632 		"invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3633 		free(url);
3634 		return 3;
3635 	}
3636 	*p = '\0';
3637 	attrs[0] = p + 1;
3638 
3639 	/* scope */
3640 	if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3641 	{
3642 		printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3643 		free(url);
3644 		return 3;
3645 	}
3646 	*p = '\0';
3647 	scopestr = p + 1;
3648 
3649 	/* filter */
3650 	if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3651 	{
3652 		printfPQExpBuffer(errorMessage,
3653 				libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
3654 		free(url);
3655 		return 3;
3656 	}
3657 	*p = '\0';
3658 	filter = p + 1;
3659 	if ((p = strchr(filter, '?')) != NULL)
3660 		*p = '\0';
3661 
3662 	/* port number? */
3663 	if ((p1 = strchr(hostname, ':')) != NULL)
3664 	{
3665 		long		lport;
3666 
3667 		*p1 = '\0';
3668 		portstr = p1 + 1;
3669 		errno = 0;
3670 		lport = strtol(portstr, &endptr, 10);
3671 		if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
3672 		{
3673 			printfPQExpBuffer(errorMessage, libpq_gettext(
3674 					"invalid LDAP URL \"%s\": invalid port number\n"), purl);
3675 			free(url);
3676 			return 3;
3677 		}
3678 		port = (int) lport;
3679 	}
3680 
3681 	/* Allow only one attribute */
3682 	if (strchr(attrs[0], ',') != NULL)
3683 	{
3684 		printfPQExpBuffer(errorMessage, libpq_gettext(
3685 		"invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3686 		free(url);
3687 		return 3;
3688 	}
3689 
3690 	/* set scope */
3691 	if (pg_strcasecmp(scopestr, "base") == 0)
3692 		scope = LDAP_SCOPE_BASE;
3693 	else if (pg_strcasecmp(scopestr, "one") == 0)
3694 		scope = LDAP_SCOPE_ONELEVEL;
3695 	else if (pg_strcasecmp(scopestr, "sub") == 0)
3696 		scope = LDAP_SCOPE_SUBTREE;
3697 	else
3698 	{
3699 		printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3700 		free(url);
3701 		return 3;
3702 	}
3703 
3704 	/* initialize LDAP structure */
3705 	if ((ld = ldap_init(hostname, port)) == NULL)
3706 	{
3707 		printfPQExpBuffer(errorMessage,
3708 						  libpq_gettext("could not create LDAP structure\n"));
3709 		free(url);
3710 		return 3;
3711 	}
3712 
3713 	/*
3714 	 * Perform an explicit anonymous bind.
3715 	 *
3716 	 * LDAP does not require that an anonymous bind is performed explicitly,
3717 	 * but we want to distinguish between the case where LDAP bind does not
3718 	 * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
3719 	 * service control file) and the case where querying the LDAP server fails
3720 	 * (return 1 to end parsing).
3721 	 *
3722 	 * Unfortunately there is no way of setting a timeout that works for both
3723 	 * Windows and OpenLDAP.
3724 	 */
3725 #ifdef WIN32
3726 	/* the nonstandard ldap_connect function performs an anonymous bind */
3727 	if (ldap_connect(ld, &time) != LDAP_SUCCESS)
3728 	{
3729 		/* error or timeout in ldap_connect */
3730 		free(url);
3731 		ldap_unbind(ld);
3732 		return 2;
3733 	}
3734 #else							/* !WIN32 */
3735 	/* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
3736 	if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3737 	{
3738 		free(url);
3739 		ldap_unbind(ld);
3740 		return 3;
3741 	}
3742 
3743 	/* anonymous bind */
3744 	if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3745 	{
3746 		/* error or network timeout */
3747 		free(url);
3748 		ldap_unbind(ld);
3749 		return 2;
3750 	}
3751 
3752 	/* wait some time for the connection to succeed */
3753 	res = NULL;
3754 	if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3755 		res == NULL)
3756 	{
3757 		/* error or timeout */
3758 		if (res != NULL)
3759 			ldap_msgfree(res);
3760 		free(url);
3761 		ldap_unbind(ld);
3762 		return 2;
3763 	}
3764 	ldap_msgfree(res);
3765 
3766 	/* reset timeout */
3767 	time.tv_sec = -1;
3768 	if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3769 	{
3770 		free(url);
3771 		ldap_unbind(ld);
3772 		return 3;
3773 	}
3774 #endif   /* WIN32 */
3775 
3776 	/* search */
3777 	res = NULL;
3778 	if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3779 		!= LDAP_SUCCESS)
3780 	{
3781 		if (res != NULL)
3782 			ldap_msgfree(res);
3783 		printfPQExpBuffer(errorMessage,
3784 						  libpq_gettext("lookup on LDAP server failed: %s\n"),
3785 						  ldap_err2string(rc));
3786 		ldap_unbind(ld);
3787 		free(url);
3788 		return 1;
3789 	}
3790 
3791 	/* complain if there was not exactly one result */
3792 	if ((rc = ldap_count_entries(ld, res)) != 1)
3793 	{
3794 		printfPQExpBuffer(errorMessage,
3795 			 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3796 						  : libpq_gettext("no entry found on LDAP lookup\n"));
3797 		ldap_msgfree(res);
3798 		ldap_unbind(ld);
3799 		free(url);
3800 		return 1;
3801 	}
3802 
3803 	/* get entry */
3804 	if ((entry = ldap_first_entry(ld, res)) == NULL)
3805 	{
3806 		/* should never happen */
3807 		printfPQExpBuffer(errorMessage,
3808 						  libpq_gettext("no entry found on LDAP lookup\n"));
3809 		ldap_msgfree(res);
3810 		ldap_unbind(ld);
3811 		free(url);
3812 		return 1;
3813 	}
3814 
3815 	/* get values */
3816 	if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3817 	{
3818 		printfPQExpBuffer(errorMessage,
3819 				  libpq_gettext("attribute has no values on LDAP lookup\n"));
3820 		ldap_msgfree(res);
3821 		ldap_unbind(ld);
3822 		free(url);
3823 		return 1;
3824 	}
3825 
3826 	ldap_msgfree(res);
3827 	free(url);
3828 
3829 	if (values[0] == NULL)
3830 	{
3831 		printfPQExpBuffer(errorMessage,
3832 				  libpq_gettext("attribute has no values on LDAP lookup\n"));
3833 		ldap_value_free_len(values);
3834 		ldap_unbind(ld);
3835 		return 1;
3836 	}
3837 
3838 	/* concatenate values into a single string with newline terminators */
3839 	size = 1;					/* for the trailing null */
3840 	for (i = 0; values[i] != NULL; i++)
3841 		size += values[i]->bv_len + 1;
3842 	if ((result = malloc(size)) == NULL)
3843 	{
3844 		printfPQExpBuffer(errorMessage,
3845 						  libpq_gettext("out of memory\n"));
3846 		ldap_value_free_len(values);
3847 		ldap_unbind(ld);
3848 		return 3;
3849 	}
3850 	p = result;
3851 	for (i = 0; values[i] != NULL; i++)
3852 	{
3853 		memcpy(p, values[i]->bv_val, values[i]->bv_len);
3854 		p += values[i]->bv_len;
3855 		*(p++) = '\n';
3856 	}
3857 	*p = '\0';
3858 
3859 	ldap_value_free_len(values);
3860 	ldap_unbind(ld);
3861 
3862 	/* parse result string */
3863 	oldstate = state = 0;
3864 	for (p = result; *p != '\0'; ++p)
3865 	{
3866 		switch (state)
3867 		{
3868 			case 0:				/* between entries */
3869 				if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3870 				{
3871 					optname = p;
3872 					state = 1;
3873 				}
3874 				break;
3875 			case 1:				/* in option name */
3876 				if (ld_is_sp_tab(*p))
3877 				{
3878 					*p = '\0';
3879 					state = 2;
3880 				}
3881 				else if (ld_is_nl_cr(*p))
3882 				{
3883 					printfPQExpBuffer(errorMessage, libpq_gettext(
3884 					"missing \"=\" after \"%s\" in connection info string\n"),
3885 									  optname);
3886 					free(result);
3887 					return 3;
3888 				}
3889 				else if (*p == '=')
3890 				{
3891 					*p = '\0';
3892 					state = 3;
3893 				}
3894 				break;
3895 			case 2:				/* after option name */
3896 				if (*p == '=')
3897 				{
3898 					state = 3;
3899 				}
3900 				else if (!ld_is_sp_tab(*p))
3901 				{
3902 					printfPQExpBuffer(errorMessage, libpq_gettext(
3903 					"missing \"=\" after \"%s\" in connection info string\n"),
3904 									  optname);
3905 					free(result);
3906 					return 3;
3907 				}
3908 				break;
3909 			case 3:				/* before option value */
3910 				if (*p == '\'')
3911 				{
3912 					optval = p + 1;
3913 					p1 = p + 1;
3914 					state = 5;
3915 				}
3916 				else if (ld_is_nl_cr(*p))
3917 				{
3918 					optval = optname + strlen(optname); /* empty */
3919 					state = 0;
3920 				}
3921 				else if (!ld_is_sp_tab(*p))
3922 				{
3923 					optval = p;
3924 					state = 4;
3925 				}
3926 				break;
3927 			case 4:				/* in unquoted option value */
3928 				if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3929 				{
3930 					*p = '\0';
3931 					state = 0;
3932 				}
3933 				break;
3934 			case 5:				/* in quoted option value */
3935 				if (*p == '\'')
3936 				{
3937 					*p1 = '\0';
3938 					state = 0;
3939 				}
3940 				else if (*p == '\\')
3941 					state = 6;
3942 				else
3943 					*(p1++) = *p;
3944 				break;
3945 			case 6:				/* in quoted option value after escape */
3946 				*(p1++) = *p;
3947 				state = 5;
3948 				break;
3949 		}
3950 
3951 		if (state == 0 && oldstate != 0)
3952 		{
3953 			found_keyword = false;
3954 			for (i = 0; options[i].keyword; i++)
3955 			{
3956 				if (strcmp(options[i].keyword, optname) == 0)
3957 				{
3958 					if (options[i].val == NULL)
3959 					{
3960 						options[i].val = strdup(optval);
3961 						if (!options[i].val)
3962 						{
3963 							printfPQExpBuffer(errorMessage,
3964 										   libpq_gettext("out of memory\n"));
3965 							free(result);
3966 							return 3;
3967 						}
3968 					}
3969 					found_keyword = true;
3970 					break;
3971 				}
3972 			}
3973 			if (!found_keyword)
3974 			{
3975 				printfPQExpBuffer(errorMessage,
3976 						 libpq_gettext("invalid connection option \"%s\"\n"),
3977 								  optname);
3978 				free(result);
3979 				return 1;
3980 			}
3981 			optname = NULL;
3982 			optval = NULL;
3983 		}
3984 		oldstate = state;
3985 	}
3986 
3987 	free(result);
3988 
3989 	if (state == 5 || state == 6)
3990 	{
3991 		printfPQExpBuffer(errorMessage, libpq_gettext(
3992 				  "unterminated quoted string in connection info string\n"));
3993 		return 3;
3994 	}
3995 
3996 	return 0;
3997 }
3998 
3999 #endif   /* USE_LDAP */
4000 
4001 #define MAXBUFSIZE 256
4002 
4003 /*
4004  * parseServiceInfo: if a service name has been given, look it up and absorb
4005  * connection options from it into *options.
4006  *
4007  * Returns 0 on success, nonzero on failure.  On failure, if errorMessage
4008  * isn't null, also store an error message there.  (Note: the only reason
4009  * this function and related ones don't dump core on errorMessage == NULL
4010  * is the undocumented fact that printfPQExpBuffer does nothing when passed
4011  * a null PQExpBuffer pointer.)
4012  */
4013 static int
parseServiceInfo(PQconninfoOption * options,PQExpBuffer errorMessage)4014 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
4015 {
4016 	const char *service = conninfo_getval(options, "service");
4017 	char		serviceFile[MAXPGPATH];
4018 	char	   *env;
4019 	bool		group_found = false;
4020 	int			status;
4021 	struct stat stat_buf;
4022 
4023 	/*
4024 	 * We have to special-case the environment variable PGSERVICE here, since
4025 	 * this is and should be called before inserting environment defaults for
4026 	 * other connection options.
4027 	 */
4028 	if (service == NULL)
4029 		service = getenv("PGSERVICE");
4030 
4031 	/* If no service name given, nothing to do */
4032 	if (service == NULL)
4033 		return 0;
4034 
4035 	/*
4036 	 * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
4037 	 * exists).
4038 	 */
4039 	if ((env = getenv("PGSERVICEFILE")) != NULL)
4040 		strlcpy(serviceFile, env, sizeof(serviceFile));
4041 	else
4042 	{
4043 		char		homedir[MAXPGPATH];
4044 
4045 		if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
4046 			goto next_file;
4047 		snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
4048 		if (stat(serviceFile, &stat_buf) != 0)
4049 			goto next_file;
4050 	}
4051 
4052 	status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
4053 	if (group_found || status != 0)
4054 		return status;
4055 
4056 next_file:
4057 
4058 	/*
4059 	 * This could be used by any application so we can't use the binary
4060 	 * location to find our config files.
4061 	 */
4062 	snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
4063 			 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
4064 	if (stat(serviceFile, &stat_buf) != 0)
4065 		goto last_file;
4066 
4067 	status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
4068 	if (status != 0)
4069 		return status;
4070 
4071 last_file:
4072 	if (!group_found)
4073 	{
4074 		printfPQExpBuffer(errorMessage,
4075 		 libpq_gettext("definition of service \"%s\" not found\n"), service);
4076 		return 3;
4077 	}
4078 
4079 	return 0;
4080 }
4081 
4082 static int
parseServiceFile(const char * serviceFile,const char * service,PQconninfoOption * options,PQExpBuffer errorMessage,bool * group_found)4083 parseServiceFile(const char *serviceFile,
4084 				 const char *service,
4085 				 PQconninfoOption *options,
4086 				 PQExpBuffer errorMessage,
4087 				 bool *group_found)
4088 {
4089 	int			linenr = 0,
4090 				i;
4091 	FILE	   *f;
4092 	char		buf[MAXBUFSIZE],
4093 			   *line;
4094 
4095 	f = fopen(serviceFile, "r");
4096 	if (f == NULL)
4097 	{
4098 		printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
4099 						  serviceFile);
4100 		return 1;
4101 	}
4102 
4103 	while ((line = fgets(buf, sizeof(buf), f)) != NULL)
4104 	{
4105 		int			len;
4106 
4107 		linenr++;
4108 
4109 		if (strlen(line) >= sizeof(buf) - 1)
4110 		{
4111 			fclose(f);
4112 			printfPQExpBuffer(errorMessage,
4113 				  libpq_gettext("line %d too long in service file \"%s\"\n"),
4114 							  linenr,
4115 							  serviceFile);
4116 			return 2;
4117 		}
4118 
4119 		/* ignore EOL at end of line, including \r in case it's a DOS file */
4120 		len = strlen(line);
4121 		while (len > 0 && (line[len - 1] == '\n' ||
4122 						   line[len - 1] == '\r'))
4123 			line[--len] = '\0';
4124 
4125 		/* ignore leading blanks */
4126 		while (*line && isspace((unsigned char) line[0]))
4127 			line++;
4128 
4129 		/* ignore comments and empty lines */
4130 		if (line[0] == '\0' || line[0] == '#')
4131 			continue;
4132 
4133 		/* Check for right groupname */
4134 		if (line[0] == '[')
4135 		{
4136 			if (*group_found)
4137 			{
4138 				/* group info already read */
4139 				fclose(f);
4140 				return 0;
4141 			}
4142 
4143 			if (strncmp(line + 1, service, strlen(service)) == 0 &&
4144 				line[strlen(service) + 1] == ']')
4145 				*group_found = true;
4146 			else
4147 				*group_found = false;
4148 		}
4149 		else
4150 		{
4151 			if (*group_found)
4152 			{
4153 				/*
4154 				 * Finally, we are in the right group and can parse the line
4155 				 */
4156 				char	   *key,
4157 						   *val;
4158 				bool		found_keyword;
4159 
4160 #ifdef USE_LDAP
4161 				if (strncmp(line, "ldap", 4) == 0)
4162 				{
4163 					int			rc = ldapServiceLookup(line, options, errorMessage);
4164 
4165 					/* if rc = 2, go on reading for fallback */
4166 					switch (rc)
4167 					{
4168 						case 0:
4169 							fclose(f);
4170 							return 0;
4171 						case 1:
4172 						case 3:
4173 							fclose(f);
4174 							return 3;
4175 						case 2:
4176 							continue;
4177 					}
4178 				}
4179 #endif
4180 
4181 				key = line;
4182 				val = strchr(line, '=');
4183 				if (val == NULL)
4184 				{
4185 					printfPQExpBuffer(errorMessage,
4186 									  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
4187 									  serviceFile,
4188 									  linenr);
4189 					fclose(f);
4190 					return 3;
4191 				}
4192 				*val++ = '\0';
4193 
4194 				if (strcmp(key, "service") == 0)
4195 				{
4196 					printfPQExpBuffer(errorMessage,
4197 									  libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
4198 									  serviceFile,
4199 									  linenr);
4200 					fclose(f);
4201 					return 3;
4202 				}
4203 
4204 				/*
4205 				 * Set the parameter --- but don't override any previous
4206 				 * explicit setting.
4207 				 */
4208 				found_keyword = false;
4209 				for (i = 0; options[i].keyword; i++)
4210 				{
4211 					if (strcmp(options[i].keyword, key) == 0)
4212 					{
4213 						if (options[i].val == NULL)
4214 							options[i].val = strdup(val);
4215 						if (!options[i].val)
4216 						{
4217 							printfPQExpBuffer(errorMessage,
4218 										   libpq_gettext("out of memory\n"));
4219 							fclose(f);
4220 							return 3;
4221 						}
4222 						found_keyword = true;
4223 						break;
4224 					}
4225 				}
4226 
4227 				if (!found_keyword)
4228 				{
4229 					printfPQExpBuffer(errorMessage,
4230 									  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
4231 									  serviceFile,
4232 									  linenr);
4233 					fclose(f);
4234 					return 3;
4235 				}
4236 			}
4237 		}
4238 	}
4239 
4240 	fclose(f);
4241 
4242 	return 0;
4243 }
4244 
4245 
4246 /*
4247  *		PQconninfoParse
4248  *
4249  * Parse a string like PQconnectdb() would do and return the
4250  * resulting connection options array.  NULL is returned on failure.
4251  * The result contains only options specified directly in the string,
4252  * not any possible default values.
4253  *
4254  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
4255  * string on failure (use PQfreemem to free it).  In out-of-memory conditions
4256  * both *errmsg and the result could be NULL.
4257  *
4258  * NOTE: the returned array is dynamically allocated and should
4259  * be freed when no longer needed via PQconninfoFree().
4260  */
4261 PQconninfoOption *
PQconninfoParse(const char * conninfo,char ** errmsg)4262 PQconninfoParse(const char *conninfo, char **errmsg)
4263 {
4264 	PQExpBufferData errorBuf;
4265 	PQconninfoOption *connOptions;
4266 
4267 	if (errmsg)
4268 		*errmsg = NULL;			/* default */
4269 	initPQExpBuffer(&errorBuf);
4270 	if (PQExpBufferDataBroken(errorBuf))
4271 		return NULL;			/* out of memory already :-( */
4272 	connOptions = parse_connection_string(conninfo, &errorBuf, false);
4273 	if (connOptions == NULL && errmsg)
4274 		*errmsg = errorBuf.data;
4275 	else
4276 		termPQExpBuffer(&errorBuf);
4277 	return connOptions;
4278 }
4279 
4280 /*
4281  * Build a working copy of the constant PQconninfoOptions array.
4282  */
4283 static PQconninfoOption *
conninfo_init(PQExpBuffer errorMessage)4284 conninfo_init(PQExpBuffer errorMessage)
4285 {
4286 	PQconninfoOption *options;
4287 	PQconninfoOption *opt_dest;
4288 	const internalPQconninfoOption *cur_opt;
4289 
4290 	/*
4291 	 * Get enough memory for all options in PQconninfoOptions, even if some
4292 	 * end up being filtered out.
4293 	 */
4294 	options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4295 	if (options == NULL)
4296 	{
4297 		printfPQExpBuffer(errorMessage,
4298 						  libpq_gettext("out of memory\n"));
4299 		return NULL;
4300 	}
4301 	opt_dest = options;
4302 
4303 	for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4304 	{
4305 		/* Only copy the public part of the struct, not the full internal */
4306 		memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4307 		opt_dest++;
4308 	}
4309 	MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4310 
4311 	return options;
4312 }
4313 
4314 /*
4315  * Connection string parser
4316  *
4317  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4318  * Otherwise, NULL is returned and an error message is left in errorMessage.
4319  *
4320  * If use_defaults is TRUE, default values are filled in (from a service file,
4321  * environment variables, etc).
4322  */
4323 static PQconninfoOption *
parse_connection_string(const char * connstr,PQExpBuffer errorMessage,bool use_defaults)4324 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4325 						bool use_defaults)
4326 {
4327 	/* Parse as URI if connection string matches URI prefix */
4328 	if (uri_prefix_length(connstr) != 0)
4329 		return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4330 
4331 	/* Parse as default otherwise */
4332 	return conninfo_parse(connstr, errorMessage, use_defaults);
4333 }
4334 
4335 /*
4336  * Checks if connection string starts with either of the valid URI prefix
4337  * designators.
4338  *
4339  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4340  *
4341  * XXX this is duplicated in psql/common.c.
4342  */
4343 static int
uri_prefix_length(const char * connstr)4344 uri_prefix_length(const char *connstr)
4345 {
4346 	if (strncmp(connstr, uri_designator,
4347 				sizeof(uri_designator) - 1) == 0)
4348 		return sizeof(uri_designator) - 1;
4349 
4350 	if (strncmp(connstr, short_uri_designator,
4351 				sizeof(short_uri_designator) - 1) == 0)
4352 		return sizeof(short_uri_designator) - 1;
4353 
4354 	return 0;
4355 }
4356 
4357 /*
4358  * Recognized connection string either starts with a valid URI prefix or
4359  * contains a "=" in it.
4360  *
4361  * Must be consistent with parse_connection_string: anything for which this
4362  * returns true should at least look like it's parseable by that routine.
4363  *
4364  * XXX this is duplicated in psql/common.c
4365  */
4366 static bool
recognized_connection_string(const char * connstr)4367 recognized_connection_string(const char *connstr)
4368 {
4369 	return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4370 }
4371 
4372 /*
4373  * Subroutine for parse_connection_string
4374  *
4375  * Deal with a string containing key=value pairs.
4376  */
4377 static PQconninfoOption *
conninfo_parse(const char * conninfo,PQExpBuffer errorMessage,bool use_defaults)4378 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4379 			   bool use_defaults)
4380 {
4381 	char	   *pname;
4382 	char	   *pval;
4383 	char	   *buf;
4384 	char	   *cp;
4385 	char	   *cp2;
4386 	PQconninfoOption *options;
4387 
4388 	/* Make a working copy of PQconninfoOptions */
4389 	options = conninfo_init(errorMessage);
4390 	if (options == NULL)
4391 		return NULL;
4392 
4393 	/* Need a modifiable copy of the input string */
4394 	if ((buf = strdup(conninfo)) == NULL)
4395 	{
4396 		printfPQExpBuffer(errorMessage,
4397 						  libpq_gettext("out of memory\n"));
4398 		PQconninfoFree(options);
4399 		return NULL;
4400 	}
4401 	cp = buf;
4402 
4403 	while (*cp)
4404 	{
4405 		/* Skip blanks before the parameter name */
4406 		if (isspace((unsigned char) *cp))
4407 		{
4408 			cp++;
4409 			continue;
4410 		}
4411 
4412 		/* Get the parameter name */
4413 		pname = cp;
4414 		while (*cp)
4415 		{
4416 			if (*cp == '=')
4417 				break;
4418 			if (isspace((unsigned char) *cp))
4419 			{
4420 				*cp++ = '\0';
4421 				while (*cp)
4422 				{
4423 					if (!isspace((unsigned char) *cp))
4424 						break;
4425 					cp++;
4426 				}
4427 				break;
4428 			}
4429 			cp++;
4430 		}
4431 
4432 		/* Check that there is a following '=' */
4433 		if (*cp != '=')
4434 		{
4435 			printfPQExpBuffer(errorMessage,
4436 							  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4437 							  pname);
4438 			PQconninfoFree(options);
4439 			free(buf);
4440 			return NULL;
4441 		}
4442 		*cp++ = '\0';
4443 
4444 		/* Skip blanks after the '=' */
4445 		while (*cp)
4446 		{
4447 			if (!isspace((unsigned char) *cp))
4448 				break;
4449 			cp++;
4450 		}
4451 
4452 		/* Get the parameter value */
4453 		pval = cp;
4454 
4455 		if (*cp != '\'')
4456 		{
4457 			cp2 = pval;
4458 			while (*cp)
4459 			{
4460 				if (isspace((unsigned char) *cp))
4461 				{
4462 					*cp++ = '\0';
4463 					break;
4464 				}
4465 				if (*cp == '\\')
4466 				{
4467 					cp++;
4468 					if (*cp != '\0')
4469 						*cp2++ = *cp++;
4470 				}
4471 				else
4472 					*cp2++ = *cp++;
4473 			}
4474 			*cp2 = '\0';
4475 		}
4476 		else
4477 		{
4478 			cp2 = pval;
4479 			cp++;
4480 			for (;;)
4481 			{
4482 				if (*cp == '\0')
4483 				{
4484 					printfPQExpBuffer(errorMessage,
4485 									  libpq_gettext("unterminated quoted string in connection info string\n"));
4486 					PQconninfoFree(options);
4487 					free(buf);
4488 					return NULL;
4489 				}
4490 				if (*cp == '\\')
4491 				{
4492 					cp++;
4493 					if (*cp != '\0')
4494 						*cp2++ = *cp++;
4495 					continue;
4496 				}
4497 				if (*cp == '\'')
4498 				{
4499 					*cp2 = '\0';
4500 					cp++;
4501 					break;
4502 				}
4503 				*cp2++ = *cp++;
4504 			}
4505 		}
4506 
4507 		/*
4508 		 * Now that we have the name and the value, store the record.
4509 		 */
4510 		if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4511 		{
4512 			PQconninfoFree(options);
4513 			free(buf);
4514 			return NULL;
4515 		}
4516 	}
4517 
4518 	/* Done with the modifiable input string */
4519 	free(buf);
4520 
4521 	/*
4522 	 * Add in defaults if the caller wants that.
4523 	 */
4524 	if (use_defaults)
4525 	{
4526 		if (!conninfo_add_defaults(options, errorMessage))
4527 		{
4528 			PQconninfoFree(options);
4529 			return NULL;
4530 		}
4531 	}
4532 
4533 	return options;
4534 }
4535 
4536 /*
4537  * Conninfo array parser routine
4538  *
4539  * If successful, a malloc'd PQconninfoOption array is returned.
4540  * If not successful, NULL is returned and an error message is
4541  * left in errorMessage.
4542  * Defaults are supplied (from a service file, environment variables, etc)
4543  * for unspecified options, but only if use_defaults is TRUE.
4544  *
4545  * If expand_dbname is non-zero, and the value passed for the first occurrence
4546  * of "dbname" keyword is a connection string (as indicated by
4547  * recognized_connection_string) then parse and process it, overriding any
4548  * previously processed conflicting keywords. Subsequent keywords will take
4549  * precedence, however. In-tree programs generally specify expand_dbname=true,
4550  * so command-line arguments naming a database can use a connection string.
4551  * Some code acquires arbitrary database names from known-literal sources like
4552  * PQdb(), PQconninfoParse() and pg_database.datname.  When connecting to such
4553  * a database, in-tree code first wraps the name in a connection string.
4554  */
4555 static PQconninfoOption *
conninfo_array_parse(const char * const * keywords,const char * const * values,PQExpBuffer errorMessage,bool use_defaults,int expand_dbname)4556 conninfo_array_parse(const char *const * keywords, const char *const * values,
4557 					 PQExpBuffer errorMessage, bool use_defaults,
4558 					 int expand_dbname)
4559 {
4560 	PQconninfoOption *options;
4561 	PQconninfoOption *dbname_options = NULL;
4562 	PQconninfoOption *option;
4563 	int			i = 0;
4564 
4565 	/*
4566 	 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4567 	 * actually a recognized connection string.
4568 	 */
4569 	while (expand_dbname && keywords[i])
4570 	{
4571 		const char *pname = keywords[i];
4572 		const char *pvalue = values[i];
4573 
4574 		/* first find "dbname" if any */
4575 		if (strcmp(pname, "dbname") == 0 && pvalue)
4576 		{
4577 			/*
4578 			 * If value is a connection string, parse it, but do not use
4579 			 * defaults here -- those get picked up later. We only want to
4580 			 * override for those parameters actually passed.
4581 			 */
4582 			if (recognized_connection_string(pvalue))
4583 			{
4584 				dbname_options = parse_connection_string(pvalue, errorMessage, false);
4585 				if (dbname_options == NULL)
4586 					return NULL;
4587 			}
4588 			break;
4589 		}
4590 		++i;
4591 	}
4592 
4593 	/* Make a working copy of PQconninfoOptions */
4594 	options = conninfo_init(errorMessage);
4595 	if (options == NULL)
4596 	{
4597 		PQconninfoFree(dbname_options);
4598 		return NULL;
4599 	}
4600 
4601 	/* Parse the keywords/values arrays */
4602 	i = 0;
4603 	while (keywords[i])
4604 	{
4605 		const char *pname = keywords[i];
4606 		const char *pvalue = values[i];
4607 
4608 		if (pvalue != NULL && pvalue[0] != '\0')
4609 		{
4610 			/* Search for the param record */
4611 			for (option = options; option->keyword != NULL; option++)
4612 			{
4613 				if (strcmp(option->keyword, pname) == 0)
4614 					break;
4615 			}
4616 
4617 			/* Check for invalid connection option */
4618 			if (option->keyword == NULL)
4619 			{
4620 				printfPQExpBuffer(errorMessage,
4621 						 libpq_gettext("invalid connection option \"%s\"\n"),
4622 								  pname);
4623 				PQconninfoFree(options);
4624 				PQconninfoFree(dbname_options);
4625 				return NULL;
4626 			}
4627 
4628 			/*
4629 			 * If we are on the first dbname parameter, and we have a parsed
4630 			 * connection string, copy those parameters across, overriding any
4631 			 * existing previous settings.
4632 			 */
4633 			if (strcmp(pname, "dbname") == 0 && dbname_options)
4634 			{
4635 				PQconninfoOption *str_option;
4636 
4637 				for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4638 				{
4639 					if (str_option->val != NULL)
4640 					{
4641 						int			k;
4642 
4643 						for (k = 0; options[k].keyword; k++)
4644 						{
4645 							if (strcmp(options[k].keyword, str_option->keyword) == 0)
4646 							{
4647 								if (options[k].val)
4648 									free(options[k].val);
4649 								options[k].val = strdup(str_option->val);
4650 								if (!options[k].val)
4651 								{
4652 									printfPQExpBuffer(errorMessage,
4653 										   libpq_gettext("out of memory\n"));
4654 									PQconninfoFree(options);
4655 									PQconninfoFree(dbname_options);
4656 									return NULL;
4657 								}
4658 								break;
4659 							}
4660 						}
4661 					}
4662 				}
4663 
4664 				/*
4665 				 * Forget the parsed connection string, so that any subsequent
4666 				 * dbname parameters will not be expanded.
4667 				 */
4668 				PQconninfoFree(dbname_options);
4669 				dbname_options = NULL;
4670 			}
4671 			else
4672 			{
4673 				/*
4674 				 * Store the value, overriding previous settings
4675 				 */
4676 				if (option->val)
4677 					free(option->val);
4678 				option->val = strdup(pvalue);
4679 				if (!option->val)
4680 				{
4681 					printfPQExpBuffer(errorMessage,
4682 									  libpq_gettext("out of memory\n"));
4683 					PQconninfoFree(options);
4684 					PQconninfoFree(dbname_options);
4685 					return NULL;
4686 				}
4687 			}
4688 		}
4689 		++i;
4690 	}
4691 	PQconninfoFree(dbname_options);
4692 
4693 	/*
4694 	 * Add in defaults if the caller wants that.
4695 	 */
4696 	if (use_defaults)
4697 	{
4698 		if (!conninfo_add_defaults(options, errorMessage))
4699 		{
4700 			PQconninfoFree(options);
4701 			return NULL;
4702 		}
4703 	}
4704 
4705 	return options;
4706 }
4707 
4708 /*
4709  * Add the default values for any unspecified options to the connection
4710  * options array.
4711  *
4712  * Defaults are obtained from a service file, environment variables, etc.
4713  *
4714  * Returns TRUE if successful, otherwise FALSE; errorMessage, if supplied,
4715  * is filled in upon failure.  Note that failure to locate a default value
4716  * is not an error condition here --- we just leave the option's value as
4717  * NULL.
4718  */
4719 static bool
conninfo_add_defaults(PQconninfoOption * options,PQExpBuffer errorMessage)4720 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4721 {
4722 	PQconninfoOption *option;
4723 	char	   *tmp;
4724 
4725 	/*
4726 	 * If there's a service spec, use it to obtain any not-explicitly-given
4727 	 * parameters.  Ignore error if no error message buffer is passed because
4728 	 * there is no way to pass back the failure message.
4729 	 */
4730 	if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
4731 		return false;
4732 
4733 	/*
4734 	 * Get the fallback resources for parameters not specified in the conninfo
4735 	 * string nor the service.
4736 	 */
4737 	for (option = options; option->keyword != NULL; option++)
4738 	{
4739 		if (option->val != NULL)
4740 			continue;			/* Value was in conninfo or service */
4741 
4742 		/*
4743 		 * Try to get the environment variable fallback
4744 		 */
4745 		if (option->envvar != NULL)
4746 		{
4747 			if ((tmp = getenv(option->envvar)) != NULL)
4748 			{
4749 				option->val = strdup(tmp);
4750 				if (!option->val)
4751 				{
4752 					if (errorMessage)
4753 						printfPQExpBuffer(errorMessage,
4754 										  libpq_gettext("out of memory\n"));
4755 					return false;
4756 				}
4757 				continue;
4758 			}
4759 		}
4760 
4761 		/*
4762 		 * Interpret the deprecated PGREQUIRESSL environment variable.  Per
4763 		 * tradition, translate values starting with "1" to sslmode=require,
4764 		 * and ignore other values.  Given both PGREQUIRESSL=1 and PGSSLMODE,
4765 		 * PGSSLMODE takes precedence; the opposite was true before v9.3.
4766 		 */
4767 		if (strcmp(option->keyword, "sslmode") == 0)
4768 		{
4769 			const char *requiresslenv = getenv("PGREQUIRESSL");
4770 
4771 			if (requiresslenv != NULL && requiresslenv[0] == '1')
4772 			{
4773 				option->val = strdup("require");
4774 				if (!option->val)
4775 				{
4776 					if (errorMessage)
4777 						printfPQExpBuffer(errorMessage,
4778 										  libpq_gettext("out of memory\n"));
4779 					return false;
4780 				}
4781 				continue;
4782 			}
4783 		}
4784 
4785 		/*
4786 		 * No environment variable specified or the variable isn't set - try
4787 		 * compiled-in default
4788 		 */
4789 		if (option->compiled != NULL)
4790 		{
4791 			option->val = strdup(option->compiled);
4792 			if (!option->val)
4793 			{
4794 				if (errorMessage)
4795 					printfPQExpBuffer(errorMessage,
4796 									  libpq_gettext("out of memory\n"));
4797 				return false;
4798 			}
4799 			continue;
4800 		}
4801 
4802 		/*
4803 		 * Special handling for "user" option.  Note that if pg_fe_getauthname
4804 		 * fails, we just leave the value as NULL; there's no need for this to
4805 		 * be an error condition if the caller provides a user name.  The only
4806 		 * reason we do this now at all is so that callers of PQconndefaults
4807 		 * will see a correct default (barring error, of course).
4808 		 */
4809 		if (strcmp(option->keyword, "user") == 0)
4810 		{
4811 			option->val = pg_fe_getauthname(NULL);
4812 			continue;
4813 		}
4814 	}
4815 
4816 	return true;
4817 }
4818 
4819 /*
4820  * Subroutine for parse_connection_string
4821  *
4822  * Deal with a URI connection string.
4823  */
4824 static PQconninfoOption *
conninfo_uri_parse(const char * uri,PQExpBuffer errorMessage,bool use_defaults)4825 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4826 				   bool use_defaults)
4827 {
4828 	PQconninfoOption *options;
4829 
4830 	/* Make a working copy of PQconninfoOptions */
4831 	options = conninfo_init(errorMessage);
4832 	if (options == NULL)
4833 		return NULL;
4834 
4835 	if (!conninfo_uri_parse_options(options, uri, errorMessage))
4836 	{
4837 		PQconninfoFree(options);
4838 		return NULL;
4839 	}
4840 
4841 	/*
4842 	 * Add in defaults if the caller wants that.
4843 	 */
4844 	if (use_defaults)
4845 	{
4846 		if (!conninfo_add_defaults(options, errorMessage))
4847 		{
4848 			PQconninfoFree(options);
4849 			return NULL;
4850 		}
4851 	}
4852 
4853 	return options;
4854 }
4855 
4856 /*
4857  * conninfo_uri_parse_options
4858  *		Actual URI parser.
4859  *
4860  * If successful, returns true while the options array is filled with parsed
4861  * options from the URI.
4862  * If not successful, returns false and fills errorMessage accordingly.
4863  *
4864  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4865  * 3986):
4866  *
4867  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4868  *
4869  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4870  * by literal square brackets.
4871  *
4872  * Any of the URI parts might use percent-encoding (%xy).
4873  */
4874 static bool
conninfo_uri_parse_options(PQconninfoOption * options,const char * uri,PQExpBuffer errorMessage)4875 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4876 						   PQExpBuffer errorMessage)
4877 {
4878 	int			prefix_len;
4879 	char	   *p;
4880 	char	   *buf;
4881 	char	   *start;
4882 	char		prevchar = '\0';
4883 	char	   *user = NULL;
4884 	char	   *host = NULL;
4885 	bool		retval = false;
4886 
4887 	/* need a modifiable copy of the input URI */
4888 	buf = strdup(uri);
4889 	if (buf == NULL)
4890 	{
4891 		printfPQExpBuffer(errorMessage,
4892 						  libpq_gettext("out of memory\n"));
4893 		return false;
4894 	}
4895 	start = buf;
4896 
4897 	/* Skip the URI prefix */
4898 	prefix_len = uri_prefix_length(uri);
4899 	if (prefix_len == 0)
4900 	{
4901 		/* Should never happen */
4902 		printfPQExpBuffer(errorMessage,
4903 						  libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4904 						  uri);
4905 		goto cleanup;
4906 	}
4907 	start += prefix_len;
4908 	p = start;
4909 
4910 	/* Look ahead for possible user credentials designator */
4911 	while (*p && *p != '@' && *p != '/')
4912 		++p;
4913 	if (*p == '@')
4914 	{
4915 		/*
4916 		 * Found username/password designator, so URI should be of the form
4917 		 * "scheme://user[:password]@[netloc]".
4918 		 */
4919 		user = start;
4920 
4921 		p = user;
4922 		while (*p != ':' && *p != '@')
4923 			++p;
4924 
4925 		/* Save last char and cut off at end of user name */
4926 		prevchar = *p;
4927 		*p = '\0';
4928 
4929 		if (*user &&
4930 			!conninfo_storeval(options, "user", user,
4931 							   errorMessage, false, true))
4932 			goto cleanup;
4933 
4934 		if (prevchar == ':')
4935 		{
4936 			const char *password = p + 1;
4937 
4938 			while (*p != '@')
4939 				++p;
4940 			*p = '\0';
4941 
4942 			if (*password &&
4943 				!conninfo_storeval(options, "password", password,
4944 								   errorMessage, false, true))
4945 				goto cleanup;
4946 		}
4947 
4948 		/* Advance past end of parsed user name or password token */
4949 		++p;
4950 	}
4951 	else
4952 	{
4953 		/*
4954 		 * No username/password designator found.  Reset to start of URI.
4955 		 */
4956 		p = start;
4957 	}
4958 
4959 	/*
4960 	 * "p" has been incremented past optional URI credential information at
4961 	 * this point and now points at the "netloc" part of the URI.
4962 	 *
4963 	 * Look for IPv6 address.
4964 	 */
4965 	if (*p == '[')
4966 	{
4967 		host = ++p;
4968 		while (*p && *p != ']')
4969 			++p;
4970 		if (!*p)
4971 		{
4972 			printfPQExpBuffer(errorMessage,
4973 							  libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4974 							  uri);
4975 			goto cleanup;
4976 		}
4977 		if (p == host)
4978 		{
4979 			printfPQExpBuffer(errorMessage,
4980 							  libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4981 							  uri);
4982 			goto cleanup;
4983 		}
4984 
4985 		/* Cut off the bracket and advance */
4986 		*(p++) = '\0';
4987 
4988 		/*
4989 		 * The address may be followed by a port specifier or a slash or a
4990 		 * query.
4991 		 */
4992 		if (*p && *p != ':' && *p != '/' && *p != '?')
4993 		{
4994 			printfPQExpBuffer(errorMessage,
4995 							  libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4996 							  *p, (int) (p - buf + 1), uri);
4997 			goto cleanup;
4998 		}
4999 	}
5000 	else
5001 	{
5002 		/* not an IPv6 address: DNS-named or IPv4 netloc */
5003 		host = p;
5004 
5005 		/*
5006 		 * Look for port specifier (colon) or end of host specifier (slash),
5007 		 * or query (question mark).
5008 		 */
5009 		while (*p && *p != ':' && *p != '/' && *p != '?')
5010 			++p;
5011 	}
5012 
5013 	/* Save the hostname terminator before we null it */
5014 	prevchar = *p;
5015 	*p = '\0';
5016 
5017 	if (*host &&
5018 		!conninfo_storeval(options, "host", host,
5019 						   errorMessage, false, true))
5020 		goto cleanup;
5021 
5022 
5023 	if (prevchar == ':')
5024 	{
5025 		const char *port = ++p; /* advance past host terminator */
5026 
5027 		while (*p && *p != '/' && *p != '?')
5028 			++p;
5029 
5030 		prevchar = *p;
5031 		*p = '\0';
5032 
5033 		if (*port &&
5034 			!conninfo_storeval(options, "port", port,
5035 							   errorMessage, false, true))
5036 			goto cleanup;
5037 	}
5038 
5039 	if (prevchar && prevchar != '?')
5040 	{
5041 		const char *dbname = ++p;		/* advance past host terminator */
5042 
5043 		/* Look for query parameters */
5044 		while (*p && *p != '?')
5045 			++p;
5046 
5047 		prevchar = *p;
5048 		*p = '\0';
5049 
5050 		/*
5051 		 * Avoid setting dbname to an empty string, as it forces the default
5052 		 * value (username) and ignores $PGDATABASE, as opposed to not setting
5053 		 * it at all.
5054 		 */
5055 		if (*dbname &&
5056 			!conninfo_storeval(options, "dbname", dbname,
5057 							   errorMessage, false, true))
5058 			goto cleanup;
5059 	}
5060 
5061 	if (prevchar)
5062 	{
5063 		++p;					/* advance past terminator */
5064 
5065 		if (!conninfo_uri_parse_params(p, options, errorMessage))
5066 			goto cleanup;
5067 	}
5068 
5069 	/* everything parsed okay */
5070 	retval = true;
5071 
5072 cleanup:
5073 	free(buf);
5074 	return retval;
5075 }
5076 
5077 /*
5078  * Connection URI parameters parser routine
5079  *
5080  * If successful, returns true while connOptions is filled with parsed
5081  * parameters.  Otherwise, returns false and fills errorMessage appropriately.
5082  *
5083  * Destructively modifies 'params' buffer.
5084  */
5085 static bool
conninfo_uri_parse_params(char * params,PQconninfoOption * connOptions,PQExpBuffer errorMessage)5086 conninfo_uri_parse_params(char *params,
5087 						  PQconninfoOption *connOptions,
5088 						  PQExpBuffer errorMessage)
5089 {
5090 	while (*params)
5091 	{
5092 		char	   *keyword = params;
5093 		char	   *value = NULL;
5094 		char	   *p = params;
5095 		bool		malloced = false;
5096 
5097 		/*
5098 		 * Scan the params string for '=' and '&', marking the end of keyword
5099 		 * and value respectively.
5100 		 */
5101 		for (;;)
5102 		{
5103 			if (*p == '=')
5104 			{
5105 				/* Was there '=' already? */
5106 				if (value != NULL)
5107 				{
5108 					printfPQExpBuffer(errorMessage,
5109 									  libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
5110 									  keyword);
5111 					return false;
5112 				}
5113 				/* Cut off keyword, advance to value */
5114 				*p++ = '\0';
5115 				value = p;
5116 			}
5117 			else if (*p == '&' || *p == '\0')
5118 			{
5119 				/*
5120 				 * If not at the end, cut off value and advance; leave p
5121 				 * pointing to start of the next parameter, if any.
5122 				 */
5123 				if (*p != '\0')
5124 					*p++ = '\0';
5125 				/* Was there '=' at all? */
5126 				if (value == NULL)
5127 				{
5128 					printfPQExpBuffer(errorMessage,
5129 									  libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
5130 									  keyword);
5131 					return false;
5132 				}
5133 				/* Got keyword and value, go process them. */
5134 				break;
5135 			}
5136 			else
5137 				++p;			/* Advance over all other bytes. */
5138 		}
5139 
5140 		keyword = conninfo_uri_decode(keyword, errorMessage);
5141 		if (keyword == NULL)
5142 		{
5143 			/* conninfo_uri_decode already set an error message */
5144 			return false;
5145 		}
5146 		value = conninfo_uri_decode(value, errorMessage);
5147 		if (value == NULL)
5148 		{
5149 			/* conninfo_uri_decode already set an error message */
5150 			free(keyword);
5151 			return false;
5152 		}
5153 		malloced = true;
5154 
5155 		/*
5156 		 * Special keyword handling for improved JDBC compatibility.
5157 		 */
5158 		if (strcmp(keyword, "ssl") == 0 &&
5159 			strcmp(value, "true") == 0)
5160 		{
5161 			free(keyword);
5162 			free(value);
5163 			malloced = false;
5164 
5165 			keyword = "sslmode";
5166 			value = "require";
5167 		}
5168 
5169 		/*
5170 		 * Store the value if the corresponding option exists; ignore
5171 		 * otherwise.  At this point both keyword and value are not
5172 		 * URI-encoded.
5173 		 */
5174 		if (!conninfo_storeval(connOptions, keyword, value,
5175 							   errorMessage, true, false))
5176 		{
5177 			/* Insert generic message if conninfo_storeval didn't give one. */
5178 			if (errorMessage->len == 0)
5179 				printfPQExpBuffer(errorMessage,
5180 					  libpq_gettext("invalid URI query parameter: \"%s\"\n"),
5181 								  keyword);
5182 			/* And fail. */
5183 			if (malloced)
5184 			{
5185 				free(keyword);
5186 				free(value);
5187 			}
5188 			return false;
5189 		}
5190 
5191 		if (malloced)
5192 		{
5193 			free(keyword);
5194 			free(value);
5195 		}
5196 
5197 		/* Proceed to next key=value pair, if any */
5198 		params = p;
5199 	}
5200 
5201 	return true;
5202 }
5203 
5204 /*
5205  * Connection URI decoder routine
5206  *
5207  * If successful, returns the malloc'd decoded string.
5208  * If not successful, returns NULL and fills errorMessage accordingly.
5209  *
5210  * The string is decoded by replacing any percent-encoded tokens with
5211  * corresponding characters, while preserving any non-encoded characters.  A
5212  * percent-encoded token is a character triplet: a percent sign, followed by a
5213  * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
5214  * treated identically.
5215  */
5216 static char *
conninfo_uri_decode(const char * str,PQExpBuffer errorMessage)5217 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
5218 {
5219 	char	   *buf;
5220 	char	   *p;
5221 	const char *q = str;
5222 
5223 	buf = malloc(strlen(str) + 1);
5224 	if (buf == NULL)
5225 	{
5226 		printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5227 		return NULL;
5228 	}
5229 	p = buf;
5230 
5231 	for (;;)
5232 	{
5233 		if (*q != '%')
5234 		{
5235 			/* copy and check for NUL terminator */
5236 			if (!(*(p++) = *(q++)))
5237 				break;
5238 		}
5239 		else
5240 		{
5241 			int			hi;
5242 			int			lo;
5243 			int			c;
5244 
5245 			++q;				/* skip the percent sign itself */
5246 
5247 			/*
5248 			 * Possible EOL will be caught by the first call to
5249 			 * get_hexdigit(), so we never dereference an invalid q pointer.
5250 			 */
5251 			if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
5252 			{
5253 				printfPQExpBuffer(errorMessage,
5254 					libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
5255 								  str);
5256 				free(buf);
5257 				return NULL;
5258 			}
5259 
5260 			c = (hi << 4) | lo;
5261 			if (c == 0)
5262 			{
5263 				printfPQExpBuffer(errorMessage,
5264 								  libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
5265 								  str);
5266 				free(buf);
5267 				return NULL;
5268 			}
5269 			*(p++) = c;
5270 		}
5271 	}
5272 
5273 	return buf;
5274 }
5275 
5276 /*
5277  * Convert hexadecimal digit character to its integer value.
5278  *
5279  * If successful, returns true and value is filled with digit's base 16 value.
5280  * If not successful, returns false.
5281  *
5282  * Lower- and upper-case letters in the range A-F are treated identically.
5283  */
5284 static bool
get_hexdigit(char digit,int * value)5285 get_hexdigit(char digit, int *value)
5286 {
5287 	if ('0' <= digit && digit <= '9')
5288 		*value = digit - '0';
5289 	else if ('A' <= digit && digit <= 'F')
5290 		*value = digit - 'A' + 10;
5291 	else if ('a' <= digit && digit <= 'f')
5292 		*value = digit - 'a' + 10;
5293 	else
5294 		return false;
5295 
5296 	return true;
5297 }
5298 
5299 /*
5300  * Find an option value corresponding to the keyword in the connOptions array.
5301  *
5302  * If successful, returns a pointer to the corresponding option's value.
5303  * If not successful, returns NULL.
5304  */
5305 static const char *
conninfo_getval(PQconninfoOption * connOptions,const char * keyword)5306 conninfo_getval(PQconninfoOption *connOptions,
5307 				const char *keyword)
5308 {
5309 	PQconninfoOption *option;
5310 
5311 	option = conninfo_find(connOptions, keyword);
5312 
5313 	return option ? option->val : NULL;
5314 }
5315 
5316 /*
5317  * Store a (new) value for an option corresponding to the keyword in
5318  * connOptions array.
5319  *
5320  * If uri_decode is true, the value is URI-decoded.  The keyword is always
5321  * assumed to be non URI-encoded.
5322  *
5323  * If successful, returns a pointer to the corresponding PQconninfoOption,
5324  * which value is replaced with a strdup'd copy of the passed value string.
5325  * The existing value for the option is free'd before replacing, if any.
5326  *
5327  * If not successful, returns NULL and fills errorMessage accordingly.
5328  * However, if the reason of failure is an invalid keyword being passed and
5329  * ignoreMissing is TRUE, errorMessage will be left untouched.
5330  */
5331 static PQconninfoOption *
conninfo_storeval(PQconninfoOption * connOptions,const char * keyword,const char * value,PQExpBuffer errorMessage,bool ignoreMissing,bool uri_decode)5332 conninfo_storeval(PQconninfoOption *connOptions,
5333 				  const char *keyword, const char *value,
5334 				  PQExpBuffer errorMessage, bool ignoreMissing,
5335 				  bool uri_decode)
5336 {
5337 	PQconninfoOption *option;
5338 	char	   *value_copy;
5339 
5340 	/*
5341 	 * For backwards compatibility, requiressl=1 gets translated to
5342 	 * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5343 	 * (which is the default for sslmode).
5344 	 */
5345 	if (strcmp(keyword, "requiressl") == 0)
5346 	{
5347 		keyword = "sslmode";
5348 		if (value[0] == '1')
5349 			value = "require";
5350 		else
5351 			value = "prefer";
5352 	}
5353 
5354 	option = conninfo_find(connOptions, keyword);
5355 	if (option == NULL)
5356 	{
5357 		if (!ignoreMissing)
5358 			printfPQExpBuffer(errorMessage,
5359 						 libpq_gettext("invalid connection option \"%s\"\n"),
5360 							  keyword);
5361 		return NULL;
5362 	}
5363 
5364 	if (uri_decode)
5365 	{
5366 		value_copy = conninfo_uri_decode(value, errorMessage);
5367 		if (value_copy == NULL)
5368 			/* conninfo_uri_decode already set an error message */
5369 			return NULL;
5370 	}
5371 	else
5372 	{
5373 		value_copy = strdup(value);
5374 		if (value_copy == NULL)
5375 		{
5376 			printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5377 			return NULL;
5378 		}
5379 	}
5380 
5381 	if (option->val)
5382 		free(option->val);
5383 	option->val = value_copy;
5384 
5385 	return option;
5386 }
5387 
5388 /*
5389  * Find a PQconninfoOption option corresponding to the keyword in the
5390  * connOptions array.
5391  *
5392  * If successful, returns a pointer to the corresponding PQconninfoOption
5393  * structure.
5394  * If not successful, returns NULL.
5395  */
5396 static PQconninfoOption *
conninfo_find(PQconninfoOption * connOptions,const char * keyword)5397 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5398 {
5399 	PQconninfoOption *option;
5400 
5401 	for (option = connOptions; option->keyword != NULL; option++)
5402 	{
5403 		if (strcmp(option->keyword, keyword) == 0)
5404 			return option;
5405 	}
5406 
5407 	return NULL;
5408 }
5409 
5410 
5411 /*
5412  * Return the connection options used for the connection
5413  */
5414 PQconninfoOption *
PQconninfo(PGconn * conn)5415 PQconninfo(PGconn *conn)
5416 {
5417 	PQExpBufferData errorBuf;
5418 	PQconninfoOption *connOptions;
5419 
5420 	if (conn == NULL)
5421 		return NULL;
5422 
5423 	/* We don't actually report any errors here, but callees want a buffer */
5424 	initPQExpBuffer(&errorBuf);
5425 	if (PQExpBufferDataBroken(errorBuf))
5426 		return NULL;			/* out of memory already :-( */
5427 
5428 	connOptions = conninfo_init(&errorBuf);
5429 
5430 	if (connOptions != NULL)
5431 	{
5432 		const internalPQconninfoOption *option;
5433 
5434 		for (option = PQconninfoOptions; option->keyword; option++)
5435 		{
5436 			char	  **connmember;
5437 
5438 			if (option->connofs < 0)
5439 				continue;
5440 
5441 			connmember = (char **) ((char *) conn + option->connofs);
5442 
5443 			if (*connmember)
5444 				conninfo_storeval(connOptions, option->keyword, *connmember,
5445 								  &errorBuf, true, false);
5446 		}
5447 	}
5448 
5449 	termPQExpBuffer(&errorBuf);
5450 
5451 	return connOptions;
5452 }
5453 
5454 
5455 void
PQconninfoFree(PQconninfoOption * connOptions)5456 PQconninfoFree(PQconninfoOption *connOptions)
5457 {
5458 	PQconninfoOption *option;
5459 
5460 	if (connOptions == NULL)
5461 		return;
5462 
5463 	for (option = connOptions; option->keyword != NULL; option++)
5464 	{
5465 		if (option->val != NULL)
5466 			free(option->val);
5467 	}
5468 	free(connOptions);
5469 }
5470 
5471 
5472 /* =========== accessor functions for PGconn ========= */
5473 char *
PQdb(const PGconn * conn)5474 PQdb(const PGconn *conn)
5475 {
5476 	if (!conn)
5477 		return NULL;
5478 	return conn->dbName;
5479 }
5480 
5481 char *
PQuser(const PGconn * conn)5482 PQuser(const PGconn *conn)
5483 {
5484 	if (!conn)
5485 		return NULL;
5486 	return conn->pguser;
5487 }
5488 
5489 char *
PQpass(const PGconn * conn)5490 PQpass(const PGconn *conn)
5491 {
5492 	if (!conn)
5493 		return NULL;
5494 	return conn->pgpass;
5495 }
5496 
5497 char *
PQhost(const PGconn * conn)5498 PQhost(const PGconn *conn)
5499 {
5500 	if (!conn)
5501 		return NULL;
5502 	if (conn->pghost != NULL && conn->pghost[0] != '\0')
5503 		return conn->pghost;
5504 	else
5505 	{
5506 #ifdef HAVE_UNIX_SOCKETS
5507 		if (conn->pgunixsocket != NULL && conn->pgunixsocket[0] != '\0')
5508 			return conn->pgunixsocket;
5509 		else
5510 			return DEFAULT_PGSOCKET_DIR;
5511 #else
5512 		return DefaultHost;
5513 #endif
5514 	}
5515 }
5516 
5517 char *
PQport(const PGconn * conn)5518 PQport(const PGconn *conn)
5519 {
5520 	if (!conn)
5521 		return NULL;
5522 	return conn->pgport;
5523 }
5524 
5525 char *
PQtty(const PGconn * conn)5526 PQtty(const PGconn *conn)
5527 {
5528 	if (!conn)
5529 		return NULL;
5530 	return conn->pgtty;
5531 }
5532 
5533 char *
PQoptions(const PGconn * conn)5534 PQoptions(const PGconn *conn)
5535 {
5536 	if (!conn)
5537 		return NULL;
5538 	return conn->pgoptions;
5539 }
5540 
5541 ConnStatusType
PQstatus(const PGconn * conn)5542 PQstatus(const PGconn *conn)
5543 {
5544 	if (!conn)
5545 		return CONNECTION_BAD;
5546 	return conn->status;
5547 }
5548 
5549 PGTransactionStatusType
PQtransactionStatus(const PGconn * conn)5550 PQtransactionStatus(const PGconn *conn)
5551 {
5552 	if (!conn || conn->status != CONNECTION_OK)
5553 		return PQTRANS_UNKNOWN;
5554 	if (conn->asyncStatus != PGASYNC_IDLE)
5555 		return PQTRANS_ACTIVE;
5556 	return conn->xactStatus;
5557 }
5558 
5559 const char *
PQparameterStatus(const PGconn * conn,const char * paramName)5560 PQparameterStatus(const PGconn *conn, const char *paramName)
5561 {
5562 	const pgParameterStatus *pstatus;
5563 
5564 	if (!conn || !paramName)
5565 		return NULL;
5566 	for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5567 	{
5568 		if (strcmp(pstatus->name, paramName) == 0)
5569 			return pstatus->value;
5570 	}
5571 	return NULL;
5572 }
5573 
5574 int
PQprotocolVersion(const PGconn * conn)5575 PQprotocolVersion(const PGconn *conn)
5576 {
5577 	if (!conn)
5578 		return 0;
5579 	if (conn->status == CONNECTION_BAD)
5580 		return 0;
5581 	return PG_PROTOCOL_MAJOR(conn->pversion);
5582 }
5583 
5584 int
PQserverVersion(const PGconn * conn)5585 PQserverVersion(const PGconn *conn)
5586 {
5587 	if (!conn)
5588 		return 0;
5589 	if (conn->status == CONNECTION_BAD)
5590 		return 0;
5591 	return conn->sversion;
5592 }
5593 
5594 char *
PQerrorMessage(const PGconn * conn)5595 PQerrorMessage(const PGconn *conn)
5596 {
5597 	if (!conn)
5598 		return libpq_gettext("connection pointer is NULL\n");
5599 
5600 	return conn->errorMessage.data;
5601 }
5602 
5603 /*
5604  * In Windows, socket values are unsigned, and an invalid socket value
5605  * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
5606  * warning). Ideally we would return an unsigned value for PQsocket() on
5607  * Windows, but that would cause the function's return value to differ from
5608  * Unix, so we just return -1 for invalid sockets.
5609  * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
5610  * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
5611  */
5612 int
PQsocket(const PGconn * conn)5613 PQsocket(const PGconn *conn)
5614 {
5615 	if (!conn)
5616 		return -1;
5617 	return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
5618 }
5619 
5620 int
PQbackendPID(const PGconn * conn)5621 PQbackendPID(const PGconn *conn)
5622 {
5623 	if (!conn || conn->status != CONNECTION_OK)
5624 		return 0;
5625 	return conn->be_pid;
5626 }
5627 
5628 int
PQconnectionNeedsPassword(const PGconn * conn)5629 PQconnectionNeedsPassword(const PGconn *conn)
5630 {
5631 	if (!conn)
5632 		return false;
5633 	if (conn->password_needed &&
5634 		(conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5635 		return true;
5636 	else
5637 		return false;
5638 }
5639 
5640 int
PQconnectionUsedPassword(const PGconn * conn)5641 PQconnectionUsedPassword(const PGconn *conn)
5642 {
5643 	if (!conn)
5644 		return false;
5645 	if (conn->password_needed)
5646 		return true;
5647 	else
5648 		return false;
5649 }
5650 
5651 int
PQclientEncoding(const PGconn * conn)5652 PQclientEncoding(const PGconn *conn)
5653 {
5654 	if (!conn || conn->status != CONNECTION_OK)
5655 		return -1;
5656 	return conn->client_encoding;
5657 }
5658 
5659 int
PQsetClientEncoding(PGconn * conn,const char * encoding)5660 PQsetClientEncoding(PGconn *conn, const char *encoding)
5661 {
5662 	char		qbuf[128];
5663 	static const char query[] = "set client_encoding to '%s'";
5664 	PGresult   *res;
5665 	int			status;
5666 
5667 	if (!conn || conn->status != CONNECTION_OK)
5668 		return -1;
5669 
5670 	if (!encoding)
5671 		return -1;
5672 
5673 	/* Resolve special "auto" value from the locale */
5674 	if (strcmp(encoding, "auto") == 0)
5675 		encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5676 
5677 	/* check query buffer overflow */
5678 	if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5679 		return -1;
5680 
5681 	/* ok, now send a query */
5682 	sprintf(qbuf, query, encoding);
5683 	res = PQexec(conn, qbuf);
5684 
5685 	if (res == NULL)
5686 		return -1;
5687 	if (res->resultStatus != PGRES_COMMAND_OK)
5688 		status = -1;
5689 	else
5690 	{
5691 		/*
5692 		 * In protocol 2 we have to assume the setting will stick, and adjust
5693 		 * our state immediately.  In protocol 3 and up we can rely on the
5694 		 * backend to report the parameter value, and we'll change state at
5695 		 * that time.
5696 		 */
5697 		if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5698 			pqSaveParameterStatus(conn, "client_encoding", encoding);
5699 		status = 0;				/* everything is ok */
5700 	}
5701 	PQclear(res);
5702 	return status;
5703 }
5704 
5705 PGVerbosity
PQsetErrorVerbosity(PGconn * conn,PGVerbosity verbosity)5706 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5707 {
5708 	PGVerbosity old;
5709 
5710 	if (!conn)
5711 		return PQERRORS_DEFAULT;
5712 	old = conn->verbosity;
5713 	conn->verbosity = verbosity;
5714 	return old;
5715 }
5716 
5717 PGContextVisibility
PQsetErrorContextVisibility(PGconn * conn,PGContextVisibility show_context)5718 PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
5719 {
5720 	PGContextVisibility old;
5721 
5722 	if (!conn)
5723 		return PQSHOW_CONTEXT_ERRORS;
5724 	old = conn->show_context;
5725 	conn->show_context = show_context;
5726 	return old;
5727 }
5728 
5729 void
PQtrace(PGconn * conn,FILE * debug_port)5730 PQtrace(PGconn *conn, FILE *debug_port)
5731 {
5732 	if (conn == NULL)
5733 		return;
5734 	PQuntrace(conn);
5735 	conn->Pfdebug = debug_port;
5736 }
5737 
5738 void
PQuntrace(PGconn * conn)5739 PQuntrace(PGconn *conn)
5740 {
5741 	if (conn == NULL)
5742 		return;
5743 	if (conn->Pfdebug)
5744 	{
5745 		fflush(conn->Pfdebug);
5746 		conn->Pfdebug = NULL;
5747 	}
5748 }
5749 
5750 PQnoticeReceiver
PQsetNoticeReceiver(PGconn * conn,PQnoticeReceiver proc,void * arg)5751 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5752 {
5753 	PQnoticeReceiver old;
5754 
5755 	if (conn == NULL)
5756 		return NULL;
5757 
5758 	old = conn->noticeHooks.noticeRec;
5759 	if (proc)
5760 	{
5761 		conn->noticeHooks.noticeRec = proc;
5762 		conn->noticeHooks.noticeRecArg = arg;
5763 	}
5764 	return old;
5765 }
5766 
5767 PQnoticeProcessor
PQsetNoticeProcessor(PGconn * conn,PQnoticeProcessor proc,void * arg)5768 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5769 {
5770 	PQnoticeProcessor old;
5771 
5772 	if (conn == NULL)
5773 		return NULL;
5774 
5775 	old = conn->noticeHooks.noticeProc;
5776 	if (proc)
5777 	{
5778 		conn->noticeHooks.noticeProc = proc;
5779 		conn->noticeHooks.noticeProcArg = arg;
5780 	}
5781 	return old;
5782 }
5783 
5784 /*
5785  * The default notice message receiver just gets the standard notice text
5786  * and sends it to the notice processor.  This two-level setup exists
5787  * mostly for backwards compatibility; perhaps we should deprecate use of
5788  * PQsetNoticeProcessor?
5789  */
5790 static void
defaultNoticeReceiver(void * arg,const PGresult * res)5791 defaultNoticeReceiver(void *arg, const PGresult *res)
5792 {
5793 	(void) arg;					/* not used */
5794 	if (res->noticeHooks.noticeProc != NULL)
5795 		(*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5796 										PQresultErrorMessage(res));
5797 }
5798 
5799 /*
5800  * The default notice message processor just prints the
5801  * message on stderr.  Applications can override this if they
5802  * want the messages to go elsewhere (a window, for example).
5803  * Note that simply discarding notices is probably a bad idea.
5804  */
5805 static void
defaultNoticeProcessor(void * arg,const char * message)5806 defaultNoticeProcessor(void *arg, const char *message)
5807 {
5808 	(void) arg;					/* not used */
5809 	/* Note: we expect the supplied string to end with a newline already. */
5810 	fprintf(stderr, "%s", message);
5811 }
5812 
5813 /*
5814  * returns a pointer to the next token or NULL if the current
5815  * token doesn't match
5816  */
5817 static char *
pwdfMatchesString(char * buf,char * token)5818 pwdfMatchesString(char *buf, char *token)
5819 {
5820 	char	   *tbuf,
5821 			   *ttok;
5822 	bool		bslash = false;
5823 
5824 	if (buf == NULL || token == NULL)
5825 		return NULL;
5826 	tbuf = buf;
5827 	ttok = token;
5828 	if (tbuf[0] == '*' && tbuf[1] == ':')
5829 		return tbuf + 2;
5830 	while (*tbuf != 0)
5831 	{
5832 		if (*tbuf == '\\' && !bslash)
5833 		{
5834 			tbuf++;
5835 			bslash = true;
5836 		}
5837 		if (*tbuf == ':' && *ttok == 0 && !bslash)
5838 			return tbuf + 1;
5839 		bslash = false;
5840 		if (*ttok == 0)
5841 			return NULL;
5842 		if (*tbuf == *ttok)
5843 		{
5844 			tbuf++;
5845 			ttok++;
5846 		}
5847 		else
5848 			return NULL;
5849 	}
5850 	return NULL;
5851 }
5852 
5853 /* Get a password from the password file. Return value is malloc'd. */
5854 static char *
PasswordFromFile(char * hostname,char * port,char * dbname,char * username)5855 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5856 {
5857 	FILE	   *fp;
5858 	char		pgpassfile[MAXPGPATH];
5859 	struct stat stat_buf;
5860 	PQExpBufferData buf;
5861 
5862 	if (dbname == NULL || strlen(dbname) == 0)
5863 		return NULL;
5864 
5865 	if (username == NULL || strlen(username) == 0)
5866 		return NULL;
5867 
5868 	/* 'localhost' matches pghost of '' or the default socket directory */
5869 	if (hostname == NULL)
5870 		hostname = DefaultHost;
5871 	else if (is_absolute_path(hostname))
5872 
5873 		/*
5874 		 * We should probably use canonicalize_path(), but then we have to
5875 		 * bring path.c into libpq, and it doesn't seem worth it.
5876 		 */
5877 		if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5878 			hostname = DefaultHost;
5879 
5880 	if (port == NULL)
5881 		port = DEF_PGPORT_STR;
5882 
5883 	if (!getPgPassFilename(pgpassfile))
5884 		return NULL;
5885 
5886 	/* If password file cannot be opened, ignore it. */
5887 	if (stat(pgpassfile, &stat_buf) != 0)
5888 		return NULL;
5889 
5890 #ifndef WIN32
5891 	if (!S_ISREG(stat_buf.st_mode))
5892 	{
5893 		fprintf(stderr,
5894 		libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5895 				pgpassfile);
5896 		return NULL;
5897 	}
5898 
5899 	/* If password file is insecure, alert the user and ignore it. */
5900 	if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5901 	{
5902 		fprintf(stderr,
5903 				libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5904 				pgpassfile);
5905 		return NULL;
5906 	}
5907 #else
5908 
5909 	/*
5910 	 * On Win32, the directory is protected, so we don't have to check the
5911 	 * file.
5912 	 */
5913 #endif
5914 
5915 	fp = fopen(pgpassfile, "r");
5916 	if (fp == NULL)
5917 		return NULL;
5918 
5919 	/* Use an expansible buffer to accommodate any reasonable line length */
5920 	initPQExpBuffer(&buf);
5921 
5922 	while (!feof(fp) && !ferror(fp))
5923 	{
5924 		/* Make sure there's a reasonable amount of room in the buffer */
5925 		if (!enlargePQExpBuffer(&buf, 128))
5926 			break;
5927 
5928 		/* Read some data, appending it to what we already have */
5929 		if (fgets(buf.data + buf.len, buf.maxlen - buf.len, fp) == NULL)
5930 			break;
5931 		buf.len += strlen(buf.data + buf.len);
5932 
5933 		/* If we don't yet have a whole line, loop around to read more */
5934 		if (!(buf.len > 0 && buf.data[buf.len - 1] == '\n') && !feof(fp))
5935 			continue;
5936 
5937 		/* ignore comments */
5938 		if (buf.data[0] != '#')
5939 		{
5940 			char	   *t = buf.data;
5941 			int			len = buf.len;
5942 
5943 			/* Remove trailing newline */
5944 			if (len > 0 && t[len - 1] == '\n')
5945 			{
5946 				t[--len] = '\0';
5947 				/* Handle DOS-style line endings, too */
5948 				if (len > 0 && t[len - 1] == '\r')
5949 					t[--len] = '\0';
5950 			}
5951 
5952 			if (len > 0 &&
5953 				(t = pwdfMatchesString(t, hostname)) != NULL &&
5954 				(t = pwdfMatchesString(t, port)) != NULL &&
5955 				(t = pwdfMatchesString(t, dbname)) != NULL &&
5956 				(t = pwdfMatchesString(t, username)) != NULL)
5957 			{
5958 				/* Found a match. */
5959 				char	   *ret,
5960 						   *p1,
5961 						   *p2;
5962 
5963 				ret = strdup(t);
5964 
5965 				fclose(fp);
5966 				termPQExpBuffer(&buf);
5967 
5968 				if (!ret)
5969 				{
5970 					/* Out of memory. XXX: an error message would be nice. */
5971 					return NULL;
5972 				}
5973 
5974 				/* De-escape password. */
5975 				for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5976 				{
5977 					if (*p1 == '\\' && p1[1] != '\0')
5978 						++p1;
5979 					*p2 = *p1;
5980 				}
5981 				*p2 = '\0';
5982 
5983 				return ret;
5984 			}
5985 		}
5986 
5987 		/* No match, reset buffer to prepare for next line. */
5988 		buf.len = 0;
5989 	}
5990 
5991 	fclose(fp);
5992 	termPQExpBuffer(&buf);
5993 	return NULL;
5994 }
5995 
5996 
5997 static bool
getPgPassFilename(char * pgpassfile)5998 getPgPassFilename(char *pgpassfile)
5999 {
6000 	char	   *passfile_env;
6001 
6002 	if ((passfile_env = getenv("PGPASSFILE")) != NULL)
6003 		/* use the literal path from the environment, if set */
6004 		strlcpy(pgpassfile, passfile_env, MAXPGPATH);
6005 	else
6006 	{
6007 		char		homedir[MAXPGPATH];
6008 
6009 		if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
6010 			return false;
6011 		snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
6012 	}
6013 	return true;
6014 }
6015 
6016 /*
6017  *	If the connection failed, we should mention if
6018  *	we got the password from .pgpass in case that
6019  *	password is wrong.
6020  */
6021 static void
dot_pg_pass_warning(PGconn * conn)6022 dot_pg_pass_warning(PGconn *conn)
6023 {
6024 	/* If it was 'invalid authorization', add .pgpass mention */
6025 	/* only works with >= 9.0 servers */
6026 	if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
6027 		strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
6028 			   ERRCODE_INVALID_PASSWORD) == 0)
6029 	{
6030 		char		pgpassfile[MAXPGPATH];
6031 
6032 		if (!getPgPassFilename(pgpassfile))
6033 			return;
6034 		appendPQExpBuffer(&conn->errorMessage,
6035 					  libpq_gettext("password retrieved from file \"%s\"\n"),
6036 						  pgpassfile);
6037 	}
6038 }
6039 
6040 
6041 /*
6042  * Obtain user's home directory, return in given buffer
6043  *
6044  * On Unix, this actually returns the user's home directory.  On Windows
6045  * it returns the PostgreSQL-specific application data folder.
6046  *
6047  * This is essentially the same as get_home_path(), but we don't use that
6048  * because we don't want to pull path.c into libpq (it pollutes application
6049  * namespace).
6050  *
6051  * Returns true on success, false on failure to obtain the directory name.
6052  *
6053  * CAUTION: although in most situations failure is unexpected, there are users
6054  * who like to run applications in a home-directory-less environment.  On
6055  * failure, you almost certainly DO NOT want to report an error.  Just act as
6056  * though whatever file you were hoping to find in the home directory isn't
6057  * there (which it isn't).
6058  */
6059 bool
pqGetHomeDirectory(char * buf,int bufsize)6060 pqGetHomeDirectory(char *buf, int bufsize)
6061 {
6062 #ifndef WIN32
6063 	char		pwdbuf[BUFSIZ];
6064 	struct passwd pwdstr;
6065 	struct passwd *pwd = NULL;
6066 
6067 	(void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
6068 	if (pwd == NULL)
6069 		return false;
6070 	strlcpy(buf, pwd->pw_dir, bufsize);
6071 	return true;
6072 #else
6073 	char		tmppath[MAX_PATH];
6074 
6075 	ZeroMemory(tmppath, sizeof(tmppath));
6076 	if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
6077 		return false;
6078 	snprintf(buf, bufsize, "%s/postgresql", tmppath);
6079 	return true;
6080 #endif
6081 }
6082 
6083 /*
6084  * To keep the API consistent, the locking stubs are always provided, even
6085  * if they are not required.
6086  */
6087 
6088 static void
default_threadlock(int acquire)6089 default_threadlock(int acquire)
6090 {
6091 #ifdef ENABLE_THREAD_SAFETY
6092 #ifndef WIN32
6093 	static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
6094 #else
6095 	static pthread_mutex_t singlethread_lock = NULL;
6096 	static long mutex_initlock = 0;
6097 
6098 	if (singlethread_lock == NULL)
6099 	{
6100 		while (InterlockedExchange(&mutex_initlock, 1) == 1)
6101 			 /* loop, another thread own the lock */ ;
6102 		if (singlethread_lock == NULL)
6103 		{
6104 			if (pthread_mutex_init(&singlethread_lock, NULL))
6105 				PGTHREAD_ERROR("failed to initialize mutex");
6106 		}
6107 		InterlockedExchange(&mutex_initlock, 0);
6108 	}
6109 #endif
6110 	if (acquire)
6111 	{
6112 		if (pthread_mutex_lock(&singlethread_lock))
6113 			PGTHREAD_ERROR("failed to lock mutex");
6114 	}
6115 	else
6116 	{
6117 		if (pthread_mutex_unlock(&singlethread_lock))
6118 			PGTHREAD_ERROR("failed to unlock mutex");
6119 	}
6120 #endif
6121 }
6122 
6123 pgthreadlock_t
PQregisterThreadLock(pgthreadlock_t newhandler)6124 PQregisterThreadLock(pgthreadlock_t newhandler)
6125 {
6126 	pgthreadlock_t prev = pg_g_threadlock;
6127 
6128 	if (newhandler)
6129 		pg_g_threadlock = newhandler;
6130 	else
6131 		pg_g_threadlock = default_threadlock;
6132 
6133 	return prev;
6134 }
6135