You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

accounts.go 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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. client.Logout()
  1143. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1144. // destroy acquires a semaphore so we can't call it while holding a lock
  1145. go client.destroy(nil)
  1146. }
  1147. if err != nil && !erase {
  1148. return errAccountDoesNotExist
  1149. }
  1150. return nil
  1151. }
  1152. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1153. if channelsStr != "" {
  1154. result = strings.Split(channelsStr, ",")
  1155. }
  1156. return
  1157. }
  1158. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1159. cfaccount, err := CasefoldName(account)
  1160. if err != nil {
  1161. return
  1162. }
  1163. var channelStr string
  1164. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1165. am.server.store.View(func(tx *buntdb.Tx) error {
  1166. channelStr, _ = tx.Get(key)
  1167. return nil
  1168. })
  1169. return unmarshalRegisteredChannels(channelStr)
  1170. }
  1171. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1172. if certfp == "" {
  1173. return errAccountInvalidCredentials
  1174. }
  1175. var account string
  1176. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1177. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1178. account, _ = tx.Get(certFPKey)
  1179. if account == "" {
  1180. return errAccountInvalidCredentials
  1181. }
  1182. return nil
  1183. })
  1184. if err != nil {
  1185. return err
  1186. }
  1187. if authzid != "" && authzid != account {
  1188. return errAuthzidAuthcidMismatch
  1189. }
  1190. // ok, we found an account corresponding to their certificate
  1191. clientAccount, err := am.LoadAccount(account)
  1192. if err != nil {
  1193. return err
  1194. } else if !clientAccount.Verified {
  1195. return errAccountUnverified
  1196. }
  1197. if client.registered {
  1198. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1199. return errNickAccountMismatch
  1200. }
  1201. }
  1202. am.Login(client, clientAccount)
  1203. return nil
  1204. }
  1205. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1206. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1207. casefoldedAccount, err := CasefoldName(account)
  1208. if err != nil {
  1209. return newSettings, errAccountDoesNotExist
  1210. }
  1211. // TODO implement this in general via a compare-and-swap API
  1212. accountData, err := am.LoadAccount(casefoldedAccount)
  1213. if err != nil {
  1214. return
  1215. } else if !accountData.Verified {
  1216. return newSettings, errAccountUnverified
  1217. }
  1218. newSettings, err = munger(accountData.Settings)
  1219. if err != nil {
  1220. return
  1221. }
  1222. text, err := json.Marshal(newSettings)
  1223. if err != nil {
  1224. return
  1225. }
  1226. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1227. serializedValue := string(text)
  1228. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1229. _, _, err = tx.Set(key, serializedValue, nil)
  1230. return
  1231. })
  1232. if err != nil {
  1233. err = errAccountUpdateFailed
  1234. return
  1235. }
  1236. // success, push new settings into the client objects
  1237. am.Lock()
  1238. defer am.Unlock()
  1239. for _, client := range am.accountToClients[casefoldedAccount] {
  1240. client.SetAccountSettings(newSettings)
  1241. }
  1242. return
  1243. }
  1244. // represents someone's status in hostserv
  1245. type VHostInfo struct {
  1246. ApprovedVHost string
  1247. Enabled bool
  1248. Forbidden bool
  1249. RequestedVHost string
  1250. RejectedVHost string
  1251. RejectionReason string
  1252. LastRequestTime time.Time
  1253. }
  1254. // pair type, <VHostInfo, accountName>
  1255. type PendingVHostRequest struct {
  1256. VHostInfo
  1257. Account string
  1258. }
  1259. type vhostThrottleExceeded struct {
  1260. timeRemaining time.Duration
  1261. }
  1262. func (vhe *vhostThrottleExceeded) Error() string {
  1263. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1264. }
  1265. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1266. if cooldown == 0 {
  1267. return nil
  1268. }
  1269. now := time.Now().UTC()
  1270. elapsed := now.Sub(vh.LastRequestTime)
  1271. if elapsed > cooldown {
  1272. // success
  1273. vh.LastRequestTime = now
  1274. return nil
  1275. } else {
  1276. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1277. }
  1278. }
  1279. // callback type implementing the actual business logic of vhost operations
  1280. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1281. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1282. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1283. output = input
  1284. output.Enabled = true
  1285. output.ApprovedVHost = vhost
  1286. return
  1287. }
  1288. return am.performVHostChange(account, munger)
  1289. }
  1290. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1291. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1292. output = input
  1293. if input.Forbidden {
  1294. err = errVhostsForbidden
  1295. return
  1296. }
  1297. // you can update your existing request, but if you were approved or rejected,
  1298. // you can't spam a new request
  1299. if output.RequestedVHost == "" {
  1300. err = output.checkThrottle(cooldown)
  1301. }
  1302. if err != nil {
  1303. return
  1304. }
  1305. output.RequestedVHost = vhost
  1306. output.RejectedVHost = ""
  1307. output.RejectionReason = ""
  1308. output.LastRequestTime = time.Now().UTC()
  1309. return
  1310. }
  1311. return am.performVHostChange(account, munger)
  1312. }
  1313. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1314. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1315. output = input
  1316. if input.Forbidden {
  1317. err = errVhostsForbidden
  1318. return
  1319. }
  1320. // if you have a request pending, you can cancel it using take;
  1321. // otherwise, you're subject to the same throttling as if you were making a request
  1322. if output.RequestedVHost == "" {
  1323. err = output.checkThrottle(cooldown)
  1324. }
  1325. if err != nil {
  1326. return
  1327. }
  1328. output.ApprovedVHost = vhost
  1329. output.RequestedVHost = ""
  1330. output.RejectedVHost = ""
  1331. output.RejectionReason = ""
  1332. output.LastRequestTime = time.Now().UTC()
  1333. return
  1334. }
  1335. return am.performVHostChange(account, munger)
  1336. }
  1337. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1338. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1339. output = input
  1340. output.Enabled = true
  1341. output.ApprovedVHost = input.RequestedVHost
  1342. output.RequestedVHost = ""
  1343. output.RejectionReason = ""
  1344. return
  1345. }
  1346. return am.performVHostChange(account, munger)
  1347. }
  1348. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1349. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1350. output = input
  1351. output.RejectedVHost = output.RequestedVHost
  1352. output.RequestedVHost = ""
  1353. output.RejectionReason = reason
  1354. return
  1355. }
  1356. return am.performVHostChange(account, munger)
  1357. }
  1358. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1359. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1360. if input.ApprovedVHost == "" {
  1361. err = errNoVhost
  1362. return
  1363. }
  1364. output = input
  1365. output.Enabled = enabled
  1366. return
  1367. }
  1368. return am.performVHostChange(client.Account(), munger)
  1369. }
  1370. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1371. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1372. output = input
  1373. output.Forbidden = forbid
  1374. return
  1375. }
  1376. return am.performVHostChange(account, munger)
  1377. }
  1378. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1379. account, err = CasefoldName(account)
  1380. if err != nil || account == "" {
  1381. err = errAccountDoesNotExist
  1382. return
  1383. }
  1384. am.vHostUpdateMutex.Lock()
  1385. defer am.vHostUpdateMutex.Unlock()
  1386. clientAccount, err := am.LoadAccount(account)
  1387. if err != nil {
  1388. err = errAccountDoesNotExist
  1389. return
  1390. } else if !clientAccount.Verified {
  1391. err = errAccountUnverified
  1392. return
  1393. }
  1394. result, err = munger(clientAccount.VHost)
  1395. if err != nil {
  1396. return
  1397. }
  1398. vhtext, err := json.Marshal(result)
  1399. if err != nil {
  1400. err = errAccountUpdateFailed
  1401. return
  1402. }
  1403. vhstr := string(vhtext)
  1404. key := fmt.Sprintf(keyAccountVHost, account)
  1405. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1406. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1407. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1408. return err
  1409. }
  1410. // update request queue
  1411. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1412. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1413. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1414. return err
  1415. }
  1416. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1417. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1418. _, err = tx.Delete(queueKey)
  1419. am.decrementVHostQueueCount(account, err)
  1420. }
  1421. return nil
  1422. })
  1423. if err != nil {
  1424. err = errAccountUpdateFailed
  1425. return
  1426. }
  1427. am.applyVhostToClients(account, result)
  1428. return result, nil
  1429. }
  1430. // XXX annoying helper method for keeping the queue count in sync with the DB
  1431. // `err` is the buntdb error returned from deleting the queue key
  1432. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1433. if err == nil {
  1434. // successfully deleted a queue entry, do a 2's complement decrement:
  1435. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1436. } else if err != buntdb.ErrNotFound {
  1437. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1438. }
  1439. }
  1440. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1441. am.vHostUpdateMutex.Lock()
  1442. defer am.vHostUpdateMutex.Unlock()
  1443. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1444. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1445. accounts := make([]string, 0, limit)
  1446. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1447. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1448. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1449. return len(accounts) < limit
  1450. })
  1451. })
  1452. if err != nil {
  1453. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1454. return
  1455. }
  1456. for _, account := range accounts {
  1457. accountInfo, err := am.LoadAccount(account)
  1458. if err == nil {
  1459. requests = append(requests, PendingVHostRequest{
  1460. Account: account,
  1461. VHostInfo: accountInfo.VHost,
  1462. })
  1463. } else {
  1464. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1465. }
  1466. }
  1467. return
  1468. }
  1469. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1470. // if hostserv is disabled in config, then don't grant vhosts
  1471. // that were previously approved while it was enabled
  1472. if !am.server.Config().Accounts.VHosts.Enabled {
  1473. return
  1474. }
  1475. vhost := ""
  1476. if info.Enabled && !info.Forbidden {
  1477. vhost = info.ApprovedVHost
  1478. }
  1479. oldNickmask := client.NickMaskString()
  1480. updated := client.SetVHost(vhost)
  1481. if updated {
  1482. // TODO: doing I/O here is kind of a kludge
  1483. go client.sendChghost(oldNickmask, client.Hostname())
  1484. }
  1485. }
  1486. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1487. am.RLock()
  1488. clients := am.accountToClients[account]
  1489. am.RUnlock()
  1490. for _, client := range clients {
  1491. am.applyVHostInfo(client, result)
  1492. }
  1493. }
  1494. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1495. client.Login(account)
  1496. client.nickTimer.Touch(nil)
  1497. am.applyVHostInfo(client, account.VHost)
  1498. casefoldedAccount := client.Account()
  1499. am.Lock()
  1500. defer am.Unlock()
  1501. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1502. }
  1503. func (am *AccountManager) Logout(client *Client) {
  1504. am.Lock()
  1505. defer am.Unlock()
  1506. casefoldedAccount := client.Account()
  1507. if casefoldedAccount == "" {
  1508. return
  1509. }
  1510. am.logoutOfAccount(client)
  1511. clients := am.accountToClients[casefoldedAccount]
  1512. if len(clients) <= 1 {
  1513. delete(am.accountToClients, casefoldedAccount)
  1514. return
  1515. }
  1516. remainingClients := make([]*Client, len(clients)-1)
  1517. remainingPos := 0
  1518. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1519. if clients[currentPos] != client {
  1520. remainingClients[remainingPos] = clients[currentPos]
  1521. remainingPos++
  1522. }
  1523. }
  1524. am.accountToClients[casefoldedAccount] = remainingClients
  1525. }
  1526. var (
  1527. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1528. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1529. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1530. "PLAIN": authPlainHandler,
  1531. "EXTERNAL": authExternalHandler,
  1532. }
  1533. )
  1534. // AccountCredentials stores the various methods for verifying accounts.
  1535. type AccountCredentials struct {
  1536. Version uint
  1537. PassphraseSalt []byte // legacy field, not used by v1 and later
  1538. PassphraseHash []byte
  1539. Certfps []string
  1540. }
  1541. func (ac *AccountCredentials) Empty() bool {
  1542. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1543. }
  1544. // helper to assemble the serialized JSON for an account's credentials
  1545. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1546. ac.Version = 1
  1547. credText, err := json.Marshal(*ac)
  1548. if err != nil {
  1549. return "", err
  1550. }
  1551. return string(credText), nil
  1552. }
  1553. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1554. if passphrase == "" {
  1555. ac.PassphraseHash = nil
  1556. return nil
  1557. }
  1558. if validatePassphrase(passphrase) != nil {
  1559. return errAccountBadPassphrase
  1560. }
  1561. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1562. if err != nil {
  1563. return errAccountBadPassphrase
  1564. }
  1565. return nil
  1566. }
  1567. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1568. // XXX we require that certfp is already normalized (rather than normalize here
  1569. // and pass back the normalized version as an additional return parameter);
  1570. // this is just a final sanity check:
  1571. if len(certfp) != 64 {
  1572. return utils.ErrInvalidCertfp
  1573. }
  1574. for _, current := range ac.Certfps {
  1575. if certfp == current {
  1576. return errNoop
  1577. }
  1578. }
  1579. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1580. return errLimitExceeded
  1581. }
  1582. ac.Certfps = append(ac.Certfps, certfp)
  1583. return nil
  1584. }
  1585. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1586. found := false
  1587. newList := make([]string, 0, len(ac.Certfps))
  1588. for _, current := range ac.Certfps {
  1589. if current == certfp {
  1590. found = true
  1591. } else {
  1592. newList = append(newList, current)
  1593. }
  1594. }
  1595. if !found {
  1596. // this is important because it prevents you from deleting someone else's
  1597. // fingerprint record
  1598. return errNoop
  1599. }
  1600. ac.Certfps = newList
  1601. return nil
  1602. }
  1603. type MulticlientAllowedSetting int
  1604. const (
  1605. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1606. MulticlientDisallowedByUser
  1607. MulticlientAllowedByUser
  1608. )
  1609. // controls whether/when clients without event-playback support see fake
  1610. // PRIVMSGs for JOINs
  1611. type ReplayJoinsSetting uint
  1612. const (
  1613. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1614. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1615. ReplayJoinsNever // never replay
  1616. )
  1617. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1618. switch strings.ToLower(str) {
  1619. case "commands-only":
  1620. result = ReplayJoinsCommandsOnly
  1621. case "always":
  1622. result = ReplayJoinsAlways
  1623. case "never":
  1624. result = ReplayJoinsNever
  1625. default:
  1626. err = errInvalidParams
  1627. }
  1628. return
  1629. }
  1630. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1631. // persistent JSON blobs in the database
  1632. type AccountSettings struct {
  1633. AutoreplayLines *int
  1634. NickEnforcement NickEnforcementMethod
  1635. AllowBouncer MulticlientAllowedSetting
  1636. ReplayJoins ReplayJoinsSetting
  1637. AlwaysOn PersistentStatus
  1638. AutoreplayMissed bool
  1639. DMHistory HistoryStatus
  1640. AutoAway PersistentStatus
  1641. }
  1642. // ClientAccount represents a user account.
  1643. type ClientAccount struct {
  1644. // Name of the account.
  1645. Name string
  1646. NameCasefolded string
  1647. RegisteredAt time.Time
  1648. Credentials AccountCredentials
  1649. Verified bool
  1650. AdditionalNicks []string
  1651. VHost VHostInfo
  1652. Settings AccountSettings
  1653. }
  1654. // convenience for passing around raw serialized account data
  1655. type rawClientAccount struct {
  1656. Name string
  1657. RegisteredAt string
  1658. Credentials string
  1659. Callback string
  1660. Verified bool
  1661. AdditionalNicks string
  1662. VHost string
  1663. Settings string
  1664. }
  1665. // logoutOfAccount logs the client out of their current account.
  1666. func (am *AccountManager) logoutOfAccount(client *Client) {
  1667. if client.Account() == "" {
  1668. // already logged out
  1669. return
  1670. }
  1671. client.Logout()
  1672. go client.nickTimer.Touch(nil)
  1673. // dispatch account-notify
  1674. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1675. go func() {
  1676. for friend := range client.Friends(caps.AccountNotify) {
  1677. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1678. }
  1679. }()
  1680. }