1
0

reverseproxy.go 8.1 KB

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