ftp.go 14 KB

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