Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

handlers.go 109KB

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