ftp.go 14 KB

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