syncthing/session_listener.go

93 lines
1.9 KiB
Go
Raw Normal View History

2015-06-24 11:39:46 +00:00
// Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
package main
import (
"log"
"net"
"time"
2015-06-28 00:52:01 +00:00
"github.com/syncthing/relaysrv/protocol"
2015-06-24 11:39:46 +00:00
)
func sessionListener(addr string) {
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalln(err)
}
for {
conn, err := listener.Accept()
if err != nil {
if debug {
log.Println(err)
}
continue
}
2015-07-20 09:38:00 +00:00
setTCPOptions(conn)
2015-06-24 11:39:46 +00:00
if debug {
log.Println("Session listener accepted connection from", conn.RemoteAddr())
}
go sessionConnectionHandler(conn)
}
}
func sessionConnectionHandler(conn net.Conn) {
2015-07-20 09:38:00 +00:00
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(messageTimeout)); err != nil {
if debug {
log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
}
return
}
2015-06-28 00:52:01 +00:00
message, err := protocol.ReadMessage(conn)
2015-06-24 11:39:46 +00:00
if err != nil {
return
}
2015-06-28 00:52:01 +00:00
switch msg := message.(type) {
case protocol.JoinSessionRequest:
ses := findSession(string(msg.Key))
if debug {
log.Println(conn.RemoteAddr(), "session lookup", ses)
}
if ses == nil {
protocol.WriteMessage(conn, protocol.ResponseNotFound)
return
}
if !ses.AddConnection(conn) {
if debug {
log.Println("Failed to add", conn.RemoteAddr(), "to session", ses)
}
protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected)
return
}
2015-06-24 11:39:46 +00:00
2015-07-20 09:38:00 +00:00
if err := protocol.WriteMessage(conn, protocol.ResponseSuccess); err != nil {
2015-06-28 00:52:01 +00:00
if debug {
log.Println("Failed to send session join response to ", conn.RemoteAddr(), "for", ses)
}
return
}
2015-07-20 09:38:00 +00:00
if err := conn.SetDeadline(time.Time{}); err != nil {
if debug {
log.Println("Weird error setting deadline:", err, "on", conn.RemoteAddr())
}
return
}
2015-06-28 00:52:01 +00:00
default:
if debug {
log.Println("Unexpected message from", conn.RemoteAddr(), message)
}
protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage)
2015-06-24 11:39:46 +00:00
}
}