您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

handlers.go 86KB

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