ftp.go 17 KB

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