ftp.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Package ftp implements a FTP client as described in RFC 959.
  2. //
  3. // A textproto.Error is returned for errors at the protocol level.
  4. // This is a stripped down version of
  5. // github.com/jlaffaye/ftp@v0.0.0-20191218041957-e1b8fdd0dcc3
  6. package ftp
  7. import (
  8. "context"
  9. "errors"
  10. "io"
  11. "net"
  12. "net/textproto"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. // EntryType describes the different types of an Entry.
  18. type EntryType int
  19. // The differents types of an Entry
  20. const (
  21. EntryTypeFile EntryType = iota
  22. EntryTypeFolder
  23. EntryTypeLink
  24. )
  25. // ServerConn represents the connection to a remote FTP server.
  26. // A single connection only supports one in-flight data connection.
  27. // It is not safe to be called concurrently.
  28. type ServerConn struct {
  29. options *dialOptions
  30. conn *textproto.Conn
  31. host string
  32. // Server capabilities discovered at runtime
  33. features map[string]string
  34. mlstSupported bool
  35. }
  36. // DialOption represents an option to start a new connection with Dial
  37. type DialOption struct {
  38. setup func(do *dialOptions)
  39. }
  40. // dialOptions contains all the options set by DialOption.setup
  41. type dialOptions struct {
  42. context context.Context
  43. dialer net.Dialer
  44. conn net.Conn
  45. disableEPSV bool
  46. location *time.Location
  47. }
  48. // Response represents a data-connection
  49. type Response struct {
  50. conn net.Conn
  51. c *ServerConn
  52. closed bool
  53. }
  54. // Dial connects to the specified address with optional options
  55. func Dial(addr string, options ...DialOption) (*ServerConn, error) {
  56. do := &dialOptions{}
  57. for _, option := range options {
  58. option.setup(do)
  59. }
  60. if do.location == nil {
  61. do.location = time.UTC
  62. }
  63. tconn := do.conn
  64. if tconn == nil {
  65. var err error
  66. ctx := do.context
  67. if ctx == nil {
  68. ctx = context.Background()
  69. }
  70. tconn, err = do.dialer.DialContext(ctx, "tcp", addr)
  71. if err != nil {
  72. return nil, err
  73. }
  74. }
  75. // Use the resolved IP address in case addr contains a domain name
  76. // If we use the domain name, we might not resolve to the same IP.
  77. remoteAddr := tconn.RemoteAddr().(*net.TCPAddr)
  78. var sourceConn io.ReadWriteCloser = tconn
  79. // if do.debugOutput != nil {
  80. // sourceConn = newDebugWrapper(tconn, do.debugOutput)
  81. // }
  82. c := &ServerConn{
  83. options: do,
  84. features: make(map[string]string),
  85. conn: textproto.NewConn(sourceConn),
  86. host: remoteAddr.IP.String(),
  87. }
  88. _, _, err := c.conn.ReadResponse(StatusReady)
  89. if err != nil {
  90. c.Quit()
  91. return nil, err
  92. }
  93. err = c.feat()
  94. if err != nil {
  95. c.Quit()
  96. return nil, err
  97. }
  98. if _, mlstSupported := c.features["MLST"]; mlstSupported {
  99. c.mlstSupported = true
  100. }
  101. return c, nil
  102. }
  103. // DialWithTimeout returns a DialOption that configures the ServerConn with specified timeout
  104. func DialWithTimeout(timeout time.Duration) DialOption {
  105. return DialOption{func(do *dialOptions) {
  106. do.dialer.Timeout = timeout
  107. }}
  108. }
  109. // DialWithDisabledEPSV returns a DialOption that configures the ServerConn with EPSV disabled
  110. // Note that EPSV is only used when advertised in the server features.
  111. func DialWithDisabledEPSV(disabled bool) DialOption {
  112. return DialOption{func(do *dialOptions) {
  113. do.disableEPSV = disabled
  114. }}
  115. }
  116. // DialTimeout initializes the connection to the specified ftp server address.
  117. //
  118. // It is generally followed by a call to Login() as most FTP commands require
  119. // an authenticated user.
  120. func DialTimeout(addr string, timeout time.Duration) (*ServerConn, error) {
  121. return Dial(addr, DialWithTimeout(timeout))
  122. }
  123. // Login authenticates the client with specified user and password.
  124. //
  125. // "anonymous"/"anonymous" is a common user/password scheme for FTP servers
  126. // that allows anonymous read-only accounts.
  127. func (c *ServerConn) Login(user, password string) error {
  128. code, message, err := c.cmd(-1, "USER %s", user)
  129. if err != nil {
  130. return err
  131. }
  132. switch code {
  133. case StatusLoggedIn:
  134. case StatusUserOK:
  135. _, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
  136. if err != nil {
  137. return err
  138. }
  139. default:
  140. return errors.New(message)
  141. }
  142. // Switch to binary mode
  143. if _, _, err = c.cmd(StatusCommandOK, "TYPE I"); err != nil {
  144. return err
  145. }
  146. return err
  147. }
  148. // feat issues a FEAT FTP command to list the additional commands supported by
  149. // the remote FTP server.
  150. // FEAT is described in RFC 2389
  151. func (c *ServerConn) feat() error {
  152. code, message, err := c.cmd(-1, "FEAT")
  153. if err != nil {
  154. return err
  155. }
  156. if code != StatusSystem {
  157. // The server does not support the FEAT command. This is not an
  158. // error: we consider that there is no additional feature.
  159. return nil
  160. }
  161. lines := strings.Split(message, "\n")
  162. for _, line := range lines {
  163. if !strings.HasPrefix(line, " ") {
  164. continue
  165. }
  166. line = strings.TrimSpace(line)
  167. featureElements := strings.SplitN(line, " ", 2)
  168. command := featureElements[0]
  169. var commandDesc string
  170. if len(featureElements) == 2 {
  171. commandDesc = featureElements[1]
  172. }
  173. c.features[command] = commandDesc
  174. }
  175. return nil
  176. }
  177. // pasv issues a "PASV" command to get a port number for a data connection.
  178. func (c *ServerConn) pasv() (host string, 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. err = errors.New("invalid PASV response format")
  188. return
  189. }
  190. // We have to split the response string
  191. pasvData := strings.Split(line[start+1:end], ",")
  192. if len(pasvData) < 6 {
  193. err = errors.New("invalid PASV response format")
  194. return
  195. }
  196. // Let's compute the port number
  197. portPart1, err1 := strconv.Atoi(pasvData[4])
  198. if err1 != nil {
  199. err = err1
  200. return
  201. }
  202. portPart2, err2 := strconv.Atoi(pasvData[5])
  203. if err2 != nil {
  204. err = err2
  205. return
  206. }
  207. // Recompose port
  208. port = portPart1*256 + portPart2
  209. // Make the IP address to connect to
  210. host = strings.Join(pasvData[0:4], ".")
  211. return
  212. }
  213. // getDataConnPort returns a host, port for a new data connection
  214. func (c *ServerConn) getDataConnPort() (string, int, error) {
  215. return c.pasv()
  216. }
  217. // openDataConn creates a new FTP data connection.
  218. func (c *ServerConn) openDataConn() (net.Conn, error) {
  219. host, port, err := c.getDataConnPort()
  220. if err != nil {
  221. return nil, err
  222. }
  223. addr := net.JoinHostPort(host, strconv.Itoa(port))
  224. return c.options.dialer.Dial("tcp", addr)
  225. }
  226. // cmd is a helper function to execute a command and check for the expected FTP
  227. // return code
  228. func (c *ServerConn) cmd(expected int, format string, args ...interface{}) (int, string, error) {
  229. _, err := c.conn.Cmd(format, args...)
  230. if err != nil {
  231. return 0, "", err
  232. }
  233. return c.conn.ReadResponse(expected)
  234. }
  235. // cmdDataConnFrom executes a command which require a FTP data connection.
  236. // Issues a REST FTP command to specify the number of bytes to skip for the transfer.
  237. func (c *ServerConn) cmdDataConnFrom(offset uint64, format string, args ...interface{}) (net.Conn, error) {
  238. conn, err := c.openDataConn()
  239. if err != nil {
  240. return nil, err
  241. }
  242. if offset != 0 {
  243. _, _, err := c.cmd(StatusRequestFilePending, "REST %d", offset)
  244. if err != nil {
  245. conn.Close()
  246. return nil, err
  247. }
  248. }
  249. _, err = c.conn.Cmd(format, args...)
  250. if err != nil {
  251. conn.Close()
  252. return nil, err
  253. }
  254. code, msg, err := c.conn.ReadResponse(-1)
  255. if err != nil {
  256. conn.Close()
  257. return nil, err
  258. }
  259. if code != StatusAlreadyOpen && code != StatusAboutToSend {
  260. conn.Close()
  261. return nil, &textproto.Error{Code: code, Msg: msg}
  262. }
  263. return conn, nil
  264. }
  265. // Retr issues a RETR FTP command to fetch the specified file from the remote
  266. // FTP server.
  267. //
  268. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  269. func (c *ServerConn) Retr(path string) (*Response, error) {
  270. return c.RetrFrom(path, 0)
  271. }
  272. // RetrFrom issues a RETR FTP command to fetch the specified file from the remote
  273. // FTP server, the server will not send the offset first bytes of the file.
  274. //
  275. // The returned ReadCloser must be closed to cleanup the FTP data connection.
  276. func (c *ServerConn) RetrFrom(path string, offset uint64) (*Response, error) {
  277. conn, err := c.cmdDataConnFrom(offset, "RETR %s", path)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return &Response{conn: conn, c: c}, nil
  282. }
  283. // Logout issues a REIN FTP command to logout the current user.
  284. func (c *ServerConn) Logout() error {
  285. _, _, err := c.cmd(StatusReady, "REIN")
  286. return err
  287. }
  288. // Quit issues a QUIT FTP command to properly close the connection from the
  289. // remote FTP server.
  290. func (c *ServerConn) Quit() error {
  291. c.conn.Cmd("QUIT")
  292. return c.conn.Close()
  293. }
  294. // Read implements the io.Reader interface on a FTP data connection.
  295. func (r *Response) Read(buf []byte) (int, error) {
  296. return r.conn.Read(buf)
  297. }
  298. // Close implements the io.Closer interface on a FTP data connection.
  299. // After the first call, Close will do nothing and return nil.
  300. func (r *Response) Close() error {
  301. if r.closed {
  302. return nil
  303. }
  304. err := r.conn.Close()
  305. _, _, err2 := r.c.conn.ReadResponse(StatusClosingDataConnection)
  306. if err2 != nil {
  307. err = err2
  308. }
  309. r.closed = true
  310. return err
  311. }
  312. // SetDeadline sets the deadlines associated with the connection.
  313. func (r *Response) SetDeadline(t time.Time) error {
  314. return r.conn.SetDeadline(t)
  315. }