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