Esempio n. 1
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new IOExection instance.");

        try
        {
            //Create the application domain setup information.
            IOException myIOExection = new IOException();
            if (myIOExection == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "the IOExection ctor error occurred. ");
                retVal = false;
            }
            
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 2
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Create a new IOExection instance,string is empty.");

        try
        {
            string expectString = string.Empty;
            //Create the application domain setup information.
            IOException myIOExection = new IOException(expectString);
            if (myIOExection.Message != expectString)
            {
                TestLibrary.TestFramework.LogError("002.1", "the IOExection ctor error occurred. ");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path.Length == 0)
            {
                throw new ArgumentException("Path cannot be the empty string or all whitespace.", "path");
            }

            if (mockFileDataAccessor.FileExists(path))
            {
                var message = string.Format(CultureInfo.InvariantCulture, @"Cannot create ""{0}"" because a file or directory with the same name already exists.", path);
                var ex = new IOException(message);
                ex.Data.Add("Path", path);
                throw ex;
            }

            path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path));

            if (!Exists(path))
            {
                mockFileDataAccessor.AddDirectory(path);
            }

            var created = new MockDirectoryInfo(mockFileDataAccessor, path);
            return created;
        }
        public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path.Length == 0)
            {
                throw new ArgumentException(Properties.Resources.PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE, "path");
            }

            if (mockFileDataAccessor.FileExists(path))
            {
                var message = string.Format(CultureInfo.InvariantCulture, @"Cannot create ""{0}"" because a file or directory with the same name already exists.", path);
                var ex = new IOException(message);
                ex.Data.Add("Path", path);
                throw ex;
            }

            path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path));

            if (!Exists(path))
            {
                mockFileDataAccessor.AddDirectory(path);
            }

            var created = new MockDirectoryInfo(mockFileDataAccessor, path);
            return created;
        }
