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

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