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.

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