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

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