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