Browse Source

added handler

Toby Chui 1 year ago
parent
commit
a1f451f81f
7 changed files with 105 additions and 6 deletions
  1. 2 2
      acme.go
  2. 5 0
      api.go
  3. 1 0
      main.go
  4. 2 3
      mod/acme/acme.go
  5. 17 0
      mod/utils/utils.go
  6. 77 0
      mod/webserv/handler.go
  7. 1 1
      mod/webserv/middleware.go

+ 2 - 2
acme.go

@@ -2,7 +2,7 @@ package main
 
 import (
 	"fmt"
-	"io/ioutil"
+	"io"
 	"log"
 	"math/rand"
 	"net/http"
@@ -65,7 +65,7 @@ func acmeRegisterSpecialRoutingRule() {
 				return
 			}
 
-			resBody, err := ioutil.ReadAll(res.Body)
+			resBody, err := io.ReadAll(res.Body)
 			defer res.Body.Close()
 			if err != nil {
 				fmt.Printf("error reading: %s\n", err)

+ 5 - 0
api.go

@@ -169,6 +169,11 @@ func initAPIs() {
 	authRouter.HandleFunc("/api/acme/autoRenew/renewNow", acmeAutoRenewer.HandleRenewNow)
 	authRouter.HandleFunc("/api/acme/wizard", acmewizard.HandleGuidedStepCheck) //ACME Wizard
 
+	//Static Web Server
+	//authRouter.HandleFunc("/api/webserv/status")
+	if *allowWebFileManager {
+
+	}
 	//Others
 	http.HandleFunc("/api/info/x", HandleZoraxyInfo)
 	authRouter.HandleFunc("/api/info/geoip", HandleGeoIpLookup)

+ 1 - 0
main.go

@@ -43,6 +43,7 @@ var ztAPIPort = flag.Int("ztport", 9993, "ZeroTier controller API port")
 var acmeAutoRenewInterval = flag.Int("autorenew", 86400, "ACME auto TLS/SSL certificate renew check interval (seconds)")
 var enableHighSpeedGeoIPLookup = flag.Bool("fastgeoip", false, "Enable high speed geoip lookup, require 1GB extra memory (Not recommend for low end devices)")
 var staticWebServerRoot = flag.String("webroot", "./www", "Static web server root folder. Only allow chnage in start paramters")
+var allowWebFileManager = flag.Bool("webfm", true, "Enable web file manager for static web server root folder")
 
 var (
 	name        = "Zoraxy"

+ 2 - 3
mod/acme/acme.go

@@ -10,7 +10,6 @@ import (
 	"encoding/json"
 	"encoding/pem"
 	"fmt"
-	"io/ioutil"
 	"log"
 	"net"
 	"net/http"
@@ -164,12 +163,12 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
 
 	// Each certificate comes back with the cert bytes, the bytes of the client's
 	// private key, and a certificate URL.
-	err = ioutil.WriteFile("./conf/certs/"+certificateName+".crt", certificates.Certificate, 0777)
+	err = os.WriteFile("./conf/certs/"+certificateName+".crt", certificates.Certificate, 0777)
 	if err != nil {
 		log.Println(err)
 		return false, err
 	}
-	err = ioutil.WriteFile("./conf/certs/"+certificateName+".key", certificates.PrivateKey, 0777)
+	err = os.WriteFile("./conf/certs/"+certificateName+".key", certificates.PrivateKey, 0777)
 	if err != nil {
 		log.Println(err)
 		return false, err

+ 17 - 0
mod/utils/utils.go

@@ -5,6 +5,7 @@ import (
 	"log"
 	"net/http"
 	"os"
+	"strconv"
 	"strings"
 	"time"
 )
@@ -76,6 +77,22 @@ func PostBool(r *http.Request, key string) (bool, error) {
 	return false, errors.New("invalid boolean given")
 }
 
+// Get POST paramter as int
+func PostInt(r *http.Request, key string) (int, error) {
+	x, err := PostPara(r, key)
+	if err != nil {
+		return 0, err
+	}
+
+	x = strings.TrimSpace(x)
+	rx, err := strconv.Atoi(x)
+	if err != nil {
+		return 0, err
+	}
+
+	return rx, nil
+}
+
 func FileExists(filename string) bool {
 	_, err := os.Stat(filename)
 	if os.IsNotExist(err) {

+ 77 - 0
mod/webserv/handler.go

@@ -1,5 +1,13 @@
 package webserv
 
+import (
+	"encoding/json"
+	"net/http"
+	"strconv"
+
+	"imuslab.com/zoraxy/mod/utils"
+)
+
 /*
 	Handler.go
 
@@ -7,3 +15,72 @@ package webserv
 	web server is directly listening to the TCP port
 	handlers in this script are for setting change only
 */
+
+type StaticWebServerStatus struct {
+	ListeningPort          int
+	EnableDirectoryListing bool
+	WebRoot                string
+	Running                bool
+}
+
+// Handle getting current static web server status
+func (ws *WebServer) HandleGetStatus(w http.ResponseWriter, r *http.Request) {
+	listeningPortInt, _ := strconv.Atoi(ws.option.Port)
+	currentStatus := StaticWebServerStatus{
+		ListeningPort:          listeningPortInt,
+		EnableDirectoryListing: ws.option.EnableDirectoryListing,
+		WebRoot:                ws.option.WebRoot,
+		Running:                ws.isRunning,
+	}
+
+	js, _ := json.Marshal(currentStatus)
+	utils.SendJSONResponse(w, string(js))
+}
+
+// Handle request for starting the static web server
+func (ws *WebServer) HandleStartServer(w http.ResponseWriter, r *http.Request) {
+	err := ws.Start()
+	if err != nil {
+		utils.SendErrorResponse(w, err.Error())
+		return
+	}
+	utils.SendOK(w)
+}
+
+// Handle request for stopping the static web server
+func (ws *WebServer) HandleStopServer(w http.ResponseWriter, r *http.Request) {
+	err := ws.Stop()
+	if err != nil {
+		utils.SendErrorResponse(w, err.Error())
+		return
+	}
+	utils.SendOK(w)
+}
+
+// Handle change server listening port request
+func (ws *WebServer) HandlePortChange(w http.ResponseWriter, r *http.Request) {
+	newPort, err := utils.PostInt(r, "port")
+	if err != nil {
+		utils.SendErrorResponse(w, "invalid port number given")
+		return
+	}
+
+	err = ws.ChangePort(strconv.Itoa(newPort))
+	if err != nil {
+		utils.SendErrorResponse(w, err.Error())
+		return
+	}
+	utils.SendOK(w)
+}
+
+// Change enable directory listing settings
+func (ws *WebServer) SetEnableDirectoryListing(w http.ResponseWriter, r *http.Request) {
+	enableList, err := utils.PostBool(r, "enable")
+	if err != nil {
+		utils.SendErrorResponse(w, "invalid setting given")
+		return
+	}
+
+	ws.option.EnableDirectoryListing = enableList
+	utils.SendOK(w)
+}

+ 1 - 1
mod/webserv/middleware.go

@@ -22,7 +22,7 @@ func (ws *WebServer) resolveFileDiskPath(requestPath string) string {
 // File server middleware to handle directory listing (and future expansion)
 func (ws *WebServer) fsMiddleware(h http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		if ws.option.EnableDirectoryListing {
+		if !ws.option.EnableDirectoryListing {
 			if strings.HasSuffix(r.URL.Path, "/") {
 				//This is a folder. Let check if index exists
 				if utils.FileExists(filepath.Join(ws.resolveFileDiskPath(r.URL.Path), "index.html")) {