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

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