Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

database.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "log"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/oragono/oragono/irc/modes"
  13. "github.com/oragono/oragono/irc/utils"
  14. "github.com/tidwall/buntdb"
  15. )
  16. const (
  17. // 'version' of the database schema
  18. keySchemaVersion = "db.version"
  19. // latest schema of the db
  20. latestDbSchema = "4"
  21. )
  22. type SchemaChanger func(*Config, *buntdb.Tx) error
  23. type SchemaChange struct {
  24. InitialVersion string // the change will take this version
  25. TargetVersion string // and transform it into this version
  26. Changer SchemaChanger
  27. }
  28. // maps an initial version to a schema change capable of upgrading it
  29. var schemaChanges map[string]SchemaChange
  30. type incompatibleSchemaError struct {
  31. currentVersion string
  32. requiredVersion string
  33. }
  34. func IncompatibleSchemaError(currentVersion string) (result *incompatibleSchemaError) {
  35. return &incompatibleSchemaError{
  36. currentVersion: currentVersion,
  37. requiredVersion: latestDbSchema,
  38. }
  39. }
  40. func (err *incompatibleSchemaError) Error() string {
  41. return fmt.Sprintf("Database requires update. Expected schema v%s, got v%s", err.requiredVersion, err.currentVersion)
  42. }
  43. // InitDB creates the database, implementing the `oragono initdb` command.
  44. func InitDB(path string) {
  45. _, err := os.Stat(path)
  46. if err == nil {
  47. log.Fatal("Datastore already exists (delete it manually to continue): ", path)
  48. } else if !os.IsNotExist(err) {
  49. log.Fatal("Datastore path is inaccessible: ", err.Error())
  50. }
  51. err = initializeDB(path)
  52. if err != nil {
  53. log.Fatal("Could not save datastore: ", err.Error())
  54. }
  55. }
  56. // internal database initialization code
  57. func initializeDB(path string) error {
  58. store, err := buntdb.Open(path)
  59. if err != nil {
  60. return err
  61. }
  62. defer store.Close()
  63. err = store.Update(func(tx *buntdb.Tx) error {
  64. // set schema version
  65. tx.Set(keySchemaVersion, latestDbSchema, nil)
  66. return nil
  67. })
  68. return err
  69. }
  70. // OpenDatabase returns an existing database, performing a schema version check.
  71. func OpenDatabase(config *Config) (*buntdb.DB, error) {
  72. return openDatabaseInternal(config, config.Datastore.AutoUpgrade)
  73. }
  74. // open the database, giving it at most one chance to auto-upgrade the schema
  75. func openDatabaseInternal(config *Config, allowAutoupgrade bool) (db *buntdb.DB, err error) {
  76. db, err = buntdb.Open(config.Datastore.Path)
  77. if err != nil {
  78. return
  79. }
  80. defer func() {
  81. if err != nil && db != nil {
  82. db.Close()
  83. db = nil
  84. }
  85. }()
  86. // read the current version string
  87. var version string
  88. err = db.View(func(tx *buntdb.Tx) error {
  89. version, err = tx.Get(keySchemaVersion)
  90. return err
  91. })
  92. if err != nil {
  93. return
  94. }
  95. if version == latestDbSchema {
  96. // success
  97. return
  98. }
  99. // XXX quiesce the DB so we can be sure it's safe to make a backup copy
  100. db.Close()
  101. db = nil
  102. if allowAutoupgrade {
  103. err = performAutoUpgrade(version, config)
  104. if err != nil {
  105. return
  106. }
  107. // successful autoupgrade, let's try this again:
  108. return openDatabaseInternal(config, false)
  109. } else {
  110. err = IncompatibleSchemaError(version)
  111. return
  112. }
  113. }
  114. func performAutoUpgrade(currentVersion string, config *Config) (err error) {
  115. path := config.Datastore.Path
  116. log.Printf("attempting to auto-upgrade schema from version %s to %s\n", currentVersion, latestDbSchema)
  117. timestamp := time.Now().UTC().Format("2006-01-02-15:04:05.000Z")
  118. backupPath := fmt.Sprintf("%s.v%s.%s.bak", path, currentVersion, timestamp)
  119. log.Printf("making a backup of current database at %s\n", backupPath)
  120. err = utils.CopyFile(path, backupPath)
  121. if err != nil {
  122. return err
  123. }
  124. err = UpgradeDB(config)
  125. if err != nil {
  126. // database upgrade is a single transaction, so we don't need to restore the backup;
  127. // we can just delete it
  128. os.Remove(backupPath)
  129. }
  130. return err
  131. }
  132. // UpgradeDB upgrades the datastore to the latest schema.
  133. func UpgradeDB(config *Config) (err error) {
  134. store, err := buntdb.Open(config.Datastore.Path)
  135. if err != nil {
  136. return err
  137. }
  138. defer store.Close()
  139. var version string
  140. err = store.Update(func(tx *buntdb.Tx) error {
  141. for {
  142. version, _ = tx.Get(keySchemaVersion)
  143. change, schemaNeedsChange := schemaChanges[version]
  144. if !schemaNeedsChange {
  145. if version == latestDbSchema {
  146. // success!
  147. break
  148. }
  149. // unable to upgrade to the desired version, roll back
  150. return IncompatibleSchemaError(version)
  151. }
  152. log.Println("attempting to update schema from version " + version)
  153. err := change.Changer(config, tx)
  154. if err != nil {
  155. return err
  156. }
  157. _, _, err = tx.Set(keySchemaVersion, change.TargetVersion, nil)
  158. if err != nil {
  159. return err
  160. }
  161. log.Println("successfully updated schema to version " + change.TargetVersion)
  162. }
  163. return nil
  164. })
  165. if err != nil {
  166. log.Printf("database upgrade failed and was rolled back: %v\n", err)
  167. }
  168. return err
  169. }
  170. func schemaChangeV1toV2(config *Config, tx *buntdb.Tx) error {
  171. // == version 1 -> 2 ==
  172. // account key changes and account.verified key bugfix.
  173. var keysToRemove []string
  174. newKeys := make(map[string]string)
  175. tx.AscendKeys("account *", func(key, value string) bool {
  176. keysToRemove = append(keysToRemove, key)
  177. splitkey := strings.Split(key, " ")
  178. // work around bug
  179. if splitkey[2] == "exists" {
  180. // manually create new verified key
  181. newVerifiedKey := fmt.Sprintf("%s.verified %s", splitkey[0], splitkey[1])
  182. newKeys[newVerifiedKey] = "1"
  183. } else if splitkey[1] == "%s" {
  184. return true
  185. }
  186. newKey := fmt.Sprintf("%s.%s %s", splitkey[0], splitkey[2], splitkey[1])
  187. newKeys[newKey] = value
  188. return true
  189. })
  190. for _, key := range keysToRemove {
  191. tx.Delete(key)
  192. }
  193. for key, value := range newKeys {
  194. tx.Set(key, value, nil)
  195. }
  196. return nil
  197. }
  198. // 1. channel founder names should be casefolded
  199. // 2. founder should be explicitly granted the ChannelFounder user mode
  200. // 3. explicitly initialize stored channel modes to the server default values
  201. func schemaChangeV2ToV3(config *Config, tx *buntdb.Tx) error {
  202. var channels []string
  203. prefix := "channel.exists "
  204. tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  205. if !strings.HasPrefix(key, prefix) {
  206. return false
  207. }
  208. chname := strings.TrimPrefix(key, prefix)
  209. channels = append(channels, chname)
  210. return true
  211. })
  212. // founder names should be casefolded
  213. // founder should be explicitly granted the ChannelFounder user mode
  214. for _, channel := range channels {
  215. founderKey := "channel.founder " + channel
  216. founder, _ := tx.Get(founderKey)
  217. if founder != "" {
  218. founder, err := CasefoldName(founder)
  219. if err == nil {
  220. tx.Set(founderKey, founder, nil)
  221. accountToUmode := map[string]modes.Mode{
  222. founder: modes.ChannelFounder,
  223. }
  224. atustr, _ := json.Marshal(accountToUmode)
  225. tx.Set("channel.accounttoumode "+channel, string(atustr), nil)
  226. }
  227. }
  228. }
  229. // explicitly store the channel modes
  230. defaultModes := config.Channels.defaultModes
  231. modeStrings := make([]string, len(defaultModes))
  232. for i, mode := range defaultModes {
  233. modeStrings[i] = string(mode)
  234. }
  235. defaultModeString := strings.Join(modeStrings, "")
  236. for _, channel := range channels {
  237. tx.Set("channel.modes "+channel, defaultModeString, nil)
  238. }
  239. return nil
  240. }
  241. // 1. ban info format changed (from `legacyBanInfo` below to `IPBanInfo`)
  242. // 2. dlines against individual IPs are normalized into dlines against the appropriate /128 network
  243. func schemaChangeV3ToV4(config *Config, tx *buntdb.Tx) error {
  244. type ipRestrictTime struct {
  245. Duration time.Duration
  246. Expires time.Time
  247. }
  248. type legacyBanInfo struct {
  249. Reason string `json:"reason"`
  250. OperReason string `json:"oper_reason"`
  251. OperName string `json:"oper_name"`
  252. Time *ipRestrictTime `json:"time"`
  253. }
  254. now := time.Now()
  255. legacyToNewInfo := func(old legacyBanInfo) (new_ IPBanInfo) {
  256. new_.Reason = old.Reason
  257. new_.OperReason = old.OperReason
  258. new_.OperName = old.OperName
  259. if old.Time == nil {
  260. new_.TimeCreated = now
  261. new_.Duration = 0
  262. } else {
  263. new_.TimeCreated = old.Time.Expires.Add(-1 * old.Time.Duration)
  264. new_.Duration = old.Time.Duration
  265. }
  266. return
  267. }
  268. var keysToDelete []string
  269. prefix := "bans.dline "
  270. dlines := make(map[string]IPBanInfo)
  271. tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  272. if !strings.HasPrefix(key, prefix) {
  273. return false
  274. }
  275. keysToDelete = append(keysToDelete, key)
  276. var lbinfo legacyBanInfo
  277. id := strings.TrimPrefix(key, prefix)
  278. err := json.Unmarshal([]byte(value), &lbinfo)
  279. if err != nil {
  280. log.Printf("error unmarshaling legacy dline: %v\n", err)
  281. return true
  282. }
  283. // legacy keys can be either an IP or a CIDR
  284. hostNet, err := utils.NormalizedNetFromString(id)
  285. if err != nil {
  286. log.Printf("error unmarshaling legacy dline network: %v\n", err)
  287. return true
  288. }
  289. dlines[utils.NetToNormalizedString(hostNet)] = legacyToNewInfo(lbinfo)
  290. return true
  291. })
  292. setOptions := func(info IPBanInfo) *buntdb.SetOptions {
  293. if info.Duration == 0 {
  294. return nil
  295. }
  296. ttl := info.TimeCreated.Add(info.Duration).Sub(now)
  297. return &buntdb.SetOptions{Expires: true, TTL: ttl}
  298. }
  299. // store the new dlines
  300. for id, info := range dlines {
  301. b, err := json.Marshal(info)
  302. if err != nil {
  303. log.Printf("error marshaling migrated dline: %v\n", err)
  304. continue
  305. }
  306. tx.Set(fmt.Sprintf("bans.dlinev2 %s", id), string(b), setOptions(info))
  307. }
  308. // same operations against klines
  309. prefix = "bans.kline "
  310. klines := make(map[string]IPBanInfo)
  311. tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  312. if !strings.HasPrefix(key, prefix) {
  313. return false
  314. }
  315. keysToDelete = append(keysToDelete, key)
  316. mask := strings.TrimPrefix(key, prefix)
  317. var lbinfo legacyBanInfo
  318. err := json.Unmarshal([]byte(value), &lbinfo)
  319. if err != nil {
  320. log.Printf("error unmarshaling legacy kline: %v\n", err)
  321. return true
  322. }
  323. klines[mask] = legacyToNewInfo(lbinfo)
  324. return true
  325. })
  326. for mask, info := range klines {
  327. b, err := json.Marshal(info)
  328. if err != nil {
  329. log.Printf("error marshaling migrated kline: %v\n", err)
  330. continue
  331. }
  332. tx.Set(fmt.Sprintf("bans.klinev2 %s", mask), string(b), setOptions(info))
  333. }
  334. // clean up all the old entries
  335. for _, key := range keysToDelete {
  336. tx.Delete(key)
  337. }
  338. return nil
  339. }
  340. func init() {
  341. allChanges := []SchemaChange{
  342. {
  343. InitialVersion: "1",
  344. TargetVersion: "2",
  345. Changer: schemaChangeV1toV2,
  346. },
  347. {
  348. InitialVersion: "2",
  349. TargetVersion: "3",
  350. Changer: schemaChangeV2ToV3,
  351. },
  352. {
  353. InitialVersion: "3",
  354. TargetVersion: "4",
  355. Changer: schemaChangeV3ToV4,
  356. },
  357. }
  358. // build the index
  359. schemaChanges = make(map[string]SchemaChange)
  360. for _, change := range allChanges {
  361. schemaChanges[change.InitialVersion] = change
  362. }
  363. }