db.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. "os"
  34. "strings"
  35. "time"
  36. common "git.semlanik.org/semlanik/gostfix/common"
  37. "git.semlanik.org/semlanik/gostfix/utils"
  38. "github.com/semlanik/berkeleydb"
  39. bcrypt "golang.org/x/crypto/bcrypt"
  40. bson "go.mongodb.org/mongo-driver/bson"
  41. "go.mongodb.org/mongo-driver/bson/primitive"
  42. mongo "go.mongodb.org/mongo-driver/mongo"
  43. options "go.mongodb.org/mongo-driver/mongo/options"
  44. config "git.semlanik.org/semlanik/gostfix/config"
  45. )
  46. type Storage struct {
  47. db *mongo.Database
  48. usersCollection *mongo.Collection
  49. tokensCollection *mongo.Collection
  50. emailsCollection *mongo.Collection
  51. allEmailsCollection *mongo.Collection
  52. }
  53. func qualifiedMailCollection(user string) string {
  54. sum := sha1.Sum([]byte(user))
  55. return "mb" + hex.EncodeToString(sum[:])
  56. }
  57. func NewStorage() (s *Storage, err error) {
  58. fullUrl := "mongodb://"
  59. if config.ConfigInstance().MongoUser != "" {
  60. fullUrl += config.ConfigInstance().MongoUser
  61. if config.ConfigInstance().MongoPassword != "" {
  62. fullUrl += ":" + config.ConfigInstance().MongoPassword
  63. }
  64. fullUrl += "@"
  65. }
  66. fullUrl += config.ConfigInstance().MongoAddress
  67. client, err := mongo.NewClient(options.Client().ApplyURI(fullUrl))
  68. if err != nil {
  69. return nil, err
  70. }
  71. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  72. defer cancel()
  73. err = client.Connect(ctx)
  74. if err != nil {
  75. return nil, err
  76. }
  77. db := client.Database("gostfix")
  78. index := mongo.IndexModel{
  79. Keys: bson.M{
  80. "user": 1,
  81. },
  82. Options: options.Index().SetUnique(true),
  83. }
  84. s = &Storage{
  85. db: db,
  86. usersCollection: db.Collection("users"),
  87. tokensCollection: db.Collection("tokens"),
  88. emailsCollection: db.Collection("emails"),
  89. allEmailsCollection: db.Collection("allEmails"),
  90. }
  91. //Initial database setup
  92. s.usersCollection.Indexes().CreateOne(context.Background(), index)
  93. s.tokensCollection.Indexes().CreateOne(context.Background(), index)
  94. s.emailsCollection.Indexes().CreateOne(context.Background(), index)
  95. return
  96. }
  97. func (s *Storage) AddUser(user, password, fullName string) error {
  98. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  99. if err != nil {
  100. return err
  101. }
  102. hashString := string(hash)
  103. userInfo := bson.M{
  104. "user": user,
  105. "password": hashString,
  106. "fullName": fullName,
  107. }
  108. _, err = s.usersCollection.InsertOne(context.Background(), userInfo)
  109. if err != nil {
  110. return err
  111. }
  112. err = s.addEmail(user, user, true)
  113. if err != nil {
  114. s.usersCollection.DeleteOne(context.Background(), bson.M{"user": user})
  115. return err
  116. }
  117. return nil
  118. }
  119. func (s *Storage) UpdateUser(user, password, fullName string) error {
  120. userInfo := bson.M{}
  121. if len(password) > 0 && len(password) < 128 {
  122. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  123. if err != nil {
  124. return err
  125. }
  126. hashString := string(hash)
  127. userInfo["password"] = hashString
  128. }
  129. if len(fullName) > 0 && len(fullName) < 128 && utils.RegExpUtilsInstance().FullNameChecker.MatchString(fullName) {
  130. userInfo["fullName"] = fullName
  131. }
  132. if len(userInfo) > 0 {
  133. _, err := s.usersCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": userInfo})
  134. if err != nil {
  135. return err
  136. }
  137. }
  138. return nil
  139. }
  140. func (s *Storage) AddEmail(user string, email string) error {
  141. return s.addEmail(user, email, false)
  142. }
  143. func (s *Storage) addEmail(user string, email string, upsert bool) error {
  144. result := struct {
  145. User string
  146. }{}
  147. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  148. if err != nil {
  149. return err
  150. }
  151. emails, err := s.GetAllEmails()
  152. if err != nil {
  153. return err
  154. }
  155. for _, existingEmail := range emails {
  156. if existingEmail == email {
  157. return errors.New("Email exists")
  158. }
  159. }
  160. emailParts := strings.Split(email, "@")
  161. if len(emailParts) != 2 {
  162. return errors.New("Invalid email format")
  163. }
  164. db, err := berkeleydb.NewDB()
  165. if err != nil {
  166. log.Fatal(err)
  167. }
  168. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  169. if err != nil {
  170. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  171. }
  172. defer db.Close()
  173. err = db.Put(email, emailParts[1]+"/"+emailParts[0])
  174. if err != nil {
  175. return errors.New("Unable to add email to maps" + err.Error())
  176. }
  177. _, err = s.emailsCollection.UpdateOne(context.Background(),
  178. bson.M{"user": user},
  179. bson.M{"$addToSet": bson.M{"email": email}},
  180. options.Update().SetUpsert(upsert))
  181. return err
  182. }
  183. func (s *Storage) RemoveEmail(user string, email string) error {
  184. log.Printf("User %s removes email %s", user, email)
  185. result := s.emailsCollection.FindOne(context.Background(), bson.M{
  186. "user": user,
  187. "email": email,
  188. })
  189. if result.Err() != nil {
  190. return result.Err()
  191. }
  192. db, err := berkeleydb.NewDB()
  193. if err != nil {
  194. log.Fatal(err)
  195. }
  196. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  197. if err != nil {
  198. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  199. }
  200. defer db.Close()
  201. err = db.Delete(email)
  202. if err != nil {
  203. return errors.New("Unable to remove email from maps" + err.Error())
  204. }
  205. err = s.cleanupAttachments(user, email)
  206. if err != nil {
  207. log.Printf("Unable to cleanup attachments for %s %s\n", email, err)
  208. }
  209. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  210. mailsCollection.DeleteMany(context.Background(), bson.M{"email": email})
  211. _, err = s.emailsCollection.UpdateOne(context.Background(),
  212. bson.M{"user": user},
  213. bson.M{"$pull": bson.M{"email": email}})
  214. return err
  215. }
  216. func (s *Storage) SaveMail(email, folder string, m *common.Mail, read bool) error {
  217. result := &struct {
  218. User string
  219. }{}
  220. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(result)
  221. mailsCollection := s.db.Collection(qualifiedMailCollection(result.User))
  222. mailsCollection.InsertOne(context.Background(), &struct {
  223. Email string
  224. Mail *common.Mail
  225. Folder string
  226. Read bool
  227. Trash bool
  228. }{
  229. Email: email,
  230. Mail: m,
  231. Folder: folder,
  232. Read: read,
  233. Trash: false,
  234. }, options.InsertOne().SetBypassDocumentValidation(true))
  235. return nil
  236. }
  237. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  238. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  239. oId, err := primitive.ObjectIDFromHex(mailId)
  240. if err != nil {
  241. return err
  242. }
  243. if folder == common.Trash {
  244. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": true}})
  245. } else {
  246. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder, "trash": false}})
  247. }
  248. return err
  249. }
  250. func (s *Storage) RestoreMail(user string, mailId string) error {
  251. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  252. oId, err := primitive.ObjectIDFromHex(mailId)
  253. if err != nil {
  254. return err
  255. }
  256. //TODO: Legacy for old databases remove soon
  257. metadata, err := s.GetMail(user, mailId)
  258. if metadata.Folder == common.Trash {
  259. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": common.Inbox}})
  260. }
  261. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": false}})
  262. return err
  263. }
  264. func (s *Storage) DeleteMail(user string, mailId string) error {
  265. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  266. oId, err := primitive.ObjectIDFromHex(mailId)
  267. if err != nil {
  268. return err
  269. }
  270. var result common.MailMetadata
  271. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(&result)
  272. if err != nil {
  273. return err
  274. }
  275. for _, attachment := range result.Mail.Body.Attachments {
  276. removeAttachment(attachment.Id)
  277. }
  278. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  279. return err
  280. }
  281. func (s *Storage) GetMailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  282. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  283. matchFilter := bson.M{"email": email}
  284. if folder == common.Trash {
  285. matchFilter["$or"] = bson.A{
  286. bson.M{"trash": true},
  287. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  288. }
  289. } else {
  290. matchFilter["folder"] = folder
  291. matchFilter["$or"] = bson.A{
  292. bson.M{"trash": false},
  293. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  294. }
  295. }
  296. request := bson.A{
  297. bson.M{"$match": matchFilter},
  298. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  299. }
  300. if frame.Skip > 0 {
  301. request = append(request, bson.M{"$skip": frame.Skip})
  302. }
  303. fmt.Printf("Trying limit number of mails: %v\n", frame)
  304. if frame.Limit > 0 {
  305. fmt.Printf("Limit number of mails: %v\n", frame)
  306. request = append(request, bson.M{"$limit": frame.Limit})
  307. }
  308. cur, err := mailsCollection.Aggregate(context.Background(), request)
  309. if err != nil {
  310. log.Println(err.Error())
  311. return nil, err
  312. }
  313. var headers []*common.MailMetadata
  314. for cur.Next(context.Background()) {
  315. result := &common.MailMetadata{}
  316. err = cur.Decode(result)
  317. if err != nil {
  318. log.Printf("Unable to read database mail record: %s", err)
  319. continue
  320. }
  321. // fmt.Printf("Add mail: %s", result.Id)
  322. headers = append(headers, result)
  323. }
  324. // fmt.Printf("Mails read from database: %v", headers)
  325. return headers, nil
  326. }
  327. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  328. result := &common.UserInfo{}
  329. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  330. return result, err
  331. }
  332. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  333. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  334. result := &struct {
  335. Total int
  336. Unread int
  337. }{}
  338. matchFilter := bson.M{"email": email}
  339. if folder == common.Trash {
  340. matchFilter["$or"] = bson.A{
  341. bson.M{"trash": true},
  342. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  343. }
  344. } else {
  345. matchFilter["folder"] = folder
  346. matchFilter["$or"] = bson.A{
  347. bson.M{"trash": false},
  348. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  349. }
  350. }
  351. unreadMatchFilter := matchFilter
  352. unreadMatchFilter["read"] = false
  353. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": unreadMatchFilter}, bson.M{"$count": "unread"}})
  354. if err == nil && cur.Next(context.Background()) {
  355. cur.Decode(result)
  356. } else {
  357. return 0, 0, err
  358. }
  359. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "total"}})
  360. if err == nil && cur.Next(context.Background()) {
  361. cur.Decode(result)
  362. } else {
  363. return 0, 0, err
  364. }
  365. return result.Unread, result.Total, err
  366. }
  367. func (s *Storage) GetMail(user string, id string) (metadata *common.MailMetadata, err error) {
  368. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  369. oId, err := primitive.ObjectIDFromHex(id)
  370. if err != nil {
  371. return nil, err
  372. }
  373. metadata = &common.MailMetadata{
  374. Mail: common.NewMail(),
  375. }
  376. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(metadata)
  377. if err != nil {
  378. return nil, err
  379. }
  380. return metadata, nil
  381. }
  382. func (s *Storage) SetRead(user string, id string, read bool) error {
  383. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  384. oId, err := primitive.ObjectIDFromHex(id)
  385. if err != nil {
  386. return err
  387. }
  388. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  389. return err
  390. }
  391. func (s *Storage) UpdateMail(user string, id string, mailMap interface{}) error {
  392. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  393. oId, err := primitive.ObjectIDFromHex(id)
  394. if err != nil {
  395. return err
  396. }
  397. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": mailMap})
  398. return err
  399. }
  400. func (s *Storage) GetUsers() (users []string, err error) {
  401. return nil, nil
  402. }
  403. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  404. result := &struct {
  405. Email []string
  406. }{}
  407. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  408. if err != nil {
  409. return nil, err
  410. }
  411. return result.Email, nil
  412. }
  413. func (s *Storage) GetAllEmails() (emails []string, err error) {
  414. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  415. if cur.Next(context.Background()) {
  416. result := struct {
  417. Emails []string
  418. }{}
  419. err = cur.Decode(&result)
  420. if err == nil {
  421. return result.Emails, nil
  422. }
  423. }
  424. return nil, err
  425. }
  426. func (s *Storage) CheckEmailExists(email string) bool {
  427. result := s.allEmailsCollection.FindOne(context.Background(), bson.M{"emails": email})
  428. return result.Err() == nil
  429. }
  430. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  431. folders = []*common.Folder{
  432. &common.Folder{Name: common.Inbox, Custom: false},
  433. &common.Folder{Name: common.Sent, Custom: false},
  434. &common.Folder{Name: common.Trash, Custom: false},
  435. &common.Folder{Name: common.Spam, Custom: false},
  436. }
  437. return
  438. }
  439. func (s *Storage) ReadEmailMaps() (map[string]string, error) {
  440. registredEmails, err := s.GetAllEmails()
  441. if err != nil {
  442. return nil, err
  443. }
  444. mailPath := config.ConfigInstance().VMailboxBase
  445. mapsFile := config.ConfigInstance().VMailboxMaps
  446. if !utils.FileExists(mapsFile) {
  447. return nil, errors.New("Could not read virtual mailbox maps")
  448. }
  449. db, err := berkeleydb.NewDB()
  450. if err != nil {
  451. log.Fatal(err)
  452. }
  453. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, berkeleydb.DbRdOnly)
  454. if err != nil {
  455. return nil, errors.New("Unable to open virtual mailbox maps " + mapsFile + " " + err.Error())
  456. }
  457. defer db.Close()
  458. cursor, err := db.Cursor()
  459. if err != nil {
  460. return nil, errors.New("Unable to read virtual mailbox maps " + mapsFile + " " + err.Error())
  461. }
  462. emailMaps := make(map[string]string)
  463. for true {
  464. email, path, dberr := cursor.GetNext()
  465. if dberr != nil {
  466. break
  467. }
  468. found := false
  469. for _, registredEmail := range registredEmails {
  470. if email == registredEmail {
  471. found = true
  472. }
  473. }
  474. if !found {
  475. return nil, errors.New("Found non-registred mailbox <" + email + "> in mail maps. Database has inconsistancy")
  476. }
  477. emailMaps[email] = mailPath + "/" + path
  478. }
  479. for _, registredEmail := range registredEmails {
  480. if _, exists := emailMaps[registredEmail]; !exists {
  481. return nil, errors.New("Found existing mailbox <" + registredEmail + "> in database. Mail maps has inconsistancy")
  482. }
  483. }
  484. return emailMaps, nil
  485. }
  486. func removeAttachment(attachmentId string) error {
  487. attachmentPath := config.ConfigInstance().AttachmentsPath + "/" + attachmentId
  488. err := os.Remove(attachmentPath)
  489. if err != nil {
  490. log.Printf("Unable to remove attachment file: %s. Database inconsistency", attachmentPath)
  491. }
  492. return err
  493. }
  494. func (s *Storage) cleanupAttachments(user, email string) error {
  495. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  496. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{
  497. bson.M{"$match": bson.M{"email": email}},
  498. bson.M{"$project": bson.M{"mail.body.attachments": 1}},
  499. bson.M{"$unwind": "$mail.body.attachments"},
  500. bson.M{"$replaceRoot": bson.M{"newRoot": "$mail.body.attachments"}},
  501. })
  502. if err != nil {
  503. return err
  504. }
  505. for cur.Next(context.Background()) {
  506. var attachment common.AttachmentHeader
  507. err = cur.Decode(&attachment)
  508. if err != nil {
  509. log.Printf("Unable to decode attachment")
  510. }
  511. removeAttachment(attachment.Id)
  512. }
  513. return nil
  514. }