aboutsummaryrefslogtreecommitdiff
path: root/challange_http.go
blob: bd53ebf2aec507658a4329c2e1a9904d339c1e21 (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
package acme

import (
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path"
)

const wellKnown = `/.well-known/acme-challenge/`

func init() {
	registerChallenge(ChallengeHTTP)
}

type httpChallenge struct {
	Challenge
	Addr string
}

func (c httpChallenge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, c.KeyAuthorization)
}

func (c httpChallenge) Solve() error {
	done := make(chan bool)
	l, err := net.Listen("tcp", c.Addr)
	if err != nil {
		return err
	}
	defer l.Close()
	s := &http.Server{
		Handler: c,
		ConnState: func(_ net.Conn, st http.ConnState) {
			if st == http.StateClosed {
				done <- true
			}
		},
	}
	s.SetKeepAlivesEnabled(false)
	go s.Serve(l)
	<-done
	return nil
}

type webRoot struct {
	Challenge
	Webroot string
}

func (c webRoot) Solve() error {
	file := path.Join(c.Webroot, wellKnown, c.Token)
	if err := os.MkdirAll(path.Dir(file), 0755); err != nil {
		return err
	}
	return ioutil.WriteFile(file, []byte(c.KeyAuthorization), 0644)
}