ftp.go 11 KB

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