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

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