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

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