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