ftp.go 16 KB

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