ftp.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package ftp
  2. import (
  3. "bufio"
  4. "io"
  5. "net"
  6. "net/textproto"
  7. "os"
  8. "fmt"
  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, os.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) os.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 os.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 = os.NewError("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, os.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, os.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, os.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, os.NewError(fmt.Sprintf("%d %s", code, msg))
  112. }
  113. return conn, nil
  114. }
  115. func parseListLine(line string) (*Entry, os.Error) {
  116. fields := strings.Fields(line)
  117. if len(fields) < 9 {
  118. return nil, os.NewError("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, os.NewError("Unknown entry type")
  130. }
  131. e.Name = strings.Join(fields[8:], " ")
  132. return e, nil
  133. }
  134. func (c *ServerConn) List(path string) (entries []*Entry, err os.Error) {
  135. conn, err := c.cmdDataConn("LIST %s", path)
  136. if err != nil {
  137. return
  138. }
  139. r := &response{conn, c}
  140. defer r.Close()
  141. bio := bufio.NewReader(r)
  142. for {
  143. line, e := bio.ReadString('\n')
  144. if e == os.EOF {
  145. break
  146. } else if e != nil {
  147. return nil, e
  148. }
  149. entry, err := parseListLine(line)
  150. if err == nil {
  151. entries = append(entries, entry)
  152. }
  153. }
  154. return
  155. }
  156. func (c *ServerConn) ChangeDir(path string) os.Error {
  157. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  158. return err
  159. }
  160. // Retrieves a remote file
  161. func (c *ServerConn) Retr(path string) (io.ReadCloser, os.Error) {
  162. conn, err := c.cmdDataConn("RETR %s", path)
  163. if err != nil {
  164. return nil, err
  165. }
  166. r := &response{conn, c}
  167. return r, nil
  168. }
  169. func (c *ServerConn) Stor(name string, r io.Reader) os.Error {
  170. conn, err := c.cmdDataConn("STOR %s", name)
  171. if err != nil {
  172. return err
  173. }
  174. _, err = io.Copy(conn, r)
  175. conn.Close()
  176. if err != nil {
  177. return err
  178. }
  179. _, _, err = c.conn.ReadCodeLine(StatusClosingDataConnection)
  180. return err
  181. }
  182. func (c *ServerConn) Rename(from, to string) os.Error {
  183. _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
  184. if err != nil {
  185. return err
  186. }
  187. _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
  188. return err
  189. }
  190. func (c *ServerConn) Delete(name string) os.Error {
  191. _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", name)
  192. return err
  193. }
  194. func (c *ServerConn) MakeDir(name string) os.Error {
  195. _, _, err := c.cmd(StatusPathCreated, "MKD %s", name)
  196. return err
  197. }
  198. func (c *ServerConn) RemoveDir(name string) os.Error {
  199. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", name)
  200. return err
  201. }
  202. // Sends a NOOP command. Usualy used to prevent timeouts.
  203. func (c *ServerConn) NoOp() os.Error {
  204. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  205. return err
  206. }
  207. func (c *ServerConn) Quit() os.Error {
  208. c.conn.Cmd("QUIT")
  209. return c.conn.Close()
  210. }
  211. func (r *response) Read(buf []byte) (int, os.Error) {
  212. n, err := r.conn.Read(buf)
  213. if err == os.EOF {
  214. _, _, err2 := r.c.conn.ReadCodeLine(StatusClosingDataConnection)
  215. if err2 != nil {
  216. err = err2
  217. }
  218. }
  219. return n, err
  220. }
  221. func (r *response) Close() os.Error {
  222. return r.conn.Close()
  223. }