acme.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "math/rand"
  7. "net/http"
  8. "regexp"
  9. "strconv"
  10. "time"
  11. "imuslab.com/zoraxy/mod/acme"
  12. "imuslab.com/zoraxy/mod/dynamicproxy"
  13. )
  14. /*
  15. acme.go
  16. This script handle special routing required for acme auto cert renew functions
  17. */
  18. // Helper function to generate a random port above a specified value
  19. func getRandomPort(minPort int) int {
  20. return rand.Intn(65535-minPort) + minPort
  21. }
  22. // init the new ACME instance
  23. func initACME() *acme.ACMEHandler {
  24. log.Println("Start initializing ACME")
  25. rand.Seed(time.Now().UnixNano())
  26. // Generate a random port above 30000
  27. port := getRandomPort(30000)
  28. // Check if the port is already in use
  29. for acme.IsPortInUse(port) {
  30. port = getRandomPort(30000)
  31. }
  32. return acme.NewACME("[email protected]", "https://acme-staging-v02.api.letsencrypt.org/directory", strconv.Itoa(port))
  33. }
  34. // create the special routing rule for ACME
  35. func acmeRegisterSpecialRoutingRule() {
  36. log.Println("Assigned temporary port:" + acmeHandler.Getport())
  37. err := dynamicProxyRouter.AddRoutingRules(&dynamicproxy.RoutingRule{
  38. ID: "acme-autorenew",
  39. MatchRule: func(r *http.Request) bool {
  40. found, _ := regexp.MatchString("/.well-known/*", r.RequestURI)
  41. return found
  42. },
  43. RoutingHandler: func(w http.ResponseWriter, r *http.Request) {
  44. req, err := http.NewRequest(http.MethodGet, "http://localhost:"+acmeHandler.Getport()+r.RequestURI, nil)
  45. req.Host = r.Host
  46. if err != nil {
  47. fmt.Printf("client: could not create request: %s\n", err)
  48. }
  49. res, err := http.DefaultClient.Do(req)
  50. if err != nil {
  51. fmt.Printf("client: error making http request: %s\n", err)
  52. }
  53. resBody, err := ioutil.ReadAll(res.Body)
  54. if err != nil {
  55. fmt.Printf("error reading: %s\n", err)
  56. }
  57. w.Write(resBody)
  58. },
  59. Enabled: true,
  60. })
  61. if err != nil {
  62. log.Println("[Err] " + err.Error())
  63. }
  64. }