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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode"
  14. "github.com/oragono/oragono/irc/caps"
  15. "github.com/oragono/oragono/irc/connection_limits"
  16. "github.com/oragono/oragono/irc/email"
  17. "github.com/oragono/oragono/irc/ldap"
  18. "github.com/oragono/oragono/irc/passwd"
  19. "github.com/oragono/oragono/irc/utils"
  20. "github.com/tidwall/buntdb"
  21. )
  22. const (
  23. keyAccountExists = "account.exists %s"
  24. keyAccountVerified = "account.verified %s"
  25. keyAccountUnregistered = "account.unregistered %s"
  26. keyAccountCallback = "account.callback %s"
  27. keyAccountVerificationCode = "account.verificationcode %s"
  28. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  29. keyAccountRegTime = "account.registered.time %s"
  30. keyAccountCredentials = "account.credentials %s"
  31. keyAccountAdditionalNicks = "account.additionalnicks %s"
  32. keyAccountSettings = "account.settings %s"
  33. keyAccountVHost = "account.vhost %s"
  34. keyCertToAccount = "account.creds.certfp %s"
  35. keyAccountChannels = "account.channels %s" // channels registered to the account
  36. keyAccountJoinedChannels = "account.joinedto %s" // channels a persistent client has joined
  37. keyAccountLastSeen = "account.lastseen %s"
  38. keyVHostQueueAcctToId = "vhostQueue %s"
  39. vhostRequestIdx = "vhostQueue"
  40. maxCertfpsPerAccount = 5
  41. )
  42. // everything about accounts is persistent; therefore, the database is the authoritative
  43. // source of truth for all account information. anything on the heap is just a cache
  44. type AccountManager struct {
  45. // XXX these are up here so they can be aligned to a 64-bit boundary, please forgive me
  46. // autoincrementing ID for vhost requests:
  47. vhostRequestID uint64
  48. vhostRequestPendingCount uint64
  49. sync.RWMutex // tier 2
  50. serialCacheUpdateMutex sync.Mutex // tier 3
  51. vHostUpdateMutex sync.Mutex // tier 3
  52. server *Server
  53. // track clients logged in to accounts
  54. accountToClients map[string][]*Client
  55. nickToAccount map[string]string
  56. skeletonToAccount map[string]string
  57. accountToMethod map[string]NickEnforcementMethod
  58. registerThrottle connection_limits.GenericThrottle
  59. }
  60. func (am *AccountManager) Initialize(server *Server) {
  61. am.accountToClients = make(map[string][]*Client)
  62. am.nickToAccount = make(map[string]string)
  63. am.skeletonToAccount = make(map[string]string)
  64. am.accountToMethod = make(map[string]NickEnforcementMethod)
  65. am.server = server
  66. config := server.Config()
  67. am.buildNickToAccountIndex(config)
  68. am.initVHostRequestQueue(config)
  69. am.createAlwaysOnClients(config)
  70. am.resetRegisterThrottle(config)
  71. }
  72. func (am *AccountManager) resetRegisterThrottle(config *Config) {
  73. am.Lock()
  74. defer am.Unlock()
  75. am.registerThrottle = connection_limits.GenericThrottle{
  76. Duration: config.Accounts.Registration.Throttling.Duration,
  77. Limit: config.Accounts.Registration.Throttling.MaxAttempts,
  78. }
  79. }
  80. func (am *AccountManager) touchRegisterThrottle() (throttled bool) {
  81. am.Lock()
  82. defer am.Unlock()
  83. throttled, _ = am.registerThrottle.Touch()
  84. return
  85. }
  86. func (am *AccountManager) createAlwaysOnClients(config *Config) {
  87. if config.Accounts.Multiclient.AlwaysOn == PersistentDisabled {
  88. return
  89. }
  90. verifiedPrefix := fmt.Sprintf(keyAccountVerified, "")
  91. am.serialCacheUpdateMutex.Lock()
  92. defer am.serialCacheUpdateMutex.Unlock()
  93. var accounts []string
  94. am.server.store.View(func(tx *buntdb.Tx) error {
  95. err := tx.AscendGreaterOrEqual("", verifiedPrefix, func(key, value string) bool {
  96. if !strings.HasPrefix(key, verifiedPrefix) {
  97. return false
  98. }
  99. account := strings.TrimPrefix(key, verifiedPrefix)
  100. accounts = append(accounts, account)
  101. return true
  102. })
  103. return err
  104. })
  105. for _, accountName := range accounts {
  106. account, err := am.LoadAccount(accountName)
  107. if err == nil && account.Verified &&
  108. persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, account.Settings.AlwaysOn) {
  109. am.server.AddAlwaysOnClient(account, am.loadChannels(accountName), am.loadLastSeen(accountName))
  110. }
  111. }
  112. }
  113. func (am *AccountManager) buildNickToAccountIndex(config *Config) {
  114. if !config.Accounts.NickReservation.Enabled {
  115. return
  116. }
  117. nickToAccount := make(map[string]string)
  118. skeletonToAccount := make(map[string]string)
  119. accountToMethod := make(map[string]NickEnforcementMethod)
  120. existsPrefix := fmt.Sprintf(keyAccountExists, "")
  121. am.serialCacheUpdateMutex.Lock()
  122. defer am.serialCacheUpdateMutex.Unlock()
  123. err := am.server.store.View(func(tx *buntdb.Tx) error {
  124. err := tx.AscendGreaterOrEqual("", existsPrefix, func(key, value string) bool {
  125. if !strings.HasPrefix(key, existsPrefix) {
  126. return false
  127. }
  128. account := strings.TrimPrefix(key, existsPrefix)
  129. if _, err := tx.Get(fmt.Sprintf(keyAccountVerified, account)); err == nil {
  130. nickToAccount[account] = account
  131. accountName, err := tx.Get(fmt.Sprintf(keyAccountName, account))
  132. if err != nil {
  133. am.server.logger.Error("internal", "missing account name for", account)
  134. } else {
  135. skeleton, _ := Skeleton(accountName)
  136. skeletonToAccount[skeleton] = account
  137. }
  138. }
  139. if rawNicks, err := tx.Get(fmt.Sprintf(keyAccountAdditionalNicks, account)); err == nil {
  140. additionalNicks := unmarshalReservedNicks(rawNicks)
  141. for _, nick := range additionalNicks {
  142. cfnick, _ := CasefoldName(nick)
  143. nickToAccount[cfnick] = account
  144. skeleton, _ := Skeleton(nick)
  145. skeletonToAccount[skeleton] = account
  146. }
  147. }
  148. if rawPrefs, err := tx.Get(fmt.Sprintf(keyAccountSettings, account)); err == nil {
  149. var prefs AccountSettings
  150. err := json.Unmarshal([]byte(rawPrefs), &prefs)
  151. if err == nil && prefs.NickEnforcement != NickEnforcementOptional {
  152. accountToMethod[account] = prefs.NickEnforcement
  153. } else if err != nil {
  154. am.server.logger.Error("internal", "corrupt account creds", account)
  155. }
  156. }
  157. return true
  158. })
  159. return err
  160. })
  161. if config.Accounts.NickReservation.Method == NickEnforcementStrict {
  162. unregisteredPrefix := fmt.Sprintf(keyAccountUnregistered, "")
  163. am.server.store.View(func(tx *buntdb.Tx) error {
  164. tx.AscendGreaterOrEqual("", unregisteredPrefix, func(key, value string) bool {
  165. if !strings.HasPrefix(key, unregisteredPrefix) {
  166. return false
  167. }
  168. account := strings.TrimPrefix(key, unregisteredPrefix)
  169. accountName := value
  170. nickToAccount[account] = account
  171. skeleton, _ := Skeleton(accountName)
  172. skeletonToAccount[skeleton] = account
  173. return true
  174. })
  175. return nil
  176. })
  177. }
  178. if err != nil {
  179. am.server.logger.Error("internal", "couldn't read reserved nicks", err.Error())
  180. } else {
  181. am.Lock()
  182. am.nickToAccount = nickToAccount
  183. am.skeletonToAccount = skeletonToAccount
  184. am.accountToMethod = accountToMethod
  185. am.Unlock()
  186. }
  187. }
  188. func (am *AccountManager) initVHostRequestQueue(config *Config) {
  189. if !config.Accounts.VHosts.Enabled {
  190. return
  191. }
  192. am.vHostUpdateMutex.Lock()
  193. defer am.vHostUpdateMutex.Unlock()
  194. // the db maps the account name to the autoincrementing integer ID of its request
  195. // create an numerically ordered index on ID, so we can list the oldest requests
  196. // finally, collect the integer id of the newest request and the total request count
  197. var total uint64
  198. var lastIDStr string
  199. err := am.server.store.Update(func(tx *buntdb.Tx) error {
  200. err := tx.CreateIndex(vhostRequestIdx, fmt.Sprintf(keyVHostQueueAcctToId, "*"), buntdb.IndexInt)
  201. if err != nil {
  202. return err
  203. }
  204. return tx.Descend(vhostRequestIdx, func(key, value string) bool {
  205. if lastIDStr == "" {
  206. lastIDStr = value
  207. }
  208. total++
  209. return true
  210. })
  211. })
  212. if err != nil {
  213. am.server.logger.Error("internal", "could not create vhost queue index", err.Error())
  214. }
  215. lastID, _ := strconv.ParseUint(lastIDStr, 10, 64)
  216. am.server.logger.Debug("services", fmt.Sprintf("vhost queue length is %d, autoincrementing id is %d", total, lastID))
  217. atomic.StoreUint64(&am.vhostRequestID, lastID)
  218. atomic.StoreUint64(&am.vhostRequestPendingCount, total)
  219. }
  220. func (am *AccountManager) NickToAccount(nick string) string {
  221. cfnick, err := CasefoldName(nick)
  222. if err != nil {
  223. return ""
  224. }
  225. am.RLock()
  226. defer am.RUnlock()
  227. return am.nickToAccount[cfnick]
  228. }
  229. // given an account, combine stored enforcement method with the config settings
  230. // to compute the actual enforcement method
  231. func configuredEnforcementMethod(config *Config, storedMethod NickEnforcementMethod) (result NickEnforcementMethod) {
  232. if !config.Accounts.NickReservation.Enabled {
  233. return NickEnforcementNone
  234. }
  235. result = storedMethod
  236. // if they don't have a custom setting, or customization is disabled, use the default
  237. if result == NickEnforcementOptional || !config.Accounts.NickReservation.AllowCustomEnforcement {
  238. result = config.Accounts.NickReservation.Method
  239. }
  240. if result == NickEnforcementOptional {
  241. // enforcement was explicitly enabled neither in the config or by the user
  242. result = NickEnforcementNone
  243. }
  244. return
  245. }
  246. // Given a nick, looks up the account that owns it and the method (none/timeout/strict)
  247. // used to enforce ownership.
  248. func (am *AccountManager) EnforcementStatus(cfnick, skeleton string) (account string, method NickEnforcementMethod) {
  249. config := am.server.Config()
  250. if !config.Accounts.NickReservation.Enabled {
  251. return "", NickEnforcementNone
  252. }
  253. am.RLock()
  254. defer am.RUnlock()
  255. finalEnforcementMethod := func(account_ string) (result NickEnforcementMethod) {
  256. storedMethod := am.accountToMethod[account_]
  257. return configuredEnforcementMethod(config, storedMethod)
  258. }
  259. nickAccount := am.nickToAccount[cfnick]
  260. skelAccount := am.skeletonToAccount[skeleton]
  261. if nickAccount == "" && skelAccount == "" {
  262. return "", NickEnforcementNone
  263. } else if nickAccount != "" && (skelAccount == nickAccount || skelAccount == "") {
  264. return nickAccount, finalEnforcementMethod(nickAccount)
  265. } else if skelAccount != "" && nickAccount == "" {
  266. return skelAccount, finalEnforcementMethod(skelAccount)
  267. } else {
  268. // nickAccount != skelAccount and both are nonempty:
  269. // two people have competing claims on (this casefolding of) this nick!
  270. nickMethod := finalEnforcementMethod(nickAccount)
  271. skelMethod := finalEnforcementMethod(skelAccount)
  272. switch {
  273. case skelMethod == NickEnforcementNone:
  274. return nickAccount, nickMethod
  275. case nickMethod == NickEnforcementNone:
  276. return skelAccount, skelMethod
  277. default:
  278. // nobody can use this nick
  279. return "!", NickEnforcementStrict
  280. }
  281. }
  282. }
  283. // Sets a custom enforcement method for an account and stores it in the database.
  284. func (am *AccountManager) SetEnforcementStatus(account string, method NickEnforcementMethod) (finalSettings AccountSettings, err error) {
  285. config := am.server.Config()
  286. if !(config.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.AllowCustomEnforcement) {
  287. err = errFeatureDisabled
  288. return
  289. }
  290. setter := func(in AccountSettings) (out AccountSettings, err error) {
  291. out = in
  292. out.NickEnforcement = method
  293. return out, nil
  294. }
  295. _, err = am.ModifyAccountSettings(account, setter)
  296. if err != nil {
  297. return
  298. }
  299. // this update of the data plane is racey, but it's probably fine
  300. am.Lock()
  301. defer am.Unlock()
  302. if method == NickEnforcementOptional {
  303. delete(am.accountToMethod, account)
  304. } else {
  305. am.accountToMethod[account] = method
  306. }
  307. return
  308. }
  309. func (am *AccountManager) AccountToClients(account string) (result []*Client) {
  310. cfaccount, err := CasefoldName(account)
  311. if err != nil {
  312. return
  313. }
  314. am.RLock()
  315. defer am.RUnlock()
  316. return am.accountToClients[cfaccount]
  317. }
  318. func (am *AccountManager) Register(client *Client, account string, callbackNamespace string, callbackValue string, passphrase string, certfp string) error {
  319. casefoldedAccount, err := CasefoldName(account)
  320. skeleton, skerr := Skeleton(account)
  321. if err != nil || skerr != nil || account == "" || account == "*" {
  322. return errAccountCreation
  323. }
  324. if restrictedCasefoldedNicks[casefoldedAccount] || restrictedSkeletons[skeleton] {
  325. return errAccountAlreadyRegistered
  326. }
  327. config := am.server.Config()
  328. // final "is registration allowed" check, probably redundant:
  329. if !(config.Accounts.Registration.Enabled || callbackNamespace == "admin") {
  330. return errFeatureDisabled
  331. }
  332. if client != nil && client.Account() != "" {
  333. return errAccountAlreadyLoggedIn
  334. }
  335. if client != nil && am.touchRegisterThrottle() {
  336. am.server.logger.Warning("accounts", "global registration throttle exceeded by client", client.Nick())
  337. return errLimitExceeded
  338. }
  339. // if nick reservation is enabled, you can only register your current nickname
  340. // as an account; this prevents "land-grab" situations where someone else
  341. // registers your nick out from under you and then NS GHOSTs you
  342. // n.b. client is nil during a SAREGISTER
  343. // n.b. if ForceGuestFormat, then there's no concern, because you can't
  344. // register a guest nickname anyway, and the actual registration system
  345. // will prevent any double-register
  346. if client != nil && config.Accounts.NickReservation.Enabled &&
  347. !config.Accounts.NickReservation.ForceGuestFormat &&
  348. client.NickCasefolded() != casefoldedAccount {
  349. return errAccountMustHoldNick
  350. }
  351. // can't register a guest nickname
  352. if config.Accounts.NickReservation.guestRegexpFolded.MatchString(casefoldedAccount) {
  353. return errAccountAlreadyRegistered
  354. }
  355. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  356. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  357. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  358. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  359. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  360. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  361. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  362. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  363. var creds AccountCredentials
  364. creds.Version = 1
  365. err = creds.SetPassphrase(passphrase, am.server.Config().Accounts.Registration.BcryptCost)
  366. if err != nil {
  367. return err
  368. }
  369. creds.AddCertfp(certfp)
  370. credStr, err := creds.Serialize()
  371. if err != nil {
  372. return err
  373. }
  374. registeredTimeStr := strconv.FormatInt(time.Now().UnixNano(), 10)
  375. callbackSpec := fmt.Sprintf("%s:%s", callbackNamespace, callbackValue)
  376. var setOptions *buntdb.SetOptions
  377. ttl := time.Duration(config.Accounts.Registration.VerifyTimeout)
  378. if ttl != 0 {
  379. setOptions = &buntdb.SetOptions{Expires: true, TTL: ttl}
  380. }
  381. err = func() error {
  382. am.serialCacheUpdateMutex.Lock()
  383. defer am.serialCacheUpdateMutex.Unlock()
  384. // can't register an account with the same name as a registered nick
  385. if am.NickToAccount(casefoldedAccount) != "" {
  386. return errAccountAlreadyRegistered
  387. }
  388. return am.server.store.Update(func(tx *buntdb.Tx) error {
  389. if _, err := tx.Get(unregisteredKey); err == nil {
  390. return errAccountAlreadyUnregistered
  391. }
  392. _, err = am.loadRawAccount(tx, casefoldedAccount)
  393. if err != errAccountDoesNotExist {
  394. return errAccountAlreadyRegistered
  395. }
  396. if certfp != "" {
  397. // make sure certfp doesn't already exist because that'd be silly
  398. _, err := tx.Get(certFPKey)
  399. if err != buntdb.ErrNotFound {
  400. return errCertfpAlreadyExists
  401. }
  402. }
  403. tx.Set(accountKey, "1", setOptions)
  404. tx.Set(accountNameKey, account, setOptions)
  405. tx.Set(registeredTimeKey, registeredTimeStr, setOptions)
  406. tx.Set(credentialsKey, credStr, setOptions)
  407. tx.Set(callbackKey, callbackSpec, setOptions)
  408. if certfp != "" {
  409. tx.Set(certFPKey, casefoldedAccount, setOptions)
  410. }
  411. return nil
  412. })
  413. }()
  414. if err != nil {
  415. return err
  416. }
  417. code, err := am.dispatchCallback(client, account, callbackNamespace, callbackValue)
  418. if err != nil {
  419. am.Unregister(casefoldedAccount, true)
  420. return errCallbackFailed
  421. } else {
  422. return am.server.store.Update(func(tx *buntdb.Tx) error {
  423. _, _, err = tx.Set(verificationCodeKey, code, setOptions)
  424. return err
  425. })
  426. }
  427. }
  428. // validatePassphrase checks whether a passphrase is allowed by our rules
  429. func validatePassphrase(passphrase string) error {
  430. // sanity check the length
  431. if len(passphrase) == 0 || len(passphrase) > 300 {
  432. return errAccountBadPassphrase
  433. }
  434. // we use * as a placeholder in some places, if it's gotten this far then fail
  435. if passphrase == "*" {
  436. return errAccountBadPassphrase
  437. }
  438. // for now, just enforce that spaces are not allowed
  439. for _, r := range passphrase {
  440. if unicode.IsSpace(r) {
  441. return errAccountBadPassphrase
  442. }
  443. }
  444. return nil
  445. }
  446. // changes the password for an account
  447. func (am *AccountManager) setPassword(account string, password string, hasPrivs bool) (err error) {
  448. cfAccount, err := CasefoldName(account)
  449. if err != nil {
  450. return errAccountDoesNotExist
  451. }
  452. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  453. var credStr string
  454. am.server.store.View(func(tx *buntdb.Tx) error {
  455. // no need to check verification status here or below;
  456. // you either need to be auth'ed to the account or be an oper to do this
  457. credStr, err = tx.Get(credKey)
  458. return nil
  459. })
  460. if err != nil {
  461. return errAccountDoesNotExist
  462. }
  463. var creds AccountCredentials
  464. err = json.Unmarshal([]byte(credStr), &creds)
  465. if err != nil {
  466. return err
  467. }
  468. if !hasPrivs && creds.Empty() {
  469. return errCredsExternallyManaged
  470. }
  471. err = creds.SetPassphrase(password, am.server.Config().Accounts.Registration.BcryptCost)
  472. if err != nil {
  473. return err
  474. }
  475. if creds.Empty() && !hasPrivs {
  476. return errEmptyCredentials
  477. }
  478. newCredStr, err := creds.Serialize()
  479. if err != nil {
  480. return err
  481. }
  482. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  483. curCredStr, err := tx.Get(credKey)
  484. if credStr != curCredStr {
  485. return errCASFailed
  486. }
  487. _, _, err = tx.Set(credKey, newCredStr, nil)
  488. return err
  489. })
  490. return err
  491. }
  492. func (am *AccountManager) saveChannels(account string, channels []string) {
  493. channelsStr := strings.Join(channels, ",")
  494. key := fmt.Sprintf(keyAccountJoinedChannels, account)
  495. am.server.store.Update(func(tx *buntdb.Tx) error {
  496. tx.Set(key, channelsStr, nil)
  497. return nil
  498. })
  499. }
  500. func (am *AccountManager) loadChannels(account string) (channels []string) {
  501. key := fmt.Sprintf(keyAccountJoinedChannels, account)
  502. var channelsStr string
  503. am.server.store.View(func(tx *buntdb.Tx) error {
  504. channelsStr, _ = tx.Get(key)
  505. return nil
  506. })
  507. if channelsStr != "" {
  508. return strings.Split(channelsStr, ",")
  509. }
  510. return
  511. }
  512. func (am *AccountManager) saveLastSeen(account string, lastSeen time.Time) {
  513. key := fmt.Sprintf(keyAccountLastSeen, account)
  514. var val string
  515. if !lastSeen.IsZero() {
  516. val = strconv.FormatInt(lastSeen.UnixNano(), 10)
  517. }
  518. am.server.store.Update(func(tx *buntdb.Tx) error {
  519. if val != "" {
  520. tx.Set(key, val, nil)
  521. } else {
  522. tx.Delete(key)
  523. }
  524. return nil
  525. })
  526. }
  527. func (am *AccountManager) loadLastSeen(account string) (lastSeen time.Time) {
  528. key := fmt.Sprintf(keyAccountLastSeen, account)
  529. var lsText string
  530. am.server.store.Update(func(tx *buntdb.Tx) error {
  531. lsText, _ = tx.Get(key)
  532. // XXX clear this on startup, because it's not clear when it's
  533. // going to be overwritten, and restarting the server twice in a row
  534. // could result in a large amount of duplicated history replay
  535. tx.Delete(key)
  536. return nil
  537. })
  538. lsNum, err := strconv.ParseInt(lsText, 10, 64)
  539. if err == nil {
  540. return time.Unix(0, lsNum).UTC()
  541. }
  542. return
  543. }
  544. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  545. certfp, err = utils.NormalizeCertfp(certfp)
  546. if err != nil {
  547. return err
  548. }
  549. cfAccount, err := CasefoldName(account)
  550. if err != nil {
  551. return errAccountDoesNotExist
  552. }
  553. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  554. var credStr string
  555. am.server.store.View(func(tx *buntdb.Tx) error {
  556. credStr, err = tx.Get(credKey)
  557. return nil
  558. })
  559. if err != nil {
  560. return errAccountDoesNotExist
  561. }
  562. var creds AccountCredentials
  563. err = json.Unmarshal([]byte(credStr), &creds)
  564. if err != nil {
  565. return err
  566. }
  567. if !hasPrivs && creds.Empty() {
  568. return errCredsExternallyManaged
  569. }
  570. if add {
  571. err = creds.AddCertfp(certfp)
  572. } else {
  573. err = creds.RemoveCertfp(certfp)
  574. }
  575. if err != nil {
  576. return err
  577. }
  578. if creds.Empty() && !hasPrivs {
  579. return errEmptyCredentials
  580. }
  581. newCredStr, err := creds.Serialize()
  582. if err != nil {
  583. return err
  584. }
  585. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  586. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  587. curCredStr, err := tx.Get(credKey)
  588. if credStr != curCredStr {
  589. return errCASFailed
  590. }
  591. if add {
  592. _, err = tx.Get(certfpKey)
  593. if err != buntdb.ErrNotFound {
  594. return errCertfpAlreadyExists
  595. }
  596. tx.Set(certfpKey, cfAccount, nil)
  597. } else {
  598. tx.Delete(certfpKey)
  599. }
  600. _, _, err = tx.Set(credKey, newCredStr, nil)
  601. return err
  602. })
  603. return err
  604. }
  605. func (am *AccountManager) dispatchCallback(client *Client, account string, callbackNamespace string, callbackValue string) (string, error) {
  606. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  607. return "", nil
  608. } else if callbackNamespace == "mailto" {
  609. return am.dispatchMailtoCallback(client, account, callbackValue)
  610. } else {
  611. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  612. }
  613. }
  614. func (am *AccountManager) dispatchMailtoCallback(client *Client, account string, callbackValue string) (code string, err error) {
  615. config := am.server.Config().Accounts.Registration.Callbacks.Mailto
  616. code = utils.GenerateSecretToken()
  617. subject := config.VerifyMessageSubject
  618. if subject == "" {
  619. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  620. }
  621. var message bytes.Buffer
  622. fmt.Fprintf(&message, "From: %s\r\n", config.Sender)
  623. fmt.Fprintf(&message, "To: %s\r\n", callbackValue)
  624. if config.DKIM.Domain != "" {
  625. fmt.Fprintf(&message, "Message-ID: <%s@%s>\r\n", utils.GenerateSecretKey(), config.DKIM.Domain)
  626. }
  627. fmt.Fprintf(&message, "Subject: %s\r\n", subject)
  628. message.WriteString("\r\n") // blank line: end headers, begin message body
  629. fmt.Fprintf(&message, client.t("Account: %s"), account)
  630. message.WriteString("\r\n")
  631. fmt.Fprintf(&message, client.t("Verification code: %s"), code)
  632. message.WriteString("\r\n")
  633. message.WriteString("\r\n")
  634. message.WriteString(client.t("To verify your account, issue the following command:"))
  635. message.WriteString("\r\n")
  636. fmt.Fprintf(&message, "/MSG NickServ VERIFY %s %s\r\n", account, code)
  637. err = email.SendMail(config, callbackValue, message.Bytes())
  638. if err != nil {
  639. am.server.logger.Error("internal", "Failed to dispatch e-mail to", callbackValue, err.Error())
  640. }
  641. return
  642. }
  643. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  644. casefoldedAccount, err := CasefoldName(account)
  645. var skeleton string
  646. if err != nil || account == "" || account == "*" {
  647. return errAccountVerificationFailed
  648. }
  649. if client != nil && client.Account() != "" {
  650. return errAccountAlreadyLoggedIn
  651. }
  652. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  653. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  654. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  655. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  656. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  657. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  658. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  659. var raw rawClientAccount
  660. func() {
  661. am.serialCacheUpdateMutex.Lock()
  662. defer am.serialCacheUpdateMutex.Unlock()
  663. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  664. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  665. if err == errAccountDoesNotExist {
  666. return errAccountDoesNotExist
  667. } else if err != nil {
  668. return errAccountVerificationFailed
  669. } else if raw.Verified {
  670. return errAccountAlreadyVerified
  671. }
  672. // actually verify the code
  673. // a stored code of "" means a none callback / no code required
  674. success := false
  675. storedCode, err := tx.Get(verificationCodeKey)
  676. if err == nil {
  677. // this is probably unnecessary
  678. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  679. success = true
  680. }
  681. }
  682. if !success {
  683. return errAccountVerificationInvalidCode
  684. }
  685. // verify the account
  686. tx.Set(verifiedKey, "1", nil)
  687. // don't need the code anymore
  688. tx.Delete(verificationCodeKey)
  689. // re-set all other keys, removing the TTL
  690. tx.Set(accountKey, "1", nil)
  691. tx.Set(accountNameKey, raw.Name, nil)
  692. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  693. tx.Set(callbackKey, raw.Callback, nil)
  694. tx.Set(credentialsKey, raw.Credentials, nil)
  695. var creds AccountCredentials
  696. // XXX we shouldn't do (de)serialization inside the txn,
  697. // but this is like 2 usec on my system
  698. json.Unmarshal([]byte(raw.Credentials), &creds)
  699. for _, cert := range creds.Certfps {
  700. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  701. tx.Set(certFPKey, casefoldedAccount, nil)
  702. }
  703. return nil
  704. })
  705. if err == nil {
  706. skeleton, _ = Skeleton(raw.Name)
  707. am.Lock()
  708. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  709. am.skeletonToAccount[skeleton] = casefoldedAccount
  710. am.Unlock()
  711. }
  712. }()
  713. if err != nil {
  714. return err
  715. }
  716. nick := "[server admin]"
  717. if client != nil {
  718. nick = client.Nick()
  719. }
  720. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  721. raw.Verified = true
  722. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  723. if err != nil {
  724. return err
  725. }
  726. if client != nil {
  727. am.Login(client, clientAccount)
  728. }
  729. _, method := am.EnforcementStatus(casefoldedAccount, skeleton)
  730. if method != NickEnforcementNone {
  731. currentClient := am.server.clients.Get(casefoldedAccount)
  732. if currentClient == nil || currentClient == client || currentClient.Account() == casefoldedAccount {
  733. return nil
  734. }
  735. if method == NickEnforcementStrict {
  736. am.server.RandomlyRename(currentClient)
  737. } else if method == NickEnforcementWithTimeout {
  738. currentClient.nickTimer.Touch(nil)
  739. }
  740. }
  741. return nil
  742. }
  743. // register and verify an account, for internal use
  744. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  745. err = am.Register(nil, account, "admin", "", passphrase, "")
  746. if err == nil {
  747. err = am.Verify(nil, account, "")
  748. }
  749. return
  750. }
  751. func marshalReservedNicks(nicks []string) string {
  752. return strings.Join(nicks, ",")
  753. }
  754. func unmarshalReservedNicks(nicks string) (result []string) {
  755. if nicks == "" {
  756. return
  757. }
  758. return strings.Split(nicks, ",")
  759. }
  760. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  761. cfnick, err := CasefoldName(nick)
  762. skeleton, skerr := Skeleton(nick)
  763. // garbage nick, or garbage options, or disabled
  764. nrconfig := am.server.Config().Accounts.NickReservation
  765. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  766. return errAccountNickReservationFailed
  767. }
  768. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  769. am.serialCacheUpdateMutex.Lock()
  770. defer am.serialCacheUpdateMutex.Unlock()
  771. // find the affected account, which is usually the client's:
  772. account := client.Account()
  773. if saUnreserve {
  774. // unless this is a sadrop:
  775. account = am.NickToAccount(cfnick)
  776. if account == "" {
  777. // nothing to do
  778. return nil
  779. }
  780. }
  781. if account == "" {
  782. return errAccountNotLoggedIn
  783. }
  784. am.Lock()
  785. accountForNick := am.nickToAccount[cfnick]
  786. var accountForSkeleton string
  787. if reserve {
  788. accountForSkeleton = am.skeletonToAccount[skeleton]
  789. }
  790. am.Unlock()
  791. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  792. return errNicknameReserved
  793. } else if !reserve && !saUnreserve && accountForNick != account {
  794. return errNicknameReserved
  795. } else if !reserve && cfnick == account {
  796. return errAccountCantDropPrimaryNick
  797. }
  798. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  799. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  800. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  801. if reserve {
  802. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  803. // however you shouldn't be able to reserve a nick out from under them
  804. _, err := tx.Get(unverifiedAccountKey)
  805. if err == nil {
  806. return errNicknameReserved
  807. }
  808. }
  809. rawNicks, err := tx.Get(nicksKey)
  810. if err != nil && err != buntdb.ErrNotFound {
  811. return err
  812. }
  813. nicks := unmarshalReservedNicks(rawNicks)
  814. if reserve {
  815. if len(nicks) >= nrconfig.AdditionalNickLimit {
  816. return errAccountTooManyNicks
  817. }
  818. nicks = append(nicks, nick)
  819. } else {
  820. // compute (original reserved nicks) minus cfnick
  821. var newNicks []string
  822. for _, reservedNick := range nicks {
  823. cfreservednick, _ := CasefoldName(reservedNick)
  824. if cfreservednick != cfnick {
  825. newNicks = append(newNicks, reservedNick)
  826. } else {
  827. // found the original, unfolded version of the nick we're dropping;
  828. // recompute the true skeleton from it
  829. skeleton, _ = Skeleton(reservedNick)
  830. }
  831. }
  832. nicks = newNicks
  833. }
  834. marshaledNicks := marshalReservedNicks(nicks)
  835. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  836. return err
  837. })
  838. if err == errAccountTooManyNicks || err == errNicknameReserved {
  839. return err
  840. } else if err != nil {
  841. return errAccountNickReservationFailed
  842. }
  843. // success
  844. am.Lock()
  845. defer am.Unlock()
  846. if reserve {
  847. am.nickToAccount[cfnick] = account
  848. am.skeletonToAccount[skeleton] = account
  849. } else {
  850. delete(am.nickToAccount, cfnick)
  851. delete(am.skeletonToAccount, skeleton)
  852. }
  853. return nil
  854. }
  855. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  856. account, err = am.LoadAccount(accountName)
  857. if err != nil {
  858. return
  859. }
  860. if !account.Verified {
  861. err = errAccountUnverified
  862. return
  863. }
  864. switch account.Credentials.Version {
  865. case 0:
  866. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  867. case 1:
  868. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  869. err = errAccountInvalidCredentials
  870. }
  871. default:
  872. err = errAccountInvalidCredentials
  873. }
  874. return
  875. }
  876. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  877. // XXX check this now, so we don't allow a redundant login for an always-on client
  878. // even for a brief period. the other potential source of nick-account conflicts
  879. // is from force-nick-equals-account, but those will be caught later by
  880. // fixupNickEqualsAccount and if there is a conflict, they will be logged out.
  881. if client.registered {
  882. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  883. return errNickAccountMismatch
  884. }
  885. }
  886. var account ClientAccount
  887. defer func() {
  888. if err == nil {
  889. am.Login(client, account)
  890. }
  891. }()
  892. ldapConf := am.server.Config().Accounts.LDAP
  893. if ldapConf.Enabled {
  894. err = ldap.CheckLDAPPassphrase(ldapConf, accountName, passphrase, am.server.logger)
  895. if err == nil {
  896. account, err = am.LoadAccount(accountName)
  897. // autocreate if necessary:
  898. if err == errAccountDoesNotExist && ldapConf.Autocreate {
  899. err = am.SARegister(accountName, "")
  900. if err != nil {
  901. return
  902. }
  903. account, err = am.LoadAccount(accountName)
  904. }
  905. return
  906. }
  907. }
  908. account, err = am.checkPassphrase(accountName, passphrase)
  909. return err
  910. }
  911. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  912. casefoldedAccount, err := CasefoldName(accountName)
  913. if err != nil {
  914. err = errAccountDoesNotExist
  915. return
  916. }
  917. var raw rawClientAccount
  918. am.server.store.View(func(tx *buntdb.Tx) error {
  919. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  920. return nil
  921. })
  922. if err != nil {
  923. return
  924. }
  925. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  926. return
  927. }
  928. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  929. result.Name = raw.Name
  930. result.NameCasefolded = cfName
  931. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  932. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  933. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  934. if e != nil {
  935. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  936. err = errAccountDoesNotExist
  937. return
  938. }
  939. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  940. result.Verified = raw.Verified
  941. if raw.VHost != "" {
  942. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  943. if e != nil {
  944. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  945. // pretend they have no vhost and move on
  946. }
  947. }
  948. if raw.Settings != "" {
  949. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  950. if e != nil {
  951. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  952. }
  953. }
  954. return
  955. }
  956. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  957. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  958. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  959. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  960. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  961. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  962. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  963. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  964. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  965. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  966. _, e := tx.Get(accountKey)
  967. if e == buntdb.ErrNotFound {
  968. err = errAccountDoesNotExist
  969. return
  970. }
  971. result.Name, _ = tx.Get(accountNameKey)
  972. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  973. result.Credentials, _ = tx.Get(credentialsKey)
  974. result.Callback, _ = tx.Get(callbackKey)
  975. result.AdditionalNicks, _ = tx.Get(nicksKey)
  976. result.VHost, _ = tx.Get(vhostKey)
  977. result.Settings, _ = tx.Get(settingsKey)
  978. if _, e = tx.Get(verifiedKey); e == nil {
  979. result.Verified = true
  980. }
  981. return
  982. }
  983. func (am *AccountManager) Unregister(account string, erase bool) error {
  984. config := am.server.Config()
  985. casefoldedAccount, err := CasefoldName(account)
  986. if err != nil {
  987. return errAccountDoesNotExist
  988. }
  989. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  990. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  991. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  992. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  993. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  994. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  995. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  996. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  997. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  998. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  999. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  1000. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1001. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  1002. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1003. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1004. var clients []*Client
  1005. var registeredChannels []string
  1006. // on our way out, unregister all the account's channels and delete them from the db
  1007. defer func() {
  1008. for _, channelName := range registeredChannels {
  1009. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1010. if err != nil {
  1011. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1012. }
  1013. }
  1014. }()
  1015. var credText string
  1016. var rawNicks string
  1017. am.serialCacheUpdateMutex.Lock()
  1018. defer am.serialCacheUpdateMutex.Unlock()
  1019. var accountName string
  1020. var channelsStr string
  1021. keepProtections := false
  1022. am.server.store.Update(func(tx *buntdb.Tx) error {
  1023. accountName, _ = tx.Get(accountNameKey)
  1024. if erase {
  1025. tx.Delete(unregisteredKey)
  1026. } else {
  1027. if _, err := tx.Get(verifiedKey); err == nil {
  1028. tx.Set(unregisteredKey, accountName, nil)
  1029. keepProtections = true
  1030. }
  1031. }
  1032. tx.Delete(accountKey)
  1033. tx.Delete(accountNameKey)
  1034. tx.Delete(verifiedKey)
  1035. tx.Delete(registeredTimeKey)
  1036. tx.Delete(callbackKey)
  1037. tx.Delete(verificationCodeKey)
  1038. tx.Delete(settingsKey)
  1039. rawNicks, _ = tx.Get(nicksKey)
  1040. tx.Delete(nicksKey)
  1041. credText, err = tx.Get(credentialsKey)
  1042. tx.Delete(credentialsKey)
  1043. tx.Delete(vhostKey)
  1044. channelsStr, _ = tx.Get(channelsKey)
  1045. tx.Delete(channelsKey)
  1046. tx.Delete(joinedChannelsKey)
  1047. tx.Delete(lastSeenKey)
  1048. _, err := tx.Delete(vhostQueueKey)
  1049. am.decrementVHostQueueCount(casefoldedAccount, err)
  1050. return nil
  1051. })
  1052. if err == nil {
  1053. var creds AccountCredentials
  1054. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1055. for _, cert := range creds.Certfps {
  1056. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1057. am.server.store.Update(func(tx *buntdb.Tx) error {
  1058. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1059. tx.Delete(certFPKey)
  1060. }
  1061. return nil
  1062. })
  1063. }
  1064. }
  1065. }
  1066. skeleton, _ := Skeleton(accountName)
  1067. additionalNicks := unmarshalReservedNicks(rawNicks)
  1068. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1069. am.Lock()
  1070. defer am.Unlock()
  1071. clients = am.accountToClients[casefoldedAccount]
  1072. delete(am.accountToClients, casefoldedAccount)
  1073. // protect the account name itself where applicable, but not any grouped nicks
  1074. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1075. delete(am.nickToAccount, casefoldedAccount)
  1076. delete(am.skeletonToAccount, skeleton)
  1077. }
  1078. for _, nick := range additionalNicks {
  1079. delete(am.nickToAccount, nick)
  1080. additionalSkel, _ := Skeleton(nick)
  1081. delete(am.skeletonToAccount, additionalSkel)
  1082. }
  1083. for _, client := range clients {
  1084. if config.Accounts.RequireSasl.Enabled {
  1085. client.Logout()
  1086. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1087. // destroy acquires a semaphore so we can't call it while holding a lock
  1088. go client.destroy(nil)
  1089. } else {
  1090. am.logoutOfAccount(client)
  1091. }
  1092. }
  1093. if err != nil && !erase {
  1094. return errAccountDoesNotExist
  1095. }
  1096. return nil
  1097. }
  1098. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1099. if channelsStr != "" {
  1100. result = strings.Split(channelsStr, ",")
  1101. }
  1102. return
  1103. }
  1104. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1105. cfaccount, err := CasefoldName(account)
  1106. if err != nil {
  1107. return
  1108. }
  1109. var channelStr string
  1110. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1111. am.server.store.View(func(tx *buntdb.Tx) error {
  1112. channelStr, _ = tx.Get(key)
  1113. return nil
  1114. })
  1115. return unmarshalRegisteredChannels(channelStr)
  1116. }
  1117. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1118. if certfp == "" {
  1119. return errAccountInvalidCredentials
  1120. }
  1121. var account string
  1122. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1123. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1124. account, _ = tx.Get(certFPKey)
  1125. if account == "" {
  1126. return errAccountInvalidCredentials
  1127. }
  1128. return nil
  1129. })
  1130. if err != nil {
  1131. return err
  1132. }
  1133. if authzid != "" && authzid != account {
  1134. return errAuthzidAuthcidMismatch
  1135. }
  1136. // ok, we found an account corresponding to their certificate
  1137. clientAccount, err := am.LoadAccount(account)
  1138. if err != nil {
  1139. return err
  1140. } else if !clientAccount.Verified {
  1141. return errAccountUnverified
  1142. }
  1143. if client.registered {
  1144. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1145. return errNickAccountMismatch
  1146. }
  1147. }
  1148. am.Login(client, clientAccount)
  1149. return nil
  1150. }
  1151. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1152. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1153. casefoldedAccount, err := CasefoldName(account)
  1154. if err != nil {
  1155. return newSettings, errAccountDoesNotExist
  1156. }
  1157. // TODO implement this in general via a compare-and-swap API
  1158. accountData, err := am.LoadAccount(casefoldedAccount)
  1159. if err != nil {
  1160. return
  1161. } else if !accountData.Verified {
  1162. return newSettings, errAccountUnverified
  1163. }
  1164. newSettings, err = munger(accountData.Settings)
  1165. if err != nil {
  1166. return
  1167. }
  1168. text, err := json.Marshal(newSettings)
  1169. if err != nil {
  1170. return
  1171. }
  1172. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1173. serializedValue := string(text)
  1174. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1175. _, _, err = tx.Set(key, serializedValue, nil)
  1176. return
  1177. })
  1178. if err != nil {
  1179. err = errAccountUpdateFailed
  1180. return
  1181. }
  1182. // success, push new settings into the client objects
  1183. am.Lock()
  1184. defer am.Unlock()
  1185. for _, client := range am.accountToClients[casefoldedAccount] {
  1186. client.SetAccountSettings(newSettings)
  1187. }
  1188. return
  1189. }
  1190. // represents someone's status in hostserv
  1191. type VHostInfo struct {
  1192. ApprovedVHost string
  1193. Enabled bool
  1194. Forbidden bool
  1195. RequestedVHost string
  1196. RejectedVHost string
  1197. RejectionReason string
  1198. LastRequestTime time.Time
  1199. }
  1200. // pair type, <VHostInfo, accountName>
  1201. type PendingVHostRequest struct {
  1202. VHostInfo
  1203. Account string
  1204. }
  1205. type vhostThrottleExceeded struct {
  1206. timeRemaining time.Duration
  1207. }
  1208. func (vhe *vhostThrottleExceeded) Error() string {
  1209. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1210. }
  1211. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1212. if cooldown == 0 {
  1213. return nil
  1214. }
  1215. now := time.Now().UTC()
  1216. elapsed := now.Sub(vh.LastRequestTime)
  1217. if elapsed > cooldown {
  1218. // success
  1219. vh.LastRequestTime = now
  1220. return nil
  1221. } else {
  1222. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1223. }
  1224. }
  1225. // callback type implementing the actual business logic of vhost operations
  1226. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1227. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1228. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1229. output = input
  1230. output.Enabled = true
  1231. output.ApprovedVHost = vhost
  1232. return
  1233. }
  1234. return am.performVHostChange(account, munger)
  1235. }
  1236. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1237. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1238. output = input
  1239. if input.Forbidden {
  1240. err = errVhostsForbidden
  1241. return
  1242. }
  1243. // you can update your existing request, but if you were approved or rejected,
  1244. // you can't spam a new request
  1245. if output.RequestedVHost == "" {
  1246. err = output.checkThrottle(cooldown)
  1247. }
  1248. if err != nil {
  1249. return
  1250. }
  1251. output.RequestedVHost = vhost
  1252. output.RejectedVHost = ""
  1253. output.RejectionReason = ""
  1254. output.LastRequestTime = time.Now().UTC()
  1255. return
  1256. }
  1257. return am.performVHostChange(account, munger)
  1258. }
  1259. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1260. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1261. output = input
  1262. if input.Forbidden {
  1263. err = errVhostsForbidden
  1264. return
  1265. }
  1266. // if you have a request pending, you can cancel it using take;
  1267. // otherwise, you're subject to the same throttling as if you were making a request
  1268. if output.RequestedVHost == "" {
  1269. err = output.checkThrottle(cooldown)
  1270. }
  1271. if err != nil {
  1272. return
  1273. }
  1274. output.ApprovedVHost = vhost
  1275. output.RequestedVHost = ""
  1276. output.RejectedVHost = ""
  1277. output.RejectionReason = ""
  1278. output.LastRequestTime = time.Now().UTC()
  1279. return
  1280. }
  1281. return am.performVHostChange(account, munger)
  1282. }
  1283. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1284. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1285. output = input
  1286. output.Enabled = true
  1287. output.ApprovedVHost = input.RequestedVHost
  1288. output.RequestedVHost = ""
  1289. output.RejectionReason = ""
  1290. return
  1291. }
  1292. return am.performVHostChange(account, munger)
  1293. }
  1294. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1295. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1296. output = input
  1297. output.RejectedVHost = output.RequestedVHost
  1298. output.RequestedVHost = ""
  1299. output.RejectionReason = reason
  1300. return
  1301. }
  1302. return am.performVHostChange(account, munger)
  1303. }
  1304. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1305. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1306. if input.ApprovedVHost == "" {
  1307. err = errNoVhost
  1308. return
  1309. }
  1310. output = input
  1311. output.Enabled = enabled
  1312. return
  1313. }
  1314. return am.performVHostChange(client.Account(), munger)
  1315. }
  1316. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1317. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1318. output = input
  1319. output.Forbidden = forbid
  1320. return
  1321. }
  1322. return am.performVHostChange(account, munger)
  1323. }
  1324. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1325. account, err = CasefoldName(account)
  1326. if err != nil || account == "" {
  1327. err = errAccountDoesNotExist
  1328. return
  1329. }
  1330. am.vHostUpdateMutex.Lock()
  1331. defer am.vHostUpdateMutex.Unlock()
  1332. clientAccount, err := am.LoadAccount(account)
  1333. if err != nil {
  1334. err = errAccountDoesNotExist
  1335. return
  1336. } else if !clientAccount.Verified {
  1337. err = errAccountUnverified
  1338. return
  1339. }
  1340. result, err = munger(clientAccount.VHost)
  1341. if err != nil {
  1342. return
  1343. }
  1344. vhtext, err := json.Marshal(result)
  1345. if err != nil {
  1346. err = errAccountUpdateFailed
  1347. return
  1348. }
  1349. vhstr := string(vhtext)
  1350. key := fmt.Sprintf(keyAccountVHost, account)
  1351. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1352. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1353. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1354. return err
  1355. }
  1356. // update request queue
  1357. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1358. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1359. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1360. return err
  1361. }
  1362. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1363. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1364. _, err = tx.Delete(queueKey)
  1365. am.decrementVHostQueueCount(account, err)
  1366. }
  1367. return nil
  1368. })
  1369. if err != nil {
  1370. err = errAccountUpdateFailed
  1371. return
  1372. }
  1373. am.applyVhostToClients(account, result)
  1374. return result, nil
  1375. }
  1376. // XXX annoying helper method for keeping the queue count in sync with the DB
  1377. // `err` is the buntdb error returned from deleting the queue key
  1378. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1379. if err == nil {
  1380. // successfully deleted a queue entry, do a 2's complement decrement:
  1381. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1382. } else if err != buntdb.ErrNotFound {
  1383. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1384. }
  1385. }
  1386. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1387. am.vHostUpdateMutex.Lock()
  1388. defer am.vHostUpdateMutex.Unlock()
  1389. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1390. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1391. accounts := make([]string, 0, limit)
  1392. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1393. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1394. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1395. return len(accounts) < limit
  1396. })
  1397. })
  1398. if err != nil {
  1399. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1400. return
  1401. }
  1402. for _, account := range accounts {
  1403. accountInfo, err := am.LoadAccount(account)
  1404. if err == nil {
  1405. requests = append(requests, PendingVHostRequest{
  1406. Account: account,
  1407. VHostInfo: accountInfo.VHost,
  1408. })
  1409. } else {
  1410. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1411. }
  1412. }
  1413. return
  1414. }
  1415. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1416. // if hostserv is disabled in config, then don't grant vhosts
  1417. // that were previously approved while it was enabled
  1418. if !am.server.Config().Accounts.VHosts.Enabled {
  1419. return
  1420. }
  1421. vhost := ""
  1422. if info.Enabled && !info.Forbidden {
  1423. vhost = info.ApprovedVHost
  1424. }
  1425. oldNickmask := client.NickMaskString()
  1426. updated := client.SetVHost(vhost)
  1427. if updated {
  1428. // TODO: doing I/O here is kind of a kludge
  1429. go client.sendChghost(oldNickmask, client.Hostname())
  1430. }
  1431. }
  1432. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1433. am.RLock()
  1434. clients := am.accountToClients[account]
  1435. am.RUnlock()
  1436. for _, client := range clients {
  1437. am.applyVHostInfo(client, result)
  1438. }
  1439. }
  1440. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1441. client.Login(account)
  1442. client.nickTimer.Touch(nil)
  1443. am.applyVHostInfo(client, account.VHost)
  1444. casefoldedAccount := client.Account()
  1445. am.Lock()
  1446. defer am.Unlock()
  1447. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1448. }
  1449. func (am *AccountManager) Logout(client *Client) {
  1450. am.Lock()
  1451. defer am.Unlock()
  1452. casefoldedAccount := client.Account()
  1453. if casefoldedAccount == "" {
  1454. return
  1455. }
  1456. am.logoutOfAccount(client)
  1457. clients := am.accountToClients[casefoldedAccount]
  1458. if len(clients) <= 1 {
  1459. delete(am.accountToClients, casefoldedAccount)
  1460. return
  1461. }
  1462. remainingClients := make([]*Client, len(clients)-1)
  1463. remainingPos := 0
  1464. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1465. if clients[currentPos] != client {
  1466. remainingClients[remainingPos] = clients[currentPos]
  1467. remainingPos++
  1468. }
  1469. }
  1470. am.accountToClients[casefoldedAccount] = remainingClients
  1471. }
  1472. var (
  1473. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1474. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1475. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1476. "PLAIN": authPlainHandler,
  1477. "EXTERNAL": authExternalHandler,
  1478. }
  1479. )
  1480. // AccountCredentials stores the various methods for verifying accounts.
  1481. type AccountCredentials struct {
  1482. Version uint
  1483. PassphraseSalt []byte // legacy field, not used by v1 and later
  1484. PassphraseHash []byte
  1485. Certfps []string
  1486. }
  1487. func (ac *AccountCredentials) Empty() bool {
  1488. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1489. }
  1490. // helper to assemble the serialized JSON for an account's credentials
  1491. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1492. ac.Version = 1
  1493. credText, err := json.Marshal(*ac)
  1494. if err != nil {
  1495. return "", err
  1496. }
  1497. return string(credText), nil
  1498. }
  1499. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1500. if passphrase == "" {
  1501. ac.PassphraseHash = nil
  1502. return nil
  1503. }
  1504. if validatePassphrase(passphrase) != nil {
  1505. return errAccountBadPassphrase
  1506. }
  1507. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1508. if err != nil {
  1509. return errAccountBadPassphrase
  1510. }
  1511. return nil
  1512. }
  1513. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1514. // XXX we require that certfp is already normalized (rather than normalize here
  1515. // and pass back the normalized version as an additional return parameter);
  1516. // this is just a final sanity check:
  1517. if len(certfp) != 64 {
  1518. return utils.ErrInvalidCertfp
  1519. }
  1520. for _, current := range ac.Certfps {
  1521. if certfp == current {
  1522. return errNoop
  1523. }
  1524. }
  1525. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1526. return errLimitExceeded
  1527. }
  1528. ac.Certfps = append(ac.Certfps, certfp)
  1529. return nil
  1530. }
  1531. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1532. found := false
  1533. newList := make([]string, 0, len(ac.Certfps))
  1534. for _, current := range ac.Certfps {
  1535. if current == certfp {
  1536. found = true
  1537. } else {
  1538. newList = append(newList, current)
  1539. }
  1540. }
  1541. if !found {
  1542. // this is important because it prevents you from deleting someone else's
  1543. // fingerprint record
  1544. return errNoop
  1545. }
  1546. ac.Certfps = newList
  1547. return nil
  1548. }
  1549. type MulticlientAllowedSetting int
  1550. const (
  1551. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1552. MulticlientDisallowedByUser
  1553. MulticlientAllowedByUser
  1554. )
  1555. // controls whether/when clients without event-playback support see fake
  1556. // PRIVMSGs for JOINs
  1557. type ReplayJoinsSetting uint
  1558. const (
  1559. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1560. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1561. ReplayJoinsNever // never replay
  1562. )
  1563. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1564. switch strings.ToLower(str) {
  1565. case "commands-only":
  1566. result = ReplayJoinsCommandsOnly
  1567. case "always":
  1568. result = ReplayJoinsAlways
  1569. case "never":
  1570. result = ReplayJoinsNever
  1571. default:
  1572. err = errInvalidParams
  1573. }
  1574. return
  1575. }
  1576. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1577. // persistent JSON blobs in the database
  1578. type AccountSettings struct {
  1579. AutoreplayLines *int
  1580. NickEnforcement NickEnforcementMethod
  1581. AllowBouncer MulticlientAllowedSetting
  1582. ReplayJoins ReplayJoinsSetting
  1583. AlwaysOn PersistentStatus
  1584. AutoreplayMissed bool
  1585. DMHistory HistoryStatus
  1586. }
  1587. // ClientAccount represents a user account.
  1588. type ClientAccount struct {
  1589. // Name of the account.
  1590. Name string
  1591. NameCasefolded string
  1592. RegisteredAt time.Time
  1593. Credentials AccountCredentials
  1594. Verified bool
  1595. AdditionalNicks []string
  1596. VHost VHostInfo
  1597. Settings AccountSettings
  1598. }
  1599. // convenience for passing around raw serialized account data
  1600. type rawClientAccount struct {
  1601. Name string
  1602. RegisteredAt string
  1603. Credentials string
  1604. Callback string
  1605. Verified bool
  1606. AdditionalNicks string
  1607. VHost string
  1608. Settings string
  1609. }
  1610. // logoutOfAccount logs the client out of their current account.
  1611. func (am *AccountManager) logoutOfAccount(client *Client) {
  1612. if client.Account() == "" {
  1613. // already logged out
  1614. return
  1615. }
  1616. client.Logout()
  1617. go client.nickTimer.Touch(nil)
  1618. // dispatch account-notify
  1619. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1620. go func() {
  1621. for friend := range client.Friends(caps.AccountNotify) {
  1622. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1623. }
  1624. }()
  1625. }