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"
134 #define DefaultGSSMode "prefer"
136 #define DefaultGSSMode "disable"
190 {
"service",
"PGSERVICE", NULL, NULL,
191 "Database-Service",
"", 20, -1},
193 {
"user",
"PGUSER", NULL, NULL,
194 "Database-User",
"", 20,
195 offsetof(
struct pg_conn, pguser)},
197 {
"password",
"PGPASSWORD", NULL, NULL,
198 "Database-Password",
"*", 20,
199 offsetof(
struct pg_conn, pgpass)},
201 {
"passfile",
"PGPASSFILE", NULL, NULL,
202 "Database-Password-File",
"", 64,
203 offsetof(
struct pg_conn, pgpassfile)},
206 "Channel-Binding",
"", 8,
207 offsetof(
struct pg_conn, channel_binding)},
209 {
"connect_timeout",
"PGCONNECT_TIMEOUT", NULL, NULL,
210 "Connect-timeout",
"", 10,
211 offsetof(
struct pg_conn, connect_timeout)},
213 {
"dbname",
"PGDATABASE", NULL, NULL,
214 "Database-Name",
"", 20,
217 {
"host",
"PGHOST", NULL, NULL,
218 "Database-Host",
"", 40,
221 {
"hostaddr",
"PGHOSTADDR", NULL, NULL,
222 "Database-Host-IP-Address",
"", 45,
223 offsetof(
struct pg_conn, pghostaddr)},
225 {
"port",
"PGPORT", DEF_PGPORT_STR, NULL,
226 "Database-Port",
"", 6,
229 {
"client_encoding",
"PGCLIENTENCODING", NULL, NULL,
230 "Client-Encoding",
"", 10,
231 offsetof(
struct pg_conn, client_encoding_initial)},
234 "Backend-Options",
"", 40,
235 offsetof(
struct pg_conn, pgoptions)},
237 {
"application_name",
"PGAPPNAME", NULL, NULL,
238 "Application-Name",
"", 64,
239 offsetof(
struct pg_conn, appname)},
241 {
"fallback_application_name", NULL, NULL, NULL,
242 "Fallback-Application-Name",
"", 64,
243 offsetof(
struct pg_conn, fbappname)},
245 {
"keepalives", NULL, NULL, NULL,
246 "TCP-Keepalives",
"", 1,
247 offsetof(
struct pg_conn, keepalives)},
249 {
"keepalives_idle", NULL, NULL, NULL,
250 "TCP-Keepalives-Idle",
"", 10,
251 offsetof(
struct pg_conn, keepalives_idle)},
253 {
"keepalives_interval", NULL, NULL, NULL,
254 "TCP-Keepalives-Interval",
"", 10,
255 offsetof(
struct pg_conn, keepalives_interval)},
257 {
"keepalives_count", NULL, NULL, NULL,
258 "TCP-Keepalives-Count",
"", 10,
259 offsetof(
struct pg_conn, keepalives_count)},
261 {
"tcp_user_timeout", NULL, NULL, NULL,
262 "TCP-User-Timeout",
"", 10,
263 offsetof(
struct pg_conn, pgtcp_user_timeout)},
273 offsetof(
struct pg_conn, sslmode)},
275 {
"sslcompression",
"PGSSLCOMPRESSION",
"0", NULL,
276 "SSL-Compression",
"", 1,
277 offsetof(
struct pg_conn, sslcompression)},
279 {
"sslcert",
"PGSSLCERT", NULL, NULL,
280 "SSL-Client-Cert",
"", 64,
281 offsetof(
struct pg_conn, sslcert)},
283 {
"sslkey",
"PGSSLKEY", NULL, NULL,
284 "SSL-Client-Key",
"", 64,
285 offsetof(
struct pg_conn, sslkey)},
287 {
"sslcertmode",
"PGSSLCERTMODE", NULL, NULL,
288 "SSL-Client-Cert-Mode",
"", 8,
289 offsetof(
struct pg_conn, sslcertmode)},
291 {
"sslpassword", NULL, NULL, NULL,
292 "SSL-Client-Key-Password",
"*", 20,
293 offsetof(
struct pg_conn, sslpassword)},
295 {
"sslrootcert",
"PGSSLROOTCERT", NULL, NULL,
296 "SSL-Root-Certificate",
"", 64,
297 offsetof(
struct pg_conn, sslrootcert)},
299 {
"sslcrl",
"PGSSLCRL", NULL, NULL,
300 "SSL-Revocation-List",
"", 64,
301 offsetof(
struct pg_conn, sslcrl)},
303 {
"sslcrldir",
"PGSSLCRLDIR", NULL, NULL,
304 "SSL-Revocation-List-Dir",
"", 64,
305 offsetof(
struct pg_conn, sslcrldir)},
307 {
"sslsni",
"PGSSLSNI",
"1", NULL,
309 offsetof(
struct pg_conn, sslsni)},
311 {
"requirepeer",
"PGREQUIREPEER", NULL, NULL,
312 "Require-Peer",
"", 10,
313 offsetof(
struct pg_conn, requirepeer)},
315 {
"require_auth",
"PGREQUIREAUTH", NULL, NULL,
316 "Require-Auth",
"", 14,
317 offsetof(
struct pg_conn, require_auth)},
319 {
"ssl_min_protocol_version",
"PGSSLMINPROTOCOLVERSION",
"TLSv1.2", NULL,
320 "SSL-Minimum-Protocol-Version",
"", 8,
323 {
"ssl_max_protocol_version",
"PGSSLMAXPROTOCOLVERSION", NULL, NULL,
324 "SSL-Maximum-Protocol-Version",
"", 8,
332 "GSSENC-Mode",
"", 8,
333 offsetof(
struct pg_conn, gssencmode)},
336 {
"krbsrvname",
"PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
337 "Kerberos-service-name",
"", 20,
338 offsetof(
struct pg_conn, krbsrvname)},
340 {
"gsslib",
"PGGSSLIB", NULL, NULL,
341 "GSS-library",
"", 7,
342 offsetof(
struct pg_conn, gsslib)},
344 {
"gssdelegation",
"PGGSSDELEGATION",
"0", NULL,
345 "GSS-delegation",
"", 1,
346 offsetof(
struct pg_conn, gssdelegation)},
348 {
"replication", NULL, NULL, NULL,
349 "Replication",
"D", 5,
350 offsetof(
struct pg_conn, replication)},
352 {
"target_session_attrs",
"PGTARGETSESSIONATTRS",
354 "Target-Session-Attrs",
"", 15,
355 offsetof(
struct pg_conn, target_session_attrs)},
357 {
"load_balance_hosts",
"PGLOADBALANCEHOSTS",
359 "Load-Balance-Hosts",
"", 8,
360 offsetof(
struct pg_conn, load_balance_hosts)},
363 {NULL, NULL, NULL, NULL,
371 "PGDATESTYLE",
"datestyle"
406 bool use_defaults,
int expand_dbname);
419 const char *keyword);
421 const char *keyword,
const char *
value,
422 PQExpBuffer errorMessage,
bool ignoreMissing,
bool uri_decode);
424 const char *keyword);
436 const char *
username,
const char *pgpassfile);
488 if (
conn->gcred != GSS_C_NO_CREDENTIAL)
490 gss_release_cred(&min_s, &
conn->gcred);
491 conn->gcred = GSS_C_NO_CREDENTIAL;
494 gss_delete_sec_context(&min_s, &
conn->gctx, GSS_C_NO_BUFFER);
496 gss_release_name(&min_s, &
conn->gtarg_nam);
497 if (
conn->gss_SendBuffer)
500 conn->gss_SendBuffer = NULL;
502 if (
conn->gss_RecvBuffer)
505 conn->gss_RecvBuffer = NULL;
507 if (
conn->gss_ResultBuffer)
510 conn->gss_ResultBuffer = NULL;
512 conn->gssenc =
false;
516 if (
conn->sspitarget)
519 conn->sspitarget = NULL;
523 FreeCredentialsHandle(
conn->sspicred);
525 conn->sspicred = NULL;
529 DeleteSecurityContext(
conn->sspictx);
531 conn->sspictx = NULL;
549 while (queue != NULL)
580 while (notify != NULL)
584 notify = notify->
next;
591 while (pstatus != NULL)
595 pstatus = pstatus->
next;
679 const char *
const *
values,
697 const char *
const *
values,
781 const char *
const *
values,
801 true, expand_dbname);
802 if (connOptions == NULL)
919 char **connmember = (
char **) ((
char *)
conn +
option->connofs);
922 *connmember = strdup(tmp);
923 if (*connmember == NULL)
954 const char **tmp = (
const char **) ((
char *) srcConn +
option->connofs);
958 char **dstConnmember = (
char **) ((
char *) dstConn +
option->connofs);
961 free(*dstConnmember);
962 *dstConnmember = strdup(*tmp);
963 if (*dstConnmember == NULL)
994 if (connOptions == NULL)
1050 char *s = *startptr;
1059 while (*
e !=
'\0' && *
e !=
',')
1061 *more = (*
e ==
',');
1064 p = (
char *)
malloc(
sizeof(
char) * (
len + 1));
1085 struct timeval tval = {0};
1092 rseed = ((uintptr_t)
conn) ^
1093 ((uint64) getpid()) ^
1094 ((uint64) tval.tv_usec) ^
1095 ((uint64) tval.tv_sec);
1187 else if (ch->
host != NULL && ch->
host[0] !=
'\0')
1211 if (ch->
host == NULL)
1239 if (
i == 1 && !more)
1317 if (pwhost == NULL || pwhost[0] ==
'\0')
1338 bool negated =
false;
1347 for (first =
true, more =
true; more; first =
false)
1396 if (strcmp(method,
"password") == 0)
1400 else if (strcmp(method,
"md5") == 0)
1404 else if (strcmp(method,
"gss") == 0)
1409 else if (strcmp(method,
"sspi") == 0)
1414 else if (strcmp(method,
"scram-sha-256") == 0)
1421 else if (strcmp(method,
"none") == 0)
1450 "require_auth", method);
1599 "ssl_min_protocol_version",
1607 "ssl_max_protocol_version",
1650 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1724 "target_session_attrs",
1745 "load_balance_hosts",
1830 if (connOptions != NULL)
1858 const char *pgtty,
const char *
dbName,
const char *login,
1920 if (pgoptions && pgoptions[0] !=
'\0')
1928 if (login && login[0] !=
'\0')
1936 if (pwd && pwd[0] !=
'\0')
1977 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_NODELAY,
2002 if (addr->ss_family == AF_INET)
2005 &((
struct sockaddr_in *) addr)->sin_addr.s_addr,
2007 host_addr, host_addr_len) == NULL)
2008 host_addr[0] =
'\0';
2010 else if (addr->ss_family == AF_INET6)
2013 &((
struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2015 host_addr, host_addr_len) == NULL)
2016 host_addr[0] =
'\0';
2019 host_addr[0] =
'\0';
2035 char service[NI_MAXHOST];
2039 service,
sizeof(service),
2042 libpq_gettext(
"connection to server on socket \"%s\" failed: "),
2047 const char *displayed_host;
2048 const char *displayed_port;
2056 if (displayed_port == NULL || displayed_port[0] ==
'\0')
2057 displayed_port = DEF_PGPORT_STR;
2066 strcmp(displayed_host, host_addr) != 0)
2068 libpq_gettext(
"connection to server at \"%s\" (%s), port %s failed: "),
2069 displayed_host, host_addr,
2073 libpq_gettext(
"connection to server at \"%s\", port %s failed: "),
2117 return val != 0 ? 1 : 0;
2138 #ifdef PG_TCP_KEEPALIVE_IDLE
2139 if (setsockopt(
conn->
sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2140 (
char *) &idle,
sizeof(idle)) < 0)
2146 PG_TCP_KEEPALIVE_IDLE_STR,
2167 "keepalives_interval"))
2172 #ifdef TCP_KEEPINTVL
2173 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPINTVL,
2202 "keepalives_count"))
2208 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPCNT,
2209 (
char *) &count,
sizeof(count)) < 0)
2224 #ifdef SIO_KEEPALIVE_VALS
2234 struct tcp_keepalive ka;
2243 ka.keepalivetime = idle * 1000;
2244 ka.keepaliveinterval =
interval * 1000;
2272 "keepalives_interval"))
2278 "WSAIoctl",
"SIO_KEEPALIVE_VALS",
2299 "tcp_user_timeout"))
2305 #ifdef TCP_USER_TIMEOUT
2306 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2307 (
char *) &timeout,
sizeof(timeout)) < 0)
2336 goto connect_errReturn;
2347 "libpq is incorrectly linked to backend functions\n");
2348 goto connect_errReturn;
2411 time_t finish_time = ((time_t) -1);
2413 int last_whichhost = -2;
2414 int last_whichaddr = -2;
2460 finish_time = time(NULL) + timeout;
2549 bool reset_connection_state_machine =
false;
2550 bool need_new_connection =
false;
2615 reset_connection_state_machine =
true;
2626 struct addrinfo hint;
2627 struct addrinfo *addrlist;
2670 MemSet(&hint, 0,
sizeof(hint));
2671 hint.ai_socktype = SOCK_STREAM;
2672 hint.ai_family = AF_UNSPEC;
2675 if (ch->
port == NULL || ch->
port[0] ==
'\0')
2676 thisport = DEF_PGPORT;
2682 if (thisport < 1 || thisport > 65535)
2696 if (ret || !addrlist)
2705 hint.ai_flags = AI_NUMERICHOST;
2708 if (ret || !addrlist)
2717 hint.ai_family = AF_UNIX;
2733 if (ret || !addrlist)
2777 reset_connection_state_machine =
true;
2782 if (reset_connection_state_machine)
2801 reset_connection_state_machine =
false;
2802 need_new_connection =
true;
2806 if (need_new_connection)
2823 need_new_connection =
false;
2840 char host_addr[NI_MAXHOST];
2872 sock_type = SOCK_STREAM;
2881 sock_type |= SOCK_CLOEXEC;
2883 #ifdef SOCK_NONBLOCK
2889 sock_type |= SOCK_NONBLOCK;
2928 if (addr_cur->
family != AF_UNIX)
2937 #ifndef SOCK_NONBLOCK
2947 #ifndef SOCK_CLOEXEC
2949 if (fcntl(
conn->
sock, F_SETFD, FD_CLOEXEC) == -1)
2959 if (addr_cur->
family != AF_UNIX)
2967 if (usekeepalives < 0)
2972 else if (usekeepalives == 0)
2978 SOL_SOCKET, SO_KEEPALIVE,
2979 (
char *) &on,
sizeof(on)) < 0)
2992 #ifdef SIO_KEEPALIVE_VALS
2993 else if (!prepKeepalivesWin32(
conn))
3039 if (setsockopt(
conn->
sock, SOL_SOCKET, SO_NOSIGPIPE,
3040 (
char *) &optval,
sizeof(optval)) == 0)
3105 if (getsockopt(
conn->
sock, SOL_SOCKET, SO_ERROR,
3106 (
char *) &optval, &optlen) == -1)
3112 else if (optval != 0)
3160 char *remote_username;
3172 if (errno == ENOSYS)
3183 if (remote_username == NULL)
3190 free(remote_username);
3193 free(remote_username);
3204 conn->allow_ssl_try =
false;
3207 conn->try_gss =
false;
3241 "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
3263 if (
conn->allow_ssl_try && !
conn->wait_ssl_try &&
3301 packetlen =
sizeof(cancelpacket);
3399 else if (SSLok ==
'N')
3413 conn->allow_ssl_try =
false;
3418 else if (SSLok ==
'E')
3470 &&
conn->allow_ssl_try
3471 && !
conn->wait_ssl_try)
3474 conn->allow_ssl_try =
false;
3475 need_new_connection =
true;
3506 else if (rdresult == 0)
3522 conn->try_gss =
false;
3523 need_new_connection =
true;
3539 conn->try_gss =
false;
3544 else if (gss_ok !=
'G')
3580 conn->try_gss =
false;
3581 need_new_connection =
true;
3657 (msgLength < 8 || msgLength > 2000))
3663 (msgLength < 8 || msgLength > 2000))
3669 #define MAX_ERRLEN 30000
3719 if (avail < msgLength)
3770 conn->try_gss =
false;
3771 need_new_connection =
true;
3784 &&
conn->allow_ssl_try
3785 &&
conn->wait_ssl_try)
3788 conn->wait_ssl_try =
false;
3789 need_new_connection =
true;
3799 &&
conn->allow_ssl_try
3800 && !
conn->wait_ssl_try)
3803 conn->allow_ssl_try =
false;
3804 need_new_connection =
true;
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",
4340 static bool wsastartup_done =
false;
4342 if (!wsastartup_done)
4346 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4348 wsastartup_done =
true;
4538 struct addrinfo *ai = addrlist;
4778 const void *
buf,
size_t buf_len)
4801 #define LDAP_URL "ldap://"
4802 #define LDAP_DEF_PORT 389
4803 #define PGLDAP_TIMEOUT 2
4805 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4806 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4832 int port = LDAP_DEF_PORT,
4855 char *attrs[2] = {NULL, NULL};
4860 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4862 if ((url = strdup(purl)) == NULL)
4877 "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
4888 p = strchr(url + strlen(LDAP_URL),
'/');
4889 if (p == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
4892 "invalid LDAP URL \"%s\": missing distinguished name",
4901 if ((p = strchr(dn,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
4904 "invalid LDAP URL \"%s\": must have exactly one attribute",
4913 if ((p = strchr(attrs[0],
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
4916 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
4925 if ((p = strchr(scopestr,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
4928 "invalid LDAP URL \"%s\": no filter",
4935 if ((p = strchr(filter,
'?')) != NULL)
4939 if ((p1 = strchr(
hostname,
':')) != NULL)
4946 lport = strtol(
portstr, &endptr, 10);
4947 if (*
portstr ==
'\0' || *endptr !=
'\0' || errno || lport < 0 || lport > 65535)
4950 "invalid LDAP URL \"%s\": invalid port number",
4959 if (strchr(attrs[0],
',') != NULL)
4962 "invalid LDAP URL \"%s\": must have exactly one attribute",
4970 scope = LDAP_SCOPE_BASE;
4972 scope = LDAP_SCOPE_ONELEVEL;
4974 scope = LDAP_SCOPE_SUBTREE;
4978 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5006 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
5015 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5023 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
5033 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &
res)) == -1 ||
5047 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5057 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &
res))
5062 libpq_append_error(errorMessage,
"lookup on LDAP server failed: %s", ldap_err2string(rc));
5069 if ((rc = ldap_count_entries(ld,
res)) != 1)
5082 if ((entry = ldap_first_entry(ld,
res)) == NULL)
5093 if ((
values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
5108 ldap_value_free_len(
values);
5120 ldap_value_free_len(
values);
5133 ldap_value_free_len(
values);
5137 oldstate =
state = 0;
5138 for (p = result; *p !=
'\0'; ++p)
5143 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5150 if (ld_is_sp_tab(*p))
5155 else if (ld_is_nl_cr(*p))
5158 "missing \"=\" after \"%s\" in connection info string",
5174 else if (!ld_is_sp_tab(*p))
5177 "missing \"=\" after \"%s\" in connection info string",
5190 else if (ld_is_nl_cr(*p))
5192 optval = optname + strlen(optname);
5195 else if (!ld_is_sp_tab(*p))
5202 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
5214 else if (*p ==
'\\')
5225 if (
state == 0 && oldstate != 0)
5227 found_keyword =
false;
5230 if (strcmp(
options[
i].keyword, optname) == 0)
5242 found_keyword =
true;
5263 "unterminated quoted string in connection info string");
5288 bool group_found =
false;
5290 struct stat stat_buf;
5297 if (service == NULL)
5298 service = getenv(
"PGSERVICE");
5301 if (service == NULL)
5308 if ((env = getenv(
"PGSERVICEFILE")) != NULL)
5309 strlcpy(serviceFile, env,
sizeof(serviceFile));
5317 if (
stat(serviceFile, &stat_buf) != 0)
5322 if (group_found || status != 0)
5332 getenv(
"PGSYSCONFDIR") ? getenv(
"PGSYSCONFDIR") : SYSCONFDIR);
5333 if (
stat(serviceFile, &stat_buf) != 0)
5352 const char *service,
5364 *group_found =
false;
5366 f = fopen(serviceFile,
"r");
5373 while ((line = fgets(
buf,
sizeof(
buf), f)) != NULL)
5379 if (strlen(line) >=
sizeof(
buf) - 1)
5382 "line %d too long in service file \"%s\"",
5391 while (
len > 0 && isspace((
unsigned char) line[
len - 1]))
5395 while (*line && isspace((
unsigned char) line[0]))
5399 if (line[0] ==
'\0' || line[0] ==
'#')
5411 if (strncmp(line + 1, service, strlen(service)) == 0 &&
5412 line[strlen(service) + 1] ==
']')
5413 *group_found =
true;
5415 *group_found =
false;
5429 if (strncmp(line,
"ldap", 4) == 0)
5431 int rc = ldapServiceLookup(line,
options, errorMessage);
5449 val = strchr(line,
'=');
5453 "syntax error in service file \"%s\", line %d",
5461 if (strcmp(
key,
"service") == 0)
5464 "nested service specifications not supported in service file \"%s\", line %d",
5475 found_keyword =
false;
5488 found_keyword =
true;
5496 "syntax error in service file \"%s\", line %d",
5540 if (connOptions == NULL &&
errmsg)
5660 if ((
buf = strdup(conninfo)) == NULL)
5671 if (isspace((
unsigned char) *cp))
5683 if (isspace((
unsigned char) *cp))
5688 if (!isspace((
unsigned char) *cp))
5701 "missing \"=\" after \"%s\" in connection info string",
5712 if (!isspace((
unsigned char) *cp))
5725 if (isspace((
unsigned char) *cp))
5749 libpq_append_error(errorMessage,
"unterminated quoted string in connection info string");
5833 while (expand_dbname && keywords[
i])
5835 const char *pname = keywords[
i];
5836 const char *pvalue =
values[
i];
5839 if (strcmp(pname,
"dbname") == 0 && pvalue)
5849 if (dbname_options == NULL)
5869 const char *pname = keywords[
i];
5870 const char *pvalue =
values[
i];
5872 if (pvalue != NULL && pvalue[0] !=
'\0')
5877 if (strcmp(
option->keyword, pname) == 0)
5882 if (
option->keyword == NULL)
5895 if (strcmp(pname,
"dbname") == 0 && dbname_options)
5899 for (str_option = dbname_options; str_option->
keyword != NULL; str_option++)
5901 if (str_option->
val != NULL)
5905 for (k = 0;
options[k].keyword; k++)
5929 dbname_options = NULL;
5982 *sslrootcert = NULL;
5999 if (strcmp(
option->keyword,
"sslrootcert") == 0)
6008 if (
option->envvar != NULL)
6010 if ((tmp = getenv(
option->envvar)) != NULL)
6029 if (strcmp(
option->keyword,
"sslmode") == 0)
6031 const char *requiresslenv = getenv(
"PGREQUIRESSL");
6033 if (requiresslenv != NULL && requiresslenv[0] ==
'1')
6050 sslmode_default =
option;
6057 if (
option->compiled != NULL)
6076 if (strcmp(
option->keyword,
"user") == 0)
6088 if (sslmode_default && sslrootcert)
6090 if (sslrootcert->val && strcmp(sslrootcert->val,
"system") == 0)
6094 sslmode_default->
val = strdup(
"verify-full");
6095 if (!sslmode_default->
val)
6173 char prevchar =
'\0';
6176 bool retval =
false;
6199 if (prefix_len == 0)
6203 "invalid URI propagated to internal parser routine: \"%s\"",
6207 start += prefix_len;
6211 while (*p && *p !=
'@' && *p !=
'/')
6222 while (*p !=
':' && *p !=
'@')
6231 errorMessage,
false,
true))
6234 if (prevchar ==
':')
6244 errorMessage,
false,
true))
6275 while (*p && *p !=
']')
6280 "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6287 "IPv6 host address may not be empty in URI: \"%s\"",
6299 if (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6302 "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6303 *p, (
int) (p -
buf + 1), uri);
6316 while (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6326 if (prevchar ==
':')
6328 const char *
port = ++p;
6330 while (*p && *p !=
'/' && *p !=
'?' && *p !=
',')
6339 if (prevchar !=
',')
6349 if (hostbuf.
data[0] &&
6351 errorMessage,
false,
true))
6353 if (portbuf.
data[0] &&
6355 errorMessage,
false,
true))
6358 if (prevchar && prevchar !=
'?')
6360 const char *
dbname = ++p;
6363 while (*p && *p !=
'?')
6376 errorMessage,
false,
true))
6413 char *keyword = params;
6416 bool malloced =
false;
6431 "extra key/value separator \"=\" in URI query parameter: \"%s\"",
6439 else if (*p ==
'&' || *p ==
'\0')
6451 "missing key/value separator \"=\" in URI query parameter: \"%s\"",
6463 if (keyword == NULL)
6480 if (strcmp(keyword,
"ssl") == 0 &&
6481 strcmp(
value,
"true") == 0)
6487 keyword =
"sslmode";
6496 oldmsglen = errorMessage->
len;
6498 errorMessage,
true,
false))
6501 if (errorMessage->
len == oldmsglen)
6503 "invalid URI query parameter: \"%s\"",
6544 const char *q =
str;
6559 if (!(*(p++) = *(q++)))
6577 "invalid percent-encoded token: \"%s\"",
6587 "forbidden value %%00 in percent-encoded value: \"%s\"",
6610 if (
'0' <= digit && digit <=
'9')
6611 *
value = digit -
'0';
6612 else if (
'A' <= digit && digit <=
'F')
6613 *
value = digit -
'A' + 10;
6614 else if (
'a' <= digit && digit <=
'f')
6615 *
value = digit -
'a' + 10;
6630 const char *keyword)
6656 const char *keyword,
const char *
value,
6668 if (strcmp(keyword,
"requiressl") == 0)
6670 keyword =
"sslmode";
6671 if (
value[0] ==
'1')
6682 "invalid connection option \"%s\"",
6690 if (value_copy == NULL)
6696 value_copy = strdup(
value);
6697 if (value_copy == NULL)
6725 if (strcmp(
option->keyword, keyword) == 0)
6755 if (connOptions != NULL)
6766 connmember = (
char **) ((
char *)
conn +
option->connofs);
6770 &errorBuf,
true,
false);
6783 if (connOptions == NULL)
6917 if (!
conn || !paramName)
6919 for (pstatus =
conn->
pstatus; pstatus != NULL; pstatus = pstatus->
next)
6921 if (strcmp(pstatus->
name, paramName) == 0)
6922 return pstatus->
value;
7047 static const char query[] =
"set client_encoding to '%s'";
7062 if (
sizeof(qbuf) < (
sizeof(query) + strlen(
encoding)))
7169 fprintf(stderr,
"%s", message);
7181 bool bslash =
false;
7187 if (tbuf[0] ==
'*' && tbuf[1] ==
':')
7191 if (*tbuf ==
'\\' && !bslash)
7196 if (*tbuf ==
':' && *ttok == 0 && !bslash)
7215 const char *
username,
const char *pgpassfile)
7218 struct stat stat_buf;
7239 if (
port == NULL ||
port[0] ==
'\0')
7240 port = DEF_PGPORT_STR;
7243 if (
stat(pgpassfile, &stat_buf) != 0)
7250 libpq_gettext(
"WARNING: password file \"%s\" is not a plain file\n"),
7259 libpq_gettext(
"WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
7271 fp = fopen(pgpassfile,
"r");
7278 while (!feof(fp) && !ferror(fp))
7285 if (fgets(
buf.data +
buf.len,
buf.maxlen -
buf.len, fp) == NULL)
7290 if (!(
buf.len > 0 &&
buf.data[
buf.len - 1] ==
'\n') && !feof(fp))
7294 if (
buf.data[0] !=
'#')
7326 for (p1 =
p2 = ret; *p1 !=
':' && *p1 !=
'\0'; ++p1, ++
p2)
7328 if (*p1 ==
'\\' && p1[1] !=
'\0')
7383 if (!version || strlen(version) == 0)
7409 if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
7461 home = getenv(
"HOME");
7462 if (home == NULL || home[0] ==
'\0')
7467 char tmppath[MAX_PATH];
7469 ZeroMemory(tmppath,
sizeof(tmppath));
7470 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7484 const char *context)
7495 numval = strtol(
value, &end, 10);
7501 if (
value == end || errno != 0 || numval != (
int) numval)
7508 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 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[]
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)
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)
#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)
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)
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)
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)
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 pqClearConnErrorState(conn)
@ SERVER_TYPE_PREFER_STANDBY_PASS2
@ SERVER_TYPE_PREFER_STANDBY
Assert(fmt[strlen(fmt) - 1] !='\n')
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
PGNoticeHooks noticeHooks
PGTargetServerType target_server_type
PGcmdQueueEntry * cmd_queue_head
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)