smtp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package smtp provides supports for sending emails
  15. package smtp
  16. import (
  17. "bytes"
  18. "context"
  19. "errors"
  20. "fmt"
  21. "html/template"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/rs/xid"
  26. "github.com/wneessen/go-mail"
  27. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  28. "github.com/drakkan/sftpgo/v2/internal/kms"
  29. "github.com/drakkan/sftpgo/v2/internal/logger"
  30. "github.com/drakkan/sftpgo/v2/internal/util"
  31. "github.com/drakkan/sftpgo/v2/internal/version"
  32. )
  33. const (
  34. logSender = "smtp"
  35. )
  36. // EmailContentType defines the support content types for email body
  37. type EmailContentType int
  38. // Supported email body content type
  39. const (
  40. EmailContentTypeTextPlain EmailContentType = iota
  41. EmailContentTypeTextHTML
  42. )
  43. const (
  44. templateEmailDir = "email"
  45. templatePasswordReset = "reset-password.html"
  46. templatePasswordExpiration = "password-expiration.html"
  47. dialTimeout = 10 * time.Second
  48. )
  49. var (
  50. config = &activeConfig{}
  51. initialConfig *Config
  52. emailTemplates = make(map[string]*template.Template)
  53. )
  54. type activeConfig struct {
  55. sync.RWMutex
  56. config *Config
  57. }
  58. func (c *activeConfig) isEnabled() bool {
  59. c.RLock()
  60. defer c.RUnlock()
  61. return c.config != nil && c.config.Host != ""
  62. }
  63. func (c *activeConfig) Set(cfg *dataprovider.SMTPConfigs) {
  64. var config *Config
  65. if cfg != nil {
  66. config = &Config{
  67. Host: cfg.Host,
  68. Port: cfg.Port,
  69. From: cfg.From,
  70. User: cfg.User,
  71. Password: cfg.Password.GetPayload(),
  72. AuthType: cfg.AuthType,
  73. Encryption: cfg.Encryption,
  74. Domain: cfg.Domain,
  75. Debug: cfg.Debug,
  76. OAuth2: OAuth2Config{
  77. Provider: cfg.OAuth2.Provider,
  78. Tenant: cfg.OAuth2.Tenant,
  79. ClientID: cfg.OAuth2.ClientID,
  80. ClientSecret: cfg.OAuth2.ClientSecret.GetPayload(),
  81. RefreshToken: cfg.OAuth2.RefreshToken.GetPayload(),
  82. },
  83. }
  84. config.OAuth2.initialize()
  85. }
  86. c.Lock()
  87. defer c.Unlock()
  88. if config != nil && config.Host != "" {
  89. if c.config != nil && c.config.isEqual(config) {
  90. return
  91. }
  92. c.config = config
  93. logger.Info(logSender, "", "activated new config, server %s:%d", c.config.Host, c.config.Port)
  94. } else {
  95. logger.Debug(logSender, "", "activating initial config")
  96. c.config = initialConfig
  97. if c.config == nil || c.config.Host == "" {
  98. logger.Debug(logSender, "", "configuration disabled, email capabilities will not be available")
  99. }
  100. }
  101. }
  102. func (c *activeConfig) getSMTPClientAndMsg(to, bcc []string, subject, body string, contentType EmailContentType,
  103. attachments ...*mail.File,
  104. ) (*mail.Client, *mail.Msg, error) {
  105. c.RLock()
  106. defer c.RUnlock()
  107. if c.config == nil || c.config.Host == "" {
  108. return nil, nil, errors.New("smtp: not configured")
  109. }
  110. return c.config.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  111. }
  112. func (c *activeConfig) sendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  113. client, msg, err := c.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  114. if err != nil {
  115. return err
  116. }
  117. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  118. defer cancelFn()
  119. return client.DialAndSendWithContext(ctx, msg)
  120. }
  121. // IsEnabled returns true if an SMTP server is configured
  122. func IsEnabled() bool {
  123. return config.isEnabled()
  124. }
  125. // Activate sets the specified config as active
  126. func Activate(c *dataprovider.SMTPConfigs) {
  127. config.Set(c)
  128. }
  129. // Config defines the SMTP configuration to use to send emails
  130. type Config struct {
  131. // Location of SMTP email server. Leavy empty to disable email sending capabilities
  132. Host string `json:"host" mapstructure:"host"`
  133. // Port of SMTP email server
  134. Port int `json:"port" mapstructure:"port"`
  135. // From address, for example "SFTPGo <[email protected]>".
  136. // Many SMTP servers reject emails without a `From` header so, if not set,
  137. // SFTPGo will try to use the username as fallback, this may or may not be appropriate
  138. From string `json:"from" mapstructure:"from"`
  139. // SMTP username
  140. User string `json:"user" mapstructure:"user"`
  141. // SMTP password. Leaving both username and password empty the SMTP authentication
  142. // will be disabled
  143. Password string `json:"password" mapstructure:"password"`
  144. // 0 Plain
  145. // 1 Login
  146. // 2 CRAM-MD5
  147. // 3 OAuth2
  148. AuthType int `json:"auth_type" mapstructure:"auth_type"`
  149. // 0 no encryption
  150. // 1 TLS
  151. // 2 start TLS
  152. Encryption int `json:"encryption" mapstructure:"encryption"`
  153. // Domain to use for HELO command, if empty localhost will be used
  154. Domain string `json:"domain" mapstructure:"domain"`
  155. // Path to the email templates. This can be an absolute path or a path relative to the config dir.
  156. // Templates are searched within a subdirectory named "email" in the specified path
  157. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  158. // Set to 1 to enable debug logs
  159. Debug int `json:"debug" mapstructure:"debug"`
  160. // OAuth2 related settings
  161. OAuth2 OAuth2Config `json:"oauth2" mapstructure:"oauth2"`
  162. }
  163. func (c *Config) isEqual(other *Config) bool {
  164. if c.Host != other.Host {
  165. return false
  166. }
  167. if c.Port != other.Port {
  168. return false
  169. }
  170. if c.From != other.From {
  171. return false
  172. }
  173. if c.User != other.User {
  174. return false
  175. }
  176. if c.Password != other.Password {
  177. return false
  178. }
  179. if c.AuthType != other.AuthType {
  180. return false
  181. }
  182. if c.Encryption != other.Encryption {
  183. return false
  184. }
  185. if c.Domain != other.Domain {
  186. return false
  187. }
  188. if c.Debug != other.Debug {
  189. return false
  190. }
  191. return c.OAuth2.isEqual(&other.OAuth2)
  192. }
  193. func (c *Config) validate() error {
  194. if c.Port <= 0 || c.Port > 65535 {
  195. return fmt.Errorf("smtp: invalid port %d", c.Port)
  196. }
  197. if c.AuthType < 0 || c.AuthType > 3 {
  198. return fmt.Errorf("smtp: invalid auth type %d", c.AuthType)
  199. }
  200. if c.Encryption < 0 || c.Encryption > 2 {
  201. return fmt.Errorf("smtp: invalid encryption %d", c.Encryption)
  202. }
  203. if c.From == "" && c.User == "" {
  204. return errors.New(`smtp: from address and user cannot both be empty`)
  205. }
  206. if c.AuthType == 3 {
  207. return c.OAuth2.Validate()
  208. }
  209. return nil
  210. }
  211. func (c *Config) loadTemplates(configDir string) error {
  212. if c.TemplatesPath == "" {
  213. logger.Debug(logSender, "", "templates path empty, using default")
  214. c.TemplatesPath = "templates"
  215. }
  216. templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
  217. if templatesPath == "" {
  218. return fmt.Errorf("smtp: invalid templates path %q", templatesPath)
  219. }
  220. loadTemplates(filepath.Join(templatesPath, templateEmailDir))
  221. return nil
  222. }
  223. // Initialize initialized and validates the SMTP configuration
  224. func (c *Config) Initialize(configDir string, isService bool) error {
  225. if !isService && c.Host == "" {
  226. if err := loadConfigFromProvider(); err != nil {
  227. return err
  228. }
  229. if !config.isEnabled() {
  230. return nil
  231. }
  232. return c.loadTemplates(configDir)
  233. }
  234. if err := c.loadTemplates(configDir); err != nil {
  235. return err
  236. }
  237. if c.Host == "" {
  238. return loadConfigFromProvider()
  239. }
  240. if err := c.validate(); err != nil {
  241. return err
  242. }
  243. initialConfig = c
  244. config.Set(nil)
  245. logger.Debug(logSender, "", "configuration successfully initialized, host: %q, port: %d, username: %q, auth: %d, encryption: %d, helo: %q",
  246. c.Host, c.Port, c.User, c.AuthType, c.Encryption, c.Domain)
  247. return loadConfigFromProvider()
  248. }
  249. func (c *Config) getMailClientOptions() []mail.Option {
  250. options := []mail.Option{mail.WithPort(c.Port), mail.WithoutNoop()}
  251. switch c.Encryption {
  252. case 1:
  253. options = append(options, mail.WithSSL())
  254. case 2:
  255. options = append(options, mail.WithTLSPolicy(mail.TLSMandatory))
  256. default:
  257. options = append(options, mail.WithTLSPolicy(mail.NoTLS))
  258. }
  259. if c.User != "" {
  260. options = append(options, mail.WithUsername(c.User))
  261. }
  262. if c.Password != "" {
  263. options = append(options, mail.WithPassword(c.Password))
  264. }
  265. if c.User != "" || c.Password != "" {
  266. switch c.AuthType {
  267. case 1:
  268. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthLogin))
  269. case 2:
  270. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthCramMD5))
  271. case 3:
  272. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthXOAUTH2))
  273. default:
  274. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthPlain))
  275. }
  276. }
  277. if c.Domain != "" {
  278. options = append(options, mail.WithHELO(c.Domain))
  279. }
  280. if c.Debug > 0 {
  281. options = append(options,
  282. mail.WithLogger(&logger.MailAdapter{
  283. ConnectionID: xid.New().String(),
  284. }),
  285. mail.WithDebugLog())
  286. }
  287. return options
  288. }
  289. func (c *Config) getSMTPClientAndMsg(to, bcc []string, subject, body string, contentType EmailContentType,
  290. attachments ...*mail.File) (*mail.Client, *mail.Msg, error) {
  291. version := version.Get()
  292. msg := mail.NewMsg()
  293. msg.SetUserAgent(fmt.Sprintf("SFTPGo-%s-%s", version.Version, version.CommitHash))
  294. var from string
  295. if c.From != "" {
  296. from = c.From
  297. } else {
  298. from = c.User
  299. }
  300. if err := msg.From(from); err != nil {
  301. return nil, nil, fmt.Errorf("invalid from address: %w", err)
  302. }
  303. if err := msg.To(to...); err != nil {
  304. return nil, nil, err
  305. }
  306. if len(bcc) > 0 {
  307. if err := msg.Bcc(bcc...); err != nil {
  308. return nil, nil, err
  309. }
  310. }
  311. msg.Subject(subject)
  312. msg.SetDate()
  313. msg.SetMessageID()
  314. msg.SetAttachements(attachments)
  315. switch contentType {
  316. case EmailContentTypeTextPlain:
  317. msg.SetBodyString(mail.TypeTextPlain, body)
  318. case EmailContentTypeTextHTML:
  319. msg.SetBodyString(mail.TypeTextHTML, body)
  320. default:
  321. return nil, nil, fmt.Errorf("smtp: unsupported body content type %v", contentType)
  322. }
  323. client, err := mail.NewClient(c.Host, c.getMailClientOptions()...)
  324. if err != nil {
  325. return nil, nil, fmt.Errorf("unable to create mail client: %w", err)
  326. }
  327. if c.AuthType == 3 {
  328. token, err := c.OAuth2.getAccessToken()
  329. if err != nil {
  330. return nil, nil, fmt.Errorf("unable to get oauth2 access token: %w", err)
  331. }
  332. client.SetPassword(token)
  333. }
  334. return client, msg, nil
  335. }
  336. // SendEmail tries to send an email using the specified parameters
  337. func (c *Config) SendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  338. client, msg, err := c.getSMTPClientAndMsg(to, bcc, subject, body, contentType, attachments...)
  339. if err != nil {
  340. return err
  341. }
  342. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  343. defer cancelFn()
  344. return client.DialAndSendWithContext(ctx, msg)
  345. }
  346. func loadTemplates(templatesPath string) {
  347. logger.Debug(logSender, "", "loading templates from %q", templatesPath)
  348. passwordResetPath := filepath.Join(templatesPath, templatePasswordReset)
  349. pwdResetTmpl := util.LoadTemplate(nil, passwordResetPath)
  350. passwordExpirationPath := filepath.Join(templatesPath, templatePasswordExpiration)
  351. pwdExpirationTmpl := util.LoadTemplate(nil, passwordExpirationPath)
  352. emailTemplates[templatePasswordReset] = pwdResetTmpl
  353. emailTemplates[templatePasswordExpiration] = pwdExpirationTmpl
  354. }
  355. // RenderPasswordResetTemplate executes the password reset template
  356. func RenderPasswordResetTemplate(buf *bytes.Buffer, data any) error {
  357. if !IsEnabled() {
  358. return errors.New("smtp: not configured")
  359. }
  360. return emailTemplates[templatePasswordReset].Execute(buf, data)
  361. }
  362. // RenderPasswordExpirationTemplate executes the password expiration template
  363. func RenderPasswordExpirationTemplate(buf *bytes.Buffer, data any) error {
  364. if !IsEnabled() {
  365. return errors.New("smtp: not configured")
  366. }
  367. return emailTemplates[templatePasswordExpiration].Execute(buf, data)
  368. }
  369. // SendEmail tries to send an email using the specified parameters.
  370. func SendEmail(to, bcc []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  371. return config.sendEmail(to, bcc, subject, body, contentType, attachments...)
  372. }
  373. // ReloadProviderConf reloads the configuration from the provider
  374. // and apply it if different from the active one
  375. func ReloadProviderConf() {
  376. loadConfigFromProvider() //nolint:errcheck
  377. }
  378. func loadConfigFromProvider() error {
  379. configs, err := dataprovider.GetConfigs()
  380. if err != nil {
  381. logger.Error(logSender, "", "unable to load config from provider: %v", err)
  382. return fmt.Errorf("smtp: unable to load config from provider: %w", err)
  383. }
  384. configs.SetNilsToEmpty()
  385. if err := configs.SMTP.TryDecrypt(); err != nil {
  386. logger.Error(logSender, "", "unable to decrypt smtp config: %v", err)
  387. return fmt.Errorf("smtp: unable to decrypt smtp config: %w", err)
  388. }
  389. config.Set(configs.SMTP)
  390. return nil
  391. }
  392. func updateRefreshToken(token string) {
  393. configs, err := dataprovider.GetConfigs()
  394. if err != nil {
  395. logger.Error(logSender, "", "unable to load config from provider, updating refresh token not possible: %v", err)
  396. return
  397. }
  398. configs.SetNilsToEmpty()
  399. if configs.SMTP.IsEmpty() {
  400. logger.Warn(logSender, "", "unable to update refresh token, smtp not configured in the data provider")
  401. return
  402. }
  403. configs.SMTP.OAuth2.RefreshToken = kms.NewPlainSecret(token)
  404. if err := dataprovider.UpdateConfigs(&configs, dataprovider.ActionExecutorSystem, "", ""); err != nil {
  405. logger.Error(logSender, "", "unable to save new refresh token: %v", err)
  406. return
  407. }
  408. logger.Info(logSender, "", "refresh token updated")
  409. }