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

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