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