db.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package db
  26. import (
  27. "context"
  28. "crypto/sha1"
  29. "encoding/hex"
  30. "errors"
  31. "fmt"
  32. "log"
  33. "strings"
  34. "time"
  35. common "git.semlanik.org/semlanik/gostfix/common"
  36. "git.semlanik.org/semlanik/gostfix/utils"
  37. "github.com/semlanik/berkeleydb"
  38. bcrypt "golang.org/x/crypto/bcrypt"
  39. bson "go.mongodb.org/mongo-driver/bson"
  40. "go.mongodb.org/mongo-driver/bson/primitive"
  41. mongo "go.mongodb.org/mongo-driver/mongo"
  42. options "go.mongodb.org/mongo-driver/mongo/options"
  43. config "git.semlanik.org/semlanik/gostfix/config"
  44. )
  45. type Storage struct {
  46. db *mongo.Database
  47. usersCollection *mongo.Collection
  48. tokensCollection *mongo.Collection
  49. emailsCollection *mongo.Collection
  50. allEmailsCollection *mongo.Collection
  51. }
  52. func qualifiedMailCollection(user string) string {
  53. sum := sha1.Sum([]byte(user))
  54. return "mb" + hex.EncodeToString(sum[:])
  55. }
  56. func NewStorage() (s *Storage, err error) {
  57. fullUrl := "mongodb://"
  58. if config.ConfigInstance().MongoUser != "" {
  59. fullUrl += config.ConfigInstance().MongoUser
  60. if config.ConfigInstance().MongoPassword != "" {
  61. fullUrl += ":" + config.ConfigInstance().MongoPassword
  62. }
  63. fullUrl += "@"
  64. }
  65. fullUrl += config.ConfigInstance().MongoAddress
  66. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  67. if err != nil {
  68. return nil, err
  69. }
  70. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  71. defer cancel()
  72. err = client.Connect(ctx)
  73. if err != nil {
  74. return nil, err
  75. }
  76. db := client.Database("gostfix")
  77. index := mongo.IndexModel{
  78. Keys: bson.M{
  79. "user": 1,
  80. },
  81. Options: options.Index().SetUnique(true),
  82. }
  83. s = &Storage{
  84. db: db,
  85. usersCollection: db.Collection("users"),
  86. tokensCollection: db.Collection("tokens"),
  87. emailsCollection: db.Collection("emails"),
  88. allEmailsCollection: db.Collection("allEmails"),
  89. }
  90. //Initial database setup
  91. s.usersCollection.Indexes().CreateOne(context.Background(), index)
  92. s.tokensCollection.Indexes().CreateOne(context.Background(), index)
  93. s.emailsCollection.Indexes().CreateOne(context.Background(), index)
  94. return
  95. }
  96. func (s *Storage) AddUser(user, password, fullName string) error {
  97. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  98. if err != nil {
  99. return err
  100. }
  101. hashString := string(hash)
  102. userInfo := bson.M{
  103. "user": user,
  104. "password": hashString,
  105. "fullName": fullName,
  106. }
  107. _, err = s.usersCollection.InsertOne(context.Background(), userInfo)
  108. if err != nil {
  109. return err
  110. }
  111. err = s.addEmail(user, user, true)
  112. if err != nil {
  113. s.usersCollection.DeleteOne(context.Background(), bson.M{"user": user})
  114. return err
  115. }
  116. return nil
  117. }
  118. func (s *Storage) AddEmail(user string, email string) error {
  119. return s.addEmail(user, email, false)
  120. }
  121. func (s *Storage) addEmail(user string, email string, upsert bool) error {
  122. result := struct {
  123. User string
  124. }{}
  125. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  126. if err != nil {
  127. return err
  128. }
  129. emails, err := s.GetAllEmails()
  130. if err != nil {
  131. return err
  132. }
  133. for _, existingEmail := range emails {
  134. if existingEmail == email {
  135. return errors.New("Email exists")
  136. }
  137. }
  138. emailParts := strings.Split(email, "@")
  139. if len(emailParts) != 2 {
  140. return errors.New("Invalid email format")
  141. }
  142. db, err := berkeleydb.NewDB()
  143. if err != nil {
  144. log.Fatal(err)
  145. }
  146. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  147. if err != nil {
  148. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  149. }
  150. defer db.Close()
  151. err = db.Put(email, emailParts[1]+"/"+emailParts[0])
  152. if err != nil {
  153. return errors.New("Unable to add email to maps" + err.Error())
  154. }
  155. _, err = s.emailsCollection.UpdateOne(context.Background(),
  156. bson.M{"user": user},
  157. bson.M{"$addToSet": bson.M{"email": email}},
  158. options.Update().SetUpsert(upsert))
  159. return err
  160. }
  161. func (s *Storage) RemoveEmail(user string, email string) error {
  162. db, err := berkeleydb.NewDB()
  163. if err != nil {
  164. log.Fatal(err)
  165. }
  166. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  167. if err != nil {
  168. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  169. }
  170. defer db.Close()
  171. err = db.Delete(email)
  172. if err != nil {
  173. return errors.New("Unable to remove email from maps" + err.Error())
  174. }
  175. _, err = s.emailsCollection.UpdateOne(context.Background(),
  176. bson.M{"user": user},
  177. bson.M{"$pull": bson.M{"email": email}})
  178. return err
  179. }
  180. func (s *Storage) CheckUser(user, password string) error {
  181. log.Printf("Check user: %s %s", user, password)
  182. result := struct {
  183. User string
  184. Password string
  185. }{}
  186. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  187. if err != nil {
  188. return errors.New("Invalid user or password")
  189. }
  190. if bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(password)) != nil {
  191. return errors.New("Invalid user or password")
  192. }
  193. return nil
  194. }
  195. func (s *Storage) AddToken(user, token string) error {
  196. log.Printf("Add token: %s\n", user)
  197. s.tokensCollection.UpdateOne(context.Background(),
  198. bson.M{"user": user},
  199. bson.M{
  200. "$addToSet": bson.M{
  201. "token": bson.M{
  202. "token": token,
  203. "expire": time.Now().Add(time.Hour * 24).Unix(),
  204. },
  205. },
  206. },
  207. options.Update().SetUpsert(true))
  208. s.CleanupTokens(user)
  209. return nil
  210. }
  211. func (s *Storage) CheckToken(user, token string) error {
  212. if token == "" {
  213. return errors.New("Invalid token")
  214. }
  215. cur, err := s.tokensCollection.Aggregate(context.Background(),
  216. bson.A{
  217. bson.M{"$match": bson.M{"user": user}},
  218. bson.M{"$unwind": "$token"},
  219. bson.M{"$match": bson.M{"token.token": token}},
  220. })
  221. if err != nil {
  222. log.Fatalln(err)
  223. return err
  224. }
  225. ok := false
  226. defer cur.Close(context.Background())
  227. if cur.Next(context.Background()) {
  228. result := struct {
  229. Token struct {
  230. Expire int64
  231. }
  232. }{}
  233. err = cur.Decode(&result)
  234. ok = err == nil && result.Token.Expire >= time.Now().Unix()
  235. }
  236. if ok {
  237. //TODO: Renew token
  238. return nil
  239. }
  240. return errors.New("Token expired")
  241. }
  242. func (s *Storage) RemoveToken(user, token string) error {
  243. s.CleanupTokens(user)
  244. _, err := s.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$pull": bson.M{"token": bson.M{"token": token}}})
  245. if err != nil {
  246. log.Printf("Unable to remove token %s", err)
  247. }
  248. return err
  249. }
  250. func (s *Storage) CleanupTokens(user string) {
  251. log.Printf("Cleanup tokens: %s\n", user)
  252. cur, err := s.tokensCollection.Aggregate(context.Background(),
  253. bson.A{
  254. bson.M{"$match": bson.M{"user": user}},
  255. bson.M{"$unwind": "$token"},
  256. })
  257. if err != nil {
  258. log.Fatalln(err)
  259. }
  260. type tokenMetadata struct {
  261. Expire int64
  262. Token string
  263. }
  264. tokensToKeep := bson.A{}
  265. defer cur.Close(context.Background())
  266. for cur.Next(context.Background()) {
  267. result := struct {
  268. Token *tokenMetadata
  269. }{
  270. Token: &tokenMetadata{},
  271. }
  272. err = cur.Decode(&result)
  273. if err == nil && result.Token.Expire >= time.Now().Unix() {
  274. tokensToKeep = append(tokensToKeep, result.Token)
  275. } else {
  276. log.Printf("Expired token found for %s : %d", user, result.Token.Expire)
  277. }
  278. }
  279. _, err = s.tokensCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": bson.M{"token": tokensToKeep}})
  280. return
  281. }
  282. func (s *Storage) SaveMail(email, folder string, m *common.Mail, read bool) error {
  283. result := &struct {
  284. User string
  285. }{}
  286. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(result)
  287. mailsCollection := s.db.Collection(qualifiedMailCollection(result.User))
  288. mailsCollection.InsertOne(context.Background(), &struct {
  289. Email string
  290. Mail *common.Mail
  291. Folder string
  292. Read bool
  293. Trash bool
  294. }{
  295. Email: email,
  296. Mail: m,
  297. Folder: folder,
  298. Read: read,
  299. Trash: false,
  300. }, options.InsertOne().SetBypassDocumentValidation(true))
  301. return nil
  302. }
  303. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  304. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  305. oId, err := primitive.ObjectIDFromHex(mailId)
  306. if err != nil {
  307. return err
  308. }
  309. if folder == common.Trash {
  310. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": true}})
  311. } else {
  312. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder, "trash": false}})
  313. }
  314. return err
  315. }
  316. func (s *Storage) RestoreMail(user string, mailId string) error {
  317. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  318. oId, err := primitive.ObjectIDFromHex(mailId)
  319. if err != nil {
  320. return err
  321. }
  322. //TODO: Legacy for old databases remove soon
  323. metadata, err := s.GetMail(user, mailId)
  324. if metadata.Folder == common.Trash {
  325. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": common.Inbox}})
  326. }
  327. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": false}})
  328. return err
  329. }
  330. func (s *Storage) DeleteMail(user string, mailId string) error {
  331. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  332. oId, err := primitive.ObjectIDFromHex(mailId)
  333. if err != nil {
  334. return err
  335. }
  336. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  337. return err
  338. }
  339. func (s *Storage) GetMailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  340. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  341. matchFilter := bson.M{"email": email}
  342. if folder == common.Trash {
  343. matchFilter["$or"] = bson.A{
  344. bson.M{"trash": true},
  345. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  346. }
  347. } else {
  348. matchFilter["folder"] = folder
  349. matchFilter["$or"] = bson.A{
  350. bson.M{"trash": false},
  351. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  352. }
  353. }
  354. request := bson.A{
  355. bson.M{"$match": matchFilter},
  356. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  357. }
  358. if frame.Skip > 0 {
  359. request = append(request, bson.M{"$skip": frame.Skip})
  360. }
  361. fmt.Printf("Trying limit number of mails: %v\n", frame)
  362. if frame.Limit > 0 {
  363. fmt.Printf("Limit number of mails: %v\n", frame)
  364. request = append(request, bson.M{"$limit": frame.Limit})
  365. }
  366. cur, err := mailsCollection.Aggregate(context.Background(), request)
  367. if err != nil {
  368. log.Println(err.Error())
  369. return nil, err
  370. }
  371. var headers []*common.MailMetadata
  372. for cur.Next(context.Background()) {
  373. result := &common.MailMetadata{}
  374. err = cur.Decode(result)
  375. if err != nil {
  376. log.Printf("Unable to read database mail record: %s", err)
  377. continue
  378. }
  379. // fmt.Printf("Add mail: %s", result.Id)
  380. headers = append(headers, result)
  381. }
  382. // fmt.Printf("Mails read from database: %v", headers)
  383. return headers, nil
  384. }
  385. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  386. result := &common.UserInfo{}
  387. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  388. return result, err
  389. }
  390. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  391. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  392. result := &struct {
  393. Total int
  394. Unread int
  395. }{}
  396. matchFilter := bson.M{"email": email}
  397. if folder == common.Trash {
  398. matchFilter["$or"] = bson.A{
  399. bson.M{"trash": true},
  400. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  401. }
  402. } else {
  403. matchFilter["folder"] = folder
  404. matchFilter["$or"] = bson.A{
  405. bson.M{"trash": false},
  406. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  407. }
  408. }
  409. unreadMatchFilter := matchFilter
  410. unreadMatchFilter["read"] = false
  411. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": unreadMatchFilter}, bson.M{"$count": "unread"}})
  412. if err == nil && cur.Next(context.Background()) {
  413. cur.Decode(result)
  414. } else {
  415. return 0, 0, err
  416. }
  417. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "total"}})
  418. if err == nil && cur.Next(context.Background()) {
  419. cur.Decode(result)
  420. } else {
  421. return 0, 0, err
  422. }
  423. return result.Unread, result.Total, err
  424. }
  425. func (s *Storage) GetMail(user string, id string) (metadata *common.MailMetadata, err error) {
  426. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  427. oId, err := primitive.ObjectIDFromHex(id)
  428. if err != nil {
  429. return nil, err
  430. }
  431. metadata = &common.MailMetadata{
  432. Mail: common.NewMail(),
  433. }
  434. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(metadata)
  435. if err != nil {
  436. return nil, err
  437. }
  438. return metadata, nil
  439. }
  440. func (s *Storage) SetRead(user string, id string, read bool) error {
  441. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  442. oId, err := primitive.ObjectIDFromHex(id)
  443. if err != nil {
  444. return err
  445. }
  446. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  447. return err
  448. }
  449. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  450. return "", nil
  451. }
  452. func (s *Storage) GetUsers() (users []string, err error) {
  453. return nil, nil
  454. }
  455. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  456. result := &struct {
  457. Email []string
  458. }{}
  459. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  460. if err != nil {
  461. return nil, err
  462. }
  463. return result.Email, nil
  464. }
  465. func (s *Storage) GetAllEmails() (emails []string, err error) {
  466. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  467. if cur.Next(context.Background()) {
  468. result := struct {
  469. Emails []string
  470. }{}
  471. err = cur.Decode(&result)
  472. if err == nil {
  473. return result.Emails, nil
  474. }
  475. }
  476. return nil, err
  477. }
  478. func (s *Storage) CheckEmailExists(email string) bool {
  479. result := s.allEmailsCollection.FindOne(context.Background(), bson.M{"emails": email})
  480. return result.Err() == nil
  481. }
  482. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  483. folders = []*common.Folder{
  484. &common.Folder{Name: common.Inbox, Custom: false},
  485. &common.Folder{Name: common.Sent, Custom: false},
  486. &common.Folder{Name: common.Trash, Custom: false},
  487. &common.Folder{Name: common.Spam, Custom: false},
  488. }
  489. return
  490. }
  491. func (s *Storage) ReadEmailMaps() (map[string]string, error) {
  492. registredEmails, err := s.GetAllEmails()
  493. if err != nil {
  494. return nil, err
  495. }
  496. mailPath := config.ConfigInstance().VMailboxBase
  497. mapsFile := config.ConfigInstance().VMailboxMaps
  498. if !utils.FileExists(mapsFile) {
  499. return nil, errors.New("Could not read virtual mailbox maps")
  500. }
  501. db, err := berkeleydb.NewDB()
  502. if err != nil {
  503. log.Fatal(err)
  504. }
  505. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, berkeleydb.DbRdOnly)
  506. if err != nil {
  507. return nil, errors.New("Unable to open virtual mailbox maps " + mapsFile + " " + err.Error())
  508. }
  509. defer db.Close()
  510. cursor, err := db.Cursor()
  511. if err != nil {
  512. return nil, errors.New("Unable to read virtual mailbox maps " + mapsFile + " " + err.Error())
  513. }
  514. emailMaps := make(map[string]string)
  515. for true {
  516. email, path, dberr := cursor.GetNext()
  517. if dberr != nil {
  518. break
  519. }
  520. found := false
  521. for _, registredEmail := range registredEmails {
  522. if email == registredEmail {
  523. found = true
  524. }
  525. }
  526. if !found {
  527. return nil, errors.New("Found non-registred mailbox <" + email + "> in mail maps. Database has inconsistancy")
  528. }
  529. emailMaps[email] = mailPath + "/" + path
  530. }
  531. for _, registredEmail := range registredEmails {
  532. if _, exists := emailMaps[registredEmail]; !exists {
  533. return nil, errors.New("Found existing mailbox <" + registredEmail + "> in database. Mail maps has inconsistancy")
  534. }
  535. }
  536. return emailMaps, nil
  537. }