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

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