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

handlers.go 109KB

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