Esempio n. 5
0
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Create a new IOExection instance,string is null,then its inner exception set to a null reference .");

        try
        {
            string expectString =null;
            //Create the application domain setup information.
            IOException myIOExection = new IOException(expectString);
            if (myIOExection== null)
            {
                TestLibrary.TestFramework.LogError("003.1", "the IOExection ctor error occurred. ");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Esempio n. 6
0
        /// <summary>
        ///     Map a .Net IOException to the matching JSimple platform independent exception.  If there's a specific exception
        ///     type for the subclass (because it's an error we're likely to care about), return that.  Otherwise, just return a
        ///     JSimple IOException.
        /// </summary>
        public static IOException jSimpleExceptionFromDotNetIOException(System.IO.IOException e)
        {
            IOException jSimpleIOException;
            string message = e.Message ?? "";

            // TODO: Map the other exceptions
            /*
            if (e is java.net.SocketTimeoutException)
                jSimpleIOException = new SocketTimeoutException(message);
            else if (e is UnknownHostException)
                jSimpleIOException = new UnknownHostException(message);
            */
            // TODO: Include DirectoryNotFoundException for .Net apps
            if (e is System.IO.FileNotFoundException)
                jSimpleIOException = new PathNotFoundException(message, e);
            else jSimpleIOException = new IOException(message, e);

            /*
            // Replace the stack trace with the original one, so it looks like the original code threw the exception.
            // In some ways that's not technically correct, but it generally makes the stack traces easier to read
            // and more standard Java-like, since the nested exception wrapping doesn't add any real info in error output
            // and in practice tends to make error output a bit harder to understand, not easier
            StackTraceElement[] stackTrace = e.getStackTrace();
            jSimpleIOException.setStackTrace(stackTrace);
             */

            return jSimpleIOException;
        }
        public sealed override bool Bind(AssemblyName refName, out MetadataReader reader, out ScopeDefinitionHandle scopeDefinitionHandle, out IEnumerable<QScopeDefinition> overflowScopes, out Exception exception)
        {
            bool foundMatch = false;
            reader = null;
            scopeDefinitionHandle = default(ScopeDefinitionHandle);
            exception = null;
            overflowScopes = null;

            foreach (KeyValuePair<string, ScopeDefinitionGroup> group in ScopeGroups)
            {
                AssemblyName defName = new AssemblyName(group.Key);
                if (AssemblyNameMatches(refName, defName))
                {
                    if (foundMatch)
                    {
                        exception = new AmbiguousMatchException();
                        return false;
                    }

                    foundMatch = true;
                    ScopeDefinitionGroup scopeDefinitionGroup = group.Value;

                    reader = scopeDefinitionGroup.CanonicalScope.Reader;
                    scopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle;
                    overflowScopes = scopeDefinitionGroup.OverflowScopes;
                }
            }

            if (!foundMatch)
            {
                exception = new IOException(SR.Format(SR.FileNotFound_AssemblyNotFound, refName.FullName));
                return false;
            }

            return true;
        }
Esempio n. 8
0
 public static void RequestBodyIOException(HttpContext httpContext, IOException exception)
 {
     _requestBodyIOException(GetLogger(httpContext), exception);
 }
Esempio n. 9
0
        // Simpler than Flush because it will never be called at the end of the request from Dispose.
        public unsafe override Task FlushAsync(CancellationToken cancellationToken)
        {
            if (_closed)
            {
                return(Helpers.CompletedTask());
            }

            bool startedSending = _requestContext.Response.HasStartedSending;
            var  byteCount      = _buffer.TotalBytes;

            if (byteCount == 0 && startedSending)
            {
                // Empty flush
                return(Helpers.CompletedTask());
            }

            var cancellationRegistration = default(CancellationTokenRegistration);

            if (cancellationToken.CanBeCanceled)
            {
                cancellationRegistration = cancellationToken.Register(RequestContext.AbortDelegate, _requestContext);
            }

            var flags = ComputeLeftToWrite();

            if (_leftToWrite != byteCount)
            {
                flags |= HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
            }

            UpdateWritenCount((uint)byteCount);
            uint statusCode  = 0;
            var  chunked     = _requestContext.Response.BoundaryType == BoundaryType.Chunked;
            var  asyncResult = new ResponseStreamAsyncResult(this, _buffer, chunked, cancellationRegistration);
            uint bytesSent   = 0;

            try
            {
                if (!startedSending)
                {
                    statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false);
                    bytesSent  = asyncResult.BytesSent;
                }
                else
                {
                    statusCode = HttpApi.HttpSendResponseEntityBody(
                        _requestContext.RequestQueueHandle,
                        _requestContext.RequestId,
                        (uint)flags,
                        asyncResult.DataChunkCount,
                        asyncResult.DataChunks,
                        &bytesSent,
                        SafeLocalFree.Zero,
                        0,
                        asyncResult.NativeOverlapped,
                        IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                LogHelper.LogException(_requestContext.Logger, "FlushAsync", e);
                asyncResult.Dispose();
                Abort();
                throw;
            }

            if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_IO_PENDING)
            {
                asyncResult.Dispose();
                if (_requestContext.Server.IgnoreWriteExceptions && startedSending)
                {
                    asyncResult.Complete();
                }
                else
                {
                    Exception exception = new IOException(string.Empty, new WebListenerException((int)statusCode));
                    LogHelper.LogException(_requestContext.Logger, "FlushAsync", exception);
                    Abort();
                    throw exception;
                }
            }

            if (statusCode == ErrorCodes.ERROR_SUCCESS && WebListener.SkipIOCPCallbackOnSuccess)
            {
                // IO operation completed synchronously - callback won't be called to signal completion.
                asyncResult.IOCompleted(statusCode, bytesSent);
            }

            // Last write, cache it for special cancellation handling.
            if ((flags & HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0)
            {
                _lastWrite = asyncResult;
            }

            return(asyncResult.Task);
        }
Esempio n. 10
0
        // Simpler than Flush because it will never be called at the end of the request from Dispose.
        private unsafe Task FlushInternalAsync(ArraySegment <byte> data, CancellationToken cancellationToken)
        {
            if (_skipWrites)
            {
                return(Task.CompletedTask);
            }

            var started = _requestContext.Response.HasStarted;

            if (data.Count == 0 && started)
            {
                // No data to send and we've already sent the headers
                return(Task.CompletedTask);
            }

            if (cancellationToken.IsCancellationRequested)
            {
                Abort(ThrowWriteExceptions);
                return(Task.FromCanceled <int>(cancellationToken));
            }

            // Make sure all validation is performed before this computes the headers
            var  flags       = ComputeLeftToWrite(data.Count);
            uint statusCode  = 0;
            var  chunked     = _requestContext.Response.BoundaryType == BoundaryType.Chunked;
            var  asyncResult = new ResponseStreamAsyncResult(this, data, chunked, cancellationToken);
            uint bytesSent   = 0;

            try
            {
                if (!started)
                {
                    statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false);
                    bytesSent  = asyncResult.BytesSent;
                }
                else
                {
                    statusCode = HttpApi.HttpSendResponseEntityBody(
                        RequestQueueHandle,
                        RequestId,
                        (uint)flags,
                        asyncResult.DataChunkCount,
                        asyncResult.DataChunks,
                        &bytesSent,
                        IntPtr.Zero,
                        0,
                        asyncResult.NativeOverlapped,
                        IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                Logger.LogError(0, e, "FlushAsync");
                asyncResult.Dispose();
                Abort();
                throw;
            }

            if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_IO_PENDING)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Logger.LogDebug($"FlushAsync; Write cancelled with error code: {statusCode}");
                    asyncResult.Cancel(ThrowWriteExceptions);
                }
                else if (ThrowWriteExceptions)
                {
                    asyncResult.Dispose();
                    Exception exception = new IOException(string.Empty, new HttpSysException((int)statusCode));
                    Logger.LogError(0, exception, "FlushAsync");
                    Abort();
                    throw exception;
                }
                else
                {
                    // Abort the request but do not close the stream, let future writes complete silently
                    Logger.LogDebug($"FlushAsync; Ignored write exception: {statusCode}");
                    asyncResult.FailSilently();
                }
            }

            if (statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess)
            {
                // IO operation completed synchronously - callback won't be called to signal completion.
                asyncResult.IOCompleted(statusCode, bytesSent);
            }

            // Last write, cache it for special cancellation handling.
            if ((flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0)
            {
                _lastWrite = asyncResult;
            }

            return(asyncResult.Task);
        }
Esempio n. 11
0
 /// <summary>
 /// Return true if the <see cref="IOException"/> is the result of a share violation
 /// </summary>
 private bool IsShareViolation(IOException e)
 {
     return(e.HResult == NativeFSLockFactory.HRESULT_FILE_SHARE_VIOLATION);
 }
        private async Task DoSendAsync()
        {
            Exception error = null;

            DebugLog("starting send loop");
            try
            {
                while (true)
                {
                    DebugLog("awaiting data from pipe...");
                    if (_sendToSocket.Reader.TryRead(out var result))
                    {
                        Helpers.Incr(Counter.SocketPipeReadReadSync);
                    }
                    else
                    {
                        Helpers.Incr(Counter.OpenSendReadAsync);
                        var read = _sendToSocket.Reader.ReadAsync();
                        Helpers.Incr(read.IsCompleted ? Counter.SocketPipeReadReadSync : Counter.SocketPipeReadReadAsync);
                        result = await read;
                        Helpers.Decr(Counter.OpenSendReadAsync);
                    }
                    var buffer = result.Buffer;

                    if (result.IsCanceled || (result.IsCompleted && buffer.IsEmpty))
                    {
                        DebugLog(result.IsCanceled ? "cancelled" : "complete");
                        break;
                    }

                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            if (_writerArgs == null)
                            {
                                _writerArgs = new SocketAwaitableEventArgs(InlineWrites ? null : _sendOptions.ReaderScheduler);
                            }
                            DebugLog($"sending {buffer.Length} bytes over socket...");
                            Helpers.Incr(Counter.OpenSendWriteAsync);
                            DoSend(Socket, _writerArgs, buffer, Name);
                            Helpers.Incr(_writerArgs.IsCompleted ? Counter.SocketSendAsyncSync : Counter.SocketSendAsyncAsync);
                            Interlocked.Add(ref _totalBytesSent, await _writerArgs);
                            Helpers.Decr(Counter.OpenSendWriteAsync);
                        }
                        else if (result.IsCompleted)
                        {
                            DebugLog("completed");
                            break;
                        }
                    }
                    finally
                    {
                        DebugLog("advancing");
                        _sendToSocket.Reader.AdvanceTo(buffer.End);
                    }
                }
                TrySetShutdown(PipeShutdownKind.WriteEndOfStream);
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted)
            {
                TrySetShutdown(PipeShutdownKind.WriteSocketError, ex.SocketErrorCode);
                DebugLog($"fail: {ex.SocketErrorCode}");
                error = null;
            }
            catch (SocketException ex)
            {
                TrySetShutdown(PipeShutdownKind.WriteSocketError, ex.SocketErrorCode);
                DebugLog($"fail: {ex.SocketErrorCode}");
                error = ex;
            }
            catch (ObjectDisposedException)
            {
                TrySetShutdown(PipeShutdownKind.WriteDisposed);
                DebugLog("fail: disposed");
                error = null;
            }
            catch (IOException ex)
            {
                TrySetShutdown(PipeShutdownKind.WriteIOException);
                DebugLog($"fail - io: {ex.Message}");
                error = ex;
            }
            catch (Exception ex)
            {
                TrySetShutdown(PipeShutdownKind.WriteException);
                DebugLog($"fail: {ex.Message}");
                error = new IOException(ex.Message, ex);
            }
            finally
            {
                // Make sure to close the connection only after the _aborted flag is set.
                // Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when
                // a BadHttpRequestException is thrown instead of a TaskCanceledException.
                _sendAborted = true;
                try
                {
                    DebugLog($"shutting down socket-send");
                    Socket.Shutdown(SocketShutdown.Send);
                }
                catch { }

                // close *both halves* of the send pipe; we're not
                // listening *and* we don't want anyone trying to write
                DebugLog($"marking {nameof(Output)} as complete");
                try { _sendToSocket.Writer.Complete(error); } catch { }
                try { _sendToSocket.Reader.Complete(error); } catch { }

                var args = _writerArgs;
                _writerArgs = null;
                if (args != null)
                {
                    try { args.Dispose(); } catch { }
                }
            }
            DebugLog(error == null ? "exiting with success" : $"exiting with failure: {error.Message}");
            //return error;
        }
Esempio n. 13
0
 public virtual string ErrorReadingResponseFile(string filePath, IOException e) =>
 $"Error reading response file '{filePath}': {e.Message}";
