ftp.go 18 KB

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