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

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