ftp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. if code != StatusCommandOK {
  157. return errors.New(message)
  158. }
  159. return nil
  160. }
  161. // epsv issues an "EPSV" command to get a port number for a data connection.
  162. func (c *ServerConn) epsv() (port int, err error) {
  163. _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
  164. if err != nil {
  165. return
  166. }
  167. start := strings.Index(line, "|||")
  168. end := strings.LastIndex(line, "|")
  169. if start == -1 || end == -1 {
  170. err = errors.New("Invalid EPSV response format")
  171. return
  172. }
  173. port, err = strconv.Atoi(line[start+3 : end])
  174. return
  175. }
  176. // pasv issues a "PASV" command to get a port number for a data connection.
  177. func (c *ServerConn) pasv() (port int, err error) {
  178. _, line, err := c.cmd(StatusPassiveMode, "PASV")
  179. if err != nil {
  180. return
  181. }
  182. // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
  183. start := strings.Index(line, "(")
  184. end := strings.LastIndex(line, ")")
  185. if start == -1 || end == -1 {
  186. return 0, errors.New("Invalid PASV response format")
  187. }
  188. // We have to split the response string
  189. pasvData := strings.Split(line[start+1:end], ",")
  190. if len(pasvData) < 6 {
  191. return 0, errors.New("Invalid PASV response format")
  192. }
  193. // Let's compute the port number
  194. portPart1, err1 := strconv.Atoi(pasvData[4])
  195. if err1 != nil {
  196. err = err1
  197. return
  198. }
  199. portPart2, err2 := strconv.Atoi(pasvData[5])
  200. if err2 != nil {
  201. err = err2
  202. return
  203. }
  204. // Recompose port
  205. port = portPart1*256 + portPart2
  206. return
  207. }
  208. // getDataConnPort returns a port for a new data connection
  209. // it uses the best available method to do so
  210. func (c *ServerConn) getDataConnPort() (int, error) {
  211. if !c.DisableEPSV {
  212. if port, err := c.epsv(); err == nil {
  213. return port, nil
  214. }
  215. // if there is an error, disable EPSV for the next attempts
  216. c.DisableEPSV = true
  217. }
  218. return c.pasv()
  219. }
  220. // openDataConn creates a new FTP data connection.
  221. func (c *ServerConn) openDataConn() (net.Conn, error) {
  222. port, err := c.getDataConnPort()
  223. if err != nil {
  224. return nil, err
  225. }
  226. return net.DialTimeout("tcp", net.JoinHostPort(c.host, strconv.Itoa(port)), c.timeout)
  227. }
  228. // cmd is a helper function to execute a command and check for the expected FTP
  229. // return code
  230. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  231. _, err := c.conn.Cmd(format, args...)
  232. if err != nil {
  233. return 0, "", err
  234. }
  235. return c.conn.ReadResponse(expected)
  236. }
  237. // cmdDataConnFrom executes a command which require a FTP data connection.
  238. // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
  239. func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
  240. conn, err := c.openDataConn()
  241. if err != nil {
  242. return nil, err
  243. }
  244. if offset != 0 {
  245. _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
  246. if err != nil {
  247. conn.Close()
  248. return nil, err
  249. }
  250. }
  251. _, err = c.conn.Cmd(format, args...)
  252. if err != nil {
  253. conn.Close()
  254. return nil, err
  255. }
  256. code, msg, err := c.conn.ReadResponse(-1)
  257. if err != nil {
  258. conn.Close()
  259. return nil, err
  260. }
  261. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  262. conn.Close()
  263. return nil, &textproto.Error{Code: code, Msg: msg}
  264. }
  265. return conn, nil
  266. }
  267. // NameList issues an NLST FTP command.
  268. func (c *ServerConn) NameList(path string) (entries []string, err error) {
  269. conn, err := c.cmdDataConnFrom(0, "NLST %s", path)
  270. if err != nil {
  271. return
  272. }
  273. r := &response{conn, c}
  274. defer r.Close()
  275. scanner := bufio.NewScanner(r)
  276. for scanner.Scan() {
  277. entries = append(entries, scanner.Text())
  278. }
  279. if err = scanner.Err(); err != nil {
  280. return entries, err
  281. }
  282. return
  283. }
  284. // List issues a LIST FTP command.
  285. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  286. var cmd string
  287. var parseFunc func(string) (*Entry, error)
  288. if c.mlstSupported {
  289. cmd = "MLSD"
  290. parseFunc = parseRFC3659ListLine
  291. } else {
  292. cmd = "LIST"
  293. parseFunc = parseListLine
  294. }
  295. conn, err := c.cmdDataConnFrom(0, "%s %s", cmd, path)
  296. if err != nil {
  297. return
  298. }
  299. r := &response{conn, c}
  300. defer r.Close()
  301. scanner := bufio.NewScanner(r)
  302. for scanner.Scan() {
  303. entry, err := parseFunc(scanner.Text())
  304. if err == nil {
  305. entries = append(entries, entry)
  306. }
  307. }
  308. if err := scanner.Err(); err != nil {
  309. return nil, err
  310. }
  311. return
  312. }
  313. // ChangeDir issues a CWD FTP command, which changes the current directory to
  314. // the specified path.
  315. func (c *ServerConn) ChangeDir(path string) error {
  316. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  317. return err
  318. }
  319. // ChangeDirToParent issues a CDUP FTP command, which changes the current
  320. // directory to the parent directory. This is similar to a call to ChangeDir
  321. // with a path set to "..".
  322. func (c *ServerConn) ChangeDirToParent() error {
  323. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  324. return err
  325. }
  326. // CurrentDir issues a PWD FTP command, which Returns the path of the current
  327. // directory.
  328. func (c *ServerConn) CurrentDir() (string, error) {
  329. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  330. if err != nil {
  331. return "", err
  332. }
  333. start := strings.Index(msg, "\"")
  334. end := strings.LastIndex(msg, "\"")
  335. if start == -1 || end == -1 {
  336. return "", errors.New("Unsuported PWD response format")
  337. }
  338. return msg[start+1 : end], nil
  339. }
  340. // FileSize issues a SIZE FTP command, which Returns the size of the file
  341. func (c *ServerConn) FileSize(path string) (int, error) {
  342. _, msg, err := c.cmd(StatusFile, "SIZE %s", path)
  343. if err != nil {
  344. return 0, err
  345. }
  346. size, err := strconv.Atoi(msg)
  347. if err != nil {
  348. return 0, err
  349. }
  350. return size, nil
  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) (io.ReadCloser, 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) (io.ReadCloser, error) {
  364. conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
  365. if err != nil {
  366. return nil, err
  367. }
  368. return &response{conn, 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. // MakeDir issues a MKD FTP command to create the specified directory on the
  411. // remote FTP server.
  412. func (c *ServerConn) MakeDir(path string) error {
  413. _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
  414. return err
  415. }
  416. // RemoveDir issues a RMD FTP command to remove the specified directory from
  417. // the remote FTP server.
  418. func (c *ServerConn) RemoveDir(path string) error {
  419. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
  420. return err
  421. }
  422. // NoOp issues a NOOP FTP command.
  423. // NOOP has no effects and is usually used to prevent the remote FTP server to
  424. // close the otherwise idle connection.
  425. func (c *ServerConn) NoOp() error {
  426. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  427. return err
  428. }
  429. // Logout issues a REIN FTP command to logout the current user.
  430. func (c *ServerConn) Logout() error {
  431. _, _, err := c.cmd(StatusReady, "REIN")
  432. return err
  433. }
  434. // Quit issues a QUIT FTP command to properly close the connection from the
  435. // remote FTP server.
  436. func (c *ServerConn) Quit() error {
  437. c.conn.Cmd("QUIT")
  438. return c.conn.Close()
  439. }
  440. // Read implements the io.Reader interface on a FTP data connection.
  441. func (r *response) Read(buf []byte) (int, error) {
  442. return r.conn.Read(buf)
  443. }
  444. // Close implements the io.Closer interface on a FTP data connection.
  445. func (r *response) Close() error {
  446. err := r.conn.Close()
  447. _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
  448. if err2 != nil {
  449. err = err2
  450. }
  451. return err
  452. }