github.com/Psiphon-Labs/psiphon-tunnel-core@v2.0.28+incompatible/psiphon/transferstats/regexp.go (about) 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 20 package transferstats 21 22 import ( 23 "fmt" 24 "regexp" 25 ) 26 27 type regexpReplace struct { 28 regexp *regexp.Regexp 29 replace string 30 } 31 32 // Regexps holds the regular expressions and replacement strings used for 33 // transforming URLs and hostnames into a stats-appropriate forms. 34 type Regexps []regexpReplace 35 36 // MakeRegexps takes the raw string-map form of the regex-replace pairs 37 // returned by the server handshake and turns them into a usable object. 38 func MakeRegexps(hostnameRegexes []map[string]string) (regexps *Regexps, notices []string) { 39 regexpsSlice := make(Regexps, 0) 40 notices = make([]string, 0) 41 42 for _, rr := range hostnameRegexes { 43 regexString := rr["regex"] 44 if regexString == "" { 45 notices = append(notices, "MakeRegexps: empty regex") 46 continue 47 } 48 49 replace := rr["replace"] 50 if replace == "" { 51 notices = append(notices, "MakeRegexps: empty replace") 52 continue 53 } 54 55 regex, err := regexp.Compile(regexString) 56 if err != nil { 57 notices = append(notices, fmt.Sprintf("MakeRegexps: failed to compile regex: %s: %s", regexString, err)) 58 continue 59 } 60 61 regexpsSlice = append(regexpsSlice, regexpReplace{regex, replace}) 62 } 63 64 regexps = ®expsSlice 65 66 return 67 } 68 69 // regexHostname processes hostname through the given regexps and returns the 70 // string that should be used for stats. 71 func regexHostname(hostname string, regexps *Regexps) (statsHostname string) { 72 statsHostname = "(OTHER)" 73 if regexps != nil { 74 for _, rr := range *regexps { 75 if rr.regexp.MatchString(hostname) { 76 statsHostname = rr.regexp.ReplaceAllString(hostname, rr.replace) 77 break 78 } 79 } 80 } 81 return 82 }