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

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