ftp.go 17 KB

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