conn.go 15 KB

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