ftp.go 13 KB

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