Compare commits
43 Commits
v0.1.0
...
nmdc-log-s
| Author | SHA1 | Date | |
|---|---|---|---|
| 611a934a4e | |||
| 1a3617b960 | |||
| a37b1773d0 | |||
| 09301f138c | |||
| 8d7b0b46af | |||
| 73f6d66cbd | |||
| 019f67a7de | |||
| debc14cea3 | |||
| ba378a8245 | |||
| e3a92da5f6 | |||
| 99e4ebb842 | |||
| 4499c7306d | |||
| d391159abe | |||
| e111c99886 | |||
| 393f156b0e | |||
| 7cd49c2c8a | |||
| 163b6623f8 | |||
| 2f0ab758b8 | |||
| 3b71ea3ce3 | |||
| b0e1c3e5d8 | |||
| 3a67b02bd9 | |||
| 27c21572b3 | |||
| da92afa51e | |||
| ec0a781538 | |||
| 052c3e2cba | |||
| db0e1a5c2f | |||
| ead04a1d4d | |||
| f8ac216379 | |||
| 28ad3c8e6a | |||
| 820fa72b77 | |||
| f4b868b0c7 | |||
| 7a590755cf | |||
| 08d048a6d3 | |||
| a09bf67b8f | |||
| d6339667fe | |||
| c532e2fe4f | |||
| 433c1ddac9 | |||
| 83792a4241 | |||
| 2c34fe7fcb | |||
| 786e99d743 | |||
| 59ca9f8251 | |||
| 4fad66857a | |||
| 1cd8190a58 |
@@ -1,6 +1,14 @@
|
|||||||
mode:regex
|
mode:regex
|
||||||
|
|
||||||
|
# Compilation output
|
||||||
\.(?:exe|a)$
|
\.(?:exe|a)$
|
||||||
^pkg/
|
^pkg/
|
||||||
|
|
||||||
|
# Dependencies
|
||||||
^src/(?:github.com|gopkg.in|golang.org)/
|
^src/(?:github.com|gopkg.in|golang.org)/
|
||||||
|
|
||||||
|
# Scratch space
|
||||||
|
^src/nmdc/
|
||||||
|
|
||||||
|
# Binary release artefacts
|
||||||
|
/?__dist/
|
||||||
|
|||||||
6
.hgtags
Normal file
6
.hgtags
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
945ab4b16d05aa084f71bf5da9a3f687e0ec8bbd libnmdc-r1
|
||||||
|
02a360e95480b97ddad83add5db48b2766339a99 nmdc-log-service-1.0.0
|
||||||
|
137c1b65039e03c80379826a6efdfd808f6fbc8f libnmdc-r2
|
||||||
|
d8b64d5527c2a5e4d76872e5bc3d69f7646135c6 libnmdc-r3
|
||||||
|
fca41372e400853775b02e951f9db91d87f41adb nmdc-log-service-1.0.1
|
||||||
|
050b424a7c5d5a27c9323c8810f3afbead1f5b96 libnmdc-r4
|
||||||
29
src/libnmdc/__dist/README.txt
Normal file
29
src/libnmdc/__dist/README.txt
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
An NMDC client protocol library for Golang.
|
||||||
|
|
||||||
|
- Offers both channel-based and synchronous APIs.
|
||||||
|
- Includes a sample logging client using the channel-based API.
|
||||||
|
- This code hosting site isn't (yet) compatible with `go get`.
|
||||||
|
|
||||||
|
Written in golang
|
||||||
|
Tags: nmdc
|
||||||
|
|
||||||
|
=CHANGELOG=
|
||||||
|
|
||||||
|
2016-04-03 r4
|
||||||
|
- Feature: Add synchronous API
|
||||||
|
- Fix an issue with reading HubConnection's state parameter
|
||||||
|
- Fix an issue with buffered protocol commands
|
||||||
|
|
||||||
|
2016-04-03 r3
|
||||||
|
- Feature: Add `SkipVerifyTLS` option
|
||||||
|
- Fix an issue with calling `panic()` if connection failed
|
||||||
|
|
||||||
|
2016-04-02 r2
|
||||||
|
- Enhancement: Support NMDC-over-TLS (NMDCS)
|
||||||
|
- Fix an issue recieving private messages
|
||||||
|
- Fix an issue with calling `panic()` if connection failed
|
||||||
|
- Fix an issue parsing URIs without a specified port
|
||||||
|
- Move sample content into directory with excluded build
|
||||||
|
|
||||||
|
2016-02-12 r1
|
||||||
|
- Initial public release
|
||||||
@@ -2,17 +2,53 @@
|
|||||||
package libnmdc
|
package libnmdc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"net/url"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_CLIENT_TAG string = "libnmdc.go"
|
||||||
|
DEFAULT_HUB_NAME string = "(unknown)"
|
||||||
|
)
|
||||||
|
|
||||||
type ConnectionState int
|
type ConnectionState int
|
||||||
type HubAddress string
|
|
||||||
type HubEventType int
|
type HubEventType int
|
||||||
|
|
||||||
|
type HubAddress string
|
||||||
|
|
||||||
|
func (this *HubAddress) parse() url.URL {
|
||||||
|
parsed, err := url.Parse(strings.ToLower(string(*this)))
|
||||||
|
if err != nil || len(parsed.Host) == 0 {
|
||||||
|
parsed = &url.URL{
|
||||||
|
Scheme: "nmdc",
|
||||||
|
Host: string(*this),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add default port if not specified
|
||||||
|
if !strings.ContainsRune(parsed.Host, ':') {
|
||||||
|
parsed.Host = parsed.Host + ":411"
|
||||||
|
}
|
||||||
|
|
||||||
|
return *parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HubAddress) IsSecure() bool {
|
||||||
|
parsed := this.parse()
|
||||||
|
|
||||||
|
return parsed.Scheme == "nmdcs" || parsed.Scheme == "dchubs"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HubAddress) GetHostOnly() string {
|
||||||
|
return this.parse().Host
|
||||||
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CONNECTIONSTATE_DISCONNECTED = 1
|
CONNECTIONSTATE_DISCONNECTED = 1
|
||||||
CONNECTIONSTATE_CONNECTING = 2 // Handshake in progress
|
CONNECTIONSTATE_CONNECTING = 2 // Handshake in progress
|
||||||
@@ -35,18 +71,25 @@ const (
|
|||||||
var rx_protocolMessage *regexp.Regexp
|
var rx_protocolMessage *regexp.Regexp
|
||||||
var rx_publicChat *regexp.Regexp
|
var rx_publicChat *regexp.Regexp
|
||||||
var rx_incomingTo *regexp.Regexp
|
var rx_incomingTo *regexp.Regexp
|
||||||
|
var ErrNotConnected error = errors.New("Not connected")
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rx_protocolMessage = regexp.MustCompile("(?ms)^[^|]*|")
|
rx_protocolMessage = regexp.MustCompile("(?ms)^[^|]*\\|")
|
||||||
rx_publicChat = regexp.MustCompile("(?ms)^<([^>]*)> (.*)$")
|
rx_publicChat = regexp.MustCompile("(?ms)^<([^>]*)> (.*)$")
|
||||||
rx_incomingTo = regexp.MustCompile("(?ms)^([^ ]+) From: ([^ ]+) $<([^>]*)> (.*)$")
|
rx_incomingTo = regexp.MustCompile("(?ms)^([^ ]+) From: ([^ ]+) \\$<([^>]*)> (.*)")
|
||||||
}
|
}
|
||||||
|
|
||||||
type HubConnectionOptions struct {
|
type HubConnectionOptions struct {
|
||||||
Address HubAddress
|
Address HubAddress
|
||||||
|
SkipVerifyTLS bool // using a negative verb, because bools default to false
|
||||||
Self UserInfo
|
Self UserInfo
|
||||||
NickPassword string
|
NickPassword string
|
||||||
|
|
||||||
|
// Returning messages in async mode
|
||||||
NumEventsToBuffer uint
|
NumEventsToBuffer uint
|
||||||
|
|
||||||
|
// Returning messages in sync mode
|
||||||
|
OnEventSync func(HubEvent)
|
||||||
}
|
}
|
||||||
|
|
||||||
type HubConnection struct {
|
type HubConnection struct {
|
||||||
@@ -59,10 +102,12 @@ type HubConnection struct {
|
|||||||
Users map[string]UserInfo
|
Users map[string]UserInfo
|
||||||
|
|
||||||
// Streamed events
|
// Streamed events
|
||||||
|
processEvent func(HubEvent)
|
||||||
OnEvent chan HubEvent
|
OnEvent chan HubEvent
|
||||||
|
|
||||||
// Private state
|
// Private state
|
||||||
conn net.Conn
|
conn net.Conn // this is an interface
|
||||||
|
connValid bool
|
||||||
sentOurHello bool
|
sentOurHello bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,7 +159,7 @@ func (this *HubConnection) userJoined_NameOnly(nick string) {
|
|||||||
_, already_existed := this.Users[nick]
|
_, already_existed := this.Users[nick]
|
||||||
if !already_existed {
|
if !already_existed {
|
||||||
this.Users[nick] = *NewUserInfo(nick)
|
this.Users[nick] = *NewUserInfo(nick)
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_USER_JOINED, Nick: nick}
|
this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: nick})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,15 +167,19 @@ func (this *HubConnection) userJoined_Full(uinf *UserInfo) {
|
|||||||
_, already_existed := this.Users[uinf.Nick]
|
_, already_existed := this.Users[uinf.Nick]
|
||||||
if !already_existed {
|
if !already_existed {
|
||||||
this.Users[uinf.Nick] = *uinf
|
this.Users[uinf.Nick] = *uinf
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_USER_JOINED, Nick: uinf.Nick}
|
this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: uinf.Nick})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note that protocol messages are transmitted on the caller thread, not from
|
// Note that protocol messages are transmitted on the caller thread, not from
|
||||||
// any internal libnmdc thread.
|
// any internal libnmdc thread.
|
||||||
func (this *HubConnection) SayRaw(protocolCommand string) error {
|
func (this *HubConnection) SayRaw(protocolCommand string) error {
|
||||||
|
if this.connValid {
|
||||||
_, err := this.conn.Write([]byte(protocolCommand))
|
_, err := this.conn.Write([]byte(protocolCommand))
|
||||||
return err
|
return err
|
||||||
|
} else {
|
||||||
|
return ErrNotConnected
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLock(lock []byte) string {
|
func parseLock(lock []byte) string {
|
||||||
@@ -167,14 +216,14 @@ func (this *HubConnection) processProtocolMessage(message string) {
|
|||||||
// ```````````
|
// ```````````
|
||||||
if rx_publicChat.MatchString(message) {
|
if rx_publicChat.MatchString(message) {
|
||||||
pubchat_parts := rx_publicChat.FindStringSubmatch(message)
|
pubchat_parts := rx_publicChat.FindStringSubmatch(message)
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_PUBLIC, Nick: pubchat_parts[1], Message: NMDCUnescape(pubchat_parts[2])}
|
this.processEvent(HubEvent{EventType: EVENT_PUBLIC, Nick: pubchat_parts[1], Message: NMDCUnescape(pubchat_parts[2])})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// System messages
|
// System messages
|
||||||
// ```````````````
|
// ```````````````
|
||||||
if message[0] != '$' {
|
if message[0] != '$' {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_HUB, Nick: this.HubName, Message: NMDCUnescape(message)}
|
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_HUB, Nick: this.HubName, Message: NMDCUnescape(message)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,27 +253,27 @@ func (this *HubConnection) processProtocolMessage(message string) {
|
|||||||
|
|
||||||
case "$HubName":
|
case "$HubName":
|
||||||
this.HubName = commandParts[1]
|
this.HubName = commandParts[1]
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_HUBNAME_CHANGED, Nick: commandParts[1]}
|
this.processEvent(HubEvent{EventType: EVENT_HUBNAME_CHANGED, Nick: commandParts[1]})
|
||||||
|
|
||||||
case "$ValidateDenide": // sic
|
case "$ValidateDenide": // sic
|
||||||
if len(this.Hco.NickPassword) > 0 {
|
if len(this.Hco.NickPassword) > 0 {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."}
|
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."})
|
||||||
} else {
|
} else {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Nick already in use."}
|
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Nick already in use."})
|
||||||
}
|
}
|
||||||
|
|
||||||
case "$HubIsFull":
|
case "$HubIsFull":
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Hub is full."}
|
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Hub is full."})
|
||||||
|
|
||||||
case "$BadPass":
|
case "$BadPass":
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."}
|
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."})
|
||||||
|
|
||||||
case "$GetPass":
|
case "$GetPass":
|
||||||
this.SayRaw("$MyPass " + NMDCEscape(this.Hco.NickPassword) + "|")
|
this.SayRaw("$MyPass " + NMDCEscape(this.Hco.NickPassword) + "|")
|
||||||
|
|
||||||
case "$Quit":
|
case "$Quit":
|
||||||
delete(this.Users, commandParts[1])
|
delete(this.Users, commandParts[1])
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_USER_PART, Nick: commandParts[1]}
|
this.processEvent(HubEvent{EventType: EVENT_USER_PART, Nick: commandParts[1]})
|
||||||
|
|
||||||
case "$MyINFO":
|
case "$MyINFO":
|
||||||
u := UserInfo{}
|
u := UserInfo{}
|
||||||
@@ -232,7 +281,7 @@ func (this *HubConnection) processProtocolMessage(message string) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
this.userJoined_Full(&u)
|
this.userJoined_Full(&u)
|
||||||
} else {
|
} else {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: err.Error()}
|
this.processEvent(HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: err.Error()})
|
||||||
}
|
}
|
||||||
|
|
||||||
case "$NickList":
|
case "$NickList":
|
||||||
@@ -243,25 +292,30 @@ func (this *HubConnection) processProtocolMessage(message string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case "$To":
|
case "$To:":
|
||||||
|
valid := false
|
||||||
if rx_incomingTo.MatchString(commandParts[1]) {
|
if rx_incomingTo.MatchString(commandParts[1]) {
|
||||||
txparts := rx_incomingTo.FindStringSubmatch(commandParts[1])
|
txparts := rx_incomingTo.FindStringSubmatch(commandParts[1])
|
||||||
if txparts[0] == this.Hco.Self.Nick && txparts[1] == txparts[2] {
|
if txparts[1] == this.Hco.Self.Nick && txparts[2] == txparts[3] {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_PRIVATE, Nick: txparts[1], Message: txparts[3]}
|
this.processEvent(HubEvent{EventType: EVENT_PRIVATE, Nick: txparts[2], Message: txparts[4]})
|
||||||
break
|
valid = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: "Malformed private message '" + commandParts[1] + "'"}
|
|
||||||
|
if !valid {
|
||||||
|
this.processEvent(HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: "Malformed private message '" + commandParts[1] + "'"})
|
||||||
|
}
|
||||||
|
|
||||||
case "$UserIP":
|
case "$UserIP":
|
||||||
// Final message in PtokaX connection handshake - trigger connection callback.
|
// Final message in PtokaX connection handshake - trigger connection callback.
|
||||||
// This might not be the case for other hubsofts, though
|
// This might not be the case for other hubsofts, though
|
||||||
if this.State != CONNECTIONSTATE_CONNECTED {
|
if this.State != CONNECTIONSTATE_CONNECTED {
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTED}
|
this.processEvent(HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTED})
|
||||||
this.State = CONNECTIONSTATE_CONNECTED
|
this.State = CONNECTIONSTATE_CONNECTED
|
||||||
}
|
}
|
||||||
|
|
||||||
case "$UserCommand":
|
case "$UserCommand":
|
||||||
|
// $UserCommand 1 1 Group chat\New group chat$<%[mynick]> !groupchat_new||
|
||||||
// TODO
|
// TODO
|
||||||
|
|
||||||
case "$ForceMove":
|
case "$ForceMove":
|
||||||
@@ -276,38 +330,50 @@ func (this *HubConnection) processProtocolMessage(message string) {
|
|||||||
case "$ConnectToMe":
|
case "$ConnectToMe":
|
||||||
|
|
||||||
default:
|
default:
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: "Unhandled protocol command '" + commandParts[0] + "'"}
|
this.processEvent(HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: "Unhandled protocol command '" + commandParts[0] + "'"})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *HubConnection) worker() {
|
func (this *HubConnection) worker() {
|
||||||
var fullBuffer string
|
var fullBuffer string
|
||||||
|
var err error = nil
|
||||||
|
var nbytes int = 0
|
||||||
|
|
||||||
for {
|
for {
|
||||||
|
|
||||||
// If we're not connected, attempt reconnect
|
// If we're not connected, attempt reconnect
|
||||||
if this.conn == nil {
|
if this.conn == nil {
|
||||||
tmp, err := net.Dial("tcp", string(this.Hco.Address))
|
|
||||||
this.conn = tmp
|
fullBuffer = "" // clear
|
||||||
if err == nil {
|
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTING}
|
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
|
||||||
|
|
||||||
|
} else {
|
||||||
|
this.State = CONNECTIONSTATE_CONNECTING
|
||||||
|
this.connValid = true
|
||||||
|
this.processEvent(HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_CONNECTING})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read from socket into our local buffer (blocking)
|
// Read from socket into our local buffer (blocking)
|
||||||
readBuff := make([]byte, 4096)
|
if this.connValid {
|
||||||
nbytes, err := this.conn.Read(readBuff)
|
readBuff := make([]byte, 1024)
|
||||||
|
nbytes, err = this.conn.Read(readBuff)
|
||||||
if nbytes > 0 {
|
if nbytes > 0 {
|
||||||
fullBuffer += string(readBuff[0:nbytes])
|
fullBuffer += string(readBuff[0:nbytes])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Maybe we disconnected
|
|
||||||
if err != nil {
|
|
||||||
this.OnEvent <- HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_DISCONNECTED}
|
|
||||||
this.conn = nil
|
|
||||||
time.Sleep(30 * time.Second) // Wait before reconnect
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempt to parse a message block
|
// Attempt to parse a message block
|
||||||
@@ -317,38 +383,66 @@ func (this *HubConnection) worker() {
|
|||||||
}
|
}
|
||||||
protocolMessage := rx_protocolMessage.FindString(fullBuffer)
|
protocolMessage := rx_protocolMessage.FindString(fullBuffer)
|
||||||
if len(protocolMessage) > 0 {
|
if len(protocolMessage) > 0 {
|
||||||
this.processProtocolMessage(string(protocolMessage))
|
this.processProtocolMessage(protocolMessage[:len(protocolMessage)-1])
|
||||||
fullBuffer = fullBuffer[len(protocolMessage):]
|
fullBuffer = fullBuffer[len(protocolMessage):]
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.processEvent(HubEvent{EventType: EVENT_CONNECTION_STATE_CHANGED, StateChange: CONNECTIONSTATE_DISCONNECTED, Message: err.Error()})
|
||||||
|
|
||||||
|
time.Sleep(30 * time.Second) // Wait before reconnect
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HubConnectionOptions) prepareConnection() *HubConnection {
|
||||||
|
if this.Self.ClientTag == "" {
|
||||||
|
this.Self.ClientTag = DEFAULT_CLIENT_TAG
|
||||||
|
}
|
||||||
|
|
||||||
|
hc := HubConnection{
|
||||||
|
Hco: this,
|
||||||
|
HubName: DEFAULT_HUB_NAME,
|
||||||
|
State: CONNECTIONSTATE_DISCONNECTED,
|
||||||
|
Users: make(map[string]UserInfo),
|
||||||
|
}
|
||||||
|
|
||||||
|
return &hc
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connects to an NMDC server, and spawns a background goroutine to handle
|
// Connects to an NMDC server, and spawns a background goroutine to handle
|
||||||
// protocol messages. Client code should select on all the interface channels.
|
// protocol messages. Client code should select on all the interface channels.
|
||||||
func (this *HubConnectionOptions) Connect() *HubConnection {
|
func (this *HubConnectionOptions) Connect() *HubConnection {
|
||||||
|
|
||||||
if this.Self.ClientTag == "" {
|
|
||||||
this.Self.ClientTag = "libnmdc.go"
|
|
||||||
}
|
|
||||||
if this.NumEventsToBuffer < 1 {
|
if this.NumEventsToBuffer < 1 {
|
||||||
this.NumEventsToBuffer = 1
|
this.NumEventsToBuffer = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := HubConnection{
|
hc := this.prepareConnection()
|
||||||
Hco: this,
|
hc.OnEvent = make(chan HubEvent, this.NumEventsToBuffer)
|
||||||
HubName: "(unknown)",
|
hc.processEvent = func(ev HubEvent) {
|
||||||
State: CONNECTIONSTATE_DISCONNECTED,
|
hc.OnEvent <- ev
|
||||||
Users: make(map[string]UserInfo),
|
|
||||||
OnEvent: make(chan HubEvent, this.NumEventsToBuffer),
|
|
||||||
sentOurHello: false,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
go hc.worker()
|
go hc.worker()
|
||||||
|
return hc
|
||||||
return &hc
|
}
|
||||||
|
|
||||||
|
// Connects to an NMDC server, and blocks forever to handle protocol messages.
|
||||||
|
// Client code should supply an event handling function.
|
||||||
|
func (this *HubConnectionOptions) ConnectSync() {
|
||||||
|
hc := this.prepareConnection()
|
||||||
|
hc.worker()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
// nmdc project main.go
|
// +build ignore
|
||||||
|
|
||||||
|
// This sample file demonstrates use of the libnmdc.go library. It's excluded
|
||||||
|
// when building the library package, but you can run it via `go run libnmdc_sample.go`.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -9,7 +13,7 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
opts := libnmdc.HubConnectionOptions{
|
opts := libnmdc.HubConnectionOptions{
|
||||||
Address: "127.0.0.1:411",
|
Address: "127.0.0.1",
|
||||||
Self: libnmdc.UserInfo{Nick: "slowpoke9"},
|
Self: libnmdc.UserInfo{Nick: "slowpoke9"},
|
||||||
}
|
}
|
||||||
hub := opts.Connect()
|
hub := opts.Connect()
|
||||||
@@ -18,7 +22,7 @@ func main() {
|
|||||||
event := <-hub.OnEvent
|
event := <-hub.OnEvent
|
||||||
switch event.EventType {
|
switch event.EventType {
|
||||||
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
|
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
|
||||||
fmt.Printf("Connection -- %s\n", event.StateChange.Format())
|
fmt.Printf("Connection -- %s (%s)\n", event.StateChange.Format(), event.Message)
|
||||||
|
|
||||||
case libnmdc.EVENT_PUBLIC:
|
case libnmdc.EVENT_PUBLIC:
|
||||||
fmt.Printf("Message from '%s': '%s'\n", event.Nick, event.Message)
|
fmt.Printf("Message from '%s': '%s'\n", event.Nick, event.Message)
|
||||||
43
src/nmdc-log-service/__dist/README.txt
Normal file
43
src/nmdc-log-service/__dist/README.txt
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
A logging service for NMDC hubs.
|
||||||
|
|
||||||
|
It logs public chat messages to a file, categorised by months. Binaries are provided for Windows/Linux amd64/i386.
|
||||||
|
|
||||||
|
Written in golang
|
||||||
|
Tags: nmdc
|
||||||
|
|
||||||
|
=USAGE=
|
||||||
|
|
||||||
|
`$nmdc-log-service -Help
|
||||||
|
|
||||||
|
Usage of nmdc-log-service:
|
||||||
|
-Debug
|
||||||
|
Print additional information on stdout
|
||||||
|
-Dir string
|
||||||
|
Output directory (default ".")
|
||||||
|
-LogConnectionState
|
||||||
|
Include connection state changes in log (default true)
|
||||||
|
-Nick string
|
||||||
|
Nick (default "nmdc-log-service")
|
||||||
|
-PMResponse string
|
||||||
|
Message to respond with on PM (default "This is an automated service. For enquiries, please contact an administrator.")
|
||||||
|
-Password string
|
||||||
|
Registered nick password
|
||||||
|
-Server string
|
||||||
|
Addresses to connect to (comma-separated)
|
||||||
|
-VerifyTLS
|
||||||
|
Verify TLS certificates (default true)
|
||||||
|
`
|
||||||
|
|
||||||
|
=CHANGELOG=
|
||||||
|
|
||||||
|
2016-04-03 1.0.2
|
||||||
|
- Enhancement: Upgrade `libnmdc` from `r3` to `r4`
|
||||||
|
|
||||||
|
2016-04-03 1.0.1
|
||||||
|
- Enhancement: Add `-VerifyTLS` option
|
||||||
|
- Enhancement: Upgrade `libnmdc` from `r2` to `r3`
|
||||||
|
- Fix an issue writing log files on Linux
|
||||||
|
- Fix a cosmetic issue with error message formatting
|
||||||
|
|
||||||
|
2016-04-02 1.0.0
|
||||||
|
- Initial public release
|
||||||
49
src/nmdc-log-service/build.sh
Normal file
49
src/nmdc-log-service/build.sh
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
export GOPATH=$(
|
||||||
|
cd ../../
|
||||||
|
cygpath -w "$(pwd)"
|
||||||
|
)
|
||||||
|
|
||||||
|
main() {
|
||||||
|
|
||||||
|
local version=""
|
||||||
|
read -p "Enter version string (blank for timestamp)> " version
|
||||||
|
if [[ $version == "" ]] ; then
|
||||||
|
version=$(date +%s)
|
||||||
|
fi
|
||||||
|
echo "Using '${version}' as the version."
|
||||||
|
|
||||||
|
if [[ -f nmdc-log-service.exe ]] ; then
|
||||||
|
rm ./nmdc-log-service.exe
|
||||||
|
fi
|
||||||
|
if [[ -f nmdc-log-service ]] ; then
|
||||||
|
rm ./nmdc-log-service
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Building win64..."
|
||||||
|
GOARCH=amd64 GOOS=windows go build -a -ldflags -s -o nmdc-log-service.exe
|
||||||
|
7z a -mx9 nmdc-log-service-${version}-win64.7z nmdc-log-service.exe >/dev/null
|
||||||
|
rm ./nmdc-log-service.exe
|
||||||
|
|
||||||
|
echo "Building win32..."
|
||||||
|
GOARCH=386 GOOS=windows go build -a -ldflags -s -o nmdc-log-service.exe
|
||||||
|
7z a -mx9 nmdc-log-service-${version}-win32.7z nmdc-log-service.exe >/dev/null
|
||||||
|
rm ./nmdc-log-service.exe
|
||||||
|
|
||||||
|
echo "Building linux64..."
|
||||||
|
GOARCH=amd64 GOOS=linux go build -a -ldflags -s -o nmdc-log-service
|
||||||
|
XZ_OPT=-9 tar caf nmdc-log-service-${version}-linux64.tar.xz nmdc-log-service --owner=0 --group=0
|
||||||
|
rm ./nmdc-log-service
|
||||||
|
|
||||||
|
echo "Building linux32..."
|
||||||
|
GOARCH=386 GOOS=linux go build -a -ldflags -s -o nmdc-log-service
|
||||||
|
XZ_OPT=-9 tar caf nmdc-log-service-${version}-linux32.tar.xz nmdc-log-service --owner=0 --group=0
|
||||||
|
rm ./nmdc-log-service
|
||||||
|
|
||||||
|
echo "Build complete."
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
153
src/nmdc-log-service/main.go
Normal file
153
src/nmdc-log-service/main.go
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"libnmdc"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var BaseDir string = "."
|
||||||
|
var PMResponse string = ""
|
||||||
|
var LogConnectionState bool
|
||||||
|
var DebugMode bool
|
||||||
|
var VerifyTLS bool
|
||||||
|
var CharacterMatcher *regexp.Regexp
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
CharacterMatcher = regexp.MustCompile("[^a-zA-Z0-9]")
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDirectoryNameForHub(hub string) string {
|
||||||
|
return filepath.Join(BaseDir, CharacterMatcher.ReplaceAllString(hub, "_"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func LogMessage(hub, message string) {
|
||||||
|
|
||||||
|
instant := time.Now() // using system timezone
|
||||||
|
|
||||||
|
// Log file path
|
||||||
|
monthStamp := instant.Format("2006-01")
|
||||||
|
logFilePath := filepath.Join(GetDirectoryNameForHub(hub), monthStamp+".log")
|
||||||
|
|
||||||
|
// Produce a timestamp
|
||||||
|
timeStamp := instant.Format("2006-01-02 15:04:05")
|
||||||
|
|
||||||
|
fh, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Couldn't open file '%s': %s\n", logFilePath, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer fh.Close()
|
||||||
|
|
||||||
|
_, err = fh.WriteString("[" + timeStamp + "] " + message + "\n")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error writing to file '%s': %s\n", logFilePath, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HubWorker(addr, nick, password string) {
|
||||||
|
|
||||||
|
opts := libnmdc.HubConnectionOptions{
|
||||||
|
Address: libnmdc.HubAddress(addr),
|
||||||
|
SkipVerifyTLS: !VerifyTLS,
|
||||||
|
Self: libnmdc.UserInfo{Nick: nick},
|
||||||
|
NickPassword: password,
|
||||||
|
}
|
||||||
|
hub := opts.Connect()
|
||||||
|
|
||||||
|
for {
|
||||||
|
event := <-hub.OnEvent
|
||||||
|
|
||||||
|
if DebugMode {
|
||||||
|
fmt.Printf("DEBUG: %s %v\n", addr, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch event.EventType {
|
||||||
|
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
|
||||||
|
if LogConnectionState {
|
||||||
|
if len(event.Message) > 0 {
|
||||||
|
LogMessage(addr, "* "+event.StateChange.Format()+" ("+event.Message+")")
|
||||||
|
} else {
|
||||||
|
LogMessage(addr, "* "+event.StateChange.Format())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case libnmdc.EVENT_PUBLIC:
|
||||||
|
LogMessage(addr, "<"+event.Nick+"> "+event.Message)
|
||||||
|
|
||||||
|
case libnmdc.EVENT_PRIVATE:
|
||||||
|
fmt.Printf("Got PM %v\n", event)
|
||||||
|
hub.SayPrivate(event.Nick, PMResponse)
|
||||||
|
|
||||||
|
case libnmdc.EVENT_SYSTEM_MESSAGE_FROM_CONN, libnmdc.EVENT_SYSTEM_MESSAGE_FROM_HUB:
|
||||||
|
if strings.HasPrefix(event.Message, "* ") {
|
||||||
|
LogMessage(addr, event.Message)
|
||||||
|
} else {
|
||||||
|
LogMessage(addr, "* "+event.Message)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
|
||||||
|
// Parse arguments
|
||||||
|
hubs := flag.String("Server", "", "Addresses to connect to (comma-separated)")
|
||||||
|
nick := flag.String("Nick", "nmdc-log-service", "Nick")
|
||||||
|
password := flag.String("Password", "", "Registered nick password")
|
||||||
|
flag.StringVar(&BaseDir, "Dir", ".", "Output directory")
|
||||||
|
flag.BoolVar(&LogConnectionState, "LogConnectionState", true, "Include connection state changes in log")
|
||||||
|
flag.StringVar(&PMResponse, "PMResponse", "This is an automated service. For enquiries, please contact an administrator.", "Message to respond with on PM")
|
||||||
|
flag.BoolVar(&DebugMode, "Debug", false, "Print additional information on stdout")
|
||||||
|
flag.BoolVar(&VerifyTLS, "VerifyTLS", true, "Verify TLS certificates")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
// Assert dir exists
|
||||||
|
dinfo, err := os.Stat(BaseDir)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "FATAL: %s\n", err.Error())
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if !dinfo.IsDir() {
|
||||||
|
fmt.Fprintf(os.Stderr, "FATAL: Path '%s' is not a directory\n", BaseDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !VerifyTLS {
|
||||||
|
fmt.Fprintf(os.Stderr, "WARNING: TLS certificates will not be verified!\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Launch loggers
|
||||||
|
all_hubs := strings.Split(*hubs, ",")
|
||||||
|
launch_ct := 0
|
||||||
|
for _, hubaddr := range all_hubs {
|
||||||
|
if len(hubaddr) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assert target directory exists
|
||||||
|
os.MkdirAll(GetDirectoryNameForHub(hubaddr), 0755)
|
||||||
|
|
||||||
|
// Launch logger
|
||||||
|
go HubWorker(hubaddr, *nick, *password)
|
||||||
|
|
||||||
|
launch_ct++
|
||||||
|
}
|
||||||
|
|
||||||
|
if launch_ct == 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "FATAL: No hubs specified")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait forever
|
||||||
|
var forever chan bool = nil
|
||||||
|
select {
|
||||||
|
case <-forever:
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user