Imported Upstream version 4.7.2
[platform/upstream/gcc48.git] / libgo / go / crypto / tls / conn.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // TLS low level connection and record layer
6
7 package tls
8
9 import (
10         "bytes"
11         "crypto/cipher"
12         "crypto/subtle"
13         "crypto/x509"
14         "errors"
15         "io"
16         "net"
17         "sync"
18         "time"
19 )
20
21 // A Conn represents a secured connection.
22 // It implements the net.Conn interface.
23 type Conn struct {
24         // constant
25         conn     net.Conn
26         isClient bool
27
28         // constant after handshake; protected by handshakeMutex
29         handshakeMutex    sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
30         vers              uint16     // TLS version
31         haveVers          bool       // version has been negotiated
32         config            *Config    // configuration passed to constructor
33         handshakeComplete bool
34         cipherSuite       uint16
35         ocspResponse      []byte // stapled OCSP response
36         peerCertificates  []*x509.Certificate
37         // verifiedChains contains the certificate chains that we built, as
38         // opposed to the ones presented by the server.
39         verifiedChains [][]*x509.Certificate
40         // serverName contains the server name indicated by the client, if any.
41         serverName string
42
43         clientProtocol         string
44         clientProtocolFallback bool
45
46         // first permanent error
47         errMutex sync.Mutex
48         err      error
49
50         // input/output
51         in, out  halfConn     // in.Mutex < out.Mutex
52         rawInput *block       // raw input, right off the wire
53         input    *block       // application data waiting to be read
54         hand     bytes.Buffer // handshake data waiting to be read
55
56         tmp [16]byte
57 }
58
59 func (c *Conn) setError(err error) error {
60         c.errMutex.Lock()
61         defer c.errMutex.Unlock()
62
63         if c.err == nil {
64                 c.err = err
65         }
66         return err
67 }
68
69 func (c *Conn) error() error {
70         c.errMutex.Lock()
71         defer c.errMutex.Unlock()
72
73         return c.err
74 }
75
76 // Access to net.Conn methods.
77 // Cannot just embed net.Conn because that would
78 // export the struct field too.
79
80 // LocalAddr returns the local network address.
81 func (c *Conn) LocalAddr() net.Addr {
82         return c.conn.LocalAddr()
83 }
84
85 // RemoteAddr returns the remote network address.
86 func (c *Conn) RemoteAddr() net.Addr {
87         return c.conn.RemoteAddr()
88 }
89
90 // SetDeadline sets the read and write deadlines associated with the connection.
91 // A zero value for t means Read and Write will not time out.
92 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
93 func (c *Conn) SetDeadline(t time.Time) error {
94         return c.conn.SetDeadline(t)
95 }
96
97 // SetReadDeadline sets the read deadline on the underlying connection.
98 // A zero value for t means Read will not time out.
99 func (c *Conn) SetReadDeadline(t time.Time) error {
100         return c.conn.SetReadDeadline(t)
101 }
102
103 // SetWriteDeadline sets the write deadline on the underlying conneciton.
104 // A zero value for t means Write will not time out.
105 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
106 func (c *Conn) SetWriteDeadline(t time.Time) error {
107         return c.conn.SetWriteDeadline(t)
108 }
109
110 // A halfConn represents one direction of the record layer
111 // connection, either sending or receiving.
112 type halfConn struct {
113         sync.Mutex
114         version uint16      // protocol version
115         cipher  interface{} // cipher algorithm
116         mac     macFunction
117         seq     [8]byte // 64-bit sequence number
118         bfree   *block  // list of free blocks
119
120         nextCipher interface{} // next encryption state
121         nextMac    macFunction // next MAC algorithm
122
123         // used to save allocating a new buffer for each MAC.
124         inDigestBuf, outDigestBuf []byte
125 }
126
127 // prepareCipherSpec sets the encryption and MAC states
128 // that a subsequent changeCipherSpec will use.
129 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
130         hc.version = version
131         hc.nextCipher = cipher
132         hc.nextMac = mac
133 }
134
135 // changeCipherSpec changes the encryption and MAC states
136 // to the ones previously passed to prepareCipherSpec.
137 func (hc *halfConn) changeCipherSpec() error {
138         if hc.nextCipher == nil {
139                 return alertInternalError
140         }
141         hc.cipher = hc.nextCipher
142         hc.mac = hc.nextMac
143         hc.nextCipher = nil
144         hc.nextMac = nil
145         return nil
146 }
147
148 // incSeq increments the sequence number.
149 func (hc *halfConn) incSeq() {
150         for i := 7; i >= 0; i-- {
151                 hc.seq[i]++
152                 if hc.seq[i] != 0 {
153                         return
154                 }
155         }
156
157         // Not allowed to let sequence number wrap.
158         // Instead, must renegotiate before it does.
159         // Not likely enough to bother.
160         panic("TLS: sequence number wraparound")
161 }
162
163 // resetSeq resets the sequence number to zero.
164 func (hc *halfConn) resetSeq() {
165         for i := range hc.seq {
166                 hc.seq[i] = 0
167         }
168 }
169
170 // removePadding returns an unpadded slice, in constant time, which is a prefix
171 // of the input. It also returns a byte which is equal to 255 if the padding
172 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
173 func removePadding(payload []byte) ([]byte, byte) {
174         if len(payload) < 1 {
175                 return payload, 0
176         }
177
178         paddingLen := payload[len(payload)-1]
179         t := uint(len(payload)-1) - uint(paddingLen)
180         // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
181         good := byte(int32(^t) >> 31)
182
183         toCheck := 255 // the maximum possible padding length
184         // The length of the padded data is public, so we can use an if here
185         if toCheck+1 > len(payload) {
186                 toCheck = len(payload) - 1
187         }
188
189         for i := 0; i < toCheck; i++ {
190                 t := uint(paddingLen) - uint(i)
191                 // if i <= paddingLen then the MSB of t is zero
192                 mask := byte(int32(^t) >> 31)
193                 b := payload[len(payload)-1-i]
194                 good &^= mask&paddingLen ^ mask&b
195         }
196
197         // We AND together the bits of good and replicate the result across
198         // all the bits.
199         good &= good << 4
200         good &= good << 2
201         good &= good << 1
202         good = uint8(int8(good) >> 7)
203
204         toRemove := good&paddingLen + 1
205         return payload[:len(payload)-int(toRemove)], good
206 }
207
208 // removePaddingSSL30 is a replacement for removePadding in the case that the
209 // protocol version is SSLv3. In this version, the contents of the padding
210 // are random and cannot be checked.
211 func removePaddingSSL30(payload []byte) ([]byte, byte) {
212         if len(payload) < 1 {
213                 return payload, 0
214         }
215
216         paddingLen := int(payload[len(payload)-1]) + 1
217         if paddingLen > len(payload) {
218                 return payload, 0
219         }
220
221         return payload[:len(payload)-paddingLen], 255
222 }
223
224 func roundUp(a, b int) int {
225         return a + (b-a%b)%b
226 }
227
228 // decrypt checks and strips the mac and decrypts the data in b.
229 func (hc *halfConn) decrypt(b *block) (bool, alert) {
230         // pull out payload
231         payload := b.data[recordHeaderLen:]
232
233         macSize := 0
234         if hc.mac != nil {
235                 macSize = hc.mac.Size()
236         }
237
238         paddingGood := byte(255)
239
240         // decrypt
241         if hc.cipher != nil {
242                 switch c := hc.cipher.(type) {
243                 case cipher.Stream:
244                         c.XORKeyStream(payload, payload)
245                 case cipher.BlockMode:
246                         blockSize := c.BlockSize()
247
248                         if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
249                                 return false, alertBadRecordMAC
250                         }
251
252                         c.CryptBlocks(payload, payload)
253                         if hc.version == versionSSL30 {
254                                 payload, paddingGood = removePaddingSSL30(payload)
255                         } else {
256                                 payload, paddingGood = removePadding(payload)
257                         }
258                         b.resize(recordHeaderLen + len(payload))
259
260                         // note that we still have a timing side-channel in the
261                         // MAC check, below. An attacker can align the record
262                         // so that a correct padding will cause one less hash
263                         // block to be calculated. Then they can iteratively
264                         // decrypt a record by breaking each byte. See
265                         // "Password Interception in a SSL/TLS Channel", Brice
266                         // Canvel et al.
267                         //
268                         // However, our behavior matches OpenSSL, so we leak
269                         // only as much as they do.
270                 default:
271                         panic("unknown cipher type")
272                 }
273         }
274
275         // check, strip mac
276         if hc.mac != nil {
277                 if len(payload) < macSize {
278                         return false, alertBadRecordMAC
279                 }
280
281                 // strip mac off payload, b.data
282                 n := len(payload) - macSize
283                 b.data[3] = byte(n >> 8)
284                 b.data[4] = byte(n)
285                 b.resize(recordHeaderLen + n)
286                 remoteMAC := payload[n:]
287                 localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
288                 hc.incSeq()
289
290                 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
291                         return false, alertBadRecordMAC
292                 }
293                 hc.inDigestBuf = localMAC
294         }
295
296         return true, 0
297 }
298
299 // padToBlockSize calculates the needed padding block, if any, for a payload.
300 // On exit, prefix aliases payload and extends to the end of the last full
301 // block of payload. finalBlock is a fresh slice which contains the contents of
302 // any suffix of payload as well as the needed padding to make finalBlock a
303 // full block.
304 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
305         overrun := len(payload) % blockSize
306         paddingLen := blockSize - overrun
307         prefix = payload[:len(payload)-overrun]
308         finalBlock = make([]byte, blockSize)
309         copy(finalBlock, payload[len(payload)-overrun:])
310         for i := overrun; i < blockSize; i++ {
311                 finalBlock[i] = byte(paddingLen - 1)
312         }
313         return
314 }
315
316 // encrypt encrypts and macs the data in b.
317 func (hc *halfConn) encrypt(b *block) (bool, alert) {
318         // mac
319         if hc.mac != nil {
320                 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
321                 hc.incSeq()
322
323                 n := len(b.data)
324                 b.resize(n + len(mac))
325                 copy(b.data[n:], mac)
326                 hc.outDigestBuf = mac
327         }
328
329         payload := b.data[recordHeaderLen:]
330
331         // encrypt
332         if hc.cipher != nil {
333                 switch c := hc.cipher.(type) {
334                 case cipher.Stream:
335                         c.XORKeyStream(payload, payload)
336                 case cipher.BlockMode:
337                         prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
338                         b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
339                         c.CryptBlocks(b.data[recordHeaderLen:], prefix)
340                         c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
341                 default:
342                         panic("unknown cipher type")
343                 }
344         }
345
346         // update length to include MAC and any block padding needed.
347         n := len(b.data) - recordHeaderLen
348         b.data[3] = byte(n >> 8)
349         b.data[4] = byte(n)
350
351         return true, 0
352 }
353
354 // A block is a simple data buffer.
355 type block struct {
356         data []byte
357         off  int // index for Read
358         link *block
359 }
360
361 // resize resizes block to be n bytes, growing if necessary.
362 func (b *block) resize(n int) {
363         if n > cap(b.data) {
364                 b.reserve(n)
365         }
366         b.data = b.data[0:n]
367 }
368
369 // reserve makes sure that block contains a capacity of at least n bytes.
370 func (b *block) reserve(n int) {
371         if cap(b.data) >= n {
372                 return
373         }
374         m := cap(b.data)
375         if m == 0 {
376                 m = 1024
377         }
378         for m < n {
379                 m *= 2
380         }
381         data := make([]byte, len(b.data), m)
382         copy(data, b.data)
383         b.data = data
384 }
385
386 // readFromUntil reads from r into b until b contains at least n bytes
387 // or else returns an error.
388 func (b *block) readFromUntil(r io.Reader, n int) error {
389         // quick case
390         if len(b.data) >= n {
391                 return nil
392         }
393
394         // read until have enough.
395         b.reserve(n)
396         for {
397                 m, err := r.Read(b.data[len(b.data):cap(b.data)])
398                 b.data = b.data[0 : len(b.data)+m]
399                 if len(b.data) >= n {
400                         break
401                 }
402                 if err != nil {
403                         return err
404                 }
405         }
406         return nil
407 }
408
409 func (b *block) Read(p []byte) (n int, err error) {
410         n = copy(p, b.data[b.off:])
411         b.off += n
412         return
413 }
414
415 // newBlock allocates a new block, from hc's free list if possible.
416 func (hc *halfConn) newBlock() *block {
417         b := hc.bfree
418         if b == nil {
419                 return new(block)
420         }
421         hc.bfree = b.link
422         b.link = nil
423         b.resize(0)
424         return b
425 }
426
427 // freeBlock returns a block to hc's free list.
428 // The protocol is such that each side only has a block or two on
429 // its free list at a time, so there's no need to worry about
430 // trimming the list, etc.
431 func (hc *halfConn) freeBlock(b *block) {
432         b.link = hc.bfree
433         hc.bfree = b
434 }
435
436 // splitBlock splits a block after the first n bytes,
437 // returning a block with those n bytes and a
438 // block with the remainder.  the latter may be nil.
439 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
440         if len(b.data) <= n {
441                 return b, nil
442         }
443         bb := hc.newBlock()
444         bb.resize(len(b.data) - n)
445         copy(bb.data, b.data[n:])
446         b.data = b.data[0:n]
447         return b, bb
448 }
449
450 // readRecord reads the next TLS record from the connection
451 // and updates the record layer state.
452 // c.in.Mutex <= L; c.input == nil.
453 func (c *Conn) readRecord(want recordType) error {
454         // Caller must be in sync with connection:
455         // handshake data if handshake not yet completed,
456         // else application data.  (We don't support renegotiation.)
457         switch want {
458         default:
459                 return c.sendAlert(alertInternalError)
460         case recordTypeHandshake, recordTypeChangeCipherSpec:
461                 if c.handshakeComplete {
462                         return c.sendAlert(alertInternalError)
463                 }
464         case recordTypeApplicationData:
465                 if !c.handshakeComplete {
466                         return c.sendAlert(alertInternalError)
467                 }
468         }
469
470 Again:
471         if c.rawInput == nil {
472                 c.rawInput = c.in.newBlock()
473         }
474         b := c.rawInput
475
476         // Read header, payload.
477         if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
478                 // RFC suggests that EOF without an alertCloseNotify is
479                 // an error, but popular web sites seem to do this,
480                 // so we can't make it an error.
481                 // if err == io.EOF {
482                 //      err = io.ErrUnexpectedEOF
483                 // }
484                 if e, ok := err.(net.Error); !ok || !e.Temporary() {
485                         c.setError(err)
486                 }
487                 return err
488         }
489         typ := recordType(b.data[0])
490         vers := uint16(b.data[1])<<8 | uint16(b.data[2])
491         n := int(b.data[3])<<8 | int(b.data[4])
492         if c.haveVers && vers != c.vers {
493                 return c.sendAlert(alertProtocolVersion)
494         }
495         if n > maxCiphertext {
496                 return c.sendAlert(alertRecordOverflow)
497         }
498         if !c.haveVers {
499                 // First message, be extra suspicious:
500                 // this might not be a TLS client.
501                 // Bail out before reading a full 'body', if possible.
502                 // The current max version is 3.1. 
503                 // If the version is >= 16.0, it's probably not real.
504                 // Similarly, a clientHello message encodes in
505                 // well under a kilobyte.  If the length is >= 12 kB,
506                 // it's probably not real.
507                 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
508                         return c.sendAlert(alertUnexpectedMessage)
509                 }
510         }
511         if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
512                 if err == io.EOF {
513                         err = io.ErrUnexpectedEOF
514                 }
515                 if e, ok := err.(net.Error); !ok || !e.Temporary() {
516                         c.setError(err)
517                 }
518                 return err
519         }
520
521         // Process message.
522         b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
523         b.off = recordHeaderLen
524         if ok, err := c.in.decrypt(b); !ok {
525                 return c.sendAlert(err)
526         }
527         data := b.data[b.off:]
528         if len(data) > maxPlaintext {
529                 c.sendAlert(alertRecordOverflow)
530                 c.in.freeBlock(b)
531                 return c.error()
532         }
533
534         switch typ {
535         default:
536                 c.sendAlert(alertUnexpectedMessage)
537
538         case recordTypeAlert:
539                 if len(data) != 2 {
540                         c.sendAlert(alertUnexpectedMessage)
541                         break
542                 }
543                 if alert(data[1]) == alertCloseNotify {
544                         c.setError(io.EOF)
545                         break
546                 }
547                 switch data[0] {
548                 case alertLevelWarning:
549                         // drop on the floor
550                         c.in.freeBlock(b)
551                         goto Again
552                 case alertLevelError:
553                         c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
554                 default:
555                         c.sendAlert(alertUnexpectedMessage)
556                 }
557
558         case recordTypeChangeCipherSpec:
559                 if typ != want || len(data) != 1 || data[0] != 1 {
560                         c.sendAlert(alertUnexpectedMessage)
561                         break
562                 }
563                 err := c.in.changeCipherSpec()
564                 if err != nil {
565                         c.sendAlert(err.(alert))
566                 }
567
568         case recordTypeApplicationData:
569                 if typ != want {
570                         c.sendAlert(alertUnexpectedMessage)
571                         break
572                 }
573                 c.input = b
574                 b = nil
575
576         case recordTypeHandshake:
577                 // TODO(rsc): Should at least pick off connection close.
578                 if typ != want {
579                         return c.sendAlert(alertNoRenegotiation)
580                 }
581                 c.hand.Write(data)
582         }
583
584         if b != nil {
585                 c.in.freeBlock(b)
586         }
587         return c.error()
588 }
589
590 // sendAlert sends a TLS alert message.
591 // c.out.Mutex <= L.
592 func (c *Conn) sendAlertLocked(err alert) error {
593         c.tmp[0] = alertLevelError
594         if err == alertNoRenegotiation {
595                 c.tmp[0] = alertLevelWarning
596         }
597         c.tmp[1] = byte(err)
598         c.writeRecord(recordTypeAlert, c.tmp[0:2])
599         // closeNotify is a special case in that it isn't an error:
600         if err != alertCloseNotify {
601                 return c.setError(&net.OpError{Op: "local error", Err: err})
602         }
603         return nil
604 }
605
606 // sendAlert sends a TLS alert message.
607 // L < c.out.Mutex.
608 func (c *Conn) sendAlert(err alert) error {
609         c.out.Lock()
610         defer c.out.Unlock()
611         return c.sendAlertLocked(err)
612 }
613
614 // writeRecord writes a TLS record with the given type and payload
615 // to the connection and updates the record layer state.
616 // c.out.Mutex <= L.
617 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
618         b := c.out.newBlock()
619         for len(data) > 0 {
620                 m := len(data)
621                 if m > maxPlaintext {
622                         m = maxPlaintext
623                 }
624                 b.resize(recordHeaderLen + m)
625                 b.data[0] = byte(typ)
626                 vers := c.vers
627                 if vers == 0 {
628                         vers = maxVersion
629                 }
630                 b.data[1] = byte(vers >> 8)
631                 b.data[2] = byte(vers)
632                 b.data[3] = byte(m >> 8)
633                 b.data[4] = byte(m)
634                 copy(b.data[recordHeaderLen:], data)
635                 c.out.encrypt(b)
636                 _, err = c.conn.Write(b.data)
637                 if err != nil {
638                         break
639                 }
640                 n += m
641                 data = data[m:]
642         }
643         c.out.freeBlock(b)
644
645         if typ == recordTypeChangeCipherSpec {
646                 err = c.out.changeCipherSpec()
647                 if err != nil {
648                         // Cannot call sendAlert directly,
649                         // because we already hold c.out.Mutex.
650                         c.tmp[0] = alertLevelError
651                         c.tmp[1] = byte(err.(alert))
652                         c.writeRecord(recordTypeAlert, c.tmp[0:2])
653                         c.err = &net.OpError{Op: "local error", Err: err}
654                         return n, c.err
655                 }
656         }
657         return
658 }
659
660 // readHandshake reads the next handshake message from
661 // the record layer.
662 // c.in.Mutex < L; c.out.Mutex < L.
663 func (c *Conn) readHandshake() (interface{}, error) {
664         for c.hand.Len() < 4 {
665                 if c.err != nil {
666                         return nil, c.err
667                 }
668                 if err := c.readRecord(recordTypeHandshake); err != nil {
669                         return nil, err
670                 }
671         }
672
673         data := c.hand.Bytes()
674         n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
675         if n > maxHandshake {
676                 c.sendAlert(alertInternalError)
677                 return nil, c.err
678         }
679         for c.hand.Len() < 4+n {
680                 if c.err != nil {
681                         return nil, c.err
682                 }
683                 if err := c.readRecord(recordTypeHandshake); err != nil {
684                         return nil, err
685                 }
686         }
687         data = c.hand.Next(4 + n)
688         var m handshakeMessage
689         switch data[0] {
690         case typeClientHello:
691                 m = new(clientHelloMsg)
692         case typeServerHello:
693                 m = new(serverHelloMsg)
694         case typeCertificate:
695                 m = new(certificateMsg)
696         case typeCertificateRequest:
697                 m = new(certificateRequestMsg)
698         case typeCertificateStatus:
699                 m = new(certificateStatusMsg)
700         case typeServerKeyExchange:
701                 m = new(serverKeyExchangeMsg)
702         case typeServerHelloDone:
703                 m = new(serverHelloDoneMsg)
704         case typeClientKeyExchange:
705                 m = new(clientKeyExchangeMsg)
706         case typeCertificateVerify:
707                 m = new(certificateVerifyMsg)
708         case typeNextProtocol:
709                 m = new(nextProtoMsg)
710         case typeFinished:
711                 m = new(finishedMsg)
712         default:
713                 c.sendAlert(alertUnexpectedMessage)
714                 return nil, alertUnexpectedMessage
715         }
716
717         // The handshake message unmarshallers
718         // expect to be able to keep references to data,
719         // so pass in a fresh copy that won't be overwritten.
720         data = append([]byte(nil), data...)
721
722         if !m.unmarshal(data) {
723                 c.sendAlert(alertUnexpectedMessage)
724                 return nil, alertUnexpectedMessage
725         }
726         return m, nil
727 }
728
729 // Write writes data to the connection.
730 func (c *Conn) Write(b []byte) (int, error) {
731         if c.err != nil {
732                 return 0, c.err
733         }
734
735         if c.err = c.Handshake(); c.err != nil {
736                 return 0, c.err
737         }
738
739         c.out.Lock()
740         defer c.out.Unlock()
741
742         if !c.handshakeComplete {
743                 return 0, alertInternalError
744         }
745
746         var n int
747         n, c.err = c.writeRecord(recordTypeApplicationData, b)
748         return n, c.err
749 }
750
751 // Read can be made to time out and return a net.Error with Timeout() == true
752 // after a fixed time limit; see SetDeadline and SetReadDeadline.
753 func (c *Conn) Read(b []byte) (n int, err error) {
754         if err = c.Handshake(); err != nil {
755                 return
756         }
757
758         c.in.Lock()
759         defer c.in.Unlock()
760
761         for c.input == nil && c.err == nil {
762                 if err := c.readRecord(recordTypeApplicationData); err != nil {
763                         // Soft error, like EAGAIN
764                         return 0, err
765                 }
766         }
767         if c.err != nil {
768                 return 0, c.err
769         }
770         n, err = c.input.Read(b)
771         if c.input.off >= len(c.input.data) {
772                 c.in.freeBlock(c.input)
773                 c.input = nil
774         }
775         return n, nil
776 }
777
778 // Close closes the connection.
779 func (c *Conn) Close() error {
780         var alertErr error
781
782         c.handshakeMutex.Lock()
783         defer c.handshakeMutex.Unlock()
784         if c.handshakeComplete {
785                 alertErr = c.sendAlert(alertCloseNotify)
786         }
787
788         if err := c.conn.Close(); err != nil {
789                 return err
790         }
791         return alertErr
792 }
793
794 // Handshake runs the client or server handshake
795 // protocol if it has not yet been run.
796 // Most uses of this package need not call Handshake
797 // explicitly: the first Read or Write will call it automatically.
798 func (c *Conn) Handshake() error {
799         c.handshakeMutex.Lock()
800         defer c.handshakeMutex.Unlock()
801         if err := c.error(); err != nil {
802                 return err
803         }
804         if c.handshakeComplete {
805                 return nil
806         }
807         if c.isClient {
808                 return c.clientHandshake()
809         }
810         return c.serverHandshake()
811 }
812
813 // ConnectionState returns basic TLS details about the connection.
814 func (c *Conn) ConnectionState() ConnectionState {
815         c.handshakeMutex.Lock()
816         defer c.handshakeMutex.Unlock()
817
818         var state ConnectionState
819         state.HandshakeComplete = c.handshakeComplete
820         if c.handshakeComplete {
821                 state.NegotiatedProtocol = c.clientProtocol
822                 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
823                 state.CipherSuite = c.cipherSuite
824                 state.PeerCertificates = c.peerCertificates
825                 state.VerifiedChains = c.verifiedChains
826                 state.ServerName = c.serverName
827         }
828
829         return state
830 }
831
832 // OCSPResponse returns the stapled OCSP response from the TLS server, if
833 // any. (Only valid for client connections.)
834 func (c *Conn) OCSPResponse() []byte {
835         c.handshakeMutex.Lock()
836         defer c.handshakeMutex.Unlock()
837
838         return c.ocspResponse
839 }
840
841 // VerifyHostname checks that the peer certificate chain is valid for
842 // connecting to host.  If so, it returns nil; if not, it returns an error
843 // describing the problem.
844 func (c *Conn) VerifyHostname(host string) error {
845         c.handshakeMutex.Lock()
846         defer c.handshakeMutex.Unlock()
847         if !c.isClient {
848                 return errors.New("VerifyHostname called on TLS server connection")
849         }
850         if !c.handshakeComplete {
851                 return errors.New("TLS handshake has not yet been performed")
852         }
853         return c.peerCertificates[0].VerifyHostname(host)
854 }