如何在Go中从同一个侦听器提供SSH和HTTP(S)流量?

时间:2017-12-07 16:20:11

标签: http go ssh

我希望能够在同一端口上同时提供SSH和HTTPS连接。为此,我需要检查客户端发送的前几个字节,如果它以" SSH"开始,以一种方式提供连接,但如果它不是&#39则让Go HTTP服务器处理它。 ; t SSH。

但是http包只能用于net.Listener。一旦我接受来自侦听器的连接并检查第一个字节,将net.Conn发送到http就太晚了。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:4)

制作两个自定义侦听器,一个用于SSH连接,另一个用于所有其他连接。然后接受来自原始侦听器的连接,查看第一个字节,并将连接发送到适当的侦听器。

l := net.Listen("tcp", ":443")
sshListener, httpListener := MuxListener(l)
go sshServer.Serve(sshListener)
go httpServer.Serve(httpListener)

MuxListener:

// MuxListener takes a net.Listener and returns two listeners, one that
// accepts connections that start with "SSH", and another that accepts
// all others. This allows SSH and HTTPS to be served from the same port.
func MuxListener(l net.Listener) (ssh net.Listener, other net.Listener) {
    sshListener, otherListener := newListener(l), newListener(l)
    go func() {
        for {
            conn, err := l.Accept()
            if err != nil {
                log.Println("Error accepting conn:", err)
                continue
            }
            conn.SetReadDeadline(time.Now().Add(time.Second * 10))
            bconn := bufferedConn{conn, bufio.NewReaderSize(conn, 3)}
            p, err := bconn.Peek(3)
            conn.SetReadDeadline(time.Time{})
            if err != nil {
                log.Println("Error peeking into conn:", err)
                continue
            }
            prefix := string(p)
            selectedListener := otherListener
            if prefix == "SSH" {
                selectedListener = sshListener
            }
            if selectedListener.accept != nil {
                selectedListener.accept <- bconn
            }
        }
    }()
    return sshListener, otherListener
}

监听器:

type listener struct {
    accept chan net.Conn
    net.Listener
}

func newListener(l net.Listener) *listener {
    return &listener{
        make(chan net.Conn),
        l,
    }
}

func (l *listener) Accept() (net.Conn, error) {
    if l.accept == nil {
        return nil, errors.New("Listener closed")
    }
    return <-l.accept, nil
}

func (l *listener) Close() error {
    close(l.accept)
    l.accept = nil
    return nil
}

bufferedConn:

type bufferedConn struct {
    net.Conn
    r *bufio.Reader
}

func (b bufferedConn) Peek(n int) ([]byte, error) {
    return b.r.Peek(n)
}

func (b bufferedConn) Read(p []byte) (int, error) {
    return b.r.Read(p)
}