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

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