config.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. package pgconn
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "maps"
  11. "math"
  12. "net"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/jackc/pgpassfile"
  20. "github.com/jackc/pgservicefile"
  21. "github.com/jackc/pgx/v5/pgconn/ctxwatch"
  22. "github.com/jackc/pgx/v5/pgproto3"
  23. )
  24. type (
  25. AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error
  26. ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error
  27. GetSSLPasswordFunc func(ctx context.Context) string
  28. )
  29. // Config is the settings used to establish a connection to a PostgreSQL server. It must be created by [ParseConfig]. A
  30. // manually initialized Config will cause ConnectConfig to panic.
  31. type Config struct {
  32. Host string // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp)
  33. Port uint16
  34. Database string
  35. User string
  36. Password string
  37. TLSConfig *tls.Config // nil disables TLS
  38. ConnectTimeout time.Duration
  39. DialFunc DialFunc // e.g. net.Dialer.DialContext
  40. LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
  41. BuildFrontend BuildFrontendFunc
  42. // BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called
  43. // when a context passed to a PgConn method is canceled.
  44. BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler
  45. RuntimeParams map[string]string // Run-time parameters to set on connection as session default values (e.g. search_path or application_name)
  46. KerberosSrvName string
  47. KerberosSpn string
  48. Fallbacks []*FallbackConfig
  49. SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct
  50. // AfterNetConnect is called after the network connection, including TLS if applicable, is established but before any
  51. // PostgreSQL protocol communication. It takes the established net.Conn and returns a net.Conn that will be used in
  52. // its place. It can be used to wrap the net.Conn (e.g. for logging, diagnostics, or testing). Its functionality has
  53. // some overlap with DialFunc. However, DialFunc takes place before TLS is established and cannot be used to control
  54. // the final net.Conn used for PostgreSQL protocol communication while AfterNetConnect can.
  55. AfterNetConnect func(ctx context.Context, config *Config, conn net.Conn) (net.Conn, error)
  56. // ValidateConnect is called during a connection attempt after a successful authentication with the PostgreSQL server.
  57. // It can be used to validate that the server is acceptable. If this returns an error the connection is closed and the next
  58. // fallback config is tried. This allows implementing high availability behavior such as libpq does with target_session_attrs.
  59. ValidateConnect ValidateConnectFunc
  60. // AfterConnect is called after ValidateConnect. It can be used to set up the connection (e.g. Set session variables
  61. // or prepare statements). If this returns an error the connection attempt fails.
  62. AfterConnect AfterConnectFunc
  63. // OnNotice is a callback function called when a notice response is received.
  64. OnNotice NoticeHandler
  65. // OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received.
  66. OnNotification NotificationHandler
  67. // OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close
  68. // the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure
  69. // that you close on FATAL errors by returning false.
  70. OnPgError PgErrorHandler
  71. createdByParseConfig bool // Used to enforce created by ParseConfig rule.
  72. }
  73. // ParseConfigOptions contains options that control how a config is built such as GetSSLPassword.
  74. type ParseConfigOptions struct {
  75. // GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the libpq function
  76. // PQsetSSLKeyPassHook_OpenSSL.
  77. GetSSLPassword GetSSLPasswordFunc
  78. }
  79. // Copy returns a deep copy of the config that is safe to use and modify.
  80. // The only exception is the TLSConfig field:
  81. // according to the tls.Config docs it must not be modified after creation.
  82. func (c *Config) Copy() *Config {
  83. newConf := new(Config)
  84. *newConf = *c
  85. if newConf.TLSConfig != nil {
  86. newConf.TLSConfig = c.TLSConfig.Clone()
  87. }
  88. if newConf.RuntimeParams != nil {
  89. newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams))
  90. maps.Copy(newConf.RuntimeParams, c.RuntimeParams)
  91. }
  92. if newConf.Fallbacks != nil {
  93. newConf.Fallbacks = make([]*FallbackConfig, len(c.Fallbacks))
  94. for i, fallback := range c.Fallbacks {
  95. newFallback := new(FallbackConfig)
  96. *newFallback = *fallback
  97. if newFallback.TLSConfig != nil {
  98. newFallback.TLSConfig = fallback.TLSConfig.Clone()
  99. }
  100. newConf.Fallbacks[i] = newFallback
  101. }
  102. }
  103. return newConf
  104. }
  105. // FallbackConfig is additional settings to attempt a connection with when the primary Config fails to establish a
  106. // network connection. It is used for TLS fallback such as sslmode=prefer and high availability (HA) connections.
  107. type FallbackConfig struct {
  108. Host string // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp)
  109. Port uint16
  110. TLSConfig *tls.Config // nil disables TLS
  111. }
  112. // connectOneConfig is the configuration for a single attempt to connect to a single host.
  113. type connectOneConfig struct {
  114. network string
  115. address string
  116. originalHostname string // original hostname before resolving
  117. tlsConfig *tls.Config // nil disables TLS
  118. }
  119. // isAbsolutePath checks if the provided value is an absolute path either
  120. // beginning with a forward slash (as on Linux-based systems) or with a capital
  121. // letter A-Z followed by a colon and a backslash, e.g., "C:\", (as on Windows).
  122. func isAbsolutePath(path string) bool {
  123. isWindowsPath := func(p string) bool {
  124. if len(p) < 3 {
  125. return false
  126. }
  127. drive := p[0]
  128. colon := p[1]
  129. backslash := p[2]
  130. if drive >= 'A' && drive <= 'Z' && colon == ':' && backslash == '\\' {
  131. return true
  132. }
  133. return false
  134. }
  135. return strings.HasPrefix(path, "/") || isWindowsPath(path)
  136. }
  137. // NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with
  138. // net.Dial.
  139. func NetworkAddress(host string, port uint16) (network, address string) {
  140. if isAbsolutePath(host) {
  141. network = "unix"
  142. address = filepath.Join(host, ".s.PGSQL.") + strconv.FormatInt(int64(port), 10)
  143. } else {
  144. network = "tcp"
  145. address = net.JoinHostPort(host, strconv.Itoa(int(port)))
  146. }
  147. return network, address
  148. }
  149. // ParseConfig builds a *Config from connString with similar behavior to the PostgreSQL standard C library libpq. It
  150. // uses the same defaults as libpq (e.g. port=5432) and understands most PG* environment variables. ParseConfig closely
  151. // matches the parsing behavior of libpq. connString may either be in URL format or keyword = value format. See
  152. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING for details. connString also may be empty
  153. // to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file.
  154. //
  155. // # Example Keyword/Value
  156. // user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca
  157. //
  158. // # Example URL
  159. // postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca
  160. //
  161. // The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done
  162. // through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be
  163. // interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should
  164. // not be modified individually. They should all be modified or all left unchanged.
  165. //
  166. // ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated
  167. // values that will be tried in order. This can be used as part of a high availability system. See
  168. // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information.
  169. //
  170. // # Example URL
  171. // postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb
  172. //
  173. // ParseConfig currently recognizes the following environment variable and their parameter key word equivalents passed
  174. // via database URL or keyword/value:
  175. //
  176. // PGHOST
  177. // PGPORT
  178. // PGDATABASE
  179. // PGUSER
  180. // PGPASSWORD
  181. // PGPASSFILE
  182. // PGSERVICE
  183. // PGSERVICEFILE
  184. // PGSSLMODE
  185. // PGSSLCERT
  186. // PGSSLKEY
  187. // PGSSLROOTCERT
  188. // PGSSLPASSWORD
  189. // PGOPTIONS
  190. // PGAPPNAME
  191. // PGCONNECT_TIMEOUT
  192. // PGTARGETSESSIONATTRS
  193. // PGTZ
  194. //
  195. // See http://www.postgresql.org/docs/current/static/libpq-envars.html for details on the meaning of environment variables.
  196. //
  197. // See https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS for parameter key word names. They are
  198. // usually but not always the environment variable name downcased and without the "PG" prefix.
  199. //
  200. // Important Security Notes:
  201. //
  202. // ParseConfig tries to match libpq behavior with regard to PGSSLMODE. This includes defaulting to "prefer" behavior if
  203. // not set.
  204. //
  205. // See http://www.postgresql.org/docs/current/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION for details on what level of
  206. // security each sslmode provides.
  207. //
  208. // The sslmode "prefer" (the default), sslmode "allow", and multiple hosts are implemented via the Fallbacks field of
  209. // the Config struct. If TLSConfig is manually changed it will not affect the fallbacks. For example, in the case of
  210. // sslmode "prefer" this means it will first try the main Config settings which use TLS, then it will try the fallback
  211. // which does not use TLS. This can lead to an unexpected unencrypted connection if the main TLS config is manually
  212. // changed later but the unencrypted fallback is present. Ensure there are no stale fallbacks when manually setting
  213. // TLSConfig.
  214. //
  215. // Other known differences with libpq:
  216. //
  217. // When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn
  218. // does not.
  219. //
  220. // In addition, ParseConfig accepts the following options:
  221. //
  222. // - servicefile.
  223. // libpq only reads servicefile from the PGSERVICEFILE environment variable. ParseConfig accepts servicefile as a
  224. // part of the connection string.
  225. func ParseConfig(connString string) (*Config, error) {
  226. var parseConfigOptions ParseConfigOptions
  227. return ParseConfigWithOptions(connString, parseConfigOptions)
  228. }
  229. // ParseConfigWithOptions builds a *Config from connString and options with similar behavior to the PostgreSQL standard
  230. // C library libpq. options contains settings that cannot be specified in a connString such as providing a function to
  231. // get the SSL password.
  232. func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error) {
  233. defaultSettings := defaultSettings()
  234. envSettings := parseEnvSettings()
  235. connStringSettings := make(map[string]string)
  236. if connString != "" {
  237. var err error
  238. // connString may be a database URL or in PostgreSQL keyword/value format
  239. if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
  240. connStringSettings, err = parseURLSettings(connString)
  241. if err != nil {
  242. return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err}
  243. }
  244. } else {
  245. connStringSettings, err = parseKeywordValueSettings(connString)
  246. if err != nil {
  247. return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as keyword/value", err: err}
  248. }
  249. }
  250. }
  251. settings := mergeSettings(defaultSettings, envSettings, connStringSettings)
  252. if service, present := settings["service"]; present {
  253. serviceSettings, err := parseServiceSettings(settings["servicefile"], service)
  254. if err != nil {
  255. return nil, &ParseConfigError{ConnString: connString, msg: "failed to read service", err: err}
  256. }
  257. settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings)
  258. }
  259. config := &Config{
  260. createdByParseConfig: true,
  261. Database: settings["database"],
  262. User: settings["user"],
  263. Password: settings["password"],
  264. RuntimeParams: make(map[string]string),
  265. BuildFrontend: func(r io.Reader, w io.Writer) *pgproto3.Frontend {
  266. return pgproto3.NewFrontend(r, w)
  267. },
  268. BuildContextWatcherHandler: func(pgConn *PgConn) ctxwatch.Handler {
  269. return &DeadlineContextWatcherHandler{Conn: pgConn.conn}
  270. },
  271. OnPgError: func(_ *PgConn, pgErr *PgError) bool {
  272. // we want to automatically close any fatal errors
  273. if strings.EqualFold(pgErr.Severity, "FATAL") {
  274. return false
  275. }
  276. return true
  277. },
  278. }
  279. if connectTimeoutSetting, present := settings["connect_timeout"]; present {
  280. connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting)
  281. if err != nil {
  282. return nil, &ParseConfigError{ConnString: connString, msg: "invalid connect_timeout", err: err}
  283. }
  284. config.ConnectTimeout = connectTimeout
  285. config.DialFunc = makeConnectTimeoutDialFunc(connectTimeout)
  286. } else {
  287. defaultDialer := makeDefaultDialer()
  288. config.DialFunc = defaultDialer.DialContext
  289. }
  290. config.LookupFunc = makeDefaultResolver().LookupHost
  291. notRuntimeParams := map[string]struct{}{
  292. "host": {},
  293. "port": {},
  294. "database": {},
  295. "user": {},
  296. "password": {},
  297. "passfile": {},
  298. "connect_timeout": {},
  299. "sslmode": {},
  300. "sslkey": {},
  301. "sslcert": {},
  302. "sslrootcert": {},
  303. "sslnegotiation": {},
  304. "sslpassword": {},
  305. "sslsni": {},
  306. "krbspn": {},
  307. "krbsrvname": {},
  308. "target_session_attrs": {},
  309. "service": {},
  310. "servicefile": {},
  311. }
  312. // Adding kerberos configuration
  313. if _, present := settings["krbsrvname"]; present {
  314. config.KerberosSrvName = settings["krbsrvname"]
  315. }
  316. if _, present := settings["krbspn"]; present {
  317. config.KerberosSpn = settings["krbspn"]
  318. }
  319. for k, v := range settings {
  320. if _, present := notRuntimeParams[k]; present {
  321. continue
  322. }
  323. config.RuntimeParams[k] = v
  324. }
  325. fallbacks := []*FallbackConfig{}
  326. hosts := strings.Split(settings["host"], ",")
  327. ports := strings.Split(settings["port"], ",")
  328. for i, host := range hosts {
  329. var portStr string
  330. if i < len(ports) {
  331. portStr = ports[i]
  332. } else {
  333. portStr = ports[0]
  334. }
  335. port, err := parsePort(portStr)
  336. if err != nil {
  337. return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err}
  338. }
  339. var tlsConfigs []*tls.Config
  340. // Ignore TLS settings if Unix domain socket like libpq
  341. if network, _ := NetworkAddress(host, port); network == "unix" {
  342. tlsConfigs = append(tlsConfigs, nil)
  343. } else {
  344. var err error
  345. tlsConfigs, err = configTLS(settings, host, options)
  346. if err != nil {
  347. return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err}
  348. }
  349. }
  350. for _, tlsConfig := range tlsConfigs {
  351. fallbacks = append(fallbacks, &FallbackConfig{
  352. Host: host,
  353. Port: port,
  354. TLSConfig: tlsConfig,
  355. })
  356. }
  357. }
  358. config.Host = fallbacks[0].Host
  359. config.Port = fallbacks[0].Port
  360. config.TLSConfig = fallbacks[0].TLSConfig
  361. config.Fallbacks = fallbacks[1:]
  362. config.SSLNegotiation = settings["sslnegotiation"]
  363. passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
  364. if err == nil {
  365. if config.Password == "" {
  366. host := config.Host
  367. if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" {
  368. host = "localhost"
  369. }
  370. config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User)
  371. }
  372. }
  373. switch tsa := settings["target_session_attrs"]; tsa {
  374. case "read-write":
  375. config.ValidateConnect = ValidateConnectTargetSessionAttrsReadWrite
  376. case "read-only":
  377. config.ValidateConnect = ValidateConnectTargetSessionAttrsReadOnly
  378. case "primary":
  379. config.ValidateConnect = ValidateConnectTargetSessionAttrsPrimary
  380. case "standby":
  381. config.ValidateConnect = ValidateConnectTargetSessionAttrsStandby
  382. case "prefer-standby":
  383. config.ValidateConnect = ValidateConnectTargetSessionAttrsPreferStandby
  384. case "any":
  385. // do nothing
  386. default:
  387. return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)}
  388. }
  389. return config, nil
  390. }
  391. func mergeSettings(settingSets ...map[string]string) map[string]string {
  392. settings := make(map[string]string)
  393. for _, s2 := range settingSets {
  394. maps.Copy(settings, s2)
  395. }
  396. return settings
  397. }
  398. func parseEnvSettings() map[string]string {
  399. settings := make(map[string]string)
  400. nameMap := map[string]string{
  401. "PGHOST": "host",
  402. "PGPORT": "port",
  403. "PGDATABASE": "database",
  404. "PGUSER": "user",
  405. "PGPASSWORD": "password",
  406. "PGPASSFILE": "passfile",
  407. "PGAPPNAME": "application_name",
  408. "PGCONNECT_TIMEOUT": "connect_timeout",
  409. "PGSSLMODE": "sslmode",
  410. "PGSSLKEY": "sslkey",
  411. "PGSSLCERT": "sslcert",
  412. "PGSSLSNI": "sslsni",
  413. "PGSSLROOTCERT": "sslrootcert",
  414. "PGSSLPASSWORD": "sslpassword",
  415. "PGSSLNEGOTIATION": "sslnegotiation",
  416. "PGTARGETSESSIONATTRS": "target_session_attrs",
  417. "PGSERVICE": "service",
  418. "PGSERVICEFILE": "servicefile",
  419. "PGTZ": "timezone",
  420. "PGOPTIONS": "options",
  421. }
  422. for envname, realname := range nameMap {
  423. value := os.Getenv(envname)
  424. if value != "" {
  425. settings[realname] = value
  426. }
  427. }
  428. return settings
  429. }
  430. func parseURLSettings(connString string) (map[string]string, error) {
  431. settings := make(map[string]string)
  432. parsedURL, err := url.Parse(connString)
  433. if err != nil {
  434. if urlErr := new(url.Error); errors.As(err, &urlErr) {
  435. return nil, urlErr.Err
  436. }
  437. return nil, err
  438. }
  439. if parsedURL.User != nil {
  440. settings["user"] = parsedURL.User.Username()
  441. if password, present := parsedURL.User.Password(); present {
  442. settings["password"] = password
  443. }
  444. }
  445. // Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port.
  446. var hosts []string
  447. var ports []string
  448. for host := range strings.SplitSeq(parsedURL.Host, ",") {
  449. if host == "" {
  450. continue
  451. }
  452. if isIPOnly(host) {
  453. hosts = append(hosts, strings.Trim(host, "[]"))
  454. continue
  455. }
  456. h, p, err := net.SplitHostPort(host)
  457. if err != nil {
  458. return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err)
  459. }
  460. if h != "" {
  461. hosts = append(hosts, h)
  462. }
  463. if p != "" {
  464. ports = append(ports, p)
  465. }
  466. }
  467. if len(hosts) > 0 {
  468. settings["host"] = strings.Join(hosts, ",")
  469. }
  470. if len(ports) > 0 {
  471. settings["port"] = strings.Join(ports, ",")
  472. }
  473. database := strings.TrimLeft(parsedURL.Path, "/")
  474. if database != "" {
  475. settings["database"] = database
  476. }
  477. nameMap := map[string]string{
  478. "dbname": "database",
  479. }
  480. for k, v := range parsedURL.Query() {
  481. if k2, present := nameMap[k]; present {
  482. k = k2
  483. }
  484. settings[k] = v[0]
  485. }
  486. return settings, nil
  487. }
  488. func isIPOnly(host string) bool {
  489. return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":")
  490. }
  491. var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
  492. func parseKeywordValueSettings(s string) (map[string]string, error) {
  493. settings := make(map[string]string)
  494. nameMap := map[string]string{
  495. "dbname": "database",
  496. }
  497. for len(s) > 0 {
  498. var key, val string
  499. eqIdx := strings.IndexRune(s, '=')
  500. if eqIdx < 0 {
  501. return nil, errors.New("invalid keyword/value")
  502. }
  503. key = strings.Trim(s[:eqIdx], " \t\n\r\v\f")
  504. s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f")
  505. if len(s) == 0 {
  506. } else if s[0] != '\'' {
  507. end := 0
  508. for ; end < len(s); end++ {
  509. if asciiSpace[s[end]] == 1 {
  510. break
  511. }
  512. if s[end] == '\\' {
  513. end++
  514. if end == len(s) {
  515. return nil, errors.New("invalid backslash")
  516. }
  517. }
  518. }
  519. val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1)
  520. if end == len(s) {
  521. s = ""
  522. } else {
  523. s = s[end+1:]
  524. }
  525. } else { // quoted string
  526. s = s[1:]
  527. end := 0
  528. for ; end < len(s); end++ {
  529. if s[end] == '\'' {
  530. break
  531. }
  532. if s[end] == '\\' {
  533. end++
  534. }
  535. }
  536. if end == len(s) {
  537. return nil, errors.New("unterminated quoted string in connection info string")
  538. }
  539. val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1)
  540. if end == len(s) {
  541. s = ""
  542. } else {
  543. s = s[end+1:]
  544. }
  545. }
  546. if k, ok := nameMap[key]; ok {
  547. key = k
  548. }
  549. if key == "" {
  550. return nil, errors.New("invalid keyword/value")
  551. }
  552. settings[key] = val
  553. }
  554. return settings, nil
  555. }
  556. func parseServiceSettings(servicefilePath, serviceName string) (map[string]string, error) {
  557. servicefile, err := pgservicefile.ReadServicefile(servicefilePath)
  558. if err != nil {
  559. return nil, fmt.Errorf("failed to read service file: %v", servicefilePath)
  560. }
  561. service, err := servicefile.GetService(serviceName)
  562. if err != nil {
  563. return nil, fmt.Errorf("unable to find service: %v", serviceName)
  564. }
  565. nameMap := map[string]string{
  566. "dbname": "database",
  567. }
  568. settings := make(map[string]string, len(service.Settings))
  569. for k, v := range service.Settings {
  570. if k2, present := nameMap[k]; present {
  571. k = k2
  572. }
  573. settings[k] = v
  574. }
  575. return settings, nil
  576. }
  577. // configTLS uses libpq's TLS parameters to construct []*tls.Config. It is
  578. // necessary to allow returning multiple TLS configs as sslmode "allow" and
  579. // "prefer" allow fallback.
  580. func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) {
  581. host := thisHost
  582. sslmode := settings["sslmode"]
  583. sslrootcert := settings["sslrootcert"]
  584. sslcert := settings["sslcert"]
  585. sslkey := settings["sslkey"]
  586. sslpassword := settings["sslpassword"]
  587. sslsni := settings["sslsni"]
  588. sslnegotiation := settings["sslnegotiation"]
  589. // Match libpq default behavior
  590. if sslmode == "" {
  591. sslmode = "prefer"
  592. }
  593. if sslsni == "" {
  594. sslsni = "1"
  595. }
  596. tlsConfig := &tls.Config{}
  597. if sslnegotiation == "direct" {
  598. tlsConfig.NextProtos = []string{"postgresql"}
  599. if sslmode == "prefer" {
  600. sslmode = "require"
  601. }
  602. }
  603. if sslrootcert != "" {
  604. var caCertPool *x509.CertPool
  605. if sslrootcert == "system" {
  606. var err error
  607. caCertPool, err = x509.SystemCertPool()
  608. if err != nil {
  609. return nil, fmt.Errorf("unable to load system certificate pool: %w", err)
  610. }
  611. sslmode = "verify-full"
  612. } else {
  613. caCertPool = x509.NewCertPool()
  614. caPath := sslrootcert
  615. caCert, err := os.ReadFile(caPath)
  616. if err != nil {
  617. return nil, fmt.Errorf("unable to read CA file: %w", err)
  618. }
  619. if !caCertPool.AppendCertsFromPEM(caCert) {
  620. return nil, errors.New("unable to add CA to cert pool")
  621. }
  622. }
  623. tlsConfig.RootCAs = caCertPool
  624. tlsConfig.ClientCAs = caCertPool
  625. }
  626. switch sslmode {
  627. case "disable":
  628. return []*tls.Config{nil}, nil
  629. case "allow", "prefer":
  630. tlsConfig.InsecureSkipVerify = true
  631. case "require":
  632. // According to PostgreSQL documentation, if a root CA file exists,
  633. // the behavior of sslmode=require should be the same as that of verify-ca
  634. //
  635. // See https://www.postgresql.org/docs/current/libpq-ssl.html
  636. if sslrootcert != "" {
  637. goto nextCase
  638. }
  639. tlsConfig.InsecureSkipVerify = true
  640. break
  641. nextCase:
  642. fallthrough
  643. case "verify-ca":
  644. // Don't perform the default certificate verification because it
  645. // will verify the hostname. Instead, verify the server's
  646. // certificate chain ourselves in VerifyPeerCertificate and
  647. // ignore the server name. This emulates libpq's verify-ca
  648. // behavior.
  649. //
  650. // See https://github.com/golang/go/issues/21971#issuecomment-332693931
  651. // and https://pkg.go.dev/crypto/tls?tab=doc#example-Config-VerifyPeerCertificate
  652. // for more info.
  653. tlsConfig.InsecureSkipVerify = true
  654. tlsConfig.VerifyPeerCertificate = func(certificates [][]byte, _ [][]*x509.Certificate) error {
  655. certs := make([]*x509.Certificate, len(certificates))
  656. for i, asn1Data := range certificates {
  657. cert, err := x509.ParseCertificate(asn1Data)
  658. if err != nil {
  659. return errors.New("failed to parse certificate from server: " + err.Error())
  660. }
  661. certs[i] = cert
  662. }
  663. // Leave DNSName empty to skip hostname verification.
  664. opts := x509.VerifyOptions{
  665. Roots: tlsConfig.RootCAs,
  666. Intermediates: x509.NewCertPool(),
  667. }
  668. // Skip the first cert because it's the leaf. All others
  669. // are intermediates.
  670. for _, cert := range certs[1:] {
  671. opts.Intermediates.AddCert(cert)
  672. }
  673. _, err := certs[0].Verify(opts)
  674. return err
  675. }
  676. case "verify-full":
  677. tlsConfig.ServerName = host
  678. default:
  679. return nil, errors.New("sslmode is invalid")
  680. }
  681. if (sslcert != "" && sslkey == "") || (sslcert == "" && sslkey != "") {
  682. return nil, errors.New(`both "sslcert" and "sslkey" are required`)
  683. }
  684. if sslcert != "" && sslkey != "" {
  685. buf, err := os.ReadFile(sslkey)
  686. if err != nil {
  687. return nil, fmt.Errorf("unable to read sslkey: %w", err)
  688. }
  689. block, _ := pem.Decode(buf)
  690. if block == nil {
  691. return nil, errors.New("failed to decode sslkey")
  692. }
  693. var pemKey []byte
  694. var decryptedKey []byte
  695. var decryptedError error
  696. // If PEM is encrypted, attempt to decrypt using pass phrase
  697. if x509.IsEncryptedPEMBlock(block) {
  698. // Attempt decryption with pass phrase
  699. // NOTE: only supports RSA (PKCS#1)
  700. if sslpassword != "" {
  701. decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
  702. }
  703. // if sslpassword not provided or has decryption error when use it
  704. // try to find sslpassword with callback function
  705. if sslpassword == "" || decryptedError != nil {
  706. if parseConfigOptions.GetSSLPassword != nil {
  707. sslpassword = parseConfigOptions.GetSSLPassword(context.Background())
  708. }
  709. if sslpassword == "" {
  710. return nil, fmt.Errorf("unable to find sslpassword")
  711. }
  712. }
  713. decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
  714. // Should we also provide warning for PKCS#1 needed?
  715. if decryptedError != nil {
  716. return nil, fmt.Errorf("unable to decrypt key: %w", err)
  717. }
  718. pemBytes := pem.Block{
  719. Type: "RSA PRIVATE KEY",
  720. Bytes: decryptedKey,
  721. }
  722. pemKey = pem.EncodeToMemory(&pemBytes)
  723. } else {
  724. pemKey = pem.EncodeToMemory(block)
  725. }
  726. certfile, err := os.ReadFile(sslcert)
  727. if err != nil {
  728. return nil, fmt.Errorf("unable to read cert: %w", err)
  729. }
  730. cert, err := tls.X509KeyPair(certfile, pemKey)
  731. if err != nil {
  732. return nil, fmt.Errorf("unable to load cert: %w", err)
  733. }
  734. tlsConfig.Certificates = []tls.Certificate{cert}
  735. }
  736. // Set Server Name Indication (SNI), if enabled by connection parameters.
  737. // Per RFC 6066, do not set it if the host is a literal IP address (IPv4
  738. // or IPv6).
  739. if sslsni == "1" && net.ParseIP(host) == nil {
  740. tlsConfig.ServerName = host
  741. }
  742. switch sslmode {
  743. case "allow":
  744. return []*tls.Config{nil, tlsConfig}, nil
  745. case "prefer":
  746. return []*tls.Config{tlsConfig, nil}, nil
  747. case "require", "verify-ca", "verify-full":
  748. return []*tls.Config{tlsConfig}, nil
  749. default:
  750. panic("BUG: bad sslmode should already have been caught")
  751. }
  752. }
  753. func parsePort(s string) (uint16, error) {
  754. port, err := strconv.ParseUint(s, 10, 16)
  755. if err != nil {
  756. return 0, err
  757. }
  758. if port < 1 || port > math.MaxUint16 {
  759. return 0, errors.New("outside range")
  760. }
  761. return uint16(port), nil
  762. }
  763. func makeDefaultDialer() *net.Dialer {
  764. // rely on GOLANG KeepAlive settings
  765. return &net.Dialer{}
  766. }
  767. func makeDefaultResolver() *net.Resolver {
  768. return net.DefaultResolver
  769. }
  770. func parseConnectTimeoutSetting(s string) (time.Duration, error) {
  771. timeout, err := strconv.ParseInt(s, 10, 64)
  772. if err != nil {
  773. return 0, err
  774. }
  775. if timeout < 0 {
  776. return 0, errors.New("negative timeout")
  777. }
  778. return time.Duration(timeout) * time.Second, nil
  779. }
  780. func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc {
  781. d := makeDefaultDialer()
  782. d.Timeout = timeout
  783. return d.DialContext
  784. }
  785. // ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
  786. // target_session_attrs=read-write.
  787. func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error {
  788. result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll()
  789. if err != nil {
  790. return err
  791. }
  792. if string(result[0].Rows[0][0]) == "on" {
  793. return errors.New("read only connection")
  794. }
  795. return nil
  796. }
  797. // ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible
  798. // target_session_attrs=read-only.
  799. func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error {
  800. result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll()
  801. if err != nil {
  802. return err
  803. }
  804. if string(result[0].Rows[0][0]) != "on" {
  805. return errors.New("connection is not read only")
  806. }
  807. return nil
  808. }
  809. // ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible
  810. // target_session_attrs=standby.
  811. func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error {
  812. result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
  813. if err != nil {
  814. return err
  815. }
  816. if string(result[0].Rows[0][0]) != "t" {
  817. return errors.New("server is not in hot standby mode")
  818. }
  819. return nil
  820. }
  821. // ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible
  822. // target_session_attrs=primary.
  823. func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error {
  824. result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
  825. if err != nil {
  826. return err
  827. }
  828. if string(result[0].Rows[0][0]) == "t" {
  829. return errors.New("server is in standby mode")
  830. }
  831. return nil
  832. }
  833. // ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible
  834. // target_session_attrs=prefer-standby.
  835. func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error {
  836. result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll()
  837. if err != nil {
  838. return err
  839. }
  840. if string(result[0].Rows[0][0]) != "t" {
  841. return &NotPreferredError{err: errors.New("server is not in hot standby mode")}
  842. }
  843. return nil
  844. }