PageRenderTime 53ms CodeModel.GetById 9ms 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

Large files files are truncated, but you can click here to view the full file

  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 = CON

Large files files are truncated, but you can click here to view the full file