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

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