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