ftp.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. )
  13. // EntryType describes the different types of an Entry.
  14. type EntryType int
  15. const (
  16. EntryTypeFile EntryType = iota
  17. EntryTypeFolder
  18. EntryTypeLink
  19. )
  20. // ServerConn represents the connection to a remote FTP server.
  21. type ServerConn struct {
  22. conn *textproto.Conn
  23. host string
  24. }
  25. // Entry describes a file and is returned by List().
  26. type Entry struct {
  27. Name string
  28. Type EntryType
  29. Size uint64
  30. }
  31. //
  32. type response struct {
  33. conn net.Conn
  34. c *ServerConn
  35. }
  36. // Connect initializes the connection to the specified ftp server address.
  37. //
  38. // It is generally followed by a call to Login() as most FTP commands require
  39. // an authenticated user.
  40. func Connect(addr string) (*ServerConn, error) {
  41. conn, err := textproto.Dial("tcp", addr)
  42. if err != nil {
  43. return nil, err
  44. }
  45. a := strings.SplitN(addr, ":", 2)
  46. c := &ServerConn{conn, a[0]}
  47. _, _, err = c.conn.ReadCodeLine(StatusReady)
  48. if err != nil {
  49. c.Quit()
  50. return nil, err
  51. }
  52. return c, nil
  53. }
  54. // Login authenticates the client with specified user and password.
  55. //
  56. // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
  57. // that allows anonymous read-only accounts.
  58. func (c *ServerConn) Login(user, password string) error {
  59. _, _, err := c.cmd(StatusUserOK, "USER %s", user)
  60. if err != nil {
  61. return err
  62. }
  63. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  64. if err != nil {
  65. return err
  66. }
  67. // Switch to binary mode
  68. _, _, err = c.cmd(StatusCommandOK, "TYPE I")
  69. if err != nil {
  70. return err
  71. }
  72. return nil
  73. }
  74. // epsv issues an "EPSV" command to get a port number for a data connection.
  75. func (c *ServerConn) epsv() (port int, err error) {
  76. _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
  77. if err != nil {
  78. return
  79. }
  80. start := strings.Index(line, "|||")
  81. end := strings.LastIndex(line, "|")
  82. if start == -1 || end == -1 {
  83. err = errors.New("Invalid EPSV response format")
  84. return
  85. }
  86. port, err = strconv.Atoi(line[start+3 : end])
  87. return
  88. }
  89. // openDataConn creates a new FTP data connection.
  90. //
  91. // Currently, only EPSV is implemented but a fallback to PASV, and to a lesser
  92. // extent, PORT should be added.
  93. func (c *ServerConn) openDataConn() (net.Conn, error) {
  94. port, err := c.epsv()
  95. if err != nil {
  96. return nil, err
  97. }
  98. // Build the new net address string
  99. addr := fmt.Sprintf("%s:%d", c.host, port)
  100. conn, err := net.Dial("tcp", addr)
  101. if err != nil {
  102. return nil, err
  103. }
  104. return conn, nil
  105. }
  106. // cmd is a helper function to execute a command and check for the expected FTP
  107. // return code
  108. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  109. _, err := c.conn.Cmd(format, args...)
  110. if err != nil {
  111. return 0, "", err
  112. }
  113. code, line, err := c.conn.ReadResponse(expected)
  114. return code, line, err
  115. }
  116. // cmdDataConn executes a command which require a FTP data connection.
  117. func (c *ServerConn) cmdDataConn(format string, args ...interface{}) (net.Conn, error) {
  118. conn, err := c.openDataConn()
  119. if err != nil {
  120. return nil, err
  121. }
  122. _, err = c.conn.Cmd(format, args...)
  123. if err != nil {
  124. conn.Close()
  125. return nil, err
  126. }
  127. code, msg, err := c.conn.ReadCodeLine(-1)
  128. if err != nil {
  129. conn.Close()
  130. return nil, err
  131. }
  132. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  133. conn.Close()
  134. return nil, &textproto.Error{code, msg}
  135. }
  136. return conn, nil
  137. }
  138. // parseListLine parses the various non-standard format returned by the LIST
  139. // FTP command.
  140. func parseListLine(line string) (*Entry, error) {
  141. fields := strings.Fields(line)
  142. if len(fields) < 9 {
  143. return nil, errors.New("Unsupported LIST line")
  144. }
  145. e := &Entry{}
  146. switch fields[0][0] {
  147. case '-':
  148. e.Type = EntryTypeFile
  149. case 'd':
  150. e.Type = EntryTypeFolder
  151. case 'l':
  152. e.Type = EntryTypeLink
  153. default:
  154. return nil, errors.New("Unknown entry type")
  155. }
  156. if e.Type == EntryTypeFile {
  157. size, err := strconv.ParseUint(fields[4], 10, 0)
  158. if err != nil {
  159. return nil, err
  160. }
  161. e.Size = size
  162. }
  163. e.Name = strings.Join(fields[8:], " ")
  164. return e, nil
  165. }
  166. // List issues a LIST FTP command.
  167. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  168. conn, err := c.cmdDataConn("LIST %s", path)
  169. if err != nil {
  170. return
  171. }
  172. r := &response{conn, c}
  173. defer r.Close()
  174. bio := bufio.NewReader(r)
  175. for {
  176. line, e := bio.ReadString('\n')
  177. if e == io.EOF {
  178. break
  179. } else if e != nil {
  180. return nil, e
  181. }
  182. entry, err := parseListLine(line)
  183. if err == nil {
  184. entries = append(entries, entry)
  185. }
  186. }
  187. return
  188. }
  189. // ChangeDir issues a CWD FTP command, which changes the current directory to
  190. // the specified path.
  191. func (c *ServerConn) ChangeDir(path string) error {
  192. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  193. return err
  194. }
  195. // ChangeDirToParent issues a CDUP FTP command, which changes the current
  196. // directory to the parent directory. This is similar to a call to ChangeDir
  197. // with a path set to "..".
  198. func (c *ServerConn) ChangeDirToParent() error {
  199. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  200. return err
  201. }
  202. // CurrentDir issues a PWD FTP command, which Returns the path of the current
  203. // directory.
  204. func (c *ServerConn) CurrentDir() (string, error) {
  205. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  206. if err != nil {
  207. return "", err
  208. }
  209. start := strings.Index(msg, "\"")
  210. end := strings.LastIndex(msg, "\"")
  211. if start == -1 || end == -1 {
  212. return "", errors.New("Unsuported PWD response format")
  213. }
  214. return msg[start+1 : end], nil
  215. }
  216. // Retr issues a RETR FTP command to fetch the specified file from the remote
  217. // FTP server.
  218. //
  219. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  220. func (c *ServerConn) Retr(path string) (io.ReadCloser, error) {
  221. conn, err := c.cmdDataConn("RETR %s", path)
  222. if err != nil {
  223. return nil, err
  224. }
  225. r := &response{conn, c}
  226. return r, nil
  227. }
  228. // Stor issues a STOR FTP command to store a file to the remote FTP server.
  229. // Stor creates the specified file with the content of the io.Reader.
  230. //
  231. // Hint: io.Pipe() can be used if an io.Writer is required.
  232. func (c *ServerConn) Stor(path string, r io.Reader) error {
  233. conn, err := c.cmdDataConn("STOR %s", path)
  234. if err != nil {
  235. return err
  236. }
  237. _, err = io.Copy(conn, r)
  238. conn.Close()
  239. if err != nil {
  240. return err
  241. }
  242. _, _, err = c.conn.ReadCodeLine(StatusClosingDataConnection)
  243. return err
  244. }
  245. // Rename renames a file on the remote FTP server.
  246. func (c *ServerConn) Rename(from, to string) error {
  247. _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
  248. if err != nil {
  249. return err
  250. }
  251. _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
  252. return err
  253. }
  254. // Delete issues a DELE FTP command to delete the specified file from the
  255. // remote FTP server.
  256. func (c *ServerConn) Delete(path string) error {
  257. _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
  258. return err
  259. }
  260. // MakeDir issues a MKD FTP command to create the specified directory on the
  261. // remote FTP server.
  262. func (c *ServerConn) MakeDir(path string) error {
  263. _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
  264. return err
  265. }
  266. // RemoveDir issues a RMD FTP command to remove the specified directory from
  267. // the remote FTP server.
  268. func (c *ServerConn) RemoveDir(path string) error {
  269. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
  270. return err
  271. }
  272. // NoOp issues a NOOP FTP command.
  273. // NOOP has no effects and is usually used to prevent the remote FTP server to
  274. // close the otherwise idle connection.
  275. func (c *ServerConn) NoOp() error {
  276. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  277. return err
  278. }
  279. // Logout issues a REIN FTP command to logout the current user.
  280. func (c *ServerConn) Logout() error {
  281. _, _, err := c.cmd(StatusLoggedIn, "REIN")
  282. return err
  283. }
  284. // Quit issues a QUIT FTP command to properly close the connection from the
  285. // remote FTP server.
  286. func (c *ServerConn) Quit() error {
  287. c.conn.Cmd("QUIT")
  288. return c.conn.Close()
  289. }
  290. // Read implements the io.Reader interface on a FTP data connection.
  291. func (r *response) Read(buf []byte) (int, error) {
  292. n, err := r.conn.Read(buf)
  293. if err == io.EOF {
  294. _, _, err2 := r.c.conn.ReadCodeLine(StatusClosingDataConnection)
  295. if err2 != nil {
  296. err = err2
  297. }
  298. }
  299. return n, err
  300. }
  301. // Close implements the io.Closer interface on a FTP data connection.
  302. func (r *response) Close() error {
  303. return r.conn.Close()
  304. }