@@ -4,13 +4,19 @@ package proxy
4
4
5
5
import (
6
6
"bufio"
7
+ "bytes"
7
8
"context"
9
+ "io"
8
10
"net"
9
11
"net/http"
12
+ "os"
13
+ "path/filepath"
10
14
"regexp"
11
15
"strconv"
12
16
"time"
13
17
18
+ "github.com/lima-vm/lima/pkg/downloader"
19
+
14
20
"github.com/elazarl/goproxy"
15
21
"github.com/sirupsen/logrus"
16
22
)
@@ -47,11 +53,51 @@ func Start(opts ServerOptions) (*Server, error) {
47
53
return server , nil
48
54
}
49
55
56
+ func sendFile (req * http.Request , path string ) (* http.Response , error ) {
57
+ resp := & http.Response {}
58
+ resp .Request = req
59
+ resp .TransferEncoding = req .TransferEncoding
60
+ resp .Header = make (http.Header )
61
+ status := http .StatusOK
62
+ resp .StatusCode = status
63
+ resp .Status = http .StatusText (status )
64
+ b , err := os .ReadFile (path )
65
+ if err != nil {
66
+ return nil , err
67
+ }
68
+ resp .Body = io .NopCloser (bytes .NewBuffer (b ))
69
+ resp .Header .Set ("Content-Type" , "application/octet-stream" )
70
+ //resp.Header.Set("Last-Modified", ")
71
+ resp .ContentLength = int64 (len (b ))
72
+ return resp , nil
73
+ }
74
+
50
75
func listenAndServe (opts ServerOptions ) (* http.Server , error ) {
76
+ ucd , err := os .UserCacheDir ()
77
+ if err != nil {
78
+ return nil , err
79
+ }
80
+ cacheDir := filepath .Join (ucd , "lima" )
81
+ downloader .HideProgress = true
82
+
51
83
addr := net .JoinHostPort (opts .Address , strconv .Itoa (opts .TCPPort ))
52
84
proxy := goproxy .NewProxyHttpServer ()
53
85
proxy .OnRequest (goproxy .ReqHostMatches (regexp .MustCompile ("^.*$" ))).
54
86
HandleConnect (goproxy .AlwaysMitm )
87
+ proxy .OnRequest ().DoFunc (func (req * http.Request , ctx * goproxy.ProxyCtx ) (* http.Request , * http.Response ) {
88
+ url := req .URL .String ()
89
+ if res , err := downloader .Cached (url , downloader .WithCacheDir (cacheDir )); err == nil {
90
+ if resp , err := sendFile (req , res .CachePath ); err == nil {
91
+ return nil , resp
92
+ }
93
+ }
94
+ if res , err := downloader .Download (context .Background (), "" , url , downloader .WithCacheDir (cacheDir )); err == nil {
95
+ if resp , err := sendFile (req , res .CachePath ); err == nil {
96
+ return nil , resp
97
+ }
98
+ }
99
+ return req , nil
100
+ })
55
101
proxy .OnRequest (goproxy .ReqHostMatches (regexp .MustCompile ("^.*:80$" ))).
56
102
HijackConnect (func (req * http.Request , client net.Conn , ctx * goproxy.ProxyCtx ) {
57
103
defer func () {
@@ -61,8 +107,6 @@ func listenAndServe(opts ServerOptions) (*http.Server, error) {
61
107
}
62
108
client .Close ()
63
109
}()
64
- url := req .URL .String ()
65
- ctx .Logf ("URL: %s" , url )
66
110
clientBuf := bufio .NewReadWriter (bufio .NewReader (client ), bufio .NewWriter (client ))
67
111
remote , err := net .Dial ("tcp" , req .URL .Host )
68
112
if err != nil {
0 commit comments