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

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