using System.Net.Cache;
using System.Security.Cryptography.X509Certificates;
using System.Net;
-
+using System.Net.Security;
+using System.Security.Authentication;
namespace System.Net
{
Uri requestUri;
string file_name; // By now, used for upload
ServicePoint servicePoint;
- Socket dataSocket;
- NetworkStream controlStream;
+ Stream dataStream;
+ Stream controlStream;
StreamReader controlReader;
NetworkCredential credentials;
IPHostEntry hostEntry;
}
}
+ [MonoTODO ("We don't support KeepAlive = true")]
public bool KeepAlive {
get {
return keepAlive;
}
set {
CheckRequestStarted ();
- keepAlive = value;
+ //keepAlive = value;
}
}
if (!InFinalState ()) {
State = RequestState.Aborted;
- ftpResponse = new FtpWebResponse (requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
+ ftpResponse = new FtpWebResponse (this, requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
}
}
}
void ProcessRequest () {
if (State == RequestState.Scheduled) {
- ftpResponse = new FtpWebResponse (requestUri, method, keepAlive);
+ ftpResponse = new FtpWebResponse (this, requestUri, method, keepAlive);
try {
ProcessMethod ();
{
string result;
string local_path = Uri.UnescapeDataString (uri.LocalPath);
- if (initial_path == null) {
+ if (initial_path == null || initial_path == "/") {
result = local_path;
} else {
if (local_path [0] == '/')
local_path = local_path.Substring (1);
- Uri initial = new Uri (initial_path);
+
+ Uri initial = new Uri ("ftp://dummy-host" + initial_path);
result = new Uri (initial, local_path).LocalPath;
}
ResolveHost ();
OpenControlConnection ();
+ CWDAndSetFileName (requestUri);
+ SetType ();
switch (method) {
// Open data connection and receive data
case WebRequestMethods.Ftp.DownloadFile:
- CWDAndSetFileName (requestUri);
- SetType ();
- DownloadData ();
- break;
case WebRequestMethods.Ftp.ListDirectory:
case WebRequestMethods.Ftp.ListDirectoryDetails:
- SetType ();
DownloadData ();
break;
// Open data connection and send data
case WebRequestMethods.Ftp.AppendFile:
case WebRequestMethods.Ftp.UploadFile:
case WebRequestMethods.Ftp.UploadFileWithUniqueName:
- CWDAndSetFileName (requestUri);
- SetType ();
UploadData ();
break;
// Get info from control connection
}
private void CloseControlConnection () {
- SendCommand (QuitCommand);
- controlStream.Close ();
+ if (controlStream != null) {
+ SendCommand (QuitCommand);
+ controlStream.Close ();
+ controlStream = null;
+ }
}
private void CloseDataConnection () {
- if(dataSocket != null)
- dataSocket.Close ();
+ if(dataStream != null) {
+ dataStream.Close ();
+ dataStream = null;
+ }
}
private void CloseConnection () {
FtpStatus status;
if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
- method = ChangeDir;
+ method = "PWD";
if (method == WebRequestMethods.Ftp.Rename)
method = RenameFromCommand;
- status = SendCommand (method, requestUri.LocalPath);
+ status = SendCommand (method, file_name);
- ftpResponse.Stream = new EmptyStream ();
+ ftpResponse.Stream = Stream.Null;
string desc = status.StatusDescription;
throw CreateExceptionFromResponse (status);
break;
case WebRequestMethods.Ftp.DeleteFile:
- if (status.StatusCode != FtpStatusCode.FileActionOK)
+ if (status.StatusCode != FtpStatusCode.FileActionOK) {
throw CreateExceptionFromResponse (status);
+ }
break;
}
OpenDataConnection ();
State = RequestState.TransferInProgress;
- requestStream = new FtpDataStream (this, dataSocket, false);
+ requestStream = new FtpDataStream (this, dataStream, false);
asyncResult.Stream = requestStream;
}
{
State = RequestState.OpeningData;
- // Handle content offset
- if (offset > 0) {
- FtpStatus status = SendCommand (RestCommand, offset.ToString ());
-
- if (status.StatusCode != FtpStatusCode.FileCommandPending)
- throw CreateExceptionFromResponse (status);
- }
-
OpenDataConnection ();
State = RequestState.TransferInProgress;
- ftpResponse.Stream = new FtpDataStream (this, dataSocket, true);
+ ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
}
void CheckRequestStarted ()
void OpenControlConnection ()
{
+ Exception exception = null;
Socket sock = null;
foreach (IPAddress address in hostEntry.AddressList) {
sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect (remote);
localEndPoint = (IPEndPoint) sock.LocalEndPoint;
break;
- } catch (SocketException) {
+ } catch (SocketException exc) {
+ exception = exc;
sock.Close ();
sock = null;
}
// Couldn't connect to any address
if (sock == null)
- throw new WebException ("Unable to connect to remote server", null,
+ throw new WebException ("Unable to connect to remote server", exception,
WebExceptionStatus.UnknownError, ftpResponse);
controlStream = new NetworkStream (sock);
WebExceptionStatus.UnknownError, null);
string msg = status.StatusDescription.Substring (4);
- if (msg [0] == '"')
- msg = msg.Substring (1, msg.Length - 2);
+ if (msg [0] == '"') {
+ int next_quote = msg.IndexOf ('\"', 1);
+ if (next_quote == -1)
+ throw new WebException ("Error getting current directory: PWD -> " + status.StatusDescription, null,
+ WebExceptionStatus.UnknownError, null);
+
+ msg = msg.Substring (1, next_quote - 1);
+ }
if (!msg.EndsWith ("/"))
msg += "/";
Exception CreateExceptionFromResponse (FtpStatus status)
{
- FtpWebResponse ftpResponse = new FtpWebResponse (requestUri, method, status);
+ FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
WebException exc = new WebException ("Server returned an error: " + status.StatusDescription,
null, WebExceptionStatus.ProtocolError, ftpResponse);
CloseConnection ();
}
+ internal void OperationCompleted ()
+ {
+ if(!keepAlive)
+ CloseConnection ();
+ }
+
void SetCompleteWithError (Exception exc)
{
if (asyncResult != null) {
}
IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
- string ipString = ep.Address.ToString ().Replace (".", ",");
+ string ipString = ep.Address.ToString ().Replace ('.', ',');
int h1 = ep.Port >> 8; // ep.Port / 256
int h2 = ep.Port % 256;
Socket s = InitDataConnection ();
- if(method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
+ // Handle content offset
+ if (offset > 0) {
+ status = SendCommand (RestCommand, offset.ToString ());
+ if (status.StatusCode != FtpStatusCode.FileCommandPending)
+ throw CreateExceptionFromResponse (status);
+ }
+
+ if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
+ method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
status = SendCommand (method, file_name);
} else {
status = SendCommand (method);
throw CreateExceptionFromResponse (status);
if (usePassive) {
- dataSocket = s;
+ dataStream = new NetworkStream (s, false);
+ if (EnableSsl)
+ ChangeToSSLSocket (ref dataStream);
}
else {
}
s.Close ();
- dataSocket = incoming;
- }
-
- if (EnableSsl) {
- InitiateSecureConnection (ref controlStream);
- controlReader = new StreamReader (controlStream, Encoding.ASCII);
+ dataStream = new NetworkStream (incoming, false);
+ if (EnableSsl)
+ ChangeToSSLSocket (ref dataStream);
}
ftpResponse.UpdateStatus (status);
if (EnableSsl) {
InitiateSecureConnection (ref controlStream);
controlReader = new StreamReader (controlStream, Encoding.ASCII);
+ status = SendCommand ("PBSZ", "0");
+ int st = (int) status.StatusCode;
+ if (st < 200 || st >= 300)
+ throw CreateExceptionFromResponse (status);
+ // TODO: what if "PROT P" is denied by the server? What does MS do?
+ status = SendCommand ("PROT", "P");
+ st = (int) status.StatusCode;
+ if (st < 200 || st >= 300)
+ throw CreateExceptionFromResponse (status);
+
+ status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
}
if (status.StatusCode != FtpStatusCode.SendUserCommand)
if (!Int32.TryParse (response.Substring (0, 3), out code))
return ServiceNotAvailable ();
- if (response [3] == '-'){
+ if (response.Length > 3 && response [3] == '-'){
string line = null;
string find = code.ToString() + ' ';
while (true){
}
}
- private void InitiateSecureConnection (ref NetworkStream stream) {
+ private void InitiateSecureConnection (ref Stream stream) {
FtpStatus status = SendCommand (AuthCommand, "TLS");
-
- if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession) {
+ if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
throw CreateExceptionFromResponse (status);
- }
ChangeToSSLSocket (ref stream);
}
- internal static bool ChangeToSSLSocket (ref NetworkStream stream) {
+#if SECURITY_DEP
+ RemoteCertificateValidationCallback callback = delegate (object sender,
+ X509Certificate certificate,
+ X509Chain chain,
+ SslPolicyErrors sslPolicyErrors) {
+ // honor any exciting callback defined on ServicePointManager
+ if (ServicePointManager.ServerCertificateValidationCallback != null)
+ return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
+ // otherwise provide our own
+ if (sslPolicyErrors != SslPolicyErrors.None)
+ throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
+ return true;
+ };
+#endif
+
+ internal bool ChangeToSSLSocket (ref Stream stream) {
#if TARGET_JVM
stream.ChangeToSSLSocket ();
return true;
+#elif SECURITY_DEP
+ SslStream sslStream = new SslStream (stream, true, callback, null);
+ //sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
+ //TODO: client certificates
+ sslStream.AuthenticateAsClient (requestUri.Host, null, SslProtocols.Default, false);
+ stream = sslStream;
+ return true;
#else
throw new NotImplementedException ();
#endif
if (InFinalState ())
throw new InvalidOperationException ("Cannot change final state");
}
-
- class EmptyStream : MemoryStream
- {
- internal EmptyStream ()
- : base (new byte [0], false) {
- }
- }
}
}