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

handlers.go 85KB

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