Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

handlers.go 116KB

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