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