PageRenderTime 76ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

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

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