blob: 892adf8c6673e36fc1994aefba42a91283703da8 [file] [log] [blame]
David K. Bainbridge215e0242017-09-05 23:18:24 -07001package nat
2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7)
8
9// PartParser parses and validates the specified string (data) using the specified template
10// e.g. ip:public:private -> 192.168.0.1:80:8000
11// DEPRECATED: do not use, this function may be removed in a future version
12func PartParser(template, data string) (map[string]string, error) {
13 // ip:public:private
14 var (
15 templateParts = strings.Split(template, ":")
16 parts = strings.Split(data, ":")
17 out = make(map[string]string, len(templateParts))
18 )
19 if len(parts) != len(templateParts) {
20 return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
21 }
22
23 for i, t := range templateParts {
24 value := ""
25 if len(parts) > i {
26 value = parts[i]
27 }
28 out[t] = value
29 }
30 return out, nil
31}
32
33// ParsePortRange parses and validates the specified string as a port-range (8000-9000)
34func ParsePortRange(ports string) (uint64, uint64, error) {
35 if ports == "" {
36 return 0, 0, fmt.Errorf("Empty string specified for ports.")
37 }
38 if !strings.Contains(ports, "-") {
39 start, err := strconv.ParseUint(ports, 10, 16)
40 end := start
41 return start, end, err
42 }
43
44 parts := strings.Split(ports, "-")
45 start, err := strconv.ParseUint(parts[0], 10, 16)
46 if err != nil {
47 return 0, 0, err
48 }
49 end, err := strconv.ParseUint(parts[1], 10, 16)
50 if err != nil {
51 return 0, 0, err
52 }
53 if end < start {
54 return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports)
55 }
56 return start, end, nil
57}