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

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