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",
"", 9,
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);
1625 libpq_append_conn_error(
conn,
"weak sslmode \"%s\" may not be used with sslnegotiation=direct (use \"require\", \"verify-ca\", or \"verify-full\")",
1661 "ssl_min_protocol_version",
1669 "ssl_max_protocol_version",
1712 #ifndef HAVE_SSL_CTX_SET_CERT_CB
1786 "target_session_attrs",
1807 "load_balance_hosts",
1892 if (connOptions != NULL)
1920 const char *pgtty,
const char *
dbName,
const char *login,
1982 if (pgoptions && pgoptions[0] !=
'\0')
1990 if (login && login[0] !=
'\0')
1998 if (pwd && pwd[0] !=
'\0')
2039 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_NODELAY,
2064 if (addr->ss_family == AF_INET)
2067 &((
struct sockaddr_in *) addr)->sin_addr.s_addr,
2069 host_addr, host_addr_len) == NULL)
2070 host_addr[0] =
'\0';
2072 else if (addr->ss_family == AF_INET6)
2075 &((
struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
2077 host_addr, host_addr_len) == NULL)
2078 host_addr[0] =
'\0';
2081 host_addr[0] =
'\0';
2097 char service[NI_MAXHOST];
2101 service,
sizeof(service),
2104 libpq_gettext(
"connection to server on socket \"%s\" failed: "),
2109 const char *displayed_host;
2110 const char *displayed_port;
2118 if (displayed_port == NULL || displayed_port[0] ==
'\0')
2119 displayed_port = DEF_PGPORT_STR;
2128 strcmp(displayed_host, host_addr) != 0)
2130 libpq_gettext(
"connection to server at \"%s\" (%s), port %s failed: "),
2131 displayed_host, host_addr,
2135 libpq_gettext(
"connection to server at \"%s\", port %s failed: "),
2179 return val != 0 ? 1 : 0;
2200 #ifdef PG_TCP_KEEPALIVE_IDLE
2201 if (setsockopt(
conn->
sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
2202 (
char *) &idle,
sizeof(idle)) < 0)
2208 PG_TCP_KEEPALIVE_IDLE_STR,
2229 "keepalives_interval"))
2234 #ifdef TCP_KEEPINTVL
2235 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPINTVL,
2264 "keepalives_count"))
2270 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_KEEPCNT,
2271 (
char *) &count,
sizeof(count)) < 0)
2286 #ifdef SIO_KEEPALIVE_VALS
2296 struct tcp_keepalive ka;
2305 ka.keepalivetime = idle * 1000;
2306 ka.keepaliveinterval =
interval * 1000;
2334 "keepalives_interval"))
2340 "WSAIoctl",
"SIO_KEEPALIVE_VALS",
2361 "tcp_user_timeout"))
2367 #ifdef TCP_USER_TIMEOUT
2368 if (setsockopt(
conn->
sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
2369 (
char *) &timeout,
sizeof(timeout)) < 0)
2398 goto connect_errReturn;
2409 "libpq is incorrectly linked to backend functions\n");
2410 goto connect_errReturn;
2475 int last_whichhost = -2;
2476 int last_whichaddr = -2;
2598 bool reset_connection_state_machine =
false;
2599 bool need_new_connection =
false;
2664 reset_connection_state_machine =
true;
2675 struct addrinfo hint;
2676 struct addrinfo *addrlist;
2719 MemSet(&hint, 0,
sizeof(hint));
2720 hint.ai_socktype = SOCK_STREAM;
2721 hint.ai_family = AF_UNSPEC;
2724 if (ch->
port == NULL || ch->
port[0] ==
'\0')
2725 thisport = DEF_PGPORT;
2731 if (thisport < 1 || thisport > 65535)
2745 if (ret || !addrlist)
2754 hint.ai_flags = AI_NUMERICHOST;
2757 if (ret || !addrlist)
2766 hint.ai_family = AF_UNIX;
2782 if (ret || !addrlist)
2826 reset_connection_state_machine =
true;
2831 if (reset_connection_state_machine)
2844 reset_connection_state_machine =
false;
2845 need_new_connection =
true;
2849 if (need_new_connection)
2866 need_new_connection =
false;
2874 #define ENCRYPTION_NEGOTIATION_FAILED(msg) \
2876 switch (encryption_negotiation_failed(conn)) \
2879 libpq_append_conn_error(conn, (msg)); \
2880 goto error_return; \
2882 conn->status = CONNECTION_MADE; \
2883 return PGRES_POLLING_WRITING; \
2885 need_new_connection = true; \
2895 #define CONNECTION_FAILED() \
2897 if (connection_failed(conn)) \
2899 need_new_connection = true; \
2903 goto error_return; \
2920 char host_addr[NI_MAXHOST];
2950 "GSSAPI encryption required but it is not supported over a local socket");
2953 if (
conn->gcred == GSS_C_NO_CREDENTIAL)
2958 "GSSAPI encryption required but no credential cache");
2989 sock_type = SOCK_STREAM;
2998 sock_type |= SOCK_CLOEXEC;
3000 #ifdef SOCK_NONBLOCK
3006 sock_type |= SOCK_NONBLOCK;
3045 if (addr_cur->
family != AF_UNIX)
3054 #ifndef SOCK_NONBLOCK
3064 #ifndef SOCK_CLOEXEC
3066 if (fcntl(
conn->
sock, F_SETFD, FD_CLOEXEC) == -1)
3076 if (addr_cur->
family != AF_UNIX)
3084 if (usekeepalives < 0)
3089 else if (usekeepalives == 0)
3095 SOL_SOCKET, SO_KEEPALIVE,
3096 (
char *) &on,
sizeof(on)) < 0)
3109 #ifdef SIO_KEEPALIVE_VALS
3110 else if (!prepKeepalivesWin32(
conn))
3156 if (setsockopt(
conn->
sock, SOL_SOCKET, SO_NOSIGPIPE,
3157 (
char *) &optval,
sizeof(optval)) == 0)
3222 if (getsockopt(
conn->
sock, SOL_SOCKET, SO_ERROR,
3223 (
char *) &optval, &optlen) == -1)
3229 else if (optval != 0)
3265 char *remote_username;
3277 if (errno == ENOSYS)
3288 if (remote_username == NULL)
3295 free(remote_username);
3298 free(remote_username);
3406 packetlen =
sizeof(cancelpacket);
3499 else if (SSLok ==
'N')
3511 else if (SSLok ==
'E')
3603 else if (rdresult == 0)
3645 else if (gss_ok !=
'G')
3751 (msgLength < 8 || msgLength > 2000))
3757 (msgLength < 8 || msgLength > 2000))
3763 #define MAX_ERRLEN 30000
3813 if (avail < msgLength)
3961 const char *sqlstate;
3969 need_new_connection =
true;
4001 bool read_only_server;
4021 "SHOW transaction_read_only"))
4034 read_only_server : !read_only_server)
4079 "SELECT pg_catalog.pg_is_in_recovery()"))
4196 if (strncmp(
val,
"on", 2) == 0)
4218 "SHOW transaction_read_only");
4252 if (strncmp(
val,
"t", 1) == 0)
4268 "SELECT pg_is_in_recovery()");
4281 "invalid connection state %d, probably indicative of memory corruption",
4319 "GSSAPI encryption required but it is not supported over a local socket");
4368 #if defined(USE_SSL) || defined(ENABLE_GSS)
4412 int remaining_methods;
4414 #define SELECT_NEXT_METHOD(method) \
4416 if ((remaining_methods & method) != 0) \
4418 conn->current_enc_method = method; \
4448 "GSSAPI encryption required but no credential cache");
4475 #undef SELECT_NEXT_METHOD
4562 static bool wsastartup_done =
false;
4564 if (!wsastartup_done)
4568 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
4570 wsastartup_done =
true;
4761 struct addrinfo *ai = addrlist;
5001 const void *
buf,
size_t buf_len)
5024 #define LDAP_URL "ldap://"
5025 #define LDAP_DEF_PORT 389
5026 #define PGLDAP_TIMEOUT 2
5028 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
5029 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
5055 int port = LDAP_DEF_PORT,
5078 char *attrs[2] = {NULL, NULL};
5083 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
5085 if ((url = strdup(purl)) == NULL)
5100 "invalid LDAP URL \"%s\": scheme must be ldap://", purl);
5111 p = strchr(url + strlen(LDAP_URL),
'/');
5112 if (p == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5115 "invalid LDAP URL \"%s\": missing distinguished name",
5124 if ((p = strchr(dn,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5127 "invalid LDAP URL \"%s\": must have exactly one attribute",
5136 if ((p = strchr(attrs[0],
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5139 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5148 if ((p = strchr(scopestr,
'?')) == NULL || *(p + 1) ==
'\0' || *(p + 1) ==
'?')
5151 "invalid LDAP URL \"%s\": no filter",
5158 if ((p = strchr(filter,
'?')) != NULL)
5162 if ((p1 = strchr(
hostname,
':')) != NULL)
5169 lport = strtol(
portstr, &endptr, 10);
5170 if (*
portstr ==
'\0' || *endptr !=
'\0' || errno || lport < 0 || lport > 65535)
5173 "invalid LDAP URL \"%s\": invalid port number",
5182 if (strchr(attrs[0],
',') != NULL)
5185 "invalid LDAP URL \"%s\": must have exactly one attribute",
5193 scope = LDAP_SCOPE_BASE;
5195 scope = LDAP_SCOPE_ONELEVEL;
5197 scope = LDAP_SCOPE_SUBTREE;
5201 "invalid LDAP URL \"%s\": must have search scope (base/one/sub)",
5229 if (ldap_connect(ld, &time) != LDAP_SUCCESS)
5238 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5246 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
5256 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &
res)) == -1 ||
5270 if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
5280 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &
res))
5285 libpq_append_error(errorMessage,
"lookup on LDAP server failed: %s", ldap_err2string(rc));
5292 if ((rc = ldap_count_entries(ld,
res)) != 1)
5305 if ((entry = ldap_first_entry(ld,
res)) == NULL)
5316 if ((
values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
5331 ldap_value_free_len(
values);
5343 ldap_value_free_len(
values);
5356 ldap_value_free_len(
values);
5360 oldstate =
state = 0;
5361 for (p = result; *p !=
'\0'; ++p)
5366 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
5373 if (ld_is_sp_tab(*p))
5378 else if (ld_is_nl_cr(*p))
5381 "missing \"=\" after \"%s\" in connection info string",
5397 else if (!ld_is_sp_tab(*p))
5400 "missing \"=\" after \"%s\" in connection info string",
5413 else if (ld_is_nl_cr(*p))
5415 optval = optname + strlen(optname);
5418 else if (!ld_is_sp_tab(*p))
5425 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
5437 else if (*p ==
'\\')
5448 if (
state == 0 && oldstate != 0)
5450 found_keyword =
false;
5453 if (strcmp(
options[
i].keyword, optname) == 0)
5465 found_keyword =
true;
5486 "unterminated quoted string in connection info string");
5511 bool group_found =
false;
5513 struct stat stat_buf;
5520 if (service == NULL)
5521 service = getenv(
"PGSERVICE");
5524 if (service == NULL)
5531 if ((env = getenv(
"PGSERVICEFILE")) != NULL)
5532 strlcpy(serviceFile, env,
sizeof(serviceFile));
5540 if (
stat(serviceFile, &stat_buf) != 0)
5545 if (group_found || status != 0)
5555 getenv(
"PGSYSCONFDIR") ? getenv(
"PGSYSCONFDIR") : SYSCONFDIR);
5556 if (
stat(serviceFile, &stat_buf) != 0)
5575 const char *service,
5587 *group_found =
false;
5589 f = fopen(serviceFile,
"r");
5596 while ((line = fgets(
buf,
sizeof(
buf), f)) != NULL)
5602 if (strlen(line) >=
sizeof(
buf) - 1)
5605 "line %d too long in service file \"%s\"",
5614 while (
len > 0 && isspace((
unsigned char) line[
len - 1]))
5618 while (*line && isspace((
unsigned char) line[0]))
5622 if (line[0] ==
'\0' || line[0] ==
'#')
5634 if (strncmp(line + 1, service, strlen(service)) == 0 &&
5635 line[strlen(service) + 1] ==
']')
5636 *group_found =
true;
5638 *group_found =
false;
5652 if (strncmp(line,
"ldap", 4) == 0)
5654 int rc = ldapServiceLookup(line,
options, errorMessage);
5672 val = strchr(line,
'=');
5676 "syntax error in service file \"%s\", line %d",
5684 if (strcmp(
key,
"service") == 0)
5687 "nested service specifications not supported in service file \"%s\", line %d",
5698 found_keyword =
false;
5711 found_keyword =
true;
5719 "syntax error in service file \"%s\", line %d",
5763 if (connOptions == NULL &&
errmsg)
5883 if ((
buf = strdup(conninfo)) == NULL)
5894 if (isspace((
unsigned char) *cp))
5906 if (isspace((
unsigned char) *cp))
5911 if (!isspace((
unsigned char) *cp))
5924 "missing \"=\" after \"%s\" in connection info string",
5935 if (!isspace((
unsigned char) *cp))
5948 if (isspace((
unsigned char) *cp))
5972 libpq_append_error(errorMessage,
"unterminated quoted string in connection info string");
6056 while (expand_dbname && keywords[
i])
6058 const char *pname = keywords[
i];
6059 const char *pvalue =
values[
i];
6062 if (strcmp(pname,
"dbname") == 0 && pvalue)
6072 if (dbname_options == NULL)
6092 const char *pname = keywords[
i];
6093 const char *pvalue =
values[
i];
6095 if (pvalue != NULL && pvalue[0] !=
'\0')
6100 if (strcmp(
option->keyword, pname) == 0)
6105 if (
option->keyword == NULL)
6118 if (strcmp(pname,
"dbname") == 0 && dbname_options)
6122 for (str_option = dbname_options; str_option->
keyword != NULL; str_option++)
6124 if (str_option->
val != NULL)
6128 for (k = 0;
options[k].keyword; k++)
6152 dbname_options = NULL;
6205 *sslrootcert = NULL;
6222 if (strcmp(
option->keyword,
"sslrootcert") == 0)
6231 if (
option->envvar != NULL)
6233 if ((tmp = getenv(
option->envvar)) != NULL)
6252 if (strcmp(
option->keyword,
"sslmode") == 0)
6254 const char *requiresslenv = getenv(
"PGREQUIRESSL");
6256 if (requiresslenv != NULL && requiresslenv[0] ==
'1')
6273 sslmode_default =
option;
6280 if (
option->compiled != NULL)
6299 if (strcmp(
option->keyword,
"user") == 0)
6311 if (sslmode_default && sslrootcert)
6313 if (sslrootcert->val && strcmp(sslrootcert->val,
"system") == 0)
6317 sslmode_default->
val = strdup(
"verify-full");
6318 if (!sslmode_default->
val)
6396 char prevchar =
'\0';
6399 bool retval =
false;
6422 if (prefix_len == 0)
6426 "invalid URI propagated to internal parser routine: \"%s\"",
6430 start += prefix_len;
6434 while (*p && *p !=
'@' && *p !=
'/')
6445 while (*p !=
':' && *p !=
'@')
6454 errorMessage,
false,
true))
6457 if (prevchar ==
':')
6467 errorMessage,
false,
true))
6498 while (*p && *p !=
']')
6503 "end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"",
6510 "IPv6 host address may not be empty in URI: \"%s\"",
6522 if (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6525 "unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"",
6526 *p, (
int) (p -
buf + 1), uri);
6539 while (*p && *p !=
':' && *p !=
'/' && *p !=
'?' && *p !=
',')
6549 if (prevchar ==
':')
6551 const char *
port = ++p;
6553 while (*p && *p !=
'/' && *p !=
'?' && *p !=
',')
6562 if (prevchar !=
',')
6572 if (hostbuf.
data[0] &&
6574 errorMessage,
false,
true))
6576 if (portbuf.
data[0] &&
6578 errorMessage,
false,
true))
6581 if (prevchar && prevchar !=
'?')
6583 const char *
dbname = ++p;
6586 while (*p && *p !=
'?')
6599 errorMessage,
false,
true))
6636 char *keyword = params;
6639 bool malloced =
false;
6654 "extra key/value separator \"=\" in URI query parameter: \"%s\"",
6662 else if (*p ==
'&' || *p ==
'\0')
6674 "missing key/value separator \"=\" in URI query parameter: \"%s\"",
6686 if (keyword == NULL)
6703 if (strcmp(keyword,
"ssl") == 0 &&
6704 strcmp(
value,
"true") == 0)
6710 keyword =
"sslmode";
6719 oldmsglen = errorMessage->
len;
6721 errorMessage,
true,
false))
6724 if (errorMessage->
len == oldmsglen)
6726 "invalid URI query parameter: \"%s\"",
6767 const char *q =
str;
6782 if (!(*(p++) = *(q++)))
6800 "invalid percent-encoded token: \"%s\"",
6810 "forbidden value %%00 in percent-encoded value: \"%s\"",
6833 if (
'0' <= digit && digit <=
'9')
6834 *
value = digit -
'0';
6835 else if (
'A' <= digit && digit <=
'F')
6836 *
value = digit -
'A' + 10;
6837 else if (
'a' <= digit && digit <=
'f')
6838 *
value = digit -
'a' + 10;
6853 const char *keyword)
6879 const char *keyword,
const char *
value,
6891 if (strcmp(keyword,
"requiressl") == 0)
6893 keyword =
"sslmode";
6894 if (
value[0] ==
'1')
6905 "invalid connection option \"%s\"",
6913 if (value_copy == NULL)
6919 value_copy = strdup(
value);
6920 if (value_copy == NULL)
6948 if (strcmp(
option->keyword, keyword) == 0)
6978 if (connOptions != NULL)
6989 connmember = (
char **) ((
char *)
conn +
option->connofs);
6993 &errorBuf,
true,
false);
7006 if (connOptions == NULL)
7140 if (!
conn || !paramName)
7142 for (pstatus =
conn->
pstatus; pstatus != NULL; pstatus = pstatus->
next)
7144 if (strcmp(pstatus->
name, paramName) == 0)
7145 return pstatus->
value;
7270 static const char query[] =
"set client_encoding to '%s'";
7285 if (
sizeof(qbuf) < (
sizeof(query) + strlen(
encoding)))
7392 fprintf(stderr,
"%s", message);
7404 bool bslash =
false;
7410 if (tbuf[0] ==
'*' && tbuf[1] ==
':')
7414 if (*tbuf ==
'\\' && !bslash)
7419 if (*tbuf ==
':' && *ttok == 0 && !bslash)
7438 const char *
username,
const char *pgpassfile)
7441 struct stat stat_buf;
7462 if (
port == NULL ||
port[0] ==
'\0')
7463 port = DEF_PGPORT_STR;
7466 if (
stat(pgpassfile, &stat_buf) != 0)
7473 libpq_gettext(
"WARNING: password file \"%s\" is not a plain file\n"),
7482 libpq_gettext(
"WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
7494 fp = fopen(pgpassfile,
"r");
7501 while (!feof(fp) && !ferror(fp))
7508 if (fgets(
buf.data +
buf.len,
buf.maxlen -
buf.len, fp) == NULL)
7513 if (!(
buf.len > 0 &&
buf.data[
buf.len - 1] ==
'\n') && !feof(fp))
7517 if (
buf.data[0] !=
'#')
7549 for (p1 =
p2 = ret; *p1 !=
':' && *p1 !=
'\0'; ++p1, ++
p2)
7551 if (*p1 ==
'\\' && p1[1] !=
'\0')
7606 if (!version || strlen(version) == 0)
7632 if (min == NULL || max == NULL || strlen(min) == 0 || strlen(max) == 0)
7684 home = getenv(
"HOME");
7685 if (home == NULL || home[0] ==
'\0')
7690 char tmppath[MAX_PATH];
7692 ZeroMemory(tmppath,
sizeof(tmppath));
7693 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7718 numval = strtol(
value, &end, 10);
7724 if (
value == end || errno != 0 || numval != (
int) numval)
7731 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)
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[]
#define ENCRYPTION_NEGOTIATION_FAILED(msg)
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)
pg_usec_time_t PQgetCurrentTimeUSec(void)
void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, pg_usec_time_t end_time)
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
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
static const char * pghost
static const char * pgport
static const char * dbName
#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
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)