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

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