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

handlers.go 88KB

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