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

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