You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handlers.go 88KB

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