您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

handlers.go 75KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  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 := "Unknown"
  136. code := ERR_UNKNOWNERROR
  137. if err == errCertfpAlreadyExists {
  138. msg = "An account already exists for your certificate fingerprint"
  139. } else if err == errAccountAlreadyRegistered {
  140. msg = "Account already exists"
  141. code = ERR_ACCOUNT_ALREADY_EXISTS
  142. } else if err == errAccountBadPassphrase {
  143. msg = "Passphrase contains forbidden characters or is otherwise invalid"
  144. }
  145. if err == errAccountAlreadyRegistered || err == errAccountCreation || err == errCertfpAlreadyExists {
  146. msg = err.Error()
  147. }
  148. rb.Add(nil, server.name, code, nick, "ACC", "REGISTER", client.t(msg))
  149. return false
  150. }
  151. // automatically complete registration
  152. if callbackNamespace == "*" {
  153. err := server.accounts.Verify(client, casefoldedAccount, "")
  154. if err != nil {
  155. return false
  156. }
  157. sendSuccessfulRegResponse(client, rb, false)
  158. } else {
  159. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s:%s")
  160. message := fmt.Sprintf(messageTemplate, callbackNamespace, callbackValue)
  161. rb.Add(nil, server.name, RPL_REG_VERIFICATION_REQUIRED, nick, casefoldedAccount, message)
  162. }
  163. return false
  164. }
  165. // helper function to dispatch messages when a client successfully registers
  166. func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
  167. if forNS {
  168. rb.Notice(client.t("Account created"))
  169. } else {
  170. rb.Add(nil, client.server.name, RPL_REGISTRATION_SUCCESS, client.nick, client.AccountName(), client.t("Account created"))
  171. }
  172. sendSuccessfulSaslAuth(client, rb, forNS)
  173. }
  174. // sendSuccessfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
  175. func sendSuccessfulSaslAuth(client *Client, rb *ResponseBuffer, forNS bool) {
  176. account := client.AccountName()
  177. if forNS {
  178. rb.Notice(fmt.Sprintf(client.t("You're now logged in as %s"), client.AccountName()))
  179. } else {
  180. rb.Add(nil, client.server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account, fmt.Sprintf(client.t("You are now logged in as %s"), account))
  181. rb.Add(nil, client.server.name, RPL_SASLSUCCESS, client.nick, client.t("Authentication successful"))
  182. }
  183. // dispatch account-notify
  184. for friend := range client.Friends(caps.AccountNotify) {
  185. friend.Send(nil, client.nickMaskString, "ACCOUNT", account)
  186. }
  187. 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]]"), client.nickMaskString, account))
  188. }
  189. // ACC VERIFY <accountname> <auth_code>
  190. func accVerifyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  191. account := strings.TrimSpace(msg.Params[1])
  192. err := server.accounts.Verify(client, account, msg.Params[2])
  193. var code string
  194. var message string
  195. if err == errAccountVerificationInvalidCode {
  196. code = ERR_ACCOUNT_INVALID_VERIFY_CODE
  197. message = err.Error()
  198. } else if err == errAccountAlreadyVerified {
  199. code = ERR_ACCOUNT_ALREADY_VERIFIED
  200. message = err.Error()
  201. } else if err != nil {
  202. code = ERR_UNKNOWNERROR
  203. message = errAccountVerificationFailed.Error()
  204. }
  205. if err == nil {
  206. sendSuccessfulRegResponse(client, rb, false)
  207. } else {
  208. rb.Add(nil, server.name, code, client.nick, account, client.t(message))
  209. }
  210. return false
  211. }
  212. // AUTHENTICATE [<mechanism>|<data>|*]
  213. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  214. // sasl abort
  215. if !server.AccountConfig().AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
  216. rb.Add(nil, server.name, ERR_SASLABORTED, client.nick, client.t("SASL authentication aborted"))
  217. client.saslInProgress = false
  218. client.saslMechanism = ""
  219. client.saslValue = ""
  220. return false
  221. }
  222. // start new sasl session
  223. if !client.saslInProgress {
  224. mechanism := strings.ToUpper(msg.Params[0])
  225. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  226. if mechanismIsEnabled {
  227. client.saslInProgress = true
  228. client.saslMechanism = mechanism
  229. rb.Add(nil, server.name, "AUTHENTICATE", "+")
  230. } else {
  231. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
  232. }
  233. return false
  234. }
  235. // continue existing sasl session
  236. rawData := msg.Params[0]
  237. if len(rawData) > 400 {
  238. rb.Add(nil, server.name, ERR_SASLTOOLONG, client.nick, client.t("SASL message too long"))
  239. client.saslInProgress = false
  240. client.saslMechanism = ""
  241. client.saslValue = ""
  242. return false
  243. } else if len(rawData) == 400 {
  244. client.saslValue += rawData
  245. // allow 4 'continuation' lines before rejecting for length
  246. if len(client.saslValue) > 400*4 {
  247. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Passphrase too long"))
  248. client.saslInProgress = false
  249. client.saslMechanism = ""
  250. client.saslValue = ""
  251. return false
  252. }
  253. return false
  254. }
  255. if rawData != "+" {
  256. client.saslValue += rawData
  257. }
  258. var data []byte
  259. var err error
  260. if client.saslValue != "+" {
  261. data, err = base64.StdEncoding.DecodeString(client.saslValue)
  262. if err != nil {
  263. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
  264. client.saslInProgress = false
  265. client.saslMechanism = ""
  266. client.saslValue = ""
  267. return false
  268. }
  269. }
  270. // call actual handler
  271. handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
  272. // like 100% not required, but it's good to be safe I guess
  273. if !handlerExists {
  274. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
  275. client.saslInProgress = false
  276. client.saslMechanism = ""
  277. client.saslValue = ""
  278. return false
  279. }
  280. // let the SASL handler do its thing
  281. exiting := handler(server, client, client.saslMechanism, data, rb)
  282. if client.LoggedIntoAccount() && server.AccountConfig().SkipServerPassword {
  283. client.SetAuthorized(true)
  284. }
  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 text string
  352. if len(msg.Params) > 0 {
  353. isAway = true
  354. text = msg.Params[0]
  355. awayLen := server.Limits().AwayLen
  356. if len(text) > awayLen {
  357. text = text[:awayLen]
  358. }
  359. }
  360. client.SetMode(modes.Away, isAway)
  361. client.awayMessage = text
  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", client.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, err := client.generateResumeToken()
  443. if err == nil {
  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. // DEBUG <subcmd>
  457. func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  458. param := strings.ToUpper(msg.Params[0])
  459. switch param {
  460. case "GCSTATS":
  461. stats := debug.GCStats{
  462. Pause: make([]time.Duration, 10),
  463. PauseQuantiles: make([]time.Duration, 5),
  464. }
  465. debug.ReadGCStats(&stats)
  466. rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
  467. rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
  468. rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
  469. rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
  470. rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
  471. rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
  472. rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
  473. rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
  474. case "NUMGOROUTINE":
  475. count := runtime.NumGoroutine()
  476. rb.Notice(fmt.Sprintf("num goroutines: %d", count))
  477. case "PROFILEHEAP":
  478. profFile := "oragono.mprof"
  479. file, err := os.Create(profFile)
  480. if err != nil {
  481. rb.Notice(fmt.Sprintf("error: %s", err))
  482. break
  483. }
  484. defer file.Close()
  485. pprof.Lookup("heap").WriteTo(file, 0)
  486. rb.Notice(fmt.Sprintf("written to %s", profFile))
  487. case "STARTCPUPROFILE":
  488. profFile := "oragono.prof"
  489. file, err := os.Create(profFile)
  490. if err != nil {
  491. rb.Notice(fmt.Sprintf("error: %s", err))
  492. break
  493. }
  494. if err := pprof.StartCPUProfile(file); err != nil {
  495. defer file.Close()
  496. rb.Notice(fmt.Sprintf("error: %s", err))
  497. break
  498. }
  499. rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
  500. case "STOPCPUPROFILE":
  501. pprof.StopCPUProfile()
  502. rb.Notice(fmt.Sprintf("CPU profiling stopped"))
  503. }
  504. return false
  505. }
  506. // helper for parsing the reason args to DLINE and KLINE
  507. func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
  508. reason = "No reason given"
  509. operReason = ""
  510. if len(params) > currentArg {
  511. reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
  512. if len(reasons) == 1 {
  513. reason = strings.TrimSpace(reasons[0])
  514. } else if len(reasons) == 2 {
  515. reason = strings.TrimSpace(reasons[0])
  516. operReason = strings.TrimSpace(reasons[1])
  517. }
  518. }
  519. return
  520. }
  521. func formatBanForListing(client *Client, key string, info IPBanInfo) string {
  522. desc := info.Reason
  523. if info.OperReason != "" && info.OperReason != info.Reason {
  524. desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
  525. }
  526. if info.Duration != 0 {
  527. desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
  528. }
  529. return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
  530. }
  531. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  532. // DLINE LIST
  533. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  534. // check oper permissions
  535. oper := client.Oper()
  536. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  537. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  538. return false
  539. }
  540. currentArg := 0
  541. // if they say LIST, we just list the current dlines
  542. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  543. bans := server.dlines.AllBans()
  544. if len(bans) == 0 {
  545. rb.Notice(client.t("No DLINEs have been set!"))
  546. }
  547. for key, info := range bans {
  548. client.Notice(formatBanForListing(client, key, info))
  549. }
  550. return false
  551. }
  552. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  553. var andKill bool
  554. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  555. andKill = true
  556. currentArg++
  557. }
  558. // when setting a ban that covers the oper's current connection, we require them to say
  559. // "DLINE MYSELF" so that we're sure they really mean it.
  560. var dlineMyself bool
  561. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  562. dlineMyself = true
  563. currentArg++
  564. }
  565. // duration
  566. duration, err := custime.ParseDuration(msg.Params[currentArg])
  567. if err != nil {
  568. duration = 0
  569. } else {
  570. currentArg++
  571. }
  572. // get host
  573. if len(msg.Params) < currentArg+1 {
  574. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  575. return false
  576. }
  577. hostString := msg.Params[currentArg]
  578. currentArg++
  579. // check host
  580. hostNet, err := utils.NormalizedNetFromString(hostString)
  581. if err != nil {
  582. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  583. return false
  584. }
  585. if !dlineMyself && hostNet.Contains(client.IP()) {
  586. 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>"))
  587. return false
  588. }
  589. // check remote
  590. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  591. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  592. return false
  593. }
  594. // get comment(s)
  595. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  596. operName := oper.Name
  597. if operName == "" {
  598. operName = server.name
  599. }
  600. err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
  601. if err != nil {
  602. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
  603. return false
  604. }
  605. var snoDescription string
  606. hostString = utils.NetToNormalizedString(hostNet)
  607. if duration != 0 {
  608. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
  609. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
  610. } else {
  611. rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
  612. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
  613. }
  614. server.snomasks.Send(sno.LocalXline, snoDescription)
  615. var killClient bool
  616. if andKill {
  617. var clientsToKill []*Client
  618. var killedClientNicks []string
  619. for _, mcl := range server.clients.AllClients() {
  620. if hostNet.Contains(mcl.IP()) {
  621. clientsToKill = append(clientsToKill, mcl)
  622. killedClientNicks = append(killedClientNicks, mcl.nick)
  623. }
  624. }
  625. for _, mcl := range clientsToKill {
  626. mcl.exitedSnomaskSent = true
  627. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
  628. if mcl == client {
  629. killClient = true
  630. } else {
  631. // if mcl == client, we kill them below
  632. mcl.destroy(false)
  633. }
  634. }
  635. // send snomask
  636. sort.Strings(killedClientNicks)
  637. 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, ", ")))
  638. }
  639. return killClient
  640. }
  641. // HELP [<query>]
  642. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  643. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  644. if len(argument) < 1 {
  645. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  646. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  647. return false
  648. }
  649. // handle index
  650. if argument == "index" {
  651. if client.HasMode(modes.Operator) {
  652. client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndexOpers), rb)
  653. } else {
  654. client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndex), rb)
  655. }
  656. return false
  657. }
  658. helpHandler, exists := Help[argument]
  659. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  660. if helpHandler.textGenerator != nil {
  661. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.textGenerator(client)), rb)
  662. } else {
  663. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  664. }
  665. } else {
  666. args := msg.Params
  667. args = append(args, client.t("Help not found"))
  668. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  669. }
  670. return false
  671. }
  672. // INFO
  673. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  674. // we do the below so that the human-readable lines in info can be translated.
  675. for _, line := range infoString1 {
  676. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  677. }
  678. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
  679. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  680. 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")
  681. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  682. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
  683. for _, line := range infoString2 {
  684. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  685. }
  686. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
  687. for _, line := range infoString3 {
  688. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  689. }
  690. // show translators for languages other than good ole' regular English
  691. tlines := server.languages.Translators()
  692. if 0 < len(tlines) {
  693. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
  694. for _, line := range tlines {
  695. rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
  696. }
  697. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  698. }
  699. rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
  700. return false
  701. }
  702. // INVITE <nickname> <channel>
  703. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  704. nickname := msg.Params[0]
  705. channelName := msg.Params[1]
  706. casefoldedNickname, err := CasefoldName(nickname)
  707. target := server.clients.Get(casefoldedNickname)
  708. if err != nil || target == nil {
  709. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  710. return false
  711. }
  712. casefoldedChannelName, err := CasefoldChannel(channelName)
  713. channel := server.channels.Get(casefoldedChannelName)
  714. if err != nil || channel == nil {
  715. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, channelName, client.t("No such channel"))
  716. return false
  717. }
  718. channel.Invite(target, client, rb)
  719. return false
  720. }
  721. // ISON <nick>{ <nick>}
  722. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  723. var nicks = msg.Params
  724. var err error
  725. var casefoldedNick string
  726. ison := make([]string, 0)
  727. for _, nick := range nicks {
  728. casefoldedNick, err = CasefoldName(nick)
  729. if err != nil {
  730. continue
  731. }
  732. if iclient := server.clients.Get(casefoldedNick); iclient != nil {
  733. ison = append(ison, iclient.nick)
  734. }
  735. }
  736. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(nicks, " "))
  737. return false
  738. }
  739. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  740. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  741. // kill JOIN 0 requests
  742. if msg.Params[0] == "0" {
  743. rb.Notice(client.t("JOIN 0 is not allowed"))
  744. return false
  745. }
  746. // handle regular JOINs
  747. channels := strings.Split(msg.Params[0], ",")
  748. var keys []string
  749. if len(msg.Params) > 1 {
  750. keys = strings.Split(msg.Params[1], ",")
  751. }
  752. for i, name := range channels {
  753. var key string
  754. if len(keys) > i {
  755. key = keys[i]
  756. }
  757. err := server.channels.Join(client, name, key, false, rb)
  758. if err == errNoSuchChannel {
  759. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), name, client.t("No such channel"))
  760. }
  761. }
  762. return false
  763. }
  764. // SAJOIN [nick] #channel{,#channel}
  765. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  766. var target *Client
  767. var channelString string
  768. if strings.HasPrefix(msg.Params[0], "#") {
  769. target = client
  770. channelString = msg.Params[0]
  771. } else {
  772. if len(msg.Params) == 1 {
  773. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "KICK", client.t("Not enough parameters"))
  774. return false
  775. } else {
  776. target = server.clients.Get(msg.Params[0])
  777. if target == nil {
  778. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), msg.Params[0], "No such nick")
  779. return false
  780. }
  781. channelString = msg.Params[1]
  782. rb = NewResponseBuffer(target)
  783. }
  784. }
  785. channels := strings.Split(channelString, ",")
  786. for _, chname := range channels {
  787. server.channels.Join(target, chname, "", true, rb)
  788. }
  789. if client != target {
  790. rb.Send(false)
  791. }
  792. return false
  793. }
  794. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  795. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  796. channels := strings.Split(msg.Params[0], ",")
  797. users := strings.Split(msg.Params[1], ",")
  798. if (len(channels) != len(users)) && (len(users) != 1) {
  799. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  800. return false
  801. }
  802. var kicks [][]string
  803. for index, channel := range channels {
  804. if len(users) == 1 {
  805. kicks = append(kicks, []string{channel, users[0]})
  806. } else {
  807. kicks = append(kicks, []string{channel, users[index]})
  808. }
  809. }
  810. var comment string
  811. if len(msg.Params) > 2 {
  812. comment = msg.Params[2]
  813. }
  814. for _, info := range kicks {
  815. chname := info[0]
  816. nickname := info[1]
  817. casefoldedChname, err := CasefoldChannel(chname)
  818. channel := server.channels.Get(casefoldedChname)
  819. if err != nil || channel == nil {
  820. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  821. continue
  822. }
  823. casefoldedNickname, err := CasefoldName(nickname)
  824. target := server.clients.Get(casefoldedNickname)
  825. if err != nil || target == nil {
  826. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  827. continue
  828. }
  829. if comment == "" {
  830. comment = nickname
  831. }
  832. channel.Kick(client, target, comment, rb)
  833. }
  834. return false
  835. }
  836. // KILL <nickname> <comment>
  837. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  838. nickname := msg.Params[0]
  839. comment := "<no reason supplied>"
  840. if len(msg.Params) > 1 {
  841. comment = msg.Params[1]
  842. }
  843. casefoldedNickname, err := CasefoldName(nickname)
  844. target := server.clients.Get(casefoldedNickname)
  845. if err != nil || target == nil {
  846. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  847. return false
  848. }
  849. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  850. 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))
  851. target.exitedSnomaskSent = true
  852. target.Quit(quitMsg)
  853. target.destroy(false)
  854. return false
  855. }
  856. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  857. // KLINE LIST
  858. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  859. // check oper permissions
  860. oper := client.Oper()
  861. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  862. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  863. return false
  864. }
  865. currentArg := 0
  866. // if they say LIST, we just list the current klines
  867. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  868. bans := server.klines.AllBans()
  869. if len(bans) == 0 {
  870. client.Notice("No KLINEs have been set!")
  871. }
  872. for key, info := range bans {
  873. client.Notice(formatBanForListing(client, key, info))
  874. }
  875. return false
  876. }
  877. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  878. var andKill bool
  879. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  880. andKill = true
  881. currentArg++
  882. }
  883. // when setting a ban that covers the oper's current connection, we require them to say
  884. // "KLINE MYSELF" so that we're sure they really mean it.
  885. var klineMyself bool
  886. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  887. klineMyself = true
  888. currentArg++
  889. }
  890. // duration
  891. duration, err := custime.ParseDuration(msg.Params[currentArg])
  892. if err != nil {
  893. duration = 0
  894. } else {
  895. currentArg++
  896. }
  897. // get mask
  898. if len(msg.Params) < currentArg+1 {
  899. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  900. return false
  901. }
  902. mask := strings.ToLower(msg.Params[currentArg])
  903. currentArg++
  904. // check mask
  905. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  906. mask = mask + "!*@*"
  907. } else if !strings.Contains(mask, "@") {
  908. mask = mask + "@*"
  909. }
  910. matcher := ircmatch.MakeMatch(mask)
  911. for _, clientMask := range client.AllNickmasks() {
  912. if !klineMyself && matcher.Match(clientMask) {
  913. 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>"))
  914. return false
  915. }
  916. }
  917. // check remote
  918. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  919. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  920. return false
  921. }
  922. // get oper name
  923. operName := oper.Name
  924. if operName == "" {
  925. operName = server.name
  926. }
  927. // get comment(s)
  928. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  929. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  930. if err != nil {
  931. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  932. return false
  933. }
  934. var snoDescription string
  935. if duration != 0 {
  936. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  937. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), client.nick, operName, duration.String(), mask)
  938. } else {
  939. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  940. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), client.nick, operName, mask)
  941. }
  942. server.snomasks.Send(sno.LocalXline, snoDescription)
  943. var killClient bool
  944. if andKill {
  945. var clientsToKill []*Client
  946. var killedClientNicks []string
  947. for _, mcl := range server.clients.AllClients() {
  948. for _, clientMask := range mcl.AllNickmasks() {
  949. if matcher.Match(clientMask) {
  950. clientsToKill = append(clientsToKill, mcl)
  951. killedClientNicks = append(killedClientNicks, mcl.nick)
  952. }
  953. }
  954. }
  955. for _, mcl := range clientsToKill {
  956. mcl.exitedSnomaskSent = true
  957. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
  958. if mcl == client {
  959. killClient = true
  960. } else {
  961. // if mcl == client, we kill them below
  962. mcl.destroy(false)
  963. }
  964. }
  965. // send snomask
  966. sort.Strings(killedClientNicks)
  967. 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, ", ")))
  968. }
  969. return killClient
  970. }
  971. // LANGUAGE <code>{ <code>}
  972. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  973. alreadyDoneLanguages := make(map[string]bool)
  974. var appliedLanguages []string
  975. supportedLanguagesCount := server.languages.Count()
  976. if supportedLanguagesCount < len(msg.Params) {
  977. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, client.nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  978. return false
  979. }
  980. for _, value := range msg.Params {
  981. value = strings.ToLower(value)
  982. // strip ~ from the language if it has it
  983. value = strings.TrimPrefix(value, "~")
  984. // silently ignore empty languages or those with spaces in them
  985. if len(value) == 0 || strings.Contains(value, " ") {
  986. continue
  987. }
  988. _, exists := server.languages.Info[value]
  989. if !exists {
  990. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, client.nick, client.t("Languages are not supported by this server"))
  991. return false
  992. }
  993. // if we've already applied the given language, skip it
  994. _, exists = alreadyDoneLanguages[value]
  995. if exists {
  996. continue
  997. }
  998. appliedLanguages = append(appliedLanguages, value)
  999. }
  1000. client.stateMutex.Lock()
  1001. if len(appliedLanguages) == 1 && appliedLanguages[0] == "en" {
  1002. // premature optimisation ahoy!
  1003. client.languages = []string{}
  1004. } else {
  1005. client.languages = appliedLanguages
  1006. }
  1007. client.stateMutex.Unlock()
  1008. params := []string{client.nick}
  1009. for _, lang := range appliedLanguages {
  1010. params = append(params, lang)
  1011. }
  1012. params = append(params, client.t("Language preferences have been set"))
  1013. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1014. return false
  1015. }
  1016. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1017. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1018. // get channels
  1019. var channels []string
  1020. for _, param := range msg.Params {
  1021. if 0 < len(param) && param[0] == '#' {
  1022. for _, channame := range strings.Split(param, ",") {
  1023. if 0 < len(channame) && channame[0] == '#' {
  1024. channels = append(channels, channame)
  1025. }
  1026. }
  1027. }
  1028. }
  1029. // get elist conditions
  1030. var matcher elistMatcher
  1031. for _, param := range msg.Params {
  1032. if len(param) < 1 {
  1033. continue
  1034. }
  1035. if param[0] == '<' {
  1036. param = param[1:]
  1037. val, err := strconv.Atoi(param)
  1038. if err != nil {
  1039. continue
  1040. }
  1041. matcher.MaxClientsActive = true
  1042. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1043. }
  1044. if param[0] == '>' {
  1045. param = param[1:]
  1046. val, err := strconv.Atoi(param)
  1047. if err != nil {
  1048. continue
  1049. }
  1050. matcher.MinClientsActive = true
  1051. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1052. }
  1053. }
  1054. clientIsOp := client.HasMode(modes.Operator)
  1055. if len(channels) == 0 {
  1056. for _, channel := range server.channels.Channels() {
  1057. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1058. continue
  1059. }
  1060. if matcher.Matches(channel) {
  1061. client.RplList(channel, rb)
  1062. }
  1063. }
  1064. } else {
  1065. // limit regular users to only listing one channel
  1066. if !clientIsOp {
  1067. channels = channels[:1]
  1068. }
  1069. for _, chname := range channels {
  1070. casefoldedChname, err := CasefoldChannel(chname)
  1071. channel := server.channels.Get(casefoldedChname)
  1072. if err != nil || channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1073. if len(chname) > 0 {
  1074. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  1075. }
  1076. continue
  1077. }
  1078. if matcher.Matches(channel) {
  1079. client.RplList(channel, rb)
  1080. }
  1081. }
  1082. }
  1083. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1084. return false
  1085. }
  1086. // LUSERS [<mask> [<server>]]
  1087. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1088. //TODO(vegax87) Fix network statistics and additional parameters
  1089. totalCount, invisibleCount, operCount := server.stats.GetStats()
  1090. 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))
  1091. rb.Add(nil, server.name, RPL_LUSEROP, client.nick, strconv.Itoa(operCount), client.t("IRC Operators online"))
  1092. rb.Add(nil, server.name, RPL_LUSERCHANNELS, client.nick, strconv.Itoa(server.channels.Len()), client.t("channels formed"))
  1093. rb.Add(nil, server.name, RPL_LUSERME, client.nick, fmt.Sprintf(client.t("I have %[1]d clients and %[2]d servers"), totalCount, 1))
  1094. return false
  1095. }
  1096. // MODE <target> [<modestring> [<mode arguments>...]]
  1097. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1098. _, errChan := CasefoldChannel(msg.Params[0])
  1099. if errChan == nil {
  1100. return cmodeHandler(server, client, msg, rb)
  1101. }
  1102. return umodeHandler(server, client, msg, rb)
  1103. }
  1104. // MODE <channel> [<modestring> [<mode arguments>...]]
  1105. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1106. channelName, err := CasefoldChannel(msg.Params[0])
  1107. channel := server.channels.Get(channelName)
  1108. if err != nil || channel == nil {
  1109. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
  1110. return false
  1111. }
  1112. // applied mode changes
  1113. applied := make(modes.ModeChanges, 0)
  1114. if 1 < len(msg.Params) {
  1115. // parse out real mode changes
  1116. params := msg.Params[1:]
  1117. changes, unknown := modes.ParseChannelModeChanges(params...)
  1118. // alert for unknown mode changes
  1119. for char := range unknown {
  1120. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1121. }
  1122. if len(unknown) == 1 && len(changes) == 0 {
  1123. return false
  1124. }
  1125. // apply mode changes
  1126. applied = channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1127. }
  1128. // save changes
  1129. var includeFlags uint
  1130. for _, change := range applied {
  1131. includeFlags |= IncludeModes
  1132. if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
  1133. includeFlags |= IncludeLists
  1134. }
  1135. }
  1136. if channel.IsRegistered() && includeFlags != 0 {
  1137. go server.channelRegistry.StoreChannel(channel, includeFlags)
  1138. }
  1139. // send out changes
  1140. if len(applied) > 0 {
  1141. //TODO(dan): we should change the name of String and make it return a slice here
  1142. args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
  1143. for _, member := range channel.Members() {
  1144. if member == client {
  1145. rb.Add(nil, client.nickMaskString, "MODE", args...)
  1146. } else {
  1147. member.Send(nil, client.nickMaskString, "MODE", args...)
  1148. }
  1149. }
  1150. } else {
  1151. args := append([]string{client.nick, channel.name}, channel.modeStrings(client)...)
  1152. rb.Add(nil, client.nickMaskString, RPL_CHANNELMODEIS, args...)
  1153. rb.Add(nil, client.nickMaskString, RPL_CHANNELCREATED, client.nick, channel.name, strconv.FormatInt(channel.createdTime.Unix(), 10))
  1154. }
  1155. return false
  1156. }
  1157. // MODE <client> [<modestring> [<mode arguments>...]]
  1158. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1159. nickname, err := CasefoldName(msg.Params[0])
  1160. target := server.clients.Get(nickname)
  1161. if err != nil || target == nil {
  1162. if len(msg.Params[0]) > 0 {
  1163. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  1164. }
  1165. return false
  1166. }
  1167. targetNick := target.Nick()
  1168. hasPrivs := client == target || msg.Command == "SAMODE"
  1169. if !hasPrivs {
  1170. if len(msg.Params) > 1 {
  1171. rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't change modes for other users"))
  1172. } else {
  1173. rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't view modes for other users"))
  1174. }
  1175. return false
  1176. }
  1177. // applied mode changes
  1178. applied := make(modes.ModeChanges, 0)
  1179. if 1 < len(msg.Params) {
  1180. // parse out real mode changes
  1181. params := msg.Params[1:]
  1182. changes, unknown := modes.ParseUserModeChanges(params...)
  1183. // alert for unknown mode changes
  1184. for char := range unknown {
  1185. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1186. }
  1187. if len(unknown) == 1 && len(changes) == 0 {
  1188. return false
  1189. }
  1190. // apply mode changes
  1191. applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
  1192. }
  1193. if len(applied) > 0 {
  1194. rb.Add(nil, client.nickMaskString, "MODE", targetNick, applied.String())
  1195. } else if hasPrivs {
  1196. rb.Add(nil, target.nickMaskString, RPL_UMODEIS, targetNick, target.ModeString())
  1197. if client.HasMode(modes.LocalOperator) || client.HasMode(modes.Operator) {
  1198. masks := server.snomasks.String(client)
  1199. if 0 < len(masks) {
  1200. rb.Add(nil, target.nickMaskString, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1201. }
  1202. }
  1203. }
  1204. return false
  1205. }
  1206. // MONITOR <subcmd> [params...]
  1207. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1208. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1209. if !exists {
  1210. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1211. return false
  1212. }
  1213. return handler(server, client, msg, rb)
  1214. }
  1215. // MONITOR - <target>{,<target>}
  1216. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1217. if len(msg.Params) < 2 {
  1218. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1219. return false
  1220. }
  1221. targets := strings.Split(msg.Params[1], ",")
  1222. for _, target := range targets {
  1223. cfnick, err := CasefoldName(target)
  1224. if err != nil {
  1225. continue
  1226. }
  1227. server.monitorManager.Remove(client, cfnick)
  1228. }
  1229. return false
  1230. }
  1231. // MONITOR + <target>{,<target>}
  1232. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1233. if len(msg.Params) < 2 {
  1234. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1235. return false
  1236. }
  1237. var online []string
  1238. var offline []string
  1239. limits := server.Limits()
  1240. targets := strings.Split(msg.Params[1], ",")
  1241. for _, target := range targets {
  1242. // check name length
  1243. if len(target) < 1 || len(targets) > limits.NickLen {
  1244. continue
  1245. }
  1246. // add target
  1247. casefoldedTarget, err := CasefoldName(target)
  1248. if err != nil {
  1249. continue
  1250. }
  1251. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1252. if err == errMonitorLimitExceeded {
  1253. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1254. break
  1255. } else if err != nil {
  1256. continue
  1257. }
  1258. // add to online / offline lists
  1259. if targetClient := server.clients.Get(casefoldedTarget); targetClient == nil {
  1260. offline = append(offline, target)
  1261. } else {
  1262. online = append(online, targetClient.Nick())
  1263. }
  1264. }
  1265. if len(online) > 0 {
  1266. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1267. }
  1268. if len(offline) > 0 {
  1269. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1270. }
  1271. return false
  1272. }
  1273. // MONITOR C
  1274. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1275. server.monitorManager.RemoveAll(client)
  1276. return false
  1277. }
  1278. // MONITOR L
  1279. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1280. monitorList := server.monitorManager.List(client)
  1281. var nickList []string
  1282. for _, cfnick := range monitorList {
  1283. replynick := cfnick
  1284. // report the uncasefolded nick if it's available, i.e., the client is online
  1285. if mclient := server.clients.Get(cfnick); mclient != nil {
  1286. replynick = mclient.Nick()
  1287. }
  1288. nickList = append(nickList, replynick)
  1289. }
  1290. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1291. rb.Add(nil, server.name, RPL_MONLIST, client.Nick(), line)
  1292. }
  1293. rb.Add(nil, server.name, RPL_ENDOFMONLIST, "End of MONITOR list")
  1294. return false
  1295. }
  1296. // MONITOR S
  1297. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1298. var online []string
  1299. var offline []string
  1300. monitorList := server.monitorManager.List(client)
  1301. for _, name := range monitorList {
  1302. target := server.clients.Get(name)
  1303. if target == nil {
  1304. offline = append(offline, name)
  1305. } else {
  1306. online = append(online, target.Nick())
  1307. }
  1308. }
  1309. if len(online) > 0 {
  1310. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1311. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1312. }
  1313. }
  1314. if len(offline) > 0 {
  1315. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1316. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1317. }
  1318. }
  1319. return false
  1320. }
  1321. // MOTD
  1322. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1323. server.MOTD(client, rb)
  1324. return false
  1325. }
  1326. // NAMES [<channel>{,<channel>} [target]]
  1327. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1328. var channels []string
  1329. if len(msg.Params) > 0 {
  1330. channels = strings.Split(msg.Params[0], ",")
  1331. }
  1332. // TODO: in a post-federation world, process `target` (server to forward request to)
  1333. if len(channels) == 0 {
  1334. for _, channel := range server.channels.Channels() {
  1335. channel.Names(client, rb)
  1336. }
  1337. return false
  1338. }
  1339. for _, chname := range channels {
  1340. channel := server.channels.Get(chname)
  1341. if channel != nil {
  1342. channel.Names(client, rb)
  1343. } else if chname != "" {
  1344. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1345. }
  1346. }
  1347. return false
  1348. }
  1349. // NICK <nickname>
  1350. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1351. if client.Registered() {
  1352. performNickChange(server, client, client, msg.Params[0], rb)
  1353. } else {
  1354. client.preregNick = msg.Params[0]
  1355. }
  1356. return false
  1357. }
  1358. // NOTICE <target>{,<target>} <message>
  1359. func noticeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1360. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  1361. targets := strings.Split(msg.Params[0], ",")
  1362. message := msg.Params[1]
  1363. // split privmsg
  1364. splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
  1365. for i, targetString := range targets {
  1366. // max of four targets per privmsg
  1367. if i > maxTargets-1 {
  1368. break
  1369. }
  1370. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  1371. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1372. target, cerr := CasefoldChannel(targetString)
  1373. if cerr == nil {
  1374. channel := server.channels.Get(target)
  1375. if channel == nil {
  1376. // errors silently ignored with NOTICE as per RFC
  1377. continue
  1378. }
  1379. if !channel.CanSpeak(client) {
  1380. // errors silently ignored with NOTICE as per RFC
  1381. continue
  1382. }
  1383. msgid := server.generateMessageID()
  1384. channel.SplitNotice(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
  1385. } else {
  1386. target, err := CasefoldName(targetString)
  1387. if err != nil {
  1388. continue
  1389. }
  1390. // NOTICEs sent to services are ignored
  1391. if _, isService := OragonoServices[target]; isService {
  1392. continue
  1393. }
  1394. user := server.clients.Get(target)
  1395. if user == nil {
  1396. // errors silently ignored with NOTICE as per RFC
  1397. continue
  1398. }
  1399. if !user.capabilities.Has(caps.MessageTags) {
  1400. clientOnlyTags = nil
  1401. }
  1402. msgid := server.generateMessageID()
  1403. // restrict messages appropriately when +R is set
  1404. // intentionally make the sending user think the message went through fine
  1405. if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
  1406. user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "NOTICE", user.nick, splitMsg)
  1407. }
  1408. nickMaskString := client.NickMaskString()
  1409. accountName := client.AccountName()
  1410. if client.capabilities.Has(caps.EchoMessage) {
  1411. rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "NOTICE", user.nick, splitMsg)
  1412. }
  1413. user.history.Add(history.Item{
  1414. Type: history.Notice,
  1415. Msgid: msgid,
  1416. Message: splitMsg,
  1417. Nick: nickMaskString,
  1418. AccountName: accountName,
  1419. })
  1420. }
  1421. }
  1422. return false
  1423. }
  1424. // NPC <target> <sourcenick> <message>
  1425. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1426. target := msg.Params[0]
  1427. fakeSource := msg.Params[1]
  1428. message := msg.Params[2]
  1429. _, err := CasefoldName(fakeSource)
  1430. if err != nil {
  1431. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1432. return false
  1433. }
  1434. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1435. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1436. return false
  1437. }
  1438. // NPCA <target> <sourcenick> <message>
  1439. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1440. target := msg.Params[0]
  1441. fakeSource := msg.Params[1]
  1442. message := msg.Params[2]
  1443. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1444. _, err := CasefoldName(fakeSource)
  1445. if err != nil {
  1446. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1447. return false
  1448. }
  1449. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1450. return false
  1451. }
  1452. // OPER <name> <password>
  1453. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1454. if client.HasMode(modes.Operator) == true {
  1455. rb.Add(nil, server.name, ERR_UNKNOWNERROR, "OPER", client.t("You're already opered-up!"))
  1456. return false
  1457. }
  1458. authorized := false
  1459. oper := server.GetOperator(msg.Params[0])
  1460. if oper != nil {
  1461. password := []byte(msg.Params[1])
  1462. authorized = (bcrypt.CompareHashAndPassword(oper.Pass, password) == nil)
  1463. }
  1464. if !authorized {
  1465. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
  1466. return true
  1467. }
  1468. oldNickmask := client.NickMaskString()
  1469. client.SetOper(oper)
  1470. if client.NickMaskString() != oldNickmask {
  1471. client.sendChghost(oldNickmask, oper.Vhost)
  1472. }
  1473. // set new modes: modes.Operator, plus anything specified in the config
  1474. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1475. modeChanges[0] = modes.ModeChange{
  1476. Mode: modes.Operator,
  1477. Op: modes.Add,
  1478. }
  1479. copy(modeChanges[1:], oper.Modes)
  1480. applied := ApplyUserModeChanges(client, modeChanges, true)
  1481. rb.Add(nil, server.name, RPL_YOUREOPER, client.nick, client.t("You are now an IRC operator"))
  1482. rb.Add(nil, server.name, "MODE", client.nick, applied.String())
  1483. 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))
  1484. // client may now be unthrottled by the fakelag system
  1485. client.resetFakelag()
  1486. return false
  1487. }
  1488. // PART <channel>{,<channel>} [<reason>]
  1489. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1490. channels := strings.Split(msg.Params[0], ",")
  1491. 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
  1492. if len(msg.Params) > 1 {
  1493. reason = msg.Params[1]
  1494. }
  1495. for _, chname := range channels {
  1496. err := server.channels.Part(client, chname, reason, rb)
  1497. if err == errNoSuchChannel {
  1498. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
  1499. }
  1500. }
  1501. return false
  1502. }
  1503. // PASS <password>
  1504. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1505. if client.Registered() {
  1506. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1507. return false
  1508. }
  1509. // if no password exists, skip checking
  1510. serverPassword := server.Password()
  1511. if serverPassword == nil {
  1512. client.SetAuthorized(true)
  1513. return false
  1514. }
  1515. // check the provided password
  1516. password := []byte(msg.Params[0])
  1517. if bcrypt.CompareHashAndPassword(serverPassword, password) != nil {
  1518. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
  1519. rb.Add(nil, server.name, "ERROR", client.t("Password incorrect"))
  1520. return true
  1521. }
  1522. client.SetAuthorized(true)
  1523. return false
  1524. }
  1525. // PING [params...]
  1526. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1527. rb.Add(nil, server.name, "PONG", msg.Params...)
  1528. return false
  1529. }
  1530. // PONG [params...]
  1531. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1532. // client gets touched when they send this command, so we don't need to do anything
  1533. return false
  1534. }
  1535. // PRIVMSG <target>{,<target>} <message>
  1536. func privmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1537. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  1538. targets := strings.Split(msg.Params[0], ",")
  1539. message := msg.Params[1]
  1540. // split privmsg
  1541. splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
  1542. for i, targetString := range targets {
  1543. // max of four targets per privmsg
  1544. if i > maxTargets-1 {
  1545. break
  1546. }
  1547. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  1548. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1549. // eh, no need to notify them
  1550. if len(targetString) < 1 {
  1551. continue
  1552. }
  1553. target, err := CasefoldChannel(targetString)
  1554. if err == nil {
  1555. channel := server.channels.Get(target)
  1556. if channel == nil {
  1557. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, targetString, client.t("No such channel"))
  1558. continue
  1559. }
  1560. if !channel.CanSpeak(client) {
  1561. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
  1562. continue
  1563. }
  1564. msgid := server.generateMessageID()
  1565. channel.SplitPrivMsg(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
  1566. } else {
  1567. target, err = CasefoldName(targetString)
  1568. if service, isService := OragonoServices[target]; isService {
  1569. servicePrivmsgHandler(service, server, client, message, rb)
  1570. continue
  1571. }
  1572. user := server.clients.Get(target)
  1573. if err != nil || user == nil {
  1574. if len(target) > 0 {
  1575. client.Send(nil, server.name, ERR_NOSUCHNICK, client.nick, target, "No such nick")
  1576. }
  1577. continue
  1578. }
  1579. if !user.capabilities.Has(caps.MessageTags) {
  1580. clientOnlyTags = nil
  1581. }
  1582. msgid := server.generateMessageID()
  1583. // restrict messages appropriately when +R is set
  1584. // intentionally make the sending user think the message went through fine
  1585. if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
  1586. user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
  1587. }
  1588. nickMaskString := client.NickMaskString()
  1589. accountName := client.AccountName()
  1590. if client.capabilities.Has(caps.EchoMessage) {
  1591. rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
  1592. }
  1593. if user.HasMode(modes.Away) {
  1594. //TODO(dan): possibly implement cooldown of away notifications to users
  1595. rb.Add(nil, server.name, RPL_AWAY, user.nick, user.awayMessage)
  1596. }
  1597. user.history.Add(history.Item{
  1598. Type: history.Privmsg,
  1599. Msgid: msgid,
  1600. Message: splitMsg,
  1601. Nick: nickMaskString,
  1602. AccountName: accountName,
  1603. })
  1604. }
  1605. }
  1606. return false
  1607. }
  1608. // QUIT [<reason>]
  1609. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1610. reason := "Quit"
  1611. if len(msg.Params) > 0 {
  1612. reason += ": " + msg.Params[0]
  1613. }
  1614. client.Quit(reason)
  1615. return true
  1616. }
  1617. // REHASH
  1618. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1619. server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
  1620. err := server.rehash()
  1621. if err == nil {
  1622. rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
  1623. } else {
  1624. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  1625. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
  1626. }
  1627. return false
  1628. }
  1629. // RENAME <oldchan> <newchan> [<reason>]
  1630. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  1631. result = false
  1632. errorResponse := func(err error, name string) {
  1633. // TODO: send correct error codes, e.g., ERR_CANNOTRENAME, ERR_CHANNAMEINUSE
  1634. var code string
  1635. switch err {
  1636. case errNoSuchChannel:
  1637. code = ERR_NOSUCHCHANNEL
  1638. case errRenamePrivsNeeded:
  1639. code = ERR_CHANOPRIVSNEEDED
  1640. case errInvalidChannelName:
  1641. code = ERR_UNKNOWNERROR
  1642. case errChannelNameInUse:
  1643. code = ERR_UNKNOWNERROR
  1644. default:
  1645. code = ERR_UNKNOWNERROR
  1646. }
  1647. rb.Add(nil, server.name, code, client.Nick(), "RENAME", name, err.Error())
  1648. }
  1649. oldName := strings.TrimSpace(msg.Params[0])
  1650. newName := strings.TrimSpace(msg.Params[1])
  1651. if oldName == "" || newName == "" {
  1652. errorResponse(errInvalidChannelName, "<empty>")
  1653. return
  1654. }
  1655. casefoldedOldName, err := CasefoldChannel(oldName)
  1656. if err != nil {
  1657. errorResponse(errInvalidChannelName, oldName)
  1658. return
  1659. }
  1660. reason := "No reason"
  1661. if 2 < len(msg.Params) {
  1662. reason = msg.Params[2]
  1663. }
  1664. channel := server.channels.Get(oldName)
  1665. if channel == nil {
  1666. errorResponse(errNoSuchChannel, oldName)
  1667. return
  1668. }
  1669. //TODO(dan): allow IRCops to do this?
  1670. if !channel.ClientIsAtLeast(client, modes.Operator) {
  1671. errorResponse(errRenamePrivsNeeded, oldName)
  1672. return
  1673. }
  1674. founder := channel.Founder()
  1675. if founder != "" && founder != client.Account() {
  1676. //TODO(dan): Change this to ERR_CANNOTRENAME
  1677. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "RENAME", oldName, client.t("Only channel founders can change registered channels"))
  1678. return false
  1679. }
  1680. // perform the channel rename
  1681. err = server.channels.Rename(oldName, newName)
  1682. if err != nil {
  1683. errorResponse(err, newName)
  1684. return
  1685. }
  1686. // rename succeeded, persist it
  1687. go server.channelRegistry.Rename(channel, casefoldedOldName)
  1688. // send RENAME messages
  1689. for _, mcl := range channel.Members() {
  1690. if mcl.capabilities.Has(caps.Rename) {
  1691. mcl.Send(nil, client.nickMaskString, "RENAME", oldName, newName, reason)
  1692. } else {
  1693. mcl.Send(nil, mcl.nickMaskString, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  1694. if mcl.capabilities.Has(caps.ExtendedJoin) {
  1695. mcl.Send(nil, mcl.nickMaskString, "JOIN", newName, mcl.AccountName(), mcl.realname)
  1696. } else {
  1697. mcl.Send(nil, mcl.nickMaskString, "JOIN", newName)
  1698. }
  1699. }
  1700. }
  1701. return false
  1702. }
  1703. // RESUME <oldnick> <token> [timestamp]
  1704. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1705. oldnick := msg.Params[0]
  1706. token := msg.Params[1]
  1707. if client.Registered() {
  1708. rb.Add(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, connection registration has already been completed"))
  1709. return false
  1710. }
  1711. var timestamp time.Time
  1712. if 2 < len(msg.Params) {
  1713. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[2])
  1714. if err == nil {
  1715. timestamp = ts
  1716. } else {
  1717. rb.Add(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  1718. }
  1719. }
  1720. client.resumeDetails = &ResumeDetails{
  1721. OldNick: oldnick,
  1722. Timestamp: timestamp,
  1723. PresentedToken: token,
  1724. }
  1725. return false
  1726. }
  1727. // SANICK <oldnick> <nickname>
  1728. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1729. targetNick := strings.TrimSpace(msg.Params[0])
  1730. target := server.clients.Get(targetNick)
  1731. if target == nil {
  1732. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  1733. return false
  1734. }
  1735. performNickChange(server, client, target, msg.Params[1], rb)
  1736. return false
  1737. }
  1738. // SCENE <target> <message>
  1739. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1740. target := msg.Params[0]
  1741. message := msg.Params[1]
  1742. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  1743. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1744. return false
  1745. }
  1746. // TAGMSG <target>{,<target>}
  1747. func tagmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1748. clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
  1749. // no client-only tags, so we can drop it
  1750. if clientOnlyTags == nil {
  1751. return false
  1752. }
  1753. targets := strings.Split(msg.Params[0], ",")
  1754. for i, targetString := range targets {
  1755. // max of four targets per privmsg
  1756. if i > maxTargets-1 {
  1757. break
  1758. }
  1759. prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
  1760. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1761. // eh, no need to notify them
  1762. if len(targetString) < 1 {
  1763. continue
  1764. }
  1765. target, err := CasefoldChannel(targetString)
  1766. if err == nil {
  1767. channel := server.channels.Get(target)
  1768. if channel == nil {
  1769. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, targetString, client.t("No such channel"))
  1770. continue
  1771. }
  1772. if !channel.CanSpeak(client) {
  1773. rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
  1774. continue
  1775. }
  1776. msgid := server.generateMessageID()
  1777. channel.TagMsg(msgid, lowestPrefix, clientOnlyTags, client, rb)
  1778. } else {
  1779. target, err = CasefoldName(targetString)
  1780. user := server.clients.Get(target)
  1781. if err != nil || user == nil {
  1782. if len(target) > 0 {
  1783. client.Send(nil, server.name, ERR_NOSUCHNICK, client.nick, target, client.t("No such nick"))
  1784. }
  1785. continue
  1786. }
  1787. msgid := server.generateMessageID()
  1788. // end user can't receive tagmsgs
  1789. if !user.capabilities.Has(caps.MessageTags) {
  1790. continue
  1791. }
  1792. user.SendFromClient(msgid, client, clientOnlyTags, "TAGMSG", user.nick)
  1793. if client.capabilities.Has(caps.EchoMessage) {
  1794. rb.AddFromClient(msgid, client.NickMaskString(), client.AccountName(), clientOnlyTags, "TAGMSG", user.nick)
  1795. }
  1796. if user.HasMode(modes.Away) {
  1797. //TODO(dan): possibly implement cooldown of away notifications to users
  1798. rb.Add(nil, server.name, RPL_AWAY, user.nick, user.awayMessage)
  1799. }
  1800. }
  1801. }
  1802. return false
  1803. }
  1804. // TIME
  1805. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1806. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().Format(time.RFC1123))
  1807. return false
  1808. }
  1809. // TOPIC <channel> [<topic>]
  1810. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1811. name, err := CasefoldChannel(msg.Params[0])
  1812. channel := server.channels.Get(name)
  1813. if err != nil || channel == nil {
  1814. if len(msg.Params[0]) > 0 {
  1815. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
  1816. }
  1817. return false
  1818. }
  1819. if len(msg.Params) > 1 {
  1820. channel.SetTopic(client, msg.Params[1], rb)
  1821. } else {
  1822. channel.SendTopic(client, rb)
  1823. }
  1824. return false
  1825. }
  1826. // UNDLINE <ip>|<net>
  1827. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1828. // check oper permissions
  1829. oper := client.Oper()
  1830. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  1831. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  1832. return false
  1833. }
  1834. // get host
  1835. hostString := msg.Params[0]
  1836. // check host
  1837. hostNet, err := utils.NormalizedNetFromString(hostString)
  1838. if err != nil {
  1839. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  1840. return false
  1841. }
  1842. err = server.dlines.RemoveNetwork(hostNet)
  1843. if err != nil {
  1844. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  1845. return false
  1846. }
  1847. hostString = utils.NetToNormalizedString(hostNet)
  1848. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  1849. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  1850. return false
  1851. }
  1852. // UNKLINE <mask>
  1853. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1854. // check oper permissions
  1855. oper := client.Oper()
  1856. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  1857. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  1858. return false
  1859. }
  1860. // get host
  1861. mask := msg.Params[0]
  1862. if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
  1863. mask = mask + "!*@*"
  1864. } else if !strings.Contains(mask, "@") {
  1865. mask = mask + "@*"
  1866. }
  1867. err := server.klines.RemoveMask(mask)
  1868. if err != nil {
  1869. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  1870. return false
  1871. }
  1872. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  1873. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
  1874. return false
  1875. }
  1876. // USER <username> * 0 <realname>
  1877. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1878. if client.Registered() {
  1879. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1880. return false
  1881. }
  1882. err := client.SetNames(msg.Params[0], msg.Params[3])
  1883. if err == errInvalidUsername {
  1884. rb.Add(nil, "", "ERROR", client.t("Malformed username"))
  1885. return true
  1886. }
  1887. return false
  1888. }
  1889. // USERHOST <nickname>{ <nickname>}
  1890. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1891. returnedNicks := make(map[string]bool)
  1892. for i, nickname := range msg.Params {
  1893. if i >= 10 {
  1894. break
  1895. }
  1896. casefoldedNickname, err := CasefoldName(nickname)
  1897. target := server.clients.Get(casefoldedNickname)
  1898. if err != nil || target == nil {
  1899. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
  1900. return false
  1901. }
  1902. if returnedNicks[casefoldedNickname] {
  1903. continue
  1904. }
  1905. // to prevent returning multiple results for a single nick
  1906. returnedNicks[casefoldedNickname] = true
  1907. var isOper, isAway string
  1908. if target.HasMode(modes.Operator) {
  1909. isOper = "*"
  1910. }
  1911. if target.HasMode(modes.Away) {
  1912. isAway = "-"
  1913. } else {
  1914. isAway = "+"
  1915. }
  1916. 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))
  1917. }
  1918. return false
  1919. }
  1920. // VERSION
  1921. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1922. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  1923. client.RplISupport(rb)
  1924. return false
  1925. }
  1926. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  1927. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1928. // only allow unregistered clients to use this command
  1929. if client.Registered() || client.proxiedIP != nil {
  1930. return false
  1931. }
  1932. // process flags
  1933. var secure bool
  1934. if 4 < len(msg.Params) {
  1935. for _, x := range strings.Split(msg.Params[4], " ") {
  1936. // split into key=value
  1937. var key string
  1938. if strings.Contains(x, "=") {
  1939. y := strings.SplitN(x, "=", 2)
  1940. key, _ = y[0], y[1]
  1941. } else {
  1942. key = x
  1943. }
  1944. lkey := strings.ToLower(key)
  1945. if lkey == "tls" || lkey == "secure" {
  1946. // only accept "tls" flag if the gateway's connection to us is secure as well
  1947. if client.HasMode(modes.TLS) || utils.AddrIsLocal(client.socket.conn.RemoteAddr()) {
  1948. secure = true
  1949. }
  1950. }
  1951. }
  1952. }
  1953. for _, info := range server.WebIRCConfig() {
  1954. for _, gateway := range info.Hosts {
  1955. if isGatewayAllowed(client.socket.conn.RemoteAddr(), gateway) {
  1956. // confirm password and/or fingerprint
  1957. givenPassword := msg.Params[0]
  1958. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, []byte(givenPassword)) != nil {
  1959. continue
  1960. }
  1961. if 0 < len(info.Fingerprint) && client.certfp != info.Fingerprint {
  1962. continue
  1963. }
  1964. proxiedIP := msg.Params[3]
  1965. // see #211; websocket gateways will wrap ipv6 addresses in square brackets
  1966. // because IRC parameters can't start with :
  1967. if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
  1968. proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
  1969. }
  1970. return !client.ApplyProxiedIP(proxiedIP, secure)
  1971. }
  1972. }
  1973. }
  1974. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"))
  1975. return true
  1976. }
  1977. // WHO [<mask> [o]]
  1978. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1979. if msg.Params[0] == "" {
  1980. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  1981. return false
  1982. }
  1983. var mask string
  1984. if len(msg.Params) > 0 {
  1985. casefoldedMask, err := Casefold(msg.Params[0])
  1986. if err != nil {
  1987. rb.Add(nil, server.name, ERR_UNKNOWNERROR, "WHO", client.t("Mask isn't valid"))
  1988. return false
  1989. }
  1990. mask = casefoldedMask
  1991. }
  1992. friends := client.Friends()
  1993. //TODO(dan): is this used and would I put this param in the Modern doc?
  1994. // if not, can we remove it?
  1995. //var operatorOnly bool
  1996. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  1997. // operatorOnly = true
  1998. //}
  1999. if mask[0] == '#' {
  2000. // TODO implement wildcard matching
  2001. //TODO(dan): ^ only for opers
  2002. channel := server.channels.Get(mask)
  2003. if channel != nil {
  2004. whoChannel(client, channel, friends, rb)
  2005. }
  2006. } else {
  2007. for mclient := range server.clients.FindAll(mask) {
  2008. client.rplWhoReply(nil, mclient, rb)
  2009. }
  2010. }
  2011. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2012. return false
  2013. }
  2014. // WHOIS [<target>] <mask>{,<mask>}
  2015. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2016. var masksString string
  2017. //var target string
  2018. if len(msg.Params) > 1 {
  2019. //target = msg.Params[0]
  2020. masksString = msg.Params[1]
  2021. } else {
  2022. masksString = msg.Params[0]
  2023. }
  2024. if len(strings.TrimSpace(masksString)) < 1 {
  2025. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("No masks given"))
  2026. return false
  2027. }
  2028. handleService := func(nick string) bool {
  2029. cfnick, _ := CasefoldName(nick)
  2030. service, ok := OragonoServices[cfnick]
  2031. if !ok {
  2032. return false
  2033. }
  2034. clientNick := client.Nick()
  2035. 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))
  2036. // hehe
  2037. if client.HasMode(modes.TLS) {
  2038. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2039. }
  2040. return true
  2041. }
  2042. if client.HasMode(modes.Operator) {
  2043. for _, mask := range strings.Split(masksString, ",") {
  2044. matches := server.clients.FindAll(mask)
  2045. if len(matches) == 0 && !handleService(mask) {
  2046. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, mask, client.t("No such nick"))
  2047. continue
  2048. }
  2049. for mclient := range matches {
  2050. client.getWhoisOf(mclient, rb)
  2051. }
  2052. }
  2053. } else {
  2054. // only get the first request; also require a nick, not a mask
  2055. nick := strings.Split(masksString, ",")[0]
  2056. mclient := server.clients.Get(nick)
  2057. if mclient != nil {
  2058. client.getWhoisOf(mclient, rb)
  2059. } else if !handleService(nick) {
  2060. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, masksString, client.t("No such nick"))
  2061. }
  2062. // fall through, ENDOFWHOIS is always sent
  2063. }
  2064. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, masksString, client.t("End of /WHOIS list"))
  2065. return false
  2066. }
  2067. // WHOWAS <nickname> [<count> [<server>]]
  2068. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2069. nicknames := strings.Split(msg.Params[0], ",")
  2070. // 0 means "all the entries", as does a negative number
  2071. var count uint64
  2072. if len(msg.Params) > 1 {
  2073. count, _ = strconv.ParseUint(msg.Params[1], 10, 64)
  2074. }
  2075. //var target string
  2076. //if len(msg.Params) > 2 {
  2077. // target = msg.Params[2]
  2078. //}
  2079. cnick := client.Nick()
  2080. for _, nickname := range nicknames {
  2081. results := server.whoWas.Find(nickname, int(count))
  2082. if len(results) == 0 {
  2083. if len(nickname) > 0 {
  2084. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, nickname, client.t("There was no such nickname"))
  2085. }
  2086. } else {
  2087. for _, whoWas := range results {
  2088. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2089. }
  2090. }
  2091. if len(nickname) > 0 {
  2092. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, nickname, client.t("End of WHOWAS"))
  2093. }
  2094. }
  2095. return false
  2096. }