conn.go 14 KB

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