Newer
Older
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
package main
import (
"database/sql"
"fmt"
"html/template"
"net"
"os"
"path/filepath"
"sort"
"strings"
"time"
"owo.codes/whats-this/cdn-origin/lib/db"
"owo.codes/whats-this/cdn-origin/lib/metrics"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
_ "github.com/lib/pq"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/valyala/fasthttp"
)
// version is the current version of cdn-origin.
// Build config
const (
configLocationUnix = "/etc/whats-this/cdn-origin/config.toml"
shutdownTimeout = 10 *time.Second
version = "0.5.0"
)
// redirectHTML is the html/template template for generating redirect HTML.
const redirectHTML = `<html><head><meta charset="UTF-8" /><meta http-equiv=refresh content="0; url={{.}}" /><script type="text/javascript">window.location.href="{{.}}"</script><title>Redirect</title></head><body><p>If you are not redirected automatically, click <a href="{{.}}">here</a> to go to the destination.</p></body></html>`
var redirectHTMLTemplate *template.Template
// redirectPreviewHTML is the html/template template for generating redirect preview HTML.
const redirectPreviewHTML = `<html><head><meta charset="UTF-8" /><title>Redirect Preview</title></head><body><p>This link goes to <code>{{.}}</code>. If you would like to visit this link, click <a href="{{.}}">here</a> to go to the destination.</p></body></html>`
var redirectPreviewHTMLTemplate *template.Template
// printConfiguration iterates through a configuration map[string]interface{}
// and prints out all of the values in alphabetical order. Configuration keys
// are printed with dot notation.
func printConfiguration(prefix string, config map[string]interface{}) {
keys := make([]string, len(config))
i := 0
for k := range config {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
if v, ok := config[k].(map[string]interface{}); ok {
printConfiguration(fmt.Sprintf("%s%s.", prefix, k), v)
} else {
fmt.Printf("%s%s: %+v\n", prefix, k, config[k])
}
}
}
func init() {
// Flag configuration
flags := pflag.NewFlagSet("whats-this-cdn-origin", pflag.ExitOnError)
flags.IntP("log-level", "l", 1, "Set zerolog logging level (5=panic, 4=fatal, 3=error, 2=warn, 1=info, 0=debug)")
configFile := flags.StringP("config-file", "c", configLocationUnix,
fmt.Sprintf("Path to configuration file, defaults to %s", configLocationUnix))
printConfig := flags.BoolP("print-config", "p", false, "Prints configuration and exits")
flags.Parse(os.Args)
// Configuration defaults
viper.SetDefault("database.objectBucket", "public")
viper.SetDefault("http.compressResponse", false)
viper.SetDefault("http.listenAddress", ":49544")
viper.SetDefault("http.trustProxy", false)
viper.BindPFlag("log.level", flags.Lookup("log-level")) // default is 1 (info)
viper.SetDefault("metrics.enable", false)
viper.SetDefault("metrics.enableHostnameWhitelist", false)
// Load configuration file
viper.SetConfigType("toml")
file, err := os.Open(*configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open configuration file (%s) for reading: %s", *configFile, err.Error())
os.Exit(1)
return
}
err = viper.ReadConfig(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse configuration file (%s): %s", *configFile, err.Error())
os.Exit(1)
return
}
file.Close()
// Configure logger
zerolog.TimeFieldFormat = ""
if lvl := viper.GetInt("log.level"); 0 <= lvl && lvl <= 5 {
zerolog.SetGlobalLevel(zerolog.Level(lvl))
} else {
viper.Set("log.level", 1)
zerolog.SetGlobalLevel(zerolog.InfoLevel)
log.Warn().Int("log.level", lvl).Msg("Invalid log level, defaulting to 1 (info)")
}
log.Debug().Uint8("level", uint8(zerolog.GlobalLevel())).Msg("Set logger level")
// Print configuration variables in alphabetical order
if *printConfig {
log.Info().Msg("Printing configuration values to Stdout")
settings := viper.AllSettings()
printConfiguration("", settings)
os.Exit(0)
return
}
// Ensure required configuration variables are set
if viper.GetString("database.connectionURL") == "" {
log.Fatal().Msg("Configuration: database.connectionURL is required")
}
if viper.GetString("database.objectBucket") == "" {
log.Fatal().Msg("Configuration: database.objectBucket is required")
}
if viper.GetBool("metrics.enable") && viper.GetBool("metrics.enableHostnameWhitelist") && len(viper.GetStringSlice("metrics.hostnameWhitelist")) == 0 {
log.Fatal().Msg("Configuration: metrics.hostnameWhitelist is required when metrics and hostname whitelist is enabled")
}
if viper.GetString("http.listenAddress") == "" {
log.Fatal().Msg("Configuration: http.listenAddress is required")
}
if viper.GetString("files.storageLocation") == "" {
log.Fatal().Msg("Configuration: files.storageLocation is required")
}
// Parse redirect templates
redirectHTMLTemplate, err = template.New("redirectHTML").Parse(redirectHTML)
if err != nil {
log.Fatal().Err(err).Msg("failed to parse redirectHTML template")
}
redirectPreviewHTMLTemplate, err = template.New("redirectPreviewHTML").Parse(redirectPreviewHTML)
if err != nil {
log.Fatal().Err(err).Msg("failed to parse redirectPreviewHTML template")
}
}
var collector *metrics.Collector
func main() {
// Connect to PostgreSQL database
err := db.Connect("postgres", viper.GetString("database.connectionURL"))
if err != nil {
log.Fatal().Err(err).Msg("failed to open database connection")
}
// Setup metrics collector
if viper.GetBool("metrics.enable") {
hostnameWhitelist := []string{}
if viper.GetBool("metrics.enableHostnameWhitelist") {
switch w := viper.Get("metrics.hostnameWhitelist").(type) {
case []interface{}:
for _, s := range w {
hostnameWhitelist = append(hostnameWhitelist, strings.TrimSpace(fmt.Sprint(s)))
}
break
default:
log.Fatal().Msg("metrics.hostnameWhitelist is not an array")
}
}
collector, err = metrics.New(
viper.GetString("metrics.elasticURL"),
viper.GetString("metrics.maxmindDBLocation"),
viper.GetBool("metrics.enableHostnameWhitelist"),
hostnameWhitelist,
)
if err != nil {
log.Fatal().Err(err).Msg("failed to setup metrics collector")
}
}
// Launch server
h := requestHandler
if viper.GetBool("http.compressResponse") {
h = fasthttp.CompressHandler(h)
}
listenAddress := viper.GetString("http.listenAddress")
log.Info().Str("listenAddress", listenAddress).Msg("Starting HTTP server")
server := &fasthttp.Server{
Handler: h,
Name: "whats-this/cdn-origin v" + version,
ReadBufferSize: 1024 * 6, // 6 KB
ReadTimeout: time.Minute * 30,
WriteTimeout: time.Minute * 30,
GetOnly: true, // TODO: OPTIONS/HEAD requests
DisableHeaderNamesNormalizing: false,
}
if err := server.ListenAndServe(listenAddress); err != nil {
log.Fatal().Err(err).Msg("error in server.ListenAndServe")
}
}
func recordMetrics(ctx *fasthttp.RequestCtx) {
if !viper.GetBool("metrics.enable") {
return
}
// Get object type
objectType := ""
if v, ok := ctx.UserValue("object_type").(string); ok {
objectType = v
}
// Determine remote IP
var remoteIP net.IP
if viper.GetBool("http.trustProxy") {
ipString := string(ctx.Request.Header.Peek("X-Forwarded-For"))
remoteIP = net.ParseIP(strings.Split(ipString, ",")[0])
} else {
remoteIP = ctx.RemoteIP()
}
// Anonymize host string and send record to Elasticsearch
hostBytes := ctx.Request.Header.Peek("Host")
statusCode := ctx.Response.StatusCode()
if len(hostBytes) != 0 {
go func() {
// Check hostname
hostStr, isValid := collector.MatchHostname(string(hostBytes))
if !isValid {
return
}
// Get country code of visitor
countryCode, err := collector.GetCountryCode(remoteIP)
if err != nil {
// Don't log the error here, it might contain an IP address
log.Warn().Msg("failed to get country code for IP, omitting from record")
}
record := metrics.GetRecord()
record.CountryCode = countryCode
record.Hostname = hostStr
record.ObjectType = objectType
record.StatusCode = statusCode
err = collector.Put(record)
if err != nil {
log.Warn().Err(err).Msg("failed to collect record")
return
}
log.Debug().Msg("successfully collected metrics")
}()
}
}
func requestHandler(ctx *fasthttp.RequestCtx) {
// Fetch object from database
key := string(ctx.Path()[1:])
object, err := db.SelectObjectByBucketKey(viper.GetString("database.objectBucket"), key)
switch {
case err == sql.ErrNoRows:
ctx.SetStatusCode(fasthttp.StatusNotFound)
ctx.SetContentType("text/plain; charset=utf8")
fmt.Fprintf(ctx, "404 Not Found: %s", ctx.Path())
recordMetrics(ctx)
return
case err != nil:
log.Error().Err(err).Msg("failed to run SELECT query on database")
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetContentType("text/plain; charset=utf8")
fmt.Fprint(ctx, "500 Internal Server Error")
recordMetrics(ctx)
return
}
switch object.ObjectType {
case 0: // file
ctx.SetUserValue("object_type", "file")
// Serve file to client
fPath := filepath.Join(viper.GetString("files.storageLocation"), key)
ctx.SetStatusCode(fasthttp.StatusOK)
if object.ContentType != nil {
ctx.SetContentType(*object.ContentType)
} else {
ctx.SetContentType("application/octet-stream")
}
fasthttp.ServeFileUncompressed(ctx, fPath)
recordMetrics(ctx)
case 1: // redirect
ctx.SetUserValue("object_type", "redirect")
if object.DestURL == nil {
log.Warn().Str("key", key).Msg("encountered redirect object with NULL dest_url")
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
ctx.SetContentType("text/plain; charset=utf8")
fmt.Fprint(ctx, "500 Internal Server Error")
recordMetrics(ctx)
return
}
previewMode := ctx.QueryArgs().Has("preview")
var err error
if previewMode {
err = redirectPreviewHTMLTemplate.Execute(ctx, object.DestURL)
} else {
err = redirectHTMLTemplate.Execute(ctx, object.DestURL)
}
if err != nil {
log.Warn().Err(err).
Str("dest_url", *object.DestURL).
Bool("preview", ctx.QueryArgs().
Has("preview")).Msg("failed to generate HTML redirect page to send to client")
ctx.SetContentType("text/plain; charset=utf8")
fmt.Fprintf(ctx, "Failed to generate HTML redirect page, destination URL: %s", *object.DestURL)
recordMetrics(ctx)
return
}
ctx.SetContentType("text/html; charset=ut8")
if !previewMode {
ctx.SetStatusCode(fasthttp.StatusFound)
ctx.Response.Header.Set("Location", *object.DestURL)
} else {
ctx.SetStatusCode(fasthttp.StatusOK)
}
recordMetrics(ctx)
case 2: // tombstone
ctx.SetUserValue("object_type", "tombstone")
// Send 410 gone response
ctx.SetStatusCode(fasthttp.StatusGone)
ctx.SetContentType("text/plain; charset=utf8")
reason := "no reason specified"
if object.DeleteReason != nil && *object.DeleteReason != "" {
reason = *object.DeleteReason
}
fmt.Fprintf(ctx, "410 Gone: %s\n\nReason: %s", ctx.Path(), reason)
recordMetrics(ctx)