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

handlers.go 99KB

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