db.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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) UpdateUser(user, password, fullName string) error {
  119. userInfo := bson.M{}
  120. if len(password) > 0 && len(password) < 128 {
  121. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  122. if err != nil {
  123. return err
  124. }
  125. hashString := string(hash)
  126. userInfo["password"] = hashString
  127. }
  128. if len(fullName) > 0 && len(fullName) < 128 && utils.RegExpUtilsInstance().FullNameChecker.MatchString(fullName) {
  129. userInfo["fullName"] = fullName
  130. }
  131. if len(userInfo) > 0 {
  132. _, err := s.usersCollection.UpdateOne(context.Background(), bson.M{"user": user}, bson.M{"$set": userInfo})
  133. if err != nil {
  134. return err
  135. }
  136. }
  137. return nil
  138. }
  139. func (s *Storage) AddEmail(user string, email string) error {
  140. return s.addEmail(user, email, false)
  141. }
  142. func (s *Storage) addEmail(user string, email string, upsert bool) error {
  143. result := struct {
  144. User string
  145. }{}
  146. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(&result)
  147. if err != nil {
  148. return err
  149. }
  150. emails, err := s.GetAllEmails()
  151. if err != nil {
  152. return err
  153. }
  154. for _, existingEmail := range emails {
  155. if existingEmail == email {
  156. return errors.New("Email exists")
  157. }
  158. }
  159. emailParts := strings.Split(email, "@")
  160. if len(emailParts) != 2 {
  161. return errors.New("Invalid email format")
  162. }
  163. db, err := berkeleydb.NewDB()
  164. if err != nil {
  165. log.Fatal(err)
  166. }
  167. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  168. if err != nil {
  169. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  170. }
  171. defer db.Close()
  172. err = db.Put(email, emailParts[1]+"/"+emailParts[0])
  173. if err != nil {
  174. return errors.New("Unable to add email to maps" + err.Error())
  175. }
  176. _, err = s.emailsCollection.UpdateOne(context.Background(),
  177. bson.M{"user": user},
  178. bson.M{"$addToSet": bson.M{"email": email}},
  179. options.Update().SetUpsert(upsert))
  180. return err
  181. }
  182. func (s *Storage) RemoveEmail(user string, email string) error {
  183. db, err := berkeleydb.NewDB()
  184. if err != nil {
  185. log.Fatal(err)
  186. }
  187. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, 0)
  188. if err != nil {
  189. log.Fatalf("Unable to open virtual mailbox maps %s %s\n", config.ConfigInstance().VMailboxMaps, err)
  190. }
  191. defer db.Close()
  192. err = db.Delete(email)
  193. if err != nil {
  194. return errors.New("Unable to remove email from maps" + err.Error())
  195. }
  196. _, err = s.emailsCollection.UpdateOne(context.Background(),
  197. bson.M{"user": user},
  198. bson.M{"$pull": bson.M{"email": email}})
  199. return err
  200. }
  201. func (s *Storage) SaveMail(email, folder string, m *common.Mail, read bool) error {
  202. result := &struct {
  203. User string
  204. }{}
  205. s.emailsCollection.FindOne(context.Background(), bson.M{"email": email}).Decode(result)
  206. mailsCollection := s.db.Collection(qualifiedMailCollection(result.User))
  207. mailsCollection.InsertOne(context.Background(), &struct {
  208. Email string
  209. Mail *common.Mail
  210. Folder string
  211. Read bool
  212. Trash bool
  213. }{
  214. Email: email,
  215. Mail: m,
  216. Folder: folder,
  217. Read: read,
  218. Trash: false,
  219. }, options.InsertOne().SetBypassDocumentValidation(true))
  220. return nil
  221. }
  222. func (s *Storage) MoveMail(user string, mailId string, folder string) error {
  223. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  224. oId, err := primitive.ObjectIDFromHex(mailId)
  225. if err != nil {
  226. return err
  227. }
  228. if folder == common.Trash {
  229. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": true}})
  230. } else {
  231. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": folder, "trash": false}})
  232. }
  233. return err
  234. }
  235. func (s *Storage) RestoreMail(user string, mailId string) error {
  236. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  237. oId, err := primitive.ObjectIDFromHex(mailId)
  238. if err != nil {
  239. return err
  240. }
  241. //TODO: Legacy for old databases remove soon
  242. metadata, err := s.GetMail(user, mailId)
  243. if metadata.Folder == common.Trash {
  244. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"folder": common.Inbox}})
  245. }
  246. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"trash": false}})
  247. return err
  248. }
  249. func (s *Storage) DeleteMail(user string, mailId string) error {
  250. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  251. oId, err := primitive.ObjectIDFromHex(mailId)
  252. if err != nil {
  253. return err
  254. }
  255. _, err = mailsCollection.DeleteOne(context.Background(), bson.M{"_id": oId})
  256. return err
  257. }
  258. func (s *Storage) GetMailList(user, email, folder string, frame common.Frame) ([]*common.MailMetadata, error) {
  259. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  260. matchFilter := bson.M{"email": email}
  261. if folder == common.Trash {
  262. matchFilter["$or"] = bson.A{
  263. bson.M{"trash": true},
  264. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  265. }
  266. } else {
  267. matchFilter["folder"] = folder
  268. matchFilter["$or"] = bson.A{
  269. bson.M{"trash": false},
  270. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  271. }
  272. }
  273. request := bson.A{
  274. bson.M{"$match": matchFilter},
  275. bson.M{"$sort": bson.M{"mail.header.date": -1}},
  276. }
  277. if frame.Skip > 0 {
  278. request = append(request, bson.M{"$skip": frame.Skip})
  279. }
  280. fmt.Printf("Trying limit number of mails: %v\n", frame)
  281. if frame.Limit > 0 {
  282. fmt.Printf("Limit number of mails: %v\n", frame)
  283. request = append(request, bson.M{"$limit": frame.Limit})
  284. }
  285. cur, err := mailsCollection.Aggregate(context.Background(), request)
  286. if err != nil {
  287. log.Println(err.Error())
  288. return nil, err
  289. }
  290. var headers []*common.MailMetadata
  291. for cur.Next(context.Background()) {
  292. result := &common.MailMetadata{}
  293. err = cur.Decode(result)
  294. if err != nil {
  295. log.Printf("Unable to read database mail record: %s", err)
  296. continue
  297. }
  298. // fmt.Printf("Add mail: %s", result.Id)
  299. headers = append(headers, result)
  300. }
  301. // fmt.Printf("Mails read from database: %v", headers)
  302. return headers, nil
  303. }
  304. func (s *Storage) GetUserInfo(user string) (*common.UserInfo, error) {
  305. result := &common.UserInfo{}
  306. err := s.usersCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  307. return result, err
  308. }
  309. func (s *Storage) GetEmailStats(user string, email string, folder string) (unread, total int, err error) {
  310. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  311. result := &struct {
  312. Total int
  313. Unread int
  314. }{}
  315. matchFilter := bson.M{"email": email}
  316. if folder == common.Trash {
  317. matchFilter["$or"] = bson.A{
  318. bson.M{"trash": true},
  319. bson.M{"folder": folder}, //TODO: Legacy for old databases remove soon
  320. }
  321. } else {
  322. matchFilter["folder"] = folder
  323. matchFilter["$or"] = bson.A{
  324. bson.M{"trash": false},
  325. bson.M{"trash": bson.M{"$exists": false}}, //TODO: Legacy for old databases remove soon
  326. }
  327. }
  328. unreadMatchFilter := matchFilter
  329. unreadMatchFilter["read"] = false
  330. cur, err := mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": unreadMatchFilter}, bson.M{"$count": "unread"}})
  331. if err == nil && cur.Next(context.Background()) {
  332. cur.Decode(result)
  333. } else {
  334. return 0, 0, err
  335. }
  336. cur, err = mailsCollection.Aggregate(context.Background(), bson.A{bson.M{"$match": matchFilter}, bson.M{"$count": "total"}})
  337. if err == nil && cur.Next(context.Background()) {
  338. cur.Decode(result)
  339. } else {
  340. return 0, 0, err
  341. }
  342. return result.Unread, result.Total, err
  343. }
  344. func (s *Storage) GetMail(user string, id string) (metadata *common.MailMetadata, err error) {
  345. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  346. oId, err := primitive.ObjectIDFromHex(id)
  347. if err != nil {
  348. return nil, err
  349. }
  350. metadata = &common.MailMetadata{
  351. Mail: common.NewMail(),
  352. }
  353. err = mailsCollection.FindOne(context.Background(), bson.M{"_id": oId}).Decode(metadata)
  354. if err != nil {
  355. return nil, err
  356. }
  357. return metadata, nil
  358. }
  359. func (s *Storage) SetRead(user string, id string, read bool) error {
  360. mailsCollection := s.db.Collection(qualifiedMailCollection(user))
  361. oId, err := primitive.ObjectIDFromHex(id)
  362. if err != nil {
  363. return err
  364. }
  365. _, err = mailsCollection.UpdateOne(context.Background(), bson.M{"_id": oId}, bson.M{"$set": bson.M{"read": read}})
  366. return err
  367. }
  368. func (s *Storage) GetAttachment(user string, attachmentId string) (filePath string, err error) {
  369. return "", nil
  370. }
  371. func (s *Storage) GetUsers() (users []string, err error) {
  372. return nil, nil
  373. }
  374. func (s *Storage) GetEmails(user string) (emails []string, err error) {
  375. result := &struct {
  376. Email []string
  377. }{}
  378. err = s.emailsCollection.FindOne(context.Background(), bson.M{"user": user}).Decode(result)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return result.Email, nil
  383. }
  384. func (s *Storage) GetAllEmails() (emails []string, err error) {
  385. cur, err := s.allEmailsCollection.Find(context.Background(), bson.M{})
  386. if cur.Next(context.Background()) {
  387. result := struct {
  388. Emails []string
  389. }{}
  390. err = cur.Decode(&result)
  391. if err == nil {
  392. return result.Emails, nil
  393. }
  394. }
  395. return nil, err
  396. }
  397. func (s *Storage) CheckEmailExists(email string) bool {
  398. result := s.allEmailsCollection.FindOne(context.Background(), bson.M{"emails": email})
  399. return result.Err() == nil
  400. }
  401. func (s *Storage) GetFolders(email string) (folders []*common.Folder) {
  402. folders = []*common.Folder{
  403. &common.Folder{Name: common.Inbox, Custom: false},
  404. &common.Folder{Name: common.Sent, Custom: false},
  405. &common.Folder{Name: common.Trash, Custom: false},
  406. &common.Folder{Name: common.Spam, Custom: false},
  407. }
  408. return
  409. }
  410. func (s *Storage) ReadEmailMaps() (map[string]string, error) {
  411. registredEmails, err := s.GetAllEmails()
  412. if err != nil {
  413. return nil, err
  414. }
  415. mailPath := config.ConfigInstance().VMailboxBase
  416. mapsFile := config.ConfigInstance().VMailboxMaps
  417. if !utils.FileExists(mapsFile) {
  418. return nil, errors.New("Could not read virtual mailbox maps")
  419. }
  420. db, err := berkeleydb.NewDB()
  421. if err != nil {
  422. log.Fatal(err)
  423. }
  424. err = db.Open(config.ConfigInstance().VMailboxMaps, berkeleydb.DbHash, berkeleydb.DbRdOnly)
  425. if err != nil {
  426. return nil, errors.New("Unable to open virtual mailbox maps " + mapsFile + " " + err.Error())
  427. }
  428. defer db.Close()
  429. cursor, err := db.Cursor()
  430. if err != nil {
  431. return nil, errors.New("Unable to read virtual mailbox maps " + mapsFile + " " + err.Error())
  432. }
  433. emailMaps := make(map[string]string)
  434. for true {
  435. email, path, dberr := cursor.GetNext()
  436. if dberr != nil {
  437. break
  438. }
  439. found := false
  440. for _, registredEmail := range registredEmails {
  441. if email == registredEmail {
  442. found = true
  443. }
  444. }
  445. if !found {
  446. return nil, errors.New("Found non-registred mailbox <" + email + "> in mail maps. Database has inconsistancy")
  447. }
  448. emailMaps[email] = mailPath + "/" + path
  449. }
  450. for _, registredEmail := range registredEmails {
  451. if _, exists := emailMaps[registredEmail]; !exists {
  452. return nil, errors.New("Found existing mailbox <" + registredEmail + "> in database. Mail maps has inconsistancy")
  453. }
  454. }
  455. return emailMaps, nil
  456. }