summaryrefslogtreecommitdiff
path: root/tinc.go
blob: d06a6d22e320f77bcea413990e0b8de45cbd58d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// Error is a parse error recording the filename and line number.
type Error struct {
	File string
	Line int
	Err  error
}

func (e Error) Error() string {
	if e.Line > 0 {
		return fmt.Sprintf("%v:%v: %v", e.File, e.Line, e.Err)
	} else {
		return fmt.Sprintf("%v: %v", e.File, e.Err)
	}
}

func parseConfigLine(line string) (key, val string) {
	line = strings.TrimRight(line, "\t ")
	keylen := strings.IndexAny(line, "\t =")
	if keylen < 0 {
		keylen = len(line)
	}

	variable := line[:keylen]

	value := strings.TrimLeft(line[keylen:], "\t ")
	if strings.HasPrefix(value, "=") {
		value = strings.TrimLeft(value[1:], "\t ")
	}

	return variable, value
}

// ReadConfigFile opens and reads a Tinc configuration file, returning
// a map of settings.  Since Tinc setting names are case-insensitive,
// the keys in the map are all lower-case.
func ReadConfigFile(fname string) (map[string][]string, error) {
	config_tree := make(map[string][]string)

	fp, err := os.Open(fname)
	if err != nil {
		return nil, Error{File: fname, Err: err}
	}

	buffer := bufio.NewScanner(fp)

	lineno := 0
	ignore := false
	for buffer.Scan() {
		line := buffer.Text()

		lineno++

		if len(line) == 0 || line[0] == '#' {
			continue
		}

		if ignore {
			if strings.HasPrefix(line, "-----END") {
				ignore = false
			}

			continue
		}

		if strings.HasPrefix(line, "-----BEGIN") {
			ignore = true
			continue

		}

		variable, value := parseConfigLine(line)
		if len(value) == 0 {
			err = fmt.Errorf("No value for variable: %s", variable)
			return nil, Error{File: fname, Line: lineno, Err: err}
		}
		variable = strings.ToLower(variable)
		config_tree[variable] = append(config_tree[variable], value)
	}

	err = buffer.Err()
	if err != nil {
		return nil, Error{File: fname, Err: err}
	}
	return config_tree, nil
}

// GetAddresses inspects a tinc host-confing settings object and
// returns a list of public addresses in it.
func GetAddresses(cfg map[string][]string) []struct{ Node, Port string } {
	var result []struct{ Node, Port string }

	for _, node := range cfg["address"] {
		var port string
		space := strings.IndexByte(node, ' ')
		if space < 0 {
			if ports, portsOk := cfg["port"]; portsOk {
				port = ports[0]
			} else {
				port = "655"
			}
		} else {
			port = node[space+1:]
			node = node[:space]
		}

		result = append(result, struct{ Node, Port string }{node, port})
	}

	return result
}