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 86KB

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