/
policy.go
138 lines (111 loc) · 2.46 KB
/
policy.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
// Copyright 2014 Simon Zimmermann. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// pkg policy implements a TCP socket server which handles policy requests
// issues by Unity3D web players.
//
// https://docs.unity3d.com/Documentation/Manual/SecuritySandbox.html
package policy
import (
"bytes"
"fmt"
"net"
"time"
"github.com/simonz05/util/log"
"github.com/simonz05/util/sig"
)
const (
// readBufSize is scaled to fit the largest policy protocol request
bufSize = 8 << 2
// max bytes allocated = bufSize * poolSize
poolSize = 8 << 11
)
var (
protocolPolicy = []byte("<policy-file-request/>\x00")
protocolPolicyResponse = []byte(`<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>`)
protocolPing = []byte("PING")
protocolPingResponse = []byte("+OK\r\n")
Timeout = time.Second * 20
)
func ListenAndServe(laddr string) error {
l, err := net.Listen("tcp", laddr)
if err != nil {
return err
}
log.Printf("Listen on %s", l.Addr())
sig.TrapCloser(l)
err = serve(l)
log.Printf("Shutting down ..")
return err
}
func serve(l net.Listener) error {
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
return err
}
go handle(c)
}
}
func handle(conn net.Conn) {
defer conn.Close()
err := conn.SetDeadline(time.Now().Add(Timeout))
if err != nil {
log.Errorf("Error setting deadline on conn")
return
}
buf := getBuf(bufSize)
defer putBuf(buf)
n, err := conn.Read(buf)
if err != nil {
log.Error("Error reading from conn")
return
}
log.Printf("Got %+q", buf[:n])
resp, err := parseRequest(buf[:n])
if err != nil {
log.Error(err)
return
}
n, err = conn.Write(resp)
if err != nil || n != len(resp) {
log.Errorf("Error writing to conn")
return
}
}
func parseRequest(buf []byte) (resp []byte, err error) {
switch {
case bytes.Equal(protocolPolicy, buf):
log.Printf("Policy request")
resp = protocolPolicyResponse
case bytes.Equal(protocolPing, buf):
log.Printf("Ping request")
resp = protocolPingResponse
default:
err = fmt.Errorf("Invalid protocol request")
}
return
}
var bufPool = make(chan []byte, poolSize)
func getBuf(size int) []byte {
for {
select {
case b := <-bufPool:
if cap(b) >= size {
return b[:size]
}
default:
return make([]byte, size)
}
}
}
func putBuf(b []byte) {
select {
case bufPool <- b:
default:
}
}