regexp.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(pageViewRegexes, httpsRequestRegexes []map[string]string) (regexps *Regexps, notices []string) {
  34. regexpsSlice := make(Regexps, 0)
  35. notices = make([]string, 0)
  36. // We aren't doing page view stats anymore, so we won't process those regexps.
  37. for _, rr := range httpsRequestRegexes {
  38. regexString := rr["regex"]
  39. if regexString == "" {
  40. notices = append(notices, "MakeRegexps: empty regex")
  41. continue
  42. }
  43. replace := rr["replace"]
  44. if replace == "" {
  45. notices = append(notices, "MakeRegexps: empty replace")
  46. continue
  47. }
  48. regex, err := regexp.Compile(regexString)
  49. if err != nil {
  50. notices = append(notices, fmt.Sprintf("MakeRegexps: failed to compile regex: %s: %s", regexString, err))
  51. continue
  52. }
  53. regexpsSlice = append(regexpsSlice, regexpReplace{regex, replace})
  54. }
  55. regexps = &regexpsSlice
  56. return
  57. }
  58. // regexHostname processes hostname through the given regexps and returns the
  59. // string that should be used for stats.
  60. func regexHostname(hostname string, regexps *Regexps) (statsHostname string) {
  61. statsHostname = "(OTHER)"
  62. if regexps != nil {
  63. for _, rr := range *regexps {
  64. if rr.regexp.MatchString(hostname) {
  65. statsHostname = rr.regexp.ReplaceAllString(hostname, rr.replace)
  66. break
  67. }
  68. }
  69. }
  70. return
  71. }