conn.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bufio"
  17. "bytes"
  18. "crypto/tls"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "net"
  23. "net/url"
  24. "regexp"
  25. "strconv"
  26. "sync"
  27. "time"
  28. )
  29. // conn is the low-level implementation of Conn
  30. type conn struct {
  31. // Shared
  32. mu sync.Mutex
  33. pending int
  34. err error
  35. conn net.Conn
  36. // Read
  37. readTimeout time.Duration
  38. br *bufio.Reader
  39. // Write
  40. writeTimeout time.Duration
  41. bw *bufio.Writer
  42. // Scratch space for formatting argument length.
  43. // '*' or '$', length, "\r\n"
  44. lenScratch [32]byte
  45. // Scratch space for formatting integers and floats.
  46. numScratch [40]byte
  47. }
  48. // DialTimeout acts like Dial but takes timeouts for establishing the
  49. // connection to the server, writing a command and reading a reply.
  50. //
  51. // Deprecated: Use Dial with options instead.
  52. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  53. return Dial(network, address,
  54. DialConnectTimeout(connectTimeout),
  55. DialReadTimeout(readTimeout),
  56. DialWriteTimeout(writeTimeout))
  57. }
  58. // DialOption specifies an option for dialing a Redis server.
  59. type DialOption struct {
  60. f func(*dialOptions)
  61. }
  62. type dialOptions struct {
  63. readTimeout time.Duration
  64. writeTimeout time.Duration
  65. dial func(network, addr string) (net.Conn, error)
  66. db int
  67. password string
  68. dialTLS bool
  69. skipVerify bool
  70. tlsConfig *tls.Config
  71. }
  72. // DialReadTimeout specifies the timeout for reading a single command reply.
  73. func DialReadTimeout(d time.Duration) DialOption {
  74. return DialOption{func(do *dialOptions) {
  75. do.readTimeout = d
  76. }}
  77. }
  78. // DialWriteTimeout specifies the timeout for writing a single command.
  79. func DialWriteTimeout(d time.Duration) DialOption {
  80. return DialOption{func(do *dialOptions) {
  81. do.writeTimeout = d
  82. }}
  83. }
  84. // DialConnectTimeout specifies the timeout for connecting to the Redis server.
  85. func DialConnectTimeout(d time.Duration) DialOption {
  86. return DialOption{func(do *dialOptions) {
  87. dialer := net.Dialer{Timeout: d}
  88. do.dial = dialer.Dial
  89. }}
  90. }
  91. // DialNetDial specifies a custom dial function for creating TCP
  92. // connections. If this option is left out, then net.Dial is
  93. // used. DialNetDial overrides DialConnectTimeout.
  94. func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
  95. return DialOption{func(do *dialOptions) {
  96. do.dial = dial
  97. }}
  98. }
  99. // DialDatabase specifies the database to select when dialing a connection.
  100. func DialDatabase(db int) DialOption {
  101. return DialOption{func(do *dialOptions) {
  102. do.db = db
  103. }}
  104. }
  105. // DialPassword specifies the password to use when connecting to
  106. // the Redis server.
  107. func DialPassword(password string) DialOption {
  108. return DialOption{func(do *dialOptions) {
  109. do.password = password
  110. }}
  111. }
  112. // DialTLSConfig specifies the config to use when a TLS connection is dialed.
  113. // Has no effect when not dialing a TLS connection.
  114. func DialTLSConfig(c *tls.Config) DialOption {
  115. return DialOption{func(do *dialOptions) {
  116. do.tlsConfig = c
  117. }}
  118. }
  119. // DialTLSSkipVerify to disable server name verification when connecting
  120. // over TLS. Has no effect when not dialing a TLS connection.
  121. func DialTLSSkipVerify(skip bool) DialOption {
  122. return DialOption{func(do *dialOptions) {
  123. do.skipVerify = skip
  124. }}
  125. }
  126. // similar cloneTLSClientConfig in the stdlib, but also honor skipVerify for the nil case
  127. func cloneTLSClientConfig(cfg *tls.Config, skipVerify bool) *tls.Config {
  128. if cfg == nil {
  129. return &tls.Config{InsecureSkipVerify: skipVerify}
  130. }
  131. return &tls.Config{
  132. Rand: cfg.Rand,
  133. Time: cfg.Time,
  134. Certificates: cfg.Certificates,
  135. NameToCertificate: cfg.NameToCertificate,
  136. GetCertificate: cfg.GetCertificate,
  137. RootCAs: cfg.RootCAs,
  138. NextProtos: cfg.NextProtos,
  139. ServerName: cfg.ServerName,
  140. ClientAuth: cfg.ClientAuth,
  141. ClientCAs: cfg.ClientCAs,
  142. InsecureSkipVerify: cfg.InsecureSkipVerify,
  143. CipherSuites: cfg.CipherSuites,
  144. PreferServerCipherSuites: cfg.PreferServerCipherSuites,
  145. ClientSessionCache: cfg.ClientSessionCache,
  146. MinVersion: cfg.MinVersion,
  147. MaxVersion: cfg.MaxVersion,
  148. CurvePreferences: cfg.CurvePreferences,
  149. DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled,
  150. Renegotiation: cfg.Renegotiation,
  151. }
  152. }
  153. // Dial connects to the Redis server at the given network and
  154. // address using the specified options.
  155. func Dial(network, address string, options ...DialOption) (Conn, error) {
  156. do := dialOptions{
  157. dial: net.Dial,
  158. }
  159. for _, option := range options {
  160. option.f(&do)
  161. }
  162. netConn, err := do.dial(network, address)
  163. if err != nil {
  164. return nil, err
  165. }
  166. if do.dialTLS {
  167. tlsConfig := cloneTLSClientConfig(do.tlsConfig, do.skipVerify)
  168. if tlsConfig.ServerName == "" {
  169. host, _, err := net.SplitHostPort(address)
  170. if err != nil {
  171. netConn.Close()
  172. return nil, err
  173. }
  174. tlsConfig.ServerName = host
  175. }
  176. tlsConn := tls.Client(netConn, tlsConfig)
  177. if err := tlsConn.Handshake(); err != nil {
  178. netConn.Close()
  179. return nil, err
  180. }
  181. netConn = tlsConn
  182. }
  183. c := &conn{
  184. conn: netConn,
  185. bw: bufio.NewWriter(netConn),
  186. br: bufio.NewReader(netConn),
  187. readTimeout: do.readTimeout,
  188. writeTimeout: do.writeTimeout,
  189. }
  190. if do.password != "" {
  191. if _, err := c.Do("AUTH", do.password); err != nil {
  192. netConn.Close()
  193. return nil, err
  194. }
  195. }
  196. if do.db != 0 {
  197. if _, err := c.Do("SELECT", do.db); err != nil {
  198. netConn.Close()
  199. return nil, err
  200. }
  201. }
  202. return c, nil
  203. }
  204. func dialTLS(do *dialOptions) {
  205. do.dialTLS = true
  206. }
  207. var pathDBRegexp = regexp.MustCompile(`/(\d*)\z`)
  208. // DialURL connects to a Redis server at the given URL using the Redis
  209. // URI scheme. URLs should follow the draft IANA specification for the
  210. // scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
  211. func DialURL(rawurl string, options ...DialOption) (Conn, error) {
  212. u, err := url.Parse(rawurl)
  213. if err != nil {
  214. return nil, err
  215. }
  216. if u.Scheme != "redis" && u.Scheme != "rediss" {
  217. return nil, fmt.Errorf("invalid redis URL scheme: %s", u.Scheme)
  218. }
  219. // As per the IANA draft spec, the host defaults to localhost and
  220. // the port defaults to 6379.
  221. host, port, err := net.SplitHostPort(u.Host)
  222. if err != nil {
  223. // assume port is missing
  224. host = u.Host
  225. port = "6379"
  226. }
  227. if host == "" {
  228. host = "localhost"
  229. }
  230. address := net.JoinHostPort(host, port)
  231. if u.User != nil {
  232. password, isSet := u.User.Password()
  233. if isSet {
  234. options = append(options, DialPassword(password))
  235. }
  236. }
  237. match := pathDBRegexp.FindStringSubmatch(u.Path)
  238. if len(match) == 2 {
  239. db := 0
  240. if len(match[1]) > 0 {
  241. db, err = strconv.Atoi(match[1])
  242. if err != nil {
  243. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  244. }
  245. }
  246. if db != 0 {
  247. options = append(options, DialDatabase(db))
  248. }
  249. } else if u.Path != "" {
  250. return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
  251. }
  252. if u.Scheme == "rediss" {
  253. options = append([]DialOption{{dialTLS}}, options...)
  254. }
  255. return Dial("tcp", address, options...)
  256. }
  257. // NewConn returns a new Redigo connection for the given net connection.
  258. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  259. return &conn{
  260. conn: netConn,
  261. bw: bufio.NewWriter(netConn),
  262. br: bufio.NewReader(netConn),
  263. readTimeout: readTimeout,
  264. writeTimeout: writeTimeout,
  265. }
  266. }
  267. func (c *conn) Close() error {
  268. c.mu.Lock()
  269. err := c.err
  270. if c.err == nil {
  271. c.err = errors.New("redigo: closed")
  272. err = c.conn.Close()
  273. }
  274. c.mu.Unlock()
  275. return err
  276. }
  277. func (c *conn) fatal(err error) error {
  278. c.mu.Lock()
  279. if c.err == nil {
  280. c.err = err
  281. // Close connection to force errors on subsequent calls and to unblock
  282. // other reader or writer.
  283. c.conn.Close()
  284. }
  285. c.mu.Unlock()
  286. return err
  287. }
  288. func (c *conn) Err() error {
  289. c.mu.Lock()
  290. err := c.err
  291. c.mu.Unlock()
  292. return err
  293. }
  294. func (c *conn) writeLen(prefix byte, n int) error {
  295. c.lenScratch[len(c.lenScratch)-1] = '\n'
  296. c.lenScratch[len(c.lenScratch)-2] = '\r'
  297. i := len(c.lenScratch) - 3
  298. for {
  299. c.lenScratch[i] = byte('0' + n%10)
  300. i -= 1
  301. n = n / 10
  302. if n == 0 {
  303. break
  304. }
  305. }
  306. c.lenScratch[i] = prefix
  307. _, err := c.bw.Write(c.lenScratch[i:])
  308. return err
  309. }
  310. func (c *conn) writeString(s string) error {
  311. c.writeLen('$', len(s))
  312. c.bw.WriteString(s)
  313. _, err := c.bw.WriteString("\r\n")
  314. return err
  315. }
  316. func (c *conn) writeBytes(p []byte) error {
  317. c.writeLen('$', len(p))
  318. c.bw.Write(p)
  319. _, err := c.bw.WriteString("\r\n")
  320. return err
  321. }
  322. func (c *conn) writeInt64(n int64) error {
  323. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  324. }
  325. func (c *conn) writeFloat64(n float64) error {
  326. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  327. }
  328. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  329. c.writeLen('*', 1+len(args))
  330. err = c.writeString(cmd)
  331. for _, arg := range args {
  332. if err != nil {
  333. break
  334. }
  335. switch arg := arg.(type) {
  336. case string:
  337. err = c.writeString(arg)
  338. case []byte:
  339. err = c.writeBytes(arg)
  340. case int:
  341. err = c.writeInt64(int64(arg))
  342. case int64:
  343. err = c.writeInt64(arg)
  344. case float64:
  345. err = c.writeFloat64(arg)
  346. case bool:
  347. if arg {
  348. err = c.writeString("1")
  349. } else {
  350. err = c.writeString("0")
  351. }
  352. case nil:
  353. err = c.writeString("")
  354. default:
  355. var buf bytes.Buffer
  356. fmt.Fprint(&buf, arg)
  357. err = c.writeBytes(buf.Bytes())
  358. }
  359. }
  360. return err
  361. }
  362. type protocolError string
  363. func (pe protocolError) Error() string {
  364. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  365. }
  366. func (c *conn) readLine() ([]byte, error) {
  367. p, err := c.br.ReadSlice('\n')
  368. if err == bufio.ErrBufferFull {
  369. return nil, protocolError("long response line")
  370. }
  371. if err != nil {
  372. return nil, err
  373. }
  374. i := len(p) - 2
  375. if i < 0 || p[i] != '\r' {
  376. return nil, protocolError("bad response line terminator")
  377. }
  378. return p[:i], nil
  379. }
  380. // parseLen parses bulk string and array lengths.
  381. func parseLen(p []byte) (int, error) {
  382. if len(p) == 0 {
  383. return -1, protocolError("malformed length")
  384. }
  385. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  386. // handle $-1 and $-1 null replies.
  387. return -1, nil
  388. }
  389. var n int
  390. for _, b := range p {
  391. n *= 10
  392. if b < '0' || b > '9' {
  393. return -1, protocolError("illegal bytes in length")
  394. }
  395. n += int(b - '0')
  396. }
  397. return n, nil
  398. }
  399. // parseInt parses an integer reply.
  400. func parseInt(p []byte) (interface{}, error) {
  401. if len(p) == 0 {
  402. return 0, protocolError("malformed integer")
  403. }
  404. var negate bool
  405. if p[0] == '-' {
  406. negate = true
  407. p = p[1:]
  408. if len(p) == 0 {
  409. return 0, protocolError("malformed integer")
  410. }
  411. }
  412. var n int64
  413. for _, b := range p {
  414. n *= 10
  415. if b < '0' || b > '9' {
  416. return 0, protocolError("illegal bytes in length")
  417. }
  418. n += int64(b - '0')
  419. }
  420. if negate {
  421. n = -n
  422. }
  423. return n, nil
  424. }
  425. var (
  426. okReply interface{} = "OK"
  427. pongReply interface{} = "PONG"
  428. )
  429. func (c *conn) readReply() (interface{}, error) {
  430. line, err := c.readLine()
  431. if err != nil {
  432. return nil, err
  433. }
  434. if len(line) == 0 {
  435. return nil, protocolError("short response line")
  436. }
  437. switch line[0] {
  438. case '+':
  439. switch {
  440. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  441. // Avoid allocation for frequent "+OK" response.
  442. return okReply, nil
  443. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  444. // Avoid allocation in PING command benchmarks :)
  445. return pongReply, nil
  446. default:
  447. return string(line[1:]), nil
  448. }
  449. case '-':
  450. return Error(string(line[1:])), nil
  451. case ':':
  452. return parseInt(line[1:])
  453. case '$':
  454. n, err := parseLen(line[1:])
  455. if n < 0 || err != nil {
  456. return nil, err
  457. }
  458. p := make([]byte, n)
  459. _, err = io.ReadFull(c.br, p)
  460. if err != nil {
  461. return nil, err
  462. }
  463. if line, err := c.readLine(); err != nil {
  464. return nil, err
  465. } else if len(line) != 0 {
  466. return nil, protocolError("bad bulk string format")
  467. }
  468. return p, nil
  469. case '*':
  470. n, err := parseLen(line[1:])
  471. if n < 0 || err != nil {
  472. return nil, err
  473. }
  474. r := make([]interface{}, n)
  475. for i := range r {
  476. r[i], err = c.readReply()
  477. if err != nil {
  478. return nil, err
  479. }
  480. }
  481. return r, nil
  482. }
  483. return nil, protocolError("unexpected response line")
  484. }
  485. func (c *conn) Send(cmd string, args ...interface{}) error {
  486. c.mu.Lock()
  487. c.pending += 1
  488. c.mu.Unlock()
  489. if c.writeTimeout != 0 {
  490. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  491. }
  492. if err := c.writeCommand(cmd, args); err != nil {
  493. return c.fatal(err)
  494. }
  495. return nil
  496. }
  497. func (c *conn) Flush() error {
  498. if c.writeTimeout != 0 {
  499. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  500. }
  501. if err := c.bw.Flush(); err != nil {
  502. return c.fatal(err)
  503. }
  504. return nil
  505. }
  506. func (c *conn) Receive() (reply interface{}, err error) {
  507. if c.readTimeout != 0 {
  508. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  509. }
  510. if reply, err = c.readReply(); err != nil {
  511. return nil, c.fatal(err)
  512. }
  513. // When using pub/sub, the number of receives can be greater than the
  514. // number of sends. To enable normal use of the connection after
  515. // unsubscribing from all channels, we do not decrement pending to a
  516. // negative value.
  517. //
  518. // The pending field is decremented after the reply is read to handle the
  519. // case where Receive is called before Send.
  520. c.mu.Lock()
  521. if c.pending > 0 {
  522. c.pending -= 1
  523. }
  524. c.mu.Unlock()
  525. if err, ok := reply.(Error); ok {
  526. return nil, err
  527. }
  528. return
  529. }
  530. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  531. c.mu.Lock()
  532. pending := c.pending
  533. c.pending = 0
  534. c.mu.Unlock()
  535. if cmd == "" && pending == 0 {
  536. return nil, nil
  537. }
  538. if c.writeTimeout != 0 {
  539. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  540. }
  541. if cmd != "" {
  542. if err := c.writeCommand(cmd, args); err != nil {
  543. return nil, c.fatal(err)
  544. }
  545. }
  546. if err := c.bw.Flush(); err != nil {
  547. return nil, c.fatal(err)
  548. }
  549. if c.readTimeout != 0 {
  550. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  551. }
  552. if cmd == "" {
  553. reply := make([]interface{}, pending)
  554. for i := range reply {
  555. r, e := c.readReply()
  556. if e != nil {
  557. return nil, c.fatal(e)
  558. }
  559. reply[i] = r
  560. }
  561. return reply, nil
  562. }
  563. var err error
  564. var reply interface{}
  565. for i := 0; i <= pending; i++ {
  566. var e error
  567. if reply, e = c.readReply(); e != nil {
  568. return nil, c.fatal(e)
  569. }
  570. if e, ok := reply.(Error); ok && err == nil {
  571. err = e
  572. }
  573. }
  574. return reply, err
  575. }