Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
f9a80d019b | |||
623ca6ffc1 | |||
568e9652da | |||
633a5dea16 | |||
0d38e8f3d9 | |||
ee1c72a7f5 | |||
5f71c07dee | |||
d91de1c3c0 | |||
3458ae3d6d | |||
0ae5183ad5 | |||
c1560dfd88 |
22
README.md
22
README.md
@ -20,7 +20,7 @@
|
||||
## Features
|
||||
|
||||
- Focuses on ~~simplicity~~ ʀᴀɪɴɪɴɢ ʜᴇʟʟғɪʀᴇ, yet tries to still be flexible.
|
||||
- Only requires [standard library packages](https://godoc.org/github.com/yunginnanet/girc-atomic?imports)
|
||||
- Only requires ~~[standard library packages](https://godoc.org/github.com/yunginnanet/girc-atomic?imports)~~ a total destruction of a 100 mile radius.
|
||||
- Event based triggering/responses ([example](https://godoc.org/github.com/yunginnanet/girc-atomic#ex-package--Commands), and [CTCP too](https://godoc.org/github.com/yunginnanet/girc-atomic#Commands.SendCTCP)!)
|
||||
- [Documentation](https://godoc.org/github.com/yunginnanet/girc-atomic) is _mostly_ complete.
|
||||
- Support for almost all of the [IRCv3 spec](http://ircv3.net/software/libraries.html).
|
||||
@ -37,25 +37,11 @@
|
||||
- Event/message rate limiting.
|
||||
- Channel, nick, and user validation methods ([IsValidChannel](https://godoc.org/github.com/yunginnanet/girc-atomic#IsValidChannel), [IsValidNick](https://godoc.org/github.com/yunginnanet/girc-atomic#IsValidNick), etc.)
|
||||
- CTCP handling and auto-responses ([CTCP](https://godoc.org/github.com/yunginnanet/girc-atomic#CTCP))
|
||||
- Utilizes the atomic/value package from stdlib to reduce backpressure in multi-client usage.
|
||||
- Additional CTCP handlers and customization.
|
||||
- Utilizes atomics and concurrent maps to reduce backpressure in multi-client usage. (fork)
|
||||
- Additional CTCP handlers and customization. (fork)
|
||||
- ??????
|
||||
- PROFIT!!!1!
|
||||
|
||||
## Examples
|
||||
|
||||
See [the examples](https://godoc.org/github.com/yunginnanet/girc-atomic#example-package--Bare)
|
||||
within the documentation for real-world usecases. Here are a few real-world
|
||||
usecases/examples/projects which utilize the real girc:
|
||||
|
||||
| Project | Description |
|
||||
| --- | --- |
|
||||
| [nagios-check-ircd](https://github.com/lrstanley/nagios-check-ircd) | Nagios utility for monitoring the health of an ircd |
|
||||
| [nagios-notify-irc](https://github.com/lrstanley/nagios-notify-irc) | Nagios utility for sending alerts to one or many channels/networks |
|
||||
| [matterbridge](https://github.com/42wim/matterbridge) | bridge between mattermost, IRC, slack, discord (and many others) with REST API |
|
||||
|
||||
Working on a project and want to add it to the list? Submit a pull request!
|
||||
|
||||
## Contributing
|
||||
|
||||
~~Please review the [CONTRIBUTING](CONTRIBUTING.md) doc for submitting issues/a guide
|
||||
@ -89,7 +75,7 @@ on submitting pull requests and helping out.~~
|
||||
|
||||
girc artwork licensed under [CC 3.0](http://creativecommons.org/licenses/by/3.0/) based on Renee French under Creative Commons 3.0 Attributions
|
||||
|
||||
later defiled by [some idiot](https://github.com/yunginnanet).
|
||||
...and then later defiled by [some idiot](https://github.com/yunginnanet).
|
||||
|
||||
## References
|
||||
|
||||
|
27
builtin.go
27
builtin.go
@ -18,9 +18,6 @@ import (
|
||||
func (c *Client) registerBuiltins() {
|
||||
c.debug.Print("registering built-in handlers")
|
||||
|
||||
c.Handlers.mu.Lock()
|
||||
defer c.Handlers.mu.Unlock()
|
||||
|
||||
// Built-in things that should always be supported.
|
||||
c.Handlers.register(true, true, RPL_WELCOME, HandlerFunc(handleConnect))
|
||||
c.Handlers.register(true, false, PING, HandlerFunc(handlePING))
|
||||
@ -129,6 +126,8 @@ func handleConnect(c *Client, e Event) {
|
||||
|
||||
// nickCollisionHandler helps prevent the client from having conflicting
|
||||
// nicknames with another bot, user, etc.
|
||||
//
|
||||
//goland:noinspection GoUnusedParameter
|
||||
func nickCollisionHandler(c *Client, e Event) {
|
||||
if c.Config.HandleNickCollide == nil {
|
||||
c.Cmd.Nick(c.GetNick() + "_")
|
||||
@ -146,6 +145,7 @@ func handlePING(c *Client, e Event) {
|
||||
c.Cmd.Pong(e.Last())
|
||||
}
|
||||
|
||||
//goland:noinspection GoUnusedParameter
|
||||
func handlePONG(c *Client, e Event) {
|
||||
c.conn.lastPong.Store(time.Now())
|
||||
}
|
||||
@ -177,7 +177,7 @@ func handleJOIN(c *Client, e Event) {
|
||||
|
||||
defer c.state.notify(c, UPDATE_STATE)
|
||||
|
||||
channel.addUser(user.Nick, user)
|
||||
channel.addUser(user.Nick.Load().(string), user)
|
||||
user.addChannel(channel.Name, channel)
|
||||
|
||||
// Assume extended-join (ircv3).
|
||||
@ -216,9 +216,6 @@ func handlePART(c *Client, e Event) {
|
||||
return
|
||||
}
|
||||
|
||||
c.state.Lock()
|
||||
defer c.state.Unlock()
|
||||
|
||||
c.debug.Println("handlePart")
|
||||
defer c.debug.Println("handlePart done for " + e.Params[0])
|
||||
|
||||
@ -235,9 +232,7 @@ func handlePART(c *Client, e Event) {
|
||||
|
||||
if chn := c.LookupChannel(channel); chn != nil {
|
||||
chn.UserList.Remove(e.Source.ID())
|
||||
c.state.Unlock()
|
||||
c.debug.Println(fmt.Sprintf("removed: %s, new count: %d", e.Source.ID(), chn.Len()))
|
||||
c.state.Lock()
|
||||
} else {
|
||||
c.debug.Println("failed to lookup channel: " + channel)
|
||||
}
|
||||
@ -248,7 +243,6 @@ func handlePART(c *Client, e Event) {
|
||||
}
|
||||
|
||||
c.state.deleteUser(channel, e.Source.ID())
|
||||
|
||||
}
|
||||
|
||||
// handleCREATIONTIME handles incoming TOPIC events and keeps channel tracking info
|
||||
@ -351,8 +345,17 @@ func handleWHO(c *Client, e Event) {
|
||||
}
|
||||
|
||||
user.Host = host
|
||||
user.Ident = ident
|
||||
user.Mask = user.Nick + "!" + user.Ident + "@" + user.Host
|
||||
user.Ident.Store(ident)
|
||||
|
||||
str := strs.Get()
|
||||
str.MustWriteString(user.Nick.Load().(string))
|
||||
str.MustWriteString("!")
|
||||
str.MustWriteString(user.Ident.Load().(string))
|
||||
str.MustWriteString("@")
|
||||
str.MustWriteString(user.Host)
|
||||
user.Mask.Store(str.String())
|
||||
strs.MustPut(str)
|
||||
|
||||
user.Extras.Name = realname
|
||||
|
||||
if account != "0" {
|
||||
|
15
cap.go
15
cap.go
@ -122,8 +122,7 @@ func handleCAP(c *Client, e Event) {
|
||||
if len(e.Params) >= 2 && e.Params[1] == CAP_DEL {
|
||||
caps := parseCap(e.Last())
|
||||
for capab := range caps {
|
||||
// TODO: test the deletion.
|
||||
delete(c.state.enabledCap, capab)
|
||||
c.state.enabledCap.Remove(capab)
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -194,10 +193,10 @@ func handleCAP(c *Client, e Event) {
|
||||
enabled := strings.Split(e.Last(), " ")
|
||||
for _, capab := range enabled {
|
||||
if val, ok := c.state.tmpCap[capab]; ok {
|
||||
c.state.enabledCap[capab] = val
|
||||
} else {
|
||||
c.state.enabledCap[capab] = nil
|
||||
c.state.enabledCap.Set(capab, val)
|
||||
continue
|
||||
}
|
||||
c.state.enabledCap.Remove(capab)
|
||||
}
|
||||
|
||||
// Anything client side that needs to be setup post-capability-acknowledgement,
|
||||
@ -205,7 +204,7 @@ func handleCAP(c *Client, e Event) {
|
||||
|
||||
// Handle STS, and only if it's something specifically we enabled (client
|
||||
// may choose to disable girc automatic STS, and do it themselves).
|
||||
if sts, sok := c.state.enabledCap["sts"]; sok && !c.Config.DisableSTS {
|
||||
if sts, sok := c.state.enabledCap.Get("sts"); sok && !c.Config.DisableSTS {
|
||||
var isError bool
|
||||
// Some things are updated in the policy depending on if the current
|
||||
// connection is over tls or not.
|
||||
@ -285,7 +284,7 @@ func handleCAP(c *Client, e Event) {
|
||||
// due to cap-notify, we can re-evaluate what we can support.
|
||||
c.state.tmpCap = make(map[string]map[string]string)
|
||||
|
||||
if _, ok := c.state.enabledCap["sasl"]; ok && c.Config.SASL != nil {
|
||||
if _, ok := c.state.enabledCap.Get("sasl"); ok && c.Config.SASL != nil {
|
||||
c.write(&Event{Command: AUTHENTICATE, Params: []string{c.Config.SASL.Method()}})
|
||||
// Don't "CAP END", since we want to authenticate.
|
||||
return
|
||||
@ -308,7 +307,7 @@ func handleCHGHOST(c *Client, e Event) {
|
||||
|
||||
user := c.state.lookupUser(e.Source.Name)
|
||||
if user != nil {
|
||||
user.Ident = e.Params[0]
|
||||
user.Ident.Store(e.Params[0])
|
||||
user.Host = e.Params[1]
|
||||
}
|
||||
|
||||
|
11
cap_tags.go
11
cap_tags.go
@ -51,9 +51,12 @@ type Tags map[string]string
|
||||
|
||||
// ParseTags parses out the key-value map of tags. raw should only be the tag
|
||||
// data, not a full message. For example:
|
||||
// @aaa=bbb;ccc;example.com/ddd=eee
|
||||
//
|
||||
// @aaa=bbb;ccc;example.com/ddd=eee
|
||||
//
|
||||
// NOT:
|
||||
// @aaa=bbb;ccc;example.com/ddd=eee :nick!ident@host.com PRIVMSG me :Hello
|
||||
//
|
||||
// @aaa=bbb;ccc;example.com/ddd=eee :nick!ident@host.com PRIVMSG me :Hello
|
||||
//
|
||||
// Technically, there is a length limit of 4096, but the server should reject
|
||||
// tag messages longer than this.
|
||||
@ -249,10 +252,6 @@ func (t Tags) Get(key string) (tag string, success bool) {
|
||||
// Set escapes given value and saves it as the value for given key. Note that
|
||||
// this is not concurrent safe.
|
||||
func (t Tags) Set(key, value string) error {
|
||||
if t == nil {
|
||||
t = make(Tags)
|
||||
}
|
||||
|
||||
if !validTag(key) {
|
||||
return fmt.Errorf("tag key %q is invalid", key)
|
||||
}
|
||||
|
52
client.go
52
client.go
@ -21,6 +21,8 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
)
|
||||
|
||||
// Client contains all of the information necessary to run a single IRC
|
||||
@ -222,13 +224,13 @@ type Config struct {
|
||||
// server.
|
||||
//
|
||||
// Client expectations:
|
||||
// - Perform any proxy resolution.
|
||||
// - Check the reverse DNS and forward DNS match.
|
||||
// - Check the IP against suitable access controls (ipaccess, dnsbl, etc).
|
||||
// - Perform any proxy resolution.
|
||||
// - Check the reverse DNS and forward DNS match.
|
||||
// - Check the IP against suitable access controls (ipaccess, dnsbl, etc).
|
||||
//
|
||||
// More information:
|
||||
// - https://ircv3.net/specs/extensions/webirc.html
|
||||
// - https://kiwiirc.com/docs/webirc
|
||||
// - https://ircv3.net/specs/extensions/webirc.html
|
||||
// - https://kiwiirc.com/docs/webirc
|
||||
type WebIRC struct {
|
||||
// Password that authenticates the WEBIRC command from this client.
|
||||
Password string
|
||||
@ -340,7 +342,12 @@ func New(config Config) *Client {
|
||||
c.Handlers = newCaller(c, c.debug)
|
||||
|
||||
// Give ourselves a new state.
|
||||
c.state = &state{}
|
||||
c.state = &state{
|
||||
channels: cmap.New[*Channel](),
|
||||
users: cmap.New[*User](),
|
||||
enabledCap: cmap.New[map[string]string](),
|
||||
serverOptions: cmap.New[string](),
|
||||
}
|
||||
c.state.RWMutex = &sync.RWMutex{}
|
||||
c.state.reset(true)
|
||||
|
||||
@ -600,7 +607,7 @@ func (c *Client) ChannelList() []string {
|
||||
|
||||
channels := make([]string, 0, len(c.state.channels.Keys()))
|
||||
for channel := range c.state.channels.IterBuffered() {
|
||||
chn := channel.Val.(*Channel)
|
||||
chn := channel.Val
|
||||
if !chn.UserIn(c.GetNick()) {
|
||||
continue
|
||||
}
|
||||
@ -616,9 +623,9 @@ func (c *Client) ChannelList() []string {
|
||||
func (c *Client) Channels() []*Channel {
|
||||
c.panicIfNotTracking()
|
||||
|
||||
channels := make([]*Channel, 0, len(c.state.channels))
|
||||
channels := make([]*Channel, 0, c.state.channels.Count())
|
||||
for channel := range c.state.channels.IterBuffered() {
|
||||
chn := channel.Val.(*Channel)
|
||||
chn := channel.Val
|
||||
channels = append(channels, chn.Copy())
|
||||
}
|
||||
|
||||
@ -633,13 +640,13 @@ func (c *Client) Channels() []*Channel {
|
||||
func (c *Client) UserList() []string {
|
||||
c.panicIfNotTracking()
|
||||
|
||||
users := make([]string, 0, len(c.state.users))
|
||||
users := make([]string, 0, c.state.users.Count())
|
||||
for user := range c.state.users.IterBuffered() {
|
||||
usr := user.Val.(*User)
|
||||
usr := user.Val
|
||||
if usr.Stale {
|
||||
continue
|
||||
}
|
||||
users = append(users, usr.Nick)
|
||||
users = append(users, usr.Nick.Load().(string))
|
||||
}
|
||||
|
||||
sort.Strings(users)
|
||||
@ -651,14 +658,14 @@ func (c *Client) UserList() []string {
|
||||
func (c *Client) Users() []*User {
|
||||
c.panicIfNotTracking()
|
||||
|
||||
users := make([]*User, 0, len(c.state.users))
|
||||
users := make([]*User, 0, c.state.users.Count())
|
||||
for user := range c.state.users.IterBuffered() {
|
||||
usr := user.Val.(*User)
|
||||
usr := user.Val
|
||||
users = append(users, usr.Copy())
|
||||
}
|
||||
|
||||
sort.Slice(users, func(i, j int) bool {
|
||||
return users[i].Nick < users[j].Nick
|
||||
return users[i].Nick.Load().(string) < users[j].Nick.Load().(string)
|
||||
})
|
||||
return users
|
||||
}
|
||||
@ -702,18 +709,15 @@ func (c *Client) IsInChannel(channel string) (in bool) {
|
||||
// during client connection. This is also known as ISUPPORT (or RPL_PROTOCTL).
|
||||
// Will panic if used when tracking has been disabled. Examples of usage:
|
||||
//
|
||||
// nickLen, success := GetServerOpt("MAXNICKLEN")
|
||||
//
|
||||
// nickLen, success := GetServerOpt("MAXNICKLEN")
|
||||
func (c *Client) GetServerOpt(key string) (result string, ok bool) {
|
||||
c.panicIfNotTracking()
|
||||
|
||||
oi, ok := c.state.serverOptions.Get(key)
|
||||
result, ok = c.state.serverOptions.Get(key)
|
||||
if !ok {
|
||||
return "", ok
|
||||
}
|
||||
|
||||
result = oi.(string)
|
||||
|
||||
if len(result) > 0 {
|
||||
ok = true
|
||||
}
|
||||
@ -726,7 +730,7 @@ func (c *Client) GetServerOpt(key string) (result string, ok bool) {
|
||||
func (c *Client) GetServerOptions() []byte {
|
||||
o := make(map[string]string)
|
||||
for opt := range c.state.serverOptions.IterBuffered() {
|
||||
o[opt.Key] = opt.Val.(string)
|
||||
o[opt.Key] = opt.Val
|
||||
}
|
||||
jcytes, _ := json.Marshal(o)
|
||||
return jcytes
|
||||
@ -799,15 +803,13 @@ func (c *Client) HasCapability(name string) (has bool) {
|
||||
|
||||
name = strings.ToLower(name)
|
||||
|
||||
c.state.RLock()
|
||||
for key := range c.state.enabledCap {
|
||||
key = strings.ToLower(key)
|
||||
for capab := range c.state.enabledCap.IterBuffered() {
|
||||
key := strings.ToLower(capab.Key)
|
||||
if key == name {
|
||||
has = true
|
||||
break
|
||||
}
|
||||
}
|
||||
c.state.RUnlock()
|
||||
|
||||
return has
|
||||
}
|
||||
|
@ -93,14 +93,24 @@ func TestClientLifetime(t *testing.T) {
|
||||
|
||||
func TestClientUptime(t *testing.T) {
|
||||
c, conn, server := genMockConn()
|
||||
defer conn.Close()
|
||||
defer server.Close()
|
||||
defer func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Errorf("failed to close connection: %s", err)
|
||||
}
|
||||
if err := server.Close(); err != nil {
|
||||
t.Errorf("failed to close server: %s", err)
|
||||
}
|
||||
}()
|
||||
go mockReadBuffer(conn)
|
||||
|
||||
done := make(chan struct{}, 1)
|
||||
c.Handlers.Add(INITIALIZED, func(c *Client, e Event) { close(done) })
|
||||
|
||||
go c.MockConnect(server)
|
||||
go func() {
|
||||
if err := c.MockConnect(server); err != nil {
|
||||
t.Errorf("failed to connect: %s", err)
|
||||
}
|
||||
}()
|
||||
defer c.Close()
|
||||
|
||||
select {
|
||||
@ -138,14 +148,24 @@ func TestClientUptime(t *testing.T) {
|
||||
|
||||
func TestClientGet(t *testing.T) {
|
||||
c, conn, server := genMockConn()
|
||||
defer conn.Close()
|
||||
defer server.Close()
|
||||
defer func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Errorf("failed to close connection: %s", err)
|
||||
}
|
||||
if err := server.Close(); err != nil {
|
||||
t.Errorf("failed to close server: %s", err)
|
||||
}
|
||||
}()
|
||||
go mockReadBuffer(conn)
|
||||
|
||||
done := make(chan struct{}, 1)
|
||||
c.Handlers.Add(INITIALIZED, func(c *Client, e Event) { close(done) })
|
||||
|
||||
go c.MockConnect(server)
|
||||
go func() {
|
||||
if err := c.MockConnect(server); err != nil {
|
||||
t.Errorf("failed to connect: %s", err)
|
||||
}
|
||||
}()
|
||||
defer c.Close()
|
||||
|
||||
select {
|
||||
@ -169,8 +189,14 @@ func TestClientGet(t *testing.T) {
|
||||
|
||||
func TestClientClose(t *testing.T) {
|
||||
c, conn, server := genMockConn()
|
||||
defer server.Close()
|
||||
defer conn.Close()
|
||||
defer func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Errorf("failed to close connection: %s", err)
|
||||
}
|
||||
if err := server.Close(); err != nil {
|
||||
t.Errorf("failed to close server: %s", err)
|
||||
}
|
||||
}()
|
||||
go mockReadBuffer(conn)
|
||||
|
||||
errchan := make(chan error, 1)
|
||||
|
@ -4,6 +4,7 @@ package girc
|
||||
IRCNumToStr takes in a numeric IRC code and returns the relevant girc name.
|
||||
IRCNumToStr accepts a string because that's how we tend to receive the codes.
|
||||
*/
|
||||
//goland:noinspection GoUnusedExportedFunction
|
||||
func IRCNumToStr(code string) string {
|
||||
if _, ok := noTranslate[code]; ok {
|
||||
return code
|
||||
|
87
commands.go
87
commands.go
@ -111,7 +111,8 @@ func (cmd *Commands) Message(target, message string) {
|
||||
// Messagef sends a formated PRIVMSG to target (either channel, service, or
|
||||
// user).
|
||||
func (cmd *Commands) Messagef(target, format string, a ...interface{}) {
|
||||
cmd.Message(target, fmt.Sprintf(Fmt(format), a...))
|
||||
message := fmt.Sprintf(format, a...)
|
||||
cmd.Message(target, Fmt(message))
|
||||
}
|
||||
|
||||
// ErrInvalidSource is returned when a method needs to know the origin of an
|
||||
@ -119,79 +120,83 @@ func (cmd *Commands) Messagef(target, format string, a ...interface{}) {
|
||||
// server.)
|
||||
var ErrInvalidSource = errors.New("event has nil or invalid source address")
|
||||
|
||||
// ErrDontKnowUser is returned when a method needs to know the origin of an event,
|
||||
var ErrDontKnowUser = errors.New("failed to lookup target user")
|
||||
|
||||
// Reply sends a reply to channel or user, based on where the supplied event
|
||||
// originated from. See also ReplyTo(). Panics if the incoming event has no
|
||||
// source.
|
||||
func (cmd *Commands) Reply(event Event, message string) {
|
||||
func (cmd *Commands) Reply(event Event, message string) error {
|
||||
if event.Source == nil {
|
||||
panic(ErrInvalidSource)
|
||||
return ErrInvalidSource
|
||||
}
|
||||
|
||||
if len(event.Params) > 0 && IsValidChannel(event.Params[0]) {
|
||||
cmd.Message(event.Params[0], message)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
cmd.Message(event.Source.Name, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplyKick kicks the source of the event from the channel where the event originated
|
||||
func (cmd *Commands) ReplyKick(event Event, reason string) {
|
||||
func (cmd *Commands) ReplyKick(event Event, reason string) error {
|
||||
if event.Source == nil {
|
||||
panic(ErrInvalidSource)
|
||||
return ErrInvalidSource
|
||||
}
|
||||
|
||||
if len(event.Params) > 0 && IsValidChannel(event.Params[0]) {
|
||||
cmd.Kick(event.Params[0], event.Source.Name, reason)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplyBan kicks the source of the event from the channel where the event originated.
|
||||
// Additionally, if a reason is provided, it will send a message to the channel.
|
||||
func (cmd *Commands) ReplyBan(event Event, reason string) {
|
||||
func (cmd *Commands) ReplyBan(event Event, reason string) (err error) {
|
||||
if event.Source == nil {
|
||||
panic(ErrInvalidSource)
|
||||
return ErrInvalidSource
|
||||
}
|
||||
|
||||
if reason != "" {
|
||||
cmd.Replyf(event, "{red}{b}[BAN] {r}%s", reason)
|
||||
err = cmd.Replyf(event, "{red}{b}[BAN] {r}%s", reason)
|
||||
}
|
||||
|
||||
if len(event.Params) > 0 && IsValidChannel(event.Params[0]) {
|
||||
cmd.Ban(event.Params[0], event.Source.Name)
|
||||
cmd.Ban(event.Params[0], fmt.Sprintf("*!%s@%s", event.Source.Ident, event.Source.Host))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Replyf sends a reply to channel or user with a format string, based on
|
||||
// where the supplied event originated from. See also ReplyTof(). Panics if
|
||||
// the incoming event has no source.
|
||||
func (cmd *Commands) Replyf(event Event, format string, a ...interface{}) {
|
||||
cmd.Reply(event, fmt.Sprintf(Fmt(format), a...))
|
||||
// Formatted means both in the sense of Sprintf as well as girc style macros.
|
||||
func (cmd *Commands) Replyf(event Event, format string, a ...interface{}) error {
|
||||
message := fmt.Sprintf(format, a...)
|
||||
return cmd.Reply(event, Fmt(message))
|
||||
}
|
||||
|
||||
// ReplyTo sends a reply to a channel or user, based on where the supplied
|
||||
// event originated from. ReplyTo(), when originating from a channel will
|
||||
// default to replying with "<user>, <message>". See also Reply(). Panics if
|
||||
// the incoming event has no source.
|
||||
func (cmd *Commands) ReplyTo(event Event, message string) {
|
||||
func (cmd *Commands) ReplyTo(event Event, message string) error {
|
||||
if event.Source == nil {
|
||||
panic(ErrInvalidSource)
|
||||
return ErrInvalidSource
|
||||
}
|
||||
|
||||
if len(event.Params) > 0 && IsValidChannel(event.Params[0]) {
|
||||
cmd.Message(event.Params[0], event.Source.Name+", "+message)
|
||||
return
|
||||
} else {
|
||||
cmd.Message(event.Source.Name, message)
|
||||
}
|
||||
|
||||
cmd.Message(event.Source.Name, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplyTof sends a reply to a channel or user with a format string, based
|
||||
// on where the supplied event originated from. ReplyTo(), when originating
|
||||
// from a channel will default to replying with "<user>, <message>". See
|
||||
// also Replyf(). Panics if the incoming event has no source.
|
||||
func (cmd *Commands) ReplyTof(event Event, format string, a ...interface{}) {
|
||||
cmd.ReplyTo(event, fmt.Sprintf(Fmt(format), a...))
|
||||
// Formatted means both in the sense of Sprintf as well as girc style macros.
|
||||
func (cmd *Commands) ReplyTof(event Event, format string, a ...interface{}) error {
|
||||
message := fmt.Sprintf(format, a...)
|
||||
return cmd.ReplyTo(event, Fmt(message))
|
||||
}
|
||||
|
||||
// Action sends a PRIVMSG ACTION (/me) to target (either channel, service,
|
||||
@ -215,9 +220,9 @@ func (cmd *Commands) Notice(target, message string) {
|
||||
}
|
||||
|
||||
// Noticef sends a formated NOTICE to target (either channel, service, or
|
||||
// user).
|
||||
// user). Formatted means both in the sense of Sprintf as well as girc styling codes.
|
||||
func (cmd *Commands) Noticef(target, format string, a ...interface{}) {
|
||||
cmd.Notice(target, fmt.Sprintf(format, a...))
|
||||
cmd.Notice(target, Fmt(fmt.Sprintf(format, a...)))
|
||||
}
|
||||
|
||||
// SendRaw sends a raw string (or multiple) to the server, without carriage
|
||||
@ -239,14 +244,21 @@ func (cmd *Commands) SendRaw(raw ...string) error {
|
||||
}
|
||||
|
||||
// SendRawf sends a formated string back to the server, without carriage
|
||||
// returns or newlines.
|
||||
// returns or newlines. Formatted means both in the sense of Sprintf as well as girc style macros.
|
||||
func (cmd *Commands) SendRawf(format string, a ...interface{}) error {
|
||||
return cmd.SendRaw(fmt.Sprintf(format, a...))
|
||||
return cmd.SendRaw(Fmt(fmt.Sprintf(format, a...)))
|
||||
}
|
||||
|
||||
// Topic sets the topic of channel to message. Does not verify the length
|
||||
// of the topic.
|
||||
func (cmd *Commands) Topic(channel, message string) {
|
||||
cmd.c.Send(&Event{Command: TOPIC, Params: []string{channel, message}})
|
||||
}
|
||||
|
||||
// Topicf sets a formatted topic command to the channel. Does not verify the length
|
||||
// of the topic. Formatted means both in the sense of Sprintf as well as girc style macros.
|
||||
func (cmd *Commands) Topicf(channel, format string, a ...interface{}) {
|
||||
message := fmt.Sprintf(format, a...)
|
||||
cmd.c.Send(&Event{Command: TOPIC, Params: []string{channel, Fmt(message)}})
|
||||
}
|
||||
|
||||
@ -286,6 +298,22 @@ func (cmd *Commands) Oper(user, pass string) {
|
||||
cmd.c.Send(&Event{Command: OPER, Params: []string{user, pass}, Sensitive: true})
|
||||
}
|
||||
|
||||
// KickBan sends a KICK query to the server, attempting to kick nick from
|
||||
// channel, with reason. If reason is blank, one will not be sent to the
|
||||
// server. Afterwards it immediately sets +b on the mask given.
|
||||
// If no mask is given, it will set +b on *!~ident@host.
|
||||
//
|
||||
// Note: this command will return an error if it cannot track the user in order to determine ban mask.
|
||||
func (cmd *Commands) KickBan(channel, user, reason string) error {
|
||||
u := cmd.c.LookupUser(user)
|
||||
if u == nil {
|
||||
return ErrDontKnowUser
|
||||
}
|
||||
cmd.Kick(channel, user, reason)
|
||||
cmd.Ban(channel, fmt.Sprintf("*!%s@%s", u.Ident, u.Host))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Kick sends a KICK query to the server, attempting to kick nick from
|
||||
// channel, with reason. If reason is blank, one will not be sent to the
|
||||
// server.
|
||||
@ -293,7 +321,6 @@ func (cmd *Commands) Kick(channel, user, reason string) {
|
||||
if reason != "" {
|
||||
cmd.c.Send(&Event{Command: KICK, Params: []string{channel, user, reason}})
|
||||
}
|
||||
|
||||
cmd.c.Send(&Event{Command: KICK, Params: []string{channel, user}})
|
||||
}
|
||||
|
||||
|
16
conn.go
16
conn.go
@ -12,6 +12,8 @@ import (
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.tcp.direct/kayos/common/pool"
|
||||
)
|
||||
|
||||
// Messages are delimited with CR and LF line endings, we're using the last
|
||||
@ -55,6 +57,8 @@ type Dialer interface {
|
||||
Dial(network, address string) (net.Conn, error)
|
||||
}
|
||||
|
||||
var strs = pool.NewStringFactory()
|
||||
|
||||
// newConn sets up and returns a new connection to the server.
|
||||
func newConn(conf Config, dialer Dialer, addr string, sts *strictTransport) (*ircConn, error) {
|
||||
if err := conf.isValid(); err != nil {
|
||||
@ -69,7 +73,11 @@ func newConn(conf Config, dialer Dialer, addr string, sts *strictTransport) (*ir
|
||||
|
||||
if conf.Bind != "" {
|
||||
var local *net.TCPAddr
|
||||
local, err = net.ResolveTCPAddr("tcp", conf.Bind+":0")
|
||||
s := strs.Get()
|
||||
s.MustWriteString(conf.Bind)
|
||||
s.MustWriteString(":0")
|
||||
local, err = net.ResolveTCPAddr("tcp", s.String())
|
||||
strs.MustPut(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -501,15 +509,13 @@ func (c *Client) sendLoop(ctx context.Context, errs chan error, working *int32)
|
||||
// Check if tags exist on the event. If they do, and message-tags
|
||||
// isn't a supported capability, remove them from the event.
|
||||
if event.Tags != nil {
|
||||
c.state.RLock()
|
||||
var in bool
|
||||
for i := 0; i < len(c.state.enabledCap); i++ {
|
||||
if _, ok := c.state.enabledCap["message-tags"]; ok {
|
||||
for i := 0; i < c.state.enabledCap.Count(); i++ {
|
||||
if _, ok := c.state.enabledCap.Get("message-tags"); ok {
|
||||
in = true
|
||||
break
|
||||
}
|
||||
}
|
||||
c.state.RUnlock()
|
||||
|
||||
if !in {
|
||||
event.Tags = Tags{}
|
||||
|
24
constants.go
24
constants.go
@ -5,6 +5,8 @@
|
||||
package girc
|
||||
|
||||
// Standard CTCP based constants.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
CTCP_ACTION = "ACTION"
|
||||
CTCP_PING = "PING"
|
||||
@ -20,6 +22,8 @@ const (
|
||||
|
||||
// Emulated event commands used to allow easier hooks into the changing
|
||||
// state of the client.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
UPDATE_STATE = "CLIENT_STATE_UPDATED" // when channel/user state is updated.
|
||||
UPDATE_GENERAL = "CLIENT_GENERAL_UPDATED" // when general state (client nick, server name, etc) is updated.
|
||||
@ -33,6 +37,8 @@ const (
|
||||
)
|
||||
|
||||
// User/channel prefixes :: RFC1459.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
DefaultPrefixes = "(ov)@+" // the most common default prefixes
|
||||
ModeAddPrefix = "+" // modes are being added
|
||||
@ -48,6 +54,8 @@ const (
|
||||
)
|
||||
|
||||
// User modes :: RFC1459; section 4.2.3.2.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
UserModeInvisible = "i" // invisible
|
||||
UserModeOperator = "o" // server operator
|
||||
@ -56,6 +64,8 @@ const (
|
||||
)
|
||||
|
||||
// Channel modes :: RFC1459; section 4.2.3.1.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
ModeDefaults = "beI,k,l,imnpst" // the most common default modes
|
||||
|
||||
@ -75,6 +85,8 @@ const (
|
||||
)
|
||||
|
||||
// IRC commands :: RFC2812; section 3 :: RFC2813; section 4.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
ADMIN = "ADMIN"
|
||||
AWAY = "AWAY"
|
||||
@ -127,6 +139,8 @@ const (
|
||||
)
|
||||
|
||||
// Numeric IRC reply mapping :: RFC2812; section 5.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
RPL_WELCOME = "001"
|
||||
RPL_YOURHOST = "002"
|
||||
@ -270,6 +284,8 @@ const (
|
||||
)
|
||||
|
||||
// IRCv3 commands and extensions :: http://ircv3.net/irc/.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
AUTHENTICATE = "AUTHENTICATE"
|
||||
MONITOR = "MONITOR"
|
||||
@ -293,6 +309,8 @@ const (
|
||||
)
|
||||
|
||||
// Numeric IRC reply mapping for ircv3 :: http://ircv3.net/irc/.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
RPL_LOGGEDIN = "900"
|
||||
RPL_LOGGEDOUT = "901"
|
||||
@ -313,6 +331,8 @@ const (
|
||||
)
|
||||
|
||||
// Numeric IRC event mapping :: RFC2812; section 5.3.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
RPL_STATSCLINE = "213"
|
||||
RPL_STATSNLINE = "214"
|
||||
@ -341,6 +361,8 @@ const (
|
||||
)
|
||||
|
||||
// Misc.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
ERR_TOOMANYMATCHES = "416" // IRCNet.
|
||||
RPL_GLOBALUSERS = "266" // aircd/hybrid/bahamut, used on freenode.
|
||||
@ -351,6 +373,8 @@ const (
|
||||
)
|
||||
|
||||
// As seen in the wild.
|
||||
//
|
||||
//goland:noinspection ALL
|
||||
const (
|
||||
RPL_WHOISAUTHNAME = "330"
|
||||
RPL_WHOISTLS = "671"
|
||||
|
37
ctcp.go
37
ctcp.go
@ -9,6 +9,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
)
|
||||
|
||||
// ctcpDelim if the delimiter used for CTCP formatted events/messages.
|
||||
@ -122,12 +124,12 @@ type CTCP struct {
|
||||
// mu is the mutex that should be used when accessing any ctcp handlers.
|
||||
mu sync.RWMutex
|
||||
// handlers is a map of CTCP message -> functions.
|
||||
handlers map[string]CTCPHandler
|
||||
handlers cmap.ConcurrentMap[string, CTCPHandler]
|
||||
}
|
||||
|
||||
// newCTCP returns a new clean CTCP handler.
|
||||
func newCTCP() *CTCP {
|
||||
return &CTCP{handlers: map[string]CTCPHandler{}}
|
||||
return &CTCP{handlers: cmap.New[CTCPHandler]()}
|
||||
}
|
||||
|
||||
// call executes the necessary CTCP handler for the incoming event/CTCP
|
||||
@ -137,23 +139,16 @@ func (c *CTCP) call(client *Client, event *CTCPEvent) {
|
||||
if client.Config.RecoverFunc != nil && event.Origin != nil {
|
||||
defer recoverHandlerPanic(client, event.Origin, "ctcp-"+strings.ToLower(event.Command), 3)
|
||||
}
|
||||
|
||||
// Support wildcard CTCP event handling. Gets executed first before
|
||||
// regular event handlers.
|
||||
if _, ok := c.handlers["*"]; ok {
|
||||
c.handlers["*"](client, *event)
|
||||
if val, ok := c.handlers.Get("*"); ok && val != nil {
|
||||
val(client, *event)
|
||||
}
|
||||
|
||||
if _, ok := c.handlers[event.Command]; !ok {
|
||||
// If ACTION, don't do anything.
|
||||
if event.Command == CTCP_ACTION {
|
||||
return
|
||||
}
|
||||
|
||||
val, ok := c.handlers.Get(event.Command)
|
||||
if !ok || val == nil || event.Command == CTCP_ACTION {
|
||||
return
|
||||
}
|
||||
|
||||
c.handlers[event.Command](client, *event)
|
||||
val(client, *event)
|
||||
}
|
||||
|
||||
// parseCMD parses a CTCP command/tag, ensuring it's valid. If not, an empty
|
||||
@ -185,9 +180,7 @@ func (c *CTCP) Set(cmd string, handler func(client *Client, ctcp CTCPEvent)) {
|
||||
if cmd = c.parseCMD(cmd); cmd == "" {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.handlers[cmd] = handler
|
||||
c.mu.Unlock()
|
||||
c.handlers.Set(cmd, handler)
|
||||
}
|
||||
|
||||
// SetBg is much like Set, however the handler is executed in the background,
|
||||
@ -204,18 +197,12 @@ func (c *CTCP) Clear(cmd string) {
|
||||
if cmd = c.parseCMD(cmd); cmd == "" {
|
||||
return
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
delete(c.handlers, cmd)
|
||||
c.mu.Unlock()
|
||||
c.handlers.Remove(cmd)
|
||||
}
|
||||
|
||||
// ClearAll removes all currently setup and re-sets the default handlers.
|
||||
func (c *CTCP) ClearAll() {
|
||||
c.mu.Lock()
|
||||
c.handlers = map[string]CTCPHandler{}
|
||||
c.mu.Unlock()
|
||||
|
||||
c.handlers = cmap.New[CTCPHandler]()
|
||||
// Register necessary handlers.
|
||||
c.addDefaultHandlers()
|
||||
}
|
||||
|
10
ctcp_test.go
10
ctcp_test.go
@ -162,13 +162,13 @@ func TestSet(t *testing.T) {
|
||||
ctcp := newCTCP()
|
||||
|
||||
ctcp.Set("TEST-1", func(client *Client, event CTCPEvent) {})
|
||||
if _, ok := ctcp.handlers["TEST"]; ok {
|
||||
if _, ok := ctcp.handlers.Get("TEST"); ok {
|
||||
t.Fatal("Set('TEST') allowed invalid command")
|
||||
}
|
||||
|
||||
ctcp.Set("TEST", func(client *Client, event CTCPEvent) {})
|
||||
// Make sure it's there.
|
||||
if _, ok := ctcp.handlers["TEST"]; !ok {
|
||||
if _, ok := ctcp.handlers.Get("TEST"); !ok {
|
||||
t.Fatal("store: Set('TEST') didn't set")
|
||||
}
|
||||
}
|
||||
@ -179,7 +179,7 @@ func TestClear(t *testing.T) {
|
||||
ctcp.Set("TEST", func(client *Client, event CTCPEvent) {})
|
||||
ctcp.Clear("TEST")
|
||||
|
||||
if _, ok := ctcp.handlers["TEST"]; ok {
|
||||
if _, ok := ctcp.handlers.Get("TEST"); ok {
|
||||
t.Fatal("ctcp.Clear('TEST') didn't remove handler")
|
||||
}
|
||||
}
|
||||
@ -191,8 +191,8 @@ func TestClearAll(t *testing.T) {
|
||||
ctcp.Set("TEST2", func(client *Client, event CTCPEvent) {})
|
||||
ctcp.ClearAll()
|
||||
|
||||
_, first := ctcp.handlers["TEST1"]
|
||||
_, second := ctcp.handlers["TEST2"]
|
||||
_, first := ctcp.handlers.Get("TEST1")
|
||||
_, second := ctcp.handlers.Get("TEST2")
|
||||
|
||||
if first || second {
|
||||
t.Fatalf("ctcp.ClearAll() didn't remove all handlers: 1: %v 2: %v", first, second)
|
||||
|
@ -111,7 +111,7 @@ func TestParseEvent(t *testing.T) {
|
||||
}
|
||||
|
||||
if got == nil {
|
||||
t.Errorf("ParseEvent: got nil, want: %s", tt.want)
|
||||
t.Fatalf("ParseEvent: got nil, want: %s", tt.want)
|
||||
}
|
||||
|
||||
if got.String() != tt.want {
|
||||
@ -133,6 +133,7 @@ func TestParseEvent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
//goland:noinspection GoNilness
|
||||
func TestEventCopy(t *testing.T) {
|
||||
var nilEvent *Event
|
||||
|
||||
|
@ -59,7 +59,7 @@ func Example_simple() {
|
||||
|
||||
client.Handlers.Add(girc.PRIVMSG, func(c *girc.Client, e girc.Event) {
|
||||
if strings.Contains(e.Last(), "hello") {
|
||||
c.Cmd.ReplyTo(e, "hello world!")
|
||||
_ = c.Cmd.ReplyTo(e, "hello world!")
|
||||
return
|
||||
}
|
||||
|
||||
@ -99,7 +99,7 @@ func Example_commands() {
|
||||
|
||||
client.Handlers.Add(girc.PRIVMSG, func(c *girc.Client, e girc.Event) {
|
||||
if strings.HasPrefix(e.Last(), "!hello") {
|
||||
c.Cmd.ReplyTo(e, girc.Fmt("{b}hello{b} {blue}world{c}!"))
|
||||
_ = c.Cmd.ReplyTo(e, girc.Fmt("{b}hello{b} {blue}world{c}!"))
|
||||
return
|
||||
}
|
||||
|
||||
|
29
format.go
29
format.go
@ -66,7 +66,7 @@ var fmtCodes = map[string]string{
|
||||
//
|
||||
// For example:
|
||||
//
|
||||
// client.Message("#channel", Fmt("{red}{b}Hello {red,blue}World{c}"))
|
||||
// client.Message("#channel", Fmt("{red}{b}Hello {red,blue}World{c}"))
|
||||
func Fmt(text string) string {
|
||||
var last = -1
|
||||
for i := 0; i < len(text); i++ {
|
||||
@ -164,12 +164,12 @@ func StripRaw(text string) string {
|
||||
// all ASCII printable chars. This function will NOT do that for
|
||||
// compatibility reasons.
|
||||
//
|
||||
// channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring
|
||||
// [ ":" chanstring ]
|
||||
// chanstring = 0x01-0x07 / 0x08-0x09 / 0x0B-0x0C / 0x0E-0x1F / 0x21-0x2B
|
||||
// chanstring = / 0x2D-0x39 / 0x3B-0xFF
|
||||
// ; any octet except NUL, BELL, CR, LF, " ", "," and ":"
|
||||
// channelid = 5( 0x41-0x5A / digit ) ; 5( A-Z / 0-9 )
|
||||
// channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring
|
||||
// [ ":" chanstring ]
|
||||
// chanstring = 0x01-0x07 / 0x08-0x09 / 0x0B-0x0C / 0x0E-0x1F / 0x21-0x2B
|
||||
// chanstring = / 0x2D-0x39 / 0x3B-0xFF
|
||||
// ; any octet except NUL, BELL, CR, LF, " ", "," and ":"
|
||||
// channelid = 5( 0x41-0x5A / digit ) ; 5( A-Z / 0-9 )
|
||||
func IsValidChannel(channel string) bool {
|
||||
if len(channel) <= 1 || len(channel) > 50 {
|
||||
return false
|
||||
@ -214,10 +214,10 @@ func IsValidChannel(channel string) bool {
|
||||
// IsValidNick validates an IRC nickname. Note that this does not validate
|
||||
// IRC nickname length.
|
||||
//
|
||||
// nickname = ( letter / special ) *8( letter / digit / special / "-" )
|
||||
// letter = 0x41-0x5A / 0x61-0x7A
|
||||
// digit = 0x30-0x39
|
||||
// special = 0x5B-0x60 / 0x7B-0x7D
|
||||
// nickname = ( letter / special ) *8( letter / digit / special / "-" )
|
||||
// letter = 0x41-0x5A / 0x61-0x7A
|
||||
// digit = 0x30-0x39
|
||||
// special = 0x5B-0x60 / 0x7B-0x7D
|
||||
func IsValidNick(nick string) bool {
|
||||
if nick == "" {
|
||||
return false
|
||||
@ -253,8 +253,9 @@ func IsValidNick(nick string) bool {
|
||||
// not be supported on all networks. Some limit this to only a single period.
|
||||
//
|
||||
// Per RFC:
|
||||
// user = 1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF )
|
||||
// ; any octet except NUL, CR, LF, " " and "@"
|
||||
//
|
||||
// user = 1*( %x01-09 / %x0B-0C / %x0E-1F / %x21-3F / %x41-FF )
|
||||
// ; any octet except NUL, CR, LF, " " and "@"
|
||||
func IsValidUser(name string) bool {
|
||||
if name == "" {
|
||||
return false
|
||||
@ -324,7 +325,7 @@ func Glob(input, match string) bool {
|
||||
|
||||
if len(parts) == 1 {
|
||||
// No globs, test for equality.
|
||||
return input == match
|
||||
return strings.EqualFold(input, match)
|
||||
}
|
||||
|
||||
leadingGlob, trailingGlob := strings.HasPrefix(match, globChar), strings.HasSuffix(match, globChar)
|
||||
|
7
go.mod
7
go.mod
@ -1,10 +1,9 @@
|
||||
module github.com/yunginnanet/girc-atomic
|
||||
|
||||
go 1.18
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
git.tcp.direct/kayos/common v0.8.1
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1
|
||||
)
|
||||
|
||||
require github.com/dvyukov/go-fuzz v0.0.0-20220220162807-a217d9bdbece // indirect
|
||||
|
8
go.sum
8
go.sum
@ -1,12 +1,12 @@
|
||||
git.tcp.direct/kayos/common v0.8.1 h1:gxcCaa7QlQzkvBPzcwoVyP89mexrxKvnmlnvh4PGu4o=
|
||||
git.tcp.direct/kayos/common v0.8.1/go.mod h1:r7lZuKTQz0uf/jNm61sz1XaMgK/RYRr7wtqr/cNYd8o=
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dvyukov/go-fuzz v0.0.0-20220220162807-a217d9bdbece h1:6BGhEtGBmkgr8TKLjMBBMpvM/fK0GHj4prrkK1tYPcA=
|
||||
github.com/dvyukov/go-fuzz v0.0.0-20220220162807-a217d9bdbece/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY=
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/6lP/L/zp6c=
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
|
69
handler.go
69
handler.go
@ -15,7 +15,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/orcaman/concurrent-map"
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
)
|
||||
|
||||
// RunHandlers manually runs handlers for a given event.
|
||||
@ -25,15 +25,18 @@ func (c *Client) RunHandlers(event *Event) {
|
||||
return
|
||||
}
|
||||
|
||||
s := strs.Get()
|
||||
// Log the event.
|
||||
prefix := "< "
|
||||
s.MustWriteString("< ")
|
||||
if event.Echo {
|
||||
prefix += "[echo-message] "
|
||||
s.MustWriteString("[echo-message] ")
|
||||
}
|
||||
c.debug.Print(prefix + StripRaw(event.String()))
|
||||
s.MustWriteString(event.String())
|
||||
c.debug.Print(s.String())
|
||||
strs.MustPut(s)
|
||||
if c.Config.Out != nil {
|
||||
if pretty, ok := event.Pretty(); ok {
|
||||
fmt.Fprintln(c.Config.Out, StripRaw(pretty))
|
||||
_, _ = fmt.Fprintln(c.Config.Out, StripRaw(pretty))
|
||||
}
|
||||
}
|
||||
|
||||
@ -78,7 +81,7 @@ func (f HandlerFunc) Execute(client *Client, event Event) {
|
||||
//
|
||||
// command and cuid are both strings.
|
||||
type nestedHandlers struct {
|
||||
cm cmap.ConcurrentMap
|
||||
cm cmap.ConcurrentMap[string, cmap.ConcurrentMap[string, Handler]]
|
||||
}
|
||||
|
||||
type handlerTuple struct {
|
||||
@ -87,40 +90,37 @@ type handlerTuple struct {
|
||||
}
|
||||
|
||||
func newNestedHandlers() *nestedHandlers {
|
||||
return &nestedHandlers{cm: cmap.New()}
|
||||
return &nestedHandlers{cm: cmap.New[cmap.ConcurrentMap[string, Handler]]()}
|
||||
}
|
||||
|
||||
func (nest *nestedHandlers) len() (total int) {
|
||||
for hs := range nest.cm.IterBuffered() {
|
||||
hndlrs := hs.Val.(cmap.ConcurrentMap)
|
||||
total += len(hndlrs.Keys())
|
||||
for hndlrs := range nest.cm.IterBuffered() {
|
||||
total += len(hndlrs.Val.Keys())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (nest *nestedHandlers) lenFor(cmd string) (total int) {
|
||||
cmd = strings.ToUpper(cmd)
|
||||
hs, ok := nest.cm.Get(cmd)
|
||||
hndlrs, ok := nest.cm.Get(cmd)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
hndlrs := hs.(cmap.ConcurrentMap)
|
||||
return hndlrs.Count()
|
||||
}
|
||||
|
||||
func (nest *nestedHandlers) getAllHandlersFor(s string) (handlers chan handlerTuple, ok bool) {
|
||||
var h interface{}
|
||||
var h cmap.ConcurrentMap[string, Handler]
|
||||
h, ok = nest.cm.Get(s)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
hm := h.(cmap.ConcurrentMap)
|
||||
handlers = make(chan handlerTuple)
|
||||
go func() {
|
||||
for hi := range hm.IterBuffered() {
|
||||
for hi := range h.IterBuffered() {
|
||||
ht := handlerTuple{
|
||||
hi.Key,
|
||||
hi.Val.(Handler),
|
||||
hi.Val,
|
||||
}
|
||||
handlers <- ht
|
||||
}
|
||||
@ -218,35 +218,25 @@ func (c *Caller) exec(command string, bg bool, client *Client, event *Event) {
|
||||
var stack []execStack
|
||||
|
||||
// Get internal handlers first.
|
||||
ihm, iok := c.internal.cm.Get(command)
|
||||
hmap, iok := c.internal.cm.Get(command)
|
||||
if iok {
|
||||
hmap := ihm.(cmap.ConcurrentMap)
|
||||
for assigned := range hmap.IterBuffered() {
|
||||
cuid := assigned.Key
|
||||
if (strings.HasSuffix(cuid, ":bg") && !bg) || (!strings.HasSuffix(cuid, ":bg") && bg) {
|
||||
continue
|
||||
}
|
||||
hi, _ := hmap.Get(cuid)
|
||||
hndlr, ok := hi.(Handler)
|
||||
if !ok {
|
||||
panic("improper handler type in map")
|
||||
}
|
||||
hndlr, _ := hmap.Get(cuid)
|
||||
stack = append(stack, execStack{hndlr, cuid})
|
||||
}
|
||||
}
|
||||
// Then external handlers.
|
||||
ehm, eok := c.external.cm.Get(command)
|
||||
hmap, eok := c.external.cm.Get(command)
|
||||
if eok {
|
||||
hmap := ehm.(cmap.ConcurrentMap)
|
||||
for _, cuid := range hmap.Keys() {
|
||||
if (strings.HasSuffix(cuid, ":bg") && !bg) || (!strings.HasSuffix(cuid, ":bg") && bg) {
|
||||
continue
|
||||
}
|
||||
hi, _ := hmap.Get(cuid)
|
||||
hndlr, ok := hi.(Handler)
|
||||
if !ok {
|
||||
panic("improper handler type in map")
|
||||
}
|
||||
hndlr, _ := hmap.Get(cuid)
|
||||
stack = append(stack, execStack{hndlr, cuid})
|
||||
}
|
||||
}
|
||||
@ -334,14 +324,12 @@ func (c *Caller) remove(cuid string) (ok bool) {
|
||||
}
|
||||
|
||||
// Check if the irc command/event has any handlers on it.
|
||||
var h interface{}
|
||||
h, ok = c.external.cm.Get(cmd)
|
||||
var hs cmap.ConcurrentMap[string, Handler]
|
||||
hs, ok = c.external.cm.Get(cmd)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
hs := h.(cmap.ConcurrentMap)
|
||||
|
||||
// Check to see if it's actually a registered handler.
|
||||
if _, ok = hs.Get(cuid); !ok {
|
||||
return
|
||||
@ -378,8 +366,7 @@ func (c *Caller) register(internal, bg bool, cmd string, handler Handler) (cuid
|
||||
|
||||
var (
|
||||
parent *nestedHandlers
|
||||
chandlers cmap.ConcurrentMap
|
||||
ei interface{}
|
||||
chandlers cmap.ConcurrentMap[string, Handler]
|
||||
ok bool
|
||||
)
|
||||
|
||||
@ -389,12 +376,10 @@ func (c *Caller) register(internal, bg bool, cmd string, handler Handler) (cuid
|
||||
parent = c.external
|
||||
}
|
||||
|
||||
ei, ok = parent.cm.Get(cmd)
|
||||
chandlers, ok = parent.cm.Get(cmd)
|
||||
|
||||
if ok {
|
||||
chandlers = ei.(cmap.ConcurrentMap)
|
||||
} else {
|
||||
chandlers = cmap.New()
|
||||
if !ok {
|
||||
chandlers = cmap.New[Handler]()
|
||||
}
|
||||
|
||||
chandlers.Set(uid, handler)
|
||||
@ -549,6 +534,8 @@ func (e *HandlerError) String() string {
|
||||
// DefaultRecoverHandler can be used with Config.RecoverFunc as a default
|
||||
// catch-all for panics. This will log the error, and the call trace to the
|
||||
// debug log (see Config.Debug), or os.Stdout if Config.Debug is unset.
|
||||
//
|
||||
//goland:noinspection GoUnusedExportedFunction
|
||||
func DefaultRecoverHandler(client *Client, err *HandlerError) {
|
||||
if client.Config.Debug == nil {
|
||||
fmt.Println(err.Error())
|
||||
|
52
modes.go
52
modes.go
@ -8,7 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
)
|
||||
|
||||
// CMode represents a single step of a given mode change.
|
||||
@ -119,13 +119,14 @@ func (c *CModes) Get(mode string) (args string, ok bool) {
|
||||
}
|
||||
|
||||
// hasArg checks to see if the mode supports arguments. What ones support this?:
|
||||
// A = Mode that adds or removes a nick or address to a list. Always has a parameter.
|
||||
// B = Mode that changes a setting and always has a parameter.
|
||||
// C = Mode that changes a setting and only has a parameter when set.
|
||||
// D = Mode that changes a setting and never has a parameter.
|
||||
// Note: Modes of type A return the list when there is no parameter present.
|
||||
// Note: Some clients assumes that any mode not listed is of type D.
|
||||
// Note: Modes in PREFIX are not listed but could be considered type B.
|
||||
//
|
||||
// A = Mode that adds or removes a nick or address to a list. Always has a parameter.
|
||||
// B = Mode that changes a setting and always has a parameter.
|
||||
// C = Mode that changes a setting and only has a parameter when set.
|
||||
// D = Mode that changes a setting and never has a parameter.
|
||||
// Note: Modes of type A return the list when there is no parameter present.
|
||||
// Note: Some clients assumes that any mode not listed is of type D.
|
||||
// Note: Modes in PREFIX are not listed but could be considered type B.
|
||||
func (c *CModes) hasArg(set bool, mode byte) (hasArgs, isSetting bool) {
|
||||
if len(c.raw) < 1 {
|
||||
return false, true
|
||||
@ -369,13 +370,9 @@ func handleMODE(c *Client, e Event) {
|
||||
// chanModes returns the ISUPPORT list of server-supported channel modes,
|
||||
// alternatively falling back to ModeDefaults.
|
||||
func (s *state) chanModes() string {
|
||||
if validmodes, ok := s.serverOptions.Get("CHANMODES"); ok {
|
||||
modes := validmodes.(string)
|
||||
if IsValidChannelMode(modes) {
|
||||
return modes
|
||||
}
|
||||
if validmodes, ok := s.serverOptions.Get("CHANMODES"); ok && IsValidChannelMode(validmodes) {
|
||||
return validmodes
|
||||
}
|
||||
|
||||
return ModeDefaults
|
||||
}
|
||||
|
||||
@ -383,26 +380,22 @@ func (s *state) chanModes() string {
|
||||
// This includes mode characters, as well as user prefix symbols. Falls back
|
||||
// to DefaultPrefixes if not server-supported.
|
||||
func (s *state) userPrefixes() string {
|
||||
if pi, ok := s.serverOptions.Get("PREFIX"); ok {
|
||||
prefix := pi.(string)
|
||||
if isValidUserPrefix(prefix) {
|
||||
return prefix
|
||||
}
|
||||
if prefix, ok := s.serverOptions.Get("PREFIX"); ok && isValidUserPrefix(prefix) {
|
||||
return prefix
|
||||
}
|
||||
|
||||
return DefaultPrefixes
|
||||
}
|
||||
|
||||
// UserPerms contains all of the permissions for each channel the user is
|
||||
// in.
|
||||
type UserPerms struct {
|
||||
channels cmap.ConcurrentMap
|
||||
channels cmap.ConcurrentMap[string, *Perms]
|
||||
}
|
||||
|
||||
// Copy returns a deep copy of the channel permissions.
|
||||
func (p *UserPerms) Copy() (perms *UserPerms) {
|
||||
np := &UserPerms{
|
||||
channels: cmap.New(),
|
||||
channels: cmap.New[*Perms](),
|
||||
}
|
||||
for tuple := range p.channels.IterBuffered() {
|
||||
np.channels.Set(tuple.Key, tuple.Val)
|
||||
@ -418,16 +411,11 @@ func (p *UserPerms) MarshalJSON() ([]byte, error) {
|
||||
|
||||
// Lookup looks up the users permissions for a given channel. ok is false
|
||||
// if the user is not in the given channel.
|
||||
func (p *UserPerms) Lookup(channel string) (perms Perms, ok bool) {
|
||||
var permsi interface{}
|
||||
permsi, ok = p.channels.Get(ToRFC1459(channel))
|
||||
if ok {
|
||||
perms = permsi.(Perms)
|
||||
}
|
||||
return perms, ok
|
||||
func (p *UserPerms) Lookup(channel string) (perms *Perms, ok bool) {
|
||||
return p.channels.Get(ToRFC1459(channel))
|
||||
}
|
||||
|
||||
func (p *UserPerms) set(channel string, perms Perms) {
|
||||
func (p *UserPerms) set(channel string, perms *Perms) {
|
||||
p.channels.Set(ToRFC1459(channel), perms)
|
||||
}
|
||||
|
||||
@ -458,7 +446,7 @@ type Perms struct {
|
||||
|
||||
// IsAdmin indicates that the user has banning abilities, and are likely a
|
||||
// very trustable user (e.g. op+).
|
||||
func (m Perms) IsAdmin() bool {
|
||||
func (m *Perms) IsAdmin() bool {
|
||||
if m.Owner || m.Admin || m.Op {
|
||||
return true
|
||||
}
|
||||
@ -468,7 +456,7 @@ func (m Perms) IsAdmin() bool {
|
||||
|
||||
// IsTrusted indicates that the user at least has modes set upon them, higher
|
||||
// than a regular joining user.
|
||||
func (m Perms) IsTrusted() bool {
|
||||
func (m *Perms) IsTrusted() bool {
|
||||
if m.IsAdmin() || m.HalfOp || m.Voice {
|
||||
return true
|
||||
}
|
||||
|
142
state.go
142
state.go
@ -10,7 +10,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
)
|
||||
|
||||
// state represents the actively-changing variables within the client
|
||||
@ -22,12 +22,13 @@ type state struct {
|
||||
nick, ident, host atomic.Value
|
||||
// channels represents all channels we're active in.
|
||||
// channels map[string]*Channel
|
||||
channels cmap.ConcurrentMap
|
||||
channels cmap.ConcurrentMap[string, *Channel]
|
||||
// users represents all of users that we're tracking.
|
||||
// users map[string]*User
|
||||
users cmap.ConcurrentMap
|
||||
users cmap.ConcurrentMap[string, *User]
|
||||
// enabledCap are the capabilities which are enabled for this connection.
|
||||
enabledCap map[string]map[string]string
|
||||
// enabledCap map[string]map[string]string
|
||||
enabledCap cmap.ConcurrentMap[string, map[string]string]
|
||||
// tmpCap are the capabilties which we share with the server during the
|
||||
// last capability check. These will get sent once we have received the
|
||||
// last capability list command from the server.
|
||||
@ -35,7 +36,8 @@ type state struct {
|
||||
// serverOptions are the standard capabilities and configurations
|
||||
// supported by the server at connection time. This also includes
|
||||
// RPL_ISUPPORT entries.
|
||||
serverOptions cmap.ConcurrentMap
|
||||
// serverOptions map[string]string
|
||||
serverOptions cmap.ConcurrentMap[string, string]
|
||||
|
||||
// network is an alternative way to store and retrieve the NETWORK server option.
|
||||
network atomic.Value
|
||||
@ -54,22 +56,31 @@ type state struct {
|
||||
sts strictTransport
|
||||
}
|
||||
|
||||
type Clearer interface {
|
||||
Clear()
|
||||
}
|
||||
|
||||
// reset resets the state back to it's original form.
|
||||
func (s *state) reset(initial bool) {
|
||||
s.nick.Store("")
|
||||
s.ident.Store("")
|
||||
s.host.Store("")
|
||||
s.network.Store("")
|
||||
var cmaps = []*cmap.ConcurrentMap{&s.channels, &s.users, &s.serverOptions}
|
||||
for _, cm := range cmaps {
|
||||
if initial {
|
||||
*cm = cmap.New()
|
||||
} else {
|
||||
var cmaps = []Clearer{&s.channels, &s.users, &s.serverOptions}
|
||||
for i, cm := range cmaps {
|
||||
switch {
|
||||
case i == 0 && initial:
|
||||
cm = cmap.New[*Channel]()
|
||||
case i == 1 && initial:
|
||||
cm = cmap.New[*User]()
|
||||
case i == 2 && initial:
|
||||
cm = cmap.New[string]()
|
||||
default:
|
||||
cm.Clear()
|
||||
}
|
||||
}
|
||||
|
||||
s.enabledCap = make(map[string]map[string]string)
|
||||
s.enabledCap = cmap.New[map[string]string]()
|
||||
s.tmpCap = make(map[string]map[string]string)
|
||||
s.motd = ""
|
||||
|
||||
@ -81,11 +92,11 @@ func (s *state) reset(initial bool) {
|
||||
// User represents an IRC user and the state attached to them.
|
||||
type User struct {
|
||||
// Nick is the users current nickname. rfc1459 compliant.
|
||||
Nick string `json:"nick"`
|
||||
Nick *MarshalableAtomicValue `json:"nick"`
|
||||
// Ident is the users username/ident. Ident is commonly prefixed with a
|
||||
// "~", which indicates that they do not have a identd server setup for
|
||||
// authentication.
|
||||
Ident string `json:"ident"`
|
||||
Ident *MarshalableAtomicValue `json:"ident"`
|
||||
// Host is the visible host of the users connection that the server has
|
||||
// provided to us for their connection. May not always be accurate due to
|
||||
// many networks spoofing/hiding parts of the hostname for privacy
|
||||
@ -93,7 +104,7 @@ type User struct {
|
||||
Host string `json:"host"`
|
||||
|
||||
// Mask is the combined Nick!Ident@Host of the given user.
|
||||
Mask string `json:"mask"`
|
||||
Mask *MarshalableAtomicValue `json:"mask"`
|
||||
|
||||
// Network is the name of the IRC network where this user was found.
|
||||
// This has been added for the purposes of girc being used in multi-client scenarios with data persistence.
|
||||
@ -106,8 +117,8 @@ type User struct {
|
||||
//
|
||||
// NOTE: If the ChannelList is empty for the user, then the user's info could be out of date.
|
||||
// turns out Concurrent-Map implements json.Marhsal!
|
||||
// https://github.com/orcaman/concurrent-map/blob/893feb299719d9cbb2cfbe08b6dd4eb567d8039d/concurrent_map.go#L305
|
||||
ChannelList cmap.ConcurrentMap `json:"channels"`
|
||||
// https://github.com/orcaman/concurrent-map/v2/blob/893feb299719d9cbb2cfbe08b6dd4eb567d8039d/concurrent_map.go#L305
|
||||
ChannelList cmap.ConcurrentMap[string, *Channel] `json:"channels"`
|
||||
|
||||
// FirstSeen represents the first time that the user was seen by the
|
||||
// client for the given channel. Only usable if from state, not in past.
|
||||
@ -144,7 +155,7 @@ type User struct {
|
||||
}
|
||||
|
||||
// Channels returns a slice of pointers to Channel types that the client knows the user is in.
|
||||
func (u User) Channels(c *Client) []*Channel {
|
||||
func (u *User) Channels(c *Client) []*Channel {
|
||||
if c == nil {
|
||||
panic("nil Client provided")
|
||||
}
|
||||
@ -152,8 +163,8 @@ func (u User) Channels(c *Client) []*Channel {
|
||||
var channels []*Channel
|
||||
|
||||
for listed := range u.ChannelList.IterBuffered() {
|
||||
chn, chok := listed.Val.(*Channel)
|
||||
if chok {
|
||||
chn := listed.Val
|
||||
if chn != nil {
|
||||
channels = append(channels, chn)
|
||||
continue
|
||||
}
|
||||
@ -178,7 +189,9 @@ func (u *User) Copy() *User {
|
||||
*nu = *u
|
||||
|
||||
nu.Perms = u.Perms.Copy()
|
||||
_ = copy(nu.ChannelList, u.ChannelList)
|
||||
for ch := range u.ChannelList.IterBuffered() {
|
||||
nu.ChannelList.Set(ch.Key, ch.Val)
|
||||
}
|
||||
|
||||
return nu
|
||||
}
|
||||
@ -197,7 +210,7 @@ func (u *User) addChannel(name string, chn *Channel) {
|
||||
|
||||
u.ChannelList.Set(name, chn)
|
||||
|
||||
u.Perms.set(name, Perms{})
|
||||
u.Perms.set(name, &Perms{})
|
||||
}
|
||||
|
||||
// deleteChannel removes an existing channel from the users channel list.
|
||||
@ -246,7 +259,7 @@ type Channel struct {
|
||||
Created string `json:"created"`
|
||||
// UserList is a sorted list of all users we are currently tracking within
|
||||
// the channel. Each is the1 nickname, and is rfc1459 compliant.
|
||||
UserList cmap.ConcurrentMap `json:"user_list"`
|
||||
UserList cmap.ConcurrentMap[string, *User] `json:"user_list"`
|
||||
// Network is the name of the IRC network where this channel was found.
|
||||
// This has been added for the purposes of girc being used in multi-client scenarios with data persistence.
|
||||
Network string `json:"network"`
|
||||
@ -258,7 +271,7 @@ type Channel struct {
|
||||
|
||||
// Users returns a reference of *Users that the client knows the channel has
|
||||
// If you're just looking for just the name of the users, use Channnel.UserList.
|
||||
func (ch Channel) Users(c *Client) []*User {
|
||||
func (ch *Channel) Users(c *Client) []*User {
|
||||
if c == nil {
|
||||
panic("nil Client provided")
|
||||
}
|
||||
@ -278,7 +291,7 @@ func (ch Channel) Users(c *Client) []*User {
|
||||
|
||||
// Trusted returns a list of users which have voice or greater in the given
|
||||
// channel. See Perms.IsTrusted() for more information.
|
||||
func (ch Channel) Trusted(c *Client) []*User {
|
||||
func (ch *Channel) Trusted(c *Client) []*User {
|
||||
if c == nil {
|
||||
panic("nil Client provided")
|
||||
}
|
||||
@ -303,7 +316,7 @@ func (ch Channel) Trusted(c *Client) []*User {
|
||||
// Admins returns a list of users which have half-op (if supported), or
|
||||
// greater permissions (op, admin, owner, etc) in the given channel. See
|
||||
// Perms.IsAdmin() for more information.
|
||||
func (ch Channel) Admins(c *Client) []*User {
|
||||
func (ch *Channel) Admins(c *Client) []*User {
|
||||
if c == nil {
|
||||
panic("nil Client provided")
|
||||
}
|
||||
@ -312,19 +325,17 @@ func (ch Channel) Admins(c *Client) []*User {
|
||||
|
||||
for listed := range ch.UserList.IterBuffered() {
|
||||
ui := listed.Val
|
||||
user, usrok := ui.(*User)
|
||||
if !usrok {
|
||||
user = c.state.lookupUser(listed.Key)
|
||||
if user == nil {
|
||||
|
||||
if ui == nil {
|
||||
if ui = c.state.lookupUser(listed.Key); ui == nil {
|
||||
continue
|
||||
} else {
|
||||
ch.UserList.Set(listed.Key, user)
|
||||
}
|
||||
ch.UserList.Set(listed.Key, ui)
|
||||
}
|
||||
|
||||
perms, ok := user.Perms.Lookup(ch.Name)
|
||||
perms, ok := ui.Perms.Lookup(ch.Name)
|
||||
if ok && perms.IsAdmin() {
|
||||
users = append(users, user)
|
||||
users = append(users, ui)
|
||||
}
|
||||
}
|
||||
|
||||
@ -354,7 +365,9 @@ func (ch *Channel) Copy() *Channel {
|
||||
nc := &Channel{}
|
||||
*nc = *ch
|
||||
|
||||
_ = copy(nc.UserList, ch.UserList)
|
||||
for v := range ch.UserList.IterBuffered() {
|
||||
nc.UserList.Set(v.Val.Nick.Load().(string), v.Val)
|
||||
}
|
||||
|
||||
// And modes.
|
||||
nc.Modes = ch.Modes.Copy()
|
||||
@ -391,7 +404,7 @@ func (s *state) createChannel(name string) (ok bool) {
|
||||
|
||||
s.channels.Set(ToRFC1459(name), &Channel{
|
||||
Name: name,
|
||||
UserList: cmap.New(),
|
||||
UserList: cmap.New[*User](),
|
||||
Joined: time.Now(),
|
||||
Network: s.client.NetworkName(),
|
||||
Modes: NewCModes(supported, prefixes),
|
||||
@ -404,17 +417,14 @@ func (s *state) createChannel(name string) (ok bool) {
|
||||
func (s *state) deleteChannel(name string) {
|
||||
name = ToRFC1459(name)
|
||||
|
||||
c, ok := s.channels.Get(name)
|
||||
chn, ok := s.channels.Get(name)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
chn := c.(*Channel)
|
||||
|
||||
for listed := range chn.UserList.IterBuffered() {
|
||||
ui, _ := s.users.Get(listed.Key)
|
||||
usr, usrok := ui.(*User)
|
||||
if usrok {
|
||||
usr, uok := s.users.Get(listed.Key)
|
||||
if uok {
|
||||
usr.deleteChannel(name)
|
||||
}
|
||||
}
|
||||
@ -426,42 +436,55 @@ func (s *state) deleteChannel(name string) {
|
||||
// found.
|
||||
func (s *state) lookupChannel(name string) *Channel {
|
||||
ci, cok := s.channels.Get(ToRFC1459(name))
|
||||
chn, ok := ci.(*Channel)
|
||||
if !ok || !cok {
|
||||
if ci == nil || !cok {
|
||||
return nil
|
||||
}
|
||||
return chn
|
||||
return ci
|
||||
}
|
||||
|
||||
// lookupUser returns a reference to a user, nil returned if no results
|
||||
// found.
|
||||
func (s *state) lookupUser(name string) *User {
|
||||
ui, uok := s.users.Get(ToRFC1459(name))
|
||||
usr, ok := ui.(*User)
|
||||
if !ok || !uok {
|
||||
usr, uok := s.users.Get(ToRFC1459(name))
|
||||
if usr == nil || !uok {
|
||||
return nil
|
||||
}
|
||||
return usr
|
||||
}
|
||||
|
||||
func (s *state) createUser(src *Source) (u *User, ok bool) {
|
||||
if _, ok := s.users.Get(src.ID()); ok {
|
||||
if u, ok = s.users.Get(src.ID()); ok {
|
||||
// User already exists.
|
||||
return nil, false
|
||||
return u, false
|
||||
}
|
||||
|
||||
mask := strs.Get()
|
||||
if src.Name != "" {
|
||||
mask.MustWriteString(src.Name)
|
||||
}
|
||||
_ = mask.WriteByte('!')
|
||||
if src.Ident != "" {
|
||||
mask.MustWriteString(src.Ident)
|
||||
}
|
||||
_ = mask.WriteByte('@')
|
||||
if src.Host != "" {
|
||||
mask.MustWriteString(src.Host)
|
||||
}
|
||||
|
||||
u = &User{
|
||||
Nick: src.Name,
|
||||
Nick: NewAtomicString(src.Name),
|
||||
Host: src.Host,
|
||||
Ident: src.Ident,
|
||||
Mask: src.Name + "!" + src.Ident + "@" + src.Host,
|
||||
ChannelList: cmap.New(),
|
||||
Ident: NewAtomicString(src.Ident),
|
||||
Mask: NewAtomicString(mask.String()),
|
||||
ChannelList: cmap.New[*Channel](),
|
||||
FirstSeen: time.Now(),
|
||||
LastActive: time.Now(),
|
||||
Network: s.client.NetworkName(),
|
||||
Perms: &UserPerms{channels: cmap.New()},
|
||||
Perms: &UserPerms{channels: cmap.New[*Perms]()},
|
||||
}
|
||||
|
||||
strs.MustPut(mask)
|
||||
|
||||
s.users.Set(src.ID(), u)
|
||||
return u, true
|
||||
}
|
||||
@ -512,20 +535,19 @@ func (s *state) renameUser(from, to string) {
|
||||
}
|
||||
|
||||
if old != nil && user == nil {
|
||||
user = old.(*User)
|
||||
user = old
|
||||
}
|
||||
|
||||
user.Nick = to
|
||||
user.Nick.Store(to)
|
||||
user.LastActive = time.Now()
|
||||
s.users.Set(ToRFC1459(to), user)
|
||||
|
||||
for chanchan := range s.channels.IterBuffered() {
|
||||
chi := chanchan.Val
|
||||
chn, chok := chi.(*Channel)
|
||||
if !chok {
|
||||
chn := chanchan.Val
|
||||
if chn == nil {
|
||||
continue
|
||||
}
|
||||
if old, oldok := chn.UserList.Pop(from); oldok {
|
||||
if old, oldok = chn.UserList.Pop(from); oldok {
|
||||
chn.UserList.Set(to, old)
|
||||
}
|
||||
}
|
||||
|
@ -123,7 +123,7 @@ func TestState(t *testing.T) {
|
||||
|
||||
fullUsers := c.Users()
|
||||
for i := 0; i < len(fullUsers); i++ {
|
||||
if fullUsers[i].Nick != users[i] {
|
||||
if fullUsers[i].Nick.Load().(string) != users[i] {
|
||||
t.Errorf("fullUsers nick doesn't map to same nick in UsersList: %q :: %#v", fullUsers[i].Nick, users)
|
||||
return
|
||||
}
|
||||
@ -136,14 +136,14 @@ func TestState(t *testing.T) {
|
||||
}
|
||||
|
||||
adm := ch.Admins(c)
|
||||
admList := []string{}
|
||||
var admList []string
|
||||
for i := 0; i < len(adm); i++ {
|
||||
admList = append(admList, adm[i].Nick)
|
||||
admList = append(admList, adm[i].Nick.Load().(string))
|
||||
}
|
||||
trusted := ch.Trusted(c)
|
||||
trustedList := []string{}
|
||||
var trustedList []string
|
||||
for i := 0; i < len(trusted); i++ {
|
||||
trustedList = append(trustedList, trusted[i].Nick)
|
||||
trustedList = append(trustedList, trusted[i].Nick.Load().(string))
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(admList, []string{"nick2"}) {
|
||||
@ -213,7 +213,7 @@ func TestState(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
if user.Nick != "fhjones" {
|
||||
if user.Nick.Load().(string) != "fhjones" {
|
||||
t.Errorf("User.Nick == %q, wanted \"nick\"", user.Nick)
|
||||
return
|
||||
}
|
||||
@ -228,7 +228,7 @@ func TestState(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
if user.Ident != "~user" {
|
||||
if user.Ident.Load().(string) != "~user" {
|
||||
t.Errorf("User.Ident == %q, wanted \"~user\"", user.Ident)
|
||||
return
|
||||
}
|
||||
@ -250,7 +250,9 @@ func TestState(t *testing.T) {
|
||||
bounceStart <- true
|
||||
})
|
||||
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := conn.Write([]byte(mockConnStartState))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@ -282,10 +284,9 @@ func TestState(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
chi, chnok := user.ChannelList.Get("#channel")
|
||||
chn, chiok := chi.(*Channel)
|
||||
chn, chnok := user.ChannelList.Get("#channel")
|
||||
|
||||
if !chnok || !chiok {
|
||||
if !chnok {
|
||||
t.Errorf("should have been able to get a pointer by looking up #channel")
|
||||
return
|
||||
}
|
||||
@ -295,8 +296,7 @@ func TestState(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
chi2, _ := user.ChannelList.Get("#channel2")
|
||||
chn2, _ := chi2.(*Channel)
|
||||
chn2, _ := user.ChannelList.Get("#channel2")
|
||||
|
||||
if chn2.Len() != len([]string{"notjones"}) {
|
||||
t.Errorf("channel.UserList.Count() == %d, wanted %d",
|
||||
@ -316,7 +316,9 @@ func TestState(t *testing.T) {
|
||||
bounceEnd <- true
|
||||
})
|
||||
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if err = conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = conn.Write([]byte(mockConnEndState))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
11
util.go
11
util.go
@ -1,11 +0,0 @@
|
||||
package girc
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func randSleep() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
time.Sleep(time.Duration(rand.Intn(25)) * time.Millisecond)
|
||||
}
|
29
value.go
Normal file
29
value.go
Normal file
@ -0,0 +1,29 @@
|
||||
package girc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type MarshalableAtomicValue struct {
|
||||
*atomic.Value
|
||||
}
|
||||
|
||||
func (m *MarshalableAtomicValue) MarshalJSON() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf("%v", m.Value.Load())), nil
|
||||
}
|
||||
|
||||
func (m *MarshalableAtomicValue) UnmarshalJSON(b []byte) error {
|
||||
m.Value.Store(string(b))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MarshalableAtomicValue) String() string {
|
||||
return m.Value.Load().(string)
|
||||
}
|
||||
|
||||
func NewAtomicString(s string) *MarshalableAtomicValue {
|
||||
obj := &atomic.Value{}
|
||||
obj.Store(s)
|
||||
return &MarshalableAtomicValue{Value: obj}
|
||||
}
|
Loading…
Reference in New Issue
Block a user