Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

handlers.go 109KB

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