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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2018 Daniel Oaks <daniel@danieloaks.net>
  4. // Copyright (c) 2017-2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  5. // released under the MIT license
  6. package irc
  7. import (
  8. "bytes"
  9. "encoding/base64"
  10. "fmt"
  11. "net"
  12. "os"
  13. "runtime"
  14. "runtime/debug"
  15. "runtime/pprof"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/goshuirc/irc-go/ircfmt"
  21. "github.com/goshuirc/irc-go/ircmsg"
  22. "github.com/oragono/oragono/irc/caps"
  23. "github.com/oragono/oragono/irc/custime"
  24. "github.com/oragono/oragono/irc/history"
  25. "github.com/oragono/oragono/irc/jwt"
  26. "github.com/oragono/oragono/irc/modes"
  27. "github.com/oragono/oragono/irc/sno"
  28. "github.com/oragono/oragono/irc/utils"
  29. "golang.org/x/crypto/bcrypt"
  30. )
  31. // helper function to parse ACC callbacks, e.g., mailto:person@example.com, tel:16505551234
  32. func parseCallback(spec string, config AccountConfig) (callbackNamespace string, callbackValue string) {
  33. callback := strings.ToLower(spec)
  34. if callback == "*" {
  35. callbackNamespace = "*"
  36. } else if strings.Contains(callback, ":") {
  37. callbackValues := strings.SplitN(callback, ":", 2)
  38. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  39. } else {
  40. // "If a callback namespace is not ... provided, the IRC server MUST use mailto""
  41. callbackNamespace = "mailto"
  42. callbackValue = callback
  43. }
  44. // ensure the callback namespace is valid
  45. // need to search callback list, maybe look at using a map later?
  46. for _, name := range config.Registration.EnabledCallbacks {
  47. if callbackNamespace == name {
  48. return
  49. }
  50. }
  51. // error value
  52. callbackNamespace = ""
  53. return
  54. }
  55. func registrationErrorToMessageAndCode(err error) (message, code string) {
  56. // default responses: let's be risk-averse about displaying internal errors
  57. // to the clients, especially for something as sensitive as accounts
  58. code = "REG_UNSPECIFIED_ERROR"
  59. message = `Could not register`
  60. switch err {
  61. case errAccountBadPassphrase:
  62. code = "REG_INVALID_CREDENTIAL"
  63. message = err.Error()
  64. case errAccountAlreadyRegistered, errAccountAlreadyVerified, errAccountAlreadyUnregistered, errAccountAlreadyLoggedIn, errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists, errFeatureDisabled:
  65. message = err.Error()
  66. case errLimitExceeded:
  67. message = `There have been too many registration attempts recently; try again later`
  68. }
  69. return
  70. }
  71. // helper function to dispatch messages when a client successfully registers
  72. func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
  73. details := client.Details()
  74. if forNS {
  75. nsNotice(rb, client.t("Account created"))
  76. } else {
  77. rb.Add(nil, client.server.name, RPL_REG_SUCCESS, details.nick, details.accountName, client.t("Account created"))
  78. }
  79. 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]]"), details.nickMask, details.accountName))
  80. sendSuccessfulAccountAuth(client, rb, forNS, false)
  81. }
  82. // sendSuccessfulAccountAuth means that an account auth attempt completed successfully, and is used to dispatch messages.
  83. func sendSuccessfulAccountAuth(client *Client, rb *ResponseBuffer, forNS, forSASL bool) {
  84. details := client.Details()
  85. if forNS {
  86. nsNotice(rb, fmt.Sprintf(client.t("You're now logged in as %s"), details.accountName))
  87. } else {
  88. //TODO(dan): some servers send this numeric even for NickServ logins iirc? to confirm and maybe do too
  89. 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))
  90. if forSASL {
  91. rb.Add(nil, client.server.name, RPL_SASLSUCCESS, details.nick, client.t("Authentication successful"))
  92. }
  93. }
  94. // dispatch account-notify
  95. for friend := range client.Friends(caps.AccountNotify) {
  96. if friend != rb.session {
  97. friend.Send(nil, details.nickMask, "ACCOUNT", details.accountName)
  98. }
  99. }
  100. if rb.session.capabilities.Has(caps.AccountNotify) {
  101. rb.Add(nil, details.nickMask, "ACCOUNT", details.accountName)
  102. }
  103. client.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]]"), details.nickMask, details.accountName))
  104. client.server.logger.Info("accounts", "client", details.nick, "logged into account", details.accountName)
  105. }
  106. // AUTHENTICATE [<mechanism>|<data>|*]
  107. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  108. session := rb.session
  109. config := server.Config()
  110. details := client.Details()
  111. if client.isSTSOnly {
  112. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  113. return false
  114. }
  115. if details.account != "" {
  116. rb.Add(nil, server.name, ERR_SASLALREADY, details.nick, client.t("You're already logged into an account"))
  117. return false
  118. }
  119. // sasl abort
  120. if !config.Accounts.AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
  121. rb.Add(nil, server.name, ERR_SASLABORTED, details.nick, client.t("SASL authentication aborted"))
  122. session.sasl.Clear()
  123. return false
  124. }
  125. // start new sasl session
  126. if session.sasl.mechanism == "" {
  127. mechanism := strings.ToUpper(msg.Params[0])
  128. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  129. if mechanismIsEnabled {
  130. session.sasl.mechanism = mechanism
  131. if !config.Server.Compatibility.SendUnprefixedSasl {
  132. // normal behavior
  133. rb.Add(nil, server.name, "AUTHENTICATE", "+")
  134. } else {
  135. // gross hack: send a raw message to ensure no tags or prefix
  136. rb.Flush(true)
  137. rb.session.SendRawMessage(ircmsg.MakeMessage(nil, "", "AUTHENTICATE", "+"), true)
  138. }
  139. } else {
  140. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  141. }
  142. return false
  143. }
  144. // continue existing sasl session
  145. rawData := msg.Params[0]
  146. if len(rawData) > 400 {
  147. rb.Add(nil, server.name, ERR_SASLTOOLONG, details.nick, client.t("SASL message too long"))
  148. session.sasl.Clear()
  149. return false
  150. } else if len(rawData) == 400 {
  151. // allow 4 'continuation' lines before rejecting for length
  152. if len(session.sasl.value) >= 400*4 {
  153. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Passphrase too long"))
  154. session.sasl.Clear()
  155. return false
  156. }
  157. session.sasl.value += rawData
  158. return false
  159. }
  160. if rawData != "+" {
  161. session.sasl.value += rawData
  162. }
  163. var data []byte
  164. var err error
  165. if session.sasl.value != "+" {
  166. data, err = base64.StdEncoding.DecodeString(session.sasl.value)
  167. if err != nil {
  168. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
  169. session.sasl.Clear()
  170. return false
  171. }
  172. }
  173. // call actual handler
  174. handler, handlerExists := EnabledSaslMechanisms[session.sasl.mechanism]
  175. // like 100% not required, but it's good to be safe I guess
  176. if !handlerExists {
  177. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  178. session.sasl.Clear()
  179. return false
  180. }
  181. // let the SASL handler do its thing
  182. exiting := handler(server, client, session.sasl.mechanism, data, rb)
  183. session.sasl.Clear()
  184. return exiting
  185. }
  186. // AUTHENTICATE PLAIN
  187. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  188. splitValue := bytes.Split(value, []byte{'\000'})
  189. // PLAIN has separate "authorization ID" (which user you want to become)
  190. // and "authentication ID" (whose password you want to use). the first is optional:
  191. // [authzid] \x00 authcid \x00 password
  192. var authzid, authcid string
  193. if len(splitValue) == 3 {
  194. authzid, authcid = string(splitValue[0]), string(splitValue[1])
  195. if authzid != "" && authcid != authzid {
  196. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: authcid and authzid should be the same"))
  197. return false
  198. }
  199. } else {
  200. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: Invalid auth blob"))
  201. return false
  202. }
  203. throttled, remainingTime := client.loginThrottle.Touch()
  204. if throttled {
  205. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  206. return false
  207. }
  208. // see #843: strip the device ID for the benefit of clients that don't
  209. // distinguish user/ident from account name
  210. if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 {
  211. var deviceID string
  212. authcid, deviceID = authcid[:strudelIndex], authcid[strudelIndex+1:]
  213. if !client.registered {
  214. rb.session.deviceID = deviceID
  215. }
  216. }
  217. password := string(splitValue[2])
  218. err := server.accounts.AuthenticateByPassphrase(client, authcid, password)
  219. if err != nil {
  220. msg := authErrorToMessage(server, err)
  221. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  222. return false
  223. } else if !fixupNickEqualsAccount(client, rb, server.Config()) {
  224. return false
  225. }
  226. sendSuccessfulAccountAuth(client, rb, false, true)
  227. return false
  228. }
  229. func authErrorToMessage(server *Server, err error) (msg string) {
  230. if throttled, ok := err.(*ThrottleError); ok {
  231. return throttled.Error()
  232. }
  233. switch err {
  234. case errAccountDoesNotExist, errAccountUnverified, errAccountInvalidCredentials, errAuthzidAuthcidMismatch, errNickAccountMismatch:
  235. return err.Error()
  236. default:
  237. // don't expose arbitrary error messages to the user
  238. server.logger.Error("internal", "sasl authentication failure", err.Error())
  239. return "Unknown"
  240. }
  241. }
  242. // AUTHENTICATE EXTERNAL
  243. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  244. if rb.session.certfp == "" {
  245. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
  246. return false
  247. }
  248. // EXTERNAL doesn't carry an authentication ID (this is determined from the
  249. // certificate), but does carry an optional authorization ID.
  250. var authzid string
  251. var err error
  252. if len(value) != 0 {
  253. authzid, err = CasefoldName(string(value))
  254. if err != nil {
  255. err = errAuthzidAuthcidMismatch
  256. }
  257. }
  258. if err == nil {
  259. // see #843: strip the device ID for the benefit of clients that don't
  260. // distinguish user/ident from account name
  261. if strudelIndex := strings.IndexByte(authzid, '@'); strudelIndex != -1 {
  262. var deviceID string
  263. authzid, deviceID = authzid[:strudelIndex], authzid[strudelIndex+1:]
  264. if !client.registered {
  265. rb.session.deviceID = deviceID
  266. }
  267. }
  268. err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid)
  269. }
  270. if err != nil {
  271. msg := authErrorToMessage(server, err)
  272. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  273. return false
  274. } else if !fixupNickEqualsAccount(client, rb, server.Config()) {
  275. return false
  276. }
  277. sendSuccessfulAccountAuth(client, rb, false, true)
  278. return false
  279. }
  280. // AWAY [<message>]
  281. func awayHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  282. var isAway bool
  283. var awayMessage string
  284. if len(msg.Params) > 0 {
  285. isAway = true
  286. awayMessage = msg.Params[0]
  287. awayLen := server.Config().Limits.AwayLen
  288. if len(awayMessage) > awayLen {
  289. awayMessage = awayMessage[:awayLen]
  290. }
  291. }
  292. client.SetAway(isAway, awayMessage)
  293. if isAway {
  294. rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
  295. } else {
  296. rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
  297. }
  298. dispatchAwayNotify(client, isAway, awayMessage)
  299. return false
  300. }
  301. func dispatchAwayNotify(client *Client, isAway bool, awayMessage string) {
  302. // dispatch away-notify
  303. details := client.Details()
  304. for session := range client.Friends(caps.AwayNotify) {
  305. if isAway {
  306. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY", awayMessage)
  307. } else {
  308. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY")
  309. }
  310. }
  311. }
  312. // BATCH {+,-}reference-tag type [params...]
  313. func batchHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  314. tag := msg.Params[0]
  315. fail := false
  316. sendErrors := rb.session.batch.command != "NOTICE"
  317. if len(tag) == 0 {
  318. fail = true
  319. } else if tag[0] == '+' {
  320. if len(msg.Params) < 3 || msg.Params[1] != caps.MultilineBatchType {
  321. fail = true
  322. } else {
  323. err := rb.session.StartMultilineBatch(tag[1:], msg.Params[2], rb.Label, msg.ClientOnlyTags())
  324. fail = (err != nil)
  325. if !fail {
  326. // suppress ACK for the initial BATCH message (we'll apply the stored label later)
  327. rb.Label = ""
  328. }
  329. }
  330. } else if tag[0] == '-' {
  331. batch, err := rb.session.EndMultilineBatch(tag[1:])
  332. fail = (err != nil)
  333. if !fail {
  334. histType, err := msgCommandToHistType(batch.command)
  335. if err != nil {
  336. histType = history.Privmsg
  337. batch.command = "PRIVMSG"
  338. }
  339. // XXX changing the label inside a handler is a bit dodgy, but it works here
  340. // because there's no way we could have triggered a flush up to this point
  341. rb.Label = batch.responseLabel
  342. dispatchMessageToTarget(client, batch.tags, histType, batch.command, batch.target, batch.message, rb)
  343. }
  344. }
  345. if fail {
  346. rb.session.EndMultilineBatch("")
  347. if sendErrors {
  348. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_INVALID", client.t("Invalid multiline batch"))
  349. }
  350. }
  351. return false
  352. }
  353. // BRB [message]
  354. func brbHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  355. success, duration := client.brbTimer.Enable()
  356. if !success {
  357. rb.Add(nil, server.name, "FAIL", "BRB", "CANNOT_BRB", client.t("Your client does not support BRB"))
  358. return false
  359. } else {
  360. rb.Add(nil, server.name, "BRB", strconv.Itoa(int(duration.Seconds())))
  361. }
  362. var message string
  363. if 0 < len(msg.Params) {
  364. message = msg.Params[0]
  365. } else {
  366. message = client.t("I'll be right back")
  367. }
  368. if len(client.Sessions()) == 1 {
  369. // true BRB
  370. client.SetAway(true, message)
  371. }
  372. return true
  373. }
  374. // CAP <subcmd> [<caps>]
  375. func capHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  376. details := client.Details()
  377. subCommand := strings.ToUpper(msg.Params[0])
  378. toAdd := caps.NewSet()
  379. toRemove := caps.NewSet()
  380. var capString string
  381. config := server.Config()
  382. supportedCaps := config.Server.supportedCaps
  383. if client.isSTSOnly {
  384. supportedCaps = stsOnlyCaps
  385. }
  386. badCaps := false
  387. if len(msg.Params) > 1 {
  388. capString = msg.Params[1]
  389. strs := strings.Fields(capString)
  390. for _, str := range strs {
  391. remove := false
  392. if str[0] == '-' {
  393. str = str[1:]
  394. remove = true
  395. }
  396. capab, err := caps.NameToCapability(str)
  397. if err != nil || (!remove && !supportedCaps.Has(capab)) {
  398. badCaps = true
  399. } else if !remove {
  400. toAdd.Enable(capab)
  401. } else {
  402. toRemove.Enable(capab)
  403. }
  404. }
  405. }
  406. sendCapLines := func(cset *caps.Set, values caps.Values) {
  407. version := rb.session.capVersion
  408. // we're working around two bugs:
  409. // 1. weechat 1.4 won't accept the CAP reply unless it contains the server.name source
  410. // 2. old versions of Kiwi and The Lounge can't parse multiline CAP LS 302 (#661),
  411. // so try as hard as possible to get the response to fit on one line.
  412. // :server.name CAP * LS * :<tokens>
  413. // 1 7 4
  414. maxLen := 510 - 1 - len(server.name) - 7 - len(subCommand) - 4
  415. capLines := cset.Strings(version, values, maxLen)
  416. for i, capStr := range capLines {
  417. if version >= caps.Cap302 && i < len(capLines)-1 {
  418. rb.Add(nil, server.name, "CAP", details.nick, subCommand, "*", capStr)
  419. } else {
  420. rb.Add(nil, server.name, "CAP", details.nick, subCommand, capStr)
  421. }
  422. }
  423. }
  424. switch subCommand {
  425. case "LS":
  426. if !client.registered {
  427. rb.session.capState = caps.NegotiatingState
  428. }
  429. if 1 < len(msg.Params) {
  430. num, err := strconv.Atoi(msg.Params[1])
  431. newVersion := caps.Version(num)
  432. if err == nil && rb.session.capVersion < newVersion {
  433. rb.session.capVersion = newVersion
  434. }
  435. }
  436. sendCapLines(supportedCaps, config.Server.capValues)
  437. case "LIST":
  438. // values not sent on LIST
  439. sendCapLines(&rb.session.capabilities, nil)
  440. case "REQ":
  441. if !client.registered {
  442. rb.session.capState = caps.NegotiatingState
  443. }
  444. // make sure all capabilities actually exist
  445. // #511, #521: oragono.io/nope is a fake cap to trap bad clients who blindly request
  446. // every offered capability. during registration, requesting it produces a quit,
  447. // otherwise just a CAP NAK
  448. if badCaps || (toAdd.Has(caps.Nope) && client.registered) {
  449. rb.Add(nil, server.name, "CAP", details.nick, "NAK", capString)
  450. return false
  451. } else if toAdd.Has(caps.Nope) && !client.registered {
  452. client.Quit(fmt.Sprintf(client.t("Requesting the %s client capability is forbidden"), caps.Nope.Name()), rb.session)
  453. return true
  454. }
  455. rb.session.capabilities.Union(toAdd)
  456. rb.session.capabilities.Subtract(toRemove)
  457. rb.Add(nil, server.name, "CAP", details.nick, "ACK", capString)
  458. // if this is the first time the client is requesting a resume token,
  459. // send it to them
  460. if toAdd.Has(caps.Resume) {
  461. token, id := server.resumeManager.GenerateToken(client)
  462. if token != "" {
  463. rb.Add(nil, server.name, "RESUME", "TOKEN", token)
  464. rb.session.SetResumeID(id)
  465. }
  466. }
  467. case "END":
  468. if !client.registered {
  469. rb.session.capState = caps.NegotiatedState
  470. }
  471. default:
  472. rb.Add(nil, server.name, ERR_INVALIDCAPCMD, details.nick, subCommand, client.t("Invalid CAP subcommand"))
  473. }
  474. return false
  475. }
  476. // CHATHISTORY <target> <preposition> <query> [<limit>]
  477. // e.g., CHATHISTORY #ircv3 AFTER id=ytNBbt565yt4r3err3 10
  478. // CHATHISTORY <target> BETWEEN <query> <query> <direction> [<limit>]
  479. // e.g., CHATHISTORY #ircv3 BETWEEN timestamp=YYYY-MM-DDThh:mm:ss.sssZ timestamp=YYYY-MM-DDThh:mm:ss.sssZ + 100
  480. func chathistoryHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (exiting bool) {
  481. var items []history.Item
  482. unknown_command := false
  483. var target string
  484. var channel *Channel
  485. var sequence history.Sequence
  486. var err error
  487. defer func() {
  488. // successful responses are sent as a chathistory or history batch
  489. if err == nil {
  490. if channel != nil {
  491. channel.replayHistoryItems(rb, items, false)
  492. } else {
  493. client.replayPrivmsgHistory(rb, items, target, true)
  494. }
  495. return
  496. }
  497. // errors are sent either without a batch, or in a draft/labeled-response batch as usual
  498. if unknown_command {
  499. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "UNKNOWN_COMMAND", utils.SafeErrorParam(msg.Params[0]), client.t("Unknown command"))
  500. } else if err == utils.ErrInvalidParams {
  501. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_PARAMETERS", msg.Params[0], client.t("Invalid parameters"))
  502. } else if err != nil {
  503. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "MESSAGE_ERROR", msg.Params[0], client.t("Messages could not be retrieved"))
  504. } else if sequence == nil {
  505. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "NO_SUCH_CHANNEL", utils.SafeErrorParam(msg.Params[1]), client.t("No such channel"))
  506. }
  507. }()
  508. config := server.Config()
  509. maxChathistoryLimit := config.History.ChathistoryMax
  510. if maxChathistoryLimit == 0 {
  511. return
  512. }
  513. preposition := strings.ToLower(msg.Params[0])
  514. target = msg.Params[1]
  515. parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
  516. if param == "*" && (preposition == "before" || preposition == "between") {
  517. // XXX compatibility with kiwi, which as of February 2020 is
  518. // using BEFORE * as a synonym for LATEST *
  519. return
  520. }
  521. err = utils.ErrInvalidParams
  522. pieces := strings.SplitN(param, "=", 2)
  523. if len(pieces) < 2 {
  524. return
  525. }
  526. identifier, value := strings.ToLower(pieces[0]), pieces[1]
  527. if identifier == "msgid" {
  528. msgid, err = value, nil
  529. return
  530. } else if identifier == "timestamp" {
  531. timestamp, err = time.Parse(IRCv3TimestampFormat, value)
  532. return
  533. }
  534. return
  535. }
  536. parseHistoryLimit := func(paramIndex int) (limit int) {
  537. if len(msg.Params) < (paramIndex + 1) {
  538. return maxChathistoryLimit
  539. }
  540. limit, err := strconv.Atoi(msg.Params[paramIndex])
  541. if err != nil || limit == 0 || limit > maxChathistoryLimit {
  542. limit = maxChathistoryLimit
  543. }
  544. return
  545. }
  546. channel, sequence, err = server.GetHistorySequence(nil, client, target)
  547. if err != nil || sequence == nil {
  548. return
  549. }
  550. roundUp := func(endpoint time.Time) (result time.Time) {
  551. return endpoint.Truncate(time.Millisecond).Add(time.Millisecond)
  552. }
  553. var start, end history.Selector
  554. var limit int
  555. switch preposition {
  556. case "between":
  557. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  558. if err != nil {
  559. return
  560. }
  561. end.Msgid, end.Time, err = parseQueryParam(msg.Params[3])
  562. if err != nil {
  563. return
  564. }
  565. // XXX preserve the ordering of the two parameters, since we might be going backwards,
  566. // but round up the chronologically first one, whichever it is, to make it exclusive
  567. if !start.Time.IsZero() && !end.Time.IsZero() {
  568. if start.Time.Before(end.Time) {
  569. start.Time = roundUp(start.Time)
  570. } else {
  571. end.Time = roundUp(end.Time)
  572. }
  573. }
  574. limit = parseHistoryLimit(4)
  575. case "before", "after", "around":
  576. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  577. if err != nil {
  578. return
  579. }
  580. if preposition == "after" && !start.Time.IsZero() {
  581. start.Time = roundUp(start.Time)
  582. }
  583. if preposition == "before" {
  584. end = start
  585. start = history.Selector{}
  586. }
  587. limit = parseHistoryLimit(3)
  588. case "latest":
  589. if msg.Params[2] != "*" {
  590. end.Msgid, end.Time, err = parseQueryParam(msg.Params[2])
  591. if err != nil {
  592. return
  593. }
  594. if !end.Time.IsZero() {
  595. end.Time = roundUp(end.Time)
  596. }
  597. start.Time = time.Now().UTC()
  598. }
  599. limit = parseHistoryLimit(3)
  600. default:
  601. unknown_command = true
  602. return
  603. }
  604. if preposition == "around" {
  605. items, err = sequence.Around(start, limit)
  606. } else {
  607. items, _, err = sequence.Between(start, end, limit)
  608. }
  609. return
  610. }
  611. // DEBUG <subcmd>
  612. func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  613. param := strings.ToUpper(msg.Params[0])
  614. switch param {
  615. case "GCSTATS":
  616. stats := debug.GCStats{
  617. Pause: make([]time.Duration, 10),
  618. PauseQuantiles: make([]time.Duration, 5),
  619. }
  620. debug.ReadGCStats(&stats)
  621. rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
  622. rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
  623. rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
  624. rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
  625. rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
  626. rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
  627. rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
  628. rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
  629. case "NUMGOROUTINE":
  630. count := runtime.NumGoroutine()
  631. rb.Notice(fmt.Sprintf("num goroutines: %d", count))
  632. case "PROFILEHEAP":
  633. profFile := server.Config().getOutputPath("oragono.mprof")
  634. file, err := os.Create(profFile)
  635. if err != nil {
  636. rb.Notice(fmt.Sprintf("error: %s", err))
  637. break
  638. }
  639. defer file.Close()
  640. pprof.Lookup("heap").WriteTo(file, 0)
  641. rb.Notice(fmt.Sprintf("written to %s", profFile))
  642. case "STARTCPUPROFILE":
  643. profFile := server.Config().getOutputPath("oragono.prof")
  644. file, err := os.Create(profFile)
  645. if err != nil {
  646. rb.Notice(fmt.Sprintf("error: %s", err))
  647. break
  648. }
  649. if err := pprof.StartCPUProfile(file); err != nil {
  650. defer file.Close()
  651. rb.Notice(fmt.Sprintf("error: %s", err))
  652. break
  653. }
  654. rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
  655. case "STOPCPUPROFILE":
  656. pprof.StopCPUProfile()
  657. rb.Notice(fmt.Sprintf("CPU profiling stopped"))
  658. case "CRASHSERVER":
  659. if !client.HasRoleCapabs("rehash") {
  660. rb.Notice(client.t("You must have rehash permissions in order to execute DEBUG CRASHSERVER"))
  661. return false
  662. }
  663. code := utils.ConfirmationCode(server.name, server.ctime)
  664. if len(msg.Params) == 1 || msg.Params[1] != code {
  665. rb.Notice(fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/DEBUG CRASHSERVER %s", code)))
  666. return false
  667. }
  668. server.logger.Error("server", fmt.Sprintf("DEBUG CRASHSERVER executed by operator %s", client.Oper().Name))
  669. go func() {
  670. // intentional nil dereference on a new goroutine, bypassing recover-from-errors
  671. var i, j *int
  672. *i = *j
  673. }()
  674. default:
  675. rb.Notice(client.t("Unrecognized DEBUG subcommand"))
  676. }
  677. return false
  678. }
  679. // helper for parsing the reason args to DLINE and KLINE
  680. func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
  681. reason = "No reason given"
  682. operReason = ""
  683. if len(params) > currentArg {
  684. reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
  685. if len(reasons) == 1 {
  686. reason = strings.TrimSpace(reasons[0])
  687. } else if len(reasons) == 2 {
  688. reason = strings.TrimSpace(reasons[0])
  689. operReason = strings.TrimSpace(reasons[1])
  690. }
  691. }
  692. return
  693. }
  694. func formatBanForListing(client *Client, key string, info IPBanInfo) string {
  695. desc := info.Reason
  696. if info.OperReason != "" && info.OperReason != info.Reason {
  697. desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
  698. }
  699. if info.Duration != 0 {
  700. desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
  701. }
  702. return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
  703. }
  704. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  705. // DLINE LIST
  706. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  707. // check oper permissions
  708. oper := client.Oper()
  709. if oper == nil || !oper.Class.Capabilities.Has("local_ban") {
  710. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  711. return false
  712. }
  713. currentArg := 0
  714. // if they say LIST, we just list the current dlines
  715. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  716. bans := server.dlines.AllBans()
  717. if len(bans) == 0 {
  718. rb.Notice(client.t("No DLINEs have been set!"))
  719. }
  720. for key, info := range bans {
  721. client.Notice(formatBanForListing(client, key, info))
  722. }
  723. return false
  724. }
  725. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  726. var andKill bool
  727. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  728. andKill = true
  729. currentArg++
  730. }
  731. // when setting a ban that covers the oper's current connection, we require them to say
  732. // "DLINE MYSELF" so that we're sure they really mean it.
  733. var dlineMyself bool
  734. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  735. dlineMyself = true
  736. currentArg++
  737. }
  738. // duration
  739. duration, err := custime.ParseDuration(msg.Params[currentArg])
  740. if err != nil {
  741. duration = 0
  742. } else {
  743. currentArg++
  744. }
  745. // get host
  746. if len(msg.Params) < currentArg+1 {
  747. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  748. return false
  749. }
  750. hostString := msg.Params[currentArg]
  751. currentArg++
  752. // check host
  753. hostNet, err := utils.NormalizedNetFromString(hostString)
  754. if err != nil {
  755. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  756. return false
  757. }
  758. if !dlineMyself && hostNet.Contains(client.IP()) {
  759. 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>"))
  760. return false
  761. }
  762. // check remote
  763. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  764. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  765. return false
  766. }
  767. // get comment(s)
  768. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  769. operName := oper.Name
  770. if operName == "" {
  771. operName = server.name
  772. }
  773. err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
  774. if err != nil {
  775. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
  776. return false
  777. }
  778. var snoDescription string
  779. hostString = utils.NetToNormalizedString(hostNet)
  780. if duration != 0 {
  781. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
  782. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
  783. } else {
  784. rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
  785. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
  786. }
  787. server.snomasks.Send(sno.LocalXline, snoDescription)
  788. var killClient bool
  789. if andKill {
  790. var clientsToKill []*Client
  791. var killedClientNicks []string
  792. for _, mcl := range server.clients.AllClients() {
  793. if hostNet.Contains(mcl.IP()) {
  794. clientsToKill = append(clientsToKill, mcl)
  795. killedClientNicks = append(killedClientNicks, mcl.nick)
  796. }
  797. }
  798. for _, mcl := range clientsToKill {
  799. mcl.SetExitedSnomaskSent()
  800. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  801. if mcl == client {
  802. killClient = true
  803. } else {
  804. // if mcl == client, we kill them below
  805. mcl.destroy(nil)
  806. }
  807. }
  808. // send snomask
  809. sort.Strings(killedClientNicks)
  810. 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, ", ")))
  811. }
  812. return killClient
  813. }
  814. // EXTJWT <target> [service_name]
  815. func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  816. accountName := client.AccountName()
  817. if accountName == "*" {
  818. accountName = ""
  819. }
  820. claims := jwt.MapClaims{
  821. "iss": server.name,
  822. "sub": client.Nick(),
  823. "account": accountName,
  824. "umodes": []string{},
  825. }
  826. if msg.Params[0] != "*" {
  827. channel := server.channels.Get(msg.Params[0])
  828. if channel == nil {
  829. rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_CHANNEL", client.t("No such channel"))
  830. return false
  831. }
  832. claims["channel"] = channel.Name()
  833. claims["joined"] = 0
  834. claims["cmodes"] = []string{}
  835. if present, cModes := channel.ClientStatus(client); present {
  836. claims["joined"] = 1
  837. var modeStrings []string
  838. for _, cMode := range cModes {
  839. modeStrings = append(modeStrings, string(cMode))
  840. }
  841. claims["cmodes"] = modeStrings
  842. }
  843. }
  844. config := server.Config()
  845. var serviceName string
  846. var sConfig jwt.JwtServiceConfig
  847. if 1 < len(msg.Params) {
  848. serviceName = strings.ToLower(msg.Params[1])
  849. sConfig = config.Extjwt.Services[serviceName]
  850. } else {
  851. serviceName = "*"
  852. sConfig = config.Extjwt.Default
  853. }
  854. if !sConfig.Enabled() {
  855. rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service"))
  856. return false
  857. }
  858. tokenString, err := sConfig.Sign(claims)
  859. if err == nil {
  860. maxTokenLength := 400
  861. for maxTokenLength < len(tokenString) {
  862. rb.Add(nil, server.name, "EXTJWT", msg.Params[0], serviceName, "*", tokenString[:maxTokenLength])
  863. tokenString = tokenString[maxTokenLength:]
  864. }
  865. rb.Add(nil, server.name, "EXTJWT", msg.Params[0], serviceName, tokenString)
  866. } else {
  867. rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Could not generate EXTJWT token"))
  868. }
  869. return false
  870. }
  871. // HELP [<query>]
  872. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  873. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  874. if len(argument) < 1 {
  875. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  876. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  877. return false
  878. }
  879. // handle index
  880. if argument == "index" {
  881. client.sendHelp("HELP", server.helpIndexManager.GetIndex(client.Languages(), client.HasMode(modes.Operator)), rb)
  882. return false
  883. }
  884. helpHandler, exists := Help[argument]
  885. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  886. if helpHandler.textGenerator != nil {
  887. client.sendHelp(strings.ToUpper(argument), helpHandler.textGenerator(client), rb)
  888. } else {
  889. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  890. }
  891. } else {
  892. args := msg.Params
  893. args = append(args, client.t("Help not found"))
  894. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  895. }
  896. return false
  897. }
  898. // HISTORY <target> [<limit>]
  899. // e.g., HISTORY #ubuntu 10
  900. // HISTORY me 15
  901. // HISTORY #darwin 1h
  902. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  903. config := server.Config()
  904. if !config.History.Enabled {
  905. rb.Notice(client.t("This command has been disabled by the server administrators"))
  906. return false
  907. }
  908. items, channel, err := easySelectHistory(server, client, msg.Params)
  909. if err == errNoSuchChannel {
  910. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  911. return false
  912. } else if err != nil {
  913. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), msg.Command, client.t("Could not retrieve history"))
  914. return false
  915. }
  916. if len(items) != 0 {
  917. if channel != nil {
  918. channel.replayHistoryItems(rb, items, false)
  919. } else {
  920. client.replayPrivmsgHistory(rb, items, "", true)
  921. }
  922. }
  923. return false
  924. }
  925. // INFO
  926. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  927. nick := client.Nick()
  928. // we do the below so that the human-readable lines in info can be translated.
  929. for _, line := range infoString1 {
  930. rb.Add(nil, server.name, RPL_INFO, nick, line)
  931. }
  932. rb.Add(nil, server.name, RPL_INFO, nick, fmt.Sprintf(client.t("This is Oragono version %s."), SemVer))
  933. if Commit != "" {
  934. rb.Add(nil, server.name, RPL_INFO, nick, fmt.Sprintf(client.t("It was built from git hash %s."), Commit))
  935. }
  936. rb.Add(nil, server.name, RPL_INFO, nick, "")
  937. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Oragono is released under the MIT license."))
  938. rb.Add(nil, server.name, RPL_INFO, nick, "")
  939. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Core Developers:"))
  940. for _, line := range infoString2 {
  941. rb.Add(nil, server.name, RPL_INFO, nick, line)
  942. }
  943. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Former Core Developers:"))
  944. for _, line := range infoString3 {
  945. rb.Add(nil, server.name, RPL_INFO, nick, line)
  946. }
  947. rb.Add(nil, server.name, RPL_INFO, nick, client.t("For a more complete list of contributors, see our changelog:"))
  948. rb.Add(nil, server.name, RPL_INFO, nick, " https://github.com/oragono/oragono/blob/master/CHANGELOG.md")
  949. rb.Add(nil, server.name, RPL_INFO, nick, "")
  950. // show translators for languages other than good ole' regular English
  951. tlines := server.Languages().Translators()
  952. if 0 < len(tlines) {
  953. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Translators:"))
  954. for _, line := range tlines {
  955. rb.Add(nil, server.name, RPL_INFO, nick, " "+strings.Replace(line, "\n", ", ", -1))
  956. }
  957. rb.Add(nil, server.name, RPL_INFO, nick, "")
  958. }
  959. rb.Add(nil, server.name, RPL_ENDOFINFO, nick, client.t("End of /INFO"))
  960. return false
  961. }
  962. // INVITE <nickname> <channel>
  963. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  964. nickname := msg.Params[0]
  965. channelName := msg.Params[1]
  966. target := server.clients.Get(nickname)
  967. if target == nil {
  968. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  969. return false
  970. }
  971. channel := server.channels.Get(channelName)
  972. if channel == nil {
  973. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(channelName), client.t("No such channel"))
  974. return false
  975. }
  976. channel.Invite(target, client, rb)
  977. return false
  978. }
  979. // ISON <nick>{ <nick>}
  980. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  981. var nicks = msg.Params
  982. ison := make([]string, 0, len(msg.Params))
  983. for _, nick := range nicks {
  984. currentNick := server.getCurrentNick(nick)
  985. if currentNick != "" {
  986. ison = append(ison, currentNick)
  987. }
  988. }
  989. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  990. return false
  991. }
  992. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  993. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  994. // kill JOIN 0 requests
  995. if msg.Params[0] == "0" {
  996. rb.Notice(client.t("JOIN 0 is not allowed"))
  997. return false
  998. }
  999. // handle regular JOINs
  1000. channels := strings.Split(msg.Params[0], ",")
  1001. var keys []string
  1002. if len(msg.Params) > 1 {
  1003. keys = strings.Split(msg.Params[1], ",")
  1004. }
  1005. config := server.Config()
  1006. oper := client.Oper()
  1007. for i, name := range channels {
  1008. if name == "" {
  1009. continue // #679
  1010. }
  1011. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  1012. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  1013. return false
  1014. }
  1015. var key string
  1016. if len(keys) > i {
  1017. key = keys[i]
  1018. }
  1019. err := server.channels.Join(client, name, key, false, rb)
  1020. if err != nil {
  1021. sendJoinError(client, name, rb, err)
  1022. }
  1023. }
  1024. return false
  1025. }
  1026. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  1027. var errMsg string
  1028. switch err {
  1029. case errInsufficientPrivs:
  1030. errMsg = `Only server operators can create new channels`
  1031. case errConfusableIdentifier:
  1032. errMsg = `That channel name is too close to the name of another channel`
  1033. case errChannelPurged:
  1034. errMsg = err.Error()
  1035. default:
  1036. errMsg = `No such channel`
  1037. }
  1038. rb.Add(nil, client.server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(name), client.t(errMsg))
  1039. }
  1040. // SAJOIN [nick] #channel{,#channel}
  1041. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1042. var target *Client
  1043. var channelString string
  1044. if strings.HasPrefix(msg.Params[0], "#") {
  1045. target = client
  1046. channelString = msg.Params[0]
  1047. } else {
  1048. if len(msg.Params) == 1 {
  1049. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  1050. return false
  1051. } else {
  1052. target = server.clients.Get(msg.Params[0])
  1053. if target == nil {
  1054. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  1055. return false
  1056. }
  1057. channelString = msg.Params[1]
  1058. }
  1059. }
  1060. channels := strings.Split(channelString, ",")
  1061. for _, chname := range channels {
  1062. err := server.channels.Join(target, chname, "", true, rb)
  1063. if err != nil {
  1064. sendJoinError(client, chname, rb, err)
  1065. }
  1066. }
  1067. return false
  1068. }
  1069. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1070. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1071. channels := strings.Split(msg.Params[0], ",")
  1072. users := strings.Split(msg.Params[1], ",")
  1073. if (len(channels) != len(users)) && (len(users) != 1) {
  1074. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1075. return false
  1076. }
  1077. type kickCmd struct {
  1078. channel string
  1079. nick string
  1080. }
  1081. kicks := make([]kickCmd, 0, len(channels))
  1082. for index, channel := range channels {
  1083. if channel == "" {
  1084. continue // #679
  1085. }
  1086. if len(users) == 1 {
  1087. kicks = append(kicks, kickCmd{channel, users[0]})
  1088. } else {
  1089. kicks = append(kicks, kickCmd{channel, users[index]})
  1090. }
  1091. }
  1092. var comment string
  1093. if len(msg.Params) > 2 {
  1094. comment = msg.Params[2]
  1095. }
  1096. for _, kick := range kicks {
  1097. channel := server.channels.Get(kick.channel)
  1098. if channel == nil {
  1099. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1100. continue
  1101. }
  1102. target := server.clients.Get(kick.nick)
  1103. if target == nil {
  1104. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1105. continue
  1106. }
  1107. if comment == "" {
  1108. comment = kick.nick
  1109. }
  1110. channel.Kick(client, target, comment, rb, false)
  1111. }
  1112. return false
  1113. }
  1114. // KILL <nickname> <comment>
  1115. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1116. nickname := msg.Params[0]
  1117. comment := "<no reason supplied>"
  1118. if len(msg.Params) > 1 {
  1119. comment = msg.Params[1]
  1120. }
  1121. target := server.clients.Get(nickname)
  1122. if target == nil {
  1123. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(nickname), client.t("No such nick"))
  1124. return false
  1125. }
  1126. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1127. 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))
  1128. target.SetExitedSnomaskSent()
  1129. target.Quit(quitMsg, nil)
  1130. target.destroy(nil)
  1131. return false
  1132. }
  1133. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1134. // KLINE LIST
  1135. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1136. details := client.Details()
  1137. // check oper permissions
  1138. oper := client.Oper()
  1139. if oper == nil || !oper.Class.Capabilities.Has("local_ban") {
  1140. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1141. return false
  1142. }
  1143. currentArg := 0
  1144. // if they say LIST, we just list the current klines
  1145. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1146. bans := server.klines.AllBans()
  1147. if len(bans) == 0 {
  1148. client.Notice("No KLINEs have been set!")
  1149. }
  1150. for key, info := range bans {
  1151. client.Notice(formatBanForListing(client, key, info))
  1152. }
  1153. return false
  1154. }
  1155. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1156. var andKill bool
  1157. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1158. andKill = true
  1159. currentArg++
  1160. }
  1161. // when setting a ban that covers the oper's current connection, we require them to say
  1162. // "KLINE MYSELF" so that we're sure they really mean it.
  1163. var klineMyself bool
  1164. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1165. klineMyself = true
  1166. currentArg++
  1167. }
  1168. // duration
  1169. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1170. if err != nil {
  1171. duration = 0
  1172. } else {
  1173. currentArg++
  1174. }
  1175. // get mask
  1176. if len(msg.Params) < currentArg+1 {
  1177. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1178. return false
  1179. }
  1180. mask := msg.Params[currentArg]
  1181. currentArg++
  1182. // check mask
  1183. mask, err = CanonicalizeMaskWildcard(mask)
  1184. if err != nil {
  1185. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1186. return false
  1187. }
  1188. matcher, err := utils.CompileGlob(mask, false)
  1189. if err != nil {
  1190. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1191. return false
  1192. }
  1193. for _, clientMask := range client.AllNickmasks() {
  1194. if !klineMyself && matcher.MatchString(clientMask) {
  1195. 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>"))
  1196. return false
  1197. }
  1198. }
  1199. // check remote
  1200. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1201. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1202. return false
  1203. }
  1204. // get oper name
  1205. operName := oper.Name
  1206. if operName == "" {
  1207. operName = server.name
  1208. }
  1209. // get comment(s)
  1210. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1211. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1212. if err != nil {
  1213. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1214. return false
  1215. }
  1216. var snoDescription string
  1217. if duration != 0 {
  1218. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1219. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1220. } else {
  1221. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1222. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1223. }
  1224. server.snomasks.Send(sno.LocalXline, snoDescription)
  1225. var killClient bool
  1226. if andKill {
  1227. var clientsToKill []*Client
  1228. var killedClientNicks []string
  1229. for _, mcl := range server.clients.AllClients() {
  1230. for _, clientMask := range mcl.AllNickmasks() {
  1231. if matcher.MatchString(clientMask) {
  1232. clientsToKill = append(clientsToKill, mcl)
  1233. killedClientNicks = append(killedClientNicks, mcl.nick)
  1234. }
  1235. }
  1236. }
  1237. for _, mcl := range clientsToKill {
  1238. mcl.SetExitedSnomaskSent()
  1239. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1240. if mcl == client {
  1241. killClient = true
  1242. } else {
  1243. // if mcl == client, we kill them below
  1244. mcl.destroy(nil)
  1245. }
  1246. }
  1247. // send snomask
  1248. sort.Strings(killedClientNicks)
  1249. 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, ", ")))
  1250. }
  1251. return killClient
  1252. }
  1253. // LANGUAGE <code>{ <code>}
  1254. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1255. nick := client.Nick()
  1256. alreadyDoneLanguages := make(map[string]bool)
  1257. var appliedLanguages []string
  1258. lm := server.Languages()
  1259. supportedLanguagesCount := lm.Count()
  1260. if supportedLanguagesCount < len(msg.Params) {
  1261. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1262. return false
  1263. }
  1264. for _, value := range msg.Params {
  1265. value = strings.ToLower(value)
  1266. // strip ~ from the language if it has it
  1267. value = strings.TrimPrefix(value, "~")
  1268. // silently ignore empty languages or those with spaces in them
  1269. if len(value) == 0 || strings.Contains(value, " ") {
  1270. continue
  1271. }
  1272. _, exists := lm.Languages[value]
  1273. if !exists {
  1274. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1275. return false
  1276. }
  1277. // if we've already applied the given language, skip it
  1278. _, exists = alreadyDoneLanguages[value]
  1279. if exists {
  1280. continue
  1281. }
  1282. appliedLanguages = append(appliedLanguages, value)
  1283. }
  1284. var langsToSet []string
  1285. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1286. langsToSet = appliedLanguages
  1287. }
  1288. client.SetLanguages(langsToSet)
  1289. params := make([]string, len(appliedLanguages)+2)
  1290. params[0] = nick
  1291. copy(params[1:], appliedLanguages)
  1292. params[len(params)-1] = client.t("Language preferences have been set")
  1293. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1294. return false
  1295. }
  1296. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1297. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1298. config := server.Config()
  1299. if time.Since(client.ctime) < config.Channels.ListDelay && client.Account() == "" && !client.HasMode(modes.Operator) {
  1300. remaining := time.Until(client.ctime.Add(config.Channels.ListDelay))
  1301. csNotice(rb, 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))
  1302. rb.Add(nil, server.name, RPL_LISTEND, client.Nick(), client.t("End of LIST"))
  1303. return false
  1304. }
  1305. // get channels
  1306. var channels []string
  1307. for _, param := range msg.Params {
  1308. if 0 < len(param) && param[0] == '#' {
  1309. for _, channame := range strings.Split(param, ",") {
  1310. if 0 < len(channame) && channame[0] == '#' {
  1311. channels = append(channels, channame)
  1312. }
  1313. }
  1314. }
  1315. }
  1316. // get elist conditions
  1317. var matcher elistMatcher
  1318. for _, param := range msg.Params {
  1319. if len(param) < 1 {
  1320. continue
  1321. }
  1322. if param[0] == '<' {
  1323. param = param[1:]
  1324. val, err := strconv.Atoi(param)
  1325. if err != nil {
  1326. continue
  1327. }
  1328. matcher.MaxClientsActive = true
  1329. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1330. }
  1331. if param[0] == '>' {
  1332. param = param[1:]
  1333. val, err := strconv.Atoi(param)
  1334. if err != nil {
  1335. continue
  1336. }
  1337. matcher.MinClientsActive = true
  1338. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1339. }
  1340. }
  1341. clientIsOp := client.HasMode(modes.Operator)
  1342. if len(channels) == 0 {
  1343. for _, channel := range server.channels.Channels() {
  1344. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1345. continue
  1346. }
  1347. if matcher.Matches(channel) {
  1348. client.RplList(channel, rb)
  1349. }
  1350. }
  1351. } else {
  1352. // limit regular users to only listing one channel
  1353. if !clientIsOp {
  1354. channels = channels[:1]
  1355. }
  1356. for _, chname := range channels {
  1357. channel := server.channels.Get(chname)
  1358. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1359. if len(chname) > 0 {
  1360. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1361. }
  1362. continue
  1363. }
  1364. if matcher.Matches(channel) {
  1365. client.RplList(channel, rb)
  1366. }
  1367. }
  1368. }
  1369. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1370. return false
  1371. }
  1372. // LUSERS [<mask> [<server>]]
  1373. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1374. server.Lusers(client, rb)
  1375. return false
  1376. }
  1377. // MODE <target> [<modestring> [<mode arguments>...]]
  1378. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1379. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1380. return cmodeHandler(server, client, msg, rb)
  1381. }
  1382. return umodeHandler(server, client, msg, rb)
  1383. }
  1384. // MODE <channel> [<modestring> [<mode arguments>...]]
  1385. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1386. channel := server.channels.Get(msg.Params[0])
  1387. if channel == nil {
  1388. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1389. return false
  1390. }
  1391. var changes modes.ModeChanges
  1392. if 1 < len(msg.Params) {
  1393. // parse out real mode changes
  1394. params := msg.Params[1:]
  1395. var unknown map[rune]bool
  1396. changes, unknown = modes.ParseChannelModeChanges(params...)
  1397. // alert for unknown mode changes
  1398. for char := range unknown {
  1399. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1400. }
  1401. if len(unknown) == 1 && len(changes) == 0 {
  1402. return false
  1403. }
  1404. }
  1405. // process mode changes, include list operations (an empty set of changes does a list)
  1406. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1407. details := client.Details()
  1408. announceCmodeChanges(channel, applied, details.nickMask, details.accountName, details.account, rb)
  1409. return false
  1410. }
  1411. func announceCmodeChanges(channel *Channel, applied modes.ModeChanges, source, accountName, account string, rb *ResponseBuffer) {
  1412. // send out changes
  1413. if len(applied) > 0 {
  1414. message := utils.MakeMessage("")
  1415. changeStrings := applied.Strings()
  1416. for _, changeString := range changeStrings {
  1417. message.Split = append(message.Split, utils.MessagePair{Message: changeString})
  1418. }
  1419. args := append([]string{channel.name}, changeStrings...)
  1420. rb.AddFromClient(message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1421. for _, member := range channel.Members() {
  1422. for _, session := range member.Sessions() {
  1423. if session != rb.session {
  1424. session.sendFromClientInternal(false, message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1425. }
  1426. }
  1427. }
  1428. channel.AddHistoryItem(history.Item{
  1429. Type: history.Mode,
  1430. Nick: source,
  1431. AccountName: accountName,
  1432. Message: message,
  1433. }, account)
  1434. }
  1435. }
  1436. // MODE <client> [<modestring> [<mode arguments>...]]
  1437. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1438. cDetails := client.Details()
  1439. target := server.clients.Get(msg.Params[0])
  1440. if target == nil {
  1441. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1442. return false
  1443. }
  1444. targetNick := target.Nick()
  1445. hasPrivs := client == target || msg.Command == "SAMODE"
  1446. if !hasPrivs {
  1447. if len(msg.Params) > 1 {
  1448. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1449. } else {
  1450. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1451. }
  1452. return false
  1453. }
  1454. // applied mode changes
  1455. applied := make(modes.ModeChanges, 0)
  1456. if 1 < len(msg.Params) {
  1457. // parse out real mode changes
  1458. params := msg.Params[1:]
  1459. changes, unknown := modes.ParseUserModeChanges(params...)
  1460. // alert for unknown mode changes
  1461. for char := range unknown {
  1462. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1463. }
  1464. if len(unknown) == 1 && len(changes) == 0 {
  1465. return false
  1466. }
  1467. // apply mode changes
  1468. applied = ApplyUserModeChanges(target, changes, msg.Command == "SAMODE", nil)
  1469. }
  1470. if len(applied) > 0 {
  1471. args := append([]string{targetNick}, applied.Strings()...)
  1472. rb.Add(nil, cDetails.nickMask, "MODE", args...)
  1473. } else if hasPrivs {
  1474. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1475. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1476. masks := server.snomasks.String(target)
  1477. if 0 < len(masks) {
  1478. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1479. }
  1480. }
  1481. }
  1482. return false
  1483. }
  1484. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1485. func (server *Server) getCurrentNick(nick string) (result string) {
  1486. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1487. return service.Name
  1488. } else if iclient := server.clients.Get(nick); iclient != nil {
  1489. return iclient.Nick()
  1490. }
  1491. return ""
  1492. }
  1493. // MONITOR <subcmd> [params...]
  1494. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1495. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1496. if !exists {
  1497. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1498. return false
  1499. }
  1500. return handler(server, client, msg, rb)
  1501. }
  1502. // MONITOR - <target>{,<target>}
  1503. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1504. if len(msg.Params) < 2 {
  1505. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1506. return false
  1507. }
  1508. targets := strings.Split(msg.Params[1], ",")
  1509. for _, target := range targets {
  1510. cfnick, err := CasefoldName(target)
  1511. if err != nil {
  1512. continue
  1513. }
  1514. server.monitorManager.Remove(client, cfnick)
  1515. }
  1516. return false
  1517. }
  1518. // MONITOR + <target>{,<target>}
  1519. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1520. if len(msg.Params) < 2 {
  1521. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1522. return false
  1523. }
  1524. var online []string
  1525. var offline []string
  1526. limits := server.Config().Limits
  1527. targets := strings.Split(msg.Params[1], ",")
  1528. for _, target := range targets {
  1529. // check name length
  1530. if len(target) < 1 || len(targets) > limits.NickLen {
  1531. continue
  1532. }
  1533. // add target
  1534. casefoldedTarget, err := CasefoldName(target)
  1535. if err != nil {
  1536. continue
  1537. }
  1538. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1539. if err == errMonitorLimitExceeded {
  1540. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1541. break
  1542. } else if err != nil {
  1543. continue
  1544. }
  1545. currentNick := server.getCurrentNick(target)
  1546. // add to online / offline lists
  1547. if currentNick != "" {
  1548. online = append(online, currentNick)
  1549. } else {
  1550. offline = append(offline, target)
  1551. }
  1552. }
  1553. if len(online) > 0 {
  1554. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1555. }
  1556. if len(offline) > 0 {
  1557. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1558. }
  1559. return false
  1560. }
  1561. // MONITOR C
  1562. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1563. server.monitorManager.RemoveAll(client)
  1564. return false
  1565. }
  1566. // MONITOR L
  1567. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1568. nick := client.Nick()
  1569. monitorList := server.monitorManager.List(client)
  1570. var nickList []string
  1571. for _, cfnick := range monitorList {
  1572. replynick := cfnick
  1573. currentNick := server.getCurrentNick(cfnick)
  1574. // report the uncasefolded nick if it's available, i.e., the client is online
  1575. if currentNick != "" {
  1576. replynick = currentNick
  1577. }
  1578. nickList = append(nickList, replynick)
  1579. }
  1580. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1581. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1582. }
  1583. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1584. return false
  1585. }
  1586. // MONITOR S
  1587. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1588. var online []string
  1589. var offline []string
  1590. monitorList := server.monitorManager.List(client)
  1591. for _, name := range monitorList {
  1592. currentNick := server.getCurrentNick(name)
  1593. if currentNick != "" {
  1594. online = append(online, currentNick)
  1595. } else {
  1596. offline = append(offline, name)
  1597. }
  1598. }
  1599. if len(online) > 0 {
  1600. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1601. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1602. }
  1603. }
  1604. if len(offline) > 0 {
  1605. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1606. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1607. }
  1608. }
  1609. return false
  1610. }
  1611. // MOTD
  1612. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1613. server.MOTD(client, rb)
  1614. return false
  1615. }
  1616. // NAMES [<channel>{,<channel>} [target]]
  1617. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1618. var channels []string
  1619. if len(msg.Params) > 0 {
  1620. channels = strings.Split(msg.Params[0], ",")
  1621. }
  1622. // TODO: in a post-federation world, process `target` (server to forward request to)
  1623. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1624. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1625. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1626. // with the <channel> parameter set to an asterix character"
  1627. if len(channels) == 0 {
  1628. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1629. return false
  1630. }
  1631. chname := channels[0]
  1632. success := false
  1633. channel := server.channels.Get(chname)
  1634. if channel != nil {
  1635. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1636. channel.Names(client, rb)
  1637. success = true
  1638. }
  1639. }
  1640. if !success { // channel.Names() sends this numeric itself on success
  1641. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1642. }
  1643. return false
  1644. }
  1645. // NICK <nickname>
  1646. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1647. if client.registered {
  1648. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1649. } else {
  1650. client.preregNick = msg.Params[0]
  1651. }
  1652. return false
  1653. }
  1654. // helper to store a batched PRIVMSG in the session object
  1655. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1656. var errorCode, errorMessage string
  1657. defer func() {
  1658. if errorCode != "" {
  1659. if histType != history.Notice {
  1660. rb.Add(nil, server.name, "FAIL", "BATCH", errorCode, errorMessage)
  1661. }
  1662. rb.session.EndMultilineBatch("")
  1663. }
  1664. }()
  1665. if batchTag != rb.session.batch.label {
  1666. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Incorrect batch tag sent")
  1667. return
  1668. } else if len(msg.Params) < 2 {
  1669. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Invalid multiline batch")
  1670. return
  1671. }
  1672. rb.session.batch.command = msg.Command
  1673. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1674. if isConcat && len(msg.Params[1]) == 0 {
  1675. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Cannot send a blank line with the multiline concat tag")
  1676. return
  1677. }
  1678. if !isConcat && len(rb.session.batch.message.Split) != 0 {
  1679. rb.session.batch.lenBytes++ // bill for the newline
  1680. }
  1681. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1682. rb.session.batch.lenBytes += len(msg.Params[1])
  1683. config := server.Config()
  1684. if config.Limits.Multiline.MaxBytes < rb.session.batch.lenBytes {
  1685. errorCode, errorMessage = "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes)
  1686. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1687. errorCode, errorMessage = "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines)
  1688. }
  1689. }
  1690. // NOTICE <target>{,<target>} <message>
  1691. // PRIVMSG <target>{,<target>} <message>
  1692. // TAGMSG <target>{,<target>}
  1693. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1694. histType, err := msgCommandToHistType(msg.Command)
  1695. if err != nil {
  1696. return false
  1697. }
  1698. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1699. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1700. return false
  1701. }
  1702. cnick := client.Nick()
  1703. clientOnlyTags := msg.ClientOnlyTags()
  1704. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1705. // nothing to do
  1706. return false
  1707. }
  1708. targets := strings.Split(msg.Params[0], ",")
  1709. var message string
  1710. if len(msg.Params) > 1 {
  1711. message = msg.Params[1]
  1712. }
  1713. if histType != history.Tagmsg && message == "" {
  1714. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1715. return false
  1716. }
  1717. if rb.session.isTor && utils.IsRestrictedCTCPMessage(message) {
  1718. // note that error replies are never sent for NOTICE
  1719. if histType != history.Notice {
  1720. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1721. }
  1722. return false
  1723. }
  1724. for i, targetString := range targets {
  1725. // max of four targets per privmsg
  1726. if i == maxTargets {
  1727. break
  1728. }
  1729. // each target gets distinct msgids
  1730. splitMsg := utils.MakeMessage(message)
  1731. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1732. }
  1733. return false
  1734. }
  1735. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1736. server := client.server
  1737. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1738. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1739. if len(target) == 0 {
  1740. return
  1741. } else if target[0] == '#' {
  1742. channel := server.channels.Get(target)
  1743. if channel == nil {
  1744. if histType != history.Notice {
  1745. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1746. }
  1747. return
  1748. }
  1749. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1750. } else {
  1751. lowercaseTarget := strings.ToLower(target)
  1752. service, isService := OragonoServices[lowercaseTarget]
  1753. _, isZNC := zncHandlers[lowercaseTarget]
  1754. if histType == history.Privmsg {
  1755. if isService {
  1756. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1757. return
  1758. } else if isZNC {
  1759. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1760. return
  1761. }
  1762. }
  1763. // NOTICE and TAGMSG to services are ignored
  1764. if isService || isZNC {
  1765. return
  1766. }
  1767. user := server.clients.Get(target)
  1768. if user == nil {
  1769. if histType != history.Notice {
  1770. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1771. }
  1772. return
  1773. }
  1774. tDetails := user.Details()
  1775. tnick := tDetails.nick
  1776. details := client.Details()
  1777. nickMaskString := details.nickMask
  1778. accountName := details.accountName
  1779. var deliverySessions []*Session
  1780. // restrict messages appropriately when +R is set
  1781. // intentionally make the sending user think the message went through fine
  1782. allowedPlusR := details.account != "" || !user.HasMode(modes.RegisteredOnly)
  1783. if allowedPlusR {
  1784. deliverySessions = append(deliverySessions, user.Sessions()...)
  1785. }
  1786. // all sessions of the sender, except the originating session, get a copy as well:
  1787. if client != user {
  1788. for _, session := range client.Sessions() {
  1789. if session != rb.session {
  1790. deliverySessions = append(deliverySessions, session)
  1791. }
  1792. }
  1793. }
  1794. for _, session := range deliverySessions {
  1795. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1796. // don't send TAGMSG at all if they don't have the tags cap
  1797. if histType == history.Tagmsg && hasTagsCap {
  1798. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1799. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1800. tagsToSend := tags
  1801. if !hasTagsCap {
  1802. tagsToSend = nil
  1803. }
  1804. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1805. }
  1806. }
  1807. // the originating session may get an echo message:
  1808. if rb.session.capabilities.Has(caps.EchoMessage) {
  1809. hasTagsCap := rb.session.capabilities.Has(caps.MessageTags)
  1810. if histType == history.Tagmsg && hasTagsCap {
  1811. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1812. } else {
  1813. tagsToSend := tags
  1814. if !hasTagsCap {
  1815. tagsToSend = nil
  1816. }
  1817. rb.AddSplitMessageFromClient(nickMaskString, accountName, tagsToSend, command, tnick, message)
  1818. }
  1819. }
  1820. if histType != history.Notice && user.Away() {
  1821. //TODO(dan): possibly implement cooldown of away notifications to users
  1822. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, user.AwayMessage())
  1823. }
  1824. config := server.Config()
  1825. if !config.History.Enabled {
  1826. return
  1827. }
  1828. item := history.Item{
  1829. Type: histType,
  1830. Message: message,
  1831. Nick: nickMaskString,
  1832. AccountName: accountName,
  1833. Tags: tags,
  1834. }
  1835. if !item.IsStorable() || !allowedPlusR {
  1836. return
  1837. }
  1838. targetedItem := item
  1839. targetedItem.Params[0] = tnick
  1840. cStatus, _ := client.historyStatus(config)
  1841. tStatus, _ := user.historyStatus(config)
  1842. // add to ephemeral history
  1843. if cStatus == HistoryEphemeral {
  1844. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1845. client.history.Add(targetedItem)
  1846. }
  1847. if tStatus == HistoryEphemeral && client != user {
  1848. item.CfCorrespondent = details.nickCasefolded
  1849. user.history.Add(item)
  1850. }
  1851. if cStatus == HistoryPersistent || tStatus == HistoryPersistent {
  1852. targetedItem.CfCorrespondent = ""
  1853. server.historyDB.AddDirectMessage(details.nickCasefolded, details.account, tDetails.nickCasefolded, tDetails.account, targetedItem)
  1854. }
  1855. }
  1856. }
  1857. // NPC <target> <sourcenick> <message>
  1858. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1859. target := msg.Params[0]
  1860. fakeSource := msg.Params[1]
  1861. message := msg.Params[2:]
  1862. _, err := CasefoldName(fakeSource)
  1863. if err != nil {
  1864. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1865. return false
  1866. }
  1867. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1868. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1869. return false
  1870. }
  1871. // NPCA <target> <sourcenick> <message>
  1872. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1873. target := msg.Params[0]
  1874. fakeSource := msg.Params[1]
  1875. message := msg.Params[2:]
  1876. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1877. _, err := CasefoldName(fakeSource)
  1878. if err != nil {
  1879. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1880. return false
  1881. }
  1882. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1883. return false
  1884. }
  1885. // OPER <name> [password]
  1886. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1887. if client.HasMode(modes.Operator) {
  1888. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1889. return false
  1890. }
  1891. // must pass at least one check, and all enabled checks
  1892. var checkPassed, checkFailed, passwordFailed bool
  1893. oper := server.GetOperator(msg.Params[0])
  1894. if oper != nil {
  1895. if oper.Fingerprint != "" {
  1896. if oper.Fingerprint == rb.session.certfp {
  1897. checkPassed = true
  1898. } else {
  1899. checkFailed = true
  1900. }
  1901. }
  1902. if !checkFailed && oper.Pass != nil {
  1903. if len(msg.Params) == 1 {
  1904. checkFailed = true
  1905. } else if bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1906. checkFailed = true
  1907. passwordFailed = true
  1908. } else {
  1909. checkPassed = true
  1910. }
  1911. }
  1912. }
  1913. if !checkPassed || checkFailed {
  1914. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1915. // #951: only disconnect them if we actually tried to check a password for them
  1916. if passwordFailed {
  1917. client.Quit(client.t("Password incorrect"), rb.session)
  1918. return true
  1919. } else {
  1920. return false
  1921. }
  1922. }
  1923. if oper != nil {
  1924. applyOper(client, oper, rb)
  1925. }
  1926. return false
  1927. }
  1928. // adds or removes operator status
  1929. // XXX: to add oper, this calls into ApplyUserModeChanges, but to remove oper,
  1930. // ApplyUserModeChanges calls into this, because the commands are asymmetric
  1931. // (/OPER to add, /MODE self -o to remove)
  1932. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  1933. details := client.Details()
  1934. client.SetOper(oper)
  1935. newDetails := client.Details()
  1936. if details.nickMask != newDetails.nickMask {
  1937. client.sendChghost(details.nickMask, newDetails.hostname)
  1938. }
  1939. if oper != nil {
  1940. // set new modes: modes.Operator, plus anything specified in the config
  1941. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1942. modeChanges[0] = modes.ModeChange{
  1943. Mode: modes.Operator,
  1944. Op: modes.Add,
  1945. }
  1946. copy(modeChanges[1:], oper.Modes)
  1947. applied := ApplyUserModeChanges(client, modeChanges, true, oper)
  1948. 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))
  1949. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  1950. args := append([]string{details.nick}, applied.Strings()...)
  1951. rb.Broadcast(nil, client.server.name, "MODE", args...)
  1952. } else {
  1953. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client deopered $c[grey][$r%s$c[grey]]"), newDetails.nickMask))
  1954. }
  1955. for _, session := range client.Sessions() {
  1956. // client may now be unthrottled by the fakelag system
  1957. session.resetFakelag()
  1958. }
  1959. }
  1960. // DEOPER
  1961. func deoperHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1962. // pretend they sent /MODE $nick -o
  1963. fakeModeMsg := ircmsg.MakeMessage(nil, "", "MODE", client.Nick(), "-o")
  1964. return umodeHandler(server, client, fakeModeMsg, rb)
  1965. }
  1966. // PART <channel>{,<channel>} [<reason>]
  1967. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1968. channels := strings.Split(msg.Params[0], ",")
  1969. var reason string
  1970. if len(msg.Params) > 1 {
  1971. reason = msg.Params[1]
  1972. }
  1973. for _, chname := range channels {
  1974. if chname == "" {
  1975. continue // #679
  1976. }
  1977. err := server.channels.Part(client, chname, reason, rb)
  1978. if err == errNoSuchChannel {
  1979. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1980. }
  1981. }
  1982. return false
  1983. }
  1984. // PASS <password>
  1985. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1986. if client.registered {
  1987. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1988. return false
  1989. }
  1990. // only give them one try to run the PASS command (if a server password is set,
  1991. // then all code paths end with this variable being set):
  1992. if rb.session.passStatus != serverPassUnsent {
  1993. return false
  1994. }
  1995. password := msg.Params[0]
  1996. config := server.Config()
  1997. if config.Accounts.LoginViaPassCommand {
  1998. colonIndex := strings.IndexByte(password, ':')
  1999. if colonIndex != -1 && client.Account() == "" {
  2000. account, accountPass := password[:colonIndex], password[colonIndex+1:]
  2001. if strudelIndex := strings.IndexByte(account, '@'); strudelIndex != -1 {
  2002. account, rb.session.deviceID = account[:strudelIndex], account[strudelIndex+1:]
  2003. }
  2004. err := server.accounts.AuthenticateByPassphrase(client, account, accountPass)
  2005. if err == nil {
  2006. sendSuccessfulAccountAuth(client, rb, false, true)
  2007. // login-via-pass-command entails that we do not need to check
  2008. // an actual server password (either no password or skip-server-password)
  2009. rb.session.passStatus = serverPassSuccessful
  2010. return false
  2011. }
  2012. }
  2013. }
  2014. // if login-via-PASS failed for any reason, proceed to try and interpret the
  2015. // provided password as the server password
  2016. serverPassword := config.Server.passwordBytes
  2017. // if no password exists, skip checking
  2018. if serverPassword == nil {
  2019. return false
  2020. }
  2021. // check the provided password
  2022. if bcrypt.CompareHashAndPassword(serverPassword, []byte(password)) == nil {
  2023. rb.session.passStatus = serverPassSuccessful
  2024. } else {
  2025. rb.session.passStatus = serverPassFailed
  2026. }
  2027. // if they failed the check, we'll bounce them later when they try to complete registration
  2028. // note in particular that with skip-server-password, you can give the wrong server
  2029. // password here, then successfully SASL and be admitted
  2030. return false
  2031. }
  2032. // PING [params...]
  2033. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2034. rb.Add(nil, server.name, "PONG", msg.Params...)
  2035. return false
  2036. }
  2037. // PONG [params...]
  2038. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2039. // client gets touched when they send this command, so we don't need to do anything
  2040. return false
  2041. }
  2042. // QUIT [<reason>]
  2043. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2044. reason := "Quit"
  2045. if len(msg.Params) > 0 {
  2046. reason += ": " + msg.Params[0]
  2047. }
  2048. client.Quit(reason, rb.session)
  2049. return true
  2050. }
  2051. // REHASH
  2052. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2053. nick := client.Nick()
  2054. server.logger.Info("server", "REHASH command used by", nick)
  2055. err := server.rehash()
  2056. if err == nil {
  2057. // we used to send RPL_REHASHING here but i don't think it really makes sense
  2058. // in the labeled-response world, since the intent is "rehash in progress" but
  2059. // it won't display until the rehash is actually complete
  2060. // TODO all operators should get a notice of some kind here
  2061. rb.Notice(client.t("Rehash complete"))
  2062. } else {
  2063. rb.Add(nil, server.name, ERR_UNKNOWNERROR, nick, "REHASH", err.Error())
  2064. }
  2065. return false
  2066. }
  2067. // RENAME <oldchan> <newchan> [<reason>]
  2068. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  2069. result = false
  2070. oldName, newName := msg.Params[0], msg.Params[1]
  2071. var reason string
  2072. if 2 < len(msg.Params) {
  2073. reason = msg.Params[2]
  2074. }
  2075. channel := server.channels.Get(oldName)
  2076. if channel == nil {
  2077. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  2078. return false
  2079. }
  2080. if !(channel.ClientIsAtLeast(client, modes.ChannelOperator) || client.HasRoleCapabs("chanreg")) {
  2081. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  2082. return false
  2083. }
  2084. founder := channel.Founder()
  2085. if founder != "" && founder != client.Account() {
  2086. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  2087. return false
  2088. }
  2089. config := server.Config()
  2090. status, _ := channel.historyStatus(config)
  2091. if status == HistoryPersistent {
  2092. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Channels with persistent history cannot be renamed"))
  2093. return false
  2094. }
  2095. // perform the channel rename
  2096. err := server.channels.Rename(oldName, newName)
  2097. if err == errInvalidChannelName {
  2098. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2099. } else if err == errChannelNameInUse {
  2100. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2101. } else if err != nil {
  2102. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  2103. }
  2104. if err != nil {
  2105. return false
  2106. }
  2107. // send RENAME messages
  2108. clientPrefix := client.NickMaskString()
  2109. for _, mcl := range channel.Members() {
  2110. mDetails := mcl.Details()
  2111. for _, mSession := range mcl.Sessions() {
  2112. targetRb := rb
  2113. targetPrefix := clientPrefix
  2114. if mSession != rb.session {
  2115. targetRb = NewResponseBuffer(mSession)
  2116. targetPrefix = mDetails.nickMask
  2117. }
  2118. if mSession.capabilities.Has(caps.Rename) {
  2119. if reason != "" {
  2120. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  2121. } else {
  2122. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  2123. }
  2124. } else {
  2125. if reason != "" {
  2126. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  2127. } else {
  2128. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  2129. }
  2130. if mSession.capabilities.Has(caps.ExtendedJoin) {
  2131. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  2132. } else {
  2133. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  2134. }
  2135. channel.SendTopic(mcl, targetRb, false)
  2136. channel.Names(mcl, targetRb)
  2137. }
  2138. if mcl != client {
  2139. targetRb.Send(false)
  2140. }
  2141. }
  2142. }
  2143. return false
  2144. }
  2145. // RESUME <token> [timestamp]
  2146. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2147. details := ResumeDetails{
  2148. PresentedToken: msg.Params[0],
  2149. }
  2150. if client.registered {
  2151. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  2152. return false
  2153. }
  2154. if 1 < len(msg.Params) {
  2155. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  2156. if err == nil {
  2157. details.Timestamp = ts
  2158. } else {
  2159. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  2160. }
  2161. }
  2162. rb.session.resumeDetails = &details
  2163. return false
  2164. }
  2165. // SANICK <oldnick> <nickname>
  2166. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2167. targetNick := strings.TrimSpace(msg.Params[0])
  2168. target := server.clients.Get(targetNick)
  2169. if target == nil {
  2170. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2171. return false
  2172. }
  2173. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2174. return false
  2175. }
  2176. // SCENE <target> <message>
  2177. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2178. target := msg.Params[0]
  2179. message := msg.Params[1:]
  2180. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2181. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2182. return false
  2183. }
  2184. // SETNAME <realname>
  2185. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2186. realname := msg.Params[0]
  2187. client.SetRealname(realname)
  2188. details := client.Details()
  2189. // alert friends
  2190. now := time.Now().UTC()
  2191. for session := range client.Friends(caps.SetName) {
  2192. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2193. }
  2194. return false
  2195. }
  2196. // SUMMON [parameters]
  2197. func summonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2198. rb.Add(nil, server.name, ERR_SUMMONDISABLED, client.Nick(), client.t("SUMMON has been disabled"))
  2199. return false
  2200. }
  2201. // TIME
  2202. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2203. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2204. return false
  2205. }
  2206. // TOPIC <channel> [<topic>]
  2207. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2208. channel := server.channels.Get(msg.Params[0])
  2209. if channel == nil {
  2210. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2211. return false
  2212. }
  2213. if len(msg.Params) > 1 {
  2214. channel.SetTopic(client, msg.Params[1], rb)
  2215. } else {
  2216. channel.SendTopic(client, rb, true)
  2217. }
  2218. return false
  2219. }
  2220. // UNDLINE <ip>|<net>
  2221. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2222. // check oper permissions
  2223. oper := client.Oper()
  2224. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2225. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2226. return false
  2227. }
  2228. // get host
  2229. hostString := msg.Params[0]
  2230. // check host
  2231. hostNet, err := utils.NormalizedNetFromString(hostString)
  2232. if err != nil {
  2233. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2234. return false
  2235. }
  2236. err = server.dlines.RemoveNetwork(hostNet)
  2237. if err != nil {
  2238. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2239. return false
  2240. }
  2241. hostString = utils.NetToNormalizedString(hostNet)
  2242. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2243. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2244. return false
  2245. }
  2246. // UNKLINE <mask>
  2247. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2248. details := client.Details()
  2249. // check oper permissions
  2250. oper := client.Oper()
  2251. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2252. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2253. return false
  2254. }
  2255. // get host
  2256. mask := msg.Params[0]
  2257. mask, err := CanonicalizeMaskWildcard(mask)
  2258. if err != nil {
  2259. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2260. return false
  2261. }
  2262. err = server.klines.RemoveMask(mask)
  2263. if err != nil {
  2264. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2265. return false
  2266. }
  2267. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2268. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2269. return false
  2270. }
  2271. // USER <username> * 0 <realname>
  2272. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2273. if client.registered {
  2274. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2275. return false
  2276. }
  2277. username, realname := msg.Params[0], msg.Params[3]
  2278. if len(realname) == 0 {
  2279. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), client.t("Not enough parameters"))
  2280. return false
  2281. }
  2282. // #843: we accept either: `USER user:pass@clientid` or `USER user@clientid`
  2283. if strudelIndex := strings.IndexByte(username, '@'); strudelIndex != -1 {
  2284. username, rb.session.deviceID = username[:strudelIndex], username[strudelIndex+1:]
  2285. if colonIndex := strings.IndexByte(username, ':'); colonIndex != -1 {
  2286. var password string
  2287. username, password = username[:colonIndex], username[colonIndex+1:]
  2288. err := server.accounts.AuthenticateByPassphrase(client, username, password)
  2289. if err == nil {
  2290. sendSuccessfulAccountAuth(client, rb, false, true)
  2291. } else {
  2292. // this is wrong, but send something for debugging that will show up in a raw transcript
  2293. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed"))
  2294. }
  2295. }
  2296. }
  2297. err := client.SetNames(username, realname, false)
  2298. if err == errInvalidUsername {
  2299. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2300. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2301. if client.preregNick == username {
  2302. client.SetNames("user", realname, false)
  2303. } else {
  2304. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2305. }
  2306. }
  2307. return false
  2308. }
  2309. // USERHOST <nickname>{ <nickname>}
  2310. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2311. returnedClients := make(ClientSet)
  2312. var tl utils.TokenLineBuilder
  2313. tl.Initialize(400, " ")
  2314. for i, nickname := range msg.Params {
  2315. if i >= 10 {
  2316. break
  2317. }
  2318. target := server.clients.Get(nickname)
  2319. if target == nil {
  2320. continue
  2321. }
  2322. // to prevent returning multiple results for a single nick
  2323. if returnedClients.Has(target) {
  2324. continue
  2325. }
  2326. returnedClients.Add(target)
  2327. var isOper, isAway string
  2328. if target.HasMode(modes.Operator) {
  2329. isOper = "*"
  2330. }
  2331. if target.Away() {
  2332. isAway = "-"
  2333. } else {
  2334. isAway = "+"
  2335. }
  2336. details := target.Details()
  2337. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2338. }
  2339. lines := tl.Lines()
  2340. if lines == nil {
  2341. lines = []string{""}
  2342. }
  2343. nick := client.Nick()
  2344. for _, line := range lines {
  2345. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2346. }
  2347. return false
  2348. }
  2349. // USERS [parameters]
  2350. func usersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2351. rb.Add(nil, server.name, ERR_USERSDISABLED, client.Nick(), client.t("USERS has been disabled"))
  2352. return false
  2353. }
  2354. // VERSION
  2355. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2356. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2357. server.RplISupport(client, rb)
  2358. return false
  2359. }
  2360. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2361. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2362. // only allow unregistered clients to use this command
  2363. if client.registered || client.proxiedIP != nil {
  2364. return false
  2365. }
  2366. // process flags
  2367. var secure bool
  2368. if 4 < len(msg.Params) {
  2369. for _, x := range strings.Split(msg.Params[4], " ") {
  2370. // split into key=value
  2371. var key string
  2372. if strings.Contains(x, "=") {
  2373. y := strings.SplitN(x, "=", 2)
  2374. key, _ = y[0], y[1]
  2375. } else {
  2376. key = x
  2377. }
  2378. lkey := strings.ToLower(key)
  2379. if lkey == "tls" || lkey == "secure" {
  2380. // only accept "tls" flag if the gateway's connection to us is secure as well
  2381. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2382. secure = true
  2383. }
  2384. }
  2385. }
  2386. }
  2387. givenPassword := []byte(msg.Params[0])
  2388. for _, info := range server.Config().Server.WebIRC {
  2389. if utils.IPInNets(client.realIP, info.allowedNets) {
  2390. // confirm password and/or fingerprint
  2391. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2392. continue
  2393. }
  2394. if info.Fingerprint != "" && info.Fingerprint != rb.session.certfp {
  2395. continue
  2396. }
  2397. err, quitMsg := client.ApplyProxiedIP(rb.session, net.ParseIP(msg.Params[3]), secure)
  2398. if err != nil {
  2399. client.Quit(quitMsg, rb.session)
  2400. return true
  2401. } else {
  2402. return false
  2403. }
  2404. }
  2405. }
  2406. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2407. return true
  2408. }
  2409. // WHO [<mask> [o]]
  2410. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2411. mask := msg.Params[0]
  2412. var err error
  2413. if mask == "" {
  2414. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2415. return false
  2416. } else if mask[0] == '#' {
  2417. mask, err = CasefoldChannel(msg.Params[0])
  2418. } else {
  2419. mask, err = CanonicalizeMaskWildcard(mask)
  2420. }
  2421. if err != nil {
  2422. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2423. return false
  2424. }
  2425. //TODO(dan): is this used and would I put this param in the Modern doc?
  2426. // if not, can we remove it?
  2427. //var operatorOnly bool
  2428. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2429. // operatorOnly = true
  2430. //}
  2431. isOper := client.HasMode(modes.Operator)
  2432. if mask[0] == '#' {
  2433. // TODO implement wildcard matching
  2434. //TODO(dan): ^ only for opers
  2435. channel := server.channels.Get(mask)
  2436. if channel != nil {
  2437. isJoined := channel.hasClient(client)
  2438. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2439. for _, member := range channel.Members() {
  2440. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2441. client.rplWhoReply(channel, member, rb)
  2442. }
  2443. }
  2444. }
  2445. }
  2446. } else {
  2447. // Construct set of channels the client is in.
  2448. userChannels := make(map[*Channel]bool)
  2449. for _, channel := range client.Channels() {
  2450. userChannels[channel] = true
  2451. }
  2452. // Another client is a friend if they share at least one channel, or they are the same client.
  2453. isFriend := func(otherClient *Client) bool {
  2454. if client == otherClient {
  2455. return true
  2456. }
  2457. for _, channel := range otherClient.Channels() {
  2458. if userChannels[channel] {
  2459. return true
  2460. }
  2461. }
  2462. return false
  2463. }
  2464. for mclient := range server.clients.FindAll(mask) {
  2465. if isOper || !mclient.HasMode(modes.Invisible) || isFriend(mclient) {
  2466. client.rplWhoReply(nil, mclient, rb)
  2467. }
  2468. }
  2469. }
  2470. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2471. return false
  2472. }
  2473. // WHOIS [<target>] <mask>{,<mask>}
  2474. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2475. var masksString string
  2476. //var target string
  2477. if len(msg.Params) > 1 {
  2478. //target = msg.Params[0]
  2479. masksString = msg.Params[1]
  2480. } else {
  2481. masksString = msg.Params[0]
  2482. }
  2483. handleService := func(nick string) bool {
  2484. cfnick, _ := CasefoldName(nick)
  2485. service, ok := OragonoServices[cfnick]
  2486. if !ok {
  2487. return false
  2488. }
  2489. clientNick := client.Nick()
  2490. rb.Add(nil, client.server.name, RPL_WHOISUSER, clientNick, service.Name, service.Name, "localhost", "*", fmt.Sprintf(client.t("Network service, for more info /msg %s HELP"), service.Name))
  2491. // #1080:
  2492. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, clientNick, service.Name, client.t("is a network service"))
  2493. // hehe
  2494. if client.HasMode(modes.TLS) {
  2495. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2496. }
  2497. return true
  2498. }
  2499. if client.HasMode(modes.Operator) {
  2500. for _, mask := range strings.Split(masksString, ",") {
  2501. matches := server.clients.FindAll(mask)
  2502. if len(matches) == 0 && !handleService(mask) {
  2503. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2504. continue
  2505. }
  2506. for mclient := range matches {
  2507. client.getWhoisOf(mclient, rb)
  2508. }
  2509. }
  2510. } else {
  2511. // only get the first request; also require a nick, not a mask
  2512. nick := strings.Split(masksString, ",")[0]
  2513. mclient := server.clients.Get(nick)
  2514. if mclient != nil {
  2515. client.getWhoisOf(mclient, rb)
  2516. } else if !handleService(nick) {
  2517. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2518. }
  2519. // fall through, ENDOFWHOIS is always sent
  2520. }
  2521. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2522. return false
  2523. }
  2524. // WHOWAS <nickname> [<count> [<server>]]
  2525. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2526. nicknames := strings.Split(msg.Params[0], ",")
  2527. // 0 means "all the entries", as does a negative number
  2528. var count int
  2529. if len(msg.Params) > 1 {
  2530. count, _ = strconv.Atoi(msg.Params[1])
  2531. if count < 0 {
  2532. count = 0
  2533. }
  2534. }
  2535. //var target string
  2536. //if len(msg.Params) > 2 {
  2537. // target = msg.Params[2]
  2538. //}
  2539. cnick := client.Nick()
  2540. for _, nickname := range nicknames {
  2541. if len(nickname) == 0 {
  2542. continue
  2543. }
  2544. results := server.whoWas.Find(nickname, count)
  2545. if len(results) == 0 {
  2546. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2547. } else {
  2548. for _, whoWas := range results {
  2549. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2550. }
  2551. }
  2552. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2553. }
  2554. return false
  2555. }
  2556. // ZNC <module> [params]
  2557. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2558. zncModuleHandler(client, msg.Params[0], msg.Params[1:], rb)
  2559. return false
  2560. }
  2561. // fake handler for unknown commands
  2562. func unknownCommandHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2563. rb.Add(nil, server.name, ERR_UNKNOWNCOMMAND, client.Nick(), utils.SafeErrorParam(msg.Command), client.t("Unknown command"))
  2564. return false
  2565. }