reverseproxy.go 8.0 KB

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