ssh: fix deadlock during error path

Fixes golang/go#11882

If an error occurs during handshakeTransport.writePacket the lock may not be
released. Fix this by using defer rather than manually unlocking in all paths.

Change-Id: I0010284b4f7d99907c86b4c0e140ab6cf37b0441
Reviewed-on: https://go-review.googlesource.com/12888
Reviewed-by: Adam Langley <agl@golang.org>
diff --git a/ssh/handshake.go b/ssh/handshake.go
index a1e2c23..4acc1a0 100644
--- a/ssh/handshake.go
+++ b/ssh/handshake.go
@@ -253,6 +253,8 @@
 
 func (t *handshakeTransport) writePacket(p []byte) error {
 	t.mu.Lock()
+	defer t.mu.Unlock()
+
 	if t.writtenSinceKex > t.config.RekeyThreshold {
 		t.sendKexInitLocked()
 	}
@@ -264,17 +266,14 @@
 	}
 	t.writtenSinceKex += uint64(len(p))
 
-	var err error
 	switch p[0] {
 	case msgKexInit:
-		err = errors.New("ssh: only handshakeTransport can send kexInit")
+		return errors.New("ssh: only handshakeTransport can send kexInit")
 	case msgNewKeys:
-		err = errors.New("ssh: only handshakeTransport can send newKeys")
+		return errors.New("ssh: only handshakeTransport can send newKeys")
 	default:
-		err = t.conn.writePacket(p)
+		return t.conn.writePacket(p)
 	}
-	t.mu.Unlock()
-	return err
 }
 
 func (t *handshakeTransport) Close() error {