forked from dyatlov/proclink-api
/
server.go
186 lines (143 loc) · 4.8 KB
/
server.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
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/dyatlov/go-oembed/oembed"
"github.com/dyatlov/go-url2oembed/url2oembed"
"github.com/jeffail/tunny"
)
type workerData struct {
Status int
Data string
}
type apiWorker struct {
Parser *url2oembed.Parser
}
type apiHandler struct {
}
func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
u := r.FormValue("url")
w.Header().Set("Server", "ProcLink")
w.Header().Set("Content-Type", "application/json")
_, err := url.Parse(u)
if err != nil {
log.Printf("Invalid URL provided: %s", u)
http.Error(w, "{\"status\": \"error\", \"message\":\"Invalid URL\"}", 500)
return
}
result, err := workerPool.SendWork(u)
if err != nil {
log.Printf("An unknown error occured: %s", err.Error())
http.Error(w, "{\"status\": \"error\", \"message\":\"Internal error\"}", 500)
return
}
if data, ok := result.(*workerData); ok {
w.WriteHeader(data.Status)
fmt.Fprintln(w, data.Data)
return
}
log.Print("Unable to decode worker result")
http.Error(w, "{\"status\": \"error\", \"message\":\"Unable to decode worker result\"}", 500)
}
// Use this call to block further jobs if necessary
func (worker *apiWorker) TunnyReady() bool {
return true
}
// This is where the work actually happens
func (worker *apiWorker) TunnyJob(data interface{}) interface{} {
if u, ok := data.(string); ok {
u = strings.Trim(u, "\r\n")
log.Printf("Got url: %s", u)
info := worker.Parser.Parse(u)
if info == nil {
log.Printf("No info for url: %s", u)
return &workerData{Status: 404, Data: "{\"status\": \"error\", \"message\":\"Unable to retrieve information from provided url\"}"}
}
if info.Status < 300 {
log.Printf("Url parsed: %s", u)
return &workerData{Status: 200, Data: info.String()}
}
log.Printf("Something weird: %s", u)
return &workerData{Status: 411, Data: fmt.Sprintf("{\"status\": \"error\", \"message\":\"Unable to obtain data. Status code: %d\"}", info.Status)}
}
return &workerData{Status: 500, Data: "{\"status\": \"error\", \"message\":\"Something weird happened\"}"}
}
var workerPool *tunny.WorkPool
// stringsToNetworks converts arrays of string representation of IP ranges into []*net.IPnet slice
func stringsToNetworks(ss []string) ([]*net.IPNet, error) {
var result []*net.IPNet
for _, s := range ss {
_, network, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
result = append(result, network)
}
return result, nil
}
func main() {
providersFile := flag.String("providers_file", "providers.json", "Path to oembed providers json file")
workerCount := flag.Int64("worker_count", 1000, "Amount of workers to start")
host := flag.String("host", "localhost", "Host to listen on")
port := flag.Int("port", 8000, "Port to listen on")
maxHTMLBytesToRead := flag.Int64("html_bytes_to_read", 50000, "How much data to read from URL if it's an html page")
maxBinaryBytesToRead := flag.Int64("binary_bytes_to_read", 4096, "How much data to read from URL if it's NOT an html page")
waitTimeout := flag.Int("wait_timeout", 7, "How much time to wait for/fetch response from remote server")
whiteListRanges := flag.String("whitelist_ranges", "", "What IP ranges to allow. Example: 178.25.32.1/8")
blackListRanges := flag.String("blacklist_ranges", "", "What IP ranges to disallow. Example: 178.25.32.1/8")
flag.Parse()
buf, err := ioutil.ReadFile(*providersFile)
if err != nil {
panic(err)
}
var whiteListNetworks []*net.IPNet
if len(*whiteListRanges) > 0 {
if whiteListNetworks, err = stringsToNetworks(strings.Split(*whiteListRanges, " ")); err != nil {
panic(err)
}
}
var blackListNetworks []*net.IPNet
if len(*blackListRanges) > 0 {
if blackListNetworks, err = stringsToNetworks(strings.Split(*blackListRanges, " ")); err != nil {
panic(err)
}
}
oe := oembed.NewOembed()
oe.ParseProviders(bytes.NewReader(buf))
workers := make([]tunny.TunnyWorker, *workerCount)
for i := range workers {
p := url2oembed.NewParser(oe)
p.MaxHTMLBodySize = *maxHTMLBytesToRead
p.MaxBinaryBodySize = *maxBinaryBytesToRead
p.WaitTimeout = time.Duration(*waitTimeout) * time.Second
p.BlacklistedIPNetworks = blackListNetworks
p.WhitelistedIPNetworks = whiteListNetworks
workers[i] = &(apiWorker{Parser: p})
}
pool, err := tunny.CreateCustomPool(workers).Open()
if err != nil {
log.Fatal(err)
}
defer pool.Close()
workerPool = pool
startServer(*host, *port, *waitTimeout)
}
func startServer(host string, port int, waitTimeout int) {
s := &http.Server{
Addr: fmt.Sprintf("%s:%d", host, port),
Handler: &apiHandler{},
ReadTimeout: time.Duration(waitTimeout) * time.Second,
WriteTimeout: time.Duration(waitTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}