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