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

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