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