forked from sxp/gotunnel2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
233 lines (209 loc) · 4.98 KB
/
common.go
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package main
import (
"bytes"
"crypto/aes"
"encoding/json"
"errors"
"fmt"
box "github.com/nsf/termbox-go"
"io/ioutil"
"log"
"math/rand"
"os"
"os/user"
"path/filepath"
"reflect"
"sort"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
CONFIG_FILENAME = ".gotunnel.conf"
sigClose = uint8(0)
sigPing = uint8(1)
keepaliveSessionMagic = "I am a keepalive session."
)
var (
PING_INTERVAL = time.Second * 5
BAD_CONN_THRESHOLD = time.Second * 15
CONFIG_FILEPATH string
)
func loadConfig(defaultConf map[string]string) map[string]string {
currentUser, err := user.Current()
if err != nil {
log.Fatal("cannot get current user")
}
CONFIG_FILEPATH = filepath.Join(currentUser.HomeDir, CONFIG_FILENAME)
s, err := ioutil.ReadFile(CONFIG_FILEPATH)
if err != nil {
//if !strings.Contains(err.Error(), "no such file") { log.Fatal(err) }
err = ioutil.WriteFile(CONFIG_FILEPATH, marshalConfig(defaultConf), os.ModePerm)
return defaultConf
}
config := make(map[string]string)
err = json.Unmarshal(s, &config)
if err != nil {
log.Fatal("config file parse error")
}
return config
}
func saveConfig(conf map[string]string) {
currentUser, err := user.Current()
if err != nil {
log.Fatal("cannot get current user")
}
CONFIG_FILEPATH = filepath.Join(currentUser.HomeDir, CONFIG_FILENAME)
err = ioutil.WriteFile(CONFIG_FILEPATH, marshalConfig(conf), os.ModePerm)
if err != nil {
log.Fatal("cannot write config file")
}
}
func marshalConfig(config map[string]string) []byte {
b, err := json.Marshal(config)
if err != nil {
log.Fatal("cannot marshal config")
}
buf := new(bytes.Buffer)
json.Indent(buf, b, "", " ")
return buf.Bytes()
}
func formatFlow(n uint64) string {
units := []string{"b", "k", "m", "g", "t"}
i := 0
ret := ""
for n > 0 && i < len(units) {
if n%1024 > 0 {
ret = fmt.Sprintf("%d%s", n%1024, units[i]) + ret
}
n = n / 1024
i += 1
}
return ret
}
func encrypt(key []byte, in []byte) ([]byte, error) {
if len(in)%aes.BlockSize != 0 {
return nil, errors.New("input data length incorrect")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
out := make([]byte, len(in))
for i, l := 0, len(in); i < l; i += aes.BlockSize {
block.Encrypt(out[i:i+aes.BlockSize], in[i:i+aes.BlockSize])
}
return out, nil
}
func genRandBytes(n int) []byte {
buf := new(bytes.Buffer)
buf.Grow(n)
for i := 0; i < n; i++ {
buf.Write([]byte{byte(rand.Intn(256))})
}
return buf.Bytes()
}
//func main() {
// println(formatFlow(5))
// println(formatFlow(1024))
// println(formatFlow(1025))
// println(formatFlow(1024 * 24))
// println(formatFlow(1024 * 1024))
// println(formatFlow(1024 * 1025))
// println(formatFlow(1024 * 1024 * 1024))
// println(formatFlow(1024 * 1024 * 1025 + 1024 * 48))
// println(formatFlow(1024 * 1024 * 1025 + 1024 * 48 + 3))
// key := genRandBytes(24)
// in := genRandBytes(64)
// enc, err := encrypt(key, in)
// if err != nil { log.Fatal(err) }
// fmt.Printf("%x\n%x\n", in, enc)
//}
// from godit
func rune_width(r rune) int {
if r >= 0x1100 &&
(r <= 0x115f || r == 0x2329 || r == 0x232a ||
(r >= 0x2e80 && r <= 0xa4cf && r != 0x303f) ||
(r >= 0xac00 && r <= 0xd7a3) ||
(r >= 0xf900 && r <= 0xfaff) ||
(r >= 0xfe30 && r <= 0xfe6f) ||
(r >= 0xff00 && r <= 0xff60) ||
(r >= 0xffe0 && r <= 0xffe6) ||
(r >= 0x20000 && r <= 0x2fffd) ||
(r >= 0x30000 && r <= 0x3fffd)) {
return 2
}
return 1
}
type Printer struct {
x int
y int
w int
h int
lineWidth int
}
func NewPrinter(lineWidth int) *Printer {
ret := &Printer{
lineWidth: lineWidth,
}
ret.w, ret.h = box.Size()
return ret
}
func (self *Printer) Reset() {
self.x = 0
self.y = 0
self.w, self.h = box.Size()
}
func (self *Printer) Print(format string, args ...interface{}) {
x := self.x
for _, c := range fmt.Sprintf(format, args...) {
cwidth := rune_width(c)
if x+cwidth > self.w { // next line
x = 0
self.y += 1
}
box.SetCell(x, self.y, c, box.ColorWhite, box.ColorDefault)
x += rune_width(c)
if x >= self.w {
x = 0
self.y += 1
}
}
self.y += 1
if self.y >= self.h {
self.y = 0
self.x += self.lineWidth
}
}
type sortByValue struct {
m interface{}
key reflect.Value
fun func(a, b reflect.Value) bool
}
func (self *sortByValue) Len() int {
return reflect.ValueOf(self.m).Len()
}
func (self *sortByValue) Less(i, j int) bool {
v := reflect.ValueOf(self.m)
return self.fun(v.MapIndex(self.key.Index(i)),
v.MapIndex(self.key.Index(j)))
}
func (self *sortByValue) Swap(i, j int) {
tmp := reflect.ValueOf(self.key.Index(i).Interface())
self.key.Index(i).Set(self.key.Index(j))
self.key.Index(j).Set(tmp)
}
func ByValue(m interface{}, fun func(a, b reflect.Value) bool) reflect.Value {
sm := new(sortByValue)
sm.m = m
sm.fun = fun
t := reflect.TypeOf(m)
v := reflect.ValueOf(m)
sm.key = reflect.MakeSlice(reflect.SliceOf(t.Key()), 0, v.Len())
for _, key := range v.MapKeys() {
sm.key = reflect.Append(sm.key, key)
}
sort.Sort(sm)
return sm.key
}