ftp.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package ftp
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/textproto"
  9. "strconv"
  10. "strings"
  11. )
  12. type EntryType int
  13. const (
  14. EntryTypeFile EntryType = iota
  15. EntryTypeFolder
  16. EntryTypeLink
  17. )
  18. type ServerConn struct {
  19. conn *textproto.Conn
  20. host string
  21. }
  22. type Entry struct {
  23. Name string
  24. Type EntryType
  25. Size uint64
  26. }
  27. type response struct {
  28. conn net.Conn
  29. c *ServerConn
  30. }
  31. // Connect to a ftp server and returns a ServerConn handler.
  32. func Connect(addr string) (*ServerConn, error) {
  33. conn, err := textproto.Dial("tcp", addr)
  34. if err != nil {
  35. return nil, err
  36. }
  37. a := strings.SplitN(addr, ":", 2)
  38. c := &ServerConn{conn, a[0]}
  39. _, _, err = c.conn.ReadCodeLine(StatusReady)
  40. if err != nil {
  41. c.Quit()
  42. return nil, err
  43. }
  44. return c, nil
  45. }
  46. func (c *ServerConn) Login(user, password string) error {
  47. _, _, err := c.cmd(StatusUserOK, "USER %s", user)
  48. if err != nil {
  49. return err
  50. }
  51. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  52. return err
  53. }
  54. // Enter extended passive mode
  55. func (c *ServerConn) epsv() (port int, err error) {
  56. c.conn.Cmd("EPSV")
  57. _, line, err := c.conn.ReadCodeLine(StatusExtendedPassiveMode)
  58. if err != nil {
  59. return
  60. }
  61. start := strings.Index(line, "|||")
  62. end := strings.LastIndex(line, "|")
  63. if start == -1 || end == -1 {
  64. err = errors.New("Invalid EPSV response format")
  65. return
  66. }
  67. port, err = strconv.Atoi(line[start+3 : end])
  68. return
  69. }
  70. // Open a new data connection using extended passive mode
  71. func (c *ServerConn) openDataConn() (net.Conn, error) {
  72. port, err := c.epsv()
  73. if err != nil {
  74. return nil, err
  75. }
  76. // Build the new net address string
  77. addr := fmt.Sprintf("%s:%d", c.host, port)
  78. conn, err := net.Dial("tcp", addr)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return conn, nil
  83. }
  84. // Helper function to execute a command and check for the expected code
  85. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  86. _, err := c.conn.Cmd(format, args...)
  87. if err != nil {
  88. return 0, "", err
  89. }
  90. code, line, err := c.conn.ReadCodeLine(expected)
  91. return code, line, err
  92. }
  93. // Helper function to execute commands which require a data connection
  94. func (c *ServerConn) cmdDataConn(format string, args ...interface{}) (net.Conn, error) {
  95. conn, err := c.openDataConn()
  96. if err != nil {
  97. return nil, err
  98. }
  99. _, err = c.conn.Cmd(format, args...)
  100. if err != nil {
  101. conn.Close()
  102. return nil, err
  103. }
  104. code, msg, err := c.conn.ReadCodeLine(-1)
  105. if err != nil {
  106. conn.Close()
  107. return nil, err
  108. }
  109. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  110. conn.Close()
  111. return nil, &textproto.Error{code, msg}
  112. }
  113. return conn, nil
  114. }
  115. func parseListLine(line string) (*Entry, error) {
  116. fields := strings.Fields(line)
  117. if len(fields) < 9 {
  118. return nil, errors.New("Unsupported LIST line")
  119. }
  120. e := &Entry{}
  121. switch fields[0][0] {
  122. case '-':
  123. e.Type = EntryTypeFile
  124. case 'd':
  125. e.Type = EntryTypeFolder
  126. case 'l':
  127. e.Type = EntryTypeLink
  128. default:
  129. return nil, errors.New("Unknown entry type")
  130. }
  131. if e.Type == EntryTypeFile {
  132. size, err := strconv.ParseUint(fields[4], 10, 0)
  133. if err != nil {
  134. return nil, err
  135. }
  136. e.Size = size
  137. }
  138. e.Name = strings.Join(fields[8:], " ")
  139. return e, nil
  140. }
  141. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  142. conn, err := c.cmdDataConn("LIST %s", path)
  143. if err != nil {
  144. return
  145. }
  146. r := &response{conn, c}
  147. defer r.Close()
  148. bio := bufio.NewReader(r)
  149. for {
  150. line, e := bio.ReadString('\n')
  151. if e == io.EOF {
  152. break
  153. } else if e != nil {
  154. return nil, e
  155. }
  156. entry, err := parseListLine(line)
  157. if err == nil {
  158. entries = append(entries, entry)
  159. }
  160. }
  161. return
  162. }
  163. // Changes the current directory to the specified path.
  164. func (c *ServerConn) ChangeDir(path string) error {
  165. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  166. return err
  167. }
  168. // Changes the current directory to the parent directory.
  169. // ChangeDir("..")
  170. func (c *ServerConn) ChangeDirToParent() error {
  171. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  172. return err
  173. }
  174. // Returns the path of the current directory.
  175. func (c *ServerConn) CurrentDir() (string, error) {
  176. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  177. if err != nil {
  178. return "", err
  179. }
  180. start := strings.Index(msg, "\"")
  181. end := strings.LastIndex(msg, "\"")
  182. if start == -1 || end == -1 {
  183. return "", errors.New("Unsuported PWD response format")
  184. }
  185. return msg[start+1 : end], nil
  186. }
  187. // Retrieves a file from the remote FTP server.
  188. // The ReadCloser must be closed at the end of the operation.
  189. func (c *ServerConn) Retr(path string) (io.ReadCloser, error) {
  190. conn, err := c.cmdDataConn("RETR %s", path)
  191. if err != nil {
  192. return nil, err
  193. }
  194. r := &response{conn, c}
  195. return r, nil
  196. }
  197. // Uploads a file to the remote FTP server.
  198. // This function gets the data from the io.Reader. Hint: io.Pipe()
  199. func (c *ServerConn) Stor(path string, r io.Reader) error {
  200. conn, err := c.cmdDataConn("STOR %s", path)
  201. if err != nil {
  202. return err
  203. }
  204. _, err = io.Copy(conn, r)
  205. conn.Close()
  206. if err != nil {
  207. return err
  208. }
  209. _, _, err = c.conn.ReadCodeLine(StatusClosingDataConnection)
  210. return err
  211. }
  212. // Renames a file on the remote FTP server.
  213. func (c *ServerConn) Rename(from, to string) error {
  214. _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
  215. if err != nil {
  216. return err
  217. }
  218. _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
  219. return err
  220. }
  221. // Deletes a file on the remote FTP server.
  222. func (c *ServerConn) Delete(path string) error {
  223. _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
  224. return err
  225. }
  226. // Creates a new directory on the remote FTP server.
  227. func (c *ServerConn) MakeDir(path string) error {
  228. _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
  229. return err
  230. }
  231. // Removes a directory from the remote FTP server.
  232. func (c *ServerConn) RemoveDir(path string) error {
  233. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
  234. return err
  235. }
  236. // Sends a NOOP command. Usualy used to prevent timeouts.
  237. func (c *ServerConn) NoOp() error {
  238. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  239. return err
  240. }
  241. // Properly close the connection from the remote FTP server.
  242. // It notifies the remote server that we are about to close the connection,
  243. // then it really closes it.
  244. func (c *ServerConn) Quit() error {
  245. c.conn.Cmd("QUIT")
  246. return c.conn.Close()
  247. }
  248. func (r *response) Read(buf []byte) (int, error) {
  249. n, err := r.conn.Read(buf)
  250. if err == io.EOF {
  251. _, _, err2 := r.c.conn.ReadCodeLine(StatusClosingDataConnection)
  252. if err2 != nil {
  253. err = err2
  254. }
  255. }
  256. return n, err
  257. }
  258. func (r *response) Close() error {
  259. return r.conn.Close()
  260. }