forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
351 lines (321 loc) · 6.89 KB
/
util.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package main
import (
"bufio"
"crypto/md5"
"errors"
"fmt"
"io"
"net"
"os"
"path"
"runtime"
"strconv"
"strings"
)
type notification chan byte
func newNotification() notification {
// Notification channle has size 1, so sending a single one will not block
return make(chan byte, 1)
}
func (n notification) notify() {
n <- 1
}
func (n notification) hasNotified() bool {
select {
case <-n:
return true
default:
return false
}
return false
}
// ReadLine read till '\n' is found or encounter error. The returned line does
// not include ending '\r' and '\n'. If returns err != nil if and only if
// len(line) == 0.
func ReadLine(r *bufio.Reader) (string, error) {
l, err := ReadLineBytes(r)
return string(l), err
}
// ReadLineBytes read till '\n' is found or encounter error. The returned line
// does not include ending '\r\n' or '\n'. Returns err != nil if and only if
// len(line) == 0. Note the returned byte should not be used for append and
// maybe overwritten by next I/O operation. Copied code of readLineSlice from
// $GOROOT/src/pkg/net/textproto/reader.go
func ReadLineBytes(r *bufio.Reader) (line []byte, err error) {
for {
l, more, err := r.ReadLine()
if err != nil {
return nil, err
}
// Avoid the copy if the first call produced a full line.
if line == nil && !more {
return l, nil
}
line = append(line, l...)
if !more {
break
}
}
return line, nil
}
func ASCIIToUpperInplace(b []byte) {
for i := 0; i < len(b); i++ {
if 97 <= b[i] && b[i] <= 122 {
b[i] -= 32
}
}
}
func ASCIIToUpper(b []byte) []byte {
buf := make([]byte, len(b))
copy(buf, b)
ASCIIToUpperInplace(buf)
return buf
}
func ASCIIToLowerInplace(b []byte) {
for i := 0; i < len(b); i++ {
if 65 <= b[i] && b[i] <= 90 {
b[i] += 32
}
}
}
func ASCIIToLower(b []byte) []byte {
buf := make([]byte, len(b))
copy(buf, b)
ASCIIToLowerInplace(buf)
return buf
}
func IsDigit(b byte) bool {
return '0' <= b && b <= '9'
}
var spaceTbl = [...]bool{
9: true, // ht
10: true, // lf
13: true, // cr
32: true, // sp
}
func IsSpace(b byte) bool {
if 9 <= b && b <= 32 {
return spaceTbl[b]
}
return false
}
func TrimSpace(s []byte) []byte {
if len(s) == 0 {
return s
}
st := 0
end := len(s) - 1
for ; st < len(s) && IsSpace(s[st]); st++ {
}
if st == len(s) {
return s[:0]
}
for ; end >= 0 && IsSpace(s[end]); end-- {
}
return s[st : end+1]
}
func isWindows() bool {
return runtime.GOOS == "windows"
}
func isFileExists(path string) (bool, error) {
stat, err := os.Stat(path)
if err == nil {
if stat.Mode()&os.ModeType == 0 {
return true, nil
}
return false, errors.New(path + " exists but is not regular file")
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func isDirExists(path string) (bool, error) {
stat, err := os.Stat(path)
if err == nil {
if stat.IsDir() {
return true, nil
}
return false, errors.New(path + " exists but is not directory")
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// Get host IP address
func hostIP() (addrs []string, err error) {
name, err := os.Hostname()
if err != nil {
fmt.Printf("Error get host name: %v\n", err)
return
}
addrs, err = net.LookupHost(name)
if err != nil {
fmt.Printf("Error getting host IP address: %v\n", err)
return
}
return
}
func trimLastDot(s string) string {
if len(s) > 0 && s[len(s)-1] == '.' {
return s[:len(s)-1]
}
return s
}
func getUserHomeDir() string {
home := os.Getenv("HOME")
if home == "" {
fmt.Println("HOME environment variable is empty")
}
return home
}
func expandTilde(pth string) string {
if len(pth) > 0 && pth[0] == '~' {
home := getUserHomeDir()
return path.Join(home, pth[1:])
}
return pth
}
// copyN copys N bytes from r to w, using the specified buf as buffer. pre and
// end are written to w before and after the n bytes. contBuf is used to store
// the content that's written for later reuse. copyN will try to minimize
// number of writes.
func copyN(r io.Reader, w, contBuf io.Writer, n int, buf, pre, end []byte) (err error) {
// XXX well, this is complicated in order to save writes
var nn int
bufLen := len(buf)
var b []byte
for n != 0 {
if pre != nil {
if len(pre) >= bufLen {
// pre is larger than bufLen, can't save write operation here
if _, err = w.Write(pre); err != nil {
return
}
pre = nil
continue
}
// append pre to buf to save one write
copy(buf, pre)
if len(pre)+n < bufLen {
// only need to read n bytes
b = buf[len(pre) : len(pre)+n]
} else {
b = buf[len(pre):]
}
} else {
if n < bufLen {
b = buf[:n]
} else {
b = buf
}
}
if nn, err = r.Read(b); err != nil {
return
}
n -= nn
if pre != nil {
// nn is how much we need to write next
nn += len(pre)
pre = nil
}
// see if we can append end in buffer to save one write
if n == 0 && end != nil && nn+len(end) <= bufLen {
copy(buf[nn:], end)
nn += len(end)
end = nil
}
if contBuf != nil {
contBuf.Write(buf[:nn])
}
if _, err = w.Write(buf[:nn]); err != nil {
return
}
}
if end != nil {
if _, err = w.Write(end); err != nil {
return
}
}
return
}
func md5sum(ss ...string) string {
h := md5.New()
for _, s := range ss {
io.WriteString(h, s)
}
return fmt.Sprintf("%x", h.Sum(nil))
}
// only handles IPv4 address now
func hostIsIP(host string) bool {
parts := strings.Split(host, ".")
if len(parts) != 4 {
return false
}
for _, i := range parts {
if len(i) == 0 || len(i) > 3 {
return false
}
n, err := strconv.Atoi(i)
if err != nil || n < 0 || n > 255 {
return false
}
}
return true
}
// NetNbitIPv4Mask returns a IPMask with highest n bit set.
func NewNbitIPv4Mask(n int) net.IPMask {
if n > 32 {
panic("NewNbitIPv4Mask: bit number > 32")
}
mask := []byte{0, 0, 0, 0}
for id := 0; id < 4; id++ {
if n >= 8 {
mask[id] = 0xff
} else {
mask[id] = ^byte(1<<(uint8(8-n)) - 1)
break
}
n -= 8
}
return net.IPMask(mask)
}
var topLevelDomain = map[string]bool{
"ac": true,
"co": true,
"org": true,
"com": true,
"net": true,
"edu": true,
}
// host2Domain returns the domain of a host. It will recognize domains like
// google.com.hk. Returns empty string for simple host.
func host2Domain(host string) (domain string) {
host, _ = splitHostPort(host)
if hostIsIP(host) {
return ""
}
host = trimLastDot(host)
lastDot := strings.LastIndex(host, ".")
if lastDot == -1 {
return ""
}
// Find the 2nd last dot
dot2ndLast := strings.LastIndex(host[:lastDot], ".")
if dot2ndLast == -1 {
return host
}
part := host[dot2ndLast+1 : lastDot]
// If the 2nd last part of a domain name equals to a top level
// domain, search for the 3rd part in the host name.
// So domains like bbc.co.uk will not be recorded as co.uk
if topLevelDomain[part] {
dot3rdLast := strings.LastIndex(host[:dot2ndLast], ".")
if dot3rdLast == -1 {
return host
}
return host[dot3rdLast+1:]
}
return host[dot2ndLast+1:]
}