2017-10-20 23:51:03 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
const MAX_NUMBER_THREADS = 8
|
2017-10-21 19:02:26 +03:00
|
|
|
const CONNECTION_TIMEOUT = time.Hour
|
2017-10-20 23:51:03 +03:00
|
|
|
|
|
|
|
type connectionMap struct {
|
|
|
|
receiver map[string]net.Conn
|
|
|
|
sender map[string]net.Conn
|
|
|
|
metadata map[string]string
|
|
|
|
potentialReceivers map[string]struct{}
|
|
|
|
sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *connectionMap) IsSenderConnected(key string) (found bool) {
|
|
|
|
c.RLock()
|
|
|
|
defer c.RUnlock()
|
|
|
|
_, found = c.sender[key]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *connectionMap) IsPotentialReceiverConnected(key string) (found bool) {
|
|
|
|
c.RLock()
|
|
|
|
defer c.RUnlock()
|
|
|
|
_, found = c.potentialReceivers[key]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
type Relay struct {
|
|
|
|
connections connectionMap
|
|
|
|
Debug bool
|
|
|
|
NumberOfConnections int
|
|
|
|
}
|
|
|
|
|
2018-02-09 05:17:25 +03:00
|
|
|
func NewRelay(config *AppConfig) *Relay {
|
2017-10-24 18:24:26 +03:00
|
|
|
r := &Relay{
|
2018-02-09 05:17:25 +03:00
|
|
|
Debug: config.Debug,
|
2017-10-24 18:24:26 +03:00
|
|
|
NumberOfConnections: MAX_NUMBER_THREADS,
|
|
|
|
}
|
|
|
|
|
2017-10-20 23:51:03 +03:00
|
|
|
log.SetFormatter(&log.TextFormatter{})
|
|
|
|
if r.Debug {
|
|
|
|
log.SetLevel(log.DebugLevel)
|
|
|
|
} else {
|
|
|
|
log.SetLevel(log.WarnLevel)
|
|
|
|
}
|
2017-10-24 18:24:26 +03:00
|
|
|
|
2017-10-20 23:51:03 +03:00
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) Run() {
|
|
|
|
r.connections = connectionMap{}
|
|
|
|
r.connections.Lock()
|
|
|
|
r.connections.receiver = make(map[string]net.Conn)
|
|
|
|
r.connections.sender = make(map[string]net.Conn)
|
|
|
|
r.connections.metadata = make(map[string]string)
|
|
|
|
r.connections.potentialReceivers = make(map[string]struct{})
|
|
|
|
r.connections.Unlock()
|
|
|
|
r.runServer()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) runServer() {
|
|
|
|
logger := log.WithFields(log.Fields{
|
|
|
|
"function": "main",
|
|
|
|
})
|
|
|
|
logger.Debug("Initializing")
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(r.NumberOfConnections)
|
|
|
|
for id := 0; id < r.NumberOfConnections; id++ {
|
|
|
|
go r.listenerThread(id, &wg)
|
|
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) listenerThread(id int, wg *sync.WaitGroup) {
|
|
|
|
logger := log.WithFields(log.Fields{
|
|
|
|
"function": "listenerThread:" + strconv.Itoa(27000+id),
|
|
|
|
})
|
|
|
|
|
|
|
|
defer wg.Done()
|
2017-10-24 18:24:26 +03:00
|
|
|
|
|
|
|
if err := r.listener(id); err != nil {
|
2017-10-20 23:51:03 +03:00
|
|
|
logger.Error(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) listener(id int) (err error) {
|
|
|
|
port := strconv.Itoa(27001 + id)
|
|
|
|
logger := log.WithFields(log.Fields{
|
2017-10-24 18:24:26 +03:00
|
|
|
"function": "listener:" + port,
|
2017-10-20 23:51:03 +03:00
|
|
|
})
|
|
|
|
server, err := net.Listen("tcp", "0.0.0.0:"+port)
|
|
|
|
if err != nil {
|
2017-10-24 18:24:26 +03:00
|
|
|
return errors.Wrap(err, "Error listening on :"+port)
|
2017-10-20 23:51:03 +03:00
|
|
|
}
|
|
|
|
defer server.Close()
|
|
|
|
logger.Debug("waiting for connections")
|
|
|
|
//Spawn a new goroutine whenever a client connects
|
|
|
|
for {
|
|
|
|
connection, err := server.Accept()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "problem accepting connection")
|
|
|
|
}
|
|
|
|
logger.Debugf("Client %s connected", connection.RemoteAddr().String())
|
|
|
|
go r.clientCommuncation(id, connection)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Relay) clientCommuncation(id int, connection net.Conn) {
|
2017-10-22 00:50:32 +03:00
|
|
|
logger := log.WithFields(log.Fields{
|
|
|
|
"id": id,
|
|
|
|
"ip": connection.RemoteAddr().String(),
|
|
|
|
})
|
2017-10-20 23:51:03 +03:00
|
|
|
|
2017-10-22 00:50:32 +03:00
|
|
|
sendMessage("who?", connection)
|
2017-10-20 23:51:03 +03:00
|
|
|
m := strings.Split(receiveMessage(connection), ".")
|
2017-10-22 00:32:00 +03:00
|
|
|
if len(m) < 3 {
|
2017-10-22 00:50:32 +03:00
|
|
|
logger.Debug("exiting, not enough information")
|
2017-10-22 00:29:35 +03:00
|
|
|
sendMessage("not enough information", connection)
|
|
|
|
return
|
|
|
|
}
|
2017-10-20 23:51:03 +03:00
|
|
|
connectionType, codePhrase, metaData := m[0], m[1], m[2]
|
|
|
|
key := codePhrase + "-" + strconv.Itoa(id)
|
|
|
|
|
2017-10-24 18:24:26 +03:00
|
|
|
switch connectionType {
|
|
|
|
case "s": // sender connection
|
2018-04-28 01:40:40 +03:00
|
|
|
if r.connections.IsSenderConnected(key) {
|
|
|
|
sendMessage("no", connection)
|
|
|
|
return
|
|
|
|
}
|
2017-10-22 00:50:32 +03:00
|
|
|
|
2017-10-20 23:51:03 +03:00
|
|
|
r.connections.Lock()
|
|
|
|
r.connections.metadata[key] = metaData
|
|
|
|
r.connections.sender[key] = connection
|
|
|
|
r.connections.Unlock()
|
|
|
|
// wait for receiver
|
|
|
|
receiversAddress := ""
|
2017-10-21 19:02:26 +03:00
|
|
|
isTimeout := time.Duration(0)
|
2017-10-20 23:51:03 +03:00
|
|
|
for {
|
2017-10-21 19:02:26 +03:00
|
|
|
if CONNECTION_TIMEOUT <= isTimeout {
|
|
|
|
sendMessage("timeout", connection)
|
|
|
|
break
|
|
|
|
}
|
2017-10-20 23:51:03 +03:00
|
|
|
r.connections.RLock()
|
|
|
|
if _, ok := r.connections.receiver[key]; ok {
|
|
|
|
receiversAddress = r.connections.receiver[key].RemoteAddr().String()
|
|
|
|
logger.Debug("got receiver")
|
|
|
|
r.connections.RUnlock()
|
|
|
|
break
|
|
|
|
}
|
|
|
|
r.connections.RUnlock()
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
2017-10-21 19:02:26 +03:00
|
|
|
isTimeout += 100 * time.Millisecond
|
2017-10-20 23:51:03 +03:00
|
|
|
}
|
|
|
|
logger.Debug("telling sender ok")
|
|
|
|
sendMessage(receiversAddress, connection)
|
|
|
|
logger.Debug("preparing pipe")
|
|
|
|
r.connections.Lock()
|
|
|
|
con1 := r.connections.sender[key]
|
|
|
|
con2 := r.connections.receiver[key]
|
|
|
|
r.connections.Unlock()
|
|
|
|
logger.Debug("piping connections")
|
|
|
|
Pipe(con1, con2)
|
|
|
|
logger.Debug("done piping")
|
|
|
|
r.connections.Lock()
|
2017-10-22 01:19:34 +03:00
|
|
|
// close connections
|
|
|
|
r.connections.sender[key].Close()
|
|
|
|
r.connections.receiver[key].Close()
|
|
|
|
// delete connctions
|
2017-10-20 23:51:03 +03:00
|
|
|
delete(r.connections.sender, key)
|
|
|
|
delete(r.connections.receiver, key)
|
|
|
|
delete(r.connections.metadata, key)
|
|
|
|
delete(r.connections.potentialReceivers, key)
|
|
|
|
r.connections.Unlock()
|
|
|
|
logger.Debug("deleted sender and receiver")
|
2017-10-24 18:24:26 +03:00
|
|
|
case "r", "c": // receiver
|
2017-10-20 23:51:03 +03:00
|
|
|
if r.connections.IsPotentialReceiverConnected(key) {
|
|
|
|
sendMessage("no", connection)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// add as a potential receiver
|
|
|
|
r.connections.Lock()
|
|
|
|
r.connections.potentialReceivers[key] = struct{}{}
|
|
|
|
r.connections.Unlock()
|
|
|
|
// wait for sender's metadata
|
|
|
|
sendersAddress := ""
|
|
|
|
for {
|
|
|
|
r.connections.RLock()
|
|
|
|
if _, ok := r.connections.metadata[key]; ok {
|
|
|
|
if _, ok2 := r.connections.sender[key]; ok2 {
|
|
|
|
sendersAddress = r.connections.sender[key].RemoteAddr().String()
|
|
|
|
logger.Debug("got sender meta data")
|
|
|
|
r.connections.RUnlock()
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
r.connections.RUnlock()
|
2017-10-21 01:18:06 +03:00
|
|
|
if connectionType == "c" {
|
|
|
|
sendMessage("0-0-0-0.0.0.0", connection)
|
2017-10-22 19:36:44 +03:00
|
|
|
// sender is not ready so delete connection
|
|
|
|
r.connections.Lock()
|
|
|
|
delete(r.connections.potentialReceivers, key)
|
|
|
|
r.connections.Unlock()
|
2017-10-21 01:18:06 +03:00
|
|
|
return
|
|
|
|
}
|
2017-10-20 23:51:03 +03:00
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
}
|
|
|
|
// send meta data
|
|
|
|
r.connections.RLock()
|
|
|
|
sendMessage(r.connections.metadata[key]+"-"+sendersAddress, connection)
|
|
|
|
r.connections.RUnlock()
|
|
|
|
// check for receiver's consent
|
|
|
|
consent := receiveMessage(connection)
|
|
|
|
logger.Debugf("consent: %s", consent)
|
|
|
|
if consent == "ok" {
|
|
|
|
logger.Debug("got consent")
|
|
|
|
r.connections.Lock()
|
|
|
|
r.connections.receiver[key] = connection
|
|
|
|
r.connections.Unlock()
|
|
|
|
}
|
2017-10-24 18:24:26 +03:00
|
|
|
default:
|
2017-10-22 00:50:32 +03:00
|
|
|
logger.Debugf("Got unknown protocol: '%s'", connectionType)
|
2017-10-20 23:51:03 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func sendMessage(message string, connection net.Conn) {
|
|
|
|
message = fillString(message, BUFFERSIZE)
|
|
|
|
connection.Write([]byte(message))
|
|
|
|
}
|
|
|
|
|
|
|
|
func receiveMessage(connection net.Conn) string {
|
2017-10-22 00:50:32 +03:00
|
|
|
logger := log.WithFields(log.Fields{
|
|
|
|
"func": "receiveMessage",
|
|
|
|
"ip": connection.RemoteAddr().String(),
|
|
|
|
})
|
2017-10-20 23:51:03 +03:00
|
|
|
messageByte := make([]byte, BUFFERSIZE)
|
2017-10-22 00:54:51 +03:00
|
|
|
err := connection.SetDeadline(time.Now().Add(60 * time.Minute))
|
2017-10-22 00:50:32 +03:00
|
|
|
if err != nil {
|
|
|
|
logger.Warn(err)
|
|
|
|
}
|
|
|
|
_, err = connection.Read(messageByte)
|
|
|
|
if err != nil {
|
|
|
|
logger.Warn("read deadline, no response")
|
|
|
|
return ""
|
|
|
|
}
|
2018-02-07 11:24:44 +03:00
|
|
|
return strings.TrimRight(string(messageByte), ":")
|
2017-10-20 23:51:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func fillString(retunString string, toLength int) string {
|
|
|
|
for {
|
|
|
|
lengthString := len(retunString)
|
|
|
|
if lengthString < toLength {
|
|
|
|
retunString = retunString + ":"
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
return retunString
|
|
|
|
}
|
|
|
|
|
|
|
|
// chanFromConn creates a channel from a Conn object, and sends everything it
|
|
|
|
// Read()s from the socket to the channel.
|
|
|
|
func chanFromConn(conn net.Conn) chan []byte {
|
|
|
|
c := make(chan []byte)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
b := make([]byte, BUFFERSIZE)
|
|
|
|
|
|
|
|
for {
|
|
|
|
n, err := conn.Read(b)
|
|
|
|
if n > 0 {
|
|
|
|
res := make([]byte, n)
|
|
|
|
// Copy the buffer so it doesn't get changed while read by the recipient.
|
|
|
|
copy(res, b[:n])
|
|
|
|
c <- res
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
c <- nil
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pipe creates a full-duplex pipe between the two sockets and transfers data from one to the other.
|
|
|
|
func Pipe(conn1 net.Conn, conn2 net.Conn) {
|
|
|
|
chan1 := chanFromConn(conn1)
|
|
|
|
chan2 := chanFromConn(conn2)
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case b1 := <-chan1:
|
|
|
|
if b1 == nil {
|
|
|
|
return
|
|
|
|
}
|
2017-10-24 13:07:03 +03:00
|
|
|
conn2.Write(b1)
|
|
|
|
|
2017-10-20 23:51:03 +03:00
|
|
|
case b2 := <-chan2:
|
|
|
|
if b2 == nil {
|
|
|
|
return
|
|
|
|
}
|
2017-10-24 13:07:03 +03:00
|
|
|
conn1.Write(b2)
|
2017-10-20 23:51:03 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|