In the previous article, we discussed RFC 959, which defines how an FTP server should work. We also walked through some of the commands that are used in this protocol. In this article, we will be creating an example FTP server in Delphi.
The Implementation of an FTP Server - The Code (Page 2 of 6 )
Now that the GUI is done, let's move on to the code. Most of the procedures below give you a clue as to what the code is all about. I have commented most of the code so that it you can easily work out what is going on in a particular procedure.
The setslashes function replaces double backslashes with single backslashes and also replaces a single frontslash with a backslash. This is to make sure that any pathnames that are sent by the client FTP application are processed in the correct order. For example if the user supplies a pathname like "c:afilename" then this function will correct it to "c:afilename," which is the correct way to handle pathnames.
function setSlashes(APath:String):String;
var
slash:string;
begin
slash := StringReplace(APath, '/', '', [rfReplaceAll]);
slash := StringReplace(slash, '', '', [rfReplaceAll]);
Result := slash;
end;
The event below gets fired when a client FTP application connects to the server. You can use this event to track what a particular client is doing. For example you can get the IP address from which the client connected and the time that the client connected. The event is entirely optional.
procedure TForm1.IdFTPServer1Connect(AContext: TIdContext);
begin
//Here you could take the client IP address, time that a particular
//client logged in etc, for tracking purposes
end;
The Vdirectory string contains the directory to which you need to change. The directory name is sent by the client FTP application.:
procedure TForm1.IdFTPServer1ChangeDirectory(ASender: TIdFTPServerContext; var VDirectory: String); begin ASender.CurrentDir:= VDirectory; end;