You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handlers.go 84KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2018 Daniel Oaks <daniel@danieloaks.net>
  4. // Copyright (c) 2017-2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  5. // released under the MIT license
  6. package irc
  7. import (
  8. "bytes"
  9. "encoding/base64"
  10. "fmt"
  11. "os"
  12. "runtime"
  13. "runtime/debug"
  14. "runtime/pprof"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/goshuirc/irc-go/ircfmt"
  20. "github.com/goshuirc/irc-go/ircmatch"
  21. "github.com/goshuirc/irc-go/ircmsg"
  22. "github.com/oragono/oragono/irc/caps"
  23. "github.com/oragono/oragono/irc/custime"
  24. "github.com/oragono/oragono/irc/history"
  25. "github.com/oragono/oragono/irc/modes"
  26. "github.com/oragono/oragono/irc/sno"
  27. "github.com/oragono/oragono/irc/utils"
  28. "golang.org/x/crypto/bcrypt"
  29. )
  30. // helper function to parse ACC callbacks, e.g., mailto:person@example.com, tel:16505551234
  31. func parseCallback(spec string, config *AccountConfig) (callbackNamespace string, callbackValue string) {
  32. callback := strings.ToLower(spec)
  33. if callback == "*" {
  34. callbackNamespace = "*"
  35. } else if strings.Contains(callback, ":") {
  36. callbackValues := strings.SplitN(callback, ":", 2)
  37. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  38. } else {
  39. // "If a callback namespace is not ... provided, the IRC server MUST use mailto""
  40. callbackNamespace = "mailto"
  41. callbackValue = callback
  42. }
  43. // ensure the callback namespace is valid
  44. // need to search callback list, maybe look at using a map later?
  45. for _, name := range config.Registration.EnabledCallbacks {
  46. if callbackNamespace == name {
  47. return
  48. }
  49. }
  50. // error value
  51. callbackNamespace = ""
  52. return
  53. }
  54. func registrationErrorToMessageAndCode(err error) (message, code string) {
  55. // default responses: let's be risk-averse about displaying internal errors
  56. // to the clients, especially for something as sensitive as accounts
  57. code = "REG_UNSPECIFIED_ERROR"
  58. message = `Could not register`
  59. switch err {
  60. case errAccountBadPassphrase:
  61. code = "REG_INVALID_CREDENTIAL"
  62. message = err.Error()
  63. case errAccountAlreadyRegistered, errAccountAlreadyVerified:
  64. message = err.Error()
  65. case errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists, errFeatureDisabled:
  66. message = err.Error()
  67. }
  68. return
  69. }
  70. // helper function to dispatch messages when a client successfully registers
  71. func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
  72. details := client.Details()
  73. if forNS {
  74. nsNotice(rb, client.t("Account created"))
  75. } else {
  76. rb.Add(nil, client.server.name, RPL_REG_SUCCESS, details.nick, details.accountName, client.t("Account created"))
  77. }
  78. client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] registered account $c[grey][$r%s$c[grey]]"), details.nickMask, details.accountName))
  79. sendSuccessfulAccountAuth(client, rb, forNS, false)
  80. }
  81. // sendSuccessfulAccountAuth means that an account auth attempt completed successfully, and is used to dispatch messages.
  82. func sendSuccessfulAccountAuth(client *Client, rb *ResponseBuffer, forNS, forSASL bool) {
  83. details := client.Details()
  84. if forNS {
  85. nsNotice(rb, fmt.Sprintf(client.t("You're now logged in as %s"), details.accountName))
  86. } else {
  87. //TODO(dan): some servers send this numeric even for NickServ logins iirc? to confirm and maybe do too
  88. rb.Add(nil, client.server.name, RPL_LOGGEDIN, details.nick, details.nickMask, details.accountName, fmt.Sprintf(client.t("You are now logged in as %s"), details.accountName))
  89. if forSASL {
  90. rb.Add(nil, client.server.name, RPL_SASLSUCCESS, details.nick, client.t("Authentication successful"))
  91. }
  92. }
  93. // dispatch account-notify
  94. for friend := range client.Friends(caps.AccountNotify) {
  95. friend.Send(nil, details.nickMask, "ACCOUNT", details.accountName)
  96. }
  97. client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] logged into account $c[grey][$r%s$c[grey]]"), details.nickMask, details.accountName))
  98. client.server.logger.Info("accounts", "client", details.nick, "logged into account", details.accountName)
  99. }
  100. // AUTHENTICATE [<mechanism>|<data>|*]
  101. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  102. session := rb.session
  103. config := server.Config()
  104. details := client.Details()
  105. if client.isSTSOnly {
  106. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  107. return false
  108. }
  109. if details.account != "" {
  110. rb.Add(nil, server.name, ERR_SASLALREADY, details.nick, client.t("You're already logged into an account"))
  111. return false
  112. }
  113. // sasl abort
  114. if !server.AccountConfig().AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
  115. rb.Add(nil, server.name, ERR_SASLABORTED, details.nick, client.t("SASL authentication aborted"))
  116. session.sasl.Clear()
  117. return false
  118. }
  119. // start new sasl session
  120. if session.sasl.mechanism == "" {
  121. mechanism := strings.ToUpper(msg.Params[0])
  122. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  123. if mechanismIsEnabled {
  124. session.sasl.mechanism = mechanism
  125. if !config.Server.Compatibility.SendUnprefixedSasl {
  126. // normal behavior
  127. rb.Add(nil, server.name, "AUTHENTICATE", "+")
  128. } else {
  129. // gross hack: send a raw message to ensure no tags or prefix
  130. rb.Flush(true)
  131. rb.session.SendRawMessage(ircmsg.MakeMessage(nil, "", "AUTHENTICATE", "+"), true)
  132. }
  133. } else {
  134. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  135. }
  136. return false
  137. }
  138. // continue existing sasl session
  139. rawData := msg.Params[0]
  140. if len(rawData) > 400 {
  141. rb.Add(nil, server.name, ERR_SASLTOOLONG, details.nick, client.t("SASL message too long"))
  142. session.sasl.Clear()
  143. return false
  144. } else if len(rawData) == 400 {
  145. // allow 4 'continuation' lines before rejecting for length
  146. if len(session.sasl.value) >= 400*4 {
  147. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Passphrase too long"))
  148. session.sasl.Clear()
  149. return false
  150. }
  151. session.sasl.value += rawData
  152. return false
  153. }
  154. if rawData != "+" {
  155. session.sasl.value += rawData
  156. }
  157. var data []byte
  158. var err error
  159. if session.sasl.value != "+" {
  160. data, err = base64.StdEncoding.DecodeString(session.sasl.value)
  161. if err != nil {
  162. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
  163. session.sasl.Clear()
  164. return false
  165. }
  166. }
  167. // call actual handler
  168. handler, handlerExists := EnabledSaslMechanisms[session.sasl.mechanism]
  169. // like 100% not required, but it's good to be safe I guess
  170. if !handlerExists {
  171. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  172. session.sasl.Clear()
  173. return false
  174. }
  175. // let the SASL handler do its thing
  176. exiting := handler(server, client, session.sasl.mechanism, data, rb)
  177. session.sasl.Clear()
  178. return exiting
  179. }
  180. // AUTHENTICATE PLAIN
  181. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  182. splitValue := bytes.Split(value, []byte{'\000'})
  183. // PLAIN has separate "authorization ID" (which user you want to become)
  184. // and "authentication ID" (whose password you want to use). the first is optional:
  185. // [authzid] \x00 authcid \x00 password
  186. var authzid, authcid string
  187. if len(splitValue) == 3 {
  188. authzid, authcid = string(splitValue[0]), string(splitValue[1])
  189. if authzid != "" && authcid != authzid {
  190. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: authcid and authzid should be the same"))
  191. return false
  192. }
  193. } else {
  194. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: Invalid auth blob"))
  195. return false
  196. }
  197. throttled, remainingTime := client.loginThrottle.Touch()
  198. if throttled {
  199. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  200. return false
  201. }
  202. password := string(splitValue[2])
  203. err := server.accounts.AuthenticateByPassphrase(client, authcid, password)
  204. if err != nil {
  205. msg := authErrorToMessage(server, err)
  206. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  207. return false
  208. }
  209. sendSuccessfulAccountAuth(client, rb, false, true)
  210. return false
  211. }
  212. func authErrorToMessage(server *Server, err error) (msg string) {
  213. switch err {
  214. case errAccountDoesNotExist, errAccountUnverified, errAccountInvalidCredentials, errAuthzidAuthcidMismatch:
  215. return err.Error()
  216. default:
  217. // don't expose arbitrary error messages to the user
  218. server.logger.Error("internal", "sasl authentication failure", err.Error())
  219. return "Unknown"
  220. }
  221. }
  222. // AUTHENTICATE EXTERNAL
  223. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  224. if rb.session.certfp == "" {
  225. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
  226. return false
  227. }
  228. // EXTERNAL doesn't carry an authentication ID (this is determined from the
  229. // certificate), but does carry an optional authorization ID.
  230. var authzid string
  231. var err error
  232. if len(value) != 0 {
  233. authzid, err = CasefoldName(string(value))
  234. if err != nil {
  235. err = errAuthzidAuthcidMismatch
  236. }
  237. }
  238. if err == nil {
  239. err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid)
  240. }
  241. if err != nil {
  242. msg := authErrorToMessage(server, err)
  243. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  244. return false
  245. }
  246. sendSuccessfulAccountAuth(client, rb, false, true)
  247. return false
  248. }
  249. // AWAY [<message>]
  250. func awayHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  251. var isAway bool
  252. var awayMessage string
  253. if len(msg.Params) > 0 {
  254. isAway = true
  255. awayMessage = msg.Params[0]
  256. awayLen := server.Config().Limits.AwayLen
  257. if len(awayMessage) > awayLen {
  258. awayMessage = awayMessage[:awayLen]
  259. }
  260. }
  261. client.SetAway(isAway, awayMessage)
  262. if isAway {
  263. rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
  264. } else {
  265. rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
  266. }
  267. // dispatch away-notify
  268. details := client.Details()
  269. for session := range client.Friends(caps.AwayNotify) {
  270. if isAway {
  271. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY", awayMessage)
  272. } else {
  273. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY")
  274. }
  275. }
  276. return false
  277. }
  278. // BATCH {+,-}reference-tag type [params...]
  279. func batchHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  280. tag := msg.Params[0]
  281. fail := false
  282. sendErrors := rb.session.batch.command != "NOTICE"
  283. if len(tag) == 0 {
  284. fail = true
  285. } else if tag[0] == '+' {
  286. if rb.session.batch.label != "" || msg.Params[1] != caps.MultilineBatchType {
  287. fail = true
  288. } else {
  289. rb.session.batch.label = tag[1:]
  290. rb.session.batch.tags = msg.ClientOnlyTags()
  291. if len(msg.Params) == 2 {
  292. fail = true
  293. } else {
  294. rb.session.batch.target = msg.Params[2]
  295. // save the response label for later
  296. rb.session.batch.responseLabel = rb.Label
  297. rb.Label = ""
  298. }
  299. }
  300. } else if tag[0] == '-' {
  301. if rb.session.batch.label == "" || rb.session.batch.label != tag[1:] {
  302. fail = true
  303. } else if rb.session.batch.message.LenLines() == 0 {
  304. fail = true
  305. } else {
  306. batch := rb.session.batch
  307. rb.session.batch = MultilineBatch{}
  308. // time tag should correspond to the time when the message was completed
  309. batch.message.SetTime()
  310. histType, err := msgCommandToHistType(batch.command)
  311. if err != nil {
  312. histType = history.Privmsg
  313. batch.command = "PRIVMSG"
  314. }
  315. // XXX changing the label inside a handler is a bit dodgy, but it works here
  316. // because there's no way we could have triggered a flush up to this point
  317. rb.Label = batch.responseLabel
  318. dispatchMessageToTarget(client, batch.tags, histType, batch.command, batch.target, batch.message, rb)
  319. }
  320. }
  321. if fail {
  322. rb.session.batch = MultilineBatch{}
  323. if sendErrors {
  324. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_INVALID", client.t("Invalid multiline batch"))
  325. }
  326. }
  327. return false
  328. }
  329. // BRB [message]
  330. func brbHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  331. success, duration := client.brbTimer.Enable()
  332. if !success {
  333. rb.Add(nil, server.name, "FAIL", "BRB", "CANNOT_BRB", client.t("Your client does not support BRB"))
  334. return false
  335. } else {
  336. rb.Add(nil, server.name, "BRB", strconv.Itoa(int(duration.Seconds())))
  337. }
  338. var message string
  339. if 0 < len(msg.Params) {
  340. message = msg.Params[0]
  341. } else {
  342. message = client.t("I'll be right back")
  343. }
  344. if len(client.Sessions()) == 1 {
  345. // true BRB
  346. client.SetAway(true, message)
  347. }
  348. return true
  349. }
  350. // CAP <subcmd> [<caps>]
  351. func capHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  352. details := client.Details()
  353. subCommand := strings.ToUpper(msg.Params[0])
  354. toAdd := caps.NewSet()
  355. toRemove := caps.NewSet()
  356. var capString string
  357. config := server.Config()
  358. supportedCaps := config.Server.supportedCaps
  359. if client.isSTSOnly {
  360. supportedCaps = stsOnlyCaps
  361. }
  362. badCaps := false
  363. if len(msg.Params) > 1 {
  364. capString = msg.Params[1]
  365. strs := strings.Fields(capString)
  366. for _, str := range strs {
  367. remove := false
  368. if str[0] == '-' {
  369. str = str[1:]
  370. remove = true
  371. }
  372. capab, err := caps.NameToCapability(str)
  373. if err != nil || (!remove && !supportedCaps.Has(capab)) {
  374. badCaps = true
  375. } else if !remove {
  376. toAdd.Enable(capab)
  377. } else {
  378. toRemove.Enable(capab)
  379. }
  380. }
  381. }
  382. sendCapLines := func(cset *caps.Set, values caps.Values) {
  383. version := rb.session.capVersion
  384. // we're working around two bugs:
  385. // 1. weechat 1.4 won't accept the CAP reply unless it contains the server.name source
  386. // 2. old versions of Kiwi and The Lounge can't parse multiline CAP LS 302 (#661),
  387. // so try as hard as possible to get the response to fit on one line.
  388. // :server.name CAP * LS * :<tokens>
  389. // 1 7 4
  390. maxLen := 510 - 1 - len(server.name) - 7 - len(subCommand) - 4
  391. capLines := cset.Strings(version, values, maxLen)
  392. for i, capStr := range capLines {
  393. if version >= caps.Cap302 && i < len(capLines)-1 {
  394. rb.Add(nil, server.name, "CAP", details.nick, subCommand, "*", capStr)
  395. } else {
  396. rb.Add(nil, server.name, "CAP", details.nick, subCommand, capStr)
  397. }
  398. }
  399. }
  400. switch subCommand {
  401. case "LS":
  402. if !client.registered {
  403. rb.session.capState = caps.NegotiatingState
  404. }
  405. if 1 < len(msg.Params) {
  406. num, err := strconv.Atoi(msg.Params[1])
  407. newVersion := caps.Version(num)
  408. if err == nil && rb.session.capVersion < newVersion {
  409. rb.session.capVersion = newVersion
  410. }
  411. }
  412. sendCapLines(supportedCaps, config.Server.capValues)
  413. case "LIST":
  414. // values not sent on LIST
  415. sendCapLines(&rb.session.capabilities, nil)
  416. case "REQ":
  417. if !client.registered {
  418. rb.session.capState = caps.NegotiatingState
  419. }
  420. // make sure all capabilities actually exist
  421. // #511, #521: oragono.io/nope is a fake cap to trap bad clients who blindly request
  422. // every offered capability. during registration, requesting it produces a quit,
  423. // otherwise just a CAP NAK
  424. if badCaps || (toAdd.Has(caps.Nope) && client.registered) {
  425. rb.Add(nil, server.name, "CAP", details.nick, "NAK", capString)
  426. return false
  427. } else if toAdd.Has(caps.Nope) && !client.registered {
  428. client.Quit(fmt.Sprintf(client.t("Requesting the %s client capability is forbidden"), caps.Nope.Name()), rb.session)
  429. return true
  430. }
  431. rb.session.capabilities.Union(toAdd)
  432. rb.session.capabilities.Subtract(toRemove)
  433. rb.Add(nil, server.name, "CAP", details.nick, "ACK", capString)
  434. // if this is the first time the client is requesting a resume token,
  435. // send it to them
  436. if toAdd.Has(caps.Resume) {
  437. token, id := server.resumeManager.GenerateToken(client)
  438. if token != "" {
  439. rb.Add(nil, server.name, "RESUME", "TOKEN", token)
  440. rb.session.SetResumeID(id)
  441. }
  442. }
  443. case "END":
  444. if !client.registered {
  445. rb.session.capState = caps.NegotiatedState
  446. }
  447. default:
  448. rb.Add(nil, server.name, ERR_INVALIDCAPCMD, details.nick, subCommand, client.t("Invalid CAP subcommand"))
  449. }
  450. return false
  451. }
  452. // CHATHISTORY <target> <preposition> <query> [<limit>]
  453. // e.g., CHATHISTORY #ircv3 AFTER id=ytNBbt565yt4r3err3 10
  454. // CHATHISTORY <target> BETWEEN <query> <query> <direction> [<limit>]
  455. // e.g., CHATHISTORY #ircv3 BETWEEN timestamp=YYYY-MM-DDThh:mm:ss.sssZ timestamp=YYYY-MM-DDThh:mm:ss.sssZ + 100
  456. func chathistoryHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (exiting bool) {
  457. var items []history.Item
  458. unknown_command := false
  459. var target string
  460. var channel *Channel
  461. var sequence history.Sequence
  462. var err error
  463. defer func() {
  464. // successful responses are sent as a chathistory or history batch
  465. if err == nil {
  466. if channel != nil {
  467. channel.replayHistoryItems(rb, items, false)
  468. } else {
  469. client.replayPrivmsgHistory(rb, items, target, true)
  470. }
  471. return
  472. }
  473. // errors are sent either without a batch, or in a draft/labeled-response batch as usual
  474. if unknown_command {
  475. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "UNKNOWN_COMMAND", utils.SafeErrorParam(msg.Params[0]), client.t("Unknown command"))
  476. } else if err == utils.ErrInvalidParams {
  477. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_PARAMETERS", msg.Params[0], client.t("Invalid parameters"))
  478. } else if err != nil {
  479. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "MESSAGE_ERROR", msg.Params[0], client.t("Messages could not be retrieved"))
  480. } else if sequence == nil {
  481. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "NO_SUCH_CHANNEL", utils.SafeErrorParam(msg.Params[1]), client.t("No such channel"))
  482. }
  483. }()
  484. config := server.Config()
  485. maxChathistoryLimit := config.History.ChathistoryMax
  486. if maxChathistoryLimit == 0 {
  487. return
  488. }
  489. preposition := strings.ToLower(msg.Params[0])
  490. target = msg.Params[1]
  491. parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
  492. if param == "*" && (preposition == "before" || preposition == "between") {
  493. // XXX compatibility with kiwi, which as of February 2020 is
  494. // using BEFORE * as a synonym for LATEST *
  495. return
  496. }
  497. err = utils.ErrInvalidParams
  498. pieces := strings.SplitN(param, "=", 2)
  499. if len(pieces) < 2 {
  500. return
  501. }
  502. identifier, value := strings.ToLower(pieces[0]), pieces[1]
  503. if identifier == "msgid" {
  504. msgid, err = value, nil
  505. return
  506. } else if identifier == "timestamp" {
  507. timestamp, err = time.Parse(IRCv3TimestampFormat, value)
  508. return
  509. }
  510. return
  511. }
  512. parseHistoryLimit := func(paramIndex int) (limit int) {
  513. if len(msg.Params) < (paramIndex + 1) {
  514. return maxChathistoryLimit
  515. }
  516. limit, err := strconv.Atoi(msg.Params[paramIndex])
  517. if err != nil || limit == 0 || limit > maxChathistoryLimit {
  518. limit = maxChathistoryLimit
  519. }
  520. return
  521. }
  522. channel, sequence, err = server.GetHistorySequence(nil, client, target)
  523. if err != nil || sequence == nil {
  524. return
  525. }
  526. roundUp := func(endpoint time.Time) (result time.Time) {
  527. return endpoint.Truncate(time.Millisecond).Add(time.Millisecond)
  528. }
  529. var start, end history.Selector
  530. var limit int
  531. switch preposition {
  532. case "between":
  533. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  534. if err != nil {
  535. return
  536. }
  537. end.Msgid, end.Time, err = parseQueryParam(msg.Params[3])
  538. if err != nil {
  539. return
  540. }
  541. // XXX preserve the ordering of the two parameters, since we might be going backwards,
  542. // but round up the chronologically first one, whichever it is, to make it exclusive
  543. if !start.Time.IsZero() && !end.Time.IsZero() {
  544. if start.Time.Before(end.Time) {
  545. start.Time = roundUp(start.Time)
  546. } else {
  547. end.Time = roundUp(end.Time)
  548. }
  549. }
  550. limit = parseHistoryLimit(4)
  551. case "before", "after", "around":
  552. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  553. if err != nil {
  554. return
  555. }
  556. if preposition == "after" && !start.Time.IsZero() {
  557. start.Time = roundUp(start.Time)
  558. }
  559. if preposition == "before" {
  560. end = start
  561. start = history.Selector{}
  562. }
  563. limit = parseHistoryLimit(3)
  564. case "latest":
  565. if msg.Params[2] != "*" {
  566. end.Msgid, end.Time, err = parseQueryParam(msg.Params[2])
  567. if err != nil {
  568. return
  569. }
  570. if !end.Time.IsZero() {
  571. end.Time = roundUp(end.Time)
  572. }
  573. start.Time = time.Now().UTC()
  574. }
  575. limit = parseHistoryLimit(3)
  576. default:
  577. unknown_command = true
  578. return
  579. }
  580. if preposition == "around" {
  581. items, err = sequence.Around(start, limit)
  582. } else {
  583. items, _, err = sequence.Between(start, end, limit)
  584. }
  585. return
  586. }
  587. // DEBUG <subcmd>
  588. func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  589. param := strings.ToUpper(msg.Params[0])
  590. switch param {
  591. case "GCSTATS":
  592. stats := debug.GCStats{
  593. Pause: make([]time.Duration, 10),
  594. PauseQuantiles: make([]time.Duration, 5),
  595. }
  596. debug.ReadGCStats(&stats)
  597. rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
  598. rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
  599. rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
  600. rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
  601. rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
  602. rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
  603. rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
  604. rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
  605. case "NUMGOROUTINE":
  606. count := runtime.NumGoroutine()
  607. rb.Notice(fmt.Sprintf("num goroutines: %d", count))
  608. case "PROFILEHEAP":
  609. profFile := "oragono.mprof"
  610. file, err := os.Create(profFile)
  611. if err != nil {
  612. rb.Notice(fmt.Sprintf("error: %s", err))
  613. break
  614. }
  615. defer file.Close()
  616. pprof.Lookup("heap").WriteTo(file, 0)
  617. rb.Notice(fmt.Sprintf("written to %s", profFile))
  618. case "STARTCPUPROFILE":
  619. profFile := "oragono.prof"
  620. file, err := os.Create(profFile)
  621. if err != nil {
  622. rb.Notice(fmt.Sprintf("error: %s", err))
  623. break
  624. }
  625. if err := pprof.StartCPUProfile(file); err != nil {
  626. defer file.Close()
  627. rb.Notice(fmt.Sprintf("error: %s", err))
  628. break
  629. }
  630. rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
  631. case "STOPCPUPROFILE":
  632. pprof.StopCPUProfile()
  633. rb.Notice(fmt.Sprintf("CPU profiling stopped"))
  634. case "CRASHSERVER":
  635. if !client.HasRoleCapabs("oper:rehash") {
  636. rb.Notice(client.t("You must have rehash permissions in order to execute DEBUG CRASHSERVER"))
  637. return false
  638. }
  639. code := utils.ConfirmationCode(server.name, server.ctime)
  640. if len(msg.Params) == 1 || msg.Params[1] != code {
  641. rb.Notice(fmt.Sprintf(client.t("To crash the server, issue the following command: /DEBUG CRASHSERVER %s"), code))
  642. return false
  643. }
  644. server.logger.Error("server", fmt.Sprintf("DEBUG CRASHSERVER executed by operator %s", client.Oper().Name))
  645. go func() {
  646. // intentional nil dereference on a new goroutine, bypassing recover-from-errors
  647. var i, j *int
  648. *i = *j
  649. }()
  650. default:
  651. rb.Notice(client.t("Unrecognized DEBUG subcommand"))
  652. }
  653. return false
  654. }
  655. // helper for parsing the reason args to DLINE and KLINE
  656. func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
  657. reason = "No reason given"
  658. operReason = ""
  659. if len(params) > currentArg {
  660. reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
  661. if len(reasons) == 1 {
  662. reason = strings.TrimSpace(reasons[0])
  663. } else if len(reasons) == 2 {
  664. reason = strings.TrimSpace(reasons[0])
  665. operReason = strings.TrimSpace(reasons[1])
  666. }
  667. }
  668. return
  669. }
  670. func formatBanForListing(client *Client, key string, info IPBanInfo) string {
  671. desc := info.Reason
  672. if info.OperReason != "" && info.OperReason != info.Reason {
  673. desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
  674. }
  675. if info.Duration != 0 {
  676. desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
  677. }
  678. return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
  679. }
  680. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  681. // DLINE LIST
  682. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  683. // check oper permissions
  684. oper := client.Oper()
  685. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  686. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  687. return false
  688. }
  689. currentArg := 0
  690. // if they say LIST, we just list the current dlines
  691. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  692. bans := server.dlines.AllBans()
  693. if len(bans) == 0 {
  694. rb.Notice(client.t("No DLINEs have been set!"))
  695. }
  696. for key, info := range bans {
  697. client.Notice(formatBanForListing(client, key, info))
  698. }
  699. return false
  700. }
  701. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  702. var andKill bool
  703. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  704. andKill = true
  705. currentArg++
  706. }
  707. // when setting a ban that covers the oper's current connection, we require them to say
  708. // "DLINE MYSELF" so that we're sure they really mean it.
  709. var dlineMyself bool
  710. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  711. dlineMyself = true
  712. currentArg++
  713. }
  714. // duration
  715. duration, err := custime.ParseDuration(msg.Params[currentArg])
  716. if err != nil {
  717. duration = 0
  718. } else {
  719. currentArg++
  720. }
  721. // get host
  722. if len(msg.Params) < currentArg+1 {
  723. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  724. return false
  725. }
  726. hostString := msg.Params[currentArg]
  727. currentArg++
  728. // check host
  729. hostNet, err := utils.NormalizedNetFromString(hostString)
  730. if err != nil {
  731. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  732. return false
  733. }
  734. if !dlineMyself && hostNet.Contains(client.IP()) {
  735. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("This ban matches you. To DLINE yourself, you must use the command: /DLINE MYSELF <arguments>"))
  736. return false
  737. }
  738. // check remote
  739. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  740. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  741. return false
  742. }
  743. // get comment(s)
  744. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  745. operName := oper.Name
  746. if operName == "" {
  747. operName = server.name
  748. }
  749. err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
  750. if err != nil {
  751. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
  752. return false
  753. }
  754. var snoDescription string
  755. hostString = utils.NetToNormalizedString(hostNet)
  756. if duration != 0 {
  757. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
  758. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
  759. } else {
  760. rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
  761. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
  762. }
  763. server.snomasks.Send(sno.LocalXline, snoDescription)
  764. var killClient bool
  765. if andKill {
  766. var clientsToKill []*Client
  767. var killedClientNicks []string
  768. for _, mcl := range server.clients.AllClients() {
  769. if hostNet.Contains(mcl.IP()) {
  770. clientsToKill = append(clientsToKill, mcl)
  771. killedClientNicks = append(killedClientNicks, mcl.nick)
  772. }
  773. }
  774. for _, mcl := range clientsToKill {
  775. mcl.SetExitedSnomaskSent()
  776. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  777. if mcl == client {
  778. killClient = true
  779. } else {
  780. // if mcl == client, we kill them below
  781. mcl.destroy(nil)
  782. }
  783. }
  784. // send snomask
  785. sort.Strings(killedClientNicks)
  786. server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s [%s] killed %d clients with a DLINE $c[grey][$r%s$c[grey]]"), client.nick, operName, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
  787. }
  788. return killClient
  789. }
  790. // HELP [<query>]
  791. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  792. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  793. if len(argument) < 1 {
  794. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  795. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  796. return false
  797. }
  798. // handle index
  799. if argument == "index" {
  800. client.sendHelp("HELP", server.helpIndexManager.GetIndex(client.Languages(), client.HasMode(modes.Operator)), rb)
  801. return false
  802. }
  803. helpHandler, exists := Help[argument]
  804. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  805. if helpHandler.textGenerator != nil {
  806. client.sendHelp(strings.ToUpper(argument), helpHandler.textGenerator(client), rb)
  807. } else {
  808. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  809. }
  810. } else {
  811. args := msg.Params
  812. args = append(args, client.t("Help not found"))
  813. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  814. }
  815. return false
  816. }
  817. // HISTORY <target> [<limit>]
  818. // e.g., HISTORY #ubuntu 10
  819. // HISTORY me 15
  820. // HISTORY #darwin 1h
  821. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  822. config := server.Config()
  823. if !config.History.Enabled {
  824. rb.Notice(client.t("This command has been disabled by the server administrators"))
  825. return false
  826. }
  827. target := msg.Params[0]
  828. if strings.ToLower(target) == "me" {
  829. target = "*"
  830. }
  831. channel, sequence, err := server.GetHistorySequence(nil, client, target)
  832. if sequence == nil || err != nil {
  833. // whatever
  834. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  835. return false
  836. }
  837. var duration time.Duration
  838. maxChathistoryLimit := config.History.ChathistoryMax
  839. limit := 100
  840. if maxChathistoryLimit < limit {
  841. limit = maxChathistoryLimit
  842. }
  843. if len(msg.Params) > 1 {
  844. providedLimit, err := strconv.Atoi(msg.Params[1])
  845. if err == nil && providedLimit != 0 {
  846. limit = providedLimit
  847. if maxChathistoryLimit < limit {
  848. limit = maxChathistoryLimit
  849. }
  850. } else if err != nil {
  851. duration, err = time.ParseDuration(msg.Params[1])
  852. if err == nil {
  853. limit = maxChathistoryLimit
  854. }
  855. }
  856. }
  857. var items []history.Item
  858. if duration == 0 {
  859. items, _, err = sequence.Between(history.Selector{}, history.Selector{}, limit)
  860. } else {
  861. now := time.Now().UTC()
  862. start := history.Selector{Time: now}
  863. end := history.Selector{Time: now.Add(-duration)}
  864. items, _, err = sequence.Between(start, end, limit)
  865. }
  866. if err == nil && len(items) != 0 {
  867. if channel != nil {
  868. channel.replayHistoryItems(rb, items, false)
  869. } else {
  870. client.replayPrivmsgHistory(rb, items, "", true)
  871. }
  872. }
  873. return false
  874. }
  875. // INFO
  876. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  877. // we do the below so that the human-readable lines in info can be translated.
  878. for _, line := range infoString1 {
  879. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  880. }
  881. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
  882. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  883. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Thanks to Jeremy Latt for founding Ergonomadic, the project this is based on")+" <3")
  884. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  885. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
  886. for _, line := range infoString2 {
  887. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  888. }
  889. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
  890. for _, line := range infoString3 {
  891. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  892. }
  893. // show translators for languages other than good ole' regular English
  894. tlines := server.Languages().Translators()
  895. if 0 < len(tlines) {
  896. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
  897. for _, line := range tlines {
  898. rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
  899. }
  900. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  901. }
  902. rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
  903. return false
  904. }
  905. // INVITE <nickname> <channel>
  906. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  907. nickname := msg.Params[0]
  908. channelName := msg.Params[1]
  909. target := server.clients.Get(nickname)
  910. if target == nil {
  911. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  912. return false
  913. }
  914. channel := server.channels.Get(channelName)
  915. if channel == nil {
  916. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(channelName), client.t("No such channel"))
  917. return false
  918. }
  919. channel.Invite(target, client, rb)
  920. return false
  921. }
  922. // ISON <nick>{ <nick>}
  923. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  924. var nicks = msg.Params
  925. ison := make([]string, 0, len(msg.Params))
  926. for _, nick := range nicks {
  927. currentNick := server.getCurrentNick(nick)
  928. if currentNick != "" {
  929. ison = append(ison, currentNick)
  930. }
  931. }
  932. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  933. return false
  934. }
  935. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  936. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  937. // kill JOIN 0 requests
  938. if msg.Params[0] == "0" {
  939. rb.Notice(client.t("JOIN 0 is not allowed"))
  940. return false
  941. }
  942. // handle regular JOINs
  943. channels := strings.Split(msg.Params[0], ",")
  944. var keys []string
  945. if len(msg.Params) > 1 {
  946. keys = strings.Split(msg.Params[1], ",")
  947. }
  948. config := server.Config()
  949. oper := client.Oper()
  950. for i, name := range channels {
  951. if name == "" {
  952. continue // #679
  953. }
  954. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  955. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  956. return false
  957. }
  958. var key string
  959. if len(keys) > i {
  960. key = keys[i]
  961. }
  962. err := server.channels.Join(client, name, key, false, rb)
  963. if err != nil {
  964. sendJoinError(client, name, rb, err)
  965. }
  966. }
  967. return false
  968. }
  969. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  970. var errMsg string
  971. switch err {
  972. case errInsufficientPrivs:
  973. errMsg = `Only server operators can create new channels`
  974. case errConfusableIdentifier:
  975. errMsg = `That channel name is too close to the name of another channel`
  976. case errChannelPurged:
  977. errMsg = err.Error()
  978. default:
  979. errMsg = `No such channel`
  980. }
  981. rb.Add(nil, client.server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(name), client.t(errMsg))
  982. }
  983. // SAJOIN [nick] #channel{,#channel}
  984. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  985. var target *Client
  986. var channelString string
  987. if strings.HasPrefix(msg.Params[0], "#") {
  988. target = client
  989. channelString = msg.Params[0]
  990. } else {
  991. if len(msg.Params) == 1 {
  992. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  993. return false
  994. } else {
  995. target = server.clients.Get(msg.Params[0])
  996. if target == nil {
  997. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  998. return false
  999. }
  1000. channelString = msg.Params[1]
  1001. }
  1002. }
  1003. channels := strings.Split(channelString, ",")
  1004. for _, chname := range channels {
  1005. err := server.channels.Join(target, chname, "", true, rb)
  1006. if err != nil {
  1007. sendJoinError(client, chname, rb, err)
  1008. }
  1009. }
  1010. return false
  1011. }
  1012. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1013. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1014. channels := strings.Split(msg.Params[0], ",")
  1015. users := strings.Split(msg.Params[1], ",")
  1016. if (len(channels) != len(users)) && (len(users) != 1) {
  1017. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1018. return false
  1019. }
  1020. type kickCmd struct {
  1021. channel string
  1022. nick string
  1023. }
  1024. kicks := make([]kickCmd, 0, len(channels))
  1025. for index, channel := range channels {
  1026. if channel == "" {
  1027. continue // #679
  1028. }
  1029. if len(users) == 1 {
  1030. kicks = append(kicks, kickCmd{channel, users[0]})
  1031. } else {
  1032. kicks = append(kicks, kickCmd{channel, users[index]})
  1033. }
  1034. }
  1035. var comment string
  1036. if len(msg.Params) > 2 {
  1037. comment = msg.Params[2]
  1038. }
  1039. for _, kick := range kicks {
  1040. channel := server.channels.Get(kick.channel)
  1041. if channel == nil {
  1042. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1043. continue
  1044. }
  1045. target := server.clients.Get(kick.nick)
  1046. if target == nil {
  1047. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1048. continue
  1049. }
  1050. if comment == "" {
  1051. comment = kick.nick
  1052. }
  1053. channel.Kick(client, target, comment, rb, false)
  1054. }
  1055. return false
  1056. }
  1057. // KILL <nickname> <comment>
  1058. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1059. nickname := msg.Params[0]
  1060. comment := "<no reason supplied>"
  1061. if len(msg.Params) > 1 {
  1062. comment = msg.Params[1]
  1063. }
  1064. target := server.clients.Get(nickname)
  1065. if target == nil {
  1066. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(nickname), client.t("No such nick"))
  1067. return false
  1068. }
  1069. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1070. server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s$r was killed by %s $c[grey][$r%s$c[grey]]"), target.nick, client.nick, comment))
  1071. target.SetExitedSnomaskSent()
  1072. target.Quit(quitMsg, nil)
  1073. target.destroy(nil)
  1074. return false
  1075. }
  1076. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1077. // KLINE LIST
  1078. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1079. details := client.Details()
  1080. // check oper permissions
  1081. oper := client.Oper()
  1082. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  1083. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1084. return false
  1085. }
  1086. currentArg := 0
  1087. // if they say LIST, we just list the current klines
  1088. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1089. bans := server.klines.AllBans()
  1090. if len(bans) == 0 {
  1091. client.Notice("No KLINEs have been set!")
  1092. }
  1093. for key, info := range bans {
  1094. client.Notice(formatBanForListing(client, key, info))
  1095. }
  1096. return false
  1097. }
  1098. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1099. var andKill bool
  1100. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1101. andKill = true
  1102. currentArg++
  1103. }
  1104. // when setting a ban that covers the oper's current connection, we require them to say
  1105. // "KLINE MYSELF" so that we're sure they really mean it.
  1106. var klineMyself bool
  1107. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1108. klineMyself = true
  1109. currentArg++
  1110. }
  1111. // duration
  1112. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1113. if err != nil {
  1114. duration = 0
  1115. } else {
  1116. currentArg++
  1117. }
  1118. // get mask
  1119. if len(msg.Params) < currentArg+1 {
  1120. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1121. return false
  1122. }
  1123. mask := msg.Params[currentArg]
  1124. currentArg++
  1125. // check mask
  1126. mask, err = CanonicalizeMaskWildcard(mask)
  1127. if err != nil {
  1128. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1129. return false
  1130. }
  1131. matcher := ircmatch.MakeMatch(mask)
  1132. for _, clientMask := range client.AllNickmasks() {
  1133. if !klineMyself && matcher.Match(clientMask) {
  1134. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("This ban matches you. To KLINE yourself, you must use the command: /KLINE MYSELF <arguments>"))
  1135. return false
  1136. }
  1137. }
  1138. // check remote
  1139. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1140. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1141. return false
  1142. }
  1143. // get oper name
  1144. operName := oper.Name
  1145. if operName == "" {
  1146. operName = server.name
  1147. }
  1148. // get comment(s)
  1149. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1150. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1151. if err != nil {
  1152. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1153. return false
  1154. }
  1155. var snoDescription string
  1156. if duration != 0 {
  1157. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1158. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1159. } else {
  1160. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1161. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1162. }
  1163. server.snomasks.Send(sno.LocalXline, snoDescription)
  1164. var killClient bool
  1165. if andKill {
  1166. var clientsToKill []*Client
  1167. var killedClientNicks []string
  1168. for _, mcl := range server.clients.AllClients() {
  1169. for _, clientMask := range mcl.AllNickmasks() {
  1170. if matcher.Match(clientMask) {
  1171. clientsToKill = append(clientsToKill, mcl)
  1172. killedClientNicks = append(killedClientNicks, mcl.nick)
  1173. }
  1174. }
  1175. }
  1176. for _, mcl := range clientsToKill {
  1177. mcl.SetExitedSnomaskSent()
  1178. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1179. if mcl == client {
  1180. killClient = true
  1181. } else {
  1182. // if mcl == client, we kill them below
  1183. mcl.destroy(nil)
  1184. }
  1185. }
  1186. // send snomask
  1187. sort.Strings(killedClientNicks)
  1188. server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s [%s] killed %d clients with a KLINE $c[grey][$r%s$c[grey]]"), details.nick, operName, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
  1189. }
  1190. return killClient
  1191. }
  1192. // LANGUAGE <code>{ <code>}
  1193. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1194. nick := client.Nick()
  1195. alreadyDoneLanguages := make(map[string]bool)
  1196. var appliedLanguages []string
  1197. lm := server.Languages()
  1198. supportedLanguagesCount := lm.Count()
  1199. if supportedLanguagesCount < len(msg.Params) {
  1200. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1201. return false
  1202. }
  1203. for _, value := range msg.Params {
  1204. value = strings.ToLower(value)
  1205. // strip ~ from the language if it has it
  1206. value = strings.TrimPrefix(value, "~")
  1207. // silently ignore empty languages or those with spaces in them
  1208. if len(value) == 0 || strings.Contains(value, " ") {
  1209. continue
  1210. }
  1211. _, exists := lm.Languages[value]
  1212. if !exists {
  1213. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1214. return false
  1215. }
  1216. // if we've already applied the given language, skip it
  1217. _, exists = alreadyDoneLanguages[value]
  1218. if exists {
  1219. continue
  1220. }
  1221. appliedLanguages = append(appliedLanguages, value)
  1222. }
  1223. var langsToSet []string
  1224. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1225. langsToSet = appliedLanguages
  1226. }
  1227. client.SetLanguages(langsToSet)
  1228. params := make([]string, len(appliedLanguages)+2)
  1229. params[0] = nick
  1230. copy(params[1:], appliedLanguages)
  1231. params[len(params)-1] = client.t("Language preferences have been set")
  1232. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1233. return false
  1234. }
  1235. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1236. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1237. // get channels
  1238. var channels []string
  1239. for _, param := range msg.Params {
  1240. if 0 < len(param) && param[0] == '#' {
  1241. for _, channame := range strings.Split(param, ",") {
  1242. if 0 < len(channame) && channame[0] == '#' {
  1243. channels = append(channels, channame)
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // get elist conditions
  1249. var matcher elistMatcher
  1250. for _, param := range msg.Params {
  1251. if len(param) < 1 {
  1252. continue
  1253. }
  1254. if param[0] == '<' {
  1255. param = param[1:]
  1256. val, err := strconv.Atoi(param)
  1257. if err != nil {
  1258. continue
  1259. }
  1260. matcher.MaxClientsActive = true
  1261. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1262. }
  1263. if param[0] == '>' {
  1264. param = param[1:]
  1265. val, err := strconv.Atoi(param)
  1266. if err != nil {
  1267. continue
  1268. }
  1269. matcher.MinClientsActive = true
  1270. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1271. }
  1272. }
  1273. clientIsOp := client.HasMode(modes.Operator)
  1274. if len(channels) == 0 {
  1275. for _, channel := range server.channels.Channels() {
  1276. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1277. continue
  1278. }
  1279. if matcher.Matches(channel) {
  1280. client.RplList(channel, rb)
  1281. }
  1282. }
  1283. } else {
  1284. // limit regular users to only listing one channel
  1285. if !clientIsOp {
  1286. channels = channels[:1]
  1287. }
  1288. for _, chname := range channels {
  1289. channel := server.channels.Get(chname)
  1290. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1291. if len(chname) > 0 {
  1292. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1293. }
  1294. continue
  1295. }
  1296. if matcher.Matches(channel) {
  1297. client.RplList(channel, rb)
  1298. }
  1299. }
  1300. }
  1301. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1302. return false
  1303. }
  1304. // LUSERS [<mask> [<server>]]
  1305. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1306. server.Lusers(client, rb)
  1307. return false
  1308. }
  1309. // MODE <target> [<modestring> [<mode arguments>...]]
  1310. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1311. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1312. return cmodeHandler(server, client, msg, rb)
  1313. }
  1314. return umodeHandler(server, client, msg, rb)
  1315. }
  1316. // MODE <channel> [<modestring> [<mode arguments>...]]
  1317. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1318. channel := server.channels.Get(msg.Params[0])
  1319. if channel == nil {
  1320. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1321. return false
  1322. }
  1323. var changes modes.ModeChanges
  1324. if 1 < len(msg.Params) {
  1325. // parse out real mode changes
  1326. params := msg.Params[1:]
  1327. var unknown map[rune]bool
  1328. changes, unknown = modes.ParseChannelModeChanges(params...)
  1329. // alert for unknown mode changes
  1330. for char := range unknown {
  1331. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1332. }
  1333. if len(unknown) == 1 && len(changes) == 0 {
  1334. return false
  1335. }
  1336. }
  1337. // process mode changes, include list operations (an empty set of changes does a list)
  1338. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1339. // save changes
  1340. var includeFlags uint
  1341. for _, change := range applied {
  1342. includeFlags |= IncludeModes
  1343. if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
  1344. includeFlags |= IncludeLists
  1345. }
  1346. }
  1347. if includeFlags != 0 {
  1348. channel.MarkDirty(includeFlags)
  1349. }
  1350. // send out changes
  1351. if len(applied) > 0 {
  1352. prefix := client.NickMaskString()
  1353. //TODO(dan): we should change the name of String and make it return a slice here
  1354. args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
  1355. rb.Add(nil, prefix, "MODE", args...)
  1356. for _, session := range client.Sessions() {
  1357. if session != rb.session {
  1358. session.Send(nil, prefix, "MODE", args...)
  1359. }
  1360. }
  1361. for _, member := range channel.Members() {
  1362. if member != client {
  1363. member.Send(nil, prefix, "MODE", args...)
  1364. }
  1365. }
  1366. }
  1367. return false
  1368. }
  1369. // MODE <client> [<modestring> [<mode arguments>...]]
  1370. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1371. cDetails := client.Details()
  1372. target := server.clients.Get(msg.Params[0])
  1373. if target == nil {
  1374. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1375. return false
  1376. }
  1377. targetNick := target.Nick()
  1378. hasPrivs := client == target || msg.Command == "SAMODE"
  1379. if !hasPrivs {
  1380. if len(msg.Params) > 1 {
  1381. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1382. } else {
  1383. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1384. }
  1385. return false
  1386. }
  1387. // applied mode changes
  1388. applied := make(modes.ModeChanges, 0)
  1389. if 1 < len(msg.Params) {
  1390. // parse out real mode changes
  1391. params := msg.Params[1:]
  1392. changes, unknown := modes.ParseUserModeChanges(params...)
  1393. // alert for unknown mode changes
  1394. for char := range unknown {
  1395. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1396. }
  1397. if len(unknown) == 1 && len(changes) == 0 {
  1398. return false
  1399. }
  1400. // apply mode changes
  1401. applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
  1402. }
  1403. if len(applied) > 0 {
  1404. rb.Add(nil, cDetails.nickMask, "MODE", targetNick, applied.String())
  1405. } else if hasPrivs {
  1406. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1407. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1408. masks := server.snomasks.String(target)
  1409. if 0 < len(masks) {
  1410. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1411. }
  1412. }
  1413. }
  1414. return false
  1415. }
  1416. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1417. func (server *Server) getCurrentNick(nick string) (result string) {
  1418. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1419. return service.Name
  1420. } else if iclient := server.clients.Get(nick); iclient != nil {
  1421. return iclient.Nick()
  1422. }
  1423. return ""
  1424. }
  1425. // MONITOR <subcmd> [params...]
  1426. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1427. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1428. if !exists {
  1429. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1430. return false
  1431. }
  1432. return handler(server, client, msg, rb)
  1433. }
  1434. // MONITOR - <target>{,<target>}
  1435. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1436. if len(msg.Params) < 2 {
  1437. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1438. return false
  1439. }
  1440. targets := strings.Split(msg.Params[1], ",")
  1441. for _, target := range targets {
  1442. cfnick, err := CasefoldName(target)
  1443. if err != nil {
  1444. continue
  1445. }
  1446. server.monitorManager.Remove(client, cfnick)
  1447. }
  1448. return false
  1449. }
  1450. // MONITOR + <target>{,<target>}
  1451. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1452. if len(msg.Params) < 2 {
  1453. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1454. return false
  1455. }
  1456. var online []string
  1457. var offline []string
  1458. limits := server.Config().Limits
  1459. targets := strings.Split(msg.Params[1], ",")
  1460. for _, target := range targets {
  1461. // check name length
  1462. if len(target) < 1 || len(targets) > limits.NickLen {
  1463. continue
  1464. }
  1465. // add target
  1466. casefoldedTarget, err := CasefoldName(target)
  1467. if err != nil {
  1468. continue
  1469. }
  1470. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1471. if err == errMonitorLimitExceeded {
  1472. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1473. break
  1474. } else if err != nil {
  1475. continue
  1476. }
  1477. currentNick := server.getCurrentNick(target)
  1478. // add to online / offline lists
  1479. if currentNick != "" {
  1480. online = append(online, currentNick)
  1481. } else {
  1482. offline = append(offline, target)
  1483. }
  1484. }
  1485. if len(online) > 0 {
  1486. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1487. }
  1488. if len(offline) > 0 {
  1489. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1490. }
  1491. return false
  1492. }
  1493. // MONITOR C
  1494. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1495. server.monitorManager.RemoveAll(client)
  1496. return false
  1497. }
  1498. // MONITOR L
  1499. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1500. nick := client.Nick()
  1501. monitorList := server.monitorManager.List(client)
  1502. var nickList []string
  1503. for _, cfnick := range monitorList {
  1504. replynick := cfnick
  1505. currentNick := server.getCurrentNick(cfnick)
  1506. // report the uncasefolded nick if it's available, i.e., the client is online
  1507. if currentNick != "" {
  1508. replynick = currentNick
  1509. }
  1510. nickList = append(nickList, replynick)
  1511. }
  1512. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1513. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1514. }
  1515. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1516. return false
  1517. }
  1518. // MONITOR S
  1519. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1520. var online []string
  1521. var offline []string
  1522. monitorList := server.monitorManager.List(client)
  1523. for _, name := range monitorList {
  1524. currentNick := server.getCurrentNick(name)
  1525. if currentNick != "" {
  1526. online = append(online, currentNick)
  1527. } else {
  1528. offline = append(offline, name)
  1529. }
  1530. }
  1531. if len(online) > 0 {
  1532. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1533. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1534. }
  1535. }
  1536. if len(offline) > 0 {
  1537. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1538. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1539. }
  1540. }
  1541. return false
  1542. }
  1543. // MOTD
  1544. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1545. server.MOTD(client, rb)
  1546. return false
  1547. }
  1548. // NAMES [<channel>{,<channel>} [target]]
  1549. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1550. var channels []string
  1551. if len(msg.Params) > 0 {
  1552. channels = strings.Split(msg.Params[0], ",")
  1553. }
  1554. // TODO: in a post-federation world, process `target` (server to forward request to)
  1555. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1556. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1557. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1558. // with the <channel> parameter set to an asterix character"
  1559. if len(channels) == 0 {
  1560. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1561. return false
  1562. }
  1563. chname := channels[0]
  1564. success := false
  1565. channel := server.channels.Get(chname)
  1566. if channel != nil {
  1567. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1568. channel.Names(client, rb)
  1569. success = true
  1570. }
  1571. }
  1572. if !success { // channel.Names() sends this numeric itself on success
  1573. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1574. }
  1575. return false
  1576. }
  1577. // NICK <nickname>
  1578. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1579. if client.registered {
  1580. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1581. } else {
  1582. client.preregNick = msg.Params[0]
  1583. }
  1584. return false
  1585. }
  1586. // helper to store a batched PRIVMSG in the session object
  1587. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1588. // sanity checks. batch tag correctness was already checked and is redundant here
  1589. // as a defensive measure. TAGMSG is checked without an error message: "don't eat paste"
  1590. if batchTag != rb.session.batch.label || histType == history.Tagmsg || len(msg.Params) == 1 || msg.Params[1] == "" {
  1591. return
  1592. }
  1593. rb.session.batch.command = msg.Command
  1594. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1595. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1596. config := server.Config()
  1597. if config.Limits.Multiline.MaxBytes < rb.session.batch.message.LenBytes() {
  1598. if histType != history.Notice {
  1599. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes))
  1600. }
  1601. rb.session.batch = MultilineBatch{}
  1602. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1603. if histType != history.Notice {
  1604. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines))
  1605. }
  1606. rb.session.batch = MultilineBatch{}
  1607. }
  1608. }
  1609. // NOTICE <target>{,<target>} <message>
  1610. // PRIVMSG <target>{,<target>} <message>
  1611. // TAGMSG <target>{,<target>}
  1612. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1613. histType, err := msgCommandToHistType(msg.Command)
  1614. if err != nil {
  1615. return false
  1616. }
  1617. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1618. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1619. return false
  1620. }
  1621. cnick := client.Nick()
  1622. clientOnlyTags := msg.ClientOnlyTags()
  1623. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1624. // nothing to do
  1625. return false
  1626. }
  1627. targets := strings.Split(msg.Params[0], ",")
  1628. var message string
  1629. if len(msg.Params) > 1 {
  1630. message = msg.Params[1]
  1631. }
  1632. if histType != history.Tagmsg && message == "" {
  1633. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1634. return false
  1635. }
  1636. if rb.session.isTor && utils.IsRestrictedCTCPMessage(message) {
  1637. // note that error replies are never sent for NOTICE
  1638. if histType != history.Notice {
  1639. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1640. }
  1641. return false
  1642. }
  1643. for i, targetString := range targets {
  1644. // max of four targets per privmsg
  1645. if i == maxTargets {
  1646. break
  1647. }
  1648. // each target gets distinct msgids
  1649. splitMsg := utils.MakeMessage(message)
  1650. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1651. }
  1652. return false
  1653. }
  1654. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1655. server := client.server
  1656. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1657. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1658. if len(target) == 0 {
  1659. return
  1660. } else if target[0] == '#' {
  1661. channel := server.channels.Get(target)
  1662. if channel == nil {
  1663. if histType != history.Notice {
  1664. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1665. }
  1666. return
  1667. }
  1668. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1669. } else {
  1670. // NOTICE and TAGMSG to services are ignored
  1671. if histType == history.Privmsg {
  1672. lowercaseTarget := strings.ToLower(target)
  1673. if service, isService := OragonoServices[lowercaseTarget]; isService {
  1674. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1675. return
  1676. } else if _, isZNC := zncHandlers[lowercaseTarget]; isZNC {
  1677. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1678. return
  1679. }
  1680. }
  1681. user := server.clients.Get(target)
  1682. if user == nil {
  1683. if histType != history.Notice {
  1684. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1685. }
  1686. return
  1687. }
  1688. tDetails := user.Details()
  1689. tnick := tDetails.nick
  1690. details := client.Details()
  1691. nickMaskString := details.nickMask
  1692. accountName := details.accountName
  1693. var deliverySessions []*Session
  1694. // restrict messages appropriately when +R is set
  1695. // intentionally make the sending user think the message went through fine
  1696. allowedPlusR := details.account != "" || !user.HasMode(modes.RegisteredOnly)
  1697. if allowedPlusR {
  1698. deliverySessions = append(deliverySessions, user.Sessions()...)
  1699. }
  1700. // all sessions of the sender, except the originating session, get a copy as well:
  1701. if client != user {
  1702. for _, session := range client.Sessions() {
  1703. if session != rb.session {
  1704. deliverySessions = append(deliverySessions, session)
  1705. }
  1706. }
  1707. }
  1708. for _, session := range deliverySessions {
  1709. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1710. // don't send TAGMSG at all if they don't have the tags cap
  1711. if histType == history.Tagmsg && hasTagsCap {
  1712. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1713. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1714. tagsToSend := tags
  1715. if !hasTagsCap {
  1716. tagsToSend = nil
  1717. }
  1718. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1719. }
  1720. }
  1721. // the originating session may get an echo message:
  1722. if rb.session.capabilities.Has(caps.EchoMessage) {
  1723. hasTagsCap := rb.session.capabilities.Has(caps.MessageTags)
  1724. if histType == history.Tagmsg && hasTagsCap {
  1725. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1726. } else {
  1727. tagsToSend := tags
  1728. if !hasTagsCap {
  1729. tagsToSend = nil
  1730. }
  1731. rb.AddSplitMessageFromClient(nickMaskString, accountName, tagsToSend, command, tnick, message)
  1732. }
  1733. }
  1734. if histType != history.Notice && user.Away() {
  1735. //TODO(dan): possibly implement cooldown of away notifications to users
  1736. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, user.AwayMessage())
  1737. }
  1738. config := server.Config()
  1739. if !config.History.Enabled {
  1740. return
  1741. }
  1742. item := history.Item{
  1743. Type: histType,
  1744. Message: message,
  1745. Nick: nickMaskString,
  1746. AccountName: accountName,
  1747. Tags: tags,
  1748. }
  1749. if !item.IsStorable() {
  1750. return
  1751. }
  1752. targetedItem := item
  1753. targetedItem.Params[0] = tnick
  1754. cStatus, _ := client.historyStatus(config)
  1755. tStatus, _ := user.historyStatus(config)
  1756. // add to ephemeral history
  1757. if cStatus == HistoryEphemeral {
  1758. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1759. client.history.Add(targetedItem)
  1760. }
  1761. if tStatus == HistoryEphemeral && client != user {
  1762. item.CfCorrespondent = details.nickCasefolded
  1763. user.history.Add(item)
  1764. }
  1765. cPersistent := cStatus == HistoryPersistent
  1766. tPersistent := tStatus == HistoryPersistent
  1767. if cPersistent || tPersistent {
  1768. item.CfCorrespondent = ""
  1769. server.historyDB.AddDirectMessage(details.nickCasefolded, user.NickCasefolded(), cPersistent, tPersistent, targetedItem)
  1770. }
  1771. }
  1772. }
  1773. // NPC <target> <sourcenick> <message>
  1774. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1775. target := msg.Params[0]
  1776. fakeSource := msg.Params[1]
  1777. message := msg.Params[2]
  1778. _, err := CasefoldName(fakeSource)
  1779. if err != nil {
  1780. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1781. return false
  1782. }
  1783. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1784. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1785. return false
  1786. }
  1787. // NPCA <target> <sourcenick> <message>
  1788. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1789. target := msg.Params[0]
  1790. fakeSource := msg.Params[1]
  1791. message := msg.Params[2]
  1792. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1793. _, err := CasefoldName(fakeSource)
  1794. if err != nil {
  1795. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1796. return false
  1797. }
  1798. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1799. return false
  1800. }
  1801. // OPER <name> [password]
  1802. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1803. if client.HasMode(modes.Operator) {
  1804. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1805. return false
  1806. }
  1807. // must pass at least one check, and all enabled checks
  1808. var checkPassed, checkFailed bool
  1809. oper := server.GetOperator(msg.Params[0])
  1810. if oper != nil {
  1811. if oper.Fingerprint != "" {
  1812. if oper.Fingerprint == rb.session.certfp {
  1813. checkPassed = true
  1814. } else {
  1815. checkFailed = true
  1816. }
  1817. }
  1818. if !checkFailed && oper.Pass != nil {
  1819. if len(msg.Params) == 1 || bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1820. checkFailed = true
  1821. } else {
  1822. checkPassed = true
  1823. }
  1824. }
  1825. }
  1826. if !checkPassed || checkFailed {
  1827. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1828. client.Quit(client.t("Password incorrect"), rb.session)
  1829. return true
  1830. }
  1831. applyOper(client, oper, rb)
  1832. return false
  1833. }
  1834. // adds or removes operator status
  1835. // XXX: to add oper, this calls into ApplyUserModeChanges, but to remove oper,
  1836. // ApplyUserModeChanges calls into this, because the commands are asymmetric
  1837. // (/OPER to add, /MODE self -o to remove)
  1838. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  1839. details := client.Details()
  1840. client.SetOper(oper)
  1841. newDetails := client.Details()
  1842. if details.nickMask != newDetails.nickMask {
  1843. client.sendChghost(details.nickMask, newDetails.hostname)
  1844. }
  1845. if oper != nil {
  1846. // set new modes: modes.Operator, plus anything specified in the config
  1847. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1848. modeChanges[0] = modes.ModeChange{
  1849. Mode: modes.Operator,
  1850. Op: modes.Add,
  1851. }
  1852. copy(modeChanges[1:], oper.Modes)
  1853. applied := ApplyUserModeChanges(client, modeChanges, true)
  1854. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client opered up $c[grey][$r%s$c[grey], $r%s$c[grey]]"), newDetails.nickMask, oper.Name))
  1855. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  1856. rb.Broadcast(nil, client.server.name, "MODE", details.nick, applied.String())
  1857. } else {
  1858. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client deopered $c[grey][$r%s$c[grey]]"), newDetails.nickMask))
  1859. }
  1860. for _, session := range client.Sessions() {
  1861. // client may now be unthrottled by the fakelag system
  1862. session.resetFakelag()
  1863. }
  1864. }
  1865. // DEOPER
  1866. func deoperHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1867. // pretend they sent /MODE $nick -o
  1868. fakeModeMsg := ircmsg.MakeMessage(nil, "", "MODE", client.Nick(), "-o")
  1869. return umodeHandler(server, client, fakeModeMsg, rb)
  1870. }
  1871. // PART <channel>{,<channel>} [<reason>]
  1872. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1873. channels := strings.Split(msg.Params[0], ",")
  1874. var reason string
  1875. if len(msg.Params) > 1 {
  1876. reason = msg.Params[1]
  1877. }
  1878. for _, chname := range channels {
  1879. if chname == "" {
  1880. continue // #679
  1881. }
  1882. err := server.channels.Part(client, chname, reason, rb)
  1883. if err == errNoSuchChannel {
  1884. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1885. }
  1886. }
  1887. return false
  1888. }
  1889. // PASS <password>
  1890. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1891. if client.registered {
  1892. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1893. return false
  1894. }
  1895. // if no password exists, skip checking
  1896. serverPassword := server.Config().Server.passwordBytes
  1897. if serverPassword == nil {
  1898. return false
  1899. }
  1900. // check the provided password
  1901. password := []byte(msg.Params[0])
  1902. rb.session.sentPassCommand = bcrypt.CompareHashAndPassword(serverPassword, password) == nil
  1903. // if they failed the check, we'll bounce them later when they try to complete registration
  1904. return false
  1905. }
  1906. // PING [params...]
  1907. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1908. rb.Add(nil, server.name, "PONG", msg.Params...)
  1909. return false
  1910. }
  1911. // PONG [params...]
  1912. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1913. // client gets touched when they send this command, so we don't need to do anything
  1914. return false
  1915. }
  1916. // QUIT [<reason>]
  1917. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1918. reason := "Quit"
  1919. if len(msg.Params) > 0 {
  1920. reason += ": " + msg.Params[0]
  1921. }
  1922. client.Quit(reason, rb.session)
  1923. return true
  1924. }
  1925. // REHASH
  1926. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1927. server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
  1928. err := server.rehash()
  1929. if err == nil {
  1930. rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
  1931. } else {
  1932. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  1933. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
  1934. }
  1935. return false
  1936. }
  1937. // RENAME <oldchan> <newchan> [<reason>]
  1938. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  1939. result = false
  1940. oldName, newName := msg.Params[0], msg.Params[1]
  1941. var reason string
  1942. if 2 < len(msg.Params) {
  1943. reason = msg.Params[2]
  1944. }
  1945. channel := server.channels.Get(oldName)
  1946. if channel == nil {
  1947. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  1948. return false
  1949. }
  1950. if !(channel.ClientIsAtLeast(client, modes.Operator) || client.HasRoleCapabs("chanreg")) {
  1951. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  1952. return false
  1953. }
  1954. founder := channel.Founder()
  1955. if founder != "" && founder != client.Account() {
  1956. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  1957. return false
  1958. }
  1959. // perform the channel rename
  1960. err := server.channels.Rename(oldName, newName)
  1961. if err == errInvalidChannelName {
  1962. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1963. } else if err == errChannelNameInUse {
  1964. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1965. } else if err != nil {
  1966. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  1967. }
  1968. if err != nil {
  1969. return false
  1970. }
  1971. // send RENAME messages
  1972. clientPrefix := client.NickMaskString()
  1973. for _, mcl := range channel.Members() {
  1974. mDetails := mcl.Details()
  1975. for _, mSession := range mcl.Sessions() {
  1976. targetRb := rb
  1977. targetPrefix := clientPrefix
  1978. if mSession != rb.session {
  1979. targetRb = NewResponseBuffer(mSession)
  1980. targetPrefix = mDetails.nickMask
  1981. }
  1982. if mSession.capabilities.Has(caps.Rename) {
  1983. if reason != "" {
  1984. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  1985. } else {
  1986. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  1987. }
  1988. } else {
  1989. if reason != "" {
  1990. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  1991. } else {
  1992. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  1993. }
  1994. if mSession.capabilities.Has(caps.ExtendedJoin) {
  1995. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  1996. } else {
  1997. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  1998. }
  1999. channel.SendTopic(mcl, targetRb, false)
  2000. channel.Names(mcl, targetRb)
  2001. }
  2002. if mcl != client {
  2003. targetRb.Send(false)
  2004. }
  2005. }
  2006. }
  2007. return false
  2008. }
  2009. // RESUME <token> [timestamp]
  2010. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2011. details := ResumeDetails{
  2012. PresentedToken: msg.Params[0],
  2013. }
  2014. if client.registered {
  2015. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  2016. return false
  2017. }
  2018. if 1 < len(msg.Params) {
  2019. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  2020. if err == nil {
  2021. details.Timestamp = ts
  2022. } else {
  2023. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  2024. }
  2025. }
  2026. rb.session.resumeDetails = &details
  2027. return false
  2028. }
  2029. // SANICK <oldnick> <nickname>
  2030. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2031. targetNick := strings.TrimSpace(msg.Params[0])
  2032. target := server.clients.Get(targetNick)
  2033. if target == nil {
  2034. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2035. return false
  2036. }
  2037. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2038. return false
  2039. }
  2040. // SCENE <target> <message>
  2041. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2042. target := msg.Params[0]
  2043. message := msg.Params[1]
  2044. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2045. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2046. return false
  2047. }
  2048. // SETNAME <realname>
  2049. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2050. realname := msg.Params[0]
  2051. client.SetRealname(realname)
  2052. details := client.Details()
  2053. // alert friends
  2054. now := time.Now().UTC()
  2055. for session := range client.Friends(caps.SetName) {
  2056. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2057. }
  2058. return false
  2059. }
  2060. // TIME
  2061. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2062. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2063. return false
  2064. }
  2065. // TOPIC <channel> [<topic>]
  2066. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2067. channel := server.channels.Get(msg.Params[0])
  2068. if channel == nil {
  2069. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2070. return false
  2071. }
  2072. if len(msg.Params) > 1 {
  2073. channel.SetTopic(client, msg.Params[1], rb)
  2074. } else {
  2075. channel.SendTopic(client, rb, true)
  2076. }
  2077. return false
  2078. }
  2079. // UNDLINE <ip>|<net>
  2080. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2081. // check oper permissions
  2082. oper := client.Oper()
  2083. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2084. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2085. return false
  2086. }
  2087. // get host
  2088. hostString := msg.Params[0]
  2089. // check host
  2090. hostNet, err := utils.NormalizedNetFromString(hostString)
  2091. if err != nil {
  2092. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2093. return false
  2094. }
  2095. err = server.dlines.RemoveNetwork(hostNet)
  2096. if err != nil {
  2097. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2098. return false
  2099. }
  2100. hostString = utils.NetToNormalizedString(hostNet)
  2101. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2102. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2103. return false
  2104. }
  2105. // UNKLINE <mask>
  2106. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2107. details := client.Details()
  2108. // check oper permissions
  2109. oper := client.Oper()
  2110. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2111. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2112. return false
  2113. }
  2114. // get host
  2115. mask := msg.Params[0]
  2116. mask, err := CanonicalizeMaskWildcard(mask)
  2117. if err != nil {
  2118. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2119. return false
  2120. }
  2121. err = server.klines.RemoveMask(mask)
  2122. if err != nil {
  2123. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2124. return false
  2125. }
  2126. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2127. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2128. return false
  2129. }
  2130. // USER <username> * 0 <realname>
  2131. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2132. if client.registered {
  2133. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2134. return false
  2135. }
  2136. err := client.SetNames(msg.Params[0], msg.Params[3], false)
  2137. if err == errInvalidUsername {
  2138. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2139. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2140. if client.preregNick == msg.Params[0] {
  2141. client.SetNames("user", msg.Params[3], false)
  2142. } else {
  2143. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2144. }
  2145. }
  2146. return false
  2147. }
  2148. // USERHOST <nickname>{ <nickname>}
  2149. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2150. returnedClients := make(ClientSet)
  2151. var tl utils.TokenLineBuilder
  2152. tl.Initialize(400, " ")
  2153. for i, nickname := range msg.Params {
  2154. if i >= 10 {
  2155. break
  2156. }
  2157. target := server.clients.Get(nickname)
  2158. if target == nil {
  2159. continue
  2160. }
  2161. // to prevent returning multiple results for a single nick
  2162. if returnedClients.Has(target) {
  2163. continue
  2164. }
  2165. returnedClients.Add(target)
  2166. var isOper, isAway string
  2167. if target.HasMode(modes.Operator) {
  2168. isOper = "*"
  2169. }
  2170. if target.Away() {
  2171. isAway = "-"
  2172. } else {
  2173. isAway = "+"
  2174. }
  2175. details := target.Details()
  2176. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2177. }
  2178. lines := tl.Lines()
  2179. if lines == nil {
  2180. lines = []string{""}
  2181. }
  2182. nick := client.Nick()
  2183. for _, line := range lines {
  2184. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2185. }
  2186. return false
  2187. }
  2188. // VERSION
  2189. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2190. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2191. server.RplISupport(client, rb)
  2192. return false
  2193. }
  2194. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2195. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2196. // only allow unregistered clients to use this command
  2197. if client.registered || client.proxiedIP != nil {
  2198. return false
  2199. }
  2200. // process flags
  2201. var secure bool
  2202. if 4 < len(msg.Params) {
  2203. for _, x := range strings.Split(msg.Params[4], " ") {
  2204. // split into key=value
  2205. var key string
  2206. if strings.Contains(x, "=") {
  2207. y := strings.SplitN(x, "=", 2)
  2208. key, _ = y[0], y[1]
  2209. } else {
  2210. key = x
  2211. }
  2212. lkey := strings.ToLower(key)
  2213. if lkey == "tls" || lkey == "secure" {
  2214. // only accept "tls" flag if the gateway's connection to us is secure as well
  2215. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2216. secure = true
  2217. }
  2218. }
  2219. }
  2220. }
  2221. givenPassword := []byte(msg.Params[0])
  2222. for _, info := range server.Config().Server.WebIRC {
  2223. if utils.IPInNets(client.realIP, info.allowedNets) {
  2224. // confirm password and/or fingerprint
  2225. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2226. continue
  2227. }
  2228. if info.Fingerprint != "" && info.Fingerprint != rb.session.certfp {
  2229. continue
  2230. }
  2231. proxiedIP := msg.Params[3]
  2232. // see #211; websocket gateways will wrap ipv6 addresses in square brackets
  2233. // because IRC parameters can't start with :
  2234. if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
  2235. proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
  2236. }
  2237. err, quitMsg := client.ApplyProxiedIP(rb.session, proxiedIP, secure)
  2238. if err != nil {
  2239. client.Quit(quitMsg, rb.session)
  2240. return true
  2241. } else {
  2242. return false
  2243. }
  2244. }
  2245. }
  2246. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2247. return true
  2248. }
  2249. // WHO [<mask> [o]]
  2250. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2251. mask := msg.Params[0]
  2252. var err error
  2253. if mask == "" {
  2254. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2255. return false
  2256. } else if mask[0] == '#' {
  2257. mask, err = CasefoldChannel(msg.Params[0])
  2258. } else {
  2259. mask, err = CanonicalizeMaskWildcard(mask)
  2260. }
  2261. if err != nil {
  2262. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2263. return false
  2264. }
  2265. //TODO(dan): is this used and would I put this param in the Modern doc?
  2266. // if not, can we remove it?
  2267. //var operatorOnly bool
  2268. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2269. // operatorOnly = true
  2270. //}
  2271. isOper := client.HasMode(modes.Operator)
  2272. if mask[0] == '#' {
  2273. // TODO implement wildcard matching
  2274. //TODO(dan): ^ only for opers
  2275. channel := server.channels.Get(mask)
  2276. if channel != nil {
  2277. isJoined := channel.hasClient(client)
  2278. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2279. for _, member := range channel.Members() {
  2280. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2281. client.rplWhoReply(channel, member, rb)
  2282. }
  2283. }
  2284. }
  2285. }
  2286. } else {
  2287. for mclient := range server.clients.FindAll(mask) {
  2288. client.rplWhoReply(nil, mclient, rb)
  2289. }
  2290. }
  2291. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2292. return false
  2293. }
  2294. // WHOIS [<target>] <mask>{,<mask>}
  2295. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2296. var masksString string
  2297. //var target string
  2298. if len(msg.Params) > 1 {
  2299. //target = msg.Params[0]
  2300. masksString = msg.Params[1]
  2301. } else {
  2302. masksString = msg.Params[0]
  2303. }
  2304. handleService := func(nick string) bool {
  2305. cfnick, _ := CasefoldName(nick)
  2306. service, ok := OragonoServices[cfnick]
  2307. if !ok {
  2308. return false
  2309. }
  2310. clientNick := client.Nick()
  2311. rb.Add(nil, client.server.name, RPL_WHOISUSER, clientNick, service.Name, service.Name, "localhost", "*", fmt.Sprintf(client.t("Network service, for more info /msg %s HELP"), service.Name))
  2312. // hehe
  2313. if client.HasMode(modes.TLS) {
  2314. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2315. }
  2316. return true
  2317. }
  2318. if client.HasMode(modes.Operator) {
  2319. for _, mask := range strings.Split(masksString, ",") {
  2320. matches := server.clients.FindAll(mask)
  2321. if len(matches) == 0 && !handleService(mask) {
  2322. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2323. continue
  2324. }
  2325. for mclient := range matches {
  2326. client.getWhoisOf(mclient, rb)
  2327. }
  2328. }
  2329. } else {
  2330. // only get the first request; also require a nick, not a mask
  2331. nick := strings.Split(masksString, ",")[0]
  2332. mclient := server.clients.Get(nick)
  2333. if mclient != nil {
  2334. client.getWhoisOf(mclient, rb)
  2335. } else if !handleService(nick) {
  2336. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2337. }
  2338. // fall through, ENDOFWHOIS is always sent
  2339. }
  2340. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2341. return false
  2342. }
  2343. // WHOWAS <nickname> [<count> [<server>]]
  2344. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2345. nicknames := strings.Split(msg.Params[0], ",")
  2346. // 0 means "all the entries", as does a negative number
  2347. var count int
  2348. if len(msg.Params) > 1 {
  2349. count, _ = strconv.Atoi(msg.Params[1])
  2350. if count < 0 {
  2351. count = 0
  2352. }
  2353. }
  2354. //var target string
  2355. //if len(msg.Params) > 2 {
  2356. // target = msg.Params[2]
  2357. //}
  2358. cnick := client.Nick()
  2359. for _, nickname := range nicknames {
  2360. if len(nickname) == 0 {
  2361. continue
  2362. }
  2363. results := server.whoWas.Find(nickname, count)
  2364. if len(results) == 0 {
  2365. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2366. } else {
  2367. for _, whoWas := range results {
  2368. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2369. }
  2370. }
  2371. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2372. }
  2373. return false
  2374. }
  2375. // ZNC <module> [params]
  2376. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2377. zncModuleHandler(client, msg.Params[0], msg.Params[1:], rb)
  2378. return false
  2379. }