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

handlers.go 77KB

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