endpoints.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package dynamicproxy
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strings"
  6. "golang.org/x/text/cases"
  7. "golang.org/x/text/language"
  8. "imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
  9. "imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
  10. )
  11. /*
  12. endpoint.go
  13. author: tobychui
  14. This script handle the proxy endpoint object actions
  15. so proxyEndpoint can be handled like a proper oop object
  16. Most of the functions are implemented in dynamicproxy.go
  17. */
  18. /*
  19. User Defined Header Functions
  20. */
  21. // Check if a user define header exists in this endpoint, ignore case
  22. func (ep *ProxyEndpoint) UserDefinedHeaderExists(key string) bool {
  23. endpointProxyRewriteRules := GetDefaultHeaderRewriteRules()
  24. if ep.HeaderRewriteRules != nil {
  25. endpointProxyRewriteRules = ep.HeaderRewriteRules
  26. }
  27. for _, header := range endpointProxyRewriteRules.UserDefinedHeaders {
  28. if strings.EqualFold(header.Key, key) {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. // Remvoe a user defined header from the list
  35. func (ep *ProxyEndpoint) RemoveUserDefinedHeader(key string) error {
  36. newHeaderList := []*rewrite.UserDefinedHeader{}
  37. if ep.HeaderRewriteRules == nil {
  38. ep.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
  39. }
  40. for _, header := range ep.HeaderRewriteRules.UserDefinedHeaders {
  41. if !strings.EqualFold(header.Key, key) {
  42. newHeaderList = append(newHeaderList, header)
  43. }
  44. }
  45. ep.HeaderRewriteRules.UserDefinedHeaders = newHeaderList
  46. return nil
  47. }
  48. // Add a user defined header to the list, duplicates will be automatically removed
  49. func (ep *ProxyEndpoint) AddUserDefinedHeader(newHeaderRule *rewrite.UserDefinedHeader) error {
  50. if ep.UserDefinedHeaderExists(newHeaderRule.Key) {
  51. ep.RemoveUserDefinedHeader(newHeaderRule.Key)
  52. }
  53. if ep.HeaderRewriteRules == nil {
  54. ep.HeaderRewriteRules = GetDefaultHeaderRewriteRules()
  55. }
  56. newHeaderRule.Key = cases.Title(language.Und, cases.NoLower).String(newHeaderRule.Key)
  57. ep.HeaderRewriteRules.UserDefinedHeaders = append(ep.HeaderRewriteRules.UserDefinedHeaders, newHeaderRule)
  58. return nil
  59. }
  60. /*
  61. Virtual Directory Functions
  62. */
  63. // Get virtual directory handler from given URI
  64. func (ep *ProxyEndpoint) GetVirtualDirectoryHandlerFromRequestURI(requestURI string) *VirtualDirectoryEndpoint {
  65. for _, vdir := range ep.VirtualDirectories {
  66. if strings.HasPrefix(requestURI, vdir.MatchingPath) {
  67. thisVdir := vdir
  68. return thisVdir
  69. }
  70. }
  71. return nil
  72. }
  73. // Get virtual directory handler by matching path (exact match required)
  74. func (ep *ProxyEndpoint) GetVirtualDirectoryRuleByMatchingPath(matchingPath string) *VirtualDirectoryEndpoint {
  75. for _, vdir := range ep.VirtualDirectories {
  76. if vdir.MatchingPath == matchingPath {
  77. thisVdir := vdir
  78. return thisVdir
  79. }
  80. }
  81. return nil
  82. }
  83. // Delete a vdir rule by its matching path
  84. func (ep *ProxyEndpoint) RemoveVirtualDirectoryRuleByMatchingPath(matchingPath string) error {
  85. entryFound := false
  86. newVirtualDirectoryList := []*VirtualDirectoryEndpoint{}
  87. for _, vdir := range ep.VirtualDirectories {
  88. if vdir.MatchingPath == matchingPath {
  89. entryFound = true
  90. } else {
  91. newVirtualDirectoryList = append(newVirtualDirectoryList, vdir)
  92. }
  93. }
  94. if entryFound {
  95. //Update the list of vdirs
  96. ep.VirtualDirectories = newVirtualDirectoryList
  97. return nil
  98. }
  99. return errors.New("target virtual directory routing rule not found")
  100. }
  101. // Add a vdir rule by its matching path
  102. func (ep *ProxyEndpoint) AddVirtualDirectoryRule(vdir *VirtualDirectoryEndpoint) (*ProxyEndpoint, error) {
  103. //Check for matching path duplicate
  104. if ep.GetVirtualDirectoryRuleByMatchingPath(vdir.MatchingPath) != nil {
  105. return nil, errors.New("rule with same matching path already exists")
  106. }
  107. //Append it to the list of virtual directory
  108. ep.VirtualDirectories = append(ep.VirtualDirectories, vdir)
  109. //Prepare to replace the current routing rule
  110. parentRouter := ep.parent
  111. readyRoutingRule, err := parentRouter.PrepareProxyRoute(ep)
  112. if err != nil {
  113. return nil, err
  114. }
  115. if ep.ProxyType == ProxyTypeRoot {
  116. parentRouter.Root = readyRoutingRule
  117. } else if ep.ProxyType == ProxyTypeHost {
  118. ep.Remove()
  119. parentRouter.AddProxyRouteToRuntime(readyRoutingRule)
  120. } else {
  121. return nil, errors.New("unsupported proxy type")
  122. }
  123. return readyRoutingRule, nil
  124. }
  125. /* Upstream related wrapper functions */
  126. //Check if there already exists another upstream with identical origin
  127. func (ep *ProxyEndpoint) UpstreamOriginExists(originURL string) bool {
  128. for _, origin := range ep.ActiveOrigins {
  129. if origin.OriginIpOrDomain == originURL {
  130. return true
  131. }
  132. }
  133. for _, origin := range ep.InactiveOrigins {
  134. if origin.OriginIpOrDomain == originURL {
  135. return true
  136. }
  137. }
  138. return false
  139. }
  140. // Get a upstream origin from given origin ip or domain
  141. func (ep *ProxyEndpoint) GetUpstreamOriginByMatchingIP(originIpOrDomain string) (*loadbalance.Upstream, error) {
  142. for _, origin := range ep.ActiveOrigins {
  143. if origin.OriginIpOrDomain == originIpOrDomain {
  144. return origin, nil
  145. }
  146. }
  147. for _, origin := range ep.InactiveOrigins {
  148. if origin.OriginIpOrDomain == originIpOrDomain {
  149. return origin, nil
  150. }
  151. }
  152. return nil, errors.New("target upstream origin not found")
  153. }
  154. // Add upstream to endpoint and update it to runtime
  155. func (ep *ProxyEndpoint) AddUpstreamOrigin(newOrigin *loadbalance.Upstream, activate bool) error {
  156. //Check if the upstream already exists
  157. if ep.UpstreamOriginExists(newOrigin.OriginIpOrDomain) {
  158. return errors.New("upstream with same origin already exists")
  159. }
  160. if activate {
  161. //Add it to the active origin list
  162. err := newOrigin.StartProxy()
  163. if err != nil {
  164. return err
  165. }
  166. ep.ActiveOrigins = append(ep.ActiveOrigins, newOrigin)
  167. } else {
  168. //Add to inactive origin list
  169. ep.InactiveOrigins = append(ep.InactiveOrigins, newOrigin)
  170. }
  171. ep.UpdateToRuntime()
  172. return nil
  173. }
  174. // Remove upstream from endpoint and update it to runtime
  175. func (ep *ProxyEndpoint) RemoveUpstreamOrigin(originIpOrDomain string) error {
  176. //Just to make sure there are no spaces
  177. originIpOrDomain = strings.TrimSpace(originIpOrDomain)
  178. //Check if the upstream already been removed
  179. if !ep.UpstreamOriginExists(originIpOrDomain) {
  180. //Not exists in the first place
  181. return nil
  182. }
  183. newActiveOriginList := []*loadbalance.Upstream{}
  184. for _, origin := range ep.ActiveOrigins {
  185. if origin.OriginIpOrDomain != originIpOrDomain {
  186. newActiveOriginList = append(newActiveOriginList, origin)
  187. }
  188. }
  189. newInactiveOriginList := []*loadbalance.Upstream{}
  190. for _, origin := range ep.InactiveOrigins {
  191. if origin.OriginIpOrDomain != originIpOrDomain {
  192. newInactiveOriginList = append(newInactiveOriginList, origin)
  193. }
  194. }
  195. //Ok, set the origin list to the new one
  196. ep.ActiveOrigins = newActiveOriginList
  197. ep.InactiveOrigins = newInactiveOriginList
  198. ep.UpdateToRuntime()
  199. return nil
  200. }
  201. // Check if the proxy endpoint hostname or alias name contains subdomain wildcard
  202. func (ep *ProxyEndpoint) ContainsWildcardName(skipAliasCheck bool) bool {
  203. hostname := ep.RootOrMatchingDomain
  204. aliasHostnames := ep.MatchingDomainAlias
  205. wildcardCheck := func(hostname string) bool {
  206. return len(hostname) > 0 && hostname[0] == '*'
  207. }
  208. if wildcardCheck(hostname) {
  209. return true
  210. }
  211. if !skipAliasCheck {
  212. for _, aliasHostname := range aliasHostnames {
  213. if wildcardCheck(aliasHostname) {
  214. return true
  215. }
  216. }
  217. }
  218. return false
  219. }
  220. // Create a deep clone object of the proxy endpoint
  221. // Note the returned object is not activated. Call to prepare function before pushing into runtime
  222. func (ep *ProxyEndpoint) Clone() *ProxyEndpoint {
  223. clonedProxyEndpoint := ProxyEndpoint{}
  224. js, _ := json.Marshal(ep)
  225. json.Unmarshal(js, &clonedProxyEndpoint)
  226. return &clonedProxyEndpoint
  227. }
  228. // Remove this proxy endpoint from running proxy endpoint list
  229. func (ep *ProxyEndpoint) Remove() error {
  230. lookupHostname := strings.ToLower(ep.RootOrMatchingDomain)
  231. ep.parent.ProxyEndpoints.Delete(lookupHostname)
  232. return nil
  233. }
  234. // Write changes to runtime without respawning the proxy handler
  235. // use prepare -> remove -> add if you change anything in the endpoint
  236. // that effects the proxy routing src / dest
  237. func (ep *ProxyEndpoint) UpdateToRuntime() {
  238. lookupHostname := strings.ToLower(ep.RootOrMatchingDomain)
  239. ep.parent.ProxyEndpoints.Store(lookupHostname, ep)
  240. }