syncthing/cmd/strelaysrv/listener.go

380 lines
9.1 KiB
Go
Raw Normal View History

2016-06-02 12:16:02 +00:00
// Copyright (C) 2015 Audrius Butkevicius and Contributors.
2015-06-24 11:39:46 +00:00
package main
import (
"crypto/tls"
"encoding/hex"
2015-06-24 11:39:46 +00:00
"log"
"net"
2015-06-28 00:52:01 +00:00
"sync"
2015-08-20 12:02:52 +00:00
"sync/atomic"
2015-06-24 11:39:46 +00:00
"time"
syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/relay/protocol"
refactor: use modern Protobuf encoder (#9817) At a high level, this is what I've done and why: - I'm moving the protobuf generation for the `protocol`, `discovery` and `db` packages to the modern alternatives, and using `buf` to generate because it's nice and simple. - After trying various approaches on how to integrate the new types with the existing code, I opted for splitting off our own data model types from the on-the-wire generated types. This means we can have a `FileInfo` type with nicer ergonomics and lots of methods, while the protobuf generated type stays clean and close to the wire protocol. It does mean copying between the two when required, which certainly adds a small amount of inefficiency. If we want to walk this back in the future and use the raw generated type throughout, that's possible, this however makes the refactor smaller (!) as it doesn't change everything about the type for everyone at the same time. - I have simply removed in cold blood a significant number of old database migrations. These depended on previous generations of generated messages of various kinds and were annoying to support in the new fashion. The oldest supported database version now is the one from Syncthing 1.9.0 from Sep 7, 2020. - I changed config structs to be regular manually defined structs. For the sake of discussion, some things I tried that turned out not to work... ### Embedding / wrapping Embedding the protobuf generated structs in our existing types as a data container and keeping our methods and stuff: ``` package protocol type FileInfo struct { *generated.FileInfo } ``` This generates a lot of problems because the internal shape of the generated struct is quite different (different names, different types, more pointers), because initializing it doesn't work like you'd expect (i.e., you end up with an embedded nil pointer and a panic), and because the types of child types don't get wrapped. That is, even if we also have a similar wrapper around a `Vector`, that's not the type you get when accessing `someFileInfo.Version`, you get the `*generated.Vector` that doesn't have methods, etc. ### Aliasing ``` package protocol type FileInfo = generated.FileInfo ``` Doesn't help because you can't attach methods to it, plus all the above. ### Generating the types into the target package like we do now and attaching methods This fails because of the different shape of the generated type (as in the embedding case above) plus the generated struct already has a bunch of methods that we can't necessarily override properly (like `String()` and a bunch of getters). ### Methods to functions I considered just moving all the methods we attach to functions in a specific package, so that for example ``` package protocol func (f FileInfo) Equal(other FileInfo) bool ``` would become ``` package fileinfos func Equal(a, b *generated.FileInfo) bool ``` and this would mostly work, but becomes quite verbose and cumbersome, and somewhat limits discoverability (you can't see what methods are available on the type in auto completions, etc). In the end I did this in some cases, like in the database layer where a lot of things like `func (fv *FileVersion) IsEmpty() bool` becomes `func fvIsEmpty(fv *generated.FileVersion)` because they were anyway just internal methods. Fixes #8247
2024-12-01 15:50:17 +00:00
"github.com/syncthing/syncthing/lib/tlsutil"
2015-06-24 11:39:46 +00:00
)
2015-06-28 00:52:01 +00:00
var (
2015-08-20 12:02:52 +00:00
outboxesMut = sync.RWMutex{}
outboxes = make(map[syncthingprotocol.DeviceID]chan interface{})
numConnections atomic.Int64
2015-06-28 00:52:01 +00:00
)
2015-06-24 11:39:46 +00:00
func listener(_, addr string, config *tls.Config, token string) {
2015-09-02 20:35:52 +00:00
tcpListener, err := net.Listen("tcp", addr)
2015-06-24 11:39:46 +00:00
if err != nil {
log.Fatalln(err)
}
listener := tlsutil.DowngradingListener{
Listener: tcpListener,
}
2015-09-02 20:35:52 +00:00
2015-06-24 11:39:46 +00:00
for {
2015-09-02 21:02:17 +00:00
conn, isTLS, err := listener.AcceptNoWrapTLS()
2015-06-24 11:39:46 +00:00
if err != nil {
// Conn may be nil if accept failed, or non-nil if the initial
// read to figure out if it's TLS or not failed. In the latter
// case, close the connection before moving on.
if conn != nil {
conn.Close()
}
2015-06-24 11:39:46 +00:00
if debug {
log.Println("Listener failed to accept:", err)
2015-06-24 11:39:46 +00:00
}
continue
}
2015-07-20 09:38:00 +00:00
setTCPOptions(conn)
2015-06-24 11:39:46 +00:00
if debug {
2015-09-02 20:35:52 +00:00
log.Println("Listener accepted connection from", conn.RemoteAddr(), "tls", isTLS)
}
if isTLS {
go protocolConnectionHandler(conn, config, token)
2015-09-02 20:35:52 +00:00
} else {
go sessionConnectionHandler(conn)
2015-06-24 11:39:46 +00:00
}
}
}
func protocolConnectionHandler(tcpConn net.Conn, config *tls.Config, token string) {
2015-06-24 11:39:46 +00:00
conn := tls.Server(tcpConn, config)
if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
if debug {
log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
}
conn.Close()
return
}
2015-06-28 00:52:01 +00:00
err := conn.Handshake()
2015-06-24 11:39:46 +00:00
if err != nil {
2015-06-28 00:52:01 +00:00
if debug {
log.Println("Protocol connection TLS handshake:", conn.RemoteAddr(), err)
}
2015-06-24 11:39:46 +00:00
conn.Close()
return
}
state := conn.ConnectionState()
if debug && state.NegotiatedProtocol != protocol.ProtocolName {
2015-06-24 11:39:46 +00:00
log.Println("Protocol negotiation error")
}
certs := state.PeerCertificates
if len(certs) != 1 {
2015-06-28 00:52:01 +00:00
if debug {
log.Println("Certificate list error")
}
2015-06-24 11:39:46 +00:00
conn.Close()
return
}
conn.SetDeadline(time.Time{})
2015-06-24 11:39:46 +00:00
2015-06-28 00:52:01 +00:00
id := syncthingprotocol.NewDeviceID(certs[0].Raw)
2015-06-24 11:39:46 +00:00
2015-06-28 00:52:01 +00:00
messages := make(chan interface{})
errors := make(chan error, 1)
outbox := make(chan interface{})
2015-06-24 11:39:46 +00:00
2015-07-20 09:38:00 +00:00
// Read messages from the connection and send them on the messages
// channel. When there is an error, send it on the error channel and
// return. Applies also when the connection gets closed, so the pattern
// below is to close the connection on error, then wait for the error
// signal from messageReader to exit.
go messageReader(conn, messages, errors)
2015-06-24 11:39:46 +00:00
pingTicker := time.NewTicker(pingInterval)
2017-08-30 16:46:50 +00:00
defer pingTicker.Stop()
2015-06-28 00:52:01 +00:00
timeoutTicker := time.NewTimer(networkTimeout)
2017-08-30 16:46:50 +00:00
defer timeoutTicker.Stop()
2015-06-24 11:39:46 +00:00
joined := false
for {
select {
2015-06-28 00:52:01 +00:00
case message := <-messages:
timeoutTicker.Reset(networkTimeout)
if debug {
log.Printf("Message %T from %s", message, id)
}
2015-07-20 09:38:00 +00:00
2015-06-28 00:52:01 +00:00
switch msg := message.(type) {
case protocol.JoinRelayRequest:
if token != "" && msg.Token != token {
if debug {
log.Printf("invalid token %s\n", msg.Token)
}
protocol.WriteMessage(conn, protocol.ResponseWrongToken)
conn.Close()
continue
}
if overLimit.Load() {
protocol.WriteMessage(conn, protocol.RelayFull{})
if debug {
log.Println("Refusing join request from", id, "due to being over limits")
}
conn.Close()
limitCheckTimer.Reset(time.Second)
continue
}
2015-06-28 00:52:01 +00:00
outboxesMut.RLock()
_, ok := outboxes[id]
outboxesMut.RUnlock()
if ok {
protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
if debug {
log.Println("Already have a peer with the same ID", id, conn.RemoteAddr())
}
2015-06-24 11:39:46 +00:00
conn.Close()
continue
}
2015-06-28 00:52:01 +00:00
outboxesMut.Lock()
outboxes[id] = outbox
outboxesMut.Unlock()
joined = true
protocol.WriteMessage(conn, protocol.ResponseSuccess)
2015-07-20 09:38:00 +00:00
2015-06-28 00:52:01 +00:00
case protocol.ConnectRequest:
requestedPeer, err := syncthingprotocol.DeviceIDFromBytes(msg.ID)
if err != nil {
if debug {
log.Println(id, "is looking for an invalid peer ID")
}
protocol.WriteMessage(conn, protocol.ResponseNotFound)
conn.Close()
continue
}
2015-06-28 00:52:01 +00:00
outboxesMut.RLock()
peerOutbox, ok := outboxes[requestedPeer]
outboxesMut.RUnlock()
2015-06-24 11:39:46 +00:00
if !ok {
if debug {
2015-08-20 12:02:52 +00:00
log.Println(id, "is looking for", requestedPeer, "which does not exist")
2015-06-24 11:39:46 +00:00
}
2015-06-28 00:52:01 +00:00
protocol.WriteMessage(conn, protocol.ResponseNotFound)
2015-06-24 11:39:46 +00:00
conn.Close()
continue
}
// requestedPeer is the server, id is the client
ses := newSession(requestedPeer, id, sessionLimiter, globalLimiter)
2015-06-24 11:39:46 +00:00
2015-06-28 00:52:01 +00:00
go ses.Serve()
clientInvitation := ses.GetClientInvitationMessage()
serverInvitation := ses.GetServerInvitationMessage()
2015-06-28 00:52:01 +00:00
if err := protocol.WriteMessage(conn, clientInvitation); err != nil {
if debug {
log.Printf("Error sending invitation from %s to client: %s", id, err)
}
2015-06-24 11:39:46 +00:00
conn.Close()
continue
}
select {
case peerOutbox <- serverInvitation:
if debug {
log.Println("Sent invitation from", id, "to", requestedPeer)
}
case <-time.After(time.Second):
if debug {
log.Println("Could not send invitation from", id, "to", requestedPeer, "as peer disconnected")
}
2015-06-24 11:39:46 +00:00
}
conn.Close()
2015-07-20 09:38:00 +00:00
2015-09-14 11:44:47 +00:00
case protocol.Ping:
if err := protocol.WriteMessage(conn, protocol.Pong{}); err != nil {
if debug {
log.Println("Error writing pong:", err)
}
conn.Close()
continue
}
2015-06-28 00:52:01 +00:00
case protocol.Pong:
2015-07-20 09:38:00 +00:00
// Nothing
2015-06-28 00:52:01 +00:00
default:
if debug {
log.Printf("Unknown message %s: %T", id, message)
}
protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
conn.Close()
}
2015-07-20 09:38:00 +00:00
2015-06-28 00:52:01 +00:00
case err := <-errors:
if debug {
log.Printf("Closing connection %s: %s", id, err)
2015-06-24 11:39:46 +00:00
}
2015-07-20 09:38:00 +00:00
// Potentially closing a second time.
2015-06-28 00:52:01 +00:00
conn.Close()
2015-07-20 09:38:00 +00:00
2015-07-17 21:04:02 +00:00
if joined {
// Only delete the outbox if the client is joined, as it might be
// a lookup request coming from the same client.
2015-07-17 21:04:02 +00:00
outboxesMut.Lock()
delete(outboxes, id)
outboxesMut.Unlock()
// Also, kill all sessions related to this node, as it probably
// went offline. This is for the other end to realize the client
// is no longer there faster. This also helps resolve
// 'already connected' errors when one of the sides is
// restarting, and connecting to the other peer before the other
// peer even realised that the node has gone away.
dropSessions(id)
2015-07-17 21:04:02 +00:00
}
2015-06-24 11:39:46 +00:00
return
2015-07-20 09:38:00 +00:00
2015-06-24 11:39:46 +00:00
case <-pingTicker.C:
if !joined {
2015-06-28 00:52:01 +00:00
if debug {
log.Println(id, "didn't join within", pingInterval)
}
2015-06-24 11:39:46 +00:00
conn.Close()
continue
}
2015-06-28 00:52:01 +00:00
if err := protocol.WriteMessage(conn, protocol.Ping{}); err != nil {
if debug {
log.Println(id, err)
}
2015-06-24 11:39:46 +00:00
conn.Close()
}
2015-07-20 09:38:00 +00:00
if overLimit.Load() && !hasSessions(id) {
if debug {
log.Println("Dropping", id, "as it has no sessions and we are over our limits")
}
protocol.WriteMessage(conn, protocol.RelayFull{})
conn.Close()
limitCheckTimer.Reset(time.Second)
}
2015-06-24 11:39:46 +00:00
case <-timeoutTicker.C:
2015-06-28 00:52:01 +00:00
// We should receive a error from the reader loop, which will cause
// us to quit this loop.
if debug {
log.Printf("%s timed out", id)
}
2015-06-24 11:39:46 +00:00
conn.Close()
2015-07-20 09:38:00 +00:00
2015-06-28 00:52:01 +00:00
case msg := <-outbox:
2015-06-24 11:39:46 +00:00
if debug {
2015-06-28 00:52:01 +00:00
log.Printf("Sending message %T to %s", msg, id)
2015-06-24 11:39:46 +00:00
}
2015-06-28 00:52:01 +00:00
if err := protocol.WriteMessage(conn, msg); err != nil {
if debug {
log.Println(id, err)
}
2015-06-24 11:39:46 +00:00
conn.Close()
}
}
}
}
2015-07-20 09:38:00 +00:00
2015-09-02 20:35:52 +00:00
func sessionConnectionHandler(conn net.Conn) {
if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
if debug {
log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
}
conn.Close()
2015-09-02 20:35:52 +00:00
return
}
message, err := protocol.ReadMessage(conn)
if err != nil {
return
}
switch msg := message.(type) {
case protocol.JoinSessionRequest:
ses := findSession(string(msg.Key))
if debug {
log.Println(conn.RemoteAddr(), "session lookup", ses, hex.EncodeToString(msg.Key)[:5])
2015-09-02 20:35:52 +00:00
}
if ses == nil {
protocol.WriteMessage(conn, protocol.ResponseNotFound)
conn.Close()
return
}
if !ses.AddConnection(conn) {
if debug {
log.Println("Failed to add", conn.RemoteAddr(), "to session", ses)
}
protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
conn.Close()
return
}
if err := protocol.WriteMessage(conn, protocol.ResponseSuccess); err != nil {
if debug {
log.Println("Failed to send session join response to ", conn.RemoteAddr(), "for", ses)
}
return
}
if err := conn.SetDeadline(time.Time{}); err != nil {
if debug {
log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
}
conn.Close()
return
}
default:
if debug {
log.Println("Unexpected message from", conn.RemoteAddr(), message)
}
protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
conn.Close()
}
}
2015-07-20 09:38:00 +00:00
func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
numConnections.Add(1)
defer numConnections.Add(-1)
2015-08-20 12:02:52 +00:00
2015-07-20 09:38:00 +00:00
for {
msg, err := protocol.ReadMessage(conn)
if err != nil {
errors <- err
return
}
messages <- msg
}
}