conn.go 15 KB

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