Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

handlers.go 84KB

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