ftp.go 12 KB

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