123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718 |
- // Copyright (c) 2012-2014 Jeremy Latt
- // Copyright (c) 2014-2015 Edmund Huber
- // Copyright (c) 2016-2018 Daniel Oaks <daniel@danieloaks.net>
- // Copyright (c) 2017-2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
- // released under the MIT license
-
- package irc
-
- import (
- "bytes"
- "encoding/base64"
- "fmt"
- "os"
- "runtime"
- "runtime/debug"
- "runtime/pprof"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/goshuirc/irc-go/ircfmt"
- "github.com/goshuirc/irc-go/ircmatch"
- "github.com/goshuirc/irc-go/ircmsg"
- "github.com/oragono/oragono/irc/caps"
- "github.com/oragono/oragono/irc/custime"
- "github.com/oragono/oragono/irc/history"
- "github.com/oragono/oragono/irc/modes"
- "github.com/oragono/oragono/irc/sno"
- "github.com/oragono/oragono/irc/utils"
- "golang.org/x/crypto/bcrypt"
- )
-
- // ACC [REGISTER|VERIFY] ...
- func accHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // make sure reg is enabled
- if !server.AccountConfig().Registration.Enabled {
- rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, "*", client.t("Account registration is disabled"))
- return false
- }
-
- subcommand := strings.ToLower(msg.Params[0])
-
- if subcommand == "register" {
- return accRegisterHandler(server, client, msg, rb)
- } else if subcommand == "verify" {
- return accVerifyHandler(server, client, msg, rb)
- } else {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", msg.Params[0], client.t("Unknown subcommand"))
- }
-
- return false
- }
-
- // helper function to parse ACC callbacks, e.g., mailto:person@example.com, tel:16505551234
- func parseCallback(spec string, config *AccountConfig) (callbackNamespace string, callbackValue string) {
- callback := strings.ToLower(spec)
- if callback == "*" {
- callbackNamespace = "*"
- } else if strings.Contains(callback, ":") {
- callbackValues := strings.SplitN(callback, ":", 2)
- callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
- } else {
- // "the IRC server MAY choose to use mailto as a default"
- callbackNamespace = "mailto"
- callbackValue = callback
- }
-
- // ensure the callback namespace is valid
- // need to search callback list, maybe look at using a map later?
- for _, name := range config.Registration.EnabledCallbacks {
- if callbackNamespace == name {
- return
- }
- }
- // error value
- callbackNamespace = ""
- return
- }
-
- // ACC REGISTER <accountname> [callback_namespace:]<callback> [cred_type] :<credential>
- func accRegisterHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- nick := client.Nick()
- // clients can't reg new accounts if they're already logged in
- if client.LoggedIntoAccount() {
- rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, nick, "*", client.t("You're already logged into an account"))
- return false
- }
-
- // get and sanitise account name
- account := strings.TrimSpace(msg.Params[1])
- casefoldedAccount, err := CasefoldName(account)
- // probably don't need explicit check for "*" here... but let's do it anyway just to make sure
- if err != nil || msg.Params[1] == "*" {
- rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, nick, account, client.t("Account name is not valid"))
- return false
- }
-
- if len(msg.Params) < 4 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, nick, msg.Command, client.t("Not enough parameters"))
- return false
- }
-
- callbackSpec := msg.Params[2]
- callbackNamespace, callbackValue := parseCallback(callbackSpec, server.AccountConfig())
-
- if callbackNamespace == "" {
- rb.Add(nil, server.name, ERR_REG_INVALID_CALLBACK, nick, account, callbackSpec, client.t("Callback namespace is not supported"))
- return false
- }
-
- // get credential type/value
- var credentialType, credentialValue string
-
- if len(msg.Params) > 4 {
- credentialType = strings.ToLower(msg.Params[3])
- credentialValue = msg.Params[4]
- } else {
- // exactly 4 params
- credentialType = "passphrase" // default from the spec
- credentialValue = msg.Params[3]
- }
-
- // ensure the credential type is valid
- var credentialValid bool
- for _, name := range server.AccountConfig().Registration.EnabledCredentialTypes {
- if credentialType == name {
- credentialValid = true
- }
- }
- if credentialType == "certfp" && client.certfp == "" {
- rb.Add(nil, server.name, ERR_REG_INVALID_CRED_TYPE, nick, credentialType, callbackNamespace, client.t("You are not using a TLS certificate"))
- return false
- }
-
- if !credentialValid {
- rb.Add(nil, server.name, ERR_REG_INVALID_CRED_TYPE, nick, credentialType, callbackNamespace, client.t("Credential type is not supported"))
- return false
- }
-
- var passphrase, certfp string
- if credentialType == "certfp" {
- certfp = client.certfp
- } else if credentialType == "passphrase" {
- passphrase = credentialValue
- }
-
- throttled, remainingTime := client.loginThrottle.Touch()
- if throttled {
- rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, nick, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
- return false
- }
-
- err = server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, certfp)
- if err != nil {
- msg, code := registrationErrorToMessageAndCode(err)
- rb.Add(nil, server.name, code, nick, "ACC", "REGISTER", client.t(msg))
- return false
- }
-
- // automatically complete registration
- if callbackNamespace == "*" {
- err := server.accounts.Verify(client, casefoldedAccount, "")
- if err != nil {
- return false
- }
- sendSuccessfulRegResponse(client, rb, false)
- } else {
- messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s:%s")
- message := fmt.Sprintf(messageTemplate, callbackNamespace, callbackValue)
- rb.Add(nil, server.name, RPL_REG_VERIFICATION_REQUIRED, nick, casefoldedAccount, message)
- }
-
- return false
- }
-
- func registrationErrorToMessageAndCode(err error) (message, numeric string) {
- // default responses: let's be risk-averse about displaying internal errors
- // to the clients, especially for something as sensitive as accounts
- message = `Could not register`
- numeric = ERR_UNKNOWNERROR
- switch err {
- case errAccountAlreadyRegistered, errAccountAlreadyVerified:
- message = err.Error()
- numeric = ERR_ACCOUNT_ALREADY_EXISTS
- case errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists:
- message = err.Error()
- }
- return
- }
-
- // helper function to dispatch messages when a client successfully registers
- func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
- if forNS {
- rb.Notice(client.t("Account created"))
- } else {
- rb.Add(nil, client.server.name, RPL_REGISTRATION_SUCCESS, client.nick, client.AccountName(), client.t("Account created"))
- }
- sendSuccessfulSaslAuth(client, rb, forNS)
- }
-
- // sendSuccessfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
- func sendSuccessfulSaslAuth(client *Client, rb *ResponseBuffer, forNS bool) {
- account := client.AccountName()
-
- if forNS {
- rb.Notice(fmt.Sprintf(client.t("You're now logged in as %s"), client.AccountName()))
- } else {
- rb.Add(nil, client.server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account, fmt.Sprintf(client.t("You are now logged in as %s"), account))
- rb.Add(nil, client.server.name, RPL_SASLSUCCESS, client.nick, client.t("Authentication successful"))
- }
-
- // dispatch account-notify
- for friend := range client.Friends(caps.AccountNotify) {
- friend.Send(nil, client.nickMaskString, "ACCOUNT", account)
- }
-
- client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] logged into account $c[grey][$r%s$c[grey]]"), client.nickMaskString, account))
- }
-
- // ACC VERIFY <accountname> <auth_code>
- func accVerifyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- account := strings.TrimSpace(msg.Params[1])
- err := server.accounts.Verify(client, account, msg.Params[2])
-
- var code string
- var message string
-
- if err == errAccountVerificationInvalidCode {
- code = ERR_ACCOUNT_INVALID_VERIFY_CODE
- message = err.Error()
- } else if err == errAccountAlreadyVerified {
- code = ERR_ACCOUNT_ALREADY_VERIFIED
- message = err.Error()
- } else if err != nil {
- code = ERR_UNKNOWNERROR
- message = errAccountVerificationFailed.Error()
- }
-
- if err == nil {
- sendSuccessfulRegResponse(client, rb, false)
- } else {
- rb.Add(nil, server.name, code, client.nick, account, client.t(message))
- }
-
- return false
- }
-
- // AUTHENTICATE [<mechanism>|<data>|*]
- func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // sasl abort
- if !server.AccountConfig().AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
- rb.Add(nil, server.name, ERR_SASLABORTED, client.nick, client.t("SASL authentication aborted"))
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
- return false
- }
-
- // start new sasl session
- if !client.saslInProgress {
- mechanism := strings.ToUpper(msg.Params[0])
- _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
-
- if mechanismIsEnabled {
- client.saslInProgress = true
- client.saslMechanism = mechanism
- rb.Add(nil, server.name, "AUTHENTICATE", "+")
- } else {
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
- }
-
- return false
- }
-
- // continue existing sasl session
- rawData := msg.Params[0]
-
- if len(rawData) > 400 {
- rb.Add(nil, server.name, ERR_SASLTOOLONG, client.nick, client.t("SASL message too long"))
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
- return false
- } else if len(rawData) == 400 {
- client.saslValue += rawData
- // allow 4 'continuation' lines before rejecting for length
- if len(client.saslValue) > 400*4 {
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Passphrase too long"))
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
- return false
- }
- return false
- }
- if rawData != "+" {
- client.saslValue += rawData
- }
-
- var data []byte
- var err error
- if client.saslValue != "+" {
- data, err = base64.StdEncoding.DecodeString(client.saslValue)
- if err != nil {
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
- return false
- }
- }
-
- // call actual handler
- handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
-
- // like 100% not required, but it's good to be safe I guess
- if !handlerExists {
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
- return false
- }
-
- // let the SASL handler do its thing
- exiting := handler(server, client, client.saslMechanism, data, rb)
-
- // wait 'til SASL is done before emptying the sasl vars
- client.saslInProgress = false
- client.saslMechanism = ""
- client.saslValue = ""
-
- return exiting
- }
-
- // AUTHENTICATE PLAIN
- func authPlainHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
- splitValue := bytes.Split(value, []byte{'\000'})
-
- var accountKey, authzid string
-
- nick := client.Nick()
-
- if len(splitValue) == 3 {
- accountKey = string(splitValue[0])
- authzid = string(splitValue[1])
-
- if accountKey == "" {
- accountKey = authzid
- } else if accountKey != authzid {
- rb.Add(nil, server.name, ERR_SASLFAIL, nick, client.t("SASL authentication failed: authcid and authzid should be the same"))
- return false
- }
- } else {
- rb.Add(nil, server.name, ERR_SASLFAIL, nick, client.t("SASL authentication failed: Invalid auth blob"))
- return false
- }
-
- throttled, remainingTime := client.loginThrottle.Touch()
- if throttled {
- rb.Add(nil, server.name, ERR_SASLFAIL, nick, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
- return false
- }
-
- password := string(splitValue[2])
- err := server.accounts.AuthenticateByPassphrase(client, accountKey, password)
- if err != nil {
- msg := authErrorToMessage(server, err)
- rb.Add(nil, server.name, ERR_SASLFAIL, nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
- return false
- }
-
- sendSuccessfulSaslAuth(client, rb, false)
- return false
- }
-
- func authErrorToMessage(server *Server, err error) (msg string) {
- if err == errAccountDoesNotExist || err == errAccountUnverified || err == errAccountInvalidCredentials {
- msg = err.Error()
- } else {
- server.logger.Error("internal", "sasl authentication failure", err.Error())
- msg = "Unknown"
- }
- return
- }
-
- // AUTHENTICATE EXTERNAL
- func authExternalHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
- if client.certfp == "" {
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
- return false
- }
-
- err := server.accounts.AuthenticateByCertFP(client)
- if err != nil {
- msg := authErrorToMessage(server, err)
- rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
- return false
- }
-
- sendSuccessfulSaslAuth(client, rb, false)
- return false
- }
-
- // AWAY [<message>]
- func awayHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var isAway bool
- var text string
- if len(msg.Params) > 0 {
- isAway = true
- text = msg.Params[0]
- awayLen := server.Limits().AwayLen
- if len(text) > awayLen {
- text = text[:awayLen]
- }
- }
-
- client.SetMode(modes.Away, isAway)
- client.awayMessage = text
-
- var op modes.ModeOp
- if isAway {
- op = modes.Add
- rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
- } else {
- op = modes.Remove
- rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
- }
- //TODO(dan): Should this be sent automagically as part of setting the flag/mode?
- modech := modes.ModeChanges{modes.ModeChange{
- Mode: modes.Away,
- Op: op,
- }}
- rb.Add(nil, server.name, "MODE", client.nick, modech.String())
-
- // dispatch away-notify
- for friend := range client.Friends(caps.AwayNotify) {
- if isAway {
- friend.SendFromClient("", client, nil, "AWAY", client.awayMessage)
- } else {
- friend.SendFromClient("", client, nil, "AWAY")
- }
- }
-
- return false
- }
-
- // CAP <subcmd> [<caps>]
- func capHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- subCommand := strings.ToUpper(msg.Params[0])
- toAdd := caps.NewSet()
- toRemove := caps.NewSet()
- var capString string
-
- badCaps := false
- if len(msg.Params) > 1 {
- capString = msg.Params[1]
- strs := strings.Fields(capString)
- for _, str := range strs {
- remove := false
- if str[0] == '-' {
- str = str[1:]
- remove = true
- }
- capab, err := caps.NameToCapability(str)
- if err != nil || (!remove && !SupportedCapabilities.Has(capab)) {
- badCaps = true
- } else if !remove {
- toAdd.Enable(capab)
- } else {
- toRemove.Enable(capab)
- }
- }
- }
-
- switch subCommand {
- case "LS":
- if !client.registered {
- client.capState = caps.NegotiatingState
- }
- if len(msg.Params) > 1 && msg.Params[1] == "302" {
- client.capVersion = 302
- }
- // weechat 1.4 has a bug here where it won't accept the CAP reply unless it contains
- // the server.name source... otherwise it doesn't respond to the CAP message with
- // anything and just hangs on connection.
- //TODO(dan): limit number of caps and send it multiline in 3.2 style as appropriate.
- rb.Add(nil, server.name, "CAP", client.nick, subCommand, SupportedCapabilities.String(client.capVersion, CapValues))
-
- case "LIST":
- rb.Add(nil, server.name, "CAP", client.nick, subCommand, client.capabilities.String(caps.Cap301, CapValues)) // values not sent on LIST so force 3.1
-
- case "REQ":
- if !client.registered {
- client.capState = caps.NegotiatingState
- }
-
- // make sure all capabilities actually exist
- if badCaps {
- rb.Add(nil, server.name, "CAP", client.nick, "NAK", capString)
- return false
- }
- client.capabilities.Union(toAdd)
- client.capabilities.Subtract(toRemove)
- rb.Add(nil, server.name, "CAP", client.nick, "ACK", capString)
-
- // if this is the first time the client is requesting a resume token,
- // send it to them
- if toAdd.Has(caps.Resume) {
- token, err := client.generateResumeToken()
- if err == nil {
- rb.Add(nil, server.name, "RESUME", "TOKEN", token)
- }
- }
-
- case "END":
- if !client.registered {
- client.capState = caps.NegotiatedState
- }
-
- default:
- rb.Add(nil, server.name, ERR_INVALIDCAPCMD, client.nick, subCommand, client.t("Invalid CAP subcommand"))
- }
- return false
- }
-
- // CHATHISTORY <target> <preposition> <query> [<limit>]
- // e.g., CHATHISTORY #ircv3 AFTER id=ytNBbt565yt4r3err3 10
- // CHATHISTORY <target> BETWEEN <query> <query> <direction> [<limit>]
- // e.g., CHATHISTORY #ircv3 BETWEEN timestamp=YYYY-MM-DDThh:mm:ss.sssZ timestamp=YYYY-MM-DDThh:mm:ss.sssZ + 100
- func chathistoryHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (exiting bool) {
- config := server.Config()
- // batch type is chathistory; send an empty batch if necessary
- rb.InitializeBatch("chathistory", true)
-
- var items []history.Item
- success := false
- var hist *history.Buffer
- var channel *Channel
- defer func() {
- if success {
- if channel == nil {
- client.replayPrivmsgHistory(rb, items, true)
- } else {
- channel.replayHistoryItems(rb, items)
- }
- }
- rb.Send(true) // terminate the chathistory batch
- if success && len(items) > 0 {
- return
- }
- newRb := NewResponseBuffer(client)
- newRb.Label = rb.Label // same label, new batch
- // TODO: send `WARN CHATHISTORY MAX_MESSAGES_EXCEEDED` when appropriate
- if !success {
- newRb.Add(nil, server.name, "ERR", "CHATHISTORY", "NEED_MORE_PARAMS")
- } else if hist == nil {
- newRb.Add(nil, server.name, "ERR", "CHATHISTORY", "NO_SUCH_CHANNEL")
- } else if len(items) == 0 {
- newRb.Add(nil, server.name, "ERR", "CHATHISTORY", "NO_TEXT_TO_SEND")
- }
- newRb.Send(true)
- }()
-
- target := msg.Params[0]
- channel = server.channels.Get(target)
- if channel != nil {
- hist = &channel.history
- } else {
- targetClient := server.clients.Get(target)
- if targetClient != nil {
- myAccount := client.Account()
- targetAccount := targetClient.Account()
- if myAccount != "" && targetAccount != "" && myAccount == targetAccount {
- hist = targetClient.history
- }
- }
- }
- if hist == nil {
- return
- }
-
- preposition := strings.ToLower(msg.Params[1])
-
- parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
- err = errInvalidParams
- pieces := strings.SplitN(param, "=", 2)
- if len(pieces) < 2 {
- return
- }
- identifier, value := strings.ToLower(pieces[0]), pieces[1]
- if identifier == "id" {
- msgid, err = value, nil
- return
- } else if identifier == "timestamp" {
- timestamp, err = time.Parse(IRCv3TimestampFormat, value)
- return
- }
- return
- }
-
- maxChathistoryLimit := config.History.ChathistoryMax
- if maxChathistoryLimit == 0 {
- return
- }
- parseHistoryLimit := func(paramIndex int) (limit int) {
- if len(msg.Params) < (paramIndex + 1) {
- return maxChathistoryLimit
- }
- limit, err := strconv.Atoi(msg.Params[paramIndex])
- if err != nil || limit == 0 || limit > maxChathistoryLimit {
- limit = maxChathistoryLimit
- }
- return
- }
-
- // TODO: as currently implemented, almost all of thes queries are worst-case O(n)
- // in the number of stored history entries. Every one of them can be made O(1)
- // if necessary, without too much difficulty. Some ideas:
- // * Ensure that the ring buffer is sorted by time, enabling binary search for times
- // * Maintain a map from msgid to position in the ring buffer
-
- if preposition == "between" {
- if len(msg.Params) >= 5 {
- startMsgid, startTimestamp, startErr := parseQueryParam(msg.Params[2])
- endMsgid, endTimestamp, endErr := parseQueryParam(msg.Params[3])
- ascending := msg.Params[4] == "+"
- limit := parseHistoryLimit(5)
- if startErr != nil || endErr != nil {
- success = false
- } else if startMsgid != "" && endMsgid != "" {
- inInterval := false
- matches := func(item history.Item) (result bool) {
- result = inInterval
- if item.HasMsgid(startMsgid) {
- if ascending {
- inInterval = true
- } else {
- inInterval = false
- return false // interval is exclusive
- }
- } else if item.HasMsgid(endMsgid) {
- if ascending {
- inInterval = false
- return false
- } else {
- inInterval = true
- }
- }
- return
- }
- items = hist.Match(matches, ascending, limit)
- success = true
- } else if !startTimestamp.IsZero() && !endTimestamp.IsZero() {
- items, _ = hist.Between(startTimestamp, endTimestamp, ascending, limit)
- if !ascending {
- history.Reverse(items)
- }
- success = true
- }
- // else: mismatched params, success = false, fail
- }
- return
- }
-
- // before, after, latest, around
- queryParam := msg.Params[2]
- msgid, timestamp, err := parseQueryParam(queryParam)
- limit := parseHistoryLimit(3)
- before := false
- switch preposition {
- case "before":
- before = true
- fallthrough
- case "after":
- var matches history.Predicate
- if err != nil {
- break
- } else if msgid != "" {
- inInterval := false
- matches = func(item history.Item) (result bool) {
- result = inInterval
- if item.HasMsgid(msgid) {
- inInterval = true
- }
- return
- }
- } else {
- matches = func(item history.Item) bool {
- return before == item.Time.Before(timestamp)
- }
- }
- items = hist.Match(matches, !before, limit)
- success = true
- case "latest":
- if queryParam == "*" {
- items = hist.Latest(limit)
- } else if err != nil {
- break
- } else {
- var matches history.Predicate
- if msgid != "" {
- shouldStop := false
- matches = func(item history.Item) bool {
- if shouldStop {
- return false
- }
- shouldStop = item.HasMsgid(msgid)
- return !shouldStop
- }
- } else {
- matches = func(item history.Item) bool {
- return item.Time.After(timestamp)
- }
- }
- items = hist.Match(matches, false, limit)
- }
- success = true
- case "around":
- if err != nil {
- break
- }
- var initialMatcher history.Predicate
- if msgid != "" {
- inInterval := false
- initialMatcher = func(item history.Item) (result bool) {
- if inInterval {
- return true
- } else {
- inInterval = item.HasMsgid(msgid)
- return inInterval
- }
- }
- } else {
- initialMatcher = func(item history.Item) (result bool) {
- return item.Time.Before(timestamp)
- }
- }
- var halfLimit int
- halfLimit = (limit + 1) / 2
- firstPass := hist.Match(initialMatcher, false, halfLimit)
- if len(firstPass) > 0 {
- timeWindowStart := firstPass[0].Time
- items = hist.Match(func(item history.Item) bool {
- return item.Time.Equal(timeWindowStart) || item.Time.After(timeWindowStart)
- }, true, limit)
- }
- success = true
- }
-
- return
- }
-
- // DEBUG <subcmd>
- func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- param := strings.ToUpper(msg.Params[0])
-
- switch param {
- case "GCSTATS":
- stats := debug.GCStats{
- Pause: make([]time.Duration, 10),
- PauseQuantiles: make([]time.Duration, 5),
- }
- debug.ReadGCStats(&stats)
-
- rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
- rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
- rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
- rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
- rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
- rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
- rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
- rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
-
- case "NUMGOROUTINE":
- count := runtime.NumGoroutine()
- rb.Notice(fmt.Sprintf("num goroutines: %d", count))
-
- case "PROFILEHEAP":
- profFile := "oragono.mprof"
- file, err := os.Create(profFile)
- if err != nil {
- rb.Notice(fmt.Sprintf("error: %s", err))
- break
- }
- defer file.Close()
- pprof.Lookup("heap").WriteTo(file, 0)
- rb.Notice(fmt.Sprintf("written to %s", profFile))
-
- case "STARTCPUPROFILE":
- profFile := "oragono.prof"
- file, err := os.Create(profFile)
- if err != nil {
- rb.Notice(fmt.Sprintf("error: %s", err))
- break
- }
- if err := pprof.StartCPUProfile(file); err != nil {
- defer file.Close()
- rb.Notice(fmt.Sprintf("error: %s", err))
- break
- }
-
- rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
-
- case "STOPCPUPROFILE":
- pprof.StopCPUProfile()
- rb.Notice(fmt.Sprintf("CPU profiling stopped"))
- }
- return false
- }
-
- // helper for parsing the reason args to DLINE and KLINE
- func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
- reason = "No reason given"
- operReason = ""
- if len(params) > currentArg {
- reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
- if len(reasons) == 1 {
- reason = strings.TrimSpace(reasons[0])
- } else if len(reasons) == 2 {
- reason = strings.TrimSpace(reasons[0])
- operReason = strings.TrimSpace(reasons[1])
- }
- }
- return
- }
-
- func formatBanForListing(client *Client, key string, info IPBanInfo) string {
- desc := info.Reason
- if info.OperReason != "" && info.OperReason != info.Reason {
- desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
- }
- if info.Duration != 0 {
- desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
- }
- return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
- }
-
- // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
- // DLINE LIST
- func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // check oper permissions
- oper := client.Oper()
- if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
- rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
- return false
- }
-
- currentArg := 0
-
- // if they say LIST, we just list the current dlines
- if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
- bans := server.dlines.AllBans()
-
- if len(bans) == 0 {
- rb.Notice(client.t("No DLINEs have been set!"))
- }
-
- for key, info := range bans {
- client.Notice(formatBanForListing(client, key, info))
- }
-
- return false
- }
-
- // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
- var andKill bool
- if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
- andKill = true
- currentArg++
- }
-
- // when setting a ban that covers the oper's current connection, we require them to say
- // "DLINE MYSELF" so that we're sure they really mean it.
- var dlineMyself bool
- if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
- dlineMyself = true
- currentArg++
- }
-
- // duration
- duration, err := custime.ParseDuration(msg.Params[currentArg])
- if err != nil {
- duration = 0
- } else {
- currentArg++
- }
-
- // get host
- if len(msg.Params) < currentArg+1 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
- return false
- }
- hostString := msg.Params[currentArg]
- currentArg++
-
- // check host
- hostNet, err := utils.NormalizedNetFromString(hostString)
-
- if err != nil {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
- return false
- }
-
- if !dlineMyself && hostNet.Contains(client.IP()) {
- 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>"))
- return false
- }
-
- // check remote
- if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
- return false
- }
-
- // get comment(s)
- reason, operReason := getReasonsFromParams(msg.Params, currentArg)
-
- operName := oper.Name
- if operName == "" {
- operName = server.name
- }
-
- err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
-
- if err != nil {
- rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
- return false
- }
-
- var snoDescription string
- hostString = utils.NetToNormalizedString(hostNet)
- if duration != 0 {
- rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
- snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
- } else {
- rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
- snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
- }
- server.snomasks.Send(sno.LocalXline, snoDescription)
-
- var killClient bool
- if andKill {
- var clientsToKill []*Client
- var killedClientNicks []string
-
- for _, mcl := range server.clients.AllClients() {
- if hostNet.Contains(mcl.IP()) {
- clientsToKill = append(clientsToKill, mcl)
- killedClientNicks = append(killedClientNicks, mcl.nick)
- }
- }
-
- for _, mcl := range clientsToKill {
- mcl.exitedSnomaskSent = true
- mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
- if mcl == client {
- killClient = true
- } else {
- // if mcl == client, we kill them below
- mcl.destroy(false)
- }
- }
-
- // send snomask
- sort.Strings(killedClientNicks)
- 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, ", ")))
- }
-
- return killClient
- }
-
- // HELP [<query>]
- func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
-
- if len(argument) < 1 {
- client.sendHelp("HELPOP", client.t(`HELPOP <argument>
-
- Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
- return false
- }
-
- // handle index
- if argument == "index" {
- if client.HasMode(modes.Operator) {
- client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndexOpers), rb)
- } else {
- client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndex), rb)
- }
- return false
- }
-
- helpHandler, exists := Help[argument]
-
- if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
- if helpHandler.textGenerator != nil {
- client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.textGenerator(client)), rb)
- } else {
- client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
- }
- } else {
- args := msg.Params
- args = append(args, client.t("Help not found"))
- rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
- }
-
- return false
- }
-
- // HISTORY <target> [<limit>]
- // e.g., HISTORY #ubuntu 10
- // HISTORY me 15
- func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- config := server.Config()
- target := msg.Params[0]
- var hist *history.Buffer
- channel := server.channels.Get(target)
- if channel != nil {
- hist = &channel.history
- } else {
- if strings.ToLower(target) == "me" {
- hist = client.history
- } else {
- targetClient := server.clients.Get(target)
- if targetClient != nil {
- myAccount, targetAccount := client.Account(), targetClient.Account()
- if myAccount != "" && targetAccount != "" && myAccount == targetAccount {
- hist = targetClient.history
- }
- }
- }
- }
-
- if hist == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), target, client.t("No such channel"))
- return false
- }
-
- limit := 10
- maxChathistoryLimit := config.History.ChathistoryMax
- if len(msg.Params) > 1 {
- providedLimit, err := strconv.Atoi(msg.Params[1])
- if providedLimit > maxChathistoryLimit {
- providedLimit = maxChathistoryLimit
- }
- if err == nil && providedLimit != 0 {
- limit = providedLimit
- }
- }
-
- items := hist.Latest(limit)
-
- if channel != nil {
- channel.replayHistoryItems(rb, items)
- } else {
- client.replayPrivmsgHistory(rb, items, true)
- }
-
- return false
- }
-
- // INFO
- func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // we do the below so that the human-readable lines in info can be translated.
- for _, line := range infoString1 {
- rb.Add(nil, server.name, RPL_INFO, client.nick, line)
- }
- rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
- rb.Add(nil, server.name, RPL_INFO, client.nick, "")
- rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Thanks to Jeremy Latt for founding Ergonomadic, the project this is based on")+" <3")
- rb.Add(nil, server.name, RPL_INFO, client.nick, "")
- rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
- for _, line := range infoString2 {
- rb.Add(nil, server.name, RPL_INFO, client.nick, line)
- }
- rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
- for _, line := range infoString3 {
- rb.Add(nil, server.name, RPL_INFO, client.nick, line)
- }
- // show translators for languages other than good ole' regular English
- tlines := server.languages.Translators()
- if 0 < len(tlines) {
- rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
- for _, line := range tlines {
- rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
- }
- rb.Add(nil, server.name, RPL_INFO, client.nick, "")
- }
- rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
- return false
- }
-
- // INVITE <nickname> <channel>
- func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- nickname := msg.Params[0]
- channelName := msg.Params[1]
-
- casefoldedNickname, err := CasefoldName(nickname)
- target := server.clients.Get(casefoldedNickname)
- if err != nil || target == nil {
- rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
- return false
- }
-
- casefoldedChannelName, err := CasefoldChannel(channelName)
- channel := server.channels.Get(casefoldedChannelName)
- if err != nil || channel == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, channelName, client.t("No such channel"))
- return false
- }
-
- channel.Invite(target, client, rb)
- return false
- }
-
- // ISON <nick>{ <nick>}
- func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var nicks = msg.Params
-
- var err error
- var casefoldedNick string
- ison := make([]string, 0)
- for _, nick := range nicks {
- casefoldedNick, err = CasefoldName(nick)
- if err != nil {
- continue
- }
- if iclient := server.clients.Get(casefoldedNick); iclient != nil {
- ison = append(ison, iclient.nick)
- }
- }
-
- rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(nicks, " "))
- return false
- }
-
- // JOIN <channel>{,<channel>} [<key>{,<key>}]
- func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // kill JOIN 0 requests
- if msg.Params[0] == "0" {
- rb.Notice(client.t("JOIN 0 is not allowed"))
- return false
- }
-
- // handle regular JOINs
- channels := strings.Split(msg.Params[0], ",")
- var keys []string
- if len(msg.Params) > 1 {
- keys = strings.Split(msg.Params[1], ",")
- }
-
- for i, name := range channels {
- var key string
- if len(keys) > i {
- key = keys[i]
- }
- err := server.channels.Join(client, name, key, false, rb)
- if err == errNoSuchChannel {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), name, client.t("No such channel"))
- }
- }
- return false
- }
-
- // SAJOIN [nick] #channel{,#channel}
- func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var target *Client
- var channelString string
- if strings.HasPrefix(msg.Params[0], "#") {
- target = client
- channelString = msg.Params[0]
- } else {
- if len(msg.Params) == 1 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "KICK", client.t("Not enough parameters"))
- return false
- } else {
- target = server.clients.Get(msg.Params[0])
- if target == nil {
- rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), msg.Params[0], "No such nick")
- return false
- }
- channelString = msg.Params[1]
- rb = NewResponseBuffer(target)
- }
- }
-
- channels := strings.Split(channelString, ",")
- for _, chname := range channels {
- server.channels.Join(target, chname, "", true, rb)
- }
- if client != target {
- rb.Send(false)
- }
- return false
- }
-
- // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
- func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- channels := strings.Split(msg.Params[0], ",")
- users := strings.Split(msg.Params[1], ",")
- if (len(channels) != len(users)) && (len(users) != 1) {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
- return false
- }
-
- var kicks [][]string
- for index, channel := range channels {
- if len(users) == 1 {
- kicks = append(kicks, []string{channel, users[0]})
- } else {
- kicks = append(kicks, []string{channel, users[index]})
- }
- }
-
- var comment string
- if len(msg.Params) > 2 {
- comment = msg.Params[2]
- }
- for _, info := range kicks {
- chname := info[0]
- nickname := info[1]
- casefoldedChname, err := CasefoldChannel(chname)
- channel := server.channels.Get(casefoldedChname)
- if err != nil || channel == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
- continue
- }
-
- casefoldedNickname, err := CasefoldName(nickname)
- target := server.clients.Get(casefoldedNickname)
- if err != nil || target == nil {
- rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
- continue
- }
-
- if comment == "" {
- comment = nickname
- }
- channel.Kick(client, target, comment, rb)
- }
- return false
- }
-
- // KILL <nickname> <comment>
- func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- nickname := msg.Params[0]
- comment := "<no reason supplied>"
- if len(msg.Params) > 1 {
- comment = msg.Params[1]
- }
-
- casefoldedNickname, err := CasefoldName(nickname)
- target := server.clients.Get(casefoldedNickname)
- if err != nil || target == nil {
- rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
- return false
- }
-
- quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
-
- 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))
- target.exitedSnomaskSent = true
-
- target.Quit(quitMsg)
- target.destroy(false)
- return false
- }
-
- // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
- // KLINE LIST
- func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // check oper permissions
- oper := client.Oper()
- if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
- rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
- return false
- }
-
- currentArg := 0
-
- // if they say LIST, we just list the current klines
- if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
- bans := server.klines.AllBans()
-
- if len(bans) == 0 {
- client.Notice("No KLINEs have been set!")
- }
-
- for key, info := range bans {
- client.Notice(formatBanForListing(client, key, info))
- }
-
- return false
- }
-
- // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
- var andKill bool
- if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
- andKill = true
- currentArg++
- }
-
- // when setting a ban that covers the oper's current connection, we require them to say
- // "KLINE MYSELF" so that we're sure they really mean it.
- var klineMyself bool
- if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
- klineMyself = true
- currentArg++
- }
-
- // duration
- duration, err := custime.ParseDuration(msg.Params[currentArg])
- if err != nil {
- duration = 0
- } else {
- currentArg++
- }
-
- // get mask
- if len(msg.Params) < currentArg+1 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
- return false
- }
- mask := strings.ToLower(msg.Params[currentArg])
- currentArg++
-
- // check mask
- if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
- mask = mask + "!*@*"
- } else if !strings.Contains(mask, "@") {
- mask = mask + "@*"
- }
-
- matcher := ircmatch.MakeMatch(mask)
-
- for _, clientMask := range client.AllNickmasks() {
- if !klineMyself && matcher.Match(clientMask) {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("This ban matches you. To KLINE yourself, you must use the command: /KLINE MYSELF <arguments>"))
- return false
- }
- }
-
- // check remote
- if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
- return false
- }
-
- // get oper name
- operName := oper.Name
- if operName == "" {
- operName = server.name
- }
-
- // get comment(s)
- reason, operReason := getReasonsFromParams(msg.Params, currentArg)
-
- err = server.klines.AddMask(mask, duration, reason, operReason, operName)
- if err != nil {
- rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
- return false
- }
-
- var snoDescription string
- if duration != 0 {
- rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
- snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), client.nick, operName, duration.String(), mask)
- } else {
- rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
- snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), client.nick, operName, mask)
- }
- server.snomasks.Send(sno.LocalXline, snoDescription)
-
- var killClient bool
- if andKill {
- var clientsToKill []*Client
- var killedClientNicks []string
-
- for _, mcl := range server.clients.AllClients() {
- for _, clientMask := range mcl.AllNickmasks() {
- if matcher.Match(clientMask) {
- clientsToKill = append(clientsToKill, mcl)
- killedClientNicks = append(killedClientNicks, mcl.nick)
- }
- }
- }
-
- for _, mcl := range clientsToKill {
- mcl.exitedSnomaskSent = true
- mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
- if mcl == client {
- killClient = true
- } else {
- // if mcl == client, we kill them below
- mcl.destroy(false)
- }
- }
-
- // send snomask
- sort.Strings(killedClientNicks)
- server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s [%s] killed %d clients with a KLINE $c[grey][$r%s$c[grey]]"), client.nick, operName, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
- }
-
- return killClient
- }
-
- // LANGUAGE <code>{ <code>}
- func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- alreadyDoneLanguages := make(map[string]bool)
- var appliedLanguages []string
-
- supportedLanguagesCount := server.languages.Count()
- if supportedLanguagesCount < len(msg.Params) {
- rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, client.nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
- return false
- }
-
- for _, value := range msg.Params {
- value = strings.ToLower(value)
- // strip ~ from the language if it has it
- value = strings.TrimPrefix(value, "~")
-
- // silently ignore empty languages or those with spaces in them
- if len(value) == 0 || strings.Contains(value, " ") {
- continue
- }
-
- _, exists := server.languages.Info[value]
- if !exists {
- rb.Add(nil, client.server.name, ERR_NOLANGUAGE, client.nick, client.t("Languages are not supported by this server"))
- return false
- }
-
- // if we've already applied the given language, skip it
- _, exists = alreadyDoneLanguages[value]
- if exists {
- continue
- }
-
- appliedLanguages = append(appliedLanguages, value)
- }
-
- client.stateMutex.Lock()
- if len(appliedLanguages) == 1 && appliedLanguages[0] == "en" {
- // premature optimisation ahoy!
- client.languages = []string{}
- } else {
- client.languages = appliedLanguages
- }
- client.stateMutex.Unlock()
-
- params := []string{client.nick}
- for _, lang := range appliedLanguages {
- params = append(params, lang)
- }
- params = append(params, client.t("Language preferences have been set"))
-
- rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
-
- return false
- }
-
- // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
- func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // get channels
- var channels []string
- for _, param := range msg.Params {
- if 0 < len(param) && param[0] == '#' {
- for _, channame := range strings.Split(param, ",") {
- if 0 < len(channame) && channame[0] == '#' {
- channels = append(channels, channame)
- }
- }
- }
- }
-
- // get elist conditions
- var matcher elistMatcher
- for _, param := range msg.Params {
- if len(param) < 1 {
- continue
- }
-
- if param[0] == '<' {
- param = param[1:]
- val, err := strconv.Atoi(param)
- if err != nil {
- continue
- }
- matcher.MaxClientsActive = true
- matcher.MaxClients = val - 1 // -1 because < means less than the given number
- }
- if param[0] == '>' {
- param = param[1:]
- val, err := strconv.Atoi(param)
- if err != nil {
- continue
- }
- matcher.MinClientsActive = true
- matcher.MinClients = val + 1 // +1 because > means more than the given number
- }
- }
-
- clientIsOp := client.HasMode(modes.Operator)
- if len(channels) == 0 {
- for _, channel := range server.channels.Channels() {
- if !clientIsOp && channel.flags.HasMode(modes.Secret) {
- continue
- }
- if matcher.Matches(channel) {
- client.RplList(channel, rb)
- }
- }
- } else {
- // limit regular users to only listing one channel
- if !clientIsOp {
- channels = channels[:1]
- }
-
- for _, chname := range channels {
- casefoldedChname, err := CasefoldChannel(chname)
- channel := server.channels.Get(casefoldedChname)
- if err != nil || channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
- if len(chname) > 0 {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
- }
- continue
- }
- if matcher.Matches(channel) {
- client.RplList(channel, rb)
- }
- }
- }
- rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
- return false
- }
-
- // LUSERS [<mask> [<server>]]
- func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- //TODO(vegax87) Fix network statistics and additional parameters
- totalCount, invisibleCount, operCount := server.stats.GetStats()
-
- rb.Add(nil, server.name, RPL_LUSERCLIENT, client.nick, fmt.Sprintf(client.t("There are %[1]d users and %[2]d invisible on %[3]d server(s)"), totalCount-invisibleCount, invisibleCount, 1))
- rb.Add(nil, server.name, RPL_LUSEROP, client.nick, strconv.Itoa(operCount), client.t("IRC Operators online"))
- rb.Add(nil, server.name, RPL_LUSERCHANNELS, client.nick, strconv.Itoa(server.channels.Len()), client.t("channels formed"))
- rb.Add(nil, server.name, RPL_LUSERME, client.nick, fmt.Sprintf(client.t("I have %[1]d clients and %[2]d servers"), totalCount, 1))
-
- return false
- }
-
- // MODE <target> [<modestring> [<mode arguments>...]]
- func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- _, errChan := CasefoldChannel(msg.Params[0])
-
- if errChan == nil {
- return cmodeHandler(server, client, msg, rb)
- }
- return umodeHandler(server, client, msg, rb)
- }
-
- // MODE <channel> [<modestring> [<mode arguments>...]]
- func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- channelName, err := CasefoldChannel(msg.Params[0])
- channel := server.channels.Get(channelName)
-
- if err != nil || channel == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
- return false
- }
-
- // applied mode changes
- applied := make(modes.ModeChanges, 0)
-
- if 1 < len(msg.Params) {
- // parse out real mode changes
- params := msg.Params[1:]
- changes, unknown := modes.ParseChannelModeChanges(params...)
-
- // alert for unknown mode changes
- for char := range unknown {
- rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
- }
- if len(unknown) == 1 && len(changes) == 0 {
- return false
- }
-
- // apply mode changes
- applied = channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
- }
-
- // save changes
- var includeFlags uint
- for _, change := range applied {
- includeFlags |= IncludeModes
- if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
- includeFlags |= IncludeLists
- }
- }
-
- if channel.IsRegistered() && includeFlags != 0 {
- go server.channelRegistry.StoreChannel(channel, includeFlags)
- }
-
- // send out changes
- if len(applied) > 0 {
- //TODO(dan): we should change the name of String and make it return a slice here
- args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
- for _, member := range channel.Members() {
- if member == client {
- rb.Add(nil, client.nickMaskString, "MODE", args...)
- } else {
- member.Send(nil, client.nickMaskString, "MODE", args...)
- }
- }
- } else {
- args := append([]string{client.nick, channel.name}, channel.modeStrings(client)...)
- rb.Add(nil, client.nickMaskString, RPL_CHANNELMODEIS, args...)
- rb.Add(nil, client.nickMaskString, RPL_CHANNELCREATED, client.nick, channel.name, strconv.FormatInt(channel.createdTime.Unix(), 10))
- }
- return false
- }
-
- // MODE <client> [<modestring> [<mode arguments>...]]
- func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- nickname, err := CasefoldName(msg.Params[0])
- target := server.clients.Get(nickname)
- if err != nil || target == nil {
- if len(msg.Params[0]) > 0 {
- rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
- }
- return false
- }
-
- targetNick := target.Nick()
- hasPrivs := client == target || msg.Command == "SAMODE"
-
- if !hasPrivs {
- if len(msg.Params) > 1 {
- rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't change modes for other users"))
- } else {
- rb.Add(nil, server.name, ERR_USERSDONTMATCH, client.nick, client.t("Can't view modes for other users"))
- }
- return false
- }
-
- // applied mode changes
- applied := make(modes.ModeChanges, 0)
-
- if 1 < len(msg.Params) {
- // parse out real mode changes
- params := msg.Params[1:]
- changes, unknown := modes.ParseUserModeChanges(params...)
-
- // alert for unknown mode changes
- for char := range unknown {
- rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
- }
- if len(unknown) == 1 && len(changes) == 0 {
- return false
- }
-
- // apply mode changes
- applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
- }
-
- if len(applied) > 0 {
- rb.Add(nil, client.nickMaskString, "MODE", targetNick, applied.String())
- } else if hasPrivs {
- rb.Add(nil, target.nickMaskString, RPL_UMODEIS, targetNick, target.ModeString())
- if client.HasMode(modes.LocalOperator) || client.HasMode(modes.Operator) {
- masks := server.snomasks.String(client)
- if 0 < len(masks) {
- rb.Add(nil, target.nickMaskString, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
- }
- }
- }
- return false
- }
-
- // MONITOR <subcmd> [params...]
- func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
-
- if !exists {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
- return false
- }
-
- return handler(server, client, msg, rb)
- }
-
- // MONITOR - <target>{,<target>}
- func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if len(msg.Params) < 2 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
- return false
- }
-
- targets := strings.Split(msg.Params[1], ",")
- for _, target := range targets {
- cfnick, err := CasefoldName(target)
- if err != nil {
- continue
- }
- server.monitorManager.Remove(client, cfnick)
- }
-
- return false
- }
-
- // MONITOR + <target>{,<target>}
- func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if len(msg.Params) < 2 {
- rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
- return false
- }
-
- var online []string
- var offline []string
-
- limits := server.Limits()
-
- targets := strings.Split(msg.Params[1], ",")
- for _, target := range targets {
- // check name length
- if len(target) < 1 || len(targets) > limits.NickLen {
- continue
- }
-
- // add target
- casefoldedTarget, err := CasefoldName(target)
- if err != nil {
- continue
- }
-
- err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
- if err == errMonitorLimitExceeded {
- rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
- break
- } else if err != nil {
- continue
- }
-
- // add to online / offline lists
- if targetClient := server.clients.Get(casefoldedTarget); targetClient == nil {
- offline = append(offline, target)
- } else {
- online = append(online, targetClient.Nick())
- }
- }
-
- if len(online) > 0 {
- rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
- }
- if len(offline) > 0 {
- rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
- }
-
- return false
- }
-
- // MONITOR C
- func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- server.monitorManager.RemoveAll(client)
- return false
- }
-
- // MONITOR L
- func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- monitorList := server.monitorManager.List(client)
-
- var nickList []string
- for _, cfnick := range monitorList {
- replynick := cfnick
- // report the uncasefolded nick if it's available, i.e., the client is online
- if mclient := server.clients.Get(cfnick); mclient != nil {
- replynick = mclient.Nick()
- }
- nickList = append(nickList, replynick)
- }
-
- for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
- rb.Add(nil, server.name, RPL_MONLIST, client.Nick(), line)
- }
-
- rb.Add(nil, server.name, RPL_ENDOFMONLIST, "End of MONITOR list")
-
- return false
- }
-
- // MONITOR S
- func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var online []string
- var offline []string
-
- monitorList := server.monitorManager.List(client)
-
- for _, name := range monitorList {
- target := server.clients.Get(name)
- if target == nil {
- offline = append(offline, name)
- } else {
- online = append(online, target.Nick())
- }
- }
-
- if len(online) > 0 {
- for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
- rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
- }
- }
- if len(offline) > 0 {
- for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
- rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
- }
- }
-
- return false
- }
-
- // MOTD
- func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- server.MOTD(client, rb)
- return false
- }
-
- // NAMES [<channel>{,<channel>} [target]]
- func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var channels []string
- if len(msg.Params) > 0 {
- channels = strings.Split(msg.Params[0], ",")
- }
-
- // TODO: in a post-federation world, process `target` (server to forward request to)
-
- if len(channels) == 0 {
- for _, channel := range server.channels.Channels() {
- channel.Names(client, rb)
- }
- return false
- }
-
- for _, chname := range channels {
- channel := server.channels.Get(chname)
- if channel != nil {
- channel.Names(client, rb)
- } else if chname != "" {
- rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
- }
- }
- return false
- }
-
- // NICK <nickname>
- func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if client.registered {
- performNickChange(server, client, client, msg.Params[0], rb)
- } else {
- client.preregNick = msg.Params[0]
- }
- return false
- }
-
- // NOTICE <target>{,<target>} <message>
- func noticeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
- targets := strings.Split(msg.Params[0], ",")
- message := msg.Params[1]
-
- // split privmsg
- splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
-
- for i, targetString := range targets {
- // max of four targets per privmsg
- if i > maxTargets-1 {
- break
- }
- prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
- lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
-
- target, cerr := CasefoldChannel(targetString)
- if cerr == nil {
- channel := server.channels.Get(target)
- if channel == nil {
- // errors silently ignored with NOTICE as per RFC
- continue
- }
- if !channel.CanSpeak(client) {
- // errors silently ignored with NOTICE as per RFC
- continue
- }
- msgid := server.generateMessageID()
- channel.SplitNotice(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
- } else {
- target, err := CasefoldName(targetString)
- if err != nil {
- continue
- }
-
- // NOTICEs sent to services are ignored
- if _, isService := OragonoServices[target]; isService {
- continue
- }
-
- user := server.clients.Get(target)
- if user == nil {
- // errors silently ignored with NOTICE as per RFC
- continue
- }
- if !user.capabilities.Has(caps.MessageTags) {
- clientOnlyTags = nil
- }
- msgid := server.generateMessageID()
- // restrict messages appropriately when +R is set
- // intentionally make the sending user think the message went through fine
- if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
- user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "NOTICE", user.nick, splitMsg)
- }
- nickMaskString := client.NickMaskString()
- accountName := client.AccountName()
- if client.capabilities.Has(caps.EchoMessage) {
- rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "NOTICE", user.nick, splitMsg)
- }
-
- user.history.Add(history.Item{
- Type: history.Notice,
- Msgid: msgid,
- Message: splitMsg,
- Nick: nickMaskString,
- AccountName: accountName,
- })
- }
- }
- return false
- }
-
- // NPC <target> <sourcenick> <message>
- func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- target := msg.Params[0]
- fakeSource := msg.Params[1]
- message := msg.Params[2]
-
- _, err := CasefoldName(fakeSource)
- if err != nil {
- client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
- return false
- }
-
- sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
-
- sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
-
- return false
- }
-
- // NPCA <target> <sourcenick> <message>
- func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- target := msg.Params[0]
- fakeSource := msg.Params[1]
- message := msg.Params[2]
- sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
-
- _, err := CasefoldName(fakeSource)
- if err != nil {
- client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
- return false
- }
-
- sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
-
- return false
- }
-
- // OPER <name> <password>
- func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if client.HasMode(modes.Operator) == true {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, "OPER", client.t("You're already opered-up!"))
- return false
- }
-
- authorized := false
- oper := server.GetOperator(msg.Params[0])
- if oper != nil {
- password := []byte(msg.Params[1])
- authorized = (bcrypt.CompareHashAndPassword(oper.Pass, password) == nil)
- }
- if !authorized {
- rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
- return true
- }
-
- oldNickmask := client.NickMaskString()
- client.SetOper(oper)
- if client.NickMaskString() != oldNickmask {
- client.sendChghost(oldNickmask, oper.Vhost)
- }
-
- // set new modes: modes.Operator, plus anything specified in the config
- modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
- modeChanges[0] = modes.ModeChange{
- Mode: modes.Operator,
- Op: modes.Add,
- }
- copy(modeChanges[1:], oper.Modes)
- applied := ApplyUserModeChanges(client, modeChanges, true)
-
- rb.Add(nil, server.name, RPL_YOUREOPER, client.nick, client.t("You are now an IRC operator"))
- rb.Add(nil, server.name, "MODE", client.nick, applied.String())
-
- server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client opered up $c[grey][$r%s$c[grey], $r%s$c[grey]]"), client.nickMaskString, oper.Name))
-
- // client may now be unthrottled by the fakelag system
- client.resetFakelag()
-
- return false
- }
-
- // PART <channel>{,<channel>} [<reason>]
- func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- channels := strings.Split(msg.Params[0], ",")
- var reason string //TODO(dan): if this isn't supplied here, make sure the param doesn't exist in the PART message sent to other users
- if len(msg.Params) > 1 {
- reason = msg.Params[1]
- }
-
- for _, chname := range channels {
- err := server.channels.Part(client, chname, reason, rb)
- if err == errNoSuchChannel {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
- }
- }
- return false
- }
-
- // PASS <password>
- func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if client.registered {
- rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
- return false
- }
-
- // if no password exists, skip checking
- serverPassword := server.Password()
- if serverPassword == nil {
- return false
- }
-
- // check the provided password
- password := []byte(msg.Params[0])
- if bcrypt.CompareHashAndPassword(serverPassword, password) != nil {
- rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.nick, client.t("Password incorrect"))
- rb.Add(nil, server.name, "ERROR", client.t("Password incorrect"))
- return true
- }
-
- client.sentPassCommand = true
- return false
- }
-
- // PING [params...]
- func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- rb.Add(nil, server.name, "PONG", msg.Params...)
- return false
- }
-
- // PONG [params...]
- func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // client gets touched when they send this command, so we don't need to do anything
- return false
- }
-
- // PRIVMSG <target>{,<target>} <message>
- func privmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
- targets := strings.Split(msg.Params[0], ",")
- message := msg.Params[1]
-
- // split privmsg
- splitMsg := utils.MakeSplitMessage(message, !client.capabilities.Has(caps.MaxLine))
-
- for i, targetString := range targets {
- // max of four targets per privmsg
- if i > maxTargets-1 {
- break
- }
- prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
- lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
-
- // eh, no need to notify them
- if len(targetString) < 1 {
- continue
- }
-
- target, err := CasefoldChannel(targetString)
- if err == nil {
- channel := server.channels.Get(target)
- if channel == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, targetString, client.t("No such channel"))
- continue
- }
- if !channel.CanSpeak(client) {
- rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
- continue
- }
- msgid := server.generateMessageID()
- channel.SplitPrivMsg(msgid, lowestPrefix, clientOnlyTags, client, splitMsg, rb)
- } else {
- target, err = CasefoldName(targetString)
- if service, isService := OragonoServices[target]; isService {
- servicePrivmsgHandler(service, server, client, message, rb)
- continue
- }
- user := server.clients.Get(target)
- if err != nil || user == nil {
- if len(target) > 0 {
- client.Send(nil, server.name, ERR_NOSUCHNICK, client.nick, target, "No such nick")
- }
- continue
- }
- if !user.capabilities.Has(caps.MessageTags) {
- clientOnlyTags = nil
- }
- msgid := server.generateMessageID()
- // restrict messages appropriately when +R is set
- // intentionally make the sending user think the message went through fine
- if !user.HasMode(modes.RegisteredOnly) || client.LoggedIntoAccount() {
- user.SendSplitMsgFromClient(msgid, client, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
- }
- nickMaskString := client.NickMaskString()
- accountName := client.AccountName()
- if client.capabilities.Has(caps.EchoMessage) {
- rb.AddSplitMessageFromClient(msgid, nickMaskString, accountName, clientOnlyTags, "PRIVMSG", user.nick, splitMsg)
- }
- if user.HasMode(modes.Away) {
- //TODO(dan): possibly implement cooldown of away notifications to users
- rb.Add(nil, server.name, RPL_AWAY, user.nick, user.awayMessage)
- }
-
- user.history.Add(history.Item{
- Type: history.Privmsg,
- Msgid: msgid,
- Message: splitMsg,
- Nick: nickMaskString,
- AccountName: accountName,
- })
- }
- }
- return false
- }
-
- // QUIT [<reason>]
- func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- reason := "Quit"
- if len(msg.Params) > 0 {
- reason += ": " + msg.Params[0]
- }
- client.Quit(reason)
- return true
- }
-
- // REHASH
- func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
- err := server.rehash()
-
- if err == nil {
- rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
- } else {
- server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
- }
- return false
- }
-
- // RENAME <oldchan> <newchan> [<reason>]
- func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
- result = false
-
- errorResponse := func(err error, name string) {
- // TODO: send correct error codes, e.g., ERR_CANNOTRENAME, ERR_CHANNAMEINUSE
- var code string
- switch err {
- case errNoSuchChannel:
- code = ERR_NOSUCHCHANNEL
- case errRenamePrivsNeeded:
- code = ERR_CHANOPRIVSNEEDED
- case errInvalidChannelName:
- code = ERR_UNKNOWNERROR
- case errChannelNameInUse:
- code = ERR_UNKNOWNERROR
- default:
- code = ERR_UNKNOWNERROR
- }
- rb.Add(nil, server.name, code, client.Nick(), "RENAME", name, err.Error())
- }
-
- oldName := strings.TrimSpace(msg.Params[0])
- newName := strings.TrimSpace(msg.Params[1])
- if oldName == "" || newName == "" {
- errorResponse(errInvalidChannelName, "<empty>")
- return
- }
- casefoldedOldName, err := CasefoldChannel(oldName)
- if err != nil {
- errorResponse(errInvalidChannelName, oldName)
- return
- }
-
- reason := "No reason"
- if 2 < len(msg.Params) {
- reason = msg.Params[2]
- }
-
- channel := server.channels.Get(oldName)
- if channel == nil {
- errorResponse(errNoSuchChannel, oldName)
- return
- }
- //TODO(dan): allow IRCops to do this?
- if !channel.ClientIsAtLeast(client, modes.Operator) {
- errorResponse(errRenamePrivsNeeded, oldName)
- return
- }
-
- founder := channel.Founder()
- if founder != "" && founder != client.Account() {
- //TODO(dan): Change this to ERR_CANNOTRENAME
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "RENAME", oldName, client.t("Only channel founders can change registered channels"))
- return false
- }
-
- // perform the channel rename
- err = server.channels.Rename(oldName, newName)
- if err != nil {
- errorResponse(err, newName)
- return
- }
-
- // rename succeeded, persist it
- go server.channelRegistry.Rename(channel, casefoldedOldName)
-
- // send RENAME messages
- for _, mcl := range channel.Members() {
- if mcl.capabilities.Has(caps.Rename) {
- mcl.Send(nil, client.nickMaskString, "RENAME", oldName, newName, reason)
- } else {
- mcl.Send(nil, mcl.nickMaskString, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
- if mcl.capabilities.Has(caps.ExtendedJoin) {
- mcl.Send(nil, mcl.nickMaskString, "JOIN", newName, mcl.AccountName(), mcl.realname)
- } else {
- mcl.Send(nil, mcl.nickMaskString, "JOIN", newName)
- }
- }
- }
-
- return false
- }
-
- // RESUME <oldnick> <token> [timestamp]
- func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- oldnick := msg.Params[0]
- token := msg.Params[1]
-
- if client.registered {
- rb.Add(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, connection registration has already been completed"))
- return false
- }
-
- var timestamp time.Time
- if 2 < len(msg.Params) {
- ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[2])
- if err == nil {
- timestamp = ts
- } else {
- rb.Add(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
- }
- }
-
- client.resumeDetails = &ResumeDetails{
- OldNick: oldnick,
- Timestamp: timestamp,
- PresentedToken: token,
- }
-
- return false
- }
-
- // SANICK <oldnick> <nickname>
- func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- targetNick := strings.TrimSpace(msg.Params[0])
- target := server.clients.Get(targetNick)
- if target == nil {
- rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
- return false
- }
- performNickChange(server, client, target, msg.Params[1], rb)
- return false
- }
-
- // SCENE <target> <message>
- func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- target := msg.Params[0]
- message := msg.Params[1]
- sourceString := fmt.Sprintf(sceneNickMask, client.nick)
-
- sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
-
- return false
- }
-
- // TAGMSG <target>{,<target>}
- func tagmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- clientOnlyTags := utils.GetClientOnlyTags(msg.Tags)
- // no client-only tags, so we can drop it
- if clientOnlyTags == nil {
- return false
- }
-
- targets := strings.Split(msg.Params[0], ",")
-
- for i, targetString := range targets {
- // max of four targets per privmsg
- if i > maxTargets-1 {
- break
- }
- prefixes, targetString := modes.SplitChannelMembershipPrefixes(targetString)
- lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
-
- // eh, no need to notify them
- if len(targetString) < 1 {
- continue
- }
-
- target, err := CasefoldChannel(targetString)
- if err == nil {
- channel := server.channels.Get(target)
- if channel == nil {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, targetString, client.t("No such channel"))
- continue
- }
- if !channel.CanSpeak(client) {
- rb.Add(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, client.t("Cannot send to channel"))
- continue
- }
- msgid := server.generateMessageID()
-
- channel.TagMsg(msgid, lowestPrefix, clientOnlyTags, client, rb)
- } else {
- target, err = CasefoldName(targetString)
- user := server.clients.Get(target)
- if err != nil || user == nil {
- if len(target) > 0 {
- client.Send(nil, server.name, ERR_NOSUCHNICK, client.nick, target, client.t("No such nick"))
- }
- continue
- }
- msgid := server.generateMessageID()
-
- // end user can't receive tagmsgs
- if !user.capabilities.Has(caps.MessageTags) {
- continue
- }
- user.SendFromClient(msgid, client, clientOnlyTags, "TAGMSG", user.nick)
- if client.capabilities.Has(caps.EchoMessage) {
- rb.AddFromClient(msgid, client.NickMaskString(), client.AccountName(), clientOnlyTags, "TAGMSG", user.nick)
- }
- if user.HasMode(modes.Away) {
- //TODO(dan): possibly implement cooldown of away notifications to users
- rb.Add(nil, server.name, RPL_AWAY, user.nick, user.awayMessage)
- }
- }
- }
- return false
- }
-
- // TIME
- func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().Format(time.RFC1123))
- return false
- }
-
- // TOPIC <channel> [<topic>]
- func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- name, err := CasefoldChannel(msg.Params[0])
- channel := server.channels.Get(name)
- if err != nil || channel == nil {
- if len(msg.Params[0]) > 0 {
- rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], client.t("No such channel"))
- }
- return false
- }
-
- if len(msg.Params) > 1 {
- channel.SetTopic(client, msg.Params[1], rb)
- } else {
- channel.SendTopic(client, rb)
- }
- return false
- }
-
- // UNDLINE <ip>|<net>
- func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // check oper permissions
- oper := client.Oper()
- if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
- rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
- return false
- }
-
- // get host
- hostString := msg.Params[0]
-
- // check host
- hostNet, err := utils.NormalizedNetFromString(hostString)
-
- if err != nil {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
- return false
- }
-
- err = server.dlines.RemoveNetwork(hostNet)
-
- if err != nil {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
- return false
- }
-
- hostString = utils.NetToNormalizedString(hostNet)
- rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
- server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
- return false
- }
-
- // UNKLINE <mask>
- func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // check oper permissions
- oper := client.Oper()
- if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
- rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
- return false
- }
-
- // get host
- mask := msg.Params[0]
-
- if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
- mask = mask + "!*@*"
- } else if !strings.Contains(mask, "@") {
- mask = mask + "@*"
- }
-
- err := server.klines.RemoveMask(mask)
-
- if err != nil {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
- return false
- }
-
- rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
- server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
- return false
- }
-
- // USER <username> * 0 <realname>
- func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if client.registered {
- rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
- return false
- }
-
- err := client.SetNames(msg.Params[0], msg.Params[3], false)
- if err == errInvalidUsername {
- // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
- // fixes clients that just use their nick as a username so they can still use the interesting nick
- if client.preregNick == msg.Params[0] {
- client.SetNames("user", msg.Params[3], false)
- } else {
- rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.t("Malformed username"))
- }
- }
-
- return false
- }
-
- // USERHOST <nickname>{ <nickname>}
- func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- returnedNicks := make(map[string]bool)
-
- for i, nickname := range msg.Params {
- if i >= 10 {
- break
- }
-
- casefoldedNickname, err := CasefoldName(nickname)
- target := server.clients.Get(casefoldedNickname)
- if err != nil || target == nil {
- rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
- return false
- }
- if returnedNicks[casefoldedNickname] {
- continue
- }
-
- // to prevent returning multiple results for a single nick
- returnedNicks[casefoldedNickname] = true
-
- var isOper, isAway string
-
- if target.HasMode(modes.Operator) {
- isOper = "*"
- }
- if target.HasMode(modes.Away) {
- isAway = "-"
- } else {
- isAway = "+"
- }
- rb.Add(nil, client.server.name, RPL_USERHOST, client.nick, fmt.Sprintf("%s%s=%s%s@%s", target.nick, isOper, isAway, target.username, target.hostname))
- }
-
- return false
- }
-
- // VERSION
- func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
- client.RplISupport(rb)
- return false
- }
-
- // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
- func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- // only allow unregistered clients to use this command
- if client.registered || client.proxiedIP != nil {
- return false
- }
-
- // process flags
- var secure bool
- if 4 < len(msg.Params) {
- for _, x := range strings.Split(msg.Params[4], " ") {
- // split into key=value
- var key string
- if strings.Contains(x, "=") {
- y := strings.SplitN(x, "=", 2)
- key, _ = y[0], y[1]
- } else {
- key = x
- }
-
- lkey := strings.ToLower(key)
- if lkey == "tls" || lkey == "secure" {
- // only accept "tls" flag if the gateway's connection to us is secure as well
- if client.HasMode(modes.TLS) || utils.AddrIsLocal(client.socket.conn.RemoteAddr()) {
- secure = true
- }
- }
- }
- }
-
- givenPassword := []byte(msg.Params[0])
- for _, info := range server.Config().Server.WebIRC {
- if utils.IPInNets(client.realIP, info.allowedNets) {
- // confirm password and/or fingerprint
- if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
- continue
- }
- if 0 < len(info.Fingerprint) && client.certfp != info.Fingerprint {
- continue
- }
-
- proxiedIP := msg.Params[3]
- // see #211; websocket gateways will wrap ipv6 addresses in square brackets
- // because IRC parameters can't start with :
- if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
- proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
- }
- return !client.ApplyProxiedIP(proxiedIP, secure)
- }
- }
-
- client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"))
- return true
- }
-
- // WHO [<mask> [o]]
- func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- if msg.Params[0] == "" {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
- return false
- }
-
- var mask string
- if len(msg.Params) > 0 {
- casefoldedMask, err := Casefold(msg.Params[0])
- if err != nil {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, "WHO", client.t("Mask isn't valid"))
- return false
- }
- mask = casefoldedMask
- }
-
- friends := client.Friends()
-
- //TODO(dan): is this used and would I put this param in the Modern doc?
- // if not, can we remove it?
- //var operatorOnly bool
- //if len(msg.Params) > 1 && msg.Params[1] == "o" {
- // operatorOnly = true
- //}
-
- if mask[0] == '#' {
- // TODO implement wildcard matching
- //TODO(dan): ^ only for opers
- channel := server.channels.Get(mask)
- if channel != nil {
- whoChannel(client, channel, friends, rb)
- }
- } else {
- for mclient := range server.clients.FindAll(mask) {
- client.rplWhoReply(nil, mclient, rb)
- }
- }
-
- rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
- return false
- }
-
- // WHOIS [<target>] <mask>{,<mask>}
- func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- var masksString string
- //var target string
-
- if len(msg.Params) > 1 {
- //target = msg.Params[0]
- masksString = msg.Params[1]
- } else {
- masksString = msg.Params[0]
- }
-
- if len(strings.TrimSpace(masksString)) < 1 {
- rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("No masks given"))
- return false
- }
-
- handleService := func(nick string) bool {
- cfnick, _ := CasefoldName(nick)
- service, ok := OragonoServices[cfnick]
- if !ok {
- return false
- }
- clientNick := client.Nick()
- 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))
- // hehe
- if client.HasMode(modes.TLS) {
- rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
- }
- return true
- }
-
- if client.HasMode(modes.Operator) {
- for _, mask := range strings.Split(masksString, ",") {
- matches := server.clients.FindAll(mask)
- if len(matches) == 0 && !handleService(mask) {
- rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, mask, client.t("No such nick"))
- continue
- }
- for mclient := range matches {
- client.getWhoisOf(mclient, rb)
- }
- }
- } else {
- // only get the first request; also require a nick, not a mask
- nick := strings.Split(masksString, ",")[0]
- mclient := server.clients.Get(nick)
- if mclient != nil {
- client.getWhoisOf(mclient, rb)
- } else if !handleService(nick) {
- rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, masksString, client.t("No such nick"))
- }
- // fall through, ENDOFWHOIS is always sent
- }
- rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, masksString, client.t("End of /WHOIS list"))
- return false
- }
-
- // WHOWAS <nickname> [<count> [<server>]]
- func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
- nicknames := strings.Split(msg.Params[0], ",")
-
- // 0 means "all the entries", as does a negative number
- var count uint64
- if len(msg.Params) > 1 {
- count, _ = strconv.ParseUint(msg.Params[1], 10, 64)
- }
- //var target string
- //if len(msg.Params) > 2 {
- // target = msg.Params[2]
- //}
- cnick := client.Nick()
- for _, nickname := range nicknames {
- results := server.whoWas.Find(nickname, int(count))
- if len(results) == 0 {
- if len(nickname) > 0 {
- rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, nickname, client.t("There was no such nickname"))
- }
- } else {
- for _, whoWas := range results {
- rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
- }
- }
- if len(nickname) > 0 {
- rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, nickname, client.t("End of WHOWAS"))
- }
- }
- return false
- }
|