main.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/exec"
  12. "strings"
  13. "time"
  14. "github.com/PuerkitoBio/goquery"
  15. "github.com/NYTimes/gziphandler"
  16. "github.com/gorilla/websocket"
  17. "golang.org/x/net/proxy"
  18. "github.com/davecgh/go-spew/spew"
  19. "github.com/go-yaml/yaml"
  20. "github.com/ogier/pflag"
  21. "github.com/superp00t/etc"
  22. "github.com/superp00t/etc/yo"
  23. )
  24. var (
  25. gitService = pflag.StringP("gitservice", "g", "https://git.ikrypto.club/", "the default Git service to map hosts to")
  26. subService = pflag.StringP("subservice", "s", "https://*.pg.ikrypto.club/", "the default web service that provides pages")
  27. addr = pflag.StringP("address", "a", ":3000", "the default address to listen on")
  28. cfg = pflag.StringP("cfg", "c", "config.yaml", "the default config file")
  29. )
  30. type coreMatch struct {
  31. Type string `yaml:"type"`
  32. Repo string `yaml:"repo"`
  33. ID string `yaml:"id"`
  34. SubPath string `yaml:"subpath"`
  35. Updated time.Time `yaml:"updated"`
  36. }
  37. type ConfigFile struct {
  38. Sites map[string]*coreMatch `yaml:"sites"`
  39. }
  40. func die(err error) {
  41. fmt.Println(err)
  42. os.Exit(0)
  43. }
  44. func dies(err string) {
  45. fmt.Println(err)
  46. os.Exit(0)
  47. }
  48. func loadOrDie() ConfigFile {
  49. f, err := ioutil.ReadFile(*cfg)
  50. if err != nil {
  51. die(err)
  52. }
  53. var cf ConfigFile
  54. err = yaml.Unmarshal(f, &cf)
  55. if err != nil {
  56. die(err)
  57. }
  58. return cf
  59. }
  60. func isSubSystem(host string) (string, string, bool) {
  61. u, err := url.Parse(host)
  62. if err != nil {
  63. fmt.Println("Encountered error", err)
  64. return "", "", false
  65. }
  66. us, err := url.Parse(*subService)
  67. if err != nil {
  68. panic(err)
  69. }
  70. s := strings.Split(us.Host, "*")
  71. if len(s) != 2 {
  72. return "", u.Hostname(), false
  73. }
  74. if strings.HasSuffix(u.Hostname(), s[1]) {
  75. base := strings.Split(u.Hostname(), ".")[0]
  76. return base, u.Hostname(), true
  77. }
  78. return "", u.Hostname(), false
  79. }
  80. func noSiteFound(rw http.ResponseWriter, r *http.Request) {
  81. fmt.Fprint(rw, "No site found.")
  82. }
  83. func cloneSite(host, repo string) {
  84. l := loadLock()
  85. if l.Sites[host] != nil {
  86. if time.Since(l.Sites[host].Updated) > (10 * time.Second) {
  87. errBuf := etc.NewBuffer()
  88. fmt.Println("Pulling", host)
  89. c := exec.Command("git", "-C", "./git_home/"+l.Sites[host].ID, "pull")
  90. c.Stderr = errBuf
  91. c.Run()
  92. l.Sites[host].Updated = time.Now()
  93. writeLock(l)
  94. return
  95. }
  96. } else {
  97. fmt.Println("Cloning", host)
  98. l.Sites[host] = &coreMatch{
  99. Type: "static",
  100. Repo: repo,
  101. ID: host,
  102. SubPath: loadOrDie().Sites[host].SubPath,
  103. Updated: time.Now(),
  104. }
  105. writeLock(l)
  106. therepo := ""
  107. branch := "master"
  108. repoel := strings.Split(repo, "#")
  109. if len(repoel) == 2 {
  110. branch = repoel[1]
  111. therepo = repoel[0]
  112. } else {
  113. therepo = repoel[0]
  114. }
  115. cmd := exec.Command("git", "clone", "-b", branch, therepo, "./git_home/"+l.Sites[host].ID)
  116. cmd.Stdout = os.Stdout
  117. cmd.Stderr = os.Stderr
  118. cmd.Run()
  119. }
  120. }
  121. func exists(url string) bool {
  122. h, err := http.Get(url)
  123. if err != nil {
  124. return false
  125. }
  126. return h.StatusCode == 200
  127. }
  128. func isRemote(_url string) bool {
  129. u, err := url.Parse(_url)
  130. if err != nil {
  131. return false
  132. }
  133. return !(u.Scheme == "" && u.Opaque == "" && u.Host == "")
  134. }
  135. func pushLocal(href string, as string, rw http.ResponseWriter, r *http.Request, slice *[]string) {
  136. pusher, ok := rw.(http.Pusher)
  137. if isRemote(href) == false {
  138. if strings.HasPrefix(href, "/") == false {
  139. href = "/" + href
  140. }
  141. if ok {
  142. err := pusher.Push(href, &http.PushOptions{
  143. Header: http.Header{
  144. "Accept-Encoding": r.Header["Accept-Encoding"],
  145. },
  146. })
  147. yo.Println("Pushing asset", href, err)
  148. } else {
  149. sli := *slice
  150. sli = append(sli, fmt.Sprintf("<%s>; as=%s; rel=preload", href, as))
  151. *slice = sli
  152. yo.Println("Pushing asset via preload", href)
  153. }
  154. } else {
  155. yo.Warn("non-remote asset", href)
  156. }
  157. }
  158. func serveHost(rw http.ResponseWriter, r *http.Request, host string) {
  159. lck := loadLock().Sites[host]
  160. id := lck.ID
  161. srcDir := "./git_home/" + id + lck.SubPath
  162. yo.Ok("Source directory: ", srcDir)
  163. var preloads = []string{}
  164. // Push static assets for acceleration
  165. if r.URL.Path == "/" {
  166. yo.Printf("%s %s [%s] (Attempting acceleration)\n", r.Method, r.URL, host)
  167. f, err := os.Open(srcDir + "/index.html")
  168. if err == nil {
  169. gq, err := goquery.NewDocumentFromReader(f)
  170. if err == nil {
  171. // Push CSS
  172. gq.Find("link").Each(func(i int, s *goquery.Selection) {
  173. if val, exists := s.Attr("rel"); exists {
  174. if val == "stylesheet" {
  175. if href, exists := s.Attr("href"); exists {
  176. pushLocal(href, "style", rw, r, &preloads)
  177. }
  178. }
  179. }
  180. })
  181. // Push JS
  182. gq.Find("script").Each(func(i int, s *goquery.Selection) {
  183. if src, exists := s.Attr("src"); exists {
  184. pushLocal(src, "script", rw, r, &preloads)
  185. }
  186. })
  187. }
  188. }
  189. }
  190. if len(preloads) > 0 {
  191. rw.Header().Set("Link", strings.Join(preloads, ","))
  192. }
  193. hnd := gziphandler.GzipHandler(http.FileServer(http.Dir(srcDir)))
  194. hnd.ServeHTTP(rw, r)
  195. }
  196. func proxyWs(rw http.ResponseWriter, r *http.Request, remote string, dFn func(network, addr string) (net.Conn, error)) {
  197. yo.Println("Attempting to proxy", remote)
  198. u, err := url.Parse(remote)
  199. if err != nil {
  200. yo.Fatal(err)
  201. }
  202. u.RawPath = r.URL.RawPath
  203. u.RawQuery = r.URL.Query().Encode()
  204. var upgrader = websocket.Upgrader{
  205. ReadBufferSize: 1024,
  206. WriteBufferSize: 1024,
  207. CheckOrigin: func(r *http.Request) bool {
  208. return true
  209. },
  210. }
  211. prx := &websocket.Dialer{
  212. NetDial: dFn,
  213. }
  214. if u.Scheme == "http" {
  215. u.Scheme = "ws"
  216. } else {
  217. u.Scheme = "wss"
  218. }
  219. remotecn, err := upgrader.Upgrade(rw, r, nil)
  220. if err != nil {
  221. yo.Println("Error upgrading", remotecn)
  222. return
  223. }
  224. yo.Ok("upgraded successfully")
  225. localcn, _, err := prx.Dial(u.String(), nil)
  226. if err != nil {
  227. http.Error(rw, "error connecting to backend websocket", 500)
  228. return
  229. }
  230. defer remotecn.Close()
  231. defer localcn.Close()
  232. go func() {
  233. for {
  234. mt, b, err := remotecn.ReadMessage()
  235. if err != nil {
  236. return
  237. }
  238. err = localcn.WriteMessage(mt, b)
  239. if err != nil {
  240. return
  241. }
  242. }
  243. }()
  244. for {
  245. mt, b, err := localcn.ReadMessage()
  246. if err != nil {
  247. return
  248. }
  249. err = remotecn.WriteMessage(mt, b)
  250. if err != nil {
  251. return
  252. }
  253. }
  254. }
  255. func serveProxy(rw http.ResponseWriter, r *http.Request, remoteURL string) {
  256. yo.Println("Serving proxy", remoteURL)
  257. cl := http.Client{}
  258. path := r.URL.Path
  259. if strings.HasSuffix(path, ".git") {
  260. http.Error(rw, "forbidden", http.StatusForbidden)
  261. return
  262. }
  263. nur, err := url.Parse(remoteURL)
  264. if err != nil {
  265. panic(err)
  266. return
  267. }
  268. var dialr func(network, address string) (net.Conn, error)
  269. // Proxy tor requests
  270. if strings.HasSuffix(nur.Host, ".onion") {
  271. yo.Println("Tor proxy", nur.Host)
  272. dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9050", nil, proxy.Direct)
  273. if err != nil {
  274. yo.Fatal(err)
  275. }
  276. dialr = dialer.Dial
  277. } else {
  278. yo.Println("Not a Tor proxy", nur.Host)
  279. dialr = func(network, addr string) (net.Conn, error) {
  280. return net.Dial(network, addr)
  281. }
  282. }
  283. cl.Transport = &http.Transport{Dial: dialr}
  284. if r.Header.Get("Upgrade") == "websocket" {
  285. proxyWs(rw, r, remoteURL, dialr)
  286. return
  287. }
  288. // handle websockets
  289. yo.Println(r.Method, r.URL.RawPath)
  290. nur.Path = path
  291. nur.RawQuery = r.URL.Query().Encode()
  292. nr, err := http.NewRequest(r.Method, nur.String(), r.Body)
  293. if err != nil {
  294. yo.Warn(err)
  295. return
  296. }
  297. nr.Header.Set("Origin", nur.String())
  298. for k := range r.Header {
  299. nr.Header.Set(k, r.Header.Get(k))
  300. }
  301. nr.Host = r.Host
  302. r.URL.RawPath = path
  303. resp, err := cl.Do(nr)
  304. if err != nil {
  305. yo.Println("Proxy error", err)
  306. rw.WriteHeader(http.StatusInternalServerError)
  307. fmt.Fprintf(rw, "Backend request error")
  308. return
  309. }
  310. for k := range resp.Header {
  311. rw.Header().Set(k, resp.Header.Get(k))
  312. }
  313. rw.WriteHeader(resp.StatusCode)
  314. io.Copy(rw, resp.Body)
  315. }
  316. func router(rw http.ResponseWriter, r *http.Request) {
  317. h := r.Host
  318. user, rur, is := isSubSystem("https://" + h)
  319. yo.Println("Opened ", rur, "with user")
  320. if !is {
  321. l := loadOrDie()
  322. if l.Sites[rur] != nil {
  323. if l.Sites[rur].Type == "proxy" {
  324. serveProxy(rw, r, l.Sites[rur].Repo)
  325. return
  326. }
  327. cloneSite(rur, l.Sites[rur].Repo)
  328. serveHost(rw, r, rur)
  329. return
  330. }
  331. noSiteFound(rw, r)
  332. } else {
  333. c := loadOrDie()
  334. if c.Sites[rur] != nil {
  335. if c.Sites[rur].Type == "proxy" {
  336. serveProxy(rw, r, c.Sites[rur].Repo)
  337. return
  338. }
  339. cloneSite(rur, c.Sites[rur].Repo)
  340. serveHost(rw, r, rur)
  341. return
  342. }
  343. l := loadLock()
  344. yo.Println("Attempting to open domain", rur)
  345. if l.Sites[rur] != nil {
  346. cloneSite(rur, l.Sites[rur].Repo)
  347. serveHost(rw, r, rur)
  348. return
  349. } else {
  350. gURL := *gitService + url.QueryEscape(user) + "/homepage.git"
  351. ex := exists(gURL)
  352. yo.Println("Queryied user repo. ", gURL, exists(gURL))
  353. if ex {
  354. cloneSite(rur, gURL)
  355. serveHost(rw, r, rur)
  356. } else {
  357. noSiteFound(rw, r)
  358. }
  359. }
  360. }
  361. }
  362. func main() {
  363. pflag.Parse()
  364. yo.Println(spew.Sdump(loadOrDie()))
  365. r := http.NewServeMux()
  366. r.HandleFunc("/", router)
  367. log.Fatal(http.ListenAndServe(*addr, r))
  368. }