Esempio n. 14
0
        /// <summary>
        /// Helper method that reads CFS entries from an input stream </summary>
        private static IDictionary <string, FileEntry> ReadEntries(IndexInputSlicer handle, Directory dir, string name)
        {
            IOException        priorE        = null;
            IndexInput         stream        = null;
            ChecksumIndexInput entriesStream = null;

            // read the first VInt. If it is negative, it's the version number
            // otherwise it's the count (pre-3.1 indexes)
            try
            {
                IDictionary <string, FileEntry> mapping;
#pragma warning disable 612, 618
                stream = handle.OpenFullSlice();
#pragma warning restore 612, 618
                int firstInt = stream.ReadVInt32();
                // impossible for 3.0 to have 63 files in a .cfs, CFS writer was not visible
                // and separate norms/etc are outside of cfs.
                if (firstInt == CODEC_MAGIC_BYTE1)
                {
                    sbyte secondByte = (sbyte)stream.ReadByte();
                    sbyte thirdByte  = (sbyte)stream.ReadByte();
                    sbyte fourthByte = (sbyte)stream.ReadByte();
                    if (secondByte != CODEC_MAGIC_BYTE2 || thirdByte != CODEC_MAGIC_BYTE3 || fourthByte != CODEC_MAGIC_BYTE4)
                    {
                        throw new CorruptIndexException("Illegal/impossible header for CFS file: " + secondByte + "," + thirdByte + "," + fourthByte);
                    }
                    int    version         = CodecUtil.CheckHeaderNoMagic(stream, CompoundFileWriter.DATA_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT);
                    string entriesFileName = IndexFileNames.SegmentFileName(
                        IndexFileNames.StripExtension(name), "",
                        IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION);
                    entriesStream = dir.OpenChecksumInput(entriesFileName, IOContext.READ_ONCE);
                    CodecUtil.CheckHeader(entriesStream, CompoundFileWriter.ENTRY_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT);
                    int numEntries = entriesStream.ReadVInt32();
                    mapping = new Dictionary <string, FileEntry>(numEntries);
                    for (int i = 0; i < numEntries; i++)
                    {
                        FileEntry fileEntry = new FileEntry();
                        string    id        = entriesStream.ReadString();
                        FileEntry previous  = mapping.Put(id, fileEntry);
                        if (previous != null)
                        {
                            throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + entriesStream);
                        }
                        fileEntry.Offset = entriesStream.ReadInt64();
                        fileEntry.Length = entriesStream.ReadInt64();
                    }
                    if (version >= CompoundFileWriter.VERSION_CHECKSUM)
                    {
                        CodecUtil.CheckFooter(entriesStream);
                    }
                    else
                    {
#pragma warning disable 612, 618
                        CodecUtil.CheckEOF(entriesStream);
#pragma warning restore 612, 618
                    }
                }
                else
                {
                    // TODO remove once 3.x is not supported anymore
                    mapping = ReadLegacyEntries(stream, firstInt);
                }
                return(mapping);
            }
            catch (IOException ioe)
            {
                priorE = ioe;
            }
            finally
            {
                IOUtils.DisposeWhileHandlingException(priorE, stream, entriesStream);
            }
            // this is needed until Java 7's real try-with-resources:
            throw new InvalidOperationException("impossible to get here");
        }
