PageRenderTime 80ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/interfaces/libpq/fe-connect.c

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