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

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