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