forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftpd.go
431 lines (409 loc) · 9.52 KB
/
ftpd.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// ex8.2 is a minimal ftp server as per section 5.1 of RFC 959.
//
// TYPE - ASCII Non-print
// MODE - Stream
// STRUCTURE - File, Record
// COMMANDS - USER, QUIT, PORT,
// TYPE, MODE, STRU,
// for the default values
// RETR, STOR,
// NOOP.
//
// The default values for transfer parameters are:
//
// TYPE - ASCII Non-print
// MODE - Stream
// STRU - File
//
// There's a contradiction above for the STRU command. Only File structure (the
// default) is supported.
//
// Additionally, passive transfers are supported.
//
// Only IPv4 is supported.
//
//
// DJB's recommendations at http://cr.yp.to/ftp.html have mostly been
// implemented when noticed and applicable.
//
// TODO: respond to telnet codes as described at http://cr.yp.to/ftp/request.html
// TODO: protect against path traversal attacks.
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"strings"
)
type conn struct {
rw net.Conn // "Protocol Interpreter" connection
dataHostPort string
prevCmd string
pasvListener net.Listener
cmdErr error // Saved command connection write error.
binary bool
}
func NewConn(cmdConn net.Conn) *conn {
return &conn{rw: cmdConn}
}
// hostPortToFTP returns a comma-separated, FTP-style address suitable for
// replying to the PASV command.
func hostPortToFTP(hostport string) (addr string, err error) {
host, portStr, err := net.SplitHostPort(hostport)
if err != nil {
return "", err
}
ipAddr, err := net.ResolveIPAddr("ip4", host)
if err != nil {
return "", err
}
port, err := strconv.ParseInt(portStr, 10, 64)
if err != nil {
return "", err
}
ip := ipAddr.IP.To4()
s := fmt.Sprintf("%d,%d,%d,%d,%d,%d", ip[0], ip[1], ip[2], ip[3], port/256, port%256)
return s, nil
}
func hostPortFromFTP(address string) (string, error) {
var a, b, c, d byte
var p1, p2 int
_, err := fmt.Sscanf(address, "%d,%d,%d,%d,%d,%d", &a, &b, &c, &d, &p1, &p2)
if err != nil {
return "", err
}
return fmt.Sprintf("%d.%d.%d.%d:%d", a, b, c, d, 256*p1+p2), nil
}
type logPairs map[string]interface{}
func (c *conn) log(pairs logPairs) {
b := &bytes.Buffer{}
fmt.Fprintf(b, "addr=%s", c.rw.RemoteAddr().String())
for k, v := range pairs {
fmt.Fprintf(b, " %s=%s", k, v)
}
log.Print(b.String())
}
func (c *conn) dataConn() (conn io.ReadWriteCloser, err error) {
switch c.prevCmd {
case "PORT":
conn, err = net.Dial("tcp", c.dataHostPort)
if err != nil {
return nil, err
}
case "PASV":
conn, err = c.pasvListener.Accept()
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("previous command not PASV or PORT")
}
return conn, nil
}
// list prints file information to a data connection specified by the
// immediately preceding PASV or PORT command.
func (c *conn) list(args []string) {
var filename string
switch len(args) {
case 0:
filename = "."
case 1:
filename = args[0]
default:
c.writeln("501 Too many arguments.")
return
}
file, err := os.Open(filename)
if err != nil {
c.writeln("550 File not found.")
return
}
c.writeln("150 Here comes the directory listing.")
w, err := c.dataConn()
if err != nil {
c.writeln("425 Can't open data connection.")
return
}
defer w.Close()
stat, err := file.Stat()
if err != nil {
c.log(logPairs{"cmd": "LIST", "err": err})
c.writeln("450 Requested file action not taken. File unavailable.")
}
// TODO: Print more than just the filenames.
if stat.IsDir() {
filenames, err := file.Readdirnames(0)
if err != nil {
c.writeln("550 Can't read directory.")
return
}
for _, f := range filenames {
_, err = fmt.Fprint(w, f, c.lineEnding())
if err != nil {
c.log(logPairs{"cmd": "LIST", "err": err})
c.writeln("426 Connection closed: transfer aborted.")
return
}
}
} else {
_, err = fmt.Fprint(w, filename, c.lineEnding())
if err != nil {
c.log(logPairs{"cmd": "LIST", "err": err})
c.writeln("426 Connection closed: transfer aborted.")
return
}
}
c.writeln("226 Closing data connection. List successful.")
}
func (c *conn) writeln(s ...interface{}) {
if c.cmdErr != nil {
return
}
s = append(s, "\r\n")
_, c.cmdErr = fmt.Fprint(c.rw, s...)
}
func (c *conn) lineEnding() string {
if c.binary {
return "\n"
} else {
return "\r\n"
}
}
func (c *conn) CmdErr() error {
return c.cmdErr
}
func (c *conn) Close() error {
err := c.rw.Close()
if err != nil {
c.log(logPairs{"err": fmt.Errorf("closing command connection: %s", err)})
}
return err
}
func (c *conn) pasv(args []string) {
if len(args) > 0 {
c.writeln("501 Too many arguments.")
return
}
var firstError error
storeFirstError := func(err error) {
if firstError == nil {
firstError = err
}
}
var err error
c.pasvListener, err = net.Listen("tcp4", "")
storeFirstError(err)
_, port, err := net.SplitHostPort(c.pasvListener.Addr().String())
storeFirstError(err)
ip, _, err := net.SplitHostPort(c.rw.LocalAddr().String())
storeFirstError(err)
addr, err := hostPortToFTP(fmt.Sprintf("%s:%s", ip, port))
storeFirstError(err)
if firstError != nil {
c.pasvListener.Close()
c.pasvListener = nil
c.log(logPairs{"cmd": "PASV", "err": err})
c.writeln("451 Requested action aborted. Local error in processing.")
return
}
// DJB recommends putting an extra character before the address.
c.writeln(fmt.Sprintf("227 =%s", addr))
}
func (c *conn) port(args []string) {
if len(args) != 1 {
c.writeln("501 Usage: PORT a,b,c,d,p1,p2")
return
}
var err error
c.dataHostPort, err = hostPortFromFTP(args[0])
if err != nil {
c.log(logPairs{"cmd": "PORT", "err": err})
c.writeln("501 Can't parse address.")
return
}
c.writeln("200 PORT command successful.")
}
func (c *conn) type_(args []string) {
if len(args) < 1 || len(args) > 2 {
c.writeln("501 Usage: TYPE takes 1 or 2 arguments.")
return
}
switch strings.ToUpper(strings.Join(args, " ")) {
case "A", "A N":
c.binary = false
case "I", "L 8":
c.binary = true
default:
c.writeln("504 Unsupported type. Supported types: A, A N, I, L 8.")
return
}
c.writeln("200 TYPE set")
}
func (c *conn) stru(args []string) {
if len(args) != 1 {
c.writeln("501 Usage: STRU F")
return
}
if args[0] != "F" {
c.writeln("504 Only file structure is supported")
return
}
c.writeln("200 STRU set")
}
func (c *conn) retr(args []string) {
if len(args) != 1 {
c.writeln("501 Usage: RETR filename")
return
}
filename := args[0]
file, err := os.Open(filename)
if err != nil {
c.log(logPairs{"cmd": "RETR", "err": err})
c.writeln("550 File not found.")
return
}
c.writeln("150 File ok. Sending.")
conn, err := c.dataConn()
if err != nil {
c.writeln("425 Can't open data connection")
return
}
defer conn.Close()
if c.binary {
_, err := io.Copy(conn, file)
if err != nil {
c.log(logPairs{"cmd": "RETR", "err": err})
c.writeln("450 File unavailable.")
return
}
} else {
// Convert line endings LF -> CRLF.
r := bufio.NewReader(file)
w := bufio.NewWriter(conn)
for {
line, isPrefix, err := r.ReadLine()
if err != nil {
if err == io.EOF {
break
}
c.log(logPairs{"cmd": "RETR", "err": err})
c.writeln("450 File unavailable.")
return
}
w.Write(line)
if !isPrefix {
w.Write([]byte("\r\n"))
}
}
w.Flush()
}
c.writeln("226 Transfer complete.")
}
func (c *conn) stor(args []string) {
if len(args) != 1 {
c.writeln("501 Usage: STOR filename")
return
}
filename := args[0]
file, err := os.Create(filename)
if err != nil {
c.log(logPairs{"cmd": "STOR", "err": err})
c.writeln("550 File can't be created.")
return
}
c.writeln("150 Ok to send data.")
conn, err := c.dataConn()
if err != nil {
c.writeln("425 Can't open data connection")
return
}
defer conn.Close()
_, err = io.Copy(file, conn)
if err != nil {
c.log(logPairs{"cmd": "RETR", "err": err})
c.writeln("450 File unavailable.")
return
}
c.writeln("226 Transfer complete.")
}
func (c *conn) run() {
c.writeln("220 Ready.")
s := bufio.NewScanner(c.rw)
var cmd string
var args []string
for s.Scan() {
if c.CmdErr() != nil {
c.log(logPairs{"err": fmt.Errorf("command connection: %s", c.CmdErr())})
return
}
fields := strings.Fields(s.Text())
if len(fields) == 0 {
continue
}
cmd = strings.ToUpper(fields[0])
args = nil
if len(fields) > 1 {
args = fields[1:]
}
switch cmd {
case "LIST":
c.list(args)
case "NOOP":
c.writeln("200 Ready.")
case "PASV":
c.pasv(args)
case "PORT":
c.port(args)
case "QUIT":
c.writeln("221 Goodbye.")
return
case "RETR":
c.retr(args)
case "STOR":
c.stor(args)
case "STRU":
c.stru(args)
case "SYST":
// DJB recommends always replying with this string, to be
// consistent with other servers and avoid weird fallback modes in
// some clients.
c.writeln("215 UNIX Type: L8")
case "TYPE":
c.type_(args)
case "USER":
c.writeln("230 Login successful.")
default:
c.writeln(fmt.Sprintf("502 Command %q not implemented.", cmd))
}
// Cleanup PASV listeners if they go unused.
if cmd != "PASV" && c.pasvListener != nil {
c.pasvListener.Close()
c.pasvListener = nil
}
c.prevCmd = cmd
}
if s.Err() != nil {
c.log(logPairs{"err": fmt.Errorf("scanning commands: %s", s.Err())})
}
}
func main() {
var port int
flag.IntVar(&port, "port", 8000, "listen port")
ln, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal("Opening main listener:", err)
}
for {
c, err := ln.Accept()
if err != nil {
log.Print("Accepting new connection:", err)
}
go NewConn(c).run()
}
}