Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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