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 83KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  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 && 0 < len(items) {
  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. parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
  490. err = utils.ErrInvalidParams
  491. pieces := strings.SplitN(param, "=", 2)
  492. if len(pieces) < 2 {
  493. return
  494. }
  495. identifier, value := strings.ToLower(pieces[0]), pieces[1]
  496. if identifier == "msgid" {
  497. msgid, err = value, nil
  498. return
  499. } else if identifier == "timestamp" {
  500. timestamp, err = time.Parse(IRCv3TimestampFormat, value)
  501. return
  502. }
  503. return
  504. }
  505. parseHistoryLimit := func(paramIndex int) (limit int) {
  506. if len(msg.Params) < (paramIndex + 1) {
  507. return maxChathistoryLimit
  508. }
  509. limit, err := strconv.Atoi(msg.Params[paramIndex])
  510. if err != nil || limit == 0 || limit > maxChathistoryLimit {
  511. limit = maxChathistoryLimit
  512. }
  513. return
  514. }
  515. preposition := strings.ToLower(msg.Params[0])
  516. target = msg.Params[1]
  517. channel, sequence, err = server.GetHistorySequence(nil, client, target)
  518. if err != nil || sequence == nil {
  519. return
  520. }
  521. roundUp := func(endpoint time.Time) (result time.Time) {
  522. return endpoint.Truncate(time.Millisecond).Add(time.Millisecond)
  523. }
  524. var start, end history.Selector
  525. var limit int
  526. switch preposition {
  527. case "between":
  528. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  529. if err != nil {
  530. return
  531. }
  532. end.Msgid, end.Time, err = parseQueryParam(msg.Params[3])
  533. if err != nil {
  534. return
  535. }
  536. // XXX preserve the ordering of the two parameters, since we might be going backwards,
  537. // but round up the chronologically first one, whichever it is, to make it exclusive
  538. if !start.Time.IsZero() && !end.Time.IsZero() {
  539. if start.Time.Before(end.Time) {
  540. start.Time = roundUp(start.Time)
  541. } else {
  542. end.Time = roundUp(end.Time)
  543. }
  544. }
  545. limit = parseHistoryLimit(4)
  546. case "before", "after", "around":
  547. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  548. if err != nil {
  549. return
  550. }
  551. if preposition == "after" && !start.Time.IsZero() {
  552. start.Time = roundUp(start.Time)
  553. }
  554. if preposition == "before" {
  555. end = start
  556. start = history.Selector{}
  557. }
  558. limit = parseHistoryLimit(3)
  559. case "latest":
  560. if msg.Params[2] != "*" {
  561. end.Msgid, end.Time, err = parseQueryParam(msg.Params[2])
  562. if err != nil {
  563. return
  564. }
  565. if !end.Time.IsZero() {
  566. end.Time = roundUp(end.Time)
  567. }
  568. start.Time = time.Now().UTC()
  569. }
  570. limit = parseHistoryLimit(3)
  571. default:
  572. unknown_command = true
  573. return
  574. }
  575. if preposition == "around" {
  576. items, err = sequence.Around(start, limit)
  577. } else {
  578. items, _, err = sequence.Between(start, end, limit)
  579. }
  580. return
  581. }
  582. // DEBUG <subcmd>
  583. func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  584. param := strings.ToUpper(msg.Params[0])
  585. switch param {
  586. case "GCSTATS":
  587. stats := debug.GCStats{
  588. Pause: make([]time.Duration, 10),
  589. PauseQuantiles: make([]time.Duration, 5),
  590. }
  591. debug.ReadGCStats(&stats)
  592. rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
  593. rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
  594. rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
  595. rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
  596. rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
  597. rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
  598. rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
  599. rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
  600. case "NUMGOROUTINE":
  601. count := runtime.NumGoroutine()
  602. rb.Notice(fmt.Sprintf("num goroutines: %d", count))
  603. case "PROFILEHEAP":
  604. profFile := "oragono.mprof"
  605. file, err := os.Create(profFile)
  606. if err != nil {
  607. rb.Notice(fmt.Sprintf("error: %s", err))
  608. break
  609. }
  610. defer file.Close()
  611. pprof.Lookup("heap").WriteTo(file, 0)
  612. rb.Notice(fmt.Sprintf("written to %s", profFile))
  613. case "STARTCPUPROFILE":
  614. profFile := "oragono.prof"
  615. file, err := os.Create(profFile)
  616. if err != nil {
  617. rb.Notice(fmt.Sprintf("error: %s", err))
  618. break
  619. }
  620. if err := pprof.StartCPUProfile(file); err != nil {
  621. defer file.Close()
  622. rb.Notice(fmt.Sprintf("error: %s", err))
  623. break
  624. }
  625. rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
  626. case "STOPCPUPROFILE":
  627. pprof.StopCPUProfile()
  628. rb.Notice(fmt.Sprintf("CPU profiling stopped"))
  629. }
  630. return false
  631. }
  632. // helper for parsing the reason args to DLINE and KLINE
  633. func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
  634. reason = "No reason given"
  635. operReason = ""
  636. if len(params) > currentArg {
  637. reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
  638. if len(reasons) == 1 {
  639. reason = strings.TrimSpace(reasons[0])
  640. } else if len(reasons) == 2 {
  641. reason = strings.TrimSpace(reasons[0])
  642. operReason = strings.TrimSpace(reasons[1])
  643. }
  644. }
  645. return
  646. }
  647. func formatBanForListing(client *Client, key string, info IPBanInfo) string {
  648. desc := info.Reason
  649. if info.OperReason != "" && info.OperReason != info.Reason {
  650. desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
  651. }
  652. if info.Duration != 0 {
  653. desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
  654. }
  655. return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
  656. }
  657. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  658. // DLINE LIST
  659. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  660. // check oper permissions
  661. oper := client.Oper()
  662. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  663. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  664. return false
  665. }
  666. currentArg := 0
  667. // if they say LIST, we just list the current dlines
  668. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  669. bans := server.dlines.AllBans()
  670. if len(bans) == 0 {
  671. rb.Notice(client.t("No DLINEs have been set!"))
  672. }
  673. for key, info := range bans {
  674. client.Notice(formatBanForListing(client, key, info))
  675. }
  676. return false
  677. }
  678. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  679. var andKill bool
  680. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  681. andKill = true
  682. currentArg++
  683. }
  684. // when setting a ban that covers the oper's current connection, we require them to say
  685. // "DLINE MYSELF" so that we're sure they really mean it.
  686. var dlineMyself bool
  687. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  688. dlineMyself = true
  689. currentArg++
  690. }
  691. // duration
  692. duration, err := custime.ParseDuration(msg.Params[currentArg])
  693. if err != nil {
  694. duration = 0
  695. } else {
  696. currentArg++
  697. }
  698. // get host
  699. if len(msg.Params) < currentArg+1 {
  700. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  701. return false
  702. }
  703. hostString := msg.Params[currentArg]
  704. currentArg++
  705. // check host
  706. hostNet, err := utils.NormalizedNetFromString(hostString)
  707. if err != nil {
  708. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  709. return false
  710. }
  711. if !dlineMyself && hostNet.Contains(client.IP()) {
  712. 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>"))
  713. return false
  714. }
  715. // check remote
  716. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  717. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  718. return false
  719. }
  720. // get comment(s)
  721. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  722. operName := oper.Name
  723. if operName == "" {
  724. operName = server.name
  725. }
  726. err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
  727. if err != nil {
  728. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
  729. return false
  730. }
  731. var snoDescription string
  732. hostString = utils.NetToNormalizedString(hostNet)
  733. if duration != 0 {
  734. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
  735. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
  736. } else {
  737. rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
  738. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
  739. }
  740. server.snomasks.Send(sno.LocalXline, snoDescription)
  741. var killClient bool
  742. if andKill {
  743. var clientsToKill []*Client
  744. var killedClientNicks []string
  745. for _, mcl := range server.clients.AllClients() {
  746. if hostNet.Contains(mcl.IP()) {
  747. clientsToKill = append(clientsToKill, mcl)
  748. killedClientNicks = append(killedClientNicks, mcl.nick)
  749. }
  750. }
  751. for _, mcl := range clientsToKill {
  752. mcl.SetExitedSnomaskSent()
  753. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  754. if mcl == client {
  755. killClient = true
  756. } else {
  757. // if mcl == client, we kill them below
  758. mcl.destroy(nil)
  759. }
  760. }
  761. // send snomask
  762. sort.Strings(killedClientNicks)
  763. 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, ", ")))
  764. }
  765. return killClient
  766. }
  767. // HELP [<query>]
  768. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  769. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  770. if len(argument) < 1 {
  771. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  772. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  773. return false
  774. }
  775. // handle index
  776. if argument == "index" {
  777. client.sendHelp("HELP", server.helpIndexManager.GetIndex(client.Languages(), client.HasMode(modes.Operator)), rb)
  778. return false
  779. }
  780. helpHandler, exists := Help[argument]
  781. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  782. if helpHandler.textGenerator != nil {
  783. client.sendHelp(strings.ToUpper(argument), helpHandler.textGenerator(client), rb)
  784. } else {
  785. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  786. }
  787. } else {
  788. args := msg.Params
  789. args = append(args, client.t("Help not found"))
  790. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  791. }
  792. return false
  793. }
  794. // HISTORY <target> [<limit>]
  795. // e.g., HISTORY #ubuntu 10
  796. // HISTORY me 15
  797. // HISTORY #darwin 1h
  798. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  799. config := server.Config()
  800. if !config.History.Enabled {
  801. rb.Notice(client.t("This command has been disabled by the server administrators"))
  802. return false
  803. }
  804. target := msg.Params[0]
  805. if strings.ToLower(target) == "me" {
  806. target = "*"
  807. }
  808. channel, sequence, err := server.GetHistorySequence(nil, client, target)
  809. if sequence == nil || err != nil {
  810. // whatever
  811. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  812. return false
  813. }
  814. var duration time.Duration
  815. maxChathistoryLimit := config.History.ChathistoryMax
  816. limit := 100
  817. if maxChathistoryLimit < limit {
  818. limit = maxChathistoryLimit
  819. }
  820. if len(msg.Params) > 1 {
  821. providedLimit, err := strconv.Atoi(msg.Params[1])
  822. if err == nil && providedLimit != 0 {
  823. limit = providedLimit
  824. if maxChathistoryLimit < limit {
  825. limit = maxChathistoryLimit
  826. }
  827. } else if err != nil {
  828. duration, err = time.ParseDuration(msg.Params[1])
  829. if err == nil {
  830. limit = maxChathistoryLimit
  831. }
  832. }
  833. }
  834. var items []history.Item
  835. if duration == 0 {
  836. items, _, err = sequence.Between(history.Selector{}, history.Selector{}, limit)
  837. } else {
  838. now := time.Now().UTC()
  839. start := history.Selector{Time: now}
  840. end := history.Selector{Time: now.Add(-duration)}
  841. items, _, err = sequence.Between(start, end, limit)
  842. }
  843. if err == nil {
  844. if channel != nil {
  845. channel.replayHistoryItems(rb, items, false)
  846. } else {
  847. client.replayPrivmsgHistory(rb, items, "", true)
  848. }
  849. }
  850. return false
  851. }
  852. // INFO
  853. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  854. // we do the below so that the human-readable lines in info can be translated.
  855. for _, line := range infoString1 {
  856. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  857. }
  858. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
  859. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  860. 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")
  861. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  862. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
  863. for _, line := range infoString2 {
  864. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  865. }
  866. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
  867. for _, line := range infoString3 {
  868. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  869. }
  870. // show translators for languages other than good ole' regular English
  871. tlines := server.Languages().Translators()
  872. if 0 < len(tlines) {
  873. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
  874. for _, line := range tlines {
  875. rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
  876. }
  877. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  878. }
  879. rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
  880. return false
  881. }
  882. // INVITE <nickname> <channel>
  883. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  884. nickname := msg.Params[0]
  885. channelName := msg.Params[1]
  886. target := server.clients.Get(nickname)
  887. if target == nil {
  888. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  889. return false
  890. }
  891. channel := server.channels.Get(channelName)
  892. if channel == nil {
  893. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(channelName), client.t("No such channel"))
  894. return false
  895. }
  896. channel.Invite(target, client, rb)
  897. return false
  898. }
  899. // ISON <nick>{ <nick>}
  900. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  901. var nicks = msg.Params
  902. ison := make([]string, 0, len(msg.Params))
  903. for _, nick := range nicks {
  904. currentNick := server.getCurrentNick(nick)
  905. if currentNick != "" {
  906. ison = append(ison, currentNick)
  907. }
  908. }
  909. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  910. return false
  911. }
  912. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  913. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  914. // kill JOIN 0 requests
  915. if msg.Params[0] == "0" {
  916. rb.Notice(client.t("JOIN 0 is not allowed"))
  917. return false
  918. }
  919. // handle regular JOINs
  920. channels := strings.Split(msg.Params[0], ",")
  921. var keys []string
  922. if len(msg.Params) > 1 {
  923. keys = strings.Split(msg.Params[1], ",")
  924. }
  925. config := server.Config()
  926. oper := client.Oper()
  927. for i, name := range channels {
  928. if name == "" {
  929. continue // #679
  930. }
  931. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  932. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  933. return false
  934. }
  935. var key string
  936. if len(keys) > i {
  937. key = keys[i]
  938. }
  939. err := server.channels.Join(client, name, key, false, rb)
  940. if err != nil {
  941. sendJoinError(client, name, rb, err)
  942. }
  943. }
  944. return false
  945. }
  946. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  947. var errMsg string
  948. switch err {
  949. case errInsufficientPrivs:
  950. errMsg = `Only server operators can create new channels`
  951. case errConfusableIdentifier:
  952. errMsg = `That channel name is too close to the name of another channel`
  953. case errChannelPurged:
  954. errMsg = err.Error()
  955. default:
  956. errMsg = `No such channel`
  957. }
  958. rb.Add(nil, client.server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(name), client.t(errMsg))
  959. }
  960. // SAJOIN [nick] #channel{,#channel}
  961. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  962. var target *Client
  963. var channelString string
  964. if strings.HasPrefix(msg.Params[0], "#") {
  965. target = client
  966. channelString = msg.Params[0]
  967. } else {
  968. if len(msg.Params) == 1 {
  969. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  970. return false
  971. } else {
  972. target = server.clients.Get(msg.Params[0])
  973. if target == nil {
  974. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  975. return false
  976. }
  977. channelString = msg.Params[1]
  978. }
  979. }
  980. channels := strings.Split(channelString, ",")
  981. for _, chname := range channels {
  982. err := server.channels.Join(target, chname, "", true, rb)
  983. if err != nil {
  984. sendJoinError(client, chname, rb, err)
  985. }
  986. }
  987. return false
  988. }
  989. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  990. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  991. channels := strings.Split(msg.Params[0], ",")
  992. users := strings.Split(msg.Params[1], ",")
  993. if (len(channels) != len(users)) && (len(users) != 1) {
  994. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  995. return false
  996. }
  997. type kickCmd struct {
  998. channel string
  999. nick string
  1000. }
  1001. kicks := make([]kickCmd, 0, len(channels))
  1002. for index, channel := range channels {
  1003. if channel == "" {
  1004. continue // #679
  1005. }
  1006. if len(users) == 1 {
  1007. kicks = append(kicks, kickCmd{channel, users[0]})
  1008. } else {
  1009. kicks = append(kicks, kickCmd{channel, users[index]})
  1010. }
  1011. }
  1012. var comment string
  1013. if len(msg.Params) > 2 {
  1014. comment = msg.Params[2]
  1015. }
  1016. for _, kick := range kicks {
  1017. channel := server.channels.Get(kick.channel)
  1018. if channel == nil {
  1019. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1020. continue
  1021. }
  1022. target := server.clients.Get(kick.nick)
  1023. if target == nil {
  1024. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1025. continue
  1026. }
  1027. if comment == "" {
  1028. comment = kick.nick
  1029. }
  1030. channel.Kick(client, target, comment, rb, false)
  1031. }
  1032. return false
  1033. }
  1034. // KILL <nickname> <comment>
  1035. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1036. nickname := msg.Params[0]
  1037. comment := "<no reason supplied>"
  1038. if len(msg.Params) > 1 {
  1039. comment = msg.Params[1]
  1040. }
  1041. target := server.clients.Get(nickname)
  1042. if target == nil {
  1043. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(nickname), client.t("No such nick"))
  1044. return false
  1045. }
  1046. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1047. 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))
  1048. target.SetExitedSnomaskSent()
  1049. target.Quit(quitMsg, nil)
  1050. target.destroy(nil)
  1051. return false
  1052. }
  1053. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1054. // KLINE LIST
  1055. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1056. details := client.Details()
  1057. // check oper permissions
  1058. oper := client.Oper()
  1059. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  1060. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1061. return false
  1062. }
  1063. currentArg := 0
  1064. // if they say LIST, we just list the current klines
  1065. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1066. bans := server.klines.AllBans()
  1067. if len(bans) == 0 {
  1068. client.Notice("No KLINEs have been set!")
  1069. }
  1070. for key, info := range bans {
  1071. client.Notice(formatBanForListing(client, key, info))
  1072. }
  1073. return false
  1074. }
  1075. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1076. var andKill bool
  1077. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1078. andKill = true
  1079. currentArg++
  1080. }
  1081. // when setting a ban that covers the oper's current connection, we require them to say
  1082. // "KLINE MYSELF" so that we're sure they really mean it.
  1083. var klineMyself bool
  1084. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1085. klineMyself = true
  1086. currentArg++
  1087. }
  1088. // duration
  1089. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1090. if err != nil {
  1091. duration = 0
  1092. } else {
  1093. currentArg++
  1094. }
  1095. // get mask
  1096. if len(msg.Params) < currentArg+1 {
  1097. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1098. return false
  1099. }
  1100. mask := msg.Params[currentArg]
  1101. currentArg++
  1102. // check mask
  1103. mask, err = CanonicalizeMaskWildcard(mask)
  1104. if err != nil {
  1105. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1106. return false
  1107. }
  1108. matcher := ircmatch.MakeMatch(mask)
  1109. for _, clientMask := range client.AllNickmasks() {
  1110. if !klineMyself && matcher.Match(clientMask) {
  1111. 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>"))
  1112. return false
  1113. }
  1114. }
  1115. // check remote
  1116. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1117. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1118. return false
  1119. }
  1120. // get oper name
  1121. operName := oper.Name
  1122. if operName == "" {
  1123. operName = server.name
  1124. }
  1125. // get comment(s)
  1126. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1127. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1128. if err != nil {
  1129. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1130. return false
  1131. }
  1132. var snoDescription string
  1133. if duration != 0 {
  1134. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1135. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1136. } else {
  1137. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1138. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1139. }
  1140. server.snomasks.Send(sno.LocalXline, snoDescription)
  1141. var killClient bool
  1142. if andKill {
  1143. var clientsToKill []*Client
  1144. var killedClientNicks []string
  1145. for _, mcl := range server.clients.AllClients() {
  1146. for _, clientMask := range mcl.AllNickmasks() {
  1147. if matcher.Match(clientMask) {
  1148. clientsToKill = append(clientsToKill, mcl)
  1149. killedClientNicks = append(killedClientNicks, mcl.nick)
  1150. }
  1151. }
  1152. }
  1153. for _, mcl := range clientsToKill {
  1154. mcl.SetExitedSnomaskSent()
  1155. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1156. if mcl == client {
  1157. killClient = true
  1158. } else {
  1159. // if mcl == client, we kill them below
  1160. mcl.destroy(nil)
  1161. }
  1162. }
  1163. // send snomask
  1164. sort.Strings(killedClientNicks)
  1165. 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, ", ")))
  1166. }
  1167. return killClient
  1168. }
  1169. // LANGUAGE <code>{ <code>}
  1170. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1171. nick := client.Nick()
  1172. alreadyDoneLanguages := make(map[string]bool)
  1173. var appliedLanguages []string
  1174. lm := server.Languages()
  1175. supportedLanguagesCount := lm.Count()
  1176. if supportedLanguagesCount < len(msg.Params) {
  1177. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1178. return false
  1179. }
  1180. for _, value := range msg.Params {
  1181. value = strings.ToLower(value)
  1182. // strip ~ from the language if it has it
  1183. value = strings.TrimPrefix(value, "~")
  1184. // silently ignore empty languages or those with spaces in them
  1185. if len(value) == 0 || strings.Contains(value, " ") {
  1186. continue
  1187. }
  1188. _, exists := lm.Languages[value]
  1189. if !exists {
  1190. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1191. return false
  1192. }
  1193. // if we've already applied the given language, skip it
  1194. _, exists = alreadyDoneLanguages[value]
  1195. if exists {
  1196. continue
  1197. }
  1198. appliedLanguages = append(appliedLanguages, value)
  1199. }
  1200. var langsToSet []string
  1201. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1202. langsToSet = appliedLanguages
  1203. }
  1204. client.SetLanguages(langsToSet)
  1205. params := make([]string, len(appliedLanguages)+2)
  1206. params[0] = nick
  1207. copy(params[1:], appliedLanguages)
  1208. params[len(params)-1] = client.t("Language preferences have been set")
  1209. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1210. return false
  1211. }
  1212. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1213. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1214. // get channels
  1215. var channels []string
  1216. for _, param := range msg.Params {
  1217. if 0 < len(param) && param[0] == '#' {
  1218. for _, channame := range strings.Split(param, ",") {
  1219. if 0 < len(channame) && channame[0] == '#' {
  1220. channels = append(channels, channame)
  1221. }
  1222. }
  1223. }
  1224. }
  1225. // get elist conditions
  1226. var matcher elistMatcher
  1227. for _, param := range msg.Params {
  1228. if len(param) < 1 {
  1229. continue
  1230. }
  1231. if param[0] == '<' {
  1232. param = param[1:]
  1233. val, err := strconv.Atoi(param)
  1234. if err != nil {
  1235. continue
  1236. }
  1237. matcher.MaxClientsActive = true
  1238. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1239. }
  1240. if param[0] == '>' {
  1241. param = param[1:]
  1242. val, err := strconv.Atoi(param)
  1243. if err != nil {
  1244. continue
  1245. }
  1246. matcher.MinClientsActive = true
  1247. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1248. }
  1249. }
  1250. clientIsOp := client.HasMode(modes.Operator)
  1251. if len(channels) == 0 {
  1252. for _, channel := range server.channels.Channels() {
  1253. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1254. continue
  1255. }
  1256. if matcher.Matches(channel) {
  1257. client.RplList(channel, rb)
  1258. }
  1259. }
  1260. } else {
  1261. // limit regular users to only listing one channel
  1262. if !clientIsOp {
  1263. channels = channels[:1]
  1264. }
  1265. for _, chname := range channels {
  1266. channel := server.channels.Get(chname)
  1267. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1268. if len(chname) > 0 {
  1269. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1270. }
  1271. continue
  1272. }
  1273. if matcher.Matches(channel) {
  1274. client.RplList(channel, rb)
  1275. }
  1276. }
  1277. }
  1278. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1279. return false
  1280. }
  1281. // LUSERS [<mask> [<server>]]
  1282. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1283. server.Lusers(client, rb)
  1284. return false
  1285. }
  1286. // MODE <target> [<modestring> [<mode arguments>...]]
  1287. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1288. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1289. return cmodeHandler(server, client, msg, rb)
  1290. }
  1291. return umodeHandler(server, client, msg, rb)
  1292. }
  1293. // MODE <channel> [<modestring> [<mode arguments>...]]
  1294. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1295. channel := server.channels.Get(msg.Params[0])
  1296. if channel == nil {
  1297. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1298. return false
  1299. }
  1300. var changes modes.ModeChanges
  1301. if 1 < len(msg.Params) {
  1302. // parse out real mode changes
  1303. params := msg.Params[1:]
  1304. var unknown map[rune]bool
  1305. changes, unknown = modes.ParseChannelModeChanges(params...)
  1306. // alert for unknown mode changes
  1307. for char := range unknown {
  1308. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1309. }
  1310. if len(unknown) == 1 && len(changes) == 0 {
  1311. return false
  1312. }
  1313. }
  1314. // process mode changes, include list operations (an empty set of changes does a list)
  1315. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1316. // save changes
  1317. var includeFlags uint
  1318. for _, change := range applied {
  1319. includeFlags |= IncludeModes
  1320. if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
  1321. includeFlags |= IncludeLists
  1322. }
  1323. }
  1324. if includeFlags != 0 {
  1325. channel.MarkDirty(includeFlags)
  1326. }
  1327. // send out changes
  1328. if len(applied) > 0 {
  1329. prefix := client.NickMaskString()
  1330. //TODO(dan): we should change the name of String and make it return a slice here
  1331. args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
  1332. rb.Add(nil, prefix, "MODE", args...)
  1333. for _, session := range client.Sessions() {
  1334. if session != rb.session {
  1335. session.Send(nil, prefix, "MODE", args...)
  1336. }
  1337. }
  1338. for _, member := range channel.Members() {
  1339. if member != client {
  1340. member.Send(nil, prefix, "MODE", args...)
  1341. }
  1342. }
  1343. }
  1344. return false
  1345. }
  1346. // MODE <client> [<modestring> [<mode arguments>...]]
  1347. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1348. cDetails := client.Details()
  1349. target := server.clients.Get(msg.Params[0])
  1350. if target == nil {
  1351. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1352. return false
  1353. }
  1354. targetNick := target.Nick()
  1355. hasPrivs := client == target || msg.Command == "SAMODE"
  1356. if !hasPrivs {
  1357. if len(msg.Params) > 1 {
  1358. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1359. } else {
  1360. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1361. }
  1362. return false
  1363. }
  1364. // applied mode changes
  1365. applied := make(modes.ModeChanges, 0)
  1366. if 1 < len(msg.Params) {
  1367. // parse out real mode changes
  1368. params := msg.Params[1:]
  1369. changes, unknown := modes.ParseUserModeChanges(params...)
  1370. // alert for unknown mode changes
  1371. for char := range unknown {
  1372. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1373. }
  1374. if len(unknown) == 1 && len(changes) == 0 {
  1375. return false
  1376. }
  1377. // apply mode changes
  1378. applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
  1379. }
  1380. if len(applied) > 0 {
  1381. rb.Add(nil, cDetails.nickMask, "MODE", targetNick, applied.String())
  1382. } else if hasPrivs {
  1383. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1384. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1385. masks := server.snomasks.String(target)
  1386. if 0 < len(masks) {
  1387. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1388. }
  1389. }
  1390. }
  1391. return false
  1392. }
  1393. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1394. func (server *Server) getCurrentNick(nick string) (result string) {
  1395. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1396. return service.Name
  1397. } else if iclient := server.clients.Get(nick); iclient != nil {
  1398. return iclient.Nick()
  1399. }
  1400. return ""
  1401. }
  1402. // MONITOR <subcmd> [params...]
  1403. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1404. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1405. if !exists {
  1406. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1407. return false
  1408. }
  1409. return handler(server, client, msg, rb)
  1410. }
  1411. // MONITOR - <target>{,<target>}
  1412. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1413. if len(msg.Params) < 2 {
  1414. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1415. return false
  1416. }
  1417. targets := strings.Split(msg.Params[1], ",")
  1418. for _, target := range targets {
  1419. cfnick, err := CasefoldName(target)
  1420. if err != nil {
  1421. continue
  1422. }
  1423. server.monitorManager.Remove(client, cfnick)
  1424. }
  1425. return false
  1426. }
  1427. // MONITOR + <target>{,<target>}
  1428. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1429. if len(msg.Params) < 2 {
  1430. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1431. return false
  1432. }
  1433. var online []string
  1434. var offline []string
  1435. limits := server.Config().Limits
  1436. targets := strings.Split(msg.Params[1], ",")
  1437. for _, target := range targets {
  1438. // check name length
  1439. if len(target) < 1 || len(targets) > limits.NickLen {
  1440. continue
  1441. }
  1442. // add target
  1443. casefoldedTarget, err := CasefoldName(target)
  1444. if err != nil {
  1445. continue
  1446. }
  1447. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1448. if err == errMonitorLimitExceeded {
  1449. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1450. break
  1451. } else if err != nil {
  1452. continue
  1453. }
  1454. currentNick := server.getCurrentNick(target)
  1455. // add to online / offline lists
  1456. if currentNick != "" {
  1457. online = append(online, currentNick)
  1458. } else {
  1459. offline = append(offline, target)
  1460. }
  1461. }
  1462. if len(online) > 0 {
  1463. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1464. }
  1465. if len(offline) > 0 {
  1466. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1467. }
  1468. return false
  1469. }
  1470. // MONITOR C
  1471. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1472. server.monitorManager.RemoveAll(client)
  1473. return false
  1474. }
  1475. // MONITOR L
  1476. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1477. nick := client.Nick()
  1478. monitorList := server.monitorManager.List(client)
  1479. var nickList []string
  1480. for _, cfnick := range monitorList {
  1481. replynick := cfnick
  1482. currentNick := server.getCurrentNick(cfnick)
  1483. // report the uncasefolded nick if it's available, i.e., the client is online
  1484. if currentNick != "" {
  1485. replynick = currentNick
  1486. }
  1487. nickList = append(nickList, replynick)
  1488. }
  1489. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1490. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1491. }
  1492. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1493. return false
  1494. }
  1495. // MONITOR S
  1496. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1497. var online []string
  1498. var offline []string
  1499. monitorList := server.monitorManager.List(client)
  1500. for _, name := range monitorList {
  1501. currentNick := server.getCurrentNick(name)
  1502. if currentNick != "" {
  1503. online = append(online, currentNick)
  1504. } else {
  1505. offline = append(offline, name)
  1506. }
  1507. }
  1508. if len(online) > 0 {
  1509. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1510. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1511. }
  1512. }
  1513. if len(offline) > 0 {
  1514. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1515. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1516. }
  1517. }
  1518. return false
  1519. }
  1520. // MOTD
  1521. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1522. server.MOTD(client, rb)
  1523. return false
  1524. }
  1525. // NAMES [<channel>{,<channel>} [target]]
  1526. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1527. var channels []string
  1528. if len(msg.Params) > 0 {
  1529. channels = strings.Split(msg.Params[0], ",")
  1530. }
  1531. // TODO: in a post-federation world, process `target` (server to forward request to)
  1532. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1533. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1534. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1535. // with the <channel> parameter set to an asterix character"
  1536. if len(channels) == 0 {
  1537. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1538. return false
  1539. }
  1540. chname := channels[0]
  1541. success := false
  1542. channel := server.channels.Get(chname)
  1543. if channel != nil {
  1544. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1545. channel.Names(client, rb)
  1546. success = true
  1547. }
  1548. }
  1549. if !success { // channel.Names() sends this numeric itself on success
  1550. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1551. }
  1552. return false
  1553. }
  1554. // NICK <nickname>
  1555. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1556. if client.registered {
  1557. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1558. } else {
  1559. client.preregNick = msg.Params[0]
  1560. }
  1561. return false
  1562. }
  1563. // helper to store a batched PRIVMSG in the session object
  1564. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1565. // sanity checks. batch tag correctness was already checked and is redundant here
  1566. // as a defensive measure. TAGMSG is checked without an error message: "don't eat paste"
  1567. if batchTag != rb.session.batch.label || histType == history.Tagmsg || len(msg.Params) == 1 || msg.Params[1] == "" {
  1568. return
  1569. }
  1570. rb.session.batch.command = msg.Command
  1571. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1572. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1573. config := server.Config()
  1574. if config.Limits.Multiline.MaxBytes < rb.session.batch.message.LenBytes() {
  1575. if histType != history.Notice {
  1576. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes))
  1577. }
  1578. rb.session.batch = MultilineBatch{}
  1579. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1580. if histType != history.Notice {
  1581. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines))
  1582. }
  1583. rb.session.batch = MultilineBatch{}
  1584. }
  1585. }
  1586. // NOTICE <target>{,<target>} <message>
  1587. // PRIVMSG <target>{,<target>} <message>
  1588. // TAGMSG <target>{,<target>}
  1589. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1590. histType, err := msgCommandToHistType(msg.Command)
  1591. if err != nil {
  1592. return false
  1593. }
  1594. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1595. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1596. return false
  1597. }
  1598. cnick := client.Nick()
  1599. clientOnlyTags := msg.ClientOnlyTags()
  1600. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1601. // nothing to do
  1602. return false
  1603. }
  1604. targets := strings.Split(msg.Params[0], ",")
  1605. var message string
  1606. if len(msg.Params) > 1 {
  1607. message = msg.Params[1]
  1608. }
  1609. if histType != history.Tagmsg && message == "" {
  1610. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1611. return false
  1612. }
  1613. if rb.session.isTor && utils.IsRestrictedCTCPMessage(message) {
  1614. // note that error replies are never sent for NOTICE
  1615. if histType != history.Notice {
  1616. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1617. }
  1618. return false
  1619. }
  1620. for i, targetString := range targets {
  1621. // max of four targets per privmsg
  1622. if i == maxTargets {
  1623. break
  1624. }
  1625. // each target gets distinct msgids
  1626. splitMsg := utils.MakeMessage(message)
  1627. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1628. }
  1629. return false
  1630. }
  1631. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1632. server := client.server
  1633. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1634. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1635. if len(target) == 0 {
  1636. return
  1637. } else if target[0] == '#' {
  1638. channel := server.channels.Get(target)
  1639. if channel == nil {
  1640. if histType != history.Notice {
  1641. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1642. }
  1643. return
  1644. }
  1645. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1646. } else {
  1647. // NOTICE and TAGMSG to services are ignored
  1648. if histType == history.Privmsg {
  1649. lowercaseTarget := strings.ToLower(target)
  1650. if service, isService := OragonoServices[lowercaseTarget]; isService {
  1651. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1652. return
  1653. } else if _, isZNC := zncHandlers[lowercaseTarget]; isZNC {
  1654. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1655. return
  1656. }
  1657. }
  1658. user := server.clients.Get(target)
  1659. if user == nil {
  1660. if histType != history.Notice {
  1661. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1662. }
  1663. return
  1664. }
  1665. tDetails := user.Details()
  1666. tnick := tDetails.nick
  1667. details := client.Details()
  1668. nickMaskString := details.nickMask
  1669. accountName := details.accountName
  1670. // restrict messages appropriately when +R is set
  1671. // intentionally make the sending user think the message went through fine
  1672. allowedPlusR := !user.HasMode(modes.RegisteredOnly) || details.account != ""
  1673. if allowedPlusR {
  1674. for _, session := range user.Sessions() {
  1675. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1676. // don't send TAGMSG at all if they don't have the tags cap
  1677. if histType == history.Tagmsg && hasTagsCap {
  1678. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1679. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1680. tagsToSend := tags
  1681. if !hasTagsCap {
  1682. tagsToSend = nil
  1683. }
  1684. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1685. }
  1686. }
  1687. }
  1688. // an echo-message may need to be included in the response:
  1689. if rb.session.capabilities.Has(caps.EchoMessage) {
  1690. if histType == history.Tagmsg && rb.session.capabilities.Has(caps.MessageTags) {
  1691. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1692. } else {
  1693. rb.AddSplitMessageFromClient(nickMaskString, accountName, tags, command, tnick, message)
  1694. }
  1695. }
  1696. // an echo-message may need to go out to other client sessions:
  1697. for _, session := range client.Sessions() {
  1698. if session == rb.session {
  1699. continue
  1700. }
  1701. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1702. if histType == history.Tagmsg && hasTagsCap {
  1703. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1704. } else if histType != history.Tagmsg {
  1705. tagsToSend := tags
  1706. if !hasTagsCap {
  1707. tagsToSend = nil
  1708. }
  1709. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1710. }
  1711. }
  1712. if histType != history.Notice && user.Away() {
  1713. //TODO(dan): possibly implement cooldown of away notifications to users
  1714. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, user.AwayMessage())
  1715. }
  1716. config := server.Config()
  1717. if !config.History.Enabled {
  1718. return
  1719. }
  1720. item := history.Item{
  1721. Type: histType,
  1722. Message: message,
  1723. Nick: nickMaskString,
  1724. AccountName: accountName,
  1725. Tags: tags,
  1726. }
  1727. if !item.IsStorable() {
  1728. return
  1729. }
  1730. targetedItem := item
  1731. targetedItem.Params[0] = tnick
  1732. cPersistent, cEphemeral := client.historyStatus(config)
  1733. tPersistent, tEphemeral := user.historyStatus(config)
  1734. // add to ephemeral history
  1735. if cEphemeral {
  1736. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1737. client.history.Add(targetedItem)
  1738. }
  1739. if tEphemeral {
  1740. item.CfCorrespondent = details.nickCasefolded
  1741. user.history.Add(item)
  1742. }
  1743. if cPersistent || tPersistent {
  1744. item.CfCorrespondent = ""
  1745. server.historyDB.AddDirectMessage(details.nickCasefolded, user.NickCasefolded(), cPersistent, tPersistent, targetedItem)
  1746. }
  1747. }
  1748. }
  1749. // NPC <target> <sourcenick> <message>
  1750. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1751. target := msg.Params[0]
  1752. fakeSource := msg.Params[1]
  1753. message := msg.Params[2]
  1754. _, err := CasefoldName(fakeSource)
  1755. if err != nil {
  1756. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1757. return false
  1758. }
  1759. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1760. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1761. return false
  1762. }
  1763. // NPCA <target> <sourcenick> <message>
  1764. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1765. target := msg.Params[0]
  1766. fakeSource := msg.Params[1]
  1767. message := msg.Params[2]
  1768. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1769. _, err := CasefoldName(fakeSource)
  1770. if err != nil {
  1771. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1772. return false
  1773. }
  1774. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1775. return false
  1776. }
  1777. // OPER <name> [password]
  1778. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1779. if client.HasMode(modes.Operator) {
  1780. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1781. return false
  1782. }
  1783. // must pass at least one check, and all enabled checks
  1784. var checkPassed, checkFailed bool
  1785. oper := server.GetOperator(msg.Params[0])
  1786. if oper != nil {
  1787. if oper.Fingerprint != "" {
  1788. if oper.Fingerprint == rb.session.certfp {
  1789. checkPassed = true
  1790. } else {
  1791. checkFailed = true
  1792. }
  1793. }
  1794. if !checkFailed && oper.Pass != nil {
  1795. if len(msg.Params) == 1 || bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1796. checkFailed = true
  1797. } else {
  1798. checkPassed = true
  1799. }
  1800. }
  1801. }
  1802. if !checkPassed || checkFailed {
  1803. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1804. client.Quit(client.t("Password incorrect"), rb.session)
  1805. return true
  1806. }
  1807. applyOper(client, oper, rb)
  1808. return false
  1809. }
  1810. // applies operator status to a client, who MUST NOT already be an operator
  1811. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  1812. details := client.Details()
  1813. oldNickmask := details.nickMask
  1814. client.SetOper(oper)
  1815. newNickmask := client.NickMaskString()
  1816. if newNickmask != oldNickmask {
  1817. client.sendChghost(oldNickmask, oper.Vhost)
  1818. }
  1819. // set new modes: modes.Operator, plus anything specified in the config
  1820. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1821. modeChanges[0] = modes.ModeChange{
  1822. Mode: modes.Operator,
  1823. Op: modes.Add,
  1824. }
  1825. copy(modeChanges[1:], oper.Modes)
  1826. applied := ApplyUserModeChanges(client, modeChanges, true)
  1827. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client opered up $c[grey][$r%s$c[grey], $r%s$c[grey]]"), client.nickMaskString, oper.Name))
  1828. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  1829. rb.Broadcast(nil, client.server.name, "MODE", details.nick, applied.String())
  1830. for _, session := range client.Sessions() {
  1831. // client may now be unthrottled by the fakelag system
  1832. session.resetFakelag()
  1833. }
  1834. }
  1835. // PART <channel>{,<channel>} [<reason>]
  1836. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1837. channels := strings.Split(msg.Params[0], ",")
  1838. var reason string
  1839. if len(msg.Params) > 1 {
  1840. reason = msg.Params[1]
  1841. }
  1842. for _, chname := range channels {
  1843. if chname == "" {
  1844. continue // #679
  1845. }
  1846. err := server.channels.Part(client, chname, reason, rb)
  1847. if err == errNoSuchChannel {
  1848. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1849. }
  1850. }
  1851. return false
  1852. }
  1853. // PASS <password>
  1854. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1855. if client.registered {
  1856. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1857. return false
  1858. }
  1859. // if no password exists, skip checking
  1860. serverPassword := server.Config().Server.passwordBytes
  1861. if serverPassword == nil {
  1862. return false
  1863. }
  1864. // check the provided password
  1865. password := []byte(msg.Params[0])
  1866. rb.session.sentPassCommand = bcrypt.CompareHashAndPassword(serverPassword, password) == nil
  1867. // if they failed the check, we'll bounce them later when they try to complete registration
  1868. return false
  1869. }
  1870. // PING [params...]
  1871. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1872. rb.Add(nil, server.name, "PONG", msg.Params...)
  1873. return false
  1874. }
  1875. // PONG [params...]
  1876. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1877. // client gets touched when they send this command, so we don't need to do anything
  1878. return false
  1879. }
  1880. // QUIT [<reason>]
  1881. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1882. reason := "Quit"
  1883. if len(msg.Params) > 0 {
  1884. reason += ": " + msg.Params[0]
  1885. }
  1886. client.Quit(reason, rb.session)
  1887. return true
  1888. }
  1889. // REHASH
  1890. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1891. server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
  1892. err := server.rehash()
  1893. if err == nil {
  1894. rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
  1895. } else {
  1896. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  1897. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
  1898. }
  1899. return false
  1900. }
  1901. // RENAME <oldchan> <newchan> [<reason>]
  1902. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  1903. result = false
  1904. oldName, newName := msg.Params[0], msg.Params[1]
  1905. var reason string
  1906. if 2 < len(msg.Params) {
  1907. reason = msg.Params[2]
  1908. }
  1909. channel := server.channels.Get(oldName)
  1910. if channel == nil {
  1911. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  1912. return false
  1913. }
  1914. if !(channel.ClientIsAtLeast(client, modes.Operator) || client.HasRoleCapabs("chanreg")) {
  1915. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  1916. return false
  1917. }
  1918. founder := channel.Founder()
  1919. if founder != "" && founder != client.Account() {
  1920. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  1921. return false
  1922. }
  1923. // perform the channel rename
  1924. err := server.channels.Rename(oldName, newName)
  1925. if err == errInvalidChannelName {
  1926. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1927. } else if err == errChannelNameInUse {
  1928. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1929. } else if err != nil {
  1930. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  1931. }
  1932. if err != nil {
  1933. return false
  1934. }
  1935. // send RENAME messages
  1936. clientPrefix := client.NickMaskString()
  1937. for _, mcl := range channel.Members() {
  1938. mDetails := mcl.Details()
  1939. for _, mSession := range mcl.Sessions() {
  1940. targetRb := rb
  1941. targetPrefix := clientPrefix
  1942. if mSession != rb.session {
  1943. targetRb = NewResponseBuffer(mSession)
  1944. targetPrefix = mDetails.nickMask
  1945. }
  1946. if mSession.capabilities.Has(caps.Rename) {
  1947. if reason != "" {
  1948. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  1949. } else {
  1950. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  1951. }
  1952. } else {
  1953. if reason != "" {
  1954. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  1955. } else {
  1956. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  1957. }
  1958. if mSession.capabilities.Has(caps.ExtendedJoin) {
  1959. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  1960. } else {
  1961. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  1962. }
  1963. channel.SendTopic(mcl, targetRb, false)
  1964. channel.Names(mcl, targetRb)
  1965. }
  1966. if mcl != client {
  1967. targetRb.Send(false)
  1968. }
  1969. }
  1970. }
  1971. return false
  1972. }
  1973. // RESUME <token> [timestamp]
  1974. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1975. details := ResumeDetails{
  1976. PresentedToken: msg.Params[0],
  1977. }
  1978. if client.registered {
  1979. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  1980. return false
  1981. }
  1982. if 1 < len(msg.Params) {
  1983. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  1984. if err == nil {
  1985. details.Timestamp = ts
  1986. } else {
  1987. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  1988. }
  1989. }
  1990. rb.session.resumeDetails = &details
  1991. return false
  1992. }
  1993. // SANICK <oldnick> <nickname>
  1994. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1995. targetNick := strings.TrimSpace(msg.Params[0])
  1996. target := server.clients.Get(targetNick)
  1997. if target == nil {
  1998. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  1999. return false
  2000. }
  2001. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2002. return false
  2003. }
  2004. // SCENE <target> <message>
  2005. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2006. target := msg.Params[0]
  2007. message := msg.Params[1]
  2008. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2009. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2010. return false
  2011. }
  2012. // SETNAME <realname>
  2013. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2014. realname := msg.Params[0]
  2015. client.SetRealname(realname)
  2016. details := client.Details()
  2017. // alert friends
  2018. now := time.Now().UTC()
  2019. for session := range client.Friends(caps.SetName) {
  2020. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2021. }
  2022. return false
  2023. }
  2024. // TIME
  2025. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2026. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2027. return false
  2028. }
  2029. // TOPIC <channel> [<topic>]
  2030. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2031. channel := server.channels.Get(msg.Params[0])
  2032. if channel == nil {
  2033. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2034. return false
  2035. }
  2036. if len(msg.Params) > 1 {
  2037. channel.SetTopic(client, msg.Params[1], rb)
  2038. } else {
  2039. channel.SendTopic(client, rb, true)
  2040. }
  2041. return false
  2042. }
  2043. // UNDLINE <ip>|<net>
  2044. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2045. // check oper permissions
  2046. oper := client.Oper()
  2047. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2048. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2049. return false
  2050. }
  2051. // get host
  2052. hostString := msg.Params[0]
  2053. // check host
  2054. hostNet, err := utils.NormalizedNetFromString(hostString)
  2055. if err != nil {
  2056. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2057. return false
  2058. }
  2059. err = server.dlines.RemoveNetwork(hostNet)
  2060. if err != nil {
  2061. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2062. return false
  2063. }
  2064. hostString = utils.NetToNormalizedString(hostNet)
  2065. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2066. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2067. return false
  2068. }
  2069. // UNKLINE <mask>
  2070. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2071. details := client.Details()
  2072. // check oper permissions
  2073. oper := client.Oper()
  2074. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2075. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2076. return false
  2077. }
  2078. // get host
  2079. mask := msg.Params[0]
  2080. mask, err := CanonicalizeMaskWildcard(mask)
  2081. if err != nil {
  2082. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2083. return false
  2084. }
  2085. err = server.klines.RemoveMask(mask)
  2086. if err != nil {
  2087. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2088. return false
  2089. }
  2090. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2091. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2092. return false
  2093. }
  2094. // USER <username> * 0 <realname>
  2095. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2096. if client.registered {
  2097. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2098. return false
  2099. }
  2100. err := client.SetNames(msg.Params[0], msg.Params[3], false)
  2101. if err == errInvalidUsername {
  2102. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2103. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2104. if client.preregNick == msg.Params[0] {
  2105. client.SetNames("user", msg.Params[3], false)
  2106. } else {
  2107. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2108. }
  2109. }
  2110. return false
  2111. }
  2112. // USERHOST <nickname>{ <nickname>}
  2113. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2114. returnedClients := make(ClientSet)
  2115. var tl utils.TokenLineBuilder
  2116. tl.Initialize(400, " ")
  2117. for i, nickname := range msg.Params {
  2118. if i >= 10 {
  2119. break
  2120. }
  2121. target := server.clients.Get(nickname)
  2122. if target == nil {
  2123. continue
  2124. }
  2125. // to prevent returning multiple results for a single nick
  2126. if returnedClients.Has(target) {
  2127. continue
  2128. }
  2129. returnedClients.Add(target)
  2130. var isOper, isAway string
  2131. if target.HasMode(modes.Operator) {
  2132. isOper = "*"
  2133. }
  2134. if target.Away() {
  2135. isAway = "-"
  2136. } else {
  2137. isAway = "+"
  2138. }
  2139. details := target.Details()
  2140. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2141. }
  2142. lines := tl.Lines()
  2143. if lines == nil {
  2144. lines = []string{""}
  2145. }
  2146. nick := client.Nick()
  2147. for _, line := range lines {
  2148. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2149. }
  2150. return false
  2151. }
  2152. // VERSION
  2153. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2154. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2155. server.RplISupport(client, rb)
  2156. return false
  2157. }
  2158. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2159. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2160. // only allow unregistered clients to use this command
  2161. if client.registered || client.proxiedIP != nil {
  2162. return false
  2163. }
  2164. // process flags
  2165. var secure bool
  2166. if 4 < len(msg.Params) {
  2167. for _, x := range strings.Split(msg.Params[4], " ") {
  2168. // split into key=value
  2169. var key string
  2170. if strings.Contains(x, "=") {
  2171. y := strings.SplitN(x, "=", 2)
  2172. key, _ = y[0], y[1]
  2173. } else {
  2174. key = x
  2175. }
  2176. lkey := strings.ToLower(key)
  2177. if lkey == "tls" || lkey == "secure" {
  2178. // only accept "tls" flag if the gateway's connection to us is secure as well
  2179. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2180. secure = true
  2181. }
  2182. }
  2183. }
  2184. }
  2185. givenPassword := []byte(msg.Params[0])
  2186. for _, info := range server.Config().Server.WebIRC {
  2187. if utils.IPInNets(client.realIP, info.allowedNets) {
  2188. // confirm password and/or fingerprint
  2189. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2190. continue
  2191. }
  2192. if info.Fingerprint != "" && info.Fingerprint != rb.session.certfp {
  2193. continue
  2194. }
  2195. proxiedIP := msg.Params[3]
  2196. // see #211; websocket gateways will wrap ipv6 addresses in square brackets
  2197. // because IRC parameters can't start with :
  2198. if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
  2199. proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
  2200. }
  2201. err, quitMsg := client.ApplyProxiedIP(rb.session, proxiedIP, secure)
  2202. if err != nil {
  2203. client.Quit(quitMsg, rb.session)
  2204. return true
  2205. } else {
  2206. return false
  2207. }
  2208. }
  2209. }
  2210. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2211. return true
  2212. }
  2213. // WHO [<mask> [o]]
  2214. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2215. mask := msg.Params[0]
  2216. var err error
  2217. if mask == "" {
  2218. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2219. return false
  2220. } else if mask[0] == '#' {
  2221. mask, err = CasefoldChannel(msg.Params[0])
  2222. } else {
  2223. mask, err = CanonicalizeMaskWildcard(mask)
  2224. }
  2225. if err != nil {
  2226. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2227. return false
  2228. }
  2229. //TODO(dan): is this used and would I put this param in the Modern doc?
  2230. // if not, can we remove it?
  2231. //var operatorOnly bool
  2232. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2233. // operatorOnly = true
  2234. //}
  2235. isOper := client.HasMode(modes.Operator)
  2236. if mask[0] == '#' {
  2237. // TODO implement wildcard matching
  2238. //TODO(dan): ^ only for opers
  2239. channel := server.channels.Get(mask)
  2240. if channel != nil {
  2241. isJoined := channel.hasClient(client)
  2242. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2243. for _, member := range channel.Members() {
  2244. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2245. client.rplWhoReply(channel, member, rb)
  2246. }
  2247. }
  2248. }
  2249. }
  2250. } else {
  2251. for mclient := range server.clients.FindAll(mask) {
  2252. client.rplWhoReply(nil, mclient, rb)
  2253. }
  2254. }
  2255. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2256. return false
  2257. }
  2258. // WHOIS [<target>] <mask>{,<mask>}
  2259. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2260. var masksString string
  2261. //var target string
  2262. if len(msg.Params) > 1 {
  2263. //target = msg.Params[0]
  2264. masksString = msg.Params[1]
  2265. } else {
  2266. masksString = msg.Params[0]
  2267. }
  2268. handleService := func(nick string) bool {
  2269. cfnick, _ := CasefoldName(nick)
  2270. service, ok := OragonoServices[cfnick]
  2271. if !ok {
  2272. return false
  2273. }
  2274. clientNick := client.Nick()
  2275. 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))
  2276. // hehe
  2277. if client.HasMode(modes.TLS) {
  2278. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2279. }
  2280. return true
  2281. }
  2282. if client.HasMode(modes.Operator) {
  2283. for _, mask := range strings.Split(masksString, ",") {
  2284. matches := server.clients.FindAll(mask)
  2285. if len(matches) == 0 && !handleService(mask) {
  2286. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2287. continue
  2288. }
  2289. for mclient := range matches {
  2290. client.getWhoisOf(mclient, rb)
  2291. }
  2292. }
  2293. } else {
  2294. // only get the first request; also require a nick, not a mask
  2295. nick := strings.Split(masksString, ",")[0]
  2296. mclient := server.clients.Get(nick)
  2297. if mclient != nil {
  2298. client.getWhoisOf(mclient, rb)
  2299. } else if !handleService(nick) {
  2300. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2301. }
  2302. // fall through, ENDOFWHOIS is always sent
  2303. }
  2304. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2305. return false
  2306. }
  2307. // WHOWAS <nickname> [<count> [<server>]]
  2308. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2309. nicknames := strings.Split(msg.Params[0], ",")
  2310. // 0 means "all the entries", as does a negative number
  2311. var count int
  2312. if len(msg.Params) > 1 {
  2313. count, _ = strconv.Atoi(msg.Params[1])
  2314. if count < 0 {
  2315. count = 0
  2316. }
  2317. }
  2318. //var target string
  2319. //if len(msg.Params) > 2 {
  2320. // target = msg.Params[2]
  2321. //}
  2322. cnick := client.Nick()
  2323. for _, nickname := range nicknames {
  2324. if len(nickname) == 0 {
  2325. continue
  2326. }
  2327. results := server.whoWas.Find(nickname, count)
  2328. if len(results) == 0 {
  2329. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2330. } else {
  2331. for _, whoWas := range results {
  2332. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2333. }
  2334. }
  2335. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2336. }
  2337. return false
  2338. }
  2339. // ZNC <module> [params]
  2340. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2341. zncModuleHandler(client, msg.Params[0], msg.Params[1:], rb)
  2342. return false
  2343. }