33 #include "pg_config_paths.h"
41 #define _WIN32_IE 0x0500
66 #define LDAP_DEPRECATED 1
68 typedef struct timeval LDAP_TIMEVAL;
75 #define PGPASSFILE ".pgpass"
77 #define PGPASSFILE "pgpass.conf"
86 #define ERRCODE_APPNAME_UNKNOWN "42704"
89 #define ERRCODE_INVALID_PASSWORD "28P01"
91 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
97 #if defined(TCP_KEEPIDLE)
99 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
100 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
101 #elif defined(TCP_KEEPALIVE_THRESHOLD)
103 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
104 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
105 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
108 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
109 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
116 #define DefaultHost "localhost"
117 #define DefaultOption ""
119 #define DefaultChannelBinding "prefer"
121 #define DefaultChannelBinding "disable"
123 #define DefaultTargetSessionAttrs "any"
124 #define DefaultLoadBalanceHosts "disable"
126 #define DefaultSSLMode "prefer"
127 #define DefaultSSLCertMode "allow"
129 #define DefaultSSLMode "disable"
130 #define DefaultSSLCertMode "disable"
132 #define DefaultSSLNegotiation "postgres"
135 #define DefaultGSSMode "prefer"
137 #define DefaultGSSMode "disable"
191 {
"service",
"PGSERVICE", NULL, NULL,
192 "Database-Service",
"", 20, -1},
194 {
"user",
"PGUSER", NULL, NULL,
195 "Database-User",
"", 20,
196 offsetof(
struct pg_conn, pguser)},
198 {
"password",
"PGPASSWORD", NULL, NULL,
199 "Database-Password",
"*", 20,
200 offsetof(
struct pg_conn, pgpass)},
202 {
"passfile",
"PGPASSFILE", NULL, NULL,
203 "Database-Password-File",
"", 64,
204 offsetof(
struct pg_conn, pgpassfile)},
207 "Channel-Binding",
"", 8,
208 offsetof(
struct pg_conn, channel_binding)},
210 {
"connect_timeout",
"PGCONNECT_TIMEOUT", NULL, NULL,
211 "Connect-timeout",
"", 10,
212 offsetof(
struct pg_conn, connect_timeout)},
214 {
"dbname",
"PGDATABASE", NULL, NULL,
215 "Database-Name",
"", 20,
218 {
"host",
"PGHOST", NULL, NULL,
219 "Database-Host",
"", 40,
222 {
"hostaddr",
"PGHOSTADDR", NULL, NULL,
223 "Database-Host-IP-Address",
"", 45,
224 offsetof(
struct pg_conn, pghostaddr)},
226 {
"port",
"PGPORT", DEF_PGPORT_STR, NULL,
227 "Database-Port",
"", 6,
230 {
"client_encoding",
"PGCLIENTENCODING", NULL, NULL,
231 "Client-Encoding",
"", 10,
232 offsetof(
struct pg_conn, client_encoding_initial)},
235 "Backend-Options",
"", 40,
236 offsetof(
struct pg_conn, pgoptions)},
238 {
"application_name",
"PGAPPNAME", NULL, NULL,
239 "Application-Name",
"", 64,
240 offsetof(
struct pg_conn, appname)},
242 {
"fallback_application_name", NULL, NULL, NULL,
243 "Fallback-Application-Name",
"", 64,
244 offsetof(
struct pg_conn, fbappname)},
246 {
"keepalives", NULL, NULL, NULL,
247 "TCP-Keepalives",
"", 1,
248 offsetof(
struct pg_conn, keepalives)},
250 {
"keepalives_idle", NULL, NULL, NULL,
251 "TCP-Keepalives-Idle",
"", 10,
252 offsetof(
struct pg_conn, keepalives_idle)},
254 {
"keepalives_interval", NULL, NULL, NULL,
255 "TCP-Keepalives-Interval",
"", 10,
256 offsetof(
struct pg_conn, keepalives_interval)},
258 {
"keepalives_count", NULL, NULL, NULL,
259 "TCP-Keepalives-Count",
"", 10,
260 offsetof(
struct pg_conn, keepalives_count)},
262 {
"tcp_user_timeout", NULL, NULL, NULL,
263 "TCP-User-Timeout",
"", 10,
264 offsetof(
struct pg_conn, pgtcp_user_timeout)},
274 offsetof(
struct pg_conn, sslmode)},
277 "SSL-Negotiation",
"", 14,
278 offsetof(
struct pg_conn, sslnegotiation)},
280 {
"sslcompression",
"PGSSLCOMPRESSION",
"0", NULL,
281 "SSL-Compression",
"", 1,
282 offsetof(
struct pg_conn, sslcompression)},
284 {
"sslcert",
"PGSSLCERT", NULL, NULL,
285 "SSL-Client-Cert",
"", 64,
286 offsetof(
struct pg_conn, sslcert)},
288 {
"sslkey",
"PGSSLKEY", NULL, NULL,
289 "SSL-Client-Key",
"", 64,
290 offsetof(
struct pg_conn, sslkey)},
292 {
"sslcertmode",
"PGSSLCERTMODE", NULL, NULL,
293 "SSL-Client-Cert-Mode",
"", 8,
294 offsetof(
struct pg_conn, sslcertmode)},
296 {
"sslpassword", NULL, NULL, NULL,
297 "SSL-Client-Key-Password",
"*", 20,
298 offsetof(
struct pg_conn, sslpassword)},
300 {
"sslrootcert",
"PGSSLROOTCERT", NULL, NULL,
301 "SSL-Root-Certificate",
"", 64,
302 offsetof(
struct pg_conn, sslrootcert)},
304 {
"sslcrl",
"PGSSLCRL", NULL, NULL,
305 "SSL-Revocation-List",
"", 64,
306 offsetof(
struct pg_conn, sslcrl)},
308 {
"sslcrldir",
"PGSSLCRLDIR", NULL, NULL,
309 "SSL-Revocation-List-Dir",
"", 64,
310 offsetof(
struct pg_conn, sslcrldir)},
312 {
"sslsni",
"PGSSLSNI",
"1", NULL,
314 offsetof(
struct pg_conn, sslsni)},
316 {
"requirepeer",
"PGREQUIREPEER", NULL, NULL,
317 "Require-Peer",
"", 10,
318 offsetof(
struct pg_conn, requirepeer)},
320 {
"require_auth",
"PGREQUIREAUTH", NULL, NULL,
321 "Require-Auth",
"", 14,
322 offsetof(
struct pg_conn, require_auth)},
324 {
"ssl_min_protocol_version",
"PGSSLMINPROTOCOLVERSION",
"TLSv1.2", NULL,
325 "SSL-Minimum-Protocol-Version",
"", 8,
328 {
"ssl_max_protocol_version",
"PGSSLMAXPROTOCOLVERSION", NULL, NULL,
329 "SSL-Maximum-Protocol-Version",
"", 8,
337 "GSSENC-Mode",
"", 8,
338 offsetof(
struct pg_conn, gssencmode)},
341 {
"krbsrvname",
"PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
342 "Kerberos-service-name",
"", 20,
343 offsetof(
struct pg_conn, krbsrvname)},
345 {
"gsslib",
"PGGSSLIB", NULL, NULL,
346 "GSS-library",
"", 7,
347 offsetof(
struct pg_conn, gsslib)},
349 {
"gssdelegation",
"PGGSSDELEGATION",
"0", NULL,
350 "GSS-delegation",
"", 1,
351 offsetof(
struct pg_conn, gssdelegation)},
353 {
"replication", NULL, NULL, NULL,
354 "Replication",
"D", 5,
355 offsetof(
struct pg_conn, replication)},
357 {
"target_session_attrs",
"PGTARGETSESSIONATTRS",
359 "Target-Session-Attrs",
"", 15,
360 offsetof(
struct pg_conn, target_session_attrs)},
362 {
"load_balance_hosts",
"PGLOADBALANCEHOSTS",
364 "Load-Balance-Hosts",
"", 8,
365 offsetof(
struct pg_conn, load_balance_hosts)},
368 {NULL, NULL, NULL, NULL,
376 "PGDATESTYLE",
"datestyle"
396 #if defined(USE_SSL) || defined(ENABLE_GSS)
397 static int encryption_negotiation_failed(
PGconn *
conn);
417 bool use_defaults,
int expand_dbname);
430 const char *keyword);
432 const char *keyword,
const char *
value,
433 PQExpBuffer errorMessage,
bool ignoreMissing,
bool uri_decode);
435 const char *keyword);
447 const char *
username,
const char *pgpassfile);
499 if (
conn->gcred != GSS_C_NO_CREDENTIAL)
501 gss_release_cred(&min_s, &
conn->gcred);
502 conn->gcred = GSS_C_NO_CREDENTIAL;
505 gss_delete_sec_context(&min_s, &
conn->gctx, GSS_C_NO_BUFFER);
507 gss_release_name(&min_s, &
conn->gtarg_nam);
508 if (
conn->gss_SendBuffer)
511 conn->gss_SendBuffer = NULL;
513 if (
conn->gss_RecvBuffer)
516 conn->gss_RecvBuffer = NULL;
518 if (
conn->gss_ResultBuffer)
521 conn->gss_ResultBuffer = NULL;
523 conn->gssenc =
false;
527 if (
conn->sspitarget)
530 conn->sspitarget = NULL;
534 FreeCredentialsHandle(
conn->sspicred);
536 conn->sspicred = NULL;
540 DeleteSecurityContext(
conn->sspictx);
542 conn->sspictx = NULL;
560 while (queue != NULL)
591 while (notify != NULL)
595 notify = notify->
next;
602 while (pstatus != NULL)
606 pstatus = pstatus->
next;
690 const char *
const *
values,
708 const char *
const *
values,
792 const char *
const *
values,
812 true, expand_dbname);
813 if (connOptions == NULL)
930 char **connmember = (
char **) ((
char *)
conn +
option->connofs);
933 *connmember = strdup(tmp);
934 if (*connmember == NULL)
965 const char **tmp = (
const char **) ((
char *) srcConn +
option->connofs);
969 char **dstConnmember = (
char **) ((
char *) dstConn +
option->connofs);
972 free(*dstConnmember);
973 *dstConnmember = strdup(*tmp);
974 if (*dstConnmember == NULL)
1005 if (connOptions == NULL)
1061 char *s = *startptr;
1070 while (*
e !=
'\0' && *
e !=
',')
1072 *more = (*
e ==
',');
1075 p = (
char *)
malloc(
sizeof(
char) * (
len + 1));
1096 struct timeval tval = {0};
1103 rseed = ((uintptr_t)
conn) ^
1104 ((uint64) getpid()) ^
1105 ((uint64) tval.tv_usec) ^
1106 ((uint64) tval.tv_sec);
1198 else if (ch->
host != NULL && ch->
host[0] !=
'\0')
1222 if (ch->
host == NULL)
1250 if (
i == 1 && !more)
1328 if (pwhost == NULL || pwhost[0] ==
'\0')
1349 bool negated =
false;
1358 for (first =
true, more =
true; more; first =
false)
1407 if (strcmp(method,
"password") == 0)
1411 else if (strcmp(method,
"md5") == 0)
1415 else if (strcmp(method,
"gss") == 0)
1420 else if (strcmp(method,
"sspi") == 0)
1425 else if (strcmp(method,
"scram-sha-256") == 0)
1432 else if (strcmp(method,
"none") == 0)
1461 "require_auth", method);
1643 "ssl_min_protocol_version",
1651 "ssl_max_protocol_version",
1694 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1768 "target_session_attrs",
1789 "load_balance_hosts",
1874 if (connOptions != NULL)
1902 const char *pgtty,
const char *
dbName,
const char *login,
1964 if (pgoptions && pgoptions[0] !=
'\0')
1972 if (login && login[0] !=
'\0')
1980 if (pwd && pwd[0] !=
'\0')
2021 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_NODELAY,
2046 if (addr->ss_family == AF_INET)
2049 &((
struct sockaddr_in *) addr)->sin_addr.s_addr,
2051 host_addr, host_addr_len) == NULL)
2052 host_addr[0] =
'\0';
2054 else if (addr->ss_family == AF_INET6)
2057 &((
struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2059 host_addr, host_addr_len) == NULL)
2060 host_addr[0] =
'\0';
2063 host_addr[0] =
'\0';
2079 char service[NI_MAXHOST];
2083 service,
sizeof(service),
2086 libpq_gettext(
"connection to server on socket \"%s\" failed: "),
2091 const char *displayed_host;
2092 const char *displayed_port;
2100 if (displayed_port == NULL || displayed_port[0] ==
'\0')
2101 displayed_port = DEF_PGPORT_STR;
2110 strcmp(displayed_host, host_addr) != 0)
2112 libpq_gettext(
"connection to server at \"%s\" (%s), port %s failed: "),
2113 displayed_host, host_addr,
2117 libpq_gettext(
"connection to server at \"%s\", port %s failed: "),
2161 return val != 0 ? 1 : 0;
2182 #ifdef PG_TCP_KEEPALIVE_IDLE
2183 if (setsockopt(
conn->
sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2184 (
char *) &idle,
sizeof(idle)) < 0)
2190 PG_TCP_KEEPALIVE_IDLE_STR,
2211 "keepalives_interval"))
2216 #ifdef TCP_KEEPINTVL
2217 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPINTVL,
2246 "keepalives_count"))
2252 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPCNT,
2253 (
char *) &count,
sizeof(count)) < 0)
2268 #ifdef SIO_KEEPALIVE_VALS
2278 struct tcp_keepalive ka;
2287 ka.keepalivetime = idle * 1000;
2288 ka.keepaliveinterval =
interval * 1000;
2316 "keepalives_interval"))
2322 "WSAIoctl",
"SIO_KEEPALIVE_VALS",
2343 "tcp_user_timeout"))
2349 #ifdef TCP_USER_TIMEOUT
2350 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2351 (
char *) &timeout,
sizeof(timeout)) < 0)
2380 goto connect_errReturn;
2391 "libpq is incorrectly linked to backend functions\n");
2392 goto connect_errReturn;
2455 time_t finish_time = ((time_t) -1);
2457 int last_whichhost = -2;
2458 int last_whichaddr = -2;
2504 finish_time = time(NULL) + timeout;
2593 bool reset_connection_state_machine =
false;
2594 bool need_new_connection =
false;
2659 reset_connection_state_machine =
true;
2670 struct addrinfo hint;
2671 struct addrinfo *addrlist;
2714 MemSet(&hint, 0,
sizeof(hint));
2715 hint.ai_socktype = SOCK_STREAM;
2716 hint.ai_family = AF_UNSPEC;
2719 if (ch->
port == NULL || ch->
port[0] ==
'\0')
2720 thisport = DEF_PGPORT;
2726 if (thisport < 1 || thisport > 65535)
2740 if (ret || !addrlist)
2749 hint.ai_flags = AI_NUMERICHOST;
2752 if (ret || !addrlist)
2761 hint.ai_family = AF_UNIX;
2777 if (ret || !addrlist)
2821 reset_connection_state_machine =
true;
2826 if (reset_connection_state_machine)
2839 reset_connection_state_machine =
false;
2840 need_new_connection =
true;
2844 if (need_new_connection)
2861 need_new_connection =
false;
2865 #define ENCRYPTION_NEGOTIATION_FAILED() \
2867 switch (encryption_negotiation_failed(conn)) \
2870 goto error_return; \
2872 conn->status = CONNECTION_MADE; \
2873 return PGRES_POLLING_WRITING; \
2875 need_new_connection = true; \
2881 #define CONNECTION_FAILED() \
2883 if (connection_failed(conn)) \
2885 need_new_connection = true; \
2889 goto error_return; \
2906 char host_addr[NI_MAXHOST];
2936 "GSSAPI encryption required but it is not supported over a local socket");
2939 if (
conn->gcred == GSS_C_NO_CREDENTIAL)
2944 "GSSAPI encryption required but no credential cache");
2975 sock_type = SOCK_STREAM;
2984 sock_type |= SOCK_CLOEXEC;
2986 #ifdef SOCK_NONBLOCK
2992 sock_type |= SOCK_NONBLOCK;
3031 if (addr_cur->
family != AF_UNIX)
3040 #ifndef SOCK_NONBLOCK
3050 #ifndef SOCK_CLOEXEC
3052 if (fcntl(
conn->
sock, F_SETFD, FD_CLOEXEC) == -1)
3062 if (addr_cur->
family != AF_UNIX)
3070 if (usekeepalives < 0)
3075 else if (usekeepalives == 0)
3081 SOL_SOCKET, SO_KEEPALIVE,
3082 (
char *) &on,
sizeof(on)) < 0)
3095 #ifdef SIO_KEEPALIVE_VALS
3096 else if (!prepKeepalivesWin32(
conn))
3142 if (setsockopt(
conn->
sock, SOL_SOCKET, SO_NOSIGPIPE,
3143 (
char *) &optval,
sizeof(optval)) == 0)
3208 if (getsockopt(
conn->
sock, SOL_SOCKET, SO_ERROR,
3209 (
char *) &optval, &optlen) == -1)
3215 else if (optval != 0)
3251 char *remote_username;
3263 if (errno == ENOSYS)
3274 if (remote_username == NULL)
3281 free(remote_username);
3284 free(remote_username);
3389 packetlen =
sizeof(cancelpacket);
3482 else if (SSLok ==
'N')
3490 else if (SSLok ==
'E')
3576 else if (rdresult == 0)
3603 else if (gss_ok !=
'G')
3705 (msgLength < 8 || msgLength > 2000))
3711 (msgLength < 8 || msgLength > 2000))
3717 #define MAX_ERRLEN 30000
3767 if (avail < msgLength)
3915 const char *sqlstate;
3923 need_new_connection =
true;
3955 bool read_only_server;
3975 "SHOW transaction_read_only"))
3988 read_only_server : !read_only_server)
4033 "SELECT pg_catalog.pg_is_in_recovery()"))
4150 if (strncmp(
val,
"on", 2) == 0)
4172 "SHOW transaction_read_only");
4206 if (strncmp(
val,
"t", 1) == 0)
4222 "SELECT pg_is_in_recovery()");
4235 "invalid connection state %d, probably indicative of memory corruption",
4273 "GSSAPI encryption required but it is not supported over a local socket)");
4327 #if defined(USE_SSL) || defined(ENABLE_GSS)
4382 int remaining_methods;
4384 #define SELECT_NEXT_METHOD(method) \
4386 if ((remaining_methods & method) != 0) \
4388 conn->current_enc_method = method; \
4418 "GSSAPI encryption required but no credential cache");
4439 if (have_valid_connection)
4451 #undef SELECT_NEXT_METHOD
4538 static bool wsastartup_done =
false;
4540 if (!wsastartup_done)
4544 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4546 wsastartup_done =
true;
4737 struct addrinfo *ai = addrlist;
4977 const void *
buf,
size_t buf_len)
5000 #define LDAP_URL "ldap://"
5001 #define LDAP_DEF_PORT 389
5002 #define PGLDAP_TIMEOUT 2
5004 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
5005 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
5031 int port = LDAP_DEF_PORT,
5054 char *attrs[2] = {NULL, NULL};
5059 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
5061 if ((url = strdup(purl)) == NULL)
5076 "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
5087 p = strchr(url + strlen(LDAP_URL),
'/');
5088 if (p == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5091 "invalid LDAP URL \"%s\": missing distinguished name",
5100 if ((p = strchr(dn,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5103 "invalid LDAP URL \"%s\": must have exactly one attribute",
5112 if ((p = strchr(attrs[0],
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5115 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5124 if ((p = strchr(scopestr,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5127 "invalid LDAP URL \"%s\": no filter",
5134 if ((p = strchr(filter,
'?')) != NULL)
5138 if ((p1 = strchr(
hostname,
':')) != NULL)
5145 lport = strtol(
portstr, &endptr, 10);
5146 if (*
portstr ==
'\0' || *endptr !=
'\0' || errno || lport < 0 || lport > 65535)
5149 "invalid LDAP URL \"%s\": invalid port number",
5158 if (strchr(attrs[0],
',') != NULL)
5161 "invalid LDAP URL \"%s\": must have exactly one attribute",
5169 scope = LDAP_SCOPE_BASE;
5171 scope = LDAP_SCOPE_ONELEVEL;
5173 scope = LDAP_SCOPE_SUBTREE;
5177 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5205 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
5214 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5222 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
5232 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &
res)) == -1 ||
5246 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5256 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &
res))
5261 libpq_append_error(errorMessage,
"lookup on LDAP server failed: %s", ldap_err2string(rc));
5268 if ((rc = ldap_count_entries(ld,
res)) != 1)
5281 if ((entry = ldap_first_entry(ld,
res)) == NULL)
5292 if ((
values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
5307 ldap_value_free_len(
values);
5319 ldap_value_free_len(
values);
5332 ldap_value_free_len(
values);
5336 oldstate =
state = 0;
5337 for (p = result; *p !=
'\0'; ++p)
5342 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5349 if (ld_is_sp_tab(*p))
5354 else if (ld_is_nl_cr(*p))
5357 "missing \"=\" after \"%s\" in connection info string",
5373 else if (!ld_is_sp_tab(*p))
5376 "missing \"=\" after \"%s\" in connection info string",
5389 else if (ld_is_nl_cr(*p))
5391 optval = optname + strlen(optname);
5394 else if (!ld_is_sp_tab(*p))
5401 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
5413 else if (*p ==
'\\')
5424 if (
state == 0 && oldstate != 0)
5426 found_keyword =
false;
5429 if (strcmp(
options[
i].keyword, optname) == 0)
5441 found_keyword =
true;
5462 "unterminated quoted string in connection info string");
5487 bool group_found =
false;
5489 struct stat stat_buf;
5496 if (service == NULL)
5497 service = getenv(
"PGSERVICE");
5500 if (service == NULL)
5507 if ((env = getenv(
"PGSERVICEFILE")) != NULL)
5508 strlcpy(serviceFile, env,
sizeof(serviceFile));
5516 if (
stat(serviceFile, &stat_buf) != 0)
5521 if (group_found || status != 0)
5531 getenv(
"PGSYSCONFDIR") ? getenv(
"PGSYSCONFDIR") : SYSCONFDIR);
5532 if (
stat(serviceFile, &stat_buf) != 0)
5551 const char *service,
5563 *group_found =
false;
5565 f = fopen(serviceFile,
"r");
5572 while ((line = fgets(
buf,
sizeof(
buf), f)) != NULL)
5578 if (strlen(line) >=
sizeof(
buf) - 1)
5581 "line %d too long in service file \"%s\"",
5590 while (
len > 0 && isspace((
unsigned char) line[
len - 1]))
5594 while (*line && isspace((
unsigned char) line[0]))
5598 if (line[0] ==
'\0' || line[0] ==
'#')
5610 if (strncmp(line + 1, service, strlen(service)) == 0 &&
5611 line[strlen(service) + 1] ==
']')
5612 *group_found =
true;
5614 *group_found =
false;
5628 if (strncmp(line,
"ldap", 4) == 0)
5630 int rc = ldapServiceLookup(line,
options, errorMessage);
5648 val = strchr(line,
'=');
5652 "syntax error in service file \"%s\", line %d",
5660 if (strcmp(
key,
"service") == 0)
5663 "nested service specifications not supported in service file \"%s\", line %d",
5674 found_keyword =
false;
5687 found_keyword =
true;
5695 "syntax error in service file \"%s\", line %d",
5739 if (connOptions == NULL &&
errmsg)
5859 if ((
buf = strdup(conninfo)) == NULL)
5870 if (isspace((
unsigned char) *cp))
5882 if (isspace((
unsigned char) *cp))
5887 if (!isspace((
unsigned char) *cp))
5900 "missing \"=\" after \"%s\" in connection info string",
5911 if (!isspace((
unsigned char) *cp))
5924 if (isspace((
unsigned char) *cp))
5948 libpq_append_error(errorMessage,
"unterminated quoted string in connection info string");
6032 while (expand_dbname && keywords[
i])
6034 const char *pname = keywords[
i];
6035 const char *pvalue =
values[
i];
6038 if (strcmp(pname,
"dbname") == 0 && pvalue)
6048 if (dbname_options == NULL)
6068 const char *pname = keywords[
i];
6069 const char *pvalue =
values[
i];
6071 if (pvalue != NULL && pvalue[0] !=
'\0')
6076 if (strcmp(
option->keyword, pname) == 0)
6081 if (
option->keyword == NULL)
6094 if (strcmp(pname,
"dbname") == 0 && dbname_options)
6098 for (str_option = dbname_options; str_option->
keyword != NULL; str_option++)
6100 if (str_option->
val != NULL)
6104 for (k = 0;
options[k].keyword; k++)
6128 dbname_options = NULL;
6181 *sslrootcert = NULL;
6198 if (strcmp(
option->keyword,
"sslrootcert") == 0)
6207 if (
option->envvar != NULL)
6209 if ((tmp = getenv(
option->envvar)) != NULL)
6228 if (strcmp(
option->keyword,
"sslmode") == 0)
6230 const char *requiresslenv = getenv(
"PGREQUIRESSL");
6232 if (requiresslenv != NULL && requiresslenv[0] ==
'1')
6249 sslmode_default =
option;
6256 if (
option->compiled != NULL)
6275 if (strcmp(
option->keyword,
"user") == 0)
6287 if (sslmode_default && sslrootcert)
6289 if (sslrootcert->val && strcmp(sslrootcert->val,
"system") == 0)
6293 sslmode_default->
val = strdup(
"verify-full");
6294 if (!sslmode_default->
val)
6372 char prevchar =
'\0';
6375 bool retval =
false;
6398 if (prefix_len == 0)
6402 "invalid URI propagated to internal parser routine: \"%s\"",
6406 start += prefix_len;
6410 while (*p && *p !=
'@' && *p !=
'/')
6421 while (*p !=
':' && *p !=
'@')
6430 errorMessage,
false,
true))
6433 if (prevchar ==
':')
6443 errorMessage,
false,
true))
6474 while (*p && *p !=
']')
6479 "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6486 "IPv6 host address may not be empty in URI: \"%s\"",
6498 if (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6501 "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6502 *p, (
int) (p -
buf + 1), uri);
6515 while (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6525 if (prevchar ==
':')
6527 const char *
port = ++p;
6529 while (*p && *p !=
'/' && *p !=
'?' && *p !=
',')
6538 if (prevchar !=
',')
6548 if (hostbuf.
data[0] &&
6550 errorMessage,
false,
true))
6552 if (portbuf.
data[0] &&
6554 errorMessage,
false,
true))
6557 if (prevchar && prevchar !=
'?')
6559 const char *
dbname = ++p;
6562 while (*p && *p !=
'?')
6575 errorMessage,
false,
true))
6612 char *keyword = params;
6615 bool malloced =
false;
6630 "extra key/value separator \"=\" in URI query parameter: \"%s\"",
6638 else if (*p ==
'&' || *p ==
'\0')
6650 "missing key/value separator \"=\" in URI query parameter: \"%s\"",
6662 if (keyword == NULL)
6679 if (strcmp(keyword,
"ssl") == 0 &&
6680 strcmp(
value,
"true") == 0)
6686 keyword =
"sslmode";
6695 oldmsglen = errorMessage->
len;
6697 errorMessage,
true,
false))
6700 if (errorMessage->
len == oldmsglen)
6702 "invalid URI query parameter: \"%s\"",
6743 const char *q =
str;
6758 if (!(*(p++) = *(q++)))
6776 "invalid percent-encoded token: \"%s\"",
6786 "forbidden value %%00 in percent-encoded value: \"%s\"",
6809 if (
'0' <= digit && digit <=
'9')
6810 *
value = digit -
'0';
6811 else if (
'A' <= digit && digit <=
'F')
6812 *
value = digit -
'A' + 10;
6813 else if (
'a' <= digit && digit <=
'f')
6814 *
value = digit -
'a' + 10;
6829 const char *keyword)
6855 const char *keyword,
const char *
value,
6867 if (strcmp(keyword,
"requiressl") == 0)
6869 keyword =
"sslmode";
6870 if (
value[0] ==
'1')
6881 "invalid connection option \"%s\"",
6889 if (value_copy == NULL)
6895 value_copy = strdup(
value);
6896 if (value_copy == NULL)
6924 if (strcmp(
option->keyword, keyword) == 0)
6954 if (connOptions != NULL)
6965 connmember = (
char **) ((
char *)
conn +
option->connofs);
6969 &errorBuf,
true,
false);
6982 if (connOptions == NULL)
7116 if (!
conn || !paramName)
7118 for (pstatus =
conn->
pstatus; pstatus != NULL; pstatus = pstatus->
next)
7120 if (strcmp(pstatus->
name, paramName) == 0)
7121 return pstatus->
value;
7246 static const char query[] =
"set client_encoding to '%s'";
7261 if (
sizeof(qbuf) < (
sizeof(query) + strlen(
encoding)))
7368 fprintf(stderr,
"%s", message);
7380 bool bslash =
false;
7386 if (tbuf[0] ==
'*' && tbuf[1] ==
':')
7390 if (*tbuf ==
'\\' && !bslash)
7395 if (*tbuf ==
':' && *ttok == 0 && !bslash)
7414 const char *
username,
const char *pgpassfile)
7417 struct stat stat_buf;
7438 if (
port == NULL ||
port[0] ==
'\0')
7439 port = DEF_PGPORT_STR;
7442 if (
stat(pgpassfile, &stat_buf) != 0)
7449 libpq_gettext(
"WARNING: password file \"%s\" is not a plain file\n"),
7458 libpq_gettext(
"WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
7470 fp = fopen(pgpassfile,
"r");
7477 while (!feof(fp) && !ferror(fp))
7484 if (fgets(
buf.data +
buf.len,
buf.maxlen -
buf.len, fp) == NULL)
7489 if (!(
buf.len > 0 &&
buf.data[
buf.len - 1] ==
'\n') && !feof(fp))
7493 if (
buf.data[0] !=
'#')
7525 for (p1 =
p2 = ret; *p1 !=
':' && *p1 !=
'\0'; ++p1, ++
p2)
7527 if (*p1 ==
'\\' && p1[1] !=
'\0')
7582 if (!version || strlen(version) == 0)
7608 if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
7660 home = getenv(
"HOME");
7661 if (home == NULL || home[0] ==
'\0')
7666 char tmppath[MAX_PATH];
7668 ZeroMemory(tmppath,
sizeof(tmppath));
7669 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7694 numval = strtol(
value, &end, 10);
7700 if (
value == end || errno != 0 || numval != (
int) numval)
7707 while (*end !=
'\0' && isspace((
unsigned char) *end))
int ssl_min_protocol_version
int ssl_max_protocol_version
static Datum values[MAXATTR]
static void cleanup(void)
#define Assert(condition)
#define MemSet(start, val, len)
static void PGresult const char * p2
static void PGresult * res
int errmsg(const char *fmt,...)
void err(int eval, const char *fmt,...)
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
char * pg_fe_getauthname(PQExpBuffer errorMessage)
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn)
static void pqFreeCommandQueue(PGcmdQueueEntry *queue)
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
int PQserverVersion(const PGconn *conn)
static const char * conninfo_getval(PQconninfoOption *connOptions, const char *keyword)
int PQprotocolVersion(const PGconn *conn)
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
void pqDropConnection(PGconn *conn, bool flushInput)
int PQresetStart(PGconn *conn)
static bool connectOptions1(PGconn *conn, const char *conninfo)
static const PQEnvironmentOption EnvironmentOptions[]
#define CONNECTION_FAILED()
bool pqConnectOptions2(PGconn *conn)
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
static void sendTerminateConn(PGconn *conn)
static int setKeepalivesCount(PGconn *conn)
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
static int useKeepalives(PGconn *conn)
static void defaultNoticeReceiver(void *arg, const PGresult *res)
static int uri_prefix_length(const char *connstr)
char * PQhost(const PGconn *conn)
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
static int parseServiceFile(const char *serviceFile, const char *service, PQconninfoOption *options, PQExpBuffer errorMessage, bool *group_found)
static void connectFailureMessage(PGconn *conn, int errorno)
static char * passwordFromFile(const char *hostname, const char *port, const char *dbname, const char *username, const char *pgpassfile)
static bool sslVerifyProtocolRange(const char *min, const char *max)
static void default_threadlock(int acquire)
PGconn * PQconnectStart(const char *conninfo)
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
char * PQdb(const PGconn *conn)
#define ENCRYPTION_NEGOTIATION_FAILED()
static void libpq_prng_init(PGconn *conn)
void PQreset(PGconn *conn)
void pqClosePGconn(PGconn *conn)
bool pqGetHomeDirectory(char *buf, int bufsize)
struct _internalPQconninfoOption internalPQconninfoOption
static const char short_uri_designator[]
static void release_conn_addrinfo(PGconn *conn)
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
static int count_comma_separated_elems(const char *input)
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
static bool select_next_encryption_method(PGconn *conn, bool have_valid_connection)
#define ERRCODE_APPNAME_UNKNOWN
static bool conninfo_uri_parse_params(char *params, PQconninfoOption *connOptions, PQExpBuffer errorMessage)
PQconninfoOption * PQconndefaults(void)
int PQconnectionUsedPassword(const PGconn *conn)
static char * conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
static int setKeepalivesInterval(PGconn *conn)
char * PQtty(const PGconn *conn)
char * PQhostaddr(const PGconn *conn)
static int setKeepalivesIdle(PGconn *conn)
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
void PQconninfoFree(PQconninfoOption *connOptions)
#define DefaultChannelBinding
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
static void defaultNoticeProcessor(void *arg, const char *message)
static void pgpassfileWarning(PGconn *conn)
static PGPing internal_ping(PGconn *conn)
static PQconninfoOption * conninfo_find(PQconninfoOption *connOptions, const char *keyword)
static const char uri_designator[]
static bool sslVerifyProtocolVersion(const char *version)
PQconninfoOption * PQconninfo(PGconn *conn)
#define SELECT_NEXT_METHOD(method)
int PQconnectionNeedsPassword(const PGconn *conn)
PostgresPollingStatusType PQresetPoll(PGconn *conn)
int PQconnectionUsedGSSAPI(const PGconn *conn)
static PQconninfoOption * conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage, bool use_defaults)
void pqReleaseConnHosts(PGconn *conn)
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
char * PQerrorMessage(const PGconn *conn)
static bool connection_failed(PGconn *conn)
pgthreadlock_t pg_g_threadlock
ConnStatusType PQstatus(const PGconn *conn)
static char * parse_comma_separated_list(char **startptr, bool *more)
static int setTCPUserTimeout(PGconn *conn)
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
int PQclientEncoding(const PGconn *conn)
PGconn * pqMakeEmptyPGconn(void)
static PQconninfoOption * conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, bool use_defaults)
PGconn * PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
void PQfinish(PGconn *conn)
static void pqDropServerData(PGconn *conn)
PGPing PQping(const char *conninfo)
PGconn * PQconnectdb(const char *conninfo)
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
#define DefaultLoadBalanceHosts
char * PQuser(const PGconn *conn)
static int connectNoDelay(PGconn *conn)
char * PQpass(const PGconn *conn)
#define DefaultSSLNegotiation
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
int PQbackendPID(const PGconn *conn)
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
static bool conninfo_uri_parse_options(PQconninfoOption *options, const char *uri, PQExpBuffer errorMessage)
int pqConnectDBStart(PGconn *conn)
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
static void freePGconn(PGconn *conn)
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
static char * pwdfMatchesString(char *buf, const char *token)
char * PQport(const PGconn *conn)
PGpipelineStatus PQpipelineStatus(const PGconn *conn)
static bool get_hexdigit(char digit, int *value)
#define ERRCODE_INVALID_PASSWORD
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
#define DefaultSSLCertMode
#define ERRCODE_CANNOT_CONNECT_NOW
static const internalPQconninfoOption PQconninfoOptions[]
static bool recognized_connection_string(const char *connstr)
#define DefaultTargetSessionAttrs
static int parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
static bool init_allowed_encryption_methods(PGconn *conn)
PGPing PQpingParams(const char *const *keywords, const char *const *values, int expand_dbname)
int PQsocket(const PGconn *conn)
char * PQoptions(const PGconn *conn)
int pqConnectDBComplete(PGconn *conn)
int PQsetClientEncoding(PGconn *conn, const char *encoding)
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
pgthreadlock_t PQregisterThreadLock(pgthreadlock_t newhandler)
int PQsendQueryContinue(PGconn *conn, const char *query)
ExecStatusType PQresultStatus(const PGresult *res)
char * PQresultErrorMessage(const PGresult *res)
int PQntuples(const PGresult *res)
PGresult * PQexec(PGconn *conn, const char *query)
int PQconsumeInput(PGconn *conn)
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
void pqClearAsyncResult(PGconn *conn)
int PQisBusy(PGconn *conn)
char * PQresultErrorField(const PGresult *res, int fieldcode)
PGresult * PQgetResult(PGconn *conn)
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadData(PGconn *conn)
int pqFlush(PGconn *conn)
int pqPutMsgStart(char msg_type, PGconn *conn)
int pqGetc(char *result, PGconn *conn)
int pqGetInt(int *result, size_t bytes, PGconn *conn)
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
int pqPutnchar(const char *s, size_t len, PGconn *conn)
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
int pqGets_append(PQExpBuffer buf, PGconn *conn)
int pqPutMsgEnd(PGconn *conn)
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
void pqsecure_close(PGconn *conn)
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
@ CONNECTION_CHECK_STANDBY
@ CONNECTION_AWAITING_RESPONSE
@ CONNECTION_CHECK_WRITABLE
@ CONNECTION_CHECK_TARGET
void(* pgthreadlock_t)(int acquire)
void(* PQnoticeReceiver)(void *arg, const PGresult *res)
void(* PQnoticeProcessor)(void *arg, const char *message)
PostgresPollingStatusType
#define ENC_NEGOTIATED_SSL
#define pqClearConnErrorState(conn)
@ SERVER_TYPE_PREFER_STANDBY_PASS2
@ SERVER_TYPE_PREFER_STANDBY
bool pg_link_canary_is_frontend(void)
#define DEFAULT_PGSOCKET_DIR
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
void pg_prng_seed(pg_prng_state *state, uint64 seed)
#define pg_prng_strong_seed(state)
#define pg_encoding_to_char
#define PG_STRERROR_R_BUFLEN
int pg_strcasecmp(const char *s1, const char *s2)
bool pg_set_noblock(pgsocket sock)
bool pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
void explicit_bzero(void *buf, size_t len)
char * pg_inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size)
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
size_t strlcpy(char *dst, const char *src, size_t siz)
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
int getpeereid(int sock, uid_t *uid, gid_t *gid)
#define PG_PROTOCOL_MAJOR(v)
static bool is_unixsock_path(const char *path)
#define CANCEL_REQUEST_CODE
#define UNIXSOCK_PATH(path, port, sockdir)
#define UNIXSOCK_PATH_BUFLEN
#define NEGOTIATE_GSS_CODE
#define NEGOTIATE_SSL_CODE
#define PG_PROTOCOL(m, n)
void initPQExpBuffer(PQExpBuffer str)
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
void termPQExpBuffer(PQExpBuffer str)
#define PQExpBufferBroken(str)
#define PQExpBufferDataBroken(buf)
#define AUTH_REQ_SASL_CONT
#define PqMsg_AuthenticationRequest
#define PqMsg_NegotiateProtocolVersion
#define AUTH_REQ_PASSWORD
#define AUTH_REQ_GSS_CONT
#define PqMsg_ErrorResponse
#define AUTH_REQ_SASL_FIN
int pthread_mutex_unlock(pthread_mutex_t *mp)
int pthread_mutex_lock(pthread_mutex_t *mp)
#define PTHREAD_MUTEX_INITIALIZER
#define SCRAM_SHA_256_DEFAULT_ITERATIONS
static pg_noinline void Size size
const char * gai_strerror(int ecode)
int pg_strip_crlf(char *str)
MsgType cancelRequestCode
PQnoticeReceiver noticeRec
PQnoticeProcessor noticeProc
struct sockaddr_storage addr
struct pgParameterStatus * next
PGTransactionStatusType xactStatus
const pg_fe_sasl_mech * sasl
char * ssl_max_protocol_version
PGTernaryBool in_hot_standby
bool client_finished_auth
PGcmdQueueEntry * cmd_queue_recycle
uint32 allowed_auth_methods
char * target_session_attrs
PGcmdQueueEntry * cmd_queue_tail
PQExpBufferData workBuffer
char * load_balance_hosts
PGTernaryBool default_transaction_read_only
pgParameterStatus * pstatus
char * client_encoding_initial
char * keepalives_interval
char * pgtcp_user_timeout
char * ssl_min_protocol_version
PQExpBufferData errorMessage
PGAsyncStatusType asyncStatus
PGLoadBalanceType load_balance_type
int scram_sha_256_iterations
PGpipelineStatus pipelineStatus
uint8 allowed_enc_methods
PGNoticeHooks noticeHooks
PGTargetServerType target_server_type
PGcmdQueueEntry * cmd_queue_head
bool ssl_handshake_started
PGContextVisibility show_context
void(* free)(void *state)
PGNoticeHooks noticeHooks
ExecStatusType resultStatus
#define socket(af, type, protocol)
#define connect(s, name, namelen)
int gettimeofday(struct timeval *tp, void *tzp)