ftp.go 9.2 KB

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