ftp.go 16 KB

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