ftp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // Package ftp implements a FTP client as described in RFC 959.
  2. package ftp
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/textproto"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // EntryType describes the different types of an Entry.
  15. type EntryType int
  16. // The differents types of an Entry
  17. const (
  18. EntryTypeFile EntryType = iota
  19. EntryTypeFolder
  20. EntryTypeLink
  21. )
  22. // ServerConn represents the connection to a remote FTP server.
  23. type ServerConn struct {
  24. conn *textproto.Conn
  25. host string
  26. timeout time.Duration
  27. features map[string]string
  28. }
  29. // Entry describes a file and is returned by List().
  30. type Entry struct {
  31. Name string
  32. Type EntryType
  33. Size uint64
  34. Time time.Time
  35. }
  36. // response represent a data-connection
  37. type response struct {
  38. conn net.Conn
  39. c *ServerConn
  40. }
  41. // Connect is an alias to Dial, for backward compatibility
  42. func Connect(addr string) (*ServerConn, error) {
  43. return Dial(addr)
  44. }
  45. // Dial is like DialTimeout with no timeout
  46. func Dial(addr string) (*ServerConn, error) {
  47. return DialTimeout(addr, 0)
  48. }
  49. // DialTimeout initializes the connection to the specified ftp server address.
  50. //
  51. // It is generally followed by a call to Login() as most FTP commands require
  52. // an authenticated user.
  53. func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error) {
  54. tconn, err := net.DialTimeout("tcp", addr, timeout)
  55. if err != nil {
  56. return nil, err
  57. }
  58. conn := textproto.NewConn(tconn)
  59. a := strings.SplitN(addr, ":", 2)
  60. c := &ServerConn{
  61. conn: conn,
  62. host: a[0],
  63. timeout: timeout,
  64. features: make(map[string]string),
  65. }
  66. _, _, err = c.conn.ReadResponse(StatusReady)
  67. if err != nil {
  68. c.Quit()
  69. return nil, err
  70. }
  71. err = c.feat()
  72. if err != nil {
  73. c.Quit()
  74. return nil, err
  75. }
  76. return c, nil
  77. }
  78. // Login authenticates the client with specified user and password.
  79. //
  80. // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
  81. // that allows anonymous read-only accounts.
  82. func (c *ServerConn) Login(user, password string) error {
  83. code, message, err := c.cmd(-1, "USER %s", user)
  84. if err != nil {
  85. return err
  86. }
  87. switch code {
  88. case StatusLoggedIn:
  89. case StatusUserOK:
  90. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  91. if err != nil {
  92. return err
  93. }
  94. default:
  95. return errors.New(message)
  96. }
  97. // Switch to binary mode
  98. _, _, err = c.cmd(StatusCommandOK, "TYPE I")
  99. if err != nil {
  100. return err
  101. }
  102. return nil
  103. }
  104. // feat issues a FEAT FTP command to list the additional commands supported by
  105. // the remote FTP server.
  106. // FEAT is described in RFC 2389
  107. func (c *ServerConn) feat() error {
  108. code, message, err := c.cmd(-1, "FEAT")
  109. if err != nil {
  110. return err
  111. }
  112. if code != StatusSystem {
  113. // The server does not support the FEAT command. This is not an
  114. // error: we consider that there is no additional feature.
  115. return nil
  116. }
  117. lines := strings.Split(message, "\n")
  118. for _, line := range lines {
  119. if !strings.HasPrefix(line, " ") {
  120. continue
  121. }
  122. line = strings.TrimSpace(line)
  123. featureElements := strings.SplitN(line, " ", 2)
  124. command := featureElements[0]
  125. var commandDesc string
  126. if len(featureElements) == 2 {
  127. commandDesc = featureElements[1]
  128. }
  129. c.features[command] = commandDesc
  130. }
  131. return nil
  132. }
  133. // epsv issues an "EPSV" command to get a port number for a data connection.
  134. func (c *ServerConn) epsv() (port int, err error) {
  135. _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
  136. if err != nil {
  137. return
  138. }
  139. start := strings.Index(line, "|||")
  140. end := strings.LastIndex(line, "|")
  141. if start == -1 || end == -1 {
  142. err = errors.New("Invalid EPSV response format")
  143. return
  144. }
  145. port, err = strconv.Atoi(line[start+3 : end])
  146. return
  147. }
  148. // pasv issues a "PASV" command to get a port number for a data connection.
  149. func (c *ServerConn) pasv() (port int, err error) {
  150. _, line, err := c.cmd(StatusPassiveMode, "PASV")
  151. if err != nil {
  152. return
  153. }
  154. // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
  155. start := strings.Index(line, "(")
  156. end := strings.LastIndex(line, ")")
  157. if start == -1 || end == -1 {
  158. err = errors.New("Invalid PASV response format")
  159. return
  160. }
  161. // We have to split the response string
  162. pasvData := strings.Split(line[start+1:end], ",")
  163. // Let's compute the port number
  164. portPart1, err1 := strconv.Atoi(pasvData[4])
  165. if err1 != nil {
  166. err = err1
  167. return
  168. }
  169. portPart2, err2 := strconv.Atoi(pasvData[5])
  170. if err2 != nil {
  171. err = err2
  172. return
  173. }
  174. // Recompose port
  175. port = portPart1*256 + portPart2
  176. return
  177. }
  178. // openDataConn creates a new FTP data connection.
  179. func (c *ServerConn) openDataConn() (net.Conn, error) {
  180. var port int
  181. var err error
  182. // If features contains nat6 or EPSV => EPSV
  183. // else -> PASV
  184. _, nat6Supported := c.features["nat6"]
  185. _, epsvSupported := c.features["EPSV"]
  186. if nat6Supported || epsvSupported {
  187. port, err = c.epsv()
  188. if err != nil {
  189. return nil, err
  190. }
  191. } else {
  192. port, err = c.pasv()
  193. if err != nil {
  194. return nil, err
  195. }
  196. }
  197. // Build the new net address string
  198. addr := fmt.Sprintf("%s:%d", c.host, port)
  199. conn, err := net.DialTimeout("tcp", addr, c.timeout)
  200. if err != nil {
  201. return nil, err
  202. }
  203. return conn, nil
  204. }
  205. // cmd is a helper function to execute a command and check for the expected FTP
  206. // return code
  207. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  208. _, err := c.conn.Cmd(format, args...)
  209. if err != nil {
  210. return 0, "", err
  211. }
  212. code, line, err := c.conn.ReadResponse(expected)
  213. return code, line, err
  214. }
  215. // cmdDataConnFrom executes a command which require a FTP data connection.
  216. // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
  217. func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
  218. conn, err := c.openDataConn()
  219. if err != nil {
  220. return nil, err
  221. }
  222. if offset != 0 {
  223. _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
  224. if err != nil {
  225. return nil, err
  226. }
  227. }
  228. _, err = c.conn.Cmd(format, args...)
  229. if err != nil {
  230. conn.Close()
  231. return nil, err
  232. }
  233. code, msg, err := c.conn.ReadResponse(-1)
  234. if err != nil {
  235. conn.Close()
  236. return nil, err
  237. }
  238. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  239. conn.Close()
  240. return nil, &textproto.Error{Code: code, Msg: msg}
  241. }
  242. return conn, nil
  243. }
  244. // parseListLine parses the various non-standard format returned by the LIST
  245. // FTP command.
  246. func parseListLine(line string) (*Entry, error) {
  247. fields := strings.Fields(line)
  248. if len(fields) < 9 {
  249. return nil, errors.New("Unsupported LIST line")
  250. }
  251. e := &Entry{}
  252. switch fields[0][0] {
  253. case '-':
  254. e.Type = EntryTypeFile
  255. case 'd':
  256. e.Type = EntryTypeFolder
  257. case 'l':
  258. e.Type = EntryTypeLink
  259. default:
  260. return nil, errors.New("Unknown entry type")
  261. }
  262. if e.Type == EntryTypeFile {
  263. size, err := strconv.ParseUint(fields[4], 10, 0)
  264. if err != nil {
  265. return nil, err
  266. }
  267. e.Size = size
  268. }
  269. var timeStr string
  270. if strings.Contains(fields[7], ":") { // this year
  271. thisYear, _, _ := time.Now().Date()
  272. timeStr = fields[6] + " " + fields[5] + " " + strconv.Itoa(thisYear)[2:4] + " " + fields[7] + " GMT"
  273. } else { // not this year
  274. timeStr = fields[6] + " " + fields[5] + " " + fields[7][2:4] + " " + "00:00" + " GMT"
  275. }
  276. t, err := time.Parse("_2 Jan 06 15:04 MST", timeStr)
  277. if err != nil {
  278. return nil, err
  279. }
  280. e.Time = t
  281. e.Name = strings.Join(fields[8:], " ")
  282. return e, nil
  283. }
  284. // NameList issues an NLST FTP command.
  285. func (c *ServerConn) NameList(path string) (entries []string, err error) {
  286. conn, err := c.cmdDataConnFrom(0, "NLST %s", path)
  287. if err != nil {
  288. return
  289. }
  290. r := &response{conn, c}
  291. defer r.Close()
  292. scanner := bufio.NewScanner(r)
  293. for scanner.Scan() {
  294. entries = append(entries, scanner.Text())
  295. }
  296. if err = scanner.Err(); err != nil {
  297. return entries, err
  298. }
  299. return
  300. }
  301. // List issues a LIST FTP command.
  302. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  303. conn, err := c.cmdDataConnFrom(0, "LIST %s", path)
  304. if err != nil {
  305. return
  306. }
  307. r := &response{conn, c}
  308. defer r.Close()
  309. bio := bufio.NewReader(r)
  310. for {
  311. line, e := bio.ReadString('\n')
  312. if e == io.EOF {
  313. break
  314. } else if e != nil {
  315. return nil, e
  316. }
  317. entry, err := parseListLine(line)
  318. if err == nil {
  319. entries = append(entries, entry)
  320. }
  321. }
  322. return
  323. }
  324. // ChangeDir issues a CWD FTP command, which changes the current directory to
  325. // the specified path.
  326. func (c *ServerConn) ChangeDir(path string) error {
  327. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  328. return err
  329. }
  330. // ChangeDirToParent issues a CDUP FTP command, which changes the current
  331. // directory to the parent directory. This is similar to a call to ChangeDir
  332. // with a path set to "..".
  333. func (c *ServerConn) ChangeDirToParent() error {
  334. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  335. return err
  336. }
  337. // CurrentDir issues a PWD FTP command, which Returns the path of the current
  338. // directory.
  339. func (c *ServerConn) CurrentDir() (string, error) {
  340. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  341. if err != nil {
  342. return "", err
  343. }
  344. start := strings.Index(msg, "\"")
  345. end := strings.LastIndex(msg, "\"")
  346. if start == -1 || end == -1 {
  347. return "", errors.New("Unsuported PWD response format")
  348. }
  349. return msg[start+1 : end], nil
  350. }
  351. // Retr issues a RETR FTP command to fetch the specified file from the remote
  352. // FTP server.
  353. //
  354. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  355. func (c *ServerConn) Retr(path string) (io.ReadCloser, error) {
  356. return c.RetrFrom(path, 0)
  357. }
  358. // Retr issues a RETR FTP command to fetch the specified file from the remote
  359. // FTP server, the server will not send the offset first bytes of the file.
  360. //
  361. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  362. func (c *ServerConn) RetrFrom(path string, offset uint64) (io.ReadCloser, error) {
  363. conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
  364. if err != nil {
  365. return nil, err
  366. }
  367. r := &response{conn, c}
  368. return r, 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. // Stor 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(StatusLoggedIn, "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. n, err := r.conn.Read(buf)
  443. return n, err
  444. }
  445. // Close implements the io.Closer interface on a FTP data connection.
  446. func (r *response) Close() error {
  447. err := r.conn.Close()
  448. _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
  449. if err2 != nil {
  450. err = err2
  451. }
  452. return err
  453. }