reverseproxy.go 9.5 KB

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