ftp.go 17 KB

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