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

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