/// <summary> /// 判断ftp上的文件目录是否存在 /// </summary> /// <param name="path"></param> /// <returns></returns> public bool RemoteFtpDirExists(string path) { //path = path; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(this._UserNm, this._Pwd); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse resFtp = null; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode;//OpeningData resFtp.Close(); return(true); } catch { if (resFtp != null) { resFtp.Close(); } return(false); } }
/// <summary> /// Upload a file to the server /// </summary> /// <param name="uri">The uri</param> /// <param name="username">The username to log into the ftp server</param> /// <param name="password">The password to log into the ftp server</param> /// <param name="filePath">The path for the file to upload</param> /// <param name="remoteName">The name of the file in the server</param> /// <returns>The FtpStatusCode</returns> public static FtpStatusCode UploadFile(Uri uri, string username, string password, string filePath, string remoteName) { FtpWebRequest ftp = Connect(new Uri(uri.AbsoluteUri + @"/" + remoteName), username, password); ftp.Method = WebRequestMethods.Ftp.UploadFile; // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(filePath); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); ftp.ContentLength = fileContents.Length; Stream requestStream = ftp.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); FtpStatusCode code = response.StatusCode; response.Close(); return(code); }
internal FtpWebResponse(Uri uri, string method, FtpStatusCode statusCode, string statusDescription) { this.uri = uri; this.method = method; this.statusCode = statusCode; this.statusDescription = statusDescription; }
/// <summary> /// 判断ftp上的文件目录是否存在 /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool RemoteFtpDirExists(string path) { path = FTPCONSTR + path; FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse resFtp = null; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode;//OpeningData resFtp.Close(); return(true); } catch { if (resFtp != null) { resFtp.Close(); } return(false); } }
public static TryDeleteFtpFolder DeleteFtpFolder(string server, string login, string password, string ftpFolder) { try { if (!server.Contains(FTP_PREFIX)) { server = $"{FTP_PREFIX}{server}"; } string path = Path.Combine(server, ftpFolder).Replace("\\", "/"); WebRequest request = WebRequest.Create(path); request.Method = WebRequestMethods.Ftp.RemoveDirectory; request.Credentials = new NetworkCredential(login, password); var resp = (FtpWebResponse)request.GetResponse(); resp.Close(); return(new TryDeleteFtpFolder()); } catch (WebException ex) { FtpWebResponse ftpWebResponse = (FtpWebResponse)ex.Response; FtpStatusCode ftpStatusCode = ftpWebResponse.StatusCode; ftpWebResponse.Close(); if (ftpStatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { return(new TryDeleteFtpFolder()); } return(new TryDeleteFtpFolder(false, ex.ToString())); } }
/// <summary> /// 获取当前目录下所有目录名和文件名 /// </summary> /// <param name="resultArray">包含目录名和文件名的结果</param> /// <returns>获取结果状态描述</returns> public string GetListDirectory(out string[] resultArray) { CreateServer(); _ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; List <string> resultList = new List <string>(); string resultString = string.Empty; using (FtpWebResponse response = (FtpWebResponse)_ftpRequest.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream)) { string lineString = sr.ReadLine(); while (lineString != null) { resultList.Add(lineString); lineString = sr.ReadLine(); } } } resultString = response.StatusDescription; CurrentStatusCode = response.StatusCode; } resultArray = resultList.ToArray(); return(resultString); }
/// <summary> /// 判断ftp上的文件目录是否存在 /// </summary> /// <param name="path"></param> /// <returns></returns> public bool RemoteFtpDirExists(string path) { path = _ftpconstr + path; FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(path)); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(_ftpusername, _ftppassword); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse resFtp = null; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode; Console.WriteLine(code); return(true); } catch (Exception exception) { Console.WriteLine("因{0},无法检测是否存在", exception.Message); return(false); } finally { resFtp?.Close(); } }
public static TryCheckFtpFileExists CheckFtpFileExists(string server, string login, string password, string ftpFolder, string fileName) { try { if (!server.Contains(FTP_PREFIX)) { server = $"{FTP_PREFIX}{server}"; } string ftpFilePath = Path.Combine(server, ftpFolder, fileName); ftpFilePath = ftpFilePath.Replace("\\", "/"); var ftpWebRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath); ftpWebRequest.Credentials = new NetworkCredential(login, password); ftpWebRequest.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); ftpWebResponse.Close(); return(new TryCheckFtpFileExists()); } catch (WebException ex) { FtpWebResponse ftpWebResponse = (FtpWebResponse)ex.Response; FtpStatusCode ftpStatusCode = ftpWebResponse.StatusCode; ftpWebResponse.Close(); if (ftpStatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { return(new TryCheckFtpFileExists(true, "", ftpStatusCode, false)); } return(new TryCheckFtpFileExists(false, ex.ToString(), ftpStatusCode, false)); } }
/// <summary> /// 文件下载 /// </summary> /// <remarks> /// 如果需要下载的文件不在当前目录,请先执行目录切换命令。 /// </remarks> /// <param name="saveFullPath">文件下载后的保存全路径</param> /// <param name="downlaodFileName">当前目录下需要下载的文件名称</param> /// <returns>文件下载结果状态描述</returns> public string Download(string saveFullPath, string downlaodFileName) { string tempCurrentURI = _currentURI; _currentURI = $"{_currentURI}/{downlaodFileName}"; CreateServer(); _ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; string resultString = string.Empty; using (FtpWebResponse response = (FtpWebResponse)_ftpRequest.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(saveFullPath, FileMode.Create, FileAccess.Write)) { int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount = responseStream.Read(buffer, 0, bufferSize); while (readCount > 0) { fs.Write(buffer, 0, bufferSize); readCount = responseStream.Read(buffer, 0, bufferSize); } } } resultString = response.StatusDescription; CurrentStatusCode = response.StatusCode; } _currentURI = tempCurrentURI; return(resultString); }
public FtpStatusCode UploadFile(byte[] fileData, string destinationPath) { destinationPath = ClearnPath(destinationPath); string folder = GetFolderPath(destinationPath); if (!string.IsNullOrEmpty(folder)) { if (!IsExistFolder(folder)) { CreateFolder(folder); } } string remoteUri = Path.Combine(ftpRootPath, destinationPath); var request = WebRequest.Create(remoteUri); request.Proxy = ftpProxy; request.Credentials = ftpCredential; request.Method = WebRequestMethods.Ftp.UploadFile; request.Timeout = -1; request.ContentLength = fileData.Length; var requestStream = request.GetRequestStream(); requestStream.Write(fileData, 0, fileData.Length); requestStream.Close(); var response = (FtpWebResponse)request.GetResponse(); FtpStatusCode status = response.StatusCode; response.Close(); return(status); }
/// <summary> /// 按行读取 /// </summary> /// <param name="response"></param> /// <param name="statusCode"></param> /// <param name="isOk"></param> /// <returns></returns> private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode, out bool isOk) { List <string> lstAccpet = new List <string>(); int i = 0; while (true) { if (response.StatusCode == statusCode) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { lstAccpet.Add(line); line = sr.ReadLine(); } } isOk = true; break; } i++; if (i > 10) { isOk = false; break; } Thread.Sleep(200); } response.Close(); return(lstAccpet.ToArray()); }
public static string GetWebStatusCodeString(FtpStatusCode statusCode, string statusDescription) { string webStatusCode = "(" + ((int)statusCode).ToString(NumberFormatInfo.InvariantInfo) + ")"; string statusMessage = null; // // Now combine the label with the base enum key and look up the status msg. // try { // // convert the HttpStatusCode to its label and look it up. // statusMessage = SR.GetString("net_ftpstatuscode_" + statusCode.ToString(), null); } catch { } if (statusMessage != null && statusMessage.Length > 0) { webStatusCode += " " + statusMessage; } else { // // Otherwise try to map the base status. // if (statusDescription != null && statusDescription.Length > 0) { webStatusCode += " " + statusDescription; } } return(webStatusCode); }
public FtpStatusCode UploadFile(string remotePath, string localPath, bool useBinary) { Uri uri = CreateUri(remotePath); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = useBinary; request.Credentials = CreateNetworkCredentials(); request.EnableSsl = UseSsl; FileStream stream = File.OpenRead(localPath); Stream requestStream = request.GetRequestStream(); stream.CopyTo(requestStream); requestStream.Close(); ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return(true); }; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); FtpStatusCode statusCode = response.StatusCode; response.Close(); stream.Close(); return(statusCode); }
/// <summary> /// 从ftp服务器上获得文件列表 /// </summary> /// <param name="RequedstPath">服务器下的相对路径</param> /// <returns></returns> public bool GetFile(string ftpServerIP, string ftpUserID, string ftpPassword, string fileDate) { FtpWebRequest reqFTP; string uri = "ftp://" + ftpServerIP + "/" + fileDate; //目标路径 path为服务器地址 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); FtpWebResponse response = null; try { // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; response = (FtpWebResponse)reqFTP.GetResponse(); FtpStatusCode code = response.StatusCode;//OpeningData response.Close(); return(true); } catch { if (response != null) { response.Close(); } return(false); } }
internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, FtpStatusCode statusCode, string statusDescription) { this.request = request; this.uri = uri; this.method = method; this.statusCode = statusCode; this.statusDescription = statusDescription; }
internal FtpWebResponse(FtpWebRequest request, System.Uri uri, string method, FtpStatusCode statusCode, string statusDescription) { this.request = request; this.uri = uri; this.method = method; this.statusCode = statusCode; this.statusDescription = statusDescription; }
public static UploadResult CreateFtpUploadResult( FtpStatusCode statusCode = FtpStatusCode.FileActionOK, string statusDescription = "DefaultStatusDescription") { return(new UploadResult( statusCode, statusDescription)); }
private FtpStatusCode beginUploadFile1(ref ftpUDParams ftpParam) { FtpStatusCode ftpStatusCode = FtpStatusCode.Undefined; string path = ftpParam.path; string filename = ftpParam.filename; FtpWebResponse ftpWebResponse = (FtpWebResponse)null; Stream stream = (Stream)null; FileStream fileStream = (FileStream)null; string requestUriString = string.Format("ftp://{0}/{1}/{2}", (object)this._FtpServerIP, (object)path, (object)filename.Substring(filename.LastIndexOf("\\") + 1)); try { FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUriString); ftpWebRequest.KeepAlive = false; ftpWebRequest.Credentials = (ICredentials) new NetworkCredential(this._UserName, this._Password); ftpWebRequest.Method = "STOR"; ftpWebRequest.UseBinary = true; stream = ftpWebRequest.GetRequestStream(); fileStream = new FileStream(filename, FileMode.Open); byte[] buffer = new byte[1024]; while (true) { int count = fileStream.Read(buffer, 0, buffer.Length); if (count != 0) { stream.Write(buffer, 0, count); } else { break; } } this.ftpUploadFileSuccess.BeginInvoke(filename, (AsyncCallback)null, (object)null); stream.Close(); ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); ftpStatusCode = ftpWebResponse.StatusCode; } catch (Exception ex) { this.ftpUploadFileFailed.BeginInvoke(filename, ex.Message, (AsyncCallback)null, (object)null); } finally { if (ftpWebResponse != null) { ftpWebResponse.Close(); } if (fileStream != null) { fileStream.Close(); } if (stream != null) { stream.Close(); } } return(ftpStatusCode); }
/// <summary> /// 创建 FTP 服务 /// </summary> private void CreateServer() { _ftpRequest = (FtpWebRequest)WebRequest.Create(_currentURI); _ftpRequest.Credentials = new NetworkCredential(_option.UserName, _option.Password); _ftpRequest.EnableSsl = _option.UseSSL; _ftpRequest.KeepAlive = _option.IsKeepAlive; CurrentStatusCode = FtpStatusCode.Undefined; }
private Boolean CheckForUrl(String identifier) { Boolean result = false; WebRequest request; WebResponse response = null; try { request = WebRequest.Create(identifier); response = request.GetResponse(); if (response.GetType() == typeof(HttpWebResponse)) { HttpStatusCode status = ((HttpWebResponse)response).StatusCode; if ((int)status >= 200 && (int)status <= 299) { return(true); } } else if (response.GetType() == typeof(FtpWebResponse)) { FtpStatusCode status = ((FtpWebResponse)response).StatusCode; if ((int)status <= 399) { return(true); } } else { // No exception, assume good. return(true); } } catch (Exception e) { //TODO: log exceptions } finally { if (response != null) { try { response.Close(); } catch (NotSupportedException e) { // TODO: Log or ignore? } } } return(result); }
/// <summary> /// Constructor for the ftp process event argument. /// </summary> /// <param name="ftpServer">The ftp server connecting to.</param> /// <param name="ftpProcess">The original command that was to be processed.</param> /// <param name="fileInfo">The original upload target file, download destination file or /// the list of files within a directory.</param> /// <param name="ftpStatusCode">The current ftp status code from the server.</param> /// <param name="ftpStatusDescription">The current ftp status description from the server.</param> /// <param name="transferDirection">The current ftp transfer direction.</param> public FTPSocketArgs(string ftpServer, string ftpProcess, string fileInfo, FtpStatusCode ftpStatusCode, string ftpStatusDescription, Nequeo.Net.Ftp.SocketTransferDirection transferDirection) { this.fileInfo = fileInfo; this.ftpServer = ftpServer; this.ftpProcess = ftpProcess; this.ftpStatusCode = ftpStatusCode; this.transferDirection = transferDirection; this.ftpStatusDescription = ftpStatusDescription; }
private static async Task <bool> TryGetResponseAsync(FtpWebRequest request, FtpStatusCode expectedResult) { for (int attempts = 0; attempts < 5; attempts++) { var response = (FtpWebResponse)await request.GetResponseAsync(); if (response.StatusCode == expectedResult) { return(true); } } return(false); }
protected override void ClearState() { this.m_ContentLength = -1L; this.m_LastModified = DateTime.MinValue; this.m_ResponseUri = null; this.m_DataHandshakeStarted = false; this.StatusCode = FtpStatusCode.Undefined; this.StatusLine = null; this.m_DataSocket = null; this.m_PassiveEndPoint = null; this.m_TlsStream = null; base.ClearState(); }
/// <summary> /// Delete a file from the server /// </summary> /// <param name="uri">The uri of the file to delete</param> /// <param name="username">The username to log into the ftp server</param> /// <param name="password">The password to log into the ftp server</param> /// <returns>The FtpStatusCode</returns> public static FtpStatusCode DeleteFile(Uri uri, string username, string password) { FtpWebRequest ftp = Connect(uri, username, password); ftp.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); FtpStatusCode code = response.StatusCode; response.Close(); return(code); }
protected override void ClearState() { _contentLength = -1; _lastModified = DateTime.MinValue; _responseUri = null; _dataHandshakeStarted = false; StatusCode = FtpStatusCode.Undefined; StatusLine = null; _dataSocket = null; _passiveEndPoint = null; _tlsStream = null; base.ClearState(); }
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { GlobalLog.Print("FtpWebResponse#" + ValidationHelper.HashString(this) + "::.ctor(" + contentLength.ToString() + ","+ statusLine+ ")"); m_ResponseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } m_ContentLength = contentLength; m_ResponseUri = responseUri; m_StatusCode = statusCode; m_StatusLine = statusLine; m_LastModified = lastModified; m_BannerMessage = bannerMessage; m_WelcomeMessage = welcomeMessage; m_ExitMessage = exitMessage; }
internal FtpWebResponse(Stream?responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string?statusLine, DateTime lastModified, string?bannerMessage, string?welcomeMessage, string?exitMessage) { _responseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } _contentLength = contentLength; _responseUri = responseUri; _statusCode = statusCode; _statusLine = statusLine; _lastModified = lastModified; _bannerMessage = bannerMessage; _welcomeMessage = welcomeMessage; _exitMessage = exitMessage; }
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { this.m_ResponseStream = responseStream; if ((responseStream == null) && (contentLength < 0L)) { contentLength = 0L; } this.m_ContentLength = contentLength; this.m_ResponseUri = responseUri; this.m_StatusCode = statusCode; this.m_StatusLine = statusLine; this.m_LastModified = lastModified; this.m_BannerMessage = bannerMessage; this.m_WelcomeMessage = welcomeMessage; this.m_ExitMessage = exitMessage; }
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { GlobalLog.Print("FtpWebResponse#" + ValidationHelper.HashString(this) + "::.ctor(" + contentLength.ToString() + "," + statusLine + ")"); m_ResponseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } m_ContentLength = contentLength; m_ResponseUri = responseUri; m_StatusCode = statusCode; m_StatusLine = statusLine; m_LastModified = lastModified; m_BannerMessage = bannerMessage; m_WelcomeMessage = welcomeMessage; m_ExitMessage = exitMessage; }
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine); _responseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } _contentLength = contentLength; _responseUri = responseUri; _statusCode = statusCode; _statusLine = statusLine; _lastModified = lastModified; _bannerMessage = bannerMessage; _welcomeMessage = welcomeMessage; _exitMessage = exitMessage; }
/// <summary> /// 删除远程文件 /// </summary> /// <param name="FolderName">目录名</param> /// <param name="FileName">文件名</param> /// <returns>执行结果,FTP返回码</returns> public FtpStatusCode DeleteFile(string FolderName, string FileName) { try { if (FolderName == null || FileName == null) { ErrMsg = "REF unvalid"; return(FtpStatusCode.Undefined); } else if (FolderName.Trim() == "" || FileName.Trim() == "") { ErrMsg = "REF unvalid"; return(FtpStatusCode.Undefined); } else { if (this.Url.Trim() != "") { string str = Url + "/" + FolderName.Trim(); str = str + "/" + FileName; Uri uri = new Uri(str); FtpWebRequest listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.DeleteFile; listRequest.Timeout = TimeOut; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); FtpStatusCode res = listResponse.StatusCode; listResponse.Close(); listResponse = null; listRequest = null; return(res); } return(FtpStatusCode.Undefined); } } catch (Exception ex) { ErrMsg = ex.Message; return(FtpStatusCode.Undefined); } }
int Upload(string fullPath) { string[] split = fullPath.Split('/'); string filename = split[split.Length - 1]; string responseDescription = null; FtpStatusCode responseCode = 0; try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpHost + "/" + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); byte[] fileContents = File.ReadAllBytes(fullPath); request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { responseDescription = response.StatusDescription; responseCode = response.StatusCode; //Debug.Log(responseCode.ToString()); //Debug.Log(responseDescription); } } catch (Exception ex) { Debug.Log(ex.Message); return(0); } if (responseCode == FtpStatusCode.ClosingControl || responseCode == FtpStatusCode.ClosingData) { return(1); } return(0); }
public static bool FtpDirExists(string dirPath) { FtpWebRequest reqFtp = FTPUtils.GetRequest(dirPath, WebRequestMethods.Ftp.ListDirectory); FtpWebResponse resFtp = null; try { resFtp = (FtpWebResponse)reqFtp.GetResponse(); FtpStatusCode code = resFtp.StatusCode;//OpeningData resFtp.Close(); return(true); } catch { if (resFtp != null) { resFtp.Close(); } return(false); } }
public static string GetWebStatusCodeString(FtpStatusCode statusCode, string statusDescription) { string str = "(" + ((int) statusCode).ToString(NumberFormatInfo.InvariantInfo) + ")"; string str2 = null; try { str2 = SR.GetString("net_ftpstatuscode_" + statusCode.ToString(), (object[]) null); } catch { } if ((str2 != null) && (str2.Length > 0)) { return (str + " " + str2); } if ((statusDescription != null) && (statusDescription.Length > 0)) { str = str + " " + statusDescription; } return str; }
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { if (GlobalLog.IsEnabled) { GlobalLog.Print("FtpWebResponse#" + LoggingHash.HashString(this) + "::.ctor(" + contentLength.ToString() + "," + statusLine + ")"); } _responseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } _contentLength = contentLength; _responseUri = responseUri; _statusCode = statusCode; _statusLine = statusLine; _lastModified = lastModified; _bannerMessage = bannerMessage; _welcomeMessage = welcomeMessage; _exitMessage = exitMessage; }
/// <summary> /// Set the "resultproperty" if specified /// </summary> /// <param name="status"></param> private void SetResultProperty(FtpStatusCode status) { if (!string.IsNullOrEmpty(ResultProperty)) { string statusString = ((int)status).ToString(); if (Properties.Contains(ResultProperty)) { Properties[ResultProperty] = statusString; } else { Properties.Add(ResultProperty, statusString); } } }
// This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the setting up of a data socket/connection, and of saving off the server responses. protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}"); // null response is not expected if (response == null) return PipelineInstruction.Abort; FtpStatusCode status = (FtpStatusCode)response.Status; // // Update global "current status" for FtpWebRequest // if (status != FtpStatusCode.ClosingControl) { // A 221 status won't be reflected on the user FTP response // Anything else will (by design?) StatusCode = status; StatusLine = response.StatusDescription; } // If the status code is outside the range defined in RFC (1xx to 5xx) throw if (response.InvalidStatusCode) throw new WebException(SR.net_InvalidStatusCode, WebExceptionStatus.ProtocolError); // Update the banner message if any, this is a little hack because the "entry" param is null if (_index == -1) { if (status == FtpStatusCode.SendUserCommand) { _bannerMessage = new StringBuilder(); _bannerMessage.Append(StatusLine); return PipelineInstruction.Advance; } else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable) { return PipelineInstruction.Reread; } else throw GenerateException(status, response.StatusDescription, null); } // // Check for the result of our attempt to use UTF8 // if (entry.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { Encoding = Encoding.UTF8; } else { Encoding = Encoding.Default; } return PipelineInstruction.Advance; } // If we are already logged in and the server returns 530 then // the server does not support re-issuing a USER command, // tear down the connection and start all over again if (entry.Command.IndexOf("USER") != -1) { // The server may not require a password for this user, so bypass the password command if (status == FtpStatusCode.LoggedInProceed) { _loginState = FtpLoginState.LoggedIn; _index++; } } // // Throw on an error with possible recovery option // if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { MarkAsRecoverableFailure(); } throw GenerateException(status, response.StatusDescription, null); } if (_loginState != FtpLoginState.LoggedIn && entry.Command.IndexOf("PASS") != -1) { // Note the fact that we logged in if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed) _loginState = FtpLoginState.LoggedIn; else throw GenerateException(status, response.StatusDescription, null); } // // Parse special cases // if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); if (!isSocketReady) return result; // otheriwse we have a stream to create } // // This is part of the above case and it's all about giving data stream back // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { if (_dataSocket == null) { return PipelineInstruction.Abort; } if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream)) { _abortReason = SR.Format(SR.net_ftp_invalid_status_response, status, entry.Command); return PipelineInstruction.Abort; } // Parse out the Content length, if we can TryUpdateContentLength(response.StatusDescription); // Parse out the file name, when it is returned and use it for our ResponseUri FtpWebRequest request = (FtpWebRequest)_request; if (request.MethodInfo.ShouldParseForResponseUri) { TryUpdateResponseUri(response.StatusDescription, request); } return QueueOrCreateFtpDataStream(ref stream); } // // Parse responses by status code exclusivelly // // Update welcome message if (status == FtpStatusCode.LoggedInProceed) { _welcomeMessage.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { _exitMessage.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } // OR set us up for SSL/TLS, after this we'll be writing securely else if (status == FtpStatusCode.ServerWantsSecureSession) { // If NetworkStream is a TlsStream, then this must be in the async callback // from completing the SSL handshake. // So just let the pipeline continue. if (!(NetworkStream is TlsStream)) { FtpWebRequest request = (FtpWebRequest)_request; TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates); if (_isAsync) { tlsStream.BeginAuthenticateAsClient(ar => { try { tlsStream.EndAuthenticateAsClient(ar); NetworkStream = tlsStream; this.ContinueCommandPipeline(); } catch (Exception e) { this.CloseSocket(); this.InvokeRequestCallback(e); } }, null); return PipelineInstruction.Pause; } else { tlsStream.AuthenticateAsClient(); NetworkStream = tlsStream; } } } // OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands else if (status == FtpStatusCode.FileStatus) { FtpWebRequest request = (FtpWebRequest)_request; if (entry.Command.StartsWith("SIZE ")) { _contentLength = GetContentLengthFrom213Response(response.StatusDescription); } else if (entry.Command.StartsWith("MDTM ")) { _lastModified = GetLastModifiedFrom213Response(response.StatusDescription); } } // OR parse out our login directory else if (status == FtpStatusCode.PathnameCreated) { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { _loginDirectory = GetLoginDirectory(response.StatusDescription); } } // Asserting we have some positive response else { // We only use CWD to reset ourselves back to the login directory. if (entry.Command.IndexOf("CWD") != -1) { _establishedServerDirectory = _requestedServerDirectory; } } // Intermediate responses require rereading if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n")) { return PipelineInstruction.Reread; } return PipelineInstruction.Advance; }
// // This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the seting up of a data socket/connection, and of saving off the server responses // protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { GlobalLog.Print("FtpControlStream#" + ValidationHelper.HashString(this) + ">" + (entry == null? "null" : entry.Command)); GlobalLog.Print("FtpControlStream#" + ValidationHelper.HashString(this) + ">" + ((response == null) ? "null" : response.StatusDescription)); // null response is not expected if (response == null) return PipelineInstruction.Abort; FtpStatusCode status = (FtpStatusCode) response.Status; // // Update global "current status" for FtpWebRequest // if (status != FtpStatusCode.ClosingControl) { // A 221 status won't be reflected on the user FTP response // Anything else will (by design?) StatusCode = status; StatusLine = response.StatusDescription; } // If the status code is outside the range defined in RFC (1xx to 5xx) throw if (response.InvalidStatusCode) throw new WebException(SR.GetString(SR.net_InvalidStatusCode), WebExceptionStatus.ProtocolError); // Update the banner message if any, this is a little hack because the "entry" param is null if (m_Index == -1) { if (status == FtpStatusCode.SendUserCommand) { m_BannerMessage = new StringBuilder(); m_BannerMessage.Append(StatusLine); return PipelineInstruction.Advance; } else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable) { return PipelineInstruction.Reread; } else throw GenerateException(status,response.StatusDescription, null); } // // Check for the result of our attempt to use UTF8 // Condsider: optimize this for speed (avoid string compare) as that is the only command that may fail // if (entry.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { Encoding = Encoding.UTF8; } else { Encoding = Encoding.Default; } return PipelineInstruction.Advance; } // If we are already logged in and the server returns 530 then // the server does not support re-issuing a USER command, // tear down the connection and start all over again if (entry.Command.IndexOf("USER") != -1) { // The server may not require a password for this user, so bypass the password command if (status == FtpStatusCode.LoggedInProceed) { m_LoginState = FtpLoginState.LoggedIn; m_Index++; } // The server does not like re-login // (We are logged in already but want to re-login under a different user) else if (status == FtpStatusCode.NotLoggedIn && m_LoginState != FtpLoginState.NotLoggedIn) { m_LoginState = FtpLoginState.ReloginFailed; throw ExceptionHelper.IsolatedException; } } // // Throw on an error with possible recovery option // if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { MarkAsRecoverableFailure(); } throw GenerateException(status,response.StatusDescription, null); } if (m_LoginState != FtpLoginState.LoggedIn && entry.Command.IndexOf("PASS") != -1) { // Note the fact that we logged in if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed) m_LoginState = FtpLoginState.LoggedIn; else throw GenerateException(status,response.StatusDescription, null); } // // Parse special cases // if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); if (!isSocketReady) return result; // otheriwse we have a stream to create } // // This is part of the above case and it's all about giving data stream back // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { if (m_DataSocket == null) { // a better diagnostic? return PipelineInstruction.Abort; } if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream)) { m_AbortReason = SR.GetString(SR.net_ftp_invalid_status_response, status, entry.Command); return PipelineInstruction.Abort; } // Parse out the Content length, if we can TryUpdateContentLength(response.StatusDescription); // Parse out the file name, when it is returned and use it for our ResponseUri FtpWebRequest request = (FtpWebRequest) m_Request; if (request.MethodInfo.ShouldParseForResponseUri) { TryUpdateResponseUri(response.StatusDescription, request); } return QueueOrCreateFtpDataStream(ref stream); } // // Parse responses by status code exclusivelly // //Update welcome message if (status == FtpStatusCode.LoggedInProceed) { m_WelcomeMessage.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { m_ExitMessage.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } #if !FEATURE_PAL // OR set us up for SSL/TLS, after this we'll be writing securely else if (status == FtpStatusCode.ServerWantsSecureSession) { FtpWebRequest request = (FtpWebRequest) m_Request; TlsStream tlsStream = new TlsStream(request.RequestUri.Host, NetworkStream, request.ClientCertificates, Pool.ServicePoint, request, m_Async ? request.GetWritingContext().ContextCopy : null); NetworkStream = tlsStream; } #endif // !FEATURE_PAL // OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands else if (status == FtpStatusCode.FileStatus) { FtpWebRequest request = (FtpWebRequest) m_Request; if (entry.Command.StartsWith("SIZE ")) { m_ContentLength = GetContentLengthFrom213Response(response.StatusDescription); } else if (entry.Command.StartsWith("MDTM ")) { m_LastModified = GetLastModifiedFrom213Response(response.StatusDescription); } } // OR parse out our login directory else if (status == FtpStatusCode.PathnameCreated) { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { m_LoginDirectory = GetLoginDirectory(response.StatusDescription); } } // Asserting we have some positive response else { // We only use CWD to reset ourselves back to the login directory. if (entry.Command.IndexOf("CWD") != -1) { m_EstablishedServerDirectory = m_RequestedServerDirectory; } } // Intermediate responses require rereading if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n")) { return PipelineInstruction.Reread; } return PipelineInstruction.Advance; }
private static async Task<bool> TryGetResponseAsync(FtpWebRequest request, FtpStatusCode expectedResult) { for (int attempts = 0; attempts < 5; attempts++) { var response = (FtpWebResponse)await request.GetResponseAsync(); if (response.StatusCode == expectedResult) { return true; } } return false; }
public static string GetWebStatusCodeString(FtpStatusCode statusCode, string statusDescription) { string webStatusCode = "(" + ((int)statusCode).ToString(NumberFormatInfo.InvariantInfo) + ")"; string statusMessage = null; switch (statusCode) { case FtpStatusCode.ServiceNotAvailable: statusMessage = SR.net_ftpstatuscode_ServiceNotAvailable; break; case FtpStatusCode.CantOpenData: statusMessage = SR.net_ftpstatuscode_CantOpenData; break; case FtpStatusCode.ConnectionClosed: statusMessage = SR.net_ftpstatuscode_ConnectionClosed; break; case FtpStatusCode.ActionNotTakenFileUnavailableOrBusy: statusMessage = SR.net_ftpstatuscode_ActionNotTakenFileUnavailableOrBusy; break; case FtpStatusCode.ActionAbortedLocalProcessingError: statusMessage = SR.net_ftpstatuscode_ActionAbortedLocalProcessingError; break; case FtpStatusCode.ActionNotTakenInsufficientSpace: statusMessage = SR.net_ftpstatuscode_ActionNotTakenInsufficientSpace; break; case FtpStatusCode.CommandSyntaxError: statusMessage = SR.net_ftpstatuscode_CommandSyntaxError; break; case FtpStatusCode.ArgumentSyntaxError: statusMessage = SR.net_ftpstatuscode_ArgumentSyntaxError; break; case FtpStatusCode.CommandNotImplemented: statusMessage = SR.net_ftpstatuscode_CommandNotImplemented; break; case FtpStatusCode.BadCommandSequence: statusMessage = SR.net_ftpstatuscode_BadCommandSequence; break; case FtpStatusCode.NotLoggedIn: statusMessage = SR.net_ftpstatuscode_NotLoggedIn; break; case FtpStatusCode.AccountNeeded: statusMessage = SR.net_ftpstatuscode_AccountNeeded; break; case FtpStatusCode.ActionNotTakenFileUnavailable: statusMessage = SR.net_ftpstatuscode_ActionNotTakenFileUnavailable; break; case FtpStatusCode.ActionAbortedUnknownPageType: statusMessage = SR.net_ftpstatuscode_ActionAbortedUnknownPageType; break; case FtpStatusCode.FileActionAborted: statusMessage = SR.net_ftpstatuscode_FileActionAborted; break; case FtpStatusCode.ActionNotTakenFilenameNotAllowed: statusMessage = SR.net_ftpstatuscode_ActionNotTakenFilenameNotAllowed; break; } if (statusMessage != null && statusMessage.Length > 0) { webStatusCode += " " + statusMessage; } else { // // Otherwise try to map the base status. // if (statusDescription != null && statusDescription.Length > 0) { webStatusCode += " " + statusDescription; } } return webStatusCode; }
internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage) { m_StatusCode = statusCode; m_StatusLine = statusLine; m_ExitMessage = exitMessage; }
protected override CommandStream.PipelineInstruction PipelineCallback(CommandStream.PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { if (response == null) { return CommandStream.PipelineInstruction.Abort; } FtpStatusCode status = (FtpStatusCode) response.Status; if (status != FtpStatusCode.ClosingControl) { this.StatusCode = status; this.StatusLine = response.StatusDescription; } if (response.InvalidStatusCode) { throw new WebException(SR.GetString("net_InvalidStatusCode"), WebExceptionStatus.ProtocolError); } if (base.m_Index == -1) { switch (status) { case FtpStatusCode.SendUserCommand: this.m_BannerMessage = new StringBuilder(); this.m_BannerMessage.Append(this.StatusLine); return CommandStream.PipelineInstruction.Advance; case FtpStatusCode.ServiceTemporarilyNotAvailable: return CommandStream.PipelineInstruction.Reread; } throw base.GenerateException(status, response.StatusDescription, null); } if (entry.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { base.Encoding = Encoding.UTF8; } else { base.Encoding = Encoding.Default; } return CommandStream.PipelineInstruction.Advance; } if (entry.Command.IndexOf("USER") != -1) { if (status == FtpStatusCode.LoggedInProceed) { this.m_LoginState = FtpLoginState.LoggedIn; base.m_Index++; } else if ((status == FtpStatusCode.NotLoggedIn) && (this.m_LoginState != FtpLoginState.NotLoggedIn)) { this.m_LoginState = FtpLoginState.ReloginFailed; throw ExceptionHelper.IsolatedException; } } if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { base.MarkAsRecoverableFailure(); } throw base.GenerateException(status, response.StatusDescription, null); } if ((this.m_LoginState != FtpLoginState.LoggedIn) && (entry.Command.IndexOf("PASS") != -1)) { switch (status) { case FtpStatusCode.NeedLoginAccount: case FtpStatusCode.LoggedInProceed: this.m_LoginState = FtpLoginState.LoggedIn; goto Label_017A; } throw base.GenerateException(status, response.StatusDescription, null); } Label_017A: if (entry.HasFlag(CommandStream.PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool flag; CommandStream.PipelineInstruction instruction = this.QueueOrCreateDataConection(entry, response, timeout, ref stream, out flag); if (!flag) { return instruction; } } switch (status) { case FtpStatusCode.OpeningData: case FtpStatusCode.DataAlreadyOpen: { if (this.m_DataSocket == null) { return CommandStream.PipelineInstruction.Abort; } if (!entry.HasFlag(CommandStream.PipelineEntryFlags.GiveDataStream)) { base.m_AbortReason = SR.GetString("net_ftp_invalid_status_response", new object[] { status, entry.Command }); return CommandStream.PipelineInstruction.Abort; } this.TryUpdateContentLength(response.StatusDescription); FtpWebRequest request = (FtpWebRequest) base.m_Request; if (request.MethodInfo.ShouldParseForResponseUri) { this.TryUpdateResponseUri(response.StatusDescription, request); } return this.QueueOrCreateFtpDataStream(ref stream); } case FtpStatusCode.LoggedInProceed: this.m_WelcomeMessage.Append(this.StatusLine); break; case FtpStatusCode.ClosingControl: this.m_ExitMessage.Append(response.StatusDescription); base.CloseSocket(); break; case FtpStatusCode.ServerWantsSecureSession: { FtpWebRequest initiatingRequest = (FtpWebRequest) base.m_Request; TlsStream stream2 = new TlsStream(initiatingRequest.RequestUri.Host, base.NetworkStream, initiatingRequest.ClientCertificates, base.Pool.ServicePoint, initiatingRequest, base.m_Async ? initiatingRequest.GetWritingContext().ContextCopy : null); base.NetworkStream = stream2; break; } case FtpStatusCode.FileStatus: { FtpWebRequest request1 = (FtpWebRequest) base.m_Request; if (entry.Command.StartsWith("SIZE ")) { this.m_ContentLength = this.GetContentLengthFrom213Response(response.StatusDescription); } else if (entry.Command.StartsWith("MDTM ")) { this.m_LastModified = this.GetLastModifiedFrom213Response(response.StatusDescription); } break; } default: if (status == FtpStatusCode.PathnameCreated) { if ((entry.Command == "PWD\r\n") && !entry.HasFlag(CommandStream.PipelineEntryFlags.UserCommand)) { this.m_LoginDirectory = this.GetLoginDirectory(response.StatusDescription); } } else if (entry.Command.IndexOf("CWD") != -1) { this.m_EstablishedServerDirectory = this.m_RequestedServerDirectory; } break; } if (!response.PositiveIntermediate && (base.UsingSecureStream || !(entry.Command == "AUTH TLS\r\n"))) { return CommandStream.PipelineInstruction.Advance; } return CommandStream.PipelineInstruction.Reread; }
// // This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the seting up of a data socket/connection, and of saving off the server responses // protected override PipelineInstruction PipelineCallback(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream stream) { GlobalLog.Print("FtpControlStream#" + ValidationHelper.HashString(this) + ">" + (entry == null? "null" : entry.Command)); GlobalLog.Print("FtpControlStream#" + ValidationHelper.HashString(this) + ">" + ((response == null) ? "null" : response.StatusDescription)); // null response is not expected if (response == null) return PipelineInstruction.Abort; FtpStatusCode status = (FtpStatusCode) response.Status; // // Update global "current status" for FtpWebRequest // if (status != FtpStatusCode.ClosingControl) { // A 221 status won't be reflected on the user FTP response // Anything else will (by design?) StatusCode = status; StatusLine = response.StatusDescription; } // If the status code is outside the range defined in RFC (1xx to 5xx) throw if (response.InvalidStatusCode) throw new WebException(SR.GetString(SR.net_InvalidStatusCode), WebExceptionStatus.ProtocolError); if (m_Index == -1) { if (status == FtpStatusCode.SendUserCommand) { m_BannerMessage = new StringBuilder(); m_BannerMessage.Append(StatusLine); return PipelineInstruction.Advance; } else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable) { return PipelineInstruction.Reread; } else throw GenerateException(status,response.StatusDescription, null); } // // Check for the result of our attempt to use UTF8 // Condsider: optimize this for speed (avoid string compare) as that is the only command that may fail // if (entry.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { Encoding = Encoding.UTF8; } else { Encoding = Encoding.Default; } return PipelineInstruction.Advance; } // If we are already logged in and the server returns 530 then // the server does not support re-issuing a USER command, // tear down the connection and start all over again if (entry.Command.IndexOf("USER") != -1) { // The server may not require a password for this user, so bypass the password command if (status == FtpStatusCode.LoggedInProceed) { m_LoginState = FtpLoginState.LoggedIn; m_Index++; } // The server does not like re-login // (We are logged in already but want to re-login under a different user) else if (status == FtpStatusCode.NotLoggedIn && m_LoginState != FtpLoginState.NotLoggedIn) { m_LoginState = FtpLoginState.ReloginFailed; throw ExceptionHelper.IsolatedException; } } // // Throw on an error with possibe recovery option // if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { MarkAsRecoverableFailure(); } throw GenerateException(status,response.StatusDescription, null); } if (m_LoginState != FtpLoginState.LoggedIn && entry.Command.IndexOf("PASS") != -1) { // Note the fact that we logged in if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed) m_LoginState = FtpLoginState.LoggedIn; else throw GenerateException(status,response.StatusDescription, null); } // // Parse special cases // if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); if (!isSocketReady) return result; // otheriwse we have a stream to create } // // This is part of the above case and it's all about giving data stream back // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { if (m_DataSocket == null) { // a better diagnostic? return PipelineInstruction.Abort; } if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream)) { m_AbortReason = SR.GetString(SR.net_ftp_invalid_status_response, status, entry.Command); return PipelineInstruction.Abort; } // Parse out the Content length, if we can TryUpdateContentLength(response.StatusDescription); // Parse out the file name, when it is returned and use it for our ResponseUri if (status == FtpStatusCode.OpeningData) { FtpWebRequest request = (FtpWebRequest) m_Request; if (request.MethodInfo.ShouldParseForResponseUri) { TryUpdateResponseUri(response.StatusDescription, request); } } return QueueOrCreateFtpDataStream(ref stream); } // // Parse responses by status code exclusivelly // //Update our command list if we have an alias if (status == FtpStatusCode.LoggedInProceed) { if(StatusLine.ToLower(CultureInfo.InvariantCulture).IndexOf("alias") > 0){ //find start of alias //skip first status code int i = StatusLine.IndexOf("230-",3); if(i > 0) { i+=4; //eat white space while(i<StatusLine.Length && StatusLine[i] == ' '){i++;} //not eol if (i <StatusLine.Length) { //get end of alias int j = StatusLine.IndexOf(' ',i); if(j<0) j=StatusLine.Length; m_Alias = StatusLine.Substring(i,j-i); if (!m_IsRootPath) { //update command list for (i=0;i<m_Commands.Length;i++){ if(m_Commands[i].Command.IndexOf("CWD") == 0) { string path = m_Alias+m_NewServerPath; m_Commands[i] = new PipelineEntry(FormatFtpCommand("CWD", path)); break; } } } } } } m_WelcomeMessage.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { m_ExitMessage.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } // OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands else if (status == FtpStatusCode.FileStatus) { FtpWebRequest request = (FtpWebRequest) m_Request; if (entry.Command.StartsWith("SIZE ")) { m_ContentLength = GetContentLengthFrom213Response(response.StatusDescription); } else if (entry.Command.StartsWith("MDTM ")) { m_LastModified = GetLastModifiedFrom213Response(response.StatusDescription); } } // OR parse out our login directory else if (status == FtpStatusCode.PathnameCreated) { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { m_LoginDirectory = GetLoginDirectory(response.StatusDescription); if (!m_IsRootPath && m_LoginDirectory != "\\" && m_LoginDirectory != "/" && m_Alias == null) { //update command list for (int i=0;i<m_Commands.Length;i++){ if(m_Commands[i].Command.IndexOf("CWD") == 0) { string path = m_LoginDirectory+m_NewServerPath; m_Commands[i] = new PipelineEntry(FormatFtpCommand("CWD", path)); break; } } } } } // Asserting we have some positive response else { // OR update the current path (optimize this pls) if (entry.Command.IndexOf("CWD") != -1) { m_PreviousServerPath = m_NewServerPath; } } // Intermidate responses require rereading if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n")) { return PipelineInstruction.Reread; } return PipelineInstruction.Advance; }
/// <summary> /// <para>Cleans up state variables for reuse of the connection</para> /// </summary> protected override void ClearState() { m_ContentLength = -1; m_LastModified = DateTime.MinValue; m_ResponseUri = null; m_DataHandshakeStarted = false; StatusCode = FtpStatusCode.Undefined; StatusLine = null; m_DataSocket = null; m_PassiveEndPoint = null; m_TlsStream = null; base.ClearState(); }
/// <summary> /// After the task is complete, it logs the result of the FTP operation. /// </summary> /// <param name="status">The FTP operation status.</param> protected void HandleResult(FtpStatusCode status) { if (Verbose) { Log(Level.Info, "Completed with status " + (int)status); } SetResultProperty(status); if (status != FtpStatusCode.CommandOK && FailOnError) { throw new BuildException(string.Format("Error status: {0} - {1}", (int)status, status)); } }
protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException) { return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)), innerException, WebExceptionStatus.ProtocolError, null); }
public FtpStatus (FtpStatusCode statusCode, string statusDescription) { this.statusCode = statusCode; this.statusDescription = statusDescription; }
internal void UpdateStatus (FtpStatus status) { statusCode = status.StatusCode; statusDescription = status.StatusDescription; }
public static string GetWebStatusCodeString(FtpStatusCode statusCode, string statusDescription) { string webStatusCode = "(" + ((int)statusCode).ToString(NumberFormatInfo.InvariantInfo) + ")"; string statusMessage = null; // // Now combine the label with the base enum key and look up the status msg. // try { // // convert the HttpStatusCode to its label and look it up. // statusMessage = SR.GetString("net_ftpstatuscode_" + statusCode.ToString(), null); } catch { } if (statusMessage!=null && statusMessage.Length>0) { webStatusCode += " " + statusMessage; } else { // // Otherwise try to map the base status. // if (statusDescription!=null && statusDescription.Length>0) { webStatusCode += " " + statusDescription; } } return webStatusCode; }
/// <summary> /// Determines whether the specified FTP status code is positive. /// </summary> /// <param name="code"> /// The <see cref="System.Net.FtpStatusCode"/> value to check. /// </param> /// <returns>True if the code is positive, otherwise false.</returns> public static bool IsPositiveStatusCode(FtpStatusCode code) { switch (code) { case FtpStatusCode.CommandOK: case FtpStatusCode.CommandExtraneous: case FtpStatusCode.DirectoryStatus: case FtpStatusCode.FileStatus: case FtpStatusCode.SystemType: case FtpStatusCode.ClosingControl: case FtpStatusCode.ClosingData: case FtpStatusCode.EnteringPassive: case FtpStatusCode.LoggedInProceed: case FtpStatusCode.FileActionOK: case FtpStatusCode.PathnameCreated: return true; default: return false; } }
protected Exception GenerateException(FtpStatusCode code, string statusDescription, Exception innerException) { return new WebException(SR.GetString("net_servererror", new object[] { NetRes.GetWebStatusCodeString(code, statusDescription) }), innerException, WebExceptionStatus.ProtocolError, null); }
private static bool TryFtpAuthenticate(out FtpStatusCode code) { FtpWebRequest ftpCheckReq = FtpWebRequest.Create(Settings[SETTING_FTP_HOST]) as FtpWebRequest; ftpCheckReq.Credentials = new NetworkCredential(Settings[SETTING_FTP_USER], FtpPassword); ftpCheckReq.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse ftpCheckResp = ftpCheckReq.GetResponseSafe() as FtpWebResponse; code = ftpCheckResp.StatusCode; ftpCheckResp.Close(); ftpCheckResp.Dispose(); return code != FtpStatusCode.NotLoggedIn; }
private static bool GetAndVerifyFtpResponse(FtpWebRequest ftpRequest, FtpStatusCode expectedStatus, bool throwException) { try { using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse()) { if (ftpResponse.StatusCode == expectedStatus) return true; string message = String.Format(Resources.ExceptionMsg_Formatable2_UnexpectedResponse, ftpResponse.StatusCode, expectedStatus); // TODO Log //Trace.WriteLineIf(RoamiePlugin.TraceSwitch.TraceError, message, TraceCategory); if (throwException) throw new WebException(message); return false; } } catch (Exception) { if (throwException) throw; return false; } }