ftp.go 14 KB

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