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