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