func (t *Terminal) listen(requests <-chan *ssh.Request, ready chan<- struct{}) {
	hasShell := false
	for req := range requests {
		var width, height int
		var ok bool
		switch req.Type {
		case "shell":
			if !hasShell {
				ok = true
				hasShell = true
				close(ready)
			}
		case "pty-req":
			var term string
			term, width, height, ok = parsePtyRequest(req.Payload)
			if ok {
				err := t.SetSize(width, height)
				ok = err == nil
				t.mu.Lock()
				t.term = term
				t.mu.Unlock()
			}
		case "window-change":
			width, height, ok = parseWinchRequest(req.Payload)
			if ok {
				err := t.SetSize(width, height)
				ok = err == nil
			}
		case "env":
			var v EnvVar
			if err := ssh.Unmarshal(req.Payload, &v); err == nil {
				t.mu.Lock()
				t.env = append(t.env, v)
				t.mu.Unlock()
				ok = true
			}
		}
		if req.WantReply {
			req.Reply(ok, nil)
		}
	}
}
listen negotiates the terminal type and state
ready is closed when the terminal is ready.
package sshd
import (
	"errors"
	"fmt"
	"net"
	"sync"
	"time"
	"github.com/shazow/ssh-chat/sshd/terminal"
	"golang.org/x/crypto/ssh"
)
var keepaliveInterval = time.Second * 30
var keepaliveRequest = "keepalive@ssh-chat"
var ErrNoSessionChannel = errors.New("no session channel")
var ErrNotSessionChannel = errors.New("terminal requires session channel")
type Connection interface {
	PublicKey() ssh.PublicKey
	RemoteAddr() net.Addr
	Name() string
	ClientVersion() []byte
	Close() error
}
type sshConn struct {
	*ssh.ServerConn
}
func (c sshConn) PublicKey() ssh.PublicKey {
	if c.Permissions == nil {
		return nil
	}
	s, ok := c.Permissions.Extensions["pubkey"]
	if !ok {
		return nil
	}
	key, err := ssh.ParsePublicKey([]byte(s))
	if err != nil {
		return nil
	}
	return key
}
func (c sshConn) Name() string {
	return c.User()
}
type EnvVar struct {
	Key   string
	Value string
}
func (v EnvVar) String() string {
	return v.Key + "=" + v.Value
}
type Env []EnvVar
func (e Env) Get(key string) string {
	for i := len(e) - 1; i >= 0; i-- {
		if e[i].Key == key {
			return e[i].Value
		}
	}
	return ""
}
type Terminal struct {
	terminal.Terminal
	Conn    Connection
	Channel ssh.Channel
	done      chan struct{}
	closeOnce sync.Once
	mu   sync.Mutex
	env  []EnvVar
	term string
}
func NewTerminal(conn *ssh.ServerConn, ch ssh.NewChannel) (*Terminal, error) {
	if ch.ChannelType() != "session" {
		return nil, ErrNotSessionChannel
	}
	channel, requests, err := ch.Accept()
	if err != nil {
		return nil, err
	}
	term := Terminal{
		Terminal: *terminal.NewTerminal(channel, ""),
		Conn:     sshConn{conn},
		Channel:  channel,
		done: make(chan struct{}),
	}
	ready := make(chan struct{})
	go term.listen(requests, ready)
	go func() {
		ticker := time.Tick(keepaliveInterval)
		for {
			select {
			case <-ticker:
				_, err := channel.SendRequest(keepaliveRequest, true, nil)
				if err != nil {
					logger.Printf("[%s] Keepalive failed, closing terminal: %s", term.Conn.RemoteAddr(), err)
					term.Close()
					return
				}
			case <-term.done:
				return
			}
		}
	}()
	select {
	case <-ready:  
		return &term, nil
	case <-term.done:
		return nil, errors.New("terminal aborted")
	case <-time.NewTimer(time.Minute).C:
		return nil, errors.New("timed out starting terminal")
	}
}
func NewSession(conn *ssh.ServerConn, channels <-chan ssh.NewChannel) (*Terminal, error) {
	for ch := range channels {
		if t := ch.ChannelType(); t != "session" {
			logger.Printf("[%s] Ignored channel type: %s", conn.RemoteAddr(), t)
			ch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t))
			continue
		}
		return NewTerminal(conn, ch)
	}
	return nil, ErrNoSessionChannel
}
func (t *Terminal) Close() error {
	var err error
	t.closeOnce.Do(func() {
		close(t.done)
		if err := t.Channel.Close(); err != nil {
			logger.Printf("[%s] Failed to close terminal channel: %s", t.Conn.RemoteAddr(), err)
		}
		err = t.Conn.Close()
	})
	return err
}