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