-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathftp-reverse-proxy.go
105 lines (86 loc) · 2.18 KB
/
ftp-reverse-proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"flag"
"fmt"
"github.com/jlaffaye/ftp"
"io"
"log"
"net/http"
"net/url"
"time"
)
func main() {
configuration := parseFlags()
http.HandleFunc("/", proxy(configuration))
log.Printf("Running on port %d, targetting %s ...", configuration.port, configuration.target.Host)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", configuration.port), nil))
}
type configuration struct {
port int
target url.URL
}
func parseFlags() configuration {
var target = flag.String("target", "", "FTP URL to proxy to (example: ftp://user:pwd@host:21)")
var port = flag.Int("port", 8080, "Port to listen to")
flag.Usage = func() {
fmt.Printf("ftp-reverse-proxy, a HTTP reverse proxy to access a FTP server.\n" +
"Usage:\n")
flag.PrintDefaults()
}
flag.Parse()
if *target == "" {
flag.PrintDefaults()
log.Fatal("Target is not defined")
}
var targetUrl, err = url.Parse(*target)
if err != nil {
flag.PrintDefaults()
log.Fatal("Target URL is malformed")
}
return configuration{
port: *port,
target: *targetUrl,
}
}
func proxy(configuration configuration) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c, err := ftp.Dial(configuration.target.Host, ftp.DialWithTimeout(5*time.Second))
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}
password, _ := configuration.target.User.Password()
err = c.Login(configuration.target.User.Username(), password)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method == "POST" {
err = c.Stor(r.URL.Path, r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
log.Printf("Stored %s", r.URL.Path)
} else if r.Method == "GET" {
response, err := c.Retr(r.URL.Path)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
_, err = io.Copy(w, response)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("Retrieved %s", r.URL.Path)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
}