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

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