util.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package guerrilla
  2. import (
  3. "errors"
  4. "github.com/flashmob/go-guerrilla/envelope"
  5. "regexp"
  6. "strings"
  7. )
  8. var extractEmailRegex, _ = regexp.Compile(`<(.+?)@(.+?)>`) // go home regex, you're drunk!
  9. func extractEmail(str string) (*envelope.EmailAddress, error) {
  10. email := &envelope.EmailAddress{}
  11. var err error
  12. if len(str) > RFC2821LimitPath {
  13. return email, errors.New("501 Path too long")
  14. }
  15. if matched := extractEmailRegex.FindStringSubmatch(str); len(matched) > 2 {
  16. email.User = matched[1]
  17. email.Host = validHost(matched[2])
  18. } else if res := strings.Split(str, "@"); len(res) > 1 {
  19. email.User = res[0]
  20. email.Host = validHost(res[1])
  21. }
  22. err = nil
  23. if email.User == "" || email.Host == "" {
  24. err = errors.New("501 Invalid address")
  25. } else if len(email.User) > RFC2832LimitLocalPart {
  26. err = errors.New("501 Local part too long, cannot exceed 64 characters")
  27. } else if len(email.Host) > RFC2821LimitDomain {
  28. err = errors.New("501 Domain cannot exceed 255 characters")
  29. }
  30. return email, err
  31. }
  32. var validhostRegex, _ = regexp.Compile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
  33. func validHost(host string) string {
  34. host = strings.Trim(host, " ")
  35. if validhostRegex.MatchString(host) {
  36. return host
  37. }
  38. return ""
  39. }