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

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