Beispiel #1
0
        /// <inheritdoc/>
        public override Task<FtpResponse> Process(FtpCommand command, CancellationToken cancellationToken)
        {
            var transferMode = FtpTransferMode.Parse(command.Argument);

            FtpResponse response;
            if (transferMode.FileType == FtpFileType.Ascii)
            {
                response = new FtpResponse(200, "ASCII transfer mode active.");
            }
            else if (transferMode.IsBinary)
            {
                response = new FtpResponse(200, "Binary transfer mode active.");
            }
            else
            {
                response = new FtpResponse(504, $"Mode {command.Argument} not supported.");
            }

            if (response.Code == 200)
            {
                Connection.Data.TransferMode = transferMode;
            }

            return Task.FromResult(response);
        }
Beispiel #2
0
        internal FtpResponse Connect(int timeout,
                                     string server,
                                     int port)
        {
            CheckDisposed();

            NSTrace.WriteLineVerbose("CC: -> Connect");
            if (null == server)
            {
                throw new ArgumentNullException("server");
            }

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException("port", "Value, specified for the port, is out of valid range.");
            }

            SetProgress(true);
            try
            {
                _socket.ConnectTimeout = timeout;

                string msg = string.Format("CC: Connecting (timeout: {0}, srv: {1}:{2})...", timeout, server, port);
                NSTrace.WriteLineInfo(msg);

                _socket.Connect(server, port);

                msg = string.Format("CC: Reading response...");
                NSTrace.WriteLineInfo(msg);

                _response = _reader.ReadResponse(timeout);

                NSTrace.WriteLineVerbose("CC: <- Connect");
            }
            catch (SocketException e)
            {
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch (Exception)
            {
                CheckDisposed();
                throw;
            }
            catch
            {
                CheckDisposed();
                throw;
            }
            finally
            {
                SetProgress(false);
            }
            OnResponseReceived();
            return(_response);
        }
