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