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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923
  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. claims["joined"] = time.Now().Unix() - 100 //TODO(dan): um we need to store when clients joined for reals
  830. claims["cmodes"] = channel.ClientModeStrings(client)
  831. }
  832. }
  833. // we default to a secret of `*`. if you want a real secret setup a service in the config~
  834. service := "*"
  835. secret := "*"
  836. if 1 < len(msg.Params) {
  837. service = strings.ToLower(msg.Params[1])
  838. c := server.Config()
  839. info, exists := c.Server.JwtServices[service]
  840. if !exists {
  841. rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service"))
  842. return false
  843. }
  844. secret = info.Secret
  845. if info.ExpiryInSeconds != 0 {
  846. expireInSeconds = info.ExpiryInSeconds
  847. }
  848. }
  849. claims["exp"] = time.Now().Unix() + expireInSeconds
  850. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  851. tokenString, err := token.SignedString([]byte(secret))
  852. if err == nil {
  853. maxTokenLength := 400
  854. for maxTokenLength < len(tokenString) {
  855. rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, "*", tokenString[:maxTokenLength])
  856. tokenString = tokenString[maxTokenLength:]
  857. }
  858. rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, tokenString)
  859. } else {
  860. rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Could not generate EXTJWT token"))
  861. }
  862. return false
  863. }
  864. // HELP [<query>]
  865. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  866. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  867. if len(argument) < 1 {
  868. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  869. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  870. return false
  871. }
  872. // handle index
  873. if argument == "index" {
  874. client.sendHelp("HELP", server.helpIndexManager.GetIndex(client.Languages(), client.HasMode(modes.Operator)), rb)
  875. return false
  876. }
  877. helpHandler, exists := Help[argument]
  878. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  879. if helpHandler.textGenerator != nil {
  880. client.sendHelp(strings.ToUpper(argument), helpHandler.textGenerator(client), rb)
  881. } else {
  882. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  883. }
  884. } else {
  885. args := msg.Params
  886. args = append(args, client.t("Help not found"))
  887. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  888. }
  889. return false
  890. }
  891. // HISTORY <target> [<limit>]
  892. // e.g., HISTORY #ubuntu 10
  893. // HISTORY me 15
  894. // HISTORY #darwin 1h
  895. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  896. config := server.Config()
  897. if !config.History.Enabled {
  898. rb.Notice(client.t("This command has been disabled by the server administrators"))
  899. return false
  900. }
  901. items, channel, err := easySelectHistory(server, client, msg.Params)
  902. if err == errNoSuchChannel {
  903. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  904. return false
  905. } else if err != nil {
  906. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), msg.Command, client.t("Could not retrieve history"))
  907. return false
  908. }
  909. if len(items) != 0 {
  910. if channel != nil {
  911. channel.replayHistoryItems(rb, items, false)
  912. } else {
  913. client.replayPrivmsgHistory(rb, items, "", true)
  914. }
  915. }
  916. return false
  917. }
  918. // INFO
  919. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  920. nick := client.Nick()
  921. // we do the below so that the human-readable lines in info can be translated.
  922. for _, line := range infoString1 {
  923. rb.Add(nil, server.name, RPL_INFO, nick, line)
  924. }
  925. rb.Add(nil, server.name, RPL_INFO, nick, fmt.Sprintf(client.t("This is Oragono version %s."), SemVer))
  926. if Commit != "" {
  927. rb.Add(nil, server.name, RPL_INFO, nick, fmt.Sprintf(client.t("It was built from git hash %s."), Commit))
  928. }
  929. rb.Add(nil, server.name, RPL_INFO, nick, "")
  930. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Oragono is released under the MIT license."))
  931. rb.Add(nil, server.name, RPL_INFO, nick, "")
  932. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Core Developers:"))
  933. for _, line := range infoString2 {
  934. rb.Add(nil, server.name, RPL_INFO, nick, line)
  935. }
  936. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Former Core Developers:"))
  937. for _, line := range infoString3 {
  938. rb.Add(nil, server.name, RPL_INFO, nick, line)
  939. }
  940. rb.Add(nil, server.name, RPL_INFO, nick, client.t("For a more complete list of contributors, see our changelog:"))
  941. rb.Add(nil, server.name, RPL_INFO, nick, " https://github.com/oragono/oragono/blob/master/CHANGELOG.md")
  942. rb.Add(nil, server.name, RPL_INFO, nick, "")
  943. // show translators for languages other than good ole' regular English
  944. tlines := server.Languages().Translators()
  945. if 0 < len(tlines) {
  946. rb.Add(nil, server.name, RPL_INFO, nick, client.t("Translators:"))
  947. for _, line := range tlines {
  948. rb.Add(nil, server.name, RPL_INFO, nick, " "+strings.Replace(line, "\n", ", ", -1))
  949. }
  950. rb.Add(nil, server.name, RPL_INFO, nick, "")
  951. }
  952. rb.Add(nil, server.name, RPL_ENDOFINFO, nick, client.t("End of /INFO"))
  953. return false
  954. }
  955. // INVITE <nickname> <channel>
  956. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  957. nickname := msg.Params[0]
  958. channelName := msg.Params[1]
  959. target := server.clients.Get(nickname)
  960. if target == nil {
  961. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  962. return false
  963. }
  964. channel := server.channels.Get(channelName)
  965. if channel == nil {
  966. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(channelName), client.t("No such channel"))
  967. return false
  968. }
  969. channel.Invite(target, client, rb)
  970. return false
  971. }
  972. // ISON <nick>{ <nick>}
  973. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  974. var nicks = msg.Params
  975. ison := make([]string, 0, len(msg.Params))
  976. for _, nick := range nicks {
  977. currentNick := server.getCurrentNick(nick)
  978. if currentNick != "" {
  979. ison = append(ison, currentNick)
  980. }
  981. }
  982. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  983. return false
  984. }
  985. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  986. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  987. // kill JOIN 0 requests
  988. if msg.Params[0] == "0" {
  989. rb.Notice(client.t("JOIN 0 is not allowed"))
  990. return false
  991. }
  992. // handle regular JOINs
  993. channels := strings.Split(msg.Params[0], ",")
  994. var keys []string
  995. if len(msg.Params) > 1 {
  996. keys = strings.Split(msg.Params[1], ",")
  997. }
  998. config := server.Config()
  999. oper := client.Oper()
  1000. for i, name := range channels {
  1001. if name == "" {
  1002. continue // #679
  1003. }
  1004. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  1005. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  1006. return false
  1007. }
  1008. var key string
  1009. if len(keys) > i {
  1010. key = keys[i]
  1011. }
  1012. err := server.channels.Join(client, name, key, false, rb)
  1013. if err != nil {
  1014. sendJoinError(client, name, rb, err)
  1015. }
  1016. }
  1017. return false
  1018. }
  1019. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  1020. var errMsg string
  1021. switch err {
  1022. case errInsufficientPrivs:
  1023. errMsg = `Only server operators can create new channels`
  1024. case errConfusableIdentifier:
  1025. errMsg = `That channel name is too close to the name of another channel`
  1026. case errChannelPurged:
  1027. errMsg = err.Error()
  1028. default:
  1029. errMsg = `No such channel`
  1030. }
  1031. rb.Add(nil, client.server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(name), client.t(errMsg))
  1032. }
  1033. // SAJOIN [nick] #channel{,#channel}
  1034. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1035. var target *Client
  1036. var channelString string
  1037. if strings.HasPrefix(msg.Params[0], "#") {
  1038. target = client
  1039. channelString = msg.Params[0]
  1040. } else {
  1041. if len(msg.Params) == 1 {
  1042. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  1043. return false
  1044. } else {
  1045. target = server.clients.Get(msg.Params[0])
  1046. if target == nil {
  1047. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  1048. return false
  1049. }
  1050. channelString = msg.Params[1]
  1051. }
  1052. }
  1053. channels := strings.Split(channelString, ",")
  1054. for _, chname := range channels {
  1055. err := server.channels.Join(target, chname, "", true, rb)
  1056. if err != nil {
  1057. sendJoinError(client, chname, rb, err)
  1058. }
  1059. }
  1060. return false
  1061. }
  1062. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1063. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1064. channels := strings.Split(msg.Params[0], ",")
  1065. users := strings.Split(msg.Params[1], ",")
  1066. if (len(channels) != len(users)) && (len(users) != 1) {
  1067. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1068. return false
  1069. }
  1070. type kickCmd struct {
  1071. channel string
  1072. nick string
  1073. }
  1074. kicks := make([]kickCmd, 0, len(channels))
  1075. for index, channel := range channels {
  1076. if channel == "" {
  1077. continue // #679
  1078. }
  1079. if len(users) == 1 {
  1080. kicks = append(kicks, kickCmd{channel, users[0]})
  1081. } else {
  1082. kicks = append(kicks, kickCmd{channel, users[index]})
  1083. }
  1084. }
  1085. var comment string
  1086. if len(msg.Params) > 2 {
  1087. comment = msg.Params[2]
  1088. }
  1089. for _, kick := range kicks {
  1090. channel := server.channels.Get(kick.channel)
  1091. if channel == nil {
  1092. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1093. continue
  1094. }
  1095. target := server.clients.Get(kick.nick)
  1096. if target == nil {
  1097. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1098. continue
  1099. }
  1100. if comment == "" {
  1101. comment = kick.nick
  1102. }
  1103. channel.Kick(client, target, comment, rb, false)
  1104. }
  1105. return false
  1106. }
  1107. // KILL <nickname> <comment>
  1108. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1109. nickname := msg.Params[0]
  1110. comment := "<no reason supplied>"
  1111. if len(msg.Params) > 1 {
  1112. comment = msg.Params[1]
  1113. }
  1114. target := server.clients.Get(nickname)
  1115. if target == nil {
  1116. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(nickname), client.t("No such nick"))
  1117. return false
  1118. }
  1119. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1120. 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))
  1121. target.SetExitedSnomaskSent()
  1122. target.Quit(quitMsg, nil)
  1123. target.destroy(nil)
  1124. return false
  1125. }
  1126. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1127. // KLINE LIST
  1128. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1129. details := client.Details()
  1130. // check oper permissions
  1131. oper := client.Oper()
  1132. if oper == nil || !oper.Class.Capabilities.Has("local_ban") {
  1133. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1134. return false
  1135. }
  1136. currentArg := 0
  1137. // if they say LIST, we just list the current klines
  1138. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1139. bans := server.klines.AllBans()
  1140. if len(bans) == 0 {
  1141. client.Notice("No KLINEs have been set!")
  1142. }
  1143. for key, info := range bans {
  1144. client.Notice(formatBanForListing(client, key, info))
  1145. }
  1146. return false
  1147. }
  1148. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1149. var andKill bool
  1150. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1151. andKill = true
  1152. currentArg++
  1153. }
  1154. // when setting a ban that covers the oper's current connection, we require them to say
  1155. // "KLINE MYSELF" so that we're sure they really mean it.
  1156. var klineMyself bool
  1157. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1158. klineMyself = true
  1159. currentArg++
  1160. }
  1161. // duration
  1162. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1163. if err != nil {
  1164. duration = 0
  1165. } else {
  1166. currentArg++
  1167. }
  1168. // get mask
  1169. if len(msg.Params) < currentArg+1 {
  1170. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1171. return false
  1172. }
  1173. mask := msg.Params[currentArg]
  1174. currentArg++
  1175. // check mask
  1176. mask, err = CanonicalizeMaskWildcard(mask)
  1177. if err != nil {
  1178. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1179. return false
  1180. }
  1181. matcher, err := utils.CompileGlob(mask, false)
  1182. if err != nil {
  1183. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1184. return false
  1185. }
  1186. for _, clientMask := range client.AllNickmasks() {
  1187. if !klineMyself && matcher.MatchString(clientMask) {
  1188. 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>"))
  1189. return false
  1190. }
  1191. }
  1192. // check remote
  1193. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1194. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1195. return false
  1196. }
  1197. // get oper name
  1198. operName := oper.Name
  1199. if operName == "" {
  1200. operName = server.name
  1201. }
  1202. // get comment(s)
  1203. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1204. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1205. if err != nil {
  1206. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1207. return false
  1208. }
  1209. var snoDescription string
  1210. if duration != 0 {
  1211. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1212. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1213. } else {
  1214. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1215. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1216. }
  1217. server.snomasks.Send(sno.LocalXline, snoDescription)
  1218. var killClient bool
  1219. if andKill {
  1220. var clientsToKill []*Client
  1221. var killedClientNicks []string
  1222. for _, mcl := range server.clients.AllClients() {
  1223. for _, clientMask := range mcl.AllNickmasks() {
  1224. if matcher.MatchString(clientMask) {
  1225. clientsToKill = append(clientsToKill, mcl)
  1226. killedClientNicks = append(killedClientNicks, mcl.nick)
  1227. }
  1228. }
  1229. }
  1230. for _, mcl := range clientsToKill {
  1231. mcl.SetExitedSnomaskSent()
  1232. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1233. if mcl == client {
  1234. killClient = true
  1235. } else {
  1236. // if mcl == client, we kill them below
  1237. mcl.destroy(nil)
  1238. }
  1239. }
  1240. // send snomask
  1241. sort.Strings(killedClientNicks)
  1242. 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, ", ")))
  1243. }
  1244. return killClient
  1245. }
  1246. // LANGUAGE <code>{ <code>}
  1247. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1248. nick := client.Nick()
  1249. alreadyDoneLanguages := make(map[string]bool)
  1250. var appliedLanguages []string
  1251. lm := server.Languages()
  1252. supportedLanguagesCount := lm.Count()
  1253. if supportedLanguagesCount < len(msg.Params) {
  1254. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1255. return false
  1256. }
  1257. for _, value := range msg.Params {
  1258. value = strings.ToLower(value)
  1259. // strip ~ from the language if it has it
  1260. value = strings.TrimPrefix(value, "~")
  1261. // silently ignore empty languages or those with spaces in them
  1262. if len(value) == 0 || strings.Contains(value, " ") {
  1263. continue
  1264. }
  1265. _, exists := lm.Languages[value]
  1266. if !exists {
  1267. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1268. return false
  1269. }
  1270. // if we've already applied the given language, skip it
  1271. _, exists = alreadyDoneLanguages[value]
  1272. if exists {
  1273. continue
  1274. }
  1275. appliedLanguages = append(appliedLanguages, value)
  1276. }
  1277. var langsToSet []string
  1278. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1279. langsToSet = appliedLanguages
  1280. }
  1281. client.SetLanguages(langsToSet)
  1282. params := make([]string, len(appliedLanguages)+2)
  1283. params[0] = nick
  1284. copy(params[1:], appliedLanguages)
  1285. params[len(params)-1] = client.t("Language preferences have been set")
  1286. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1287. return false
  1288. }
  1289. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1290. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1291. config := server.Config()
  1292. if time.Since(client.ctime) < config.Channels.ListDelay && client.Account() == "" && !client.HasMode(modes.Operator) {
  1293. remaining := time.Until(client.ctime.Add(config.Channels.ListDelay))
  1294. 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))
  1295. rb.Add(nil, server.name, RPL_LISTEND, client.Nick(), client.t("End of LIST"))
  1296. return false
  1297. }
  1298. // get channels
  1299. var channels []string
  1300. for _, param := range msg.Params {
  1301. if 0 < len(param) && param[0] == '#' {
  1302. for _, channame := range strings.Split(param, ",") {
  1303. if 0 < len(channame) && channame[0] == '#' {
  1304. channels = append(channels, channame)
  1305. }
  1306. }
  1307. }
  1308. }
  1309. // get elist conditions
  1310. var matcher elistMatcher
  1311. for _, param := range msg.Params {
  1312. if len(param) < 1 {
  1313. continue
  1314. }
  1315. if param[0] == '<' {
  1316. param = param[1:]
  1317. val, err := strconv.Atoi(param)
  1318. if err != nil {
  1319. continue
  1320. }
  1321. matcher.MaxClientsActive = true
  1322. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1323. }
  1324. if param[0] == '>' {
  1325. param = param[1:]
  1326. val, err := strconv.Atoi(param)
  1327. if err != nil {
  1328. continue
  1329. }
  1330. matcher.MinClientsActive = true
  1331. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1332. }
  1333. }
  1334. clientIsOp := client.HasMode(modes.Operator)
  1335. if len(channels) == 0 {
  1336. for _, channel := range server.channels.Channels() {
  1337. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1338. continue
  1339. }
  1340. if matcher.Matches(channel) {
  1341. client.RplList(channel, rb)
  1342. }
  1343. }
  1344. } else {
  1345. // limit regular users to only listing one channel
  1346. if !clientIsOp {
  1347. channels = channels[:1]
  1348. }
  1349. for _, chname := range channels {
  1350. channel := server.channels.Get(chname)
  1351. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1352. if len(chname) > 0 {
  1353. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1354. }
  1355. continue
  1356. }
  1357. if matcher.Matches(channel) {
  1358. client.RplList(channel, rb)
  1359. }
  1360. }
  1361. }
  1362. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1363. return false
  1364. }
  1365. // LUSERS [<mask> [<server>]]
  1366. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1367. server.Lusers(client, rb)
  1368. return false
  1369. }
  1370. // MODE <target> [<modestring> [<mode arguments>...]]
  1371. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1372. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1373. return cmodeHandler(server, client, msg, rb)
  1374. }
  1375. return umodeHandler(server, client, msg, rb)
  1376. }
  1377. // MODE <channel> [<modestring> [<mode arguments>...]]
  1378. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1379. channel := server.channels.Get(msg.Params[0])
  1380. if channel == nil {
  1381. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1382. return false
  1383. }
  1384. var changes modes.ModeChanges
  1385. if 1 < len(msg.Params) {
  1386. // parse out real mode changes
  1387. params := msg.Params[1:]
  1388. var unknown map[rune]bool
  1389. changes, unknown = modes.ParseChannelModeChanges(params...)
  1390. // alert for unknown mode changes
  1391. for char := range unknown {
  1392. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1393. }
  1394. if len(unknown) == 1 && len(changes) == 0 {
  1395. return false
  1396. }
  1397. }
  1398. // process mode changes, include list operations (an empty set of changes does a list)
  1399. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1400. details := client.Details()
  1401. announceCmodeChanges(channel, applied, details.nickMask, details.accountName, details.account, rb)
  1402. return false
  1403. }
  1404. func announceCmodeChanges(channel *Channel, applied modes.ModeChanges, source, accountName, account string, rb *ResponseBuffer) {
  1405. // send out changes
  1406. if len(applied) > 0 {
  1407. message := utils.MakeMessage("")
  1408. changeStrings := applied.Strings()
  1409. for _, changeString := range changeStrings {
  1410. message.Split = append(message.Split, utils.MessagePair{Message: changeString})
  1411. }
  1412. args := append([]string{channel.name}, changeStrings...)
  1413. rb.AddFromClient(message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1414. for _, member := range channel.Members() {
  1415. for _, session := range member.Sessions() {
  1416. if session != rb.session {
  1417. session.sendFromClientInternal(false, message.Time, message.Msgid, source, accountName, nil, "MODE", args...)
  1418. }
  1419. }
  1420. }
  1421. channel.AddHistoryItem(history.Item{
  1422. Type: history.Mode,
  1423. Nick: source,
  1424. AccountName: accountName,
  1425. Message: message,
  1426. }, account)
  1427. }
  1428. }
  1429. // MODE <client> [<modestring> [<mode arguments>...]]
  1430. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1431. cDetails := client.Details()
  1432. target := server.clients.Get(msg.Params[0])
  1433. if target == nil {
  1434. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1435. return false
  1436. }
  1437. targetNick := target.Nick()
  1438. hasPrivs := client == target || msg.Command == "SAMODE"
  1439. if !hasPrivs {
  1440. if len(msg.Params) > 1 {
  1441. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1442. } else {
  1443. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1444. }
  1445. return false
  1446. }
  1447. // applied mode changes
  1448. applied := make(modes.ModeChanges, 0)
  1449. if 1 < len(msg.Params) {
  1450. // parse out real mode changes
  1451. params := msg.Params[1:]
  1452. changes, unknown := modes.ParseUserModeChanges(params...)
  1453. // alert for unknown mode changes
  1454. for char := range unknown {
  1455. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1456. }
  1457. if len(unknown) == 1 && len(changes) == 0 {
  1458. return false
  1459. }
  1460. // apply mode changes
  1461. applied = ApplyUserModeChanges(target, changes, msg.Command == "SAMODE", nil)
  1462. }
  1463. if len(applied) > 0 {
  1464. args := append([]string{targetNick}, applied.Strings()...)
  1465. rb.Add(nil, cDetails.nickMask, "MODE", args...)
  1466. } else if hasPrivs {
  1467. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1468. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1469. masks := server.snomasks.String(target)
  1470. if 0 < len(masks) {
  1471. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1472. }
  1473. }
  1474. }
  1475. return false
  1476. }
  1477. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1478. func (server *Server) getCurrentNick(nick string) (result string) {
  1479. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1480. return service.Name
  1481. } else if iclient := server.clients.Get(nick); iclient != nil {
  1482. return iclient.Nick()
  1483. }
  1484. return ""
  1485. }
  1486. // MONITOR <subcmd> [params...]
  1487. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1488. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1489. if !exists {
  1490. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1491. return false
  1492. }
  1493. return handler(server, client, msg, rb)
  1494. }
  1495. // MONITOR - <target>{,<target>}
  1496. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1497. if len(msg.Params) < 2 {
  1498. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1499. return false
  1500. }
  1501. targets := strings.Split(msg.Params[1], ",")
  1502. for _, target := range targets {
  1503. cfnick, err := CasefoldName(target)
  1504. if err != nil {
  1505. continue
  1506. }
  1507. server.monitorManager.Remove(client, cfnick)
  1508. }
  1509. return false
  1510. }
  1511. // MONITOR + <target>{,<target>}
  1512. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1513. if len(msg.Params) < 2 {
  1514. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1515. return false
  1516. }
  1517. var online []string
  1518. var offline []string
  1519. limits := server.Config().Limits
  1520. targets := strings.Split(msg.Params[1], ",")
  1521. for _, target := range targets {
  1522. // check name length
  1523. if len(target) < 1 || len(targets) > limits.NickLen {
  1524. continue
  1525. }
  1526. // add target
  1527. casefoldedTarget, err := CasefoldName(target)
  1528. if err != nil {
  1529. continue
  1530. }
  1531. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1532. if err == errMonitorLimitExceeded {
  1533. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1534. break
  1535. } else if err != nil {
  1536. continue
  1537. }
  1538. currentNick := server.getCurrentNick(target)
  1539. // add to online / offline lists
  1540. if currentNick != "" {
  1541. online = append(online, currentNick)
  1542. } else {
  1543. offline = append(offline, target)
  1544. }
  1545. }
  1546. if len(online) > 0 {
  1547. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1548. }
  1549. if len(offline) > 0 {
  1550. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1551. }
  1552. return false
  1553. }
  1554. // MONITOR C
  1555. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1556. server.monitorManager.RemoveAll(client)
  1557. return false
  1558. }
  1559. // MONITOR L
  1560. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1561. nick := client.Nick()
  1562. monitorList := server.monitorManager.List(client)
  1563. var nickList []string
  1564. for _, cfnick := range monitorList {
  1565. replynick := cfnick
  1566. currentNick := server.getCurrentNick(cfnick)
  1567. // report the uncasefolded nick if it's available, i.e., the client is online
  1568. if currentNick != "" {
  1569. replynick = currentNick
  1570. }
  1571. nickList = append(nickList, replynick)
  1572. }
  1573. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1574. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1575. }
  1576. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1577. return false
  1578. }
  1579. // MONITOR S
  1580. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1581. var online []string
  1582. var offline []string
  1583. monitorList := server.monitorManager.List(client)
  1584. for _, name := range monitorList {
  1585. currentNick := server.getCurrentNick(name)
  1586. if currentNick != "" {
  1587. online = append(online, currentNick)
  1588. } else {
  1589. offline = append(offline, name)
  1590. }
  1591. }
  1592. if len(online) > 0 {
  1593. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1594. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1595. }
  1596. }
  1597. if len(offline) > 0 {
  1598. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1599. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1600. }
  1601. }
  1602. return false
  1603. }
  1604. // MOTD
  1605. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1606. server.MOTD(client, rb)
  1607. return false
  1608. }
  1609. // NAMES [<channel>{,<channel>} [target]]
  1610. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1611. var channels []string
  1612. if len(msg.Params) > 0 {
  1613. channels = strings.Split(msg.Params[0], ",")
  1614. }
  1615. // TODO: in a post-federation world, process `target` (server to forward request to)
  1616. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1617. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1618. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1619. // with the <channel> parameter set to an asterix character"
  1620. if len(channels) == 0 {
  1621. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1622. return false
  1623. }
  1624. chname := channels[0]
  1625. success := false
  1626. channel := server.channels.Get(chname)
  1627. if channel != nil {
  1628. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1629. channel.Names(client, rb)
  1630. success = true
  1631. }
  1632. }
  1633. if !success { // channel.Names() sends this numeric itself on success
  1634. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1635. }
  1636. return false
  1637. }
  1638. // NICK <nickname>
  1639. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1640. if client.registered {
  1641. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1642. } else {
  1643. client.preregNick = msg.Params[0]
  1644. }
  1645. return false
  1646. }
  1647. // helper to store a batched PRIVMSG in the session object
  1648. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1649. var errorCode, errorMessage string
  1650. defer func() {
  1651. if errorCode != "" {
  1652. if histType != history.Notice {
  1653. rb.Add(nil, server.name, "FAIL", "BATCH", errorCode, errorMessage)
  1654. }
  1655. rb.session.EndMultilineBatch("")
  1656. }
  1657. }()
  1658. if batchTag != rb.session.batch.label {
  1659. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Incorrect batch tag sent")
  1660. return
  1661. } else if len(msg.Params) < 2 {
  1662. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Invalid multiline batch")
  1663. return
  1664. }
  1665. rb.session.batch.command = msg.Command
  1666. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1667. if isConcat && len(msg.Params[1]) == 0 {
  1668. errorCode, errorMessage = "MULTILINE_INVALID", client.t("Cannot send a blank line with the multiline concat tag")
  1669. return
  1670. }
  1671. if !isConcat && len(rb.session.batch.message.Split) != 0 {
  1672. rb.session.batch.lenBytes++ // bill for the newline
  1673. }
  1674. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1675. rb.session.batch.lenBytes += len(msg.Params[1])
  1676. config := server.Config()
  1677. if config.Limits.Multiline.MaxBytes < rb.session.batch.lenBytes {
  1678. errorCode, errorMessage = "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes)
  1679. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1680. errorCode, errorMessage = "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines)
  1681. }
  1682. }
  1683. // NOTICE <target>{,<target>} <message>
  1684. // PRIVMSG <target>{,<target>} <message>
  1685. // TAGMSG <target>{,<target>}
  1686. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1687. histType, err := msgCommandToHistType(msg.Command)
  1688. if err != nil {
  1689. return false
  1690. }
  1691. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1692. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1693. return false
  1694. }
  1695. cnick := client.Nick()
  1696. clientOnlyTags := msg.ClientOnlyTags()
  1697. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1698. // nothing to do
  1699. return false
  1700. }
  1701. targets := strings.Split(msg.Params[0], ",")
  1702. var message string
  1703. if len(msg.Params) > 1 {
  1704. message = msg.Params[1]
  1705. }
  1706. if histType != history.Tagmsg && message == "" {
  1707. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1708. return false
  1709. }
  1710. if rb.session.isTor && utils.IsRestrictedCTCPMessage(message) {
  1711. // note that error replies are never sent for NOTICE
  1712. if histType != history.Notice {
  1713. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1714. }
  1715. return false
  1716. }
  1717. for i, targetString := range targets {
  1718. // max of four targets per privmsg
  1719. if i == maxTargets {
  1720. break
  1721. }
  1722. // each target gets distinct msgids
  1723. splitMsg := utils.MakeMessage(message)
  1724. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1725. }
  1726. return false
  1727. }
  1728. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1729. server := client.server
  1730. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1731. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1732. if len(target) == 0 {
  1733. return
  1734. } else if target[0] == '#' {
  1735. channel := server.channels.Get(target)
  1736. if channel == nil {
  1737. if histType != history.Notice {
  1738. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1739. }
  1740. return
  1741. }
  1742. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1743. } else {
  1744. lowercaseTarget := strings.ToLower(target)
  1745. service, isService := OragonoServices[lowercaseTarget]
  1746. _, isZNC := zncHandlers[lowercaseTarget]
  1747. if histType == history.Privmsg {
  1748. if isService {
  1749. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1750. return
  1751. } else if isZNC {
  1752. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1753. return
  1754. }
  1755. }
  1756. // NOTICE and TAGMSG to services are ignored
  1757. if isService || isZNC {
  1758. return
  1759. }
  1760. user := server.clients.Get(target)
  1761. if user == nil {
  1762. if histType != history.Notice {
  1763. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1764. }
  1765. return
  1766. }
  1767. tDetails := user.Details()
  1768. tnick := tDetails.nick
  1769. details := client.Details()
  1770. nickMaskString := details.nickMask
  1771. accountName := details.accountName
  1772. var deliverySessions []*Session
  1773. // restrict messages appropriately when +R is set
  1774. // intentionally make the sending user think the message went through fine
  1775. allowedPlusR := details.account != "" || !user.HasMode(modes.RegisteredOnly)
  1776. if allowedPlusR {
  1777. deliverySessions = append(deliverySessions, user.Sessions()...)
  1778. }
  1779. // all sessions of the sender, except the originating session, get a copy as well:
  1780. if client != user {
  1781. for _, session := range client.Sessions() {
  1782. if session != rb.session {
  1783. deliverySessions = append(deliverySessions, session)
  1784. }
  1785. }
  1786. }
  1787. for _, session := range deliverySessions {
  1788. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1789. // don't send TAGMSG at all if they don't have the tags cap
  1790. if histType == history.Tagmsg && hasTagsCap {
  1791. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1792. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1793. tagsToSend := tags
  1794. if !hasTagsCap {
  1795. tagsToSend = nil
  1796. }
  1797. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1798. }
  1799. }
  1800. // the originating session may get an echo message:
  1801. if rb.session.capabilities.Has(caps.EchoMessage) {
  1802. hasTagsCap := rb.session.capabilities.Has(caps.MessageTags)
  1803. if histType == history.Tagmsg && hasTagsCap {
  1804. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1805. } else {
  1806. tagsToSend := tags
  1807. if !hasTagsCap {
  1808. tagsToSend = nil
  1809. }
  1810. rb.AddSplitMessageFromClient(nickMaskString, accountName, tagsToSend, command, tnick, message)
  1811. }
  1812. }
  1813. if histType != history.Notice && user.Away() {
  1814. //TODO(dan): possibly implement cooldown of away notifications to users
  1815. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, user.AwayMessage())
  1816. }
  1817. config := server.Config()
  1818. if !config.History.Enabled {
  1819. return
  1820. }
  1821. item := history.Item{
  1822. Type: histType,
  1823. Message: message,
  1824. Nick: nickMaskString,
  1825. AccountName: accountName,
  1826. Tags: tags,
  1827. }
  1828. if !item.IsStorable() || !allowedPlusR {
  1829. return
  1830. }
  1831. targetedItem := item
  1832. targetedItem.Params[0] = tnick
  1833. cStatus, _ := client.historyStatus(config)
  1834. tStatus, _ := user.historyStatus(config)
  1835. // add to ephemeral history
  1836. if cStatus == HistoryEphemeral {
  1837. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1838. client.history.Add(targetedItem)
  1839. }
  1840. if tStatus == HistoryEphemeral && client != user {
  1841. item.CfCorrespondent = details.nickCasefolded
  1842. user.history.Add(item)
  1843. }
  1844. if cStatus == HistoryPersistent || tStatus == HistoryPersistent {
  1845. targetedItem.CfCorrespondent = ""
  1846. server.historyDB.AddDirectMessage(details.nickCasefolded, details.account, tDetails.nickCasefolded, tDetails.account, targetedItem)
  1847. }
  1848. }
  1849. }
  1850. // NPC <target> <sourcenick> <message>
  1851. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1852. target := msg.Params[0]
  1853. fakeSource := msg.Params[1]
  1854. message := msg.Params[2:]
  1855. _, err := CasefoldName(fakeSource)
  1856. if err != nil {
  1857. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1858. return false
  1859. }
  1860. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1861. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1862. return false
  1863. }
  1864. // NPCA <target> <sourcenick> <message>
  1865. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1866. target := msg.Params[0]
  1867. fakeSource := msg.Params[1]
  1868. message := msg.Params[2:]
  1869. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1870. _, err := CasefoldName(fakeSource)
  1871. if err != nil {
  1872. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1873. return false
  1874. }
  1875. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1876. return false
  1877. }
  1878. // OPER <name> [password]
  1879. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1880. if client.HasMode(modes.Operator) {
  1881. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1882. return false
  1883. }
  1884. // must pass at least one check, and all enabled checks
  1885. var checkPassed, checkFailed, passwordFailed bool
  1886. oper := server.GetOperator(msg.Params[0])
  1887. if oper != nil {
  1888. if oper.Fingerprint != "" {
  1889. if oper.Fingerprint == rb.session.certfp {
  1890. checkPassed = true
  1891. } else {
  1892. checkFailed = true
  1893. }
  1894. }
  1895. if !checkFailed && oper.Pass != nil {
  1896. if len(msg.Params) == 1 {
  1897. checkFailed = true
  1898. } else if bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1899. checkFailed = true
  1900. passwordFailed = true
  1901. } else {
  1902. checkPassed = true
  1903. }
  1904. }
  1905. }
  1906. if !checkPassed || checkFailed {
  1907. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1908. // #951: only disconnect them if we actually tried to check a password for them
  1909. if passwordFailed {
  1910. client.Quit(client.t("Password incorrect"), rb.session)
  1911. return true
  1912. } else {
  1913. return false
  1914. }
  1915. }
  1916. if oper != nil {
  1917. applyOper(client, oper, rb)
  1918. }
  1919. return false
  1920. }
  1921. // adds or removes operator status
  1922. // XXX: to add oper, this calls into ApplyUserModeChanges, but to remove oper,
  1923. // ApplyUserModeChanges calls into this, because the commands are asymmetric
  1924. // (/OPER to add, /MODE self -o to remove)
  1925. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  1926. details := client.Details()
  1927. client.SetOper(oper)
  1928. newDetails := client.Details()
  1929. if details.nickMask != newDetails.nickMask {
  1930. client.sendChghost(details.nickMask, newDetails.hostname)
  1931. }
  1932. if oper != nil {
  1933. // set new modes: modes.Operator, plus anything specified in the config
  1934. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1935. modeChanges[0] = modes.ModeChange{
  1936. Mode: modes.Operator,
  1937. Op: modes.Add,
  1938. }
  1939. copy(modeChanges[1:], oper.Modes)
  1940. applied := ApplyUserModeChanges(client, modeChanges, true, oper)
  1941. 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))
  1942. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  1943. args := append([]string{details.nick}, applied.Strings()...)
  1944. rb.Broadcast(nil, client.server.name, "MODE", args...)
  1945. } else {
  1946. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client deopered $c[grey][$r%s$c[grey]]"), newDetails.nickMask))
  1947. }
  1948. for _, session := range client.Sessions() {
  1949. // client may now be unthrottled by the fakelag system
  1950. session.resetFakelag()
  1951. }
  1952. }
  1953. // DEOPER
  1954. func deoperHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1955. // pretend they sent /MODE $nick -o
  1956. fakeModeMsg := ircmsg.MakeMessage(nil, "", "MODE", client.Nick(), "-o")
  1957. return umodeHandler(server, client, fakeModeMsg, rb)
  1958. }
  1959. // PART <channel>{,<channel>} [<reason>]
  1960. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1961. channels := strings.Split(msg.Params[0], ",")
  1962. var reason string
  1963. if len(msg.Params) > 1 {
  1964. reason = msg.Params[1]
  1965. }
  1966. for _, chname := range channels {
  1967. if chname == "" {
  1968. continue // #679
  1969. }
  1970. err := server.channels.Part(client, chname, reason, rb)
  1971. if err == errNoSuchChannel {
  1972. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1973. }
  1974. }
  1975. return false
  1976. }
  1977. // PASS <password>
  1978. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1979. if client.registered {
  1980. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1981. return false
  1982. }
  1983. // only give them one try to run the PASS command (if a server password is set,
  1984. // then all code paths end with this variable being set):
  1985. if rb.session.passStatus != serverPassUnsent {
  1986. return false
  1987. }
  1988. password := msg.Params[0]
  1989. config := server.Config()
  1990. if config.Accounts.LoginViaPassCommand {
  1991. colonIndex := strings.IndexByte(password, ':')
  1992. if colonIndex != -1 && client.Account() == "" {
  1993. account, accountPass := password[:colonIndex], password[colonIndex+1:]
  1994. if strudelIndex := strings.IndexByte(account, '@'); strudelIndex != -1 {
  1995. account, rb.session.deviceID = account[:strudelIndex], account[strudelIndex+1:]
  1996. }
  1997. err := server.accounts.AuthenticateByPassphrase(client, account, accountPass)
  1998. if err == nil {
  1999. sendSuccessfulAccountAuth(client, rb, false, true)
  2000. // login-via-pass-command entails that we do not need to check
  2001. // an actual server password (either no password or skip-server-password)
  2002. rb.session.passStatus = serverPassSuccessful
  2003. return false
  2004. }
  2005. }
  2006. }
  2007. // if login-via-PASS failed for any reason, proceed to try and interpret the
  2008. // provided password as the server password
  2009. serverPassword := config.Server.passwordBytes
  2010. // if no password exists, skip checking
  2011. if serverPassword == nil {
  2012. return false
  2013. }
  2014. // check the provided password
  2015. if bcrypt.CompareHashAndPassword(serverPassword, []byte(password)) == nil {
  2016. rb.session.passStatus = serverPassSuccessful
  2017. } else {
  2018. rb.session.passStatus = serverPassFailed
  2019. }
  2020. // if they failed the check, we'll bounce them later when they try to complete registration
  2021. // note in particular that with skip-server-password, you can give the wrong server
  2022. // password here, then successfully SASL and be admitted
  2023. return false
  2024. }
  2025. // PING [params...]
  2026. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2027. rb.Add(nil, server.name, "PONG", msg.Params...)
  2028. return false
  2029. }
  2030. // PONG [params...]
  2031. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2032. // client gets touched when they send this command, so we don't need to do anything
  2033. return false
  2034. }
  2035. // QUIT [<reason>]
  2036. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2037. reason := "Quit"
  2038. if len(msg.Params) > 0 {
  2039. reason += ": " + msg.Params[0]
  2040. }
  2041. client.Quit(reason, rb.session)
  2042. return true
  2043. }
  2044. // REHASH
  2045. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2046. nick := client.Nick()
  2047. server.logger.Info("server", "REHASH command used by", nick)
  2048. err := server.rehash()
  2049. if err == nil {
  2050. // we used to send RPL_REHASHING here but i don't think it really makes sense
  2051. // in the labeled-response world, since the intent is "rehash in progress" but
  2052. // it won't display until the rehash is actually complete
  2053. // TODO all operators should get a notice of some kind here
  2054. rb.Notice(client.t("Rehash complete"))
  2055. } else {
  2056. rb.Add(nil, server.name, ERR_UNKNOWNERROR, nick, "REHASH", err.Error())
  2057. }
  2058. return false
  2059. }
  2060. // RENAME <oldchan> <newchan> [<reason>]
  2061. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  2062. result = false
  2063. oldName, newName := msg.Params[0], msg.Params[1]
  2064. var reason string
  2065. if 2 < len(msg.Params) {
  2066. reason = msg.Params[2]
  2067. }
  2068. channel := server.channels.Get(oldName)
  2069. if channel == nil {
  2070. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  2071. return false
  2072. }
  2073. if !(channel.ClientIsAtLeast(client, modes.ChannelOperator) || client.HasRoleCapabs("chanreg")) {
  2074. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  2075. return false
  2076. }
  2077. founder := channel.Founder()
  2078. if founder != "" && founder != client.Account() {
  2079. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  2080. return false
  2081. }
  2082. config := server.Config()
  2083. status, _ := channel.historyStatus(config)
  2084. if status == HistoryPersistent {
  2085. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Channels with persistent history cannot be renamed"))
  2086. return false
  2087. }
  2088. // perform the channel rename
  2089. err := server.channels.Rename(oldName, newName)
  2090. if err == errInvalidChannelName {
  2091. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2092. } else if err == errChannelNameInUse {
  2093. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  2094. } else if err != nil {
  2095. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  2096. }
  2097. if err != nil {
  2098. return false
  2099. }
  2100. // send RENAME messages
  2101. clientPrefix := client.NickMaskString()
  2102. for _, mcl := range channel.Members() {
  2103. mDetails := mcl.Details()
  2104. for _, mSession := range mcl.Sessions() {
  2105. targetRb := rb
  2106. targetPrefix := clientPrefix
  2107. if mSession != rb.session {
  2108. targetRb = NewResponseBuffer(mSession)
  2109. targetPrefix = mDetails.nickMask
  2110. }
  2111. if mSession.capabilities.Has(caps.Rename) {
  2112. if reason != "" {
  2113. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  2114. } else {
  2115. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  2116. }
  2117. } else {
  2118. if reason != "" {
  2119. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  2120. } else {
  2121. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  2122. }
  2123. if mSession.capabilities.Has(caps.ExtendedJoin) {
  2124. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  2125. } else {
  2126. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  2127. }
  2128. channel.SendTopic(mcl, targetRb, false)
  2129. channel.Names(mcl, targetRb)
  2130. }
  2131. if mcl != client {
  2132. targetRb.Send(false)
  2133. }
  2134. }
  2135. }
  2136. return false
  2137. }
  2138. // RESUME <token> [timestamp]
  2139. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2140. details := ResumeDetails{
  2141. PresentedToken: msg.Params[0],
  2142. }
  2143. if client.registered {
  2144. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  2145. return false
  2146. }
  2147. if 1 < len(msg.Params) {
  2148. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  2149. if err == nil {
  2150. details.Timestamp = ts
  2151. } else {
  2152. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  2153. }
  2154. }
  2155. rb.session.resumeDetails = &details
  2156. return false
  2157. }
  2158. // SANICK <oldnick> <nickname>
  2159. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2160. targetNick := strings.TrimSpace(msg.Params[0])
  2161. target := server.clients.Get(targetNick)
  2162. if target == nil {
  2163. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2164. return false
  2165. }
  2166. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2167. return false
  2168. }
  2169. // SCENE <target> <message>
  2170. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2171. target := msg.Params[0]
  2172. message := msg.Params[1:]
  2173. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2174. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2175. return false
  2176. }
  2177. // SETNAME <realname>
  2178. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2179. realname := msg.Params[0]
  2180. client.SetRealname(realname)
  2181. details := client.Details()
  2182. // alert friends
  2183. now := time.Now().UTC()
  2184. for session := range client.Friends(caps.SetName) {
  2185. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2186. }
  2187. return false
  2188. }
  2189. // SUMMON [parameters]
  2190. func summonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2191. rb.Add(nil, server.name, ERR_SUMMONDISABLED, client.Nick(), client.t("SUMMON has been disabled"))
  2192. return false
  2193. }
  2194. // TIME
  2195. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2196. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2197. return false
  2198. }
  2199. // TOPIC <channel> [<topic>]
  2200. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2201. channel := server.channels.Get(msg.Params[0])
  2202. if channel == nil {
  2203. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2204. return false
  2205. }
  2206. if len(msg.Params) > 1 {
  2207. channel.SetTopic(client, msg.Params[1], rb)
  2208. } else {
  2209. channel.SendTopic(client, rb, true)
  2210. }
  2211. return false
  2212. }
  2213. // UNDLINE <ip>|<net>
  2214. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2215. // check oper permissions
  2216. oper := client.Oper()
  2217. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2218. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2219. return false
  2220. }
  2221. // get host
  2222. hostString := msg.Params[0]
  2223. // check host
  2224. hostNet, err := utils.NormalizedNetFromString(hostString)
  2225. if err != nil {
  2226. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2227. return false
  2228. }
  2229. err = server.dlines.RemoveNetwork(hostNet)
  2230. if err != nil {
  2231. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2232. return false
  2233. }
  2234. hostString = utils.NetToNormalizedString(hostNet)
  2235. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2236. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2237. return false
  2238. }
  2239. // UNKLINE <mask>
  2240. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2241. details := client.Details()
  2242. // check oper permissions
  2243. oper := client.Oper()
  2244. if oper == nil || !oper.Class.Capabilities.Has("local_unban") {
  2245. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2246. return false
  2247. }
  2248. // get host
  2249. mask := msg.Params[0]
  2250. mask, err := CanonicalizeMaskWildcard(mask)
  2251. if err != nil {
  2252. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2253. return false
  2254. }
  2255. err = server.klines.RemoveMask(mask)
  2256. if err != nil {
  2257. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2258. return false
  2259. }
  2260. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2261. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2262. return false
  2263. }
  2264. // USER <username> * 0 <realname>
  2265. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2266. if client.registered {
  2267. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2268. return false
  2269. }
  2270. username, realname := msg.Params[0], msg.Params[3]
  2271. if len(realname) == 0 {
  2272. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), client.t("Not enough parameters"))
  2273. return false
  2274. }
  2275. // #843: we accept either: `USER user:pass@clientid` or `USER user@clientid`
  2276. if strudelIndex := strings.IndexByte(username, '@'); strudelIndex != -1 {
  2277. username, rb.session.deviceID = username[:strudelIndex], username[strudelIndex+1:]
  2278. if colonIndex := strings.IndexByte(username, ':'); colonIndex != -1 {
  2279. var password string
  2280. username, password = username[:colonIndex], username[colonIndex+1:]
  2281. err := server.accounts.AuthenticateByPassphrase(client, username, password)
  2282. if err == nil {
  2283. sendSuccessfulAccountAuth(client, rb, false, true)
  2284. } else {
  2285. // this is wrong, but send something for debugging that will show up in a raw transcript
  2286. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed"))
  2287. }
  2288. }
  2289. }
  2290. err := client.SetNames(username, realname, false)
  2291. if err == errInvalidUsername {
  2292. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2293. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2294. if client.preregNick == username {
  2295. client.SetNames("user", realname, false)
  2296. } else {
  2297. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2298. }
  2299. }
  2300. return false
  2301. }
  2302. // USERHOST <nickname>{ <nickname>}
  2303. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2304. returnedClients := make(ClientSet)
  2305. var tl utils.TokenLineBuilder
  2306. tl.Initialize(400, " ")
  2307. for i, nickname := range msg.Params {
  2308. if i >= 10 {
  2309. break
  2310. }
  2311. target := server.clients.Get(nickname)
  2312. if target == nil {
  2313. continue
  2314. }
  2315. // to prevent returning multiple results for a single nick
  2316. if returnedClients.Has(target) {
  2317. continue
  2318. }
  2319. returnedClients.Add(target)
  2320. var isOper, isAway string
  2321. if target.HasMode(modes.Operator) {
  2322. isOper = "*"
  2323. }
  2324. if target.Away() {
  2325. isAway = "-"
  2326. } else {
  2327. isAway = "+"
  2328. }
  2329. details := target.Details()
  2330. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2331. }
  2332. lines := tl.Lines()
  2333. if lines == nil {
  2334. lines = []string{""}
  2335. }
  2336. nick := client.Nick()
  2337. for _, line := range lines {
  2338. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2339. }
  2340. return false
  2341. }
  2342. // USERS [parameters]
  2343. func usersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2344. rb.Add(nil, server.name, ERR_USERSDISABLED, client.Nick(), client.t("USERS has been disabled"))
  2345. return false
  2346. }
  2347. // VERSION
  2348. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2349. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2350. server.RplISupport(client, rb)
  2351. return false
  2352. }
  2353. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2354. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2355. // only allow unregistered clients to use this command
  2356. if client.registered || client.proxiedIP != nil {
  2357. return false
  2358. }
  2359. // process flags
  2360. var secure bool
  2361. if 4 < len(msg.Params) {
  2362. for _, x := range strings.Split(msg.Params[4], " ") {
  2363. // split into key=value
  2364. var key string
  2365. if strings.Contains(x, "=") {
  2366. y := strings.SplitN(x, "=", 2)
  2367. key, _ = y[0], y[1]
  2368. } else {
  2369. key = x
  2370. }
  2371. lkey := strings.ToLower(key)
  2372. if lkey == "tls" || lkey == "secure" {
  2373. // only accept "tls" flag if the gateway's connection to us is secure as well
  2374. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2375. secure = true
  2376. }
  2377. }
  2378. }
  2379. }
  2380. givenPassword := []byte(msg.Params[0])
  2381. for _, info := range server.Config().Server.WebIRC {
  2382. if utils.IPInNets(client.realIP, info.allowedNets) {
  2383. // confirm password and/or fingerprint
  2384. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2385. continue
  2386. }
  2387. if info.Fingerprint != "" && info.Fingerprint != rb.session.certfp {
  2388. continue
  2389. }
  2390. err, quitMsg := client.ApplyProxiedIP(rb.session, net.ParseIP(msg.Params[3]), secure)
  2391. if err != nil {
  2392. client.Quit(quitMsg, rb.session)
  2393. return true
  2394. } else {
  2395. return false
  2396. }
  2397. }
  2398. }
  2399. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2400. return true
  2401. }
  2402. // WHO [<mask> [o]]
  2403. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2404. mask := msg.Params[0]
  2405. var err error
  2406. if mask == "" {
  2407. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2408. return false
  2409. } else if mask[0] == '#' {
  2410. mask, err = CasefoldChannel(msg.Params[0])
  2411. } else {
  2412. mask, err = CanonicalizeMaskWildcard(mask)
  2413. }
  2414. if err != nil {
  2415. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2416. return false
  2417. }
  2418. //TODO(dan): is this used and would I put this param in the Modern doc?
  2419. // if not, can we remove it?
  2420. //var operatorOnly bool
  2421. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2422. // operatorOnly = true
  2423. //}
  2424. isOper := client.HasMode(modes.Operator)
  2425. if mask[0] == '#' {
  2426. // TODO implement wildcard matching
  2427. //TODO(dan): ^ only for opers
  2428. channel := server.channels.Get(mask)
  2429. if channel != nil {
  2430. isJoined := channel.hasClient(client)
  2431. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2432. for _, member := range channel.Members() {
  2433. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2434. client.rplWhoReply(channel, member, rb)
  2435. }
  2436. }
  2437. }
  2438. }
  2439. } else {
  2440. // Construct set of channels the client is in.
  2441. userChannels := make(map[*Channel]bool)
  2442. for _, channel := range client.Channels() {
  2443. userChannels[channel] = true
  2444. }
  2445. // Another client is a friend if they share at least one channel, or they are the same client.
  2446. isFriend := func(otherClient *Client) bool {
  2447. if client == otherClient {
  2448. return true
  2449. }
  2450. for _, channel := range otherClient.Channels() {
  2451. if userChannels[channel] {
  2452. return true
  2453. }
  2454. }
  2455. return false
  2456. }
  2457. for mclient := range server.clients.FindAll(mask) {
  2458. if isOper || !mclient.HasMode(modes.Invisible) || isFriend(mclient) {
  2459. client.rplWhoReply(nil, mclient, rb)
  2460. }
  2461. }
  2462. }
  2463. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2464. return false
  2465. }
  2466. // WHOIS [<target>] <mask>{,<mask>}
  2467. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2468. var masksString string
  2469. //var target string
  2470. if len(msg.Params) > 1 {
  2471. //target = msg.Params[0]
  2472. masksString = msg.Params[1]
  2473. } else {
  2474. masksString = msg.Params[0]
  2475. }
  2476. handleService := func(nick string) bool {
  2477. cfnick, _ := CasefoldName(nick)
  2478. service, ok := OragonoServices[cfnick]
  2479. if !ok {
  2480. return false
  2481. }
  2482. clientNick := client.Nick()
  2483. 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))
  2484. // #1080:
  2485. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, clientNick, service.Name, client.t("is a network service"))
  2486. // hehe
  2487. if client.HasMode(modes.TLS) {
  2488. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2489. }
  2490. return true
  2491. }
  2492. if client.HasMode(modes.Operator) {
  2493. for _, mask := range strings.Split(masksString, ",") {
  2494. matches := server.clients.FindAll(mask)
  2495. if len(matches) == 0 && !handleService(mask) {
  2496. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2497. continue
  2498. }
  2499. for mclient := range matches {
  2500. client.getWhoisOf(mclient, rb)
  2501. }
  2502. }
  2503. } else {
  2504. // only get the first request; also require a nick, not a mask
  2505. nick := strings.Split(masksString, ",")[0]
  2506. mclient := server.clients.Get(nick)
  2507. if mclient != nil {
  2508. client.getWhoisOf(mclient, rb)
  2509. } else if !handleService(nick) {
  2510. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2511. }
  2512. // fall through, ENDOFWHOIS is always sent
  2513. }
  2514. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2515. return false
  2516. }
  2517. // WHOWAS <nickname> [<count> [<server>]]
  2518. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2519. nicknames := strings.Split(msg.Params[0], ",")
  2520. // 0 means "all the entries", as does a negative number
  2521. var count int
  2522. if len(msg.Params) > 1 {
  2523. count, _ = strconv.Atoi(msg.Params[1])
  2524. if count < 0 {
  2525. count = 0
  2526. }
  2527. }
  2528. //var target string
  2529. //if len(msg.Params) > 2 {
  2530. // target = msg.Params[2]
  2531. //}
  2532. cnick := client.Nick()
  2533. for _, nickname := range nicknames {
  2534. if len(nickname) == 0 {
  2535. continue
  2536. }
  2537. results := server.whoWas.Find(nickname, count)
  2538. if len(results) == 0 {
  2539. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2540. } else {
  2541. for _, whoWas := range results {
  2542. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2543. }
  2544. }
  2545. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2546. }
  2547. return false
  2548. }
  2549. // ZNC <module> [params]
  2550. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2551. zncModuleHandler(client, msg.Params[0], msg.Params[1:], rb)
  2552. return false
  2553. }
  2554. // fake handler for unknown commands
  2555. func unknownCommandHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2556. rb.Add(nil, server.name, ERR_UNKNOWNCOMMAND, client.Nick(), utils.SafeErrorParam(msg.Command), client.t("Unknown command"))
  2557. return false
  2558. }