Beispiel #3
0
        public void Handle(FtpMessage message)
        {
            Console.WriteLine("Request received with id:" + message.Id);

            var rep = new FtpResponse {
                Id = 500, OtherData = Guid.NewGuid(), IsThisCool = true, Description = "What the?", ResponseId = message.Id
            };

            Bus.Reply(rep);
        }
        /// <inheritdoc />
        public async Task ExecuteAsync(DataConnectionServerCommand command, CancellationToken cancellationToken)
        {
            var connection          = _connectionAccessor.FtpConnection;
            var serverCommandWriter = connection.Features.Get <IServerCommandFeature>().ServerCommandWriter;
            var localizationFeature = connection.Features.Get <ILocalizationFeature>();

            using (new ConnectionKeepAlive(connection, command.Command))
            {
                // Try to open the data connection
                IFtpDataConnection dataConnection;
                try
                {
                    dataConnection = await connection.OpenDataConnectionAsync(null, cancellationToken)
                                     .ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger?.LogWarning(0, ex, "Could not open data connection: {error}", ex.Message);
                    var errorResponse = new FtpResponse(
                        425,
                        localizationFeature.Catalog.GetString("Could not open data connection"));
                    await serverCommandWriter
                    .WriteAsync(new SendResponseServerCommand(errorResponse), cancellationToken)
                    .ConfigureAwait(false);

                    return;
                }

                // Execute the operation on the data connection.
                var commandResponse = await connection.ExecuteCommand(
                    command.Command,
                    (_, ct) => command.DataConnectionDelegate(dataConnection, ct),
                    _logger,
                    cancellationToken);

                var response =
                    commandResponse
                    ?? new FtpResponse(226, localizationFeature.Catalog.GetString("Closing data connection."));

                // We have to leave the connection open if the response code is 250.
                if (response.Code != 250)
                {
                    // Close the data connection.
                    await serverCommandWriter
                    .WriteAsync(new CloseDataConnectionServerCommand(dataConnection), cancellationToken)
                    .ConfigureAwait(false);
                }

                // Send the response.
                await serverCommandWriter
                .WriteAsync(new SendResponseServerCommand(response), cancellationToken)
                .ConfigureAwait(false);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Throws an exception if the server response is not one of the given acceptable codes
        /// </summary>
        /// <param name="response"></param>
        /// <param name="codes"></param>
        /// <returns></returns>
        private async Task BailIfResponseNotAsync(FtpResponse response, params FtpStatusCode[] codes)
        {
            if (codes.Any(x => x == response.FtpStatusCode))
            {
                return;
            }

            Logger?.LogDebug($"Bailing due to response codes being {response.FtpStatusCode}, which is not one of: [{string.Join( ",", codes )}]");

            await LogOutAsync();

            throw new FtpException(response.ResponseMessage);
        }
Beispiel #6
0
        //this function used by routines - Connect, SendCommandEx, ReadResponse
        void OnResponse(IAsyncResult ar)
        {
            AsyncResultBase stateObj = (AsyncResultBase)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                _response = _reader.EndReadResponse(ar);
                OnResponseReceived();
            }
            catch (SocketException e)
            {
                if (_disposed)
                {
                    stateObj.Exception = GetDisposedException();
                }
                else if (e.ErrorCode == SockErrors.WSAETIMEDOUT)
                {
                    stateObj.Exception = GetTimeoutException(e);
                }
                else
                {
                    stateObj.Exception = e;
                }
            }
            catch (Exception e)
            {
                if (_disposed)
                {
                    stateObj.Exception = GetDisposedException();
                }
                else
                {
                    stateObj.Exception = e;
                }
            }
            catch
            {
                if (_disposed)
                {
                    stateObj.Exception = GetDisposedException();
                }
                else
                {
                    NSTrace.WriteLineError("Non-CLS exception at: " + Environment.StackTrace);
                    throw;
                }
            }
            _response = _reader.Response;
            stateObj.SetCompleted();
        }
Beispiel #7
0
        internal FtpResponse SendCommandEx(int timeout, string command)
        {
            CheckDisposed();

            if (null == command)
            {
                throw new ArgumentNullException("command", "'command' argument cannot be null");
            }

            command = AppendCRLF(command);
            SetProgress(true);
            _response = null;
            try
            {
                _socket.SendTimeout = timeout;
                byte[] cmdBytes = _encoding.GetBytes(command);
                int    startPos = 0;
                while (startPos < cmdBytes.Length)
                {
                    startPos += _socket.Send(cmdBytes, startPos, cmdBytes.Length - startPos);
                }

                OnCommandSent(command);
                try
                {
                    _response = _reader.ReadResponse(timeout);
                }
                catch
                {
                    _response = _reader.Response;
                    throw;
                }
            }
            catch (SocketException e)
            {
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch
            {
                CheckDisposed();
                throw;
            }
            finally
            {
                SetProgress(false);
            }
            OnResponseReceived();
            return(_response);
        }
Beispiel #8
0
        bool RunLoginCmd(int timeout, string cmd, ref FtpResponse response)
        {
            response = _cc.SendCommandEx(timeout, cmd);
            if (!response.IsCompletionReply &&
                !response.IsIntermediateReply)
            {
                throw GetLoginFailedException(response);
            }

            if (response.IsCompletionReply)
            {
                return(false);       //login successed
            }
            return(true);            //need more
        }
Beispiel #9
0
        internal FtpResponse Execute(int timeout, string command)
        {
            SetProgress(true);
            FtpResponse response = null;

            try
            {
                response = _cc.SendCommandEx(timeout, command);
            }
            finally
            {
                SetProgress(false);
            }
            return(response);
        }
Beispiel #10
0
        public async Task <FtpResponse> GetResponseAsync(CancellationToken token = default(CancellationToken))
        {
            Logger?.LogDebug("Getting Response");

            if (Encoding == null)
            {
                throw new ArgumentNullException(nameof(Encoding));
            }

            await receiveSemaphore.WaitAsync(token);

            try
            {
                token.ThrowIfCancellationRequested();
                if (!SocketDataAvailable())
                {
                    Logger?.LogDebug("Response expected, but no data exists on the socket");
                }

                var response = new FtpResponse();
                var data     = new List <string>();

                foreach (string line in ReadLines(token))
                {
                    token.ThrowIfCancellationRequested();
                    Logger?.LogDebug(line);
                    data.Add(line);

                    Match match;

                    if (!(match = Regex.Match(line, "^(?<statusCode>[0-9]{3}) (?<message>.*)$")).Success)
                    {
                        continue;
                    }
                    Logger?.LogDebug("Finished receiving message");
                    response.FtpStatusCode   = match.Groups["statusCode"].Value.ToStatusCode();
                    response.ResponseMessage = match.Groups["message"].Value;
                    break;
                }
                response.Data = data.ToArray();
                return(response);
            }
            finally
            {
                receiveSemaphore.Release();
            }
        }
Beispiel #11
0
 /* Download File */
 public void Download(string localFile, string remoteFile)
 {
     try
     {
         /* Create an FTP Request */
         FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + remoteFile);
         /* Log in to the FTP Server with the User Name and Password Provided */
         FtpRequest.Credentials = new NetworkCredential(UserName, Password);
         LogInToInterlocutor(InterlocutorAddress);
         /* When in doubt, use these options */
         FtpRequest.UseBinary  = true;
         FtpRequest.UsePassive = true;
         FtpRequest.KeepAlive  = true;
         /* Specify the Type of FTP Request */
         FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
         /* Establish Return Communication with the FTP Server */
         FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
         /* Get the FTP Server's Response Stream */
         StartDownloadData(localFile, remoteFile, InterlocutorAddress);
         FtpStream = FtpResponse.GetResponseStream();
         /* Open a File Stream to Write the Downloaded File */
         FileStream localFileStream = new FileStream(localFile, FileMode.Create);
         /* Buffer for the Downloaded Data */
         byte[] byteBuffer = new byte[BufferSize];
         int    bytesRead  = FtpStream.Read(byteBuffer, 0, BufferSize);
         /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
         try
         {
             while (bytesRead > 0)
             {
                 localFileStream.Write(byteBuffer, 0, bytesRead);
                 bytesRead = FtpStream.Read(byteBuffer, 0, BufferSize);
             }
         }
         finally
         { /* Resource Cleanup */
             localFileStream.Close();
             EndDownloadData(localFile, remoteFile, InterlocutorAddress);
         }
     }
     finally
     {
         FtpStream.Close();
         FtpResponse.Close();
         FtpRequest = null;
     }
 }
Beispiel #12
0
        public async Task <FtpResponse> GetResponseAsync(CancellationToken token = default(CancellationToken))
        {
            LoggerHelper.Trace("Getting Response");

            if (Encoding == null)
            {
                throw new ArgumentNullException(nameof(Encoding));
            }
#if NET40
            await Task.Factory.StartNew(() => receiveSemaphore.Wait(token));
#else
            await receiveSemaphore.WaitAsync(token);
#endif

            try
            {
                token.ThrowIfCancellationRequested();

                var response = new FtpResponse();
                var data     = new List <string>();

                foreach (string line in ReadLines(token))
                {
                    token.ThrowIfCancellationRequested();
                    LoggerHelper.Debug(line);
                    data.Add(line);

                    Match match;

                    if (!(match = Regex.Match(line, "^(?<statusCode>[0-9]{3}) (?<message>.*)$")).Success)
                    {
                        continue;
                    }
                    LoggerHelper.Trace("Finished receiving message");
                    response.FtpStatusCode   = match.Groups["statusCode"].Value.ToStatusCode();
                    response.ResponseMessage = match.Groups["message"].Value;
                    break;
                }
                response.Data = data.ToArray();
                return(response);
            }
            finally
            {
                receiveSemaphore.Release();
            }
        }
Beispiel #13
0
        internal void SendCommand(int timeout, string command)
        {
            CheckDisposed();

            if (null == command)
            {
                throw new ArgumentNullException("command", "Value cannot be null.");
            }

            command = AppendCRLF(command);

            SetProgress(true);
            _response = null;
            try
            {
                _socket.SendTimeout = timeout;
                byte[] cmdBytes = _encoding.GetBytes(command);
                int    startPos = 0;
                while (startPos < cmdBytes.Length)
                {
                    startPos += _socket.Send(cmdBytes, startPos, cmdBytes.Length - startPos);
                }

                OnCommandSent(command);
            }
            catch (SocketException e)
            {
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch (Exception)
            {
                CheckDisposed();
                throw;
            }
            catch
            {
                CheckDisposed();
                throw;
            }
            finally
            {
                SetProgress(false);
            }
        }
Beispiel #14
0
        /* Get the Size of a File */
        public string GetFileSize(string fileName)
        {
            try
            {
                /* Create an FTP Request */
                FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + fileName);
                /* Log in to the FTP Server with the User Name and Password Provided */
                FtpRequest.Credentials = new NetworkCredential(UserName, Password);
                LogInToInterlocutor(InterlocutorAddress);
                /* When in doubt, use these options */
                FtpRequest.UseBinary  = true;
                FtpRequest.UsePassive = true;
                FtpRequest.KeepAlive  = true;
                /* Specify the Type of FTP Request */
                FtpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                /* Establish Return Communication with the FTP Server */
                FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                /* Establish Return Communication with the FTP Server */
                FtpStream = FtpResponse.GetResponseStream();
                /* Get the FTP Server's Response Stream */
                StreamReader ftpReader = new StreamReader(FtpStream);
                /* Store the Raw Response */
                string fileInfo = null;
                /* Read the Full Response Stream */
                try { while (ftpReader.Peek() != -1)
                      {
                          fileInfo = ftpReader.ReadToEnd();
                      }
                }
                finally
                {
                    /* Resource Cleanup */
                    ftpReader.Close();
                }

                /* Return File Size */
                return(fileInfo);
            }
            finally
            {
                FtpStream.Close();
                FtpResponse.Close();
                FtpRequest = null;
            }
        }
        IPEndPoint GetPasvEndPoint(FtpResponse response)
        {
            string respStr = _encoding.GetString(response.RawBytes);
            Regex  re      = new Regex(@"^227.*[^\d](?<a1>\d{1,3}) *, *(?<a2>\d{1,3}) *, *(?<a3>\d{1,3}) *, *(?<a4>\d{1,3}) *, *(?<p1>\d{1,3}) *, *(?<p2>\d{1,3}).*");
            Match  m       = re.Match(respStr);

            if (7 != m.Groups.Count)
            {
                throw new Exception();                 // some error in reply
            }
            string ip = m.Groups["a1"] + "." + m.Groups["a2"] + "." +
                        m.Groups["a3"] + "." + m.Groups["a4"];
            IPAddress address = IPAddress.Parse(ip);

            int port = (int.Parse(m.Groups["p1"].Value) << 8) | int.Parse(m.Groups["p2"].Value);

            return(new IPEndPoint(address, port));
        }
Beispiel #16
0
        /// <summary> Renombrar un archivo remoto. </summary>
        ///
        /// <param name="remotePathFile"> Path del archivo remoto a renombrar. </param>
        /// <param name="remoteFileNew"> Nuevo nombre del archivo remoto. </param>
        ///
        /// <returns></returns>
        ///
        public Char FtpRenameFile(string remotePathFile, string remoteFileNew)
        {
            Resultado = 'N';

            try
            {
                if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null)
                {
                    UsrError  = "KO - Faltan parámetros de conexión al Host Ftp";
                    UsrErrorC = -1;
                    Resultado = 'N';

                    return(Resultado);
                }

                FtpRequest             = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remotePathFile);
                FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd);
                FtpRequest.Method      = WebRequestMethods.Ftp.Rename;
                FtpRequest.RenameTo    = remoteFileNew;

                // Canal de comunicación con el Host Ftp.
                FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();

                // Cerrar canales de comunicación Ftp.
                FtpRequest = null;
                FtpResponse.Close();

                Resultado = 'S';
                UsrError  = "OK";
            }

            catch (Exception ex)
            {
                // Error de programa.
                UsrErrorC = ex.HResult;
                UsrError  = ex.Message;
                UsrErrorE = ex.StackTrace;

                Resultado = 'C';
            }

            return(Resultado);
        }
