Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717
  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. "os"
  12. "runtime"
  13. "runtime/debug"
  14. "runtime/pprof"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/goshuirc/irc-go/ircfmt"
  20. "github.com/goshuirc/irc-go/ircmatch"
  21. "github.com/goshuirc/irc-go/ircmsg"
  22. "github.com/oragono/oragono/irc/caps"
  23. "github.com/oragono/oragono/irc/custime"
  24. "github.com/oragono/oragono/irc/history"
  25. "github.com/oragono/oragono/irc/modes"
  26. "github.com/oragono/oragono/irc/sno"
  27. "github.com/oragono/oragono/irc/utils"
  28. "golang.org/x/crypto/bcrypt"
  29. )
  30. // helper function to parse ACC callbacks, e.g., mailto:person@example.com, tel:16505551234
  31. func parseCallback(spec string, config *AccountConfig) (callbackNamespace string, callbackValue string) {
  32. callback := strings.ToLower(spec)
  33. if callback == "*" {
  34. callbackNamespace = "*"
  35. } else if strings.Contains(callback, ":") {
  36. callbackValues := strings.SplitN(callback, ":", 2)
  37. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  38. } else {
  39. // "If a callback namespace is not ... provided, the IRC server MUST use mailto""
  40. callbackNamespace = "mailto"
  41. callbackValue = callback
  42. }
  43. // ensure the callback namespace is valid
  44. // need to search callback list, maybe look at using a map later?
  45. for _, name := range config.Registration.EnabledCallbacks {
  46. if callbackNamespace == name {
  47. return
  48. }
  49. }
  50. // error value
  51. callbackNamespace = ""
  52. return
  53. }
  54. func registrationErrorToMessageAndCode(err error) (message, code string) {
  55. // default responses: let's be risk-averse about displaying internal errors
  56. // to the clients, especially for something as sensitive as accounts
  57. code = "REG_UNSPECIFIED_ERROR"
  58. message = `Could not register`
  59. switch err {
  60. case errAccountBadPassphrase:
  61. code = "REG_INVALID_CREDENTIAL"
  62. message = err.Error()
  63. case errAccountAlreadyRegistered, errAccountAlreadyVerified:
  64. message = err.Error()
  65. case errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists, errFeatureDisabled:
  66. message = err.Error()
  67. }
  68. return
  69. }
  70. // helper function to dispatch messages when a client successfully registers
  71. func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
  72. details := client.Details()
  73. if forNS {
  74. nsNotice(rb, client.t("Account created"))
  75. } else {
  76. rb.Add(nil, client.server.name, RPL_REG_SUCCESS, details.nick, details.accountName, client.t("Account created"))
  77. }
  78. 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]]"), details.nickMask, details.accountName))
  79. sendSuccessfulAccountAuth(client, rb, forNS, false)
  80. }
  81. // sendSuccessfulAccountAuth means that an account auth attempt completed successfully, and is used to dispatch messages.
  82. func sendSuccessfulAccountAuth(client *Client, rb *ResponseBuffer, forNS, forSASL bool) {
  83. details := client.Details()
  84. if forNS {
  85. nsNotice(rb, fmt.Sprintf(client.t("You're now logged in as %s"), details.accountName))
  86. } else {
  87. //TODO(dan): some servers send this numeric even for NickServ logins iirc? to confirm and maybe do too
  88. 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))
  89. if forSASL {
  90. rb.Add(nil, client.server.name, RPL_SASLSUCCESS, details.nick, client.t("Authentication successful"))
  91. }
  92. }
  93. // dispatch account-notify
  94. for friend := range client.Friends(caps.AccountNotify) {
  95. friend.Send(nil, details.nickMask, "ACCOUNT", details.accountName)
  96. }
  97. client.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]]"), details.nickMask, details.accountName))
  98. client.server.logger.Info("accounts", "client", details.nick, "logged into account", details.accountName)
  99. }
  100. // AUTHENTICATE [<mechanism>|<data>|*]
  101. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  102. session := rb.session
  103. config := server.Config()
  104. details := client.Details()
  105. if client.isSTSOnly {
  106. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  107. return false
  108. }
  109. if details.account != "" {
  110. rb.Add(nil, server.name, ERR_SASLALREADY, details.nick, client.t("You're already logged into an account"))
  111. return false
  112. }
  113. // sasl abort
  114. if !server.AccountConfig().AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
  115. rb.Add(nil, server.name, ERR_SASLABORTED, details.nick, client.t("SASL authentication aborted"))
  116. session.sasl.Clear()
  117. return false
  118. }
  119. // start new sasl session
  120. if session.sasl.mechanism == "" {
  121. mechanism := strings.ToUpper(msg.Params[0])
  122. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  123. if mechanismIsEnabled {
  124. session.sasl.mechanism = mechanism
  125. if !config.Server.Compatibility.SendUnprefixedSasl {
  126. // normal behavior
  127. rb.Add(nil, server.name, "AUTHENTICATE", "+")
  128. } else {
  129. // gross hack: send a raw message to ensure no tags or prefix
  130. rb.Flush(true)
  131. rb.session.SendRawMessage(ircmsg.MakeMessage(nil, "", "AUTHENTICATE", "+"), true)
  132. }
  133. } else {
  134. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  135. }
  136. return false
  137. }
  138. // continue existing sasl session
  139. rawData := msg.Params[0]
  140. if len(rawData) > 400 {
  141. rb.Add(nil, server.name, ERR_SASLTOOLONG, details.nick, client.t("SASL message too long"))
  142. session.sasl.Clear()
  143. return false
  144. } else if len(rawData) == 400 {
  145. // allow 4 'continuation' lines before rejecting for length
  146. if len(session.sasl.value) >= 400*4 {
  147. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Passphrase too long"))
  148. session.sasl.Clear()
  149. return false
  150. }
  151. session.sasl.value += rawData
  152. return false
  153. }
  154. if rawData != "+" {
  155. session.sasl.value += rawData
  156. }
  157. var data []byte
  158. var err error
  159. if session.sasl.value != "+" {
  160. data, err = base64.StdEncoding.DecodeString(session.sasl.value)
  161. if err != nil {
  162. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
  163. session.sasl.Clear()
  164. return false
  165. }
  166. }
  167. // call actual handler
  168. handler, handlerExists := EnabledSaslMechanisms[session.sasl.mechanism]
  169. // like 100% not required, but it's good to be safe I guess
  170. if !handlerExists {
  171. rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
  172. session.sasl.Clear()
  173. return false
  174. }
  175. // let the SASL handler do its thing
  176. exiting := handler(server, client, session.sasl.mechanism, data, rb)
  177. session.sasl.Clear()
  178. return exiting
  179. }
  180. // AUTHENTICATE PLAIN
  181. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  182. splitValue := bytes.Split(value, []byte{'\000'})
  183. // PLAIN has separate "authorization ID" (which user you want to become)
  184. // and "authentication ID" (whose password you want to use). the first is optional:
  185. // [authzid] \x00 authcid \x00 password
  186. var authzid, authcid string
  187. if len(splitValue) == 3 {
  188. authzid, authcid = string(splitValue[0]), string(splitValue[1])
  189. if authzid != "" && authcid != authzid {
  190. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: authcid and authzid should be the same"))
  191. return false
  192. }
  193. } else {
  194. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: Invalid auth blob"))
  195. return false
  196. }
  197. throttled, remainingTime := client.loginThrottle.Touch()
  198. if throttled {
  199. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  200. return false
  201. }
  202. password := string(splitValue[2])
  203. err := server.accounts.AuthenticateByPassphrase(client, authcid, password)
  204. if err != nil {
  205. msg := authErrorToMessage(server, err)
  206. rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  207. return false
  208. }
  209. sendSuccessfulAccountAuth(client, rb, false, true)
  210. return false
  211. }
  212. func authErrorToMessage(server *Server, err error) (msg string) {
  213. switch err {
  214. case errAccountDoesNotExist, errAccountUnverified, errAccountInvalidCredentials, errAuthzidAuthcidMismatch:
  215. return err.Error()
  216. default:
  217. // don't expose arbitrary error messages to the user
  218. server.logger.Error("internal", "sasl authentication failure", err.Error())
  219. return "Unknown"
  220. }
  221. }
  222. // AUTHENTICATE EXTERNAL
  223. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
  224. if rb.session.certfp == "" {
  225. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
  226. return false
  227. }
  228. // EXTERNAL doesn't carry an authentication ID (this is determined from the
  229. // certificate), but does carry an optional authorization ID.
  230. var authzid string
  231. var err error
  232. if len(value) != 0 {
  233. authzid, err = CasefoldName(string(value))
  234. if err != nil {
  235. err = errAuthzidAuthcidMismatch
  236. }
  237. }
  238. if err == nil {
  239. err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid)
  240. }
  241. if err != nil {
  242. msg := authErrorToMessage(server, err)
  243. rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
  244. return false
  245. }
  246. sendSuccessfulAccountAuth(client, rb, false, true)
  247. return false
  248. }
  249. // AWAY [<message>]
  250. func awayHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  251. var isAway bool
  252. var awayMessage string
  253. if len(msg.Params) > 0 {
  254. isAway = true
  255. awayMessage = msg.Params[0]
  256. awayLen := server.Config().Limits.AwayLen
  257. if len(awayMessage) > awayLen {
  258. awayMessage = awayMessage[:awayLen]
  259. }
  260. }
  261. client.SetAway(isAway, awayMessage)
  262. if isAway {
  263. rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
  264. } else {
  265. rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
  266. }
  267. // dispatch away-notify
  268. details := client.Details()
  269. for session := range client.Friends(caps.AwayNotify) {
  270. if isAway {
  271. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY", awayMessage)
  272. } else {
  273. session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.account, nil, "AWAY")
  274. }
  275. }
  276. return false
  277. }
  278. // BATCH {+,-}reference-tag type [params...]
  279. func batchHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  280. tag := msg.Params[0]
  281. fail := false
  282. sendErrors := rb.session.batch.command != "NOTICE"
  283. if len(tag) == 0 {
  284. fail = true
  285. } else if tag[0] == '+' {
  286. if rb.session.batch.label != "" || msg.Params[1] != caps.MultilineBatchType {
  287. fail = true
  288. } else {
  289. rb.session.batch.label = tag[1:]
  290. rb.session.batch.tags = msg.ClientOnlyTags()
  291. if len(msg.Params) == 2 {
  292. fail = true
  293. } else {
  294. rb.session.batch.target = msg.Params[2]
  295. // save the response label for later
  296. rb.session.batch.responseLabel = rb.Label
  297. rb.Label = ""
  298. }
  299. }
  300. } else if tag[0] == '-' {
  301. if rb.session.batch.label == "" || rb.session.batch.label != tag[1:] {
  302. fail = true
  303. } else if rb.session.batch.message.LenLines() == 0 {
  304. fail = true
  305. } else {
  306. batch := rb.session.batch
  307. rb.session.batch = MultilineBatch{}
  308. // time tag should correspond to the time when the message was completed
  309. batch.message.SetTime()
  310. histType, err := msgCommandToHistType(batch.command)
  311. if err != nil {
  312. histType = history.Privmsg
  313. batch.command = "PRIVMSG"
  314. }
  315. // XXX changing the label inside a handler is a bit dodgy, but it works here
  316. // because there's no way we could have triggered a flush up to this point
  317. rb.Label = batch.responseLabel
  318. dispatchMessageToTarget(client, batch.tags, histType, batch.command, batch.target, batch.message, rb)
  319. }
  320. }
  321. if fail {
  322. rb.session.batch = MultilineBatch{}
  323. if sendErrors {
  324. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_INVALID", client.t("Invalid multiline batch"))
  325. }
  326. }
  327. return false
  328. }
  329. // BRB [message]
  330. func brbHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  331. success, duration := client.brbTimer.Enable()
  332. if !success {
  333. rb.Add(nil, server.name, "FAIL", "BRB", "CANNOT_BRB", client.t("Your client does not support BRB"))
  334. return false
  335. } else {
  336. rb.Add(nil, server.name, "BRB", strconv.Itoa(int(duration.Seconds())))
  337. }
  338. var message string
  339. if 0 < len(msg.Params) {
  340. message = msg.Params[0]
  341. } else {
  342. message = client.t("I'll be right back")
  343. }
  344. if len(client.Sessions()) == 1 {
  345. // true BRB
  346. client.SetAway(true, message)
  347. }
  348. return true
  349. }
  350. // CAP <subcmd> [<caps>]
  351. func capHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  352. details := client.Details()
  353. subCommand := strings.ToUpper(msg.Params[0])
  354. toAdd := caps.NewSet()
  355. toRemove := caps.NewSet()
  356. var capString string
  357. config := server.Config()
  358. supportedCaps := config.Server.supportedCaps
  359. if client.isSTSOnly {
  360. supportedCaps = stsOnlyCaps
  361. }
  362. badCaps := false
  363. if len(msg.Params) > 1 {
  364. capString = msg.Params[1]
  365. strs := strings.Fields(capString)
  366. for _, str := range strs {
  367. remove := false
  368. if str[0] == '-' {
  369. str = str[1:]
  370. remove = true
  371. }
  372. capab, err := caps.NameToCapability(str)
  373. if err != nil || (!remove && !supportedCaps.Has(capab)) {
  374. badCaps = true
  375. } else if !remove {
  376. toAdd.Enable(capab)
  377. } else {
  378. toRemove.Enable(capab)
  379. }
  380. }
  381. }
  382. sendCapLines := func(cset *caps.Set, values caps.Values) {
  383. version := rb.session.capVersion
  384. // we're working around two bugs:
  385. // 1. weechat 1.4 won't accept the CAP reply unless it contains the server.name source
  386. // 2. old versions of Kiwi and The Lounge can't parse multiline CAP LS 302 (#661),
  387. // so try as hard as possible to get the response to fit on one line.
  388. // :server.name CAP * LS * :<tokens>
  389. // 1 7 4
  390. maxLen := 510 - 1 - len(server.name) - 7 - len(subCommand) - 4
  391. capLines := cset.Strings(version, values, maxLen)
  392. for i, capStr := range capLines {
  393. if version >= caps.Cap302 && i < len(capLines)-1 {
  394. rb.Add(nil, server.name, "CAP", details.nick, subCommand, "*", capStr)
  395. } else {
  396. rb.Add(nil, server.name, "CAP", details.nick, subCommand, capStr)
  397. }
  398. }
  399. }
  400. switch subCommand {
  401. case "LS":
  402. if !client.registered {
  403. rb.session.capState = caps.NegotiatingState
  404. }
  405. if 1 < len(msg.Params) {
  406. num, err := strconv.Atoi(msg.Params[1])
  407. newVersion := caps.Version(num)
  408. if err == nil && rb.session.capVersion < newVersion {
  409. rb.session.capVersion = newVersion
  410. }
  411. }
  412. sendCapLines(supportedCaps, config.Server.capValues)
  413. case "LIST":
  414. // values not sent on LIST
  415. sendCapLines(&rb.session.capabilities, nil)
  416. case "REQ":
  417. if !client.registered {
  418. rb.session.capState = caps.NegotiatingState
  419. }
  420. // make sure all capabilities actually exist
  421. // #511, #521: oragono.io/nope is a fake cap to trap bad clients who blindly request
  422. // every offered capability. during registration, requesting it produces a quit,
  423. // otherwise just a CAP NAK
  424. if badCaps || (toAdd.Has(caps.Nope) && client.registered) {
  425. rb.Add(nil, server.name, "CAP", details.nick, "NAK", capString)
  426. return false
  427. } else if toAdd.Has(caps.Nope) && !client.registered {
  428. client.Quit(fmt.Sprintf(client.t("Requesting the %s client capability is forbidden"), caps.Nope.Name()), rb.session)
  429. return true
  430. }
  431. rb.session.capabilities.Union(toAdd)
  432. rb.session.capabilities.Subtract(toRemove)
  433. rb.Add(nil, server.name, "CAP", details.nick, "ACK", capString)
  434. // if this is the first time the client is requesting a resume token,
  435. // send it to them
  436. if toAdd.Has(caps.Resume) {
  437. token, id := server.resumeManager.GenerateToken(client)
  438. if token != "" {
  439. rb.Add(nil, server.name, "RESUME", "TOKEN", token)
  440. rb.session.SetResumeID(id)
  441. }
  442. }
  443. case "END":
  444. if !client.registered {
  445. rb.session.capState = caps.NegotiatedState
  446. }
  447. default:
  448. rb.Add(nil, server.name, ERR_INVALIDCAPCMD, details.nick, subCommand, client.t("Invalid CAP subcommand"))
  449. }
  450. return false
  451. }
  452. // CHATHISTORY <target> <preposition> <query> [<limit>]
  453. // e.g., CHATHISTORY #ircv3 AFTER id=ytNBbt565yt4r3err3 10
  454. // CHATHISTORY <target> BETWEEN <query> <query> <direction> [<limit>]
  455. // e.g., CHATHISTORY #ircv3 BETWEEN timestamp=YYYY-MM-DDThh:mm:ss.sssZ timestamp=YYYY-MM-DDThh:mm:ss.sssZ + 100
  456. func chathistoryHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (exiting bool) {
  457. var items []history.Item
  458. unknown_command := false
  459. var target string
  460. var channel *Channel
  461. var sequence history.Sequence
  462. var err error
  463. defer func() {
  464. // successful responses are sent as a chathistory or history batch
  465. if err == nil {
  466. if channel != nil {
  467. channel.replayHistoryItems(rb, items, false)
  468. } else {
  469. client.replayPrivmsgHistory(rb, items, target, true)
  470. }
  471. return
  472. }
  473. // errors are sent either without a batch, or in a draft/labeled-response batch as usual
  474. if unknown_command {
  475. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "UNKNOWN_COMMAND", utils.SafeErrorParam(msg.Params[0]), client.t("Unknown command"))
  476. } else if err == utils.ErrInvalidParams {
  477. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_PARAMETERS", msg.Params[0], client.t("Invalid parameters"))
  478. } else if err != nil {
  479. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "MESSAGE_ERROR", msg.Params[0], client.t("Messages could not be retrieved"))
  480. } else if sequence == nil {
  481. rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "NO_SUCH_CHANNEL", utils.SafeErrorParam(msg.Params[1]), client.t("No such channel"))
  482. }
  483. }()
  484. config := server.Config()
  485. maxChathistoryLimit := config.History.ChathistoryMax
  486. if maxChathistoryLimit == 0 {
  487. return
  488. }
  489. preposition := strings.ToLower(msg.Params[0])
  490. target = msg.Params[1]
  491. parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
  492. if param == "*" && (preposition == "before" || preposition == "between") {
  493. // XXX compatibility with kiwi, which as of February 2020 is
  494. // using BEFORE * as a synonym for LATEST *
  495. return
  496. }
  497. err = utils.ErrInvalidParams
  498. pieces := strings.SplitN(param, "=", 2)
  499. if len(pieces) < 2 {
  500. return
  501. }
  502. identifier, value := strings.ToLower(pieces[0]), pieces[1]
  503. if identifier == "msgid" {
  504. msgid, err = value, nil
  505. return
  506. } else if identifier == "timestamp" {
  507. timestamp, err = time.Parse(IRCv3TimestampFormat, value)
  508. return
  509. }
  510. return
  511. }
  512. parseHistoryLimit := func(paramIndex int) (limit int) {
  513. if len(msg.Params) < (paramIndex + 1) {
  514. return maxChathistoryLimit
  515. }
  516. limit, err := strconv.Atoi(msg.Params[paramIndex])
  517. if err != nil || limit == 0 || limit > maxChathistoryLimit {
  518. limit = maxChathistoryLimit
  519. }
  520. return
  521. }
  522. channel, sequence, err = server.GetHistorySequence(nil, client, target)
  523. if err != nil || sequence == nil {
  524. return
  525. }
  526. roundUp := func(endpoint time.Time) (result time.Time) {
  527. return endpoint.Truncate(time.Millisecond).Add(time.Millisecond)
  528. }
  529. var start, end history.Selector
  530. var limit int
  531. switch preposition {
  532. case "between":
  533. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  534. if err != nil {
  535. return
  536. }
  537. end.Msgid, end.Time, err = parseQueryParam(msg.Params[3])
  538. if err != nil {
  539. return
  540. }
  541. // XXX preserve the ordering of the two parameters, since we might be going backwards,
  542. // but round up the chronologically first one, whichever it is, to make it exclusive
  543. if !start.Time.IsZero() && !end.Time.IsZero() {
  544. if start.Time.Before(end.Time) {
  545. start.Time = roundUp(start.Time)
  546. } else {
  547. end.Time = roundUp(end.Time)
  548. }
  549. }
  550. limit = parseHistoryLimit(4)
  551. case "before", "after", "around":
  552. start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
  553. if err != nil {
  554. return
  555. }
  556. if preposition == "after" && !start.Time.IsZero() {
  557. start.Time = roundUp(start.Time)
  558. }
  559. if preposition == "before" {
  560. end = start
  561. start = history.Selector{}
  562. }
  563. limit = parseHistoryLimit(3)
  564. case "latest":
  565. if msg.Params[2] != "*" {
  566. end.Msgid, end.Time, err = parseQueryParam(msg.Params[2])
  567. if err != nil {
  568. return
  569. }
  570. if !end.Time.IsZero() {
  571. end.Time = roundUp(end.Time)
  572. }
  573. start.Time = time.Now().UTC()
  574. }
  575. limit = parseHistoryLimit(3)
  576. default:
  577. unknown_command = true
  578. return
  579. }
  580. if preposition == "around" {
  581. items, err = sequence.Around(start, limit)
  582. } else {
  583. items, _, err = sequence.Between(start, end, limit)
  584. }
  585. return
  586. }
  587. // DEBUG <subcmd>
  588. func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  589. param := strings.ToUpper(msg.Params[0])
  590. switch param {
  591. case "GCSTATS":
  592. stats := debug.GCStats{
  593. Pause: make([]time.Duration, 10),
  594. PauseQuantiles: make([]time.Duration, 5),
  595. }
  596. debug.ReadGCStats(&stats)
  597. rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
  598. rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
  599. rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
  600. rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
  601. rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
  602. rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
  603. rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
  604. rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
  605. case "NUMGOROUTINE":
  606. count := runtime.NumGoroutine()
  607. rb.Notice(fmt.Sprintf("num goroutines: %d", count))
  608. case "PROFILEHEAP":
  609. profFile := "oragono.mprof"
  610. file, err := os.Create(profFile)
  611. if err != nil {
  612. rb.Notice(fmt.Sprintf("error: %s", err))
  613. break
  614. }
  615. defer file.Close()
  616. pprof.Lookup("heap").WriteTo(file, 0)
  617. rb.Notice(fmt.Sprintf("written to %s", profFile))
  618. case "STARTCPUPROFILE":
  619. profFile := "oragono.prof"
  620. file, err := os.Create(profFile)
  621. if err != nil {
  622. rb.Notice(fmt.Sprintf("error: %s", err))
  623. break
  624. }
  625. if err := pprof.StartCPUProfile(file); err != nil {
  626. defer file.Close()
  627. rb.Notice(fmt.Sprintf("error: %s", err))
  628. break
  629. }
  630. rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
  631. case "STOPCPUPROFILE":
  632. pprof.StopCPUProfile()
  633. rb.Notice(fmt.Sprintf("CPU profiling stopped"))
  634. case "CRASHSERVER":
  635. if !client.HasRoleCapabs("oper:rehash") {
  636. rb.Notice(client.t("You must have rehash permissions in order to execute DEBUG CRASHSERVER"))
  637. return false
  638. }
  639. code := utils.ConfirmationCode(server.name, server.ctime)
  640. if len(msg.Params) == 1 || msg.Params[1] != code {
  641. rb.Notice(fmt.Sprintf(client.t("To crash the server, issue the following command: /DEBUG CRASHSERVER %s"), code))
  642. return false
  643. }
  644. server.logger.Error("server", fmt.Sprintf("DEBUG CRASHSERVER executed by operator %s", client.Oper().Name))
  645. go func() {
  646. // intentional nil dereference on a new goroutine, bypassing recover-from-errors
  647. var i, j *int
  648. *i = *j
  649. }()
  650. default:
  651. rb.Notice(client.t("Unrecognized DEBUG subcommand"))
  652. }
  653. return false
  654. }
  655. // helper for parsing the reason args to DLINE and KLINE
  656. func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
  657. reason = "No reason given"
  658. operReason = ""
  659. if len(params) > currentArg {
  660. reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
  661. if len(reasons) == 1 {
  662. reason = strings.TrimSpace(reasons[0])
  663. } else if len(reasons) == 2 {
  664. reason = strings.TrimSpace(reasons[0])
  665. operReason = strings.TrimSpace(reasons[1])
  666. }
  667. }
  668. return
  669. }
  670. func formatBanForListing(client *Client, key string, info IPBanInfo) string {
  671. desc := info.Reason
  672. if info.OperReason != "" && info.OperReason != info.Reason {
  673. desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
  674. }
  675. if info.Duration != 0 {
  676. desc = fmt.Sprintf("%s [%s]", desc, info.TimeLeft())
  677. }
  678. return fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, desc)
  679. }
  680. // DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
  681. // DLINE LIST
  682. func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  683. // check oper permissions
  684. oper := client.Oper()
  685. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  686. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  687. return false
  688. }
  689. currentArg := 0
  690. // if they say LIST, we just list the current dlines
  691. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  692. bans := server.dlines.AllBans()
  693. if len(bans) == 0 {
  694. rb.Notice(client.t("No DLINEs have been set!"))
  695. }
  696. for key, info := range bans {
  697. client.Notice(formatBanForListing(client, key, info))
  698. }
  699. return false
  700. }
  701. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  702. var andKill bool
  703. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  704. andKill = true
  705. currentArg++
  706. }
  707. // when setting a ban that covers the oper's current connection, we require them to say
  708. // "DLINE MYSELF" so that we're sure they really mean it.
  709. var dlineMyself bool
  710. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  711. dlineMyself = true
  712. currentArg++
  713. }
  714. // duration
  715. duration, err := custime.ParseDuration(msg.Params[currentArg])
  716. if err != nil {
  717. duration = 0
  718. } else {
  719. currentArg++
  720. }
  721. // get host
  722. if len(msg.Params) < currentArg+1 {
  723. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
  724. return false
  725. }
  726. hostString := msg.Params[currentArg]
  727. currentArg++
  728. // check host
  729. hostNet, err := utils.NormalizedNetFromString(hostString)
  730. if err != nil {
  731. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  732. return false
  733. }
  734. if !dlineMyself && hostNet.Contains(client.IP()) {
  735. 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>"))
  736. return false
  737. }
  738. // check remote
  739. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  740. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
  741. return false
  742. }
  743. // get comment(s)
  744. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  745. operName := oper.Name
  746. if operName == "" {
  747. operName = server.name
  748. }
  749. err = server.dlines.AddNetwork(hostNet, duration, reason, operReason, operName)
  750. if err != nil {
  751. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
  752. return false
  753. }
  754. var snoDescription string
  755. hostString = utils.NetToNormalizedString(hostNet)
  756. if duration != 0 {
  757. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
  758. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
  759. } else {
  760. rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
  761. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
  762. }
  763. server.snomasks.Send(sno.LocalXline, snoDescription)
  764. var killClient bool
  765. if andKill {
  766. var clientsToKill []*Client
  767. var killedClientNicks []string
  768. for _, mcl := range server.clients.AllClients() {
  769. if hostNet.Contains(mcl.IP()) {
  770. clientsToKill = append(clientsToKill, mcl)
  771. killedClientNicks = append(killedClientNicks, mcl.nick)
  772. }
  773. }
  774. for _, mcl := range clientsToKill {
  775. mcl.SetExitedSnomaskSent()
  776. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  777. if mcl == client {
  778. killClient = true
  779. } else {
  780. // if mcl == client, we kill them below
  781. mcl.destroy(nil)
  782. }
  783. }
  784. // send snomask
  785. sort.Strings(killedClientNicks)
  786. 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, ", ")))
  787. }
  788. return killClient
  789. }
  790. // HELP [<query>]
  791. func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  792. argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
  793. if len(argument) < 1 {
  794. client.sendHelp("HELPOP", client.t(`HELPOP <argument>
  795. Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
  796. return false
  797. }
  798. // handle index
  799. if argument == "index" {
  800. client.sendHelp("HELP", server.helpIndexManager.GetIndex(client.Languages(), client.HasMode(modes.Operator)), rb)
  801. return false
  802. }
  803. helpHandler, exists := Help[argument]
  804. if exists && (!helpHandler.oper || (helpHandler.oper && client.HasMode(modes.Operator))) {
  805. if helpHandler.textGenerator != nil {
  806. client.sendHelp(strings.ToUpper(argument), helpHandler.textGenerator(client), rb)
  807. } else {
  808. client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
  809. }
  810. } else {
  811. args := msg.Params
  812. args = append(args, client.t("Help not found"))
  813. rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
  814. }
  815. return false
  816. }
  817. // HISTORY <target> [<limit>]
  818. // e.g., HISTORY #ubuntu 10
  819. // HISTORY me 15
  820. // HISTORY #darwin 1h
  821. func historyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  822. config := server.Config()
  823. if !config.History.Enabled {
  824. rb.Notice(client.t("This command has been disabled by the server administrators"))
  825. return false
  826. }
  827. target := msg.Params[0]
  828. if strings.ToLower(target) == "me" {
  829. target = "*"
  830. }
  831. channel, sequence, err := server.GetHistorySequence(nil, client, target)
  832. if sequence == nil || err != nil {
  833. // whatever
  834. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  835. return false
  836. }
  837. var duration time.Duration
  838. maxChathistoryLimit := config.History.ChathistoryMax
  839. limit := 100
  840. if maxChathistoryLimit < limit {
  841. limit = maxChathistoryLimit
  842. }
  843. if len(msg.Params) > 1 {
  844. providedLimit, err := strconv.Atoi(msg.Params[1])
  845. if err == nil && providedLimit != 0 {
  846. limit = providedLimit
  847. if maxChathistoryLimit < limit {
  848. limit = maxChathistoryLimit
  849. }
  850. } else if err != nil {
  851. duration, err = time.ParseDuration(msg.Params[1])
  852. if err == nil {
  853. limit = maxChathistoryLimit
  854. }
  855. }
  856. }
  857. var items []history.Item
  858. if duration == 0 {
  859. items, _, err = sequence.Between(history.Selector{}, history.Selector{}, limit)
  860. } else {
  861. now := time.Now().UTC()
  862. start := history.Selector{Time: now}
  863. end := history.Selector{Time: now.Add(-duration)}
  864. items, _, err = sequence.Between(start, end, limit)
  865. }
  866. if err == nil && len(items) != 0 {
  867. if channel != nil {
  868. channel.replayHistoryItems(rb, items, false)
  869. } else {
  870. client.replayPrivmsgHistory(rb, items, "", true)
  871. }
  872. }
  873. return false
  874. }
  875. // INFO
  876. func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  877. // we do the below so that the human-readable lines in info can be translated.
  878. for _, line := range infoString1 {
  879. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  880. }
  881. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
  882. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  883. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Thanks to Jeremy Latt for founding Ergonomadic, the project this is based on")+" <3")
  884. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  885. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
  886. for _, line := range infoString2 {
  887. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  888. }
  889. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
  890. for _, line := range infoString3 {
  891. rb.Add(nil, server.name, RPL_INFO, client.nick, line)
  892. }
  893. // show translators for languages other than good ole' regular English
  894. tlines := server.Languages().Translators()
  895. if 0 < len(tlines) {
  896. rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
  897. for _, line := range tlines {
  898. rb.Add(nil, server.name, RPL_INFO, client.nick, " "+strings.Replace(line, "\n", ", ", -1))
  899. }
  900. rb.Add(nil, server.name, RPL_INFO, client.nick, "")
  901. }
  902. rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
  903. return false
  904. }
  905. // INVITE <nickname> <channel>
  906. func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  907. nickname := msg.Params[0]
  908. channelName := msg.Params[1]
  909. target := server.clients.Get(nickname)
  910. if target == nil {
  911. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(nickname), client.t("No such nick"))
  912. return false
  913. }
  914. channel := server.channels.Get(channelName)
  915. if channel == nil {
  916. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(channelName), client.t("No such channel"))
  917. return false
  918. }
  919. channel.Invite(target, client, rb)
  920. return false
  921. }
  922. // ISON <nick>{ <nick>}
  923. func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  924. var nicks = msg.Params
  925. ison := make([]string, 0, len(msg.Params))
  926. for _, nick := range nicks {
  927. currentNick := server.getCurrentNick(nick)
  928. if currentNick != "" {
  929. ison = append(ison, currentNick)
  930. }
  931. }
  932. rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(ison, " "))
  933. return false
  934. }
  935. // JOIN <channel>{,<channel>} [<key>{,<key>}]
  936. func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  937. // kill JOIN 0 requests
  938. if msg.Params[0] == "0" {
  939. rb.Notice(client.t("JOIN 0 is not allowed"))
  940. return false
  941. }
  942. // handle regular JOINs
  943. channels := strings.Split(msg.Params[0], ",")
  944. var keys []string
  945. if len(msg.Params) > 1 {
  946. keys = strings.Split(msg.Params[1], ",")
  947. }
  948. config := server.Config()
  949. oper := client.Oper()
  950. for i, name := range channels {
  951. if name == "" {
  952. continue // #679
  953. }
  954. if config.Channels.MaxChannelsPerClient <= client.NumChannels() && oper == nil {
  955. rb.Add(nil, server.name, ERR_TOOMANYCHANNELS, client.Nick(), name, client.t("You have joined too many channels"))
  956. return false
  957. }
  958. var key string
  959. if len(keys) > i {
  960. key = keys[i]
  961. }
  962. err := server.channels.Join(client, name, key, false, rb)
  963. if err != nil {
  964. sendJoinError(client, name, rb, err)
  965. }
  966. }
  967. return false
  968. }
  969. func sendJoinError(client *Client, name string, rb *ResponseBuffer, err error) {
  970. var errMsg string
  971. switch err {
  972. case errInsufficientPrivs:
  973. errMsg = `Only server operators can create new channels`
  974. case errConfusableIdentifier:
  975. errMsg = `That channel name is too close to the name of another channel`
  976. case errChannelPurged:
  977. errMsg = err.Error()
  978. default:
  979. errMsg = `No such channel`
  980. }
  981. rb.Add(nil, client.server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(name), client.t(errMsg))
  982. }
  983. // SAJOIN [nick] #channel{,#channel}
  984. func sajoinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  985. var target *Client
  986. var channelString string
  987. if strings.HasPrefix(msg.Params[0], "#") {
  988. target = client
  989. channelString = msg.Params[0]
  990. } else {
  991. if len(msg.Params) == 1 {
  992. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), "SAJOIN", client.t("Not enough parameters"))
  993. return false
  994. } else {
  995. target = server.clients.Get(msg.Params[0])
  996. if target == nil {
  997. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(msg.Params[0]), "No such nick")
  998. return false
  999. }
  1000. channelString = msg.Params[1]
  1001. }
  1002. }
  1003. channels := strings.Split(channelString, ",")
  1004. for _, chname := range channels {
  1005. err := server.channels.Join(target, chname, "", true, rb)
  1006. if err != nil {
  1007. sendJoinError(client, chname, rb, err)
  1008. }
  1009. }
  1010. return false
  1011. }
  1012. // KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
  1013. func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1014. channels := strings.Split(msg.Params[0], ",")
  1015. users := strings.Split(msg.Params[1], ",")
  1016. if (len(channels) != len(users)) && (len(users) != 1) {
  1017. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
  1018. return false
  1019. }
  1020. type kickCmd struct {
  1021. channel string
  1022. nick string
  1023. }
  1024. kicks := make([]kickCmd, 0, len(channels))
  1025. for index, channel := range channels {
  1026. if channel == "" {
  1027. continue // #679
  1028. }
  1029. if len(users) == 1 {
  1030. kicks = append(kicks, kickCmd{channel, users[0]})
  1031. } else {
  1032. kicks = append(kicks, kickCmd{channel, users[index]})
  1033. }
  1034. }
  1035. var comment string
  1036. if len(msg.Params) > 2 {
  1037. comment = msg.Params[2]
  1038. }
  1039. for _, kick := range kicks {
  1040. channel := server.channels.Get(kick.channel)
  1041. if channel == nil {
  1042. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(kick.channel), client.t("No such channel"))
  1043. continue
  1044. }
  1045. target := server.clients.Get(kick.nick)
  1046. if target == nil {
  1047. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(kick.nick), client.t("No such nick"))
  1048. continue
  1049. }
  1050. if comment == "" {
  1051. comment = kick.nick
  1052. }
  1053. channel.Kick(client, target, comment, rb, false)
  1054. }
  1055. return false
  1056. }
  1057. // KILL <nickname> <comment>
  1058. func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1059. nickname := msg.Params[0]
  1060. comment := "<no reason supplied>"
  1061. if len(msg.Params) > 1 {
  1062. comment = msg.Params[1]
  1063. }
  1064. target := server.clients.Get(nickname)
  1065. if target == nil {
  1066. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, utils.SafeErrorParam(nickname), client.t("No such nick"))
  1067. return false
  1068. }
  1069. quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
  1070. 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))
  1071. target.SetExitedSnomaskSent()
  1072. target.Quit(quitMsg, nil)
  1073. target.destroy(nil)
  1074. return false
  1075. }
  1076. // KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
  1077. // KLINE LIST
  1078. func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1079. details := client.Details()
  1080. // check oper permissions
  1081. oper := client.Oper()
  1082. if oper == nil || !oper.Class.Capabilities["oper:local_ban"] {
  1083. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  1084. return false
  1085. }
  1086. currentArg := 0
  1087. // if they say LIST, we just list the current klines
  1088. if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
  1089. bans := server.klines.AllBans()
  1090. if len(bans) == 0 {
  1091. client.Notice("No KLINEs have been set!")
  1092. }
  1093. for key, info := range bans {
  1094. client.Notice(formatBanForListing(client, key, info))
  1095. }
  1096. return false
  1097. }
  1098. // when setting a ban, if they say "ANDKILL" we should also kill all users who match it
  1099. var andKill bool
  1100. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
  1101. andKill = true
  1102. currentArg++
  1103. }
  1104. // when setting a ban that covers the oper's current connection, we require them to say
  1105. // "KLINE MYSELF" so that we're sure they really mean it.
  1106. var klineMyself bool
  1107. if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
  1108. klineMyself = true
  1109. currentArg++
  1110. }
  1111. // duration
  1112. duration, err := custime.ParseDuration(msg.Params[currentArg])
  1113. if err != nil {
  1114. duration = 0
  1115. } else {
  1116. currentArg++
  1117. }
  1118. // get mask
  1119. if len(msg.Params) < currentArg+1 {
  1120. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, details.nick, msg.Command, client.t("Not enough parameters"))
  1121. return false
  1122. }
  1123. mask := msg.Params[currentArg]
  1124. currentArg++
  1125. // check mask
  1126. mask, err = CanonicalizeMaskWildcard(mask)
  1127. if err != nil {
  1128. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  1129. return false
  1130. }
  1131. matcher := ircmatch.MakeMatch(mask)
  1132. for _, clientMask := range client.AllNickmasks() {
  1133. if !klineMyself && matcher.Match(clientMask) {
  1134. 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>"))
  1135. return false
  1136. }
  1137. }
  1138. // check remote
  1139. if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
  1140. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Remote servers not yet supported"))
  1141. return false
  1142. }
  1143. // get oper name
  1144. operName := oper.Name
  1145. if operName == "" {
  1146. operName = server.name
  1147. }
  1148. // get comment(s)
  1149. reason, operReason := getReasonsFromParams(msg.Params, currentArg)
  1150. err = server.klines.AddMask(mask, duration, reason, operReason, operName)
  1151. if err != nil {
  1152. rb.Notice(fmt.Sprintf(client.t("Could not successfully save new K-LINE: %s"), err.Error()))
  1153. return false
  1154. }
  1155. var snoDescription string
  1156. if duration != 0 {
  1157. rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) K-Line for %[2]s"), duration.String(), mask))
  1158. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) K-Line for %s"), details.nick, operName, duration.String(), mask)
  1159. } else {
  1160. rb.Notice(fmt.Sprintf(client.t("Added K-Line for %s"), mask))
  1161. snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added K-Line for %s"), details.nick, operName, mask)
  1162. }
  1163. server.snomasks.Send(sno.LocalXline, snoDescription)
  1164. var killClient bool
  1165. if andKill {
  1166. var clientsToKill []*Client
  1167. var killedClientNicks []string
  1168. for _, mcl := range server.clients.AllClients() {
  1169. for _, clientMask := range mcl.AllNickmasks() {
  1170. if matcher.Match(clientMask) {
  1171. clientsToKill = append(clientsToKill, mcl)
  1172. killedClientNicks = append(killedClientNicks, mcl.nick)
  1173. }
  1174. }
  1175. }
  1176. for _, mcl := range clientsToKill {
  1177. mcl.SetExitedSnomaskSent()
  1178. mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason), nil)
  1179. if mcl == client {
  1180. killClient = true
  1181. } else {
  1182. // if mcl == client, we kill them below
  1183. mcl.destroy(nil)
  1184. }
  1185. }
  1186. // send snomask
  1187. sort.Strings(killedClientNicks)
  1188. 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, ", ")))
  1189. }
  1190. return killClient
  1191. }
  1192. // LANGUAGE <code>{ <code>}
  1193. func languageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1194. nick := client.Nick()
  1195. alreadyDoneLanguages := make(map[string]bool)
  1196. var appliedLanguages []string
  1197. lm := server.Languages()
  1198. supportedLanguagesCount := lm.Count()
  1199. if supportedLanguagesCount < len(msg.Params) {
  1200. rb.Add(nil, client.server.name, ERR_TOOMANYLANGUAGES, nick, strconv.Itoa(supportedLanguagesCount), client.t("You specified too many languages"))
  1201. return false
  1202. }
  1203. for _, value := range msg.Params {
  1204. value = strings.ToLower(value)
  1205. // strip ~ from the language if it has it
  1206. value = strings.TrimPrefix(value, "~")
  1207. // silently ignore empty languages or those with spaces in them
  1208. if len(value) == 0 || strings.Contains(value, " ") {
  1209. continue
  1210. }
  1211. _, exists := lm.Languages[value]
  1212. if !exists {
  1213. rb.Add(nil, client.server.name, ERR_NOLANGUAGE, nick, fmt.Sprintf(client.t("Language %s is not supported by this server"), value))
  1214. return false
  1215. }
  1216. // if we've already applied the given language, skip it
  1217. _, exists = alreadyDoneLanguages[value]
  1218. if exists {
  1219. continue
  1220. }
  1221. appliedLanguages = append(appliedLanguages, value)
  1222. }
  1223. var langsToSet []string
  1224. if !(len(appliedLanguages) == 1 && appliedLanguages[0] == "en") {
  1225. langsToSet = appliedLanguages
  1226. }
  1227. client.SetLanguages(langsToSet)
  1228. params := make([]string, len(appliedLanguages)+2)
  1229. params[0] = nick
  1230. copy(params[1:], appliedLanguages)
  1231. params[len(params)-1] = client.t("Language preferences have been set")
  1232. rb.Add(nil, client.server.name, RPL_YOURLANGUAGESARE, params...)
  1233. return false
  1234. }
  1235. // LIST [<channel>{,<channel>}] [<elistcond>{,<elistcond>}]
  1236. func listHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1237. // get channels
  1238. var channels []string
  1239. for _, param := range msg.Params {
  1240. if 0 < len(param) && param[0] == '#' {
  1241. for _, channame := range strings.Split(param, ",") {
  1242. if 0 < len(channame) && channame[0] == '#' {
  1243. channels = append(channels, channame)
  1244. }
  1245. }
  1246. }
  1247. }
  1248. // get elist conditions
  1249. var matcher elistMatcher
  1250. for _, param := range msg.Params {
  1251. if len(param) < 1 {
  1252. continue
  1253. }
  1254. if param[0] == '<' {
  1255. param = param[1:]
  1256. val, err := strconv.Atoi(param)
  1257. if err != nil {
  1258. continue
  1259. }
  1260. matcher.MaxClientsActive = true
  1261. matcher.MaxClients = val - 1 // -1 because < means less than the given number
  1262. }
  1263. if param[0] == '>' {
  1264. param = param[1:]
  1265. val, err := strconv.Atoi(param)
  1266. if err != nil {
  1267. continue
  1268. }
  1269. matcher.MinClientsActive = true
  1270. matcher.MinClients = val + 1 // +1 because > means more than the given number
  1271. }
  1272. }
  1273. clientIsOp := client.HasMode(modes.Operator)
  1274. if len(channels) == 0 {
  1275. for _, channel := range server.channels.Channels() {
  1276. if !clientIsOp && channel.flags.HasMode(modes.Secret) {
  1277. continue
  1278. }
  1279. if matcher.Matches(channel) {
  1280. client.RplList(channel, rb)
  1281. }
  1282. }
  1283. } else {
  1284. // limit regular users to only listing one channel
  1285. if !clientIsOp {
  1286. channels = channels[:1]
  1287. }
  1288. for _, chname := range channels {
  1289. channel := server.channels.Get(chname)
  1290. if channel == nil || (!clientIsOp && channel.flags.HasMode(modes.Secret)) {
  1291. if len(chname) > 0 {
  1292. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1293. }
  1294. continue
  1295. }
  1296. if matcher.Matches(channel) {
  1297. client.RplList(channel, rb)
  1298. }
  1299. }
  1300. }
  1301. rb.Add(nil, server.name, RPL_LISTEND, client.nick, client.t("End of LIST"))
  1302. return false
  1303. }
  1304. // LUSERS [<mask> [<server>]]
  1305. func lusersHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1306. server.Lusers(client, rb)
  1307. return false
  1308. }
  1309. // MODE <target> [<modestring> [<mode arguments>...]]
  1310. func modeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1311. if 0 < len(msg.Params[0]) && msg.Params[0][0] == '#' {
  1312. return cmodeHandler(server, client, msg, rb)
  1313. }
  1314. return umodeHandler(server, client, msg, rb)
  1315. }
  1316. // MODE <channel> [<modestring> [<mode arguments>...]]
  1317. func cmodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1318. channel := server.channels.Get(msg.Params[0])
  1319. if channel == nil {
  1320. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  1321. return false
  1322. }
  1323. var changes modes.ModeChanges
  1324. if 1 < len(msg.Params) {
  1325. // parse out real mode changes
  1326. params := msg.Params[1:]
  1327. var unknown map[rune]bool
  1328. changes, unknown = modes.ParseChannelModeChanges(params...)
  1329. // alert for unknown mode changes
  1330. for char := range unknown {
  1331. rb.Add(nil, server.name, ERR_UNKNOWNMODE, client.nick, string(char), client.t("is an unknown mode character to me"))
  1332. }
  1333. if len(unknown) == 1 && len(changes) == 0 {
  1334. return false
  1335. }
  1336. }
  1337. // process mode changes, include list operations (an empty set of changes does a list)
  1338. applied := channel.ApplyChannelModeChanges(client, msg.Command == "SAMODE", changes, rb)
  1339. // save changes
  1340. var includeFlags uint
  1341. for _, change := range applied {
  1342. includeFlags |= IncludeModes
  1343. if change.Mode == modes.BanMask || change.Mode == modes.ExceptMask || change.Mode == modes.InviteMask {
  1344. includeFlags |= IncludeLists
  1345. }
  1346. }
  1347. if includeFlags != 0 {
  1348. channel.MarkDirty(includeFlags)
  1349. }
  1350. // send out changes
  1351. if len(applied) > 0 {
  1352. prefix := client.NickMaskString()
  1353. //TODO(dan): we should change the name of String and make it return a slice here
  1354. args := append([]string{channel.name}, strings.Split(applied.String(), " ")...)
  1355. rb.Add(nil, prefix, "MODE", args...)
  1356. for _, session := range client.Sessions() {
  1357. if session != rb.session {
  1358. session.Send(nil, prefix, "MODE", args...)
  1359. }
  1360. }
  1361. for _, member := range channel.Members() {
  1362. if member != client {
  1363. member.Send(nil, prefix, "MODE", args...)
  1364. }
  1365. }
  1366. }
  1367. return false
  1368. }
  1369. // MODE <client> [<modestring> [<mode arguments>...]]
  1370. func umodeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1371. cDetails := client.Details()
  1372. target := server.clients.Get(msg.Params[0])
  1373. if target == nil {
  1374. rb.Add(nil, server.name, ERR_NOSUCHNICK, cDetails.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such nick"))
  1375. return false
  1376. }
  1377. targetNick := target.Nick()
  1378. hasPrivs := client == target || msg.Command == "SAMODE"
  1379. if !hasPrivs {
  1380. if len(msg.Params) > 1 {
  1381. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't change modes for other users"))
  1382. } else {
  1383. rb.Add(nil, server.name, ERR_USERSDONTMATCH, cDetails.nick, client.t("Can't view modes for other users"))
  1384. }
  1385. return false
  1386. }
  1387. // applied mode changes
  1388. applied := make(modes.ModeChanges, 0)
  1389. if 1 < len(msg.Params) {
  1390. // parse out real mode changes
  1391. params := msg.Params[1:]
  1392. changes, unknown := modes.ParseUserModeChanges(params...)
  1393. // alert for unknown mode changes
  1394. for char := range unknown {
  1395. rb.Add(nil, server.name, ERR_UNKNOWNMODE, cDetails.nick, string(char), client.t("is an unknown mode character to me"))
  1396. }
  1397. if len(unknown) == 1 && len(changes) == 0 {
  1398. return false
  1399. }
  1400. // apply mode changes
  1401. applied = ApplyUserModeChanges(client, changes, msg.Command == "SAMODE")
  1402. }
  1403. if len(applied) > 0 {
  1404. rb.Add(nil, cDetails.nickMask, "MODE", targetNick, applied.String())
  1405. } else if hasPrivs {
  1406. rb.Add(nil, server.name, RPL_UMODEIS, targetNick, target.ModeString())
  1407. if target.HasMode(modes.LocalOperator) || target.HasMode(modes.Operator) {
  1408. masks := server.snomasks.String(target)
  1409. if 0 < len(masks) {
  1410. rb.Add(nil, server.name, RPL_SNOMASKIS, targetNick, masks, client.t("Server notice masks"))
  1411. }
  1412. }
  1413. }
  1414. return false
  1415. }
  1416. // get the correct capitalization of a nick (if it's online), otherwise return ""
  1417. func (server *Server) getCurrentNick(nick string) (result string) {
  1418. if service, isService := OragonoServices[strings.ToLower(nick)]; isService {
  1419. return service.Name
  1420. } else if iclient := server.clients.Get(nick); iclient != nil {
  1421. return iclient.Nick()
  1422. }
  1423. return ""
  1424. }
  1425. // MONITOR <subcmd> [params...]
  1426. func monitorHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1427. handler, exists := monitorSubcommands[strings.ToLower(msg.Params[0])]
  1428. if !exists {
  1429. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "MONITOR", msg.Params[0], client.t("Unknown subcommand"))
  1430. return false
  1431. }
  1432. return handler(server, client, msg, rb)
  1433. }
  1434. // MONITOR - <target>{,<target>}
  1435. func monitorRemoveHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1436. if len(msg.Params) < 2 {
  1437. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1438. return false
  1439. }
  1440. targets := strings.Split(msg.Params[1], ",")
  1441. for _, target := range targets {
  1442. cfnick, err := CasefoldName(target)
  1443. if err != nil {
  1444. continue
  1445. }
  1446. server.monitorManager.Remove(client, cfnick)
  1447. }
  1448. return false
  1449. }
  1450. // MONITOR + <target>{,<target>}
  1451. func monitorAddHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1452. if len(msg.Params) < 2 {
  1453. rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.Nick(), msg.Command, client.t("Not enough parameters"))
  1454. return false
  1455. }
  1456. var online []string
  1457. var offline []string
  1458. limits := server.Config().Limits
  1459. targets := strings.Split(msg.Params[1], ",")
  1460. for _, target := range targets {
  1461. // check name length
  1462. if len(target) < 1 || len(targets) > limits.NickLen {
  1463. continue
  1464. }
  1465. // add target
  1466. casefoldedTarget, err := CasefoldName(target)
  1467. if err != nil {
  1468. continue
  1469. }
  1470. err = server.monitorManager.Add(client, casefoldedTarget, limits.MonitorEntries)
  1471. if err == errMonitorLimitExceeded {
  1472. rb.Add(nil, server.name, ERR_MONLISTFULL, client.Nick(), strconv.Itoa(limits.MonitorEntries), strings.Join(targets, ","))
  1473. break
  1474. } else if err != nil {
  1475. continue
  1476. }
  1477. currentNick := server.getCurrentNick(target)
  1478. // add to online / offline lists
  1479. if currentNick != "" {
  1480. online = append(online, currentNick)
  1481. } else {
  1482. offline = append(offline, target)
  1483. }
  1484. }
  1485. if len(online) > 0 {
  1486. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), strings.Join(online, ","))
  1487. }
  1488. if len(offline) > 0 {
  1489. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), strings.Join(offline, ","))
  1490. }
  1491. return false
  1492. }
  1493. // MONITOR C
  1494. func monitorClearHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1495. server.monitorManager.RemoveAll(client)
  1496. return false
  1497. }
  1498. // MONITOR L
  1499. func monitorListHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1500. nick := client.Nick()
  1501. monitorList := server.monitorManager.List(client)
  1502. var nickList []string
  1503. for _, cfnick := range monitorList {
  1504. replynick := cfnick
  1505. currentNick := server.getCurrentNick(cfnick)
  1506. // report the uncasefolded nick if it's available, i.e., the client is online
  1507. if currentNick != "" {
  1508. replynick = currentNick
  1509. }
  1510. nickList = append(nickList, replynick)
  1511. }
  1512. for _, line := range utils.ArgsToStrings(maxLastArgLength, nickList, ",") {
  1513. rb.Add(nil, server.name, RPL_MONLIST, nick, line)
  1514. }
  1515. rb.Add(nil, server.name, RPL_ENDOFMONLIST, nick, "End of MONITOR list")
  1516. return false
  1517. }
  1518. // MONITOR S
  1519. func monitorStatusHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1520. var online []string
  1521. var offline []string
  1522. monitorList := server.monitorManager.List(client)
  1523. for _, name := range monitorList {
  1524. currentNick := server.getCurrentNick(name)
  1525. if currentNick != "" {
  1526. online = append(online, currentNick)
  1527. } else {
  1528. offline = append(offline, name)
  1529. }
  1530. }
  1531. if len(online) > 0 {
  1532. for _, line := range utils.ArgsToStrings(maxLastArgLength, online, ",") {
  1533. rb.Add(nil, server.name, RPL_MONONLINE, client.Nick(), line)
  1534. }
  1535. }
  1536. if len(offline) > 0 {
  1537. for _, line := range utils.ArgsToStrings(maxLastArgLength, offline, ",") {
  1538. rb.Add(nil, server.name, RPL_MONOFFLINE, client.Nick(), line)
  1539. }
  1540. }
  1541. return false
  1542. }
  1543. // MOTD
  1544. func motdHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1545. server.MOTD(client, rb)
  1546. return false
  1547. }
  1548. // NAMES [<channel>{,<channel>} [target]]
  1549. func namesHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1550. var channels []string
  1551. if len(msg.Params) > 0 {
  1552. channels = strings.Split(msg.Params[0], ",")
  1553. }
  1554. // TODO: in a post-federation world, process `target` (server to forward request to)
  1555. // implement the modern behavior: https://modern.ircdocs.horse/#names-message
  1556. // "Servers MAY only return information about the first <channel> and silently ignore the others."
  1557. // "If no parameter is given for this command, servers SHOULD return one RPL_ENDOFNAMES numeric
  1558. // with the <channel> parameter set to an asterix character"
  1559. if len(channels) == 0 {
  1560. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), "*", client.t("End of NAMES list"))
  1561. return false
  1562. }
  1563. chname := channels[0]
  1564. success := false
  1565. channel := server.channels.Get(chname)
  1566. if channel != nil {
  1567. if !channel.flags.HasMode(modes.Secret) || channel.hasClient(client) || client.HasMode(modes.Operator) {
  1568. channel.Names(client, rb)
  1569. success = true
  1570. }
  1571. }
  1572. if !success { // channel.Names() sends this numeric itself on success
  1573. rb.Add(nil, server.name, RPL_ENDOFNAMES, client.Nick(), chname, client.t("End of NAMES list"))
  1574. }
  1575. return false
  1576. }
  1577. // NICK <nickname>
  1578. func nickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1579. if client.registered {
  1580. performNickChange(server, client, client, nil, msg.Params[0], rb)
  1581. } else {
  1582. client.preregNick = msg.Params[0]
  1583. }
  1584. return false
  1585. }
  1586. // helper to store a batched PRIVMSG in the session object
  1587. func absorbBatchedMessage(server *Server, client *Client, msg ircmsg.IrcMessage, batchTag string, histType history.ItemType, rb *ResponseBuffer) {
  1588. // sanity checks. batch tag correctness was already checked and is redundant here
  1589. // as a defensive measure. TAGMSG is checked without an error message: "don't eat paste"
  1590. if batchTag != rb.session.batch.label || histType == history.Tagmsg || len(msg.Params) == 1 || msg.Params[1] == "" {
  1591. return
  1592. }
  1593. rb.session.batch.command = msg.Command
  1594. isConcat, _ := msg.GetTag(caps.MultilineConcatTag)
  1595. rb.session.batch.message.Append(msg.Params[1], isConcat)
  1596. config := server.Config()
  1597. if config.Limits.Multiline.MaxBytes < rb.session.batch.message.LenBytes() {
  1598. if histType != history.Notice {
  1599. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_BYTES", strconv.Itoa(config.Limits.Multiline.MaxBytes))
  1600. }
  1601. rb.session.batch = MultilineBatch{}
  1602. } else if config.Limits.Multiline.MaxLines != 0 && config.Limits.Multiline.MaxLines < rb.session.batch.message.LenLines() {
  1603. if histType != history.Notice {
  1604. rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_MAX_LINES", strconv.Itoa(config.Limits.Multiline.MaxLines))
  1605. }
  1606. rb.session.batch = MultilineBatch{}
  1607. }
  1608. }
  1609. // NOTICE <target>{,<target>} <message>
  1610. // PRIVMSG <target>{,<target>} <message>
  1611. // TAGMSG <target>{,<target>}
  1612. func messageHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1613. histType, err := msgCommandToHistType(msg.Command)
  1614. if err != nil {
  1615. return false
  1616. }
  1617. if isBatched, batchTag := msg.GetTag("batch"); isBatched {
  1618. absorbBatchedMessage(server, client, msg, batchTag, histType, rb)
  1619. return false
  1620. }
  1621. cnick := client.Nick()
  1622. clientOnlyTags := msg.ClientOnlyTags()
  1623. if histType == history.Tagmsg && len(clientOnlyTags) == 0 {
  1624. // nothing to do
  1625. return false
  1626. }
  1627. targets := strings.Split(msg.Params[0], ",")
  1628. var message string
  1629. if len(msg.Params) > 1 {
  1630. message = msg.Params[1]
  1631. }
  1632. if histType != history.Tagmsg && message == "" {
  1633. rb.Add(nil, server.name, ERR_NOTEXTTOSEND, cnick, client.t("No text to send"))
  1634. return false
  1635. }
  1636. if rb.session.isTor && utils.IsRestrictedCTCPMessage(message) {
  1637. // note that error replies are never sent for NOTICE
  1638. if histType != history.Notice {
  1639. rb.Notice(client.t("CTCP messages are disabled over Tor"))
  1640. }
  1641. return false
  1642. }
  1643. for i, targetString := range targets {
  1644. // max of four targets per privmsg
  1645. if i == maxTargets {
  1646. break
  1647. }
  1648. // each target gets distinct msgids
  1649. splitMsg := utils.MakeMessage(message)
  1650. dispatchMessageToTarget(client, clientOnlyTags, histType, msg.Command, targetString, splitMsg, rb)
  1651. }
  1652. return false
  1653. }
  1654. func dispatchMessageToTarget(client *Client, tags map[string]string, histType history.ItemType, command, target string, message utils.SplitMessage, rb *ResponseBuffer) {
  1655. server := client.server
  1656. prefixes, target := modes.SplitChannelMembershipPrefixes(target)
  1657. lowestPrefix := modes.GetLowestChannelModePrefix(prefixes)
  1658. if len(target) == 0 {
  1659. return
  1660. } else if target[0] == '#' {
  1661. channel := server.channels.Get(target)
  1662. if channel == nil {
  1663. if histType != history.Notice {
  1664. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(target), client.t("No such channel"))
  1665. }
  1666. return
  1667. }
  1668. channel.SendSplitMessage(command, lowestPrefix, tags, client, message, rb)
  1669. } else {
  1670. // NOTICE and TAGMSG to services are ignored
  1671. if histType == history.Privmsg {
  1672. lowercaseTarget := strings.ToLower(target)
  1673. if service, isService := OragonoServices[lowercaseTarget]; isService {
  1674. servicePrivmsgHandler(service, server, client, message.Message, rb)
  1675. return
  1676. } else if _, isZNC := zncHandlers[lowercaseTarget]; isZNC {
  1677. zncPrivmsgHandler(client, lowercaseTarget, message.Message, rb)
  1678. return
  1679. }
  1680. }
  1681. user := server.clients.Get(target)
  1682. if user == nil {
  1683. if histType != history.Notice {
  1684. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.Nick(), target, "No such nick")
  1685. }
  1686. return
  1687. }
  1688. tDetails := user.Details()
  1689. tnick := tDetails.nick
  1690. details := client.Details()
  1691. nickMaskString := details.nickMask
  1692. accountName := details.accountName
  1693. var deliverySessions []*Session
  1694. // restrict messages appropriately when +R is set
  1695. // intentionally make the sending user think the message went through fine
  1696. allowedPlusR := details.account != "" || !user.HasMode(modes.RegisteredOnly)
  1697. if allowedPlusR {
  1698. deliverySessions = append(deliverySessions, user.Sessions()...)
  1699. }
  1700. // all sessions of the sender, except the originating session, get a copy as well:
  1701. if client != user {
  1702. for _, session := range client.Sessions() {
  1703. if session != rb.session {
  1704. deliverySessions = append(deliverySessions, session)
  1705. }
  1706. }
  1707. }
  1708. for _, session := range deliverySessions {
  1709. hasTagsCap := session.capabilities.Has(caps.MessageTags)
  1710. // don't send TAGMSG at all if they don't have the tags cap
  1711. if histType == history.Tagmsg && hasTagsCap {
  1712. session.sendFromClientInternal(false, message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1713. } else if histType != history.Tagmsg && !(session.isTor && message.IsRestrictedCTCPMessage()) {
  1714. tagsToSend := tags
  1715. if !hasTagsCap {
  1716. tagsToSend = nil
  1717. }
  1718. session.sendSplitMsgFromClientInternal(false, nickMaskString, accountName, tagsToSend, command, tnick, message)
  1719. }
  1720. }
  1721. // the originating session may get an echo message:
  1722. if rb.session.capabilities.Has(caps.EchoMessage) {
  1723. hasTagsCap := rb.session.capabilities.Has(caps.MessageTags)
  1724. if histType == history.Tagmsg && hasTagsCap {
  1725. rb.AddFromClient(message.Time, message.Msgid, nickMaskString, accountName, tags, command, tnick)
  1726. } else {
  1727. tagsToSend := tags
  1728. if !hasTagsCap {
  1729. tagsToSend = nil
  1730. }
  1731. rb.AddSplitMessageFromClient(nickMaskString, accountName, tagsToSend, command, tnick, message)
  1732. }
  1733. }
  1734. if histType != history.Notice && user.Away() {
  1735. //TODO(dan): possibly implement cooldown of away notifications to users
  1736. rb.Add(nil, server.name, RPL_AWAY, client.Nick(), tnick, user.AwayMessage())
  1737. }
  1738. config := server.Config()
  1739. if !config.History.Enabled {
  1740. return
  1741. }
  1742. item := history.Item{
  1743. Type: histType,
  1744. Message: message,
  1745. Nick: nickMaskString,
  1746. AccountName: accountName,
  1747. Tags: tags,
  1748. }
  1749. if !item.IsStorable() {
  1750. return
  1751. }
  1752. targetedItem := item
  1753. targetedItem.Params[0] = tnick
  1754. cStatus, _ := client.historyStatus(config)
  1755. tStatus, _ := user.historyStatus(config)
  1756. // add to ephemeral history
  1757. if cStatus == HistoryEphemeral {
  1758. targetedItem.CfCorrespondent = tDetails.nickCasefolded
  1759. client.history.Add(targetedItem)
  1760. }
  1761. if tStatus == HistoryEphemeral && client != user {
  1762. item.CfCorrespondent = details.nickCasefolded
  1763. user.history.Add(item)
  1764. }
  1765. if cStatus == HistoryPersistent || tStatus == HistoryPersistent {
  1766. targetedItem.CfCorrespondent = ""
  1767. server.historyDB.AddDirectMessage(details.nickCasefolded, details.account, tDetails.nickCasefolded, tDetails.account, targetedItem)
  1768. }
  1769. }
  1770. }
  1771. // NPC <target> <sourcenick> <message>
  1772. func npcHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1773. target := msg.Params[0]
  1774. fakeSource := msg.Params[1]
  1775. message := msg.Params[2]
  1776. _, err := CasefoldName(fakeSource)
  1777. if err != nil {
  1778. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1779. return false
  1780. }
  1781. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1782. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  1783. return false
  1784. }
  1785. // NPCA <target> <sourcenick> <message>
  1786. func npcaHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1787. target := msg.Params[0]
  1788. fakeSource := msg.Params[1]
  1789. message := msg.Params[2]
  1790. sourceString := fmt.Sprintf(npcNickMask, fakeSource, client.nick)
  1791. _, err := CasefoldName(fakeSource)
  1792. if err != nil {
  1793. client.Send(nil, client.server.name, ERR_CANNOTSENDRP, target, client.t("Fake source must be a valid nickname"))
  1794. return false
  1795. }
  1796. sendRoleplayMessage(server, client, sourceString, target, true, message, rb)
  1797. return false
  1798. }
  1799. // OPER <name> [password]
  1800. func operHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1801. if client.HasMode(modes.Operator) {
  1802. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "OPER", client.t("You're already opered-up!"))
  1803. return false
  1804. }
  1805. // must pass at least one check, and all enabled checks
  1806. var checkPassed, checkFailed bool
  1807. oper := server.GetOperator(msg.Params[0])
  1808. if oper != nil {
  1809. if oper.Fingerprint != "" {
  1810. if oper.Fingerprint == rb.session.certfp {
  1811. checkPassed = true
  1812. } else {
  1813. checkFailed = true
  1814. }
  1815. }
  1816. if !checkFailed && oper.Pass != nil {
  1817. if len(msg.Params) == 1 || bcrypt.CompareHashAndPassword(oper.Pass, []byte(msg.Params[1])) != nil {
  1818. checkFailed = true
  1819. } else {
  1820. checkPassed = true
  1821. }
  1822. }
  1823. }
  1824. if !checkPassed || checkFailed {
  1825. rb.Add(nil, server.name, ERR_PASSWDMISMATCH, client.Nick(), client.t("Password incorrect"))
  1826. client.Quit(client.t("Password incorrect"), rb.session)
  1827. return true
  1828. }
  1829. applyOper(client, oper, rb)
  1830. return false
  1831. }
  1832. // adds or removes operator status
  1833. // XXX: to add oper, this calls into ApplyUserModeChanges, but to remove oper,
  1834. // ApplyUserModeChanges calls into this, because the commands are asymmetric
  1835. // (/OPER to add, /MODE self -o to remove)
  1836. func applyOper(client *Client, oper *Oper, rb *ResponseBuffer) {
  1837. details := client.Details()
  1838. client.SetOper(oper)
  1839. newDetails := client.Details()
  1840. if details.nickMask != newDetails.nickMask {
  1841. client.sendChghost(details.nickMask, newDetails.hostname)
  1842. }
  1843. if oper != nil {
  1844. // set new modes: modes.Operator, plus anything specified in the config
  1845. modeChanges := make([]modes.ModeChange, len(oper.Modes)+1)
  1846. modeChanges[0] = modes.ModeChange{
  1847. Mode: modes.Operator,
  1848. Op: modes.Add,
  1849. }
  1850. copy(modeChanges[1:], oper.Modes)
  1851. applied := ApplyUserModeChanges(client, modeChanges, true)
  1852. 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))
  1853. rb.Broadcast(nil, client.server.name, RPL_YOUREOPER, details.nick, client.t("You are now an IRC operator"))
  1854. rb.Broadcast(nil, client.server.name, "MODE", details.nick, applied.String())
  1855. } else {
  1856. client.server.snomasks.Send(sno.LocalOpers, fmt.Sprintf(ircfmt.Unescape("Client deopered $c[grey][$r%s$c[grey]]"), newDetails.nickMask))
  1857. }
  1858. for _, session := range client.Sessions() {
  1859. // client may now be unthrottled by the fakelag system
  1860. session.resetFakelag()
  1861. }
  1862. }
  1863. // DEOPER
  1864. func deoperHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1865. // pretend they sent /MODE $nick -o
  1866. fakeModeMsg := ircmsg.MakeMessage(nil, "", "MODE", client.Nick(), "-o")
  1867. return umodeHandler(server, client, fakeModeMsg, rb)
  1868. }
  1869. // PART <channel>{,<channel>} [<reason>]
  1870. func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1871. channels := strings.Split(msg.Params[0], ",")
  1872. var reason string
  1873. if len(msg.Params) > 1 {
  1874. reason = msg.Params[1]
  1875. }
  1876. for _, chname := range channels {
  1877. if chname == "" {
  1878. continue // #679
  1879. }
  1880. err := server.channels.Part(client, chname, reason, rb)
  1881. if err == errNoSuchChannel {
  1882. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(chname), client.t("No such channel"))
  1883. }
  1884. }
  1885. return false
  1886. }
  1887. // PASS <password>
  1888. func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1889. if client.registered {
  1890. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister"))
  1891. return false
  1892. }
  1893. // if no password exists, skip checking
  1894. serverPassword := server.Config().Server.passwordBytes
  1895. if serverPassword == nil {
  1896. return false
  1897. }
  1898. // check the provided password
  1899. password := []byte(msg.Params[0])
  1900. rb.session.sentPassCommand = bcrypt.CompareHashAndPassword(serverPassword, password) == nil
  1901. // if they failed the check, we'll bounce them later when they try to complete registration
  1902. return false
  1903. }
  1904. // PING [params...]
  1905. func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1906. rb.Add(nil, server.name, "PONG", msg.Params...)
  1907. return false
  1908. }
  1909. // PONG [params...]
  1910. func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1911. // client gets touched when they send this command, so we don't need to do anything
  1912. return false
  1913. }
  1914. // QUIT [<reason>]
  1915. func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1916. reason := "Quit"
  1917. if len(msg.Params) > 0 {
  1918. reason += ": " + msg.Params[0]
  1919. }
  1920. client.Quit(reason, rb.session)
  1921. return true
  1922. }
  1923. // REHASH
  1924. func rehashHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  1925. server.logger.Info("server", fmt.Sprintf("REHASH command used by %s", client.nick))
  1926. err := server.rehash()
  1927. if err == nil {
  1928. rb.Add(nil, server.name, RPL_REHASHING, client.nick, "ircd.yaml", client.t("Rehashing"))
  1929. } else {
  1930. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  1931. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "REHASH", err.Error())
  1932. }
  1933. return false
  1934. }
  1935. // RENAME <oldchan> <newchan> [<reason>]
  1936. func renameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) (result bool) {
  1937. result = false
  1938. oldName, newName := msg.Params[0], msg.Params[1]
  1939. var reason string
  1940. if 2 < len(msg.Params) {
  1941. reason = msg.Params[2]
  1942. }
  1943. channel := server.channels.Get(oldName)
  1944. if channel == nil {
  1945. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(oldName), client.t("No such channel"))
  1946. return false
  1947. }
  1948. if !(channel.ClientIsAtLeast(client, modes.Operator) || client.HasRoleCapabs("chanreg")) {
  1949. rb.Add(nil, server.name, ERR_CHANOPRIVSNEEDED, client.Nick(), oldName, client.t("You're not a channel operator"))
  1950. return false
  1951. }
  1952. founder := channel.Founder()
  1953. if founder != "" && founder != client.Account() {
  1954. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, newName, client.t("Only channel founders can change registered channels"))
  1955. return false
  1956. }
  1957. // perform the channel rename
  1958. err := server.channels.Rename(oldName, newName)
  1959. if err == errInvalidChannelName {
  1960. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1961. } else if err == errChannelNameInUse {
  1962. rb.Add(nil, server.name, ERR_CHANNAMEINUSE, client.Nick(), utils.SafeErrorParam(newName), client.t(err.Error()))
  1963. } else if err != nil {
  1964. rb.Add(nil, server.name, ERR_CANNOTRENAME, client.Nick(), oldName, utils.SafeErrorParam(newName), client.t("Cannot rename channel"))
  1965. }
  1966. if err != nil {
  1967. return false
  1968. }
  1969. // send RENAME messages
  1970. clientPrefix := client.NickMaskString()
  1971. for _, mcl := range channel.Members() {
  1972. mDetails := mcl.Details()
  1973. for _, mSession := range mcl.Sessions() {
  1974. targetRb := rb
  1975. targetPrefix := clientPrefix
  1976. if mSession != rb.session {
  1977. targetRb = NewResponseBuffer(mSession)
  1978. targetPrefix = mDetails.nickMask
  1979. }
  1980. if mSession.capabilities.Has(caps.Rename) {
  1981. if reason != "" {
  1982. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName, reason)
  1983. } else {
  1984. targetRb.Add(nil, clientPrefix, "RENAME", oldName, newName)
  1985. }
  1986. } else {
  1987. if reason != "" {
  1988. targetRb.Add(nil, targetPrefix, "PART", oldName, fmt.Sprintf(mcl.t("Channel renamed: %s"), reason))
  1989. } else {
  1990. targetRb.Add(nil, targetPrefix, "PART", oldName, mcl.t("Channel renamed"))
  1991. }
  1992. if mSession.capabilities.Has(caps.ExtendedJoin) {
  1993. targetRb.Add(nil, targetPrefix, "JOIN", newName, mDetails.accountName, mDetails.realname)
  1994. } else {
  1995. targetRb.Add(nil, targetPrefix, "JOIN", newName)
  1996. }
  1997. channel.SendTopic(mcl, targetRb, false)
  1998. channel.Names(mcl, targetRb)
  1999. }
  2000. if mcl != client {
  2001. targetRb.Send(false)
  2002. }
  2003. }
  2004. }
  2005. return false
  2006. }
  2007. // RESUME <token> [timestamp]
  2008. func resumeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2009. details := ResumeDetails{
  2010. PresentedToken: msg.Params[0],
  2011. }
  2012. if client.registered {
  2013. rb.Add(nil, server.name, "FAIL", "RESUME", "REGISTRATION_IS_COMPLETED", client.t("Cannot resume connection, connection registration has already been completed"))
  2014. return false
  2015. }
  2016. if 1 < len(msg.Params) {
  2017. ts, err := time.Parse(IRCv3TimestampFormat, msg.Params[1])
  2018. if err == nil {
  2019. details.Timestamp = ts
  2020. } else {
  2021. rb.Add(nil, server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it"))
  2022. }
  2023. }
  2024. rb.session.resumeDetails = &details
  2025. return false
  2026. }
  2027. // SANICK <oldnick> <nickname>
  2028. func sanickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2029. targetNick := strings.TrimSpace(msg.Params[0])
  2030. target := server.clients.Get(targetNick)
  2031. if target == nil {
  2032. rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, msg.Params[0], client.t("No such nick"))
  2033. return false
  2034. }
  2035. performNickChange(server, client, target, nil, msg.Params[1], rb)
  2036. return false
  2037. }
  2038. // SCENE <target> <message>
  2039. func sceneHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2040. target := msg.Params[0]
  2041. message := msg.Params[1]
  2042. sourceString := fmt.Sprintf(sceneNickMask, client.nick)
  2043. sendRoleplayMessage(server, client, sourceString, target, false, message, rb)
  2044. return false
  2045. }
  2046. // SETNAME <realname>
  2047. func setnameHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2048. realname := msg.Params[0]
  2049. client.SetRealname(realname)
  2050. details := client.Details()
  2051. // alert friends
  2052. now := time.Now().UTC()
  2053. for session := range client.Friends(caps.SetName) {
  2054. session.sendFromClientInternal(false, now, "", details.nickMask, details.account, nil, "SETNAME", details.realname)
  2055. }
  2056. return false
  2057. }
  2058. // TIME
  2059. func timeHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2060. rb.Add(nil, server.name, RPL_TIME, client.nick, server.name, time.Now().UTC().Format(time.RFC1123))
  2061. return false
  2062. }
  2063. // TOPIC <channel> [<topic>]
  2064. func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2065. channel := server.channels.Get(msg.Params[0])
  2066. if channel == nil {
  2067. rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, utils.SafeErrorParam(msg.Params[0]), client.t("No such channel"))
  2068. return false
  2069. }
  2070. if len(msg.Params) > 1 {
  2071. channel.SetTopic(client, msg.Params[1], rb)
  2072. } else {
  2073. channel.SendTopic(client, rb, true)
  2074. }
  2075. return false
  2076. }
  2077. // UNDLINE <ip>|<net>
  2078. func unDLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2079. // check oper permissions
  2080. oper := client.Oper()
  2081. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2082. rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
  2083. return false
  2084. }
  2085. // get host
  2086. hostString := msg.Params[0]
  2087. // check host
  2088. hostNet, err := utils.NormalizedNetFromString(hostString)
  2089. if err != nil {
  2090. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
  2091. return false
  2092. }
  2093. err = server.dlines.RemoveNetwork(hostNet)
  2094. if err != nil {
  2095. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2096. return false
  2097. }
  2098. hostString = utils.NetToNormalizedString(hostNet)
  2099. rb.Notice(fmt.Sprintf(client.t("Removed D-Line for %s"), hostString))
  2100. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed D-Line for %s"), client.nick, hostString))
  2101. return false
  2102. }
  2103. // UNKLINE <mask>
  2104. func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2105. details := client.Details()
  2106. // check oper permissions
  2107. oper := client.Oper()
  2108. if oper == nil || !oper.Class.Capabilities["oper:local_unban"] {
  2109. rb.Add(nil, server.name, ERR_NOPRIVS, details.nick, msg.Command, client.t("Insufficient oper privs"))
  2110. return false
  2111. }
  2112. // get host
  2113. mask := msg.Params[0]
  2114. mask, err := CanonicalizeMaskWildcard(mask)
  2115. if err != nil {
  2116. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, client.t("Erroneous nickname"))
  2117. return false
  2118. }
  2119. err = server.klines.RemoveMask(mask)
  2120. if err != nil {
  2121. rb.Add(nil, server.name, ERR_UNKNOWNERROR, details.nick, msg.Command, fmt.Sprintf(client.t("Could not remove ban [%s]"), err.Error()))
  2122. return false
  2123. }
  2124. rb.Notice(fmt.Sprintf(client.t("Removed K-Line for %s"), mask))
  2125. server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), details.nick, mask))
  2126. return false
  2127. }
  2128. // USER <username> * 0 <realname>
  2129. func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2130. if client.registered {
  2131. rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.Nick(), client.t("You may not reregister"))
  2132. return false
  2133. }
  2134. err := client.SetNames(msg.Params[0], msg.Params[3], false)
  2135. if err == errInvalidUsername {
  2136. // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead.
  2137. // fixes clients that just use their nick as a username so they can still use the interesting nick
  2138. if client.preregNick == msg.Params[0] {
  2139. client.SetNames("user", msg.Params[3], false)
  2140. } else {
  2141. rb.Add(nil, server.name, ERR_INVALIDUSERNAME, client.Nick(), client.t("Malformed username"))
  2142. }
  2143. }
  2144. return false
  2145. }
  2146. // USERHOST <nickname>{ <nickname>}
  2147. func userhostHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2148. returnedClients := make(ClientSet)
  2149. var tl utils.TokenLineBuilder
  2150. tl.Initialize(400, " ")
  2151. for i, nickname := range msg.Params {
  2152. if i >= 10 {
  2153. break
  2154. }
  2155. target := server.clients.Get(nickname)
  2156. if target == nil {
  2157. continue
  2158. }
  2159. // to prevent returning multiple results for a single nick
  2160. if returnedClients.Has(target) {
  2161. continue
  2162. }
  2163. returnedClients.Add(target)
  2164. var isOper, isAway string
  2165. if target.HasMode(modes.Operator) {
  2166. isOper = "*"
  2167. }
  2168. if target.Away() {
  2169. isAway = "-"
  2170. } else {
  2171. isAway = "+"
  2172. }
  2173. details := target.Details()
  2174. tl.Add(fmt.Sprintf("%s%s=%s%s@%s", details.nick, isOper, isAway, details.username, details.hostname))
  2175. }
  2176. lines := tl.Lines()
  2177. if lines == nil {
  2178. lines = []string{""}
  2179. }
  2180. nick := client.Nick()
  2181. for _, line := range lines {
  2182. rb.Add(nil, client.server.name, RPL_USERHOST, nick, line)
  2183. }
  2184. return false
  2185. }
  2186. // VERSION
  2187. func versionHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2188. rb.Add(nil, server.name, RPL_VERSION, client.nick, Ver, server.name)
  2189. server.RplISupport(client, rb)
  2190. return false
  2191. }
  2192. // WEBIRC <password> <gateway> <hostname> <ip> [:flag1 flag2=x flag3]
  2193. func webircHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2194. // only allow unregistered clients to use this command
  2195. if client.registered || client.proxiedIP != nil {
  2196. return false
  2197. }
  2198. // process flags
  2199. var secure bool
  2200. if 4 < len(msg.Params) {
  2201. for _, x := range strings.Split(msg.Params[4], " ") {
  2202. // split into key=value
  2203. var key string
  2204. if strings.Contains(x, "=") {
  2205. y := strings.SplitN(x, "=", 2)
  2206. key, _ = y[0], y[1]
  2207. } else {
  2208. key = x
  2209. }
  2210. lkey := strings.ToLower(key)
  2211. if lkey == "tls" || lkey == "secure" {
  2212. // only accept "tls" flag if the gateway's connection to us is secure as well
  2213. if client.HasMode(modes.TLS) || client.realIP.IsLoopback() {
  2214. secure = true
  2215. }
  2216. }
  2217. }
  2218. }
  2219. givenPassword := []byte(msg.Params[0])
  2220. for _, info := range server.Config().Server.WebIRC {
  2221. if utils.IPInNets(client.realIP, info.allowedNets) {
  2222. // confirm password and/or fingerprint
  2223. if 0 < len(info.Password) && bcrypt.CompareHashAndPassword(info.Password, givenPassword) != nil {
  2224. continue
  2225. }
  2226. if info.Fingerprint != "" && info.Fingerprint != rb.session.certfp {
  2227. continue
  2228. }
  2229. proxiedIP := msg.Params[3]
  2230. // see #211; websocket gateways will wrap ipv6 addresses in square brackets
  2231. // because IRC parameters can't start with :
  2232. if strings.HasPrefix(proxiedIP, "[") && strings.HasSuffix(proxiedIP, "]") {
  2233. proxiedIP = proxiedIP[1 : len(proxiedIP)-1]
  2234. }
  2235. err, quitMsg := client.ApplyProxiedIP(rb.session, proxiedIP, secure)
  2236. if err != nil {
  2237. client.Quit(quitMsg, rb.session)
  2238. return true
  2239. } else {
  2240. return false
  2241. }
  2242. }
  2243. }
  2244. client.Quit(client.t("WEBIRC command is not usable from your address or incorrect password given"), rb.session)
  2245. return true
  2246. }
  2247. // WHO [<mask> [o]]
  2248. func whoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2249. mask := msg.Params[0]
  2250. var err error
  2251. if mask == "" {
  2252. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "WHO", client.t("First param must be a mask or channel"))
  2253. return false
  2254. } else if mask[0] == '#' {
  2255. mask, err = CasefoldChannel(msg.Params[0])
  2256. } else {
  2257. mask, err = CanonicalizeMaskWildcard(mask)
  2258. }
  2259. if err != nil {
  2260. rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), "WHO", client.t("Mask isn't valid"))
  2261. return false
  2262. }
  2263. //TODO(dan): is this used and would I put this param in the Modern doc?
  2264. // if not, can we remove it?
  2265. //var operatorOnly bool
  2266. //if len(msg.Params) > 1 && msg.Params[1] == "o" {
  2267. // operatorOnly = true
  2268. //}
  2269. isOper := client.HasMode(modes.Operator)
  2270. if mask[0] == '#' {
  2271. // TODO implement wildcard matching
  2272. //TODO(dan): ^ only for opers
  2273. channel := server.channels.Get(mask)
  2274. if channel != nil {
  2275. isJoined := channel.hasClient(client)
  2276. if !channel.flags.HasMode(modes.Secret) || isJoined || isOper {
  2277. for _, member := range channel.Members() {
  2278. if !member.HasMode(modes.Invisible) || isJoined || isOper {
  2279. client.rplWhoReply(channel, member, rb)
  2280. }
  2281. }
  2282. }
  2283. }
  2284. } else {
  2285. for mclient := range server.clients.FindAll(mask) {
  2286. client.rplWhoReply(nil, mclient, rb)
  2287. }
  2288. }
  2289. rb.Add(nil, server.name, RPL_ENDOFWHO, client.nick, mask, client.t("End of WHO list"))
  2290. return false
  2291. }
  2292. // WHOIS [<target>] <mask>{,<mask>}
  2293. func whoisHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2294. var masksString string
  2295. //var target string
  2296. if len(msg.Params) > 1 {
  2297. //target = msg.Params[0]
  2298. masksString = msg.Params[1]
  2299. } else {
  2300. masksString = msg.Params[0]
  2301. }
  2302. handleService := func(nick string) bool {
  2303. cfnick, _ := CasefoldName(nick)
  2304. service, ok := OragonoServices[cfnick]
  2305. if !ok {
  2306. return false
  2307. }
  2308. clientNick := client.Nick()
  2309. rb.Add(nil, client.server.name, RPL_WHOISUSER, clientNick, service.Name, service.Name, "localhost", "*", fmt.Sprintf(client.t("Network service, for more info /msg %s HELP"), service.Name))
  2310. // hehe
  2311. if client.HasMode(modes.TLS) {
  2312. rb.Add(nil, client.server.name, RPL_WHOISSECURE, clientNick, service.Name, client.t("is using a secure connection"))
  2313. }
  2314. return true
  2315. }
  2316. if client.HasMode(modes.Operator) {
  2317. for _, mask := range strings.Split(masksString, ",") {
  2318. matches := server.clients.FindAll(mask)
  2319. if len(matches) == 0 && !handleService(mask) {
  2320. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(mask), client.t("No such nick"))
  2321. continue
  2322. }
  2323. for mclient := range matches {
  2324. client.getWhoisOf(mclient, rb)
  2325. }
  2326. }
  2327. } else {
  2328. // only get the first request; also require a nick, not a mask
  2329. nick := strings.Split(masksString, ",")[0]
  2330. mclient := server.clients.Get(nick)
  2331. if mclient != nil {
  2332. client.getWhoisOf(mclient, rb)
  2333. } else if !handleService(nick) {
  2334. rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.Nick(), utils.SafeErrorParam(masksString), client.t("No such nick"))
  2335. }
  2336. // fall through, ENDOFWHOIS is always sent
  2337. }
  2338. rb.Add(nil, server.name, RPL_ENDOFWHOIS, client.nick, utils.SafeErrorParam(masksString), client.t("End of /WHOIS list"))
  2339. return false
  2340. }
  2341. // WHOWAS <nickname> [<count> [<server>]]
  2342. func whowasHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2343. nicknames := strings.Split(msg.Params[0], ",")
  2344. // 0 means "all the entries", as does a negative number
  2345. var count int
  2346. if len(msg.Params) > 1 {
  2347. count, _ = strconv.Atoi(msg.Params[1])
  2348. if count < 0 {
  2349. count = 0
  2350. }
  2351. }
  2352. //var target string
  2353. //if len(msg.Params) > 2 {
  2354. // target = msg.Params[2]
  2355. //}
  2356. cnick := client.Nick()
  2357. for _, nickname := range nicknames {
  2358. if len(nickname) == 0 {
  2359. continue
  2360. }
  2361. results := server.whoWas.Find(nickname, count)
  2362. if len(results) == 0 {
  2363. rb.Add(nil, server.name, ERR_WASNOSUCHNICK, cnick, utils.SafeErrorParam(nickname), client.t("There was no such nickname"))
  2364. } else {
  2365. for _, whoWas := range results {
  2366. rb.Add(nil, server.name, RPL_WHOWASUSER, cnick, whoWas.nick, whoWas.username, whoWas.hostname, "*", whoWas.realname)
  2367. }
  2368. }
  2369. rb.Add(nil, server.name, RPL_ENDOFWHOWAS, cnick, utils.SafeErrorParam(nickname), client.t("End of WHOWAS"))
  2370. }
  2371. return false
  2372. }
  2373. // ZNC <module> [params]
  2374. func zncHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
  2375. zncModuleHandler(client, msg.Params[0], msg.Params[1:], rb)
  2376. return false
  2377. }