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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  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, "Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
  628. fmt.Fprintf(&message, "Subject: %s\r\n", subject)
  629. message.WriteString("\r\n") // blank line: end headers, begin message body
  630. fmt.Fprintf(&message, client.t("Account: %s"), account)
  631. message.WriteString("\r\n")
  632. fmt.Fprintf(&message, client.t("Verification code: %s"), code)
  633. message.WriteString("\r\n")
  634. message.WriteString("\r\n")
  635. message.WriteString(client.t("To verify your account, issue the following command:"))
  636. message.WriteString("\r\n")
  637. fmt.Fprintf(&message, "/MSG NickServ VERIFY %s %s\r\n", account, code)
  638. err = email.SendMail(config, callbackValue, message.Bytes())
  639. if err != nil {
  640. am.server.logger.Error("internal", "Failed to dispatch e-mail to", callbackValue, err.Error())
  641. }
  642. return
  643. }
  644. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  645. casefoldedAccount, err := CasefoldName(account)
  646. var skeleton string
  647. if err != nil || account == "" || account == "*" {
  648. return errAccountVerificationFailed
  649. }
  650. if client != nil && client.Account() != "" {
  651. return errAccountAlreadyLoggedIn
  652. }
  653. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  654. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  655. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  656. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  657. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  658. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  659. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  660. var raw rawClientAccount
  661. func() {
  662. am.serialCacheUpdateMutex.Lock()
  663. defer am.serialCacheUpdateMutex.Unlock()
  664. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  665. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  666. if err == errAccountDoesNotExist {
  667. return errAccountDoesNotExist
  668. } else if err != nil {
  669. return errAccountVerificationFailed
  670. } else if raw.Verified {
  671. return errAccountAlreadyVerified
  672. }
  673. // actually verify the code
  674. // a stored code of "" means a none callback / no code required
  675. success := false
  676. storedCode, err := tx.Get(verificationCodeKey)
  677. if err == nil {
  678. // this is probably unnecessary
  679. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  680. success = true
  681. }
  682. }
  683. if !success {
  684. return errAccountVerificationInvalidCode
  685. }
  686. // verify the account
  687. tx.Set(verifiedKey, "1", nil)
  688. // don't need the code anymore
  689. tx.Delete(verificationCodeKey)
  690. // re-set all other keys, removing the TTL
  691. tx.Set(accountKey, "1", nil)
  692. tx.Set(accountNameKey, raw.Name, nil)
  693. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  694. tx.Set(callbackKey, raw.Callback, nil)
  695. tx.Set(credentialsKey, raw.Credentials, nil)
  696. var creds AccountCredentials
  697. // XXX we shouldn't do (de)serialization inside the txn,
  698. // but this is like 2 usec on my system
  699. json.Unmarshal([]byte(raw.Credentials), &creds)
  700. for _, cert := range creds.Certfps {
  701. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  702. tx.Set(certFPKey, casefoldedAccount, nil)
  703. }
  704. return nil
  705. })
  706. if err == nil {
  707. skeleton, _ = Skeleton(raw.Name)
  708. am.Lock()
  709. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  710. am.skeletonToAccount[skeleton] = casefoldedAccount
  711. am.Unlock()
  712. }
  713. }()
  714. if err != nil {
  715. return err
  716. }
  717. nick := "[server admin]"
  718. if client != nil {
  719. nick = client.Nick()
  720. }
  721. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  722. raw.Verified = true
  723. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  724. if err != nil {
  725. return err
  726. }
  727. if client != nil {
  728. am.Login(client, clientAccount)
  729. }
  730. _, method := am.EnforcementStatus(casefoldedAccount, skeleton)
  731. if method != NickEnforcementNone {
  732. currentClient := am.server.clients.Get(casefoldedAccount)
  733. if currentClient == nil || currentClient == client || currentClient.Account() == casefoldedAccount {
  734. return nil
  735. }
  736. if method == NickEnforcementStrict {
  737. am.server.RandomlyRename(currentClient)
  738. } else if method == NickEnforcementWithTimeout {
  739. currentClient.nickTimer.Touch(nil)
  740. }
  741. }
  742. return nil
  743. }
  744. // register and verify an account, for internal use
  745. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  746. err = am.Register(nil, account, "admin", "", passphrase, "")
  747. if err == nil {
  748. err = am.Verify(nil, account, "")
  749. }
  750. return
  751. }
  752. func marshalReservedNicks(nicks []string) string {
  753. return strings.Join(nicks, ",")
  754. }
  755. func unmarshalReservedNicks(nicks string) (result []string) {
  756. if nicks == "" {
  757. return
  758. }
  759. return strings.Split(nicks, ",")
  760. }
  761. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  762. cfnick, err := CasefoldName(nick)
  763. skeleton, skerr := Skeleton(nick)
  764. // garbage nick, or garbage options, or disabled
  765. nrconfig := am.server.Config().Accounts.NickReservation
  766. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  767. return errAccountNickReservationFailed
  768. }
  769. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  770. am.serialCacheUpdateMutex.Lock()
  771. defer am.serialCacheUpdateMutex.Unlock()
  772. // find the affected account, which is usually the client's:
  773. account := client.Account()
  774. if saUnreserve {
  775. // unless this is a sadrop:
  776. account = am.NickToAccount(cfnick)
  777. if account == "" {
  778. // nothing to do
  779. return nil
  780. }
  781. }
  782. if account == "" {
  783. return errAccountNotLoggedIn
  784. }
  785. am.Lock()
  786. accountForNick := am.nickToAccount[cfnick]
  787. var accountForSkeleton string
  788. if reserve {
  789. accountForSkeleton = am.skeletonToAccount[skeleton]
  790. }
  791. am.Unlock()
  792. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  793. return errNicknameReserved
  794. } else if !reserve && !saUnreserve && accountForNick != account {
  795. return errNicknameReserved
  796. } else if !reserve && cfnick == account {
  797. return errAccountCantDropPrimaryNick
  798. }
  799. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  800. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  801. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  802. if reserve {
  803. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  804. // however you shouldn't be able to reserve a nick out from under them
  805. _, err := tx.Get(unverifiedAccountKey)
  806. if err == nil {
  807. return errNicknameReserved
  808. }
  809. }
  810. rawNicks, err := tx.Get(nicksKey)
  811. if err != nil && err != buntdb.ErrNotFound {
  812. return err
  813. }
  814. nicks := unmarshalReservedNicks(rawNicks)
  815. if reserve {
  816. if len(nicks) >= nrconfig.AdditionalNickLimit {
  817. return errAccountTooManyNicks
  818. }
  819. nicks = append(nicks, nick)
  820. } else {
  821. // compute (original reserved nicks) minus cfnick
  822. var newNicks []string
  823. for _, reservedNick := range nicks {
  824. cfreservednick, _ := CasefoldName(reservedNick)
  825. if cfreservednick != cfnick {
  826. newNicks = append(newNicks, reservedNick)
  827. } else {
  828. // found the original, unfolded version of the nick we're dropping;
  829. // recompute the true skeleton from it
  830. skeleton, _ = Skeleton(reservedNick)
  831. }
  832. }
  833. nicks = newNicks
  834. }
  835. marshaledNicks := marshalReservedNicks(nicks)
  836. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  837. return err
  838. })
  839. if err == errAccountTooManyNicks || err == errNicknameReserved {
  840. return err
  841. } else if err != nil {
  842. return errAccountNickReservationFailed
  843. }
  844. // success
  845. am.Lock()
  846. defer am.Unlock()
  847. if reserve {
  848. am.nickToAccount[cfnick] = account
  849. am.skeletonToAccount[skeleton] = account
  850. } else {
  851. delete(am.nickToAccount, cfnick)
  852. delete(am.skeletonToAccount, skeleton)
  853. }
  854. return nil
  855. }
  856. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  857. account, err = am.LoadAccount(accountName)
  858. if err != nil {
  859. return
  860. }
  861. if !account.Verified {
  862. err = errAccountUnverified
  863. return
  864. }
  865. switch account.Credentials.Version {
  866. case 0:
  867. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  868. case 1:
  869. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  870. err = errAccountInvalidCredentials
  871. }
  872. default:
  873. err = errAccountInvalidCredentials
  874. }
  875. return
  876. }
  877. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  878. // XXX check this now, so we don't allow a redundant login for an always-on client
  879. // even for a brief period. the other potential source of nick-account conflicts
  880. // is from force-nick-equals-account, but those will be caught later by
  881. // fixupNickEqualsAccount and if there is a conflict, they will be logged out.
  882. if client.registered {
  883. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  884. return errNickAccountMismatch
  885. }
  886. }
  887. var account ClientAccount
  888. defer func() {
  889. if err == nil {
  890. am.Login(client, account)
  891. }
  892. }()
  893. ldapConf := am.server.Config().Accounts.LDAP
  894. if ldapConf.Enabled {
  895. err = ldap.CheckLDAPPassphrase(ldapConf, accountName, passphrase, am.server.logger)
  896. if err == nil {
  897. account, err = am.LoadAccount(accountName)
  898. // autocreate if necessary:
  899. if err == errAccountDoesNotExist && ldapConf.Autocreate {
  900. err = am.SARegister(accountName, "")
  901. if err != nil {
  902. return
  903. }
  904. account, err = am.LoadAccount(accountName)
  905. }
  906. return
  907. }
  908. }
  909. account, err = am.checkPassphrase(accountName, passphrase)
  910. return err
  911. }
  912. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  913. casefoldedAccount, err := CasefoldName(accountName)
  914. if err != nil {
  915. err = errAccountDoesNotExist
  916. return
  917. }
  918. var raw rawClientAccount
  919. am.server.store.View(func(tx *buntdb.Tx) error {
  920. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  921. return nil
  922. })
  923. if err != nil {
  924. return
  925. }
  926. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  927. return
  928. }
  929. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  930. result.Name = raw.Name
  931. result.NameCasefolded = cfName
  932. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  933. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  934. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  935. if e != nil {
  936. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  937. err = errAccountDoesNotExist
  938. return
  939. }
  940. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  941. result.Verified = raw.Verified
  942. if raw.VHost != "" {
  943. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  944. if e != nil {
  945. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  946. // pretend they have no vhost and move on
  947. }
  948. }
  949. if raw.Settings != "" {
  950. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  951. if e != nil {
  952. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  953. }
  954. }
  955. return
  956. }
  957. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  958. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  959. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  960. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  961. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  962. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  963. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  964. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  965. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  966. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  967. _, e := tx.Get(accountKey)
  968. if e == buntdb.ErrNotFound {
  969. err = errAccountDoesNotExist
  970. return
  971. }
  972. result.Name, _ = tx.Get(accountNameKey)
  973. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  974. result.Credentials, _ = tx.Get(credentialsKey)
  975. result.Callback, _ = tx.Get(callbackKey)
  976. result.AdditionalNicks, _ = tx.Get(nicksKey)
  977. result.VHost, _ = tx.Get(vhostKey)
  978. result.Settings, _ = tx.Get(settingsKey)
  979. if _, e = tx.Get(verifiedKey); e == nil {
  980. result.Verified = true
  981. }
  982. return
  983. }
  984. func (am *AccountManager) Unregister(account string, erase bool) error {
  985. config := am.server.Config()
  986. casefoldedAccount, err := CasefoldName(account)
  987. if err != nil {
  988. return errAccountDoesNotExist
  989. }
  990. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  991. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  992. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  993. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  994. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  995. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  996. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  997. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  998. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  999. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1000. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  1001. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1002. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  1003. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1004. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1005. var clients []*Client
  1006. var registeredChannels []string
  1007. // on our way out, unregister all the account's channels and delete them from the db
  1008. defer func() {
  1009. for _, channelName := range registeredChannels {
  1010. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1011. if err != nil {
  1012. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1013. }
  1014. }
  1015. }()
  1016. var credText string
  1017. var rawNicks string
  1018. am.serialCacheUpdateMutex.Lock()
  1019. defer am.serialCacheUpdateMutex.Unlock()
  1020. var accountName string
  1021. var channelsStr string
  1022. keepProtections := false
  1023. am.server.store.Update(func(tx *buntdb.Tx) error {
  1024. accountName, _ = tx.Get(accountNameKey)
  1025. if erase {
  1026. tx.Delete(unregisteredKey)
  1027. } else {
  1028. if _, err := tx.Get(verifiedKey); err == nil {
  1029. tx.Set(unregisteredKey, accountName, nil)
  1030. keepProtections = true
  1031. }
  1032. }
  1033. tx.Delete(accountKey)
  1034. tx.Delete(accountNameKey)
  1035. tx.Delete(verifiedKey)
  1036. tx.Delete(registeredTimeKey)
  1037. tx.Delete(callbackKey)
  1038. tx.Delete(verificationCodeKey)
  1039. tx.Delete(settingsKey)
  1040. rawNicks, _ = tx.Get(nicksKey)
  1041. tx.Delete(nicksKey)
  1042. credText, err = tx.Get(credentialsKey)
  1043. tx.Delete(credentialsKey)
  1044. tx.Delete(vhostKey)
  1045. channelsStr, _ = tx.Get(channelsKey)
  1046. tx.Delete(channelsKey)
  1047. tx.Delete(joinedChannelsKey)
  1048. tx.Delete(lastSeenKey)
  1049. _, err := tx.Delete(vhostQueueKey)
  1050. am.decrementVHostQueueCount(casefoldedAccount, err)
  1051. return nil
  1052. })
  1053. if err == nil {
  1054. var creds AccountCredentials
  1055. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1056. for _, cert := range creds.Certfps {
  1057. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1058. am.server.store.Update(func(tx *buntdb.Tx) error {
  1059. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1060. tx.Delete(certFPKey)
  1061. }
  1062. return nil
  1063. })
  1064. }
  1065. }
  1066. }
  1067. skeleton, _ := Skeleton(accountName)
  1068. additionalNicks := unmarshalReservedNicks(rawNicks)
  1069. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1070. am.Lock()
  1071. defer am.Unlock()
  1072. clients = am.accountToClients[casefoldedAccount]
  1073. delete(am.accountToClients, casefoldedAccount)
  1074. // protect the account name itself where applicable, but not any grouped nicks
  1075. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1076. delete(am.nickToAccount, casefoldedAccount)
  1077. delete(am.skeletonToAccount, skeleton)
  1078. }
  1079. for _, nick := range additionalNicks {
  1080. delete(am.nickToAccount, nick)
  1081. additionalSkel, _ := Skeleton(nick)
  1082. delete(am.skeletonToAccount, additionalSkel)
  1083. }
  1084. for _, client := range clients {
  1085. if config.Accounts.RequireSasl.Enabled {
  1086. client.Logout()
  1087. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1088. // destroy acquires a semaphore so we can't call it while holding a lock
  1089. go client.destroy(nil)
  1090. } else {
  1091. am.logoutOfAccount(client)
  1092. }
  1093. }
  1094. if err != nil && !erase {
  1095. return errAccountDoesNotExist
  1096. }
  1097. return nil
  1098. }
  1099. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1100. if channelsStr != "" {
  1101. result = strings.Split(channelsStr, ",")
  1102. }
  1103. return
  1104. }
  1105. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1106. cfaccount, err := CasefoldName(account)
  1107. if err != nil {
  1108. return
  1109. }
  1110. var channelStr string
  1111. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1112. am.server.store.View(func(tx *buntdb.Tx) error {
  1113. channelStr, _ = tx.Get(key)
  1114. return nil
  1115. })
  1116. return unmarshalRegisteredChannels(channelStr)
  1117. }
  1118. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1119. if certfp == "" {
  1120. return errAccountInvalidCredentials
  1121. }
  1122. var account string
  1123. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1124. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1125. account, _ = tx.Get(certFPKey)
  1126. if account == "" {
  1127. return errAccountInvalidCredentials
  1128. }
  1129. return nil
  1130. })
  1131. if err != nil {
  1132. return err
  1133. }
  1134. if authzid != "" && authzid != account {
  1135. return errAuthzidAuthcidMismatch
  1136. }
  1137. // ok, we found an account corresponding to their certificate
  1138. clientAccount, err := am.LoadAccount(account)
  1139. if err != nil {
  1140. return err
  1141. } else if !clientAccount.Verified {
  1142. return errAccountUnverified
  1143. }
  1144. if client.registered {
  1145. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1146. return errNickAccountMismatch
  1147. }
  1148. }
  1149. am.Login(client, clientAccount)
  1150. return nil
  1151. }
  1152. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1153. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1154. casefoldedAccount, err := CasefoldName(account)
  1155. if err != nil {
  1156. return newSettings, errAccountDoesNotExist
  1157. }
  1158. // TODO implement this in general via a compare-and-swap API
  1159. accountData, err := am.LoadAccount(casefoldedAccount)
  1160. if err != nil {
  1161. return
  1162. } else if !accountData.Verified {
  1163. return newSettings, errAccountUnverified
  1164. }
  1165. newSettings, err = munger(accountData.Settings)
  1166. if err != nil {
  1167. return
  1168. }
  1169. text, err := json.Marshal(newSettings)
  1170. if err != nil {
  1171. return
  1172. }
  1173. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1174. serializedValue := string(text)
  1175. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1176. _, _, err = tx.Set(key, serializedValue, nil)
  1177. return
  1178. })
  1179. if err != nil {
  1180. err = errAccountUpdateFailed
  1181. return
  1182. }
  1183. // success, push new settings into the client objects
  1184. am.Lock()
  1185. defer am.Unlock()
  1186. for _, client := range am.accountToClients[casefoldedAccount] {
  1187. client.SetAccountSettings(newSettings)
  1188. }
  1189. return
  1190. }
  1191. // represents someone's status in hostserv
  1192. type VHostInfo struct {
  1193. ApprovedVHost string
  1194. Enabled bool
  1195. Forbidden bool
  1196. RequestedVHost string
  1197. RejectedVHost string
  1198. RejectionReason string
  1199. LastRequestTime time.Time
  1200. }
  1201. // pair type, <VHostInfo, accountName>
  1202. type PendingVHostRequest struct {
  1203. VHostInfo
  1204. Account string
  1205. }
  1206. type vhostThrottleExceeded struct {
  1207. timeRemaining time.Duration
  1208. }
  1209. func (vhe *vhostThrottleExceeded) Error() string {
  1210. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1211. }
  1212. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1213. if cooldown == 0 {
  1214. return nil
  1215. }
  1216. now := time.Now().UTC()
  1217. elapsed := now.Sub(vh.LastRequestTime)
  1218. if elapsed > cooldown {
  1219. // success
  1220. vh.LastRequestTime = now
  1221. return nil
  1222. } else {
  1223. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1224. }
  1225. }
  1226. // callback type implementing the actual business logic of vhost operations
  1227. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1228. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1229. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1230. output = input
  1231. output.Enabled = true
  1232. output.ApprovedVHost = vhost
  1233. return
  1234. }
  1235. return am.performVHostChange(account, munger)
  1236. }
  1237. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1238. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1239. output = input
  1240. if input.Forbidden {
  1241. err = errVhostsForbidden
  1242. return
  1243. }
  1244. // you can update your existing request, but if you were approved or rejected,
  1245. // you can't spam a new request
  1246. if output.RequestedVHost == "" {
  1247. err = output.checkThrottle(cooldown)
  1248. }
  1249. if err != nil {
  1250. return
  1251. }
  1252. output.RequestedVHost = vhost
  1253. output.RejectedVHost = ""
  1254. output.RejectionReason = ""
  1255. output.LastRequestTime = time.Now().UTC()
  1256. return
  1257. }
  1258. return am.performVHostChange(account, munger)
  1259. }
  1260. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1261. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1262. output = input
  1263. if input.Forbidden {
  1264. err = errVhostsForbidden
  1265. return
  1266. }
  1267. // if you have a request pending, you can cancel it using take;
  1268. // otherwise, you're subject to the same throttling as if you were making a request
  1269. if output.RequestedVHost == "" {
  1270. err = output.checkThrottle(cooldown)
  1271. }
  1272. if err != nil {
  1273. return
  1274. }
  1275. output.ApprovedVHost = vhost
  1276. output.RequestedVHost = ""
  1277. output.RejectedVHost = ""
  1278. output.RejectionReason = ""
  1279. output.LastRequestTime = time.Now().UTC()
  1280. return
  1281. }
  1282. return am.performVHostChange(account, munger)
  1283. }
  1284. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1285. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1286. output = input
  1287. output.Enabled = true
  1288. output.ApprovedVHost = input.RequestedVHost
  1289. output.RequestedVHost = ""
  1290. output.RejectionReason = ""
  1291. return
  1292. }
  1293. return am.performVHostChange(account, munger)
  1294. }
  1295. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1296. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1297. output = input
  1298. output.RejectedVHost = output.RequestedVHost
  1299. output.RequestedVHost = ""
  1300. output.RejectionReason = reason
  1301. return
  1302. }
  1303. return am.performVHostChange(account, munger)
  1304. }
  1305. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1306. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1307. if input.ApprovedVHost == "" {
  1308. err = errNoVhost
  1309. return
  1310. }
  1311. output = input
  1312. output.Enabled = enabled
  1313. return
  1314. }
  1315. return am.performVHostChange(client.Account(), munger)
  1316. }
  1317. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1318. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1319. output = input
  1320. output.Forbidden = forbid
  1321. return
  1322. }
  1323. return am.performVHostChange(account, munger)
  1324. }
  1325. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1326. account, err = CasefoldName(account)
  1327. if err != nil || account == "" {
  1328. err = errAccountDoesNotExist
  1329. return
  1330. }
  1331. am.vHostUpdateMutex.Lock()
  1332. defer am.vHostUpdateMutex.Unlock()
  1333. clientAccount, err := am.LoadAccount(account)
  1334. if err != nil {
  1335. err = errAccountDoesNotExist
  1336. return
  1337. } else if !clientAccount.Verified {
  1338. err = errAccountUnverified
  1339. return
  1340. }
  1341. result, err = munger(clientAccount.VHost)
  1342. if err != nil {
  1343. return
  1344. }
  1345. vhtext, err := json.Marshal(result)
  1346. if err != nil {
  1347. err = errAccountUpdateFailed
  1348. return
  1349. }
  1350. vhstr := string(vhtext)
  1351. key := fmt.Sprintf(keyAccountVHost, account)
  1352. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1353. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1354. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1355. return err
  1356. }
  1357. // update request queue
  1358. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1359. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1360. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1361. return err
  1362. }
  1363. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1364. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1365. _, err = tx.Delete(queueKey)
  1366. am.decrementVHostQueueCount(account, err)
  1367. }
  1368. return nil
  1369. })
  1370. if err != nil {
  1371. err = errAccountUpdateFailed
  1372. return
  1373. }
  1374. am.applyVhostToClients(account, result)
  1375. return result, nil
  1376. }
  1377. // XXX annoying helper method for keeping the queue count in sync with the DB
  1378. // `err` is the buntdb error returned from deleting the queue key
  1379. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1380. if err == nil {
  1381. // successfully deleted a queue entry, do a 2's complement decrement:
  1382. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1383. } else if err != buntdb.ErrNotFound {
  1384. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1385. }
  1386. }
  1387. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1388. am.vHostUpdateMutex.Lock()
  1389. defer am.vHostUpdateMutex.Unlock()
  1390. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1391. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1392. accounts := make([]string, 0, limit)
  1393. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1394. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1395. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1396. return len(accounts) < limit
  1397. })
  1398. })
  1399. if err != nil {
  1400. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1401. return
  1402. }
  1403. for _, account := range accounts {
  1404. accountInfo, err := am.LoadAccount(account)
  1405. if err == nil {
  1406. requests = append(requests, PendingVHostRequest{
  1407. Account: account,
  1408. VHostInfo: accountInfo.VHost,
  1409. })
  1410. } else {
  1411. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1412. }
  1413. }
  1414. return
  1415. }
  1416. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1417. // if hostserv is disabled in config, then don't grant vhosts
  1418. // that were previously approved while it was enabled
  1419. if !am.server.Config().Accounts.VHosts.Enabled {
  1420. return
  1421. }
  1422. vhost := ""
  1423. if info.Enabled && !info.Forbidden {
  1424. vhost = info.ApprovedVHost
  1425. }
  1426. oldNickmask := client.NickMaskString()
  1427. updated := client.SetVHost(vhost)
  1428. if updated {
  1429. // TODO: doing I/O here is kind of a kludge
  1430. go client.sendChghost(oldNickmask, client.Hostname())
  1431. }
  1432. }
  1433. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1434. am.RLock()
  1435. clients := am.accountToClients[account]
  1436. am.RUnlock()
  1437. for _, client := range clients {
  1438. am.applyVHostInfo(client, result)
  1439. }
  1440. }
  1441. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1442. client.Login(account)
  1443. client.nickTimer.Touch(nil)
  1444. am.applyVHostInfo(client, account.VHost)
  1445. casefoldedAccount := client.Account()
  1446. am.Lock()
  1447. defer am.Unlock()
  1448. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1449. }
  1450. func (am *AccountManager) Logout(client *Client) {
  1451. am.Lock()
  1452. defer am.Unlock()
  1453. casefoldedAccount := client.Account()
  1454. if casefoldedAccount == "" {
  1455. return
  1456. }
  1457. am.logoutOfAccount(client)
  1458. clients := am.accountToClients[casefoldedAccount]
  1459. if len(clients) <= 1 {
  1460. delete(am.accountToClients, casefoldedAccount)
  1461. return
  1462. }
  1463. remainingClients := make([]*Client, len(clients)-1)
  1464. remainingPos := 0
  1465. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1466. if clients[currentPos] != client {
  1467. remainingClients[remainingPos] = clients[currentPos]
  1468. remainingPos++
  1469. }
  1470. }
  1471. am.accountToClients[casefoldedAccount] = remainingClients
  1472. }
  1473. var (
  1474. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1475. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1476. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1477. "PLAIN": authPlainHandler,
  1478. "EXTERNAL": authExternalHandler,
  1479. }
  1480. )
  1481. // AccountCredentials stores the various methods for verifying accounts.
  1482. type AccountCredentials struct {
  1483. Version uint
  1484. PassphraseSalt []byte // legacy field, not used by v1 and later
  1485. PassphraseHash []byte
  1486. Certfps []string
  1487. }
  1488. func (ac *AccountCredentials) Empty() bool {
  1489. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1490. }
  1491. // helper to assemble the serialized JSON for an account's credentials
  1492. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1493. ac.Version = 1
  1494. credText, err := json.Marshal(*ac)
  1495. if err != nil {
  1496. return "", err
  1497. }
  1498. return string(credText), nil
  1499. }
  1500. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1501. if passphrase == "" {
  1502. ac.PassphraseHash = nil
  1503. return nil
  1504. }
  1505. if validatePassphrase(passphrase) != nil {
  1506. return errAccountBadPassphrase
  1507. }
  1508. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1509. if err != nil {
  1510. return errAccountBadPassphrase
  1511. }
  1512. return nil
  1513. }
  1514. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1515. // XXX we require that certfp is already normalized (rather than normalize here
  1516. // and pass back the normalized version as an additional return parameter);
  1517. // this is just a final sanity check:
  1518. if len(certfp) != 64 {
  1519. return utils.ErrInvalidCertfp
  1520. }
  1521. for _, current := range ac.Certfps {
  1522. if certfp == current {
  1523. return errNoop
  1524. }
  1525. }
  1526. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1527. return errLimitExceeded
  1528. }
  1529. ac.Certfps = append(ac.Certfps, certfp)
  1530. return nil
  1531. }
  1532. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1533. found := false
  1534. newList := make([]string, 0, len(ac.Certfps))
  1535. for _, current := range ac.Certfps {
  1536. if current == certfp {
  1537. found = true
  1538. } else {
  1539. newList = append(newList, current)
  1540. }
  1541. }
  1542. if !found {
  1543. // this is important because it prevents you from deleting someone else's
  1544. // fingerprint record
  1545. return errNoop
  1546. }
  1547. ac.Certfps = newList
  1548. return nil
  1549. }
  1550. type MulticlientAllowedSetting int
  1551. const (
  1552. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1553. MulticlientDisallowedByUser
  1554. MulticlientAllowedByUser
  1555. )
  1556. // controls whether/when clients without event-playback support see fake
  1557. // PRIVMSGs for JOINs
  1558. type ReplayJoinsSetting uint
  1559. const (
  1560. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1561. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1562. ReplayJoinsNever // never replay
  1563. )
  1564. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1565. switch strings.ToLower(str) {
  1566. case "commands-only":
  1567. result = ReplayJoinsCommandsOnly
  1568. case "always":
  1569. result = ReplayJoinsAlways
  1570. case "never":
  1571. result = ReplayJoinsNever
  1572. default:
  1573. err = errInvalidParams
  1574. }
  1575. return
  1576. }
  1577. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1578. // persistent JSON blobs in the database
  1579. type AccountSettings struct {
  1580. AutoreplayLines *int
  1581. NickEnforcement NickEnforcementMethod
  1582. AllowBouncer MulticlientAllowedSetting
  1583. ReplayJoins ReplayJoinsSetting
  1584. AlwaysOn PersistentStatus
  1585. AutoreplayMissed bool
  1586. DMHistory HistoryStatus
  1587. }
  1588. // ClientAccount represents a user account.
  1589. type ClientAccount struct {
  1590. // Name of the account.
  1591. Name string
  1592. NameCasefolded string
  1593. RegisteredAt time.Time
  1594. Credentials AccountCredentials
  1595. Verified bool
  1596. AdditionalNicks []string
  1597. VHost VHostInfo
  1598. Settings AccountSettings
  1599. }
  1600. // convenience for passing around raw serialized account data
  1601. type rawClientAccount struct {
  1602. Name string
  1603. RegisteredAt string
  1604. Credentials string
  1605. Callback string
  1606. Verified bool
  1607. AdditionalNicks string
  1608. VHost string
  1609. Settings string
  1610. }
  1611. // logoutOfAccount logs the client out of their current account.
  1612. func (am *AccountManager) logoutOfAccount(client *Client) {
  1613. if client.Account() == "" {
  1614. // already logged out
  1615. return
  1616. }
  1617. client.Logout()
  1618. go client.nickTimer.Touch(nil)
  1619. // dispatch account-notify
  1620. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1621. go func() {
  1622. for friend := range client.Friends(caps.AccountNotify) {
  1623. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1624. }
  1625. }()
  1626. }