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

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