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.

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