-
Notifications
You must be signed in to change notification settings - Fork 99
/
ftp.go
776 lines (629 loc) · 15.4 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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
package goftp
import (
"bufio"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
)
// RePwdPath is the default expression for matching files in the current working directory
var RePwdPath = regexp.MustCompile(`\"(.*)\"`)
// FTP is a session for File Transfer Protocol
type FTP struct {
conn net.Conn
addr string
debug bool
tlsconfig *tls.Config
reader *bufio.Reader
writer *bufio.Writer
}
// Close ends the FTP connection
func (ftp *FTP) Close() error {
return ftp.conn.Close()
}
type (
// WalkFunc is called on each path in a Walk. Errors are filtered through WalkFunc
WalkFunc func(path string, info os.FileMode, err error) error
// RetrFunc is passed to Retr and is the handler for the stream received for a given path
RetrFunc func(r io.Reader) error
)
func parseLine(line string) (perm string, t string, filename string) {
for _, v := range strings.Split(line, ";") {
v2 := strings.Split(v, "=")
switch v2[0] {
case "perm":
perm = v2[1]
case "type":
t = v2[1]
default:
filename = v[1 : len(v)-2]
}
}
return
}
// Walk walks recursively through path and call walkfunc for each file
func (ftp *FTP) Walk(path string, walkFn WalkFunc) (err error) {
/*
if err = walkFn(path, os.ModeDir, nil); err != nil {
if err == filepath.SkipDir {
return nil
}
}
*/
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 {
_, t, subpath := parseLine(line)
switch t {
case "dir":
if subpath == "." {
} else if subpath == ".." {
} else {
if err = ftp.Walk(path+subpath+"/", walkFn); err != nil {
return
}
}
case "file":
if err = walkFn(path+subpath, os.FileMode(0), nil); err != nil {
return
}
}
}
return
}
// Quit sends quit to the server and close the connection. No need to Close after this.
func (ftp *FTP) Quit() (err error) {
if _, err := ftp.cmd(StatusConnectionClosing, "QUIT"); err != nil {
return err
}
ftp.conn.Close()
ftp.conn = nil
return nil
}
// Noop will send a NOOP (no operation) to the server
func (ftp *FTP) Noop() (err error) {
_, err = ftp.cmd(StatusOK, "NOOP")
return
}
// RawCmd sends raw commands to the remote server. Returns response code as int and response as string.
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 = -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 on the remote host
func (ftp *FTP) Rename(from string, to string) (err error) {
if _, err = ftp.cmd(StatusActionPending, "RNFR %s", from); err != nil {
return
}
if _, err = ftp.cmd(StatusActionOK, "RNTO %s", to); err != nil {
return
}
return
}
// Mkd makes a directory on the remote host
func (ftp *FTP) Mkd(path string) error {
_, err := ftp.cmd(StatusPathCreated, "MKD %s", path)
return err
}
// Rmd remove directory
func (ftp *FTP) Rmd(path string) (err error) {
_, err = ftp.cmd(StatusActionOK, "RMD %s", path)
return
}
// Pwd gets current path on the remote host
func (ftp *FTP) Pwd() (path string, err error) {
var line string
if line, err = ftp.cmd(StatusPathCreated, "PWD"); err != nil {
return
}
res := RePwdPath.FindAllStringSubmatch(line[4:], -1)
path = res[0][1]
return
}
// Cwd changes current working directory on remote host to path
func (ftp *FTP) Cwd(path string) (err error) {
_, err = ftp.cmd(StatusActionOK, "CWD %s", path)
return
}
// Dele deletes path on remote host
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, StatusActionOK) {
return errors.New(line)
}
return
}
// AuthTLS 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(StatusOK, "PBSZ 0"); err != nil {
return err
}
if _, err := ftp.cmd(StatusOK, "PROT P"); err != nil {
return err
}
return nil
}
// ReadAndDiscard reads all the buffered bytes and returns the number of bytes
// that cleared from the buffer
func (ftp *FTP) ReadAndDiscard() (int, error) {
var i int
bufferSize := ftp.reader.Buffered()
for i = 0; i < bufferSize; i++ {
if _, err := ftp.reader.ReadByte(); err != nil {
return i, err
}
}
return i, nil
}
// Type changes transfer type.
func (ftp *FTP) Type(t TypeCode) error {
_, err := ftp.cmd(StatusOK, "TYPE %s", t)
return err
}
// TypeCode for the representation types
type TypeCode string
const (
// TypeASCII for ASCII
TypeASCII = "A"
// TypeEBCDIC for EBCDIC
TypeEBCDIC = "E"
// TypeImage for an Image
TypeImage = "I"
// TypeLocal for local byte size
TypeLocal = "L"
)
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) receiveNoDiscard() (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
}
// Pasv enables passive data connection and returns port number
func (ftp *FTP) Pasv() (port int, err error) {
doneChan := make(chan int, 1)
go func() {
defer func() {
doneChan <- 1
}()
var line string
if line, err = ftp.cmd("227", "PASV"); err != nil {
return
}
re := regexp.MustCompile(`\((.*)\)`)
res := re.FindAllStringSubmatch(line, -1)
if len(res) == 0 || len(res[0]) < 2 {
err = errors.New("PasvBadAnswer")
return
}
s := strings.Split(res[0][1], ",")
if len(s) < 2 {
err = errors.New("PasvBadAnswer")
return
}
l1, _ := strconv.Atoi(s[len(s)-2])
l2, _ := strconv.Atoi(s[len(s)-1])
port = l1<<8 + l2
return
}()
select {
case _ = <-doneChan:
case <-time.After(time.Second * 10):
err = errors.New("PasvTimeout")
ftp.Close()
}
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
}
// Stor uploads file to remote host path, from r
func (ftp *FTP) Stor(path string, r io.Reader) (err error) {
if err = ftp.Type(TypeImage); 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
}
defer pconn.Close()
var line string
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, StatusFileOK) {
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, StatusClosingDataConnection) {
err = errors.New(line)
return
}
return
}
// Syst returns the system type of the remote host
func (ftp *FTP) Syst() (line string, err error) {
if err := ftp.send("SYST"); err != nil {
return "", err
}
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, StatusSystemType) {
err = errors.New(line)
return
}
return strings.SplitN(strings.TrimSpace(line), " ", 2)[1], nil
}
// System types from Syst
var (
SystemTypeUnixL8 = "UNIX Type: L8"
SystemTypeWindowsNT = "Windows_NT"
)
var reSystStatus = map[string]*regexp.Regexp{
SystemTypeUnixL8: regexp.MustCompile(""),
SystemTypeWindowsNT: regexp.MustCompile(""),
}
// Stat gets the status of path from the remote host
func (ftp *FTP) Stat(path string) ([]string, error) {
if err := ftp.send("STAT %s", path); err != nil {
return nil, err
}
stat, err := ftp.receive()
if err != nil {
return nil, err
}
if !strings.HasPrefix(stat, StatusFileStatus) &&
!strings.HasPrefix(stat, StatusDirectoryStatus) &&
!strings.HasPrefix(stat, StatusSystemStatus) {
return nil, errors.New(stat)
}
if strings.HasPrefix(stat, StatusSystemStatus) {
return strings.Split(stat, "\n"), nil
}
lines := []string{}
for _, line := range strings.Split(stat, "\n") {
if strings.HasPrefix(line, StatusFileStatus) {
continue
}
//fmt.Printf("%v\n", re.FindAllStringSubmatch(line, -1))
lines = append(lines, strings.TrimSpace(line))
}
// TODO(vbatts) parse this line for SystemTypeWindowsNT
//"213-status of /remfdata/all.zip:\r\n 09-12-15 04:07AM 37192705 all.zip\r\n213 End of status.\r\n"
// and this for SystemTypeUnixL8
// "-rw-r--r-- 22 4015 4015 17976 Jun 10 1994 COPYING"
// "drwxr-xr-x 6 4015 4015 4096 Aug 21 17:25 kernels"
return lines, nil
}
// Retr retrieves file from remote host at path, using retrFn to read from the remote file.
func (ftp *FTP) Retr(path string, retrFn RetrFunc) (s string, err error) {
if err = ftp.Type(TypeImage); 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
}
defer pconn.Close()
var line string
if line, err = ftp.receiveNoDiscard(); err != nil {
return
}
if !strings.HasPrefix(line, StatusFileOK) {
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, StatusClosingDataConnection) {
err = errors.New(line)
return
}
return
}
/*func GetFilesList(path string) (files []string, err error) {
}*/
// List lists the path (or current directory)
func (ftp *FTP) List(path string) (files []string, err error) {
if err = ftp.Type(TypeASCII); 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
}
defer pconn.Close()
var line string
if line, err = ftp.receiveNoDiscard(); err != nil {
return
}
if !strings.HasPrefix(line, StatusFileOK) {
// MLSD failed, lets try LIST
if err = ftp.send("LIST %s", path); err != nil {
return
}
if line, err = ftp.receiveNoDiscard(); err != nil {
return
}
if !strings.HasPrefix(line, StatusFileOK) {
// 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))
}
// Must close for vsftp tlsed conenction otherwise does not receive connection
pconn.Close()
if line, err = ftp.receive(); err != nil {
return
}
if !strings.HasPrefix(line, StatusClosingDataConnection) {
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 with provided username and password.
// Typical default may be ("anonymous","").
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 at addr (format "host:port"). 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
}
// ConnectDbg to server at addr (format "host:port"). 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
}
// Size returns the size of a file.
func (ftp *FTP) Size(path string) (size int, err error) {
line, err := ftp.cmd("213", "SIZE %s", path)
if err != nil {
return 0, err
}
return strconv.Atoi(line[4 : len(line)-2])
}