// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public FtpState Upload(string _file, string _uri, string _account, string _pass, UploadStepDelegate _stepDelegate) { state = new FtpState(); request = (FtpWebRequest)WebRequest.Create(new Uri(_uri + "/" + Path.GetFileName(_file))); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential(_account, _pass); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = _file; state.StepProgressDelegate = _stepDelegate; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); return(state); }
//---------------------------------------------------------------------------------------------- /// <summary> /// Make a FTP request to get a file from the server. /// It will raise an event on the BaseHandler, when done /// </summary> /// <param name="target"> url that is the name of the file being uploaded to the server</param> /// <param name="state">holds all the required data as supplied by the caller</param> /// <param name="user">username used to connect to the server</param> /// <param name="passwrd">username used to connect to the server</param> public static void DownloadRequest(Uri target, FtpState state, string user, string passwrd) { try { SetupRequest(target, state, state.FileName.Name, user, passwrd); state.mRequest.Method = WebRequestMethods.Ftp.DownloadFile; // // Store the request in the object that we pass into the // asynchronous operations. // Asynchronously get the stream for the file contents. // state.mRequest.BeginGetResponse( new AsyncCallback(EndDownloadResponseCallback), state); //.BeginGetRequestStream( // new AsyncCallback(EndDownloadGetStreamCallback), // state //); } catch (Exception e) { state.RaiseException(e); } }
/// <summary> /// Upload a MemoryStream object to the given FTP server. /// </summary> /// <param name="stream"></param> /// <param name="target"></param> /// <param name="username"></param> /// <param name="password"></param> public static void Upload(MemoryStream stream, Uri target, string username, string password) { var state = new FtpState(); var request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username, password); // Store the request in the object that we pass into the asynchronous operations. state.Request = request; state.Stream = stream; // Get the event to wait on. var waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream(EndGetStreamCallback, state); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } }
//---------------------------------------------------------------------------------------------- /// <summary> /// Make a FTP request to put a file onto the server. /// It will raise an event on the BaseHandler, when done /// </summary> /// <param name="target"> url that is the name of the file being uploaded to the server</param> /// <param name="state">holds all the required data as supplied by the caller</param> /// <param name="user">username used to connect to the server</param> /// <param name="passwrd">username used to connect to the server</param> public static void UploadRequest(Uri target, FtpState state, string user, string passwrd) { try { if (!state.FileName.Exists) { throw new Exception("FTP_Handler::UploadRequest file: " + state.FileName.FullName + " does not exist"); } SetupRequest(target, state, state.FileName.Name, user, passwrd); state.mRequest.Method = WebRequestMethods.Ftp.UploadFile; // // Store the request in the object that we pass into the // asynchronous operations. // Asynchronously get the stream for the file contents. // state.mRequest.BeginGetRequestStream( new AsyncCallback(EndUploadGetStreamCallback), state ); } catch (Exception e) { state.RaiseException(e); } }
public static string FtpFileUpload(string ftpUri, string ftpUsername, string ftpPassword, string fileFullPath, string fileName) { ManualResetEvent waitObject; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri + fileName); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); state.Request = request; state.FileName = fileFullPath; waitObject = state.OperationComplete; request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { return(state.OperationException.Message); } else { return(string.Empty); } }
///////////////////////////////////////////////////////////////////////////////////////////////////// //get_stream ///////////////////////////////////////////////////////////////////////////////////////////////////// private void get_stream(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; try { Stream request_stream = state.request.EndGetRequestStream(ar); const int len = 2048; byte[] buf = new byte[len]; int count = 0; int read = 0; FileStream file_stream = File.OpenRead(state.full_filename); do { read = file_stream.Read(buf, 0, len); request_stream.Write(buf, 0, read); count += read; }while (read != 0); request_stream.Close(); state.request.BeginGetResponse(new AsyncCallback(end_response), state); } catch (Exception e) { Console.WriteLine(e.Message); return; } }
private static void EndGetStreamCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; FileStream stream = null; Stream requestStream = null; // End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); // Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes = 0; stream = File.OpenRead(state.Argument); do { readBytes = stream.Read(buffer, 0, bufferLength); requestStream.Write(buffer, 0, readBytes); count += readBytes; }while (readBytes != 0); Utils.configLog("I", String.Format("Writing {0} bytes to the stream.", count)); // IMPORTANT: Close the request stream before sending the request. requestStream.Close(); requestStream = null; // Asynchronously get the response to the upload request. state.Request.BeginGetResponse( new AsyncCallback(EndGetResponseCallback), state ); } // Return exceptions to the main application thread. catch (Exception e) { Utils.configLog("E", String.Format("Could not get the request stream")); state.OperationException = e; state.OperationComplete.Set(); return; } finally { if (null != requestStream) { requestStream.Close(); } if (null != stream) { stream.Close(); } } }
public static void SendFile(string FTPSite, string fileName, string user, string pass, string fullPath) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(FTPSite); FtpState state = new FtpState(); //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target + @"/" + fileName); //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://10.1.36.34/"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Proxy = null; request.Credentials = new NetworkCredential(user, pass); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; // Set a time limit for the operation to complete. request.Timeout = 600000; //state.FileName = @"C:\Software\PFCApps\IntranetSite\PurchaseImport\XML\PFC_Order_11050303_toms.xml"; ; state.FileName = fullPath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { //lblSuccessMessage.Text = "XML sent to " + FTPSite; //MessageUpdatePanel.Update(); } }
// The EndGetResponseCallback method // completes a call to BeginGetResponse. private static void EndGetResponseCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; FtpWebResponse response = null; FileStream stream = null; try { response = (FtpWebResponse)state.Request.EndGetResponse(ar); state.StatusDescription = response.StatusDescription; state.ResponseStream = response.GetResponseStream(); if (state.Request.Method == WebRequestMethods.Ftp.DownloadFile) { const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int writeBytes = 0; stream = File.OpenWrite(state.Argument); do { writeBytes = state.ResponseStream.Read(buffer, 0, bufferLength); stream.Write(buffer, 0, writeBytes); count += writeBytes; }while (writeBytes != 0); Utils.configLog("I", String.Format("Writing {0} bytes to the file.", count)); } // Signal the main application thread that // the operation is complete. state.OperationComplete.Set(); } // Return exceptions to the main application thread. catch (Exception e) { Utils.configLog("E", String.Format("Error getting response.")); state.OperationException = e; state.OperationComplete.Set(); } finally { if (null != response) { response.Close(); } if (null != stream) { stream.Close(); } } }
// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public static void Main(string[] args) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(args[0]); string fileName = args[1]; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential("anonymous", "*****@*****.**"); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Console.WriteLine("The operation completed - {0}", state.StatusDescription); } }
///////////////////////////////////////////////////////////////////////////////////////////////////// //end_response ///////////////////////////////////////////////////////////////////////////////////////////////////// private void end_response(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; try { FtpWebResponse response = (FtpWebResponse)state.request.EndGetResponse(ar); response.Close(); state.wait.Set(); } catch (Exception e) { Console.WriteLine(e.Message); state.wait.Set(); } }
private void EndGetStreamCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; Stream requestStream = null; // End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); // Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes = 0; FileStream stream = File.OpenRead(state.FileName); do { readBytes = stream.Read(buffer, 0, bufferLength); requestStream.Write(buffer, 0, readBytes); count += readBytes; if (state.StepProgressDelegate != null) { state.StepProgressDelegate(count); } }while (readBytes != 0); Debug.Log("Writing {0} bytes to the stream.", count); // IMPORTANT: Close the request stream before sending the request. requestStream.Close(); // Asynchronously get the response to the upload request. state.Request.BeginGetResponse( new AsyncCallback(EndGetResponseCallback), state ); } // Return exceptions to the main application thread. catch (Exception e) { Debug.LogError("AsynchronousFtpUpLoader Could not get the request stream. " + e.Message); state.OperationException = e; } }
///////////////////////////////////////////////////////////////////////////////////////////////////// //get_stream_buf //gets buffer from FtpState ///////////////////////////////////////////////////////////////////////////////////////////////////// private void get_stream_buf(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; try { Stream stream = state.request.EndGetRequestStream(ar); byte[] buf = Encoding.ASCII.GetBytes(state.buf); stream.Write(buf, 0, state.buf.Length); stream.Close(); state.request.BeginGetResponse(new AsyncCallback(end_response), state); } catch (Exception e) { Console.WriteLine(e.Message); return; } }
///////////////////////////////////////////////////////////////////////////////////////////////////// //upload_async_read ///////////////////////////////////////////////////////////////////////////////////////////////////// private bool upload_async_read(string full_filename, string filename, bool alive, string connection_name, int connection_limit) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + address + "/" + directory + "/" + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username, password); request.KeepAlive = alive; if (!String.IsNullOrEmpty(connection_name)) { request.ConnectionGroupName = connection_name; } request.ServicePoint.ConnectionLimit = connection_limit; FtpState state = new FtpState(request, full_filename); ManualResetEvent wait = state.wait; request.BeginGetRequestStream(new AsyncCallback(get_stream), state); wait.WaitOne(); return(true); }
// The EndGetResponseCallback method // completes a call to BeginGetResponse. private void EndGetResponseCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; FtpWebResponse response = null; try { response = (FtpWebResponse)state.Request.EndGetResponse(ar); response.Close(); state.StatusDescription = response.StatusDescription; } // Return exceptions to the main application thread. catch (Exception e) { Debug.LogError("AsynchronousFtpUpLoader Error getting response." + e.Message); state.OperationException = e; } }
private static void EndGetStreamCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; Stream requestStream = null; // End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); // Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes = 0; FileStream stream = File.OpenRead(state.FileName); do { readBytes = stream.Read(buffer, 0, bufferLength); requestStream.Write(buffer, 0, readBytes); count += readBytes; }while (readBytes != 0); // IMPORTANT: Close the request stream before sending the request. requestStream.Close(); // Asynchronously get the response to the upload request. state.Request.BeginGetResponse( new AsyncCallback(EndGetResponseCallback), state ); if (stream != null) { stream.Close(); } } // Return exceptions to the main application thread. catch (Exception e) { state.OperationException = e; state.OperationComplete.Set(); return; } }
// The EndGetResponseCallback method // completes a call to BeginGetResponse. private static void EndGetResponseCallback(IAsyncResult ar) { FtpState state = (FtpState)ar.AsyncState; FtpWebResponse response = null; try { response = (FtpWebResponse)state.Request.EndGetResponse(ar); response.Close(); state.StatusDescription = response.StatusDescription; // Signal the main application thread that // the operation is complete. state.OperationComplete.Set(); } // Return exceptions to the main application thread. catch (Exception e) { state.OperationException = e; state.OperationComplete.Set(); } }
private async Task PerformUpload(string lServerPath, string tempPath) { var fileName = Path.GetFileName(lServerPath); var state = new FtpState(); var request = (FtpWebRequest)(WebRequest.Create(FTPServerAddress + lServerPath)); request.Credentials = new NetworkCredential(Username, Password); request.Method = WebRequestMethods.Ftp.UploadFile; state.Request = request; state.FileName = tempPath; using (var requestStream = await state.Request.GetRequestStreamAsync()) { const int bufferLength = 10000; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes; using (FileStream stream = File.OpenRead(state.FileName)) { do { readBytes = await stream.ReadAsync(buffer, 0, bufferLength); await requestStream.WriteAsync(buffer, 0, readBytes); count += readBytes; var percentageComplete = (int)(((double)count / stream.Length) * 100); UpdateStatusMessage($"Uploading {fileName}: ({percentageComplete}% complete)"); } while (readBytes != 0); } } using (FtpWebResponse response = (FtpWebResponse)await state.Request.GetResponseAsync()) { state.StatusDescription = response.StatusDescription; } }
private static void HandleFileTransfer(Uri serverUri, string filepath, bool up, string userName, string password, bool enableSSL) { if (serverUri.Scheme != Uri.UriSchemeFtp) { throw new ArgumentException(String.Format("{0} scheme is not ftp", serverUri.AbsoluteUri)); } ManualResetEvent waitObject; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri); request.EnableSsl = enableSSL; if (up) { request.Method = WebRequestMethods.Ftp.UploadFile; } else { request.Method = WebRequestMethods.Ftp.DownloadFile; } request.Credentials = new NetworkCredential(userName, password); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.Argument = filepath; // Get the event to wait on. waitObject = state.OperationComplete; if (up) { // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); } else { request.BeginGetResponse( new AsyncCallback(EndGetResponseCallback), state ); } // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Utils.configLog("I", String.Format("The operation completed - {0}", state.StatusDescription)); } }
/// <summary>Upload the File to Ftp.</summary> /// <param name="objUploadFileDistributionRequest">Input File distribution request.</param> /// <returns>error if any.</returns> internal static string Upload(ref UploadFileDistributionRequest objUploadFileDistributionRequest) { string error = string.Empty; if (objUploadFileDistributionRequest != null && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpServerIP) && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpUserName) && !string.IsNullOrEmpty(objUploadFileDistributionRequest.FtpPassword) && objUploadFileDistributionRequest.Folder.NbFiles > 0) { foreach (IRemoteFileClass lRemoteFile in objUploadFileDistributionRequest.Folder.FolderFilesList) { if (lRemoteFile.Exists) { /* Testing mode is enable. So, simulate that file was uploaded properly. * * In the future, a better approach might be found. */ if (lRemoteFile.FileType == FileTypeEnum.Undefined && RemoteFileClass.TestingModeEnabled) { FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = FtpStatusCode.FileActionOK;; ftpStatus.OperationException = null; ftpStatus.StatusDescription = "OK"; lRemoteFile.FtpStatus = ftpStatus; continue; } DateTime dtTime = DateTime.Now; FtpWebRequest reqFTP = null; try { InitializeFtpRequest(lRemoteFile, objUploadFileDistributionRequest.FtpServerIP, objUploadFileDistributionRequest.FtpDirectory, objUploadFileDistributionRequest.FtpUserName, objUploadFileDistributionRequest.FtpPassword, out reqFTP); } catch (Exception ex) { return(ex.Message); } if (reqFTP != null) { FtpWebResponse response = null; try { using (ManualResetEvent timerEvent = new ManualResetEvent(false)) using (FtpState ftpState = new FtpState()) { ftpState.RemoteFile = lRemoteFile; ftpState.Request = reqFTP; ftpState.Request.Timeout = Timeout.Infinite; UploadFile(ftpState); if (ftpState.Response != null) { response = ftpState.Response; if (response.StatusCode == FtpStatusCode.ServiceNotAvailable || response.StatusCode == FtpStatusCode.ServiceTemporarilyNotAvailable) { if (DateTime.Now.Subtract(dtTime).TotalMinutes > TimeOut) { error = "T2G Ground Server not responding for " + TimeOut + " period uploading terminated"; objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; return(error); } } if (response.StatusCode != FtpStatusCode.FileActionOK && response.StatusCode != FtpStatusCode.ClosingData && response.StatusCode != FtpStatusCode.DirectoryStatus && response.StatusCode != FtpStatusCode.FileStatus && response.StatusCode != FtpStatusCode.SystemType && response.StatusCode != FtpStatusCode.SendUserCommand && response.StatusCode != FtpStatusCode.ClosingControl && response.StatusCode != FtpStatusCode.ClosingData && response.StatusCode != FtpStatusCode.PathnameCreated) { lRemoteFile.HasError = true; LogManager.WriteLog(TraceType.INFO, "File upload error, create transfer task. RequestID = " + objUploadFileDistributionRequest.RequestId.ToString() + ", CRCGuid = " + objUploadFileDistributionRequest.Folder.CRCGuid + ", Folder ID = " + objUploadFileDistributionRequest.Folder.FolderId.ToString() + ", FTP error = " + response.StatusCode.ToString(), "Ground.Core.T2G.T2GClient.StartTransferTask", null, EventIdEnum.GroundCore); objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; } FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = response.StatusCode; ftpStatus.OperationException = null; ftpStatus.StatusDescription = response.StatusDescription; lRemoteFile.FtpStatus = ftpStatus; } else { error = "Can't upload file on T2G Ftp Server. Server is not responding or input file is invalid, check error log."; objUploadFileDistributionRequest.Folder.UploadingState = UploadingStateEnum.Failed; return(error); } } } catch (Exception ex) { response = (FtpWebResponse)reqFTP.GetResponse(); if (response != null) { FtpStatus ftpStatus = new FtpStatus(); ftpStatus.FileName = lRemoteFile.FilePath; ftpStatus.FtpStatusCode = response.StatusCode; ftpStatus.OperationException = ex; ftpStatus.StatusDescription = response.StatusDescription; lRemoteFile.FtpStatus = ftpStatus; LogManager.WriteLog(TraceType.ERROR, PIS.Ground.Core.Properties.Resources.ExFtpError, "PIS.Ground.Core.Utility.Upload", ex, EventIdEnum.GroundCore); } } finally { if (response != null) { response.Close(); } } } } else { error = "File " + lRemoteFile.FilePath + " does not exist."; return(error); } } } else { error = "Invalid Input parameter"; } return(error); }
/// <summary>Uploads a file.</summary> /// <exception cref="FileNotFoundException">Thrown when the requested file is not present.</exception> /// <param name="state">The state.</param> private static void UploadFile(object state) { if (state is FtpState) { FtpState ftpState = state as FtpState; ftpState.Response = null; if (!string.IsNullOrEmpty(ftpState.RemoteFile.FileName) && ftpState.RemoteFile.Exists) { //// Notify the server about the size of the uploaded file ftpState.Request.ContentLength = ftpState.RemoteFile.Size; //// The buffer size is set to 2kb const int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; try { //// Opens a file stream to read the file to be uploaded Stream fs; ftpState.RemoteFile.OpenStream(out fs); if (fs != null) { using (fs) { fs.Seek(0, SeekOrigin.Begin); //// Stream to which the file to be upload is written using (Stream strm = ftpState.Request.GetRequestStream()) { //// Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); //// Till Stream content ends while (contentLen != 0) { //// Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } } } } else { string lErrorMessage = "Can't read file "; lErrorMessage += ftpState.RemoteFile.FilePath; FileNotFoundException lFNFEx = new FileNotFoundException(lErrorMessage, ftpState.RemoteFile.FilePath); LogManager.WriteLog(TraceType.ERROR, lFNFEx.Message, "PIS.Ground.Core.Utility.FtpUtility.UploadFile", lFNFEx, EventIdEnum.GroundCore); throw lFNFEx; } if (ftpState.Request != null) { ftpState.Response = (FtpWebResponse)ftpState.Request.GetResponse(); if (ftpState.Response.StatusCode != FtpStatusCode.ServiceNotAvailable && ftpState.Response.StatusCode != FtpStatusCode.ServiceTemporarilyNotAvailable) { ftpState.OperationComplete.Set(); } } } catch (Exception ex) { ftpState.FtpStatus.OperationException = ex; ftpState.OperationComplete.Set(); // Avoid logging error for ThreadAbortException if (!(ex is ThreadAbortException)) { LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Core.Utility.FtpUtility.UploadFile", ex, EventIdEnum.GroundCore); } else { LogManager.WriteLog(TraceType.DEBUG, ex.Message, "PIS.Ground.Core.Utility.FtpUtility.UploadFile", ex, EventIdEnum.GroundCore); } } } } }
//---------------------------------------------------------------------------------------------- private static void SetupRequest(Uri target, FtpState state, string fileName, string user, string passwrd) { if (target.Scheme != Uri.UriSchemeFtp) { throw new Exception("UploadRequest: Target uri was not ftp"); } state.mRequest = (FtpWebRequest)WebRequest.Create(target + @"/" + fileName); state.mRequest.Proxy = null; // // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. // if (user != null && user.Length != 0) { state.mRequest.Credentials = new NetworkCredential(user, passwrd); //"anonymous", "*****@*****.**"); } }
/// <summary> /// Control thread /// TODO: separate the functionalities into functions to reduce maintenance cost /// </summary> private void WorkerThread() { FtpCommand command; FtpState state = FtpState.WaitUser; string tempName = null; // store old name for "rename from" command string response; int timeout = 0; try { while (m_IsAlive) { if (m_IsDisposed) { break; } else if (!m_Welcomed) { response = "220 MyFTP " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " Server [" + m_HostIp.ToString() + "] \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); m_Welcomed = true; } else if (m_CommandSocket == null) { Logging.Print("Session socket has been closed."); break; } else if (m_CommandSocket.Poll(1000, SelectMode.SelectRead)) { if (m_CommandSocket.Available == 0) { Logging.Print("REMOTE DISCONNECT " + m_CommandSocket.RemoteEndPoint.ToString()); m_IsAlive = false; break; } // read until find the end of a line command = FtpCommandCreator.Create(ReadCommand()); if (command == null) { break; } else { switch (command.Type) { case FtpCommandType.User: response = "331 " + command.Content + " login ok \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); state = FtpState.WaitPwd; tempName = command.Content; break; case FtpCommandType.Pass: if (state != FtpState.WaitPwd) { response = "332 Need Account for Login.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { UserAuthenticatorArgs args = new UserAuthenticatorArgs(tempName, command.Content); FtpListener.RaiseEvent(this, args); if (args.Result == UserAuthenticationResult.Approved) { User.UserName = tempName; User.PassWord = command.Content; response = "230 access granted for " + User.UserName + ", restrictions apply. \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); state = FtpState.WaitCommand; break; } else { response = "530 Login incorrect. \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); state = FtpState.WaitCommand; break; } } case FtpCommandType.Cwd: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitUser) { response = "332 Need Account for Login.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { if (command.Content == null) { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethodsEx.Ftp.ChangeDirectory, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Quit: m_IsAlive = false; CloseDataChannel(); response = "221 Goodbye.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); m_CommandSocket.Close(); m_CommandSocket = null; break; case FtpCommandType.Pasv: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { CloseDataChannel(); m_DataThread = new Thread(PassiveThread); m_DataThread.Start(); m_DataReadyEvent.WaitOne(); // wait until port has been successfully assigned byte[] addrs = m_HostIp.GetAddressBytes(); int upper = m_HostPort / 256; int lower = m_HostPort % 256; if (addrs.Length == 4) //IPv4 { response = "227 Entering Passive Mode ("; foreach (int i in addrs) { response += i.ToString() + ","; } response += upper.ToString() + "," + lower.ToString() + ")\r\n"; } else // currently do not support IPv6 { throw new NotImplementedException("currently does not support IPv6"); } m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Type: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "200 Command OK.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.List: if (!m_DataModeON) { response = "425 Use PORT or PASV first.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "150 Opening UTF8 mode data connection for *** \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.ListDirectoryDetails, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.NList: if (!m_DataModeON) { response = "425 Use PORT or PASV first.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "150 Opening UTF8 mode data connection for *** \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.ListDirectory, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Port: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand && command.Content != null) { CloseDataChannel(); string[] epad = command.Content.Split(new char[] { ',' }); if (epad.Length != 6) { response = "500 Invalid PORT command.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); } else { try { m_ClientIp = IPAddress.Parse(epad[0] + "." + epad[1] + "." + epad[2] + "." + epad[3]); m_ClientPort = Int32.Parse(epad[4]) * 256 + Int32.Parse(epad[5]); if (m_ClientPort <= 0 || m_ClientPort > 65535) { response = "500 Invalid PORT command.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); } else { m_ActThreadW = true; m_DataThread = new Thread(ActiveThread); m_DataThread.Start(); response = "200 PORT command successful.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); } } catch (Exception) { response = "500 Invalid PORT command.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); } } break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Sys: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "215 System Type: EMIC\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Feature: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "211-Features:\r\n SIZE\r\n211 End\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Pwd: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { response = "257 \"" + m_CurrentDirectory.GetNetPath() + "\" is the current directory. \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Retr: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { if (!m_DataModeON) { response = "425 Use PORT or PASV first.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } response = "150 Opening BINARY mode data connection for " + command.Content + ". \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.DownloadFile, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Opts: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { if (command.Content == "utf8") { response = "213 Always in utf8 mode \r\n"; } else { response = "550 Requested action not taken. Mode not support. \r\n"; } m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Size: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.GetFileSize, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Store: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { if (!m_DataModeON) { response = "425 Use PORT or PASV first.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } response = "150 Opening BINARY mode data connection for " + command.Content + ". \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.UploadFile, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Noop: response = "200 NOOP command successful. \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; case FtpCommandType.Delete: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.DeleteFile, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.MkDir: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.MakeDirectory, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Rmd: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethods.Ftp.RemoveDirectory, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Rnfr: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethodsEx.Ftp.RenameFrom, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } case FtpCommandType.Rnto: if (state == FtpState.WaitPwd) { response = "331 Need Password.\r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } else if (state == FtpState.WaitCommand) { FtpListenerRequest request = new FtpListenerRequest(WebRequestMethodsEx.Ftp.RenameTo, m_CurrentDirectory.Combine(command.Content).GetNetPath(), this); FtpListenerContext context = new FtpListenerContext(this, request); m_SendContext.AddContext(context); break; } else { response = m_BadSequence; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } default: response = "502 Command not implemented. \r\n"; if (state == FtpState.WaitPwd) { state = FtpState.WaitUser; } m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); break; } } // reset time out timeout = 0; } else if (m_CommandSocket.Poll(1000, SelectMode.SelectError)) { Logging.Print("Disconnected unproperly."); break; } else { if (!m_Welcomed) { response = "220 MyFTP " + typeof(FtpListenerSession).Assembly.GetName().Version.ToString() + " Server [" + m_HostIp.ToString() + "] \r\n"; m_CommandSocket.Send(Encoding.UTF8.GetBytes(response)); m_Welcomed = true; } else { if (SessionTimeOut != -1) { if (timeout > SessionTimeOut) { m_IsAlive = false; Logging.Print("Connection time out."); break; } timeout += 50; } Thread.Sleep(50); } } } } catch (SocketException se) { Logging.Print("Control Socket Exception : " + se.ErrorCode.ToString()); } catch (IOException ioe) { Logging.Print("IOException: " + ioe.Message); } finally { m_IsAlive = false; if (m_CommandSocket != null) { m_CommandSocket.Close(); m_CommandSocket = null; } if (m_ListenSocket != null) { m_ListenSocket.Close(); m_CommandSocket = null; } Logging.Print("Client Disconnected."); } }