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