ftp.go 16 KB

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