libnmdc/HubConnection.go

243 lines
5.9 KiB
Go
Raw Normal View History

2016-05-04 07:03:36 +00:00
package libnmdc
import (
"crypto/tls"
"fmt"
2016-05-04 07:03:36 +00:00
"net"
"regexp"
"sync"
2016-05-04 07:03:36 +00:00
"time"
)
type HubConnection struct {
// Supplied parameters
Hco *HubConnectionOptions
// Current remote status
HubName string
State ConnectionState
usersMut sync.RWMutex
users map[string]UserInfo
userSIDs map[string]string
2016-05-04 07:03:36 +00:00
proto Protocol
// Event callback
2016-05-04 07:03:36 +00:00
processEvent func(HubEvent)
// Private state
conn net.Conn // this is an interface
connValid bool
autoReconnect bool
lastDataRecieved time.Time
2016-05-04 07:03:36 +00:00
}
2016-11-29 06:49:53 +00:00
// Thread-safe user accessor.
func (this *HubConnection) Users(cb func(*map[string]UserInfo) error) error {
this.usersMut.Lock()
defer this.usersMut.Unlock()
return cb(&this.users)
}
func (this *HubConnection) SayPublic(message string) error {
if this.proto == nil {
return ErrNotConnected
}
return this.proto.SayPublic(message)
2016-05-04 07:03:36 +00:00
}
func (this *HubConnection) SayPrivate(recipient string, message string) error {
if this.proto == nil {
return ErrNotConnected
}
return this.proto.SayPrivate(recipient, message)
2016-05-04 07:03:36 +00:00
}
func (this *HubConnection) SayInfo() error {
if this.proto == nil {
return ErrNotConnected
}
return this.proto.SayInfo()
}
func (this *HubConnection) UserExists(nick string) bool {
this.usersMut.RLock()
defer this.usersMut.RUnlock()
_, already_existed := this.users[nick]
return already_existed
}
func (this *HubConnection) UserCount() int {
this.usersMut.RLock()
defer this.usersMut.RUnlock()
return len(this.users)
}
2016-05-04 07:03:36 +00:00
func (this *HubConnection) userJoined_NameOnly(nick string) {
if !this.UserExists(nick) {
this.usersMut.Lock()
this.users[nick] = *NewUserInfo(nick)
this.usersMut.Unlock() // Don't lock over a processEvent boundary
2016-05-04 07:03:36 +00:00
this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: nick})
}
}
func (this *HubConnection) userJoined_Full(uinf *UserInfo) {
// n.b. also called when we get a replacement MyINFO for someone
this.usersMut.Lock()
_, userExisted := this.users[uinf.Nick] // don't use UserExists as it would deadlock the mutex
this.users[uinf.Nick] = *uinf
this.usersMut.Unlock() // Don't lock over a processEvent boundary
if !userExisted {
2016-05-04 07:03:36 +00:00
this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: uinf.Nick})
} else {
this.processEvent(HubEvent{EventType: EVENT_USER_UPDATED_INFO, Nick: uinf.Nick})
2016-05-04 07:03:36 +00:00
}
}
2016-11-29 06:49:53 +00:00
// SayRaw sends raw bytes over the TCP socket. Callers should add the protocol
2017-11-22 07:07:29 +00:00
// terminating character themselves (e.g. `|` for NMDC).
2016-05-04 07:03:36 +00:00
// Note that protocol messages are transmitted on the caller thread, not from
// any internal libnmdc thread.
func (this *HubConnection) SayRaw(protocolCommand string) error {
if !this.connValid {
2016-05-04 07:03:36 +00:00
return ErrNotConnected
}
_, err := this.conn.Write([]byte(protocolCommand))
return err
2016-05-04 07:03:36 +00:00
}
func (this *HubConnection) SayKeepalive() error {
if !this.connValid {
return ErrNotConnected
}
return this.SayRaw(this.proto.ProtoMessageSeparator())
}
func (this *HubConnection) Disconnect() {
this.autoReconnect = false
if this.conn != nil {
this.conn.Close()
}
// A CONNECTIONSTATE_DISCONNECTED message will be emitted by the worker.
}
2016-05-04 07:03:36 +00:00
func (this *HubConnection) worker() {
var fullBuffer string
var err error = nil
var nbytes int = 0
for {
// If we're not connected, attempt reconnect
if this.conn == nil {
fullBuffer = "" // clear
if this.Hco.Address.IsSecure() {
this.conn, err = tls.Dial("tcp", this.Hco.Address.GetHostOnly(), &tls.Config{
InsecureSkipVerify: this.Hco.SkipVerifyTLS,
})
} else {
this.conn, err = net.Dial("tcp", this.Hco.Address.GetHostOnly())
}
if err != nil {
this.State = CONNECTIONSTATE_DISCONNECTED
this.connValid = false
this.proto = nil
2016-05-04 07:03:36 +00:00
} else {
this.State = CONNECTIONSTATE_CONNECTING
this.connValid = true
this.processEvent(HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTING})
this.proto = this.Hco.Address.GetProtocol().Create(this)
2016-05-04 07:03:36 +00:00
}
}
// Read from socket into our local buffer (blocking)
if this.connValid {
2016-05-04 07:03:36 +00:00
readBuff := make([]byte, 1024)
this.conn.SetReadDeadline(time.Now().Add(SEND_KEEPALIVE_EVERY))
2016-05-04 07:03:36 +00:00
nbytes, err = this.conn.Read(readBuff)
2016-11-29 06:43:32 +00:00
if checkIsNetTimeout(err) {
2016-05-04 07:03:36 +00:00
// No data before read deadline
err = nil
if this.proto == nil {
// Autodetect: switch to ADC
this.proto = NewAdcProtocol(this)
} else {
// Normal
// Send KA packet
err = this.SayKeepalive()
}
}
2016-05-04 07:03:36 +00:00
if nbytes > 0 {
this.lastDataRecieved = time.Now()
2016-05-04 07:03:36 +00:00
fullBuffer += string(readBuff[0:nbytes])
}
}
if this.proto != nil {
rxSeparator := regexp.QuoteMeta(this.proto.ProtoMessageSeparator())
rxProtocolMessage := regexp.MustCompile(`(?ms)\A[^` + rxSeparator + `]*` + rxSeparator)
// Attempt to parse a message block
for len(fullBuffer) > 0 {
2017-11-22 07:07:29 +00:00
// FIXME nmdc
for len(fullBuffer) > 0 && fullBuffer[0] == '|' {
fullBuffer = fullBuffer[1:]
}
2017-11-22 07:07:29 +00:00
protocolMessage := rxProtocolMessage.FindString(fullBuffer)
if len(protocolMessage) > 0 {
this.proto.ProcessCommand(protocolMessage[:len(protocolMessage)-1])
fullBuffer = fullBuffer[len(protocolMessage):]
} else {
break
}
2016-05-04 07:03:36 +00:00
}
if err == nil && time.Now().Sub(this.lastDataRecieved) > RECONNECT_IF_NO_DATA_RECIEVED_IN {
err = fmt.Errorf("No packets recieved since %s, connection presumed lost", this.lastDataRecieved.Format(time.RFC3339))
}
}
2016-05-04 07:03:36 +00:00
// Maybe we disconnected
// Perform this check *last*, to ensure we've had a final shot at
// clearing out any queued messages
if err != nil {
this.State = CONNECTIONSTATE_DISCONNECTED
this.conn = nil
this.connValid = false
this.proto = nil
2016-05-04 07:03:36 +00:00
this.processEvent(HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_DISCONNECTED, Message: err.Error()})
if this.autoReconnect {
time.Sleep(AUTO_RECONNECT_AFTER) // Wait before reconnect
continue
} else {
return // leave the worker for good
}
2016-05-04 07:03:36 +00:00
}
}
}