Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "regexp"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/ergochat/ergo/irc/modes"
  11. "github.com/ergochat/ergo/irc/sno"
  12. "github.com/ergochat/ergo/irc/utils"
  13. "github.com/ergochat/irc-go/ircfmt"
  14. )
  15. const chanservHelp = `ChanServ lets you register and manage channels.`
  16. func chanregEnabled(config *Config) bool {
  17. return config.Channels.Registration.Enabled
  18. }
  19. var (
  20. chanservCommands = map[string]*serviceCommand{
  21. "op": {
  22. handler: csOpHandler,
  23. help: `Syntax: $bOP #channel [nickname]$b
  24. OP makes the given nickname, or yourself, a channel admin. You can only use
  25. this command if you're a founder or in the AMODEs of the channel.`,
  26. helpShort: `$bOP$b makes the given user (or yourself) a channel admin.`,
  27. authRequired: true,
  28. enabled: chanregEnabled,
  29. minParams: 1,
  30. },
  31. "deop": {
  32. handler: csDeopHandler,
  33. help: `Syntax: $bDEOP #channel [nickname]$b
  34. DEOP removes the given nickname, or yourself, the channel admin. You can only use
  35. this command if you're the founder of the channel.`,
  36. helpShort: `$bDEOP$b removes the given user (or yourself) from a channel admin.`,
  37. enabled: chanregEnabled,
  38. minParams: 1,
  39. },
  40. "register": {
  41. handler: csRegisterHandler,
  42. help: `Syntax: $bREGISTER #channel$b
  43. REGISTER lets you own the given channel. If you rejoin this channel, you'll be
  44. given admin privs on it. Modes set on the channel and the topic will also be
  45. remembered.`,
  46. helpShort: `$bREGISTER$b lets you own a given channel.`,
  47. authRequired: true,
  48. enabled: chanregEnabled,
  49. minParams: 1,
  50. },
  51. "unregister": {
  52. handler: csUnregisterHandler,
  53. help: `Syntax: $bUNREGISTER #channel [code]$b
  54. UNREGISTER deletes a channel registration, allowing someone else to claim it.
  55. To prevent accidental unregistrations, a verification code is required;
  56. invoking the command without a code will display the necessary code.`,
  57. helpShort: `$bUNREGISTER$b deletes a channel registration.`,
  58. enabled: chanregEnabled,
  59. minParams: 1,
  60. },
  61. "drop": {
  62. aliasOf: "unregister",
  63. },
  64. "amode": {
  65. handler: csAmodeHandler,
  66. help: `Syntax: $bAMODE #channel [mode change] [account]$b
  67. AMODE lists or modifies persistent mode settings that affect channel members.
  68. For example, $bAMODE #channel +o dan$b grants the holder of the "dan"
  69. account the +o operator mode every time they join #channel. To list current
  70. accounts and modes, use $bAMODE #channel$b. Note that users are always
  71. referenced by their registered account names, not their nicknames.
  72. The permissions hierarchy for adding and removing modes is the same as in
  73. the ordinary /MODE command.`,
  74. helpShort: `$bAMODE$b modifies persistent mode settings for channel members.`,
  75. enabled: chanregEnabled,
  76. minParams: 1,
  77. },
  78. "clear": {
  79. handler: csClearHandler,
  80. help: `Syntax: $bCLEAR #channel target$b
  81. CLEAR removes users or settings from a channel. Specifically:
  82. $bCLEAR #channel users$b kicks all users except for you.
  83. $bCLEAR #channel access$b resets all stored bans, invites, ban exceptions,
  84. and persistent user-mode grants made with CS AMODE.`,
  85. helpShort: `$bCLEAR$b removes users or settings from a channel.`,
  86. enabled: chanregEnabled,
  87. minParams: 2,
  88. },
  89. "transfer": {
  90. handler: csTransferHandler,
  91. help: `Syntax: $bTRANSFER [accept] #channel user [code]$b
  92. TRANSFER transfers ownership of a channel from one user to another.
  93. To prevent accidental transfers, a verification code is required. For
  94. example, $bTRANSFER #channel alice$b displays the required confirmation
  95. code, then $bTRANSFER #channel alice 2930242125$b initiates the transfer.
  96. Unless you are an IRC operator with the correct permissions, alice must
  97. then accept the transfer, which she can do with $bTRANSFER accept #channel$b.
  98. To cancel a pending transfer, transfer the channel to yourself.`,
  99. helpShort: `$bTRANSFER$b transfers ownership of a channel to another user.`,
  100. enabled: chanregEnabled,
  101. minParams: 2,
  102. },
  103. "purge": {
  104. handler: csPurgeHandler,
  105. help: `Syntax: $bPURGE <ADD | DEL | LIST> #channel [code] [reason]$b
  106. PURGE ADD blacklists a channel from the server, making it impossible to join
  107. or otherwise interact with the channel. If the channel currently has members,
  108. they will be kicked from it. PURGE may also be applied preemptively to
  109. channels that do not currently have members. A purge can be undone with
  110. PURGE DEL. To list purged channels, use PURGE LIST.`,
  111. helpShort: `$bPURGE$b blacklists a channel from the server.`,
  112. capabs: []string{"chanreg"},
  113. minParams: 1,
  114. maxParams: 3,
  115. unsplitFinalParam: true,
  116. },
  117. "list": {
  118. handler: csListHandler,
  119. help: `Syntax: $bLIST [regex]$b
  120. LIST returns the list of registered channels, which match the given regex.
  121. If no regex is provided, all registered channels are returned.`,
  122. helpShort: `$bLIST$b searches the list of registered channels.`,
  123. capabs: []string{"chanreg"},
  124. minParams: 0,
  125. },
  126. "info": {
  127. handler: csInfoHandler,
  128. help: `Syntax: $INFO #channel$b
  129. INFO displays info about a registered channel.`,
  130. helpShort: `$bINFO$b displays info about a registered channel.`,
  131. enabled: chanregEnabled,
  132. },
  133. "get": {
  134. handler: csGetHandler,
  135. help: `Syntax: $bGET #channel <setting>$b
  136. GET queries the current values of the channel settings. For more information
  137. on the settings and their possible values, see HELP SET.`,
  138. helpShort: `$bGET$b queries the current values of a channel's settings`,
  139. enabled: chanregEnabled,
  140. minParams: 2,
  141. },
  142. "set": {
  143. handler: csSetHandler,
  144. helpShort: `$bSET$b modifies a channel's settings`,
  145. // these are broken out as separate strings so they can be translated separately
  146. helpStrings: []string{
  147. `Syntax $bSET #channel <setting> <value>$b
  148. SET modifies a channel's settings. The following settings are available:`,
  149. `$bHISTORY$b
  150. 'history' lets you control how channel history is stored. Your options are:
  151. 1. 'off' [no history]
  152. 2. 'ephemeral' [a limited amount of temporary history, not stored on disk]
  153. 3. 'on' [history stored in a permanent database, if available]
  154. 4. 'default' [use the server default]`,
  155. `$bQUERY-CUTOFF$b
  156. 'query-cutoff' lets you restrict how much channel history can be retrieved
  157. by unprivileged users. Your options are:
  158. 1. 'none' [no restrictions]
  159. 2. 'registration-time' [users can view history from after their account was
  160. registered, plus a grace period]
  161. 3. 'join-time' [users can view history from after they joined the
  162. channel; note that history will be effectively
  163. unavailable to clients that are not always-on]
  164. 4. 'default' [use the server default]`,
  165. },
  166. enabled: chanregEnabled,
  167. minParams: 3,
  168. },
  169. "howtoban": {
  170. handler: csHowToBanHandler,
  171. helpShort: `$bHOWTOBAN$b suggests the best available way of banning a user`,
  172. help: `Syntax: $bHOWTOBAN #channel <nick>
  173. The best way to ban a user from a channel will depend on how they are
  174. connected to the server. $bHOWTOBAN$b suggests a ban command that will
  175. (ideally) prevent the user from returning to the channel.`,
  176. enabled: chanregEnabled,
  177. minParams: 2,
  178. },
  179. }
  180. )
  181. func csAmodeHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  182. channelName := params[0]
  183. channel := server.channels.Get(channelName)
  184. if channel == nil {
  185. service.Notice(rb, client.t("Channel does not exist"))
  186. return
  187. } else if channel.Founder() == "" {
  188. service.Notice(rb, client.t("Channel is not registered"))
  189. return
  190. }
  191. modeChanges, unknown := modes.ParseChannelModeChanges(params[1:]...)
  192. var change modes.ModeChange
  193. if len(modeChanges) > 1 || len(unknown) > 0 {
  194. service.Notice(rb, client.t("Invalid mode change"))
  195. return
  196. } else if len(modeChanges) == 1 {
  197. change = modeChanges[0]
  198. } else {
  199. change = modes.ModeChange{Op: modes.List}
  200. }
  201. // normalize and validate the account argument
  202. accountIsValid := false
  203. change.Arg, _ = CasefoldName(change.Arg)
  204. switch change.Op {
  205. case modes.List:
  206. accountIsValid = true
  207. case modes.Add:
  208. // if we're adding a mode, the account must exist
  209. if change.Arg != "" {
  210. _, err := server.accounts.LoadAccount(change.Arg)
  211. accountIsValid = (err == nil)
  212. }
  213. case modes.Remove:
  214. // allow removal of accounts that may have been deleted
  215. accountIsValid = (change.Arg != "")
  216. }
  217. if !accountIsValid {
  218. service.Notice(rb, client.t("Account does not exist"))
  219. return
  220. }
  221. affectedModes, err := channel.ProcessAccountToUmodeChange(client, change)
  222. if err == errInsufficientPrivs {
  223. service.Notice(rb, client.t("Insufficient privileges"))
  224. return
  225. } else if err != nil {
  226. service.Notice(rb, client.t("Internal error"))
  227. return
  228. }
  229. switch change.Op {
  230. case modes.List:
  231. // sort the persistent modes in descending order of priority
  232. sort.Slice(affectedModes, func(i, j int) bool {
  233. return umodeGreaterThan(affectedModes[i].Mode, affectedModes[j].Mode)
  234. })
  235. service.Notice(rb, fmt.Sprintf(client.t("Channel %[1]s has %[2]d persistent modes set"), channelName, len(affectedModes)))
  236. for _, modeChange := range affectedModes {
  237. service.Notice(rb, fmt.Sprintf(client.t("Account %[1]s receives mode +%[2]s"), modeChange.Arg, string(modeChange.Mode)))
  238. }
  239. case modes.Add, modes.Remove:
  240. if len(affectedModes) > 0 {
  241. service.Notice(rb, fmt.Sprintf(client.t("Successfully set persistent mode %[1]s on %[2]s"), strings.Join([]string{string(change.Op), string(change.Mode)}, ""), change.Arg))
  242. // #729: apply change to current membership
  243. for _, member := range channel.Members() {
  244. if member.Account() == change.Arg {
  245. // applyModeToMember takes the nickname, not the account name,
  246. // so translate:
  247. modeChange := change
  248. modeChange.Arg = member.Nick()
  249. applied, modeChange := channel.applyModeToMember(client, modeChange, rb)
  250. if applied {
  251. announceCmodeChanges(channel, modes.ModeChanges{modeChange}, server.name, "*", "", false, rb)
  252. }
  253. }
  254. }
  255. } else {
  256. service.Notice(rb, client.t("No changes were made"))
  257. }
  258. }
  259. }
  260. func csOpHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  261. channelInfo := server.channels.Get(params[0])
  262. if channelInfo == nil {
  263. service.Notice(rb, client.t("Channel does not exist"))
  264. return
  265. }
  266. channelName := channelInfo.Name()
  267. founder := channelInfo.Founder()
  268. clientAccount := client.Account()
  269. if clientAccount == "" {
  270. service.Notice(rb, client.t("You're not logged into an account"))
  271. return
  272. }
  273. var target *Client
  274. if len(params) > 1 {
  275. target = server.clients.Get(params[1])
  276. if target == nil {
  277. service.Notice(rb, client.t("Could not find given client"))
  278. return
  279. }
  280. } else {
  281. target = client
  282. }
  283. var givenMode modes.Mode
  284. if target == client {
  285. if clientAccount == founder {
  286. givenMode = modes.ChannelFounder
  287. } else {
  288. givenMode = channelInfo.getAmode(clientAccount)
  289. if givenMode == modes.Mode(0) {
  290. service.Notice(rb, client.t("You don't have any stored privileges on that channel"))
  291. return
  292. }
  293. }
  294. } else {
  295. if clientAccount == founder {
  296. givenMode = modes.ChannelOperator
  297. } else {
  298. service.Notice(rb, client.t("Only the channel founder can do this"))
  299. return
  300. }
  301. }
  302. applied, change := channelInfo.applyModeToMember(client,
  303. modes.ModeChange{Mode: givenMode,
  304. Op: modes.Add,
  305. Arg: target.NickCasefolded(),
  306. },
  307. rb)
  308. if applied {
  309. announceCmodeChanges(channelInfo, modes.ModeChanges{change}, server.name, "*", "", false, rb)
  310. }
  311. service.Notice(rb, client.t("Successfully granted operator privileges"))
  312. tnick := target.Nick()
  313. server.logger.Info("services", fmt.Sprintf("Client %s op'd [%s] in channel %s", client.Nick(), tnick, channelName))
  314. server.snomasks.Send(sno.LocalChannels, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] CS OP'd $c[grey][$r%s$c[grey]] in channel $c[grey][$r%s$c[grey]]"), client.NickMaskString(), tnick, channelName))
  315. }
  316. func csDeopHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  317. channel := server.channels.Get(params[0])
  318. if channel == nil {
  319. service.Notice(rb, client.t("Channel does not exist"))
  320. return
  321. }
  322. if !channel.hasClient(client) {
  323. service.Notice(rb, client.t("You're not on that channel"))
  324. return
  325. }
  326. var target *Client
  327. if len(params) > 1 {
  328. target = server.clients.Get(params[1])
  329. if target == nil {
  330. service.Notice(rb, client.t("Could not find given client"))
  331. return
  332. }
  333. } else {
  334. target = client
  335. }
  336. present, _, cumodes := channel.ClientStatus(target)
  337. if !present || len(cumodes) == 0 {
  338. service.Notice(rb, client.t("Target has no privileges to remove"))
  339. return
  340. }
  341. tnick := target.Nick()
  342. modeChanges := make(modes.ModeChanges, len(cumodes))
  343. for i, mode := range cumodes {
  344. modeChanges[i] = modes.ModeChange{
  345. Mode: mode,
  346. Op: modes.Remove,
  347. Arg: tnick,
  348. }
  349. }
  350. // use the user's own permissions for the check, then announce
  351. // the changes as coming from chanserv
  352. applied := channel.ApplyChannelModeChanges(client, false, modeChanges, rb)
  353. details := client.Details()
  354. isBot := client.HasMode(modes.Bot)
  355. announceCmodeChanges(channel, applied, details.nickMask, details.accountName, details.account, isBot, rb)
  356. if len(applied) == 0 {
  357. return
  358. }
  359. service.Notice(rb, client.t("Successfully removed operator privileges"))
  360. }
  361. func csRegisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  362. if server.Config().Channels.Registration.OperatorOnly && !client.HasRoleCapabs("chanreg") {
  363. service.Notice(rb, client.t("Channel registration is restricted to server operators"))
  364. return
  365. }
  366. channelName := params[0]
  367. channelInfo := server.channels.Get(channelName)
  368. if channelInfo == nil {
  369. service.Notice(rb, client.t("No such channel"))
  370. return
  371. }
  372. if !channelInfo.ClientIsAtLeast(client, modes.ChannelOperator) {
  373. service.Notice(rb, client.t("You must be an oper on the channel to register it"))
  374. return
  375. }
  376. account := client.Account()
  377. if !checkChanLimit(service, client, rb) {
  378. return
  379. }
  380. // this provides the synchronization that allows exactly one registration of the channel:
  381. err := server.channels.SetRegistered(channelName, account)
  382. if err != nil {
  383. service.Notice(rb, err.Error())
  384. return
  385. }
  386. service.Notice(rb, fmt.Sprintf(client.t("Channel %s successfully registered"), channelName))
  387. server.logger.Info("services", fmt.Sprintf("Client %s registered channel %s", client.Nick(), channelName))
  388. server.snomasks.Send(sno.LocalChannels, fmt.Sprintf(ircfmt.Unescape("Channel registered $c[grey][$r%s$c[grey]] by $c[grey][$r%s$c[grey]]"), channelName, client.nickMaskString))
  389. // give them founder privs
  390. applied, change := channelInfo.applyModeToMember(client,
  391. modes.ModeChange{
  392. Mode: modes.ChannelFounder,
  393. Op: modes.Add,
  394. Arg: client.NickCasefolded(),
  395. },
  396. rb)
  397. if applied {
  398. announceCmodeChanges(channelInfo, modes.ModeChanges{change}, service.prefix, "*", "", false, rb)
  399. }
  400. }
  401. // check whether a client has already registered too many channels
  402. func checkChanLimit(service *ircService, client *Client, rb *ResponseBuffer) (ok bool) {
  403. account := client.Account()
  404. channelsAlreadyRegistered := client.server.accounts.ChannelsForAccount(account)
  405. ok = len(channelsAlreadyRegistered) < client.server.Config().Channels.Registration.MaxChannelsPerAccount || client.HasRoleCapabs("chanreg")
  406. if !ok {
  407. service.Notice(rb, client.t("You have already registered the maximum number of channels; try dropping some with /CS UNREGISTER"))
  408. }
  409. return
  410. }
  411. func csPrivsCheck(service *ircService, channel RegisteredChannel, client *Client, rb *ResponseBuffer) (success bool) {
  412. founder := channel.Founder
  413. if founder == "" {
  414. service.Notice(rb, client.t("That channel is not registered"))
  415. return false
  416. }
  417. if client.HasRoleCapabs("chanreg") {
  418. return true
  419. }
  420. if founder != client.Account() {
  421. service.Notice(rb, client.t("Insufficient privileges"))
  422. return false
  423. }
  424. return true
  425. }
  426. func csUnregisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  427. channelName := params[0]
  428. var verificationCode string
  429. if len(params) > 1 {
  430. verificationCode = params[1]
  431. }
  432. channel := server.channels.Get(channelName)
  433. if channel == nil {
  434. service.Notice(rb, client.t("No such channel"))
  435. return
  436. }
  437. info := channel.ExportRegistration(0)
  438. channelKey := info.NameCasefolded
  439. if !csPrivsCheck(service, info, client, rb) {
  440. return
  441. }
  442. expectedCode := utils.ConfirmationCode(info.Name, info.RegisteredAt)
  443. if expectedCode != verificationCode {
  444. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: unregistering this channel will remove all stored channel attributes.$b")))
  445. service.Notice(rb, fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/CS UNREGISTER %s %s", channelKey, expectedCode)))
  446. return
  447. }
  448. server.channels.SetUnregistered(channelKey, info.Founder)
  449. service.Notice(rb, fmt.Sprintf(client.t("Channel %s is now unregistered"), channelKey))
  450. }
  451. func csClearHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  452. channel := server.channels.Get(params[0])
  453. if channel == nil {
  454. service.Notice(rb, client.t("Channel does not exist"))
  455. return
  456. }
  457. if !csPrivsCheck(service, channel.ExportRegistration(0), client, rb) {
  458. return
  459. }
  460. switch strings.ToLower(params[1]) {
  461. case "access":
  462. channel.resetAccess()
  463. service.Notice(rb, client.t("Successfully reset channel access"))
  464. case "users":
  465. for _, target := range channel.Members() {
  466. if target != client {
  467. channel.Kick(client, target, "Cleared by ChanServ", rb, true)
  468. }
  469. }
  470. default:
  471. service.Notice(rb, client.t("Invalid parameters"))
  472. }
  473. }
  474. func csTransferHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  475. if strings.ToLower(params[0]) == "accept" {
  476. processTransferAccept(service, client, params[1], rb)
  477. return
  478. }
  479. chname := params[0]
  480. channel := server.channels.Get(chname)
  481. if channel == nil {
  482. service.Notice(rb, client.t("Channel does not exist"))
  483. return
  484. }
  485. regInfo := channel.ExportRegistration(0)
  486. chname = regInfo.Name
  487. account := client.Account()
  488. isFounder := account != "" && account == regInfo.Founder
  489. oper := client.Oper()
  490. hasPrivs := oper.HasRoleCapab("chanreg")
  491. if !isFounder && !hasPrivs {
  492. service.Notice(rb, client.t("Insufficient privileges"))
  493. return
  494. }
  495. target := params[1]
  496. targetAccount, err := server.accounts.LoadAccount(params[1])
  497. if err != nil {
  498. service.Notice(rb, client.t("Account does not exist"))
  499. return
  500. }
  501. if targetAccount.NameCasefolded != account {
  502. expectedCode := utils.ConfirmationCode(regInfo.Name, regInfo.RegisteredAt)
  503. codeValidated := 2 < len(params) && params[2] == expectedCode
  504. if !codeValidated {
  505. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: you are about to transfer control of your channel to another user.$b")))
  506. service.Notice(rb, fmt.Sprintf(client.t("To confirm your channel transfer, type: /CS TRANSFER %[1]s %[2]s %[3]s"), chname, target, expectedCode))
  507. return
  508. }
  509. }
  510. if !isFounder {
  511. message := fmt.Sprintf("Operator %s ran CS TRANSFER on %s to account %s", oper.Name, chname, target)
  512. server.snomasks.Send(sno.LocalOpers, message)
  513. server.logger.Info("opers", message)
  514. }
  515. status, err := channel.Transfer(client, target, hasPrivs)
  516. if err == nil {
  517. switch status {
  518. case channelTransferComplete:
  519. service.Notice(rb, fmt.Sprintf(client.t("Successfully transferred channel %[1]s to account %[2]s"), chname, target))
  520. case channelTransferPending:
  521. sendTransferPendingNotice(service, server, target, chname)
  522. service.Notice(rb, fmt.Sprintf(client.t("Transfer of channel %[1]s to account %[2]s succeeded, pending acceptance"), chname, target))
  523. case channelTransferCancelled:
  524. service.Notice(rb, fmt.Sprintf(client.t("Cancelled pending transfer of channel %s"), chname))
  525. }
  526. } else {
  527. switch err {
  528. case errChannelNotOwnedByAccount:
  529. service.Notice(rb, client.t("You don't own that channel"))
  530. default:
  531. service.Notice(rb, client.t("Could not transfer channel"))
  532. }
  533. }
  534. }
  535. func sendTransferPendingNotice(service *ircService, server *Server, account, chname string) {
  536. clients := server.accounts.AccountToClients(account)
  537. if len(clients) == 0 {
  538. return
  539. }
  540. var client *Client
  541. for _, candidate := range clients {
  542. client = candidate
  543. if candidate.NickCasefolded() == candidate.Account() {
  544. break // prefer the login where the nick is the account
  545. }
  546. }
  547. client.Send(nil, service.prefix, "NOTICE", client.Nick(), fmt.Sprintf(client.t("You have been offered ownership of channel %[1]s. To accept, /CS TRANSFER ACCEPT %[1]s"), chname))
  548. }
  549. func processTransferAccept(service *ircService, client *Client, chname string, rb *ResponseBuffer) {
  550. channel := client.server.channels.Get(chname)
  551. if channel == nil {
  552. service.Notice(rb, client.t("Channel does not exist"))
  553. return
  554. }
  555. if !checkChanLimit(service, client, rb) {
  556. return
  557. }
  558. switch channel.AcceptTransfer(client) {
  559. case nil:
  560. service.Notice(rb, fmt.Sprintf(client.t("Successfully accepted ownership of channel %s"), channel.Name()))
  561. case errChannelTransferNotOffered:
  562. service.Notice(rb, fmt.Sprintf(client.t("You weren't offered ownership of channel %s"), channel.Name()))
  563. default:
  564. service.Notice(rb, fmt.Sprintf(client.t("Could not accept ownership of channel %s"), channel.Name()))
  565. }
  566. }
  567. func csPurgeHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  568. oper := client.Oper()
  569. if oper == nil {
  570. return // should be impossible because you need oper capabs for this
  571. }
  572. switch strings.ToLower(params[0]) {
  573. case "add":
  574. csPurgeAddHandler(service, client, params[1:], oper.Name, rb)
  575. case "del", "remove":
  576. csPurgeDelHandler(service, client, params[1:], oper.Name, rb)
  577. case "list":
  578. csPurgeListHandler(service, client, rb)
  579. default:
  580. service.Notice(rb, client.t("Invalid parameters"))
  581. }
  582. }
  583. func csPurgeAddHandler(service *ircService, client *Client, params []string, operName string, rb *ResponseBuffer) {
  584. if len(params) == 0 {
  585. service.Notice(rb, client.t("Invalid parameters"))
  586. return
  587. }
  588. chname := params[0]
  589. params = params[1:]
  590. channel := client.server.channels.Get(chname) // possibly nil
  591. var ctime time.Time
  592. if channel != nil {
  593. chname = channel.Name()
  594. ctime = channel.Ctime()
  595. }
  596. code := utils.ConfirmationCode(chname, ctime)
  597. if len(params) == 0 || params[0] != code {
  598. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: you are about to empty this channel and remove it from the server.$b")))
  599. service.Notice(rb, fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/CS PURGE ADD %s %s", chname, code)))
  600. return
  601. }
  602. params = params[1:]
  603. var reason string
  604. if 1 < len(params) {
  605. reason = params[1]
  606. }
  607. purgeRecord := ChannelPurgeRecord{
  608. Oper: operName,
  609. PurgedAt: time.Now().UTC(),
  610. Reason: reason,
  611. }
  612. switch client.server.channels.Purge(chname, purgeRecord) {
  613. case nil:
  614. if channel != nil { // channel need not exist to be purged
  615. for _, target := range channel.Members() {
  616. channel.Kick(client, target, "Cleared by ChanServ", rb, true)
  617. }
  618. }
  619. service.Notice(rb, fmt.Sprintf(client.t("Successfully purged channel %s from the server"), chname))
  620. client.server.snomasks.Send(sno.LocalChannels, fmt.Sprintf("Operator %s purged channel %s [reason: %s]", operName, chname, reason))
  621. case errInvalidChannelName:
  622. service.Notice(rb, fmt.Sprintf(client.t("Can't purge invalid channel %s"), chname))
  623. default:
  624. service.Notice(rb, client.t("An error occurred"))
  625. }
  626. }
  627. func csPurgeDelHandler(service *ircService, client *Client, params []string, operName string, rb *ResponseBuffer) {
  628. if len(params) == 0 {
  629. service.Notice(rb, client.t("Invalid parameters"))
  630. return
  631. }
  632. chname := params[0]
  633. switch client.server.channels.Unpurge(chname) {
  634. case nil:
  635. service.Notice(rb, fmt.Sprintf(client.t("Successfully unpurged channel %s from the server"), chname))
  636. client.server.snomasks.Send(sno.LocalChannels, fmt.Sprintf("Operator %s removed purge of channel %s", operName, chname))
  637. case errNoSuchChannel:
  638. service.Notice(rb, fmt.Sprintf(client.t("Channel %s wasn't previously purged from the server"), chname))
  639. default:
  640. service.Notice(rb, client.t("An error occurred"))
  641. }
  642. }
  643. func csPurgeListHandler(service *ircService, client *Client, rb *ResponseBuffer) {
  644. l := client.server.channels.ListPurged()
  645. service.Notice(rb, fmt.Sprintf(client.t("There are %d purged channel(s)."), len(l)))
  646. for i, c := range l {
  647. service.Notice(rb, fmt.Sprintf("%d: %s", i+1, c))
  648. }
  649. }
  650. func csListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  651. if !client.HasRoleCapabs("chanreg") {
  652. service.Notice(rb, client.t("Insufficient privileges"))
  653. return
  654. }
  655. var searchRegex *regexp.Regexp
  656. if len(params) > 0 {
  657. var err error
  658. searchRegex, err = regexp.Compile(params[0])
  659. if err != nil {
  660. service.Notice(rb, client.t("Invalid regex"))
  661. return
  662. }
  663. }
  664. service.Notice(rb, ircfmt.Unescape(client.t("*** $bChanServ LIST$b ***")))
  665. channels := server.channelRegistry.AllChannels()
  666. for _, channel := range channels {
  667. if searchRegex == nil || searchRegex.MatchString(channel) {
  668. service.Notice(rb, fmt.Sprintf(" %s", channel))
  669. }
  670. }
  671. service.Notice(rb, ircfmt.Unescape(client.t("*** $bEnd of ChanServ LIST$b ***")))
  672. }
  673. func csInfoHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  674. if len(params) == 0 {
  675. // #765
  676. listRegisteredChannels(service, client.Account(), rb)
  677. return
  678. }
  679. chname, err := CasefoldChannel(params[0])
  680. if err != nil {
  681. service.Notice(rb, client.t("Invalid channel name"))
  682. return
  683. }
  684. // purge status
  685. if client.HasRoleCapabs("chanreg") {
  686. purgeRecord, err := server.channelRegistry.LoadPurgeRecord(chname)
  687. if err == nil {
  688. service.Notice(rb, fmt.Sprintf(client.t("Channel %s was purged by the server operators and cannot be used"), chname))
  689. service.Notice(rb, fmt.Sprintf(client.t("Purged by operator: %s"), purgeRecord.Oper))
  690. service.Notice(rb, fmt.Sprintf(client.t("Purged at: %s"), purgeRecord.PurgedAt.Format(time.RFC1123)))
  691. if purgeRecord.Reason != "" {
  692. service.Notice(rb, fmt.Sprintf(client.t("Purge reason: %s"), purgeRecord.Reason))
  693. }
  694. }
  695. } else {
  696. if server.channels.IsPurged(chname) {
  697. service.Notice(rb, fmt.Sprintf(client.t("Channel %s was purged by the server operators and cannot be used"), chname))
  698. }
  699. }
  700. var chinfo RegisteredChannel
  701. channel := server.channels.Get(params[0])
  702. if channel != nil {
  703. chinfo = channel.ExportRegistration(0)
  704. } else {
  705. chinfo, err = server.channelRegistry.LoadChannel(chname)
  706. if err != nil && !(err == errNoSuchChannel || err == errFeatureDisabled) {
  707. service.Notice(rb, client.t("An error occurred"))
  708. return
  709. }
  710. }
  711. // channel exists but is unregistered, or doesn't exist:
  712. if chinfo.Founder == "" {
  713. service.Notice(rb, fmt.Sprintf(client.t("Channel %s is not registered"), chname))
  714. return
  715. }
  716. service.Notice(rb, fmt.Sprintf(client.t("Channel %s is registered"), chinfo.Name))
  717. service.Notice(rb, fmt.Sprintf(client.t("Founder: %s"), chinfo.Founder))
  718. service.Notice(rb, fmt.Sprintf(client.t("Registered at: %s"), chinfo.RegisteredAt.Format(time.RFC1123)))
  719. }
  720. func displayChannelSetting(service *ircService, settingName string, settings ChannelSettings, client *Client, rb *ResponseBuffer) {
  721. config := client.server.Config()
  722. switch strings.ToLower(settingName) {
  723. case "history":
  724. effectiveValue := historyEnabled(config.History.Persistent.RegisteredChannels, settings.History)
  725. service.Notice(rb, fmt.Sprintf(client.t("The stored channel history setting is: %s"), historyStatusToString(settings.History)))
  726. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, the channel history setting is: %s"), historyStatusToString(effectiveValue)))
  727. case "query-cutoff":
  728. effectiveValue := settings.QueryCutoff
  729. if effectiveValue == HistoryCutoffDefault {
  730. effectiveValue = config.History.Restrictions.queryCutoff
  731. }
  732. service.Notice(rb, fmt.Sprintf(client.t("The stored channel history query cutoff setting is: %s"), historyCutoffToString(settings.QueryCutoff)))
  733. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, the channel history query cutoff setting is: %s"), historyCutoffToString(effectiveValue)))
  734. default:
  735. service.Notice(rb, client.t("Invalid params"))
  736. }
  737. }
  738. func csGetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  739. chname, setting := params[0], params[1]
  740. channel := server.channels.Get(chname)
  741. if channel == nil {
  742. service.Notice(rb, client.t("No such channel"))
  743. return
  744. }
  745. info := channel.ExportRegistration(IncludeSettings)
  746. if !csPrivsCheck(service, info, client, rb) {
  747. return
  748. }
  749. displayChannelSetting(service, setting, info.Settings, client, rb)
  750. }
  751. func csSetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  752. chname, setting, value := params[0], params[1], params[2]
  753. channel := server.channels.Get(chname)
  754. if channel == nil {
  755. service.Notice(rb, client.t("No such channel"))
  756. return
  757. }
  758. info := channel.ExportRegistration(IncludeSettings)
  759. settings := info.Settings
  760. if !csPrivsCheck(service, info, client, rb) {
  761. return
  762. }
  763. var err error
  764. switch strings.ToLower(setting) {
  765. case "history":
  766. settings.History, err = historyStatusFromString(value)
  767. if err != nil {
  768. err = errInvalidParams
  769. break
  770. }
  771. channel.SetSettings(settings)
  772. channel.resizeHistory(server.Config())
  773. case "query-cutoff":
  774. settings.QueryCutoff, err = historyCutoffFromString(value)
  775. if err != nil {
  776. err = errInvalidParams
  777. break
  778. }
  779. channel.SetSettings(settings)
  780. }
  781. switch err {
  782. case nil:
  783. service.Notice(rb, client.t("Successfully changed the channel settings"))
  784. displayChannelSetting(service, setting, settings, client, rb)
  785. case errInvalidParams:
  786. service.Notice(rb, client.t("Invalid parameters"))
  787. default:
  788. server.logger.Error("internal", "CS SET error:", err.Error())
  789. service.Notice(rb, client.t("An error occurred"))
  790. }
  791. }
  792. func csHowToBanHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  793. success := false
  794. defer func() {
  795. if success {
  796. service.Notice(rb, client.t("Note that if the user is currently in the channel, you must /KICK them after you ban them"))
  797. }
  798. }()
  799. chname, nick := params[0], params[1]
  800. channel := server.channels.Get(chname)
  801. if channel == nil {
  802. service.Notice(rb, client.t("No such channel"))
  803. return
  804. }
  805. if !(channel.ClientIsAtLeast(client, modes.ChannelOperator) || client.HasRoleCapabs("samode")) {
  806. service.Notice(rb, client.t("Insufficient privileges"))
  807. return
  808. }
  809. var details WhoWas
  810. target := server.clients.Get(nick)
  811. if target == nil {
  812. whowasList := server.whoWas.Find(nick, 1)
  813. if len(whowasList) == 0 {
  814. service.Notice(rb, client.t("No such nick"))
  815. return
  816. }
  817. service.Notice(rb, fmt.Sprintf(client.t("Warning: %s is not currently connected to the server. Using WHOWAS data, which may be inaccurate:"), nick))
  818. details = whowasList[0]
  819. } else {
  820. details = target.Details().WhoWas
  821. }
  822. if details.account != "" {
  823. if channel.getAmode(details.account) != modes.Mode(0) {
  824. service.Notice(rb, fmt.Sprintf(client.t("Warning: account %s currently has a persistent channel privilege granted with CS AMODE. If this mode is not removed, bans will not be respected"), details.accountName))
  825. return
  826. } else if details.account == channel.Founder() {
  827. service.Notice(rb, fmt.Sprintf(client.t("Warning: account %s is the channel founder and cannot be banned"), details.accountName))
  828. return
  829. }
  830. }
  831. config := server.Config()
  832. if !config.Server.Cloaks.EnabledForAlwaysOn {
  833. service.Notice(rb, client.t("Warning: server.ip-cloaking.enabled-for-always-on is disabled. This reduces the precision of channel bans."))
  834. }
  835. if details.account != "" {
  836. if config.Accounts.NickReservation.ForceNickEqualsAccount || target.AlwaysOn() {
  837. service.Notice(rb, fmt.Sprintf(client.t("User %[1]s is authenticated and can be banned by nickname: /MODE %[2]s +b %[3]s!*@*"), details.nick, channel.Name(), details.nick))
  838. success = true
  839. return
  840. }
  841. }
  842. ban := fmt.Sprintf("*!*@%s", strings.ToLower(details.hostname))
  843. banRe, err := utils.CompileGlob(ban, false)
  844. if err != nil {
  845. server.logger.Error("internal", "couldn't compile ban regex", ban, err.Error())
  846. service.Notice(rb, "An error occurred")
  847. return
  848. }
  849. var collateralDamage []string
  850. for _, mcl := range channel.Members() {
  851. if mcl != target && banRe.MatchString(mcl.NickMaskCasefolded()) {
  852. collateralDamage = append(collateralDamage, mcl.Nick())
  853. }
  854. }
  855. service.Notice(rb, fmt.Sprintf(client.t("User %[1]s can be banned by hostname: /MODE %[2]s +b %[3]s"), details.nick, channel.Name(), ban))
  856. success = true
  857. if len(collateralDamage) != 0 {
  858. service.Notice(rb, fmt.Sprintf(client.t("Warning: this ban will affect %d other users:"), len(collateralDamage)))
  859. for _, line := range utils.BuildTokenLines(maxLastArgLength, collateralDamage, " ") {
  860. service.Notice(rb, line)
  861. }
  862. }
  863. }