lego/acme/http_challenge.go
Tommie Gannert 5dc33c8c08 Simplify httpChallenge code.
Solve is blocking, so no need to run initialization code in a separate
goroutine. Removes the need for s.start.

Once the listener is closed, all I/O resources have been returned. No
need to wait for http.Serve to return. Removes the need for s.end.
2015-12-05 12:00:00 +00:00

59 lines
1.5 KiB
Go

package acme
import (
"fmt"
"net"
"net/http"
"strings"
)
type httpChallenge struct {
jws *jws
optPort string
}
func (s *httpChallenge) Solve(chlng challenge, domain string) error {
logf("[INFO] acme: Trying to solve HTTP-01")
// Generate the Key Authorization for the challenge
keyAuth, err := getKeyAuthorization(chlng.Token, &s.jws.privKey.PublicKey)
if err != nil {
return err
}
// Allow for CLI port override
port := ":80"
if s.optPort != "" {
port = ":" + s.optPort
}
listener, err := net.Listen("tcp", domain+port)
if err != nil {
// if the domain:port bind failed, fall back to :port bind and try that instead.
listener, err = net.Listen("tcp", port)
if err != nil {
return fmt.Errorf("Could not start HTTP server for challenge -> %v", err)
}
}
defer listener.Close()
path := "/.well-known/acme-challenge/" + chlng.Token
// The handler validates the HOST header and request type.
// For validation it then writes the token the server returned with the challenge
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, domain) && r.Method == "GET" {
w.Header().Add("Content-Type", "text/plain")
w.Write([]byte(keyAuth))
logf("[INFO] Served key authentication")
} else {
logf("[INFO] Received request for domain %s with method %s", r.Host, r.Method)
w.Write([]byte("TEST"))
}
})
go http.Serve(listener, nil)
return validate(s.jws, chlng.URI, challenge{Resource: "challenge", Type: chlng.Type, Token: chlng.Token, KeyAuthorization: keyAuth})
}