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.
3875  */
3876  WSADATA wsaData;
3877 
3878  if (WSAStartup(MAKEWORD(1, 1), &wsaData))
3879  return NULL;
3880  WSASetLastError(0);
3881 #endif
3882 
3883  conn = (PGconn *) malloc(sizeof(PGconn));
3884  if (conn == NULL)
3885  {
3886 #ifdef WIN32
3887  WSACleanup();
3888 #endif
3889  return conn;
3890  }
3891 
3892  /* Zero all pointers and booleans */
3893  MemSet(conn, 0, sizeof(PGconn));
3894 
3895  /* install default notice hooks */
3898 
3899  conn->status = CONNECTION_BAD;
3900  conn->asyncStatus = PGASYNC_IDLE;
3901  conn->xactStatus = PQTRANS_IDLE;
3902  conn->options_valid = false;
3903  conn->nonblocking = false;
3905  conn->client_encoding = PG_SQL_ASCII;
3906  conn->std_strings = false; /* unless server says differently */
3907  conn->verbosity = PQERRORS_DEFAULT;
3909  conn->sock = PGINVALID_SOCKET;
3910 
3911  /*
3912  * We try to send at least 8K at a time, which is the usual size of pipe
3913  * buffers on Unix systems. That way, when we are sending a large amount
3914  * of data, we avoid incurring extra kernel context swaps for partial
3915  * bufferloads. The output buffer is initially made 16K in size, and we
3916  * try to dump it after accumulating 8K.
3917  *
3918  * With the same goal of minimizing context swaps, the input buffer will
3919  * be enlarged anytime it has less than 8K free, so we initially allocate
3920  * twice that.
3921  */
3922  conn->inBufSize = 16 * 1024;
3923  conn->inBuffer = (char *) malloc(conn->inBufSize);
3924  conn->outBufSize = 16 * 1024;
3925  conn->outBuffer = (char *) malloc(conn->outBufSize);
3926  conn->rowBufLen = 32;
3927  conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
3928  initPQExpBuffer(&conn->errorMessage);
3929  initPQExpBuffer(&conn->workBuffer);
3930 
3931  if (conn->inBuffer == NULL ||
3932  conn->outBuffer == NULL ||
3933  conn->rowBuf == NULL ||
3934  PQExpBufferBroken(&conn->errorMessage) ||
3935  PQExpBufferBroken(&conn->workBuffer))
3936  {
3937  /* out of memory already :-( */
3938  freePGconn(conn);
3939  conn = NULL;
3940  }
3941 
3942  return conn;
3943 }
3944 
3945 /*
3946  * freePGconn
3947  * - free an idle (closed) PGconn data structure
3948  *
3949  * NOTE: this should not overlap any functionality with closePGconn().
3950  * Clearing/resetting of transient state belongs there; what we do here is
3951  * release data that is to be held for the life of the PGconn structure.
3952  * If a value ought to be cleared/freed during PQreset(), do it there not here.
3953  */
3954 static void
3956 {
3957  int i;
3958 
3959  /* let any event procs clean up their state data */
3960  for (i = 0; i < conn->nEvents; i++)
3961  {
3962  PGEventConnDestroy evt;
3963 
3964  evt.conn = conn;
3965  (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3966  conn->events[i].passThrough);
3967  free(conn->events[i].name);
3968  }
3969 
3970  /* clean up pg_conn_host structures */
3971  if (conn->connhost != NULL)
3972  {
3973  for (i = 0; i < conn->nconnhost; ++i)
3974  {
3975  if (conn->connhost[i].host != NULL)
3976  free(conn->connhost[i].host);
3977  if (conn->connhost[i].hostaddr != NULL)
3978  free(conn->connhost[i].hostaddr);
3979  if (conn->connhost[i].port != NULL)
3980  free(conn->connhost[i].port);
3981  if (conn->connhost[i].password != NULL)
3982  {
3983  explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
3984  free(conn->connhost[i].password);
3985  }
3986  }
3987  free(conn->connhost);
3988  }
3989 
3990  if (conn->client_encoding_initial)
3992  if (conn->events)
3993  free(conn->events);
3994  if (conn->pghost)
3995  free(conn->pghost);
3996  if (conn->pghostaddr)
3997  free(conn->pghostaddr);
3998  if (conn->pgport)
3999  free(conn->pgport);
4000  if (conn->pgtty)
4001  free(conn->pgtty);
4002  if (conn->connect_timeout)
4003  free(conn->connect_timeout);
4004  if (conn->pgtcp_user_timeout)
4005  free(conn->pgtcp_user_timeout);
4006  if (conn->pgoptions)
4007  free(conn->pgoptions);
4008  if (conn->appname)
4009  free(conn->appname);
4010  if (conn->fbappname)
4011  free(conn->fbappname);
4012  if (conn->dbName)
4013  free(conn->dbName);
4014  if (conn->replication)
4015  free(conn->replication);
4016  if (conn->pguser)
4017  free(conn->pguser);
4018  if (conn->pgpass)
4019  {
4020  explicit_bzero(conn->pgpass, strlen(conn->pgpass));
4021  free(conn->pgpass);
4022  }
4023  if (conn->pgpassfile)
4024  free(conn->pgpassfile);
4025  if (conn->channel_binding)
4026  free(conn->channel_binding);
4027  if (conn->keepalives)
4028  free(conn->keepalives);
4029  if (conn->keepalives_idle)
4030  free(conn->keepalives_idle);
4031  if (conn->keepalives_interval)
4032  free(conn->keepalives_interval);
4033  if (conn->keepalives_count)
4034  free(conn->keepalives_count);
4035  if (conn->sslmode)
4036  free(conn->sslmode);
4037  if (conn->sslcert)
4038  free(conn->sslcert);
4039  if (conn->sslkey)
4040  free(conn->sslkey);
4041  if (conn->sslpassword)
4042  {
4043  explicit_bzero(conn->sslpassword, strlen(conn->sslpassword));
4044  free(conn->sslpassword);
4045  }
4046  if (conn->sslrootcert)
4047  free(conn->sslrootcert);
4048  if (conn->sslcrl)
4049  free(conn->sslcrl);
4050  if (conn->sslcompression)
4051  free(conn->sslcompression);
4052  if (conn->requirepeer)
4053  free(conn->requirepeer);
4054  if (conn->ssl_min_protocol_version)
4056  if (conn->ssl_max_protocol_version)
4058  if (conn->gssencmode)
4059  free(conn->gssencmode);
4060  if (conn->krbsrvname)
4061  free(conn->krbsrvname);
4062  if (conn->gsslib)
4063  free(conn->gsslib);
4064  if (conn->connip)
4065  free(conn->connip);
4066  /* Note that conn->Pfdebug is not ours to close or free */
4067  if (conn->last_query)
4068  free(conn->last_query);
4069  if (conn->write_err_msg)
4070  free(conn->write_err_msg);
4071  if (conn->inBuffer)
4072  free(conn->inBuffer);
4073  if (conn->outBuffer)
4074  free(conn->outBuffer);
4075  if (conn->rowBuf)
4076  free(conn->rowBuf);
4077  if (conn->target_session_attrs)
4078  free(conn->target_session_attrs);
4079  termPQExpBuffer(&conn->errorMessage);
4080  termPQExpBuffer(&conn->workBuffer);
4081 
4082  free(conn);
4083 
4084 #ifdef WIN32
4085  WSACleanup();
4086 #endif
4087 }
4088 
4089 /*
4090  * release_conn_addrinfo
4091  * - Free any addrinfo list in the PGconn.
4092  */
4093 static void
4095 {
4096  if (conn->addrlist)
4097  {
4099  conn->addrlist = NULL;
4100  conn->addr_cur = NULL; /* for safety */
4101  }
4102 }
4103 
4104 /*
4105  * sendTerminateConn
4106  * - Send a terminate message to backend.
4107  */
4108 static void
4110 {
4111  /*
4112  * Note that the protocol doesn't allow us to send Terminate messages
4113  * during the startup phase.
4114  */
4115  if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
4116  {
4117  /*
4118  * Try to send "close connection" message to backend. Ignore any
4119  * error.
4120  */
4121  pqPutMsgStart('X', false, conn);
4122  pqPutMsgEnd(conn);
4123  (void) pqFlush(conn);
4124  }
4125 }
4126 
4127 /*
4128  * closePGconn
4129  * - properly close a connection to the backend
4130  *
4131  * This should reset or release all transient state, but NOT the connection
4132  * parameters. On exit, the PGconn should be in condition to start a fresh
4133  * connection with the same parameters (see PQreset()).
4134  */
4135 static void
4137 {
4138  /*
4139  * If possible, send Terminate message to close the connection politely.
4140  */
4141  sendTerminateConn(conn);
4142 
4143  /*
4144  * Must reset the blocking status so a possible reconnect will work.
4145  *
4146  * Don't call PQsetnonblocking() because it will fail if it's unable to
4147  * flush the connection.
4148  */
4149  conn->nonblocking = false;
4150 
4151  /*
4152  * Close the connection, reset all transient state, flush I/O buffers.
4153  */
4154  pqDropConnection(conn, true);
4155  conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
4156  conn->asyncStatus = PGASYNC_IDLE;
4157  conn->xactStatus = PQTRANS_IDLE;
4158  pqClearAsyncResult(conn); /* deallocate result */
4160  release_conn_addrinfo(conn);
4161 
4162  /* Reset all state obtained from server, too */
4163  pqDropServerData(conn);
4164 }
4165 
4166 /*
4167  * PQfinish: properly close a connection to the backend. Also frees
4168  * the PGconn data structure so it shouldn't be re-used after this.
4169  */
4170 void
4172 {
4173  if (conn)
4174  {
4175  closePGconn(conn);
4176  freePGconn(conn);
4177  }
4178 }
4179 
4180 /*
4181  * PQreset: resets the connection to the backend by closing the
4182  * existing connection and creating a new one.
4183  */
4184 void
4186 {
4187  if (conn)
4188  {
4189  closePGconn(conn);
4190 
4191  if (connectDBStart(conn) && connectDBComplete(conn))
4192  {
4193  /*
4194  * Notify event procs of successful reset. We treat an event proc
4195  * failure as disabling the connection ... good idea?
4196  */
4197  int i;
4198 
4199  for (i = 0; i < conn->nEvents; i++)
4200  {
4201  PGEventConnReset evt;
4202 
4203  evt.conn = conn;
4204  if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4205  conn->events[i].passThrough))
4206  {
4207  conn->status = CONNECTION_BAD;
4209  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4210  conn->events[i].name);
4211  break;
4212  }
4213  }
4214  }
4215  }
4216 }
4217 
4218 
4219 /*
4220  * PQresetStart:
4221  * resets the connection to the backend
4222  * closes the existing connection and makes a new one
4223  * Returns 1 on success, 0 on failure.
4224  */
4225 int
4227 {
4228  if (conn)
4229  {
4230  closePGconn(conn);
4231 
4232  return connectDBStart(conn);
4233  }
4234 
4235  return 0;
4236 }
4237 
4238 
4239 /*
4240  * PQresetPoll:
4241  * resets the connection to the backend
4242  * closes the existing connection and makes a new one
4243  */
4246 {
4247  if (conn)
4248  {
4250 
4251  if (status == PGRES_POLLING_OK)
4252  {
4253  /*
4254  * Notify event procs of successful reset. We treat an event proc
4255  * failure as disabling the connection ... good idea?
4256  */
4257  int i;
4258 
4259  for (i = 0; i < conn->nEvents; i++)
4260  {
4261  PGEventConnReset evt;
4262 
4263  evt.conn = conn;
4264  if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4265  conn->events[i].passThrough))
4266  {
4267  conn->status = CONNECTION_BAD;
4269  libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4270  conn->events[i].name);
4271  return PGRES_POLLING_FAILED;
4272  }
4273  }
4274  }
4275 
4276  return status;
4277  }
4278 
4279  return PGRES_POLLING_FAILED;
4280 }
4281 
4282 /*
4283  * PQgetCancel: get a PGcancel structure corresponding to a connection.
4284  *
4285  * A copy is needed to be able to cancel a running query from a different
4286  * thread. If the same structure is used all structure members would have
4287  * to be individually locked (if the entire structure was locked, it would
4288  * be impossible to cancel a synchronous query because the structure would
4289  * have to stay locked for the duration of the query).
4290  */
4291 PGcancel *
4293 {
4294  PGcancel *cancel;
4295 
4296  if (!conn)
4297  return NULL;
4298 
4299  if (conn->sock == PGINVALID_SOCKET)
4300  return NULL;
4301 
4302  cancel = malloc(sizeof(PGcancel));
4303  if (cancel == NULL)
4304  return NULL;
4305 
4306  memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
4307  cancel->be_pid = conn->be_pid;
4308  cancel->be_key = conn->be_key;
4309 
4310  return cancel;
4311 }
4312 
4313 /* PQfreeCancel: free a cancel structure */
4314 void
4316 {
4317  if (cancel)
4318  free(cancel);
4319 }
4320 
4321 
4322 /*
4323  * PQcancel and PQrequestCancel: attempt to request cancellation of the
4324  * current operation.
4325  *
4326  * The return value is true if the cancel request was successfully
4327  * dispatched, false if not (in which case an error message is available).
4328  * Note: successful dispatch is no guarantee that there will be any effect at
4329  * the backend. The application must read the operation result as usual.
4330  *
4331  * CAUTION: we want this routine to be safely callable from a signal handler
4332  * (for example, an application might want to call it in a SIGINT handler).
4333  * This means we cannot use any C library routine that might be non-reentrant.
4334  * malloc/free are often non-reentrant, and anything that might call them is
4335  * just as dangerous. We avoid sprintf here for that reason. Building up
4336  * error messages with strcpy/strcat is tedious but should be quite safe.
4337  * We also save/restore errno in case the signal handler support doesn't.
4338  *
4339  * internal_cancel() is an internal helper function to make code-sharing
4340  * between the two versions of the cancel function possible.
4341  */
4342 static int
4343 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
4344  char *errbuf, int errbufsize)
4345 {
4346  int save_errno = SOCK_ERRNO;
4347  pgsocket tmpsock = PGINVALID_SOCKET;
4348  char sebuf[PG_STRERROR_R_BUFLEN];
4349  int maxlen;
4350  struct
4351  {
4352  uint32 packetlen;
4354  } crp;
4355 
4356  /*
4357  * We need to open a temporary connection to the postmaster. Do this with
4358  * only kernel calls.
4359  */
4360  if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4361  {
4362  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4363  goto cancel_errReturn;
4364  }
4365 retry3:
4366  if (connect(tmpsock, (struct sockaddr *) &raddr->addr,
4367  raddr->salen) < 0)
4368  {
4369  if (SOCK_ERRNO == EINTR)
4370  /* Interrupted system call - we'll just try again */
4371  goto retry3;
4372  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4373  goto cancel_errReturn;
4374  }
4375 
4376  /*
4377  * We needn't set nonblocking I/O or NODELAY options here.
4378  */
4379 
4380  /* Create and send the cancel request packet. */
4381 
4382  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4383  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4384  crp.cp.backendPID = pg_hton32(be_pid);
4385  crp.cp.cancelAuthCode = pg_hton32(be_key);
4386 
4387 retry4:
4388  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4389  {
4390  if (SOCK_ERRNO == EINTR)
4391  /* Interrupted system call - we'll just try again */
4392  goto retry4;
4393  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4394  goto cancel_errReturn;
4395  }
4396 
4397  /*
4398  * Wait for the postmaster to close the connection, which indicates that
4399  * it's processed the request. Without this delay, we might issue another
4400  * command only to find that our cancel zaps that command instead of the
4401  * one we thought we were canceling. Note we don't actually expect this
4402  * read to obtain any data, we are just waiting for EOF to be signaled.
4403  */
4404 retry5:
4405  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4406  {
4407  if (SOCK_ERRNO == EINTR)
4408  /* Interrupted system call - we'll just try again */
4409  goto retry5;
4410  /* we ignore other error conditions */
4411  }
4412 
4413  /* All done */
4414  closesocket(tmpsock);
4415  SOCK_ERRNO_SET(save_errno);
4416  return true;
4417 
4418 cancel_errReturn:
4419 
4420  /*
4421  * Make sure we don't overflow the error buffer. Leave space for the \n at
4422  * the end, and for the terminating zero.
4423  */
4424  maxlen = errbufsize - strlen(errbuf) - 2;
4425  if (maxlen >= 0)
4426  {
4427  strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
4428  maxlen);
4429  strcat(errbuf, "\n");
4430  }
4431  if (tmpsock != PGINVALID_SOCKET)
4432  closesocket(tmpsock);
4433  SOCK_ERRNO_SET(save_errno);
4434  return false;
4435 }
4436 
4437 /*
4438  * PQcancel: request query cancel
4439  *
4440  * Returns true if able to send the cancel request, false if not.
4441  *
4442  * On failure, an error message is stored in *errbuf, which must be of size
4443  * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
4444  * success return.
4445  */
4446 int
4447 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
4448 {
4449  if (!cancel)
4450  {
4451  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4452  return false;
4453  }
4454 
4455  return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4456  errbuf, errbufsize);
4457 }
4458 
4459 /*
4460  * PQrequestCancel: old, not thread-safe function for requesting query cancel
4461  *
4462  * Returns true if able to send the cancel request, false if not.
4463  *
4464  * On failure, the error message is saved in conn->errorMessage; this means
4465  * that this can't be used when there might be other active operations on
4466  * the connection object.
4467  *
4468  * NOTE: error messages will be cut off at the current size of the
4469  * error message buffer, since we dare not try to expand conn->errorMessage!
4470  */
4471 int
4473 {
4474  int r;
4475 
4476  /* Check we have an open connection */
4477  if (!conn)
4478  return false;
4479 
4480  if (conn->sock == PGINVALID_SOCKET)
4481  {
4482  strlcpy(conn->errorMessage.data,
4483  "PQrequestCancel() -- connection is not open\n",
4484  conn->errorMessage.maxlen);
4485  conn->errorMessage.len = strlen(conn->errorMessage.data);
4486 
4487  return false;
4488  }
4489 
4490  r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
4491  conn->errorMessage.data, conn->errorMessage.maxlen);
4492 
4493  if (!r)
4494  conn->errorMessage.len = strlen(conn->errorMessage.data);
4495 
4496  return r;
4497 }
4498 
4499 
4500 /*
4501  * pqPacketSend() -- convenience routine to send a message to server.
4502  *
4503  * pack_type: the single-byte message type code. (Pass zero for startup
4504  * packets, which have no message type code.)
4505  *
4506  * buf, buf_len: contents of message. The given length includes only what
4507  * is in buf; the message type and message length fields are added here.
4508  *
4509  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4510  * SIDE_EFFECTS: may block.
4511  *
4512  * Note: all messages sent with this routine have a length word, whether
4513  * it's protocol 2.0 or 3.0.
4514  */
4515 int
4516 pqPacketSend(PGconn *conn, char pack_type,
4517  const void *buf, size_t buf_len)
4518 {
4519  /* Start the message. */
4520  if (pqPutMsgStart(pack_type, true, conn))
4521  return STATUS_ERROR;
4522 
4523  /* Send the message body. */
4524  if (pqPutnchar(buf, buf_len, conn))
4525  return STATUS_ERROR;
4526 
4527  /* Finish the message. */
4528  if (pqPutMsgEnd(conn))
4529  return STATUS_ERROR;
4530 
4531  /* Flush to ensure backend gets it. */
4532  if (pqFlush(conn))
4533  return STATUS_ERROR;
4534 
4535  return STATUS_OK;
4536 }
4537 
4538 #ifdef USE_LDAP
4539 
4540 #define LDAP_URL "ldap://"
4541 #define LDAP_DEF_PORT 389
4542 #define PGLDAP_TIMEOUT 2
4543 
4544 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4545 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4546 
4547 
4548 /*
4549  * ldapServiceLookup
4550  *
4551  * Search the LDAP URL passed as first argument, treat the result as a
4552  * string of connection options that are parsed and added to the array of
4553  * options passed as second argument.
4554  *
4555  * LDAP URLs must conform to RFC 1959 without escape sequences.
4556  * ldap://host:port/dn?attributes?scope?filter?extensions
4557  *
4558  * Returns
4559  * 0 if the lookup was successful,
4560  * 1 if the connection to the LDAP server could be established but
4561  * the search was unsuccessful,
4562  * 2 if a connection could not be established, and
4563  * 3 if a fatal error occurred.
4564  *
4565  * An error message is returned in the third argument for return codes 1 and 3.
4566  */
4567 static int
4568 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4569  PQExpBuffer errorMessage)
4570 {
4571  int port = LDAP_DEF_PORT,
4572  scope,
4573  rc,
4574  size,
4575  state,
4576  oldstate,
4577  i;
4578 #ifndef WIN32
4579  int msgid;
4580 #endif
4581  bool found_keyword;
4582  char *url,
4583  *hostname,
4584  *portstr,
4585  *endptr,
4586  *dn,
4587  *scopestr,
4588  *filter,
4589  *result,
4590  *p,
4591  *p1 = NULL,
4592  *optname = NULL,
4593  *optval = NULL;
4594  char *attrs[2] = {NULL, NULL};
4595  LDAP *ld = NULL;
4596  LDAPMessage *res,
4597  *entry;
4598  struct berval **values;
4599  LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4600 
4601  if ((url = strdup(purl)) == NULL)
4602  {
4603  printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4604  return 3;
4605  }
4606 
4607  /*
4608  * Parse URL components, check for correctness. Basically, url has '\0'
4609  * placed at component boundaries and variables are pointed at each
4610  * component.
4611  */
4612 
4613  if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4614  {
4615  printfPQExpBuffer(errorMessage,
4616  libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
4617  free(url);
4618  return 3;
4619  }
4620 
4621  /* hostname */
4622  hostname = url + strlen(LDAP_URL);
4623  if (*hostname == '/') /* no hostname? */
4624  hostname = DefaultHost; /* the default */
4625 
4626  /* dn, "distinguished name" */
4627  p = strchr(url + strlen(LDAP_URL), '/');
4628  if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4629  {
4630  printfPQExpBuffer(errorMessage,
4631  libpq_gettext("invalid LDAP URL \"%s\": missing distinguished name\n"),
4632  purl);
4633  free(url);
4634  return 3;
4635  }
4636  *p = '\0'; /* terminate hostname */
4637  dn = p + 1;
4638 
4639  /* attribute */
4640  if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4641  {
4642  printfPQExpBuffer(errorMessage,
4643  libpq_gettext("invalid LDAP URL \"%s\": must have exactly one attribute\n"),
4644  purl);
4645  free(url);
4646  return 3;
4647  }
4648  *p = '\0';
4649  attrs[0] = p + 1;
4650 
4651  /* scope */
4652  if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4653  {
4654  printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4655  free(url);
4656  return 3;
4657  }
4658  *p = '\0';
4659  scopestr = p + 1;
4660 
4661  /* filter */
4662  if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4663  {
4664  printfPQExpBuffer(errorMessage,
4665  libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
4666  free(url);
4667  return 3;
4668  }
4669  *p = '\0';
4670  filter = p + 1;
4671  if ((p = strchr(filter, '?')) != NULL)
4672  *p = '\0';
4673 
4674  /* port number? */
4675  if ((p1 = strchr(hostname, ':')) != NULL)
4676  {
4677  long lport;
4678 
4679  *p1 = '\0';
4680  portstr = p1 + 1;
4681  errno = 0;
4682  lport = strtol(portstr, &endptr, 10);
4683  if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4684  {
4685  printfPQExpBuffer(errorMessage,
4686  libpq_gettext("invalid LDAP URL \"%s\": invalid port number\n"),
4687  purl);
4688  free(url);
4689  return 3;
4690  }
4691  port = (int) lport;
4692  }
4693 
4694  /* Allow only one attribute */
4695  if (strchr(attrs[0], ',') != NULL)
4696  {
4697  printfPQExpBuffer(errorMessage,
4698  libpq_gettext("invalid LDAP URL \"%s\": must have exactly one attribute\n"),
4699  purl);
4700  free(url);
4701  return 3;
4702  }
4703 
4704  /* set scope */
4705  if (pg_strcasecmp(scopestr, "base") == 0)
4706  scope = LDAP_SCOPE_BASE;
4707  else if (pg_strcasecmp(scopestr, "one") == 0)
4708  scope = LDAP_SCOPE_ONELEVEL;
4709  else if (pg_strcasecmp(scopestr, "sub") == 0)
4710  scope = LDAP_SCOPE_SUBTREE;
4711  else
4712  {
4713  printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4714  free(url);
4715  return 3;
4716  }
4717 
4718  /* initialize LDAP structure */
4719  if ((ld = ldap_init(hostname, port)) == NULL)
4720  {
4721  printfPQExpBuffer(errorMessage,
4722  libpq_gettext("could not create LDAP structure\n"));
4723  free(url);
4724  return 3;
4725  }
4726 
4727  /*
4728  * Perform an explicit anonymous bind.
4729  *
4730  * LDAP does not require that an anonymous bind is performed explicitly,
4731  * but we want to distinguish between the case where LDAP bind does not
4732  * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4733  * service control file) and the case where querying the LDAP server fails
4734  * (return 1 to end parsing).
4735  *
4736  * Unfortunately there is no way of setting a timeout that works for both
4737  * Windows and OpenLDAP.
4738  */
4739 #ifdef WIN32
4740  /* the nonstandard ldap_connect function performs an anonymous bind */
4741  if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4742  {
4743  /* error or timeout in ldap_connect */
4744  free(url);
4745  ldap_unbind(ld);
4746  return 2;
4747  }
4748 #else /* !WIN32 */
4749  /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4750  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4751  {
4752  free(url);
4753  ldap_unbind(ld);
4754  return 3;
4755  }
4756 
4757  /* anonymous bind */
4758  if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4759  {
4760  /* error or network timeout */
4761  free(url);
4762  ldap_unbind(ld);
4763  return 2;
4764  }
4765 
4766  /* wait some time for the connection to succeed */
4767  res = NULL;
4768  if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4769  res == NULL)
4770  {
4771  /* error or timeout */
4772  if (res != NULL)
4773  ldap_msgfree(res);
4774  free(url);
4775  ldap_unbind(ld);
4776  return 2;
4777  }
4778  ldap_msgfree(res);
4779 
4780  /* reset timeout */
4781  time.tv_sec = -1;
4782  if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4783  {
4784  free(url);
4785  ldap_unbind(ld);
4786  return 3;
4787  }
4788 #endif /* WIN32 */
4789 
4790  /* search */
4791  res = NULL;
4792  if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4793  != LDAP_SUCCESS)
4794  {
4795  if (res != NULL)
4796  ldap_msgfree(res);
4797  printfPQExpBuffer(errorMessage,
4798  libpq_gettext("lookup on LDAP server failed: %s\n"),
4799  ldap_err2string(rc));
4800  ldap_unbind(ld);
4801  free(url);
4802  return 1;
4803  }
4804 
4805  /* complain if there was not exactly one result */
4806  if ((rc = ldap_count_entries(ld, res)) != 1)
4807  {
4808  printfPQExpBuffer(errorMessage,
4809  rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
4810  : libpq_gettext("no entry found on LDAP lookup\n"));
4811  ldap_msgfree(res);
4812  ldap_unbind(ld);
4813  free(url);
4814  return 1;
4815  }
4816 
4817  /* get entry */
4818  if ((entry = ldap_first_entry(ld, res)) == NULL)
4819  {
4820  /* should never happen */
4821  printfPQExpBuffer(errorMessage,
4822  libpq_gettext("no entry found on LDAP lookup\n"));
4823  ldap_msgfree(res);
4824  ldap_unbind(ld);
4825  free(url);
4826  return 1;
4827  }
4828 
4829  /* get values */
4830  if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4831  {
4832  printfPQExpBuffer(errorMessage,
4833  libpq_gettext("attribute has no values on LDAP lookup\n"));
4834  ldap_msgfree(res);
4835  ldap_unbind(ld);
4836  free(url);
4837  return 1;
4838  }
4839 
4840  ldap_msgfree(res);
4841  free(url);
4842 
4843  if (values[0] == NULL)
4844  {
4845  printfPQExpBuffer(errorMessage,
4846  libpq_gettext("attribute has no values on LDAP lookup\n"));
4847  ldap_value_free_len(values);
4848  ldap_unbind(ld);
4849  return 1;
4850  }
4851 
4852  /* concatenate values into a single string with newline terminators */
4853  size = 1; /* for the trailing null */
4854  for (i = 0; values[i] != NULL; i++)
4855  size += values[i]->bv_len + 1;
4856  if ((result = malloc(size)) == NULL)
4857  {
4858  printfPQExpBuffer(errorMessage,
4859  libpq_gettext("out of memory\n"));
4860  ldap_value_free_len(values);
4861  ldap_unbind(ld);
4862  return 3;
4863  }
4864  p = result;
4865  for (i = 0; values[i] != NULL; i++)
4866  {
4867  memcpy(p, values[i]->bv_val, values[i]->bv_len);
4868  p += values[i]->bv_len;
4869  *(p++) = '\n';
4870  }
4871  *p = '\0';
4872 
4873  ldap_value_free_len(values);
4874  ldap_unbind(ld);
4875 
4876  /* parse result string */
4877  oldstate = state = 0;
4878  for (p = result; *p != '\0'; ++p)
4879  {
4880  switch (state)
4881  {
4882  case 0: /* between entries */
4883  if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
4884  {
4885  optname = p;
4886  state = 1;
4887  }
4888  break;
4889  case 1: /* in option name */
4890  if (ld_is_sp_tab(*p))
4891  {
4892  *p = '\0';
4893  state = 2;
4894  }
4895  else if (ld_is_nl_cr(*p))
4896  {
4897  printfPQExpBuffer(errorMessage,
4898  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4899  optname);
4900  free(result);
4901  return 3;
4902  }
4903  else if (*p == '=')
4904  {
4905  *p = '\0';
4906  state = 3;
4907  }
4908  break;
4909  case 2: /* after option name */
4910  if (*p == '=')
4911  {
4912  state = 3;
4913  }
4914  else if (!ld_is_sp_tab(*p))
4915  {
4916  printfPQExpBuffer(errorMessage,
4917  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4918  optname);
4919  free(result);
4920  return 3;
4921  }
4922  break;
4923  case 3: /* before option value */
4924  if (*p == '\'')
4925  {
4926  optval = p + 1;
4927  p1 = p + 1;
4928  state = 5;
4929  }
4930  else if (ld_is_nl_cr(*p))
4931  {
4932  optval = optname + strlen(optname); /* empty */
4933  state = 0;
4934  }
4935  else if (!ld_is_sp_tab(*p))
4936  {
4937  optval = p;
4938  state = 4;
4939  }
4940  break;
4941  case 4: /* in unquoted option value */
4942  if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
4943  {
4944  *p = '\0';
4945  state = 0;
4946  }
4947  break;
4948  case 5: /* in quoted option value */
4949  if (*p == '\'')
4950  {
4951  *p1 = '\0';
4952  state = 0;
4953  }
4954  else if (*p == '\\')
4955  state = 6;
4956  else
4957  *(p1++) = *p;
4958  break;
4959  case 6: /* in quoted option value after escape */
4960  *(p1++) = *p;
4961  state = 5;
4962  break;
4963  }
4964 
4965  if (state == 0 && oldstate != 0)
4966  {
4967  found_keyword = false;
4968  for (i = 0; options[i].keyword; i++)
4969  {
4970  if (strcmp(options[i].keyword, optname) == 0)
4971  {
4972  if (options[i].val == NULL)
4973  {
4974  options[i].val = strdup(optval);
4975  if (!options[i].val)
4976  {
4977  printfPQExpBuffer(errorMessage,
4978  libpq_gettext("out of memory\n"));
4979  free(result);
4980  return 3;
4981  }
4982  }
4983  found_keyword = true;
4984  break;
4985  }
4986  }
4987  if (!found_keyword)
4988  {
4989  printfPQExpBuffer(errorMessage,
4990  libpq_gettext("invalid connection option \"%s\"\n"),
4991  optname);
4992  free(result);
4993  return 1;
4994  }
4995  optname = NULL;
4996  optval = NULL;
4997  }
4998  oldstate = state;
4999  }
5000 
5001  free(result);
5002 
5003  if (state == 5 || state == 6)
5004  {
5005  printfPQExpBuffer(errorMessage,
5006  libpq_gettext("unterminated quoted string in connection info string\n"));
5007  return 3;
5008  }
5009 
5010  return 0;
5011 }
5012 
5013 #endif /* USE_LDAP */
5014 
5015 /*
5016  * parseServiceInfo: if a service name has been given, look it up and absorb
5017  * connection options from it into *options.
5018  *
5019  * Returns 0 on success, nonzero on failure. On failure, if errorMessage
5020  * isn't null, also store an error message there. (Note: the only reason
5021  * this function and related ones don't dump core on errorMessage == NULL
5022  * is the undocumented fact that printfPQExpBuffer does nothing when passed
5023  * a null PQExpBuffer pointer.)
5024  */
5025 static int
5027 {
5028  const char *service = conninfo_getval(options, "service");
5029  char serviceFile[MAXPGPATH];
5030  char *env;
5031  bool group_found = false;
5032  int status;
5033  struct stat stat_buf;
5034 
5035  /*
5036  * We have to special-case the environment variable PGSERVICE here, since
5037  * this is and should be called before inserting environment defaults for
5038  * other connection options.
5039  */
5040  if (service == NULL)
5041  service = getenv("PGSERVICE");
5042 
5043  /* If no service name given, nothing to do */
5044  if (service == NULL)
5045  return 0;
5046 
5047  /*
5048  * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
5049  * exists).
5050  */
5051  if ((env = getenv("PGSERVICEFILE")) != NULL)
5052  strlcpy(serviceFile, env, sizeof(serviceFile));
5053  else
5054  {
5055  char homedir[MAXPGPATH];
5056 
5057  if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5058  goto next_file;
5059  snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5060  if (stat(serviceFile, &stat_buf) != 0)
5061  goto next_file;
5062  }
5063 
5064  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5065  if (group_found || status != 0)
5066  return status;
5067 
5068 next_file:
5069 
5070  /*
5071  * This could be used by any application so we can't use the binary
5072  * location to find our config files.
5073  */
5074  snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5075  getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5076  if (stat(serviceFile, &stat_buf) != 0)
5077  goto last_file;
5078 
5079  status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5080  if (status != 0)
5081  return status;
5082 
5083 last_file:
5084  if (!group_found)
5085  {
5086  printfPQExpBuffer(errorMessage,
5087  libpq_gettext("definition of service \"%s\" not found\n"), service);
5088  return 3;
5089  }
5090 
5091  return 0;
5092 }
5093 
5094 static int
5095 parseServiceFile(const char *serviceFile,
5096  const char *service,
5097  PQconninfoOption *options,
5098  PQExpBuffer errorMessage,
5099  bool *group_found)
5100 {
5101  int result = 0,
5102  linenr = 0,
5103  i;
5104  FILE *f;
5105  char *line;
5106  StringInfoData linebuf;
5107 
5108  *group_found = false;
5109 
5110  f = fopen(serviceFile, "r");
5111  if (f == NULL)
5112  {
5113  printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
5114  serviceFile);
5115  return 1;
5116  }
5117 
5118  initStringInfo(&linebuf);
5119 
5120  while (pg_get_line_buf(f, &linebuf))
5121  {
5122  linenr++;
5123 
5124  /* ignore whitespace at end of line, especially the newline */
5125  while (linebuf.len > 0 &&
5126  isspace((unsigned char) linebuf.data[linebuf.len - 1]))
5127  linebuf.data[--linebuf.len] = '\0';
5128 
5129  line = linebuf.data;
5130 
5131  /* ignore leading whitespace too */
5132  while (*line && isspace((unsigned char) line[0]))
5133  line++;
5134 
5135  /* ignore comments and empty lines */
5136  if (line[0] == '\0' || line[0] == '#')
5137  continue;
5138 
5139  /* Check for right groupname */
5140  if (line[0] == '[')
5141  {
5142  if (*group_found)
5143  {
5144  /* end of desired group reached; return success */
5145  goto exit;
5146  }
5147 
5148  if (strncmp(line + 1, service, strlen(service)) == 0 &&
5149  line[strlen(service) + 1] == ']')
5150  *group_found = true;
5151  else
5152  *group_found = false;
5153  }
5154  else
5155  {
5156  if (*group_found)
5157  {
5158  /*
5159  * Finally, we are in the right group and can parse the line
5160  */
5161  char *key,
5162  *val;
5163  bool found_keyword;
5164 
5165 #ifdef USE_LDAP
5166  if (strncmp(line, "ldap", 4) == 0)
5167  {
5168  int rc = ldapServiceLookup(line, options, errorMessage);
5169 
5170  /* if rc = 2, go on reading for fallback */
5171  switch (rc)
5172  {
5173  case 0:
5174  goto exit;
5175  case 1:
5176  case 3:
5177  result = 3;
5178  goto exit;
5179  case 2:
5180  continue;
5181  }
5182  }
5183 #endif
5184 
5185  key = line;
5186  val = strchr(line, '=');
5187  if (val == NULL)
5188  {
5189  printfPQExpBuffer(errorMessage,
5190  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5191  serviceFile,
5192  linenr);
5193  result = 3;
5194  goto exit;
5195  }
5196  *val++ = '\0';
5197 
5198  if (strcmp(key, "service") == 0)
5199  {
5200  printfPQExpBuffer(errorMessage,
5201  libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
5202  serviceFile,
5203  linenr);
5204  result = 3;
5205  goto exit;
5206  }
5207 
5208  /*
5209  * Set the parameter --- but don't override any previous
5210  * explicit setting.
5211  */
5212  found_keyword = false;
5213  for (i = 0; options[i].keyword; i++)
5214  {
5215  if (strcmp(options[i].keyword, key) == 0)
5216  {
5217  if (options[i].val == NULL)
5218  options[i].val = strdup(val);
5219  if (!options[i].val)
5220  {
5221  printfPQExpBuffer(errorMessage,
5222  libpq_gettext("out of memory\n"));
5223  result = 3;
5224  goto exit;
5225  }
5226  found_keyword = true;
5227  break;
5228  }
5229  }
5230 
5231  if (!found_keyword)
5232  {
5233  printfPQExpBuffer(errorMessage,
5234  libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5235  serviceFile,
5236  linenr);
5237  result = 3;
5238  goto exit;
5239  }
5240  }
5241  }
5242  }
5243 
5244 exit:
5245  fclose(f);
5246  pfree(linebuf.data);
5247 
5248  return result;
5249 }
5250 
5251 
5252 /*
5253  * PQconninfoParse
5254  *
5255  * Parse a string like PQconnectdb() would do and return the
5256  * resulting connection options array. NULL is returned on failure.
5257  * The result contains only options specified directly in the string,
5258  * not any possible default values.
5259  *
5260  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
5261  * string on failure (use PQfreemem to free it). In out-of-memory conditions
5262  * both *errmsg and the result could be NULL.
5263  *
5264  * NOTE: the returned array is dynamically allocated and should
5265  * be freed when no longer needed via PQconninfoFree().
5266  */
5268 PQconninfoParse(const char *conninfo, char **errmsg)
5269 {
5270  PQExpBufferData errorBuf;
5271  PQconninfoOption *connOptions;
5272 
5273  if (errmsg)
5274  *errmsg = NULL; /* default */
5275  initPQExpBuffer(&errorBuf);
5276  if (PQExpBufferDataBroken(errorBuf))
5277  return NULL; /* out of memory already :-( */
5278  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5279  if (connOptions == NULL && errmsg)
5280  *errmsg = errorBuf.data;
5281  else
5282  termPQExpBuffer(&errorBuf);
5283  return connOptions;
5284 }
5285 
5286 /*
5287  * Build a working copy of the constant PQconninfoOptions array.
5288  */
5289 static PQconninfoOption *
5291 {
5293  PQconninfoOption *opt_dest;
5294  const internalPQconninfoOption *cur_opt;
5295 
5296  /*
5297  * Get enough memory for all options in PQconninfoOptions, even if some
5298  * end up being filtered out.
5299  */
5300  options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
5301  if (options == NULL)
5302  {
5303  printfPQExpBuffer(errorMessage,
5304  libpq_gettext("out of memory\n"));
5305  return NULL;
5306  }
5307  opt_dest = options;
5308 
5309  for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5310  {
5311  /* Only copy the public part of the struct, not the full internal */
5312  memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5313  opt_dest++;
5314  }
5315  MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5316 
5317  return options;
5318 }
5319 
5320 /*
5321  * Connection string parser
5322  *
5323  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
5324  * Otherwise, NULL is returned and an error message is left in errorMessage.
5325  *
5326  * If use_defaults is true, default values are filled in (from a service file,
5327  * environment variables, etc).
5328  */
5329 static PQconninfoOption *
5330 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
5331  bool use_defaults)
5332 {
5333  /* Parse as URI if connection string matches URI prefix */
5334  if (uri_prefix_length(connstr) != 0)
5335  return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5336 
5337  /* Parse as default otherwise */
5338  return conninfo_parse(connstr, errorMessage, use_defaults);
5339 }
5340 
5341 /*
5342  * Checks if connection string starts with either of the valid URI prefix
5343  * designators.
5344  *
5345  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
5346  *
5347  * XXX this is duplicated in psql/common.c.
5348  */
5349 static int
5351 {
5352  if (strncmp(connstr, uri_designator,
5353  sizeof(uri_designator) - 1) == 0)
5354  return sizeof(uri_designator) - 1;
5355 
5356  if (strncmp(connstr, short_uri_designator,
5357  sizeof(short_uri_designator) - 1) == 0)
5358  return sizeof(short_uri_designator) - 1;
5359 
5360  return 0;
5361 }
5362 
5363 /*
5364  * Recognized connection string either starts with a valid URI prefix or
5365  * contains a "=" in it.
5366  *
5367  * Must be consistent with parse_connection_string: anything for which this
5368  * returns true should at least look like it's parseable by that routine.
5369  *
5370  * XXX this is duplicated in psql/common.c
5371  */
5372 static bool
5374 {
5375  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5376 }
5377 
5378 /*
5379  * Subroutine for parse_connection_string
5380  *
5381  * Deal with a string containing key=value pairs.
5382  */
5383 static PQconninfoOption *
5384 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5385  bool use_defaults)
5386 {
5387  char *pname;
5388  char *pval;
5389  char *buf;
5390  char *cp;
5391  char *cp2;
5393 
5394  /* Make a working copy of PQconninfoOptions */
5395  options = conninfo_init(errorMessage);
5396  if (options == NULL)
5397  return NULL;
5398 
5399  /* Need a modifiable copy of the input string */
5400  if ((buf = strdup(conninfo)) == NULL)
5401  {
5402  printfPQExpBuffer(errorMessage,
5403  libpq_gettext("out of memory\n"));
5404  PQconninfoFree(options);
5405  return NULL;
5406  }
5407  cp = buf;
5408 
5409  while (*cp)
5410  {
5411  /* Skip blanks before the parameter name */
5412  if (isspace((unsigned char) *cp))
5413  {
5414  cp++;
5415  continue;
5416  }
5417 
5418  /* Get the parameter name */
5419  pname = cp;
5420  while (*cp)
5421  {
5422  if (*cp == '=')
5423  break;
5424  if (isspace((unsigned char) *cp))
5425  {
5426  *cp++ = '\0';
5427  while (*cp)
5428  {
5429  if (!isspace((unsigned char) *cp))
5430  break;
5431  cp++;
5432  }
5433  break;
5434  }
5435  cp++;
5436  }
5437 
5438  /* Check that there is a following '=' */
5439  if (*cp != '=')
5440  {
5441  printfPQExpBuffer(errorMessage,
5442  libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
5443  pname);
5444  PQconninfoFree(options);
5445  free(buf);
5446  return NULL;
5447  }
5448  *cp++ = '\0';
5449 
5450  /* Skip blanks after the '=' */
5451  while (*cp)
5452  {
5453  if (!isspace((unsigned char) *cp))
5454  break;
5455  cp++;
5456  }
5457 
5458  /* Get the parameter value */
5459  pval = cp;
5460 
5461  if (*cp != '\'')
5462  {
5463  cp2 = pval;
5464  while (*cp)
5465  {
5466  if (isspace((unsigned char) *cp))
5467  {
5468  *cp++ = '\0';
5469  break;
5470  }
5471  if (*cp == '\\')
5472  {
5473  cp++;
5474  if (*cp != '\0')
5475  *cp2++ = *cp++;
5476  }
5477  else
5478  *cp2++ = *cp++;
5479  }
5480  *cp2 = '\0';
5481  }
5482  else
5483  {
5484  cp2 = pval;
5485  cp++;
5486  for (;;)
5487  {
5488  if (*cp == '\0')
5489  {
5490  printfPQExpBuffer(errorMessage,
5491  libpq_gettext("unterminated quoted string in connection info string\n"));
5492  PQconninfoFree(options);
5493  free(buf);
5494  return NULL;
5495  }
5496  if (*cp == '\\')
5497  {
5498  cp++;
5499  if (*cp != '\0')
5500  *cp2++ = *cp++;
5501  continue;
5502  }
5503  if (*cp == '\'')
5504  {
5505  *cp2 = '\0';
5506  cp++;
5507  break;
5508  }
5509  *cp2++ = *cp++;
5510  }
5511  }
5512 
5513  /*
5514  * Now that we have the name and the value, store the record.
5515  */
5516  if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5517  {
5518  PQconninfoFree(options);
5519  free(buf);
5520  return NULL;
5521  }
5522  }
5523 
5524  /* Done with the modifiable input string */
5525  free(buf);
5526 
5527  /*
5528  * Add in defaults if the caller wants that.
5529  */
5530  if (use_defaults)
5531  {
5532  if (!conninfo_add_defaults(options, errorMessage))
5533  {
5534  PQconninfoFree(options);
5535  return NULL;
5536  }
5537  }
5538 
5539  return options;
5540 }
5541 
5542 /*
5543  * Conninfo array parser routine
5544  *
5545  * If successful, a malloc'd PQconninfoOption array is returned.
5546  * If not successful, NULL is returned and an error message is
5547  * left in errorMessage.
5548  * Defaults are supplied (from a service file, environment variables, etc)
5549  * for unspecified options, but only if use_defaults is true.
5550  *
5551  * If expand_dbname is non-zero, and the value passed for the first occurrence
5552  * of "dbname" keyword is a connection string (as indicated by
5553  * recognized_connection_string) then parse and process it, overriding any
5554  * previously processed conflicting keywords. Subsequent keywords will take
5555  * precedence, however. In-tree programs generally specify expand_dbname=true,
5556  * so command-line arguments naming a database can use a connection string.
5557  * Some code acquires arbitrary database names from known-literal sources like
5558  * PQdb(), PQconninfoParse() and pg_database.datname. When connecting to such
5559  * a database, in-tree code first wraps the name in a connection string.
5560  */
5561 static PQconninfoOption *
5562 conninfo_array_parse(const char *const *keywords, const char *const *values,
5563  PQExpBuffer errorMessage, bool use_defaults,
5564  int expand_dbname)
5565 {
5567  PQconninfoOption *dbname_options = NULL;
5569  int i = 0;
5570 
5571  /*
5572  * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5573  * actually a recognized connection string.
5574  */
5575  while (expand_dbname && keywords[i])
5576  {
5577  const char *pname = keywords[i];
5578  const char *pvalue = values[i];
5579 
5580  /* first find "dbname" if any */
5581  if (strcmp(pname, "dbname") == 0 && pvalue)
5582  {
5583  /*
5584  * If value is a connection string, parse it, but do not use
5585  * defaults here -- those get picked up later. We only want to
5586  * override for those parameters actually passed.
5587  */
5588  if (recognized_connection_string(pvalue))
5589  {
5590  dbname_options = parse_connection_string(pvalue, errorMessage, false);
5591  if (dbname_options == NULL)
5592  return NULL;
5593  }
5594  break;
5595  }
5596  ++i;
5597  }
5598 
5599  /* Make a working copy of PQconninfoOptions */
5600  options = conninfo_init(errorMessage);
5601  if (options == NULL)
5602  {
5603  PQconninfoFree(dbname_options);
5604  return NULL;
5605  }
5606 
5607  /* Parse the keywords/values arrays */
5608  i = 0;
5609  while (keywords[i])
5610  {
5611  const char *pname = keywords[i];
5612  const char *pvalue = values[i];
5613 
5614  if (pvalue != NULL && pvalue[0] != '\0')
5615  {
5616  /* Search for the param record */
5617  for (option = options; option->keyword != NULL; option++)
5618  {
5619  if (strcmp(option->keyword, pname) == 0)
5620  break;
5621  }
5622 
5623  /* Check for invalid connection option */
5624  if (option->keyword == NULL)
5625  {
5626  printfPQExpBuffer(errorMessage,
5627  libpq_gettext("invalid connection option \"%s\"\n"),
5628  pname);
5629  PQconninfoFree(options);
5630  PQconninfoFree(dbname_options);
5631  return NULL;
5632  }
5633 
5634  /*
5635  * If we are on the first dbname parameter, and we have a parsed
5636  * connection string, copy those parameters across, overriding any
5637  * existing previous settings.
5638  */
5639  if (strcmp(pname, "dbname") == 0 && dbname_options)
5640  {
5641  PQconninfoOption *str_option;
5642 
5643  for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5644  {
5645  if (str_option->val != NULL)
5646  {
5647  int k;
5648 
5649  for (k = 0; options[k].keyword; k++)
5650  {
5651  if (strcmp(options[k].keyword, str_option->keyword) == 0)
5652  {
5653  if (options[k].val)
5654  free(options[k].val);
5655  options[k].val = strdup(str_option->val);
5656  if (!options[k].val)
5657  {
5658  printfPQExpBuffer(errorMessage,
5659  libpq_gettext("out of memory\n"));
5660  PQconninfoFree(options);
5661  PQconninfoFree(dbname_options);
5662  return NULL;
5663  }
5664  break;
5665  }
5666  }
5667  }
5668  }
5669 
5670  /*
5671  * Forget the parsed connection string, so that any subsequent
5672  * dbname parameters will not be expanded.
5673  */
5674  PQconninfoFree(dbname_options);
5675  dbname_options = NULL;
5676  }
5677  else
5678  {
5679  /*
5680  * Store the value, overriding previous settings
5681  */
5682  if (option->val)
5683  free(option->val);
5684  option->val = strdup(pvalue);
5685  if (!option->val)
5686  {
5687  printfPQExpBuffer(errorMessage,
5688  libpq_gettext("out of memory\n"));
5689  PQconninfoFree(options);
5690  PQconninfoFree(dbname_options);
5691  return NULL;
5692  }
5693  }
5694  }
5695  ++i;
5696  }
5697  PQconninfoFree(dbname_options);
5698 
5699  /*
5700  * Add in defaults if the caller wants that.
5701  */
5702  if (use_defaults)
5703  {
5704  if (!conninfo_add_defaults(options, errorMessage))
5705  {
5706  PQconninfoFree(options);
5707  return NULL;
5708  }
5709  }
5710 
5711  return options;
5712 }
5713 
5714 /*
5715  * Add the default values for any unspecified options to the connection
5716  * options array.
5717  *
5718  * Defaults are obtained from a service file, environment variables, etc.
5719  *
5720  * Returns true if successful, otherwise false; errorMessage, if supplied,
5721  * is filled in upon failure. Note that failure to locate a default value
5722  * is not an error condition here --- we just leave the option's value as
5723  * NULL.
5724  */
5725 static bool
5727 {
5729  char *tmp;
5730 
5731  /*
5732  * If there's a service spec, use it to obtain any not-explicitly-given
5733  * parameters. Ignore error if no error message buffer is passed because
5734  * there is no way to pass back the failure message.
5735  */
5736  if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5737  return false;
5738 
5739  /*
5740  * Get the fallback resources for parameters not specified in the conninfo
5741  * string nor the service.
5742  */
5743  for (option = options; option->keyword != NULL; option++)
5744  {
5745  if (option->val != NULL)
5746  continue; /* Value was in conninfo or service */
5747 
5748  /*
5749  * Try to get the environment variable fallback
5750  */
5751  if (option->envvar != NULL)
5752  {
5753  if ((tmp = getenv(option->envvar)) != NULL)
5754  {
5755  option->val = strdup(tmp);
5756  if (!option->val)
5757  {
5758  if (errorMessage)
5759  printfPQExpBuffer(errorMessage,
5760  libpq_gettext("out of memory\n"));
5761  return false;
5762  }
5763  continue;
5764  }
5765  }
5766 
5767  /*
5768  * Interpret the deprecated PGREQUIRESSL environment variable. Per
5769  * tradition, translate values starting with "1" to sslmode=require,
5770  * and ignore other values. Given both PGREQUIRESSL=1 and PGSSLMODE,
5771  * PGSSLMODE takes precedence; the opposite was true before v9.3.
5772  */
5773  if (strcmp(option->keyword, "sslmode") == 0)
5774  {
5775  const char *requiresslenv = getenv("PGREQUIRESSL");
5776 
5777  if (requiresslenv != NULL && requiresslenv[0] == '1')
5778  {
5779  option->val = strdup("require");
5780  if (!option->val)
5781  {
5782  if (errorMessage)
5783  printfPQExpBuffer(errorMessage,
5784  libpq_gettext("out of memory\n"));
5785  return false;
5786  }
5787  continue;
5788  }
5789  }
5790 
5791  /*
5792  * No environment variable specified or the variable isn't set - try
5793  * compiled-in default
5794  */
5795  if (option->compiled != NULL)
5796  {
5797  option->val = strdup(option->compiled);
5798  if (!option->val)
5799  {
5800  if (errorMessage)
5801  printfPQExpBuffer(errorMessage,
5802  libpq_gettext("out of memory\n"));
5803  return false;
5804  }
5805  continue;
5806  }
5807 
5808  /*
5809  * Special handling for "user" option. Note that if pg_fe_getauthname
5810  * fails, we just leave the value as NULL; there's no need for this to
5811  * be an error condition if the caller provides a user name. The only
5812  * reason we do this now at all is so that callers of PQconndefaults
5813  * will see a correct default (barring error, of course).
5814  */
5815  if (strcmp(option->keyword, "user") == 0)
5816  {
5817  option->val = pg_fe_getauthname(NULL);
5818  continue;
5819  }
5820  }
5821 
5822  return true;
5823 }
5824 
5825 /*
5826  * Subroutine for parse_connection_string
5827  *
5828  * Deal with a URI connection string.
5829  */
5830 static PQconninfoOption *
5831 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
5832  bool use_defaults)
5833 {
5835 
5836  /* Make a working copy of PQconninfoOptions */
5837  options = conninfo_init(errorMessage);
5838  if (options == NULL)
5839  return NULL;
5840 
5841  if (!conninfo_uri_parse_options(options, uri, errorMessage))
5842  {
5843  PQconninfoFree(options);
5844  return NULL;
5845  }
5846 
5847  /*
5848  * Add in defaults if the caller wants that.
5849  */
5850  if (use_defaults)
5851  {
5852  if (!conninfo_add_defaults(options, errorMessage))
5853  {
5854  PQconninfoFree(options);
5855  return NULL;
5856  }
5857  }
5858 
5859  return options;
5860 }
5861 
5862 /*
5863  * conninfo_uri_parse_options
5864  * Actual URI parser.
5865  *
5866  * If successful, returns true while the options array is filled with parsed
5867  * options from the URI.
5868  * If not successful, returns false and fills errorMessage accordingly.
5869  *
5870  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
5871  * 3986):
5872  *
5873  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
5874  *
5875  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
5876  * by literal square brackets. As an extension, we also allow multiple
5877  * netloc[:port] specifications, separated by commas:
5878  *
5879  * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
5880  *
5881  * Any of the URI parts might use percent-encoding (%xy).
5882  */
5883 static bool
5885  PQExpBuffer errorMessage)
5886 {
5887  int prefix_len;
5888  char *p;
5889  char *buf = NULL;
5890  char *start;
5891  char prevchar = '\0';
5892  char *user = NULL;
5893  char *host = NULL;
5894  bool retval = false;
5895  PQExpBufferData hostbuf;
5896  PQExpBufferData portbuf;
5897 
5898  initPQExpBuffer(&hostbuf);
5899  initPQExpBuffer(&portbuf);
5900  if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5901  {
5902  printfPQExpBuffer(errorMessage,
5903  libpq_gettext("out of memory\n"));
5904  goto cleanup;
5905  }
5906 
5907  /* need a modifiable copy of the input URI */
5908  buf = strdup(uri);
5909  if (buf == NULL)
5910  {
5911  printfPQExpBuffer(errorMessage,
5912  libpq_gettext("out of memory\n"));
5913  goto cleanup;
5914  }
5915  start = buf;
5916 
5917  /* Skip the URI prefix */
5918  prefix_len = uri_prefix_length(uri);
5919  if (prefix_len == 0)
5920  {
5921  /* Should never happen */
5922  printfPQExpBuffer(errorMessage,
5923  libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
5924  uri);
5925  goto cleanup;
5926  }
5927  start += prefix_len;
5928  p = start;
5929 
5930  /* Look ahead for possible user credentials designator */
5931  while (*p && *p != '@' && *p != '/')
5932  ++p;
5933  if (*p == '@')
5934  {
5935  /*
5936  * Found username/password designator, so URI should be of the form
5937  * "scheme://user[:password]@[netloc]".
5938  */
5939  user = start;
5940 
5941  p = user;
5942  while (*p != ':' && *p != '@')
5943  ++p;
5944 
5945  /* Save last char and cut off at end of user name */
5946  prevchar = *p;
5947  *p = '\0';
5948 
5949  if (*user &&
5950  !conninfo_storeval(options, "user", user,
5951  errorMessage, false, true))
5952  goto cleanup;
5953 
5954  if (prevchar == ':')
5955  {
5956  const char *password = p + 1;
5957 
5958  while (*p != '@')
5959  ++p;
5960  *p = '\0';
5961 
5962  if (*password &&
5963  !conninfo_storeval(options, "password", password,
5964  errorMessage, false, true))
5965  goto cleanup;
5966  }
5967 
5968  /* Advance past end of parsed user name or password token */
5969  ++p;
5970  }
5971  else
5972  {
5973  /*
5974  * No username/password designator found. Reset to start of URI.
5975  */
5976  p = start;
5977  }
5978 
5979  /*
5980  * There may be multiple netloc[:port] pairs, each separated from the next
5981  * by a comma. When we initially enter this loop, "p" has been
5982  * incremented past optional URI credential information at this point and
5983  * now points at the "netloc" part of the URI. On subsequent loop
5984  * iterations, "p" has been incremented past the comma separator and now
5985  * points at the start of the next "netloc".
5986  */
5987  for (;;)
5988  {
5989  /*
5990  * Look for IPv6 address.
5991  */
5992  if (*p == '[')
5993  {
5994  host = ++p;
5995  while (*p && *p != ']')
5996  ++p;
5997  if (!*p)
5998  {
5999  printfPQExpBuffer(errorMessage,
6000  libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
6001  uri);
6002  goto cleanup;
6003  }
6004  if (p == host)
6005  {
6006  printfPQExpBuffer(errorMessage,
6007  libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
6008  uri);
6009  goto cleanup;
6010  }
6011 
6012  /* Cut off the bracket and advance */
6013  *(p++) = '\0';
6014 
6015  /*
6016  * The address may be followed by a port specifier or a slash or a
6017  * query or a separator comma.
6018  */
6019  if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6020  {
6021  printfPQExpBuffer(errorMessage,
6022  libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
6023  *p, (int) (p - buf + 1), uri);
6024  goto cleanup;
6025  }
6026  }
6027  else
6028  {
6029  /* not an IPv6 address: DNS-named or IPv4 netloc */
6030  host = p;
6031 
6032  /*
6033  * Look for port specifier (colon) or end of host specifier
6034  * (slash) or query (question mark) or host separator (comma).
6035  */
6036  while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
6037  ++p;
6038  }
6039 
6040  /* Save the hostname terminator before we null it */
6041  prevchar = *p;
6042  *p = '\0';
6043 
6044  appendPQExpBufferStr(&hostbuf, host);
6045 
6046  if (prevchar == ':')
6047  {
6048  const char *port = ++p; /* advance past host terminator */
6049 
6050  while (*p && *p != '/' && *p != '?' && *p != ',')
6051  ++p;
6052 
6053  prevchar = *p;
6054  *p = '\0';
6055 
6056  appendPQExpBufferStr(&portbuf, port);
6057  }
6058 
6059  if (prevchar != ',')
6060  break;
6061  ++p; /* advance past comma separator */
6062  appendPQExpBufferChar(&hostbuf, ',');
6063  appendPQExpBufferChar(&portbuf, ',');
6064  }
6065 
6066  /* Save final values for host and port. */