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