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