123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- package main
- import (
- "fmt"
- "io/ioutil"
- "log"
- "math/rand"
- "net/http"
- "regexp"
- "strconv"
- "time"
- "imuslab.com/zoraxy/mod/acme"
- "imuslab.com/zoraxy/mod/dynamicproxy"
- "imuslab.com/zoraxy/mod/utils"
- )
- func getRandomPort(minPort int) int {
- return rand.Intn(65535-minPort) + minPort
- }
- func initACME() *acme.ACMEHandler {
- log.Println("Starting ACME handler")
- rand.Seed(time.Now().UnixNano())
-
- port := getRandomPort(30000)
-
- for acme.IsPortInUse(port) {
- port = getRandomPort(30000)
- }
- return acme.NewACME("https://acme-staging-v02.api.letsencrypt.org/directory", strconv.Itoa(port))
- }
- func acmeRegisterSpecialRoutingRule() {
- log.Println("Assigned temporary port:" + acmeHandler.Getport())
- err := dynamicProxyRouter.AddRoutingRules(&dynamicproxy.RoutingRule{
- ID: "acme-autorenew",
- MatchRule: func(r *http.Request) bool {
- found, _ := regexp.MatchString("/.well-known/acme-challenge/*", r.RequestURI)
- return found
- },
- RoutingHandler: func(w http.ResponseWriter, r *http.Request) {
- req, err := http.NewRequest(http.MethodGet, "http://localhost:"+acmeHandler.Getport()+r.RequestURI, nil)
- req.Host = r.Host
- if err != nil {
- fmt.Printf("client: could not create request: %s\n", err)
- return
- }
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- fmt.Printf("client: error making http request: %s\n", err)
- return
- }
- resBody, err := ioutil.ReadAll(res.Body)
- defer res.Body.Close()
- if err != nil {
- fmt.Printf("error reading: %s\n", err)
- return
- }
- w.Write(resBody)
- },
- Enabled: true,
- UseSystemAccessControl: false,
- })
- if err != nil {
- log.Println("[Err] " + err.Error())
- }
- }
- func AcmeCheckAndHandleRenewCertificate(w http.ResponseWriter, r *http.Request) {
- isForceHttpsRedirectEnabledOriginally := false
- if dynamicProxyRouter.Option.Port == 443 {
-
- if !dynamicProxyRouter.Option.ForceHttpsRedirect {
- log.Println("Temporary enabling HTTP to HTTPS redirect for ACME certificate renew requests")
- dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
- } else {
-
- isForceHttpsRedirectEnabledOriginally = true
- }
- } else if dynamicProxyRouter.Option.Port == 80 {
-
- } else {
-
- utils.SendErrorResponse(w, "ACME renew only support web server listening on port 80 (http) or 443 (https)")
- }
-
- acmeHandler.HandleRenewCertificate(w, r)
- if dynamicProxyRouter.Option.Port == 443 {
- if !isForceHttpsRedirectEnabledOriginally {
-
- log.Println("Restoring HTTP to HTTPS redirect settings")
- dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
- }
- }
- }
|