reverseproxy.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. //Check if it is loopback
  96. if dynamicProxyRouter.IsProxiedSubdomain(r) {
  97. //Loopback routing. Turning it off will make the user lost control
  98. //of the whole system. Do not allow shutdown
  99. utils.SendErrorResponse(w, "Unable to shutdown in loopback rp mode. Remove proxy rules for management interface and retry.")
  100. return
  101. }
  102. err := dynamicProxyRouter.StopProxyService()
  103. if err != nil {
  104. utils.SendErrorResponse(w, err.Error())
  105. return
  106. }
  107. }
  108. utils.SendOK(w)
  109. }
  110. func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
  111. eptype, err := utils.PostPara(r, "type") //Support root, vdir and subd
  112. if err != nil {
  113. utils.SendErrorResponse(w, "type not defined")
  114. return
  115. }
  116. endpoint, err := utils.PostPara(r, "ep")
  117. if err != nil {
  118. utils.SendErrorResponse(w, "endpoint not defined")
  119. return
  120. }
  121. tls, _ := utils.PostPara(r, "tls")
  122. if tls == "" {
  123. tls = "false"
  124. }
  125. useTLS := (tls == "true")
  126. rootname := ""
  127. if eptype == "vdir" {
  128. vdir, err := utils.PostPara(r, "rootname")
  129. if err != nil {
  130. utils.SendErrorResponse(w, "vdir not defined")
  131. return
  132. }
  133. if !strings.HasPrefix(vdir, "/") {
  134. vdir = "/" + vdir
  135. }
  136. rootname = vdir
  137. dynamicProxyRouter.AddVirtualDirectoryProxyService(vdir, endpoint, useTLS)
  138. } else if eptype == "subd" {
  139. subdomain, err := utils.PostPara(r, "rootname")
  140. if err != nil {
  141. utils.SendErrorResponse(w, "subdomain not defined")
  142. return
  143. }
  144. rootname = subdomain
  145. dynamicProxyRouter.AddSubdomainRoutingService(subdomain, endpoint, useTLS)
  146. } else if eptype == "root" {
  147. rootname = "root"
  148. dynamicProxyRouter.SetRootProxy(endpoint, useTLS)
  149. } else {
  150. //Invalid eptype
  151. utils.SendErrorResponse(w, "Invalid endpoint type")
  152. return
  153. }
  154. //Save it
  155. SaveReverseProxyConfig(eptype, rootname, endpoint, useTLS)
  156. utils.SendOK(w)
  157. }
  158. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  159. ep, err := utils.GetPara(r, "ep")
  160. if err != nil {
  161. utils.SendErrorResponse(w, "Invalid ep given")
  162. }
  163. ptype, err := utils.PostPara(r, "ptype")
  164. if err != nil {
  165. utils.SendErrorResponse(w, "Invalid ptype given")
  166. }
  167. err = dynamicProxyRouter.RemoveProxy(ptype, ep)
  168. if err != nil {
  169. utils.SendErrorResponse(w, err.Error())
  170. }
  171. RemoveReverseProxyConfig(ep)
  172. utils.SendOK(w)
  173. }
  174. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  175. js, _ := json.Marshal(dynamicProxyRouter)
  176. utils.SendJSONResponse(w, string(js))
  177. }
  178. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  179. eptype, err := utils.PostPara(r, "type") //Support root, vdir and subd
  180. if err != nil {
  181. utils.SendErrorResponse(w, "type not defined")
  182. return
  183. }
  184. if eptype == "vdir" {
  185. results := []*dynamicproxy.ProxyEndpoint{}
  186. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  187. results = append(results, value.(*dynamicproxy.ProxyEndpoint))
  188. return true
  189. })
  190. sort.Slice(results, func(i, j int) bool {
  191. return results[i].Domain < results[j].Domain
  192. })
  193. js, _ := json.Marshal(results)
  194. utils.SendJSONResponse(w, string(js))
  195. } else if eptype == "subd" {
  196. results := []*dynamicproxy.SubdomainEndpoint{}
  197. dynamicProxyRouter.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  198. results = append(results, value.(*dynamicproxy.SubdomainEndpoint))
  199. return true
  200. })
  201. sort.Slice(results, func(i, j int) bool {
  202. return results[i].MatchingDomain < results[j].MatchingDomain
  203. })
  204. js, _ := json.Marshal(results)
  205. utils.SendJSONResponse(w, string(js))
  206. } else if eptype == "root" {
  207. js, _ := json.Marshal(dynamicProxyRouter.Root)
  208. utils.SendJSONResponse(w, string(js))
  209. } else {
  210. utils.SendErrorResponse(w, "Invalid type given")
  211. }
  212. }
  213. // Handle https redirect
  214. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  215. useRedirect, err := utils.GetPara(r, "set")
  216. if err != nil {
  217. currentRedirectToHttps := false
  218. //Load the current status
  219. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  220. if err != nil {
  221. utils.SendErrorResponse(w, err.Error())
  222. return
  223. }
  224. js, _ := json.Marshal(currentRedirectToHttps)
  225. utils.SendJSONResponse(w, string(js))
  226. } else {
  227. if useRedirect == "true" {
  228. sysdb.Write("settings", "redirect", true)
  229. log.Println("Updating force HTTPS redirection to true")
  230. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  231. } else if useRedirect == "false" {
  232. sysdb.Write("settings", "redirect", false)
  233. log.Println("Updating force HTTPS redirection to false")
  234. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  235. }
  236. utils.SendOK(w)
  237. }
  238. }
  239. //Handle checking if the current user is accessing via the reverse proxied interface
  240. //Of the management interface.
  241. func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
  242. isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
  243. js, _ := json.Marshal(isProxied)
  244. utils.SendJSONResponse(w, string(js))
  245. }
  246. // Handle incoming port set. Change the current proxy incoming port
  247. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  248. newIncomingPort, err := utils.PostPara(r, "incoming")
  249. if err != nil {
  250. utils.SendErrorResponse(w, "invalid incoming port given")
  251. return
  252. }
  253. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  254. if err != nil {
  255. utils.SendErrorResponse(w, "invalid incoming port given")
  256. return
  257. }
  258. //Stop and change the setting of the reverse proxy service
  259. if dynamicProxyRouter.Running {
  260. dynamicProxyRouter.StopProxyService()
  261. dynamicProxyRouter.Option.Port = newIncomingPortInt
  262. dynamicProxyRouter.StartProxyService()
  263. } else {
  264. //Only change setting but not starting the proxy service
  265. dynamicProxyRouter.Option.Port = newIncomingPortInt
  266. }
  267. sysdb.Write("settings", "inbound", newIncomingPortInt)
  268. utils.SendOK(w)
  269. }