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