controller.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. GNU GENERAL PUBLIC LICENSE
  3. Version 3, 29 June 2007
  4. Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
  5. Everyone is permitted to copy and distribute verbatim copies
  6. of this license document, but changing it is not allowed.
  7. http-wokou, An HTTP Proxying framework for bypassing DNS Security
  8. Copyright (C) 2024 Russell Hrubesky, ChiralWorks Software LLC
  9. This program is free software: you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation, either version 3 of the License, or
  12. (at your option) any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. package httpserver
  21. import (
  22. "fmt"
  23. "log"
  24. "net/http"
  25. "net/http/cookiejar"
  26. "net/url"
  27. "os"
  28. "time"
  29. "github.com/gin-gonic/gin"
  30. "github.com/patrickmn/go-cache"
  31. "golang.org/x/net/publicsuffix"
  32. )
  33. // Implementing a 'set'
  34. var NonmutableHeaders = map[string]struct{}{
  35. "Cookie": struct{}{},
  36. "User-Agent": struct{}{},
  37. "Accept-Encoding": struct{}{},
  38. "Referer": struct{}{},
  39. "X-Proxy-Url": struct{}{},
  40. "Host": struct{}{},
  41. }
  42. type TokenUpdate struct {
  43. Code string `form:"code"`
  44. Content string `form:"content"`
  45. }
  46. type Controller struct {
  47. Config *HttpServerConfig
  48. RouteMaps *RouteMap
  49. PageMods *AllPageMods
  50. Client *http.Client
  51. SiteUrl *url.URL
  52. cache *cache.Cache
  53. }
  54. type ProxyCookies struct {
  55. ck map[*url.URL][]*http.Cookie
  56. }
  57. /*
  58. Returns a new Controller struct to register routes to the gin router
  59. :param cfg: A pointer to an HttpServerConfig struct
  60. */
  61. func NewController(cfg *HttpServerConfig, routeMap *RouteMap) *Controller {
  62. jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
  63. if err != nil {
  64. log.Fatal(err)
  65. }
  66. sessCookies := cfg.CookieJar
  67. domain, err := url.Parse(cfg.FullDomain)
  68. if err != nil {
  69. log.Fatal(err)
  70. }
  71. pgMod := LoadPageMods(cfg.PageModPath)
  72. jar.SetCookies(domain, sessCookies)
  73. var resCache *cache.Cache
  74. if cfg.Caching {
  75. fmt.Printf("Starting server with resource caching ENABLED.\n")
  76. resCache = cache.New(24*time.Hour, 10*time.Minute)
  77. } else {
  78. fmt.Printf("Starting server with resource caching DISABLED.\n")
  79. resCache = nil
  80. }
  81. return &Controller{Config: cfg, Client: &http.Client{Jar: jar, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }},
  82. SiteUrl: domain, cache: resCache, RouteMaps: routeMap, PageMods: pgMod}
  83. }
  84. /*
  85. This handler will be responsible for proxying out the GET requests that the server recieves
  86. */
  87. func (c *Controller) HandleAny(ctx *gin.Context) {
  88. incomingPath := ctx.Param("ProxiedPath")
  89. for idx := range c.Config.Redirects {
  90. if incomingPath == c.Config.Redirects[idx].From {
  91. ctx.Header("Location", c.Config.Redirects[idx].To)
  92. ctx.Status(302)
  93. return
  94. }
  95. }
  96. if incomingPath == "/update" {
  97. if ctx.Request.Method == "POST" {
  98. c.UpdatePost(ctx)
  99. return
  100. }
  101. }
  102. if c.Config.CustomFserve != nil {
  103. for idx := range c.Config.CustomFserve.Config {
  104. if incomingPath == c.Config.CustomFserve.Config[idx].Request {
  105. fmt.Print("Custom file server path hit.\n")
  106. ctx.Data(200, c.Config.CustomFserve.Config[idx].ContentType, c.Config.CustomFserve.Config[idx].FileData)
  107. return
  108. }
  109. }
  110. }
  111. if c.Config.Caching {
  112. cacheHit := c.GetResource(incomingPath)
  113. if cacheHit != nil {
  114. for k, v := range *cacheHit.Headers {
  115. _, ok := NonmutableHeaders[k]
  116. if !ok {
  117. for i := range v {
  118. ctx.Header(k, v[i])
  119. }
  120. }
  121. }
  122. ctx.Data(cacheHit.Rcode, cacheHit.Headers.Get("content-type"), cacheHit.Data)
  123. return
  124. } else {
  125. fmt.Printf("Cache MISS! For resource URI: %s\n", incomingPath)
  126. }
  127. }
  128. dname, ok := c.RouteMaps.GetMappedDomain(incomingPath)
  129. if ok { // below, RequestURI() returns the whole URI with the query
  130. data, headers, rcode, err := c.RequestGeneric(ctx.Request.Method, dname, ctx.Request.URL.RequestURI(), &ctx.Request.Header, ctx.Request.Body)
  131. if err != nil {
  132. log.Fatal(err, " failed to route the request: ", incomingPath, " to the target domain: ", dname, " Error: ", err)
  133. }
  134. for k, v := range *headers {
  135. _, ok := NonmutableHeaders[k]
  136. if !ok {
  137. ctx.Header(k, v[0])
  138. }
  139. }
  140. ctx.Header("access-control-allow-origin", c.Config.FullProxyDomain)
  141. ctx.Data(rcode, headers.Get("content-type"), data)
  142. return
  143. }
  144. c.TryHosts(ctx.Request.Method, ctx.Request.URL.RequestURI(), &ctx.Request.Header, ctx.Request.Body, c.Config.KnownHosts)
  145. }
  146. /*
  147. This function handles the updating of cookie values, meant to be extendable down the road // TODO: Make this more configurable
  148. :param ctx: pointer to a gin Context struct
  149. */
  150. func (c *Controller) UpdatePost(ctx *gin.Context) {
  151. tk := TokenUpdate{
  152. Code: ctx.PostForm("code"),
  153. Content: ctx.PostForm("content"),
  154. }
  155. if tk.Code != c.Config.TkUpdateCode {
  156. ctx.JSON(401, map[string]string{
  157. "msg": "UNAUTHORIZED",
  158. })
  159. return
  160. }
  161. err := os.WriteFile(c.Config.TokenSaveLoc, []byte(tk.Content), os.ModePerm)
  162. if err != nil {
  163. ctx.JSON(500, map[string]string{
  164. "Error": fmt.Sprintf("couldnt write token to disk. Error: %s", err),
  165. })
  166. return
  167. }
  168. ctx.String(200, "Token updated.")
  169. }