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

accounts.go 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "net/smtp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode"
  14. "github.com/oragono/oragono/irc/caps"
  15. "github.com/oragono/oragono/irc/passwd"
  16. "github.com/oragono/oragono/irc/utils"
  17. "github.com/tidwall/buntdb"
  18. )
  19. const (
  20. keyAccountExists = "account.exists %s"
  21. keyAccountVerified = "account.verified %s"
  22. keyAccountCallback = "account.callback %s"
  23. keyAccountVerificationCode = "account.verificationcode %s"
  24. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  25. keyAccountRegTime = "account.registered.time %s"
  26. keyAccountCredentials = "account.credentials %s"
  27. keyAccountAdditionalNicks = "account.additionalnicks %s"
  28. keyAccountSettings = "account.settings %s"
  29. keyAccountVHost = "account.vhost %s"
  30. keyCertToAccount = "account.creds.certfp %s"
  31. keyAccountChannels = "account.channels %s"
  32. keyVHostQueueAcctToId = "vhostQueue %s"
  33. vhostRequestIdx = "vhostQueue"
  34. )
  35. // everything about accounts is persistent; therefore, the database is the authoritative
  36. // source of truth for all account information. anything on the heap is just a cache
  37. type AccountManager struct {
  38. // XXX these are up here so they can be aligned to a 64-bit boundary, please forgive me
  39. // autoincrementing ID for vhost requests:
  40. vhostRequestID uint64
  41. vhostRequestPendingCount uint64
  42. sync.RWMutex // tier 2
  43. serialCacheUpdateMutex sync.Mutex // tier 3
  44. vHostUpdateMutex sync.Mutex // tier 3
  45. server *Server
  46. // track clients logged in to accounts
  47. accountToClients map[string][]*Client
  48. nickToAccount map[string]string
  49. skeletonToAccount map[string]string
  50. accountToMethod map[string]NickEnforcementMethod
  51. }
  52. func (am *AccountManager) Initialize(server *Server) {
  53. am.accountToClients = make(map[string][]*Client)
  54. am.nickToAccount = make(map[string]string)
  55. am.skeletonToAccount = make(map[string]string)
  56. am.accountToMethod = make(map[string]NickEnforcementMethod)
  57. am.server = server
  58. am.buildNickToAccountIndex()
  59. am.initVHostRequestQueue()
  60. }
  61. func (am *AccountManager) buildNickToAccountIndex() {
  62. if !am.server.AccountConfig().NickReservation.Enabled {
  63. return
  64. }
  65. nickToAccount := make(map[string]string)
  66. skeletonToAccount := make(map[string]string)
  67. accountToMethod := make(map[string]NickEnforcementMethod)
  68. existsPrefix := fmt.Sprintf(keyAccountExists, "")
  69. am.serialCacheUpdateMutex.Lock()
  70. defer am.serialCacheUpdateMutex.Unlock()
  71. err := am.server.store.View(func(tx *buntdb.Tx) error {
  72. err := tx.AscendGreaterOrEqual("", existsPrefix, func(key, value string) bool {
  73. if !strings.HasPrefix(key, existsPrefix) {
  74. return false
  75. }
  76. account := strings.TrimPrefix(key, existsPrefix)
  77. if _, err := tx.Get(fmt.Sprintf(keyAccountVerified, account)); err == nil {
  78. nickToAccount[account] = account
  79. accountName, err := tx.Get(fmt.Sprintf(keyAccountName, account))
  80. if err != nil {
  81. am.server.logger.Error("internal", "missing account name for", account)
  82. } else {
  83. skeleton, _ := Skeleton(accountName)
  84. skeletonToAccount[skeleton] = account
  85. }
  86. }
  87. if rawNicks, err := tx.Get(fmt.Sprintf(keyAccountAdditionalNicks, account)); err == nil {
  88. additionalNicks := unmarshalReservedNicks(rawNicks)
  89. for _, nick := range additionalNicks {
  90. cfnick, _ := CasefoldName(nick)
  91. nickToAccount[cfnick] = account
  92. skeleton, _ := Skeleton(nick)
  93. skeletonToAccount[skeleton] = account
  94. }
  95. }
  96. if rawPrefs, err := tx.Get(fmt.Sprintf(keyAccountSettings, account)); err == nil {
  97. var prefs AccountSettings
  98. err := json.Unmarshal([]byte(rawPrefs), &prefs)
  99. if err == nil && prefs.NickEnforcement != NickEnforcementOptional {
  100. accountToMethod[account] = prefs.NickEnforcement
  101. } else {
  102. am.server.logger.Error("internal", "corrupt account creds", account)
  103. }
  104. }
  105. return true
  106. })
  107. return err
  108. })
  109. if err != nil {
  110. am.server.logger.Error("internal", "couldn't read reserved nicks", err.Error())
  111. } else {
  112. am.Lock()
  113. am.nickToAccount = nickToAccount
  114. am.skeletonToAccount = skeletonToAccount
  115. am.accountToMethod = accountToMethod
  116. am.Unlock()
  117. }
  118. }
  119. func (am *AccountManager) initVHostRequestQueue() {
  120. if !am.server.AccountConfig().VHosts.Enabled {
  121. return
  122. }
  123. am.vHostUpdateMutex.Lock()
  124. defer am.vHostUpdateMutex.Unlock()
  125. // the db maps the account name to the autoincrementing integer ID of its request
  126. // create an numerically ordered index on ID, so we can list the oldest requests
  127. // finally, collect the integer id of the newest request and the total request count
  128. var total uint64
  129. var lastIDStr string
  130. err := am.server.store.Update(func(tx *buntdb.Tx) error {
  131. err := tx.CreateIndex(vhostRequestIdx, fmt.Sprintf(keyVHostQueueAcctToId, "*"), buntdb.IndexInt)
  132. if err != nil {
  133. return err
  134. }
  135. return tx.Descend(vhostRequestIdx, func(key, value string) bool {
  136. if lastIDStr == "" {
  137. lastIDStr = value
  138. }
  139. total++
  140. return true
  141. })
  142. })
  143. if err != nil {
  144. am.server.logger.Error("internal", "could not create vhost queue index", err.Error())
  145. }
  146. lastID, _ := strconv.ParseUint(lastIDStr, 10, 64)
  147. am.server.logger.Debug("services", fmt.Sprintf("vhost queue length is %d, autoincrementing id is %d", total, lastID))
  148. atomic.StoreUint64(&am.vhostRequestID, lastID)
  149. atomic.StoreUint64(&am.vhostRequestPendingCount, total)
  150. }
  151. func (am *AccountManager) NickToAccount(nick string) string {
  152. cfnick, err := CasefoldName(nick)
  153. if err != nil {
  154. return ""
  155. }
  156. am.RLock()
  157. defer am.RUnlock()
  158. return am.nickToAccount[cfnick]
  159. }
  160. // given an account, combine stored enforcement method with the config settings
  161. // to compute the actual enforcement method
  162. func configuredEnforcementMethod(config *Config, storedMethod NickEnforcementMethod) (result NickEnforcementMethod) {
  163. if !config.Accounts.NickReservation.Enabled {
  164. return NickEnforcementNone
  165. }
  166. result = storedMethod
  167. // if they don't have a custom setting, or customization is disabled, use the default
  168. if result == NickEnforcementOptional || !config.Accounts.NickReservation.AllowCustomEnforcement {
  169. result = config.Accounts.NickReservation.Method
  170. }
  171. if result == NickEnforcementOptional {
  172. // enforcement was explicitly enabled neither in the config or by the user
  173. result = NickEnforcementNone
  174. }
  175. return
  176. }
  177. // Given a nick, looks up the account that owns it and the method (none/timeout/strict)
  178. // used to enforce ownership.
  179. func (am *AccountManager) EnforcementStatus(cfnick, skeleton string) (account string, method NickEnforcementMethod) {
  180. config := am.server.Config()
  181. if !config.Accounts.NickReservation.Enabled {
  182. return "", NickEnforcementNone
  183. }
  184. am.RLock()
  185. defer am.RUnlock()
  186. finalEnforcementMethod := func(account_ string) (result NickEnforcementMethod) {
  187. storedMethod := am.accountToMethod[account_]
  188. return configuredEnforcementMethod(config, storedMethod)
  189. }
  190. nickAccount := am.nickToAccount[cfnick]
  191. skelAccount := am.skeletonToAccount[skeleton]
  192. if nickAccount == "" && skelAccount == "" {
  193. return "", NickEnforcementNone
  194. } else if nickAccount != "" && (skelAccount == nickAccount || skelAccount == "") {
  195. return nickAccount, finalEnforcementMethod(nickAccount)
  196. } else if skelAccount != "" && nickAccount == "" {
  197. return skelAccount, finalEnforcementMethod(skelAccount)
  198. } else {
  199. // nickAccount != skelAccount and both are nonempty:
  200. // two people have competing claims on (this casefolding of) this nick!
  201. nickMethod := finalEnforcementMethod(nickAccount)
  202. skelMethod := finalEnforcementMethod(skelAccount)
  203. switch {
  204. case skelMethod == NickEnforcementNone:
  205. return nickAccount, nickMethod
  206. case nickMethod == NickEnforcementNone:
  207. return skelAccount, skelMethod
  208. default:
  209. // nobody can use this nick
  210. return "!", NickEnforcementStrict
  211. }
  212. }
  213. }
  214. // Sets a custom enforcement method for an account and stores it in the database.
  215. func (am *AccountManager) SetEnforcementStatus(account string, method NickEnforcementMethod) (finalSettings AccountSettings, err error) {
  216. config := am.server.Config()
  217. if !(config.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.AllowCustomEnforcement) {
  218. err = errFeatureDisabled
  219. return
  220. }
  221. setter := func(in AccountSettings) (out AccountSettings, err error) {
  222. out = in
  223. out.NickEnforcement = method
  224. return out, nil
  225. }
  226. _, err = am.ModifyAccountSettings(account, setter)
  227. if err != nil {
  228. return
  229. }
  230. // this update of the data plane is racey, but it's probably fine
  231. am.Lock()
  232. defer am.Unlock()
  233. if method == NickEnforcementOptional {
  234. delete(am.accountToMethod, account)
  235. } else {
  236. am.accountToMethod[account] = method
  237. }
  238. return
  239. }
  240. func (am *AccountManager) AccountToClients(account string) (result []*Client) {
  241. cfaccount, err := CasefoldName(account)
  242. if err != nil {
  243. return
  244. }
  245. am.RLock()
  246. defer am.RUnlock()
  247. return am.accountToClients[cfaccount]
  248. }
  249. func (am *AccountManager) Register(client *Client, account string, callbackNamespace string, callbackValue string, passphrase string, certfp string) error {
  250. casefoldedAccount, err := CasefoldName(account)
  251. skeleton, skerr := Skeleton(account)
  252. if err != nil || skerr != nil || account == "" || account == "*" {
  253. return errAccountCreation
  254. }
  255. if restrictedNicknames[casefoldedAccount] || restrictedNicknames[skeleton] {
  256. return errAccountAlreadyRegistered
  257. }
  258. config := am.server.AccountConfig()
  259. // final "is registration allowed" check, probably redundant:
  260. if !(config.Registration.Enabled || callbackNamespace == "admin") {
  261. return errFeatureDisabled
  262. }
  263. // if nick reservation is enabled, you can only register your current nickname
  264. // as an account; this prevents "land-grab" situations where someone else
  265. // registers your nick out from under you and then NS GHOSTs you
  266. // n.b. client is nil during a SAREGISTER:
  267. if config.NickReservation.Enabled && client != nil && client.NickCasefolded() != casefoldedAccount {
  268. return errAccountMustHoldNick
  269. }
  270. // can't register a guest nickname
  271. renamePrefix := strings.ToLower(config.NickReservation.RenamePrefix)
  272. if renamePrefix != "" && strings.HasPrefix(casefoldedAccount, renamePrefix) {
  273. return errAccountAlreadyRegistered
  274. }
  275. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  276. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  277. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  278. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  279. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  280. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  281. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  282. credStr, err := am.serializeCredentials(passphrase, certfp)
  283. if err != nil {
  284. return err
  285. }
  286. registeredTimeStr := strconv.FormatInt(time.Now().Unix(), 10)
  287. callbackSpec := fmt.Sprintf("%s:%s", callbackNamespace, callbackValue)
  288. var setOptions *buntdb.SetOptions
  289. ttl := config.Registration.VerifyTimeout
  290. if ttl != 0 {
  291. setOptions = &buntdb.SetOptions{Expires: true, TTL: ttl}
  292. }
  293. err = func() error {
  294. am.serialCacheUpdateMutex.Lock()
  295. defer am.serialCacheUpdateMutex.Unlock()
  296. // can't register an account with the same name as a registered nick
  297. if am.NickToAccount(casefoldedAccount) != "" {
  298. return errAccountAlreadyRegistered
  299. }
  300. return am.server.store.Update(func(tx *buntdb.Tx) error {
  301. _, err := am.loadRawAccount(tx, casefoldedAccount)
  302. if err != errAccountDoesNotExist {
  303. return errAccountAlreadyRegistered
  304. }
  305. if certfp != "" {
  306. // make sure certfp doesn't already exist because that'd be silly
  307. _, err := tx.Get(certFPKey)
  308. if err != buntdb.ErrNotFound {
  309. return errCertfpAlreadyExists
  310. }
  311. }
  312. tx.Set(accountKey, "1", setOptions)
  313. tx.Set(accountNameKey, account, setOptions)
  314. tx.Set(registeredTimeKey, registeredTimeStr, setOptions)
  315. tx.Set(credentialsKey, credStr, setOptions)
  316. tx.Set(callbackKey, callbackSpec, setOptions)
  317. if certfp != "" {
  318. tx.Set(certFPKey, casefoldedAccount, setOptions)
  319. }
  320. return nil
  321. })
  322. }()
  323. if err != nil {
  324. return err
  325. }
  326. code, err := am.dispatchCallback(client, casefoldedAccount, callbackNamespace, callbackValue)
  327. if err != nil {
  328. am.Unregister(casefoldedAccount)
  329. return errCallbackFailed
  330. } else {
  331. return am.server.store.Update(func(tx *buntdb.Tx) error {
  332. _, _, err = tx.Set(verificationCodeKey, code, setOptions)
  333. return err
  334. })
  335. }
  336. }
  337. // validatePassphrase checks whether a passphrase is allowed by our rules
  338. func validatePassphrase(passphrase string) error {
  339. // sanity check the length
  340. if len(passphrase) == 0 || len(passphrase) > 600 {
  341. return errAccountBadPassphrase
  342. }
  343. // for now, just enforce that spaces are not allowed
  344. for _, r := range passphrase {
  345. if unicode.IsSpace(r) {
  346. return errAccountBadPassphrase
  347. }
  348. }
  349. return nil
  350. }
  351. // helper to assemble the serialized JSON for an account's credentials
  352. func (am *AccountManager) serializeCredentials(passphrase string, certfp string) (result string, err error) {
  353. var creds AccountCredentials
  354. creds.Version = 1
  355. // we need at least one of passphrase and certfp:
  356. if passphrase == "" && certfp == "" {
  357. return "", errAccountBadPassphrase
  358. }
  359. // but if we have one, it's fine if the other is missing, it just means no
  360. // credential of that type will be accepted.
  361. creds.Certificate = certfp
  362. if passphrase != "" {
  363. if validatePassphrase(passphrase) != nil {
  364. return "", errAccountBadPassphrase
  365. }
  366. bcryptCost := int(am.server.Config().Accounts.Registration.BcryptCost)
  367. creds.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), bcryptCost)
  368. if err != nil {
  369. am.server.logger.Error("internal", "could not hash password", err.Error())
  370. return "", errAccountCreation
  371. }
  372. }
  373. credText, err := json.Marshal(creds)
  374. if err != nil {
  375. am.server.logger.Error("internal", "could not marshal credentials", err.Error())
  376. return "", errAccountCreation
  377. }
  378. return string(credText), nil
  379. }
  380. // changes the password for an account
  381. func (am *AccountManager) setPassword(account string, password string) (err error) {
  382. casefoldedAccount, err := CasefoldName(account)
  383. if err != nil {
  384. return err
  385. }
  386. act, err := am.LoadAccount(casefoldedAccount)
  387. if err != nil {
  388. return err
  389. }
  390. credStr, err := am.serializeCredentials(password, act.Credentials.Certificate)
  391. if err != nil {
  392. return err
  393. }
  394. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  395. return am.server.store.Update(func(tx *buntdb.Tx) error {
  396. _, _, err := tx.Set(credentialsKey, credStr, nil)
  397. return err
  398. })
  399. }
  400. func (am *AccountManager) dispatchCallback(client *Client, casefoldedAccount string, callbackNamespace string, callbackValue string) (string, error) {
  401. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  402. return "", nil
  403. } else if callbackNamespace == "mailto" {
  404. return am.dispatchMailtoCallback(client, casefoldedAccount, callbackValue)
  405. } else {
  406. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  407. }
  408. }
  409. func (am *AccountManager) dispatchMailtoCallback(client *Client, casefoldedAccount string, callbackValue string) (code string, err error) {
  410. config := am.server.AccountConfig().Registration.Callbacks.Mailto
  411. code = utils.GenerateSecretToken()
  412. subject := config.VerifyMessageSubject
  413. if subject == "" {
  414. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  415. }
  416. messageStrings := []string{
  417. fmt.Sprintf("From: %s\r\n", config.Sender),
  418. fmt.Sprintf("To: %s\r\n", callbackValue),
  419. fmt.Sprintf("Subject: %s\r\n", subject),
  420. "\r\n", // end headers, begin message body
  421. fmt.Sprintf(client.t("Account: %s"), casefoldedAccount) + "\r\n",
  422. fmt.Sprintf(client.t("Verification code: %s"), code) + "\r\n",
  423. "\r\n",
  424. client.t("To verify your account, issue one of these commands:") + "\r\n",
  425. fmt.Sprintf("/MSG NickServ VERIFY %s %s", casefoldedAccount, code) + "\r\n",
  426. }
  427. var message []byte
  428. for i := 0; i < len(messageStrings); i++ {
  429. message = append(message, []byte(messageStrings[i])...)
  430. }
  431. addr := fmt.Sprintf("%s:%d", config.Server, config.Port)
  432. var auth smtp.Auth
  433. if config.Username != "" && config.Password != "" {
  434. auth = smtp.PlainAuth("", config.Username, config.Password, config.Server)
  435. }
  436. // TODO: this will never send the password in plaintext over a nonlocal link,
  437. // but it might send the email in plaintext, regardless of the value of
  438. // config.TLS.InsecureSkipVerify
  439. err = smtp.SendMail(addr, auth, config.Sender, []string{callbackValue}, message)
  440. if err != nil {
  441. am.server.logger.Error("internal", "Failed to dispatch e-mail", err.Error())
  442. }
  443. return
  444. }
  445. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  446. casefoldedAccount, err := CasefoldName(account)
  447. if err != nil || account == "" || account == "*" {
  448. return errAccountVerificationFailed
  449. }
  450. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  451. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  452. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  453. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  454. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  455. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  456. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  457. var raw rawClientAccount
  458. func() {
  459. am.serialCacheUpdateMutex.Lock()
  460. defer am.serialCacheUpdateMutex.Unlock()
  461. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  462. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  463. if err == errAccountDoesNotExist {
  464. return errAccountDoesNotExist
  465. } else if err != nil {
  466. return errAccountVerificationFailed
  467. } else if raw.Verified {
  468. return errAccountAlreadyVerified
  469. }
  470. // actually verify the code
  471. // a stored code of "" means a none callback / no code required
  472. success := false
  473. storedCode, err := tx.Get(verificationCodeKey)
  474. if err == nil {
  475. // this is probably unnecessary
  476. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  477. success = true
  478. }
  479. }
  480. if !success {
  481. return errAccountVerificationInvalidCode
  482. }
  483. // verify the account
  484. tx.Set(verifiedKey, "1", nil)
  485. // don't need the code anymore
  486. tx.Delete(verificationCodeKey)
  487. // re-set all other keys, removing the TTL
  488. tx.Set(accountKey, "1", nil)
  489. tx.Set(accountNameKey, raw.Name, nil)
  490. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  491. tx.Set(callbackKey, raw.Callback, nil)
  492. tx.Set(credentialsKey, raw.Credentials, nil)
  493. var creds AccountCredentials
  494. // XXX we shouldn't do (de)serialization inside the txn,
  495. // but this is like 2 usec on my system
  496. json.Unmarshal([]byte(raw.Credentials), &creds)
  497. if creds.Certificate != "" {
  498. certFPKey := fmt.Sprintf(keyCertToAccount, creds.Certificate)
  499. tx.Set(certFPKey, casefoldedAccount, nil)
  500. }
  501. return nil
  502. })
  503. if err == nil {
  504. skeleton, _ := Skeleton(raw.Name)
  505. am.Lock()
  506. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  507. am.skeletonToAccount[skeleton] = casefoldedAccount
  508. am.Unlock()
  509. }
  510. }()
  511. if err != nil {
  512. return err
  513. }
  514. nick := "[server admin]"
  515. if client != nil {
  516. nick = client.Nick()
  517. }
  518. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  519. raw.Verified = true
  520. clientAccount, err := am.deserializeRawAccount(raw)
  521. if err != nil {
  522. return err
  523. }
  524. if client != nil {
  525. am.Login(client, clientAccount)
  526. }
  527. return nil
  528. }
  529. func marshalReservedNicks(nicks []string) string {
  530. return strings.Join(nicks, ",")
  531. }
  532. func unmarshalReservedNicks(nicks string) (result []string) {
  533. if nicks == "" {
  534. return
  535. }
  536. return strings.Split(nicks, ",")
  537. }
  538. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  539. cfnick, err := CasefoldName(nick)
  540. skeleton, skerr := Skeleton(nick)
  541. // garbage nick, or garbage options, or disabled
  542. nrconfig := am.server.AccountConfig().NickReservation
  543. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  544. return errAccountNickReservationFailed
  545. }
  546. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  547. am.serialCacheUpdateMutex.Lock()
  548. defer am.serialCacheUpdateMutex.Unlock()
  549. // find the affected account, which is usually the client's:
  550. account := client.Account()
  551. if saUnreserve {
  552. // unless this is a sadrop:
  553. account = am.NickToAccount(cfnick)
  554. if account == "" {
  555. // nothing to do
  556. return nil
  557. }
  558. }
  559. if account == "" {
  560. return errAccountNotLoggedIn
  561. }
  562. am.Lock()
  563. accountForNick := am.nickToAccount[cfnick]
  564. var accountForSkeleton string
  565. if reserve {
  566. accountForSkeleton = am.skeletonToAccount[skeleton]
  567. }
  568. am.Unlock()
  569. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  570. return errNicknameReserved
  571. } else if !reserve && !saUnreserve && accountForNick != account {
  572. return errNicknameReserved
  573. } else if !reserve && cfnick == account {
  574. return errAccountCantDropPrimaryNick
  575. }
  576. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  577. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  578. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  579. if reserve {
  580. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  581. // however you shouldn't be able to reserve a nick out from under them
  582. _, err := tx.Get(unverifiedAccountKey)
  583. if err == nil {
  584. return errNicknameReserved
  585. }
  586. }
  587. rawNicks, err := tx.Get(nicksKey)
  588. if err != nil && err != buntdb.ErrNotFound {
  589. return err
  590. }
  591. nicks := unmarshalReservedNicks(rawNicks)
  592. if reserve {
  593. if len(nicks) >= nrconfig.AdditionalNickLimit {
  594. return errAccountTooManyNicks
  595. }
  596. nicks = append(nicks, nick)
  597. } else {
  598. // compute (original reserved nicks) minus cfnick
  599. var newNicks []string
  600. for _, reservedNick := range nicks {
  601. cfreservednick, _ := CasefoldName(reservedNick)
  602. if cfreservednick != cfnick {
  603. newNicks = append(newNicks, reservedNick)
  604. } else {
  605. // found the original, unfolded version of the nick we're dropping;
  606. // recompute the true skeleton from it
  607. skeleton, _ = Skeleton(reservedNick)
  608. }
  609. }
  610. nicks = newNicks
  611. }
  612. marshaledNicks := marshalReservedNicks(nicks)
  613. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  614. return err
  615. })
  616. if err == errAccountTooManyNicks || err == errNicknameReserved {
  617. return err
  618. } else if err != nil {
  619. return errAccountNickReservationFailed
  620. }
  621. // success
  622. am.Lock()
  623. defer am.Unlock()
  624. if reserve {
  625. am.nickToAccount[cfnick] = account
  626. am.skeletonToAccount[skeleton] = account
  627. } else {
  628. delete(am.nickToAccount, cfnick)
  629. delete(am.skeletonToAccount, skeleton)
  630. }
  631. return nil
  632. }
  633. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  634. account, err = am.LoadAccount(accountName)
  635. if err != nil {
  636. return
  637. }
  638. if !account.Verified {
  639. err = errAccountUnverified
  640. return
  641. }
  642. switch account.Credentials.Version {
  643. case 0:
  644. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  645. case 1:
  646. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  647. err = errAccountInvalidCredentials
  648. }
  649. default:
  650. err = errAccountInvalidCredentials
  651. }
  652. return
  653. }
  654. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) error {
  655. account, err := am.checkPassphrase(accountName, passphrase)
  656. if err != nil {
  657. return err
  658. }
  659. am.Login(client, account)
  660. return nil
  661. }
  662. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  663. casefoldedAccount, err := CasefoldName(accountName)
  664. if err != nil {
  665. err = errAccountDoesNotExist
  666. return
  667. }
  668. var raw rawClientAccount
  669. am.server.store.View(func(tx *buntdb.Tx) error {
  670. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  671. return nil
  672. })
  673. if err != nil {
  674. return
  675. }
  676. result, err = am.deserializeRawAccount(raw)
  677. return
  678. }
  679. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount) (result ClientAccount, err error) {
  680. result.Name = raw.Name
  681. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  682. result.RegisteredAt = time.Unix(regTimeInt, 0)
  683. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  684. if e != nil {
  685. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  686. err = errAccountDoesNotExist
  687. return
  688. }
  689. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  690. result.Verified = raw.Verified
  691. if raw.VHost != "" {
  692. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  693. if e != nil {
  694. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  695. // pretend they have no vhost and move on
  696. }
  697. }
  698. if raw.Settings != "" {
  699. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  700. if e != nil {
  701. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  702. }
  703. }
  704. return
  705. }
  706. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  707. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  708. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  709. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  710. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  711. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  712. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  713. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  714. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  715. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  716. _, e := tx.Get(accountKey)
  717. if e == buntdb.ErrNotFound {
  718. err = errAccountDoesNotExist
  719. return
  720. }
  721. result.Name, _ = tx.Get(accountNameKey)
  722. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  723. result.Credentials, _ = tx.Get(credentialsKey)
  724. result.Callback, _ = tx.Get(callbackKey)
  725. result.AdditionalNicks, _ = tx.Get(nicksKey)
  726. result.VHost, _ = tx.Get(vhostKey)
  727. result.Settings, _ = tx.Get(settingsKey)
  728. if _, e = tx.Get(verifiedKey); e == nil {
  729. result.Verified = true
  730. }
  731. return
  732. }
  733. func (am *AccountManager) Unregister(account string) error {
  734. config := am.server.Config()
  735. casefoldedAccount, err := CasefoldName(account)
  736. if err != nil {
  737. return errAccountDoesNotExist
  738. }
  739. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  740. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  741. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  742. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  743. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  744. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  745. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  746. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  747. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  748. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  749. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  750. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  751. var clients []*Client
  752. var registeredChannels []string
  753. // on our way out, unregister all the account's channels and delete them from the db
  754. defer func() {
  755. for _, channelName := range registeredChannels {
  756. am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  757. }
  758. }()
  759. var credText string
  760. var rawNicks string
  761. am.serialCacheUpdateMutex.Lock()
  762. defer am.serialCacheUpdateMutex.Unlock()
  763. var accountName string
  764. var channelsStr string
  765. am.server.store.Update(func(tx *buntdb.Tx) error {
  766. tx.Delete(accountKey)
  767. accountName, _ = tx.Get(accountNameKey)
  768. tx.Delete(accountNameKey)
  769. tx.Delete(verifiedKey)
  770. tx.Delete(registeredTimeKey)
  771. tx.Delete(callbackKey)
  772. tx.Delete(verificationCodeKey)
  773. tx.Delete(settingsKey)
  774. rawNicks, _ = tx.Get(nicksKey)
  775. tx.Delete(nicksKey)
  776. credText, err = tx.Get(credentialsKey)
  777. tx.Delete(credentialsKey)
  778. tx.Delete(vhostKey)
  779. channelsStr, _ = tx.Get(channelsKey)
  780. tx.Delete(channelsKey)
  781. _, err := tx.Delete(vhostQueueKey)
  782. am.decrementVHostQueueCount(casefoldedAccount, err)
  783. return nil
  784. })
  785. if err == nil {
  786. var creds AccountCredentials
  787. if err = json.Unmarshal([]byte(credText), &creds); err == nil && creds.Certificate != "" {
  788. certFPKey := fmt.Sprintf(keyCertToAccount, creds.Certificate)
  789. am.server.store.Update(func(tx *buntdb.Tx) error {
  790. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  791. tx.Delete(certFPKey)
  792. }
  793. return nil
  794. })
  795. }
  796. }
  797. skeleton, _ := Skeleton(accountName)
  798. additionalNicks := unmarshalReservedNicks(rawNicks)
  799. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  800. am.Lock()
  801. defer am.Unlock()
  802. clients = am.accountToClients[casefoldedAccount]
  803. delete(am.accountToClients, casefoldedAccount)
  804. delete(am.nickToAccount, casefoldedAccount)
  805. delete(am.skeletonToAccount, skeleton)
  806. for _, nick := range additionalNicks {
  807. delete(am.nickToAccount, nick)
  808. additionalSkel, _ := Skeleton(nick)
  809. delete(am.skeletonToAccount, additionalSkel)
  810. }
  811. for _, client := range clients {
  812. if config.Accounts.RequireSasl.Enabled {
  813. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  814. // destroy acquires a semaphore so we can't call it while holding a lock
  815. go client.destroy(nil)
  816. } else {
  817. am.logoutOfAccount(client)
  818. }
  819. }
  820. if err != nil {
  821. return errAccountDoesNotExist
  822. }
  823. return nil
  824. }
  825. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  826. if channelsStr != "" {
  827. result = strings.Split(channelsStr, ",")
  828. }
  829. return
  830. }
  831. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  832. cfaccount, err := CasefoldName(account)
  833. if err != nil {
  834. return
  835. }
  836. var channelStr string
  837. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  838. am.server.store.View(func(tx *buntdb.Tx) error {
  839. channelStr, _ = tx.Get(key)
  840. return nil
  841. })
  842. return unmarshalRegisteredChannels(channelStr)
  843. }
  844. func (am *AccountManager) AuthenticateByCertFP(client *Client) error {
  845. if client.certfp == "" {
  846. return errAccountInvalidCredentials
  847. }
  848. var account string
  849. certFPKey := fmt.Sprintf(keyCertToAccount, client.certfp)
  850. err := am.server.store.View(func(tx *buntdb.Tx) error {
  851. account, _ = tx.Get(certFPKey)
  852. if account == "" {
  853. return errAccountInvalidCredentials
  854. }
  855. return nil
  856. })
  857. if err != nil {
  858. return err
  859. }
  860. // ok, we found an account corresponding to their certificate
  861. clientAccount, err := am.LoadAccount(account)
  862. if err != nil {
  863. return err
  864. } else if !clientAccount.Verified {
  865. return errAccountUnverified
  866. }
  867. am.Login(client, clientAccount)
  868. return nil
  869. }
  870. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  871. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  872. casefoldedAccount, err := CasefoldName(account)
  873. if err != nil {
  874. return newSettings, errAccountDoesNotExist
  875. }
  876. // TODO implement this in general via a compare-and-swap API
  877. accountData, err := am.LoadAccount(casefoldedAccount)
  878. if err != nil {
  879. return
  880. } else if !accountData.Verified {
  881. return newSettings, errAccountUnverified
  882. }
  883. newSettings, err = munger(accountData.Settings)
  884. if err != nil {
  885. return
  886. }
  887. text, err := json.Marshal(newSettings)
  888. if err != nil {
  889. return
  890. }
  891. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  892. serializedValue := string(text)
  893. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  894. _, _, err = tx.Set(key, serializedValue, nil)
  895. return
  896. })
  897. if err != nil {
  898. err = errAccountUpdateFailed
  899. return
  900. }
  901. // success, push new settings into the client objects
  902. am.Lock()
  903. defer am.Unlock()
  904. for _, client := range am.accountToClients[casefoldedAccount] {
  905. client.SetAccountSettings(newSettings)
  906. }
  907. return
  908. }
  909. // represents someone's status in hostserv
  910. type VHostInfo struct {
  911. ApprovedVHost string
  912. Enabled bool
  913. RequestedVHost string
  914. RejectedVHost string
  915. RejectionReason string
  916. LastRequestTime time.Time
  917. }
  918. // pair type, <VHostInfo, accountName>
  919. type PendingVHostRequest struct {
  920. VHostInfo
  921. Account string
  922. }
  923. // callback type implementing the actual business logic of vhost operations
  924. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  925. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  926. munger := func(input VHostInfo) (output VHostInfo, err error) {
  927. output = input
  928. output.Enabled = true
  929. output.ApprovedVHost = vhost
  930. return
  931. }
  932. return am.performVHostChange(account, munger)
  933. }
  934. func (am *AccountManager) VHostRequest(account string, vhost string) (result VHostInfo, err error) {
  935. munger := func(input VHostInfo) (output VHostInfo, err error) {
  936. output = input
  937. output.RequestedVHost = vhost
  938. output.RejectedVHost = ""
  939. output.RejectionReason = ""
  940. output.LastRequestTime = time.Now().UTC()
  941. return
  942. }
  943. return am.performVHostChange(account, munger)
  944. }
  945. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  946. munger := func(input VHostInfo) (output VHostInfo, err error) {
  947. output = input
  948. output.Enabled = true
  949. output.ApprovedVHost = input.RequestedVHost
  950. output.RequestedVHost = ""
  951. output.RejectionReason = ""
  952. return
  953. }
  954. return am.performVHostChange(account, munger)
  955. }
  956. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  957. munger := func(input VHostInfo) (output VHostInfo, err error) {
  958. output = input
  959. output.RejectedVHost = output.RequestedVHost
  960. output.RequestedVHost = ""
  961. output.RejectionReason = reason
  962. return
  963. }
  964. return am.performVHostChange(account, munger)
  965. }
  966. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  967. munger := func(input VHostInfo) (output VHostInfo, err error) {
  968. if input.ApprovedVHost == "" {
  969. err = errNoVhost
  970. return
  971. }
  972. output = input
  973. output.Enabled = enabled
  974. return
  975. }
  976. return am.performVHostChange(client.Account(), munger)
  977. }
  978. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  979. account, err = CasefoldName(account)
  980. if err != nil || account == "" {
  981. err = errAccountDoesNotExist
  982. return
  983. }
  984. am.vHostUpdateMutex.Lock()
  985. defer am.vHostUpdateMutex.Unlock()
  986. clientAccount, err := am.LoadAccount(account)
  987. if err != nil {
  988. err = errAccountDoesNotExist
  989. return
  990. } else if !clientAccount.Verified {
  991. err = errAccountUnverified
  992. return
  993. }
  994. result, err = munger(clientAccount.VHost)
  995. if err != nil {
  996. return
  997. }
  998. vhtext, err := json.Marshal(result)
  999. if err != nil {
  1000. err = errAccountUpdateFailed
  1001. return
  1002. }
  1003. vhstr := string(vhtext)
  1004. key := fmt.Sprintf(keyAccountVHost, account)
  1005. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1006. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1007. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1008. return err
  1009. }
  1010. // update request queue
  1011. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1012. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1013. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1014. return err
  1015. }
  1016. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1017. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1018. _, err = tx.Delete(queueKey)
  1019. am.decrementVHostQueueCount(account, err)
  1020. }
  1021. return nil
  1022. })
  1023. if err != nil {
  1024. err = errAccountUpdateFailed
  1025. return
  1026. }
  1027. am.applyVhostToClients(account, result)
  1028. return result, nil
  1029. }
  1030. // XXX annoying helper method for keeping the queue count in sync with the DB
  1031. // `err` is the buntdb error returned from deleting the queue key
  1032. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1033. if err == nil {
  1034. // successfully deleted a queue entry, do a 2's complement decrement:
  1035. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1036. } else if err != buntdb.ErrNotFound {
  1037. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1038. }
  1039. }
  1040. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1041. am.vHostUpdateMutex.Lock()
  1042. defer am.vHostUpdateMutex.Unlock()
  1043. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1044. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1045. accounts := make([]string, 0, limit)
  1046. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1047. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1048. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1049. return len(accounts) < limit
  1050. })
  1051. })
  1052. if err != nil {
  1053. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1054. return
  1055. }
  1056. for _, account := range accounts {
  1057. accountInfo, err := am.LoadAccount(account)
  1058. if err == nil {
  1059. requests = append(requests, PendingVHostRequest{
  1060. Account: account,
  1061. VHostInfo: accountInfo.VHost,
  1062. })
  1063. } else {
  1064. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1065. }
  1066. }
  1067. return
  1068. }
  1069. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1070. // if hostserv is disabled in config, then don't grant vhosts
  1071. // that were previously approved while it was enabled
  1072. if !am.server.AccountConfig().VHosts.Enabled {
  1073. return
  1074. }
  1075. vhost := ""
  1076. if info.Enabled {
  1077. vhost = info.ApprovedVHost
  1078. }
  1079. oldNickmask := client.NickMaskString()
  1080. updated := client.SetVHost(vhost)
  1081. if updated {
  1082. // TODO: doing I/O here is kind of a kludge
  1083. go client.sendChghost(oldNickmask, client.Hostname())
  1084. }
  1085. }
  1086. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1087. am.RLock()
  1088. clients := am.accountToClients[account]
  1089. am.RUnlock()
  1090. for _, client := range clients {
  1091. am.applyVHostInfo(client, result)
  1092. }
  1093. }
  1094. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1095. changed := client.SetAccountName(account.Name)
  1096. if !changed {
  1097. return
  1098. }
  1099. client.nickTimer.Touch(nil)
  1100. am.applyVHostInfo(client, account.VHost)
  1101. casefoldedAccount := client.Account()
  1102. am.Lock()
  1103. defer am.Unlock()
  1104. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1105. for _, client := range am.accountToClients[casefoldedAccount] {
  1106. client.SetAccountSettings(account.Settings)
  1107. }
  1108. }
  1109. func (am *AccountManager) Logout(client *Client) {
  1110. am.Lock()
  1111. defer am.Unlock()
  1112. casefoldedAccount := client.Account()
  1113. if casefoldedAccount == "" {
  1114. return
  1115. }
  1116. am.logoutOfAccount(client)
  1117. clients := am.accountToClients[casefoldedAccount]
  1118. if len(clients) <= 1 {
  1119. delete(am.accountToClients, casefoldedAccount)
  1120. return
  1121. }
  1122. remainingClients := make([]*Client, len(clients)-1)
  1123. remainingPos := 0
  1124. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1125. if clients[currentPos] != client {
  1126. remainingClients[remainingPos] = clients[currentPos]
  1127. remainingPos++
  1128. }
  1129. }
  1130. am.accountToClients[casefoldedAccount] = remainingClients
  1131. }
  1132. var (
  1133. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1134. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1135. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1136. "PLAIN": authPlainHandler,
  1137. "EXTERNAL": authExternalHandler,
  1138. }
  1139. )
  1140. // AccountCredentials stores the various methods for verifying accounts.
  1141. type AccountCredentials struct {
  1142. Version uint
  1143. PassphraseSalt []byte // legacy field, not used by v1 and later
  1144. PassphraseHash []byte
  1145. Certificate string // fingerprint
  1146. }
  1147. type BouncerAllowedSetting int
  1148. const (
  1149. BouncerAllowedServerDefault BouncerAllowedSetting = iota
  1150. BouncerDisallowedByUser
  1151. BouncerAllowedByUser
  1152. )
  1153. type AccountSettings struct {
  1154. AutoreplayLines *int
  1155. NickEnforcement NickEnforcementMethod
  1156. AllowBouncer BouncerAllowedSetting
  1157. AutoreplayJoins bool
  1158. }
  1159. // ClientAccount represents a user account.
  1160. type ClientAccount struct {
  1161. // Name of the account.
  1162. Name string
  1163. // RegisteredAt represents the time that the account was registered.
  1164. RegisteredAt time.Time
  1165. Credentials AccountCredentials
  1166. Verified bool
  1167. AdditionalNicks []string
  1168. VHost VHostInfo
  1169. Settings AccountSettings
  1170. }
  1171. // convenience for passing around raw serialized account data
  1172. type rawClientAccount struct {
  1173. Name string
  1174. RegisteredAt string
  1175. Credentials string
  1176. Callback string
  1177. Verified bool
  1178. AdditionalNicks string
  1179. VHost string
  1180. Settings string
  1181. }
  1182. // logoutOfAccount logs the client out of their current account.
  1183. func (am *AccountManager) logoutOfAccount(client *Client) {
  1184. if client.Account() == "" {
  1185. // already logged out
  1186. return
  1187. }
  1188. client.SetAccountName("")
  1189. go client.nickTimer.Touch(nil)
  1190. // dispatch account-notify
  1191. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1192. go func() {
  1193. for friend := range client.Friends(caps.AccountNotify) {
  1194. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1195. }
  1196. }()
  1197. }