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