Beispiel #17
0
        internal void ReadQuitResponse_End(IAsyncResult ar)
        {
            RunDTP_SO stateObj = (RunDTP_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse response = _cc.EndReadResponse(ar);
                ClearAtEnd(stateObj);
            }
            catch (Exception e)
            {
                HandleCatch(e, stateObj);
            }
            catch
            {
                HandleCatch(null, stateObj);
            }
        }
Beispiel #18
0
        void AccountCmd_End(IAsyncResult ar)
        {
            Login_SO stateObj = (Login_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse response = _cc.EndSendCommandEx(ar);
                if (!response.IsCompletionReply)
                {
                    throw GetLoginFailedException(response);
                }
            }
            catch (Exception e)
            {
                stateObj.Exception = e;
            }
            stateObj.SetCompleted();
        }
Beispiel #19
0
        internal FtpResponse ReadResponse(int timeout)
        {
            SetProgress(true);
            try
            {
                _response = new FtpResponse(_encoding);
                _response.NewLineEvent     += new FtpResponse.NewLineEventHandler(this.OnNewLine);
                _linesBuilder.NewLineEvent += new BytesRoad.Net.Ftp.Advanced.LinesBuilder.NewLineEventHandler(LinesBuilder_NewLineEvent);
                _socket.ReceiveTimeout      = timeout;

                while (true)
                {
                    ParseExistentData();

                    if (_response.IsCompleted)
                    {
                        break;
                    }

                    if (_linesBuilder.Available > 0)
                    {
                        continue;
                    }

                    int readNum = _socket.Receive(_recvBuffer);
                    if (0 == readNum)
                    {
                        throw GetClosedException();
                    }

                    _linesBuilder.PutData(_recvBuffer, readNum, false);
                }
            }
            finally
            {
                SetProgress(false);
                _linesBuilder.NewLineEvent -= new BytesRoad.Net.Ftp.Advanced.LinesBuilder.NewLineEventHandler(LinesBuilder_NewLineEvent);
                _response.NewLineEvent     -= new FtpResponse.NewLineEventHandler(this.OnNewLine);

                _linesBuilder.ClearCompleted();
            }
            return(_response);
        }
