You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handlers.go 86KB

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