ftp.go 11 KB

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