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