ftp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Package ftp implements a FTP client as described in RFC 959.
  2. package ftp
  3. import (
  4. "bufio"
  5. "errors"
  6. "io"
  7. "net"
  8. "net/textproto"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // EntryType describes the different types of an Entry.
  14. type EntryType int
  15. // The differents types of an Entry
  16. const (
  17. EntryTypeFile EntryType = iota
  18. EntryTypeFolder
  19. EntryTypeLink
  20. )
  21. // ServerConn represents the connection to a remote FTP server.
  22. type ServerConn struct {
  23. conn *textproto.Conn
  24. host string
  25. timeout time.Duration
  26. features map[string]string
  27. disableEPSV bool
  28. }
  29. // Entry describes a file and is returned by List().
  30. type Entry struct {
  31. Name string
  32. Type EntryType
  33. Size uint64
  34. Time time.Time
  35. }
  36. // response represent a data-connection
  37. type response struct {
  38. conn net.Conn
  39. c *ServerConn
  40. }
  41. // Connect is an alias to Dial, for backward compatibility
  42. func Connect(addr string) (*ServerConn, error) {
  43. return Dial(addr)
  44. }
  45. // Dial is like DialTimeout with no timeout
  46. func Dial(addr string) (*ServerConn, error) {
  47. return DialTimeout(addr, 0)
  48. }
  49. // DialTimeout initializes the connection to the specified ftp server address.
  50. //
  51. // It is generally followed by a call to Login() as most FTP commands require
  52. // an authenticated user.
  53. func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error) {
  54. tconn, err := net.DialTimeout("tcp", addr, timeout)
  55. if err != nil {
  56. return nil, err
  57. }
  58. // Use the resolved IP address in case addr contains a domain name
  59. // If we use the domain name, we might not resolve to the same IP.
  60. remoteAddr := tconn.RemoteAddr().String()
  61. host, _, err := net.SplitHostPort(remoteAddr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. conn := textproto.NewConn(tconn)
  66. c := &ServerConn{
  67. conn: conn,
  68. host: host,
  69. timeout: timeout,
  70. features: make(map[string]string),
  71. }
  72. _, _, err = c.conn.ReadResponse(StatusReady)
  73. if err != nil {
  74. c.Quit()
  75. return nil, err
  76. }
  77. err = c.feat()
  78. if err != nil {
  79. c.Quit()
  80. return nil, err
  81. }
  82. return c, nil
  83. }
  84. // Login authenticates the client with specified user and password.
  85. //
  86. // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
  87. // that allows anonymous read-only accounts.
  88. func (c *ServerConn) Login(user, password string) error {
  89. code, message, err := c.cmd(-1, "USER %s", user)
  90. if err != nil {
  91. return err
  92. }
  93. switch code {
  94. case StatusLoggedIn:
  95. case StatusUserOK:
  96. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  97. if err != nil {
  98. return err
  99. }
  100. default:
  101. return errors.New(message)
  102. }
  103. // Switch to binary mode
  104. _, _, err = c.cmd(StatusCommandOK, "TYPE I")
  105. if err != nil {
  106. return err
  107. }
  108. return nil
  109. }
  110. // feat issues a FEAT FTP command to list the additional commands supported by
  111. // the remote FTP server.
  112. // FEAT is described in RFC 2389
  113. func (c *ServerConn) feat() error {
  114. code, message, err := c.cmd(-1, "FEAT")
  115. if err != nil {
  116. return err
  117. }
  118. if code != StatusSystem {
  119. // The server does not support the FEAT command. This is not an
  120. // error: we consider that there is no additional feature.
  121. return nil
  122. }
  123. lines := strings.Split(message, "\n")
  124. for _, line := range lines {
  125. if !strings.HasPrefix(line, " ") {
  126. continue
  127. }
  128. line = strings.TrimSpace(line)
  129. featureElements := strings.SplitN(line, " ", 2)
  130. command := featureElements[0]
  131. var commandDesc string
  132. if len(featureElements) == 2 {
  133. commandDesc = featureElements[1]
  134. }
  135. c.features[command] = commandDesc
  136. }
  137. return nil
  138. }
  139. // epsv issues an "EPSV" command to get a port number for a data connection.
  140. func (c *ServerConn) epsv() (port int, err error) {
  141. _, line, err := c.cmd(StatusExtendedPassiveMode, "EPSV")
  142. if err != nil {
  143. return
  144. }
  145. start := strings.Index(line, "|||")
  146. end := strings.LastIndex(line, "|")
  147. if start == -1 || end == -1 {
  148. err = errors.New("Invalid EPSV response format")
  149. return
  150. }
  151. port, err = strconv.Atoi(line[start+3 : end])
  152. return
  153. }
  154. // pasv issues a "PASV" command to get a port number for a data connection.
  155. func (c *ServerConn) pasv() (port int, err error) {
  156. _, line, err := c.cmd(StatusPassiveMode, "PASV")
  157. if err != nil {
  158. return
  159. }
  160. // PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
  161. start := strings.Index(line, "(")
  162. end := strings.LastIndex(line, ")")
  163. if start == -1 || end == -1 {
  164. return 0, errors.New("Invalid PASV response format")
  165. }
  166. // We have to split the response string
  167. pasvData := strings.Split(line[start+1:end], ",")
  168. if len(pasvData) < 6 {
  169. return 0, errors.New("Invalid PASV response format")
  170. }
  171. // Let's compute the port number
  172. portPart1, err1 := strconv.Atoi(pasvData[4])
  173. if err1 != nil {
  174. err = err1
  175. return
  176. }
  177. portPart2, err2 := strconv.Atoi(pasvData[5])
  178. if err2 != nil {
  179. err = err2
  180. return
  181. }
  182. // Recompose port
  183. port = portPart1*256 + portPart2
  184. return
  185. }
  186. // getDataConnPort returns a port for a new data connection
  187. // it uses the best available method to do so
  188. func (c *ServerConn) getDataConnPort() (int, error) {
  189. if !c.disableEPSV {
  190. if port, err := c.epsv(); err == nil {
  191. return port, nil
  192. }
  193. // if there is an error, disable EPSV for the next attempts
  194. c.disableEPSV = true
  195. }
  196. return c.pasv()
  197. }
  198. // openDataConn creates a new FTP data connection.
  199. func (c *ServerConn) openDataConn() (net.Conn, error) {
  200. port, err := c.getDataConnPort()
  201. if err != nil {
  202. return nil, err
  203. }
  204. return net.DialTimeout("tcp", net.JoinHostPort(c.host, strconv.Itoa(port)), c.timeout)
  205. }
  206. // cmd is a helper function to execute a command and check for the expected FTP
  207. // return code
  208. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  209. _, err := c.conn.Cmd(format, args...)
  210. if err != nil {
  211. return 0, "", err
  212. }
  213. return c.conn.ReadResponse(expected)
  214. }
  215. // cmdDataConnFrom executes a command which require a FTP data connection.
  216. // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
  217. func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
  218. conn, err := c.openDataConn()
  219. if err != nil {
  220. return nil, err
  221. }
  222. if offset != 0 {
  223. _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
  224. if err != nil {
  225. conn.Close()
  226. return nil, err
  227. }
  228. }
  229. _, err = c.conn.Cmd(format, args...)
  230. if err != nil {
  231. conn.Close()
  232. return nil, err
  233. }
  234. code, msg, err := c.conn.ReadResponse(-1)
  235. if err != nil {
  236. conn.Close()
  237. return nil, err
  238. }
  239. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  240. conn.Close()
  241. return nil, &textproto.Error{Code: code, Msg: msg}
  242. }
  243. return conn, nil
  244. }
  245. // NameList issues an NLST FTP command.
  246. func (c *ServerConn) NameList(path string) (entries []string, err error) {
  247. conn, err := c.cmdDataConnFrom(0, "NLST %s", path)
  248. if err != nil {
  249. return
  250. }
  251. r := &response{conn, c}
  252. defer r.Close()
  253. scanner := bufio.NewScanner(r)
  254. for scanner.Scan() {
  255. entries = append(entries, scanner.Text())
  256. }
  257. if err = scanner.Err(); err != nil {
  258. return entries, err
  259. }
  260. return
  261. }
  262. // List issues a LIST FTP command.
  263. func (c *ServerConn) List(path string) (entries []*Entry, err error) {
  264. conn, err := c.cmdDataConnFrom(0, "LIST %s", path)
  265. if err != nil {
  266. return
  267. }
  268. r := &response{conn, c}
  269. defer r.Close()
  270. scanner := bufio.NewScanner(r)
  271. for scanner.Scan() {
  272. line := scanner.Text()
  273. entry, err := parseListLine(line)
  274. if err == nil {
  275. entries = append(entries, entry)
  276. }
  277. }
  278. if err := scanner.Err(); err != nil {
  279. return nil, err
  280. }
  281. return
  282. }
  283. // ChangeDir issues a CWD FTP command, which changes the current directory to
  284. // the specified path.
  285. func (c *ServerConn) ChangeDir(path string) error {
  286. _, _, err := c.cmd(StatusRequestedFileActionOK, "CWD %s", path)
  287. return err
  288. }
  289. // ChangeDirToParent issues a CDUP FTP command, which changes the current
  290. // directory to the parent directory. This is similar to a call to ChangeDir
  291. // with a path set to "..".
  292. func (c *ServerConn) ChangeDirToParent() error {
  293. _, _, err := c.cmd(StatusRequestedFileActionOK, "CDUP")
  294. return err
  295. }
  296. // CurrentDir issues a PWD FTP command, which Returns the path of the current
  297. // directory.
  298. func (c *ServerConn) CurrentDir() (string, error) {
  299. _, msg, err := c.cmd(StatusPathCreated, "PWD")
  300. if err != nil {
  301. return "", err
  302. }
  303. start := strings.Index(msg, "\"")
  304. end := strings.LastIndex(msg, "\"")
  305. if start == -1 || end == -1 {
  306. return "", errors.New("Unsuported PWD response format")
  307. }
  308. return msg[start+1 : end], nil
  309. }
  310. // Retr issues a RETR FTP command to fetch the specified file from the remote
  311. // FTP server.
  312. //
  313. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  314. func (c *ServerConn) Retr(path string) (io.ReadCloser, error) {
  315. return c.RetrFrom(path, 0)
  316. }
  317. // RetrFrom issues a RETR FTP command to fetch the specified file from the remote
  318. // FTP server, the server will not send the offset first bytes of the file.
  319. //
  320. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  321. func (c *ServerConn) RetrFrom(path string, offset uint64) (io.ReadCloser, error) {
  322. conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
  323. if err != nil {
  324. return nil, err
  325. }
  326. return &response{conn, c}, nil
  327. }
  328. // Stor issues a STOR FTP command to store a file to the remote FTP server.
  329. // Stor creates the specified file with the content of the io.Reader.
  330. //
  331. // Hint: io.Pipe() can be used if an io.Writer is required.
  332. func (c *ServerConn) Stor(path string, r io.Reader) error {
  333. return c.StorFrom(path, r, 0)
  334. }
  335. // StorFrom issues a STOR FTP command to store a file to the remote FTP server.
  336. // Stor creates the specified file with the content of the io.Reader, writing
  337. // on the server will start at the given file offset.
  338. //
  339. // Hint: io.Pipe() can be used if an io.Writer is required.
  340. func (c *ServerConn) StorFrom(path string, r io.Reader, offset uint64) error {
  341. conn, err := c.cmdDataConnFrom(offset, "STOR %s", path)
  342. if err != nil {
  343. return err
  344. }
  345. _, err = io.Copy(conn, r)
  346. conn.Close()
  347. if err != nil {
  348. return err
  349. }
  350. _, _, err = c.conn.ReadResponse(StatusClosingDataConnection)
  351. return err
  352. }
  353. // Rename renames a file on the remote FTP server.
  354. func (c *ServerConn) Rename(from, to string) error {
  355. _, _, err := c.cmd(StatusRequestFilePending, "RNFR %s", from)
  356. if err != nil {
  357. return err
  358. }
  359. _, _, err = c.cmd(StatusRequestedFileActionOK, "RNTO %s", to)
  360. return err
  361. }
  362. // Delete issues a DELE FTP command to delete the specified file from the
  363. // remote FTP server.
  364. func (c *ServerConn) Delete(path string) error {
  365. _, _, err := c.cmd(StatusRequestedFileActionOK, "DELE %s", path)
  366. return err
  367. }
  368. // MakeDir issues a MKD FTP command to create the specified directory on the
  369. // remote FTP server.
  370. func (c *ServerConn) MakeDir(path string) error {
  371. _, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
  372. return err
  373. }
  374. // RemoveDir issues a RMD FTP command to remove the specified directory from
  375. // the remote FTP server.
  376. func (c *ServerConn) RemoveDir(path string) error {
  377. _, _, err := c.cmd(StatusRequestedFileActionOK, "RMD %s", path)
  378. return err
  379. }
  380. // NoOp issues a NOOP FTP command.
  381. // NOOP has no effects and is usually used to prevent the remote FTP server to
  382. // close the otherwise idle connection.
  383. func (c *ServerConn) NoOp() error {
  384. _, _, err := c.cmd(StatusCommandOK, "NOOP")
  385. return err
  386. }
  387. // Logout issues a REIN FTP command to logout the current user.
  388. func (c *ServerConn) Logout() error {
  389. _, _, err := c.cmd(StatusReady, "REIN")
  390. return err
  391. }
  392. // Quit issues a QUIT FTP command to properly close the connection from the
  393. // remote FTP server.
  394. func (c *ServerConn) Quit() error {
  395. c.conn.Cmd("QUIT")
  396. return c.conn.Close()
  397. }
  398. // Read implements the io.Reader interface on a FTP data connection.
  399. func (r *response) Read(buf []byte) (int, error) {
  400. return r.conn.Read(buf)
  401. }
  402. // Close implements the io.Closer interface on a FTP data connection.
  403. func (r *response) Close() error {
  404. err := r.conn.Close()
  405. _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
  406. if err2 != nil {
  407. err = err2
  408. }
  409. return err
  410. }