You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handlers.go 108KB

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