-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
515 lines (469 loc) · 11.9 KB
/
main.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
)
type userConfig struct {
Password string `json:"password"`
HomeDir string `json:"homeDir"`
}
type FTPConn struct {
conn net.Conn
username string
running bool
homeDir string
currDir string
identified bool
pasv bool
dataConn net.Conn
dataHost string
dataPort int
listener net.Listener // For Pasv mode
commands map[string]func(string)
config map[string]userConfig
renameTempPath string
}
var p = flag.Int("p", 9021, "listen port")
func main() {
flag.Parse()
config, err := parseConfig()
if err != nil {
log.Println(err)
os.Exit(1)
}
laddr := fmt.Sprintf(":%d", *p)
listener, err := net.Listen("tcp", laddr)
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
log.Printf("New Connection from %s\n", conn.RemoteAddr())
go handleConn(conn, config)
}
listener.Close()
}
func handleConn(conn net.Conn, config map[string]userConfig) {
handler := NewFTPConn(conn, config)
handler.start()
}
func parseConfig() (map[string]userConfig, error) {
file, err := os.Open("config.json")
if err != nil {
log.Println(err)
return nil, err
}
defer file.Close()
decoder := json.NewDecoder(file)
config := make(map[string]userConfig)
decoder.Decode(&config)
return config, nil
}
func NewFTPConn(conn net.Conn, config map[string]userConfig) *FTPConn {
ftpConn := &FTPConn{conn: conn, config: config, running: true, identified: false}
ftpConn.buildCommandMap()
dir, err := os.Getwd()
if err != nil {
dir = "."
}
ftpConn.homeDir = dir
ftpConn.currDir = "/"
return ftpConn
}
func (ftpConn *FTPConn) start() error {
ftpConn.buildCommandMap()
ftpConn.sayWelcome()
input := bufio.NewScanner(ftpConn.conn)
for input.Scan() {
command, arg := "", ""
data := strings.Split(input.Text(), " ")
length := len(data)
if len(data) == 0 {
ftpConn.running = false
break
} else if length == 1 {
command = data[0]
} else {
command = data[0]
arg = data[1]
}
methond, ok := ftpConn.commands[strings.ToUpper(command)]
if !ok {
ftpConn.sendMsg(500, "Command Not Found")
continue
}
methond(arg)
if !ftpConn.running {
break
}
}
ftpConn.sayBye()
ftpConn.closeDataConn()
ftpConn.conn.Close()
log.Println("FTP connnection closed.")
return nil
}
func (ftpConn *FTPConn) sayWelcome() {
ftpConn.sendMsg(220, "Welcome to Ftp.go FTP")
}
func (ftpConn *FTPConn) sayBye() {
ftpConn.sendMsg(200, "OK")
}
func (ftpConn *FTPConn) sendMsg(code int, msg string) error {
_, err := fmt.Fprintf(ftpConn.conn, "%d %s\r\n", code, msg)
if err != nil {
log.Println(err)
}
return err
}
func (ftpConn *FTPConn) parsePath(arg string) (remote, local string) {
if arg == "" {
arg = "."
}
if arg[0] != '/' {
arg = path.Join(ftpConn.currDir, arg)
}
arg = filepath.Clean(arg)
local = path.Join(ftpConn.homeDir, arg)
remote = arg
if remote == "." {
remote = "/"
}
return
}
func (ftpConn *FTPConn) dataConnConn() (err error) {
ftpConn.closeDataConn()
var conn net.Conn
if ftpConn.pasv {
conn, err = ftpConn.listener.Accept()
if err != nil {
return
}
} else {
raddr := fmt.Sprintf("%s:%d", ftpConn.dataHost, ftpConn.dataPort)
conn, err = net.Dial("tcp", raddr)
if err != nil {
return
}
}
ftpConn.dataConn = conn
return
}
func (ftpConn *FTPConn) closeDataConn() {
if ftpConn.dataConn != nil {
ftpConn.dataConn.Close()
ftpConn.dataConn = nil
}
}
func (ftpConn *FTPConn) handleSecurity(f func(string)) func(string) {
return func(arg string) {
if ftpConn.identified {
f(arg)
} else {
ftpConn.sendMsg(530, "Not logged in")
}
}
}
func (ftpConn *FTPConn) handleUSER(arg string) {
if userConfig, ok := ftpConn.config[arg]; ok {
ftpConn.username = arg
if arg == "anonymous" {
ftpConn.identified = true
ftpConn.homeDir = userConfig.HomeDir
ftpConn.sendMsg(230, "OK")
} else {
ftpConn.sendMsg(331, "Need password")
}
} else {
ftpConn.sendMsg(550, "Invalid User")
ftpConn.running = false
}
}
func (ftpConn *FTPConn) handlePASS(arg string) {
if arg == ftpConn.config[ftpConn.username].Password {
ftpConn.homeDir = ftpConn.config[ftpConn.username].HomeDir
ftpConn.identified = true
ftpConn.sendMsg(230, "OK")
} else {
ftpConn.sendMsg(530, "Password is not corrected")
ftpConn.running = false
}
}
func (ftpConn *FTPConn) handleCWD(arg string) {
remote, local := ftpConn.parsePath(arg)
info, err := os.Stat(local)
if err != nil {
log.Println(err)
ftpConn.sendMsg(500, "Change directory failed!")
return
}
if info.IsDir() {
ftpConn.currDir = remote
ftpConn.sendMsg(250, "Working directory changed")
} else {
ftpConn.sendMsg(500, "Change directory failed!")
}
}
func (ftpConn *FTPConn) handleXCWD(arg string) {
ftpConn.handleCWD(arg)
}
func (ftpConn *FTPConn) handleCDUP(arg string) {
ftpConn.handleCWD("..")
}
func (ftpConn *FTPConn) handleRNFR(arg string) {
remote, local := ftpConn.parsePath(arg)
ftpConn.renameTempPath = local
ftpConn.sendMsg(350, "rename from "+remote)
}
func (ftpConn *FTPConn) handleRNTO(arg string) {
remote, local := ftpConn.parsePath(arg)
os.Rename(ftpConn.renameTempPath, local)
ftpConn.sendMsg(250, "rename to "+remote)
}
func (ftpConn *FTPConn) handleDELE(arg string) {
_, local := ftpConn.parsePath(arg)
if _, err := os.Stat(local); os.IsNotExist(err) {
ftpConn.sendMsg(450, "File does not exist")
} else {
os.Remove(local)
ftpConn.sendMsg(250, "File deleted")
}
}
func (ftpConn *FTPConn) handleRMD(arg string) {
_, local := ftpConn.parsePath(arg)
if _, err := os.Stat(local); os.IsNotExist(err) {
ftpConn.sendMsg(500, "Directory does not exist")
} else {
os.Remove(local)
ftpConn.sendMsg(250, "OK")
}
}
func (ftpConn *FTPConn) handleMKD(arg string) {
_, local := ftpConn.parsePath(arg)
if _, err := os.Stat(local); os.IsNotExist(err) {
os.MkdirAll(local, os.ModePerm)
ftpConn.sendMsg(257, fmt.Sprintf("\"%s\" directory created", arg))
} else {
ftpConn.sendMsg(500, "Folder is already existed")
}
}
func (ftpConn *FTPConn) handleXMKD(arg string) {
ftpConn.handleMKD(arg)
}
func (ftpConn *FTPConn) handlePWD(arg string) {
remote, _ := ftpConn.parsePath(arg)
ftpConn.sendMsg(257, fmt.Sprintf("\"%s\"", remote))
}
func (ftpConn *FTPConn) handleLIST(arg string) {
if err := ftpConn.dataConnConn(); err != nil {
ftpConn.handleErr(err, 500, "List directory failed")
return
}
defer ftpConn.closeDataConn()
ftpConn.sendMsg(125, "OK")
format := "%s%s%s------ %d %s %s %d %s %s\r\n"
_, local := ftpConn.parsePath(ftpConn.currDir)
infos, err := ioutil.ReadDir(local)
if err != nil {
ftpConn.handleErr(err, 500, "List directory failed")
return
}
for _, info := range infos {
var f string = "-"
var modTime string
if time.Now().Sub(info.ModTime()).Hours() > 6*30*24 {
modTime = info.ModTime().Format("JAN 02 2006")
} else {
modTime = info.ModTime().Format("01 02 15:04")
}
if info.IsDir() {
f = "d"
}
msg := fmt.Sprintf(format,
f, "r", "w", 1, "0", "0",
info.Size(), modTime, info.Name())
io.WriteString(ftpConn.dataConn, msg)
}
ftpConn.sendMsg(226, "Limit")
}
func (ftpConn *FTPConn) handleQUIT(arg string) {
ftpConn.closeDataConn()
ftpConn.running = false
ftpConn.username = ""
ftpConn.identified = false
ftpConn.sendMsg(221, "OK")
}
func (ftpConn *FTPConn) handlePORT(arg string) {
ftpConn.closeDataConn()
params := strings.Split(arg, ",")
if len(params) != 6 {
ftpConn.sendMsg(501, "Parameter error")
} else {
ftpConn.dataHost = strings.Join(params[:4], ".")
p1, err := strconv.Atoi(params[4])
if err != nil {
ftpConn.handleErr(err, 501, "Parameter error")
return
}
p2, err := strconv.Atoi(params[5])
if err != nil {
ftpConn.sendMsg(501, "Parameter error")
return
}
ftpConn.dataPort = p1*256 + p2
ftpConn.sendMsg(200, "OK")
ftpConn.pasv = false
}
}
func (ftpConn *FTPConn) handlePASV(arg string) {
if ftpConn.listener != nil {
ftpConn.listener.Close()
ftpConn.listener = nil
}
ip, err := externalIP()
if err != nil {
ftpConn.handleErr(err, 500, "passive mode error")
return
}
laddr := fmt.Sprintf("%s:0", ip)
l, err := net.Listen("tcp", laddr)
if err != nil {
ftpConn.handleErr(err, 500, "passive mode error")
return
}
ftpConn.listener = l
h := strings.Replace(ip, ".", ",", -1)
port := l.Addr().(*net.TCPAddr).Port
ftpConn.sendMsg(227, fmt.Sprintf("Entering Passive Mode (%s,%d,%d)", h, port>>8&0xFF, port&0xFF))
ftpConn.pasv = true
}
func (ftpConn *FTPConn) handleTYPE(arg string) {
ftpConn.sendMsg(220, "OK")
}
func (ftpConn *FTPConn) handleRETR(arg string) {
if err := ftpConn.dataConnConn(); err != nil {
ftpConn.handleErr(err, 425, "Can't open data connection")
return
}
defer ftpConn.closeDataConn()
ftpConn.sendMsg(125, "OK")
_, local := ftpConn.parsePath(arg)
f, err := os.Open(local)
if err != nil {
ftpConn.sendMsg(450, "Can't open file")
return
}
defer f.Close()
_, err = io.Copy(ftpConn.dataConn, f)
if err != nil {
ftpConn.sendMsg(451, "Transfer file failed")
return
}
ftpConn.sendMsg(226, "OK")
}
func (ftpConn *FTPConn) handleSTOR(arg string) {
if err := ftpConn.dataConnConn(); err != nil {
ftpConn.handleErr(err, 425, "Can't open data connection")
return
}
defer ftpConn.closeDataConn()
ftpConn.sendMsg(125, "OK")
_, local := ftpConn.parsePath(arg)
f, err := os.Create(local)
if err != nil {
ftpConn.sendMsg(450, "Can't create file")
return
}
defer f.Close()
_, err = io.Copy(f, ftpConn.dataConn)
if err != nil {
ftpConn.sendMsg(451, "Store file failed")
return
}
ftpConn.sendMsg(226, "OK")
}
func (ftpConn *FTPConn) handleSYST(arg string) {
ftpConn.sendMsg(215, "UNIX")
}
func (ftpConn *FTPConn) handleErr(err error, code int, msg string) {
log.Println(err)
ftpConn.sendMsg(code, msg)
}
func (ftpConn *FTPConn) buildCommandMap() {
ftpConn.commands = make(map[string]func(string))
commands := ftpConn.commands
commands["USER"] = ftpConn.handleUSER
commands["PASS"] = ftpConn.handlePASS
commands["CWD"] = ftpConn.handleSecurity(ftpConn.handleCWD)
commands["XCWD"] = ftpConn.handleSecurity(ftpConn.handleXCWD)
commands["CDUP"] = ftpConn.handleSecurity(ftpConn.handleCDUP)
commands["RNFR"] = ftpConn.handleSecurity(ftpConn.handleRNFR)
commands["RNTO"] = ftpConn.handleSecurity(ftpConn.handleRNTO)
commands["DELE"] = ftpConn.handleSecurity(ftpConn.handleDELE)
commands["RMD"] = ftpConn.handleSecurity(ftpConn.handleRMD)
commands["MKD"] = ftpConn.handleSecurity(ftpConn.handleMKD)
commands["XMKD"] = ftpConn.handleSecurity(ftpConn.handleXMKD)
commands["PWD"] = ftpConn.handleSecurity(ftpConn.handlePWD)
commands["QUIT"] = ftpConn.handleSecurity(ftpConn.handleQUIT)
commands["PORT"] = ftpConn.handleSecurity(ftpConn.handlePORT)
commands["PASV"] = ftpConn.handleSecurity(ftpConn.handlePASV)
commands["TYPE"] = ftpConn.handleSecurity(ftpConn.handleTYPE)
commands["RETR"] = ftpConn.handleSecurity(ftpConn.handleRETR)
commands["STOR"] = ftpConn.handleSecurity(ftpConn.handleSTOR)
commands["SYST"] = ftpConn.handleSecurity(ftpConn.handleSYST)
commands["LIST"] = ftpConn.handleSecurity(ftpConn.handleLIST)
}
// http://play.golang.org/p/BDt3qEQ_2H
func externalIP() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
return ip.String(), nil
}
}
return "", errors.New("are you connected to the network?")
}