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

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