reverseproxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. //Vdir must start with /
  146. if !strings.HasPrefix(vdir, "/") {
  147. vdir = "/" + vdir
  148. }
  149. rootname = vdir
  150. dynamicProxyRouter.AddVirtualDirectoryProxyService(vdir, endpoint, useTLS)
  151. } else if eptype == "subd" {
  152. subdomain, err := utils.PostPara(r, "rootname")
  153. if err != nil {
  154. utils.SendErrorResponse(w, "subdomain not defined")
  155. return
  156. }
  157. rootname = subdomain
  158. dynamicProxyRouter.AddSubdomainRoutingService(subdomain, endpoint, useTLS)
  159. } else if eptype == "root" {
  160. rootname = "root"
  161. dynamicProxyRouter.SetRootProxy(endpoint, useTLS)
  162. } else {
  163. //Invalid eptype
  164. utils.SendErrorResponse(w, "Invalid endpoint type")
  165. return
  166. }
  167. //Save it
  168. SaveReverseProxyConfig(eptype, rootname, endpoint, useTLS)
  169. //Update utm if exists
  170. if uptimeMonitor != nil {
  171. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  172. uptimeMonitor.CleanRecords()
  173. }
  174. utils.SendOK(w)
  175. }
  176. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  177. ep, err := utils.GetPara(r, "ep")
  178. if err != nil {
  179. utils.SendErrorResponse(w, "Invalid ep given")
  180. }
  181. ptype, err := utils.PostPara(r, "ptype")
  182. if err != nil {
  183. utils.SendErrorResponse(w, "Invalid ptype given")
  184. }
  185. err = dynamicProxyRouter.RemoveProxy(ptype, ep)
  186. if err != nil {
  187. utils.SendErrorResponse(w, err.Error())
  188. }
  189. RemoveReverseProxyConfig(ep)
  190. //Update utm if exists
  191. if uptimeMonitor != nil {
  192. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  193. uptimeMonitor.CleanRecords()
  194. }
  195. utils.SendOK(w)
  196. }
  197. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  198. js, _ := json.Marshal(dynamicProxyRouter)
  199. utils.SendJSONResponse(w, string(js))
  200. }
  201. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  202. eptype, err := utils.PostPara(r, "type") //Support root, vdir and subd
  203. if err != nil {
  204. utils.SendErrorResponse(w, "type not defined")
  205. return
  206. }
  207. if eptype == "vdir" {
  208. results := []*dynamicproxy.ProxyEndpoint{}
  209. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  210. results = append(results, value.(*dynamicproxy.ProxyEndpoint))
  211. return true
  212. })
  213. sort.Slice(results, func(i, j int) bool {
  214. return results[i].Domain < results[j].Domain
  215. })
  216. js, _ := json.Marshal(results)
  217. utils.SendJSONResponse(w, string(js))
  218. } else if eptype == "subd" {
  219. results := []*dynamicproxy.SubdomainEndpoint{}
  220. dynamicProxyRouter.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  221. results = append(results, value.(*dynamicproxy.SubdomainEndpoint))
  222. return true
  223. })
  224. sort.Slice(results, func(i, j int) bool {
  225. return results[i].MatchingDomain < results[j].MatchingDomain
  226. })
  227. js, _ := json.Marshal(results)
  228. utils.SendJSONResponse(w, string(js))
  229. } else if eptype == "root" {
  230. js, _ := json.Marshal(dynamicProxyRouter.Root)
  231. utils.SendJSONResponse(w, string(js))
  232. } else {
  233. utils.SendErrorResponse(w, "Invalid type given")
  234. }
  235. }
  236. // Handle https redirect
  237. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  238. useRedirect, err := utils.GetPara(r, "set")
  239. if err != nil {
  240. currentRedirectToHttps := false
  241. //Load the current status
  242. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  243. if err != nil {
  244. utils.SendErrorResponse(w, err.Error())
  245. return
  246. }
  247. js, _ := json.Marshal(currentRedirectToHttps)
  248. utils.SendJSONResponse(w, string(js))
  249. } else {
  250. if useRedirect == "true" {
  251. sysdb.Write("settings", "redirect", true)
  252. log.Println("Updating force HTTPS redirection to true")
  253. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  254. } else if useRedirect == "false" {
  255. sysdb.Write("settings", "redirect", false)
  256. log.Println("Updating force HTTPS redirection to false")
  257. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  258. }
  259. utils.SendOK(w)
  260. }
  261. }
  262. // Handle checking if the current user is accessing via the reverse proxied interface
  263. // Of the management interface.
  264. func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
  265. isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
  266. js, _ := json.Marshal(isProxied)
  267. utils.SendJSONResponse(w, string(js))
  268. }
  269. // Handle incoming port set. Change the current proxy incoming port
  270. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  271. newIncomingPort, err := utils.PostPara(r, "incoming")
  272. if err != nil {
  273. utils.SendErrorResponse(w, "invalid incoming port given")
  274. return
  275. }
  276. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  277. if err != nil {
  278. utils.SendErrorResponse(w, "invalid incoming port given")
  279. return
  280. }
  281. //Check if it is identical as proxy root (recursion!)
  282. proxyRoot := strings.TrimSuffix(dynamicProxyRouter.Root.Domain, "/")
  283. if strings.HasPrefix(proxyRoot, "localhost:"+strconv.Itoa(newIncomingPortInt)) || strings.HasPrefix(proxyRoot, "127.0.0.1:"+strconv.Itoa(newIncomingPortInt)) {
  284. //Listening port is same as proxy root
  285. //Not allow recursive settings
  286. utils.SendErrorResponse(w, "Recursive listening port! Check your proxy root settings.")
  287. return
  288. }
  289. //Stop and change the setting of the reverse proxy service
  290. if dynamicProxyRouter.Running {
  291. dynamicProxyRouter.StopProxyService()
  292. dynamicProxyRouter.Option.Port = newIncomingPortInt
  293. dynamicProxyRouter.StartProxyService()
  294. } else {
  295. //Only change setting but not starting the proxy service
  296. dynamicProxyRouter.Option.Port = newIncomingPortInt
  297. }
  298. sysdb.Write("settings", "inbound", newIncomingPortInt)
  299. utils.SendOK(w)
  300. }