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

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