Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

accounts.go 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  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. // look up the unfolded version of an account name, possibly after deletion
  962. func (am *AccountManager) AccountToAccountName(account string) (result string) {
  963. casefoldedAccount, err := CasefoldName(account)
  964. if err != nil {
  965. return
  966. }
  967. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  968. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  969. am.server.store.View(func(tx *buntdb.Tx) error {
  970. if name, err := tx.Get(accountNameKey); err == nil {
  971. result = name
  972. return nil
  973. }
  974. if name, err := tx.Get(unregisteredKey); err == nil {
  975. result = name
  976. }
  977. return nil
  978. })
  979. return
  980. }
  981. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  982. result.Name = raw.Name
  983. result.NameCasefolded = cfName
  984. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  985. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  986. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  987. if e != nil {
  988. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  989. err = errAccountDoesNotExist
  990. return
  991. }
  992. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  993. result.Verified = raw.Verified
  994. if raw.VHost != "" {
  995. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  996. if e != nil {
  997. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  998. // pretend they have no vhost and move on
  999. }
  1000. }
  1001. if raw.Settings != "" {
  1002. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  1003. if e != nil {
  1004. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  1005. }
  1006. }
  1007. return
  1008. }
  1009. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  1010. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1011. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1012. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1013. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1014. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1015. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1016. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1017. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1018. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1019. _, e := tx.Get(accountKey)
  1020. if e == buntdb.ErrNotFound {
  1021. err = errAccountDoesNotExist
  1022. return
  1023. }
  1024. result.Name, _ = tx.Get(accountNameKey)
  1025. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  1026. result.Credentials, _ = tx.Get(credentialsKey)
  1027. result.Callback, _ = tx.Get(callbackKey)
  1028. result.AdditionalNicks, _ = tx.Get(nicksKey)
  1029. result.VHost, _ = tx.Get(vhostKey)
  1030. result.Settings, _ = tx.Get(settingsKey)
  1031. if _, e = tx.Get(verifiedKey); e == nil {
  1032. result.Verified = true
  1033. }
  1034. return
  1035. }
  1036. func (am *AccountManager) Unregister(account string, erase bool) error {
  1037. config := am.server.Config()
  1038. casefoldedAccount, err := CasefoldName(account)
  1039. if err != nil {
  1040. return errAccountDoesNotExist
  1041. }
  1042. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1043. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1044. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1045. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1046. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1047. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  1048. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1049. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1050. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1051. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1052. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  1053. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1054. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  1055. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1056. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1057. var clients []*Client
  1058. var registeredChannels []string
  1059. // on our way out, unregister all the account's channels and delete them from the db
  1060. defer func() {
  1061. for _, channelName := range registeredChannels {
  1062. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1063. if err != nil {
  1064. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1065. }
  1066. }
  1067. }()
  1068. var credText string
  1069. var rawNicks string
  1070. am.serialCacheUpdateMutex.Lock()
  1071. defer am.serialCacheUpdateMutex.Unlock()
  1072. var accountName string
  1073. var channelsStr string
  1074. keepProtections := false
  1075. am.server.store.Update(func(tx *buntdb.Tx) error {
  1076. // get the unfolded account name; for an active account, this is
  1077. // stored under accountNameKey, for an unregistered account under unregisteredKey
  1078. accountName, _ = tx.Get(accountNameKey)
  1079. if accountName == "" {
  1080. accountName, _ = tx.Get(unregisteredKey)
  1081. }
  1082. if erase {
  1083. tx.Delete(unregisteredKey)
  1084. } else {
  1085. if _, err := tx.Get(verifiedKey); err == nil {
  1086. tx.Set(unregisteredKey, accountName, nil)
  1087. keepProtections = true
  1088. }
  1089. }
  1090. tx.Delete(accountKey)
  1091. tx.Delete(accountNameKey)
  1092. tx.Delete(verifiedKey)
  1093. tx.Delete(registeredTimeKey)
  1094. tx.Delete(callbackKey)
  1095. tx.Delete(verificationCodeKey)
  1096. tx.Delete(settingsKey)
  1097. rawNicks, _ = tx.Get(nicksKey)
  1098. tx.Delete(nicksKey)
  1099. credText, err = tx.Get(credentialsKey)
  1100. tx.Delete(credentialsKey)
  1101. tx.Delete(vhostKey)
  1102. channelsStr, _ = tx.Get(channelsKey)
  1103. tx.Delete(channelsKey)
  1104. tx.Delete(joinedChannelsKey)
  1105. tx.Delete(lastSeenKey)
  1106. _, err := tx.Delete(vhostQueueKey)
  1107. am.decrementVHostQueueCount(casefoldedAccount, err)
  1108. return nil
  1109. })
  1110. if err == nil {
  1111. var creds AccountCredentials
  1112. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1113. for _, cert := range creds.Certfps {
  1114. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1115. am.server.store.Update(func(tx *buntdb.Tx) error {
  1116. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1117. tx.Delete(certFPKey)
  1118. }
  1119. return nil
  1120. })
  1121. }
  1122. }
  1123. }
  1124. skeleton, _ := Skeleton(accountName)
  1125. additionalNicks := unmarshalReservedNicks(rawNicks)
  1126. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1127. am.Lock()
  1128. defer am.Unlock()
  1129. clients = am.accountToClients[casefoldedAccount]
  1130. delete(am.accountToClients, casefoldedAccount)
  1131. // protect the account name itself where applicable, but not any grouped nicks
  1132. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1133. delete(am.nickToAccount, casefoldedAccount)
  1134. delete(am.skeletonToAccount, skeleton)
  1135. }
  1136. for _, nick := range additionalNicks {
  1137. delete(am.nickToAccount, nick)
  1138. additionalSkel, _ := Skeleton(nick)
  1139. delete(am.skeletonToAccount, additionalSkel)
  1140. }
  1141. for _, client := range clients {
  1142. if config.Accounts.RequireSasl.Enabled {
  1143. client.Logout()
  1144. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1145. // destroy acquires a semaphore so we can't call it while holding a lock
  1146. go client.destroy(nil)
  1147. } else {
  1148. am.logoutOfAccount(client)
  1149. }
  1150. }
  1151. if err != nil && !erase {
  1152. return errAccountDoesNotExist
  1153. }
  1154. return nil
  1155. }
  1156. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1157. if channelsStr != "" {
  1158. result = strings.Split(channelsStr, ",")
  1159. }
  1160. return
  1161. }
  1162. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1163. cfaccount, err := CasefoldName(account)
  1164. if err != nil {
  1165. return
  1166. }
  1167. var channelStr string
  1168. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1169. am.server.store.View(func(tx *buntdb.Tx) error {
  1170. channelStr, _ = tx.Get(key)
  1171. return nil
  1172. })
  1173. return unmarshalRegisteredChannels(channelStr)
  1174. }
  1175. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1176. if certfp == "" {
  1177. return errAccountInvalidCredentials
  1178. }
  1179. var account string
  1180. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1181. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1182. account, _ = tx.Get(certFPKey)
  1183. if account == "" {
  1184. return errAccountInvalidCredentials
  1185. }
  1186. return nil
  1187. })
  1188. if err != nil {
  1189. return err
  1190. }
  1191. if authzid != "" && authzid != account {
  1192. return errAuthzidAuthcidMismatch
  1193. }
  1194. // ok, we found an account corresponding to their certificate
  1195. clientAccount, err := am.LoadAccount(account)
  1196. if err != nil {
  1197. return err
  1198. } else if !clientAccount.Verified {
  1199. return errAccountUnverified
  1200. }
  1201. if client.registered {
  1202. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1203. return errNickAccountMismatch
  1204. }
  1205. }
  1206. am.Login(client, clientAccount)
  1207. return nil
  1208. }
  1209. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1210. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1211. casefoldedAccount, err := CasefoldName(account)
  1212. if err != nil {
  1213. return newSettings, errAccountDoesNotExist
  1214. }
  1215. // TODO implement this in general via a compare-and-swap API
  1216. accountData, err := am.LoadAccount(casefoldedAccount)
  1217. if err != nil {
  1218. return
  1219. } else if !accountData.Verified {
  1220. return newSettings, errAccountUnverified
  1221. }
  1222. newSettings, err = munger(accountData.Settings)
  1223. if err != nil {
  1224. return
  1225. }
  1226. text, err := json.Marshal(newSettings)
  1227. if err != nil {
  1228. return
  1229. }
  1230. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1231. serializedValue := string(text)
  1232. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1233. _, _, err = tx.Set(key, serializedValue, nil)
  1234. return
  1235. })
  1236. if err != nil {
  1237. err = errAccountUpdateFailed
  1238. return
  1239. }
  1240. // success, push new settings into the client objects
  1241. am.Lock()
  1242. defer am.Unlock()
  1243. for _, client := range am.accountToClients[casefoldedAccount] {
  1244. client.SetAccountSettings(newSettings)
  1245. }
  1246. return
  1247. }
  1248. // represents someone's status in hostserv
  1249. type VHostInfo struct {
  1250. ApprovedVHost string
  1251. Enabled bool
  1252. Forbidden bool
  1253. RequestedVHost string
  1254. RejectedVHost string
  1255. RejectionReason string
  1256. LastRequestTime time.Time
  1257. }
  1258. // pair type, <VHostInfo, accountName>
  1259. type PendingVHostRequest struct {
  1260. VHostInfo
  1261. Account string
  1262. }
  1263. type vhostThrottleExceeded struct {
  1264. timeRemaining time.Duration
  1265. }
  1266. func (vhe *vhostThrottleExceeded) Error() string {
  1267. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1268. }
  1269. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1270. if cooldown == 0 {
  1271. return nil
  1272. }
  1273. now := time.Now().UTC()
  1274. elapsed := now.Sub(vh.LastRequestTime)
  1275. if elapsed > cooldown {
  1276. // success
  1277. vh.LastRequestTime = now
  1278. return nil
  1279. } else {
  1280. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1281. }
  1282. }
  1283. // callback type implementing the actual business logic of vhost operations
  1284. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1285. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1286. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1287. output = input
  1288. output.Enabled = true
  1289. output.ApprovedVHost = vhost
  1290. return
  1291. }
  1292. return am.performVHostChange(account, munger)
  1293. }
  1294. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1295. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1296. output = input
  1297. if input.Forbidden {
  1298. err = errVhostsForbidden
  1299. return
  1300. }
  1301. // you can update your existing request, but if you were approved or rejected,
  1302. // you can't spam a new request
  1303. if output.RequestedVHost == "" {
  1304. err = output.checkThrottle(cooldown)
  1305. }
  1306. if err != nil {
  1307. return
  1308. }
  1309. output.RequestedVHost = vhost
  1310. output.RejectedVHost = ""
  1311. output.RejectionReason = ""
  1312. output.LastRequestTime = time.Now().UTC()
  1313. return
  1314. }
  1315. return am.performVHostChange(account, munger)
  1316. }
  1317. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1318. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1319. output = input
  1320. if input.Forbidden {
  1321. err = errVhostsForbidden
  1322. return
  1323. }
  1324. // if you have a request pending, you can cancel it using take;
  1325. // otherwise, you're subject to the same throttling as if you were making a request
  1326. if output.RequestedVHost == "" {
  1327. err = output.checkThrottle(cooldown)
  1328. }
  1329. if err != nil {
  1330. return
  1331. }
  1332. output.ApprovedVHost = vhost
  1333. output.RequestedVHost = ""
  1334. output.RejectedVHost = ""
  1335. output.RejectionReason = ""
  1336. output.LastRequestTime = time.Now().UTC()
  1337. return
  1338. }
  1339. return am.performVHostChange(account, munger)
  1340. }
  1341. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1342. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1343. output = input
  1344. output.Enabled = true
  1345. output.ApprovedVHost = input.RequestedVHost
  1346. output.RequestedVHost = ""
  1347. output.RejectionReason = ""
  1348. return
  1349. }
  1350. return am.performVHostChange(account, munger)
  1351. }
  1352. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1353. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1354. output = input
  1355. output.RejectedVHost = output.RequestedVHost
  1356. output.RequestedVHost = ""
  1357. output.RejectionReason = reason
  1358. return
  1359. }
  1360. return am.performVHostChange(account, munger)
  1361. }
  1362. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1363. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1364. if input.ApprovedVHost == "" {
  1365. err = errNoVhost
  1366. return
  1367. }
  1368. output = input
  1369. output.Enabled = enabled
  1370. return
  1371. }
  1372. return am.performVHostChange(client.Account(), munger)
  1373. }
  1374. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1375. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1376. output = input
  1377. output.Forbidden = forbid
  1378. return
  1379. }
  1380. return am.performVHostChange(account, munger)
  1381. }
  1382. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1383. account, err = CasefoldName(account)
  1384. if err != nil || account == "" {
  1385. err = errAccountDoesNotExist
  1386. return
  1387. }
  1388. am.vHostUpdateMutex.Lock()
  1389. defer am.vHostUpdateMutex.Unlock()
  1390. clientAccount, err := am.LoadAccount(account)
  1391. if err != nil {
  1392. err = errAccountDoesNotExist
  1393. return
  1394. } else if !clientAccount.Verified {
  1395. err = errAccountUnverified
  1396. return
  1397. }
  1398. result, err = munger(clientAccount.VHost)
  1399. if err != nil {
  1400. return
  1401. }
  1402. vhtext, err := json.Marshal(result)
  1403. if err != nil {
  1404. err = errAccountUpdateFailed
  1405. return
  1406. }
  1407. vhstr := string(vhtext)
  1408. key := fmt.Sprintf(keyAccountVHost, account)
  1409. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1410. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1411. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1412. return err
  1413. }
  1414. // update request queue
  1415. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1416. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1417. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1418. return err
  1419. }
  1420. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1421. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1422. _, err = tx.Delete(queueKey)
  1423. am.decrementVHostQueueCount(account, err)
  1424. }
  1425. return nil
  1426. })
  1427. if err != nil {
  1428. err = errAccountUpdateFailed
  1429. return
  1430. }
  1431. am.applyVhostToClients(account, result)
  1432. return result, nil
  1433. }
  1434. // XXX annoying helper method for keeping the queue count in sync with the DB
  1435. // `err` is the buntdb error returned from deleting the queue key
  1436. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1437. if err == nil {
  1438. // successfully deleted a queue entry, do a 2's complement decrement:
  1439. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1440. } else if err != buntdb.ErrNotFound {
  1441. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1442. }
  1443. }
  1444. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1445. am.vHostUpdateMutex.Lock()
  1446. defer am.vHostUpdateMutex.Unlock()
  1447. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1448. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1449. accounts := make([]string, 0, limit)
  1450. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1451. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1452. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1453. return len(accounts) < limit
  1454. })
  1455. })
  1456. if err != nil {
  1457. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1458. return
  1459. }
  1460. for _, account := range accounts {
  1461. accountInfo, err := am.LoadAccount(account)
  1462. if err == nil {
  1463. requests = append(requests, PendingVHostRequest{
  1464. Account: account,
  1465. VHostInfo: accountInfo.VHost,
  1466. })
  1467. } else {
  1468. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1469. }
  1470. }
  1471. return
  1472. }
  1473. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1474. // if hostserv is disabled in config, then don't grant vhosts
  1475. // that were previously approved while it was enabled
  1476. if !am.server.Config().Accounts.VHosts.Enabled {
  1477. return
  1478. }
  1479. vhost := ""
  1480. if info.Enabled && !info.Forbidden {
  1481. vhost = info.ApprovedVHost
  1482. }
  1483. oldNickmask := client.NickMaskString()
  1484. updated := client.SetVHost(vhost)
  1485. if updated {
  1486. // TODO: doing I/O here is kind of a kludge
  1487. go client.sendChghost(oldNickmask, client.Hostname())
  1488. }
  1489. }
  1490. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1491. am.RLock()
  1492. clients := am.accountToClients[account]
  1493. am.RUnlock()
  1494. for _, client := range clients {
  1495. am.applyVHostInfo(client, result)
  1496. }
  1497. }
  1498. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1499. client.Login(account)
  1500. client.nickTimer.Touch(nil)
  1501. am.applyVHostInfo(client, account.VHost)
  1502. casefoldedAccount := client.Account()
  1503. am.Lock()
  1504. defer am.Unlock()
  1505. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1506. }
  1507. func (am *AccountManager) Logout(client *Client) {
  1508. am.Lock()
  1509. defer am.Unlock()
  1510. casefoldedAccount := client.Account()
  1511. if casefoldedAccount == "" {
  1512. return
  1513. }
  1514. am.logoutOfAccount(client)
  1515. clients := am.accountToClients[casefoldedAccount]
  1516. if len(clients) <= 1 {
  1517. delete(am.accountToClients, casefoldedAccount)
  1518. return
  1519. }
  1520. remainingClients := make([]*Client, len(clients)-1)
  1521. remainingPos := 0
  1522. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1523. if clients[currentPos] != client {
  1524. remainingClients[remainingPos] = clients[currentPos]
  1525. remainingPos++
  1526. }
  1527. }
  1528. am.accountToClients[casefoldedAccount] = remainingClients
  1529. }
  1530. var (
  1531. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1532. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1533. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1534. "PLAIN": authPlainHandler,
  1535. "EXTERNAL": authExternalHandler,
  1536. }
  1537. )
  1538. // AccountCredentials stores the various methods for verifying accounts.
  1539. type AccountCredentials struct {
  1540. Version uint
  1541. PassphraseSalt []byte // legacy field, not used by v1 and later
  1542. PassphraseHash []byte
  1543. Certfps []string
  1544. }
  1545. func (ac *AccountCredentials) Empty() bool {
  1546. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1547. }
  1548. // helper to assemble the serialized JSON for an account's credentials
  1549. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1550. ac.Version = 1
  1551. credText, err := json.Marshal(*ac)
  1552. if err != nil {
  1553. return "", err
  1554. }
  1555. return string(credText), nil
  1556. }
  1557. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1558. if passphrase == "" {
  1559. ac.PassphraseHash = nil
  1560. return nil
  1561. }
  1562. if validatePassphrase(passphrase) != nil {
  1563. return errAccountBadPassphrase
  1564. }
  1565. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1566. if err != nil {
  1567. return errAccountBadPassphrase
  1568. }
  1569. return nil
  1570. }
  1571. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1572. // XXX we require that certfp is already normalized (rather than normalize here
  1573. // and pass back the normalized version as an additional return parameter);
  1574. // this is just a final sanity check:
  1575. if len(certfp) != 64 {
  1576. return utils.ErrInvalidCertfp
  1577. }
  1578. for _, current := range ac.Certfps {
  1579. if certfp == current {
  1580. return errNoop
  1581. }
  1582. }
  1583. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1584. return errLimitExceeded
  1585. }
  1586. ac.Certfps = append(ac.Certfps, certfp)
  1587. return nil
  1588. }
  1589. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1590. found := false
  1591. newList := make([]string, 0, len(ac.Certfps))
  1592. for _, current := range ac.Certfps {
  1593. if current == certfp {
  1594. found = true
  1595. } else {
  1596. newList = append(newList, current)
  1597. }
  1598. }
  1599. if !found {
  1600. // this is important because it prevents you from deleting someone else's
  1601. // fingerprint record
  1602. return errNoop
  1603. }
  1604. ac.Certfps = newList
  1605. return nil
  1606. }
  1607. type MulticlientAllowedSetting int
  1608. const (
  1609. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1610. MulticlientDisallowedByUser
  1611. MulticlientAllowedByUser
  1612. )
  1613. // controls whether/when clients without event-playback support see fake
  1614. // PRIVMSGs for JOINs
  1615. type ReplayJoinsSetting uint
  1616. const (
  1617. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1618. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1619. ReplayJoinsNever // never replay
  1620. )
  1621. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1622. switch strings.ToLower(str) {
  1623. case "commands-only":
  1624. result = ReplayJoinsCommandsOnly
  1625. case "always":
  1626. result = ReplayJoinsAlways
  1627. case "never":
  1628. result = ReplayJoinsNever
  1629. default:
  1630. err = errInvalidParams
  1631. }
  1632. return
  1633. }
  1634. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1635. // persistent JSON blobs in the database
  1636. type AccountSettings struct {
  1637. AutoreplayLines *int
  1638. NickEnforcement NickEnforcementMethod
  1639. AllowBouncer MulticlientAllowedSetting
  1640. ReplayJoins ReplayJoinsSetting
  1641. AlwaysOn PersistentStatus
  1642. AutoreplayMissed bool
  1643. DMHistory HistoryStatus
  1644. }
  1645. // ClientAccount represents a user account.
  1646. type ClientAccount struct {
  1647. // Name of the account.
  1648. Name string
  1649. NameCasefolded string
  1650. RegisteredAt time.Time
  1651. Credentials AccountCredentials
  1652. Verified bool
  1653. AdditionalNicks []string
  1654. VHost VHostInfo
  1655. Settings AccountSettings
  1656. }
  1657. // convenience for passing around raw serialized account data
  1658. type rawClientAccount struct {
  1659. Name string
  1660. RegisteredAt string
  1661. Credentials string
  1662. Callback string
  1663. Verified bool
  1664. AdditionalNicks string
  1665. VHost string
  1666. Settings string
  1667. }
  1668. // logoutOfAccount logs the client out of their current account.
  1669. func (am *AccountManager) logoutOfAccount(client *Client) {
  1670. if client.Account() == "" {
  1671. // already logged out
  1672. return
  1673. }
  1674. client.Logout()
  1675. go client.nickTimer.Touch(nil)
  1676. // dispatch account-notify
  1677. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1678. go func() {
  1679. for friend := range client.Friends(caps.AccountNotify) {
  1680. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1681. }
  1682. }()
  1683. }