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

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