3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-24 21:09:30 +01:00
ergo/irc/services.go

389 lines
12 KiB
Go
Raw Normal View History

2018-04-19 08:48:19 +02:00
// Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package irc
import (
"bytes"
2018-04-19 08:48:19 +02:00
"fmt"
"log"
2018-04-19 08:48:19 +02:00
"sort"
"strings"
"time"
2018-04-19 08:48:19 +02:00
2021-05-25 06:34:38 +02:00
"github.com/ergochat/ergo/irc/utils"
"github.com/ergochat/irc-go/ircfmt"
"github.com/ergochat/irc-go/ircmsg"
2018-04-19 08:48:19 +02:00
)
// defines an IRC service, e.g., NICKSERV
type ircService struct {
Name string
ShortName string
prefix string // NUH source of messages from this service
2018-04-19 08:48:19 +02:00
CommandAliases []string
Commands map[string]*serviceCommand
HelpBanner string
}
func (service *ircService) Realname(client *Client) string {
return fmt.Sprintf(client.t("Network service, for more info /msg %s HELP"), service.Name)
}
2018-04-19 08:48:19 +02:00
// defines a command associated with a service, e.g., NICKSERV IDENTIFY
type serviceCommand struct {
2019-05-29 10:25:20 +02:00
aliasOf string // marks this command as an alias of another
capabs []string // oper capabs the given user has to have to access this command
handler func(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer)
2019-05-29 10:25:20 +02:00
help string
helpStrings []string
helpShort string
enabled func(*Config) bool // is this command enabled in the server config?
authRequired bool
hidden bool
minParams int
maxParams int // optional, if set it's an error if the user passes more than this many params
unsplitFinalParam bool // split into at most maxParams, with last param containing unsplit text
2018-04-19 08:48:19 +02:00
}
// looks up a command in the table of command definitions for a service, resolving aliases
func lookupServiceCommand(commands map[string]*serviceCommand, command string) *serviceCommand {
maxDepth := 1
depth := 0
for depth <= maxDepth {
result, ok := commands[command]
if !ok {
return nil
} else if result.aliasOf == "" {
return result
} else {
command = result.aliasOf
depth += 1
}
}
return nil
}
var (
nickservService = &ircService{
2018-04-19 08:48:19 +02:00
Name: "NickServ",
ShortName: "NS",
CommandAliases: []string{"NICKSERV", "NS"},
Commands: nickservCommands,
HelpBanner: nickservHelp,
}
chanservService = &ircService{
2018-04-19 08:48:19 +02:00
Name: "ChanServ",
ShortName: "CS",
CommandAliases: []string{"CHANSERV", "CS"},
Commands: chanservCommands,
HelpBanner: chanservHelp,
}
hostservService = &ircService{
2018-04-19 08:48:19 +02:00
Name: "HostServ",
ShortName: "HS",
CommandAliases: []string{"HOSTSERV", "HS"},
Commands: hostservCommands,
HelpBanner: hostservHelp,
}
histservService = &ircService{
2020-05-12 18:05:40 +02:00
Name: "HistServ",
ShortName: "HISTSERV",
CommandAliases: []string{"HISTSERV"},
Commands: histservCommands,
HelpBanner: histservHelp,
}
)
// all services, by lowercase name
var ErgoServices = map[string]*ircService{
"nickserv": nickservService,
"chanserv": chanservService,
"hostserv": hostservService,
"histserv": histservService,
}
func (service *ircService) Notice(rb *ResponseBuffer, text string) {
rb.Add(nil, service.prefix, "NOTICE", rb.target.Nick(), text)
2018-04-19 08:48:19 +02:00
}
// all service commands at the protocol level, by uppercase command name
// e.g., NICKSERV, NS
var ergoServicesByCommandAlias map[string]*ircService
2018-04-19 08:48:19 +02:00
// special-cased command shared by all services
var servHelpCmd serviceCommand = serviceCommand{
help: `Syntax: $bHELP [command]$b
HELP returns information on the given command.`,
helpShort: `$bHELP$b shows in-depth information about commands.`,
}
2019-01-04 04:32:07 +01:00
// generic handler for IRC commands like `/NICKSERV INFO`
2021-03-11 02:07:43 +01:00
func serviceCmdHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
service, ok := ergoServicesByCommandAlias[msg.Command]
2018-04-19 08:48:19 +02:00
if !ok {
server.logger.Warning("internal", "can't handle unrecognized service", msg.Command)
return false
}
if len(msg.Params) == 0 {
return false
}
commandName := strings.ToLower(msg.Params[0])
params := msg.Params[1:]
cmd := lookupServiceCommand(service.Commands, commandName)
// for a maxParams command, join all final parameters together if necessary
2019-05-29 10:25:20 +02:00
if cmd != nil && cmd.unsplitFinalParam && cmd.maxParams < len(params) {
newParams := make([]string, cmd.maxParams)
copy(newParams, params[:cmd.maxParams-1])
newParams[cmd.maxParams-1] = strings.Join(params[cmd.maxParams-1:], " ")
params = newParams
}
serviceRunCommand(service, server, client, cmd, commandName, params, rb)
2018-04-19 08:48:19 +02:00
return false
}
2019-01-04 04:32:07 +01:00
// generic handler for service PRIVMSG, like `/msg NickServ INFO`
2018-04-19 08:48:19 +02:00
func servicePrivmsgHandler(service *ircService, server *Server, client *Client, message string, rb *ResponseBuffer) {
if strings.HasPrefix(message, "\x01") {
serviceCTCPHandler(service, client, message)
return
}
params := strings.Fields(message)
2019-01-04 04:32:07 +01:00
if len(params) == 0 {
return
}
// look up the service command to see how to parse it
2019-01-04 04:32:07 +01:00
commandName := strings.ToLower(params[0])
cmd := lookupServiceCommand(service.Commands, commandName)
// reparse if needed
2019-05-29 10:25:20 +02:00
if cmd != nil && cmd.unsplitFinalParam {
params = utils.FieldsN(message, cmd.maxParams+1)[1:]
} else {
params = params[1:]
}
serviceRunCommand(service, server, client, cmd, commandName, params, rb)
}
2018-04-19 08:48:19 +02:00
func serviceCTCPHandler(service *ircService, client *Client, message string) {
ctcp := strings.TrimSuffix(message[1:], "\x01")
ctcpSplit := utils.FieldsN(ctcp, 2)
ctcpCmd := strings.ToUpper(ctcpSplit[0])
ctcpOut := ""
switch ctcpCmd {
case "VERSION":
ctcpOut = fmt.Sprintf("%s (%s)", service.Name, Ver)
case "PING":
if len(ctcpSplit) > 1 {
ctcpOut = ctcpSplit[1]
}
case "TIME":
ctcpOut = time.Now().UTC().Format(time.RFC1123)
}
if ctcpOut != "" {
client.Send(nil, service.prefix, "NOTICE", client.Nick(), fmt.Sprintf("\x01%s %s\x01", ctcpCmd, ctcpOut))
}
}
// actually execute a service command
func serviceRunCommand(service *ircService, server *Server, client *Client, cmd *serviceCommand, commandName string, params []string, rb *ResponseBuffer) {
2018-04-19 08:48:19 +02:00
nick := rb.target.Nick()
sendNotice := func(notice string) {
2019-05-19 10:27:44 +02:00
rb.Add(nil, service.prefix, "NOTICE", nick, notice)
2018-04-19 08:48:19 +02:00
}
if cmd == nil {
sendNotice(fmt.Sprintf(client.t("Unknown command. To see available commands, run: /%s HELP"), service.ShortName))
2018-04-19 08:48:19 +02:00
return
}
2019-05-29 10:25:20 +02:00
if len(params) < cmd.minParams || (0 < cmd.maxParams && cmd.maxParams < len(params)) {
sendNotice(fmt.Sprintf(client.t("Invalid parameters. For usage, do /msg %[1]s HELP %[2]s"), service.Name, strings.ToUpper(commandName)))
2019-01-04 04:32:07 +01:00
return
}
if cmd.enabled != nil && !cmd.enabled(server.Config()) {
2018-04-19 08:48:19 +02:00
sendNotice(client.t("This command has been disabled by the server administrators"))
return
}
if 0 < len(cmd.capabs) && !client.HasRoleCapabs(cmd.capabs...) {
sendNotice(client.t("Command restricted"))
return
}
if cmd.authRequired && client.Account() == "" {
sendNotice(client.t("You're not logged into an account"))
return
}
server.logger.Debug("services", fmt.Sprintf("Client %s ran %s command %s", client.Nick(), service.Name, commandName))
if commandName == "help" {
serviceHelpHandler(service, server, client, params, rb)
} else {
cmd.handler(service, server, client, commandName, params, rb)
2018-04-19 08:48:19 +02:00
}
}
// generic handler that displays help for service commands
2019-01-04 04:32:07 +01:00
func serviceHelpHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
2018-04-19 08:48:19 +02:00
nick := rb.target.Nick()
2019-01-04 04:32:07 +01:00
config := server.Config()
2018-04-19 08:48:19 +02:00
sendNotice := func(notice string) {
2019-05-19 10:27:44 +02:00
rb.Add(nil, service.prefix, "NOTICE", nick, notice)
2018-04-19 08:48:19 +02:00
}
2020-12-28 02:17:24 +01:00
sendNotice(fmt.Sprintf(ircfmt.Unescape("*** $b%s HELP$b ***"), service.Name))
2018-04-19 08:48:19 +02:00
2019-01-04 04:32:07 +01:00
if len(params) == 0 {
helpBannerLines := strings.Split(client.t(service.HelpBanner), "\n")
helpBannerLines = append(helpBannerLines, []string{
"",
client.t("To see in-depth help for a specific command, try:"),
2020-12-28 02:17:24 +01:00
fmt.Sprintf(ircfmt.Unescape(client.t(" $b/msg %s HELP <command>$b")), service.Name),
"",
client.t("Here are the commands you can use:"),
}...)
2018-04-19 08:48:19 +02:00
// show general help
var shownHelpLines sort.StringSlice
var disabledCommands bool
2018-04-19 08:48:19 +02:00
for _, commandInfo := range service.Commands {
// skip commands user can't access
if 0 < len(commandInfo.capabs) && !client.HasRoleCapabs(commandInfo.capabs...) {
continue
}
2019-05-19 10:27:44 +02:00
if commandInfo.aliasOf != "" || commandInfo.hidden {
continue // don't show help lines for aliases
}
2019-01-04 04:32:07 +01:00
if commandInfo.enabled != nil && !commandInfo.enabled(config) {
disabledCommands = true
2018-04-19 08:48:19 +02:00
continue
}
2020-12-28 02:17:24 +01:00
shownHelpLines = append(shownHelpLines, " "+ircfmt.Unescape(client.t(commandInfo.helpShort)))
2018-04-19 08:48:19 +02:00
}
if disabledCommands {
shownHelpLines = append(shownHelpLines, " "+client.t("... and other commands which have been disabled"))
}
2018-04-19 08:48:19 +02:00
// sort help lines
sort.Sort(shownHelpLines)
// push out help text
for _, line := range helpBannerLines {
sendNotice(line)
}
for _, line := range shownHelpLines {
2018-04-19 08:48:19 +02:00
sendNotice(line)
}
} else {
2019-01-04 04:32:07 +01:00
commandName := strings.ToLower(params[0])
commandInfo := lookupServiceCommand(service.Commands, commandName)
2018-04-19 08:48:19 +02:00
if commandInfo == nil {
sendNotice(client.t(fmt.Sprintf("Unknown command. To see available commands, run /%s HELP", service.ShortName)))
} else {
2019-05-20 08:56:49 +02:00
helpStrings := commandInfo.helpStrings
if helpStrings == nil {
hsArray := [1]string{commandInfo.help}
helpStrings = hsArray[:]
}
for i, helpString := range helpStrings {
if 0 < i {
sendNotice("")
}
for _, line := range strings.Split(ircfmt.Unescape(client.t(helpString)), "\n") {
sendNotice(line)
}
2018-04-19 08:48:19 +02:00
}
}
}
2020-12-28 02:17:24 +01:00
sendNotice(fmt.Sprintf(ircfmt.Unescape(client.t("*** $bEnd of %s HELP$b ***")), service.Name))
2018-04-19 08:48:19 +02:00
}
func makeServiceHelpTextGenerator(cmd string, banner string) func(*Client) string {
return func(client *Client) string {
var buf bytes.Buffer
fmt.Fprintf(&buf, client.t("%s <subcommand> [params]"), cmd)
buf.WriteRune('\n')
buf.WriteString(client.t(banner)) // may contain newlines, that's fine
buf.WriteRune('\n')
fmt.Fprintf(&buf, client.t("For more details, try /%s HELP"), cmd)
return buf.String()
}
}
func overrideServicePrefixes(hostname string) error {
if hostname == "" {
return nil
}
if !utils.IsHostname(hostname) {
return fmt.Errorf("`%s` is an invalid services hostname", hostname)
}
for _, serv := range ErgoServices {
serv.prefix = fmt.Sprintf("%s!%s@%s", serv.Name, serv.Name, hostname)
}
return nil
}
2018-04-19 08:48:19 +02:00
func initializeServices() {
// this modifies the global Commands map,
// so it must be called from irc/commands.go's init()
ergoServicesByCommandAlias = make(map[string]*ircService)
2018-04-19 08:48:19 +02:00
for serviceName, service := range ErgoServices {
2019-05-19 10:27:44 +02:00
service.prefix = fmt.Sprintf("%s!%s@localhost", service.Name, service.Name)
2018-04-19 08:48:19 +02:00
// make `/MSG ServiceName HELP` work correctly
service.Commands["help"] = &servHelpCmd
// reserve the nickname
restrictedNicknames = append(restrictedNicknames, service.Name)
2018-04-19 08:48:19 +02:00
// register the protocol-level commands (NICKSERV, NS) that talk to the service,
// and their associated help entries
2018-04-19 08:48:19 +02:00
var ircCmdDef Command
ircCmdDef.handler = serviceCmdHandler
for _, ircCmd := range service.CommandAliases {
Commands[ircCmd] = ircCmdDef
ergoServicesByCommandAlias[ircCmd] = service
Help[strings.ToLower(ircCmd)] = HelpEntry{
textGenerator: makeServiceHelpTextGenerator(ircCmd, service.HelpBanner),
}
2018-04-19 08:48:19 +02:00
}
// force devs to write a help entry for every command
for commandName, commandInfo := range service.Commands {
2019-05-20 08:56:49 +02:00
if commandInfo.aliasOf == "" && !commandInfo.hidden {
if (commandInfo.help == "" && commandInfo.helpStrings == nil) || commandInfo.helpShort == "" {
log.Fatal(fmt.Sprintf("help entry missing for %s command %s", serviceName, commandName))
}
}
2019-05-29 10:25:20 +02:00
if commandInfo.maxParams == 0 && commandInfo.unsplitFinalParam {
log.Fatal("unsplitFinalParam requires use of maxParams")
}
}
2018-04-19 08:48:19 +02:00
}
for _, restrictedNickname := range restrictedNicknames {
cfName, err := CasefoldName(restrictedNickname)
if err != nil {
panic(err)
}
2020-08-23 04:43:21 +02:00
restrictedCasefoldedNicks.Add(cfName)
skeleton, err := Skeleton(restrictedNickname)
if err != nil {
panic(err)
}
2020-08-23 04:43:21 +02:00
restrictedSkeletons.Add(skeleton)
}
2018-04-19 08:48:19 +02:00
}