2023-12-02 01:22:49 +00:00
|
|
|
package cnet
|
2023-11-28 03:23:28 +00:00
|
|
|
|
|
|
|
import (
|
2023-12-01 06:56:34 +00:00
|
|
|
"context"
|
2023-11-30 01:57:45 +00:00
|
|
|
"errors"
|
2023-11-28 03:23:28 +00:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
2023-11-30 01:57:45 +00:00
|
|
|
"reflect"
|
|
|
|
"strconv"
|
2023-11-28 03:23:28 +00:00
|
|
|
"sync"
|
|
|
|
|
2023-12-02 01:56:23 +00:00
|
|
|
"github.com/CPunch/gopenfusion/cnet/protocol"
|
2023-12-03 04:09:11 +00:00
|
|
|
"github.com/CPunch/gopenfusion/internal/config"
|
2023-11-28 03:23:28 +00:00
|
|
|
)
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
type PacketHandler func(peer *Peer, pkt protocol.Packet) error
|
2023-11-28 03:23:28 +00:00
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func StubbedPacket(_ *Peer, _ protocol.Packet) error {
|
2023-11-28 03:23:28 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type Service struct {
|
|
|
|
listener net.Listener
|
|
|
|
port int
|
|
|
|
Name string
|
2023-12-01 06:56:34 +00:00
|
|
|
ctx context.Context
|
2023-11-30 01:57:45 +00:00
|
|
|
started chan struct{}
|
2023-12-01 06:56:34 +00:00
|
|
|
stopped chan struct{}
|
2023-11-28 03:23:28 +00:00
|
|
|
packetHandlers map[uint32]PacketHandler
|
2023-12-02 01:22:49 +00:00
|
|
|
peers map[chan *PacketEvent]*Peer
|
2023-11-30 01:57:45 +00:00
|
|
|
stateLock sync.Mutex
|
2023-11-28 03:23:28 +00:00
|
|
|
|
|
|
|
// OnDisconnect is called when a peer disconnects from the service.
|
|
|
|
// uData is the stored value of the key/value pair in the peer map.
|
|
|
|
// It may not be set while the service is running. (eg. srvc.Start() has been called)
|
2023-12-02 01:22:49 +00:00
|
|
|
OnDisconnect func(peer *Peer)
|
2023-11-28 03:23:28 +00:00
|
|
|
|
|
|
|
// OnConnect is called when a peer connects to the service.
|
|
|
|
// return value is used as the value in the peer map.
|
|
|
|
// It may not be set while the service is running. (eg. srvc.Start() has been called)
|
2023-12-02 01:22:49 +00:00
|
|
|
OnConnect func(peer *Peer)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
func RandomPort() (int, error) {
|
|
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
2023-11-28 03:23:28 +00:00
|
|
|
if err != nil {
|
2023-11-30 01:57:45 +00:00
|
|
|
return 0, err
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
2023-11-30 01:57:45 +00:00
|
|
|
defer l.Close()
|
2023-11-28 03:23:28 +00:00
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
_, port, err := net.SplitHostPort(l.Addr().String())
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
return strconv.Atoi(port)
|
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
func NewService(ctx context.Context, name string, port int) *Service {
|
2023-11-30 01:57:45 +00:00
|
|
|
srvc := &Service{
|
|
|
|
port: port,
|
|
|
|
Name: name,
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.Reset(ctx)
|
2023-11-30 01:57:45 +00:00
|
|
|
return srvc
|
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) Reset(ctx context.Context) {
|
|
|
|
srvc.ctx = ctx
|
|
|
|
srvc.packetHandlers = make(map[uint32]PacketHandler)
|
2023-12-02 01:22:49 +00:00
|
|
|
srvc.peers = make(map[chan *PacketEvent]*Peer)
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.started = make(chan struct{})
|
|
|
|
srvc.stopped = make(chan struct{})
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// may not be called while the service is running (eg. srvc.Start() has been called)
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) AddPacketHandler(pktID uint32, handler PacketHandler) {
|
|
|
|
srvc.packetHandlers[pktID] = handler
|
|
|
|
}
|
|
|
|
|
|
|
|
type newPeerConnection struct {
|
2023-12-02 01:22:49 +00:00
|
|
|
peer *Peer
|
|
|
|
channel chan *PacketEvent
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) Start() error {
|
|
|
|
peerConnections := make(chan newPeerConnection)
|
|
|
|
defer close(peerConnections)
|
|
|
|
go srvc.handleEvents(peerConnections)
|
2023-11-28 03:23:28 +00:00
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
// open listener socket
|
|
|
|
var err error
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.listener, err = net.Listen("tcp", fmt.Sprintf(":%d", srvc.port))
|
2023-11-30 01:57:45 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-12-01 06:56:34 +00:00
|
|
|
defer srvc.listener.Close()
|
2023-11-30 01:57:45 +00:00
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
log.Printf("%s service hosted on %s:%d\n", srvc.Name, config.GetAnnounceIP(), srvc.port)
|
|
|
|
|
|
|
|
close(srvc.started) // signal that the service has started
|
2023-11-28 03:23:28 +00:00
|
|
|
for {
|
2023-12-01 06:56:34 +00:00
|
|
|
conn, err := srvc.listener.Accept()
|
2023-11-28 03:23:28 +00:00
|
|
|
if err != nil {
|
2023-11-30 01:57:45 +00:00
|
|
|
fmt.Println(err)
|
|
|
|
// we expect this to happen when the service is stopped
|
|
|
|
if errors.Is(err, net.ErrClosed) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
// create a new peer and pass it to the event loop
|
2023-12-02 01:22:49 +00:00
|
|
|
peer := NewPeer(srvc.ctx, conn)
|
|
|
|
eRecv := make(chan *PacketEvent)
|
2023-12-01 06:56:34 +00:00
|
|
|
peerConnections <- newPeerConnection{channel: eRecv, peer: peer}
|
2023-11-30 01:57:45 +00:00
|
|
|
go peer.Handler(eRecv)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) getPeer(channel chan *PacketEvent) *Peer {
|
2023-12-01 06:56:34 +00:00
|
|
|
return srvc.peers[channel]
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) setPeer(channel chan *PacketEvent, peer *Peer) {
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.peers[channel] = peer
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) removePeer(channel chan *PacketEvent) {
|
2023-12-01 06:56:34 +00:00
|
|
|
delete(srvc.peers, channel)
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
// returns a channel that is closed when the service has started.
|
|
|
|
// this is useful if you need to wait until after the service has started.
|
|
|
|
func (srvc *Service) Started() <-chan struct{} {
|
|
|
|
return srvc.started
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
// returns a channel that is closed when the service has stopped.
|
|
|
|
// this is useful if you need wait until after the service has stopped.
|
|
|
|
func (srvc *Service) Stopped() <-chan struct{} {
|
|
|
|
return srvc.stopped
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// calls f for each peer in the service passing the peer and the stored uData.
|
|
|
|
// if f returns false, the iteration is stopped.
|
|
|
|
// NOTE: the peer map is not locked while iterating, if you're calling this
|
|
|
|
// outside of the service's event loop, you'll need to lock the peer map yourself.
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) RangePeers(f func(peer *Peer) bool) {
|
2023-12-01 06:56:34 +00:00
|
|
|
for _, peer := range srvc.peers {
|
|
|
|
if !f(peer) {
|
2023-11-30 01:57:45 +00:00
|
|
|
break
|
|
|
|
}
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
// locks the peer map.
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) Lock() {
|
|
|
|
srvc.stateLock.Lock()
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// unlocks the peer map.
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) Unlock() {
|
|
|
|
srvc.stateLock.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srvc *Service) stop() {
|
|
|
|
// OnDisconnect handler might need to do something important
|
2023-12-02 01:22:49 +00:00
|
|
|
srvc.RangePeers(func(peer *Peer) bool {
|
2023-12-01 06:56:34 +00:00
|
|
|
peer.Kill()
|
|
|
|
if srvc.OnDisconnect != nil {
|
|
|
|
srvc.OnDisconnect(peer)
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
log.Printf("%s service stopped\n", srvc.Name)
|
|
|
|
close(srvc.stopped)
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// handleEvents is the main event loop for the service.
|
|
|
|
// it handles all events from the peers and calls the appropriate handlers.
|
2023-12-01 06:56:34 +00:00
|
|
|
func (srvc *Service) handleEvents(peerPipe <-chan newPeerConnection) {
|
|
|
|
defer srvc.stop()
|
|
|
|
|
2023-11-30 01:57:45 +00:00
|
|
|
poll := make([]reflect.SelectCase, 0, 4)
|
|
|
|
|
|
|
|
// add the stop channel and the peer connection channel to our poll queue
|
|
|
|
poll = append(poll, reflect.SelectCase{
|
|
|
|
Dir: reflect.SelectRecv,
|
2023-12-01 06:56:34 +00:00
|
|
|
Chan: reflect.ValueOf(srvc.ctx.Done()),
|
2023-11-30 01:57:45 +00:00
|
|
|
})
|
|
|
|
poll = append(poll, reflect.SelectCase{
|
|
|
|
Dir: reflect.SelectRecv,
|
2023-12-01 06:56:34 +00:00
|
|
|
Chan: reflect.ValueOf(peerPipe),
|
2023-11-30 01:57:45 +00:00
|
|
|
})
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
addPoll := func(channel chan *PacketEvent) {
|
2023-12-01 06:56:34 +00:00
|
|
|
poll = append(poll, reflect.SelectCase{
|
|
|
|
Dir: reflect.SelectRecv,
|
|
|
|
Chan: reflect.ValueOf(channel),
|
|
|
|
})
|
|
|
|
}
|
2023-11-30 01:57:45 +00:00
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
removePoll := func(index int) {
|
|
|
|
poll = append(poll[:index], poll[index+1:]...)
|
|
|
|
}
|
2023-11-30 01:57:45 +00:00
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
for {
|
|
|
|
chosen, value, recvOK := reflect.Select(poll)
|
|
|
|
switch chosen {
|
|
|
|
case 0: // cancel signal received, stop the service
|
2023-11-30 01:57:45 +00:00
|
|
|
return
|
2023-12-01 06:56:34 +00:00
|
|
|
case 1: // new peer, add it to our poll queue
|
|
|
|
if !recvOK {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
evnt := value.Interface().(newPeerConnection)
|
|
|
|
addPoll(evnt.channel)
|
|
|
|
srvc.connect(evnt.channel, evnt.peer)
|
|
|
|
default: // peer event
|
2023-12-02 01:22:49 +00:00
|
|
|
channel := poll[chosen].Chan.Interface().(chan *PacketEvent)
|
2023-12-01 06:56:34 +00:00
|
|
|
peer := srvc.getPeer(channel)
|
|
|
|
if peer == nil {
|
|
|
|
log.Printf("Unknown peer event: %v", value)
|
|
|
|
removePoll(chosen)
|
|
|
|
continue
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
evnt, ok := value.Interface().(*PacketEvent)
|
2023-12-01 06:56:34 +00:00
|
|
|
if !recvOK || !ok || evnt == nil {
|
|
|
|
// peer disconnected, remove it from our poll queue
|
|
|
|
removePoll(chosen)
|
|
|
|
srvc.disconnect(channel, peer)
|
|
|
|
continue
|
2023-11-30 01:57:45 +00:00
|
|
|
}
|
2023-12-01 06:56:34 +00:00
|
|
|
|
|
|
|
srvc.Lock()
|
|
|
|
if err := srvc.handlePacket(peer, evnt.PktID, protocol.NewPacket(evnt.Pkt)); err != nil {
|
|
|
|
log.Printf("Error handling packet: %v", err)
|
|
|
|
peer.Kill()
|
|
|
|
}
|
|
|
|
srvc.Unlock()
|
|
|
|
|
|
|
|
// the packet buffer is given to us by the event, so we'll need to make sure to return it to the pool
|
|
|
|
protocol.PutBuffer(evnt.Pkt)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) handlePacket(peer *Peer, typeID uint32, pkt protocol.Packet) error {
|
2023-12-01 06:56:34 +00:00
|
|
|
if hndlr, ok := srvc.packetHandlers[typeID]; ok {
|
2023-11-30 01:57:45 +00:00
|
|
|
// fmt.Printf("Handling packet %x\n", typeID)
|
2023-12-01 06:56:34 +00:00
|
|
|
if err := hndlr(peer, pkt); err != nil {
|
2023-11-28 03:23:28 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.Printf("[WARN] unknown packet ID: %x\n", typeID)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) disconnect(channel chan *PacketEvent, peer *Peer) {
|
2023-12-01 06:56:34 +00:00
|
|
|
log.Printf("Peer %p disconnected from %s\n", peer, srvc.Name)
|
|
|
|
if srvc.OnDisconnect != nil {
|
|
|
|
srvc.OnDisconnect(peer)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.removePeer(channel)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-02 01:22:49 +00:00
|
|
|
func (srvc *Service) connect(channel chan *PacketEvent, peer *Peer) {
|
2023-12-01 06:56:34 +00:00
|
|
|
log.Printf("New peer %p connected to %s\n", peer, srvc.Name)
|
|
|
|
if srvc.OnConnect != nil {
|
|
|
|
srvc.OnConnect(peer)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
2023-12-01 06:56:34 +00:00
|
|
|
srvc.setPeer(channel, peer)
|
2023-11-28 03:23:28 +00:00
|
|
|
}
|