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

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