OSDN Git Service

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