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

handlers.go 108KB

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