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

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