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

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