conn.go 14 KB

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