ftp.go 17 KB

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