123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194 |
- /*
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
- http-wokou, An HTTP Proxying framework for bypassing DNS Security
- Copyright (C) 2024 Russell Hrubesky, ChiralWorks Software LLC
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- package httpserver
- import (
- "fmt"
- "log"
- "net/http"
- "net/http/cookiejar"
- "net/url"
- "os"
- "time"
- "github.com/gin-gonic/gin"
- "github.com/patrickmn/go-cache"
- "golang.org/x/net/publicsuffix"
- )
- // Implementing a 'set'
- var NonmutableHeaders = map[string]struct{}{
- "Cookie": struct{}{},
- "User-Agent": struct{}{},
- "Accept-Encoding": struct{}{},
- "Referer": struct{}{},
- "X-Proxy-Url": struct{}{},
- "Host": struct{}{},
- }
- type TokenUpdate struct {
- Code string `form:"code"`
- Content string `form:"content"`
- }
- type Controller struct {
- Config *HttpServerConfig
- RouteMaps *RouteMap
- PageMods *AllPageMods
- Client *http.Client
- SiteUrl *url.URL
- cache *cache.Cache
- }
- type ProxyCookies struct {
- ck map[*url.URL][]*http.Cookie
- }
- /*
- Returns a new Controller struct to register routes to the gin router
- :param cfg: A pointer to an HttpServerConfig struct
- */
- func NewController(cfg *HttpServerConfig, routeMap *RouteMap) *Controller {
- jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
- if err != nil {
- log.Fatal(err)
- }
- sessCookies := cfg.CookieJar
- domain, err := url.Parse(cfg.FullDomain)
- if err != nil {
- log.Fatal(err)
- }
- pgMod := LoadPageMods(cfg.PageModPath)
- jar.SetCookies(domain, sessCookies)
- var resCache *cache.Cache
- if cfg.Caching {
- fmt.Printf("Starting server with resource caching ENABLED.\n")
- resCache = cache.New(24*time.Hour, 10*time.Minute)
- } else {
- fmt.Printf("Starting server with resource caching DISABLED.\n")
- resCache = nil
- }
- return &Controller{Config: cfg, Client: &http.Client{Jar: jar, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }},
- SiteUrl: domain, cache: resCache, RouteMaps: routeMap, PageMods: pgMod}
- }
- /*
- This handler will be responsible for proxying out the GET requests that the server recieves
- */
- func (c *Controller) HandleAny(ctx *gin.Context) {
- incomingPath := ctx.Param("ProxiedPath")
- for idx := range c.Config.Redirects {
- if incomingPath == c.Config.Redirects[idx].From {
- ctx.Header("Location", c.Config.Redirects[idx].To)
- ctx.Status(302)
- return
- }
- }
- if incomingPath == "/update" {
- if ctx.Request.Method == "POST" {
- c.UpdatePost(ctx)
- return
- }
- }
- if c.Config.CustomFserve != nil {
- for idx := range c.Config.CustomFserve.Config {
- if incomingPath == c.Config.CustomFserve.Config[idx].Request {
- fmt.Print("Custom file server path hit.\n")
- ctx.Data(200, c.Config.CustomFserve.Config[idx].ContentType, c.Config.CustomFserve.Config[idx].FileData)
- return
- }
- }
- }
- if c.Config.Caching {
- cacheHit := c.GetResource(incomingPath)
- if cacheHit != nil {
- for k, v := range *cacheHit.Headers {
- _, ok := NonmutableHeaders[k]
- if !ok {
- for i := range v {
- ctx.Header(k, v[i])
- }
- }
- }
- ctx.Data(cacheHit.Rcode, cacheHit.Headers.Get("content-type"), cacheHit.Data)
- return
- } else {
- fmt.Printf("Cache MISS! For resource URI: %s\n", incomingPath)
- }
- }
- dname, ok := c.RouteMaps.GetMappedDomain(incomingPath)
- if ok { // below, RequestURI() returns the whole URI with the query
- data, headers, rcode, err := c.RequestGeneric(ctx.Request.Method, dname, ctx.Request.URL.RequestURI(), &ctx.Request.Header, ctx.Request.Body)
- if err != nil {
- log.Fatal(err, " failed to route the request: ", incomingPath, " to the target domain: ", dname, " Error: ", err)
- }
- for k, v := range *headers {
- _, ok := NonmutableHeaders[k]
- if !ok {
- ctx.Header(k, v[0])
- }
- }
- ctx.Header("access-control-allow-origin", c.Config.FullProxyDomain)
- ctx.Data(rcode, headers.Get("content-type"), data)
- return
- }
- c.TryHosts(ctx.Request.Method, ctx.Request.URL.RequestURI(), &ctx.Request.Header, ctx.Request.Body, c.Config.KnownHosts)
- }
- /*
- This function handles the updating of cookie values, meant to be extendable down the road // TODO: Make this more configurable
- :param ctx: pointer to a gin Context struct
- */
- func (c *Controller) UpdatePost(ctx *gin.Context) {
- tk := TokenUpdate{
- Code: ctx.PostForm("code"),
- Content: ctx.PostForm("content"),
- }
- if tk.Code != c.Config.TkUpdateCode {
- ctx.JSON(401, map[string]string{
- "msg": "UNAUTHORIZED",
- })
- return
- }
- err := os.WriteFile(c.Config.TokenSaveLoc, []byte(tk.Content), os.ModePerm)
- if err != nil {
- ctx.JSON(500, map[string]string{
- "Error": fmt.Sprintf("couldnt write token to disk. Error: %s", err),
- })
- return
- }
- ctx.String(200, "Token updated.")
- }
|