Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

services.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "bytes"
  6. "fmt"
  7. "log"
  8. "sort"
  9. "strings"
  10. "github.com/goshuirc/irc-go/ircfmt"
  11. "github.com/goshuirc/irc-go/ircmsg"
  12. "github.com/oragono/oragono/irc/utils"
  13. )
  14. // defines an IRC service, e.g., NICKSERV
  15. type ircService struct {
  16. Name string
  17. ShortName string
  18. prefix string
  19. CommandAliases []string
  20. Commands map[string]*serviceCommand
  21. HelpBanner string
  22. }
  23. // defines a command associated with a service, e.g., NICKSERV IDENTIFY
  24. type serviceCommand struct {
  25. aliasOf string // marks this command as an alias of another
  26. capabs []string // oper capabs the given user has to have to access this command
  27. handler func(server *Server, client *Client, command string, params []string, rb *ResponseBuffer)
  28. help string
  29. helpStrings []string
  30. helpShort string
  31. enabled func(*Config) bool // is this command enabled in the server config?
  32. authRequired bool
  33. hidden bool
  34. minParams int
  35. maxParams int // optional, if set it's an error if the user passes more than this many params
  36. unsplitFinalParam bool // split into at most maxParams, with last param containing unsplit text
  37. }
  38. // looks up a command in the table of command definitions for a service, resolving aliases
  39. func lookupServiceCommand(commands map[string]*serviceCommand, command string) *serviceCommand {
  40. maxDepth := 1
  41. depth := 0
  42. for depth <= maxDepth {
  43. result, ok := commands[command]
  44. if !ok {
  45. return nil
  46. } else if result.aliasOf == "" {
  47. return result
  48. } else {
  49. command = result.aliasOf
  50. depth += 1
  51. }
  52. }
  53. return nil
  54. }
  55. // all services, by lowercase name
  56. var OragonoServices = map[string]*ircService{
  57. "nickserv": {
  58. Name: "NickServ",
  59. ShortName: "NS",
  60. CommandAliases: []string{"NICKSERV", "NS"},
  61. Commands: nickservCommands,
  62. HelpBanner: nickservHelp,
  63. },
  64. "chanserv": {
  65. Name: "ChanServ",
  66. ShortName: "CS",
  67. CommandAliases: []string{"CHANSERV", "CS"},
  68. Commands: chanservCommands,
  69. HelpBanner: chanservHelp,
  70. },
  71. "hostserv": {
  72. Name: "HostServ",
  73. ShortName: "HS",
  74. CommandAliases: []string{"HOSTSERV", "HS"},
  75. Commands: hostservCommands,
  76. HelpBanner: hostservHelp,
  77. },
  78. "histserv": {
  79. Name: "HistServ",
  80. ShortName: "HISTSERV",
  81. CommandAliases: []string{"HISTSERV"},
  82. Commands: histservCommands,
  83. HelpBanner: histservHelp,
  84. },
  85. }
  86. // all service commands at the protocol level, by uppercase command name
  87. // e.g., NICKSERV, NS
  88. var oragonoServicesByCommandAlias map[string]*ircService
  89. // special-cased command shared by all services
  90. var servHelpCmd serviceCommand = serviceCommand{
  91. help: `Syntax: $bHELP [command]$b
  92. HELP returns information on the given command.`,
  93. helpShort: `$bHELP$b shows in-depth information about commands.`,
  94. }
  95. // generic handler for IRC commands like `/NICKSERV INFO`
  96. func serviceCmdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  97. service, ok := oragonoServicesByCommandAlias[msg.Command]
  98. if !ok {
  99. server.logger.Warning("internal", "can't handle unrecognized service", msg.Command)
  100. return false
  101. }
  102. if len(msg.Params) == 0 {
  103. return false
  104. }
  105. commandName := strings.ToLower(msg.Params[0])
  106. params := msg.Params[1:]
  107. cmd := lookupServiceCommand(service.Commands, commandName)
  108. // for a maxParams command, join all final parameters together if necessary
  109. if cmd != nil && cmd.unsplitFinalParam && cmd.maxParams < len(params) {
  110. newParams := make([]string, cmd.maxParams)
  111. copy(newParams, params[:cmd.maxParams-1])
  112. newParams[cmd.maxParams-1] = strings.Join(params[cmd.maxParams-1:], " ")
  113. params = newParams
  114. }
  115. serviceRunCommand(service, server, client, cmd, commandName, params, rb)
  116. return false
  117. }
  118. // generic handler for service PRIVMSG, like `/msg NickServ INFO`
  119. func servicePrivmsgHandler(service *ircService, server *Server, client *Client, message string, rb *ResponseBuffer) {
  120. params := strings.Fields(message)
  121. if len(params) == 0 {
  122. return
  123. }
  124. // look up the service command to see how to parse it
  125. commandName := strings.ToLower(params[0])
  126. cmd := lookupServiceCommand(service.Commands, commandName)
  127. // reparse if needed
  128. if cmd != nil && cmd.unsplitFinalParam {
  129. params = utils.FieldsN(message, cmd.maxParams+1)[1:]
  130. } else {
  131. params = params[1:]
  132. }
  133. serviceRunCommand(service, server, client, cmd, commandName, params, rb)
  134. }
  135. // actually execute a service command
  136. func serviceRunCommand(service *ircService, server *Server, client *Client, cmd *serviceCommand, commandName string, params []string, rb *ResponseBuffer) {
  137. nick := rb.target.Nick()
  138. sendNotice := func(notice string) {
  139. rb.Add(nil, service.prefix, "NOTICE", nick, notice)
  140. }
  141. if cmd == nil {
  142. sendNotice(fmt.Sprintf(client.t("Unknown command. To see available commands, run: /%s HELP"), service.ShortName))
  143. return
  144. }
  145. if len(params) < cmd.minParams || (0 < cmd.maxParams && cmd.maxParams < len(params)) {
  146. sendNotice(fmt.Sprintf(client.t("Invalid parameters. For usage, do /msg %[1]s HELP %[2]s"), service.Name, strings.ToUpper(commandName)))
  147. return
  148. }
  149. if cmd.enabled != nil && !cmd.enabled(server.Config()) {
  150. sendNotice(client.t("This command has been disabled by the server administrators"))
  151. return
  152. }
  153. if 0 < len(cmd.capabs) && !client.HasRoleCapabs(cmd.capabs...) {
  154. sendNotice(client.t("Command restricted"))
  155. return
  156. }
  157. if cmd.authRequired && client.Account() == "" {
  158. sendNotice(client.t("You're not logged into an account"))
  159. return
  160. }
  161. server.logger.Debug("services", fmt.Sprintf("Client %s ran %s command %s", client.Nick(), service.Name, commandName))
  162. if commandName == "help" {
  163. serviceHelpHandler(service, server, client, params, rb)
  164. } else {
  165. cmd.handler(server, client, commandName, params, rb)
  166. }
  167. }
  168. // generic handler that displays help for service commands
  169. func serviceHelpHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  170. nick := rb.target.Nick()
  171. config := server.Config()
  172. sendNotice := func(notice string) {
  173. rb.Add(nil, service.prefix, "NOTICE", nick, notice)
  174. }
  175. sendNotice(ircfmt.Unescape(fmt.Sprintf("*** $b%s HELP$b ***", service.Name)))
  176. if len(params) == 0 {
  177. helpBannerLines := strings.Split(client.t(service.HelpBanner), "\n")
  178. helpBannerLines = append(helpBannerLines, []string{
  179. "",
  180. client.t("To see in-depth help for a specific command, try:"),
  181. ircfmt.Unescape(fmt.Sprintf(client.t(" $b/msg %s HELP <command>$b"), service.Name)),
  182. "",
  183. client.t("Here are the commands you can use:"),
  184. }...)
  185. // show general help
  186. var shownHelpLines sort.StringSlice
  187. var disabledCommands bool
  188. for _, commandInfo := range service.Commands {
  189. // skip commands user can't access
  190. if 0 < len(commandInfo.capabs) && !client.HasRoleCapabs(commandInfo.capabs...) {
  191. continue
  192. }
  193. if commandInfo.aliasOf != "" || commandInfo.hidden {
  194. continue // don't show help lines for aliases
  195. }
  196. if commandInfo.enabled != nil && !commandInfo.enabled(config) {
  197. disabledCommands = true
  198. continue
  199. }
  200. shownHelpLines = append(shownHelpLines, ircfmt.Unescape(" "+client.t(commandInfo.helpShort)))
  201. }
  202. if disabledCommands {
  203. shownHelpLines = append(shownHelpLines, " "+client.t("... and other commands which have been disabled"))
  204. }
  205. // sort help lines
  206. sort.Sort(shownHelpLines)
  207. // push out help text
  208. for _, line := range helpBannerLines {
  209. sendNotice(line)
  210. }
  211. for _, line := range shownHelpLines {
  212. sendNotice(line)
  213. }
  214. } else {
  215. commandName := strings.ToLower(params[0])
  216. commandInfo := lookupServiceCommand(service.Commands, commandName)
  217. if commandInfo == nil {
  218. sendNotice(client.t(fmt.Sprintf("Unknown command. To see available commands, run /%s HELP", service.ShortName)))
  219. } else {
  220. helpStrings := commandInfo.helpStrings
  221. if helpStrings == nil {
  222. hsArray := [1]string{commandInfo.help}
  223. helpStrings = hsArray[:]
  224. }
  225. for i, helpString := range helpStrings {
  226. if 0 < i {
  227. sendNotice("")
  228. }
  229. for _, line := range strings.Split(ircfmt.Unescape(client.t(helpString)), "\n") {
  230. sendNotice(line)
  231. }
  232. }
  233. }
  234. }
  235. sendNotice(ircfmt.Unescape(fmt.Sprintf(client.t("*** $bEnd of %s HELP$b ***"), service.Name)))
  236. }
  237. func makeServiceHelpTextGenerator(cmd string, banner string) func(*Client) string {
  238. return func(client *Client) string {
  239. var buf bytes.Buffer
  240. fmt.Fprintf(&buf, client.t("%s <subcommand> [params]"), cmd)
  241. buf.WriteRune('\n')
  242. buf.WriteString(client.t(banner)) // may contain newlines, that's fine
  243. buf.WriteRune('\n')
  244. fmt.Fprintf(&buf, client.t("For more details, try /%s HELP"), cmd)
  245. return buf.String()
  246. }
  247. }
  248. func initializeServices() {
  249. // this modifies the global Commands map,
  250. // so it must be called from irc/commands.go's init()
  251. oragonoServicesByCommandAlias = make(map[string]*ircService)
  252. for serviceName, service := range OragonoServices {
  253. service.prefix = fmt.Sprintf("%s!%s@localhost", service.Name, service.Name)
  254. // make `/MSG ServiceName HELP` work correctly
  255. service.Commands["help"] = &servHelpCmd
  256. // reserve the nickname
  257. restrictedNicknames = append(restrictedNicknames, service.Name)
  258. // register the protocol-level commands (NICKSERV, NS) that talk to the service,
  259. // and their associated help entries
  260. var ircCmdDef Command
  261. ircCmdDef.handler = serviceCmdHandler
  262. for _, ircCmd := range service.CommandAliases {
  263. Commands[ircCmd] = ircCmdDef
  264. oragonoServicesByCommandAlias[ircCmd] = service
  265. Help[strings.ToLower(ircCmd)] = HelpEntry{
  266. textGenerator: makeServiceHelpTextGenerator(ircCmd, service.HelpBanner),
  267. }
  268. }
  269. // force devs to write a help entry for every command
  270. for commandName, commandInfo := range service.Commands {
  271. if commandInfo.aliasOf == "" && !commandInfo.hidden {
  272. if (commandInfo.help == "" && commandInfo.helpStrings == nil) || commandInfo.helpShort == "" {
  273. log.Fatal(fmt.Sprintf("help entry missing for %s command %s", serviceName, commandName))
  274. }
  275. }
  276. if commandInfo.maxParams == 0 && commandInfo.unsplitFinalParam {
  277. log.Fatal("unsplitFinalParam requires use of maxParams")
  278. }
  279. }
  280. }
  281. for _, restrictedNickname := range restrictedNicknames {
  282. cfName, err := CasefoldName(restrictedNickname)
  283. if err != nil {
  284. panic(err)
  285. }
  286. restrictedCasefoldedNicks[cfName] = true
  287. skeleton, err := Skeleton(restrictedNickname)
  288. if err != nil {
  289. panic(err)
  290. }
  291. restrictedSkeletons[skeleton] = true
  292. }
  293. }