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

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