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