Debian Codegraph @

debian/vendor/github.com/etix/goftp/ftp.go

raw
1 // Package ftp implements a FTP client as described in RFC 959.
2 package ftp
3
4 import (
5 "bufio"
6 "errors"
7 "io"
8 "net"
9 "net/textproto"
10 "strconv"
11 "strings"
12 "time"
13 "unicode"
14 )
15
16 // EntryType describes the different types of an Entry.
17 type EntryType int
18
19 // The differents types of an Entry
20 const (
21 EntryTypeFile EntryType = iota
22 EntryTypeFolder
23 EntryTypeLink
24 )
25
26 // ServerConn represents the connection to a remote FTP server.
27 type ServerConn struct {
28 conn *textproto.Conn
29 host string
30 timeout time.Duration
31 rwtimeout time.Duration
32 features map[string]string
33 disableEPSV bool
34 listall bool
35 }
36
37 // Entry describes a file and is returned by List().
38 type Entry struct {
39 Name string
40 Type EntryType
41 Size uint64
42 Time time.Time
43 }
44
45 // response represent a data-connection
46 type response struct {
47 conn net.Conn
48 c *ServerConn
49 }
50
51 type ttConn struct {
52 net.Conn
53 timeout time.Duration
54 }
55
56 func (t ttConn) Read(buf []byte) (int, error) {
57 t.Conn.SetReadDeadline(time.Now().Add(t.timeout))
58 return t.Conn.Read(buf)
59 }
60
61 func (t ttConn) Write(buf []byte) (int, error) {
62 t.Conn.SetWriteDeadline(time.Now().Add(t.timeout))
63 return t.Conn.Write(buf)
64 }
65
66 // Connect is an alias to Dial, for backward compatibility
67 func Connect(addr string) (*ServerConn, error) {
68 return Dial(addr)
69 }
70
71 // Dial is like DialTimeout with no timeout
72 func Dial(addr string) (*ServerConn, error) {
73 return DialTimeout(addr, 0, 0)
74 }
75
76 // DialTimeout initializes the connection to the specified ftp server address.
77 //
78 // It is generally followed by a call to Login() as most FTP commands require
79 // an authenticated user.
80 func DialTimeout(addr string, timeout time.Duration, rwtimeout time.Duration) (*ServerConn, error) {
81 tconn, err := net.DialTimeout("tcp", addr, timeout)
82 if err != nil {
83 return nil, err
84 }
85
86 ttconn := ttConn{
87 Conn: tconn,
88 timeout: rwtimeout,
89 }
90
91 // Use the resolved IP address in case addr contains a domain name
92 // If we use the domain name, we might not resolve to the same IP.
93 remoteAddr := ttconn.RemoteAddr().String()
94 host, _, err := net.SplitHostPort(remoteAddr)
95 if err != nil {
96 return nil, err
97 }
98
99 conn := textproto.NewConn(ttconn)
100
101 c := &ServerConn{
102 conn: conn,
103 host: host,
104 timeout: timeout,
105 rwtimeout: rwtimeout,
106 features: make(map[string]string),
107 listall: true,
108 }
109
110 _, _, err = c.conn.ReadResponse(StatusReady)
111 if err != nil {
112 c.Quit()
113 return nil, err
114 }
115
116 err = c.feat()
117 if err != nil {
118 c.Quit()
119 return nil, err
120 }
121
122 return c, nil
123 }
124
125 // Login authenticates the client with specified user and password.
126 //
127 // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
128 // that allows anonymous read-only accounts.
129 func (c *ServerConn) Login(user, password string) error {
130 code, message, err := c.cmd(-1, "USER %s", user)
131 if err != nil {
132 return err
133 }
134
135 switch code {
136 case StatusLoggedIn:
137 case StatusUserOK:
138 _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
139 if err != nil {
140 return err
141 }
142 default:
143 return errors.New(message)
144 }
145
146 // Switch to binary mode
147 _, _, err = c.cmd(StatusCommandOK, "TYPE I")
148 if err != nil {
149 return err
150 }
151
152 return nil
153 }
154
155 // feat issues a FEAT FTP command to list the additional commands supported by
156 // the remote FTP server.
157 // FEAT is described in RFC 2389
158 func (c *ServerConn) feat() error {
159 code, message, err := c.cmd(-1, "FEAT")
160 if err != nil {
161 return err
162 }
163
164 if code != StatusSystem {
165 // The server does not support the FEAT command. This is not an
166 // error: we consider that there is no additional feature.
167 return nil
168 }
169
170 lines := strings.Split(message, "\n")
171 for _, line := range lines {
172 if !strings.HasPrefix(line, " ") {
173 continue
174 }
175
176 line = strings.TrimSpace(line)
177 featureElements := strings.SplitN(line, " ", 2)
178
179 command := featureElements[0]
180
181 var commandDesc string
182 if len(featureElements) == 2 {
183 commandDesc = featureElements[1]
184 }
185
186 c.features[command] = commandDesc
187 }
188
189 return nil
190 }
191
192 func (c *ServerConn) Feature(feat string) (string, bool) {
193 v, ok := c.features[feat]
194 return v, ok
195 }
196
197 // epsv issues an "EPSV" command to get a port number for a data connection.
198 func (c *ServerConn) epsv() (port int, err error) {
199 _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
200 if err != nil {
201 return
202 }
203
204 start := strings.Index(line, "|||")
205 end := strings.LastIndex(line, "|")
206 if start == -1 || end == -1 {
207 err = errors.New("Invalid EPSV response format")
208 return
209 }
210 port, err = strconv.Atoi(line[start+3 : end])
211 return
212 }
213
214 // pasv issues a "PASV" command to get a port number for a data connection.
215 func (c *ServerConn) pasv() (port int, err error) {
216 _, line, err := c.cmd(StatusPassiveMode, "PASV")
217 if err != nil {
218 return
219 }
220
221 // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
222 start := strings.Index(line, "(")
223 end := strings.LastIndex(line, ")")
224 if start == -1 || end == -1 {
225 return 0, errors.New("Invalid PASV response format")
226 }
227
228 // We have to split the response string
229 pasvData := strings.Split(line[start+1:end], ",")
230
231 if len(pasvData) < 6 {
232 return 0, errors.New("Invalid PASV response format")
233 }
234
235 // Let's compute the port number
236 portPart1, err1 := strconv.Atoi(pasvData[4])
237 if err1 != nil {
238 err = err1
239 return
240 }
241
242 portPart2, err2 := strconv.Atoi(pasvData[5])
243 if err2 != nil {
244 err = err2
245 return
246 }
247
248 // Recompose port
249 port = portPart1*256 + portPart2
250 return
251 }
252
253 // getDataConnPort returns a port for a new data connection
254 // it uses the best available method to do so
255 func (c *ServerConn) getDataConnPort() (int, error) {
256 if !c.disableEPSV {
257 if port, err := c.epsv(); err == nil {
258 return port, nil
259 }
260
261 // if there is an error, disable EPSV for the next attempts
262 c.disableEPSV = true
263 }
264
265 return c.pasv()
266 }
267
268 // openDataConn creates a new FTP data connection.
269 func (c *ServerConn) openDataConn() (net.Conn, error) {
270 port, err := c.getDataConnPort()
271 if err != nil {
272 return nil, err
273 }
274
275 tconn, err := net.DialTimeout("tcp", net.JoinHostPort(c.host, strconv.Itoa(port)), c.timeout)
276 if err != nil {
277 return tconn, err
278 }
279
280 conn := ttConn{
281 Conn: tconn,
282 timeout: c.rwtimeout,
283 }
284 return conn, nil
285 }
286
287 // cmd is a helper function to execute a command and check for the expected FTP
288 // return code
289 func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
290 _, err := c.conn.Cmd(format, args...)
291 if err != nil {
292 return 0, "", err
293 }
294
295 return c.conn.ReadResponse(expected)
296 }
297
298 // cmdDataConnFrom executes a command which require a FTP data connection.
299 // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
300 func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
301 conn, err := c.openDataConn()
302 if err != nil {
303 return nil, err
304 }
305
306 if offset != 0 {
307 _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
308 if err != nil {
309 conn.Close()
310 return nil, err
311 }
312 }
313
314 _, err = c.conn.Cmd(format, args...)
315 if err != nil {
316 conn.Close()
317 return nil, err
318 }
319
320 code, msg, err := c.conn.ReadResponse(-1)
321 if err != nil {
322 conn.Close()
323 return nil, err
324 }
325 if code != StatusAlreadyOpen && code != StatusAboutToSend {
326 conn.Close()
327 return nil, &textproto.Error{Code: code, Msg: msg}
328 }
329
330 return conn, nil
331 }
332
333 var errUnsupportedListLine = errors.New("Unsupported LIST line")
334
335 // parseRFC3659ListLine parses the style of directory line defined in RFC 3659.
336 func parseRFC3659ListLine(line string) (*Entry, error) {
337 iSemicolon := strings.Index(line, ";")
338 iWhitespace := strings.Index(line, " ")
339
340 if iSemicolon < 0 || iSemicolon > iWhitespace {
341 return nil, errUnsupportedListLine
342 }
343
344 e := &Entry{
345 Name: line[iWhitespace+1:],
346 }
347
348 for _, field := range strings.Split(line[:iWhitespace-1], ";") {
349 i := strings.Index(field, "=")
350 if i < 1 {
351 return nil, errUnsupportedListLine
352 }
353
354 key := field[:i]
355 value := field[i+1:]
356
357 switch key {
358 case "modify":
359 var err error
360 e.Time, err = time.Parse("20060102150405", value)
361 if err != nil {
362 return nil, err
363 }
364 case "type":
365 switch value {
366 case "cdir", "pdir":
367 // Discard current and parent dir
368 return nil, nil
369 case "dir":
370 e.Type = EntryTypeFolder
371 case "file":
372 e.Type = EntryTypeFile
373 case "OS.unix=symlink":
374 e.Type = EntryTypeLink
375 }
376 case "size":
377 e.setSize(value)
378 }
379 }
380 return e, nil
381 }
382
383 // parse file or folder name with starting or containing multiple whitespaces
384 func fieldsLsList(s string) []string {
385 n := 8
386 fields := make([]string, 0, n+1)
387 fieldStart := -1
388 nextbreak := false
389 for i, c := range s {
390 if unicode.IsSpace(c) {
391 if fieldStart >= 0 {
392 fields = append(fields, s[fieldStart:i])
393 fieldStart = -1
394 }
395 if nextbreak {
396 fields = append(fields, s[i+1:])
397 break
398 }
399 } else {
400 if fieldStart == -1 {
401 fieldStart = i
402 if len(fields) == n-1 {
403 nextbreak = true
404 }
405 }
406 }
407 }
408 if fieldStart != -1 {
409 fields = append(fields, s[fieldStart:])
410 }
411 return fields
412 }
413
414 // parseLsListLine parses a directory line in a format based on the output of
415 // the UNIX ls command.
416 func parseLsListLine(line string) (*Entry, error) {
417 fields := fieldsLsList(line)
418
419 if len(fields) >= 7 && fields[1] == "folder" && fields[2] == "0" {
420 e := &Entry{
421 Type: EntryTypeFolder,
422 Name: strings.Join(fields[6:], " "),
423 }
424 if err := e.setTime(fields[3:6]); err != nil {
425 return nil, err
426 }
427
428 return e, nil
429 }
430
431 if len(fields) < 8 {
432 return nil, errUnsupportedListLine
433 }
434
435 if fields[1] == "0" {
436 e := &Entry{
437 Type: EntryTypeFile,
438 Name: strings.Join(fields[7:], " "),
439 }
440
441 if err := e.setSize(fields[2]); err != nil {
442 return nil, err
443 }
444 if err := e.setTime(fields[4:7]); err != nil {
445 return nil, err
446 }
447
448 return e, nil
449 }
450
451 if len(fields) < 9 {
452 return nil, errUnsupportedListLine
453 }
454
455 e := &Entry{}
456 switch fields[0][0] {
457 case '-':
458 e.Type = EntryTypeFile
459 if err := e.setSize(fields[4]); err != nil {
460 return nil, err
461 }
462 case 'd':
463 e.Type = EntryTypeFolder
464 case 'l':
465 e.Type = EntryTypeLink
466 default:
467 return nil, errors.New("Unknown entry type")
468 }
469
470 if err := e.setTime(fields[5:8]); err != nil {
471 return nil, err
472 }
473
474 e.Name = fields[8]
475
476 return e, nil
477 }
478
479 var dirTimeFormats = []string{
480 "01-02-06 03:04PM",
481 "2006-01-02 15:04",
482 }
483
484 // parseDirListLine parses a directory line in a format based on the output of
485 // the MS-DOS DIR command.
486 func parseDirListLine(line string) (*Entry, error) {
487 e := &Entry{}
488 var err error
489
490 // Try various time formats that DIR might use, and stop when one works.
491 for _, format := range dirTimeFormats {
492 if len(line) > len(format) {
493 e.Time, err = time.Parse(format, line[:len(format)])
494 if err == nil {
495 line = line[len(format):]
496 break
497 }
498 }
499 }
500 if err != nil {
501 // None of the time formats worked.
502 return nil, errUnsupportedListLine
503 }
504
505 line = strings.TrimLeft(line, " ")
506 if strings.HasPrefix(line, "<DIR>") {
507 e.Type = EntryTypeFolder
508 line = strings.TrimPrefix(line, "<DIR>")
509 } else {
510 space := strings.Index(line, " ")
511 if space == -1 {
512 return nil, errUnsupportedListLine
513 }
514 e.Size, err = strconv.ParseUint(line[:space], 10, 64)
515 if err != nil {
516 return nil, errUnsupportedListLine
517 }
518 e.Type = EntryTypeFile
519 line = line[space:]
520 }
521
522 e.Name = strings.TrimLeft(line, " ")
523 return e, nil
524 }
525
526 var listLineParsers = []func(line string) (*Entry, error){
527 parseRFC3659ListLine,
528 parseLsListLine,
529 parseDirListLine,
530 }
531
532 // parseListLine parses the various non-standard format returned by the LIST
533 // FTP command.
534 func parseListLine(line string) (*Entry, error) {
535 for _, f := range listLineParsers {
536 e, err := f(line)
537 if err == errUnsupportedListLine {
538 // Try another format.
539 continue
540 }
541 return e, err
542 }
543 return nil, errUnsupportedListLine
544 }
545
546 func (e *Entry) setSize(str string) (err error) {
547 e.Size, err = strconv.ParseUint(str, 0, 64)
548 return
549 }
550
551 func (e *Entry) setTime(fields []string) (err error) {
552 var timeStr string
553 if strings.Contains(fields[2], ":") { // this year
554 thisYear, _, _ := time.Now().Date()
555 timeStr = fields[1] + " " + fields[0] + " " + strconv.Itoa(thisYear)[2:4] + " " + fields[2] + " GMT"
556 } else { // not this year
557 if len(fields[2]) != 4 {
558 return errors.New("Invalid year format in time string")
559 }
560 timeStr = fields[1] + " " + fields[0] + " " + fields[2][2:4] + " 00:00 GMT"
561 }
562 e.Time, err = time.Parse("_2 Jan 06 15:04 MST", timeStr)
563 return
564 }
565
566 func (c *ServerConn) LastModificationDate(path string) (t time.Time, err error) {
567 if _, mdtmSupported := c.features["MDTM"]; !mdtmSupported {
568 return t, errors.New("MDTM is not supported on this server")
569 }
570
571 _, msg, err := c.cmd(StatusFile, "MDTM %s", path)
572 if err != nil {
573 return
574 }
575
576 // Line formats:
577 // 213 20150413095032
578 // 213 20150413095032.999
579 if len(msg) < 14 {
580 return t, errors.New("Command unsupported on this server")
581 }
582
583 gmtLoc, _ := time.LoadLocation("GMT")
584 t, err = time.ParseInLocation("20060102150405.999", msg, gmtLoc)
585 return
586 }
587
588 // NameList issues an NLST FTP command.
589 func (c *ServerConn) NameList(path string) (entries []string, err error) {
590 conn, err := c.cmdDataConnFrom(0, "NLST %s", path)
591 if err != nil {
592 return
593 }
594
595 r := &response{conn, c}
596 defer r.Close()
597
598 scanner := bufio.NewScanner(r)
599 for scanner.Scan() {
600 entries = append(entries, scanner.Text())
601 }
602 if err = scanner.Err(); err != nil {
603 return entries, err
604 }
605 return
606 }
607
608 // List issues a LIST FTP command.
609 func (c *ServerConn) List(path string) (entries []*Entry, err error) {
610 var conn net.Conn
611
612 commands := []string{"MLSD", "LIST -a", "LIST"}
613 if !c.listall {
614 commands = append(commands[:1], commands[2:]...)
615 }
616 if _, mlstSupported := c.features["MLST"]; !mlstSupported {
617 commands = commands[1:]
618 }
619
620 for _, cmd := range commands {
621 conn, err = c.cmdDataConnFrom(0, "%s %s", cmd, path)
622 if err == nil {
623 break
624 }
625 if cmd == "LIST -a" {
626 // "LIST -a" is not supported
627 // Fall back to LIST
628 c.listall = false
629 }
630 }
631
632 if err != nil {
633 return
634 }
635
636 r := &response{conn, c}
637 defer r.Close()
638
639 scanner := bufio.NewScanner(r)
640 for scanner.Scan() {
641 line := scanner.Text()
642 entry, err := parseListLine(line)
643 if err == nil && entry != nil {
644 entries = append(entries, entry)
645 }
646 }
647 if err := scanner.Err(); err != nil {
648 return nil, err
649 }
650 return
651 }
652
653 // ChangeDir issues a CWD FTP command, which changes the current directory to
654 // the specified path.
655 func (c *ServerConn) ChangeDir(path string) error {
656 _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
657 return err
658 }
659
660 // ChangeDirToParent issues a CDUP FTP command, which changes the current
661 // directory to the parent directory. This is similar to a call to ChangeDir
662 // with a path set to "..".
663 func (c *ServerConn) ChangeDirToParent() error {
664 _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
665 return err
666 }
667
668 // CurrentDir issues a PWD FTP command, which Returns the path of the current
669 // directory.
670 func (c *ServerConn) CurrentDir() (string, error) {
671 _, msg, err := c.cmd(StatusPathCreated, "PWD")
672 if err != nil {
673 return "", err
674 }
675
676 start := strings.Index(msg, "\"")
677 end := strings.LastIndex(msg, "\"")
678
679 if start == -1 || end == -1 {
680 return "", errors.New("Unsuported PWD response format")
681 }
682
683 return msg[start+1 : end], nil
684 }
685
686 // Retr issues a RETR FTP command to fetch the specified file from the remote
687 // FTP server.
688 //
689 // The returned ReadCloser must be closed to cleanup the FTP data connection.
690 func (c *ServerConn) Retr(path string) (io.ReadCloser, error) {
691 return c.RetrFrom(path, 0)
692 }
693
694 // RetrFrom issues a RETR FTP command to fetch the specified file from the remote
695 // FTP server, the server will not send the offset first bytes of the file.
696 //
697 // The returned ReadCloser must be closed to cleanup the FTP data connection.
698 func (c *ServerConn) RetrFrom(path string, offset uint64) (io.ReadCloser, error) {
699 conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
700 if err != nil {
701 return nil, err
702 }
703
704 return &response{conn, c}, nil
705 }
706
707 // Stor issues a STOR FTP command to store a file to the remote FTP server.
708 // Stor creates the specified file with the content of the io.Reader.
709 //
710 // Hint: io.Pipe() can be used if an io.Writer is required.
711 func (c *ServerConn) Stor(path string, r io.Reader) error {
712 return c.StorFrom(path, r, 0)
713 }
714
715 // StorFrom issues a STOR FTP command to store a file to the remote FTP server.
716 // Stor creates the specified file with the content of the io.Reader, writing
717 // on the server will start at the given file offset.
718 //
719 // Hint: io.Pipe() can be used if an io.Writer is required.
720 func (c *ServerConn) StorFrom(path string, r io.Reader, offset uint64) error {
721 conn, err := c.cmdDataConnFrom(offset, "STOR %s", path)
722 if err != nil {
723 return err
724 }
725
726 _, err = io.Copy(conn, r)
727 conn.Close()
728 if err != nil {
729 return err
730 }
731
732 _, _, err = c.conn.ReadResponse(StatusClosingDataConnection)
733 return err
734 }
735
736 // Rename renames a file on the remote FTP server.
737 func (c *ServerConn) Rename(from, to string) error {
738 _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
739 if err != nil {
740 return err
741 }
742
743 _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
744 return err
745 }
746
747 // Delete issues a DELE FTP command to delete the specified file from the
748 // remote FTP server.
749 func (c *ServerConn) Delete(path string) error {
750 _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
751 return err
752 }
753
754 // MakeDir issues a MKD FTP command to create the specified directory on the
755 // remote FTP server.
756 func (c *ServerConn) MakeDir(path string) error {
757 _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
758 return err
759 }
760
761 // RemoveDir issues a RMD FTP command to remove the specified directory from
762 // the remote FTP server.
763 func (c *ServerConn) RemoveDir(path string) error {
764 _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
765 return err
766 }
767
768 // NoOp issues a NOOP FTP command.
769 // NOOP has no effects and is usually used to prevent the remote FTP server to
770 // close the otherwise idle connection.
771 func (c *ServerConn) NoOp() error {
772 _, _, err := c.cmd(StatusCommandOK, "NOOP")
773 return err
774 }
775
776 // Logout issues a REIN FTP command to logout the current user.
777 func (c *ServerConn) Logout() error {
778 _, _, err := c.cmd(StatusReady, "REIN")
779 return err
780 }
781
782 // Quit issues a QUIT FTP command to properly close the connection from the
783 // remote FTP server.
784 func (c *ServerConn) Quit() error {
785 c.conn.Cmd("QUIT")
786 return c.conn.Close()
787 }
788
789 // Read implements the io.Reader interface on a FTP data connection.
790 func (r *response) Read(buf []byte) (int, error) {
791 return r.conn.Read(buf)
792 }
793
794 // Close implements the io.Closer interface on a FTP data connection.
795 func (r *response) Close() error {
796 err := r.conn.Close()
797 _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
798 if err2 != nil {
799 err = err2
800 }
801 return err
802 }