regexp.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package transferstats
  20. import (
  21. "fmt"
  22. "regexp"
  23. )
  24. type regexpReplace struct {
  25. regexp *regexp.Regexp
  26. replace string
  27. }
  28. // Regexps holds the regular expressions and replacement strings used for
  29. // transforming URLs and hostnames into a stats-appropriate forms.
  30. type Regexps []regexpReplace
  31. // MakeRegexps takes the raw string-map form of the regex-replace pairs
  32. // returned by the server handshake and turns them into a usable object.
  33. func MakeRegexps(hostnameRegexes []map[string]string) (regexps *Regexps, notices []string) {
  34. regexpsSlice := make(Regexps, 0)
  35. notices = make([]string, 0)
  36. for _, rr := range hostnameRegexes {
  37. regexString := rr["regex"]
  38. if regexString == "" {
  39. notices = append(notices, "MakeRegexps: empty regex")
  40. continue
  41. }
  42. replace := rr["replace"]
  43. if replace == "" {
  44. notices = append(notices, "MakeRegexps: empty replace")
  45. continue
  46. }
  47. regex, err := regexp.Compile(regexString)
  48. if err != nil {
  49. notices = append(notices, fmt.Sprintf("MakeRegexps: failed to compile regex: %s: %s", regexString, err))
  50. continue
  51. }
  52. regexpsSlice = append(regexpsSlice, regexpReplace{regex, replace})
  53. }
  54. regexps = &regexpsSlice
  55. return
  56. }
  57. // regexHostname processes hostname through the given regexps and returns the
  58. // string that should be used for stats.
  59. func regexHostname(hostname string, regexps *Regexps) (statsHostname string) {
  60. statsHostname = "(OTHER)"
  61. if regexps != nil {
  62. for _, rr := range *regexps {
  63. if rr.regexp.MatchString(hostname) {
  64. statsHostname = rr.regexp.ReplaceAllString(hostname, rr.replace)
  65. break
  66. }
  67. }
  68. }
  69. return
  70. }