util.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package guerrilla
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "fmt"
  7. "github.com/flashmob/go-guerrilla/envelope"
  8. "github.com/flashmob/go-guerrilla/response"
  9. )
  10. var extractEmailRegex, _ = regexp.Compile(`<(.+?)@(.+?)>`) // go home regex, you're drunk!
  11. func extractEmail(str string) (*envelope.EmailAddress, error) {
  12. email := &envelope.EmailAddress{}
  13. var err error
  14. if len(str) > RFC2821LimitPath {
  15. resp := &response.Response{
  16. EnhancedCode: response.InvalidCommandArguments,
  17. BasicCode: 550,
  18. Class: response.ClassPermanentFailure,
  19. Comment: "Path too long",
  20. }
  21. return email, errors.New(resp.String())
  22. }
  23. if matched := extractEmailRegex.FindStringSubmatch(str); len(matched) > 2 {
  24. email.User = matched[1]
  25. email.Host = validHost(matched[2])
  26. } else if res := strings.Split(str, "@"); len(res) > 1 {
  27. email.User = res[0]
  28. email.Host = validHost(res[1])
  29. }
  30. err = nil
  31. resp := &response.Response{
  32. EnhancedCode: response.InvalidCommandArguments,
  33. BasicCode: 501,
  34. Class: response.ClassPermanentFailure,
  35. }
  36. if email.User == "" || email.Host == "" {
  37. resp.Comment = "Invalid address"
  38. err = fmt.Errorf("%s", resp)
  39. } else if len(email.User) > RFC2832LimitLocalPart {
  40. resp.BasicCode = 550
  41. resp.Comment = "Local part too long, cannot exceed 64 characters"
  42. err = fmt.Errorf("%s", resp)
  43. } else if len(email.Host) > RFC2821LimitDomain {
  44. resp.BasicCode = 550
  45. resp.Comment = "Domain cannot exceed 255 characters"
  46. err = fmt.Errorf("%s", resp)
  47. }
  48. return email, err
  49. }
  50. 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])$`)
  51. func validHost(host string) string {
  52. host = strings.Trim(host, " ")
  53. if validhostRegex.MatchString(host) {
  54. return host
  55. }
  56. return ""
  57. }