tapir/networks/tor/BaseOnionService.go

205 lines
6.5 KiB
Go
Raw Normal View History

2019-06-06 16:41:03 +00:00
package tor
import (
"crypto/rand"
"encoding/base64"
"errors"
"git.openprivacy.ca/cwtch.im/tapir"
"git.openprivacy.ca/cwtch.im/tapir/primitives"
"git.openprivacy.ca/openprivacy/connectivity"
"git.openprivacy.ca/openprivacy/log"
2019-06-06 16:41:03 +00:00
"golang.org/x/crypto/ed25519"
"sync"
"time"
)
// BaseOnionService is a concrete implementation of the service interface over Tor onion services.
type BaseOnionService struct {
connections sync.Map
acn connectivity.ACN
id *primitives.Identity
2019-06-06 16:41:03 +00:00
privateKey ed25519.PrivateKey
2019-07-17 18:44:08 +00:00
ls connectivity.ListenService
2020-03-21 19:42:46 +00:00
lock sync.Mutex
port int
2019-06-06 16:41:03 +00:00
}
2020-07-14 23:35:21 +00:00
// Metrics provides a report of useful information about the status of the service e.g. the number of active
// connections
2020-07-14 23:35:21 +00:00
func (s *BaseOnionService) Metrics() tapir.ServiceMetrics {
s.lock.Lock()
defer s.lock.Unlock()
count := 0
s.connections.Range(func(key, value interface{}) bool {
connection := value.(tapir.Connection)
if !connection.IsClosed() {
count++
}
return true
})
return tapir.ServiceMetrics{
ConnectionCount: count,
}
}
2019-06-06 16:41:03 +00:00
// Init initializes a BaseOnionService with a given private key and identity
// The private key is needed to initialize the Onion listen socket, ideally we could just pass an Identity in here.
func (s *BaseOnionService) Init(acn connectivity.ACN, sk ed25519.PrivateKey, id *primitives.Identity) {
2019-06-06 16:41:03 +00:00
// run add onion
// get listen context
s.acn = acn
s.id = id
s.privateKey = sk
s.port = 9878
}
// SetPort configures the port that the service uses.
func (s *BaseOnionService) SetPort(port int) {
s.port = port
2019-06-06 16:41:03 +00:00
}
// WaitForCapabilityOrClose blocks until the connection has the given capability or the underlying connection is closed
// (through error or user action)
2019-09-15 21:20:05 +00:00
func (s *BaseOnionService) WaitForCapabilityOrClose(cid string, name tapir.Capability) (tapir.Connection, error) {
2019-06-06 16:41:03 +00:00
conn, err := s.GetConnection(cid)
// If there is at least one active connection, then check the one that is returned and use it
for conn != nil {
if conn.HasCapability(name) {
return conn, nil
}
time.Sleep(time.Millisecond * 200)
// If we received both a Connection and an Error from GetConnection that means we have multiple connections
// If that was the case we refresh from the connection store as the likely case is one of them has been
// closed and the other one has the capabilities we need.
if err != nil {
conn, err = s.GetConnection(cid)
2019-06-06 16:41:03 +00:00
}
}
// There are no active connections with that hostname
2019-06-06 16:41:03 +00:00
return nil, err
}
// GetConnection returns a connection for a given hostname.
2019-08-07 20:08:02 +00:00
func (s *BaseOnionService) GetConnection(hostname string) (tapir.Connection, error) {
conn := make([]tapir.Connection, 0)
2019-07-16 20:22:30 +00:00
s.connections.Range(func(key, value interface{}) bool {
2019-08-07 20:08:02 +00:00
connection := value.(tapir.Connection)
if connection.Hostname() == hostname {
if !connection.IsClosed() {
conn = append(conn, connection)
return true
2019-07-16 20:22:30 +00:00
}
}
return true
})
if len(conn) == 0 {
2019-06-06 16:41:03 +00:00
return nil, errors.New("no connection found")
}
if len(conn) > 1 {
// If there are multiple connections we return the first one but also notify the user (this should be a
// temporary edgecase (see Connect))
return conn[0], errors.New("multiple connections found")
}
return conn[0], nil
2019-06-06 16:41:03 +00:00
}
// Connect initializes a new outbound connection to the given peer, using the defined Application
2019-07-30 23:43:07 +00:00
func (s *BaseOnionService) Connect(hostname string, app tapir.Application) (bool, error) {
2019-07-16 20:22:30 +00:00
_, err := s.GetConnection(hostname)
if err == nil {
// Note: This check is not 100% reliable. And we may end up with two connections between peers
// This can happen when a client connects to a server as the server is connecting to the client
// Because at the start of the connection the server cannot derive the true hostname of the client until it
// has auth'd
// We mitigate this by performing multiple checks when Connect'ing
2019-07-30 23:43:07 +00:00
return true, errors.New("already connected to " + hostname)
2019-07-16 20:22:30 +00:00
}
2019-06-06 16:41:03 +00:00
// connects to a remote server
// spins off to a connection struct
log.Debugf("Connecting to %v", hostname)
conn, _, err := s.acn.Open(hostname)
if err == nil {
connectionID := s.getNewConnectionID()
2019-07-16 20:22:30 +00:00
// Second check. If we didn't catch a double connection attempt before the Open we *should* catch it now because
// the auth protocol is quick and Open over onion connections can take some time.
// Again this isn't 100% reliable.
_, err := s.GetConnection(hostname)
if err == nil {
conn.Close()
2019-07-30 23:43:07 +00:00
return true, errors.New("already connected to " + hostname)
2019-07-16 20:22:30 +00:00
}
2019-06-06 16:41:03 +00:00
log.Debugf("Connected to %v [%v]", hostname, connectionID)
2020-07-14 21:59:08 +00:00
s.connections.Store(connectionID, tapir.NewConnection(s, s.id, hostname, true, conn, app.NewInstance()))
2019-07-30 23:43:07 +00:00
return true, nil
2019-06-06 16:41:03 +00:00
}
log.Debugf("Error connecting to %v %v", hostname, err)
2019-07-30 23:43:07 +00:00
return false, err
2019-06-06 16:41:03 +00:00
}
func (s *BaseOnionService) getNewConnectionID() string {
id := make([]byte, 10)
rand.Read(id)
connectionID := "connection-" + base64.StdEncoding.EncodeToString(id)
return connectionID
}
// Listen starts a blocking routine that waits for incoming connections and initializes connections with them based
// on the given Application.
func (s *BaseOnionService) Listen(app tapir.Application) error {
// accepts a new connection
// spins off to a connection struct
s.lock.Lock()
ls, err := s.acn.Listen(s.privateKey, s.port)
2019-07-17 18:44:08 +00:00
s.ls = ls
s.lock.Unlock()
2019-06-06 16:41:03 +00:00
if err == nil {
2021-06-09 17:36:34 +00:00
log.Debugf("Starting a service on %v ", s.ls.AddressFull())
2019-06-06 16:41:03 +00:00
for {
2019-07-17 18:44:08 +00:00
conn, err := s.ls.Accept()
2019-06-06 16:41:03 +00:00
if err == nil {
tempHostname := s.getNewConnectionID()
log.Debugf("Accepted connection from %v", tempHostname)
2020-07-14 21:59:08 +00:00
s.connections.Store(tempHostname, tapir.NewConnection(s, s.id, tempHostname, false, conn, app.NewInstance()))
2019-06-06 16:41:03 +00:00
} else {
log.Debugf("Error accepting connection %v", err)
return err
}
}
}
log.Debugf("Error listening to connection %v", err)
return err
}
2019-07-17 18:44:08 +00:00
2019-08-07 20:08:02 +00:00
// Shutdown closes the service and ensures that any connections are closed.
2019-07-17 18:44:08 +00:00
func (s *BaseOnionService) Shutdown() {
s.lock.Lock()
defer s.lock.Unlock()
if s.ls != nil {
s.ls.Close()
}
2019-07-17 19:00:27 +00:00
s.connections.Range(func(key, value interface{}) bool {
2019-08-07 20:08:02 +00:00
connection := value.(tapir.Connection)
2019-07-17 19:00:27 +00:00
connection.Close()
2019-07-23 18:41:49 +00:00
return true
2019-07-17 19:00:27 +00:00
})
2019-07-17 18:44:08 +00:00
}
2020-07-14 21:23:27 +00:00
// Broadcast sends a message to all connections who possess the given capability
func (s *BaseOnionService) Broadcast(message []byte, capability tapir.Capability) error {
s.lock.Lock()
defer s.lock.Unlock()
s.connections.Range(func(key, value interface{}) bool {
connection := value.(tapir.Connection)
if connection.HasCapability(capability) {
connection.Send(message)
}
return true
})
return nil
}