Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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