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

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