Esempio n. 15
0
		//
		// Complete the I/O operation.
		//
		
		internal void OnComplete(int result, IOException error) {
			_result = result;
			_error = error;
			_isCompleted = true;
            Thread.MemoryBarrier();
			if (_waitEvent != null)
				_waitEvent.Set();
			if (_userCallback != null)
				_userCallback(this);				
		}
        private async Task <Tuple <bool, Stream> > ResumeDownloadAsync(string remotePath, Stream downStream, long offset, IOException ex)
        {
            // resume if server disconnects midway (fixes #39 and #410)
            if (ex.InnerException != null || ex.Message.IsKnownError(unexpectedEOFStrings))
            {
                var ie = ex.InnerException as SocketException;
#if CORE
                if (ie == null || ie != null && (int)ie.SocketErrorCode == 10054)
                {
#else
                if (ie == null || ie != null && ie.ErrorCode == 10054)
                {
#endif
                    downStream.Dispose();
                    return(Tuple.Create(true, await OpenReadAsync(remotePath, DownloadDataType, offset)));
                }
            }

            return(Tuple.Create(false, (Stream)null));
        }
#endif

        #endregion
    }
        public void Oneway(Command command)
        {
            Exception error = null;

            lock (reconnectMutex)
            {
                if (IsShutdownCommand(command) && ConnectedTransport == null)
                {
                    if (command.IsShutdownInfo)
                    {
                        // Skipping send of ShutdownInfo command when not connected.
                        return;
                    }

                    if (command is RemoveInfo)
                    {
                        // Simulate response to RemoveInfo command
                        Response response = new Response();
                        response.CorrelationId = command.CommandId;
                        OnCommand(this, response);
                        return;
                    }
                }

                // Keep trying until the message is sent.
                for (int i = 0; !disposed; i++)
                {
                    try
                    {
                        // Wait for transport to be connected.
                        ITransport transport = ConnectedTransport;
                        while (transport == null && !disposed && connectionFailure == null)
                        {
                            Tracer.Info("Waiting for transport to reconnect.");
                            // Release so that the reconnect task can run
                            try
                            {
                                // Wait for something
                                Monitor.Wait(reconnectMutex, 1000);
                            }
                            catch (ThreadInterruptedException e)
                            {
                                Tracer.DebugFormat("Interrupted: {0}", e.Message);
                            }

                            transport = ConnectedTransport;
                        }

                        if (transport == null)
                        {
                            // Previous loop may have exited due to use being disposed.
                            if (disposed)
                            {
                                error = new IOException("Transport disposed.");
                            }
                            else if (connectionFailure != null)
                            {
                                error = connectionFailure;
                            }
                            else
                            {
                                error = new IOException("Unexpected failure.");
                            }
                            break;
                        }

                        // If it was a request and it was not being tracked by
                        // the state tracker, then hold it in the requestMap so
                        // that we can replay it later.
                        Tracked tracked = stateTracker.track(command);
                        lock (((ICollection)requestMap).SyncRoot)
                        {
                            if (tracked != null && tracked.WaitingForResponse)
                            {
                                requestMap.Add(command.CommandId, tracked);
                            }
                            else if (tracked == null && command.ResponseRequired)
                            {
                                requestMap.Add(command.CommandId, command);
                            }
                        }

                        // Send the message.
                        try
                        {
                            transport.Oneway(command);
                            stateTracker.trackBack(command);
                        }
                        catch (Exception e)
                        {
                            // If the command was not tracked.. we will retry in
                            // this method
                            if (tracked == null)
                            {
                                // since we will retry in this method.. take it
                                // out of the request map so that it is not
                                // sent 2 times on recovery
                                if (command.ResponseRequired)
                                {
                                    lock (((ICollection)requestMap).SyncRoot)
                                    {
                                        requestMap.Remove(command.CommandId);
                                    }
                                }

                                // Rethrow the exception so it will handled by
                                // the outer catch
                                throw e;
                            }
                        }

                        return;
                    }
                    catch (Exception e)
                    {
                        Tracer.DebugFormat("Send Oneway attempt: {0} failed: Message = {1}", i, e.Message);
                        Tracer.DebugFormat("Failed Message Was: {0}", command);
                        HandleTransportFailure(e);
                    }
                }
            }

            if (!disposed)
            {
                if (error != null)
                {
                    throw error;
                }
            }
        }
        private bool ResumeDownload(string remotePath, ref Stream downStream, long offset, IOException ex)
        {
            // resume if server disconnects midway (fixes #39 and #410)
            if (ex.InnerException != null || ex.Message.IsKnownError(unexpectedEOFStrings))
            {
                var ie = ex.InnerException as SocketException;
#if CORE
                if (ie == null || ie != null && (int)ie.SocketErrorCode == 10054)
                {
#else
                if (ie == null || ie != null && ie.ErrorCode == 10054)
                {
#endif
                    downStream.Dispose();
                    downStream = OpenRead(remotePath, DownloadDataType, offset);
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 19
0
        private async Task OnProcessExited()
        {
            // Wait until all incoming report messages from the detoured process have been handled.
            await WaitUntilReportEof(m_detouredProcess.Killed);

            // Ensure no further modifications to the report
            m_reports?.Freeze();

            // We can get extended accounting information (peak memory, etc. rolled up for the entire process tree) if this process was wrapped in a job.
            JobObject.AccountingInformation?jobAccountingInformation = null;
            JobObject jobObject = m_detouredProcess.GetJobObject();

            if (jobObject != null)
            {
                jobAccountingInformation = jobObject.GetAccountingInformation(Convert.ToUInt64(m_peakWorkingSet.Maximum), Convert.ToUInt64(m_peakPagefileUsage.Maximum));
            }

            ProcessTimes primaryProcessTimes = m_detouredProcess.GetTimesForPrimaryProcess();

            IOException standardInputException = null;

            try
            {
                await m_standardInputTcs.Task;
            }
            catch (IOException ex)
            {
                standardInputException = ex;
            }

            // Construct result; note that the process is expected to have exited at this point, even if we decided to forcefully kill it
            // (this callback is always a result of the process handle being signaled).
            int exitCode = 0;

            if (m_reports?.MessageProcessingFailure != null)
            {
                exitCode = ExitCodes.MessageProcessingFailure;
            }
            else
            {
                Contract.Assert(m_detouredProcess.HasExited, "Detoured process has not been marked as exited");
                exitCode = m_detouredProcess.GetExitCode();
            }

            SandboxedProcessResult result =
                new SandboxedProcessResult
            {
                // If there is a message parsing failure, fail the pip.
                ExitCode = exitCode,
                Killed   = m_detouredProcess.Killed,
                TimedOut = m_detouredProcess.TimedOut,
                HasDetoursInjectionFailures = m_detouredProcess.HasDetoursInjectionFailures,
                SurvivingChildProcesses     = m_survivingChildProcesses?.Values.ToArray(),
                PrimaryProcessTimes         = primaryProcessTimes,
                JobAccountingInformation    = jobAccountingInformation,
                StandardOutput            = m_output.Freeze(),
                StandardError             = m_error.Freeze(),
                AllUnexpectedFileAccesses = m_reports?.FileUnexpectedAccesses,
                FileAccesses      = m_reports?.FileAccesses,
                DetouringStatuses = m_reports?.ProcessDetoursStatuses,
                ExplicitlyReportedFileAccesses = m_reports?.ExplicitlyReportedFileAccesses,
                Processes                           = m_reports?.Processes,
                DumpFileDirectory                   = m_detouredProcess.DumpFileDirectory,
                DumpCreationException               = m_detouredProcess.DumpCreationException,
                StandardInputException              = standardInputException,
                MessageProcessingFailure            = m_reports?.MessageProcessingFailure,
                ProcessStartTime                    = m_detouredProcess.StartTime,
                HasReadWriteToReadFileAccessRequest = m_reports?.HasReadWriteToReadFileAccessRequest ?? false,
            };

            SetResult(result);
        }
Esempio n. 20
0
 /// <summary>
 /// Defines the action, if any, to be taken if an IOException occurs when trying to load a configuration.
 /// </summary>
 protected abstract T HandleIOException(IOException ex);
Esempio n. 21
0
 public void OnLoadError(int sourceId, IOException e)
 {
     if (_internalErrorListener != null)
     {
         _internalErrorListener.OnLoadError(sourceId, e);
     }
 }
Esempio n. 22
0
        public virtual void TestRandomPhrases()
        {
            Directory dir      = NewDirectory();
            Analyzer  analyzer = new MockAnalyzer(Random());

            RandomIndexWriter       w    = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetMergePolicy(NewLogMergePolicy()));
            IList <IList <string> > docs = new List <IList <string> >();

            Documents.Document d = new Documents.Document();
            Field f = NewTextField("f", "", Field.Store.NO);

            d.Add(f);

            Random r = Random();

            int NUM_DOCS = AtLeast(10);

            for (int i = 0; i < NUM_DOCS; i++)
            {
                // must be > 4096 so it spans multiple chunks
                int termCount = TestUtil.NextInt(Random(), 4097, 8200);

                IList <string> doc = new List <string>();

                StringBuilder sb = new StringBuilder();
                while (doc.Count < termCount)
                {
                    if (r.Next(5) == 1 || docs.Count == 0)
                    {
                        // make new non-empty-string term
                        string term;
                        while (true)
                        {
                            term = TestUtil.RandomUnicodeString(r);
                            if (term.Length > 0)
                            {
                                break;
                            }
                        }
                        IOException priorException = null;
                        TokenStream ts             = analyzer.TokenStream("ignore", new StringReader(term));
                        try
                        {
                            ICharTermAttribute termAttr = ts.AddAttribute <ICharTermAttribute>();
                            ts.Reset();
                            while (ts.IncrementToken())
                            {
                                string text = termAttr.ToString();
                                doc.Add(text);
                                sb.Append(text).Append(' ');
                            }
                            ts.End();
                        }
                        catch (IOException e)
                        {
                            priorException = e;
                        }
                        finally
                        {
                            IOUtils.CloseWhileHandlingException(priorException, ts);
                        }
                    }
                    else
                    {
                        // pick existing sub-phrase
                        IList <string> lastDoc = docs[r.Next(docs.Count)];
                        int            len     = TestUtil.NextInt(r, 1, 10);
                        int            start   = r.Next(lastDoc.Count - len);
                        for (int k = start; k < start + len; k++)
                        {
                            string t = lastDoc[k];
                            doc.Add(t);
                            sb.Append(t).Append(' ');
                        }
                    }
                }
                docs.Add(doc);
                f.StringValue = sb.ToString();
                w.AddDocument(d);
            }

            IndexReader   reader = w.Reader;
            IndexSearcher s      = NewSearcher(reader);

            w.Dispose();

            // now search
            int num = AtLeast(10);

            for (int i = 0; i < num; i++)
            {
                int            docID = r.Next(docs.Count);
                IList <string> doc   = docs[docID];

                int           numTerm = TestUtil.NextInt(r, 2, 20);
                int           start   = r.Next(doc.Count - numTerm);
                PhraseQuery   pq      = new PhraseQuery();
                StringBuilder sb      = new StringBuilder();
                for (int t = start; t < start + numTerm; t++)
                {
                    pq.Add(new Term("f", doc[t]));
                    sb.Append(doc[t]).Append(' ');
                }

                TopDocs hits  = s.Search(pq, NUM_DOCS);
                bool    found = false;
                for (int j = 0; j < hits.ScoreDocs.Length; j++)
                {
                    if (hits.ScoreDocs[j].Doc == docID)
                    {
                        found = true;
                        break;
                    }
                }

                Assert.IsTrue(found, "phrase '" + sb + "' not found; start=" + start);
            }

            reader.Dispose();
            dir.Dispose();
        }
Esempio n. 23
0
        internal unsafe Task SendFileAsyncCore(string fileName, long offset, long?count, CancellationToken cancellationToken)
        {
            _requestContext.Response.Start();
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
            if (count == 0 && _leftToWrite != 0)
            {
                return(Helpers.CompletedTask());
            }
            if (_leftToWrite >= 0 && count > _leftToWrite)
            {
                throw new InvalidOperationException(Resources.Exception_TooMuchWritten);
            }
            // TODO: Verbose log

            if (cancellationToken.IsCancellationRequested)
            {
                return(Helpers.CanceledTask <int>());
            }

            var cancellationRegistration = default(CancellationTokenRegistration);

            if (cancellationToken.CanBeCanceled)
            {
                cancellationRegistration = cancellationToken.Register(RequestContext.AbortDelegate, _requestContext);
            }

            uint statusCode;
            uint bytesSent      = 0;
            bool startedSending = _requestContext.Response.HasStartedSending;
            var  chunked        = _requestContext.Response.BoundaryType == BoundaryType.Chunked;
            ResponseStreamAsyncResult asyncResult = new ResponseStreamAsyncResult(this, fileName, offset, count, chunked, cancellationRegistration);

            long bytesWritten;

            if (chunked)
            {
                bytesWritten = 0;
            }
            else if (count.HasValue)
            {
                bytesWritten = count.Value;
            }
            else
            {
                bytesWritten = asyncResult.FileLength - offset;
            }
            // Update _leftToWrite now so we can queue up additional calls to SendFileAsync.
            flags |= _leftToWrite == bytesWritten ? HttpApi.HTTP_FLAGS.NONE : HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
            UpdateWritenCount((uint)bytesWritten);

            try
            {
                if (!startedSending)
                {
                    statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false);
                    bytesSent  = asyncResult.BytesSent;
                }
                else
                {
                    // TODO: If opaque then include the buffer data flag.
                    statusCode = HttpApi.HttpSendResponseEntityBody(
                        _requestContext.RequestQueueHandle,
                        _requestContext.RequestId,
                        (uint)flags,
                        asyncResult.DataChunkCount,
                        asyncResult.DataChunks,
                        &bytesSent,
                        SafeLocalFree.Zero,
                        0,
                        asyncResult.NativeOverlapped,
                        IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                LogHelper.LogException(_requestContext.Logger, "SendFileAsync", e);
                asyncResult.Dispose();
                Abort();
                throw;
            }

            if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
            {
                asyncResult.Dispose();
                if (_requestContext.Server.IgnoreWriteExceptions && startedSending)
                {
                    asyncResult.Complete();
                }
                else
                {
                    Exception exception = new IOException(string.Empty, new WebListenerException((int)statusCode));
                    LogHelper.LogException(_requestContext.Logger, "SendFileAsync", exception);
                    Abort();
                    throw exception;
                }
            }

            if (statusCode == ErrorCodes.ERROR_SUCCESS && WebListener.SkipIOCPCallbackOnSuccess)
            {
                // IO operation completed synchronously - callback won't be called to signal completion.
                asyncResult.IOCompleted(statusCode, bytesSent);
            }

            // Last write, cache it for special cancellation handling.
            if ((flags & HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0)
            {
                _lastWrite = asyncResult;
            }

            return(asyncResult.Task);
        }
Esempio n. 24
0
        /*
         * open JSON file and store stdin value in dictionaries in preparation of output
         * TODO
         * test building objects with serializeTasks storing objects in dictionaries
         * so they are ready for stdout
         */
        public static void SetStreamIn(string p)
        {
            try
            {
                //open file using stream reader
                using (StreamReader r = File.OpenText(p))
                {
                    //read entire file content
                    string json = r.ReadToEnd();
                    string name = "";
                    string app  = "";
                    string vers = "";
                    string role = "";
                    string loc  = "";

                    //parse to object using string
                    JObject jobj = JObject.Parse(json);

                    //iterate through object to gather key values
                    foreach (JProperty property in jobj.Properties())
                    {
                        name = "node" + (count);

                        //check for null values and skip them if they aren't used
                        //values based upon sample data of known input
                        //node values increment real values would likely need the program to find the name of the initial key
                        if (jobj.SelectToken(name + ".application") != null)
                        {
                            app = jobj.SelectToken(name + ".application").ToString();

                            appType.Add(countApp, app);
                            countApp++;
                        }
                        if (jobj.SelectToken(name + ".version") != null)
                        {
                            vers = (string)jobj.SelectToken(name + ".version");

                            version.Add(countVer, vers);
                            countVer++;
                        }
                        if (jobj.SelectToken(name + ".role") != null)
                        {
                            role = (string)jobj.SelectToken(name + ".role");

                            roleType.Add(countRole, role);
                            countRole++;
                        }
                        if (jobj.SelectToken(name + ".location") != null)
                        {
                            loc = (string)jobj.SelectToken(name + ".location");

                            location.Add(countLoc, loc);
                            countLoc++;
                        }
                        count++;
                    }
                }
            }
            catch (IOException ex)
            {
                IOException except = new IOException("An I/O error occurred while opening the file.", ex);
                throw except;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 25
0
        private async void OnRead(UvStreamHandle handle, int status)
        {
            if (status == 0)
            {
                // A zero status does not indicate an error or connection end. It indicates
                // there is no data to be read right now.
                // See the note at http://docs.libuv.org/en/v1.x/stream.html#c.uv_read_cb.
                _inputBuffer?.Commit();
                _inputBuffer = null;
                UnpinInputBuffer();

                return;
            }

            var normalRead = status > 0;
            var normalDone = status == EOF;
            var errorDone  = !(normalDone || normalRead);
            var readCount  = normalRead ? status : 0;

            if (!normalRead)
            {
                handle.ReadStop();
            }

            IOException error = null;

            if (errorDone)
            {
                handle.Libuv.Check(status, out Exception uvError);
                error = new IOException(uvError.Message, uvError);

                _inputBuffer?.Commit();
                UnpinInputBuffer();

                // REVIEW: Should we treat ECONNRESET as an error?
                // Ignore the error for now
                _input.Writer.Complete();
            }
            else
            {
                var inputBuffer = _inputBuffer.Value;

                _inputBuffer = null;

                inputBuffer.Advance(readCount);
                inputBuffer.Commit();
                UnpinInputBuffer();

                // Flush if there was data
                if (readCount > 0)
                {
                    var awaitable = inputBuffer.FlushAsync();

                    if (!awaitable.IsCompleted)
                    {
                        // If there's back pressure
                        handle.ReadStop();

                        // Resume reading when the awaitable completes
                        var flushResult = await awaitable;
                        if (!flushResult.IsCompleted)
                        {
                            StartReading();
                        }
                        else
                        {
                            // We're done writing, the reading is gone
                            _input.Writer.Complete();
                        }
                    }
                }
            }

            if (normalDone)
            {
                _input.Writer.Complete();
            }
        }
 public ConnectionRefusedEventArgs(IOException cause)
 {
     Cause = cause;
 }
Esempio n. 27
0
 public virtual void ReportError(IOException e)
 {
     ErrorManager.InternalError(e);
 }
Esempio n. 28
0
        private static bool ExceptionForLockedFile(IOException exception)
        {
            int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);

            return(errorCode == 32 || errorCode == 33);
        }
Esempio n. 29
0
        // We never expect endOfRequest and data at the same time
        private unsafe void FlushInternal(bool endOfRequest, ArraySegment <byte> data = new ArraySegment <byte>())
        {
            Debug.Assert(!(endOfRequest && data.Count > 0), "Data is not supported at the end of the request.");

            if (_skipWrites)
            {
                return;
            }

            var started = _requestContext.Response.HasStarted;

            if (data.Count == 0 && started && !endOfRequest)
            {
                // No data to send and we've already sent the headers
                return;
            }

            // Make sure all validation is performed before this computes the headers
            var flags = ComputeLeftToWrite(data.Count, endOfRequest);

            if (endOfRequest && _leftToWrite > 0)
            {
                if (!RequestContext.DisconnectToken.IsCancellationRequested)
                {
                    // This is logged rather than thrown because it is too late for an exception to be visible in user code.
                    Logger.LogError("ResponseStream::Dispose; Fewer bytes were written than were specified in the Content-Length.");
                }
                _requestContext.Abort();
                return;
            }

            uint statusCode = 0;

            HttpApiTypes.HTTP_DATA_CHUNK[] dataChunks;
            var pinnedBuffers = PinDataBuffers(endOfRequest, data, out dataChunks);

            try
            {
                if (!started)
                {
                    statusCode = _requestContext.Response.SendHeaders(dataChunks, null, flags, false);
                }
                else
                {
                    fixed(HttpApiTypes.HTTP_DATA_CHUNK *pDataChunks = dataChunks)
                    {
                        statusCode = HttpApi.HttpSendResponseEntityBody(
                            RequestQueueHandle,
                            RequestId,
                            (uint)flags,
                            (ushort)dataChunks.Length,
                            pDataChunks,
                            null,
                            IntPtr.Zero,
                            0,
                            SafeNativeOverlapped.Zero,
                            IntPtr.Zero);
                    }
                }
            }
            finally
            {
                FreeDataBuffers(pinnedBuffers);
            }

            if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_HANDLE_EOF
                // Don't throw for disconnects, we were already finished with the response.
                && (!endOfRequest || (statusCode != ErrorCodes.ERROR_CONNECTION_INVALID && statusCode != ErrorCodes.ERROR_INVALID_PARAMETER)))
            {
                if (ThrowWriteExceptions)
                {
                    var exception = new IOException(string.Empty, new HttpSysException((int)statusCode));
                    Logger.LogError(0, exception, "Flush");
                    Abort();
                    throw exception;
                }
                else
                {
                    // Abort the request but do not close the stream, let future writes complete silently
                    Logger.LogDebug($"Flush; Ignored write exception: {statusCode}");
                    Abort(dispose: false);
                }
            }
        }
Esempio n. 30
0
            public void OnTimestampError(UtcTimingElement utcTiming, IOException e)
            {
                if (_canceled)
                {
                    return;
                }

                Log.Error(Tag, "Failed to resolve UtcTiming element [" + utcTiming + "]", e);
                // Be optimistic and continue in the hope that the device clock is correct.
                BuildRenderers();
            }
Esempio n. 31
0
        internal unsafe Task SendFileAsyncCore(string fileName, long offset, long?count, CancellationToken cancellationToken)
        {
            if (_skipWrites)
            {
                return(Task.CompletedTask);
            }

            var started = _requestContext.Response.HasStarted;

            if (count == 0 && started)
            {
                // No data to send and we've already sent the headers
                return(Task.CompletedTask);
            }

            if (cancellationToken.IsCancellationRequested)
            {
                Abort(ThrowWriteExceptions);
                return(Task.FromCanceled <int>(cancellationToken));
            }

            // We are setting buffer size to 1 to prevent FileStream from allocating it's internal buffer
            // It's too expensive to validate anything before opening the file. Open the file and then check the lengths.
            var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1,
                                            options: FileOptions.Asynchronous | FileOptions.SequentialScan); // Extremely expensive.

            try
            {
                var length = fileStream.Length; // Expensive, only do it once
                if (!count.HasValue)
                {
                    count = length - offset;
                }
                if (offset < 0 || offset > length)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
                }
                if (count < 0 || count > length - offset)
                {
                    throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
                }

                CheckWriteCount(count);
            }
            catch
            {
                fileStream.Dispose();
                throw;
            }

            // Make sure all validation is performed before this computes the headers
            var  flags = ComputeLeftToWrite(count.Value);
            uint statusCode;
            uint bytesSent   = 0;
            var  chunked     = _requestContext.Response.BoundaryType == BoundaryType.Chunked;
            var  asyncResult = new ResponseStreamAsyncResult(this, fileStream, offset, count.Value, chunked, cancellationToken);

            try
            {
                if (!started)
                {
                    statusCode = _requestContext.Response.SendHeaders(null, asyncResult, flags, false);
                    bytesSent  = asyncResult.BytesSent;
                }
                else
                {
                    // TODO: If opaque then include the buffer data flag.
                    statusCode = HttpApi.HttpSendResponseEntityBody(
                        RequestQueueHandle,
                        RequestId,
                        (uint)flags,
                        asyncResult.DataChunkCount,
                        asyncResult.DataChunks,
                        &bytesSent,
                        IntPtr.Zero,
                        0,
                        asyncResult.NativeOverlapped,
                        IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                Logger.LogError(0, e, "SendFileAsync");
                asyncResult.Dispose();
                Abort();
                throw;
            }

            if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Logger.LogDebug($"SendFileAsync; Write cancelled with error code: {statusCode}");
                    asyncResult.Cancel(ThrowWriteExceptions);
                }
                else if (ThrowWriteExceptions)
                {
                    asyncResult.Dispose();
                    var exception = new IOException(string.Empty, new HttpSysException((int)statusCode));
                    Logger.LogError(0, exception, "SendFileAsync");
                    Abort();
                    throw exception;
                }
                else
                {
                    // Abort the request but do not close the stream, let future writes complete silently
                    Logger.LogDebug($"SendFileAsync; Ignored write exception: {statusCode}");
                    asyncResult.FailSilently();
                }
            }

            if (statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess)
            {
                // IO operation completed synchronously - callback won't be called to signal completion.
                asyncResult.IOCompleted(statusCode, bytesSent);
            }

            // Last write, cache it for special cancellation handling.
            if ((flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0)
            {
                _lastWrite = asyncResult;
            }

            return(asyncResult.Task);
        }
 // DemoPlayer.InternalErrorListener
 public void OnLoadError(int sourceId, IOException e)
 {
     PrintInternalError("loadError", e);
 }
Esempio n. 33
0
 public static void LogIoException([NotNull] this Logger l, string message, [NotNull] IOException wex)
 {
     l.Warn(message + " " + wex.LoggableDetails());
 }
Esempio n. 34
0
 public void OnFailure(Request request, IOException iOException)
 {
 }
Esempio n. 35
0
 public BrokenConnectionException(IOException ex)
     : base("", ex)
 {
 }
 protected override Configuration HandleIOException(IOException ex)
 {
     return(GetDefaultConfiguration());
 }
Esempio n. 37
0
			public bool Iterate()
			{
				if(this.pending.CompareAndSet(true, false) && this.parent.monitorStarted.Value)
				{
					IOException ex = new IOException("Channel was inactive for too long: " + remote);
					this.parent.OnException(parent, ex);
				}

				return this.pending.Value;
			}
Esempio n. 38
0
        private unsafe void FlushInternal(bool endOfRequest)
        {
            bool startedSending = _requestContext.Response.HasStartedSending;
            var  byteCount      = _buffer.TotalBytes;

            if (byteCount == 0 && startedSending && !endOfRequest)
            {
                // Empty flush
                return;
            }

            var flags = ComputeLeftToWrite(endOfRequest);

            if (!_inOpaqueMode && endOfRequest && _leftToWrite > byteCount)
            {
                _requestContext.Abort();
                // This is logged rather than thrown because it is too late for an exception to be visible in user code.
                LogHelper.LogError(_requestContext.Logger, "ResponseStream::Dispose", "Fewer bytes were written than were specified in the Content-Length.");
                return;
            }

            if (endOfRequest && _requestContext.Response.BoundaryType == BoundaryType.Close)
            {
                flags |= HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
            }
            else if (!endOfRequest && _leftToWrite != byteCount)
            {
                flags |= HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
            }

            UpdateWritenCount((uint)byteCount);
            uint statusCode = 0;

            HttpApi.HTTP_DATA_CHUNK[] dataChunks;
            var pinnedBuffers = PinDataBuffers(endOfRequest, out dataChunks);

            try
            {
                if (!startedSending)
                {
                    statusCode = _requestContext.Response.SendHeaders(dataChunks, null, flags, false);
                }
                else
                {
                    fixed(HttpApi.HTTP_DATA_CHUNK *pDataChunks = dataChunks)
                    {
                        statusCode = HttpApi.HttpSendResponseEntityBody(
                            _requestContext.RequestQueueHandle,
                            _requestContext.RequestId,
                            (uint)flags,
                            (ushort)dataChunks.Length,
                            pDataChunks,
                            null,
                            SafeLocalFree.Zero,
                            0,
                            SafeNativeOverlapped.Zero,
                            IntPtr.Zero);
                    }

                    if (_requestContext.Server.IgnoreWriteExceptions)
                    {
                        statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
                    }
                }
            }
            finally
            {
                FreeDataBuffers(pinnedBuffers);
                _buffer.Clear();
            }

            if (statusCode != ErrorCodes.ERROR_SUCCESS && statusCode != ErrorCodes.ERROR_HANDLE_EOF
                // Don't throw for disconnects, we were already finished with the response.
                && (!endOfRequest || (statusCode != ErrorCodes.ERROR_CONNECTION_INVALID && statusCode != ErrorCodes.ERROR_INVALID_PARAMETER)))
            {
                Exception exception = new IOException(string.Empty, new WebListenerException((int)statusCode));
                LogHelper.LogException(_requestContext.Logger, "Flush", exception);
                Abort();
                throw exception;
            }
        }
Esempio n. 39
0
        private void OnRead(UvStreamHandle handle, int status)
        {
            if (status == 0)
            {
                // EAGAIN/EWOULDBLOCK so just return the buffer.
                // http://docs.libuv.org/en/v1.x/stream.html#c.uv_read_cb
                Debug.Assert(_currentWritableBuffer != null);
                _currentWritableBuffer.Value.Commit();
            }
            else if (status > 0)
            {
                Log.ConnectionRead(ConnectionId, status);

                Debug.Assert(_currentWritableBuffer != null);
                var currentWritableBuffer = _currentWritableBuffer.Value;
                currentWritableBuffer.Advance(status);
                var flushTask = currentWritableBuffer.FlushAsync();

                if (!flushTask.IsCompleted)
                {
                    // We wrote too many bytes to the reader, so pause reading and resume when
                    // we hit the low water mark.
                    _ = ApplyBackpressureAsync(flushTask);
                }
            }
            else
            {
                // Given a negative status, it's possible that OnAlloc wasn't called.
                _currentWritableBuffer?.Commit();
                _socket.ReadStop();

                IOException error = null;

                if (status == LibuvConstants.EOF)
                {
                    Log.ConnectionReadFin(ConnectionId);
                }
                else
                {
                    handle.Libuv.Check(status, out var uvError);

                    // Log connection resets at a lower (Debug) level.
                    if (status == LibuvConstants.ECONNRESET)
                    {
                        Log.ConnectionReset(ConnectionId);
                        error = new ConnectionResetException(uvError.Message, uvError);
                    }
                    else
                    {
                        Log.ConnectionError(ConnectionId, uvError);
                        error = new IOException(uvError.Message, uvError);
                    }
                }

                _connectionContext.Abort(error);
                // Complete after aborting the connection
                Input.Complete(error);
            }

            // Cleanup state from last OnAlloc. This is safe even if OnAlloc wasn't called.
            _currentWritableBuffer = null;
            _bufferHandle.Dispose();
        }
Esempio n. 40
0
                /// <summary>
                /// reconnect, if there is a timeout exception and isAutoReconnect is true
                ///
                /// </summary>
                private bool executeReconnect(IOException ex, string command, byte[] commandBytes)
                {
                    if (ex.InnerException != null&& ex.InnerException is SocketException)
                            {
                                //SocketException
                                SocketException innerEx = (SocketException) ex.InnerException;
                                if (innerEx.ErrorCode == 10053)
                                {
                                    //probably timeout: An established connection was aborted by the software in your host machine.
                                    CallWarning("ExecuteCommand", "", "probably timeout occured", null);
                                    if (IsAutoReconnect)
                                    {
                                        //try to reconnect and send one more time
                                        isTimeoutReconnect = true;
                                        try
                                        {
                                            CallTrace("   try to auto reconnect", null);
                                            Connect();

                                            CallTrace("   reconnect successful, try to resend command", null);
                                            CallTrace("Tx \'{0}\'", command);
                                            pop3Stream.Write(commandBytes, 0, commandBytes.Length);
                                            pop3Stream.Flush();
                                            return true;
                                        }
                                        finally
                                        {
                                            isTimeoutReconnect = false;
                                        }

                                    }
                                }
                            }
                            return false;
                }
 public void OnLoadError(IOException ex)
 {
     OnMediaFileFailed(new MediaFileFailedEventArgs(ex, CurrentFile));
 }
Esempio n. 42
0
        /// <summary>
        /// Invoked for a file that could not be visited.
        ///
        /// <para> Unless overridden, this method re-throws the I/O exception that prevented
        /// the file from being visited.
        /// </para>
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public FileVisitResult visitFileFailed(T file, java.io.IOException exc) throws java.io.IOException
        public override FileVisitResult VisitFileFailed(T file, IOException exc)
        {
            Objects.RequireNonNull(file);
            throw exc;
        }
Esempio n. 43
0
        public void Oneway(Command command)
        {
            Exception error = null;

            lock(reconnectMutex)
            {
                if(command != null && ConnectedTransport == null)
                {
                    if(command.IsShutdownInfo)
                    {
                        // Skipping send of ShutdownInfo command when not connected.
                        return;
                    }
                    else if(command.IsRemoveInfo || command.IsMessageAck)
                    {
                        // Simulate response to RemoveInfo command or a MessageAck
                        // since it would be stale at this point.
                        if(command.ResponseRequired)
                        {
                            OnCommand(this, new Response() { CorrelationId = command.CommandId });
                        }
                        return;
                    }
                }

                // Keep trying until the message is sent.
                for(int i = 0; !disposed; i++)
                {
                    try
                    {
                        // Any Ack that was being sent when the connection dropped is now
                        // stale so we don't send it here as it would cause an unmatched ack
                        // on the broker side and probably prevent a consumer from getting
                        // any new messages.
                        if(command.IsMessageAck && i > 0)
                        {
                            Tracer.Debug("Inflight MessageAck being dropped as stale.");
                            if(command.ResponseRequired)
                            {
                                OnCommand(this, new Response() { CorrelationId = command.CommandId });
                            }
                            return;
                        }

                        // Wait for transport to be connected.
                        ITransport transport = ConnectedTransport;
                        DateTime start = DateTime.Now;
                        bool timedout = false;
                        while(transport == null && !disposed && connectionFailure == null)
                        {
                            Tracer.Info("Waiting for transport to reconnect.");

                            int elapsed = (int) (DateTime.Now - start).TotalMilliseconds;
                            if(this.timeout > 0 && elapsed > timeout)
                            {
                                timedout = true;
                                Tracer.DebugFormat("FailoverTransport.oneway - timed out after {0} mills", elapsed);
                                break;
                            }

                            // Release so that the reconnect task can run
                            try
                            {
                                // Wait for something
                                Monitor.Wait(reconnectMutex, 100);
                            }
                            catch(ThreadInterruptedException e)
                            {
                                Tracer.DebugFormat("Interrupted: {0}", e.Message);
                            }

                            transport = ConnectedTransport;
                        }

                        if(transport == null)
                        {
                            // Previous loop may have exited due to use being disposed.
                            if(disposed)
                            {
                                error = new IOException("Transport disposed.");
                            }
                            else if(connectionFailure != null)
                            {
                                error = connectionFailure;
                            }
                            else if(timedout)
                            {
                                error = new IOException("Failover oneway timed out after " + timeout + " milliseconds.");
                            }
                            else
                            {
                                error = new IOException("Unexpected failure.");
                            }
                            break;
                        }

                        // If it was a request and it was not being tracked by
                        // the state tracker, then hold it in the requestMap so
                        // that we can replay it later.
                        Tracked tracked = stateTracker.Track(command);
                        lock(((ICollection) requestMap).SyncRoot)
                        {
                            if(tracked != null && tracked.WaitingForResponse)
                            {
                                requestMap.Add(command.CommandId, tracked);
                            }
                            else if(tracked == null && command.ResponseRequired)
                            {
                                requestMap.Add(command.CommandId, command);
                            }
                        }

                        // Send the message.
                        try
                        {
                            transport.Oneway(command);
                            stateTracker.TrackBack(command);
                        }
                        catch(Exception e)
                        {
                            // If the command was not tracked.. we will retry in this method
                            // otherwise we need to trigger a reconnect before returning as
                            // the transport is failed.
                            if (tracked == null)
                            {
                                // since we will retry in this method.. take it
                                // out of the request map so that it is not
                                // sent 2 times on recovery
                                if(command.ResponseRequired)
                                {
                                    lock(((ICollection) requestMap).SyncRoot)
                                    {
                                        requestMap.Remove(command.CommandId);
                                    }
                                }

                                // Rethrow the exception so it will handled by
                                // the outer catch
                                throw e;
                            }
                            else
                            {
                                Tracer.DebugFormat("Send Oneway attempt: {0} failed: Message = {1}", i, e.Message);
                                Tracer.DebugFormat("Failed Message Was: {0}", command);
                                HandleTransportFailure(e);
                            }
                        }

                        return;
                    }
                    catch(Exception e)
                    {
                        Tracer.DebugFormat("Send Oneway attempt: {0} failed: Message = {1}", i, e.Message);
                        Tracer.DebugFormat("Failed Message Was: {0}", command);
                        HandleTransportFailure(e);
                    }
                }
            }

            if(!disposed)
            {
                if(error != null)
                {
                    throw error;
                }
            }
        }
Esempio n. 44
0
        private async Task DoSend()
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    // Wait for data to write from the pipe producer
                    var result = await Output.ReadAsync();

                    var buffer = result.Buffer;

                    if (result.IsCancelled)
                    {
                        break;
                    }

                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            await _sender.SendAsync(buffer);
                        }
                        else if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        Output.Advance(buffer.End);
                    }
                }
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted)
            {
                error = null;
            }
            catch (ObjectDisposedException)
            {
                error = null;
            }
            catch (IOException ex)
            {
                error = ex;
            }
            catch (Exception ex)
            {
                error = new IOException(ex.Message, ex);
            }
            finally
            {
                Output.Complete(error);

                // Make sure to close the connection only after the _aborted flag is set.
                // Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when
                // a BadHttpRequestException is thrown instead of a TaskCanceledException.
                _aborted = true;
                _trace.ConnectionWriteFin(ConnectionId);
                _socket.Shutdown(SocketShutdown.Both);
            }
        }
