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

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