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

handlers.go 131KB

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