Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

handlers.go 87KB

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