forked from dutchcoders/goftp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftp.go
667 lines (535 loc) · 12.3 KB
/
ftp.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
package goftp
import (
"bufio"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"regexp"
"strconv"
"strings"
"time"
)
var REGEX_PWD_PATH *regexp.Regexp = regexp.MustCompile(`\"(.*)\"`)
type FTP struct {
conn net.Conn
addr string
debug bool
tlsconfig *tls.Config
reader *bufio.Reader
writer *bufio.Writer
}
func (ftp *FTP) Close() {
ftp.conn.Close()
}
type WalkFunc func(item FtpItem) error
type RetrFunc func(r io.Reader) error
type FtpItem struct {
IsDir bool
Permission string
FileCode int
Owner string
Group string
Size int
Time time.Time
Path string
Name string
}
func parseLine(line string) (item FtpItem) {
r, _ := regexp.Compile(
`^(?P<dir>[\-ld])` +
`(?P<permission>(?:[\-r][\-w][\-xs]){3})\s+` +
`(?P<filecode>\d+)\s+` +
`(?P<owner>\w+)\s+` +
`(?P<group>\w+)\s+` +
`(?P<size>\d+)\s+` +
`(?P<ts>` +
`(?:(?P<month>\w{3})\s+(?P<day>\d{2})\s+(?P<hour>\d{2}):(?P<minute>\d{2}))|` +
`(?:(?P<month>\w{3})\s+(?P<day>\d{2})\s+(?P<year>\d{4}))` +
`)\s+` +
`(?P<name>.+)$`)
matches := r.FindStringSubmatch(strings.TrimSpace(line))
if len(matches) > 0 {
result := make(map[string]string)
for i, name := range r.SubexpNames() {
if i != 0 && len(matches[i]) > 0 {
result[name] = matches[i]
}
}
if v, ok := result["dir"]; ok && v != "-" {
item.IsDir = true
}
if v, ok := result["permission"]; ok {
item.Permission = v
}
if v, ok := result["filecode"]; ok {
if i, err := strconv.Atoi(v); err == nil {
item.FileCode = i
}
}
if v, ok := result["owner"]; ok {
item.Owner = v
}
if v, ok := result["group"]; ok {
item.Group = v
}
if v, ok := result["size"]; ok {
if i, err := strconv.Atoi(v); err == nil {
item.Size = i
}
}
if v, ok := result["ts"]; ok {
var err error
item.Time, err = time.Parse("2006 Jan 02 15:04", strconv.Itoa(time.Now().Year()) + " " + v)
if err != nil {
item.Time, _ = time.Parse("Jan 02 2006", v)
}
if item.Time.After(time.Now()) {
item.Time, err = time.Parse("2006 Jan 02 15:04", strconv.Itoa(time.Now().Year() - 1) + " " + v)
}
}
if v, ok := result["name"]; ok {
item.Name = v
}
}
return
}
// walks recursively through path and call walkfunc for each file
func (ftp *FTP) Walk(path string, walkFn WalkFunc, recursive bool) (err error) {
if ftp.debug {
log.Printf("Walking: '%s'\n", path)
}
var lines []string
if lines, err = ftp.List(path); err != nil {
return
}
for _, line := range lines {
item := parseLine(line)
item.Path = path
if item.IsDir {
if err = walkFn(item); err != nil {
return
}
if recursive {
if err = ftp.Walk(item.Path + item.Name + "/", walkFn, recursive); err != nil {
return
}
}
} else {
if err = walkFn(item); err != nil {
return
}
}
}
return
}
// send quit to the server and close the connection
func (ftp *FTP) Quit() (err error) {
if _, err := ftp.cmd("221", "QUIT"); err != nil {
return err
}
ftp.conn.Close()
ftp.conn = nil
return nil
}
// will send a NOOP (no operation) to the server
func (ftp *FTP) Noop() (err error) {
_, err = ftp.cmd("200", "NOOP")
return
}
// Send raw commands, return response as string and response code as int
func (ftp *FTP) RawCmd(command string, args ...interface{}) (code int, line string) {
if ftp.debug {
log.Printf("Raw-> %s\n", fmt.Sprintf(command, args...), code)
}
code = -1
var err error
if err = ftp.send(command, args...); err != nil {
return code, ""
}
if line, err = ftp.receive(); err != nil {
return code, ""
}
code, err = strconv.Atoi(line[:3])
if ftp.debug {
log.Printf("Raw<- <- %d \n", code)
}
return code, line
}
// private function to send command and compare return code with expects
func (ftp *FTP) cmd(expects string, command string, args ...interface{}) (line string, err error) {
if err = ftp.send(command, args...); err != nil {
return
}
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, expects) {
err = errors.New(line)
return
}
return
}
// rename file
func (ftp *FTP) Rename(from string, to string) (err error) {
if _, err = ftp.cmd("350", "RNFR %s", from); err != nil {
return
}
if _, err = ftp.cmd("250", "RNTO %s", to); err != nil {
return
}
return
}
// make directory
func (ftp *FTP) Mkd(path string) error {
_, err := ftp.cmd("257", "MKD %s", path)
return err
}
// get current path
func (ftp *FTP) Pwd() (path string, err error) {
var line string
if line, err = ftp.cmd("257", "PWD"); err != nil {
return
}
res := REGEX_PWD_PATH.FindAllStringSubmatch(line[4:], -1)
path = res[0][1]
return
}
// change current path
func (ftp *FTP) Cwd(path string) (err error) {
_, err = ftp.cmd("250", "CWD %s", path)
return
}
// delete file
func (ftp *FTP) Dele(path string) (err error) {
if err = ftp.send("DELE %s", path); err != nil {
return
}
var line string
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "250") {
return errors.New(line)
}
return
}
// secures the ftp connection by using TLS
func (ftp *FTP) AuthTLS(config tls.Config) error {
if _, err := ftp.cmd("234", "AUTH TLS"); err != nil {
return err
}
// wrap tls on existing connection
ftp.tlsconfig = &config
ftp.conn = tls.Client(ftp.conn, &config)
ftp.writer = bufio.NewWriter(ftp.conn)
ftp.reader = bufio.NewReader(ftp.conn)
if _, err := ftp.cmd("200", "PBSZ 0"); err != nil {
return err
}
if _, err := ftp.cmd("200", "PROT P"); err != nil {
return err
}
return nil
}
// read all the buffered bytes and return
func (ftp *FTP) ReadAndDiscard() (int, error) {
var i int
var err error
buffer_size := ftp.reader.Buffered()
for i = 0; i < buffer_size; i++ {
if _, err = ftp.reader.ReadByte(); err != nil {
return i, err
}
}
return i, err
}
// change transfer type
func (ftp *FTP) Type(t string) error {
_, err := ftp.cmd("200", "TYPE %s", t)
return err
}
func (ftp *FTP) receiveLine() (string, error) {
line, err := ftp.reader.ReadString('\n')
if ftp.debug {
log.Printf("< %s", line)
}
return line, err
}
func (ftp *FTP) receive() (string, error) {
line, err := ftp.receiveLine()
if err != nil {
return line, err
}
if (len(line) >= 4) && (line[3] == '-') {
//Multiline response
closingCode := line[:3] + " "
for {
str, err := ftp.receiveLine()
line = line + str
if err != nil {
return line, err
}
if len(str) < 4 {
if ftp.debug {
log.Println("Uncorrectly terminated response")
}
break
} else {
if str[:4] == closingCode {
break
}
}
}
}
ftp.ReadAndDiscard()
//fmt.Println(line)
return line, err
}
func (ftp *FTP) send(command string, arguments ...interface{}) error {
if ftp.debug {
log.Printf("> %s", fmt.Sprintf(command, arguments...))
}
command = fmt.Sprintf(command, arguments...)
command += "\r\n"
if _, err := ftp.writer.WriteString(command); err != nil {
return err
}
if err := ftp.writer.Flush(); err != nil {
return err
}
return nil
}
// enables passive data connection and returns port number
func (ftp *FTP) Pasv() (port int, err error) {
var line string
if line, err = ftp.cmd("227", "PASV"); err != nil {
return
}
re, err := regexp.Compile(`\((.*)\)`)
res := re.FindAllStringSubmatch(line, -1)
s := strings.Split(res[0][1], ",")
l1, _ := strconv.Atoi(s[len(s)-2])
l2, _ := strconv.Atoi(s[len(s)-1])
port = l1<<8 + l2
return
}
// open new data connection
func (ftp *FTP) newConnection(port int) (conn net.Conn, err error) {
addr := fmt.Sprintf("%s:%d", strings.Split(ftp.addr, ":")[0], port)
if ftp.debug {
log.Printf("Connecting to %s\n", addr)
}
if conn, err = net.Dial("tcp", addr); err != nil {
return
}
if ftp.tlsconfig != nil {
conn = tls.Client(conn, ftp.tlsconfig)
}
return
}
// upload file
func (ftp *FTP) Stor(path string, r io.Reader) (err error) {
if err = ftp.Type("I"); err != nil {
return
}
var port int
if port, err = ftp.Pasv(); err != nil {
return
}
if err = ftp.send("STOR %s", path); err != nil {
return
}
var pconn net.Conn
if pconn, err = ftp.newConnection(port); err != nil {
return
}
var line string
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "150") {
err = errors.New(line)
return
}
if _, err = io.Copy(pconn, r); err != nil {
return
}
pconn.Close()
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "226") {
err = errors.New(line)
return
}
return
}
// retrieves file
func (ftp *FTP) Retr(path string, retrFn RetrFunc) (err error) {
if err = ftp.Type("I"); err != nil {
return
}
var port int
if port, err = ftp.Pasv(); err != nil {
return
}
if err = ftp.send("RETR %s", path); err != nil {
return
}
var pconn net.Conn
if pconn, err = ftp.newConnection(port); err != nil {
return
}
var line string
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "150") {
err = errors.New(line)
return
}
if err = retrFn(pconn); err != nil {
return
}
pconn.Close()
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "226") {
err = errors.New(line)
return
}
return
}
/*func GetFilesList(path string) (files []string, err error) {
}*/
// list the path (or current directory)
func (ftp *FTP) List(path string) (files []string, err error) {
if err = ftp.Type("A"); err != nil {
return
}
var port int
if port, err = ftp.Pasv(); err != nil {
return
}
// check if MLSD works
if err = ftp.send("MLSD %s", path); err != nil {
}
var pconn net.Conn
if pconn, err = ftp.newConnection(port); err != nil {
return
}
var line string
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "150") {
// MLSD failed, lets try LIST
if err = ftp.send("LIST %s", path); err != nil {
return
}
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "150") {
// Really list is not working here
err = errors.New(line)
return
}
}
reader := bufio.NewReader(pconn)
for {
line, err = reader.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return
}
files = append(files, string(line))
}
pconn.Close()
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, "226") {
err = errors.New(line)
return
}
return
}
/*
// login on server with strange login behavior
func (ftp *FTP) SmartLogin(username string, password string) (err error) {
var code int
// Maybe the server has some useless words to say. Make him talk
code, _ = ftp.RawCmd("NOOP")
if code == 220 || code == 530 {
// Maybe with another Noop the server will ask us to login?
code, _ = ftp.RawCmd("NOOP")
if code == 530 {
// ok, let's login
code, _ = ftp.RawCmd("USER %s", username)
code, _ = ftp.RawCmd("NOOP")
if code == 331 {
// user accepted, password required
code, _ = ftp.RawCmd("PASS %s", password)
code, _ = ftp.RawCmd("PASS %s", password)
if code == 230 {
code, _ = ftp.RawCmd("NOOP")
return
}
}
}
}
// Nothing strange... let's try a normal login
return ftp.Login(username, password)
}
*/
// login to the server
func (ftp *FTP) Login(username string, password string) (err error) {
if _, err = ftp.cmd("331", "USER %s", username); err != nil {
if strings.HasPrefix(err.Error(), "230") {
// Ok, probably anonymous server
// but login was fine, so return no error
err = nil
} else {
return
}
}
if _, err = ftp.cmd("230", "PASS %s", password); err != nil {
return
}
return
}
// connect to server, debug is OFF
func Connect(addr string) (*FTP, error) {
var err error
var conn net.Conn
if conn, err = net.Dial("tcp", addr); err != nil {
return nil, err
}
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
//reader.ReadString('\n')
object := &FTP{conn: conn, addr: addr, reader: reader, writer: writer, debug: false}
object.receive()
return object, nil
}
// connect to server, debug is ON
func ConnectDbg(addr string) (*FTP, error) {
var err error
var conn net.Conn
if conn, err = net.Dial("tcp", addr); err != nil {
return nil, err
}
writer := bufio.NewWriter(conn)
reader := bufio.NewReader(conn)
var line string
object := &FTP{conn: conn, addr: addr, reader: reader, writer: writer, debug: true}
line, _ = object.receive()
log.Print(line)
return object, nil
}