ftp.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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(host, user, password string) (*ServerConn, os.Error) {
  33. conn, err := textproto.Dial("tcp", host)
  34. if err != nil {
  35. return nil, err
  36. }
  37. a := strings.SplitN(host, ":", 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. c.conn.Cmd("USER %s", user)
  45. _, _, err = c.conn.ReadCodeLine(StatusUserOK)
  46. if err != nil {
  47. c.Quit()
  48. return nil, err
  49. }
  50. c.conn.Cmd("PASS %s", password)
  51. _, _, err = c.conn.ReadCodeLine(StatusLoggedIn)
  52. if err != nil {
  53. c.Quit()
  54. return nil, err
  55. }
  56. return c, nil
  57. }
  58. // Like Connect() but with anonymous credentials.
  59. func ConnectAnonymous(host string) (*ServerConn, os.Error) {
  60. return Connect(host, "anonymous", "anonymous")
  61. }
  62. // Enter extended passive mode
  63. func (c *ServerConn) epsv() (port int, err os.Error) {
  64. c.conn.Cmd("EPSV")
  65. _, line, err := c.conn.ReadCodeLine(StatusExtendedPassiveMode)
  66. if err != nil {
  67. return
  68. }
  69. start := strings.Index(line, "|||")
  70. end := strings.LastIndex(line, "|")
  71. if start == -1 || end == -1 {
  72. err = os.NewError("Invalid EPSV response format")
  73. return
  74. }
  75. port, err = strconv.Atoi(line[start+3 : end])
  76. return
  77. }
  78. // Open a new data connection using extended passive mode
  79. func (c *ServerConn) openDataConnection() (net.Conn, os.Error) {
  80. port, err := c.epsv()
  81. if err != nil {
  82. return nil, err
  83. }
  84. // Build the new net address string
  85. addr := fmt.Sprintf("%s:%d", c.host, port)
  86. conn, err := net.Dial("tcp", addr)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return conn, nil
  91. }
  92. // Helper function to check if the last command succeeded and if it will
  93. // send the data to the data connection.
  94. // This is needed because some servers return StatusAboutToSend (150)
  95. // and some StatusAlreadyOpen (125)
  96. func (c *ServerConn) checkDataConn() os.Error {
  97. code, msg, err := c.conn.ReadCodeLine(-1)
  98. if err != nil {
  99. return err
  100. }
  101. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  102. return os.NewError(fmt.Sprintf("%d %s", code, msg))
  103. }
  104. return nil
  105. }
  106. func parseListLine(line string) (*Entry, os.Error) {
  107. fields := strings.Fields(line)
  108. if len(fields) < 9 {
  109. return nil, os.NewError("Unsupported LIST line")
  110. }
  111. e := &Entry{}
  112. switch fields[0][0] {
  113. case '-':
  114. e.Type = EntryTypeFile
  115. case 'd':
  116. e.Type = EntryTypeFolder
  117. case 'l':
  118. e.Type = EntryTypeLink
  119. default:
  120. return nil, os.NewError("Unknown entry type")
  121. }
  122. e.Name = strings.Join(fields[8:], " ")
  123. return e, nil
  124. }
  125. func (c *ServerConn) List(path string) (entries []*Entry, err os.Error) {
  126. conn, err := c.openDataConnection()
  127. if err != nil {
  128. return
  129. }
  130. r := &response{conn, c}
  131. defer r.Close()
  132. _, err = c.conn.Cmd("LIST %s", path)
  133. if err != nil {
  134. return
  135. }
  136. err = c.checkDataConn()
  137. if err != nil {
  138. return
  139. }
  140. bio := bufio.NewReader(r)
  141. for {
  142. line, e := bio.ReadString('\n')
  143. if e == os.EOF {
  144. break
  145. } else if e != nil {
  146. return nil, e
  147. }
  148. entry, err := parseListLine(line)
  149. if err == nil {
  150. entries = append(entries, entry)
  151. }
  152. }
  153. return
  154. }
  155. func (c *ServerConn) ChangeDir(path string) (err os.Error) {
  156. _, err = c.conn.Cmd("CWD %s", path)
  157. if err == nil {
  158. _, _, err = c.conn.ReadCodeLine(StatusRequestedFileActionOK)
  159. }
  160. return
  161. }
  162. // Retrieves a remote file
  163. func (c *ServerConn) Retr(path string) (io.ReadCloser, os.Error) {
  164. conn, err := c.openDataConnection()
  165. if err != nil {
  166. return nil, err
  167. }
  168. _, err = c.conn.Cmd("RETR %s", path)
  169. if err != nil {
  170. conn.Close()
  171. return nil, err
  172. }
  173. err = c.checkDataConn()
  174. if err != nil {
  175. conn.Close()
  176. return nil, err
  177. }
  178. r := &response{conn, c}
  179. return r, nil
  180. }
  181. func (c *ServerConn) Stor(name string, r io.Reader) os.Error {
  182. conn, err := c.openDataConnection()
  183. if err != nil {
  184. return err
  185. }
  186. _, err = c.conn.Cmd("STOR %s", name)
  187. if err != nil {
  188. conn.Close()
  189. return err
  190. }
  191. err = c.checkDataConn()
  192. if err != nil {
  193. conn.Close()
  194. return err
  195. }
  196. _, err = io.Copy(conn, r)
  197. conn.Close()
  198. if err != nil {
  199. return err
  200. }
  201. _, _, err = c.conn.ReadCodeLine(StatusClosingDataConnection)
  202. return err
  203. }
  204. func (c *ServerConn) Rename(from, to string) os.Error {
  205. _, err := c.conn.Cmd("RNFR %s", from)
  206. if err != nil {
  207. return err
  208. }
  209. _, _, err = c.conn.ReadCodeLine(StatusRequestFilePending)
  210. if err != nil {
  211. return err
  212. }
  213. _, err = c.conn.Cmd("RNTO %s", to)
  214. if err != nil {
  215. return err
  216. }
  217. _, _, err = c.conn.ReadCodeLine(StatusRequestedFileActionOK)
  218. return err
  219. }
  220. func (c *ServerConn) Delete(name string) os.Error {
  221. _, err := c.conn.Cmd("DELE %s", name)
  222. if err != nil {
  223. return err
  224. }
  225. _, _, err = c.conn.ReadCodeLine(StatusRequestedFileActionOK)
  226. return err
  227. }
  228. func (c *ServerConn) MakeDir(name string) os.Error {
  229. _, err := c.conn.Cmd("MKD %s", name)
  230. if err != nil {
  231. return err
  232. }
  233. _, _, err = c.conn.ReadCodeLine(StatusPathCreated)
  234. return err
  235. }
  236. func (c *ServerConn) RemoveDir(name string) os.Error {
  237. _, err := c.conn.Cmd("RMD %s", name)
  238. if err != nil {
  239. return err
  240. }
  241. _, _, err = c.conn.ReadCodeLine(StatusRequestedFileActionOK)
  242. return err
  243. }
  244. // Sends a NOOP command. Usualy used to prevent timeouts.
  245. func (c *ServerConn) NoOp() os.Error {
  246. _, err := c.conn.Cmd("NOOP")
  247. if err != nil {
  248. return err
  249. }
  250. _, _, err = c.conn.ReadCodeLine(StatusCommandOK)
  251. return err
  252. }
  253. func (c *ServerConn) Quit() os.Error {
  254. c.conn.Cmd("QUIT")
  255. return c.conn.Close()
  256. }
  257. func (r *response) Read(buf []byte) (int, os.Error) {
  258. n, err := r.conn.Read(buf)
  259. if err == os.EOF {
  260. _, _, err2 := r.c.conn.ReadCodeLine(StatusClosingDataConnection)
  261. if err2 != nil {
  262. err = err2
  263. }
  264. }
  265. return n, err
  266. }
  267. func (r *response) Close() os.Error {
  268. return r.conn.Close()
  269. }