summaryrefslogtreecommitdiff
path: root/http.go
blob: e6939f9f2ef2b8bb833c77c8df181e55c8c73f7b (plain)
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
package dyndns

import (
	"errors"
	"fmt"
	"net/http"
	//"strings"
)

var (
	ErrBadAuth  = errors.New("badauth")
	ErrNotFQDN  = errors.New("notfqdn")
	ErrNoHost   = errors.New("nohost")
	ErrNumHost  = errors.New("numhost")
	ErrAbuse    = errors.New("abuse")
	ErrBadAgent = errors.New("badagent")
	ErrDNSErr   = errors.New("dnserr")
	Err911      = errors.New("911")
)

var errorCode = map[error]int{
	ErrBadAuth:  401,
	ErrNotFQDN:  406,
	ErrNoHost:   406,
	ErrNumHost:  406,
	ErrAbuse:    406,
	ErrBadAgent: 406,
	ErrDNSErr:   500,
	Err911:      500,
}

// https://{user}:{key}@example.com/v3/update?hostname={hostname}
// https://{user}:{key}@example.com/v3/update?hostname={hostname}&myip={IP address}

func respond(w http.ResponseWriter, e error) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.WriteHeader(errorCode[e])
	fmt.Fprintln(w, e)
}

func basicAuth(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		username, password, _ := r.BasicAuth()

		if !validateAuth(username, password) {
			respond(w, ErrBadAuth)
			return
		}
		next(w, r)
	})
}

func validateAuth(username, password string) bool {
	// TODO lookup
	if username == "username" && password == "password" {
		return true
	}
	return false
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()

	hnStr := qs.Get("hostname")
	if hnStr == "" {
		respond(w, ErrNoHost)
		return
	}

	//hostnames := strings.Split(hnStr, ",")

}