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