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

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