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

handlers.go 85KB

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