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