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. if client.HasMode(modes.Operator) {
  871. client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndexOpers), rb)
  872. } else {
  873. client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndex), rb)
  874. }
  875. return false
  876. }
  877. helpHandler, exists := Help[argument]
  878. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  879. if helpHandler.textGenerator != nil {
  880. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.textGenerator(client)), rb)
  881. } else {
  882. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  883. }
  884. } else {
  885. args := msg.Params
  886. args = append(args, client.t("Help not found"))
  887. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  888. }
  889. return false
  890. }
  891. // HISTORY <target> [<limit>]
  892. // e.g., HISTORY #ubuntu 10
  893. // HISTORY me 15
  894. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  895. config := server.Config()
  896. target := msg.Params[0]
  897. var hist *history.Buffer
  898. channel := server.channels.Get(target)
  899. if channel != nil && channel.hasClient(client) {
  900. hist = &channel.history
  901. } else {
  902. if strings.ToLower(target) == "me" {
  903. hist = client.history
  904. } else {
  905. targetClient := server.clients.Get(target)
  906. if targetClient != nil {
  907. myAccount, targetAccount := client.Account(), targetClient.Account()
  908. if myAccount != "" && targetAccount != "" && myAccount == targetAccount {
  909. hist = targetClient.history
  910. }
  911. }
  912. }
  913. }
  914. if hist == nil {
  915. if channel == nil {
  916. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), target, client.t("No such channel"))
  917. } else {
  918. rb.Add(nil, server.name, ERR_NOTONCHANNEL, client.Nick(), target, client.t("You're not on that channel"))
  919. }
  920. return false
  921. }
  922. limit := 10
  923. maxChathistoryLimit := config.History.ChathistoryMax
  924. if len(msg.Params) > 1 {
  925. providedLimit, err := strconv.Atoi(msg.Params[1])
  926. if providedLimit > maxChathistoryLimit {
  927. providedLimit = maxChathistoryLimit
  928. }
  929. if err == nil && providedLimit != 0 {
  930. limit = providedLimit
  931. }
  932. }
  933. items := hist.Latest(limit)
  934. if channel != nil {
  935. channel.replayHistoryItems(rb, items)
  936. } else {
  937. client.replayPrivmsgHistory(rb, items, true)
  938. }
  939. return false
  940. }
  941. // INFO
  942. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  943. // we do the below so that the human-readable lines in info can be translated.
  944. for _, line := range infoString1 {
  945. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  946. }
  947. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
  948. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  949. 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")
  950. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  951. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
  952. for _, line := range infoString2 {
  953. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  954. }
  955. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
  956. for _, line := range infoString3 {
  957. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  958. }
  959. // show translators for languages other than good ole' regular English
  960. tlines := server.languages.Translators()
  961. if 0 < len(tlines) {
  962. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
  963. for _, line := range tlines {
  964. rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
  965. }
  966. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  967. }
  968. rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
  969. return false
  970. }
  971. // INVITE <nickname> <channel>
  972. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  973. nickname := msg.Params[0]
  974. channelName := msg.Params[1]
  975. casefoldedNickname, err := CasefoldName(nickname)
  976. target := server.clients.Get(casefoldedNickname)
  977. if err != nil || target == nil {
  978. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  979. return false
  980. }
  981. casefoldedChannelName, err := CasefoldChannel(channelName)
  982. channel := server.channels.Get(casefoldedChannelName)
  983. if err != nil || channel == nil {
  984. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, channelName, client.t("No such channel"))
  985. return false
  986. }
  987. channel.Invite(target, client, rb)
  988. return false
  989. }
  990. // ISON <nick>{ <nick>}
  991. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  992. var nicks = msg.Params
  993. var err error
  994. var casefoldedNick string
  995. ison := make([]string, 0)
  996. for _, nick := range nicks {
  997. casefoldedNick, err = CasefoldName(nick)
  998. if err != nil {
  999. continue
  1000. }
  1001. if iclient := server.clients.Get(casefoldedNick); iclient != nil {
  1002. ison = append(ison, iclient.nick)
  1003. }
  1004. }
  1005. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(nicks, " "))
  1006. return false
  1007. }
  1008. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  1009. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1010. // kill JOIN 0 requests
  1011. if msg.Params[0] == "0" {
  1012. rb.Notice(client.t("JOIN 0 is not allowed"))
  1013. return false
  1014. }
  1015. // handle regular JOINs
  1016. channels := strings.Split(msg.Params[0], ",")
  1017. var keys []string
  1018. if len(msg.Params) > 1 {
  1019. keys = strings.Split(msg.Params[1], ",")
  1020. }
  1021. config := server.Config()
  1022. oper := client.Oper()
  1023. for i, name := range channels {
  1024. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  1025. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  1026. return false
  1027. }
  1028. var key string
  1029. if len(keys) > i {
  1030. key = keys[i]
  1031. }
  1032. err := server.channels.Join(client, name, key, false, rb)
  1033. if err == errNoSuchChannel {
  1034. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), name, client.t("No such channel"))
  1035. }
  1036. }
  1037. return false
  1038. }
  1039. // SAJOIN [nick] #channel{,#channel}
  1040. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1041. var target *Client
  1042. var channelString string
  1043. if strings.HasPrefix(msg.Params[0], "#") {
  1044. target = client
  1045. channelString = msg.Params[0]
  1046. } else {
  1047. if len(msg.Params) == 1 {
  1048. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "KICK", client.t("Not enough parameters"))
  1049. return false
  1050. } else {
  1051. target = server.clients.Get(msg.Params[0])
  1052. if target == nil {
  1053. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), msg.Params[0], "No such nick")
  1054. return false
  1055. }
  1056. channelString = msg.Params[1]
  1057. rb = NewResponseBuffer(target)
  1058. }
  1059. }
  1060. channels := strings.Split(channelString, ",")
  1061. for _, chname := range channels {
  1062. server.channels.Join(target, chname, "", true, rb)
  1063. }
  1064. if client != target {
  1065. rb.Send(false)
  1066. }
  1067. return false
  1068. }
  1069. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1070. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1071. channels := strings.Split(msg.Params[0], ",")
  1072. users := strings.Split(msg.Params[1], ",")
  1073. if (len(channels) != len(users)) && (len(users) != 1) {
  1074. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1075. return false
  1076. }
  1077. var kicks [][]string
  1078. for index, channel := range channels {
  1079. if len(users) == 1 {
  1080. kicks = append(kicks, []string{channel, users[0]})
  1081. } else {
  1082. kicks = append(kicks, []string{channel, users[index]})
  1083. }
  1084. }
  1085. var comment string
  1086. if len(msg.Params) > 2 {
  1087. comment = msg.Params[2]
  1088. }
  1089. for _, info := range kicks {
  1090. chname := info[0]
  1091. nickname := info[1]
  1092. casefoldedChname, err := CasefoldChannel(chname)
  1093. channel := server.channels.Get(casefoldedChname)
  1094. if err != nil || channel == nil {
  1095. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  1096. continue
  1097. }
  1098. casefoldedNickname, err := CasefoldName(nickname)
  1099. target := server.clients.Get(casefoldedNickname)
  1100. if err != nil || target == nil {
  1101. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  1102. continue
  1103. }
  1104. if comment == "" {
  1105. comment = nickname
  1106. }
  1107. channel.Kick(client, target, comment, rb)
  1108. }
  1109. return false
  1110. }
  1111. // KILL <nickname> <comment>
  1112. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1113. nickname := msg.Params[0]
  1114. comment := "<no reason supplied>"
  1115. if len(msg.Params) > 1 {
  1116. comment = msg.Params[1]
  1117. }
  1118. casefoldedNickname, err := CasefoldName(nickname)
  1119. target := server.clients.Get(casefoldedNickname)
  1120. if err != nil || target == nil {
  1121. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  1122. return false
  1123. }
  1124. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1125. 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))
  1126. target.exitedSnomaskSent = true
  1127. target.Quit(quitMsg)
  1128. target.destroy(false)
  1129. return false
  1130. }
  1131. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1132. // KLINE LIST
  1133. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1134. // check oper permissions
  1135. oper := client.Oper()
  1136. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  1137. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  1138. return false
  1139. }
  1140. currentArg := 0
  1141. // if they say LIST, we just list the current klines
  1142. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1143. bans := server.klines.AllBans()
  1144. if len(bans) == 0 {
  1145. client.Notice("No KLINEs have been set!")
  1146. }
  1147. for key, info := range bans {
  1148. client.Notice(formatBanForListing(client, key, info))
  1149. }
  1150. return false
  1151. }
  1152. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1153. var andKill bool
  1154. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1155. andKill = true
  1156. currentArg++
  1157. }
  1158. // when setting a ban that covers the oper's current connection, we require them to say
  1159. // "KLINE MYSELF" so that we're sure they really mean it.
  1160. var klineMyself bool
  1161. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1162. klineMyself = true
  1163. currentArg++
  1164. }
  1165. // duration
  1166. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1167. if err != nil {
  1168. duration = 0
  1169. } else {
  1170. currentArg++
  1171. }
  1172. // get mask
  1173. if len(msg.Params) < currentArg+1 {
  1174. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  1175. return false
  1176. }
  1177. mask := strings.ToLower(msg.Params[currentArg])
  1178. currentArg++
  1179. // check mask
  1180. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  1181. mask = mask + "!*@*"
  1182. } else if !strings.Contains(mask, "@") {
  1183. mask = mask + "@*"
  1184. }
  1185. matcher := ircmatch.MakeMatch(mask)
  1186. for _, clientMask := range client.AllNickmasks() {
  1187. if !klineMyself && matcher.Match(clientMask) {
  1188. 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>"))
  1189. return false
  1190. }
  1191. }
  1192. // check remote
  1193. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1194. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  1195. return false
  1196. }
  1197. // get oper name
  1198. operName := oper.Name
  1199. if operName == "" {
  1200. operName = server.name
  1201. }
  1202. // get comment(s)
  1203. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1204. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1205. if err != nil {
  1206. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1207. return false
  1208. }
  1209. var snoDescription string
  1210. if duration != 0 {
  1211. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1212. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), client.nick, operName, duration.String(), mask)
  1213. } else {
  1214. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1215. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), client.nick, operName, mask)
  1216. }
  1217. server.snomasks.Send(sno.LocalXline, snoDescription)
  1218. var killClient bool
  1219. if andKill {
  1220. var clientsToKill []*Client
  1221. var killedClientNicks []string
  1222. for _, mcl := range server.clients.AllClients() {
  1223. for _, clientMask := range mcl.AllNickmasks() {
  1224. if matcher.Match(clientMask) {
  1225. clientsToKill = append(clientsToKill, mcl)
  1226. killedClientNicks = append(killedClientNicks, mcl.nick)
  1227. }
  1228. }
  1229. }
  1230. for _, mcl := range clientsToKill {
  1231. mcl.exitedSnomaskSent = true
  1232. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
  1233. if mcl == client {
  1234. killClient = true
  1235. } else {
  1236. // if mcl == client, we kill them below
  1237. mcl.destroy(false)
  1238. }
  1239. }
  1240. // send snomask
  1241. sort.Strings(killedClientNicks)
  1242. 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, ", ")))
  1243. }
  1244. return killClient
  1245. }
  1246. // LANGUAGE <code>{ <code>}
  1247. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1248. alreadyDoneLanguages := make(map[string]bool)
  1249. var appliedLanguages []string
  1250. supportedLanguagesCount := server.languages.Count()
  1251. if supportedLanguagesCount < len(msg.Params) {
  1252. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, client.nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1253. return false
  1254. }
  1255. for _, value := range msg.Params {
  1256. value = strings.ToLower(value)
  1257. // strip ~ from the language if it has it
  1258. value = strings.TrimPrefix(value, "~")
  1259. // silently ignore empty languages or those with spaces in them
  1260. if len(value) == 0 || strings.Contains(value, " ") {
  1261. continue
  1262. }
  1263. _, exists := server.languages.Info[value]
  1264. if !exists {
  1265. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, client.nick, client.t("Languages are not supported by this server"))
  1266. return false
  1267. }
  1268. // if we've already applied the given language, skip it
  1269. _, exists = alreadyDoneLanguages[value]
  1270. if exists {
  1271. continue
  1272. }
  1273. appliedLanguages = append(appliedLanguages, value)
  1274. }
  1275. client.stateMutex.Lock()
  1276. if len(appliedLanguages) == 1 && appliedLanguages[0] == "en" {
  1277. // premature optimisation ahoy!
  1278. client.languages = []string{}
  1279. } else {
  1280. client.languages = appliedLanguages
  1281. }
  1282. client.stateMutex.Unlock()
  1283. params := []string{client.nick}
  1284. for _, lang := range appliedLanguages {
  1285. params = append(params, lang)
  1286. }
  1287. params = append(params, client.t("Language preferences have been set"))
  1288. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1289. return false
  1290. }
  1291. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1292. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1293. // get channels
  1294. var channels []string
  1295. for _, param := range msg.Params {
  1296. if 0 < len(param) && param[0] == '#' {
  1297. for _, channame := range strings.Split(param, ",") {
  1298. if 0 < len(channame) && channame[0] == '#' {
  1299. channels = append(channels, channame)
  1300. }
  1301. }
  1302. }
  1303. }
  1304. // get elist conditions
  1305. var matcher elistMatcher
  1306. for _, param := range msg.Params {
  1307. if len(param) < 1 {
  1308. continue
  1309. }
  1310. if param[0] == '<' {
  1311. param = param[1:]
  1312. val, err := strconv.Atoi(param)
  1313. if err != nil {
  1314. continue
  1315. }
  1316. matcher.MaxClientsActive = true
  1317. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1318. }
  1319. if param[0] == '>' {
  1320. param = param[1:]
  1321. val, err := strconv.Atoi(param)
  1322. if err != nil {
  1323. continue
  1324. }
  1325. matcher.MinClientsActive = true
  1326. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1327. }
  1328. }
  1329. clientIsOp := client.HasMode(modes.Operator)
  1330. if len(channels) == 0 {
  1331. for _, channel := range server.channels.Channels() {
  1332. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1333. continue
  1334. }
  1335. if matcher.Matches(channel) {
  1336. client.RplList(channel, rb)
  1337. }
  1338. }
  1339. } else {
  1340. // limit regular users to only listing one channel
  1341. if !clientIsOp {
  1342. channels = channels[:1]
  1343. }
  1344. for _, chname := range channels {
  1345. casefoldedChname, err := CasefoldChannel(chname)
  1346. channel := server.channels.Get(casefoldedChname)
  1347. if err != nil || channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1348. if len(chname) > 0 {
  1349. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  1350. }
  1351. continue
  1352. }
  1353. if matcher.Matches(channel) {
  1354. client.RplList(channel, rb)
  1355. }
  1356. }
  1357. }
  1358. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1359. return false
  1360. }
  1361. // LUSERS [<mask> [<server>]]
  1362. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1363. //TODO(vegax87) Fix network statistics and additional parameters
  1364. totalCount, invisibleCount, operCount := server.stats.GetStats()
  1365. 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))
  1366. rb.Add(nil, server.name, RPL_LUSEROP, client.nick, strconv.Itoa(operCount), client.t("IRC Operators online"))
  1367. rb.Add(nil, server.name, RPL_LUSERCHANNELS, client.nick, strconv.Itoa(server.channels.Len()), client.t("channels formed"))
  1368. rb.Add(nil, server.name, RPL_LUSERME, client.nick, fmt.Sprintf(client.t("I have %[1]d clients and %[2]d servers"), totalCount, 1))
  1369. return false
  1370. }
  1371. // MODE <target> [<modestring> [<mode arguments>...]]
  1372. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1373. _, errChan := CasefoldChannel(msg.Params[0])
  1374. if errChan == nil {
  1375. return cmodeHandler(server, client, msg, rb)
  1376. }
  1377. return umodeHandler(server, client, msg, rb)
  1378. }
  1379. // MODE <channel> [<modestring> [<mode arguments>...]]
  1380. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1381. channelName, err := CasefoldChannel(msg.Params[0])
  1382. channel := server.channels.Get(channelName)
  1383. if err != nil || channel == nil {
  1384. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
  1385. return false
  1386. }
  1387. // applied mode changes
  1388. applied := make(modes.ModeChanges, 0)
  1389. if 1 < len(msg.Params) {
  1390. // parse out real mode changes
  1391. params := msg.Params[1:]
  1392. changes, unknown := modes.ParseChannelModeChanges(params...)
  1393. // alert for unknown mode changes
  1394. for char := range unknown {
  1395. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1396. }
  1397. if len(unknown) == 1 && len(changes) == 0 {
  1398. return false
  1399. }
  1400. // apply mode changes
  1401. applied = channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1402. }
  1403. // save changes
  1404. var includeFlags uint
  1405. for _, change := range applied {
  1406. includeFlags |= IncludeModes
  1407. if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
  1408. includeFlags |= IncludeLists
  1409. }
  1410. }
  1411. if channel.IsRegistered() && includeFlags != 0 {
  1412. go server.channelRegistry.StoreChannel(channel, includeFlags)
  1413. }
  1414. // send out changes
  1415. if len(applied) > 0 {
  1416. //TODO(dan): we should change the name of String and make it return a slice here
  1417. args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
  1418. for _, member := range channel.Members() {
  1419. if member == client {
  1420. rb.Add(nil, client.nickMaskString, "MODE", args...)
  1421. } else {
  1422. member.Send(nil, client.nickMaskString, "MODE", args...)
  1423. }
  1424. }
  1425. } else {
  1426. args := append([]string{client.nick, channel.name}, channel.modeStrings(client)...)
  1427. rb.Add(nil, client.nickMaskString, RPL_CHANNELMODEIS, args...)
  1428. rb.Add(nil, client.nickMaskString, RPL_CHANNELCREATED, client.nick, channel.name, strconv.FormatInt(channel.createdTime.Unix(), 10))
  1429. }
  1430. return false
  1431. }
  1432. // MODE <client> [<modestring> [<mode arguments>...]]
  1433. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1434. nickname, err := CasefoldName(msg.Params[0])
  1435. target := server.clients.Get(nickname)
  1436. if err != nil || target == nil {
  1437. if len(msg.Params[0]) > 0 {
  1438. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  1439. }
  1440. return false
  1441. }
  1442. targetNick := target.Nick()
  1443. hasPrivs := client == target || msg.Command == "SAMODE"
  1444. if !hasPrivs {
  1445. if len(msg.Params) > 1 {
  1446. rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't change modes for other users"))
  1447. } else {
  1448. rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't view modes for other users"))
  1449. }
  1450. return false
  1451. }
  1452. // applied mode changes
  1453. applied := make(modes.ModeChanges, 0)
  1454. if 1 < len(msg.Params) {
  1455. // parse out real mode changes
  1456. params := msg.Params[1:]
  1457. changes, unknown := modes.ParseUserModeChanges(params...)
  1458. // alert for unknown mode changes
  1459. for char := range unknown {
  1460. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1461. }
  1462. if len(unknown) == 1 && len(changes) == 0 {
  1463. return false
  1464. }
  1465. // apply mode changes
  1466. applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
  1467. }
  1468. if len(applied) > 0 {
  1469. rb.Add(nil, client.nickMaskString, "MODE", targetNick, applied.String())
  1470. } else if hasPrivs {
  1471. rb.Add(nil, target.nickMaskString, RPL_UMODEIS, targetNick, target.ModeString())
  1472. if client.HasMode(modes.LocalOperator) || client.HasMode(modes.Operator) {
  1473. masks := server.snomasks.String(client)
  1474. if 0 < len(masks) {
  1475. rb.Add(nil, target.nickMaskString, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1476. }
  1477. }
  1478. }
  1479. return false
  1480. }
  1481. // MONITOR <subcmd> [params...]
  1482. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1483. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1484. if !exists {
  1485. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1486. return false
  1487. }
  1488. return handler(server, client, msg, rb)
  1489. }
  1490. // MONITOR - <target>{,<target>}
  1491. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1492. if len(msg.Params) < 2 {
  1493. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1494. return false
  1495. }
  1496. targets := strings.Split(msg.Params[1], ",")
  1497. for _, target := range targets {
  1498. cfnick, err := CasefoldName(target)
  1499. if err != nil {
  1500. continue
  1501. }
  1502. server.monitorManager.Remove(client, cfnick)
  1503. }
  1504. return false
  1505. }
  1506. // MONITOR + <target>{,<target>}
  1507. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1508. if len(msg.Params) < 2 {
  1509. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1510. return false
  1511. }
  1512. var online []string
  1513. var offline []string
  1514. limits := server.Limits()
  1515. targets := strings.Split(msg.Params[1], ",")
  1516. for _, target := range targets {
  1517. // check name length
  1518. if len(target) < 1 || len(targets) > limits.NickLen {
  1519. continue
  1520. }
  1521. // add target
  1522. casefoldedTarget, err := CasefoldName(target)
  1523. if err != nil {
  1524. continue
  1525. }
  1526. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1527. if err == errMonitorLimitExceeded {
  1528. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1529. break
  1530. } else if err != nil {
  1531. continue
  1532. }
  1533. // add to online / offline lists
  1534. if targetClient := server.clients.Get(casefoldedTarget); targetClient == nil {
  1535. offline = append(offline, target)
  1536. } else {
  1537. online = append(online, targetClient.Nick())
  1538. }
  1539. }
  1540. if len(online) > 0 {
  1541. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1542. }
  1543. if len(offline) > 0 {
  1544. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1545. }
  1546. return false
  1547. }
  1548. // MONITOR C
  1549. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1550. server.monitorManager.RemoveAll(client)
  1551. return false
  1552. }
  1553. // MONITOR L
  1554. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1555. nick := client.Nick()
  1556. monitorList := server.monitorManager.List(client)
  1557. var nickList []string
  1558. for _, cfnick := range monitorList {
  1559. replynick := cfnick
  1560. // report the uncasefolded nick if it's available, i.e., the client is online
  1561. if mclient := server.clients.Get(cfnick); mclient != nil {
  1562. replynick = mclient.Nick()
  1563. }
  1564. nickList = append(nickList, replynick)
  1565. }
  1566. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1567. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1568. }
  1569. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1570. return false
  1571. }
  1572. // MONITOR S
  1573. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1574. var online []string
  1575. var offline []string
  1576. monitorList := server.monitorManager.List(client)
  1577. for _, name := range monitorList {
  1578. target := server.clients.Get(name)
  1579. if target == nil {
  1580. offline = append(offline, name)
  1581. } else {
  1582. online = append(online, target.Nick())
  1583. }
  1584. }
  1585. if len(online) > 0 {
  1586. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1587. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1588. }
  1589. }
  1590. if len(offline) > 0 {
  1591. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1592. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1593. }
  1594. }
  1595. return false
  1596. }
  1597. // MOTD
  1598. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1599. server.MOTD(client, rb)
  1600. return false
  1601. }
  1602. // NAMES [<channel>{,<channel>} [target]]
  1603. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1604. var channels []string
  1605. if len(msg.Params) > 0 {
  1606. channels = strings.Split(msg.Params[0], ",")
  1607. }
  1608. // TODO: in a post-federation world, process `target` (server to forward request to)
  1609. if len(channels) == 0 {
  1610. for _, channel := range server.channels.Channels() {
  1611. channel.Names(client, rb)
  1612. }
  1613. return false
  1614. }
  1615. for _, chname := range channels {
  1616. channel := server.channels.Get(chname)
  1617. if channel != nil {
  1618. channel.Names(client, rb)
  1619. } else if chname != "" {
  1620. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1621. }
  1622. }
  1623. return false
  1624. }
  1625. // NICK <nickname>
  1626. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1627. if client.registered {
  1628. performNickChange(server, client, client, msg.Params[0], rb)
  1629. } else {
  1630. client.preregNick = msg.Params[0]
  1631. }
  1632. return false
  1633. }
  1634. // NOTICE <target>{,<target>} <message>
  1635. func noticeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1636. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  1637. targets := strings.Split(msg.Params[0], ",")
  1638. message := msg.Params[1]
  1639. // split privmsg
  1640. splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
  1641. for i, targetString := range targets {
  1642. // max of four targets per privmsg
  1643. if i > maxTargets-1 {
  1644. break
  1645. }
  1646. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  1647. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1648. target, cerr := CasefoldChannel(targetString)
  1649. if cerr == nil {
  1650. channel := server.channels.Get(target)
  1651. if channel == nil {
  1652. // errors silently ignored with NOTICE as per RFC
  1653. continue
  1654. }
  1655. if !channel.CanSpeak(client) {
  1656. // errors silently ignored with NOTICE as per RFC
  1657. continue
  1658. }
  1659. msgid := server.generateMessageID()
  1660. channel.SplitNotice(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
  1661. } else {
  1662. target, err := CasefoldName(targetString)
  1663. if err != nil {
  1664. continue
  1665. }
  1666. // NOTICEs sent to services are ignored
  1667. if _, isService := OragonoServices[target]; isService {
  1668. continue
  1669. }
  1670. user := server.clients.Get(target)
  1671. if user == nil {
  1672. // errors silently ignored with NOTICE as per RFC
  1673. continue
  1674. }
  1675. if !user.capabilities.Has(caps.MessageTags) {
  1676. clientOnlyTags = nil
  1677. }
  1678. msgid := server.generateMessageID()
  1679. // restrict messages appropriately when +R is set
  1680. // intentionally make the sending user think the message went through fine
  1681. if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
  1682. user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "NOTICE", user.nick, splitMsg)
  1683. }
  1684. nickMaskString := client.NickMaskString()
  1685. accountName := client.AccountName()
  1686. if client.capabilities.Has(caps.EchoMessage) {
  1687. rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "NOTICE", user.nick, splitMsg)
  1688. }
  1689. user.history.Add(history.Item{
  1690. Type: history.Notice,
  1691. Msgid: msgid,
  1692. Message: splitMsg,
  1693. Nick: nickMaskString,
  1694. AccountName: accountName,
  1695. })
  1696. }
  1697. }
  1698. return false
  1699. }
  1700. // NPC <target> <sourcenick> <message>
  1701. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1702. target := msg.Params[0]
  1703. fakeSource := msg.Params[1]
  1704. message := msg.Params[2]
  1705. _, err := CasefoldName(fakeSource)
  1706. if err != nil {
  1707. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1708. return false
  1709. }
  1710. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1711. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1712. return false
  1713. }
  1714. // NPCA <target> <sourcenick> <message>
  1715. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1716. target := msg.Params[0]
  1717. fakeSource := msg.Params[1]
  1718. message := msg.Params[2]
  1719. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1720. _, err := CasefoldName(fakeSource)
  1721. if err != nil {
  1722. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1723. return false
  1724. }
  1725. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1726. return false
  1727. }
  1728. // OPER <name> <password>
  1729. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1730. if client.HasMode(modes.Operator) == true {
  1731. rb.Add(nil, server.name, ERR_UNKNOWNERROR, "OPER", client.t("You're already opered-up!"))
  1732. return false
  1733. }
  1734. authorized := false
  1735. oper := server.GetOperator(msg.Params[0])
  1736. if oper != nil {
  1737. password := []byte(msg.Params[1])
  1738. authorized = (bcrypt.CompareHashAndPassword(oper.Pass, password) == nil)
  1739. }
  1740. if !authorized {
  1741. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
  1742. client.Quit(client.t("Password incorrect"))
  1743. return true
  1744. }
  1745. oldNickmask := client.NickMaskString()
  1746. client.SetOper(oper)
  1747. if client.NickMaskString() != oldNickmask {
  1748. client.sendChghost(oldNickmask, oper.Vhost)
  1749. }
  1750. // set new modes: modes.Operator, plus anything specified in the config
  1751. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1752. modeChanges[0] = modes.ModeChange{
  1753. Mode: modes.Operator,
  1754. Op: modes.Add,
  1755. }
  1756. copy(modeChanges[1:], oper.Modes)
  1757. applied := ApplyUserModeChanges(client, modeChanges, true)
  1758. rb.Add(nil, server.name, RPL_YOUREOPER, client.nick, client.t("You are now an IRC operator"))
  1759. rb.Add(nil, server.name, "MODE", client.nick, applied.String())
  1760. 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))
  1761. // client may now be unthrottled by the fakelag system
  1762. client.resetFakelag()
  1763. return false
  1764. }
  1765. // PART <channel>{,<channel>} [<reason>]
  1766. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1767. channels := strings.Split(msg.Params[0], ",")
  1768. 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
  1769. if len(msg.Params) > 1 {
  1770. reason = msg.Params[1]
  1771. }
  1772. for _, chname := range channels {
  1773. err := server.channels.Part(client, chname, reason, rb)
  1774. if err == errNoSuchChannel {
  1775. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  1776. }
  1777. }
  1778. return false
  1779. }
  1780. // PASS <password>
  1781. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1782. if client.registered {
  1783. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1784. return false
  1785. }
  1786. // if no password exists, skip checking
  1787. serverPassword := server.Password()
  1788. if serverPassword == nil {
  1789. return false
  1790. }
  1791. // check the provided password
  1792. password := []byte(msg.Params[0])
  1793. if bcrypt.CompareHashAndPassword(serverPassword, password) != nil {
  1794. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
  1795. client.Quit(client.t("Password incorrect"))
  1796. return true
  1797. }
  1798. client.sentPassCommand = true
  1799. return false
  1800. }
  1801. // PING [params...]
  1802. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1803. rb.Add(nil, server.name, "PONG", msg.Params...)
  1804. return false
  1805. }
  1806. // PONG [params...]
  1807. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1808. // client gets touched when they send this command, so we don't need to do anything
  1809. return false
  1810. }
  1811. // PRIVMSG <target>{,<target>} <message>
  1812. func privmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1813. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  1814. targets := strings.Split(msg.Params[0], ",")
  1815. message := msg.Params[1]
  1816. // split privmsg
  1817. splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
  1818. cnick := client.Nick()
  1819. for i, targetString := range targets {
  1820. // max of four targets per privmsg
  1821. if i > maxTargets-1 {
  1822. break
  1823. }
  1824. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  1825. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1826. // eh, no need to notify them
  1827. if len(targetString) < 1 {
  1828. continue
  1829. }
  1830. target, err := CasefoldChannel(targetString)
  1831. if err == nil {
  1832. channel := server.channels.Get(target)
  1833. if channel == nil {
  1834. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, cnick, targetString, client.t("No such channel"))
  1835. continue
  1836. }
  1837. if !channel.CanSpeak(client) {
  1838. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
  1839. continue
  1840. }
  1841. msgid := server.generateMessageID()
  1842. channel.SplitPrivMsg(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
  1843. } else {
  1844. target, err = CasefoldName(targetString)
  1845. if service, isService := OragonoServices[target]; isService {
  1846. servicePrivmsgHandler(service, server, client, message, rb)
  1847. continue
  1848. }
  1849. user := server.clients.Get(target)
  1850. if err != nil || user == nil {
  1851. if len(target) > 0 {
  1852. client.Send(nil, server.name, ERR_NOSUCHNICK, cnick, target, "No such nick")
  1853. }
  1854. continue
  1855. }
  1856. if !user.capabilities.Has(caps.MessageTags) {
  1857. clientOnlyTags = nil
  1858. }
  1859. msgid := server.generateMessageID()
  1860. // restrict messages appropriately when +R is set
  1861. // intentionally make the sending user think the message went through fine
  1862. if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
  1863. user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
  1864. }
  1865. nickMaskString := client.NickMaskString()
  1866. accountName := client.AccountName()
  1867. if client.capabilities.Has(caps.EchoMessage) {
  1868. rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
  1869. }
  1870. if user.HasMode(modes.Away) {
  1871. //TODO(dan): possibly implement cooldown of away notifications to users
  1872. rb.Add(nil, server.name, RPL_AWAY, cnick, user.Nick(), user.AwayMessage())
  1873. }
  1874. user.history.Add(history.Item{
  1875. Type: history.Privmsg,
  1876. Msgid: msgid,
  1877. Message: splitMsg,
  1878. Nick: nickMaskString,
  1879. AccountName: accountName,
  1880. })
  1881. }
  1882. }
  1883. return false
  1884. }
  1885. // QUIT [<reason>]
  1886. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1887. reason := "Quit"
  1888. if len(msg.Params) > 0 {
  1889. reason += ": " + msg.Params[0]
  1890. }
  1891. client.Quit(reason)
  1892. return true
  1893. }
  1894. // REHASH
  1895. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1896. server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
  1897. err := server.rehash()
  1898. if err == nil {
  1899. rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
  1900. } else {
  1901. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  1902. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
  1903. }
  1904. return false
  1905. }
  1906. // RENAME <oldchan> <newchan> [<reason>]
  1907. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  1908. result = false
  1909. errorResponse := func(err error, name string) {
  1910. // TODO: send correct error codes, e.g., ERR_CANNOTRENAME, ERR_CHANNAMEINUSE
  1911. var code string
  1912. switch err {
  1913. case errNoSuchChannel:
  1914. code = ERR_NOSUCHCHANNEL
  1915. case errRenamePrivsNeeded:
  1916. code = ERR_CHANOPRIVSNEEDED
  1917. case errInvalidChannelName:
  1918. code = ERR_UNKNOWNERROR
  1919. case errChannelNameInUse:
  1920. code = ERR_UNKNOWNERROR
  1921. default:
  1922. code = ERR_UNKNOWNERROR
  1923. }
  1924. rb.Add(nil, server.name, code, client.Nick(), "RENAME", name, err.Error())
  1925. }
  1926. oldName := strings.TrimSpace(msg.Params[0])
  1927. newName := strings.TrimSpace(msg.Params[1])
  1928. if oldName == "" || newName == "" {
  1929. errorResponse(errInvalidChannelName, "<empty>")
  1930. return
  1931. }
  1932. casefoldedOldName, err := CasefoldChannel(oldName)
  1933. if err != nil {
  1934. errorResponse(errInvalidChannelName, oldName)
  1935. return
  1936. }
  1937. reason := "No reason"
  1938. if 2 < len(msg.Params) {
  1939. reason = msg.Params[2]
  1940. }
  1941. channel := server.channels.Get(oldName)
  1942. if channel == nil {
  1943. errorResponse(errNoSuchChannel, oldName)
  1944. return
  1945. }
  1946. //TODO(dan): allow IRCops to do this?
  1947. if !channel.ClientIsAtLeast(client, modes.Operator) {
  1948. errorResponse(errRenamePrivsNeeded, oldName)
  1949. return
  1950. }
  1951. founder := channel.Founder()
  1952. if founder != "" && founder != client.Account() {
  1953. //TODO(dan): Change this to ERR_CANNOTRENAME
  1954. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "RENAME", oldName, client.t("Only channel founders can change registered channels"))
  1955. return false
  1956. }
  1957. // perform the channel rename
  1958. err = server.channels.Rename(oldName, newName)
  1959. if err != nil {
  1960. errorResponse(err, newName)
  1961. return
  1962. }
  1963. // rename succeeded, persist it
  1964. go server.channelRegistry.Rename(channel, casefoldedOldName)
  1965. // send RENAME messages
  1966. for _, mcl := range channel.Members() {
  1967. if mcl.capabilities.Has(caps.Rename) {
  1968. mcl.Send(nil, client.nickMaskString, "RENAME", oldName, newName, reason)
  1969. } else {
  1970. mcl.Send(nil, mcl.nickMaskString, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  1971. if mcl.capabilities.Has(caps.ExtendedJoin) {
  1972. mcl.Send(nil, mcl.nickMaskString, "JOIN", newName, mcl.AccountName(), mcl.realname)
  1973. } else {
  1974. mcl.Send(nil, mcl.nickMaskString, "JOIN", newName)
  1975. }
  1976. }
  1977. }
  1978. return false
  1979. }
  1980. // RESUME <token> [timestamp]
  1981. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1982. token := msg.Params[0]
  1983. if client.registered {
  1984. rb.Add(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection, connection registration has already been completed"))
  1985. return false
  1986. }
  1987. var timestamp time.Time
  1988. if 1 < len(msg.Params) {
  1989. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  1990. if err == nil {
  1991. timestamp = ts
  1992. } else {
  1993. rb.Add(nil, server.name, "RESUME", "WARN", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  1994. }
  1995. }
  1996. client.resumeDetails = &ResumeDetails{
  1997. Timestamp: timestamp,
  1998. PresentedToken: token,
  1999. }
  2000. return false
  2001. }
  2002. // SANICK <oldnick> <nickname>
  2003. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2004. targetNick := strings.TrimSpace(msg.Params[0])
  2005. target := server.clients.Get(targetNick)
  2006. if target == nil {
  2007. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2008. return false
  2009. }
  2010. performNickChange(server, client, target, msg.Params[1], rb)
  2011. return false
  2012. }
  2013. // SCENE <target> <message>
  2014. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2015. target := msg.Params[0]
  2016. message := msg.Params[1]
  2017. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2018. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2019. return false
  2020. }
  2021. // SETNAME <realname>
  2022. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2023. realname := msg.Params[0]
  2024. client.stateMutex.Lock()
  2025. client.realname = realname
  2026. client.stateMutex.Unlock()
  2027. // alert friends
  2028. for friend := range client.Friends(caps.SetName) {
  2029. friend.SendFromClient("", client, nil, "SETNAME", realname)
  2030. }
  2031. return false
  2032. }
  2033. // TAGMSG <target>{,<target>}
  2034. func tagmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2035. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  2036. // no client-only tags, so we can drop it
  2037. if clientOnlyTags == nil {
  2038. return false
  2039. }
  2040. targets := strings.Split(msg.Params[0], ",")
  2041. cnick := client.Nick()
  2042. for i, targetString := range targets {
  2043. // max of four targets per privmsg
  2044. if i > maxTargets-1 {
  2045. break
  2046. }
  2047. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  2048. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  2049. // eh, no need to notify them
  2050. if len(targetString) < 1 {
  2051. continue
  2052. }
  2053. target, err := CasefoldChannel(targetString)
  2054. if err == nil {
  2055. channel := server.channels.Get(target)
  2056. if channel == nil {
  2057. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, cnick, targetString, client.t("No such channel"))
  2058. continue
  2059. }
  2060. if !channel.CanSpeak(client) {
  2061. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
  2062. continue
  2063. }
  2064. msgid := server.generateMessageID()
  2065. channel.TagMsg(msgid, lowestPrefix, clientOnlyTags, client, rb)
  2066. } else {
  2067. target, err = CasefoldName(targetString)
  2068. user := server.clients.Get(target)
  2069. if err != nil || user == nil {
  2070. if len(target) > 0 {
  2071. client.Send(nil, server.name, ERR_NOSUCHNICK, cnick, target, client.t("No such nick"))
  2072. }
  2073. continue
  2074. }
  2075. msgid := server.generateMessageID()
  2076. // end user can't receive tagmsgs
  2077. if !user.capabilities.Has(caps.MessageTags) {
  2078. continue
  2079. }
  2080. user.SendFromClient(msgid, client, clientOnlyTags, "TAGMSG", user.nick)
  2081. if client.capabilities.Has(caps.EchoMessage) {
  2082. rb.AddFromClient(msgid, client.NickMaskString(), client.AccountName(), clientOnlyTags, "TAGMSG", user.nick)
  2083. }
  2084. if user.HasMode(modes.Away) {
  2085. //TODO(dan): possibly implement cooldown of away notifications to users
  2086. rb.Add(nil, server.name, RPL_AWAY, cnick, user.Nick(), user.AwayMessage())
  2087. }
  2088. }
  2089. }
  2090. return false
  2091. }
  2092. // TIME
  2093. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2094. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().Format(time.RFC1123))
  2095. return false
  2096. }
  2097. // TOPIC <channel> [<topic>]
  2098. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2099. name, err := CasefoldChannel(msg.Params[0])
  2100. channel := server.channels.Get(name)
  2101. if err != nil || channel == nil {
  2102. if len(msg.Params[0]) > 0 {
  2103. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
  2104. }
  2105. return false
  2106. }
  2107. if len(msg.Params) > 1 {
  2108. channel.SetTopic(client, msg.Params[1], rb)
  2109. } else {
  2110. channel.SendTopic(client, rb, true)
  2111. }
  2112. return false
  2113. }
  2114. // UNDLINE <ip>|<net>
  2115. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2116. // check oper permissions
  2117. oper := client.Oper()
  2118. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2119. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2120. return false
  2121. }
  2122. // get host
  2123. hostString := msg.Params[0]
  2124. // check host
  2125. hostNet, err := utils.NormalizedNetFromString(hostString)
  2126. if err != nil {
  2127. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2128. return false
  2129. }
  2130. err = server.dlines.RemoveNetwork(hostNet)
  2131. if err != nil {
  2132. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2133. return false
  2134. }
  2135. hostString = utils.NetToNormalizedString(hostNet)
  2136. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2137. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2138. return false
  2139. }
  2140. // UNKLINE <mask>
  2141. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2142. // check oper permissions
  2143. oper := client.Oper()
  2144. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2145. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2146. return false
  2147. }
  2148. // get host
  2149. mask := msg.Params[0]
  2150. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  2151. mask = mask + "!*@*"
  2152. } else if !strings.Contains(mask, "@") {
  2153. mask = mask + "@*"
  2154. }
  2155. err := server.klines.RemoveMask(mask)
  2156. if err != nil {
  2157. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2158. return false
  2159. }
  2160. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2161. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
  2162. return false
  2163. }
  2164. // USER <username> * 0 <realname>
  2165. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2166. if client.registered {
  2167. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  2168. return false
  2169. }
  2170. err := client.SetNames(msg.Params[0], msg.Params[3], false)
  2171. if err == errInvalidUsername {
  2172. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2173. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2174. if client.preregNick == msg.Params[0] {
  2175. client.SetNames("user", msg.Params[3], false)
  2176. } else {
  2177. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.t("Malformed username"))
  2178. }
  2179. }
  2180. return false
  2181. }
  2182. // USERHOST <nickname>{ <nickname>}
  2183. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2184. returnedNicks := make(map[string]bool)
  2185. for i, nickname := range msg.Params {
  2186. if i >= 10 {
  2187. break
  2188. }
  2189. casefoldedNickname, err := CasefoldName(nickname)
  2190. target := server.clients.Get(casefoldedNickname)
  2191. if err != nil || target == nil {
  2192. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  2193. return false
  2194. }
  2195. if returnedNicks[casefoldedNickname] {
  2196. continue
  2197. }
  2198. // to prevent returning multiple results for a single nick
  2199. returnedNicks[casefoldedNickname] = true
  2200. var isOper, isAway string
  2201. if target.HasMode(modes.Operator) {
  2202. isOper = "*"
  2203. }
  2204. if target.HasMode(modes.Away) {
  2205. isAway = "-"
  2206. } else {
  2207. isAway = "+"
  2208. }
  2209. 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))
  2210. }
  2211. return false
  2212. }
  2213. // VERSION
  2214. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2215. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2216. client.RplISupport(rb)
  2217. return false
  2218. }
  2219. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2220. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2221. // only allow unregistered clients to use this command
  2222. if client.registered || client.proxiedIP != nil {
  2223. return false
  2224. }
  2225. // process flags
  2226. var secure bool
  2227. if 4 < len(msg.Params) {
  2228. for _, x := range strings.Split(msg.Params[4], " ") {
  2229. // split into key=value
  2230. var key string
  2231. if strings.Contains(x, "=") {
  2232. y := strings.SplitN(x, "=", 2)
  2233. key, _ = y[0], y[1]
  2234. } else {
  2235. key = x
  2236. }
  2237. lkey := strings.ToLower(key)
  2238. if lkey == "tls" || lkey == "secure" {
  2239. // only accept "tls" flag if the gateway's connection to us is secure as well
  2240. if client.HasMode(modes.TLS) || utils.AddrIsLocal(client.socket.conn.RemoteAddr()) {
  2241. secure = true
  2242. }
  2243. }
  2244. }
  2245. }
  2246. givenPassword := []byte(msg.Params[0])
  2247. for _, info := range server.Config().Server.WebIRC {
  2248. if utils.IPInNets(client.realIP, info.allowedNets) {
  2249. // confirm password and/or fingerprint
  2250. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2251. continue
  2252. }
  2253. if 0 < len(info.Fingerprint) && client.certfp != info.Fingerprint {
  2254. continue
  2255. }
  2256. proxiedIP := msg.Params[3]
  2257. // see #211; websocket gateways will wrap ipv6 addresses in square brackets
  2258. // because IRC parameters can't start with :
  2259. if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
  2260. proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
  2261. }
  2262. return !client.ApplyProxiedIP(proxiedIP, secure)
  2263. }
  2264. }
  2265. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"))
  2266. return true
  2267. }
  2268. // WHO [<mask> [o]]
  2269. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2270. if msg.Params[0] == "" {
  2271. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2272. return false
  2273. }
  2274. var mask string
  2275. if len(msg.Params) > 0 {
  2276. casefoldedMask, err := Casefold(msg.Params[0])
  2277. if err != nil {
  2278. rb.Add(nil, server.name, ERR_UNKNOWNERROR, "WHO", client.t("Mask isn't valid"))
  2279. return false
  2280. }
  2281. mask = casefoldedMask
  2282. }
  2283. friends := client.Friends()
  2284. //TODO(dan): is this used and would I put this param in the Modern doc?
  2285. // if not, can we remove it?
  2286. //var operatorOnly bool
  2287. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2288. // operatorOnly = true
  2289. //}
  2290. if mask[0] == '#' {
  2291. // TODO implement wildcard matching
  2292. //TODO(dan): ^ only for opers
  2293. channel := server.channels.Get(mask)
  2294. if channel != nil {
  2295. whoChannel(client, channel, friends, rb)
  2296. }
  2297. } else {
  2298. for mclient := range server.clients.FindAll(mask) {
  2299. client.rplWhoReply(nil, mclient, rb)
  2300. }
  2301. }
  2302. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2303. return false
  2304. }
  2305. // WHOIS [<target>] <mask>{,<mask>}
  2306. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2307. var masksString string
  2308. //var target string
  2309. if len(msg.Params) > 1 {
  2310. //target = msg.Params[0]
  2311. masksString = msg.Params[1]
  2312. } else {
  2313. masksString = msg.Params[0]
  2314. }
  2315. if len(strings.TrimSpace(masksString)) < 1 {
  2316. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("No masks given"))
  2317. return false
  2318. }
  2319. handleService := func(nick string) bool {
  2320. cfnick, _ := CasefoldName(nick)
  2321. service, ok := OragonoServices[cfnick]
  2322. if !ok {
  2323. return false
  2324. }
  2325. clientNick := client.Nick()
  2326. 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))
  2327. // hehe
  2328. if client.HasMode(modes.TLS) {
  2329. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2330. }
  2331. return true
  2332. }
  2333. if client.HasMode(modes.Operator) {
  2334. for _, mask := range strings.Split(masksString, ",") {
  2335. matches := server.clients.FindAll(mask)
  2336. if len(matches) == 0 && !handleService(mask) {
  2337. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, mask, client.t("No such nick"))
  2338. continue
  2339. }
  2340. for mclient := range matches {
  2341. client.getWhoisOf(mclient, rb)
  2342. }
  2343. }
  2344. } else {
  2345. // only get the first request; also require a nick, not a mask
  2346. nick := strings.Split(masksString, ",")[0]
  2347. mclient := server.clients.Get(nick)
  2348. if mclient != nil {
  2349. client.getWhoisOf(mclient, rb)
  2350. } else if !handleService(nick) {
  2351. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, masksString, client.t("No such nick"))
  2352. }
  2353. // fall through, ENDOFWHOIS is always sent
  2354. }
  2355. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, masksString, client.t("End of /WHOIS list"))
  2356. return false
  2357. }
  2358. // WHOWAS <nickname> [<count> [<server>]]
  2359. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2360. nicknames := strings.Split(msg.Params[0], ",")
  2361. // 0 means "all the entries", as does a negative number
  2362. var count uint64
  2363. if len(msg.Params) > 1 {
  2364. count, _ = strconv.ParseUint(msg.Params[1], 10, 64)
  2365. }
  2366. //var target string
  2367. //if len(msg.Params) > 2 {
  2368. // target = msg.Params[2]
  2369. //}
  2370. cnick := client.Nick()
  2371. for _, nickname := range nicknames {
  2372. results := server.whoWas.Find(nickname, int(count))
  2373. if len(results) == 0 {
  2374. if len(nickname) > 0 {
  2375. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, nickname, client.t("There was no such nickname"))
  2376. }
  2377. } else {
  2378. for _, whoWas := range results {
  2379. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2380. }
  2381. }
  2382. if len(nickname) > 0 {
  2383. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, nickname, client.t("End of WHOWAS"))
  2384. }
  2385. }
  2386. return false
  2387. }