2015-10-11 04:33:07 +00:00
|
|
|
package goricochet
|
|
|
|
|
|
|
|
import (
|
2017-05-02 23:33:51 +00:00
|
|
|
"github.com/s-rah/go-ricochet/utils"
|
|
|
|
"github.com/s-rah/go-ricochet/connection"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"log"
|
2015-10-11 04:33:07 +00:00
|
|
|
)
|
2016-10-09 00:51:13 +00:00
|
|
|
// Open establishes a protocol session on an established net.Conn, and returns a new
|
|
|
|
// OpenConnection instance representing this connection. On error, the connection
|
|
|
|
// will be closed. This function blocks until version negotiation has completed.
|
|
|
|
// The application should call Process() on the returned OpenConnection to continue
|
|
|
|
// handling protocol messages.
|
2017-05-02 23:33:51 +00:00
|
|
|
func Open(remoteHostname string) (*connection.Connection, error) {
|
|
|
|
networkResolver := utils.NetworkResolver{}
|
|
|
|
log.Printf("Connecting...")
|
|
|
|
conn, remoteHostname, err := networkResolver.Resolve(remoteHostname)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Connected...negotiating version")
|
|
|
|
rc, err := negotiateVersion(conn, remoteHostname)
|
|
|
|
if err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
log.Printf("Connected...negotiated version")
|
|
|
|
return rc, nil
|
2015-10-12 23:03:48 +00:00
|
|
|
}
|
|
|
|
|
2016-10-02 22:39:08 +00:00
|
|
|
|
2017-05-02 23:33:51 +00:00
|
|
|
// negotiate version takes an open network connection and executes
|
|
|
|
// the ricochet version negotiation procedure.
|
|
|
|
func negotiateVersion(conn net.Conn, remoteHostname string) (*connection.Connection, error) {
|
|
|
|
versions := []byte{0x49, 0x4D, 0x01, 0x01}
|
|
|
|
if n, err := conn.Write(versions); err != nil || n < len(versions) {
|
|
|
|
return nil, utils.VersionNegotiationError
|
|
|
|
}
|
|
|
|
|
|
|
|
res := make([]byte, 1)
|
|
|
|
if _, err := io.ReadAtLeast(conn, res, len(res)); err != nil {
|
|
|
|
return nil, utils.VersionNegotiationError
|
|
|
|
}
|
|
|
|
|
|
|
|
if res[0] != 0x01 {
|
|
|
|
return nil, utils.VersionNegotiationFailed
|
|
|
|
}
|
|
|
|
rc := connection.NewOutboundConnection(conn,remoteHostname)
|
|
|
|
return rc, nil
|
2016-01-02 01:43:30 +00:00
|
|
|
}
|
|
|
|
|
2016-01-02 08:47:32 +00:00
|
|
|
|