Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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