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

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