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

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