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-2020, 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 <time.h>
22 #include <unistd.h>
23 
24 #include "common/ip.h"
25 #include "common/link-canary.h"
26 #include "common/scram-common.h"
27 #include "common/string.h"
28 #include "fe-auth.h"
29 #include "libpq-fe.h"
30 #include "libpq-int.h"
31 #include "lib/stringinfo.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 #ifdef _MSC_VER /* mstcpip.h is missing on mingw */
48 #include <mstcpip.h>
49 #endif
50 #else
51 #include <sys/socket.h>
52 #include <netdb.h>
53 #include <netinet/in.h>
54 #ifdef HAVE_NETINET_TCP_H
55 #include <netinet/tcp.h>
56 #endif
57 #endif
58 
59 #ifdef ENABLE_THREAD_SAFETY
60 #ifdef WIN32
61 #include "pthread-win32.h"
62 #else
63 #include <pthread.h>
64 #endif
65 #endif
66 
67 #ifdef USE_LDAP
68 #ifdef WIN32
69 #include <winldap.h>
70 #else
71 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
72 #define LDAP_DEPRECATED 1
73 #include <ldap.h>
74 typedef struct timeval LDAP_TIMEVAL;
75 #endif
76 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
77  PQExpBuffer errorMessage);
78 #endif
79 
80 #ifndef WIN32
81 #define PGPASSFILE ".pgpass"
82 #else
83 #define PGPASSFILE "pgpass.conf"
84 #endif
85 
86 /*
87  * Pre-9.0 servers will return this SQLSTATE if asked to set
88  * application_name in a startup packet. We hard-wire the value rather
89  * than looking into errcodes.h since it reflects historical behavior
90  * rather than that of the current code.
91  */
92 #define ERRCODE_APPNAME_UNKNOWN "42704"
93 
94 /* This is part of the protocol so just define it */
95 #define ERRCODE_INVALID_PASSWORD "28P01"
96 /* This too */
97 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
98 
99 /*
100  * Cope with the various platform-specific ways to spell TCP keepalive socket
101  * options. This doesn't cover Windows, which as usual does its own thing.
102  */
103 #if defined(TCP_KEEPIDLE)
104 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
105 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
106 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
107 #elif defined(TCP_KEEPALIVE_THRESHOLD)
108 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
109 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
110 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
111 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
112 /* TCP_KEEPALIVE is the name of this option on macOS */
113 /* Caution: Solaris has this symbol but it means something different */
114 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
115 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
116 #endif
117 
118 /*
119  * fall back options if they are not specified by arguments or defined
120  * by environment variables
121  */
122 #define DefaultHost "localhost"
123 #define DefaultTty ""
124 #define DefaultOption ""
125 #define DefaultAuthtype ""
126 #ifdef USE_SSL
127 #define DefaultChannelBinding "prefer"
128 #else
129 #define DefaultChannelBinding "disable"
130 #endif
131 #define DefaultTargetSessionAttrs "any"
132 #ifdef USE_SSL
133 #define DefaultSSLMode "prefer"
134 #else
135 #define DefaultSSLMode "disable"
136 #endif
137 #ifdef ENABLE_GSS
138 #include "fe-gssapi-common.h"
139 #define DefaultGSSMode "prefer"
140 #else
141 #define DefaultGSSMode "disable"
142 #endif
143 
144 /* ----------
145  * Definition of the conninfo parameters and their fallback resources.
146  *
147  * If Environment-Var and Compiled-in are specified as NULL, no
148  * fallback is available. If after all no value can be determined
149  * for an option, an error is returned.
150  *
151  * The value for the username is treated specially in conninfo_add_defaults.
152  * If the value is not obtained any other way, the username is determined
153  * by pg_fe_getauthname().
154  *
155  * The Label and Disp-Char entries are provided for applications that
156  * want to use PQconndefaults() to create a generic database connection
157  * dialog. Disp-Char is defined as follows:
158  * "" Normal input field
159  * "*" Password field - hide value
160  * "D" Debug option - don't show by default
161  *
162  * PQconninfoOptions[] is a constant static array that we use to initialize
163  * a dynamically allocated working copy. All the "val" fields in
164  * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
165  * fields point to malloc'd strings that should be freed when the working
166  * array is freed (see PQconninfoFree).
167  *
168  * The first part of each struct is identical to the one in libpq-fe.h,
169  * which is required since we memcpy() data between the two!
170  * ----------
171  */
173 {
174  char *keyword; /* The keyword of the option */
175  char *envvar; /* Fallback environment variable name */
176  char *compiled; /* Fallback compiled in default value */
177  char *val; /* Option's current value, or NULL */
178  char *label; /* Label for field in connect dialog */
179  char *dispchar; /* Indicates how to display this field in a
180  * connect dialog. Values are: "" Display
181  * entered value as is "*" Password field -
182  * hide value "D" Debug option - don't show
183  * by default */
184  int dispsize; /* Field size in characters for dialog */
185  /* ---
186  * Anything above this comment must be synchronized with
187  * PQconninfoOption in libpq-fe.h, since we memcpy() data
188  * between them!
189  * ---
190  */
191  off_t connofs; /* Offset into PGconn struct, -1 if not there */
193 
195  /*
196  * "authtype" is no longer used, so mark it "don't show". We keep it in
197  * the array so as not to reject conninfo strings from old apps that might
198  * still try to set it.
199  */
200  {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
201  "Database-Authtype", "D", 20, -1},
202 
203  {"service", "PGSERVICE", NULL, NULL,
204  "Database-Service", "", 20, -1},
205 
206  {"user", "PGUSER", NULL, NULL,
207  "Database-User", "", 20,
208  offsetof(struct pg_conn, pguser)},
209 
210  {"password", "PGPASSWORD", NULL, NULL,
211  "Database-Password", "*", 20,
212  offsetof(struct pg_conn, pgpass)},
213 
214  {"passfile", "PGPASSFILE", NULL, NULL,
215  "Database-Password-File", "", 64,
216  offsetof(struct pg_conn, pgpassfile)},
217 
218  {"channel_binding", "PGCHANNELBINDING", NULL, NULL,
219  "Channel-Binding", "", 8, /* sizeof("require") == 8 */
220  offsetof(struct pg_conn, channel_binding)},
221 
222  {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
223  "Connect-timeout", "", 10, /* strlen(INT32_MAX) == 10 */
224  offsetof(struct pg_conn, connect_timeout)},
225 
226  {"dbname", "PGDATABASE", NULL, NULL,
227  "Database-Name", "", 20,
228  offsetof(struct pg_conn, dbName)},
229 
230  {"host", "PGHOST", NULL, NULL,
231  "Database-Host", "", 40,
232  offsetof(struct pg_conn, pghost)},
233 
234  {"hostaddr", "PGHOSTADDR", NULL, NULL,
235  "Database-Host-IP-Address", "", 45,
236  offsetof(struct pg_conn, pghostaddr)},
237 
238  {"port", "PGPORT", DEF_PGPORT_STR, NULL,
239  "Database-Port", "", 6,
240  offsetof(struct pg_conn, pgport)},
241 
242  {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
243  "Client-Encoding", "", 10,
244  offsetof(struct pg_conn, client_encoding_initial)},
245 
246  /*
247  * "tty" is no longer used either, but keep it present for backwards
248  * compatibility.
249  */
250  {"tty", "PGTTY", DefaultTty, NULL,
251  "Backend-Debug-TTY", "D", 40,
252  offsetof(struct pg_conn, pgtty)},
253 
254  {"options", "PGOPTIONS", DefaultOption, NULL,
255  "Backend-Options", "", 40,
256  offsetof(struct pg_conn, pgoptions)},
257 
258  {"application_name", "PGAPPNAME", NULL, NULL,
259  "Application-Name", "", 64,
260  offsetof(struct pg_conn, appname)},
261 
262  {"fallback_application_name", NULL, NULL, NULL,
263  "Fallback-Application-Name", "", 64,
264  offsetof(struct pg_conn, fbappname)},
265 
266  {"keepalives", NULL, NULL, NULL,
267  "TCP-Keepalives", "", 1, /* should be just '0' or '1' */
268  offsetof(struct pg_conn, keepalives)},
269 
270  {"keepalives_idle", NULL, NULL, NULL,
271  "TCP-Keepalives-Idle", "", 10, /* strlen(INT32_MAX) == 10 */
272  offsetof(struct pg_conn, keepalives_idle)},
273 
274  {"keepalives_interval", NULL, NULL, NULL,
275  "TCP-Keepalives-Interval", "", 10, /* strlen(INT32_MAX) == 10 */
276  offsetof(struct pg_conn, keepalives_interval)},
277 
278  {"keepalives_count", NULL, NULL, NULL,
279  "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
280  offsetof(struct pg_conn, keepalives_count)},
281 
282  {"tcp_user_timeout", NULL, NULL, NULL,
283  "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
284  offsetof(struct pg_conn, pgtcp_user_timeout)},
285 
286  /*
287  * ssl options are allowed even without client SSL support because the
288  * client can still handle SSL modes "disable" and "allow". Other
289  * parameters have no effect on non-SSL connections, so there is no reason
290  * to exclude them since none of them are mandatory.
291  */
292  {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
293  "SSL-Mode", "", 12, /* sizeof("verify-full") == 12 */
294  offsetof(struct pg_conn, sslmode)},
295 
296  {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
297  "SSL-Compression", "", 1,
298  offsetof(struct pg_conn, sslcompression)},
299 
300  {"sslcert", "PGSSLCERT", NULL, NULL,
301  "SSL-Client-Cert", "", 64,
302  offsetof(struct pg_conn, sslcert)},
303 
304  {"sslkey", "PGSSLKEY", NULL, NULL,
305  "SSL-Client-Key", "", 64,
306  offsetof(struct pg_conn, sslkey)},
307 
308  {"sslpassword", NULL, NULL, NULL,
309  "SSL-Client-Key-Password", "*", 20,
310  offsetof(struct pg_conn, sslpassword)},
311 
312  {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
313  "SSL-Root-Certificate", "", 64,
314  offsetof(struct pg_conn, sslrootcert)},
315 
316  {"sslcrl", "PGSSLCRL", NULL, NULL,
317  "SSL-Revocation-List", "", 64,
318  offsetof(struct pg_conn, sslcrl)},
319 
320  {"requirepeer", "PGREQUIREPEER", NULL, NULL,
321  "Require-Peer", "", 10,
322  offsetof(struct pg_conn, requirepeer)},
323 
324  {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL,
325  "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
327 
328  {"ssl_max_protocol_version", "PGSSLMAXPROTOCOLVERSION", NULL, NULL,
329  "SSL-Maximum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */
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  {"replication", NULL, NULL, NULL,
350  "Replication", "D", 5,
351  offsetof(struct pg_conn, replication)},
352 
353  {"target_session_attrs", "PGTARGETSESSIONATTRS",
355  "Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
356  offsetof(struct pg_conn, target_session_attrs)},
357 
358  /* Terminating entry --- MUST BE LAST */
359  {NULL, NULL, NULL, NULL,
360  NULL, NULL, 0}
361 };
362 
364 {
365  /* common user-interface settings */
366  {
367  "PGDATESTYLE", "datestyle"
368  },
369  {
370  "PGTZ", "timezone"
371  },
372  /* internal performance-related settings */
373  {
374  "PGGEQO", "geqo"
375  },
376  {
377  NULL, NULL
378  }
379 };
380 
381 /* The connection URI must start with either of the following designators: */
382 static const char uri_designator[] = "postgresql://";
383 static const char short_uri_designator[] = "postgres://";
384 
385 static bool connectOptions1(PGconn *conn, const char *conninfo);
386 static bool connectOptions2(PGconn *conn);
387 static int connectDBStart(PGconn *conn);
388 static int connectDBComplete(PGconn *conn);
390 static PGconn *makeEmptyPGconn(void);
391 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
392 static void freePGconn(PGconn *conn);
393 static void closePGconn(PGconn *conn);
394 static void release_conn_addrinfo(PGconn *conn);
395 static void sendTerminateConn(PGconn *conn);
396 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
397 static PQconninfoOption *parse_connection_string(const char *conninfo,
398  PQExpBuffer errorMessage, bool use_defaults);
399 static int uri_prefix_length(const char *connstr);
400 static bool recognized_connection_string(const char *connstr);
401 static PQconninfoOption *conninfo_parse(const char *conninfo,
402  PQExpBuffer errorMessage, bool use_defaults);
403 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
404  const char *const *values, PQExpBuffer errorMessage,
405  bool use_defaults, int expand_dbname);
407  PQExpBuffer errorMessage);
408 static PQconninfoOption *conninfo_uri_parse(const char *uri,
409  PQExpBuffer errorMessage, bool use_defaults);
411  const char *uri, PQExpBuffer errorMessage);
412 static bool conninfo_uri_parse_params(char *params,
413  PQconninfoOption *connOptions,
414  PQExpBuffer errorMessage);
415 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
416 static bool get_hexdigit(char digit, int *value);
417 static const char *conninfo_getval(PQconninfoOption *connOptions,
418  const char *keyword);
420  const char *keyword, const char *value,
421  PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
422 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
423  const char *keyword);
424 static void defaultNoticeReceiver(void *arg, const PGresult *res);
425 static void defaultNoticeProcessor(void *arg, const char *message);
427  PQExpBuffer errorMessage);
428 static int parseServiceFile(const char *serviceFile,
429  const char *service,
431  PQExpBuffer errorMessage,
432  bool *group_found);
433 static char *pwdfMatchesString(char *buf, const char *token);
434 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
435  const char *username, const char *pgpassfile);
436 static void pgpassfileWarning(PGconn *conn);
437 static void default_threadlock(int acquire);
438 static bool sslVerifyProtocolVersion(const char *version);
439 static bool sslVerifyProtocolRange(const char *min, const char *max);
440 
441 
442 /* global variable because fe-auth.c needs to access it */
444 
445 
446 /*
447  * pqDropConnection
448  *
449  * Close any physical connection to the server, and reset associated
450  * state inside the connection object. We don't release state that
451  * would be needed to reconnect, though, nor local state that might still
452  * be useful later.
453  *
454  * We can always flush the output buffer, since there's no longer any hope
455  * of sending that data. However, unprocessed input data might still be
456  * valuable, so the caller must tell us whether to flush that or not.
457  */
458 void
459 pqDropConnection(PGconn *conn, bool flushInput)
460 {
461  /* Drop any SSL state */
462  pqsecure_close(conn);
463 
464  /* Close the socket itself */
465  if (conn->sock != PGINVALID_SOCKET)
466  closesocket(conn->sock);
467  conn->sock = PGINVALID_SOCKET;
468 
469  /* Optionally discard any unread data */
470  if (flushInput)
471  conn->inStart = conn->inCursor = conn->inEnd = 0;
472 
473  /* Always discard any unsent data */
474  conn->outCount = 0;
475 
476  /* Free authentication/encryption state */
477 #ifdef ENABLE_GSS
478  {
479  OM_uint32 min_s;
480 
481  if (conn->gcred != GSS_C_NO_CREDENTIAL)
482  {
483  gss_release_cred(&min_s, &conn->gcred);
484  conn->gcred = GSS_C_NO_CREDENTIAL;
485  }
486  if (conn->gctx)
487  gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
488  if (conn->gtarg_nam)
489  gss_release_name(&min_s, &conn->gtarg_nam);
490  if (conn->gss_SendBuffer)
491  {
492  free(conn->gss_SendBuffer);
493  conn->gss_SendBuffer = NULL;
494  }
495  if (conn->gss_RecvBuffer)
496  {
497  free(conn->gss_RecvBuffer);
498  conn->gss_RecvBuffer = NULL;
499  }
500  if (conn->gss_ResultBuffer)
501  {
502  free(conn->gss_ResultBuffer);
503  conn->gss_ResultBuffer = NULL;
504  }
505  conn->gssenc = false;
506  }
507 #endif
508 #ifdef ENABLE_SSPI
509  if (conn->sspitarget)
510  {
511  free(conn->sspitarget);
512  conn->sspitarget = NULL;
513  }
514  if (conn->sspicred)
515  {
516  FreeCredentialsHandle(conn->sspicred);
517  free(conn->sspicred);
518  conn->sspicred = NULL;
519  }
520  if (conn->sspictx)
521  {
522  DeleteSecurityContext(conn->sspictx);
523  free(conn->sspictx);
524  conn->sspictx = NULL;
525  }
526  conn->usesspi = 0;
527 #endif
528  if (conn->sasl_state)
529  {
530  /*
531  * XXX: if support for more authentication mechanisms is added, this
532  * needs to call the right 'free' function.
533  */
535  conn->sasl_state = NULL;
536  }
537 }
538 
539 
540 /*
541  * pqDropServerData
542  *
543  * Clear all connection state data that was received from (or deduced about)
544  * the server. This is essential to do between connection attempts to
545  * different servers, else we may incorrectly hold over some data from the
546  * old server.
547  *
548  * It would be better to merge this into pqDropConnection, perhaps, but
549  * right now we cannot because that function is called immediately on
550  * detection of connection loss (cf. pqReadData, for instance). This data
551  * should be kept until we are actually starting a new connection.
552  */
553 static void
555 {
556  PGnotify *notify;
557  pgParameterStatus *pstatus;
558 
559  /* Forget pending notifies */
560  notify = conn->notifyHead;
561  while (notify != NULL)
562  {
563  PGnotify *prev = notify;
564 
565  notify = notify->next;
566  free(prev);
567  }
568  conn->notifyHead = conn->notifyTail = NULL;
569 
570  /* Reset ParameterStatus data, as well as variables deduced from it */
571  pstatus = conn->pstatus;
572  while (pstatus != NULL)
573  {
574  pgParameterStatus *prev = pstatus;
575 
576  pstatus = pstatus->next;
577  free(prev);
578  }
579  conn->pstatus = NULL;
581  conn->std_strings = false;
582  conn->sversion = 0;
583 
584  /* Drop large-object lookup data */
585  if (conn->lobjfuncs)
586  free(conn->lobjfuncs);
587  conn->lobjfuncs = NULL;
588 
589  /* Reset assorted other per-connection state */
590  conn->last_sqlstate[0] = '\0';
591  conn->auth_req_received = false;
592  conn->password_needed = false;
593  conn->write_failed = false;
594  if (conn->write_err_msg)
595  free(conn->write_err_msg);
596  conn->write_err_msg = NULL;
597  conn->be_pid = 0;
598  conn->be_key = 0;
599 }
600 
601 
602 /*
603  * Connecting to a Database
604  *
605  * There are now six different ways a user of this API can connect to the
606  * database. Two are not recommended for use in new code, because of their
607  * lack of extensibility with respect to the passing of options to the
608  * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
609  * to the latter).
610  *
611  * If it is desired to connect in a synchronous (blocking) manner, use the
612  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
613  * option = value pairs (or a URI) which must be parsed; the latter takes two
614  * NULL terminated arrays instead.
615  *
616  * To connect in an asynchronous (non-blocking) manner, use the functions
617  * PQconnectStart or PQconnectStartParams (which differ in the same way as
618  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
619  *
620  * Internally, the static functions connectDBStart, connectDBComplete
621  * are part of the connection procedure.
622  */
623 
624 /*
625  * PQconnectdbParams
626  *
627  * establishes a connection to a postgres backend through the postmaster
628  * using connection information in two arrays.
629  *
630  * The keywords array is defined as
631  *
632  * const char *params[] = {"option1", "option2", NULL}
633  *
634  * The values array is defined as
635  *
636  * const char *values[] = {"value1", "value2", NULL}
637  *
638  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
639  * if a memory allocation failed.
640  * If the status field of the connection returned is CONNECTION_BAD,
641  * then some fields may be null'ed out instead of having valid values.
642  *
643  * You should call PQfinish (if conn is not NULL) regardless of whether this
644  * call succeeded.
645  */
646 PGconn *
647 PQconnectdbParams(const char *const *keywords,
648  const char *const *values,
649  int expand_dbname)
650 {
651  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
652 
653  if (conn && conn->status != CONNECTION_BAD)
654  (void) connectDBComplete(conn);
655 
656  return conn;
657 
658 }
659 
660 /*
661  * PQpingParams
662  *
663  * check server status, accepting parameters identical to PQconnectdbParams
664  */
665 PGPing
666 PQpingParams(const char *const *keywords,
667  const char *const *values,
668  int expand_dbname)
669 {
670  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
671  PGPing ret;
672 
673  ret = internal_ping(conn);
674  PQfinish(conn);
675 
676  return ret;
677 }
678 
679 /*
680  * PQconnectdb
681  *
682  * establishes a connection to a postgres backend through the postmaster
683  * using connection information in a string.
684  *
685  * The conninfo string is either a whitespace-separated list of
686  *
687  * option = value
688  *
689  * definitions or a URI (refer to the documentation for details.) Value
690  * might be a single value containing no whitespaces or a single quoted
691  * string. If a single quote should appear anywhere in the value, it must be
692  * escaped with a backslash like \'
693  *
694  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
695  * if a memory allocation failed.
696  * If the status field of the connection returned is CONNECTION_BAD,
697  * then some fields may be null'ed out instead of having valid values.
698  *
699  * You should call PQfinish (if conn is not NULL) regardless of whether this
700  * call succeeded.
701  */
702 PGconn *
703 PQconnectdb(const char *conninfo)
704 {
705  PGconn *conn = PQconnectStart(conninfo);
706 
707  if (conn && conn->status != CONNECTION_BAD)
708  (void) connectDBComplete(conn);
709 
710  return conn;
711 }
712 
713 /*
714  * PQping
715  *
716  * check server status, accepting parameters identical to PQconnectdb
717  */
718 PGPing
719 PQping(const char *conninfo)
720 {
721  PGconn *conn = PQconnectStart(conninfo);
722  PGPing ret;
723 
724  ret = internal_ping(conn);
725  PQfinish(conn);
726 
727  return ret;
728 }
729 
730 /*
731  * PQconnectStartParams
732  *
733  * Begins the establishment of a connection to a postgres backend through the
734  * postmaster using connection information in a struct.
735  *
736  * See comment for PQconnectdbParams for the definition of the string format.
737  *
738  * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
739  * you should not attempt to proceed with this connection. If the status
740  * field of the connection returned is CONNECTION_BAD, an error has
741  * occurred. In this case you should call PQfinish on the result, (perhaps
742  * inspecting the error message first). Other fields of the structure may not
743  * be valid if that occurs. If the status field is not CONNECTION_BAD, then
744  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
745  * this is necessary.
746  *
747  * See PQconnectPoll for more info.
748  */
749 PGconn *
750 PQconnectStartParams(const char *const *keywords,
751  const char *const *values,
752  int expand_dbname)
753 {
754  PGconn *conn;
755  PQconninfoOption *connOptions;
756 
757  /*
758  * Allocate memory for the conn structure
759  */
760  conn = makeEmptyPGconn();
761  if (conn == NULL)
762  return NULL;
763 
764  /*
765  * Parse the conninfo arrays
766  */
767  connOptions = conninfo_array_parse(keywords, values,
768  &conn->errorMessage,
769  true, expand_dbname);
770  if (connOptions == NULL)
771  {
772  conn->status = CONNECTION_BAD;
773  /* errorMessage is already set */
774  return conn;
775  }
776 
777  /*
778  * Move option values into conn structure
779  */
780  if (!fillPGconn(conn, connOptions))
781  {
782  PQconninfoFree(connOptions);
783  return conn;
784  }
785 
786  /*
787  * Free the option info - all is in conn now
788  */
789  PQconninfoFree(connOptions);
790 
791  /*
792  * Compute derived options
793  */
794  if (!connectOptions2(conn))
795  return conn;
796 
797  /*
798  * Connect to the database
799  */
800  if (!connectDBStart(conn))
801  {
802  /* Just in case we failed to set it in connectDBStart */
803  conn->status = CONNECTION_BAD;
804  }
805 
806  return conn;
807 }
808 
809 /*
810  * PQconnectStart
811  *
812  * Begins the establishment of a connection to a postgres backend through the
813  * postmaster using connection information in a string.
814  *
815  * See comment for PQconnectdb for the definition of the string format.
816  *
817  * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
818  * you should not attempt to proceed with this connection. If the status
819  * field of the connection returned is CONNECTION_BAD, an error has
820  * occurred. In this case you should call PQfinish on the result, (perhaps
821  * inspecting the error message first). Other fields of the structure may not
822  * be valid if that occurs. If the status field is not CONNECTION_BAD, then
823  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
824  * this is necessary.
825  *
826  * See PQconnectPoll for more info.
827  */
828 PGconn *
829 PQconnectStart(const char *conninfo)
830 {
831  PGconn *conn;
832 
833  /*
834  * Allocate memory for the conn structure
835  */
836  conn = makeEmptyPGconn();
837  if (conn == NULL)
838  return NULL;
839 
840  /*
841  * Parse the conninfo string
842  */
843  if (!connectOptions1(conn, conninfo))
844  return conn;
845 
846  /*
847  * Compute derived options
848  */
849  if (!connectOptions2(conn))
850  return conn;
851 
852  /*
853  * Connect to the database
854  */
855  if (!connectDBStart(conn))
856  {
857  /* Just in case we failed to set it in connectDBStart */
858  conn->status = CONNECTION_BAD;
859  }
860 
861  return conn;
862 }
863 
864 /*
865  * Move option values into conn structure
866  *
867  * Don't put anything cute here --- intelligence should be in
868  * connectOptions2 ...
869  *
870  * Returns true on success. On failure, returns false and sets error message.
871  */
872 static bool
874 {
876 
877  for (option = PQconninfoOptions; option->keyword; option++)
878  {
879  if (option->connofs >= 0)
880  {
881  const char *tmp = conninfo_getval(connOptions, option->keyword);
882 
883  if (tmp)
884  {
885  char **connmember = (char **) ((char *) conn + option->connofs);
886 
887  if (*connmember)
888  free(*connmember);
889  *connmember = strdup(tmp);
890  if (*connmember == NULL)
891  {
893  libpq_gettext("out of memory\n"));
894  return false;
895  }
896  }
897  }
898  }
899 
900  return true;
901 }
902 
903 /*
904  * connectOptions1
905  *
906  * Internal subroutine to set up connection parameters given an already-
907  * created PGconn and a conninfo string. Derived settings should be
908  * processed by calling connectOptions2 next. (We split them because
909  * PQsetdbLogin overrides defaults in between.)
910  *
911  * Returns true if OK, false if trouble (in which case errorMessage is set
912  * and so is conn->status).
913  */
914 static bool
915 connectOptions1(PGconn *conn, const char *conninfo)
916 {
917  PQconninfoOption *connOptions;
918 
919  /*
920  * Parse the conninfo string
921  */
922  connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
923  if (connOptions == NULL)
924  {
925  conn->status = CONNECTION_BAD;
926  /* errorMessage is already set */
927  return false;
928  }
929 
930  /*
931  * Move option values into conn structure
932  */
933  if (!fillPGconn(conn, connOptions))
934  {
935  conn->status = CONNECTION_BAD;
936  PQconninfoFree(connOptions);
937  return false;
938  }
939 
940  /*
941  * Free the option info - all is in conn now
942  */
943  PQconninfoFree(connOptions);
944 
945  return true;
946 }
947 
948 /*
949  * Count the number of elements in a simple comma-separated list.
950  */
951 static int
952 count_comma_separated_elems(const char *input)
953 {
954  int n;
955 
956  n = 1;
957  for (; *input != '\0'; input++)
958  {
959  if (*input == ',')
960  n++;
961  }
962 
963  return n;
964 }
965 
966 /*
967  * Parse a simple comma-separated list.
968  *
969  * On each call, returns a malloc'd copy of the next element, and sets *more
970  * to indicate whether there are any more elements in the list after this,
971  * and updates *startptr to point to the next element, if any.
972  *
973  * On out of memory, returns NULL.
974  */
975 static char *
977 {
978  char *p;
979  char *s = *startptr;
980  char *e;
981  int len;
982 
983  /*
984  * Search for the end of the current element; a comma or end-of-string
985  * acts as a terminator.
986  */
987  e = s;
988  while (*e != '\0' && *e != ',')
989  ++e;
990  *more = (*e == ',');
991 
992  len = e - s;
993  p = (char *) malloc(sizeof(char) * (len + 1));
994  if (p)
995  {
996  memcpy(p, s, len);
997  p[len] = '\0';
998  }
999  *startptr = e + 1;
1000 
1001  return p;
1002 }
1003 
1004 /*
1005  * connectOptions2
1006  *
1007  * Compute derived connection options after absorbing all user-supplied info.
1008  *
1009  * Returns true if OK, false if trouble (in which case errorMessage is set
1010  * and so is conn->status).
1011  */
1012 static bool
1014 {
1015  int i;
1016 
1017  /*
1018  * Allocate memory for details about each host to which we might possibly
1019  * try to connect. For that, count the number of elements in the hostaddr
1020  * or host options. If neither is given, assume one host.
1021  */
1022  conn->whichhost = 0;
1023  if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1025  else if (conn->pghost && conn->pghost[0] != '\0')
1027  else
1028  conn->nconnhost = 1;
1029  conn->connhost = (pg_conn_host *)
1030  calloc(conn->nconnhost, sizeof(pg_conn_host));
1031  if (conn->connhost == NULL)
1032  goto oom_error;
1033 
1034  /*
1035  * We now have one pg_conn_host structure per possible host. Fill in the
1036  * host and hostaddr fields for each, by splitting the parameter strings.
1037  */
1038  if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1039  {
1040  char *s = conn->pghostaddr;
1041  bool more = true;
1042 
1043  for (i = 0; i < conn->nconnhost && more; i++)
1044  {
1045  conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
1046  if (conn->connhost[i].hostaddr == NULL)
1047  goto oom_error;
1048  }
1049 
1050  /*
1051  * If hostaddr was given, the array was allocated according to the
1052  * number of elements in the hostaddr list, so it really should be the
1053  * right size.
1054  */
1055  Assert(!more);
1056  Assert(i == conn->nconnhost);
1057  }
1058 
1059  if (conn->pghost != NULL && conn->pghost[0] != '\0')
1060  {
1061  char *s = conn->pghost;
1062  bool more = true;
1063 
1064  for (i = 0; i < conn->nconnhost && more; i++)
1065  {
1066  conn->connhost[i].host = parse_comma_separated_list(&s, &more);
1067  if (conn->connhost[i].host == NULL)
1068  goto oom_error;
1069  }
1070 
1071  /* Check for wrong number of host items. */
1072  if (more || i != conn->nconnhost)
1073  {
1074  conn->status = CONNECTION_BAD;
1076  libpq_gettext("could not match %d host names to %d hostaddr values\n"),
1078  return false;
1079  }
1080  }
1081 
1082  /*
1083  * Now, for each host slot, identify the type of address spec, and fill in
1084  * the default address if nothing was given.
1085  */
1086  for (i = 0; i < conn->nconnhost; i++)
1087  {
1088  pg_conn_host *ch = &conn->connhost[i];
1089 
1090  if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1091  ch->type = CHT_HOST_ADDRESS;
1092  else if (ch->host != NULL && ch->host[0] != '\0')
1093  {
1094  ch->type = CHT_HOST_NAME;
1095 #ifdef HAVE_UNIX_SOCKETS
1096  if (is_absolute_path(ch->host))
1097  ch->type = CHT_UNIX_SOCKET;
1098 #endif
1099  }
1100  else
1101  {
1102  if (ch->host)
1103  free(ch->host);
1104 #ifdef HAVE_UNIX_SOCKETS
1105  if (DEFAULT_PGSOCKET_DIR[0])
1106  {
1107  ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1108  ch->type = CHT_UNIX_SOCKET;
1109  }
1110  else
1111 #endif
1112  {
1113  ch->host = strdup(DefaultHost);
1114  ch->type = CHT_HOST_NAME;
1115  }
1116  if (ch->host == NULL)
1117  goto oom_error;
1118  }
1119  }
1120 
1121  /*
1122  * Next, work out the port number corresponding to each host name.
1123  *
1124  * Note: unlike the above for host names, this could leave the port fields
1125  * as null or empty strings. We will substitute DEF_PGPORT whenever we
1126  * read such a port field.
1127  */
1128  if (conn->pgport != NULL && conn->pgport[0] != '\0')
1129  {
1130  char *s = conn->pgport;
1131  bool more = true;
1132 
1133  for (i = 0; i < conn->nconnhost && more; i++)
1134  {
1135  conn->connhost[i].port = parse_comma_separated_list(&s, &more);
1136  if (conn->connhost[i].port == NULL)
1137  goto oom_error;
1138  }
1139 
1140  /*
1141  * If exactly one port was given, use it for every host. Otherwise,
1142  * there must be exactly as many ports as there were hosts.
1143  */
1144  if (i == 1 && !more)
1145  {
1146  for (i = 1; i < conn->nconnhost; i++)
1147  {
1148  conn->connhost[i].port = strdup(conn->connhost[0].port);
1149  if (conn->connhost[i].port == NULL)
1150  goto oom_error;
1151  }
1152  }
1153  else if (more || i != conn->nconnhost)
1154  {
1155  conn->status = CONNECTION_BAD;
1157  libpq_gettext("could not match %d port numbers to %d hosts\n"),
1159  return false;
1160  }
1161  }
1162 
1163  /*
1164  * If user name was not given, fetch it. (Most likely, the fetch will
1165  * fail, since the only way we get here is if pg_fe_getauthname() failed
1166  * during conninfo_add_defaults(). But now we want an error message.)
1167  */
1168  if (conn->pguser == NULL || conn->pguser[0] == '\0')
1169  {
1170  if (conn->pguser)
1171  free(conn->pguser);
1172  conn->pguser = pg_fe_getauthname(&conn->errorMessage);
1173  if (!conn->pguser)
1174  {
1175  conn->status = CONNECTION_BAD;
1176  return false;
1177  }
1178  }
1179 
1180  /*
1181  * If database name was not given, default it to equal user name
1182  */
1183  if (conn->dbName == NULL || conn->dbName[0] == '\0')
1184  {
1185  if (conn->dbName)
1186  free(conn->dbName);
1187  conn->dbName = strdup(conn->pguser);
1188  if (!conn->dbName)
1189  goto oom_error;
1190  }
1191 
1192  /*
1193  * If password was not given, try to look it up in password file. Note
1194  * that the result might be different for each host/port pair.
1195  */
1196  if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1197  {
1198  /* If password file wasn't specified, use ~/PGPASSFILE */
1199  if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1200  {
1201  char homedir[MAXPGPATH];
1202 
1203  if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1204  {
1205  if (conn->pgpassfile)
1206  free(conn->pgpassfile);
1207  conn->pgpassfile = malloc(MAXPGPATH);
1208  if (!conn->pgpassfile)
1209  goto oom_error;
1210  snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1211  homedir, PGPASSFILE);
1212  }
1213  }
1214 
1215  if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1216  {
1217  for (i = 0; i < conn->nconnhost; i++)
1218  {
1219  /*
1220  * Try to get a password for this host from file. We use host
1221  * for the hostname search key if given, else hostaddr (at
1222  * least one of them is guaranteed nonempty by now).
1223  */
1224  const char *pwhost = conn->connhost[i].host;
1225 
1226  if (pwhost == NULL || pwhost[0] == '\0')
1227  pwhost = conn->connhost[i].hostaddr;
1228 
1229  conn->connhost[i].password =
1230  passwordFromFile(pwhost,
1231  conn->connhost[i].port,
1232  conn->dbName,
1233  conn->pguser,
1234  conn->pgpassfile);
1235  }
1236  }
1237  }
1238 
1239  /*
1240  * validate channel_binding option
1241  */
1242  if (conn->channel_binding)
1243  {
1244  if (strcmp(conn->channel_binding, "disable") != 0
1245  && strcmp(conn->channel_binding, "prefer") != 0
1246  && strcmp(conn->channel_binding, "require") != 0)
1247  {
1248  conn->status = CONNECTION_BAD;
1250  libpq_gettext("invalid %s value: \"%s\"\n"),
1251  "channel_binding", conn->channel_binding);
1252  return false;
1253  }
1254  }
1255  else
1256  {
1257  conn->channel_binding = strdup(DefaultChannelBinding);
1258  if (!conn->channel_binding)
1259  goto oom_error;
1260  }
1261 
1262  /*
1263  * validate sslmode option
1264  */
1265  if (conn->sslmode)
1266  {
1267  if (strcmp(conn->sslmode, "disable") != 0
1268  && strcmp(conn->sslmode, "allow") != 0
1269  && strcmp(conn->sslmode, "prefer") != 0
1270  && strcmp(conn->sslmode, "require") != 0
1271  && strcmp(conn->sslmode, "verify-ca") != 0
1272  && strcmp(conn->sslmode, "verify-full") != 0)
1273  {
1274  conn->status = CONNECTION_BAD;
1276  libpq_gettext("invalid %s value: \"%s\"\n"),
1277  "sslmode", conn->sslmode);
1278  return false;
1279  }
1280 
1281 #ifndef USE_SSL
1282  switch (conn->sslmode[0])
1283  {
1284  case 'a': /* "allow" */
1285  case 'p': /* "prefer" */
1286 
1287  /*
1288  * warn user that an SSL connection will never be negotiated
1289  * since SSL was not compiled in?
1290  */
1291  break;
1292 
1293  case 'r': /* "require" */
1294  case 'v': /* "verify-ca" or "verify-full" */
1295  conn->status = CONNECTION_BAD;
1297  libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
1298  conn->sslmode);
1299  return false;
1300  }
1301 #endif
1302  }
1303  else
1304  {
1305  conn->sslmode = strdup(DefaultSSLMode);
1306  if (!conn->sslmode)
1307  goto oom_error;
1308  }
1309 
1310  /*
1311  * Validate TLS protocol versions for ssl_min_protocol_version and
1312  * ssl_max_protocol_version.
1313  */
1315  {
1316  conn->status = CONNECTION_BAD;
1318  libpq_gettext("invalid %s value: \"%s\"\n"),
1319  "ssl_min_protocol_version",
1320  conn->ssl_min_protocol_version);
1321  return false;
1322  }
1324  {
1325  conn->status = CONNECTION_BAD;
1327  libpq_gettext("invalid %s value: \"%s\"\n"),
1328  "ssl_max_protocol_version",
1329  conn->ssl_max_protocol_version);
1330  return false;
1331  }
1332 
1333  /*
1334  * Check if the range of SSL protocols defined is correct. This is done
1335  * at this early step because this is independent of the SSL
1336  * implementation used, and this avoids unnecessary cycles with an
1337  * already-built SSL context when the connection is being established, as
1338  * it would be doomed anyway.
1339  */
1341  conn->ssl_max_protocol_version))
1342  {
1343  conn->status = CONNECTION_BAD;
1345  libpq_gettext("invalid SSL protocol version range\n"));
1346  return false;
1347  }
1348 
1349  /*
1350  * validate gssencmode option
1351  */
1352  if (conn->gssencmode)
1353  {
1354  if (strcmp(conn->gssencmode, "disable") != 0 &&
1355  strcmp(conn->gssencmode, "prefer") != 0 &&
1356  strcmp(conn->gssencmode, "require") != 0)
1357  {
1358  conn->status = CONNECTION_BAD;
1360  libpq_gettext("invalid %s value: \"%s\"\n"),
1361  "gssencmode",
1362  conn->gssencmode);
1363  return false;
1364  }
1365 #ifndef ENABLE_GSS
1366  if (strcmp(conn->gssencmode, "require") == 0)
1367  {
1368  conn->status = CONNECTION_BAD;
1370  libpq_gettext("gssencmode value \"%s\" invalid when GSSAPI support is not compiled in\n"),
1371  conn->gssencmode);
1372  return false;
1373  }
1374 #endif
1375  }
1376  else
1377  {
1378  conn->gssencmode = strdup(DefaultGSSMode);
1379  if (!conn->gssencmode)
1380  goto oom_error;
1381  }
1382 
1383  /*
1384  * Resolve special "auto" client_encoding from the locale
1385  */
1386  if (conn->client_encoding_initial &&
1387  strcmp(conn->client_encoding_initial, "auto") == 0)
1388  {
1391  if (!conn->client_encoding_initial)
1392  goto oom_error;
1393  }
1394 
1395  /*
1396  * Validate target_session_attrs option.
1397  */
1398  if (conn->target_session_attrs)
1399  {
1400  if (strcmp(conn->target_session_attrs, "any") != 0
1401  && strcmp(conn->target_session_attrs, "read-write") != 0)
1402  {
1403  conn->status = CONNECTION_BAD;
1405  libpq_gettext("invalid %s value: \"%s\"\n"),
1406  "target_settion_attrs",
1407  conn->target_session_attrs);
1408  return false;
1409  }
1410  }
1411 
1412  /*
1413  * Only if we get this far is it appropriate to try to connect. (We need a
1414  * state flag, rather than just the boolean result of this function, in
1415  * case someone tries to PQreset() the PGconn.)
1416  */
1417  conn->options_valid = true;
1418 
1419  return true;
1420 
1421 oom_error:
1422  conn->status = CONNECTION_BAD;
1424  libpq_gettext("out of memory\n"));
1425  return false;
1426 }
1427 
1428 /*
1429  * PQconndefaults
1430  *
1431  * Construct a default connection options array, which identifies all the
1432  * available options and shows any default values that are available from the
1433  * environment etc. On error (eg out of memory), NULL is returned.
1434  *
1435  * Using this function, an application may determine all possible options
1436  * and their current default values.
1437  *
1438  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1439  * and should be freed when no longer needed via PQconninfoFree(). (In prior
1440  * versions, the returned array was static, but that's not thread-safe.)
1441  * Pre-7.0 applications that use this function will see a small memory leak
1442  * until they are updated to call PQconninfoFree.
1443  */
1446 {
1447  PQExpBufferData errorBuf;
1448  PQconninfoOption *connOptions;
1449 
1450  /* We don't actually report any errors here, but callees want a buffer */
1451  initPQExpBuffer(&errorBuf);
1452  if (PQExpBufferDataBroken(errorBuf))
1453  return NULL; /* out of memory already :-( */
1454 
1455  connOptions = conninfo_init(&errorBuf);
1456  if (connOptions != NULL)
1457  {
1458  /* pass NULL errorBuf to ignore errors */
1459  if (!conninfo_add_defaults(connOptions, NULL))
1460  {
1461  PQconninfoFree(connOptions);
1462  connOptions = NULL;
1463  }
1464  }
1465 
1466  termPQExpBuffer(&errorBuf);
1467  return connOptions;
1468 }
1469 
1470 /* ----------------
1471  * PQsetdbLogin
1472  *
1473  * establishes a connection to a postgres backend through the postmaster
1474  * at the specified host and port.
1475  *
1476  * returns a PGconn* which is needed for all subsequent libpq calls
1477  *
1478  * if the status field of the connection returned is CONNECTION_BAD,
1479  * then only the errorMessage is likely to be useful.
1480  * ----------------
1481  */
1482 PGconn *
1483 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1484  const char *pgtty, const char *dbName, const char *login,
1485  const char *pwd)
1486 {
1487  PGconn *conn;
1488 
1489  /*
1490  * Allocate memory for the conn structure
1491  */
1492  conn = makeEmptyPGconn();
1493  if (conn == NULL)
1494  return NULL;
1495 
1496  /*
1497  * If the dbName parameter contains what looks like a connection string,
1498  * parse it into conn struct using connectOptions1.
1499  */
1500  if (dbName && recognized_connection_string(dbName))
1501  {
1502  if (!connectOptions1(conn, dbName))
1503  return conn;
1504  }
1505  else
1506  {
1507  /*
1508  * Old-style path: first, parse an empty conninfo string in order to
1509  * set up the same defaults that PQconnectdb() would use.
1510  */
1511  if (!connectOptions1(conn, ""))
1512  return conn;
1513 
1514  /* Insert dbName parameter value into struct */
1515  if (dbName && dbName[0] != '\0')
1516  {
1517  if (conn->dbName)
1518  free(conn->dbName);
1519  conn->dbName = strdup(dbName);
1520  if (!conn->dbName)
1521  goto oom_error;
1522  }
1523  }
1524 
1525  /*
1526  * Insert remaining parameters into struct, overriding defaults (as well
1527  * as any conflicting data from dbName taken as a conninfo).
1528  */
1529  if (pghost && pghost[0] != '\0')
1530  {
1531  if (conn->pghost)
1532  free(conn->pghost);
1533  conn->pghost = strdup(pghost);
1534  if (!conn->pghost)
1535  goto oom_error;
1536  }
1537 
1538  if (pgport && pgport[0] != '\0')
1539  {
1540  if (conn->pgport)
1541  free(conn->pgport);
1542  conn->pgport = strdup(pgport);
1543  if (!conn->pgport)
1544  goto oom_error;
1545  }
1546 
1547  if (pgoptions && pgoptions[0] != '\0')
1548  {
1549  if (conn->pgoptions)
1550  free(conn->pgoptions);
1551  conn->pgoptions = strdup(pgoptions);
1552  if (!conn->pgoptions)
1553  goto oom_error;
1554  }
1555 
1556  if (pgtty && pgtty[0] != '\0')
1557  {
1558  if (conn->pgtty)
1559  free(conn->pgtty);
1560  conn->pgtty = strdup(pgtty);
1561  if (!conn->pgtty)
1562  goto oom_error;
1563  }
1564 
1565  if (login && login[0] != '\0')
1566  {
1567  if (conn->pguser)
1568  free(conn->pguser);
1569  conn->pguser = strdup(login);
1570  if (!conn->pguser)
1571  goto oom_error;
1572  }
1573 
1574  if (pwd && pwd[0] != '\0')
1575  {
1576  if (conn->pgpass)
1577  free(conn->pgpass);
1578  conn->pgpass = strdup(pwd);
1579  if (!conn->pgpass)
1580  goto oom_error;
1581  }
1582 
1583  /*
1584  * Compute derived options
1585  */
1586  if (!connectOptions2(conn))
1587  return conn;
1588 
1589  /*
1590  * Connect to the database
1591  */
1592  if (connectDBStart(conn))
1593  (void) connectDBComplete(conn);
1594 
1595  return conn;
1596 
1597 oom_error:
1598  conn->status = CONNECTION_BAD;
1600  libpq_gettext("out of memory\n"));
1601  return conn;
1602 }
1603 
1604 
1605 /* ----------
1606  * connectNoDelay -
1607  * Sets the TCP_NODELAY socket option.
1608  * Returns 1 if successful, 0 if not.
1609  * ----------
1610  */
1611 static int
1613 {
1614 #ifdef TCP_NODELAY
1615  int on = 1;
1616 
1617  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1618  (char *) &on,
1619  sizeof(on)) < 0)
1620  {
1621  char sebuf[PG_STRERROR_R_BUFLEN];
1622 
1624  libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1625  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1626  return 0;
1627  }
1628 #endif
1629 
1630  return 1;
1631 }
1632 
1633 /* ----------
1634  * Write currently connected IP address into host_addr (of len host_addr_len).
1635  * If unable to, set it to the empty string.
1636  * ----------
1637  */
1638 static void
1639 getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
1640 {
1641  struct sockaddr_storage *addr = &conn->raddr.addr;
1642 
1643  if (addr->ss_family == AF_INET)
1644  {
1645  if (pg_inet_net_ntop(AF_INET,
1646  &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1647  32,
1648  host_addr, host_addr_len) == NULL)
1649  host_addr[0] = '\0';
1650  }
1651 #ifdef HAVE_IPV6
1652  else if (addr->ss_family == AF_INET6)
1653  {
1654  if (pg_inet_net_ntop(AF_INET6,
1655  &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1656  128,
1657  host_addr, host_addr_len) == NULL)
1658  host_addr[0] = '\0';
1659  }
1660 #endif
1661  else
1662  host_addr[0] = '\0';
1663 }
1664 
1665 /* ----------
1666  * connectFailureMessage -
1667  * create a friendly error message on connection failure.
1668  * ----------
1669  */
1670 static void
1672 {
1673  char sebuf[PG_STRERROR_R_BUFLEN];
1674 
1675 #ifdef HAVE_UNIX_SOCKETS
1676  if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1677  {
1678  char service[NI_MAXHOST];
1679 
1680  pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1681  NULL, 0,
1682  service, sizeof(service),
1683  NI_NUMERICSERV);
1685  libpq_gettext("could not connect to server: %s\n"
1686  "\tIs the server running locally and accepting\n"
1687  "\tconnections on Unix domain socket \"%s\"?\n"),
1688  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1689  service);
1690  }
1691  else
1692 #endif /* HAVE_UNIX_SOCKETS */
1693  {
1694  char host_addr[NI_MAXHOST];
1695  const char *displayed_host;
1696  const char *displayed_port;
1697 
1698  /*
1699  * Optionally display the network address with the hostname. This is
1700  * useful to distinguish between IPv4 and IPv6 connections.
1701  */
1702  getHostaddr(conn, host_addr, NI_MAXHOST);
1703 
1704  /* To which host and port were we actually connecting? */
1705  if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
1706  displayed_host = conn->connhost[conn->whichhost].hostaddr;
1707  else
1708  displayed_host = conn->connhost[conn->whichhost].host;
1709  displayed_port = conn->connhost[conn->whichhost].port;
1710  if (displayed_port == NULL || displayed_port[0] == '\0')
1711  displayed_port = DEF_PGPORT_STR;
1712 
1713  /*
1714  * If the user did not supply an IP address using 'hostaddr', and
1715  * 'host' was missing or does not match our lookup, display the
1716  * looked-up IP address.
1717  */
1718  if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
1719  strlen(host_addr) > 0 &&
1720  strcmp(displayed_host, host_addr) != 0)
1722  libpq_gettext("could not connect to server: %s\n"
1723  "\tIs the server running on host \"%s\" (%s) and accepting\n"
1724  "\tTCP/IP connections on port %s?\n"),
1725  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1726  displayed_host, host_addr,
1727  displayed_port);
1728  else
1730  libpq_gettext("could not connect to server: %s\n"
1731  "\tIs the server running on host \"%s\" and accepting\n"
1732  "\tTCP/IP connections on port %s?\n"),
1733  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1734  displayed_host,
1735  displayed_port);
1736  }
1737 }
1738 
1739 /*
1740  * Should we use keepalives? Returns 1 if yes, 0 if no, and -1 if
1741  * conn->keepalives is set to a value which is not parseable as an
1742  * integer.
1743  */
1744 static int
1746 {
1747  char *ep;
1748  int val;
1749 
1750  if (conn->keepalives == NULL)
1751  return 1;
1752  val = strtol(conn->keepalives, &ep, 10);
1753  if (*ep)
1754  return -1;
1755  return val != 0 ? 1 : 0;
1756 }
1757 
1758 /*
1759  * Parse and try to interpret "value" as an integer value, and if successful,
1760  * store it in *result, complaining if there is any trailing garbage or an
1761  * overflow. This allows any number of leading and trailing whitespaces.
1762  */
1763 static bool
1764 parse_int_param(const char *value, int *result, PGconn *conn,
1765  const char *context)
1766 {
1767  char *end;
1768  long numval;
1769 
1770  Assert(value != NULL);
1771 
1772  *result = 0;
1773 
1774  /* strtol(3) skips leading whitespaces */
1775  errno = 0;
1776  numval = strtol(value, &end, 10);
1777 
1778  /*
1779  * If no progress was done during the parsing or an error happened, fail.
1780  * This tests properly for overflows of the result.
1781  */
1782  if (value == end || errno != 0 || numval != (int) numval)
1783  goto error;
1784 
1785  /*
1786  * Skip any trailing whitespace; if anything but whitespace remains before
1787  * the terminating character, fail
1788  */
1789  while (*end != '\0' && isspace((unsigned char) *end))
1790  end++;
1791 
1792  if (*end != '\0')
1793  goto error;
1794 
1795  *result = numval;
1796  return true;
1797 
1798 error:
1800  libpq_gettext("invalid integer value \"%s\" for connection option \"%s\"\n"),
1801  value, context);
1802  return false;
1803 }
1804 
1805 #ifndef WIN32
1806 /*
1807  * Set the keepalive idle timer.
1808  */
1809 static int
1811 {
1812  int idle;
1813 
1814  if (conn->keepalives_idle == NULL)
1815  return 1;
1816 
1817  if (!parse_int_param(conn->keepalives_idle, &idle, conn,
1818  "keepalives_idle"))
1819  return 0;
1820  if (idle < 0)
1821  idle = 0;
1822 
1823 #ifdef PG_TCP_KEEPALIVE_IDLE
1824  if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1825  (char *) &idle, sizeof(idle)) < 0)
1826  {
1827  char sebuf[PG_STRERROR_R_BUFLEN];
1828 
1830  libpq_gettext("setsockopt(%s) failed: %s\n"),
1831  PG_TCP_KEEPALIVE_IDLE_STR,
1832  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1833  return 0;
1834  }
1835 #endif
1836 
1837  return 1;
1838 }
1839 
1840 /*
1841  * Set the keepalive interval.
1842  */
1843 static int
1845 {
1846  int interval;
1847 
1848  if (conn->keepalives_interval == NULL)
1849  return 1;
1850 
1851  if (!parse_int_param(conn->keepalives_interval, &interval, conn,
1852  "keepalives_interval"))
1853  return 0;
1854  if (interval < 0)
1855  interval = 0;
1856 
1857 #ifdef TCP_KEEPINTVL
1858  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1859  (char *) &interval, sizeof(interval)) < 0)
1860  {
1861  char sebuf[PG_STRERROR_R_BUFLEN];
1862 
1864  libpq_gettext("setsockopt(%s) failed: %s\n"),
1865  "TCP_KEEPINTVL",
1866  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1867  return 0;
1868  }
1869 #endif
1870 
1871  return 1;
1872 }
1873 
1874 /*
1875  * Set the count of lost keepalive packets that will trigger a connection
1876  * break.
1877  */
1878 static int
1880 {
1881  int count;
1882 
1883  if (conn->keepalives_count == NULL)
1884  return 1;
1885 
1886  if (!parse_int_param(conn->keepalives_count, &count, conn,
1887  "keepalives_count"))
1888  return 0;
1889  if (count < 0)
1890  count = 0;
1891 
1892 #ifdef TCP_KEEPCNT
1893  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1894  (char *) &count, sizeof(count)) < 0)
1895  {
1896  char sebuf[PG_STRERROR_R_BUFLEN];
1897 
1899  libpq_gettext("setsockopt(%s) failed: %s\n"),
1900  "TCP_KEEPCNT",
1901  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1902  return 0;
1903  }
1904 #endif
1905 
1906  return 1;
1907 }
1908 #else /* WIN32 */
1909 #ifdef SIO_KEEPALIVE_VALS
1910 /*
1911  * Enable keepalives and set the keepalive values on Win32,
1912  * where they are always set in one batch.
1913  */
1914 static int
1915 setKeepalivesWin32(PGconn *conn)
1916 {
1917  struct tcp_keepalive ka;
1918  DWORD retsize;
1919  int idle = 0;
1920  int interval = 0;
1921 
1922  if (conn->keepalives_idle &&
1923  !parse_int_param(conn->keepalives_idle, &idle, conn,
1924  "keepalives_idle"))
1925  return 0;
1926  if (idle <= 0)
1927  idle = 2 * 60 * 60; /* 2 hours = default */
1928 
1929  if (conn->keepalives_interval &&
1930  !parse_int_param(conn->keepalives_interval, &interval, conn,
1931  "keepalives_interval"))
1932  return 0;
1933  if (interval <= 0)
1934  interval = 1; /* 1 second = default */
1935 
1936  ka.onoff = 1;
1937  ka.keepalivetime = idle * 1000;
1938  ka.keepaliveinterval = interval * 1000;
1939 
1940  if (WSAIoctl(conn->sock,
1941  SIO_KEEPALIVE_VALS,
1942  (LPVOID) &ka,
1943  sizeof(ka),
1944  NULL,
1945  0,
1946  &retsize,
1947  NULL,
1948  NULL)
1949  != 0)
1950  {
1952  libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1953  WSAGetLastError());
1954  return 0;
1955  }
1956  return 1;
1957 }
1958 #endif /* SIO_KEEPALIVE_VALS */
1959 #endif /* WIN32 */
1960 
1961 /*
1962  * Set the TCP user timeout.
1963  */
1964 static int
1966 {
1967  int timeout;
1968 
1969  if (conn->pgtcp_user_timeout == NULL)
1970  return 1;
1971 
1972  if (!parse_int_param(conn->pgtcp_user_timeout, &timeout, conn,
1973  "tcp_user_timeout"))
1974  return 0;
1975 
1976  if (timeout < 0)
1977  timeout = 0;
1978 
1979 #ifdef TCP_USER_TIMEOUT
1980  if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1981  (char *) &timeout, sizeof(timeout)) < 0)
1982  {
1983  char sebuf[256];
1984 
1986  libpq_gettext("setsockopt(%s) failed: %s\n"),
1987  "TCP_USER_TIMEOUT",
1988  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1989  return 0;
1990  }
1991 #endif
1992 
1993  return 1;
1994 }
1995 
1996 /* ----------
1997  * connectDBStart -
1998  * Begin the process of making a connection to the backend.
1999  *
2000  * Returns 1 if successful, 0 if not.
2001  * ----------
2002  */
2003 static int
2005 {
2006  if (!conn)
2007  return 0;
2008 
2009  if (!conn->options_valid)
2010  goto connect_errReturn;
2011 
2012  /*
2013  * Check for bad linking to backend-internal versions of src/common
2014  * functions (see comments in link-canary.c for the reason we need this).
2015  * Nobody but developers should see this message, so we don't bother
2016  * translating it.
2017  */
2019  {
2021  "libpq is incorrectly linked to backend functions\n");
2022  goto connect_errReturn;
2023  }
2024 
2025  /* Ensure our buffers are empty */
2026  conn->inStart = conn->inCursor = conn->inEnd = 0;
2027  conn->outCount = 0;
2028 
2029  /*
2030  * Ensure errorMessage is empty, too. PQconnectPoll will append messages
2031  * to it in the process of scanning for a working server. Thus, if we
2032  * fail to connect to multiple hosts, the final error message will include
2033  * details about each failure.
2034  */
2036 
2037  /*
2038  * Set up to try to connect to the first host. (Setting whichhost = -1 is
2039  * a bit of a cheat, but PQconnectPoll will advance it to 0 before
2040  * anything else looks at it.)
2041  */
2042  conn->whichhost = -1;
2043  conn->try_next_addr = false;
2044  conn->try_next_host = true;
2045  conn->status = CONNECTION_NEEDED;
2046 
2047  /*
2048  * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
2049  * so that it can easily be re-executed if needed again during the
2050  * asynchronous startup process. However, we must run it once here,
2051  * because callers expect a success return from this routine to mean that
2052  * we are in PGRES_POLLING_WRITING connection state.
2053  */
2054  if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
2055  return 1;
2056 
2057 connect_errReturn:
2058 
2059  /*
2060  * If we managed to open a socket, close it immediately rather than
2061  * waiting till PQfinish. (The application cannot have gotten the socket
2062  * from PQsocket yet, so this doesn't risk breaking anything.)
2063  */
2064  pqDropConnection(conn, true);
2065  conn->status = CONNECTION_BAD;
2066  return 0;
2067 }
2068 
2069 
2070 /*
2071  * connectDBComplete
2072  *
2073  * Block and complete a connection.
2074  *
2075  * Returns 1 on success, 0 on failure.
2076  */
2077 static int
2079 {
2081  time_t finish_time = ((time_t) -1);
2082  int timeout = 0;
2083  int last_whichhost = -2; /* certainly different from whichhost */
2084  struct addrinfo *last_addr_cur = NULL;
2085 
2086  if (conn == NULL || conn->status == CONNECTION_BAD)
2087  return 0;
2088 
2089  /*
2090  * Set up a time limit, if connect_timeout isn't zero.
2091  */
2092  if (conn->connect_timeout != NULL)
2093  {
2094  if (!parse_int_param(conn->connect_timeout, &timeout, conn,
2095  "connect_timeout"))
2096  {
2097  /* mark the connection as bad to report the parsing failure */
2098  conn->status = CONNECTION_BAD;
2099  return 0;
2100  }
2101 
2102  if (timeout > 0)
2103  {
2104  /*
2105  * Rounding could cause connection to fail unexpectedly quickly;
2106  * to prevent possibly waiting hardly-at-all, insist on at least
2107  * two seconds.
2108  */
2109  if (timeout < 2)
2110  timeout = 2;
2111  }
2112  else /* negative means 0 */
2113  timeout = 0;
2114  }
2115 
2116  for (;;)
2117  {
2118  int ret = 0;
2119 
2120  /*
2121  * (Re)start the connect_timeout timer if it's active and we are
2122  * considering a different host than we were last time through. If
2123  * we've already succeeded, though, needn't recalculate.
2124  */
2125  if (flag != PGRES_POLLING_OK &&
2126  timeout > 0 &&
2127  (conn->whichhost != last_whichhost ||
2128  conn->addr_cur != last_addr_cur))
2129  {
2130  finish_time = time(NULL) + timeout;
2131  last_whichhost = conn->whichhost;
2132  last_addr_cur = conn->addr_cur;
2133  }
2134 
2135  /*
2136  * Wait, if necessary. Note that the initial state (just after
2137  * PQconnectStart) is to wait for the socket to select for writing.
2138  */
2139  switch (flag)
2140  {
2141  case PGRES_POLLING_OK:
2142 
2143  /*
2144  * Reset stored error messages since we now have a working
2145  * connection
2146  */
2148  return 1; /* success! */
2149 
2150  case PGRES_POLLING_READING:
2151  ret = pqWaitTimed(1, 0, conn, finish_time);
2152  if (ret == -1)
2153  {
2154  /* hard failure, eg select() problem, aborts everything */
2155  conn->status = CONNECTION_BAD;
2156  return 0;
2157  }
2158  break;
2159 
2160  case PGRES_POLLING_WRITING:
2161  ret = pqWaitTimed(0, 1, conn, finish_time);
2162  if (ret == -1)
2163  {
2164  /* hard failure, eg select() problem, aborts everything */
2165  conn->status = CONNECTION_BAD;
2166  return 0;
2167  }
2168  break;
2169 
2170  default:
2171  /* Just in case we failed to set it in PQconnectPoll */
2172  conn->status = CONNECTION_BAD;
2173  return 0;
2174  }
2175 
2176  if (ret == 1) /* connect_timeout elapsed */
2177  {
2178  /*
2179  * Give up on current server/address, try the next one.
2180  */
2181  conn->try_next_addr = true;
2182  conn->status = CONNECTION_NEEDED;
2183  }
2184 
2185  /*
2186  * Now try to advance the state machine.
2187  */
2188  flag = PQconnectPoll(conn);
2189  }
2190 }
2191 
2192 /*
2193  * This subroutine saves conn->errorMessage, which will be restored back by
2194  * restoreErrorMessage subroutine. Returns false on OOM failure.
2195  */
2196 static bool
2198 {
2199  initPQExpBuffer(savedMessage);
2200  appendPQExpBufferStr(savedMessage,
2201  conn->errorMessage.data);
2202  if (PQExpBufferBroken(savedMessage))
2203  {
2205  libpq_gettext("out of memory\n"));
2206  return false;
2207  }
2208  /* Clear whatever is in errorMessage now */
2210  return true;
2211 }
2212 
2213 /*
2214  * Restores saved error messages back to conn->errorMessage, prepending them
2215  * to whatever is in conn->errorMessage already. (This does the right thing
2216  * if anything's been added to conn->errorMessage since saveErrorMessage.)
2217  */
2218 static void
2220 {
2221  appendPQExpBufferStr(savedMessage, conn->errorMessage.data);
2223  appendPQExpBufferStr(&conn->errorMessage, savedMessage->data);
2224  /* If any step above hit OOM, just report that */
2225  if (PQExpBufferBroken(savedMessage) ||
2228  libpq_gettext("out of memory\n"));
2229  termPQExpBuffer(savedMessage);
2230 }
2231 
2232 /* ----------------
2233  * PQconnectPoll
2234  *
2235  * Poll an asynchronous connection.
2236  *
2237  * Returns a PostgresPollingStatusType.
2238  * Before calling this function, use select(2) to determine when data
2239  * has arrived..
2240  *
2241  * You must call PQfinish whether or not this fails.
2242  *
2243  * This function and PQconnectStart are intended to allow connections to be
2244  * made without blocking the execution of your program on remote I/O. However,
2245  * there are a number of caveats:
2246  *
2247  * o If you call PQtrace, ensure that the stream object into which you trace
2248  * will not block.
2249  * o If you do not supply an IP address for the remote host (i.e. you
2250  * supply a host name instead) then PQconnectStart will block on
2251  * gethostbyname. You will be fine if using Unix sockets (i.e. by
2252  * supplying neither a host name nor a host address).
2253  * o If your backend wants to use Kerberos authentication then you must
2254  * supply both a host name and a host address, otherwise this function
2255  * may block on gethostname.
2256  *
2257  * ----------------
2258  */
2261 {
2262  bool reset_connection_state_machine = false;
2263  bool need_new_connection = false;
2264  PGresult *res;
2265  char sebuf[PG_STRERROR_R_BUFLEN];
2266  int optval;
2267  PQExpBufferData savedMessage;
2268 
2269  if (conn == NULL)
2270  return PGRES_POLLING_FAILED;
2271 
2272  /* Get the new data */
2273  switch (conn->status)
2274  {
2275  /*
2276  * We really shouldn't have been polled in these two cases, but we
2277  * can handle it.
2278  */
2279  case CONNECTION_BAD:
2280  return PGRES_POLLING_FAILED;
2281  case CONNECTION_OK:
2282  return PGRES_POLLING_OK;
2283 
2284  /* These are reading states */
2286  case CONNECTION_AUTH_OK:
2287  {
2288  /* Load waiting data */
2289  int n = pqReadData(conn);
2290 
2291  if (n < 0)
2292  goto error_return;
2293  if (n == 0)
2294  return PGRES_POLLING_READING;
2295 
2296  break;
2297  }
2298 
2299  /* These are writing states, so we just proceed. */
2300  case CONNECTION_STARTED:
2301  case CONNECTION_MADE:
2302  break;
2303 
2304  /* We allow pqSetenvPoll to decide whether to proceed. */
2305  case CONNECTION_SETENV:
2306  break;
2307 
2308  /* Special cases: proceed without waiting. */
2310  case CONNECTION_NEEDED:
2312  case CONNECTION_CONSUME:
2314  break;
2315 
2316  default:
2318  libpq_gettext("invalid connection state, probably indicative of memory corruption\n"));
2319  goto error_return;
2320  }
2321 
2322 
2323 keep_going: /* We will come back to here until there is
2324  * nothing left to do. */
2325 
2326  /* Time to advance to next address, or next host if no more addresses? */
2327  if (conn->try_next_addr)
2328  {
2329  if (conn->addr_cur && conn->addr_cur->ai_next)
2330  {
2331  conn->addr_cur = conn->addr_cur->ai_next;
2332  reset_connection_state_machine = true;
2333  }
2334  else
2335  conn->try_next_host = true;
2336  conn->try_next_addr = false;
2337  }
2338 
2339  /* Time to advance to next connhost[] entry? */
2340  if (conn->try_next_host)
2341  {
2342  pg_conn_host *ch;
2343  struct addrinfo hint;
2344  int thisport;
2345  int ret;
2346  char portstr[MAXPGPATH];
2347 
2348  if (conn->whichhost + 1 >= conn->nconnhost)
2349  {
2350  /*
2351  * Oops, no more hosts. An appropriate error message is already
2352  * set up, so just set the right status.
2353  */
2354  goto error_return;
2355  }
2356  conn->whichhost++;
2357 
2358  /* Drop any address info for previous host */
2359  release_conn_addrinfo(conn);
2360 
2361  /*
2362  * Look up info for the new host. On failure, log the problem in
2363  * conn->errorMessage, then loop around to try the next host. (Note
2364  * we don't clear try_next_host until we've succeeded.)
2365  */
2366  ch = &conn->connhost[conn->whichhost];
2367 
2368  /* Initialize hint structure */
2369  MemSet(&hint, 0, sizeof(hint));
2370  hint.ai_socktype = SOCK_STREAM;
2371  conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2372 
2373  /* Figure out the port number we're going to use. */
2374  if (ch->port == NULL || ch->port[0] == '\0')
2375  thisport = DEF_PGPORT;
2376  else
2377  {
2378  if (!parse_int_param(ch->port, &thisport, conn, "port"))
2379  goto error_return;
2380 
2381  if (thisport < 1 || thisport > 65535)
2382  {
2384  libpq_gettext("invalid port number: \"%s\"\n"),
2385  ch->port);
2386  goto keep_going;
2387  }
2388  }
2389  snprintf(portstr, sizeof(portstr), "%d", thisport);
2390 
2391  /* Use pg_getaddrinfo_all() to resolve the address */
2392  switch (ch->type)
2393  {
2394  case CHT_HOST_NAME:
2395  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2396  &conn->addrlist);
2397  if (ret || !conn->addrlist)
2398  {
2400  libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
2401  ch->host, gai_strerror(ret));
2402  goto keep_going;
2403  }
2404  break;
2405 
2406  case CHT_HOST_ADDRESS:
2407  hint.ai_flags = AI_NUMERICHOST;
2408  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2409  &conn->addrlist);
2410  if (ret || !conn->addrlist)
2411  {
2413  libpq_gettext("could not parse network address \"%s\": %s\n"),
2414  ch->hostaddr, gai_strerror(ret));
2415  goto keep_going;
2416  }
2417  break;
2418 
2419  case CHT_UNIX_SOCKET:
2420 #ifdef HAVE_UNIX_SOCKETS
2421  conn->addrlist_family = hint.ai_family = AF_UNIX;
2422  UNIXSOCK_PATH(portstr, thisport, ch->host);
2423  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2424  {
2426  libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
2427  portstr,
2428  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2429  goto keep_going;
2430  }
2431 
2432  /*
2433  * NULL hostname tells pg_getaddrinfo_all to parse the service
2434  * name as a Unix-domain socket path.
2435  */
2436  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2437  &conn->addrlist);
2438  if (ret || !conn->addrlist)
2439  {
2441  libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
2442  portstr, gai_strerror(ret));
2443  goto keep_going;
2444  }
2445 #else
2446  Assert(false);
2447 #endif
2448  break;
2449  }
2450 
2451  /* OK, scan this addrlist for a working server address */
2452  conn->addr_cur = conn->addrlist;
2453  reset_connection_state_machine = true;
2454  conn->try_next_host = false;
2455  }
2456 
2457  /* Reset connection state machine? */
2458  if (reset_connection_state_machine)
2459  {
2460  /*
2461  * (Re) initialize our connection control variables for a set of
2462  * connection attempts to a single server address. These variables
2463  * must persist across individual connection attempts, but we must
2464  * reset them when we start to consider a new server.
2465  */
2466  conn->pversion = PG_PROTOCOL(3, 0);
2467  conn->send_appname = true;
2468 #ifdef USE_SSL
2469  /* initialize these values based on SSL mode */
2470  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2471  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2472 #endif
2473 #ifdef ENABLE_GSS
2474  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2475 #endif
2476 
2477  reset_connection_state_machine = false;
2478  need_new_connection = true;
2479  }
2480 
2481  /* Force a new connection (perhaps to the same server as before)? */
2482  if (need_new_connection)
2483  {
2484  /* Drop any existing connection */
2485  pqDropConnection(conn, true);
2486 
2487  /* Reset all state obtained from old server */
2488  pqDropServerData(conn);
2489 
2490  /* Drop any PGresult we might have, too */
2491  conn->asyncStatus = PGASYNC_IDLE;
2492  conn->xactStatus = PQTRANS_IDLE;
2493  pqClearAsyncResult(conn);
2494 
2495  /* Reset conn->status to put the state machine in the right state */
2496  conn->status = CONNECTION_NEEDED;
2497 
2498  need_new_connection = false;
2499  }
2500 
2501  /* Now try to advance the state machine for this connection */
2502  switch (conn->status)
2503  {
2504  case CONNECTION_NEEDED:
2505  {
2506  /*
2507  * Try to initiate a connection to one of the addresses
2508  * returned by pg_getaddrinfo_all(). conn->addr_cur is the
2509  * next one to try.
2510  *
2511  * The extra level of braces here is historical. It's not
2512  * worth reindenting this whole switch case to remove 'em.
2513  */
2514  {
2515  struct addrinfo *addr_cur = conn->addr_cur;
2516  char host_addr[NI_MAXHOST];
2517 
2518  /*
2519  * Advance to next possible host, if we've tried all of
2520  * the addresses for the current host.
2521  */
2522  if (addr_cur == NULL)
2523  {
2524  conn->try_next_host = true;
2525  goto keep_going;
2526  }
2527 
2528  /* Remember current address for possible error msg */
2529  memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2530  addr_cur->ai_addrlen);
2531  conn->raddr.salen = addr_cur->ai_addrlen;
2532 
2533  /* set connip */
2534  if (conn->connip != NULL)
2535  {
2536  free(conn->connip);
2537  conn->connip = NULL;
2538  }
2539 
2540  getHostaddr(conn, host_addr, NI_MAXHOST);
2541  if (strlen(host_addr) > 0)
2542  conn->connip = strdup(host_addr);
2543 
2544  /*
2545  * purposely ignore strdup failure; not a big problem if
2546  * it fails anyway.
2547  */
2548 
2549  conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2550  if (conn->sock == PGINVALID_SOCKET)
2551  {
2552  /*
2553  * Silently ignore socket() failure if we have more
2554  * addresses to try; this reduces useless chatter in
2555  * cases where the address list includes both IPv4 and
2556  * IPv6 but kernel only accepts one family.
2557  */
2558  if (addr_cur->ai_next != NULL ||
2559  conn->whichhost + 1 < conn->nconnhost)
2560  {
2561  conn->try_next_addr = true;
2562  goto keep_going;
2563  }
2565  libpq_gettext("could not create socket: %s\n"),
2566  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2567  goto error_return;
2568  }
2569 
2570  /*
2571  * Select socket options: no delay of outgoing data for
2572  * TCP sockets, nonblock mode, close-on-exec. Try the
2573  * next address if any of this fails.
2574  */
2575  if (!IS_AF_UNIX(addr_cur->ai_family))
2576  {
2577  if (!connectNoDelay(conn))
2578  {
2579  /* error message already created */
2580  conn->try_next_addr = true;
2581  goto keep_going;
2582  }
2583  }
2584  if (!pg_set_noblock(conn->sock))
2585  {
2587  libpq_gettext("could not set socket to nonblocking mode: %s\n"),
2588  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2589  conn->try_next_addr = true;
2590  goto keep_going;
2591  }
2592 
2593 #ifdef F_SETFD
2594  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2595  {
2597  libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
2598  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2599  conn->try_next_addr = true;
2600  goto keep_going;
2601  }
2602 #endif /* F_SETFD */
2603 
2604  if (!IS_AF_UNIX(addr_cur->ai_family))
2605  {
2606 #ifndef WIN32
2607  int on = 1;
2608 #endif
2609  int usekeepalives = useKeepalives(conn);
2610  int err = 0;
2611 
2612  if (usekeepalives < 0)
2613  {
2615  libpq_gettext("keepalives parameter must be an integer\n"));
2616  err = 1;
2617  }
2618  else if (usekeepalives == 0)
2619  {
2620  /* Do nothing */
2621  }
2622 #ifndef WIN32
2623  else if (setsockopt(conn->sock,
2624  SOL_SOCKET, SO_KEEPALIVE,
2625  (char *) &on, sizeof(on)) < 0)
2626  {
2628  libpq_gettext("setsockopt(%s) failed: %s\n"),
2629  "SO_KEEPALIVE",
2630  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2631  err = 1;
2632  }
2633  else if (!setKeepalivesIdle(conn)
2634  || !setKeepalivesInterval(conn)
2635  || !setKeepalivesCount(conn))
2636  err = 1;
2637 #else /* WIN32 */
2638 #ifdef SIO_KEEPALIVE_VALS
2639  else if (!setKeepalivesWin32(conn))
2640  err = 1;
2641 #endif /* SIO_KEEPALIVE_VALS */
2642 #endif /* WIN32 */
2643  else if (!setTCPUserTimeout(conn))
2644  err = 1;
2645 
2646  if (err)
2647  {
2648  conn->try_next_addr = true;
2649  goto keep_going;
2650  }
2651  }
2652 
2653  /*----------
2654  * We have three methods of blocking SIGPIPE during
2655  * send() calls to this socket:
2656  *
2657  * - setsockopt(sock, SO_NOSIGPIPE)
2658  * - send(sock, ..., MSG_NOSIGNAL)
2659  * - setting the signal mask to SIG_IGN during send()
2660  *
2661  * The third method requires three syscalls per send,
2662  * so we prefer either of the first two, but they are
2663  * less portable. The state is tracked in the following
2664  * members of PGconn:
2665  *
2666  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
2667  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
2668  *
2669  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2670  * and we're done. Otherwise, set sigpipe_flag so that
2671  * we will try MSG_NOSIGNAL on sends. If we get an error
2672  * with MSG_NOSIGNAL, we'll clear that flag and revert to
2673  * signal masking.
2674  *----------
2675  */
2676  conn->sigpipe_so = false;
2677 #ifdef MSG_NOSIGNAL
2678  conn->sigpipe_flag = true;
2679 #else
2680  conn->sigpipe_flag = false;
2681 #endif /* MSG_NOSIGNAL */
2682 
2683 #ifdef SO_NOSIGPIPE
2684  optval = 1;
2685  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2686  (char *) &optval, sizeof(optval)) == 0)
2687  {
2688  conn->sigpipe_so = true;
2689  conn->sigpipe_flag = false;
2690  }
2691 #endif /* SO_NOSIGPIPE */
2692 
2693  /*
2694  * Start/make connection. This should not block, since we
2695  * are in nonblock mode. If it does, well, too bad.
2696  */
2697  if (connect(conn->sock, addr_cur->ai_addr,
2698  addr_cur->ai_addrlen) < 0)
2699  {
2700  if (SOCK_ERRNO == EINPROGRESS ||
2701 #ifdef WIN32
2702  SOCK_ERRNO == EWOULDBLOCK ||
2703 #endif
2704  SOCK_ERRNO == EINTR)
2705  {
2706  /*
2707  * This is fine - we're in non-blocking mode, and
2708  * the connection is in progress. Tell caller to
2709  * wait for write-ready on socket.
2710  */
2711  conn->status = CONNECTION_STARTED;
2712  return PGRES_POLLING_WRITING;
2713  }
2714  /* otherwise, trouble */
2715  }
2716  else
2717  {
2718  /*
2719  * Hm, we're connected already --- seems the "nonblock
2720  * connection" wasn't. Advance the state machine and
2721  * go do the next stuff.
2722  */
2723  conn->status = CONNECTION_STARTED;
2724  goto keep_going;
2725  }
2726 
2727  /*
2728  * This connection failed. Add the error report to
2729  * conn->errorMessage, then try the next address if any.
2730  */
2732  conn->try_next_addr = true;
2733  goto keep_going;
2734  }
2735  }
2736 
2737  case CONNECTION_STARTED:
2738  {
2739  ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2740 
2741  /*
2742  * Write ready, since we've made it here, so the connection
2743  * has been made ... or has failed.
2744  */
2745 
2746  /*
2747  * Now check (using getsockopt) that there is not an error
2748  * state waiting for us on the socket.
2749  */
2750 
2751  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2752  (char *) &optval, &optlen) == -1)
2753  {
2755  libpq_gettext("could not get socket error status: %s\n"),
2756  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2757  goto error_return;
2758  }
2759  else if (optval != 0)
2760  {
2761  /*
2762  * When using a nonblocking connect, we will typically see
2763  * connect failures at this point, so provide a friendly
2764  * error message.
2765  */
2766  connectFailureMessage(conn, optval);
2767 
2768  /*
2769  * Try the next address if any, just as in the case where
2770  * connect() returned failure immediately.
2771  */
2772  conn->try_next_addr = true;
2773  goto keep_going;
2774  }
2775 
2776  /* Fill in the client address */
2777  conn->laddr.salen = sizeof(conn->laddr.addr);
2778  if (getsockname(conn->sock,
2779  (struct sockaddr *) &conn->laddr.addr,
2780  &conn->laddr.salen) < 0)
2781  {
2783  libpq_gettext("could not get client address from socket: %s\n"),
2784  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2785  goto error_return;
2786  }
2787 
2788  /*
2789  * Make sure we can write before advancing to next step.
2790  */
2791  conn->status = CONNECTION_MADE;
2792  return PGRES_POLLING_WRITING;
2793  }
2794 
2795  case CONNECTION_MADE:
2796  {
2797  char *startpacket;
2798  int packetlen;
2799 
2800  /*
2801  * Implement requirepeer check, if requested and it's a
2802  * Unix-domain socket.
2803  */
2804  if (conn->requirepeer && conn->requirepeer[0] &&
2805  IS_AF_UNIX(conn->raddr.addr.ss_family))
2806  {
2807 #ifndef WIN32
2808  char pwdbuf[BUFSIZ];
2809  struct passwd pass_buf;
2810  struct passwd *pass;
2811  int passerr;
2812 #endif
2813  uid_t uid;
2814  gid_t gid;
2815 
2816  errno = 0;
2817  if (getpeereid(conn->sock, &uid, &gid) != 0)
2818  {
2819  /*
2820  * Provide special error message if getpeereid is a
2821  * stub
2822  */
2823  if (errno == ENOSYS)
2825  libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2826  else
2828  libpq_gettext("could not get peer credentials: %s\n"),
2829  strerror_r(errno, sebuf, sizeof(sebuf)));
2830  goto error_return;
2831  }
2832 
2833 #ifndef WIN32
2834  passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2835  if (pass == NULL)
2836  {
2837  if (passerr != 0)
2839  libpq_gettext("could not look up local user ID %d: %s\n"),
2840  (int) uid,
2841  strerror_r(passerr, sebuf, sizeof(sebuf)));
2842  else
2844  libpq_gettext("local user with ID %d does not exist\n"),
2845  (int) uid);
2846  goto error_return;
2847  }
2848 
2849  if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2850  {
2852  libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2853  conn->requirepeer, pass->pw_name);
2854  goto error_return;
2855  }
2856 #else /* WIN32 */
2857  /* should have failed with ENOSYS above */
2858  Assert(false);
2859 #endif /* WIN32 */
2860  }
2861 
2862  if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2863  {
2864  /* Don't request SSL or GSSAPI over Unix sockets */
2865 #ifdef USE_SSL
2866  conn->allow_ssl_try = false;
2867 #endif
2868 #ifdef ENABLE_GSS
2869  conn->try_gss = false;
2870 #endif
2871  }
2872 
2873 #ifdef ENABLE_GSS
2874 
2875  /*
2876  * If GSSAPI encryption is enabled, then call
2877  * pg_GSS_have_cred_cache() which will return true if we can
2878  * acquire credentials (and give us a handle to use in
2879  * conn->gcred), and then send a packet to the server asking
2880  * for GSSAPI Encryption (and skip past SSL negotiation and
2881  * regular startup below).
2882  */
2883  if (conn->try_gss && !conn->gctx)
2884  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
2885  if (conn->try_gss && !conn->gctx)
2886  {
2888 
2889  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2890  {
2892  libpq_gettext("could not send GSSAPI negotiation packet: %s\n"),
2893  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2894  goto error_return;
2895  }
2896 
2897  /* Ok, wait for response */
2899  return PGRES_POLLING_READING;
2900  }
2901  else if (!conn->gctx && conn->gssencmode[0] == 'r')
2902  {
2904  libpq_gettext("GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n"));
2905  goto error_return;
2906  }
2907 #endif
2908 
2909 #ifdef USE_SSL
2910 
2911  /*
2912  * If SSL is enabled and we haven't already got it running,
2913  * request it instead of sending the startup message.
2914  */
2915  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2916  !conn->ssl_in_use)
2917  {
2918  ProtocolVersion pv;
2919 
2920  /*
2921  * Send the SSL request packet.
2922  *
2923  * Theoretically, this could block, but it really
2924  * shouldn't since we only got here if the socket is
2925  * write-ready.
2926  */
2928  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2929  {
2931  libpq_gettext("could not send SSL negotiation packet: %s\n"),
2932  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2933  goto error_return;
2934  }
2935  /* Ok, wait for response */
2937  return PGRES_POLLING_READING;
2938  }
2939 #endif /* USE_SSL */
2940 
2941  /*
2942  * Build the startup packet.
2943  */
2944  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2945  startpacket = pqBuildStartupPacket3(conn, &packetlen,
2946  EnvironmentOptions);
2947  else
2948  startpacket = pqBuildStartupPacket2(conn, &packetlen,
2949  EnvironmentOptions);
2950  if (!startpacket)
2951  {
2952  /*
2953  * will not appendbuffer here, since it's likely to also
2954  * run out of memory
2955  */
2957  libpq_gettext("out of memory\n"));
2958  goto error_return;
2959  }
2960 
2961  /*
2962  * Send the startup packet.
2963  *
2964  * Theoretically, this could block, but it really shouldn't
2965  * since we only got here if the socket is write-ready.
2966  */
2967  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2968  {
2970  libpq_gettext("could not send startup packet: %s\n"),
2971  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2972  free(startpacket);
2973  goto error_return;
2974  }
2975 
2976  free(startpacket);
2977 
2979  return PGRES_POLLING_READING;
2980  }
2981 
2982  /*
2983  * Handle SSL negotiation: wait for postmaster messages and
2984  * respond as necessary.
2985  */
2987  {
2988 #ifdef USE_SSL
2989  PostgresPollingStatusType pollres;
2990 
2991  /*
2992  * On first time through, get the postmaster's response to our
2993  * SSL negotiation packet.
2994  */
2995  if (!conn->ssl_in_use)
2996  {
2997  /*
2998  * We use pqReadData here since it has the logic to
2999  * distinguish no-data-yet from connection closure. Since
3000  * conn->ssl isn't set, a plain recv() will occur.
3001  */
3002  char SSLok;
3003  int rdresult;
3004 
3005  rdresult = pqReadData(conn);
3006  if (rdresult < 0)
3007  {
3008  /* errorMessage is already filled in */
3009  goto error_return;
3010  }
3011  if (rdresult == 0)
3012  {
3013  /* caller failed to wait for data */
3014  return PGRES_POLLING_READING;
3015  }
3016  if (pqGetc(&SSLok, conn) < 0)
3017  {
3018  /* should not happen really */
3019  return PGRES_POLLING_READING;
3020  }
3021  if (SSLok == 'S')
3022  {
3023  /* mark byte consumed */
3024  conn->inStart = conn->inCursor;
3025  /* Set up global SSL state if required */
3026  if (pqsecure_initialize(conn) != 0)
3027  goto error_return;
3028  }
3029  else if (SSLok == 'N')
3030  {
3031  /* mark byte consumed */
3032  conn->inStart = conn->inCursor;
3033  /* OK to do without SSL? */
3034  if (conn->sslmode[0] == 'r' || /* "require" */
3035  conn->sslmode[0] == 'v') /* "verify-ca" or
3036  * "verify-full" */
3037  {
3038  /* Require SSL, but server does not want it */
3040  libpq_gettext("server does not support SSL, but SSL was required\n"));
3041  goto error_return;
3042  }
3043  /* Otherwise, proceed with normal startup */
3044  conn->allow_ssl_try = false;
3045  conn->status = CONNECTION_MADE;
3046  return PGRES_POLLING_WRITING;
3047  }
3048  else if (SSLok == 'E')
3049  {
3050  /*
3051  * Server failure of some sort, such as failure to
3052  * fork a backend process. We need to process and
3053  * report the error message, which might be formatted
3054  * according to either protocol 2 or protocol 3.
3055  * Rather than duplicate the code for that, we flip
3056  * into AWAITING_RESPONSE state and let the code there
3057  * deal with it. Note we have *not* consumed the "E"
3058  * byte here.
3059  */
3061  goto keep_going;
3062  }
3063  else
3064  {
3066  libpq_gettext("received invalid response to SSL negotiation: %c\n"),
3067  SSLok);
3068  goto error_return;
3069  }
3070  }
3071 
3072  /*
3073  * Begin or continue the SSL negotiation process.
3074  */
3075  pollres = pqsecure_open_client(conn);
3076  if (pollres == PGRES_POLLING_OK)
3077  {
3078  /* SSL handshake done, ready to send startup packet */
3079  conn->status = CONNECTION_MADE;
3080  return PGRES_POLLING_WRITING;
3081  }
3082  if (pollres == PGRES_POLLING_FAILED)
3083  {
3084  /*
3085  * Failed ... if sslmode is "prefer" then do a non-SSL
3086  * retry
3087  */
3088  if (conn->sslmode[0] == 'p' /* "prefer" */
3089  && conn->allow_ssl_try /* redundant? */
3090  && !conn->wait_ssl_try) /* redundant? */
3091  {
3092  /* only retry once */
3093  conn->allow_ssl_try = false;
3094  need_new_connection = true;
3095  goto keep_going;
3096  }
3097  /* Else it's a hard failure */
3098  goto error_return;
3099  }
3100  /* Else, return POLLING_READING or POLLING_WRITING status */
3101  return pollres;
3102 #else /* !USE_SSL */
3103  /* can't get here */
3104  goto error_return;
3105 #endif /* USE_SSL */
3106  }
3107 
3109  {
3110 #ifdef ENABLE_GSS
3111  PostgresPollingStatusType pollres;
3112 
3113  /*
3114  * If we haven't yet, get the postmaster's response to our
3115  * negotiation packet
3116  */
3117  if (conn->try_gss && !conn->gctx)
3118  {
3119  char gss_ok;
3120  int rdresult = pqReadData(conn);
3121 
3122  if (rdresult < 0)
3123  /* pqReadData fills in error message */
3124  goto error_return;
3125  else if (rdresult == 0)
3126  /* caller failed to wait for data */
3127  return PGRES_POLLING_READING;
3128  if (pqGetc(&gss_ok, conn) < 0)
3129  /* shouldn't happen... */
3130  return PGRES_POLLING_READING;
3131 
3132  if (gss_ok == 'E')
3133  {
3134  /*
3135  * Server failure of some sort. Assume it's a
3136  * protocol version support failure, and let's see if
3137  * we can't recover (if it's not, we'll get a better
3138  * error message on retry). Server gets fussy if we
3139  * don't hang up the socket, though.
3140  */
3141  conn->try_gss = false;
3142  pqDropConnection(conn, true);
3143  conn->status = CONNECTION_NEEDED;
3144  goto keep_going;
3145  }
3146 
3147  /* mark byte consumed */
3148  conn->inStart = conn->inCursor;
3149 
3150  if (gss_ok == 'N')
3151  {
3152  /* Server doesn't want GSSAPI; fall back if we can */
3153  if (conn->gssencmode[0] == 'r')
3154  {
3156  libpq_gettext("server doesn't support GSSAPI encryption, but it was required\n"));
3157  goto error_return;
3158  }
3159 
3160  conn->try_gss = false;
3161  conn->status = CONNECTION_MADE;
3162  return PGRES_POLLING_WRITING;
3163  }
3164  else if (gss_ok != 'G')
3165  {
3167  libpq_gettext("received invalid response to GSSAPI negotiation: %c\n"),
3168  gss_ok);
3169  goto error_return;
3170  }
3171  }
3172 
3173  /* Begin or continue GSSAPI negotiation */
3174  pollres = pqsecure_open_gss(conn);
3175  if (pollres == PGRES_POLLING_OK)
3176  {
3177  /* All set for startup packet */
3178  conn->status = CONNECTION_MADE;
3179  return PGRES_POLLING_WRITING;
3180  }
3181  else if (pollres == PGRES_POLLING_FAILED &&
3182  conn->gssencmode[0] == 'p')
3183  {
3184  /*
3185  * We failed, but we can retry on "prefer". Have to drop
3186  * the current connection to do so, though.
3187  */
3188  conn->try_gss = false;
3189  pqDropConnection(conn, true);
3190  conn->status = CONNECTION_NEEDED;
3191  goto keep_going;
3192  }
3193  return pollres;
3194 #else /* !ENABLE_GSS */
3195  /* unreachable */
3196  goto error_return;
3197 #endif /* ENABLE_GSS */
3198  }
3199 
3200  /*
3201  * Handle authentication exchange: wait for postmaster messages
3202  * and respond as necessary.
3203  */
3205  {
3206  char beresp;
3207  int msgLength;
3208  int avail;
3209  AuthRequest areq;
3210  int res;
3211 
3212  /*
3213  * Scan the message from current point (note that if we find
3214  * the message is incomplete, we will return without advancing
3215  * inStart, and resume here next time).
3216  */
3217  conn->inCursor = conn->inStart;
3218 
3219  /* Read type byte */
3220  if (pqGetc(&beresp, conn))
3221  {
3222  /* We'll come back when there is more data */
3223  return PGRES_POLLING_READING;
3224  }
3225 
3226  /*
3227  * Validate message type: we expect only an authentication
3228  * request or an error here. Anything else probably means
3229  * it's not Postgres on the other end at all.
3230  */
3231  if (!(beresp == 'R' || beresp == 'E'))
3232  {
3234  libpq_gettext("expected authentication request from server, but received %c\n"),
3235  beresp);
3236  goto error_return;
3237  }
3238 
3239  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3240  {
3241  /* Read message length word */
3242  if (pqGetInt(&msgLength, 4, conn))
3243  {
3244  /* We'll come back when there is more data */
3245  return PGRES_POLLING_READING;
3246  }
3247  }
3248  else
3249  {
3250  /* Set phony message length to disable checks below */
3251  msgLength = 8;
3252  }
3253 
3254  /*
3255  * Try to validate message length before using it.
3256  * Authentication requests can't be very large, although GSS
3257  * auth requests may not be that small. Errors can be a
3258  * little larger, but not huge. If we see a large apparent
3259  * length in an error, it means we're really talking to a
3260  * pre-3.0-protocol server; cope.
3261  */
3262  if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
3263  {
3265  libpq_gettext("expected authentication request from server, but received %c\n"),
3266  beresp);
3267  goto error_return;
3268  }
3269 
3270  if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
3271  {
3272  /* Handle error from a pre-3.0 server */
3273  conn->inCursor = conn->inStart + 1; /* reread data */
3274  if (pqGets_append(&conn->errorMessage, conn))
3275  {
3276  /* We'll come back when there is more data */
3277  return PGRES_POLLING_READING;
3278  }
3279  /* OK, we read the message; mark data consumed */
3280  conn->inStart = conn->inCursor;
3281 
3282  /*
3283  * The postmaster typically won't end its message with a
3284  * newline, so add one to conform to libpq conventions.
3285  */
3286  appendPQExpBufferChar(&conn->errorMessage, '\n');
3287 
3288  /*
3289  * If we tried to open the connection in 3.0 protocol,
3290  * fall back to 2.0 protocol.
3291  */
3292  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3293  {
3294  conn->pversion = PG_PROTOCOL(2, 0);
3295  need_new_connection = true;
3296  goto keep_going;
3297  }
3298 
3299  goto error_return;
3300  }
3301 
3302  /*
3303  * Can't process if message body isn't all here yet.
3304  *
3305  * (In protocol 2.0 case, we are assuming messages carry at
3306  * least 4 bytes of data.)
3307  */
3308  msgLength -= 4;
3309  avail = conn->inEnd - conn->inCursor;
3310  if (avail < msgLength)
3311  {
3312  /*
3313  * Before returning, try to enlarge the input buffer if
3314  * needed to hold the whole message; see notes in
3315  * pqParseInput3.
3316  */
3317  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3318  conn))
3319  goto error_return;
3320  /* We'll come back when there is more data */
3321  return PGRES_POLLING_READING;
3322  }
3323 
3324  /* Handle errors. */
3325  if (beresp == 'E')
3326  {
3327  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3328  {
3329  if (pqGetErrorNotice3(conn, true))
3330  {
3331  /* We'll come back when there is more data */
3332  return PGRES_POLLING_READING;
3333  }
3334  }
3335  else
3336  {
3337  if (pqGets_append(&conn->errorMessage, conn))
3338  {
3339  /* We'll come back when there is more data */
3340  return PGRES_POLLING_READING;
3341  }
3342  }
3343  /* OK, we read the message; mark data consumed */
3344  conn->inStart = conn->inCursor;
3345 
3346  /* Check to see if we should mention pgpassfile */
3347  pgpassfileWarning(conn);
3348 
3349 #ifdef ENABLE_GSS
3350 
3351  /*
3352  * If gssencmode is "prefer" and we're using GSSAPI, retry
3353  * without it.
3354  */
3355  if (conn->gssenc && conn->gssencmode[0] == 'p')
3356  {
3357  /* postmaster expects us to drop the connection */
3358  conn->try_gss = false;
3359  pqDropConnection(conn, true);
3360  conn->status = CONNECTION_NEEDED;
3361  goto keep_going;
3362  }
3363 #endif
3364 
3365 #ifdef USE_SSL
3366 
3367  /*
3368  * if sslmode is "allow" and we haven't tried an SSL
3369  * connection already, then retry with an SSL connection
3370  */
3371  if (conn->sslmode[0] == 'a' /* "allow" */
3372  && !conn->ssl_in_use
3373  && conn->allow_ssl_try
3374  && conn->wait_ssl_try)
3375  {
3376  /* only retry once */
3377  conn->wait_ssl_try = false;
3378  need_new_connection = true;
3379  goto keep_going;
3380  }
3381 
3382  /*
3383  * if sslmode is "prefer" and we're in an SSL connection,
3384  * then do a non-SSL retry
3385  */
3386  if (conn->sslmode[0] == 'p' /* "prefer" */
3387  && conn->ssl_in_use
3388  && conn->allow_ssl_try /* redundant? */
3389  && !conn->wait_ssl_try) /* redundant? */
3390  {
3391  /* only retry once */
3392  conn->allow_ssl_try = false;
3393  need_new_connection = true;
3394  goto keep_going;
3395  }
3396 #endif
3397 
3398  goto error_return;
3399  }
3400 
3401  /* It is an authentication request. */
3402  conn->auth_req_received = true;
3403 
3404  /* Get the type of request. */
3405  if (pqGetInt((int *) &areq, 4, conn))
3406  {
3407  /* We'll come back when there are more data */
3408  return PGRES_POLLING_READING;
3409  }
3410  msgLength -= 4;
3411 
3412  /*
3413  * Ensure the password salt is in the input buffer, if it's an
3414  * MD5 request. All the other authentication methods that
3415  * contain extra data in the authentication request are only
3416  * supported in protocol version 3, in which case we already
3417  * read the whole message above.
3418  */
3419  if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3420  {
3421  msgLength += 4;
3422 
3423  avail = conn->inEnd - conn->inCursor;
3424  if (avail < 4)
3425  {
3426  /*
3427  * Before returning, try to enlarge the input buffer
3428  * if needed to hold the whole message; see notes in
3429  * pqParseInput3.
3430  */
3431  if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
3432  conn))
3433  goto error_return;
3434  /* We'll come back when there is more data */
3435  return PGRES_POLLING_READING;
3436  }
3437  }
3438 
3439  /*
3440  * Process the rest of the authentication request message, and
3441  * respond to it if necessary.
3442  *
3443  * Note that conn->pghost must be non-NULL if we are going to
3444  * avoid the Kerberos code doing a hostname look-up.
3445  */
3446  res = pg_fe_sendauth(areq, msgLength, conn);
3447  conn->errorMessage.len = strlen(conn->errorMessage.data);
3448 
3449  /* OK, we have processed the message; mark data consumed */
3450  conn->inStart = conn->inCursor;
3451 
3452  if (res != STATUS_OK)
3453  goto error_return;
3454 
3455  /*
3456  * Just make sure that any data sent by pg_fe_sendauth is
3457  * flushed out. Although this theoretically could block, it
3458  * really shouldn't since we don't send large auth responses.
3459  */
3460  if (pqFlush(conn))
3461  goto error_return;
3462 
3463  if (areq == AUTH_REQ_OK)
3464  {
3465  /* We are done with authentication exchange */
3466  conn->status = CONNECTION_AUTH_OK;
3467 
3468  /*
3469  * Set asyncStatus so that PQgetResult will think that
3470  * what comes back next is the result of a query. See
3471  * below.
3472  */
3473  conn->asyncStatus = PGASYNC_BUSY;
3474  }
3475 
3476  /* Look to see if we have more data yet. */
3477  goto keep_going;
3478  }
3479 
3480  case CONNECTION_AUTH_OK:
3481  {
3482  /*
3483  * Now we expect to hear from the backend. A ReadyForQuery
3484  * message indicates that startup is successful, but we might
3485  * also get an Error message indicating failure. (Notice
3486  * messages indicating nonfatal warnings are also allowed by
3487  * the protocol, as are ParameterStatus and BackendKeyData
3488  * messages.) Easiest way to handle this is to let
3489  * PQgetResult() read the messages. We just have to fake it
3490  * out about the state of the connection, by setting
3491  * asyncStatus = PGASYNC_BUSY (done above).
3492  */
3493 
3494  if (PQisBusy(conn))
3495  return PGRES_POLLING_READING;
3496 
3497  res = PQgetResult(conn);
3498 
3499  /*
3500  * NULL return indicating we have gone to IDLE state is
3501  * expected
3502  */
3503  if (res)
3504  {
3505  if (res->resultStatus != PGRES_FATAL_ERROR)
3507  libpq_gettext("unexpected message from server during startup\n"));
3508  else if (conn->send_appname &&
3509  (conn->appname || conn->fbappname))
3510  {
3511  /*
3512  * If we tried to send application_name, check to see
3513  * if the error is about that --- pre-9.0 servers will
3514  * reject it at this stage of the process. If so,
3515  * close the connection and retry without sending
3516  * application_name. We could possibly get a false
3517  * SQLSTATE match here and retry uselessly, but there
3518  * seems no great harm in that; we'll just get the
3519  * same error again if it's unrelated.
3520  */
3521  const char *sqlstate;
3522 
3523  sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3524  if (sqlstate &&
3525  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3526  {
3527  PQclear(res);
3528  conn->send_appname = false;
3529  need_new_connection = true;
3530  goto keep_going;
3531  }
3532  }
3533 
3534  /*
3535  * if the resultStatus is FATAL, then conn->errorMessage
3536  * already has a copy of the error; needn't copy it back.
3537  * But add a newline if it's not there already, since
3538  * postmaster error messages may not have one.
3539  */
3540  if (conn->errorMessage.len <= 0 ||
3541  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3542  appendPQExpBufferChar(&conn->errorMessage, '\n');
3543  PQclear(res);
3544  goto error_return;
3545  }
3546 
3547  /* Fire up post-connection housekeeping if needed */
3548  if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3549  {
3550  conn->status = CONNECTION_SETENV;
3552  conn->next_eo = EnvironmentOptions;
3553  return PGRES_POLLING_WRITING;
3554  }
3555 
3556  /* Almost there now ... */
3558  goto keep_going;
3559  }
3560 
3562  {
3563  /*
3564  * If a read-write connection is required, see if we have one.
3565  *
3566  * Servers before 7.4 lack the transaction_read_only GUC, but
3567  * by the same token they don't have any read-only mode, so we
3568  * may just skip the test in that case.
3569  */
3570  if (conn->sversion >= 70400 &&
3571  conn->target_session_attrs != NULL &&
3572  strcmp(conn->target_session_attrs, "read-write") == 0)
3573  {
3574  /*
3575  * Save existing error messages across the PQsendQuery
3576  * attempt. This is necessary because PQsendQuery is
3577  * going to reset conn->errorMessage, so we would lose
3578  * error messages related to previous hosts we have tried
3579  * and failed to connect to.
3580  */
3581  if (!saveErrorMessage(conn, &savedMessage))
3582  goto error_return;
3583 
3584  conn->status = CONNECTION_OK;
3585  if (!PQsendQuery(conn,
3586  "SHOW transaction_read_only"))
3587  {
3588  restoreErrorMessage(conn, &savedMessage);
3589  goto error_return;
3590  }
3592  restoreErrorMessage(conn, &savedMessage);
3593  return PGRES_POLLING_READING;
3594  }
3595 
3596  /* We can release the address list now. */
3597  release_conn_addrinfo(conn);
3598 
3599  /* We are open for business! */
3600  conn->status = CONNECTION_OK;
3601  return PGRES_POLLING_OK;
3602  }
3603 
3604  case CONNECTION_SETENV:
3605  {
3606  /*
3607  * Do post-connection housekeeping (only needed in protocol
3608  * 2.0).
3609  *
3610  * We pretend that the connection is OK for the duration of
3611  * these queries.
3612  */
3613  conn->status = CONNECTION_OK;
3614 
3615  switch (pqSetenvPoll(conn))
3616  {
3617  case PGRES_POLLING_OK: /* Success */
3618  break;
3619 
3620  case PGRES_POLLING_READING: /* Still going */
3621  conn->status = CONNECTION_SETENV;
3622  return PGRES_POLLING_READING;
3623 
3624  case PGRES_POLLING_WRITING: /* Still going */
3625  conn->status = CONNECTION_SETENV;
3626  return PGRES_POLLING_WRITING;
3627 
3628  default:
3629  goto error_return;
3630  }
3631 
3632  /* Almost there now ... */
3634  goto keep_going;
3635  }
3636 
3637  case CONNECTION_CONSUME:
3638  {
3639  conn->status = CONNECTION_OK;
3640  if (!PQconsumeInput(conn))
3641  goto error_return;
3642 
3643  if (PQisBusy(conn))
3644  {
3645  conn->status = CONNECTION_CONSUME;
3646  return PGRES_POLLING_READING;
3647  }
3648 
3649  /*
3650  * Call PQgetResult() again to consume NULL result.
3651  */
3652  res = PQgetResult(conn);
3653  if (res != NULL)
3654  {
3655  PQclear(res);
3656  conn->status = CONNECTION_CONSUME;
3657  goto keep_going;
3658  }
3659 
3660  /* We can release the address list now. */
3661  release_conn_addrinfo(conn);
3662 
3663  /* We are open for business! */
3664  conn->status = CONNECTION_OK;
3665  return PGRES_POLLING_OK;
3666  }
3668  {
3669  const char *displayed_host;
3670  const char *displayed_port;
3671 
3672  if (!saveErrorMessage(conn, &savedMessage))
3673  goto error_return;
3674 
3675  conn->status = CONNECTION_OK;
3676  if (!PQconsumeInput(conn))
3677  {
3678  restoreErrorMessage(conn, &savedMessage);
3679  goto error_return;
3680  }
3681 
3682  if (PQisBusy(conn))
3683  {
3685  restoreErrorMessage(conn, &savedMessage);
3686  return PGRES_POLLING_READING;
3687  }
3688 
3689  res = PQgetResult(conn);
3690  if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
3691  PQntuples(res) == 1)
3692  {
3693  char *val;
3694 
3695  val = PQgetvalue(res, 0, 0);
3696  if (strncmp(val, "on", 2) == 0)
3697  {
3698  /* Not writable; fail this connection. */
3699  PQclear(res);
3700  restoreErrorMessage(conn, &savedMessage);
3701 
3702  /* Append error report to conn->errorMessage. */
3703  if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3704  displayed_host = conn->connhost[conn->whichhost].hostaddr;
3705  else
3706  displayed_host = conn->connhost[conn->whichhost].host;
3707  displayed_port = conn->connhost[conn->whichhost].port;
3708  if (displayed_port == NULL || displayed_port[0] == '\0')
3709  displayed_port = DEF_PGPORT_STR;
3710 
3712  libpq_gettext("could not make a writable "
3713  "connection to server "
3714  "\"%s:%s\"\n"),
3715  displayed_host, displayed_port);
3716 
3717  /* Close connection politely. */
3718  conn->status = CONNECTION_OK;
3719  sendTerminateConn(conn);
3720 
3721  /*
3722  * Try next host if any, but we don't want to consider
3723  * additional addresses for this host.
3724  */
3725  conn->try_next_host = true;
3726  goto keep_going;
3727  }
3728 
3729  /* Session is read-write, so we're good. */
3730  PQclear(res);
3731  termPQExpBuffer(&savedMessage);
3732 
3733  /*
3734  * Finish reading any remaining messages before being
3735  * considered as ready.
3736  */
3737  conn->status = CONNECTION_CONSUME;
3738  goto keep_going;
3739  }
3740 
3741  /*
3742  * Something went wrong with "SHOW transaction_read_only". We
3743  * should try next addresses.
3744  */
3745  if (res)
3746  PQclear(res);
3747  restoreErrorMessage(conn, &savedMessage);
3748 
3749  /* Append error report to conn->errorMessage. */
3750  if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3751  displayed_host = conn->connhost[conn->whichhost].hostaddr;
3752  else
3753  displayed_host = conn->connhost[conn->whichhost].host;
3754  displayed_port = conn->connhost[conn->whichhost].port;
3755  if (displayed_port == NULL || displayed_port[0] == '\0')
3756  displayed_port = DEF_PGPORT_STR;
3758  libpq_gettext("test \"SHOW transaction_read_only\" failed "
3759  "on server \"%s:%s\"\n"),
3760  displayed_host, displayed_port);
3761 
3762  /* Close connection politely. */
3763  conn->status = CONNECTION_OK;
3764  sendTerminateConn(conn);
3765 
3766  /* Try next address */
3767  conn->try_next_addr = true;
3768  goto keep_going;
3769  }
3770 
3771  default:
3773  libpq_gettext("invalid connection state %d, "
3774  "probably indicative of memory corruption\n"),
3775  conn->status);
3776  goto error_return;
3777  }
3778 
3779  /* Unreachable */
3780 
3781 error_return:
3782 
3783  /*
3784  * We used to close the socket at this point, but that makes it awkward
3785  * for those above us if they wish to remove this socket from their own
3786  * records (an fd_set for example). We'll just have this socket closed
3787  * when PQfinish is called (which is compulsory even after an error, since
3788  * the connection structure must be freed).
3789  */
3790  conn->status = CONNECTION_BAD;
3791  return PGRES_POLLING_FAILED;
3792 }
3793 
3794 
3795 /*
3796  * internal_ping
3797  * Determine if a server is running and if we can connect to it.
3798  *
3799  * The argument is a connection that's been started, but not completed.
3800  */
3801 static PGPing
3803 {
3804  /* Say "no attempt" if we never got to PQconnectPoll */
3805  if (!conn || !conn->options_valid)
3806  return PQPING_NO_ATTEMPT;
3807 
3808  /* Attempt to complete the connection */
3809  if (conn->status != CONNECTION_BAD)
3810  (void) connectDBComplete(conn);
3811 
3812  /* Definitely OK if we succeeded */
3813  if (conn->status != CONNECTION_BAD)
3814  return PQPING_OK;
3815 
3816  /*
3817  * Here begins the interesting part of "ping": determine the cause of the
3818  * failure in sufficient detail to decide what to return. We do not want
3819  * to report that the server is not up just because we didn't have a valid
3820  * password, for example. In fact, any sort of authentication request
3821  * implies the server is up. (We need this check since the libpq side of
3822  * things might have pulled the plug on the connection before getting an
3823  * error as such from the postmaster.)
3824  */
3825  if (conn->auth_req_received)
3826  return PQPING_OK;
3827 
3828  /*
3829  * If we failed to get any ERROR response from the postmaster, report
3830  * PQPING_NO_RESPONSE. This result could be somewhat misleading for a
3831  * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
3832  * out of support. Another corner case where the server could return a
3833  * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
3834  * isn't totally unreasonable for that anyway. We expect that every other
3835  * failure case in a modern server will produce a report with a SQLSTATE.
3836  *
3837  * NOTE: whenever we get around to making libpq generate SQLSTATEs for
3838  * client-side errors, we should either not store those into
3839  * last_sqlstate, or add an extra flag so we can tell client-side errors
3840  * apart from server-side ones.
3841  */
3842  if (strlen(conn->last_sqlstate) != 5)
3843  return PQPING_NO_RESPONSE;
3844 
3845  /*
3846  * Report PQPING_REJECT if server says it's not accepting connections. (We
3847  * distinguish this case mainly for the convenience of pg_ctl.)
3848  */
3849  if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
3850  return PQPING_REJECT;
3851 
3852  /*
3853  * Any other SQLSTATE can be taken to indicate that the server is up.
3854  * Presumably it didn't like our username, password, or database name; or
3855  * perhaps it had some transient failure, but that should not be taken as
3856  * meaning "it's down".
3857  */
3858  return PQPING_OK;
3859 }
3860 
3861 
3862 /*
3863  * makeEmptyPGconn
3864  * - create a PGconn data structure with (as yet) no interesting data
3865  */
3866 static PGconn *
3868 {
3869  PGconn *conn;
3870 
3871 #ifdef WIN32
3872 
3873  /*
3874  * Make sure socket support is up and running in this process.
3875  *
3876  * Note: the Windows documentation says that we should eventually do a
3877  * matching WSACleanup() call, but experience suggests that that is at
3878  * least as likely to cause problems as fix them. So we don't.
3879  */
3880  static bool wsastartup_done = false;
3881 
3882  if (!wsastartup_done)
3883  {
3884  WSADATA wsaData;
3885 
3886  if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
3887  return NULL;
3888  wsastartup_done = true;
3889  }
3890 
3891  /* Forget any earlier error */
3892  WSASetLastError(0);
3893 #endif /* WIN32 */
3894 
3895  conn = (PGconn *) malloc(sizeof(PGconn));
3896  if (conn == NULL)
3897  return conn;
3898 
3899  /* Zero all pointers and booleans */
3900  MemSet(conn, 0, sizeof(PGconn));
3901 
3902  /* install default notice hooks */
3905 
3906  conn->status = CONNECTION_BAD;
3907  conn->asyncStatus = PGASYNC_IDLE;
3908  conn->xactStatus = PQTRANS_IDLE;
3909  conn->options_valid = false;
3910  conn->nonblocking = false;
3912  conn->client_encoding = PG_SQL_ASCII;
3913  conn->std_strings = false; /* unless server says differently */
3914  conn->verbosity = PQERRORS_DEFAULT;
3916  conn->sock = PGINVALID_SOCKET;
3917 
3918  /*
3919  * We try to send at least 8K at a time, which is the usual size of pipe
3920  * buffers on Unix systems. That way, when we are sending a large amount
3921  * of data, we avoid incurring extra kernel context swaps for partial
3922  * bufferloads. The output buffer is initially made 16K in size, and we
3923  * try to dump it after accumulating 8K.
3924  *
3925  * With the same goal of minimizing context swaps, the input buffer will
3926  * be enlarged anytime it has less than 8K free, so we initially allocate
3927  * twice that.
3928  */
3929  conn->inBufSize = 16 * 1024;
3930  conn->inBuffer = (char *) malloc(conn->inBufSize);
3931  conn->outBufSize = 16 * 1024;
3932  conn->outBuffer = (char *) malloc(conn->outBufSize);
3933  conn->rowBufLen = 32;
3934  conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
3935  initPQExpBuffer(&conn->errorMessage);
3936  initPQExpBuffer(&conn->workBuffer);
3937 
3938  if (conn->inBuffer == NULL ||
3939  conn->outBuffer == NULL ||
3940  conn->rowBuf == NULL ||
3941  PQExpBufferBroken(&conn->errorMessage) ||
3942  PQExpBufferBroken(&conn->workBuffer))
3943  {
3944  /* out of memory already :-( */
3945  freePGconn(conn);
3946  conn = NULL;
3947  }
3948 
3949  return conn;
3950 }
3951 
3952 /*
3953  * freePGconn
3954  * - free an idle (closed) PGconn data structure
3955  *
3956  * NOTE: this should not overlap any functionality with closePGconn().
3957  * Clearing/resetting of transient state belongs there; what we do here is
3958  * release data that is to be held for the life of the PGconn structure.
3959  * If a value ought to be cleared/freed during PQreset(), do it there not here.
3960  */
3961 static void
3963 {
3964  int i;
3965 
3966  /* let any event procs clean up their state data */
3967  for (i = 0; i < conn->nEvents; i++)
3968  {
3969  PGEventConnDestroy evt;
3970 
3971  evt.conn = conn;
3972  (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3973  conn->events[i].passThrough);
3974  free(conn->events[i].name);
3975  }
3976 
3977  /* clean up pg_conn_host structures */
3978  if (conn->connhost != NULL)
3979  {
3980  for (i = 0; i < conn->nconnhost; ++i)
3981  {
3982  if (conn->connhost[i].host != NULL)
3983  free(conn->connhost[i].host);
3984  if (conn->connhost[i].hostaddr != NULL)
3985  free(conn->connhost[i].hostaddr);
3986  if (conn->connhost[i].port != NULL)
3987  free(conn->connhost[i].port);
3988  if (conn->connhost[i].password != NULL)
3989  {
3990  explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
3991  free(conn->connhost[i].password);
3992  }
3993  }
3994  free(conn->connhost);
3995  }
3996 
3997  if (conn->client_encoding_initial)
3999  if (conn->events)
4000  free(conn->events);
4001  if (conn->pghost)
4002  free(conn->pghost);
4003  if (conn->pghostaddr)
4004  free(conn->pghostaddr);
4005  if (conn->pgport)
4006  free(conn->pgport);
4007  if (conn->pgtty)
4008  free(conn->pgtty);
4009  if (conn->connect_timeout)
4010  free(conn->connect_timeout);
4011  if (conn->pgtcp_user_timeout)
4012  free(conn->pgtcp_user_timeout);
4013  if (conn->pgoptions)
4014  free(conn->pgoptions);
4015  if (conn->appname)
4016  free(conn->appname);
4017  if (conn->fbappname)
4018  free(conn->fbappname);
4019  if (conn->dbName)
4020  free(conn->dbName);
4021  if (conn->replication)
4022  free(conn->replication);
4023  if (conn->pguser)
4024  free(conn->pguser);
4025  if (conn->pgpass)
4026  {
4027  explicit_bzero(conn->pgpass, strlen(conn->pgpass));
4028  free(conn->pgpass);
4029  }
4030  if (conn->pgpassfile)
4031  free(conn->pgpassfile);
4032  if (conn->channel_binding)
4033  free(conn->channel_binding);
4034  if (conn->keepalives)
4035  free(conn->keepalives);
4036  if (conn->keepalives_idle)
4037  free(conn->keepalives_idle);
4038  if (conn->keepalives_interval)
4039  free(conn->keepalives_interval);
4040  if (conn->keepalives_count)
4041  free(conn->keepalives_count);
4042  if (conn->sslmode)
4043  free(conn->sslmode);
4044  if (conn->sslcert)
4045  free(conn->sslcert);
4046  if (conn->sslkey)
4047  free(conn->sslkey);
4048  if (conn->sslpassword)
4049  {
4050  explicit_bzero(conn->sslpassword, strlen(conn->sslpassword));
4051  free(conn->sslpassword);
4052  }
4053  if (conn->sslrootcert)
4054  free(conn->sslrootcert);
4055  if (conn->sslcrl)
4056  free(conn->sslcrl);
4057  if (conn->sslcompression)
4058  free(conn->sslcompression);
4059  if (conn->requirepeer)
4060  free(conn->requirepeer);
4061  if (conn->ssl_min_protocol_version)
4063  if (conn->ssl_max_protocol_version)
4065  if (conn->gssencmode)
4066  free(conn->gssencmode);
4067  if (conn->krbsrvname)
4068  free(conn->krbsrvname);
4069  if (conn->gsslib)
4070  free(conn->gsslib);
4071  if (conn->connip)
4072  free(conn->connip);
4073  /* Note that conn->Pfdebug is not ours to close or free */
4074  if (conn->last_query)
4075  free(conn->last_query);
4076  if (conn->write_err_msg)
4077  free(conn->write_err_msg);
4078  if (conn->inBuffer)
4079  free(conn->inBuffer);
4080  if (conn->outBuffer)
4081  free(conn->outBuffer);
4082  if (conn->rowBuf)
4083  free(conn->rowBuf);
4084  if (conn->target_session_attrs)
4085  free(conn->target_session_attrs);
4086  termPQExpBuffer(&conn->errorMessage);
4087  termPQExpBuffer(&conn->workBuffer);
4088 
4089  free(conn);
4090 }
4091 
4092 /*
4093  * release_conn_addrinfo
4094  * - Free any addrinfo list in the PGconn.
4095  */
4096 static void
4098 {
4099  if (conn->addrlist)
4100  {
4102  conn->addrlist = NULL;
4103  conn->addr_cur = NULL; /* for safety */
4104  }
4105 }
4106 
4107 /*
4108  * sendTerminateConn
4109  * - Send a terminate message to backend.
4110  */
4111 static void
4113 {
4114  /*
4115  * Note that the protocol doesn't allow us to send Terminate messages
4116  * during the startup phase.
4117  */
4118  if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
4119  {
4120  /*
4121  * Try to send "close connection" message to backend. Ignore any
4122  * error.
4123  */
4124  pqPutMsgStart('X', false, conn);
4125  pqPutMsgEnd(conn);
4126  (void) pqFlush(conn);
4127  }
4128 }
4129 
4130 /*
4131  * closePGconn
4132  * - properly close a connection to the backend
4133  *
4134  * This should reset or release all transient state, but NOT the connection
4135  * parameters. On exit, the PGconn should be in condition to start a fresh
4136  * connection with the same parameters (see PQreset()).
4137  */
4138 static void
4140 {
4141  /*
4142  * If possible, send Terminate message to close the connection politely.
4143  */
4144  sendTerminateConn(conn);
4145 
4146  /*
4147  * Must reset the blocking status so a possible reconnect will work.
4148  *
4149  * Don't call PQsetnonblocking() because it will fail if it's unable to
4150  * flush the connection.
4151  */
4152  conn->nonblocking = false;
4153 
4154  /*
4155  * Close the connection, reset all transient state, flush I/O buffers.
4156  */
4157  pqDropConnection(conn, true);
4158  conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4159  conn->asyncStatus = PGASYNC_IDLE;
4160  conn->xactStatus = PQTRANS_IDLE;
4161  pqClearAsyncResult(conn); /* deallocate result */
4163  release_conn_addrinfo(conn);
4164 
4165  /* Reset all state obtained from server, too */
4166  pqDropServerData(conn);
4167 }
4168 
4169 /*
4170  * PQfinish: properly close a connection to the backend. Also frees
4171  * the PGconn data structure so it shouldn't be re-used after this.
4172  */
4173 void
4175 {
4176  if (conn)
4177  {
4178  closePGconn(conn);
4179  freePGconn(conn);
4180  }
4181 }
4182 
4183 /*
4184  * PQreset: resets the connection to the backend by closing the
4185  * existing connection and creating a new one.
4186  */
4187 void
4189 {
4190  if (conn)
4191  {
4192  closePGconn(conn);
4193 
4194  if (connectDBStart(conn) && connectDBComplete(conn))
4195  {
4196  /*
4197  * Notify event procs of successful reset. We treat an event proc
4198  * failure as disabling the connection ... good idea?
4199  */
4200  int i;
4201 
4202  for (i = 0; i < conn->nEvents; i++)
4203  {
4204  PGEventConnReset evt;
4205 
4206  evt.conn = conn;
4207  if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4208  conn->events[i].passThrough))
4209  {
4210  conn->status = CONNECTION_BAD;
4212  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4213  conn->events[i].name);
4214  break;
4215  }
4216  }
4217  }
4218  }
4219 }
4220 
4221 
4222 /*
4223  * PQresetStart:
4224  * resets the connection to the backend
4225  * closes the existing connection and makes a new one
4226  * Returns 1 on success, 0 on failure.
4227  */
4228 int
4230 {
4231  if (conn)
4232  {
4233  closePGconn(conn);
4234 
4235  return connectDBStart(conn);
4236  }
4237 
4238  return 0;
4239 }
4240 
4241 
4242 /*
4243  * PQresetPoll:
4244  * resets the connection to the backend
4245  * closes the existing connection and makes a new one
4246  */
4249 {
4250  if (conn)
4251  {
4253 
4254  if (status == PGRES_POLLING_OK)
4255  {
4256  /*
4257  * Notify event procs of successful reset. We treat an event proc
4258  * failure as disabling the connection ... good idea?
4259  */
4260  int i;
4261 
4262  for (i = 0; i < conn->nEvents; i++)
4263  {
4264  PGEventConnReset evt;
4265 
4266  evt.conn = conn;
4267  if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4268  conn->events[i].passThrough))
4269  {
4270  conn->status = CONNECTION_BAD;
4272  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4273  conn->events[i].name);
4274  return PGRES_POLLING_FAILED;
4275  }
4276  }
4277  }
4278 
4279  return status;
4280  }
4281 
4282  return PGRES_POLLING_FAILED;
4283 }
4284 
4285 /*
4286  * PQgetCancel: get a PGcancel structure corresponding to a connection.
4287  *
4288  * A copy is needed to be able to cancel a running query from a different
4289  * thread. If the same structure is used all structure members would have
4290  * to be individually locked (if the entire structure was locked, it would
4291  * be impossible to cancel a synchronous query because the structure would
4292  * have to stay locked for the duration of the query).
4293  */
4294 PGcancel *
4296 {
4297  PGcancel *cancel;
4298 
4299  if (!conn)
4300  return NULL;
4301 
4302  if (conn->sock == PGINVALID_SOCKET)
4303  return NULL;
4304 
4305  cancel = malloc(sizeof(PGcancel));
4306  if (cancel == NULL)
4307  return NULL;
4308 
4309  memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
4310  cancel->be_pid = conn->be_pid;
4311  cancel->be_key = conn->be_key;
4312 
4313  return cancel;
4314 }
4315 
4316 /* PQfreeCancel: free a cancel structure */
4317 void
4319 {
4320  if (cancel)
4321  free(cancel);
4322 }
4323 
4324 
4325 /*
4326  * PQcancel and PQrequestCancel: attempt to request cancellation of the
4327  * current operation.
4328  *
4329  * The return value is true if the cancel request was successfully
4330  * dispatched, false if not (in which case an error message is available).
4331  * Note: successful dispatch is no guarantee that there will be any effect at
4332  * the backend. The application must read the operation result as usual.
4333  *
4334  * CAUTION: we want this routine to be safely callable from a signal handler
4335  * (for example, an application might want to call it in a SIGINT handler).
4336  * This means we cannot use any C library routine that might be non-reentrant.
4337  * malloc/free are often non-reentrant, and anything that might call them is
4338  * just as dangerous. We avoid sprintf here for that reason. Building up
4339  * error messages with strcpy/strcat is tedious but should be quite safe.
4340  * We also save/restore errno in case the signal handler support doesn't.
4341  *
4342  * internal_cancel() is an internal helper function to make code-sharing
4343  * between the two versions of the cancel function possible.
4344  */
4345 static int
4346 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
4347  char *errbuf, int errbufsize)
4348 {
4349  int save_errno = SOCK_ERRNO;
4350  pgsocket tmpsock = PGINVALID_SOCKET;
4351  char sebuf[PG_STRERROR_R_BUFLEN];
4352  int maxlen;
4353  struct
4354  {
4355  uint32 packetlen;
4357  } crp;
4358 
4359  /*
4360  * We need to open a temporary connection to the postmaster. Do this with
4361  * only kernel calls.
4362  */
4363  if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4364  {
4365  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4366  goto cancel_errReturn;
4367  }
4368 retry3:
4369  if (connect(tmpsock, (struct sockaddr *) &raddr->addr,
4370  raddr->salen) < 0)
4371  {
4372  if (SOCK_ERRNO == EINTR)
4373  /* Interrupted system call - we'll just try again */
4374  goto retry3;
4375  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4376  goto cancel_errReturn;
4377  }
4378 
4379  /*
4380  * We needn't set nonblocking I/O or NODELAY options here.
4381  */
4382 
4383  /* Create and send the cancel request packet. */
4384 
4385  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4386  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4387  crp.cp.backendPID = pg_hton32(be_pid);
4388  crp.cp.cancelAuthCode = pg_hton32(be_key);
4389 
4390 retry4:
4391  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4392  {
4393  if (SOCK_ERRNO == EINTR)
4394  /* Interrupted system call - we'll just try again */
4395  goto retry4;
4396  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4397  goto cancel_errReturn;
4398  }
4399 
4400  /*
4401  * Wait for the postmaster to close the connection, which indicates that
4402  * it's processed the request. Without this delay, we might issue another
4403  * command only to find that our cancel zaps that command instead of the
4404  * one we thought we were canceling. Note we don't actually expect this
4405  * read to obtain any data, we are just waiting for EOF to be signaled.
4406  */
4407 retry5:
4408  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4409  {
4410  if (SOCK_ERRNO == EINTR)
4411  /* Interrupted system call - we'll just try again */
4412  goto retry5;
4413  /* we ignore other error conditions */
4414  }
4415 
4416  /* All done */
4417  closesocket(tmpsock);
4418  SOCK_ERRNO_SET(save_errno);
4419  return true;
4420 
4421 cancel_errReturn:
4422 
4423  /*
4424  * Make sure we don't overflow the error buffer. Leave space for the \n at
4425  * the end, and for the terminating zero.
4426  */
4427  maxlen = errbufsize - strlen(errbuf) - 2;
4428  if (maxlen >= 0)
4429  {
4430  strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
4431  maxlen);
4432  strcat(errbuf, "\n");
4433  }
4434  if (tmpsock != PGINVALID_SOCKET)
4435  closesocket(tmpsock);
4436  SOCK_ERRNO_SET(save_errno);
4437  return false;
4438 }
4439 
4440 /*
4441  * PQcancel: request query cancel
4442  *
4443  * Returns true if able to send the cancel request, false if not.
4444  *
4445  * On failure, an error message is stored in *errbuf, which must be of size
4446  * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
4447  * success return.
4448  */
4449 int
4450 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
4451 {
4452  if (!cancel)
4453  {
4454  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4455  return false;
4456  }
4457 
4458  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4459  errbuf, errbufsize);
4460 }
4461 
4462 /*
4463  * PQrequestCancel: old, not thread-safe function for requesting query cancel
4464  *
4465  * Returns true if able to send the cancel request, false if not.
4466  *
4467  * On failure, the error message is saved in conn->errorMessage; this means
4468  * that this can't be used when there might be other active operations on
4469  * the connection object.
4470  *
4471  * NOTE: error messages will be cut off at the current size of the
4472  * error message buffer, since we dare not try to expand conn->errorMessage!
4473  */
4474 int
4476 {
4477  int r;
4478 
4479  /* Check we have an open connection */
4480  if (!conn)
4481  return false;
4482 
4483  if (conn->sock == PGINVALID_SOCKET)
4484  {
4485  strlcpy(conn->errorMessage.data,
4486  "PQrequestCancel() -- connection is not open\n",
4487  conn->errorMessage.maxlen);
4488  conn->errorMessage.len = strlen(conn->errorMessage.data);
4489 
4490  return false;
4491  }
4492 
4493  r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
4494  conn->errorMessage.data, conn->errorMessage.maxlen);
4495 
4496  if (!r)
4497  conn->errorMessage.len = strlen(conn->errorMessage.data);
4498 
4499  return r;
4500 }
4501 
4502 
4503 /*
4504  * pqPacketSend() -- convenience routine to send a message to server.
4505  *
4506  * pack_type: the single-byte message type code. (Pass zero for startup
4507  * packets, which have no message type code.)
4508  *
4509  * buf, buf_len: contents of message. The given length includes only what
4510  * is in buf; the message type and message length fields are added here.
4511  *
4512  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4513  * SIDE_EFFECTS: may block.
4514  *
4515  * Note: all messages sent with this routine have a length word, whether
4516  * it's protocol 2.0 or 3.0.
4517  */
4518 int
4519 pqPacketSend(PGconn *conn, char pack_type,
4520  const void *buf, size_t buf_len)
4521 {
4522  /* Start the message. */
4523  if (pqPutMsgStart(pack_type, true, conn))
4524  return STATUS_ERROR;
4525 
4526  /* Send the message body. */
4527  if (pqPutnchar(buf, buf_len, conn))
4528  return STATUS_ERROR;
4529 
4530  /* Finish the message. */
4531  if (pqPutMsgEnd(conn))
4532  return STATUS_ERROR;
4533 
4534  /* Flush to ensure backend gets it. */
4535  if (pqFlush(conn))
4536  return STATUS_ERROR;
4537 
4538  return STATUS_OK;
4539 }
4540 
4541 #ifdef USE_LDAP
4542 
4543 #define LDAP_URL "ldap://"
4544 #define LDAP_DEF_PORT 389
4545 #define PGLDAP_TIMEOUT 2
4546 
4547 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4548 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4549 
4550 
4551 /*
4552  * ldapServiceLookup
4553  *
4554  * Search the LDAP URL passed as first argument, treat the result as a
4555  * string of connection options that are parsed and added to the array of
4556  * options passed as second argument.
4557  *
4558  * LDAP URLs must conform to RFC 1959 without escape sequences.
4559  * ldap://host:port/dn?attributes?scope?filter?extensions
4560  *
4561  * Returns
4562  * 0 if the lookup was successful,
4563  * 1 if the connection to the LDAP server could be established but
4564  * the search was unsuccessful,
4565  * 2 if a connection could not be established, and
4566  * 3 if a fatal error occurred.
4567  *
4568  * An error message is returned in the third argument for return codes 1 and 3.
4569  */
4570 static int
4571 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4572  PQExpBuffer errorMessage)
4573 {
4574  int port = LDAP_DEF_PORT,
4575  scope,
4576  rc,
4577  size,
4578  state,
4579  oldstate,
4580  i;
4581 #ifndef WIN32
4582  int msgid;
4583 #endif
4584  bool found_keyword;
4585  char *url,
4586  *hostname,
4587  *portstr,
4588  *endptr,
4589  *dn,
4590  *scopestr,
4591  *filter,
4592  *result,
4593  *p,
4594  *p1 = NULL,
4595  *optname = NULL,
4596  *optval = NULL;
4597  char *attrs[2] = {NULL, NULL};
4598  LDAP *ld = NULL;
4599  LDAPMessage *res,
4600  *entry;
4601  struct berval **values;
4602  LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4603 
4604  if ((url = strdup(purl)) == NULL)
4605  {
4606  printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4607  return 3;
4608  }
4609 
4610  /*
4611  * Parse URL components, check for correctness. Basically, url has '\0'
4612  * placed at component boundaries and variables are pointed at each
4613  * component.
4614  */
4615 
4616  if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4617  {
4618  printfPQExpBuffer(errorMessage,
4619  libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
4620  free(url);
4621  return 3;
4622  }
4623 
4624  /* hostname */
4625  hostname = url + strlen(LDAP_URL);
4626  if (*hostname == '/') /* no hostname? */
4627  hostname = DefaultHost; /* the default */
4628 
4629  /* dn, "distinguished name" */
4630  p = strchr(url + strlen(LDAP_URL), '/');
4631  if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4632  {
4633  printfPQExpBuffer(errorMessage,
4634  libpq_gettext("invalid LDAP URL \"%s\": missing distinguished name\n"),
4635  purl);
4636  free(url);
4637  return 3;
4638  }
4639  *p = '\0'; /* terminate hostname */
4640  dn = p + 1;
4641 
4642  /* attribute */
4643  if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4644  {
4645  printfPQExpBuffer(errorMessage,
4646  libpq_gettext("invalid LDAP URL \"%s\": must have exactly one attribute\n"),
4647  purl);
4648  free(url);
4649  return 3;
4650  }
4651  *p = '\0';
4652  attrs[0] = p + 1;
4653 
4654  /* scope */
4655  if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4656  {
4657  printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4658  free(url);
4659  return 3;
4660  }
4661  *p = '\0';
4662  scopestr = p + 1;
4663 
4664  /* filter */
4665  if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4666  {
4667  printfPQExpBuffer(errorMessage,
4668  libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
4669  free(url);
4670  return 3;
4671  }
4672  *p = '\0';
4673  filter = p + 1;
4674  if ((p = strchr(filter, '?')) != NULL)
4675  *p = '\0';
4676 
4677  /* port number? */
4678  if ((p1 = strchr(hostname, ':')) != NULL)
4679  {
4680  long lport;
4681 
4682  *p1 = '\0';
4683  portstr = p1 + 1;
4684  errno = 0;
4685  lport = strtol(portstr, &endptr, 10);
4686  if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4687  {
4688  printfPQExpBuffer(errorMessage,
4689  libpq_gettext("invalid LDAP URL \"%s\": invalid port number\n"),
4690  purl);
4691  free(url);
4692  return 3;
4693  }
4694  port = (int) lport;
4695  }
4696 
4697  /* Allow only one attribute */
4698  if (strchr(attrs[0], ',') != NULL)
4699  {
4700  printfPQExpBuffer(errorMessage,
4701  libpq_gettext("invalid LDAP URL \"%s\": must have exactly one attribute\n"),
4702  purl);
4703  free(url);
4704  return 3;
4705  }
4706 
4707  /* set scope */
4708  if (pg_strcasecmp(scopestr, "base") == 0)
4709  scope = LDAP_SCOPE_BASE;
4710  else if (pg_strcasecmp(scopestr, "one") == 0)
4711  scope = LDAP_SCOPE_ONELEVEL;
4712  else if (pg_strcasecmp(scopestr, "sub") == 0)
4713  scope = LDAP_SCOPE_SUBTREE;
4714  else
4715  {
4716  printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4717  free(url);
4718  return 3;
4719  }
4720 
4721  /* initialize LDAP structure */
4722  if ((ld = ldap_init(hostname, port)) == NULL)
4723  {
4724  printfPQExpBuffer(errorMessage,
4725  libpq_gettext("could not create LDAP structure\n"));
4726  free(url);
4727  return 3;
4728  }
4729 
4730  /*
4731  * Perform an explicit anonymous bind.
4732  *
4733  * LDAP does not require that an anonymous bind is performed explicitly,
4734  * but we want to distinguish between the case where LDAP bind does not
4735  * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4736  * service control file) and the case where querying the LDAP server fails
4737  * (return 1 to end parsing).
4738  *
4739  * Unfortunately there is no way of setting a timeout that works for both
4740  * Windows and OpenLDAP.
4741  */
4742 #ifdef WIN32
4743  /* the nonstandard ldap_connect function performs an anonymous bind */
4744  if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4745  {
4746  /* error or timeout in ldap_connect */
4747  free(url);
4748  ldap_unbind(ld);
4749  return 2;
4750  }
4751 #else /* !WIN32 */
4752  /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4753  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4754  {
4755  free(url);
4756  ldap_unbind(ld);
4757  return 3;
4758  }
4759 
4760  /* anonymous bind */
4761  if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4762  {
4763  /* error or network timeout */
4764  free(url);
4765  ldap_unbind(ld);
4766  return 2;
4767  }
4768 
4769  /* wait some time for the connection to succeed */
4770  res = NULL;
4771  if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4772  res == NULL)
4773  {
4774  /* error or timeout */
4775  if (res != NULL)
4776  ldap_msgfree(res);
4777  free(url);
4778  ldap_unbind(ld);
4779  return 2;
4780  }
4781  ldap_msgfree(res);
4782 
4783  /* reset timeout */
4784  time.tv_sec = -1;
4785  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4786  {
4787  free(url);
4788  ldap_unbind(ld);
4789  return 3;
4790  }
4791 #endif /* WIN32 */
4792 
4793  /* search */
4794  res = NULL;
4795  if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4796  != LDAP_SUCCESS)
4797  {
4798  if (res != NULL)
4799  ldap_msgfree(res);
4800  printfPQExpBuffer(errorMessage,
4801  libpq_gettext("lookup on LDAP server failed: %s\n"),
4802  ldap_err2string(rc));
4803  ldap_unbind(ld);
4804  free(url);
4805  return 1;
4806  }
4807 
4808  /* complain if there was not exactly one result */
4809  if ((rc = ldap_count_entries(ld, res)) != 1)
4810  {
4811  printfPQExpBuffer(errorMessage,
4812  rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
4813  : libpq_gettext("no entry found on LDAP lookup\n"));
4814  ldap_msgfree(res);
4815  ldap_unbind(ld);
4816  free(url);
4817  return 1;
4818  }
4819 
4820  /* get entry */
4821  if ((entry = ldap_first_entry(ld, res)) == NULL)
4822  {
4823  /* should never happen */
4824  printfPQExpBuffer(errorMessage,
4825  libpq_gettext("no entry found on LDAP lookup\n"));
4826  ldap_msgfree(res);
4827  ldap_unbind(ld);
4828  free(url);
4829  return 1;
4830  }
4831 
4832  /* get values */
4833  if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4834  {
4835  printfPQExpBuffer(errorMessage,
4836  libpq_gettext("attribute has no values on LDAP lookup\n"));
4837  ldap_msgfree(res);
4838  ldap_unbind(ld);
4839  free(url);
4840  return 1;
4841  }
4842 
4843  ldap_msgfree(res);
4844  free(url);
4845 
4846  if (values[0] == NULL)
4847  {
4848  printfPQExpBuffer(errorMessage,
4849  libpq_gettext("attribute has no values on LDAP lookup\n"));
4850  ldap_value_free_len(values);
4851  ldap_unbind(ld);
4852  return 1;
4853  }
4854 
4855  /* concatenate values into a single string with newline terminators */
4856  size = 1; /* for the trailing null */
4857  for (i = 0; values[i] != NULL; i++)
4858  size += values[i]->bv_len + 1;
4859  if ((result = malloc(size)) == NULL)
4860  {
4861  printfPQExpBuffer(errorMessage,
4862  libpq_gettext("out of memory\n"));
4863  ldap_value_free_len(values);
4864  ldap_unbind(ld);
4865  return 3;
4866  }
4867  p = result;
4868  for (i = 0; values[i] != NULL; i++)
4869  {
4870  memcpy(p, values[i]->bv_val, values[i]->bv_len);
4871  p += values[i]->bv_len;
4872  *(p++) = '\n';
4873  }
4874  *p = '\0';
4875 
4876  ldap_value_free_len(values);
4877  ldap_unbind(ld);
4878 
4879  /* parse result string */
4880  oldstate = state = 0;
4881  for (p = result; *p != '\0'; ++p)
4882  {
4883  switch (state)
4884  {
4885  case 0: /* between entries */
4886  if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
4887  {
4888  optname = p;
4889  state = 1;
4890  }
4891  break;
4892  case 1: /* in option name */
4893  if (ld_is_sp_tab(*p))
4894  {
4895  *p = '\0';
4896  state = 2;
4897  }
4898  else if (ld_is_nl_cr(*p))
4899  {
4900  printfPQExpBuffer(errorMessage,
4901  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4902  optname);
4903  free(result);
4904  return 3;
4905  }
4906  else if (*p == '=')
4907  {
4908  *p = '\0';
4909  state = 3;
4910  }
4911  break;
4912  case 2: /* after option name */
4913  if (*p == '=')
4914  {
4915  state = 3;
4916  }
4917  else if (!ld_is_sp_tab(*p))
4918  {
4919  printfPQExpBuffer(errorMessage,
4920  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4921  optname);
4922  free(result);
4923  return 3;
4924  }
4925  break;
4926  case 3: /* before option value */
4927  if (*p == '\'')
4928  {
4929  optval = p + 1;
4930  p1 = p + 1;
4931  state = 5;
4932  }
4933  else if (ld_is_nl_cr(*p))
4934  {
4935  optval = optname + strlen(optname); /* empty */
4936  state = 0;
4937  }
4938  else if (!ld_is_sp_tab(*p))
4939  {
4940  optval = p;
4941  state = 4;
4942  }
4943  break;
4944  case 4: /* in unquoted option value */
4945  if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
4946  {
4947  *p = '\0';
4948  state = 0;
4949  }
4950  break;
4951  case 5: /* in quoted option value */
4952  if (*p == '\'')
4953  {
4954  *p1 = '\0';
4955  state = 0;
4956  }
4957  else if (*p == '\\')
4958  state = 6;
4959  else
4960  *(p1++) = *p;
4961  break;
4962  case 6: /* in quoted option value after escape */
4963  *(p1++) = *p;
4964  state = 5;
4965  break;
4966  }
4967 
4968  if (state == 0 && oldstate != 0)
4969  {
4970  found_keyword = false;
4971  for (i = 0; options[i].keyword; i++)
4972  {
4973  if (strcmp(options[i].keyword, optname) == 0)
4974  {
4975  if (options[i].val == NULL)
4976  {
4977  options[i].val = strdup(optval);
4978  if (!options[i].val)
4979  {
4980  printfPQExpBuffer(errorMessage,
4981  libpq_gettext("out of memory\n"));
4982  free(result);
4983  return 3;
4984  }
4985  }
4986  found_keyword = true;
4987  break;
4988  }
4989  }
4990  if (!found_keyword)
4991  {
4992  printfPQExpBuffer(errorMessage,
4993  libpq_gettext("invalid connection option \"%s\"\n"),
4994  optname);
4995  free(result);
4996  return 1;
4997  }
4998  optname = NULL;
4999  optval = NULL;
5000  }
5001  oldstate = state;
5002  }
5003 
5004  free(result);
5005 
5006  if (state == 5 || state == 6)
5007  {
5008  printfPQExpBuffer(errorMessage,
5009  libpq_gettext("unterminated quoted string in connection info string\n"));
5010  return 3;
5011  }
5012 
5013  return 0;
5014 }
5015 
5016 #endif /* USE_LDAP */
5017 
5018 /*
5019  * parseServiceInfo: if a service name has been given, look it up and absorb
5020  * connection options from it into *options.
5021  *
5022  * Returns 0 on success, nonzero on failure. On failure, if errorMessage
5023  * isn't null, also store an error message there. (Note: the only reason
5024  * this function and related ones don't dump core on errorMessage == NULL
5025  * is the undocumented fact that printfPQExpBuffer does nothing when passed
5026  * a null PQExpBuffer pointer.)
5027  */
5028 static int
5030 {
5031  const char *service = conninfo_getval(options, "service");
5032  char serviceFile[MAXPGPATH];
5033  char *env;
5034  bool group_found = false;
5035  int status;
5036  struct stat stat_buf;
5037 
5038  /*
5039  * We have to special-case the environment variable PGSERVICE here, since
5040  * this is and should be called before inserting environment defaults for
5041  * other connection options.
5042  */
5043  if (service == NULL)
5044  service = getenv("PGSERVICE");
5045 
5046  /* If no service name given, nothing to do */
5047  if (service == NULL)
5048  return 0;
5049 
5050  /*
5051  * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
5052  * exists).
5053  */
5054  if ((env = getenv("PGSERVICEFILE")) != NULL)
5055  strlcpy(serviceFile, env, sizeof(serviceFile));
5056  else
5057  {
5058  char homedir[MAXPGPATH];
5059 
5060  if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5061  goto next_file;
5062  snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5063  if (stat(serviceFile, &stat_buf) != 0)
5064  goto next_file;
5065  }
5066 
5067  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5068  if (group_found || status != 0)
5069  return status;
5070 
5071 next_file:
5072 
5073  /*
5074  * This could be used by any application so we can't use the binary
5075  * location to find our config files.
5076  */
5077  snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5078  getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5079  if (stat(serviceFile, &stat_buf) != 0)
5080  goto last_file;
5081 
5082  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5083  if (status != 0)
5084  return status;
5085 
5086 last_file:
5087  if (!group_found)
5088  {
5089  printfPQExpBuffer(errorMessage,
5090  libpq_gettext("definition of service \"%s\" not found\n"), service);
5091  return 3;
5092  }
5093 
5094  return 0;
5095 }
5096 
5097 static int
5098 parseServiceFile(const char *serviceFile,
5099  const char *service,
5100  PQconninfoOption *options,
5101  PQExpBuffer errorMessage,
5102  bool *group_found)
5103 {
5104  int result = 0,
5105  linenr = 0,
5106  i;
5107  FILE *f;
5108  char *line;
5109  StringInfoData linebuf;
5110 
5111  *group_found = false;
5112 
5113  f = fopen(serviceFile, "r");
5114  if (f == NULL)
5115  {
5116  printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
5117  serviceFile);
5118  return 1;
5119  }
5120 
5121  initStringInfo(&linebuf);
5122 
5123  while (pg_get_line_buf(f, &linebuf))
5124  {
5125  linenr++;
5126 
5127  /* ignore whitespace at end of line, especially the newline */
5128  while (linebuf.len > 0 &&
5129  isspace((unsigned char) linebuf.data[linebuf.len - 1]))
5130  linebuf.data[--linebuf.len] = '\0';
5131 
5132  line = linebuf.data;
5133 
5134  /* ignore leading whitespace too */
5135  while (*line && isspace((unsigned char) line[0]))
5136  line++;
5137 
5138  /* ignore comments and empty lines */
5139  if (line[0] == '\0' || line[0] == '#')
5140  continue;
5141 
5142  /* Check for right groupname */
5143  if (line[0] == '[')
5144  {
5145  if (*group_found)
5146  {
5147  /* end of desired group reached; return success */
5148  goto exit;
5149  }
5150 
5151  if (strncmp(line + 1, service, strlen(service)) == 0 &&
5152  line[strlen(service) + 1] == ']')
5153  *group_found = true;
5154  else
5155  *group_found = false;
5156  }
5157  else
5158  {
5159  if (*group_found)
5160  {
5161  /*
5162  * Finally, we are in the right group and can parse the line
5163  */
5164  char *key,
5165  *val;
5166  bool found_keyword;
5167 
5168 #ifdef USE_LDAP
5169  if (strncmp(line, "ldap", 4) == 0)
5170  {
5171  int rc = ldapServiceLookup(line, options, errorMessage);
5172 
5173  /* if rc = 2, go on reading for fallback */
5174  switch (rc)
5175  {
5176  case 0:
5177  goto exit;
5178  case 1:
5179  case 3:
5180  result = 3;
5181  goto exit;
5182  case 2:
5183  continue;
5184  }
5185  }
5186 #endif
5187 
5188  key = line;
5189  val = strchr(line, '=');
5190  if (val == NULL)
5191  {
5192  printfPQExpBuffer(errorMessage,
5193  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5194  serviceFile,
5195  linenr);
5196  result = 3;
5197  goto exit;
5198  }
5199  *val++ = '\0';
5200 
5201  if (strcmp(key, "service") == 0)
5202  {
5203  printfPQExpBuffer(errorMessage,
5204  libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
5205  serviceFile,
5206  linenr);
5207  result = 3;
5208  goto exit;
5209  }
5210 
5211  /*
5212  * Set the parameter --- but don't override any previous
5213  * explicit setting.
5214  */
5215  found_keyword = false;
5216  for (i = 0; options[i].keyword; i++)
5217  {
5218  if (strcmp(options[i].keyword, key) == 0)
5219  {
5220  if (options[i].val == NULL)
5221  options[i].val = strdup(val);
5222  if (!options[i].val)
5223  {
5224  printfPQExpBuffer(errorMessage,
5225  libpq_gettext("out of memory\n"));
5226  result = 3;
5227  goto exit;
5228  }
5229  found_keyword = true;
5230  break;
5231  }
5232  }
5233 
5234  if (!found_keyword)
5235  {
5236  printfPQExpBuffer(errorMessage,
5237  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5238  serviceFile,
5239  linenr);
5240  result = 3;
5241  goto exit;
5242  }
5243  }
5244  }
5245  }
5246 
5247 exit:
5248  fclose(f);
5249  pfree(linebuf.data);
5250 
5251  return result;
5252 }
5253 
5254 
5255 /*
5256  * PQconninfoParse
5257  *
5258  * Parse a string like PQconnectdb() would do and return the
5259  * resulting connection options array. NULL is returned on failure.
5260  * The result contains only options specified directly in the string,
5261  * not any possible default values.
5262  *
5263  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
5264  * string on failure (use PQfreemem to free it). In out-of-memory conditions
5265  * both *errmsg and the result could be NULL.
5266  *
5267  * NOTE: the returned array is dynamically allocated and should
5268  * be freed when no longer needed via PQconninfoFree().
5269  */
5271 PQconninfoParse(const char *conninfo, char **errmsg)
5272 {
5273  PQExpBufferData errorBuf;
5274  PQconninfoOption *connOptions;
5275 
5276  if (errmsg)
5277  *errmsg = NULL; /* default */
5278  initPQExpBuffer(&errorBuf);
5279  if (PQExpBufferDataBroken(errorBuf))
5280  return NULL; /* out of memory already :-( */
5281  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5282  if (connOptions == NULL && errmsg)
5283  *errmsg = errorBuf.data;
5284  else
5285  termPQExpBuffer(&errorBuf);
5286  return connOptions;
5287 }
5288 
5289 /*
5290  * Build a working copy of the constant PQconninfoOptions array.
5291  */
5292 static PQconninfoOption *
5294 {
5296  PQconninfoOption *opt_dest;
5297  const internalPQconninfoOption *cur_opt;
5298 
5299  /*
5300  * Get enough memory for all options in PQconninfoOptions, even if some
5301  * end up being filtered out.
5302  */
5303  options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
5304  if (options == NULL)
5305  {
5306  printfPQExpBuffer(errorMessage,
5307  libpq_gettext("out of memory\n"));
5308  return NULL;
5309  }
5310  opt_dest = options;
5311 
5312  for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5313  {
5314  /* Only copy the public part of the struct, not the full internal */
5315  memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5316  opt_dest++;
5317  }
5318  MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5319 
5320  return options;
5321 }
5322 
5323 /*
5324  * Connection string parser
5325  *
5326  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
5327  * Otherwise, NULL is returned and an error message is left in errorMessage.
5328  *
5329  * If use_defaults is true, default values are filled in (from a service file,
5330  * environment variables, etc).
5331  */
5332 static PQconninfoOption *
5333 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
5334  bool use_defaults)
5335 {
5336  /* Parse as URI if connection string matches URI prefix */
5337  if (uri_prefix_length(connstr) != 0)
5338  return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5339 
5340  /* Parse as default otherwise */
5341  return conninfo_parse(connstr, errorMessage, use_defaults);
5342 }
5343 
5344 /*
5345  * Checks if connection string starts with either of the valid URI prefix
5346  * designators.
5347  *
5348  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
5349  *
5350  * XXX this is duplicated in psql/common.c.
5351  */
5352 static int
5354 {
5355  if (strncmp(connstr, uri_designator,
5356  sizeof(uri_designator) - 1) == 0)
5357  return sizeof(uri_designator) - 1;
5358 
5359  if (strncmp(connstr, short_uri_designator,
5360  sizeof(short_uri_designator) - 1) == 0)
5361  return sizeof(short_uri_designator) - 1;
5362 
5363  return 0;
5364 }
5365 
5366 /*
5367  * Recognized connection string either starts with a valid URI prefix or
5368  * contains a "=" in it.
5369  *
5370  * Must be consistent with parse_connection_string: anything for which this
5371  * returns true should at least look like it's parseable by that routine.
5372  *
5373  * XXX this is duplicated in psql/common.c
5374  */
5375 static bool
5377 {
5378  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5379 }
5380 
5381 /*
5382  * Subroutine for parse_connection_string
5383  *
5384  * Deal with a string containing key=value pairs.
5385  */
5386 static PQconninfoOption *
5387 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5388  bool use_defaults)
5389 {
5390  char *pname;
5391  char *pval;
5392  char *buf;
5393  char *cp;
5394  char *cp2;
5396 
5397  /* Make a working copy of PQconninfoOptions */
5398  options = conninfo_init(errorMessage);
5399  if (options == NULL)
5400  return NULL;
5401 
5402  /* Need a modifiable copy of the input string */
5403  if ((buf = strdup(conninfo)) == NULL)
5404  {
5405  printfPQExpBuffer(errorMessage,
5406  libpq_gettext("out of memory\n"));
5407  PQconninfoFree(options);
5408  return NULL;
5409  }
5410  cp = buf;
5411 
5412  while (*cp)
5413  {
5414  /* Skip blanks before the parameter name */
5415  if (isspace((unsigned char) *cp))
5416  {
5417  cp++;
5418  continue;
5419  }
5420 
5421  /* Get the parameter name */
5422  pname = cp;
5423  while (*cp)
5424  {
5425  if (*cp == '=')
5426  break;
5427  if (isspace((unsigned char) *cp))
5428  {
5429  *cp++ = '\0';
5430  while (*cp)
5431  {
5432  if (!isspace((unsigned char) *cp))
5433  break;
5434  cp++;
5435  }
5436  break;
5437  }
5438  cp++;
5439  }
5440 
5441  /* Check that there is a following '=' */
5442  if (*cp != '=')
5443  {
5444  printfPQExpBuffer(errorMessage,
5445  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
5446  pname);
5447  PQconninfoFree(options);
5448  free(buf);
5449  return NULL;
5450  }
5451  *cp++ = '\0';
5452 
5453  /* Skip blanks after the '=' */
5454  while (*cp)
5455  {
5456  if (!isspace((unsigned char) *cp))
5457  break;
5458  cp++;
5459  }
5460 
5461  /* Get the parameter value */
5462  pval = cp;
5463 
5464  if (*cp != '\'')
5465  {
5466  cp2 = pval;
5467  while (*cp)
5468  {
5469  if (isspace((unsigned char) *cp))
5470  {
5471  *cp++ = '\0';
5472  break;
5473  }
5474  if (*cp == '\\')
5475  {
5476  cp++;
5477  if (*cp != '\0')
5478  *cp2++ = *cp++;
5479  }
5480  else
5481  *cp2++ = *cp++;
5482  }
5483  *cp2 = '\0';
5484  }
5485  else
5486  {
5487  cp2 = pval;
5488  cp++;
5489  for (;;)
5490  {
5491  if (*cp == '\0')
5492  {
5493  printfPQExpBuffer(errorMessage,
5494  libpq_gettext("unterminated quoted string in connection info string\n"));
5495  PQconninfoFree(options);
5496  free(buf);
5497  return NULL;
5498  }
5499  if (*cp == '\\')
5500  {
5501  cp++;
5502  if (*cp != '\0')
5503  *cp2++ = *cp++;
5504  continue;
5505  }
5506  if (*cp == '\'')
5507  {
5508  *cp2 = '\0';
5509  cp++;
5510  break;
5511  }
5512  *cp2++ = *cp++;
5513  }
5514  }
5515 
5516  /*
5517  * Now that we have the name and the value, store the record.
5518  */
5519  if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5520  {
5521  PQconninfoFree(options);
5522  free(buf);
5523  return NULL;
5524  }
5525  }
5526 
5527  /* Done with the modifiable input string */
5528  free(buf);
5529 
5530  /*
5531  * Add in defaults if the caller wants that.
5532  */
5533  if (use_defaults)
5534  {
5535  if (!conninfo_add_defaults(options, errorMessage))
5536  {
5537  PQconninfoFree(options);
5538  return NULL;
5539  }
5540  }
5541 
5542  return options;
5543 }
5544 
5545 /*
5546  * Conninfo array parser routine
5547  *
5548  * If successful, a malloc'd PQconninfoOption array is returned.
5549  * If not successful, NULL is returned and an error message is
5550  * left in errorMessage.
5551  * Defaults are supplied (from a service file, environment variables, etc)
5552  * for unspecified options, but only if use_defaults is true.
5553  *
5554  * If expand_dbname is non-zero, and the value passed for the first occurrence
5555  * of "dbname" keyword is a connection string (as indicated by
5556  * recognized_connection_string) then parse and process it, overriding any
5557  * previously processed conflicting keywords. Subsequent keywords will take
5558  * precedence, however. In-tree programs generally specify expand_dbname=true,
5559  * so command-line arguments naming a database can use a connection string.
5560  * Some code acquires arbitrary database names from known-literal sources like
5561  * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
5562  * a database, in-tree code first wraps the name in a connection string.
5563  */
5564 static PQconninfoOption *
5565 conninfo_array_parse(const char *const *keywords, const char *const *values,
5566  PQExpBuffer errorMessage, bool use_defaults,
5567  int expand_dbname)
5568 {
5570  PQconninfoOption *dbname_options = NULL;
5572  int i = 0;
5573 
5574  /*
5575  * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5576  * actually a recognized connection string.
5577  */
5578  while (expand_dbname && keywords[i])
5579  {
5580  const char *pname = keywords[i];
5581  const char *pvalue = values[i];
5582 
5583  /* first find "dbname" if any */
5584  if (strcmp(pname, "dbname") == 0 && pvalue)
5585  {
5586  /*
5587  * If value is a connection string, parse it, but do not use
5588  * defaults here -- those get picked up later. We only want to
5589  * override for those parameters actually passed.
5590  */
5591  if (recognized_connection_string(pvalue))
5592  {
5593  dbname_options = parse_connection_string(pvalue, errorMessage, false);
5594  if (dbname_options == NULL)
5595  return NULL;
5596  }
5597  break;
5598  }
5599  ++i;
5600  }
5601 
5602  /* Make a working copy of PQconninfoOptions */
5603  options = conninfo_init(errorMessage);
5604  if (options == NULL)
5605  {
5606  PQconninfoFree(dbname_options);
5607  return NULL;
5608  }
5609 
5610  /* Parse the keywords/values arrays */
5611  i = 0;
5612  while (keywords[i])
5613  {
5614  const char *pname = keywords[i];
5615  const char *pvalue = values[i];
5616 
5617  if (pvalue != NULL && pvalue[0] != '\0')
5618  {
5619  /* Search for the param record */
5620  for (option = options; option->keyword != NULL; option++)
5621  {
5622  if (strcmp(option->keyword, pname) == 0)
5623  break;
5624  }
5625 
5626  /* Check for invalid connection option */
5627  if (option->keyword == NULL)
5628  {
5629  printfPQExpBuffer(errorMessage,
5630  libpq_gettext("invalid connection option \"%s\"\n"),
5631  pname);
5632  PQconninfoFree(options);
5633  PQconninfoFree(dbname_options);
5634  return NULL;
5635  }
5636 
5637  /*
5638  * If we are on the first dbname parameter, and we have a parsed
5639  * connection string, copy those parameters across, overriding any
5640  * existing previous settings.
5641  */
5642  if (strcmp(pname, "dbname") == 0 && dbname_options)
5643  {
5644  PQconninfoOption *str_option;
5645 
5646  for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5647  {
5648  if (str_option->val != NULL)
5649  {
5650  int k;
5651 
5652  for (k = 0; options[k].keyword; k++)
5653  {
5654  if (strcmp(options[k].keyword, str_option->keyword) == 0)
5655  {
5656  if (options[k].val)
5657  free(options[k].val);
5658  options[k].val = strdup(str_option->val);
5659  if (!options[k].val)
5660  {
5661  printfPQExpBuffer(errorMessage,
5662  libpq_gettext("out of memory\n"));
5663  PQconninfoFree(options);
5664  PQconninfoFree(dbname_options);
5665  return NULL;
5666  }
5667  break;
5668  }
5669  }
5670  }
5671  }
5672 
5673  /*
5674  * Forget the parsed connection string, so that any subsequent
5675  * dbname parameters will not be expanded.
5676  */
5677  PQconninfoFree(dbname_options);
5678  dbname_options = NULL;
5679  }
5680  else
5681  {
5682  /*
5683  * Store the value, overriding previous settings
5684  */
5685  if (option->val)
5686  free(option->val);
5687  option->val = strdup(pvalue);
5688  if (!option->val)
5689  {
5690  printfPQExpBuffer(errorMessage,
5691  libpq_gettext("out of memory\n"));
5692  PQconninfoFree(options);
5693  PQconninfoFree(dbname_options);
5694  return NULL;
5695  }
5696  }
5697  }
5698  ++i;
5699  }
5700  PQconninfoFree(dbname_options);
5701 
5702  /*
5703  * Add in defaults if the caller wants that.
5704  */
5705  if (use_defaults)
5706  {
5707  if (!conninfo_add_defaults(options, errorMessage))
5708  {
5709  PQconninfoFree(options);
5710  return NULL;
5711  }
5712  }
5713 
5714  return options;
5715 }
5716 
5717 /*
5718  * Add the default values for any unspecified options to the connection
5719  * options array.
5720  *
5721  * Defaults are obtained from a service file, environment variables, etc.
5722  *
5723  * Returns true if successful, otherwise false; errorMessage, if supplied,
5724  * is filled in upon failure. Note that failure to locate a default value
5725  * is not an error condition here --- we just leave the option's value as
5726  * NULL.
5727  */
5728 static bool
5730 {
5732  char *tmp;
5733 
5734  /*
5735  * If there's a service spec, use it to obtain any not-explicitly-given
5736  * parameters. Ignore error if no error message buffer is passed because
5737  * there is no way to pass back the failure message.
5738  */
5739  if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5740  return false;
5741 
5742  /*
5743  * Get the fallback resources for parameters not specified in the conninfo
5744  * string nor the service.
5745  */
5746  for (option = options; option->keyword != NULL; option++)
5747  {
5748  if (option->val != NULL)
5749  continue; /* Value was in conninfo or service */
5750 
5751  /*
5752  * Try to get the environment variable fallback
5753  */
5754  if (option->envvar != NULL)
5755  {
5756  if ((tmp = getenv(option->envvar)) != NULL)
5757  {
5758  option->val = strdup(tmp);
5759  if (!option->val)
5760  {
5761  if (errorMessage)
5762  printfPQExpBuffer(errorMessage,
5763  libpq_gettext("out of memory\n"));
5764  return false;
5765  }
5766  continue;
5767  }
5768  }
5769 
5770  /*
5771  * Interpret the deprecated PGREQUIRESSL environment variable. Per
5772  * tradition, translate values starting with "1" to sslmode=require,
5773  * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
5774  * PGSSLMODE takes precedence; the opposite was true before v9.3.
5775  */
5776  if (strcmp(option->keyword, "sslmode") == 0)
5777  {
5778  const char *requiresslenv = getenv("PGREQUIRESSL");
5779 
5780  if (requiresslenv != NULL && requiresslenv[0] == '1')
5781  {
5782  option->val = strdup("require");
5783  if (!option->val)
5784  {
5785  if (errorMessage)
5786  printfPQExpBuffer(errorMessage,
5787  libpq_gettext("out of memory\n"));
5788  return false;
5789  }
5790  continue;
5791  }
5792  }
5793 
5794  /*
5795  * No environment variable specified or the variable isn't set - try
5796  * compiled-in default
5797  */
5798  if (option->compiled != NULL)
5799  {
5800  option->val = strdup(option->compiled);
5801  if (!option->val)
5802  {
5803  if (errorMessage)
5804  printfPQExpBuffer(errorMessage,
5805  libpq_gettext("out of memory\n"));
5806  return false;
5807  }
5808  continue;
5809  }
5810 
5811  /*
5812  * Special handling for "user" option. Note that if pg_fe_getauthname
5813  * fails, we just leave the value as NULL; there's no need for this to
5814  * be an error condition if the caller provides a user name. The only
5815  * reason we do this now at all is so that callers of PQconndefaults
5816  * will see a correct default (barring error, of course).
5817  */
5818  if (strcmp(option->keyword, "user") == 0)
5819  {
5820  option->val = pg_fe_getauthname(NULL);
5821  continue;
5822  }
5823  }
5824 
5825  return true;
5826 }
5827 
5828 /*
5829  * Subroutine for parse_connection_string
5830  *
5831  * Deal with a URI connection string.
5832  */
5833 static PQconninfoOption *
5834 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
5835  bool use_defaults)
5836 {
5838 
5839  /* Make a working copy of PQconninfoOptions */
5840  options = conninfo_init(errorMessage);
5841  if (options == NULL)
5842  return NULL;
5843 
5844  if (!conninfo_uri_parse_options(options, uri, errorMessage))
5845  {
5846  PQconninfoFree(options);
5847  return NULL;
5848  }
5849 
5850  /*
5851  * Add in defaults if the caller wants that.
5852  */
5853  if (use_defaults)
5854  {
5855  if (!conninfo_add_defaults(options, errorMessage))
5856  {
5857  PQconninfoFree(options);
5858  return NULL;
5859  }
5860  }
5861 
5862  return options;
5863 }
5864 
5865 /*
5866  * conninfo_uri_parse_options
5867  * Actual URI parser.
5868  *
5869  * If successful, returns true while the options array is filled with parsed
5870  * options from the URI.
5871  * If not successful, returns false and fills errorMessage accordingly.
5872  *
5873  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
5874  * 3986):
5875  *
5876  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
5877  *
5878  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
5879  * by literal square brackets. As an extension, we also allow multiple
5880  * netloc[:port] specifications, separated by commas:
5881  *
5882  * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
5883  *
5884  * Any of the URI parts might use percent-encoding (%xy).
5885  */
5886 static bool
5888  PQExpBuffer errorMessage)
5889 {
5890  int prefix_len;
5891  char *p;
5892  char *buf = NULL;
5893  char *start;
5894  char prevchar = '\0';
5895  char *user = NULL;
5896  char *host = NULL;
5897  bool retval = false;
5898  PQExpBufferData hostbuf;
5899  PQExpBufferData portbuf;
5900 
5901  initPQExpBuffer(&hostbuf);
5902  initPQExpBuffer(&portbuf);
5903  if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5904  {
5905  printfPQExpBuffer(errorMessage,
5906  libpq_gettext("out of memory\n"));
5907  goto cleanup;
5908  }
5909 
5910  /* need a modifiable copy of the input URI */
5911  buf = strdup(uri);
5912  if (buf == NULL)
5913  {
5914  printfPQExpBuffer(errorMessage,
5915  libpq_gettext("out of memory\n"));
5916  goto cleanup;
5917  }
5918  start = buf;
5919 
5920  /* Skip the URI prefix */
5921  prefix_len = uri_prefix_length(uri);
5922  if (prefix_len == 0)
5923  {
5924  /* Should never happen */
5925  printfPQExpBuffer(errorMessage,
5926  libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
5927  uri);
5928  goto cleanup;
5929  }
5930  start += prefix_len;
5931  p = start;
5932 
5933  /* Look ahead for possible user credentials designator */
5934  while (*p && *p != '@' && *p != '/')
5935  ++p;
5936  if (*p == '@')
5937  {
5938  /*
5939  * Found username/password designator, so URI should be of the form
5940  * "scheme://user[:password]@[netloc]".
5941  */
5942  user = start;
5943 
5944  p = user;
5945  while (*p != ':' && *p != '@')
5946  ++p;
5947 
5948  /* Save last char and cut off at end of user name */
5949  prevchar = *p;
5950  *p = '\0';
5951 
5952  if (*user &&
5953  !conninfo_storeval(options, "user", user,
5954  errorMessage, false, true))
5955  goto cleanup;
5956 
5957  if (prevchar == ':')
5958  {
5959  const char *password = p + 1;
5960 
5961  while (*p != '@')
5962  ++p;
5963  *p = '\0';
5964 
5965  if (*password &&
5966  !conninfo_storeval(options, "password", password,
5967  errorMessage, false, true))
5968  goto cleanup;
5969  }
5970 
5971  /* Advance past end of parsed user name or password token */
5972  ++p;
5973  }
5974  else
5975  {
5976  /*
5977  * No username/password designator found. Reset to start of URI.
5978  */
5979  p = start;
5980  }
5981 
5982  /*
5983  * There may be multiple netloc[:port] pairs, each separated from the next
5984  * by a comma. When we initially enter this loop, "p" has been
5985  * incremented past optional URI credential information at this point and
5986  * now points at the "netloc" part of the URI. On subsequent loop
5987  * iterations, "p" has been incremented past the comma separator and now
5988  * points at the start of the next "netloc".
5989  */
5990  for (;;)
5991  {
5992  /*
5993  * Look for IPv6 address.
5994  */
5995  if (*p == '[')
5996  {
5997  host = ++p;
5998  while (*p && *p != ']')
5999  ++p;
6000  if (!*p)
6001  {
6002  printfPQExpBuffer(errorMessage,
6003  libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
6004  uri);
6005  goto cleanup;
6006  }
6007  if (p == host)
6008  {
6009  printfPQExpBuffer(errorMessage,
6010  libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
6011  uri);
6012  goto cleanup;
6013  }
6014 
6015  /* Cut off the bracket and advance */
6016  *(p++) = '\0';
6017 
6018  /*
6019  * The address may be followed by a port specifier or a slash or a
6020  * query or a separator comma.
6021  */
6022  if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6023  {
6024  printfPQExpBuffer(errorMessage,
6025  libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
6026  *p, (int) (p - buf + 1), uri);
6027  goto cleanup;
6028  }
6029  }
6030  else
6031  {
6032  /* not an IPv6 address: DNS-named or IPv4 netloc */
6033  host = p;
6034 
6035  /*
6036  * Look for port specifier (colon) or end of host specifier
6037  * (slash) or query (question mark) or host separator (comma).
6038  */
6039  while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6040  ++p;
6041  }
6042 
6043  /* Save the hostname terminator before we null it */
6044  prevchar = *p;
6045  *p = '\0';
6046 
6047  appendPQExpBufferStr(&hostbuf, host);
6048 
6049  if (prevchar == ':')
6050  {
6051  const char *port = ++p; /* advance past host terminator */
6052 
6053  while (*p && *p != '/' && *p != '?' && *p != ',')
6054  ++p;
6055 
6056  prevchar = *p;
6057  *p = '\0';
6058 
6059  appendPQExpBufferStr(&portbuf, port);
6060  }
6061 
6062  if (prevchar != ',')
6063  break;
6064  ++p; /* advance past comma separator */
6065