tags:

views:

351

answers:

3

I'm working on a simple ftp server in c. I don't know when ftp server accepts passive data connection from client. To my understanding here is how passive ftp works:

  1. client sends "PASV" command to server
  2. server creates and binds a socket, and listens on a random port.
  3. server uses getsockname to get random port
  4. assemble passive reply message in format: 227 Entering Passive Mode(a1,a2,a3,a4,a5,a6). Note: server ip is a1.a2.a3.a4 and port number is: a5 * 256 + a6.

my question is: when does ftp server accepts the connection to said random port? should server accept data connection after sending reply? or should ftp server accept connection right before data connection is required, i.e. when client is requesting a file?

I have RFC959. is there any other useful ftp resource out there? google is not particularly helpful.

thanks in advance

+1  A: 
Havenard
+4  A: 

I would have the server start accepting connections on that port (by calling listen()) before sending the 227 reply. If you wait until after sending the 227, the client may try to connect before you're accepting connections, and get a "connection refused" error.

After calling listen() which starts the TCP system listening, you can call accept() whenever you're ready to start accepting connections. When to call that is an application-level decision (but obviously once the client sends a data transfer command, it will want to connect). Connections from the client will wait in an accept queue until the server actually calls accept(), which removes them from the accept queue.

Greg Hewgill
is this what you meant:1. client sends "pasv"2. server sends reply with ip and port and start listening3. client send "get filename"4. server calls accept() and send the filelet me know whether I understand it correctly
Quincy
That's correct. As long as you call `listen()` before sending the 227 reply back, you should be fine with that. You can test this by delaying for a few seconds after receiving the GET command, just to make sure that the client doesn't abort before you have a chance to `accept()`.
Greg Hewgill
A: 

IMHO, the best resource on implementing FTP is http://cr.yp.to/ftp.html

There are also more recent FTP RFCs that you might find useful:

James Healy