conn.go 14 KB

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