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

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