ftp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. conn *textproto.Conn
  24. host string
  25. timeout time.Duration
  26. features map[string]string
  27. }
  28. // Entry describes a file and is returned by List().
  29. type Entry struct {
  30. Name string
  31. Type EntryType
  32. Size uint64
  33. Time time.Time
  34. }
  35. // response represent a data-connection
  36. type response struct {
  37. conn net.Conn
  38. c *ServerConn
  39. }
  40. // Connect is an alias to Dial, for backward compatibility
  41. func Connect(addr string) (*ServerConn, error) {
  42. return Dial(addr)
  43. }
  44. // Dial is like DialTimeout with no timeout
  45. func Dial(addr string) (*ServerConn, error) {
  46. return DialTimeout(addr, 0)
  47. }
  48. // DialTimeout initializes the connection to the specified ftp server address.
  49. //
  50. // It is generally followed by a call to Login() as most FTP commands require
  51. // an authenticated user.
  52. func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error) {
  53. tconn, err := net.DialTimeout("tcp", addr, timeout)
  54. if err != nil {
  55. return nil, err
  56. }
  57. conn := textproto.NewConn(tconn)
  58. host, _, err := net.SplitHostPort(addr)
  59. if err != nil {
  60. conn.Close()
  61. return nil, err
  62. }
  63. c := &ServerConn{
  64. conn: conn,
  65. host: host,
  66. timeout: timeout,
  67. features: make(map[string]string),
  68. }
  69. _, _, err = c.conn.ReadResponse(StatusReady)
  70. if err != nil {
  71. c.Quit()
  72. return nil, err
  73. }
  74. err = c.feat()
  75. if err != nil {
  76. c.Quit()
  77. return nil, err
  78. }
  79. return c, nil
  80. }
  81. // Login authenticates the client with specified user and password.
  82. //
  83. // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
  84. // that allows anonymous read-only accounts.
  85. func (c *ServerConn) Login(user, password string) error {
  86. code, message, err := c.cmd(-1, "USER %s", user)
  87. if err != nil {
  88. return err
  89. }
  90. switch code {
  91. case StatusLoggedIn:
  92. case StatusUserOK:
  93. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  94. if err != nil {
  95. return err
  96. }
  97. default:
  98. return errors.New(message)
  99. }
  100. // Switch to binary mode
  101. _, _, err = c.cmd(StatusCommandOK, "TYPE I")
  102. if err != nil {
  103. return err
  104. }
  105. return nil
  106. }
  107. // feat issues a FEAT FTP command to list the additional commands supported by
  108. // the remote FTP server.
  109. // FEAT is described in RFC 2389
  110. func (c *ServerConn) feat() error {
  111. code, message, err := c.cmd(-1, "FEAT")
  112. if err != nil {
  113. return err
  114. }
  115. if code != StatusSystem {
  116. // The server does not support the FEAT command. This is not an
  117. // error: we consider that there is no additional feature.
  118. return nil
  119. }
  120. lines := strings.Split(message, "\n")
  121. for _, line := range lines {
  122. if !strings.HasPrefix(line, " ") {
  123. continue
  124. }
  125. line = strings.TrimSpace(line)
  126. featureElements := strings.SplitN(line, " ", 2)
  127. command := featureElements[0]
  128. var commandDesc string
  129. if len(featureElements) == 2 {
  130. commandDesc = featureElements[1]
  131. }
  132. c.features[command] = commandDesc
  133. }
  134. return nil
  135. }
  136. // epsv issues an "EPSV" command to get a port number for a data connection.
  137. func (c *ServerConn) epsv() (port int, err error) {
  138. _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
  139. if err != nil {
  140. return
  141. }
  142. start := strings.Index(line, "|||")
  143. end := strings.LastIndex(line, "|")
  144. if start == -1 || end == -1 {
  145. err = errors.New("Invalid EPSV response format")
  146. return
  147. }
  148. port, err = strconv.Atoi(line[start+3 : end])
  149. return
  150. }
  151. // pasv issues a "PASV" command to get a port number for a data connection.
  152. func (c *ServerConn) pasv() (port int, err error) {
  153. _, line, err := c.cmd(StatusPassiveMode, "PASV")
  154. if err != nil {
  155. return
  156. }
  157. // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
  158. start := strings.Index(line, "(")
  159. end := strings.LastIndex(line, ")")
  160. if start == -1 || end == -1 {
  161. err = errors.New("Invalid PASV response format")
  162. return
  163. }
  164. // We have to split the response string
  165. pasvData := strings.Split(line[start+1:end], ",")
  166. // Let's compute the port number
  167. portPart1, err1 := strconv.Atoi(pasvData[4])
  168. if err1 != nil {
  169. err = err1
  170. return
  171. }
  172. portPart2, err2 := strconv.Atoi(pasvData[5])
  173. if err2 != nil {
  174. err = err2
  175. return
  176. }
  177. // Recompose port
  178. port = portPart1*256 + portPart2
  179. return
  180. }
  181. // openDataConn creates a new FTP data connection.
  182. func (c *ServerConn) openDataConn() (net.Conn, error) {
  183. var port int
  184. var err error
  185. // If features contains nat6 or EPSV => EPSV
  186. // else -> PASV
  187. _, nat6Supported := c.features["nat6"]
  188. _, epsvSupported := c.features["EPSV"]
  189. if !nat6Supported && !epsvSupported {
  190. port, _ = c.pasv()
  191. }
  192. if port == 0 {
  193. port, err = c.epsv()
  194. if err != nil {
  195. return nil, err
  196. }
  197. }
  198. // Build the new net address string
  199. addr := net.JoinHostPort(c.host, strconv.Itoa(port))
  200. conn, err := net.DialTimeout("tcp", addr, c.timeout)
  201. if err != nil {
  202. return nil, err
  203. }
  204. return conn, nil
  205. }
  206. // cmd is a helper function to execute a command and check for the expected FTP
  207. // return code
  208. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  209. _, err := c.conn.Cmd(format, args...)
  210. if err != nil {
  211. return 0, "", err
  212. }
  213. code, line, err := c.conn.ReadResponse(expected)
  214. return code, line, err
  215. }
  216. // cmdDataConnFrom executes a command which require a FTP data connection.
  217. // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
  218. func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
  219. conn, err := c.openDataConn()
  220. if err != nil {
  221. return nil, err
  222. }
  223. if offset != 0 {
  224. _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
  225. if err != nil {
  226. return nil, err
  227. }
  228. }
  229. _, err = c.conn.Cmd(format, args...)
  230. if err != nil {
  231. conn.Close()
  232. return nil, err
  233. }
  234. code, msg, err := c.conn.ReadResponse(-1)
  235. if err != nil {
  236. conn.Close()
  237. return nil, err
  238. }
  239. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  240. conn.Close()
  241. return nil, &textproto.Error{Code: code, Msg: msg}
  242. }
  243. return conn, nil
  244. }
  245. // parseListLine parses the various non-standard format returned by the LIST
  246. // FTP command.
  247. func parseListLine(line string) (*Entry, error) {
  248. fields := strings.Fields(line)
  249. if len(fields) < 9 {
  250. return nil, errors.New("Unsupported LIST line")
  251. }
  252. e := &Entry{}
  253. switch fields[0][0] {
  254. case '-':
  255. e.Type = EntryTypeFile
  256. case 'd':
  257. e.Type = EntryTypeFolder
  258. case 'l':
  259. e.Type = EntryTypeLink
  260. default:
  261. return nil, errors.New("Unknown entry type")
  262. }
  263. if e.Type == EntryTypeFile {
  264. size, err := strconv.ParseUint(fields[4], 10, 0)
  265. if err != nil {
  266. return nil, err
  267. }
  268. e.Size = size
  269. }
  270. var timeStr string
  271. if strings.Contains(fields[7], ":") { // this year
  272. thisYear, _, _ := time.Now().Date()
  273. timeStr = fields[6] + " " + fields[5] + " " + strconv.Itoa(thisYear)[2:4] + " " + fields[7] + " GMT"
  274. } else { // not this year
  275. timeStr = fields[6] + " " + fields[5] + " " + fields[7][2:4] + " " + "00:00" + " GMT"
  276. }
  277. t, err := time.Parse("_2 Jan 06 15:04 MST", timeStr)
  278. if err != nil {
  279. return nil, err
  280. }
  281. e.Time = t
  282. e.Name = strings.Join(fields[8:], " ")
  283. return e, nil
  284. }
  285. // NameList issues an NLST FTP command.
  286. func (c *ServerConn) NameList(path string) (entries []string, err error) {
  287. conn, err := c.cmdDataConnFrom(0, "NLST %s", path)
  288. if err != nil {
  289. return
  290. }
  291. r := &response{conn, c}
  292. defer r.Close()
  293. scanner := bufio.NewScanner(r)
  294. for scanner.Scan() {
  295. entries = append(entries, scanner.Text())
  296. }
  297. if err = scanner.Err(); err != nil {
  298. return entries, err
  299. }
  300. return
  301. }
  302. // List issues a LIST FTP command.
  303. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  304. conn, err := c.cmdDataConnFrom(0, "LIST %s", path)
  305. if err != nil {
  306. return
  307. }
  308. r := &response{conn, c}
  309. defer r.Close()
  310. bio := bufio.NewReader(r)
  311. for {
  312. line, e := bio.ReadString('\n')
  313. if e == io.EOF {
  314. break
  315. } else if e != nil {
  316. return nil, e
  317. }
  318. entry, err := parseListLine(line)
  319. if err == nil {
  320. entries = append(entries, entry)
  321. }
  322. }
  323. return
  324. }
  325. // ChangeDir issues a CWD FTP command, which changes the current directory to
  326. // the specified path.
  327. func (c *ServerConn) ChangeDir(path string) error {
  328. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  329. return err
  330. }
  331. // ChangeDirToParent issues a CDUP FTP command, which changes the current
  332. // directory to the parent directory. This is similar to a call to ChangeDir
  333. // with a path set to "..".
  334. func (c *ServerConn) ChangeDirToParent() error {
  335. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  336. return err
  337. }
  338. // CurrentDir issues a PWD FTP command, which Returns the path of the current
  339. // directory.
  340. func (c *ServerConn) CurrentDir() (string, error) {
  341. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  342. if err != nil {
  343. return "", err
  344. }
  345. start := strings.Index(msg, "\"")
  346. end := strings.LastIndex(msg, "\"")
  347. if start == -1 || end == -1 {
  348. return "", errors.New("Unsuported PWD response format")
  349. }
  350. return msg[start+1 : end], 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. // Retr 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. r := &response{conn, c}
  369. return r, nil
  370. }
  371. // Stor issues a STOR FTP command to store a file to the remote FTP server.
  372. // Stor creates the specified file with the content of the io.Reader.
  373. //
  374. // Hint: io.Pipe() can be used if an io.Writer is required.
  375. func (c *ServerConn) Stor(path string, r io.Reader) error {
  376. return c.StorFrom(path, r, 0)
  377. }
  378. // Stor issues a STOR FTP command to store a file to the remote FTP server.
  379. // Stor creates the specified file with the content of the io.Reader, writing
  380. // on the server will start at the given file offset.
  381. //
  382. // Hint: io.Pipe() can be used if an io.Writer is required.
  383. func (c *ServerConn) StorFrom(path string, r io.Reader, offset uint64) error {
  384. conn, err := c.cmdDataConnFrom(offset, "STOR %s", path)
  385. if err != nil {
  386. return err
  387. }
  388. _, err = io.Copy(conn, r)
  389. conn.Close()
  390. if err != nil {
  391. return err
  392. }
  393. _, _, err = c.conn.ReadResponse(StatusClosingDataConnection)
  394. return err
  395. }
  396. // Rename renames a file on the remote FTP server.
  397. func (c *ServerConn) Rename(from, to string) error {
  398. _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
  399. if err != nil {
  400. return err
  401. }
  402. _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
  403. return err
  404. }
  405. // Delete issues a DELE FTP command to delete the specified file from the
  406. // remote FTP server.
  407. func (c *ServerConn) Delete(path string) error {
  408. _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
  409. return err
  410. }
  411. // MakeDir issues a MKD FTP command to create the specified directory on the
  412. // remote FTP server.
  413. func (c *ServerConn) MakeDir(path string) error {
  414. _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
  415. return err
  416. }
  417. // RemoveDir issues a RMD FTP command to remove the specified directory from
  418. // the remote FTP server.
  419. func (c *ServerConn) RemoveDir(path string) error {
  420. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
  421. return err
  422. }
  423. // NoOp issues a NOOP FTP command.
  424. // NOOP has no effects and is usually used to prevent the remote FTP server to
  425. // close the otherwise idle connection.
  426. func (c *ServerConn) NoOp() error {
  427. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  428. return err
  429. }
  430. // Logout issues a REIN FTP command to logout the current user.
  431. func (c *ServerConn) Logout() error {
  432. _, _, err := c.cmd(StatusReady, "REIN")
  433. return err
  434. }
  435. // Quit issues a QUIT FTP command to properly close the connection from the
  436. // remote FTP server.
  437. func (c *ServerConn) Quit() error {
  438. c.conn.Cmd("QUIT")
  439. return c.conn.Close()
  440. }
  441. // Read implements the io.Reader interface on a FTP data connection.
  442. func (r *response) Read(buf []byte) (int, error) {
  443. n, err := r.conn.Read(buf)
  444. return n, err
  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. }