1
0

reverseproxy.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package main
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "path/filepath"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "imuslab.com/Zoraxy/mod/dynamicproxy"
  12. "imuslab.com/Zoraxy/mod/utils"
  13. )
  14. var (
  15. dynamicProxyRouter *dynamicproxy.Router
  16. )
  17. // Add user customizable reverse proxy
  18. func ReverseProxtInit() {
  19. inboundPort := 80
  20. if sysdb.KeyExists("settings", "inbound") {
  21. sysdb.Read("settings", "inbound", &inboundPort)
  22. log.Println("Serving inbound port ", inboundPort)
  23. } else {
  24. log.Println("Inbound port not set. Using default (80)")
  25. }
  26. useTls := false
  27. sysdb.Read("settings", "usetls", &useTls)
  28. if useTls {
  29. log.Println("TLS mode enabled. Serving proxxy request with TLS")
  30. } else {
  31. log.Println("TLS mode disabled. Serving proxy request with plain http")
  32. }
  33. forceHttpsRedirect := false
  34. sysdb.Read("settings", "redirect", &forceHttpsRedirect)
  35. if forceHttpsRedirect {
  36. log.Println("Force HTTPS mode enabled")
  37. } else {
  38. log.Println("Force HTTPS mode disabled")
  39. }
  40. dprouter, err := dynamicproxy.NewDynamicProxy(dynamicproxy.RouterOption{
  41. Port: inboundPort,
  42. UseTls: useTls,
  43. ForceHttpsRedirect: forceHttpsRedirect,
  44. TlsManager: tlsCertManager,
  45. RedirectRuleTable: redirectTable,
  46. GeodbStore: geodbStore,
  47. StatisticCollector: statisticCollector,
  48. })
  49. if err != nil {
  50. log.Println(err.Error())
  51. return
  52. }
  53. dynamicProxyRouter = dprouter
  54. //Load all conf from files
  55. confs, _ := filepath.Glob("./conf/*.config")
  56. for _, conf := range confs {
  57. record, err := LoadReverseProxyConfig(conf)
  58. if err != nil {
  59. log.Println("Failed to load "+filepath.Base(conf), err.Error())
  60. return
  61. }
  62. if record.ProxyType == "root" {
  63. dynamicProxyRouter.SetRootProxy(record.ProxyTarget, record.UseTLS)
  64. } else if record.ProxyType == "subd" {
  65. dynamicProxyRouter.AddSubdomainRoutingService(record.Rootname, record.ProxyTarget, record.UseTLS)
  66. } else if record.ProxyType == "vdir" {
  67. dynamicProxyRouter.AddVirtualDirectoryProxyService(record.Rootname, record.ProxyTarget, record.UseTLS)
  68. } else {
  69. log.Println("Unsupported endpoint type: " + record.ProxyType + ". Skipping " + filepath.Base(conf))
  70. }
  71. }
  72. /*
  73. dynamicProxyRouter.SetRootProxy("192.168.0.107:8080", false)
  74. dynamicProxyRouter.AddSubdomainRoutingService("aroz.localhost", "192.168.0.107:8080/private/AOB/", false)
  75. dynamicProxyRouter.AddSubdomainRoutingService("loopback.localhost", "localhost:8080", false)
  76. dynamicProxyRouter.AddSubdomainRoutingService("git.localhost", "mc.alanyeung.co:3000", false)
  77. dynamicProxyRouter.AddVirtualDirectoryProxyService("/git/server/", "mc.alanyeung.co:3000", false)
  78. */
  79. //Start Service
  80. //Not sure why but delay must be added if you have another
  81. //reverse proxy server in front of this service
  82. time.Sleep(300 * time.Millisecond)
  83. dynamicProxyRouter.StartProxyService()
  84. log.Println("Dynamic Reverse Proxy service started")
  85. }
  86. func ReverseProxyHandleOnOff(w http.ResponseWriter, r *http.Request) {
  87. enable, _ := utils.PostPara(r, "enable") //Support root, vdir and subd
  88. if enable == "true" {
  89. err := dynamicProxyRouter.StartProxyService()
  90. if err != nil {
  91. utils.SendErrorResponse(w, err.Error())
  92. return
  93. }
  94. } else {
  95. err := dynamicProxyRouter.StopProxyService()
  96. if err != nil {
  97. utils.SendErrorResponse(w, err.Error())
  98. return
  99. }
  100. }
  101. utils.SendOK(w)
  102. }
  103. func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
  104. eptype, err := utils.PostPara(r, "type") //Support root, vdir and subd
  105. if err != nil {
  106. utils.SendErrorResponse(w, "type not defined")
  107. return
  108. }
  109. endpoint, err := utils.PostPara(r, "ep")
  110. if err != nil {
  111. utils.SendErrorResponse(w, "endpoint not defined")
  112. return
  113. }
  114. tls, _ := utils.PostPara(r, "tls")
  115. if tls == "" {
  116. tls = "false"
  117. }
  118. useTLS := (tls == "true")
  119. rootname := ""
  120. if eptype == "vdir" {
  121. vdir, err := utils.PostPara(r, "rootname")
  122. if err != nil {
  123. utils.SendErrorResponse(w, "vdir not defined")
  124. return
  125. }
  126. if !strings.HasPrefix(vdir, "/") {
  127. vdir = "/" + vdir
  128. }
  129. rootname = vdir
  130. dynamicProxyRouter.AddVirtualDirectoryProxyService(vdir, endpoint, useTLS)
  131. } else if eptype == "subd" {
  132. subdomain, err := utils.PostPara(r, "rootname")
  133. if err != nil {
  134. utils.SendErrorResponse(w, "subdomain not defined")
  135. return
  136. }
  137. rootname = subdomain
  138. dynamicProxyRouter.AddSubdomainRoutingService(subdomain, endpoint, useTLS)
  139. } else if eptype == "root" {
  140. rootname = "root"
  141. dynamicProxyRouter.SetRootProxy(endpoint, useTLS)
  142. } else {
  143. //Invalid eptype
  144. utils.SendErrorResponse(w, "Invalid endpoint type")
  145. return
  146. }
  147. //Save it
  148. SaveReverseProxyConfig(eptype, rootname, endpoint, useTLS)
  149. utils.SendOK(w)
  150. }
  151. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  152. ep, err := utils.GetPara(r, "ep")
  153. if err != nil {
  154. utils.SendErrorResponse(w, "Invalid ep given")
  155. }
  156. ptype, err := utils.PostPara(r, "ptype")
  157. if err != nil {
  158. utils.SendErrorResponse(w, "Invalid ptype given")
  159. }
  160. err = dynamicProxyRouter.RemoveProxy(ptype, ep)
  161. if err != nil {
  162. utils.SendErrorResponse(w, err.Error())
  163. }
  164. RemoveReverseProxyConfig(ep)
  165. utils.SendOK(w)
  166. }
  167. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  168. js, _ := json.Marshal(dynamicProxyRouter)
  169. utils.SendJSONResponse(w, string(js))
  170. }
  171. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  172. eptype, err := utils.PostPara(r, "type") //Support root, vdir and subd
  173. if err != nil {
  174. utils.SendErrorResponse(w, "type not defined")
  175. return
  176. }
  177. if eptype == "vdir" {
  178. results := []*dynamicproxy.ProxyEndpoint{}
  179. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  180. results = append(results, value.(*dynamicproxy.ProxyEndpoint))
  181. return true
  182. })
  183. sort.Slice(results, func(i, j int) bool {
  184. return results[i].Domain < results[j].Domain
  185. })
  186. js, _ := json.Marshal(results)
  187. utils.SendJSONResponse(w, string(js))
  188. } else if eptype == "subd" {
  189. results := []*dynamicproxy.SubdomainEndpoint{}
  190. dynamicProxyRouter.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  191. results = append(results, value.(*dynamicproxy.SubdomainEndpoint))
  192. return true
  193. })
  194. sort.Slice(results, func(i, j int) bool {
  195. return results[i].MatchingDomain < results[j].MatchingDomain
  196. })
  197. js, _ := json.Marshal(results)
  198. utils.SendJSONResponse(w, string(js))
  199. } else if eptype == "root" {
  200. js, _ := json.Marshal(dynamicProxyRouter.Root)
  201. utils.SendJSONResponse(w, string(js))
  202. } else {
  203. utils.SendErrorResponse(w, "Invalid type given")
  204. }
  205. }
  206. // Handle https redirect
  207. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  208. useRedirect, err := utils.GetPara(r, "set")
  209. if err != nil {
  210. currentRedirectToHttps := false
  211. //Load the current status
  212. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  213. if err != nil {
  214. utils.SendErrorResponse(w, err.Error())
  215. return
  216. }
  217. js, _ := json.Marshal(currentRedirectToHttps)
  218. utils.SendJSONResponse(w, string(js))
  219. } else {
  220. if useRedirect == "true" {
  221. sysdb.Write("settings", "redirect", true)
  222. log.Println("Updating force HTTPS redirection to true")
  223. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  224. } else if useRedirect == "false" {
  225. sysdb.Write("settings", "redirect", false)
  226. log.Println("Updating force HTTPS redirection to false")
  227. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  228. }
  229. utils.SendOK(w)
  230. }
  231. }
  232. // Handle incoming port set. Change the current proxy incoming port
  233. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  234. newIncomingPort, err := utils.PostPara(r, "incoming")
  235. if err != nil {
  236. utils.SendErrorResponse(w, "invalid incoming port given")
  237. return
  238. }
  239. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  240. if err != nil {
  241. utils.SendErrorResponse(w, "invalid incoming port given")
  242. return
  243. }
  244. //Stop and change the setting of the reverse proxy service
  245. if dynamicProxyRouter.Running {
  246. dynamicProxyRouter.StopProxyService()
  247. dynamicProxyRouter.Option.Port = newIncomingPortInt
  248. dynamicProxyRouter.StartProxyService()
  249. } else {
  250. //Only change setting but not starting the proxy service
  251. dynamicProxyRouter.Option.Port = newIncomingPortInt
  252. }
  253. sysdb.Write("settings", "inbound", newIncomingPortInt)
  254. utils.SendOK(w)
  255. }