Esempio n. 45
0
        private async Task DoReceive()
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    // Ensure we have some reasonable amount of buffer space
                    var buffer = Input.Alloc(MinAllocBufferSize);

                    try
                    {
                        var bytesReceived = await _receiver.ReceiveAsync(buffer.Buffer);

                        if (bytesReceived == 0)
                        {
                            // FIN
                            _trace.ConnectionReadFin(ConnectionId);
                            break;
                        }

                        buffer.Advance(bytesReceived);
                    }
                    finally
                    {
                        buffer.Commit();
                    }

                    var flushTask = buffer.FlushAsync();

                    if (!flushTask.IsCompleted)
                    {
                        _trace.ConnectionPause(ConnectionId);

                        await flushTask;

                        _trace.ConnectionResume(ConnectionId);
                    }

                    var result = flushTask.GetAwaiter().GetResult();
                    if (result.IsCompleted)
                    {
                        // Pipe consumer is shut down, do we stop writing
                        break;
                    }
                }
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionReset)
            {
                error = new ConnectionResetException(ex.Message, ex);
                _trace.ConnectionReset(ConnectionId);
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted ||
                                            ex.SocketErrorCode == SocketError.ConnectionAborted ||
                                            ex.SocketErrorCode == SocketError.Interrupted ||
                                            ex.SocketErrorCode == SocketError.InvalidArgument)
            {
                if (!_aborted)
                {
                    // Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (ObjectDisposedException)
            {
                if (!_aborted)
                {
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (IOException ex)
            {
                error = ex;
                _trace.ConnectionError(ConnectionId, error);
            }
            catch (Exception ex)
            {
                error = new IOException(ex.Message, ex);
                _trace.ConnectionError(ConnectionId, error);
            }
            finally
            {
                if (_aborted)
                {
                    error = error ?? new ConnectionAbortedException();
                }

                Input.Complete(error);
            }
        }
Esempio n. 46
0
 public LuceneIndexReaderAcquisitionException(string message, IOException e) : base(message, e)
 {
 }
            public void OnSingleManifestError(IOException exception)
            {
                if (_canceled)
                {
                    return;
                }

                _player.OnRenderersError(exception);
            }
		/// <summary>
		/// Creates FFmpegException from XmlDocument
		/// </summary>
		/// <param name="xmlDoc">XmlDocument containing data for creating FFmpegException object.</param>
		/// <returns>FFmpegException object</returns>
		public static FFmpegException CreateFromXml(XmlDocument xmlDoc) {
			FFmpegException exception = null;

			if (xmlDoc.DocumentElement != null) {
				XmlNode formatNode = xmlDoc.DocumentElement.SelectSingleNode(FORMAT_NODE);

				if (formatNode != null && formatNode.Attributes != null) {
					var code = formatNode.Attributes[CODE] != null
					           	? Int32.Parse(formatNode.Attributes[CODE].InnerText)
					           	: 0;

					var message = formatNode.Attributes[MESSAGE] != null ? formatNode.Attributes[MESSAGE].InnerText : null;

					switch (code) {
						case -1:
							exception = new OperationNotPermittedException();
							break;
						case -5:
							exception = new IOException();
							break;
						case -10060:
							exception = new UnknownException();
							break;
						case -1094995529:
							exception = new InvalidDataException();
							break;
						default:
							exception = new FFmpegException(message, code);
							break;
					}

				}
			}

			return exception;
		}