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

handlers.go 115KB

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