soju/irc.go

281 lines
6.4 KiB
Go
Raw Normal View History

2020-03-13 17:13:03 +00:00
package soju
2020-02-06 18:24:32 +00:00
import (
"fmt"
"strings"
2021-03-27 12:08:31 +00:00
"time"
2021-04-13 16:54:58 +00:00
"unicode"
"unicode/utf8"
2020-02-07 11:36:02 +00:00
2022-11-14 11:06:58 +00:00
"gopkg.in/irc.v4"
2022-05-09 10:34:43 +00:00
2022-05-09 14:15:00 +00:00
"git.sr.ht/~emersion/soju/xirc"
2020-02-06 18:24:32 +00:00
)
2022-05-09 14:15:00 +00:00
// TODO: generalize and move helpers to the xirc package
type userModes string
2020-02-06 18:24:32 +00:00
func (ms userModes) Has(c byte) bool {
2020-02-06 18:24:32 +00:00
return strings.IndexByte(string(ms), c) >= 0
}
func (ms *userModes) Add(c byte) {
2020-02-06 18:24:32 +00:00
if !ms.Has(c) {
*ms += userModes(c)
2020-02-06 18:24:32 +00:00
}
}
func (ms *userModes) Del(c byte) {
2020-02-06 18:24:32 +00:00
i := strings.IndexByte(string(*ms), c)
if i >= 0 {
*ms = (*ms)[:i] + (*ms)[i+1:]
}
}
func (ms *userModes) Apply(s string) error {
2020-02-06 18:24:32 +00:00
var plusMinus byte
for i := 0; i < len(s); i++ {
switch c := s[i]; c {
case '+', '-':
plusMinus = c
default:
switch plusMinus {
case '+':
ms.Add(c)
case '-':
ms.Del(c)
default:
return fmt.Errorf("malformed modestring %q: missing plus/minus", s)
}
}
}
return nil
}
type channelModeType byte
// standard channel mode types, as explained in https://modern.ircdocs.horse/#mode-message
const (
// modes that add or remove an address to or from a list
modeTypeA channelModeType = iota
// modes that change a setting on a channel, and must always have a parameter
modeTypeB
// modes that change a setting on a channel, and must have a parameter when being set, and no parameter when being unset
modeTypeC
// modes that change a setting on a channel, and must not have a parameter
modeTypeD
)
var stdChannelModes = map[byte]channelModeType{
'b': modeTypeA, // ban list
'e': modeTypeA, // ban exception list
'I': modeTypeA, // invite exception list
'k': modeTypeB, // channel key
'l': modeTypeC, // channel user limit
'i': modeTypeD, // channel is invite-only
'm': modeTypeD, // channel is moderated
'n': modeTypeD, // channel has no external messages
's': modeTypeD, // channel is secret
't': modeTypeD, // channel has protected topic
}
type channelModes map[byte]string
// applyChannelModes parses a mode string and mode arguments from a MODE message,
// and applies the corresponding channel mode and user membership changes on that channel.
//
// If ch.modes is nil, channel modes are not updated.
func applyChannelModes(ch *upstreamChannel, modeStr string, arguments []string) error {
nextArgument := 0
var plusMinus byte
outer:
for i := 0; i < len(modeStr); i++ {
mode := modeStr[i]
if mode == '+' || mode == '-' {
plusMinus = mode
continue
}
if plusMinus != '+' && plusMinus != '-' {
return fmt.Errorf("malformed modestring %q: missing plus/minus", modeStr)
}
for _, membership := range ch.conn.availableMemberships {
if membership.Mode == mode {
if nextArgument >= len(arguments) {
return fmt.Errorf("malformed modestring %q: missing mode argument for %c%c", modeStr, plusMinus, mode)
}
member := arguments[nextArgument]
m := ch.Members.Get(member)
Implement casemapping TL;DR: supports for casemapping, now logs are saved in casemapped/canonical/tolower form (eg. in the #channel directory instead of #Channel... or something) == What is casemapping? == see <https://modern.ircdocs.horse/#casemapping-parameter> == Casemapping and multi-upstream == Since each upstream does not necessarily use the same casemapping, and since casemappings cannot coexist [0], 1. soju must also update the database accordingly to upstreams' casemapping, otherwise it will end up inconsistent, 2. soju must "normalize" entity names and expose only one casemapping that is a subset of all supported casemappings (here, ascii). [0] On some upstreams, "emersion[m]" and "emersion{m}" refer to the same user (upstreams that advertise rfc1459 for example), while on others (upstreams that advertise ascii) they don't. Once upstream's casemapping is known (default to rfc1459), entity names in map keys are made into casemapped form, for upstreamConn, upstreamChannel and network. downstreamConn advertises "CASEMAPPING=ascii", and always casemap map keys with ascii. Some functions require the caller to casemap their argument (to avoid needless calls to casemapping functions). == Message forwarding and casemapping == downstream message handling (joins and parts basically): When relaying entity names from downstreams to upstreams, soju uses the upstream casemapping, in order to not get in the way of the user. This does not brings any issue, as long as soju replies with the ascii casemapping in mind (solves point 1.). marshalEntity/marshalUserPrefix: When relaying entity names from upstreams with non-ascii casemappings, soju *partially* casemap them: it only change the case of characters which are not ascii letters. ASCII case is thus kept intact, while special symbols like []{} are the same every time soju sends them to downstreams (solves point 2.). == Casemapping changes == Casemapping changes are not fully supported by this patch and will result in loss of history. This is a limitation of the protocol and should be solved by the RENAME spec.
2021-03-16 09:00:34 +00:00
if m != nil {
if plusMinus == '+' {
Implement casemapping TL;DR: supports for casemapping, now logs are saved in casemapped/canonical/tolower form (eg. in the #channel directory instead of #Channel... or something) == What is casemapping? == see <https://modern.ircdocs.horse/#casemapping-parameter> == Casemapping and multi-upstream == Since each upstream does not necessarily use the same casemapping, and since casemappings cannot coexist [0], 1. soju must also update the database accordingly to upstreams' casemapping, otherwise it will end up inconsistent, 2. soju must "normalize" entity names and expose only one casemapping that is a subset of all supported casemappings (here, ascii). [0] On some upstreams, "emersion[m]" and "emersion{m}" refer to the same user (upstreams that advertise rfc1459 for example), while on others (upstreams that advertise ascii) they don't. Once upstream's casemapping is known (default to rfc1459), entity names in map keys are made into casemapped form, for upstreamConn, upstreamChannel and network. downstreamConn advertises "CASEMAPPING=ascii", and always casemap map keys with ascii. Some functions require the caller to casemap their argument (to avoid needless calls to casemapping functions). == Message forwarding and casemapping == downstream message handling (joins and parts basically): When relaying entity names from downstreams to upstreams, soju uses the upstream casemapping, in order to not get in the way of the user. This does not brings any issue, as long as soju replies with the ascii casemapping in mind (solves point 1.). marshalEntity/marshalUserPrefix: When relaying entity names from upstreams with non-ascii casemappings, soju *partially* casemap them: it only change the case of characters which are not ascii letters. ASCII case is thus kept intact, while special symbols like []{} are the same every time soju sends them to downstreams (solves point 2.). == Casemapping changes == Casemapping changes are not fully supported by this patch and will result in loss of history. This is a limitation of the protocol and should be solved by the RENAME spec.
2021-03-16 09:00:34 +00:00
m.Add(ch.conn.availableMemberships, membership)
} else {
// TODO: for upstreams without multi-prefix, query the user modes again
Implement casemapping TL;DR: supports for casemapping, now logs are saved in casemapped/canonical/tolower form (eg. in the #channel directory instead of #Channel... or something) == What is casemapping? == see <https://modern.ircdocs.horse/#casemapping-parameter> == Casemapping and multi-upstream == Since each upstream does not necessarily use the same casemapping, and since casemappings cannot coexist [0], 1. soju must also update the database accordingly to upstreams' casemapping, otherwise it will end up inconsistent, 2. soju must "normalize" entity names and expose only one casemapping that is a subset of all supported casemappings (here, ascii). [0] On some upstreams, "emersion[m]" and "emersion{m}" refer to the same user (upstreams that advertise rfc1459 for example), while on others (upstreams that advertise ascii) they don't. Once upstream's casemapping is known (default to rfc1459), entity names in map keys are made into casemapped form, for upstreamConn, upstreamChannel and network. downstreamConn advertises "CASEMAPPING=ascii", and always casemap map keys with ascii. Some functions require the caller to casemap their argument (to avoid needless calls to casemapping functions). == Message forwarding and casemapping == downstream message handling (joins and parts basically): When relaying entity names from downstreams to upstreams, soju uses the upstream casemapping, in order to not get in the way of the user. This does not brings any issue, as long as soju replies with the ascii casemapping in mind (solves point 1.). marshalEntity/marshalUserPrefix: When relaying entity names from upstreams with non-ascii casemappings, soju *partially* casemap them: it only change the case of characters which are not ascii letters. ASCII case is thus kept intact, while special symbols like []{} are the same every time soju sends them to downstreams (solves point 2.). == Casemapping changes == Casemapping changes are not fully supported by this patch and will result in loss of history. This is a limitation of the protocol and should be solved by the RENAME spec.
2021-03-16 09:00:34 +00:00
m.Remove(membership)
}
}
nextArgument++
continue outer
}
}
mt, ok := ch.conn.availableChannelModes[mode]
if !ok {
continue
}
if mt == modeTypeA {
nextArgument++
} else if mt == modeTypeB || (mt == modeTypeC && plusMinus == '+') {
if plusMinus == '+' {
var argument string
// some sentitive arguments (such as channel keys) can be omitted for privacy
// (this will only happen for RPL_CHANNELMODEIS, never for MODE messages)
if nextArgument < len(arguments) {
argument = arguments[nextArgument]
}
if ch.modes != nil {
ch.modes[mode] = argument
}
} else {
delete(ch.modes, mode)
}
nextArgument++
} else if mt == modeTypeC || mt == modeTypeD {
if plusMinus == '+' {
if ch.modes != nil {
ch.modes[mode] = ""
}
} else {
delete(ch.modes, mode)
}
}
}
return nil
}
func (cm channelModes) Format() (modeString string, parameters []string) {
var modesWithValues strings.Builder
var modesWithoutValues strings.Builder
parameters = make([]string, 0, 16)
for mode, value := range cm {
if value != "" {
modesWithValues.WriteString(string(mode))
parameters = append(parameters, value)
} else {
modesWithoutValues.WriteString(string(mode))
}
}
modeString = "+" + modesWithValues.String() + modesWithoutValues.String()
return
}
const stdChannelTypes = "#&+!"
2022-05-30 07:12:28 +00:00
var stdMemberships = []xirc.Membership{
{'q', '~'}, // founder
{'a', '&'}, // protected
{'o', '@'}, // operator
{'h', '%'}, // halfop
{'v', '+'}, // voice
2020-03-20 01:15:23 +00:00
}
2022-05-30 07:12:28 +00:00
func formatMemberPrefix(ms xirc.MembershipSet, dc *downstreamConn) string {
2022-03-14 18:15:17 +00:00
if !dc.caps.IsEnabled("multi-prefix") {
2022-05-30 07:12:28 +00:00
if len(ms) == 0 {
return ""
}
2022-05-30 07:12:28 +00:00
return string(ms[0].Prefix)
}
2022-05-30 07:12:28 +00:00
prefixes := make([]byte, len(ms))
for i, m := range ms {
prefixes[i] = m.Prefix
2020-02-06 18:24:32 +00:00
}
return string(prefixes)
2020-02-06 18:24:32 +00:00
}
2020-02-07 11:36:02 +00:00
func parseMessageParams(msg *irc.Message, out ...*string) error {
if len(msg.Params) < len(out) {
return newNeedMoreParamsError(msg.Command)
}
for i := range out {
if out[i] != nil {
*out[i] = msg.Params[i]
}
}
return nil
}
2020-03-23 02:18:16 +00:00
func copyClientTags(tags irc.Tags) irc.Tags {
t := make(irc.Tags, len(tags))
for k, v := range tags {
if strings.HasPrefix(k, "+") {
t[k] = v
}
}
return t
}
2023-03-01 12:30:47 +00:00
var stdCaseMapping = xirc.CaseMappingRFC1459
Implement casemapping TL;DR: supports for casemapping, now logs are saved in casemapped/canonical/tolower form (eg. in the #channel directory instead of #Channel... or something) == What is casemapping? == see <https://modern.ircdocs.horse/#casemapping-parameter> == Casemapping and multi-upstream == Since each upstream does not necessarily use the same casemapping, and since casemappings cannot coexist [0], 1. soju must also update the database accordingly to upstreams' casemapping, otherwise it will end up inconsistent, 2. soju must "normalize" entity names and expose only one casemapping that is a subset of all supported casemappings (here, ascii). [0] On some upstreams, "emersion[m]" and "emersion{m}" refer to the same user (upstreams that advertise rfc1459 for example), while on others (upstreams that advertise ascii) they don't. Once upstream's casemapping is known (default to rfc1459), entity names in map keys are made into casemapped form, for upstreamConn, upstreamChannel and network. downstreamConn advertises "CASEMAPPING=ascii", and always casemap map keys with ascii. Some functions require the caller to casemap their argument (to avoid needless calls to casemapping functions). == Message forwarding and casemapping == downstream message handling (joins and parts basically): When relaying entity names from downstreams to upstreams, soju uses the upstream casemapping, in order to not get in the way of the user. This does not brings any issue, as long as soju replies with the ascii casemapping in mind (solves point 1.). marshalEntity/marshalUserPrefix: When relaying entity names from upstreams with non-ascii casemappings, soju *partially* casemap them: it only change the case of characters which are not ascii letters. ASCII case is thus kept intact, while special symbols like []{} are the same every time soju sends them to downstreams (solves point 2.). == Casemapping changes == Casemapping changes are not fully supported by this patch and will result in loss of history. This is a limitation of the protocol and should be solved by the RENAME spec.
2021-03-16 09:00:34 +00:00
2021-04-13 16:54:58 +00:00
func isWordBoundary(r rune) bool {
switch r {
2022-02-25 10:32:09 +00:00
case '-', '_', '|': // inspired from weechat.look.highlight_regex
2021-04-13 16:54:58 +00:00
return false
default:
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
}
}
func isHighlight(text, nick string) bool {
if len(nick) == 0 {
panic("isHighlight called with empty nick")
}
2021-04-13 16:54:58 +00:00
for {
i := strings.Index(text, nick)
if i < 0 {
return false
}
2022-02-25 10:32:09 +00:00
left, _ := utf8.DecodeLastRuneInString(text[:i])
right, _ := utf8.DecodeRuneInString(text[i+len(nick):])
2021-04-13 16:54:58 +00:00
if isWordBoundary(left) && isWordBoundary(right) {
return true
}
text = text[i+len(nick):]
}
}
2021-03-27 12:08:31 +00:00
// parseChatHistoryBound parses the given CHATHISTORY parameter as a bound.
// The zero time is returned on error.
func parseChatHistoryBound(param string) time.Time {
parts := strings.SplitN(param, "=", 2)
if len(parts) != 2 {
return time.Time{}
}
switch parts[0] {
case "timestamp":
2022-05-09 14:15:00 +00:00
timestamp, err := time.Parse(xirc.ServerTimeLayout, parts[1])
2021-03-27 12:08:31 +00:00
if err != nil {
return time.Time{}
}
return timestamp
default:
return time.Time{}
}
}
func isNumeric(cmd string) bool {
if len(cmd) != 3 {
return false
}
for i := 0; i < 3; i++ {
if cmd[i] < '0' || cmd[i] > '9' {
return false
}
}
return true
}