conn.go 13 KB

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