aboutsummaryrefslogtreecommitdiff
path: root/challange_http.go
blob: 09f1db18efb1d6a477e2afed93c1e45dc7bb11ae (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
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
	done chan bool
}

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

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

func (c *httpChallenge) Solved() error {
	c.done <- true
	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)
}

func (c *webRoot) Solved() error {
	file := path.Join(c.Webroot, wellKnown, c.Token)
	return os.Remove(file)
}