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

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