Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / test / runner / common.go
1 // Copyright 2009 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 package main
6
7 import (
8         "container/list"
9         "crypto"
10         "crypto/ecdsa"
11         "crypto/rand"
12         "crypto/x509"
13         "fmt"
14         "io"
15         "math/big"
16         "strings"
17         "sync"
18         "time"
19 )
20
21 const (
22         VersionSSL30 = 0x0300
23         VersionTLS10 = 0x0301
24         VersionTLS11 = 0x0302
25         VersionTLS12 = 0x0303
26 )
27
28 const (
29         maxPlaintext        = 16384        // maximum plaintext payload length
30         maxCiphertext       = 16384 + 2048 // maximum ciphertext payload length
31         tlsRecordHeaderLen  = 5            // record header length
32         dtlsRecordHeaderLen = 13
33         maxHandshake        = 65536 // maximum handshake we support (protocol max is 16 MB)
34
35         minVersion = VersionSSL30
36         maxVersion = VersionTLS12
37 )
38
39 // TLS record types.
40 type recordType uint8
41
42 const (
43         recordTypeChangeCipherSpec recordType = 20
44         recordTypeAlert            recordType = 21
45         recordTypeHandshake        recordType = 22
46         recordTypeApplicationData  recordType = 23
47 )
48
49 // TLS handshake message types.
50 const (
51         typeHelloRequest        uint8 = 0
52         typeClientHello         uint8 = 1
53         typeServerHello         uint8 = 2
54         typeHelloVerifyRequest  uint8 = 3
55         typeNewSessionTicket    uint8 = 4
56         typeCertificate         uint8 = 11
57         typeServerKeyExchange   uint8 = 12
58         typeCertificateRequest  uint8 = 13
59         typeServerHelloDone     uint8 = 14
60         typeCertificateVerify   uint8 = 15
61         typeClientKeyExchange   uint8 = 16
62         typeFinished            uint8 = 20
63         typeCertificateStatus   uint8 = 22
64         typeNextProtocol        uint8 = 67  // Not IANA assigned
65         typeEncryptedExtensions uint8 = 203 // Not IANA assigned
66 )
67
68 // TLS compression types.
69 const (
70         compressionNone uint8 = 0
71 )
72
73 // TLS extension numbers
74 const (
75         extensionServerName           uint16 = 0
76         extensionStatusRequest        uint16 = 5
77         extensionSupportedCurves      uint16 = 10
78         extensionSupportedPoints      uint16 = 11
79         extensionSignatureAlgorithms  uint16 = 13
80         extensionALPN                 uint16 = 16
81         extensionExtendedMasterSecret uint16 = 23
82         extensionSessionTicket        uint16 = 35
83         extensionNextProtoNeg         uint16 = 13172 // not IANA assigned
84         extensionRenegotiationInfo    uint16 = 0xff01
85         extensionChannelID            uint16 = 30032 // not IANA assigned
86 )
87
88 // TLS signaling cipher suite values
89 const (
90         scsvRenegotiation uint16 = 0x00ff
91 )
92
93 // CurveID is the type of a TLS identifier for an elliptic curve. See
94 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
95 type CurveID uint16
96
97 const (
98         CurveP256 CurveID = 23
99         CurveP384 CurveID = 24
100         CurveP521 CurveID = 25
101 )
102
103 // TLS Elliptic Curve Point Formats
104 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
105 const (
106         pointFormatUncompressed uint8 = 0
107 )
108
109 // TLS CertificateStatusType (RFC 3546)
110 const (
111         statusTypeOCSP uint8 = 1
112 )
113
114 // Certificate types (for certificateRequestMsg)
115 const (
116         CertTypeRSASign    = 1 // A certificate containing an RSA key
117         CertTypeDSSSign    = 2 // A certificate containing a DSA key
118         CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
119         CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
120
121         // See RFC4492 sections 3 and 5.5.
122         CertTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
123         CertTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
124         CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
125
126         // Rest of these are reserved by the TLS spec
127 )
128
129 // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
130 const (
131         hashSHA1   uint8 = 2
132         hashSHA256 uint8 = 4
133 )
134
135 // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
136 const (
137         signatureRSA   uint8 = 1
138         signatureECDSA uint8 = 3
139 )
140
141 // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
142 // RFC 5246, section A.4.1.
143 type signatureAndHash struct {
144         signature, hash uint8
145 }
146
147 // supportedSKXSignatureAlgorithms contains the signature and hash algorithms
148 // that the code advertises as supported in a TLS 1.2 ClientHello.
149 var supportedSKXSignatureAlgorithms = []signatureAndHash{
150         {signatureRSA, hashSHA256},
151         {signatureECDSA, hashSHA256},
152         {signatureRSA, hashSHA1},
153         {signatureECDSA, hashSHA1},
154 }
155
156 // supportedClientCertSignatureAlgorithms contains the signature and hash
157 // algorithms that the code advertises as supported in a TLS 1.2
158 // CertificateRequest.
159 var supportedClientCertSignatureAlgorithms = []signatureAndHash{
160         {signatureRSA, hashSHA256},
161         {signatureECDSA, hashSHA256},
162 }
163
164 // ConnectionState records basic TLS details about the connection.
165 type ConnectionState struct {
166         Version                    uint16                // TLS version used by the connection (e.g. VersionTLS12)
167         HandshakeComplete          bool                  // TLS handshake is complete
168         DidResume                  bool                  // connection resumes a previous TLS connection
169         CipherSuite                uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
170         NegotiatedProtocol         string                // negotiated next protocol (from Config.NextProtos)
171         NegotiatedProtocolIsMutual bool                  // negotiated protocol was advertised by server
172         NegotiatedProtocolFromALPN bool                  // protocol negotiated with ALPN
173         ServerName                 string                // server name requested by client, if any (server side only)
174         PeerCertificates           []*x509.Certificate   // certificate chain presented by remote peer
175         VerifiedChains             [][]*x509.Certificate // verified chains built from PeerCertificates
176         ChannelID                  *ecdsa.PublicKey      // the channel ID for this connection
177 }
178
179 // ClientAuthType declares the policy the server will follow for
180 // TLS Client Authentication.
181 type ClientAuthType int
182
183 const (
184         NoClientCert ClientAuthType = iota
185         RequestClientCert
186         RequireAnyClientCert
187         VerifyClientCertIfGiven
188         RequireAndVerifyClientCert
189 )
190
191 // ClientSessionState contains the state needed by clients to resume TLS
192 // sessions.
193 type ClientSessionState struct {
194         sessionTicket        []uint8             // Encrypted ticket used for session resumption with server
195         vers                 uint16              // SSL/TLS version negotiated for the session
196         cipherSuite          uint16              // Ciphersuite negotiated for the session
197         masterSecret         []byte              // MasterSecret generated by client on a full handshake
198         handshakeHash        []byte              // Handshake hash for Channel ID purposes.
199         serverCertificates   []*x509.Certificate // Certificate chain presented by the server
200         extendedMasterSecret bool                // Whether an extended master secret was used to generate the session
201 }
202
203 // ClientSessionCache is a cache of ClientSessionState objects that can be used
204 // by a client to resume a TLS session with a given server. ClientSessionCache
205 // implementations should expect to be called concurrently from different
206 // goroutines.
207 type ClientSessionCache interface {
208         // Get searches for a ClientSessionState associated with the given key.
209         // On return, ok is true if one was found.
210         Get(sessionKey string) (session *ClientSessionState, ok bool)
211
212         // Put adds the ClientSessionState to the cache with the given key.
213         Put(sessionKey string, cs *ClientSessionState)
214 }
215
216 // A Config structure is used to configure a TLS client or server.
217 // After one has been passed to a TLS function it must not be
218 // modified. A Config may be reused; the tls package will also not
219 // modify it.
220 type Config struct {
221         // Rand provides the source of entropy for nonces and RSA blinding.
222         // If Rand is nil, TLS uses the cryptographic random reader in package
223         // crypto/rand.
224         // The Reader must be safe for use by multiple goroutines.
225         Rand io.Reader
226
227         // Time returns the current time as the number of seconds since the epoch.
228         // If Time is nil, TLS uses time.Now.
229         Time func() time.Time
230
231         // Certificates contains one or more certificate chains
232         // to present to the other side of the connection.
233         // Server configurations must include at least one certificate.
234         Certificates []Certificate
235
236         // NameToCertificate maps from a certificate name to an element of
237         // Certificates. Note that a certificate name can be of the form
238         // '*.example.com' and so doesn't have to be a domain name as such.
239         // See Config.BuildNameToCertificate
240         // The nil value causes the first element of Certificates to be used
241         // for all connections.
242         NameToCertificate map[string]*Certificate
243
244         // RootCAs defines the set of root certificate authorities
245         // that clients use when verifying server certificates.
246         // If RootCAs is nil, TLS uses the host's root CA set.
247         RootCAs *x509.CertPool
248
249         // NextProtos is a list of supported, application level protocols.
250         NextProtos []string
251
252         // ServerName is used to verify the hostname on the returned
253         // certificates unless InsecureSkipVerify is given. It is also included
254         // in the client's handshake to support virtual hosting.
255         ServerName string
256
257         // ClientAuth determines the server's policy for
258         // TLS Client Authentication. The default is NoClientCert.
259         ClientAuth ClientAuthType
260
261         // ClientCAs defines the set of root certificate authorities
262         // that servers use if required to verify a client certificate
263         // by the policy in ClientAuth.
264         ClientCAs *x509.CertPool
265
266         // ClientCertificateTypes defines the set of allowed client certificate
267         // types. The default is CertTypeRSASign and CertTypeECDSASign.
268         ClientCertificateTypes []byte
269
270         // InsecureSkipVerify controls whether a client verifies the
271         // server's certificate chain and host name.
272         // If InsecureSkipVerify is true, TLS accepts any certificate
273         // presented by the server and any host name in that certificate.
274         // In this mode, TLS is susceptible to man-in-the-middle attacks.
275         // This should be used only for testing.
276         InsecureSkipVerify bool
277
278         // CipherSuites is a list of supported cipher suites. If CipherSuites
279         // is nil, TLS uses a list of suites supported by the implementation.
280         CipherSuites []uint16
281
282         // PreferServerCipherSuites controls whether the server selects the
283         // client's most preferred ciphersuite, or the server's most preferred
284         // ciphersuite. If true then the server's preference, as expressed in
285         // the order of elements in CipherSuites, is used.
286         PreferServerCipherSuites bool
287
288         // SessionTicketsDisabled may be set to true to disable session ticket
289         // (resumption) support.
290         SessionTicketsDisabled bool
291
292         // SessionTicketKey is used by TLS servers to provide session
293         // resumption. See RFC 5077. If zero, it will be filled with
294         // random data before the first server handshake.
295         //
296         // If multiple servers are terminating connections for the same host
297         // they should all have the same SessionTicketKey. If the
298         // SessionTicketKey leaks, previously recorded and future TLS
299         // connections using that key are compromised.
300         SessionTicketKey [32]byte
301
302         // SessionCache is a cache of ClientSessionState entries for TLS session
303         // resumption.
304         ClientSessionCache ClientSessionCache
305
306         // MinVersion contains the minimum SSL/TLS version that is acceptable.
307         // If zero, then SSLv3 is taken as the minimum.
308         MinVersion uint16
309
310         // MaxVersion contains the maximum SSL/TLS version that is acceptable.
311         // If zero, then the maximum version supported by this package is used,
312         // which is currently TLS 1.2.
313         MaxVersion uint16
314
315         // CurvePreferences contains the elliptic curves that will be used in
316         // an ECDHE handshake, in preference order. If empty, the default will
317         // be used.
318         CurvePreferences []CurveID
319
320         // ChannelID contains the ECDSA key for the client to use as
321         // its TLS Channel ID.
322         ChannelID *ecdsa.PrivateKey
323
324         // RequestChannelID controls whether the server requests a TLS
325         // Channel ID. If negotiated, the client's public key is
326         // returned in the ConnectionState.
327         RequestChannelID bool
328
329         // PreSharedKey, if not nil, is the pre-shared key to use with
330         // the PSK cipher suites.
331         PreSharedKey []byte
332
333         // PreSharedKeyIdentity, if not empty, is the identity to use
334         // with the PSK cipher suites.
335         PreSharedKeyIdentity string
336
337         // Bugs specifies optional misbehaviour to be used for testing other
338         // implementations.
339         Bugs ProtocolBugs
340
341         serverInitOnce sync.Once // guards calling (*Config).serverInit
342 }
343
344 type BadValue int
345
346 const (
347         BadValueNone BadValue = iota
348         BadValueNegative
349         BadValueZero
350         BadValueLimit
351         BadValueLarge
352         NumBadValues
353 )
354
355 type ProtocolBugs struct {
356         // InvalidSKXSignature specifies that the signature in a
357         // ServerKeyExchange message should be invalid.
358         InvalidSKXSignature bool
359
360         // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
361         // to be wrong.
362         InvalidSKXCurve bool
363
364         // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
365         // can be invalid.
366         BadECDSAR BadValue
367         BadECDSAS BadValue
368
369         // MaxPadding causes CBC records to have the maximum possible padding.
370         MaxPadding bool
371         // PaddingFirstByteBad causes the first byte of the padding to be
372         // incorrect.
373         PaddingFirstByteBad bool
374         // PaddingFirstByteBadIf255 causes the first byte of padding to be
375         // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
376         PaddingFirstByteBadIf255 bool
377
378         // FailIfNotFallbackSCSV causes a server handshake to fail if the
379         // client doesn't send the fallback SCSV value.
380         FailIfNotFallbackSCSV bool
381
382         // DuplicateExtension causes an extra empty extension of bogus type to
383         // be emitted in either the ClientHello or the ServerHello.
384         DuplicateExtension bool
385
386         // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
387         // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
388         // Certificate message is sent and no signature is added to
389         // ServerKeyExchange.
390         UnauthenticatedECDH bool
391
392         // SkipServerKeyExchange causes the server to skip sending
393         // ServerKeyExchange messages.
394         SkipServerKeyExchange bool
395
396         // SkipChangeCipherSpec causes the implementation to skip
397         // sending the ChangeCipherSpec message (and adjusting cipher
398         // state accordingly for the Finished message).
399         SkipChangeCipherSpec bool
400
401         // EarlyChangeCipherSpec causes the client to send an early
402         // ChangeCipherSpec message before the ClientKeyExchange. A value of
403         // zero disables this behavior. One and two configure variants for 0.9.8
404         // and 1.0.1 modes, respectively.
405         EarlyChangeCipherSpec int
406
407         // FragmentAcrossChangeCipherSpec causes the implementation to fragment
408         // the Finished (or NextProto) message around the ChangeCipherSpec
409         // messages.
410         FragmentAcrossChangeCipherSpec bool
411
412         // SkipNewSessionTicket causes the server to skip sending the
413         // NewSessionTicket message despite promising to in ServerHello.
414         SkipNewSessionTicket bool
415
416         // SendV2ClientHello causes the client to send a V2ClientHello
417         // instead of a normal ClientHello.
418         SendV2ClientHello bool
419
420         // SendFallbackSCSV causes the client to include
421         // TLS_FALLBACK_SCSV in the ClientHello.
422         SendFallbackSCSV bool
423
424         // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
425         // handshake record. Handshake messages will be split into multiple
426         // records at the specified size, except that the client_version will
427         // never be fragmented.
428         MaxHandshakeRecordLength int
429
430         // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
431         // the first 6 bytes of the ClientHello.
432         FragmentClientVersion bool
433
434         // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
435         // ClientKeyExchange with the specified version rather than the
436         // client_version when performing the RSA key exchange.
437         RsaClientKeyExchangeVersion uint16
438
439         // RenewTicketOnResume causes the server to renew the session ticket and
440         // send a NewSessionTicket message during an abbreviated handshake.
441         RenewTicketOnResume bool
442
443         // SendClientVersion, if non-zero, causes the client to send a different
444         // TLS version in the ClientHello than the maximum supported version.
445         SendClientVersion uint16
446
447         // SkipHelloVerifyRequest causes a DTLS server to skip the
448         // HelloVerifyRequest message.
449         SkipHelloVerifyRequest bool
450
451         // ExpectFalseStart causes the server to, on full handshakes,
452         // expect the peer to False Start; the server Finished message
453         // isn't sent until we receive an application data record
454         // from the peer.
455         ExpectFalseStart bool
456
457         // SSL3RSAKeyExchange causes the client to always send an RSA
458         // ClientKeyExchange message without the two-byte length
459         // prefix, as if it were SSL3.
460         SSL3RSAKeyExchange bool
461
462         // SkipCipherVersionCheck causes the server to negotiate
463         // TLS 1.2 ciphers in earlier versions of TLS.
464         SkipCipherVersionCheck bool
465
466         // ExpectServerName, if not empty, is the hostname the client
467         // must specify in the server_name extension.
468         ExpectServerName string
469
470         // SwapNPNAndALPN switches the relative order between NPN and
471         // ALPN on the server. This is to test that server preference
472         // of ALPN works regardless of their relative order.
473         SwapNPNAndALPN bool
474
475         // AllowSessionVersionMismatch causes the server to resume sessions
476         // regardless of the version associated with the session.
477         AllowSessionVersionMismatch bool
478
479         // CorruptTicket causes a client to corrupt a session ticket before
480         // sending it in a resume handshake.
481         CorruptTicket bool
482
483         // OversizedSessionId causes the session id that is sent with a ticket
484         // resumption attempt to be too large (33 bytes).
485         OversizedSessionId bool
486
487         // RequireExtendedMasterSecret, if true, requires that the peer support
488         // the extended master secret option.
489         RequireExtendedMasterSecret bool
490
491         // NoExtendedMasterSecret causes the client and server to behave is if
492         // they didn't support an extended master secret.
493         NoExtendedMasterSecret bool
494
495         // EmptyRenegotiationInfo causes the renegotiation extension to be
496         // empty in a renegotiation handshake.
497         EmptyRenegotiationInfo bool
498
499         // BadRenegotiationInfo causes the renegotiation extension value in a
500         // renegotiation handshake to be incorrect.
501         BadRenegotiationInfo bool
502 }
503
504 func (c *Config) serverInit() {
505         if c.SessionTicketsDisabled {
506                 return
507         }
508
509         // If the key has already been set then we have nothing to do.
510         for _, b := range c.SessionTicketKey {
511                 if b != 0 {
512                         return
513                 }
514         }
515
516         if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
517                 c.SessionTicketsDisabled = true
518         }
519 }
520
521 func (c *Config) rand() io.Reader {
522         r := c.Rand
523         if r == nil {
524                 return rand.Reader
525         }
526         return r
527 }
528
529 func (c *Config) time() time.Time {
530         t := c.Time
531         if t == nil {
532                 t = time.Now
533         }
534         return t()
535 }
536
537 func (c *Config) cipherSuites() []uint16 {
538         s := c.CipherSuites
539         if s == nil {
540                 s = defaultCipherSuites()
541         }
542         return s
543 }
544
545 func (c *Config) minVersion() uint16 {
546         if c == nil || c.MinVersion == 0 {
547                 return minVersion
548         }
549         return c.MinVersion
550 }
551
552 func (c *Config) maxVersion() uint16 {
553         if c == nil || c.MaxVersion == 0 {
554                 return maxVersion
555         }
556         return c.MaxVersion
557 }
558
559 var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
560
561 func (c *Config) curvePreferences() []CurveID {
562         if c == nil || len(c.CurvePreferences) == 0 {
563                 return defaultCurvePreferences
564         }
565         return c.CurvePreferences
566 }
567
568 // mutualVersion returns the protocol version to use given the advertised
569 // version of the peer.
570 func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
571         minVersion := c.minVersion()
572         maxVersion := c.maxVersion()
573
574         if vers < minVersion {
575                 return 0, false
576         }
577         if vers > maxVersion {
578                 vers = maxVersion
579         }
580         return vers, true
581 }
582
583 // getCertificateForName returns the best certificate for the given name,
584 // defaulting to the first element of c.Certificates if there are no good
585 // options.
586 func (c *Config) getCertificateForName(name string) *Certificate {
587         if len(c.Certificates) == 1 || c.NameToCertificate == nil {
588                 // There's only one choice, so no point doing any work.
589                 return &c.Certificates[0]
590         }
591
592         name = strings.ToLower(name)
593         for len(name) > 0 && name[len(name)-1] == '.' {
594                 name = name[:len(name)-1]
595         }
596
597         if cert, ok := c.NameToCertificate[name]; ok {
598                 return cert
599         }
600
601         // try replacing labels in the name with wildcards until we get a
602         // match.
603         labels := strings.Split(name, ".")
604         for i := range labels {
605                 labels[i] = "*"
606                 candidate := strings.Join(labels, ".")
607                 if cert, ok := c.NameToCertificate[candidate]; ok {
608                         return cert
609                 }
610         }
611
612         // If nothing matches, return the first certificate.
613         return &c.Certificates[0]
614 }
615
616 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
617 // from the CommonName and SubjectAlternateName fields of each of the leaf
618 // certificates.
619 func (c *Config) BuildNameToCertificate() {
620         c.NameToCertificate = make(map[string]*Certificate)
621         for i := range c.Certificates {
622                 cert := &c.Certificates[i]
623                 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
624                 if err != nil {
625                         continue
626                 }
627                 if len(x509Cert.Subject.CommonName) > 0 {
628                         c.NameToCertificate[x509Cert.Subject.CommonName] = cert
629                 }
630                 for _, san := range x509Cert.DNSNames {
631                         c.NameToCertificate[san] = cert
632                 }
633         }
634 }
635
636 // A Certificate is a chain of one or more certificates, leaf first.
637 type Certificate struct {
638         Certificate [][]byte
639         PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
640         // OCSPStaple contains an optional OCSP response which will be served
641         // to clients that request it.
642         OCSPStaple []byte
643         // Leaf is the parsed form of the leaf certificate, which may be
644         // initialized using x509.ParseCertificate to reduce per-handshake
645         // processing for TLS clients doing client authentication. If nil, the
646         // leaf certificate will be parsed as needed.
647         Leaf *x509.Certificate
648 }
649
650 // A TLS record.
651 type record struct {
652         contentType  recordType
653         major, minor uint8
654         payload      []byte
655 }
656
657 type handshakeMessage interface {
658         marshal() []byte
659         unmarshal([]byte) bool
660 }
661
662 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
663 // caching strategy.
664 type lruSessionCache struct {
665         sync.Mutex
666
667         m        map[string]*list.Element
668         q        *list.List
669         capacity int
670 }
671
672 type lruSessionCacheEntry struct {
673         sessionKey string
674         state      *ClientSessionState
675 }
676
677 // NewLRUClientSessionCache returns a ClientSessionCache with the given
678 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
679 // is used instead.
680 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
681         const defaultSessionCacheCapacity = 64
682
683         if capacity < 1 {
684                 capacity = defaultSessionCacheCapacity
685         }
686         return &lruSessionCache{
687                 m:        make(map[string]*list.Element),
688                 q:        list.New(),
689                 capacity: capacity,
690         }
691 }
692
693 // Put adds the provided (sessionKey, cs) pair to the cache.
694 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
695         c.Lock()
696         defer c.Unlock()
697
698         if elem, ok := c.m[sessionKey]; ok {
699                 entry := elem.Value.(*lruSessionCacheEntry)
700                 entry.state = cs
701                 c.q.MoveToFront(elem)
702                 return
703         }
704
705         if c.q.Len() < c.capacity {
706                 entry := &lruSessionCacheEntry{sessionKey, cs}
707                 c.m[sessionKey] = c.q.PushFront(entry)
708                 return
709         }
710
711         elem := c.q.Back()
712         entry := elem.Value.(*lruSessionCacheEntry)
713         delete(c.m, entry.sessionKey)
714         entry.sessionKey = sessionKey
715         entry.state = cs
716         c.q.MoveToFront(elem)
717         c.m[sessionKey] = elem
718 }
719
720 // Get returns the ClientSessionState value associated with a given key. It
721 // returns (nil, false) if no value is found.
722 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
723         c.Lock()
724         defer c.Unlock()
725
726         if elem, ok := c.m[sessionKey]; ok {
727                 c.q.MoveToFront(elem)
728                 return elem.Value.(*lruSessionCacheEntry).state, true
729         }
730         return nil, false
731 }
732
733 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
734 type dsaSignature struct {
735         R, S *big.Int
736 }
737
738 type ecdsaSignature dsaSignature
739
740 var emptyConfig Config
741
742 func defaultConfig() *Config {
743         return &emptyConfig
744 }
745
746 var (
747         once                   sync.Once
748         varDefaultCipherSuites []uint16
749 )
750
751 func defaultCipherSuites() []uint16 {
752         once.Do(initDefaultCipherSuites)
753         return varDefaultCipherSuites
754 }
755
756 func initDefaultCipherSuites() {
757         for _, suite := range cipherSuites {
758                 if suite.flags&suitePSK == 0 {
759                         varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
760                 }
761         }
762 }
763
764 func unexpectedMessageError(wanted, got interface{}) error {
765         return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
766 }