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.
22 type clientHandshakeState struct {
24 serverHello *serverHelloMsg
27 finishedHash finishedHash
29 session *ClientSessionState
32 func makeClientHello(config *Config) (*clientHelloMsg, error) {
33 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
34 return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
38 for _, proto := range config.NextProtos {
39 if l := len(proto); l == 0 || l > 255 {
40 return nil, errors.New("tls: invalid NextProtos value")
42 nextProtosLength += 1 + l
46 if nextProtosLength > 0xffff {
47 return nil, errors.New("tls: NextProtos values too large")
50 hello := &clientHelloMsg{
51 vers: config.maxVersion(),
52 compressionMethods: []uint8{compressionNone},
53 random: make([]byte, 32),
56 serverName: hostnameInSNI(config.ServerName),
57 supportedCurves: config.curvePreferences(),
58 supportedPoints: []uint8{pointFormatUncompressed},
59 nextProtoNeg: len(config.NextProtos) > 0,
60 secureRenegotiationSupported: true,
61 alpnProtocols: config.NextProtos,
63 possibleCipherSuites := config.cipherSuites()
64 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
67 for _, suiteId := range possibleCipherSuites {
68 for _, suite := range cipherSuites {
69 if suite.id != suiteId {
72 // Don't advertise TLS 1.2-only cipher suites unless
73 // we're attempting TLS 1.2.
74 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
77 hello.cipherSuites = append(hello.cipherSuites, suiteId)
78 continue NextCipherSuite
82 _, err := io.ReadFull(config.rand(), hello.random)
84 return nil, errors.New("tls: short read from Rand: " + err.Error())
87 if hello.vers >= VersionTLS12 {
88 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
90 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
91 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
97 // c.out.Mutex <= L; c.handshakeMutex <= L.
98 func (c *Conn) clientHandshake() error {
100 c.config = defaultConfig()
103 // This may be a renegotiation handshake, in which case some fields
107 hello, err := makeClientHello(c.config)
112 if c.handshakes > 0 {
113 hello.secureRenegotiation = c.clientFinished[:]
116 var session *ClientSessionState
118 sessionCache := c.config.ClientSessionCache
119 if c.config.SessionTicketsDisabled {
123 if sessionCache != nil {
124 hello.ticketSupported = true
127 // Session resumption is not allowed if renegotiating because
128 // renegotiation is primarily used to allow a client to send a client
129 // certificate, which would be skipped if session resumption occurred.
130 if sessionCache != nil && c.handshakes == 0 {
131 // Try to resume a previously negotiated TLS session, if
133 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
134 candidateSession, ok := sessionCache.Get(cacheKey)
136 // Check that the ciphersuite/version used for the
137 // previous session are still valid.
138 cipherSuiteOk := false
139 for _, id := range hello.cipherSuites {
140 if id == candidateSession.cipherSuite {
146 versOk := candidateSession.vers >= c.config.minVersion() &&
147 candidateSession.vers <= c.config.maxVersion()
148 if versOk && cipherSuiteOk {
149 session = candidateSession
155 hello.sessionTicket = session.sessionTicket
156 // A random session ID is used to detect when the
157 // server accepted the ticket and is resuming a session
159 hello.sessionId = make([]byte, 16)
160 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
161 return errors.New("tls: short read from Rand: " + err.Error())
165 hs := &clientHandshakeState{
171 if err = hs.handshake(); err != nil {
175 // If we had a successful handshake and hs.session is different from
176 // the one already cached - cache a new one
177 if sessionCache != nil && hs.session != nil && session != hs.session {
178 sessionCache.Put(cacheKey, hs.session)
184 // Does the handshake, either a full one or resumes old session.
185 // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
186 func (hs *clientHandshakeState) handshake() error {
190 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
194 msg, err := c.readHandshake()
200 if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
201 c.sendAlert(alertUnexpectedMessage)
202 return unexpectedMessageError(hs.serverHello, msg)
205 if err = hs.pickTLSVersion(); err != nil {
209 if err = hs.pickCipherSuite(); err != nil {
213 isResume, err := hs.processServerHello()
218 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
220 // No signatures of the handshake are needed in a resumption.
221 // Otherwise, in a full handshake, if we don't have any certificates
222 // configured then we will never send a CertificateVerify message and
223 // thus no signatures are needed in that case either.
224 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
225 hs.finishedHash.discardHandshakeBuffer()
228 hs.finishedHash.Write(hs.hello.marshal())
229 hs.finishedHash.Write(hs.serverHello.marshal())
233 if err := hs.establishKeys(); err != nil {
236 if err := hs.readSessionTicket(); err != nil {
239 if err := hs.readFinished(c.serverFinished[:]); err != nil {
242 c.clientFinishedIsFirst = false
243 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
246 if _, err := c.flush(); err != nil {
250 if err := hs.doFullHandshake(); err != nil {
253 if err := hs.establishKeys(); err != nil {
256 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
259 if _, err := c.flush(); err != nil {
262 c.clientFinishedIsFirst = true
263 if err := hs.readSessionTicket(); err != nil {
266 if err := hs.readFinished(c.serverFinished[:]); err != nil {
271 c.didResume = isResume
272 c.handshakeComplete = true
277 func (hs *clientHandshakeState) pickTLSVersion() error {
278 vers, ok := hs.c.config.mutualVersion(hs.serverHello.vers)
279 if !ok || vers < VersionTLS10 {
280 // TLS 1.0 is the minimum version supported as a client.
281 hs.c.sendAlert(alertProtocolVersion)
282 return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
291 func (hs *clientHandshakeState) pickCipherSuite() error {
292 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
293 hs.c.sendAlert(alertHandshakeFailure)
294 return errors.New("tls: server chose an unconfigured cipher suite")
297 hs.c.cipherSuite = hs.suite.id
301 func (hs *clientHandshakeState) doFullHandshake() error {
304 msg, err := c.readHandshake()
308 certMsg, ok := msg.(*certificateMsg)
309 if !ok || len(certMsg.certificates) == 0 {
310 c.sendAlert(alertUnexpectedMessage)
311 return unexpectedMessageError(certMsg, msg)
313 hs.finishedHash.Write(certMsg.marshal())
315 if c.handshakes == 0 {
316 // If this is the first handshake on a connection, process and
317 // (optionally) verify the server's certificates.
318 certs := make([]*x509.Certificate, len(certMsg.certificates))
319 for i, asn1Data := range certMsg.certificates {
320 cert, err := x509.ParseCertificate(asn1Data)
322 c.sendAlert(alertBadCertificate)
323 return errors.New("tls: failed to parse certificate from server: " + err.Error())
328 if !c.config.InsecureSkipVerify {
329 opts := x509.VerifyOptions{
330 IsBoring: isBoringCertificate,
332 Roots: c.config.RootCAs,
333 CurrentTime: c.config.time(),
334 DNSName: c.config.ServerName,
335 Intermediates: x509.NewCertPool(),
338 for i, cert := range certs {
342 opts.Intermediates.AddCert(cert)
344 c.verifiedChains, err = certs[0].Verify(opts)
346 c.sendAlert(alertBadCertificate)
351 if c.config.VerifyPeerCertificate != nil {
352 if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
353 c.sendAlert(alertBadCertificate)
358 switch certs[0].PublicKey.(type) {
359 case *rsa.PublicKey, *ecdsa.PublicKey:
362 c.sendAlert(alertUnsupportedCertificate)
363 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
366 c.peerCertificates = certs
368 // This is a renegotiation handshake. We require that the
369 // server's identity (i.e. leaf certificate) is unchanged and
370 // thus any previous trust decision is still valid.
372 // See https://mitls.org/pages/attacks/3SHAKE for the
373 // motivation behind this requirement.
374 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
375 c.sendAlert(alertBadCertificate)
376 return errors.New("tls: server's identity changed during renegotiation")
380 if hs.serverHello.ocspStapling {
381 msg, err = c.readHandshake()
385 cs, ok := msg.(*certificateStatusMsg)
387 c.sendAlert(alertUnexpectedMessage)
388 return unexpectedMessageError(cs, msg)
390 hs.finishedHash.Write(cs.marshal())
392 if cs.statusType == statusTypeOCSP {
393 c.ocspResponse = cs.response
397 msg, err = c.readHandshake()
402 keyAgreement := hs.suite.ka(c.vers)
404 skx, ok := msg.(*serverKeyExchangeMsg)
406 hs.finishedHash.Write(skx.marshal())
407 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
409 c.sendAlert(alertUnexpectedMessage)
413 msg, err = c.readHandshake()
419 var chainToSend *Certificate
420 var certRequested bool
421 certReq, ok := msg.(*certificateRequestMsg)
424 hs.finishedHash.Write(certReq.marshal())
426 if chainToSend, err = hs.getCertificate(certReq); err != nil {
427 c.sendAlert(alertInternalError)
431 msg, err = c.readHandshake()
437 shd, ok := msg.(*serverHelloDoneMsg)
439 c.sendAlert(alertUnexpectedMessage)
440 return unexpectedMessageError(shd, msg)
442 hs.finishedHash.Write(shd.marshal())
444 // If the server requested a certificate then we have to send a
445 // Certificate message, even if it's empty because we don't have a
446 // certificate to send.
448 certMsg = new(certificateMsg)
449 certMsg.certificates = chainToSend.Certificate
450 hs.finishedHash.Write(certMsg.marshal())
451 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
456 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
458 c.sendAlert(alertInternalError)
462 hs.finishedHash.Write(ckx.marshal())
463 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
468 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
469 certVerify := &certificateVerifyMsg{
470 hasSignatureAndHash: c.vers >= VersionTLS12,
473 key, ok := chainToSend.PrivateKey.(crypto.Signer)
475 c.sendAlert(alertInternalError)
476 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
479 var signatureType uint8
480 switch key.Public().(type) {
481 case *ecdsa.PublicKey:
482 signatureType = signatureECDSA
484 signatureType = signatureRSA
486 c.sendAlert(alertInternalError)
487 return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
490 // SignatureAndHashAlgorithm was introduced in TLS 1.2.
491 if certVerify.hasSignatureAndHash {
492 certVerify.signatureAlgorithm, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.supportedSignatureAlgorithms, signatureType)
494 c.sendAlert(alertInternalError)
498 digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(signatureType, certVerify.signatureAlgorithm, hs.masterSecret)
500 c.sendAlert(alertInternalError)
503 certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
505 c.sendAlert(alertInternalError)
509 hs.finishedHash.Write(certVerify.marshal())
510 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
515 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
516 if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
517 c.sendAlert(alertInternalError)
518 return errors.New("tls: failed to write to key log: " + err.Error())
521 hs.finishedHash.discardHandshakeBuffer()
526 func (hs *clientHandshakeState) establishKeys() error {
529 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
530 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
531 var clientCipher, serverCipher interface{}
532 var clientHash, serverHash macFunction
533 if hs.suite.cipher != nil {
534 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
535 clientHash = hs.suite.mac(c.vers, clientMAC)
536 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
537 serverHash = hs.suite.mac(c.vers, serverMAC)
539 clientCipher = hs.suite.aead(clientKey, clientIV)
540 serverCipher = hs.suite.aead(serverKey, serverIV)
543 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
544 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
548 func (hs *clientHandshakeState) serverResumedSession() bool {
549 // If the server responded with the same sessionId then it means the
550 // sessionTicket is being used to resume a TLS session.
551 return hs.session != nil && hs.hello.sessionId != nil &&
552 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
555 func (hs *clientHandshakeState) processServerHello() (bool, error) {
558 if hs.serverHello.compressionMethod != compressionNone {
559 c.sendAlert(alertUnexpectedMessage)
560 return false, errors.New("tls: server selected unsupported compression format")
563 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
564 c.secureRenegotiation = true
565 if len(hs.serverHello.secureRenegotiation) != 0 {
566 c.sendAlert(alertHandshakeFailure)
567 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
571 if c.handshakes > 0 && c.secureRenegotiation {
572 var expectedSecureRenegotiation [24]byte
573 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
574 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
575 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
576 c.sendAlert(alertHandshakeFailure)
577 return false, errors.New("tls: incorrect renegotiation extension contents")
581 clientDidNPN := hs.hello.nextProtoNeg
582 clientDidALPN := len(hs.hello.alpnProtocols) > 0
583 serverHasNPN := hs.serverHello.nextProtoNeg
584 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
586 if !clientDidNPN && serverHasNPN {
587 c.sendAlert(alertHandshakeFailure)
588 return false, errors.New("tls: server advertised unrequested NPN extension")
591 if !clientDidALPN && serverHasALPN {
592 c.sendAlert(alertHandshakeFailure)
593 return false, errors.New("tls: server advertised unrequested ALPN extension")
596 if serverHasNPN && serverHasALPN {
597 c.sendAlert(alertHandshakeFailure)
598 return false, errors.New("tls: server advertised both NPN and ALPN extensions")
602 c.clientProtocol = hs.serverHello.alpnProtocol
603 c.clientProtocolFallback = false
605 c.scts = hs.serverHello.scts
607 if !hs.serverResumedSession() {
611 if hs.session.vers != c.vers {
612 c.sendAlert(alertHandshakeFailure)
613 return false, errors.New("tls: server resumed a session with a different version")
616 if hs.session.cipherSuite != hs.suite.id {
617 c.sendAlert(alertHandshakeFailure)
618 return false, errors.New("tls: server resumed a session with a different cipher suite")
621 // Restore masterSecret and peerCerts from previous state
622 hs.masterSecret = hs.session.masterSecret
623 c.peerCertificates = hs.session.serverCertificates
624 c.verifiedChains = hs.session.verifiedChains
628 func (hs *clientHandshakeState) readFinished(out []byte) error {
631 c.readRecord(recordTypeChangeCipherSpec)
636 msg, err := c.readHandshake()
640 serverFinished, ok := msg.(*finishedMsg)
642 c.sendAlert(alertUnexpectedMessage)
643 return unexpectedMessageError(serverFinished, msg)
646 verify := hs.finishedHash.serverSum(hs.masterSecret)
647 if len(verify) != len(serverFinished.verifyData) ||
648 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
649 c.sendAlert(alertHandshakeFailure)
650 return errors.New("tls: server's Finished message was incorrect")
652 hs.finishedHash.Write(serverFinished.marshal())
657 func (hs *clientHandshakeState) readSessionTicket() error {
658 if !hs.serverHello.ticketSupported {
663 msg, err := c.readHandshake()
667 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
669 c.sendAlert(alertUnexpectedMessage)
670 return unexpectedMessageError(sessionTicketMsg, msg)
672 hs.finishedHash.Write(sessionTicketMsg.marshal())
674 hs.session = &ClientSessionState{
675 sessionTicket: sessionTicketMsg.ticket,
677 cipherSuite: hs.suite.id,
678 masterSecret: hs.masterSecret,
679 serverCertificates: c.peerCertificates,
680 verifiedChains: c.verifiedChains,
686 func (hs *clientHandshakeState) sendFinished(out []byte) error {
689 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
692 if hs.serverHello.nextProtoNeg {
693 nextProto := new(nextProtoMsg)
694 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
695 nextProto.proto = proto
696 c.clientProtocol = proto
697 c.clientProtocolFallback = fallback
699 hs.finishedHash.Write(nextProto.marshal())
700 if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
705 finished := new(finishedMsg)
706 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
707 hs.finishedHash.Write(finished.marshal())
708 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
711 copy(out, finished.verifyData)
715 // tls11SignatureSchemes contains the signature schemes that we synthesise for
716 // a TLS <= 1.1 connection, based on the supported certificate types.
717 var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
720 // tls11SignatureSchemesNumECDSA is the number of initial elements of
721 // tls11SignatureSchemes that use ECDSA.
722 tls11SignatureSchemesNumECDSA = 3
723 // tls11SignatureSchemesNumRSA is the number of trailing elements of
724 // tls11SignatureSchemes that use RSA.
725 tls11SignatureSchemesNumRSA = 4
728 func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
731 var rsaAvail, ecdsaAvail bool
732 for _, certType := range certReq.certificateTypes {
734 case certTypeRSASign:
736 case certTypeECDSASign:
741 if c.config.GetClientCertificate != nil {
742 var signatureSchemes []SignatureScheme
744 if !certReq.hasSignatureAndHash {
745 // Prior to TLS 1.2, the signature schemes were not
746 // included in the certificate request message. In this
747 // case we use a plausible list based on the acceptable
748 // certificate types.
749 signatureSchemes = tls11SignatureSchemes
751 signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
754 signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
757 signatureSchemes = certReq.supportedSignatureAlgorithms
760 return c.config.GetClientCertificate(&CertificateRequestInfo{
761 AcceptableCAs: certReq.certificateAuthorities,
762 SignatureSchemes: signatureSchemes,
766 // RFC 4346 on the certificateAuthorities field: A list of the
767 // distinguished names of acceptable certificate authorities.
768 // These distinguished names may specify a desired
769 // distinguished name for a root CA or for a subordinate CA;
770 // thus, this message can be used to describe both known roots
771 // and a desired authorization space. If the
772 // certificate_authorities list is empty then the client MAY
773 // send any certificate of the appropriate
774 // ClientCertificateType, unless there is some external
775 // arrangement to the contrary.
777 // We need to search our list of client certs for one
778 // where SignatureAlgorithm is acceptable to the server and the
779 // Issuer is in certReq.certificateAuthorities
781 for i, chain := range c.config.Certificates {
782 if !rsaAvail && !ecdsaAvail {
786 for j, cert := range chain.Certificate {
787 x509Cert := chain.Leaf
788 // parse the certificate if this isn't the leaf
789 // node, or if chain.Leaf was nil
790 if j != 0 || x509Cert == nil {
792 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
793 c.sendAlert(alertInternalError)
794 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
799 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
800 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
805 if len(certReq.certificateAuthorities) == 0 {
806 // they gave us an empty list, so just take the
807 // first cert from c.config.Certificates
811 for _, ca := range certReq.certificateAuthorities {
812 if bytes.Equal(x509Cert.RawIssuer, ca) {
819 // No acceptable certificate found. Don't send a certificate.
820 return new(Certificate), nil
823 // clientSessionCacheKey returns a key used to cache sessionTickets that could
824 // be used to resume previously negotiated TLS sessions with a server.
825 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
826 if len(config.ServerName) > 0 {
827 return config.ServerName
829 return serverAddr.String()
832 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
833 // given list of possible protocols and a list of the preference order. The
834 // first list must not be empty. It returns the resulting protocol and flag
835 // indicating if the fallback case was reached.
836 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
837 for _, s := range preferenceProtos {
838 for _, c := range protos {
845 return protos[0], true
848 // hostnameInSNI converts name into an approriate hostname for SNI.
849 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
850 // See https://tools.ietf.org/html/rfc6066#section-3.
851 func hostnameInSNI(name string) string {
853 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
854 host = host[1 : len(host)-1]
856 if i := strings.LastIndex(host, "%"); i > 0 {
859 if net.ParseIP(host) != nil {
862 for len(name) > 0 && name[len(name)-1] == '.' {
863 name = name[:len(name)-1]