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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153
  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 AccountConfig) (callbackNamespace string, callbackValue string) {
  33. callback := strings.ToLower(spec)
  34. if callback == "*" {
  35. callbackNamespace = "*"
  36. } else if strings.Contains(callback, ":") {
  37. callbackValues := strings.SplitN(callback, ":", 2)
  38. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  39. } else {
  40. // "If a callback namespace is not ... provided, the IRC server MUST use mailto""
  41. callbackNamespace = "mailto"
  42. callbackValue = callback
  43. }
  44. // ensure the callback namespace is valid
  45. // need to search callback list, maybe look at using a map later?
  46. for _, name := range config.Registration.EnabledCallbacks {
  47. if callbackNamespace == name {
  48. return
  49. }
  50. }
  51. // error value
  52. callbackNamespace = ""
  53. return
  54. }
  55. func registrationErrorToMessageAndCode(err error) (message, code string) {
  56. // default responses: let's be risk-averse about displaying internal errors
  57. // to the clients, especially for something as sensitive as accounts
  58. code = "REG_UNSPECIFIED_ERROR"
  59. message = `Could not register`
  60. switch err {
  61. case errAccountBadPassphrase:
  62. code = "REG_INVALID_CREDENTIAL"
  63. message = err.Error()
  64. case errAccountAlreadyRegistered, errAccountAlreadyVerified, errAccountAlreadyUnregistered, errAccountAlreadyLoggedIn, errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists, errFeatureDisabled:
  65. message = err.Error()
  66. case errLimitExceeded:
  67. message = `There have been too many registration attempts recently; try again later`
  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.AuthenticateByCertFP(client, rb.session.certfp, 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.account, nil, "AWAY", awayMessage)
  307. } else {
  308. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, 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. // successful responses are sent as a chathistory or history batch
  489. if err == nil {
  490. if channel != nil {
  491. channel.replayHistoryItems(rb, items, false)
  492. } else {
  493. client.replayPrivmsgHistory(rb, items, target, true)
  494. }
  495. return
  496. }
  497. // errors are sent either without a batch, or in a draft/labeled-response batch as usual
  498. if unknown_command {
  499. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "UNKNOWN_COMMAND", utils.SafeErrorParam(msg.Params[0]), client.t("Unknown command"))
  500. } else if err == utils.ErrInvalidParams {
  501. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_PARAMETERS", msg.Params[0], client.t("Invalid parameters"))
  502. } else if err != nil {
  503. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "MESSAGE_ERROR", msg.Params[0], client.t("Messages could not be retrieved"))
  504. } else if sequence == nil {
  505. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "NO_SUCH_CHANNEL", utils.SafeErrorParam(msg.Params[1]), client.t("No such channel"))
  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, "")
  957. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Oragono is released under the MIT license."))
  958. rb.Add(nil, server.name, RPL_INFO, nick, "")
  959. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Core Developers:"))
  960. for _, line := range infoString2 {
  961. rb.Add(nil, server.name, RPL_INFO, nick, line)
  962. }
  963. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Former Core Developers:"))
  964. for _, line := range infoString3 {
  965. rb.Add(nil, server.name, RPL_INFO, nick, line)
  966. }
  967. rb.Add(nil, server.name, RPL_INFO, nick, client.t("For a more complete list of contributors, see our changelog:"))
  968. rb.Add(nil, server.name, RPL_INFO, nick, " https://github.com/oragono/oragono/blob/master/CHANGELOG.md")
  969. rb.Add(nil, server.name, RPL_INFO, nick, "")
  970. // show translators for languages other than good ole' regular English
  971. tlines := server.Languages().Translators()
  972. if 0 < len(tlines) {
  973. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Translators:"))
  974. for _, line := range tlines {
  975. rb.Add(nil, server.name, RPL_INFO, nick, " "+strings.Replace(line, "\n", ", ", -1))
  976. }
  977. rb.Add(nil, server.name, RPL_INFO, nick, "")
  978. }
  979. rb.Add(nil, server.name, RPL_ENDOFINFO, nick, client.t("End of /INFO"))
  980. return false
  981. }
  982. // INVITE <nickname> <channel>
  983. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  984. nickname := msg.Params[0]
  985. channelName := msg.Params[1]
  986. target := server.clients.Get(nickname)
  987. if target == nil {
  988. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  989. return false
  990. }
  991. channel := server.channels.Get(channelName)
  992. if channel == nil {
  993. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(channelName), client.t("No such channel"))
  994. return false
  995. }
  996. channel.Invite(target, client, rb)
  997. return false
  998. }
  999. // ISON <nick>{ <nick>}
  1000. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1001. var nicks = msg.Params
  1002. ison := make([]string, 0, len(msg.Params))
  1003. for _, nick := range nicks {
  1004. currentNick := server.getCurrentNick(nick)
  1005. if currentNick != "" {
  1006. ison = append(ison, currentNick)
  1007. }
  1008. }
  1009. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  1010. return false
  1011. }
  1012. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  1013. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1014. // kill JOIN 0 requests
  1015. if msg.Params[0] == "0" {
  1016. rb.Notice(client.t("JOIN 0 is not allowed"))
  1017. return false
  1018. }
  1019. // handle regular JOINs
  1020. channels := strings.Split(msg.Params[0], ",")
  1021. var keys []string
  1022. if len(msg.Params) > 1 {
  1023. keys = strings.Split(msg.Params[1], ",")
  1024. }
  1025. for i, name := range channels {
  1026. if name == "" {
  1027. continue // #679
  1028. }
  1029. var key string
  1030. if len(keys) > i {
  1031. key = keys[i]
  1032. }
  1033. err := server.channels.Join(client, name, key, false, rb)
  1034. if err != nil {
  1035. sendJoinError(client, name, rb, err)
  1036. }
  1037. }
  1038. return false
  1039. }
  1040. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  1041. var code, errMsg, forbiddingMode string
  1042. switch err {
  1043. case errInsufficientPrivs:
  1044. code, errMsg = ERR_NOSUCHCHANNEL, `Only server operators can create new channels`
  1045. case errConfusableIdentifier:
  1046. code, errMsg = ERR_NOSUCHCHANNEL, `That channel name is too close to the name of another channel`
  1047. case errChannelPurged:
  1048. code, errMsg = ERR_NOSUCHCHANNEL, err.Error()
  1049. case errTooManyChannels:
  1050. code, errMsg = ERR_TOOMANYCHANNELS, `You have joined too many channels`
  1051. case errLimitExceeded:
  1052. code, forbiddingMode = ERR_CHANNELISFULL, "l"
  1053. case errWrongChannelKey:
  1054. code, forbiddingMode = ERR_BADCHANNELKEY, "k"
  1055. case errInviteOnly:
  1056. code, forbiddingMode = ERR_INVITEONLYCHAN, "i"
  1057. case errBanned:
  1058. code, forbiddingMode = ERR_BANNEDFROMCHAN, "b"
  1059. case errRegisteredOnly:
  1060. code, errMsg = ERR_NEEDREGGEDNICK, `You must be registered to join that channel`
  1061. default:
  1062. code, errMsg = ERR_NOSUCHCHANNEL, `No such channel`
  1063. }
  1064. if forbiddingMode != "" {
  1065. errMsg = fmt.Sprintf(client.t("Cannot join channel (+%s)"), forbiddingMode)
  1066. } else {
  1067. errMsg = client.t(errMsg)
  1068. }
  1069. rb.Add(nil, client.server.name, code, client.Nick(), utils.SafeErrorParam(name), errMsg)
  1070. }
  1071. // SAJOIN [nick] #channel{,#channel}
  1072. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1073. var target *Client
  1074. var channelString string
  1075. if strings.HasPrefix(msg.Params[0], "#") {
  1076. target = client
  1077. channelString = msg.Params[0]
  1078. } else {
  1079. if len(msg.Params) == 1 {
  1080. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  1081. return false
  1082. } else {
  1083. target = server.clients.Get(msg.Params[0])
  1084. if target == nil {
  1085. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  1086. return false
  1087. }
  1088. channelString = msg.Params[1]
  1089. }
  1090. }
  1091. channels := strings.Split(channelString, ",")
  1092. for _, chname := range channels {
  1093. err := server.channels.Join(target, chname, "", true, rb)
  1094. if err != nil {
  1095. sendJoinError(client, chname, rb, err)
  1096. }
  1097. }
  1098. return false
  1099. }
  1100. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1101. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1102. channels := strings.Split(msg.Params[0], ",")
  1103. users := strings.Split(msg.Params[1], ",")
  1104. if (len(channels) != len(users)) && (len(users) != 1) {
  1105. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1106. return false
  1107. }
  1108. type kickCmd struct {
  1109. channel string
  1110. nick string
  1111. }
  1112. kicks := make([]kickCmd, 0, len(channels))
  1113. for index, channel := range channels {
  1114. if channel == "" {
  1115. continue // #679
  1116. }
  1117. if len(users) == 1 {
  1118. kicks = append(kicks, kickCmd{channel, users[0]})
  1119. } else {
  1120. kicks = append(kicks, kickCmd{channel, users[index]})
  1121. }
  1122. }
  1123. var comment string
  1124. if len(msg.Params) > 2 {
  1125. comment = msg.Params[2]
  1126. }
  1127. for _, kick := range kicks {
  1128. channel := server.channels.Get(kick.channel)
  1129. if channel == nil {
  1130. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1131. continue
  1132. }
  1133. target := server.clients.Get(kick.nick)
  1134. if target == nil {
  1135. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1136. continue
  1137. }
  1138. if comment == "" {
  1139. comment = kick.nick
  1140. }
  1141. channel.Kick(client, target, comment, rb, false)
  1142. }
  1143. return false
  1144. }
  1145. // KILL <nickname> <comment>
  1146. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1147. nickname := msg.Params[0]
  1148. comment := "<no reason supplied>"
  1149. if len(msg.Params) > 1 {
  1150. comment = msg.Params[1]
  1151. }
  1152. target := server.clients.Get(nickname)
  1153. if target == nil {
  1154. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  1155. return false
  1156. } else if target.AlwaysOn() {
  1157. 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()))
  1158. }
  1159. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1160. 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))
  1161. target.Quit(quitMsg, nil)
  1162. target.destroy(nil)
  1163. return false
  1164. }
  1165. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1166. // KLINE LIST
  1167. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1168. details := client.Details()
  1169. // check oper permissions
  1170. oper := client.Oper()
  1171. if oper == nil || !oper.Class.Capabilities.Has("local_ban") {
  1172. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1173. return false
  1174. }
  1175. currentArg := 0
  1176. // if they say LIST, we just list the current klines
  1177. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1178. bans := server.klines.AllBans()
  1179. if len(bans) == 0 {
  1180. client.Notice("No KLINEs have been set!")
  1181. }
  1182. for key, info := range bans {
  1183. client.Notice(formatBanForListing(client, key, info))
  1184. }
  1185. return false
  1186. }
  1187. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1188. var andKill bool
  1189. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1190. andKill = true
  1191. currentArg++
  1192. }
  1193. // when setting a ban that covers the oper's current connection, we require them to say
  1194. // "KLINE MYSELF" so that we're sure they really mean it.
  1195. var klineMyself bool
  1196. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1197. klineMyself = true
  1198. currentArg++
  1199. }
  1200. // duration
  1201. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1202. if err != nil {
  1203. duration = 0
  1204. } else {
  1205. currentArg++
  1206. }
  1207. // get mask
  1208. if len(msg.Params) < currentArg+1 {
  1209. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1210. return false
  1211. }
  1212. mask := msg.Params[currentArg]
  1213. currentArg++
  1214. // check mask
  1215. mask, err = CanonicalizeMaskWildcard(mask)
  1216. if err != nil {
  1217. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1218. return false
  1219. }
  1220. matcher, err := utils.CompileGlob(mask, false)
  1221. if err != nil {
  1222. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1223. return false
  1224. }
  1225. for _, clientMask := range client.AllNickmasks() {
  1226. if !klineMyself && matcher.MatchString(clientMask) {
  1227. 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>"))
  1228. return false
  1229. }
  1230. }
  1231. // check remote
  1232. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1233. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1234. return false
  1235. }
  1236. // get oper name
  1237. operName := oper.Name
  1238. if operName == "" {
  1239. operName = server.name
  1240. }
  1241. // get comment(s)
  1242. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1243. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1244. if err != nil {
  1245. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1246. return false
  1247. }
  1248. var snoDescription string
  1249. if duration != 0 {
  1250. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1251. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1252. } else {
  1253. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1254. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1255. }
  1256. server.snomasks.Send(sno.LocalXline, snoDescription)
  1257. var killClient bool
  1258. if andKill {
  1259. var clientsToKill []*Client
  1260. var killedClientNicks []string
  1261. for _, mcl := range server.clients.AllClients() {
  1262. for _, clientMask := range mcl.AllNickmasks() {
  1263. if matcher.MatchString(clientMask) {
  1264. clientsToKill = append(clientsToKill, mcl)
  1265. killedClientNicks = append(killedClientNicks, mcl.nick)
  1266. }
  1267. }
  1268. }
  1269. for _, mcl := range clientsToKill {
  1270. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1271. if mcl == client {
  1272. killClient = true
  1273. } else {
  1274. // if mcl == client, we kill them below
  1275. mcl.destroy(nil)
  1276. }
  1277. }
  1278. // send snomask
  1279. sort.Strings(killedClientNicks)
  1280. 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, ", ")))
  1281. }
  1282. return killClient
  1283. }
  1284. // LANGUAGE <code>{ <code>}
  1285. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1286. nick := client.Nick()
  1287. alreadyDoneLanguages := make(map[string]bool)
  1288. var appliedLanguages []string
  1289. lm := server.Languages()
  1290. supportedLanguagesCount := lm.Count()
  1291. if supportedLanguagesCount < len(msg.Params) {
  1292. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1293. return false
  1294. }
  1295. for _, value := range msg.Params {
  1296. value = strings.ToLower(value)
  1297. // strip ~ from the language if it has it
  1298. value = strings.TrimPrefix(value, "~")
  1299. // silently ignore empty languages or those with spaces in them
  1300. if len(value) == 0 || strings.Contains(value, " ") {
  1301. continue
  1302. }
  1303. _, exists := lm.Languages[value]
  1304. if !exists {
  1305. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1306. return false
  1307. }
  1308. // if we've already applied the given language, skip it
  1309. _, exists = alreadyDoneLanguages[value]
  1310. if exists {
  1311. continue
  1312. }
  1313. appliedLanguages = append(appliedLanguages, value)
  1314. }
  1315. var langsToSet []string
  1316. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1317. langsToSet = appliedLanguages
  1318. }
  1319. client.SetLanguages(langsToSet)
  1320. params := make([]string, len(appliedLanguages)+2)
  1321. params[0] = nick
  1322. copy(params[1:], appliedLanguages)
  1323. params[len(params)-1] = client.t("Language preferences have been set")
  1324. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1325. return false
  1326. }
  1327. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1328. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1329. config := server.Config()
  1330. if time.Since(client.ctime) < config.Channels.ListDelay && client.Account() == "" && !client.HasMode(modes.Operator) {
  1331. remaining := time.Until(client.ctime.Add(config.Channels.ListDelay))
  1332. 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))
  1333. rb.Add(nil, server.name, RPL_LISTEND, client.Nick(), client.t("End of LIST"))
  1334. return false
  1335. }
  1336. // get channels
  1337. var channels []string
  1338. for _, param := range msg.Params {
  1339. if 0 < len(param) && param[0] == '#' {
  1340. for _, channame := range strings.Split(param, ",") {
  1341. if 0 < len(channame) && channame[0] == '#' {
  1342. channels = append(channels, channame)
  1343. }
  1344. }
  1345. }
  1346. }
  1347. // get elist conditions
  1348. var matcher elistMatcher
  1349. for _, param := range msg.Params {
  1350. if len(param) < 1 {
  1351. continue
  1352. }
  1353. if param[0] == '<' {
  1354. param = param[1:]
  1355. val, err := strconv.Atoi(param)
  1356. if err != nil {
  1357. continue
  1358. }
  1359. matcher.MaxClientsActive = true
  1360. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1361. }
  1362. if param[0] == '>' {
  1363. param = param[1:]
  1364. val, err := strconv.Atoi(param)
  1365. if err != nil {
  1366. continue
  1367. }
  1368. matcher.MinClientsActive = true
  1369. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1370. }
  1371. }
  1372. nick := client.Nick()
  1373. rplList := func(channel *Channel) {
  1374. if members, name, topic := channel.listData(); members != 0 {
  1375. rb.Add(nil, client.server.name, RPL_LIST, nick, name, strconv.Itoa(members), topic)
  1376. }
  1377. }
  1378. clientIsOp := client.HasMode(modes.Operator)
  1379. if len(channels) == 0 {
  1380. for _, channel := range server.channels.Channels() {
  1381. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1382. continue
  1383. }
  1384. if matcher.Matches(channel) {
  1385. rplList(channel)
  1386. }
  1387. }
  1388. } else {
  1389. // limit regular users to only listing one channel
  1390. if !clientIsOp {
  1391. channels = channels[:1]
  1392. }
  1393. for _, chname := range channels {
  1394. channel := server.channels.Get(chname)
  1395. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1396. if len(chname) > 0 {
  1397. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1398. }
  1399. continue
  1400. }
  1401. if matcher.Matches(channel) {
  1402. rplList(channel)
  1403. }
  1404. }
  1405. }
  1406. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1407. return false
  1408. }
  1409. // LUSERS [<mask> [<server>]]
  1410. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1411. server.Lusers(client, rb)
  1412. return false
  1413. }
  1414. // MODE <target> [<modestring> [<mode arguments>...]]
  1415. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1416. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1417. return cmodeHandler(server, client, msg, rb)
  1418. }
  1419. return umodeHandler(server, client, msg, rb)
  1420. }
  1421. // MODE <channel> [<modestring> [<mode arguments>...]]
  1422. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1423. channel := server.channels.Get(msg.Params[0])
  1424. if channel == nil {
  1425. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1426. return false
  1427. }
  1428. var changes modes.ModeChanges
  1429. if 1 < len(msg.Params) {
  1430. // parse out real mode changes
  1431. params := msg.Params[1:]
  1432. var unknown map[rune]bool
  1433. changes, unknown = modes.ParseChannelModeChanges(params...)
  1434. // alert for unknown mode changes
  1435. for char := range unknown {
  1436. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1437. }
  1438. if len(unknown) == 1 && len(changes) == 0 {
  1439. return false
  1440. }
  1441. }
  1442. // process mode changes, include list operations (an empty set of changes does a list)
  1443. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1444. details := client.Details()
  1445. announceCmodeChanges(channel, applied, details.nickMask, details.accountName, details.account, rb)
  1446. return false
  1447. }
  1448. func announceCmodeChanges(channel *Channel, applied modes.ModeChanges, source, accountName, account string, rb *ResponseBuffer) {
  1449. // send out changes
  1450. if len(applied) > 0 {
  1451. message := utils.MakeMessage("")
  1452. changeStrings := applied.Strings()
  1453. for _, changeString := range changeStrings {
  1454. message.Split = append(message.Split, utils.MessagePair{Message: changeString})
  1455. }
  1456. args := append([]string{channel.name}, changeStrings...)
  1457. rb.AddFromClient(message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1458. for _, member := range channel.Members() {
  1459. for _, session := range member.Sessions() {
  1460. if session != rb.session {
  1461. session.sendFromClientInternal(false, message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1462. }
  1463. }
  1464. }
  1465. channel.AddHistoryItem(history.Item{
  1466. Type: history.Mode,
  1467. Nick: source,
  1468. AccountName: accountName,
  1469. Message: message,
  1470. }, account)
  1471. }
  1472. }
  1473. // MODE <client> [<modestring> [<mode arguments>...]]
  1474. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1475. cDetails := client.Details()
  1476. target := server.clients.Get(msg.Params[0])
  1477. if target == nil {
  1478. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1479. return false
  1480. }
  1481. targetNick := target.Nick()
  1482. hasPrivs := client == target || msg.Command == "SAMODE"
  1483. if !hasPrivs {
  1484. if len(msg.Params) > 1 {
  1485. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1486. } else {
  1487. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1488. }
  1489. return false
  1490. }
  1491. // applied mode changes
  1492. applied := make(modes.ModeChanges, 0)
  1493. if 1 < len(msg.Params) {
  1494. // parse out real mode changes
  1495. params := msg.Params[1:]
  1496. changes, unknown := modes.ParseUserModeChanges(params...)
  1497. // alert for unknown mode changes
  1498. for char := range unknown {
  1499. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1500. }
  1501. if len(unknown) == 1 && len(changes) == 0 {
  1502. return false
  1503. }
  1504. // apply mode changes
  1505. applied = ApplyUserModeChanges(target, changes, msg.Command == "SAMODE", nil)
  1506. }
  1507. if len(applied) > 0 {
  1508. args := append([]string{targetNick}, applied.Strings()...)
  1509. rb.Add(nil, cDetails.nickMask, "MODE", args...)
  1510. } else if hasPrivs {
  1511. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1512. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1513. masks := server.snomasks.String(target)
  1514. if 0 < len(masks) {
  1515. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1516. }
  1517. }
  1518. }
  1519. return false
  1520. }
  1521. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1522. func (server *Server) getCurrentNick(nick string) (result string) {
  1523. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1524. return service.Name
  1525. } else if iclient := server.clients.Get(nick); iclient != nil {
  1526. return iclient.Nick()
  1527. }
  1528. return ""
  1529. }
  1530. // MONITOR <subcmd> [params...]
  1531. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1532. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1533. if !exists {
  1534. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1535. return false
  1536. }
  1537. return handler(server, client, msg, rb)
  1538. }
  1539. // MONITOR - <target>{,<target>}
  1540. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1541. if len(msg.Params) < 2 {
  1542. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1543. return false
  1544. }
  1545. targets := strings.Split(msg.Params[1], ",")
  1546. for _, target := range targets {
  1547. server.monitorManager.Remove(rb.session, target)
  1548. }
  1549. return false
  1550. }
  1551. // MONITOR + <target>{,<target>}
  1552. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1553. if len(msg.Params) < 2 {
  1554. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1555. return false
  1556. }
  1557. var online []string
  1558. var offline []string
  1559. limits := server.Config().Limits
  1560. targets := strings.Split(msg.Params[1], ",")
  1561. for _, target := range targets {
  1562. // check name length
  1563. if len(target) < 1 || len(targets) > limits.NickLen {
  1564. continue
  1565. }
  1566. // add target
  1567. err := server.monitorManager.Add(rb.session, target, limits.MonitorEntries)
  1568. if err == errMonitorLimitExceeded {
  1569. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1570. break
  1571. } else if err != nil {
  1572. continue
  1573. }
  1574. currentNick := server.getCurrentNick(target)
  1575. // add to online / offline lists
  1576. if currentNick != "" {
  1577. online = append(online, currentNick)
  1578. } else {
  1579. offline = append(offline, target)
  1580. }
  1581. }
  1582. if len(online) > 0 {
  1583. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1584. }
  1585. if len(offline) > 0 {
  1586. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1587. }
  1588. return false
  1589. }
  1590. // MONITOR C
  1591. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1592. server.monitorManager.RemoveAll(rb.session)
  1593. return false
  1594. }
  1595. // MONITOR L
  1596. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1597. nick := client.Nick()
  1598. monitorList := server.monitorManager.List(rb.session)
  1599. var nickList []string
  1600. for _, cfnick := range monitorList {
  1601. replynick := cfnick
  1602. currentNick := server.getCurrentNick(cfnick)
  1603. // report the uncasefolded nick if it's available, i.e., the client is online
  1604. if currentNick != "" {
  1605. replynick = currentNick
  1606. }
  1607. nickList = append(nickList, replynick)
  1608. }
  1609. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1610. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1611. }
  1612. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1613. return false
  1614. }
  1615. // MONITOR S
  1616. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1617. var online []string
  1618. var offline []string
  1619. monitorList := server.monitorManager.List(rb.session)
  1620. for _, name := range monitorList {
  1621. currentNick := server.getCurrentNick(name)
  1622. if currentNick != "" {
  1623. online = append(online, currentNick)
  1624. } else {
  1625. offline = append(offline, name)
  1626. }
  1627. }
  1628. if len(online) > 0 {
  1629. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1630. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1631. }
  1632. }
  1633. if len(offline) > 0 {
  1634. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1635. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1636. }
  1637. }
  1638. return false
  1639. }
  1640. // MOTD
  1641. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1642. server.MOTD(client, rb)
  1643. return false
  1644. }
  1645. // NAMES [<channel>{,<channel>} [target]]
  1646. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1647. var channels []string
  1648. if len(msg.Params) > 0 {
  1649. channels = strings.Split(msg.Params[0], ",")
  1650. }
  1651. // TODO: in a post-federation world, process `target` (server to forward request to)
  1652. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1653. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1654. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1655. // with the <channel> parameter set to an asterix character"
  1656. if len(channels) == 0 {
  1657. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1658. return false
  1659. }
  1660. chname := channels[0]
  1661. success := false
  1662. channel := server.channels.Get(chname)
  1663. if channel != nil {
  1664. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1665. channel.Names(client, rb)
  1666. success = true
  1667. }
  1668. }
  1669. if !success { // channel.Names() sends this numeric itself on success
  1670. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1671. }
  1672. return false
  1673. }
  1674. // NICK <nickname>
  1675. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1676. if client.registered {
  1677. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1678. } else {
  1679. client.preregNick = msg.Params[0]
  1680. }
  1681. return false
  1682. }
  1683. // helper to store a batched PRIVMSG in the session object
  1684. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1685. var errorCode, errorMessage string
  1686. defer func() {
  1687. if errorCode != "" {
  1688. if histType != history.Notice {
  1689. rb.Add(nil, server.name, "FAIL", "BATCH", errorCode, errorMessage)
  1690. }
  1691. rb.session.EndMultilineBatch("")
  1692. }
  1693. }()
  1694. if batchTag != rb.session.batch.label {
  1695. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Incorrect batch tag sent")
  1696. return
  1697. } else if len(msg.Params) < 2 {
  1698. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Invalid multiline batch")
  1699. return
  1700. }
  1701. rb.session.batch.command = msg.Command
  1702. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1703. if isConcat && len(msg.Params[1]) == 0 {
  1704. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Cannot send a blank line with the multiline concat tag")
  1705. return
  1706. }
  1707. if !isConcat && len(rb.session.batch.message.Split) != 0 {
  1708. rb.session.batch.lenBytes++ // bill for the newline
  1709. }
  1710. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1711. rb.session.batch.lenBytes += len(msg.Params[1])
  1712. config := server.Config()
  1713. if config.Limits.Multiline.MaxBytes < rb.session.batch.lenBytes {
  1714. errorCode, errorMessage = "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes)
  1715. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1716. errorCode, errorMessage = "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines)
  1717. }
  1718. }
  1719. // NOTICE <target>{,<target>} <message>
  1720. // PRIVMSG <target>{,<target>} <message>
  1721. // TAGMSG <target>{,<target>}
  1722. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1723. histType, err := msgCommandToHistType(msg.Command)
  1724. if err != nil {
  1725. return false
  1726. }
  1727. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1728. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1729. return false
  1730. }
  1731. cnick := client.Nick()
  1732. clientOnlyTags := msg.ClientOnlyTags()
  1733. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1734. // nothing to do
  1735. return false
  1736. }
  1737. targets := strings.Split(msg.Params[0], ",")
  1738. var message string
  1739. if len(msg.Params) > 1 {
  1740. message = msg.Params[1]
  1741. }
  1742. if histType != history.Tagmsg && message == "" {
  1743. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1744. return false
  1745. }
  1746. isCTCP := utils.IsRestrictedCTCPMessage(message)
  1747. if histType == history.Privmsg && !isCTCP {
  1748. client.UpdateActive(rb.session)
  1749. }
  1750. if rb.session.isTor && isCTCP {
  1751. // note that error replies are never sent for NOTICE
  1752. if histType != history.Notice {
  1753. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1754. }
  1755. return false
  1756. }
  1757. for i, targetString := range targets {
  1758. // max of four targets per privmsg
  1759. if i == maxTargets {
  1760. break
  1761. }
  1762. // each target gets distinct msgids
  1763. splitMsg := utils.MakeMessage(message)
  1764. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1765. }
  1766. return false
  1767. }
  1768. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1769. server := client.server
  1770. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1771. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1772. if len(target) == 0 {
  1773. return
  1774. } else if target[0] == '#' {
  1775. channel := server.channels.Get(target)
  1776. if channel == nil {
  1777. if histType != history.Notice {
  1778. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1779. }
  1780. return
  1781. }
  1782. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1783. } else {
  1784. lowercaseTarget := strings.ToLower(target)
  1785. service, isService := OragonoServices[lowercaseTarget]
  1786. _, isZNC := zncHandlers[lowercaseTarget]
  1787. if histType == history.Privmsg {
  1788. if isService {
  1789. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1790. return
  1791. } else if isZNC {
  1792. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1793. return
  1794. }
  1795. }
  1796. // NOTICE and TAGMSG to services are ignored
  1797. if isService || isZNC {
  1798. return
  1799. }
  1800. user := server.clients.Get(target)
  1801. if user == nil {
  1802. if histType != history.Notice {
  1803. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1804. }
  1805. return
  1806. }
  1807. // Restrict CTCP message for target user with +T
  1808. if user.modes.HasMode(modes.UserNoCTCP) && message.IsRestrictedCTCPMessage() {
  1809. return
  1810. }
  1811. tDetails := user.Details()
  1812. tnick := tDetails.nick
  1813. details := client.Details()
  1814. if details.account == "" && server.Defcon() <= 3 {
  1815. rb.Add(nil, server.name, ERR_NEEDREGGEDNICK, client.Nick(), tnick, client.t("Direct messages from unregistered users are temporarily restricted"))
  1816. return
  1817. }
  1818. nickMaskString := details.nickMask
  1819. accountName := details.accountName
  1820. var deliverySessions []*Session
  1821. // restrict messages appropriately when +R is set
  1822. // intentionally make the sending user think the message went through fine
  1823. allowedPlusR := details.account != "" || !user.HasMode(modes.RegisteredOnly)
  1824. if allowedPlusR {
  1825. deliverySessions = append(deliverySessions, user.Sessions()...)
  1826. }
  1827. // all sessions of the sender, except the originating session, get a copy as well:
  1828. if client != user {
  1829. for _, session := range client.Sessions() {
  1830. if session != rb.session {
  1831. deliverySessions = append(deliverySessions, session)
  1832. }
  1833. }
  1834. }
  1835. for _, session := range deliverySessions {
  1836. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1837. // don't send TAGMSG at all if they don't have the tags cap
  1838. if histType == history.Tagmsg && hasTagsCap {
  1839. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1840. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1841. tagsToSend := tags
  1842. if !hasTagsCap {
  1843. tagsToSend = nil
  1844. }
  1845. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1846. }
  1847. }
  1848. // the originating session may get an echo message:
  1849. if rb.session.capabilities.Has(caps.EchoMessage) {
  1850. hasTagsCap := rb.session.capabilities.Has(caps.MessageTags)
  1851. if histType == history.Tagmsg && hasTagsCap {
  1852. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1853. } else {
  1854. tagsToSend := tags
  1855. if !hasTagsCap {
  1856. tagsToSend = nil
  1857. }
  1858. rb.AddSplitMessageFromClient(nickMaskString, accountName, tagsToSend, command, tnick, message)
  1859. }
  1860. }
  1861. if histType != history.Notice {
  1862. //TODO(dan): possibly implement cooldown of away notifications to users
  1863. if away, awayMessage := user.Away(); away {
  1864. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, awayMessage)
  1865. }
  1866. }
  1867. config := server.Config()
  1868. if !config.History.Enabled {
  1869. return
  1870. }
  1871. item := history.Item{
  1872. Type: histType,
  1873. Message: message,
  1874. Nick: nickMaskString,
  1875. AccountName: accountName,
  1876. Tags: tags,
  1877. }
  1878. if !itemIsStorable(&item, config) || !allowedPlusR {
  1879. return
  1880. }
  1881. targetedItem := item
  1882. targetedItem.Params[0] = tnick
  1883. cStatus, _ := client.historyStatus(config)
  1884. tStatus, _ := user.historyStatus(config)
  1885. // add to ephemeral history
  1886. if cStatus == HistoryEphemeral {
  1887. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1888. client.history.Add(targetedItem)
  1889. }
  1890. if tStatus == HistoryEphemeral && client != user {
  1891. item.CfCorrespondent = details.nickCasefolded
  1892. user.history.Add(item)
  1893. }
  1894. if cStatus == HistoryPersistent || tStatus == HistoryPersistent {
  1895. targetedItem.CfCorrespondent = ""
  1896. server.historyDB.AddDirectMessage(details.nickCasefolded, details.account, tDetails.nickCasefolded, tDetails.account, targetedItem)
  1897. }
  1898. }
  1899. }
  1900. func itemIsStorable(item *history.Item, config *Config) bool {
  1901. switch item.Type {
  1902. case history.Tagmsg:
  1903. if config.History.TagmsgStorage.Default {
  1904. for _, blacklistedTag := range config.History.TagmsgStorage.Blacklist {
  1905. if _, ok := item.Tags[blacklistedTag]; ok {
  1906. return false
  1907. }
  1908. }
  1909. return true
  1910. } else {
  1911. for _, whitelistedTag := range config.History.TagmsgStorage.Whitelist {
  1912. if _, ok := item.Tags[whitelistedTag]; ok {
  1913. return true
  1914. }
  1915. }
  1916. return false
  1917. }
  1918. case history.Privmsg, history.Notice:
  1919. // don't store CTCP other than ACTION
  1920. return !item.Message.IsRestrictedCTCPMessage()
  1921. default:
  1922. return true
  1923. }
  1924. }
  1925. // NPC <target> <sourcenick> <message>
  1926. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1927. target := msg.Params[0]
  1928. fakeSource := msg.Params[1]
  1929. message := msg.Params[2:]
  1930. _, err := CasefoldName(fakeSource)
  1931. if err != nil {
  1932. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1933. return false
  1934. }
  1935. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1936. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1937. return false
  1938. }
  1939. // NPCA <target> <sourcenick> <message>
  1940. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1941. target := msg.Params[0]
  1942. fakeSource := msg.Params[1]
  1943. message := msg.Params[2:]
  1944. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1945. _, err := CasefoldName(fakeSource)
  1946. if err != nil {
  1947. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1948. return false
  1949. }
  1950. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1951. return false
  1952. }
  1953. // OPER <name> [password]
  1954. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1955. if client.HasMode(modes.Operator) {
  1956. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1957. return false
  1958. }
  1959. // must pass at least one check, and all enabled checks
  1960. var checkPassed, checkFailed, passwordFailed bool
  1961. oper := server.GetOperator(msg.Params[0])
  1962. if oper != nil {
  1963. if oper.Certfp != "" {
  1964. if oper.Certfp == rb.session.certfp {
  1965. checkPassed = true
  1966. } else {
  1967. checkFailed = true
  1968. }
  1969. }
  1970. if !checkFailed && oper.Pass != nil {
  1971. if len(msg.Params) == 1 {
  1972. checkFailed = true
  1973. } else if bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1974. checkFailed = true
  1975. passwordFailed = true
  1976. } else {
  1977. checkPassed = true
  1978. }
  1979. }
  1980. }
  1981. if !checkPassed || checkFailed {
  1982. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1983. // #951: only disconnect them if we actually tried to check a password for them
  1984. if passwordFailed {
  1985. client.Quit(client.t("Password incorrect"), rb.session)
  1986. return true
  1987. } else {
  1988. return false
  1989. }
  1990. }
  1991. if oper != nil {
  1992. applyOper(client, oper, rb)
  1993. }
  1994. return false
  1995. }
  1996. // adds or removes operator status
  1997. // XXX: to add oper, this calls into ApplyUserModeChanges, but to remove oper,
  1998. // ApplyUserModeChanges calls into this, because the commands are asymmetric
  1999. // (/OPER to add, /MODE self -o to remove)
  2000. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  2001. details := client.Details()
  2002. client.SetOper(oper)
  2003. newDetails := client.Details()
  2004. if details.nickMask != newDetails.nickMask {
  2005. client.sendChghost(details.nickMask, newDetails.hostname)
  2006. }
  2007. if oper != nil {
  2008. // set new modes: modes.Operator, plus anything specified in the config
  2009. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  2010. modeChanges[0] = modes.ModeChange{
  2011. Mode: modes.Operator,
  2012. Op: modes.Add,
  2013. }
  2014. copy(modeChanges[1:], oper.Modes)
  2015. applied := ApplyUserModeChanges(client, modeChanges, true, oper)
  2016. 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))
  2017. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  2018. args := append([]string{details.nick}, applied.Strings()...)
  2019. rb.Broadcast(nil, client.server.name, "MODE", args...)
  2020. } else {
  2021. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client deopered $c[grey][$r%s$c[grey]]"), newDetails.nickMask))
  2022. }
  2023. for _, session := range client.Sessions() {
  2024. // client may now be unthrottled by the fakelag system
  2025. session.resetFakelag()
  2026. }
  2027. }
  2028. // DEOPER
  2029. func deoperHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2030. // pretend they sent /MODE $nick -o
  2031. fakeModeMsg := ircmsg.MakeMessage(nil, "", "MODE", client.Nick(), "-o")
  2032. return umodeHandler(server, client, fakeModeMsg, rb)
  2033. }
  2034. // PART <channel>{,<channel>} [<reason>]
  2035. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2036. channels := strings.Split(msg.Params[0], ",")
  2037. var reason string
  2038. if len(msg.Params) > 1 {
  2039. reason = msg.Params[1]
  2040. }
  2041. for _, chname := range channels {
  2042. if chname == "" {
  2043. continue // #679
  2044. }
  2045. err := server.channels.Part(client, chname, reason, rb)
  2046. if err == errNoSuchChannel {
  2047. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  2048. }
  2049. }
  2050. return false
  2051. }
  2052. // PASS <password>
  2053. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2054. if client.registered {
  2055. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  2056. return false
  2057. }
  2058. // only give them one try to run the PASS command (if a server password is set,
  2059. // then all code paths end with this variable being set):
  2060. if rb.session.passStatus != serverPassUnsent {
  2061. return false
  2062. }
  2063. password := msg.Params[0]
  2064. config := server.Config()
  2065. if config.Accounts.LoginViaPassCommand {
  2066. colonIndex := strings.IndexByte(password, ':')
  2067. if colonIndex != -1 && client.Account() == "" {
  2068. account, accountPass := password[:colonIndex], password[colonIndex+1:]
  2069. if strudelIndex := strings.IndexByte(account, '@'); strudelIndex != -1 {
  2070. account, rb.session.deviceID = account[:strudelIndex], account[strudelIndex+1:]
  2071. }
  2072. err := server.accounts.AuthenticateByPassphrase(client, account, accountPass)
  2073. if err == nil {
  2074. sendSuccessfulAccountAuth(client, rb, false, true)
  2075. // login-via-pass-command entails that we do not need to check
  2076. // an actual server password (either no password or skip-server-password)
  2077. rb.session.passStatus = serverPassSuccessful
  2078. return false
  2079. }
  2080. }
  2081. }
  2082. // if login-via-PASS failed for any reason, proceed to try and interpret the
  2083. // provided password as the server password
  2084. serverPassword := config.Server.passwordBytes
  2085. // if no password exists, skip checking
  2086. if serverPassword == nil {
  2087. return false
  2088. }
  2089. // check the provided password
  2090. if bcrypt.CompareHashAndPassword(serverPassword, []byte(password)) == nil {
  2091. rb.session.passStatus = serverPassSuccessful
  2092. } else {
  2093. rb.session.passStatus = serverPassFailed
  2094. }
  2095. // if they failed the check, we'll bounce them later when they try to complete registration
  2096. // note in particular that with skip-server-password, you can give the wrong server
  2097. // password here, then successfully SASL and be admitted
  2098. return false
  2099. }
  2100. // PING [params...]
  2101. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2102. rb.Add(nil, server.name, "PONG", msg.Params...)
  2103. return false
  2104. }
  2105. // PONG [params...]
  2106. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2107. // client gets touched when they send this command, so we don't need to do anything
  2108. return false
  2109. }
  2110. // QUIT [<reason>]
  2111. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2112. reason := "Quit"
  2113. if len(msg.Params) > 0 {
  2114. reason += ": " + msg.Params[0]
  2115. }
  2116. client.Quit(reason, rb.session)
  2117. return true
  2118. }
  2119. // REHASH
  2120. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2121. nick := client.Nick()
  2122. server.logger.Info("server", "REHASH command used by", nick)
  2123. err := server.rehash()
  2124. if err == nil {
  2125. // we used to send RPL_REHASHING here but i don't think it really makes sense
  2126. // in the labeled-response world, since the intent is "rehash in progress" but
  2127. // it won't display until the rehash is actually complete
  2128. // TODO all operators should get a notice of some kind here
  2129. rb.Notice(client.t("Rehash complete"))
  2130. } else {
  2131. rb.Add(nil, server.name, ERR_UNKNOWNERROR, nick, "REHASH", err.Error())
  2132. }
  2133. return false
  2134. }
  2135. // RENAME <oldchan> <newchan> [<reason>]
  2136. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  2137. result = false
  2138. oldName, newName := msg.Params[0], msg.Params[1]
  2139. var reason string
  2140. if 2 < len(msg.Params) {
  2141. reason = msg.Params[2]
  2142. }
  2143. channel := server.channels.Get(oldName)
  2144. if channel == nil {
  2145. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  2146. return false
  2147. }
  2148. if !(channel.ClientIsAtLeast(client, modes.ChannelOperator) || client.HasRoleCapabs("chanreg")) {
  2149. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  2150. return false
  2151. }
  2152. founder := channel.Founder()
  2153. if founder != "" && founder != client.Account() {
  2154. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  2155. return false
  2156. }
  2157. config := server.Config()
  2158. status, _ := channel.historyStatus(config)
  2159. if status == HistoryPersistent {
  2160. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Channels with persistent history cannot be renamed"))
  2161. return false
  2162. }
  2163. // perform the channel rename
  2164. err := server.channels.Rename(oldName, newName)
  2165. if err == errInvalidChannelName {
  2166. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2167. } else if err == errChannelNameInUse {
  2168. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2169. } else if err != nil {
  2170. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  2171. }
  2172. if err != nil {
  2173. return false
  2174. }
  2175. // send RENAME messages
  2176. clientPrefix := client.NickMaskString()
  2177. for _, mcl := range channel.Members() {
  2178. mDetails := mcl.Details()
  2179. for _, mSession := range mcl.Sessions() {
  2180. targetRb := rb
  2181. targetPrefix := clientPrefix
  2182. if mSession != rb.session {
  2183. targetRb = NewResponseBuffer(mSession)
  2184. targetPrefix = mDetails.nickMask
  2185. }
  2186. if mSession.capabilities.Has(caps.Rename) {
  2187. if reason != "" {
  2188. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  2189. } else {
  2190. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  2191. }
  2192. } else {
  2193. if reason != "" {
  2194. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  2195. } else {
  2196. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  2197. }
  2198. if mSession.capabilities.Has(caps.ExtendedJoin) {
  2199. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  2200. } else {
  2201. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  2202. }
  2203. channel.SendTopic(mcl, targetRb, false)
  2204. channel.Names(mcl, targetRb)
  2205. }
  2206. if mcl != client {
  2207. targetRb.Send(false)
  2208. }
  2209. }
  2210. }
  2211. return false
  2212. }
  2213. // RESUME <token> [timestamp]
  2214. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2215. details := ResumeDetails{
  2216. PresentedToken: msg.Params[0],
  2217. }
  2218. if client.registered {
  2219. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  2220. return false
  2221. }
  2222. if 1 < len(msg.Params) {
  2223. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  2224. if err == nil {
  2225. details.Timestamp = ts
  2226. } else {
  2227. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  2228. }
  2229. }
  2230. rb.session.resumeDetails = &details
  2231. return false
  2232. }
  2233. // SANICK <oldnick> <nickname>
  2234. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2235. targetNick := strings.TrimSpace(msg.Params[0])
  2236. target := server.clients.Get(targetNick)
  2237. if target == nil {
  2238. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2239. return false
  2240. }
  2241. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2242. return false
  2243. }
  2244. // SCENE <target> <message>
  2245. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2246. target := msg.Params[0]
  2247. message := msg.Params[1:]
  2248. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2249. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2250. return false
  2251. }
  2252. // SETNAME <realname>
  2253. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2254. realname := msg.Params[0]
  2255. if realname == "" {
  2256. rb.Add(nil, server.name, "FAIL", "SETNAME", "INVALID_REALNAME", client.t("Realname is not valid"))
  2257. return false
  2258. }
  2259. client.SetRealname(realname)
  2260. details := client.Details()
  2261. // alert friends
  2262. now := time.Now().UTC()
  2263. for session := range client.Friends(caps.SetName) {
  2264. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2265. }
  2266. return false
  2267. }
  2268. // SUMMON [parameters]
  2269. func summonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2270. rb.Add(nil, server.name, ERR_SUMMONDISABLED, client.Nick(), client.t("SUMMON has been disabled"))
  2271. return false
  2272. }
  2273. // TIME
  2274. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2275. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2276. return false
  2277. }
  2278. // TOPIC <channel> [<topic>]
  2279. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2280. channel := server.channels.Get(msg.Params[0])
  2281. if channel == nil {
  2282. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2283. return false
  2284. }
  2285. if len(msg.Params) > 1 {
  2286. channel.SetTopic(client, msg.Params[1], rb)
  2287. } else {
  2288. channel.SendTopic(client, rb, true)
  2289. }
  2290. return false
  2291. }
  2292. // UNDLINE <ip>|<net>
  2293. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2294. // check oper permissions
  2295. oper := client.Oper()
  2296. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2297. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2298. return false
  2299. }
  2300. // get host
  2301. hostString := msg.Params[0]
  2302. // check host
  2303. hostNet, err := utils.NormalizedNetFromString(hostString)
  2304. if err != nil {
  2305. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2306. return false
  2307. }
  2308. err = server.dlines.RemoveNetwork(hostNet)
  2309. if err != nil {
  2310. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2311. return false
  2312. }
  2313. hostString = utils.NetToNormalizedString(hostNet)
  2314. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2315. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2316. return false
  2317. }
  2318. // UNKLINE <mask>
  2319. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2320. details := client.Details()
  2321. // check oper permissions
  2322. oper := client.Oper()
  2323. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2324. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2325. return false
  2326. }
  2327. // get host
  2328. mask := msg.Params[0]
  2329. mask, err := CanonicalizeMaskWildcard(mask)
  2330. if err != nil {
  2331. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2332. return false
  2333. }
  2334. err = server.klines.RemoveMask(mask)
  2335. if err != nil {
  2336. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2337. return false
  2338. }
  2339. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2340. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2341. return false
  2342. }
  2343. // USER <username> * 0 <realname>
  2344. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2345. if client.registered {
  2346. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2347. return false
  2348. }
  2349. username, realname := msg.Params[0], msg.Params[3]
  2350. if len(realname) == 0 {
  2351. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), client.t("Not enough parameters"))
  2352. return false
  2353. }
  2354. // #843: we accept either: `USER user:pass@clientid` or `USER user@clientid`
  2355. if strudelIndex := strings.IndexByte(username, '@'); strudelIndex != -1 {
  2356. username, rb.session.deviceID = username[:strudelIndex], username[strudelIndex+1:]
  2357. if colonIndex := strings.IndexByte(username, ':'); colonIndex != -1 {
  2358. var password string
  2359. username, password = username[:colonIndex], username[colonIndex+1:]
  2360. err := server.accounts.AuthenticateByPassphrase(client, username, password)
  2361. if err == nil {
  2362. sendSuccessfulAccountAuth(client, rb, false, true)
  2363. } else {
  2364. // this is wrong, but send something for debugging that will show up in a raw transcript
  2365. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed"))
  2366. }
  2367. }
  2368. }
  2369. err := client.SetNames(username, realname, false)
  2370. if err == errInvalidUsername {
  2371. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2372. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2373. if client.preregNick == username {
  2374. client.SetNames("user", realname, false)
  2375. } else {
  2376. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2377. }
  2378. }
  2379. return false
  2380. }
  2381. // USERHOST <nickname>{ <nickname>}
  2382. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2383. returnedClients := make(ClientSet)
  2384. var tl utils.TokenLineBuilder
  2385. tl.Initialize(400, " ")
  2386. for i, nickname := range msg.Params {
  2387. if i >= 10 {
  2388. break
  2389. }
  2390. target := server.clients.Get(nickname)
  2391. if target == nil {
  2392. continue
  2393. }
  2394. // to prevent returning multiple results for a single nick
  2395. if returnedClients.Has(target) {
  2396. continue
  2397. }
  2398. returnedClients.Add(target)
  2399. var isOper, isAway string
  2400. if target.HasMode(modes.Operator) {
  2401. isOper = "*"
  2402. }
  2403. if away, _ := target.Away(); away {
  2404. isAway = "-"
  2405. } else {
  2406. isAway = "+"
  2407. }
  2408. details := target.Details()
  2409. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2410. }
  2411. lines := tl.Lines()
  2412. if lines == nil {
  2413. lines = []string{""}
  2414. }
  2415. nick := client.Nick()
  2416. for _, line := range lines {
  2417. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2418. }
  2419. return false
  2420. }
  2421. // USERS [parameters]
  2422. func usersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2423. rb.Add(nil, server.name, ERR_USERSDISABLED, client.Nick(), client.t("USERS has been disabled"))
  2424. return false
  2425. }
  2426. // VERSION
  2427. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2428. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2429. server.RplISupport(client, rb)
  2430. return false
  2431. }
  2432. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2433. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2434. // only allow unregistered clients to use this command
  2435. if client.registered || client.proxiedIP != nil {
  2436. return false
  2437. }
  2438. // process flags
  2439. var secure bool
  2440. if 4 < len(msg.Params) {
  2441. for _, x := range strings.Split(msg.Params[4], " ") {
  2442. // split into key=value
  2443. var key string
  2444. if strings.Contains(x, "=") {
  2445. y := strings.SplitN(x, "=", 2)
  2446. key, _ = y[0], y[1]
  2447. } else {
  2448. key = x
  2449. }
  2450. lkey := strings.ToLower(key)
  2451. if lkey == "tls" || lkey == "secure" {
  2452. // only accept "tls" flag if the gateway's connection to us is secure as well
  2453. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2454. secure = true
  2455. }
  2456. }
  2457. }
  2458. }
  2459. givenPassword := []byte(msg.Params[0])
  2460. for _, info := range server.Config().Server.WebIRC {
  2461. if utils.IPInNets(client.realIP, info.allowedNets) {
  2462. // confirm password and/or fingerprint
  2463. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2464. continue
  2465. }
  2466. if info.Certfp != "" && info.Certfp != rb.session.certfp {
  2467. continue
  2468. }
  2469. err, quitMsg := client.ApplyProxiedIP(rb.session, net.ParseIP(msg.Params[3]), secure)
  2470. if err != nil {
  2471. client.Quit(quitMsg, rb.session)
  2472. return true
  2473. } else {
  2474. return false
  2475. }
  2476. }
  2477. }
  2478. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2479. return true
  2480. }
  2481. type whoxFields uint32 // bitset to hold the WHOX field values, 'a' through 'z'
  2482. func (fields whoxFields) Add(field rune) (result whoxFields) {
  2483. index := int(field) - int('a')
  2484. if 0 <= index && index < 26 {
  2485. return fields | (1 << index)
  2486. } else {
  2487. return fields
  2488. }
  2489. }
  2490. func (fields whoxFields) Has(field rune) bool {
  2491. index := int(field) - int('a')
  2492. if 0 <= index && index < 26 {
  2493. return (fields & (1 << index)) != 0
  2494. } else {
  2495. return false
  2496. }
  2497. }
  2498. // rplWhoReply returns the WHO(X) reply between one user and another channel/user.
  2499. // who format:
  2500. // <channel> <user> <host> <server> <nick> <H|G>[*][~|&|@|%|+][B] :<hopcount> <real name>
  2501. // whox format:
  2502. // <type> <channel> <user> <ip> <host> <server> <nick> <H|G>[*][~|&|@|%|+][B] <hops> <idle> <account> <rank> :<real name>
  2503. func (client *Client) rplWhoReply(channel *Channel, target *Client, rb *ResponseBuffer, isWhox bool, fields whoxFields, whoType string) {
  2504. params := []string{client.Nick()}
  2505. details := target.Details()
  2506. if fields.Has('t') {
  2507. params = append(params, whoType)
  2508. }
  2509. if fields.Has('c') {
  2510. fChannel := "*"
  2511. if channel != nil {
  2512. fChannel = channel.name
  2513. }
  2514. params = append(params, fChannel)
  2515. }
  2516. if fields.Has('u') {
  2517. params = append(params, details.username)
  2518. }
  2519. if fields.Has('i') {
  2520. fIP := "255.255.255.255"
  2521. if client.HasMode(modes.Operator) || client == target {
  2522. // you can only see a target's IP if they're you or you're an oper
  2523. fIP = target.IPString()
  2524. }
  2525. params = append(params, fIP)
  2526. }
  2527. if fields.Has('h') {
  2528. params = append(params, details.hostname)
  2529. }
  2530. if fields.Has('s') {
  2531. params = append(params, target.server.name)
  2532. }
  2533. if fields.Has('n') {
  2534. params = append(params, details.nick)
  2535. }
  2536. if fields.Has('f') { // "flags" (away + oper state + channel status prefix + bot)
  2537. var flags strings.Builder
  2538. if away, _ := target.Away(); away {
  2539. flags.WriteRune('G') // Gone
  2540. } else {
  2541. flags.WriteRune('H') // Here
  2542. }
  2543. if target.HasMode(modes.Operator) {
  2544. flags.WriteRune('*')
  2545. }
  2546. if channel != nil {
  2547. flags.WriteString(channel.ClientPrefixes(target, rb.session.capabilities.Has(caps.MultiPrefix)))
  2548. }
  2549. if target.HasMode(modes.Bot) {
  2550. flags.WriteRune('B')
  2551. }
  2552. params = append(params, flags.String())
  2553. }
  2554. if fields.Has('d') { // server hops from us to target
  2555. params = append(params, "0")
  2556. }
  2557. if fields.Has('l') {
  2558. params = append(params, fmt.Sprintf("%d", target.IdleSeconds()))
  2559. }
  2560. if fields.Has('a') {
  2561. fAccount := "0"
  2562. if details.accountName != "*" {
  2563. // WHOX uses "0" to mean "no account"
  2564. fAccount = details.accountName
  2565. }
  2566. params = append(params, fAccount)
  2567. }
  2568. if fields.Has('o') { // target's channel power level
  2569. //TODO: implement this
  2570. params = append(params, "0")
  2571. }
  2572. if fields.Has('r') {
  2573. params = append(params, details.realname)
  2574. }
  2575. numeric := RPL_WHOSPCRPL
  2576. if !isWhox {
  2577. numeric = RPL_WHOREPLY
  2578. // if this isn't WHOX, stick hops + realname at the end
  2579. params = append(params, "0 "+details.realname)
  2580. }
  2581. rb.Add(nil, client.server.name, numeric, params...)
  2582. }
  2583. // WHO <mask> [<filter>%<fields>,<type>]
  2584. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2585. mask := msg.Params[0]
  2586. var err error
  2587. if mask == "" {
  2588. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2589. return false
  2590. } else if mask[0] == '#' {
  2591. mask, err = CasefoldChannel(msg.Params[0])
  2592. } else {
  2593. mask, err = CanonicalizeMaskWildcard(mask)
  2594. }
  2595. if err != nil {
  2596. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2597. return false
  2598. }
  2599. sFields := "cuhsnf"
  2600. whoType := "0"
  2601. isWhox := false
  2602. if len(msg.Params) > 1 && strings.Contains(msg.Params[1], "%") {
  2603. isWhox = true
  2604. whoxData := msg.Params[1]
  2605. fieldStart := strings.Index(whoxData, "%")
  2606. sFields = whoxData[fieldStart+1:]
  2607. typeIndex := strings.Index(sFields, ",")
  2608. if typeIndex > -1 && typeIndex < (len(sFields)-1) { // make sure there's , and a value after it
  2609. whoType = sFields[typeIndex+1:]
  2610. sFields = strings.ToLower(sFields[:typeIndex])
  2611. }
  2612. }
  2613. var fields whoxFields
  2614. for _, field := range sFields {
  2615. fields = fields.Add(field)
  2616. }
  2617. //TODO(dan): is this used and would I put this param in the Modern doc?
  2618. // if not, can we remove it?
  2619. //var operatorOnly bool
  2620. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2621. // operatorOnly = true
  2622. //}
  2623. isOper := client.HasMode(modes.Operator)
  2624. if mask[0] == '#' {
  2625. // TODO implement wildcard matching
  2626. //TODO(dan): ^ only for opers
  2627. channel := server.channels.Get(mask)
  2628. if channel != nil {
  2629. isJoined := channel.hasClient(client)
  2630. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2631. for _, member := range channel.Members() {
  2632. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2633. client.rplWhoReply(channel, member, rb, isWhox, fields, whoType)
  2634. }
  2635. }
  2636. }
  2637. }
  2638. } else {
  2639. // Construct set of channels the client is in.
  2640. userChannels := make(map[*Channel]bool)
  2641. for _, channel := range client.Channels() {
  2642. userChannels[channel] = true
  2643. }
  2644. // Another client is a friend if they share at least one channel, or they are the same client.
  2645. isFriend := func(otherClient *Client) bool {
  2646. if client == otherClient {
  2647. return true
  2648. }
  2649. for _, channel := range otherClient.Channels() {
  2650. if userChannels[channel] {
  2651. return true
  2652. }
  2653. }
  2654. return false
  2655. }
  2656. for mclient := range server.clients.FindAll(mask) {
  2657. if isOper || !mclient.HasMode(modes.Invisible) || isFriend(mclient) {
  2658. client.rplWhoReply(nil, mclient, rb, isWhox, fields, whoType)
  2659. }
  2660. }
  2661. }
  2662. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2663. return false
  2664. }
  2665. // WHOIS [<target>] <mask>{,<mask>}
  2666. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2667. var masksString string
  2668. //var target string
  2669. if len(msg.Params) > 1 {
  2670. //target = msg.Params[0]
  2671. masksString = msg.Params[1]
  2672. } else {
  2673. masksString = msg.Params[0]
  2674. }
  2675. handleService := func(nick string) bool {
  2676. cfnick, _ := CasefoldName(nick)
  2677. service, ok := OragonoServices[cfnick]
  2678. if !ok {
  2679. return false
  2680. }
  2681. clientNick := client.Nick()
  2682. 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))
  2683. // #1080:
  2684. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, clientNick, service.Name, client.t("is a network service"))
  2685. // hehe
  2686. if client.HasMode(modes.TLS) {
  2687. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2688. }
  2689. return true
  2690. }
  2691. if client.HasMode(modes.Operator) {
  2692. for _, mask := range strings.Split(masksString, ",") {
  2693. matches := server.clients.FindAll(mask)
  2694. if len(matches) == 0 && !handleService(mask) {
  2695. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2696. continue
  2697. }
  2698. for mclient := range matches {
  2699. client.getWhoisOf(mclient, rb)
  2700. }
  2701. }
  2702. } else {
  2703. // only get the first request; also require a nick, not a mask
  2704. nick := strings.Split(masksString, ",")[0]
  2705. mclient := server.clients.Get(nick)
  2706. if mclient != nil {
  2707. client.getWhoisOf(mclient, rb)
  2708. } else if !handleService(nick) {
  2709. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2710. }
  2711. // fall through, ENDOFWHOIS is always sent
  2712. }
  2713. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2714. return false
  2715. }
  2716. // WHOWAS <nickname> [<count> [<server>]]
  2717. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2718. nicknames := strings.Split(msg.Params[0], ",")
  2719. // 0 means "all the entries", as does a negative number
  2720. var count int
  2721. if len(msg.Params) > 1 {
  2722. count, _ = strconv.Atoi(msg.Params[1])
  2723. if count < 0 {
  2724. count = 0
  2725. }
  2726. }
  2727. //var target string
  2728. //if len(msg.Params) > 2 {
  2729. // target = msg.Params[2]
  2730. //}
  2731. cnick := client.Nick()
  2732. for _, nickname := range nicknames {
  2733. if len(nickname) == 0 {
  2734. continue
  2735. }
  2736. results := server.whoWas.Find(nickname, count)
  2737. if len(results) == 0 {
  2738. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2739. } else {
  2740. for _, whoWas := range results {
  2741. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2742. }
  2743. }
  2744. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2745. }
  2746. return false
  2747. }
  2748. // ZNC <module> [params]
  2749. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2750. params := msg.Params[1:]
  2751. // #1205: compatibility with Palaver, which sends `ZNC *playback :play ...`
  2752. if len(params) == 1 && strings.IndexByte(params[0], ' ') != -1 {
  2753. params = strings.Fields(params[0])
  2754. }
  2755. zncModuleHandler(client, msg.Params[0], params, rb)
  2756. return false
  2757. }
  2758. // fake handler for unknown commands
  2759. func unknownCommandHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2760. rb.Add(nil, server.name, ERR_UNKNOWNCOMMAND, client.Nick(), utils.SafeErrorParam(msg.Command), client.t("Unknown command"))
  2761. return false
  2762. }
  2763. // fake handler for invalid utf8
  2764. func invalidUtf8Handler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2765. rb.Add(nil, server.name, "FAIL", utils.SafeErrorParam(msg.Command), "INVALID_UTF8", client.t("Message rejected for containing invalid UTF-8"))
  2766. return false
  2767. }