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

handlers.go 85KB

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