Beispiel #20
0
 /* List Directory Contents in Detail (Name, Size, Created, etc.) */
 public string[] DirectoryListDetailed(string directory)
 {
     try
     {
         /* Create an FTP Request */
         FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + directory);
         /* Log in to the FTP Server with the User Name and Password Provided */
         FtpRequest.Credentials = new NetworkCredential(UserName, Password);
         LogInToInterlocutor(InterlocutorAddress);
         /* When in doubt, use these options */
         FtpRequest.UseBinary  = true;
         FtpRequest.UsePassive = true;
         FtpRequest.KeepAlive  = true;
         /* Specify the Type of FTP Request */
         FtpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
         /* Establish Return Communication with the FTP Server */
         FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
         /* Establish Return Communication with the FTP Server */
         FtpStream = FtpResponse.GetResponseStream();
         /* Get the FTP Server's Response Stream */
         StreamReader ftpReader = new StreamReader(FtpStream);
         /* Store the Raw Response */
         string directoryRaw = null;
         /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
         try { while (ftpReader.Peek() != -1)
               {
                   directoryRaw += ftpReader.ReadLine() + "|";
               }
         }
         finally
         {  /* Resource Cleanup */
             ftpReader.Close();
         }
         /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
         return(directoryRaw.Split("|".ToCharArray()));
     }
     finally
     {
         FtpStream.Close();
         FtpResponse.Close();
         FtpRequest = null;
     }
 }
 /// <summary>
 /// Populates the capabilities flags based on capabilities
 /// supported by this server. This method is overridable
 /// so that new features can be supported
 /// </summary>
 /// <param name="reply">The reply object from the FEAT command. The InfoMessages property will
 /// contain a list of the features the server supported delimited by a new line '\n' character.</param>
 internal void ParseFeatures(FtpResponse reply)
 {
     foreach (string feat in reply.InfoMessages.Split(new [] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
     {
         if (feat.ToUpper().Trim().StartsWith("MLST") || feat.ToUpper().Trim().StartsWith("MLSD"))
         {
             m_Caps |= FtpCapability.MLSD;
         }
         else if (feat.ToUpper().Trim().StartsWith("MDTM"))
         {
             m_Caps |= FtpCapability.MDTM;
         }
         else if (feat.ToUpper().Trim().StartsWith("REST STREAM"))
         {
             m_Caps |= FtpCapability.REST;
         }
         else if (feat.ToUpper().Trim().StartsWith("SIZE"))
         {
             m_Caps |= FtpCapability.SIZE;
         }
         else if (feat.ToUpper().Trim().StartsWith("UTF8"))
         {
             m_Caps |= FtpCapability.UTF8;
         }
         else if (feat.ToUpper().Trim().StartsWith("PRET"))
         {
             m_Caps |= FtpCapability.PRET;
         }
         else if (feat.ToUpper().Trim().StartsWith("MFMT"))
         {
             m_Caps |= FtpCapability.MFMT;
         }
         else if (feat.ToUpper().Trim().StartsWith("MFCT"))
         {
             m_Caps |= FtpCapability.MFCT;
         }
         else if (feat.ToUpper().Trim().StartsWith("MFF"))
         {
             m_Caps |= FtpCapability.MFF;
         }
     }
 }
Beispiel #22
0
        internal IAsyncResult BeginSendCommand(int timeout, string command, AsyncCallback cb, object state)
        {
            CheckDisposed();

            if (null == command)
            {
                throw new ArgumentNullException("command", "'command' argument cannot be null");
            }

            command = AppendCRLF(command);

            SetProgress(true);
            _response = null;
            try
            {
                _socket.SendTimeout = timeout;
                byte[] cmdBytes = _encoding.GetBytes(command);

                CCSendStateObject stateObj =
                    new CCSendStateObject(timeout, cmdBytes, cb, state);
                _socket.BeginSend(cmdBytes,
                                  0,
                                  cmdBytes.Length,
                                  new AsyncCallback(this.OnEndSend),
                                  stateObj);
                return(stateObj);
            }
            catch (SocketException e)
            {
                SetProgress(false);
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch
            {
                SetProgress(false);
                CheckDisposed();
                throw;
            }
        }
        /// <inheritdoc />
        public override Task <IFtpResponse> HandlePbszAsync(long size, CancellationToken cancellationToken)
        {
            IFtpResponse response;

            var hostSelector = Connection.ConnectionServices.GetRequiredService <IFtpHostSelector>();

            if (hostSelector.SelectedHost.Certificate == null)
            {
                response = new FtpResponse(500, T("Syntax error, command unrecognized."));
            }
            else if (size != 0)
            {
                response = new FtpResponse(501, T("A protection buffer size other than 0 is not supported. Use PBSZ=0 instead."));
            }
            else
            {
                response = new FtpResponse(200, T("Protection buffer size set to {0}.", size));
            }

            return(Task.FromResult(response));
        }
Beispiel #24
0
        void SendCommandEx_End(IAsyncResult ar)
        {
            RunDTP_SO stateObj = (RunDTP_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse response = _cc.EndSendCommandEx(ar);
                if (response.IsCompletionReply)
                {
                    NSTrace.WriteLineWarning("Executing DTP: receive completion as first reply.");
                    UnlockCC(stateObj);
                    stateObj.SetCompleted();
                }
                else
                {
                    FtpClient.CheckPreliminaryResponse(response);

                    //establish connection now, if it is inbound
                    if (FtpDataConnectionType.Inbound == _currentDC.Type)
                    {
                        _currentDC.BeginEstablish(stateObj.Timeout,
                                                  new AsyncCallback(this.InboundEstablish_End),
                                                  stateObj);
                    }
                    else
                    {
                        DoRunDTP(stateObj);
                    }
                }
            }
            catch (Exception e)
            {
                HandleCatch(e, stateObj);
            }
            catch
            {
                HandleCatch(null, stateObj);
            }
        }
        public static async Task <FtpResponse> ReceiveAsync(this Socket socket,
                                                            int bufferSize,
                                                            Func <SocketAsyncEventArgs> createSocketAsyncEventArgsPredicate,
                                                            Encoding encoding,
                                                            CancellationToken cancellationToken)
        {
            var rawFtpResponse = await socket.ReceiveAsync(bufferSize,
                                                           createSocketAsyncEventArgsPredicate,
                                                           cancellationToken);

            if (!rawFtpResponse.Success)
            {
                return(FtpResponse.Failed);
            }

            var data = encoding.GetString(rawFtpResponse.Buffer,
                                          0,
                                          rawFtpResponse.Buffer.Length);
            var ftpResponse = new FtpResponse(data);

            return(ftpResponse);
        }
Beispiel #26
0
        internal void Execute(int timeout)
        {
            bool ccLocked = false;

            try
            {
                ccLocked = _cc.Lock(Timeout.Infinite);
                if (null != _client.CurrentDTP)
                {
                    //----------------------------------------
                    //In case when we have active DTP we delegate
                    //handling responses to it and here only send
                    //abort command
                    _cc.SendCommand(timeout, "ABOR");

                    //----------------------------------------
                    //Notify DTP that it should abort data
                    //connection and handle abort command
                    //
                    _client.CurrentDTP.Abort();
                }
                else
                {
                    //----------------------------------------
                    //In case there is no DTP, but user wants
                    //issue abort command we should dealing with
                    //responses here ...
                    FtpResponse response = _cc.SendCommandEx(timeout, "ABOR");
                    FtpClient.CheckCompletionResponse(response);
                }
            }
            finally
            {
                if (true == ccLocked)
                {
                    _cc.Unlock();
                }
            }
        }
        void GetDC_EndCmd(IAsyncResult ar)
        {
            GetDC_SO stateObj = (GetDC_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse response = _cc.EndSendCommandEx(ar);
                if (_passiveMode)
                {
                    if (false == response.IsCompletionReply)
                    {
                        NSTrace.WriteLineError("PASV: " + response.ToString());
                        stateObj.Exception = new FtpErrorException("Error while configuring data connection.", response);
                    }
                    else
                    {
                        IPEndPoint ep = GetPasvEndPoint(response);
                        stateObj.DC = new FtpDataConnectionOutbound(_client, ep);
                    }
                }
                else
                {
                    if (false == response.IsCompletionReply)
                    {
                        stateObj.DC.Dispose();
                        stateObj.DC = null;
                        NSTrace.WriteLineError(stateObj.Cmd + ": " + response.ToString());
                        stateObj.Exception = new FtpErrorException("Error while configure data connection.", response);
                    }
                }
            }
            catch (Exception e)
            {
                stateObj.Exception = e;
            }
            stateObj.SetCompleted();
        }
Beispiel #28
0
        void Restart_End(IAsyncResult ar)
        {
            RunDTP_SO stateObj = (RunDTP_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse res = _cc.EndSendCommandEx(ar);
                if (false == res.IsIntermediateReply)
                {
                    throw GetRestartNotSuppException(res);
                }

                //establish connection now, if it is outbound
                if (FtpDataConnectionType.Outbound == _currentDC.Type)
                {
                    _currentDC.BeginEstablish(stateObj.Timeout,
                                              new AsyncCallback(this.OutboundEstablish_End),
                                              stateObj);
                }
                else
                {
                    _cc.BeginSendCommandEx(stateObj.Timeout,
                                           stateObj.Command,
                                           new AsyncCallback(this.SendCommandEx_End),
                                           stateObj);
                }
            }
            catch (Exception e)
            {
                HandleCatch(e, stateObj);
            }
            catch
            {
                HandleCatch(null, stateObj);
            }
        }
Beispiel #29
0
        internal void Execute(int timeout)
        {
            bool ccLocked = false;

            try
            {
                ccLocked = _cc.Lock(Timeout.Infinite);
                if (null != _client.CurrentDTP)
                {
                    //----------------------------------------
                    //In case when we have active DTP we delegate
                    //handling responses to it and here only send
                    //quit command
                    _cc.SendCommand(timeout, "QUIT");

                    //----------------------------------------
                    //Notify DTP that it should handle quit
                    //issue
                    _client.CurrentDTP.Quit();
                }
                else
                {
                    //----------------------------------------
                    //In case there is no DTP, we should
                    //dealing with responses here ...
                    FtpResponse response = _cc.SendCommandEx(timeout, "QUIT");
                    FtpClient.CheckCompletionResponse(response);
                }
            }
            finally
            {
                if (true == ccLocked)
                {
                    _cc.Unlock();
                }
            }
        }
Beispiel #30
0
        void PasswordCmd_End(IAsyncResult ar)
        {
            Login_SO stateObj = (Login_SO)ar.AsyncState;

            try
            {
                stateObj.UpdateContext();
                FtpResponse response = _cc.EndSendCommandEx(ar);
                if (!response.IsCompletionReply &&
                    !response.IsIntermediateReply)
                {
                    throw GetLoginFailedException(response);
                }

                if (response.IsCompletionReply)
                {
                    stateObj.SetCompleted();
                }
                else
                {
                    if (null == stateObj.Account)
                    {
                        throw new FtpAccountRequiredException("Unable to login, account is required.", response);
                    }

                    _cc.BeginSendCommandEx(stateObj.Timeout,
                                           "ACCT " + stateObj.Account,
                                           new AsyncCallback(AccountCmd_End),
                                           stateObj);
                }
            }
            catch (Exception e)
            {
                stateObj.Exception = e;
                stateObj.SetCompleted();
            }
        }
Beispiel #31
0
        internal IAsyncResult BeginReadResponse(int timeout,
                                                AsyncCallback cb,
                                                object state)
        {
            CheckDisposed();

            CCReadStateObject stateObj = null;

            SetProgress(true);
            _response = null;
            try
            {
                stateObj = new CCReadStateObject(cb, state);
                _reader.BeginReadResponse(timeout,
                                          new AsyncCallback(this.OnResponse),
                                          stateObj);
            }
            catch (SocketException e)
            {
                SetProgress(false);
                CheckDisposed();
                CheckTimeoutException(e);
                throw;
            }
            catch
            {
                SetProgress(false);
                CheckDisposed();
                throw;
            }
            finally
            {
                _response = _reader.Response;
            }
            return(stateObj);
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="message">Exception message text.</param>
 /// <param name="response">Ftp response object.</param>
 /// <param name="innerException">The inner exception object.</param>
 public FtpDataConnectionException(string message, FtpResponse response, Exception innerException)
     : base(message, response, innerException)
 {
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="message">Exception message text.</param>
 /// <param name="response">Ftp response object.</param>
 public FtpDataConnectionException(string message, FtpResponse response)
     : base(message, response)
 {
 }
Beispiel #34
0
 /// <summary>
 ///     Constructor.
 /// </summary>
 /// <param name="message">Exception message text.</param>
 /// <param name="response">Response object.</param>
 /// <param name="innerException">The inner exception object.</param>
 public FtpException(string message, FtpResponse response, Exception innerException)
     : base(message, innerException)
 {
     _response = response;
 }
Beispiel #35
0
 /// <summary>
 ///     Constructor.
 /// </summary>
 /// <param name="message">Exception message text.</param>
 /// <param name="response">Ftp response object.</param>
 public FtpException(string message, FtpResponse response)
     : base(message)
 {
     _response = response;
 }