ftp.go 14 KB

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