Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

handlers.go 86KB

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