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

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