private void SetTimespanTimeout(UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE type, TimeSpan value)
        {
            Int64 timeoutValue;

            //
            // All timeouts are defined as USHORT in native layer (except MinSendRate, which is ULONG). Make sure that
            // timeout value is within range.
            //
            timeoutValue = Convert.ToInt64(value.TotalSeconds);

            if (timeoutValue < 0 || timeoutValue > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException("value");
            }

            //
            // Use local state to get values for other timeouts. Call into the native layer and if that 
            // call succeeds, update local state.
            //

            int[] currentTimeouts = timeouts;
            currentTimeouts[(int)type] = (int)timeoutValue;
            listener.SetServerTimeout(currentTimeouts, minSendBytesPerSecond);
            timeouts[(int)type] = (int)timeoutValue;
        }
 private TimeSpan GetTimeout(UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE type)
 {
     //
     // Since we maintain local state, GET is local.
     //
     return new TimeSpan(0, 0, (int)timeouts[(int)type]);            
 }
 private SendPacketsElement(string filepath, byte[] buffer, int offset, int count, UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags)
 {
     this.m_FilePath = filepath;
     this.m_Buffer = buffer;
     this.m_Offset = offset;
     this.m_Count = count;
     this.m_Flags = flags;
 }
        internal void CancelLastWrite(CriticalHandle requestQueueHandle)
        {
            HttpResponseStreamAsyncResult asyncState = m_LastWrite;

            if (asyncState != null && !asyncState.IsCompleted)
            {
                UnsafeNclNativeMethods.CancelIoEx(requestQueueHandle, asyncState.m_pOverlapped);
            }
        }
Beispiel #5
0
        internal static uint GetThreadId()
        {
            uint threadId = UnsafeNclNativeMethods.GetCurrentThreadId();

            if (threadId == 0)
            {
                threadId = (uint)Thread.CurrentThread.GetHashCode();
            }
            return(threadId);
        }
 protected unsafe void BaseConstruction(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* requestBlob)
 {
     if (requestBlob == null)
     {
         GC.SuppressFinalize(this);
     }
     else
     {
         this.m_MemoryBlob = requestBlob;
     }
 }
        /*
         * //
         * public Semaphore(int initialCount, int maxCount, string name) : base() {
         *  lock (this) {
         *      //
         *      Handle = UnsafeNclNativeMethods.CreateSemaphore(IntPtr.Zero, initialCount, maxCount, name);
         *  }
         * }
         */

        internal bool ReleaseSemaphore()
        {
#if DEBUG
            int  previousCount;
            bool success = UnsafeNclNativeMethods.ReleaseSemaphore(Handle, 1, out previousCount);
            GlobalLog.Print("ReleaseSemaphore#" + ValidationHelper.HashString(this) + " success:" + success + " previousCount:" + previousCount.ToString());
            return(success);
#else
            return(UnsafeNclNativeMethods.ReleaseSemaphore(Handle, 1, IntPtr.Zero));
#endif
        }
Beispiel #8
0
 public static void Assert(string message, string detailMessage)
 {
     try
     {
         Logobject.DumpArray(false);
     }
     finally
     {
         UnsafeNclNativeMethods.DebugBreak();
         Debugger.Break();
     }
 }
Beispiel #9
0
        private static string ReadConfigString(String ConfigName)
        {
            const int     parameterValueLength = 255;
            StringBuilder parameterValue       = new StringBuilder(parameterValueLength);
            bool          rc = UnsafeNclNativeMethods.FetchConfigurationString(true, ConfigName, parameterValue, parameterValueLength);

            if (rc)
            {
                return(parameterValue.ToString());
            }
            return("");
        }
Beispiel #10
0
        internal Semaphore(int initialCount, int maxCount) : base()
        {
            lock (this) {
#if MONO
                int errorCode;
                Handle = System.Threading.Semaphore.CreateSemaphore_internal(initialCount, maxCount, null, out errorCode);
#else
                //
                Handle = UnsafeNclNativeMethods.CreateSemaphore(IntPtr.Zero, initialCount, maxCount, IntPtr.Zero);
#endif
            }
        }
 private void SetTimespanTimeout(UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE type, TimeSpan value)
 {
     long num = Convert.ToInt64(value.TotalSeconds);
     if ((num < 0L) || (num > 0xffffL))
     {
         throw new ArgumentOutOfRangeException("value");
     }
     int[] timeouts = this.timeouts;
     timeouts[(int) type] = (int) num;
     this.listener.SetServerTimeout(timeouts, this.minSendRate);
     this.timeouts[(int) type] = (int) num;
 }
Beispiel #12
0
        internal static uint GetThreadId()
        {
#if MONO
            uint threadId = (uint)Thread.CurrentThread.ManagedThreadId;
#else
            uint threadId = UnsafeNclNativeMethods.GetCurrentThreadId();
#endif
            if (threadId == 0)
            {
                threadId = (uint)Thread.CurrentThread.GetHashCode();
            }
            return(threadId);
        }
 protected unsafe void SetBlob(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* requestBlob)
 {
     if (requestBlob == null)
     {
         this.UnsetBlob();
     }
     else
     {
         if (this.m_MemoryBlob == null)
         {
             GC.ReRegisterForFinalize(this);
         }
         this.m_MemoryBlob = requestBlob;
     }
 }
Beispiel #14
0
        // This function cancels pending m_AbortSocket and m_AbortSocket6 connecting sockets as needed.
        // This is only needed if we are closing before Activate() succeeded.
        // There are never IO operations on m_AbortSocket or m_AbortSocket6
        private void CloseConnectingSockets(bool useTimeout, int timeout)
        {
            Socket socket4 = m_AbortSocket;
            Socket socket6 = m_AbortSocket6;

            if (socket4 != null)
            {
                if (ServicePointManager.UseSafeSynchronousClose)
                {
                    try {
                        UnsafeNclNativeMethods.CancelIoEx(socket4.SafeHandle, IntPtr.Zero);
                    }
                    catch { }
                }

                if (useTimeout)
                {
                    socket4.Close(timeout);
                }
                else
                {
                    socket4.Close();
                }
                m_AbortSocket = null;
            }

            if (socket6 != null)
            {
                if (ServicePointManager.UseSafeSynchronousClose)
                {
                    try {
                        UnsafeNclNativeMethods.CancelIoEx(socket6.SafeHandle, IntPtr.Zero);
                    }
                    catch { }
                }

                if (useTimeout)
                {
                    socket6.Close(timeout);
                }
                else
                {
                    socket6.Close();
                }
                m_AbortSocket6 = null;
            }
        }
Beispiel #15
0
        public static void Assert(string message, string detailMessage)
        {
            try
            {
                Print("Assert: " + message + (!string.IsNullOrEmpty(detailMessage) ? ": " + detailMessage : ""));
                Print("*******");
                Logobject.DumpArray(false);
            }
            finally
            {
#if DEBUG && !STRESS
                Debug.Assert(false, message, detailMessage);
#else
                UnsafeNclNativeMethods.DebugBreak();
                Debugger.Break();
#endif
            }
        }
        public int SendUnsafe(UnsafeNclNativeMethods.WSABuffer[] buffers, SocketFlags flags)
        {
            SocketError errorCode;
            int bytesTransferred;
            try
            {
                errorCode = UnsafeNclNativeMethods.OSSOCK.WSASend_Blocking(this.Handle,
                                                               buffers,
                                                               buffers.Length,
                                                               out bytesTransferred,
                                                               flags,
                                                               IntPtr.Zero,
                                                               IntPtr.Zero);

                if ((SocketError)errorCode == SocketError.SocketError)
                {
                    errorCode = (SocketError)Marshal.GetLastWin32Error();
                }
            }
            finally
            {

            }

            if (errorCode != SocketError.Success)
            {
                //
                // update our internal state after this socket error and throw
                //
                if (Connected && ((Handle.ToPointer() == null || Handle == new IntPtr(-1)) || (errorCode != SocketError.WouldBlock &&
                    errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable)))
                {
                    // the socket is no longer a valid socket
                    //
                    Disconnect(false);
                }
                return 0;
            }
            return bytesTransferred;
        }
 private static unsafe Uri SafeDetectAutoProxyUrl(UnsafeNclNativeMethods.WinHttp.AutoDetectType discoveryMethod)
 {
     Uri result = null;
     string uriString = null;
     if (ComNetOS.IsWinHttp51)
     {
         SafeGlobalFree free;
         if (!UnsafeNclNativeMethods.WinHttp.WinHttpDetectAutoProxyConfigUrl(discoveryMethod, out free))
         {
             if (free != null)
             {
                 free.SetHandleAsInvalid();
             }
         }
         else
         {
             uriString = new string((char*) free.DangerousGetHandle());
             free.Close();
         }
     }
     else
     {
         StringBuilder autoProxyUrl = new StringBuilder(0x80a);
         if (UnsafeNclNativeMethods.WinInet.DetectAutoProxyUrl(autoProxyUrl, 0x80a, (int) discoveryMethod))
         {
             uriString = autoProxyUrl.ToString();
         }
     }
     if (uriString == null)
     {
         if (Logging.On)
         {
             Logging.PrintWarning(Logging.Web, SR.GetString("net_log_proxy_autodetect_failed"));
         }
         return result;
     }
     if (!Uri.TryCreate(uriString, UriKind.Absolute, out result) && Logging.On)
     {
         Logging.PrintWarning(Logging.Web, SR.GetString("net_log_proxy_autodetect_script_location_parse_error", new object[] { ValidationHelper.ToString(uriString) }));
     }
     return result;
 }
Beispiel #18
0
        internal override void PrintLine(string msg)
        {
            if (m_Finalized)
            {
                return;
            }
            string spc = "";

            _IamAlive++;

            spc = GetNestingString();

            string tickString = "";

            if (GlobalLog.s_UsePerfCounter)
            {
                long counter;
                SafeNativeMethods.QueryPerformanceCounter(out counter);
                if (_StartTickCountMicroseconds > counter) // counter reset, restart from 0
                {
                    _StartTickCountMicroseconds = counter;
                }
                counter -= _StartTickCountMicroseconds;
                if (GlobalLog.s_UseTimeSpan)
                {
                    tickString = new TimeSpan(counter / 100).ToString();
                    // note: TimeSpan().ToString() doesn't return the uSec part
                    // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16
                    if (tickString.Length < 16)
                    {
                        tickString += ".0000000";
                    }
                }
                else
                {
                    tickString = ((double)counter * _MillisecondsPerTicks).ToString("f3");
                }
            }
            else
            {
                int counter = Environment.TickCount;
                if (_StartTickCountMilliseconds > counter)
                {
                    _StartTickCountMilliseconds = counter;
                }
                counter -= _StartTickCountMilliseconds;
                if (GlobalLog.s_UseTimeSpan)
                {
                    tickString = new TimeSpan(counter * 10000).ToString();
                    // note: TimeSpan().ToString() doesn't return the uSec part
                    // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16
                    if (tickString.Length < 16)
                    {
                        tickString += ".0000000";
                    }
                }
                else
                {
                    tickString = (counter).ToString();
                }
            }

            int threadId = 0;

            if (GlobalLog.s_UseThreadId)
            {
                try {
                    threadId = (int)Thread.GetData(GlobalLog.s_ThreadIdSlot);
                }
                catch {
                }
                if (threadId == 0)
                {
                    threadId = UnsafeNclNativeMethods.GetCurrentThreadId();
                    Thread.SetData(GlobalLog.s_ThreadIdSlot, threadId);
                }
            }
            if (threadId == 0)
            {
                threadId = Thread.CurrentThread.GetHashCode();
            }

            string str = String.Format("[{0:x8}]", threadId) + " (" + tickString + ") " + spc + msg;

            Monitor.Enter(this);

            _AddCount++;
            _Logarray.Add(str);

            int MaxLines = GlobalLog.s_DumpToConsole ? 0 : GlobalLog.MaxLinesBeforeSave;

            if (_AddCount > MaxLines)
            {
                _AddCount = 0;

                if (!GlobalLog.SaveOnlyOnError || GlobalLog.s_DumpToConsole)
                {
                    DumpArray(false);
                }

                _Logarray = new ArrayList();
            }

            Monitor.Exit(this);
        }
 internal static extern uint HttpCreateRequestQueue(UnsafeNclNativeMethods.HttpApi.HTTPAPI_VERSION version, string pName, Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES pSecurityAttributes, uint flags, out HttpRequestQueueV2Handle pReqQueueHandle);
 private void SetUrlGroupProperty(UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize)
 {
     uint num = 0;
     num = UnsafeNclNativeMethods.HttpApi.HttpSetUrlGroupProperty(this.m_UrlGroupId, property, info, infosize);
     if (num != 0)
     {
         HttpListenerException e = new HttpListenerException((int) num);
         if (Logging.On)
         {
             Logging.Exception(Logging.HttpListener, this, "HttpSetUrlGroupProperty:: Property: " + property, e);
         }
         throw e;
     }
 }
        private List<GCHandle> SerializeHeaders(ref UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADERS headers,
            bool isWebSocketHandshake) {
            UnsafeNclNativeMethods.HttpApi.HTTP_UNKNOWN_HEADER[] unknownHeaders = null;
            List<GCHandle> pinnedHeaders;
            GCHandle gcHandle;
            /*
            // here we would check for BoundaryType.Raw, in this case we wouldn't need to do anything
            if (m_BoundaryType==BoundaryType.Raw) {
                return null;
            }
            */
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SerializeHeaders(HTTP_RESPONSE_HEADERS)");
            if (Headers.Count==0) {
                return null;
            }
            string headerName;
            string headerValue;
            int lookup;
            byte[] bytes = null;
            pinnedHeaders = new List<GCHandle>();

            //---------------------------------------------------
            // DTS Issue: 609383:
            // The Set-Cookie headers are being merged into one. 
            // There are two issues here. 
            // 1. When Set-Cookie headers are set through SetCookie method on the ListenerResponse,
            // there is code in the SetCookie method and the methods it calls to flatten the Set-Cookie
            // values. This blindly concatenates the cookies with a comma delimiter. There could be 
            // a cookie value that contains comma, but we don't escape it with %XX value
            //  
            // As an alternative users can add the Set-Cookie header through the AddHeader method
            // like ListenerResponse.Headers.Add("name", "value")
            // That way they can add multiple headers - AND They can format the value like they want it.
            //
            // 2. Now that the header collection contains multiple Set-Cookie name, value pairs
            // you would think the problem would go away. However here is an interesting thing.
            // For NameValueCollection, when you add 
            // "Set-Cookie", "value1"
            // "Set-Cookie", "value2"
            //  The NameValueCollection.Count == 1. Because there is only one key
            //  NameValueCollection.Get("Set-Cookie") would conviniently take these two valuess
            //  concatenate them with a comma like 
            //  value1,value2. 
            //  In order to get individual values, you need to use 
            //  string[] values = NameValueCollection.GetValues("Set-Cookie");
            //
            //  -------------------------------------------------------------
            //  So here is the proposed fix here.
            //  We must first to loop through all the NameValueCollection keys
            //  and if the name is a unknown header, we must compute the number of 
            //  values it has. Then, we should allocate that many unknown header array 
            //  elements.
            //  
            //  Note that a part of the fix here is to treat Set-Cookie as an unknown header
            //
            //
            //-----------------------------------------------------------
            int numUnknownHeaders = 0;
            for (int index=0; index<Headers.Count; index++) {            
                headerName = Headers.GetKey(index) as string;
                
                //See if this is an unknown header
                lookup = UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName);
                
                //Treat Set-Cookie as well as Connection header in Websocket mode as unknown
                if (lookup == (int)HttpResponseHeader.SetCookie ||
                    isWebSocketHandshake && lookup == (int)HttpResponseHeader.Connection)
                {
                    lookup = -1;
                }

                if(lookup == -1)
                {
                    string[] headerValues = Headers.GetValues(index);
                    numUnknownHeaders += headerValues.Length;
                }
            }

            try{
                fixed (UnsafeNclNativeMethods.HttpApi.HTTP_KNOWN_HEADER* pKnownHeaders = &headers.KnownHeaders) {
                    for (int index=0; index<Headers.Count; index++) {
                        headerName = Headers.GetKey(index) as string;
                        headerValue = Headers.Get(index) as string;
                        lookup = UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName);
                        if (lookup == (int)HttpResponseHeader.SetCookie ||
                            isWebSocketHandshake && lookup == (int)HttpResponseHeader.Connection)
                        {
                            lookup = -1;
                        }
                        GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SerializeHeaders(" + index + "/" + Headers.Count + ") headerName:" + ValidationHelper.ToString(headerName) + " lookup:" + lookup + " headerValue:" + ValidationHelper.ToString(headerValue));
                        if (lookup==-1) {

                            if (unknownHeaders==null) {
                                //----------------------------------------
                                //*** This following comment is no longer true ***
                                // we waste some memory here (up to 32*41=1312 bytes) but we gain speed
                                //unknownHeaders = new UnsafeNclNativeMethods.HttpApi.HTTP_UNKNOWN_HEADER[Headers.Count-index];
                                //--------------------------------------------
                                unknownHeaders = new UnsafeNclNativeMethods.HttpApi.HTTP_UNKNOWN_HEADER[numUnknownHeaders];                                    
                                gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned);
                                pinnedHeaders.Add(gcHandle);
                                headers.pUnknownHeaders = (UnsafeNclNativeMethods.HttpApi.HTTP_UNKNOWN_HEADER*)gcHandle.AddrOfPinnedObject();
                            }

                            //----------------------------------------
                            //FOR UNKNOWN HEADERS
                            //ALLOW MULTIPLE HEADERS to be added 
                            //---------------------------------------
                            string[] headerValues = Headers.GetValues(index);
                            for(int headerValueIndex = 0; headerValueIndex < headerValues.Length; headerValueIndex++)
                            {
                                //Add Name
                                bytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(headerName)];
                                unknownHeaders[headers.UnknownHeaderCount].NameLength = (ushort)bytes.Length;
                                WebHeaderCollection.HeaderEncoding.GetBytes(headerName, 0, bytes.Length, bytes, 0);
                                gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                                pinnedHeaders.Add(gcHandle);
                                unknownHeaders[headers.UnknownHeaderCount].pName = (sbyte*)gcHandle.AddrOfPinnedObject();

                                //Add Value
                                headerValue = headerValues[headerValueIndex];
                                bytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(headerValue)];
                                unknownHeaders[headers.UnknownHeaderCount].RawValueLength = (ushort)bytes.Length;
                                WebHeaderCollection.HeaderEncoding.GetBytes(headerValue, 0, bytes.Length, bytes, 0);
                                gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                                pinnedHeaders.Add(gcHandle);
                                unknownHeaders[headers.UnknownHeaderCount].pRawValue = (sbyte*)gcHandle.AddrOfPinnedObject();
                                headers.UnknownHeaderCount++;
                                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SerializeHeaders(Unknown) UnknownHeaderCount:" + headers.UnknownHeaderCount);
                            }
                            
                        }
                        else {
                            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SerializeHeaders(Known) HttpResponseHeader[" + lookup + "]:" + ((HttpResponseHeader)lookup) + " headerValue:" + ValidationHelper.ToString(headerValue));
                            if (headerValue!=null) {
                                bytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(headerValue)];
                                pKnownHeaders[lookup].RawValueLength = (ushort)bytes.Length;
                                WebHeaderCollection.HeaderEncoding.GetBytes(headerValue, 0, bytes.Length, bytes, 0);
                                gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                                pinnedHeaders.Add(gcHandle);
                                pKnownHeaders[lookup].pRawValue = (sbyte*)gcHandle.AddrOfPinnedObject();
                                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SerializeHeaders(Known) pRawValue:" + ValidationHelper.ToString((IntPtr)(pKnownHeaders[lookup].pRawValue)) + " RawValueLength:" + pKnownHeaders[lookup].RawValueLength + " lookup:" + lookup);
                                GlobalLog.Dump((IntPtr)pKnownHeaders[lookup].pRawValue, 0, pKnownHeaders[lookup].RawValueLength);
                            }
                        }
                    }
                }
            }
            catch {
                FreePinnedHeaders(pinnedHeaders);
                throw;
            }
            return pinnedHeaders;
        }
Beispiel #22
0
        private void Initialize(string filePath, byte[] buffer, int offset, int count, 
            UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags, bool endOfPacket) {

            m_FilePath = filePath;
            m_Buffer = buffer;
            m_Offset = offset;
            m_Count = count;
            m_Flags = flags;
            if (endOfPacket) {
                m_Flags |= UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket;
            }
        }
        private bool WinHttpGetProxyForUrl(string destination,
            ref UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions,
            out string proxyListString)
        {
            proxyListString = null;

            bool success = false;
            UnsafeNclNativeMethods.WinHttp.WINHTTP_PROXY_INFO proxyInfo =
                new UnsafeNclNativeMethods.WinHttp.WINHTTP_PROXY_INFO();

            // Make sure the strings get cleaned up in a CER (thus unexpected exceptions, like
            // ThreadAbortException will not interrupt the execution of the finally block, and we'll not
            // leak resources).
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                success = UnsafeNclNativeMethods.WinHttp.WinHttpGetProxyForUrl(session,
                    destination, ref autoProxyOptions, out proxyInfo);

                if (success)
                {
                    proxyListString = Marshal.PtrToStringUni(proxyInfo.Proxy);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(proxyInfo.Proxy);
                Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
            }

            return success;
        }
 internal Semaphore(int initialCount, int maxCount) : base()
 {
     lock (this) {
         Handle = UnsafeNclNativeMethods.CreateSemaphore(IntPtr.Zero, initialCount, maxCount, IntPtr.Zero);
     }
 }
        private static unsafe Uri SafeDetectAutoProxyUrl(
            UnsafeNclNativeMethods.WinHttp.AutoDetectType discoveryMethod)
        {
            Uri autoProxy = null;

#if !FEATURE_PAL
            string url = null;
            
            GlobalLog.Print("NetWebProxyFinder::SafeDetectAutoProxyUrl() Using WinHttp.");
            SafeGlobalFree autoProxyUrl;
            bool success = UnsafeNclNativeMethods.WinHttp.WinHttpDetectAutoProxyConfigUrl(discoveryMethod, out autoProxyUrl);
            if (!success)
            {
                if (autoProxyUrl != null)
                {
                    autoProxyUrl.SetHandleAsInvalid();
                }
            }
            else
            {
                url = new string((char*)autoProxyUrl.DangerousGetHandle());
                autoProxyUrl.Close();
            }
            
            if (url != null)
            {
                bool parsed = Uri.TryCreate(url, UriKind.Absolute, out autoProxy);
                if (!parsed)
                {
                    if (Logging.On) Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_autodetect_script_location_parse_error, ValidationHelper.ToString(url)));
                    GlobalLog.Print("NetWebProxyFinder::SafeDetectAutoProxyUrl() Uri.TryParse() failed url:" + ValidationHelper.ToString(url));
                }
            }
            else
            {
                if (Logging.On) Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_autodetect_failed));
                GlobalLog.Print("NetWebProxyFinder::SafeDetectAutoProxyUrl() DetectAutoProxyUrl() returned false");
            }
#endif // !FEATURE_PAL

            return autoProxy;
        }
Beispiel #26
0
        internal override void PrintLine(string msg)
        {
            if (_Finalized)
            {
                return;
            }
            string spc = "";

            _IamAlive++;

            spc = GetNestingString();

            string tickString = "";

            if (GlobalLog.s_UsePerfCounter)
            {
                long nowTicks;
                SafeNativeMethods.QueryPerformanceCounter(out nowTicks);
                if (_StartTicks > nowTicks) // counter reset, restart from 0
                {
                    _StartTicks = nowTicks;
                }
                nowTicks -= _StartTicks;
                if (GlobalLog.s_UseTimeSpan)
                {
                    tickString = new TimeSpan((long)(nowTicks * _NanosecondsPerTick)).ToString();
                    // note: TimeSpan().ToString() doesn't return the uSec part
                    // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16
                    if (tickString.Length < 16)
                    {
                        tickString += ".0000000";
                    }
                }
                else
                {
                    tickString = ((double)nowTicks * _NanosecondsPerTick / 10000).ToString("f3");
                }
            }
            else
            {
                int nowMilliseconds = Environment.TickCount;
                if (_StartMilliseconds > nowMilliseconds)
                {
                    _StartMilliseconds = nowMilliseconds;
                }
                nowMilliseconds -= _StartMilliseconds;
                if (GlobalLog.s_UseTimeSpan)
                {
                    tickString = new TimeSpan(nowMilliseconds * 10000).ToString();
                    // note: TimeSpan().ToString() doesn't return the uSec part
                    // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16
                    if (tickString.Length < 16)
                    {
                        tickString += ".0000000";
                    }
                }
                else
                {
                    tickString = nowMilliseconds.ToString();
                }
            }

            uint threadId = 0;

            if (GlobalLog.s_UseThreadId)
            {
                try {
                    object threadData = Thread.GetData(GlobalLog.s_ThreadIdSlot);
                    if (threadData != null)
                    {
                        threadId = (uint)threadData;
                    }
                }
                catch (Exception exception) {
                    if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                    {
                        throw;
                    }
                }
                if (threadId == 0)
                {
                    threadId = UnsafeNclNativeMethods.GetCurrentThreadId();
                    Thread.SetData(GlobalLog.s_ThreadIdSlot, threadId);
                }
            }
            if (threadId == 0)
            {
                threadId = (uint)Thread.CurrentThread.GetHashCode();
            }

            string str = "[" + threadId.ToString("x8") + "]" + " (" + tickString + ") " + spc + msg;

            lock (this) {
                _AddCount++;
                _Logarray.Add(str);
                int MaxLines = GlobalLog.s_DumpToConsole ? 0 : GlobalLog.MaxLinesBeforeSave;
                if (_AddCount > MaxLines)
                {
                    _AddCount = 0;
                    DumpArray(false);
                    _Logarray = new ArrayList();
                }
            }
        }
Beispiel #27
0
 internal bool ReleaseSemaphore()
 {
     return(UnsafeNclNativeMethods.ReleaseSemaphore(this.Handle, 1, IntPtr.Zero));
 }
        protected void SetBlob(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST* requestBlob)
        {
            GlobalLog.Assert(m_MemoryBlob != null || m_BackingBuffer == null, "RequestContextBase::Dispose()|SetBlob() called after ReleasePins().");
            if (requestBlob == null)
            {
                UnsetBlob();
                return;
            }

            if (m_MemoryBlob == null)
            {
                GC.ReRegisterForFinalize(this);
            }
            m_MemoryBlob = requestBlob;
        }
/*
12.3
HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values.
The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls:

#define HTTP_SEND_RESPONSE_FLAG_DISCONNECT          0x00000001
#define HTTP_SEND_RESPONSE_FLAG_MORE_DATA           0x00000002
#define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER          0x00000004
#define HTTP_SEND_RESPONSE_FLAG_VALID               0x00000007

HTTP_SEND_RESPONSE_FLAG_DISCONNECT:
    specifies that the network connection should be disconnected immediately after
    sending the response, overriding the HTTP protocol's persistent connection features.
HTTP_SEND_RESPONSE_FLAG_MORE_DATA:
    specifies that additional entity body data will be sent by the caller. Thus,
    the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset.
HTTP_SEND_RESPONSE_RAW_HEADER:
    specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting
    a call to HttpSendHttpResponse() in order to bypass normal header processing. The
    actual HTTP header will be generated by the application and sent as entity body.
    This flag should be passed on the first call to HttpSendResponseEntityBody, and
    not after. Thus, flag is not applicable to HttpSendHttpResponse.
*/
        internal unsafe uint SendHeaders(UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK* pDataChunk, 
            HttpResponseStreamAsyncResult asyncResult, 
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags,
            bool isWebSocketHandshake) {
            GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() pDataChunk:" + ValidationHelper.ToString((IntPtr)pDataChunk) + " asyncResult:" + ValidationHelper.ToString(asyncResult));
            GlobalLog.Assert(!SentHeaders, "HttpListenerResponse#{0}::SendHeaders()|SentHeaders is true.", ValidationHelper.HashString(this));
            
            if (StatusCode == (int)HttpStatusCode.Unauthorized) { // User set 401
                // Using the configured Auth schemes, populate the auth challenge headers. This is for scenarios where 
                // Anonymous access is allowed for some resources, but the server later determines that authorization 
                // is required for this request.
                HttpListenerContext.SetAuthenticationHeaders();
            }
            
            // Log headers
            if(Logging.On) {
                StringBuilder sb = new StringBuilder("HttpListenerResponse Headers:\n");
                for (int i=0; i<Headers.Count; i++) {
                    sb.Append("\t");
                    sb.Append(Headers.GetKey(i));
                    sb.Append(" : ");
                    sb.Append(Headers.Get(i));
                    sb.Append("\n");
                }
                Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString());
            }
            m_ResponseState = ResponseState.SentHeaders;
            /*
            if (m_BoundaryType==BoundaryType.Raw) {
                use HTTP_SEND_RESPONSE_FLAG_RAW_HEADER;
            }
            */
            uint statusCode;
            uint bytesSent;
            List<GCHandle> pinnedHeaders = SerializeHeaders(ref m_NativeResponse.Headers, isWebSocketHandshake);
            try {
                if (pDataChunk!=null) {
                    m_NativeResponse.EntityChunkCount = 1;
                    m_NativeResponse.pEntityChunks = pDataChunk;
                }
                else if (asyncResult!=null && asyncResult.pDataChunks!=null) {
                    m_NativeResponse.EntityChunkCount = asyncResult.dataChunkCount;
                    m_NativeResponse.pEntityChunks = asyncResult.pDataChunks;
                } 
                else {
                    m_NativeResponse.EntityChunkCount = 0;
                    m_NativeResponse.pEntityChunks = null;
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() calling UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse flags:" + flags);
                if (StatusDescription.Length>0) {
                    byte[] statusDescriptionBytes = new byte[WebHeaderCollection.HeaderEncoding.GetByteCount(StatusDescription)];
                    fixed (byte* pStatusDescription = statusDescriptionBytes) {
                        m_NativeResponse.ReasonLength = (ushort)statusDescriptionBytes.Length;
                        WebHeaderCollection.HeaderEncoding.GetBytes(StatusDescription, 0, statusDescriptionBytes.Length, statusDescriptionBytes, 0);
                        m_NativeResponse.pReason = (sbyte*)pStatusDescription;
                        fixed (UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE* pResponse = &m_NativeResponse) {
                            if (asyncResult != null)
                            {
                                HttpListenerContext.EnsureBoundHandle();
                            }
                            statusCode =
                                UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                    HttpListenerContext.RequestQueueHandle,
                                    HttpListenerRequest.RequestId,
                                    (uint)flags,
                                    pResponse,
                                    null,
                                    &bytesSent,
                                    SafeLocalFree.Zero,
                                    0,
                                    asyncResult==null ? null : asyncResult.m_pOverlapped,
                                    null );

                            if (asyncResult != null && 
                                statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                                HttpListener.SkipIOCPCallbackOnSuccess)
                            {
                                asyncResult.IOCompleted(statusCode, bytesSent);
                                // IO operation completed synchronously - callback won't be called to signal completion.
                            }
                        }
                    }
                }
                else {
                    fixed (UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE* pResponse = &m_NativeResponse) {
                        if (asyncResult != null)
                        {
                            HttpListenerContext.EnsureBoundHandle();
                        }
                        statusCode =
                            UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse(
                                HttpListenerContext.RequestQueueHandle,
                                HttpListenerRequest.RequestId,
                                (uint)flags,
                                pResponse,
                                null,
                                &bytesSent,
                                SafeLocalFree.Zero,
                                0,
                                asyncResult==null ? null : asyncResult.m_pOverlapped,
                                null );

                        if (asyncResult != null && 
                            statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS &&
                            HttpListener.SkipIOCPCallbackOnSuccess)
                        {
                            asyncResult.IOCompleted(statusCode, bytesSent);
                            // IO operation completed synchronously - callback won't be called to signal completion.
                        }
                    }
                }
                GlobalLog.Print("HttpListenerResponse#" + ValidationHelper.HashString(this) + "::SendHeaders() call to UnsafeNclNativeMethods.HttpApi.HttpSendHttpResponse returned:" + statusCode);
            }
            finally {
                FreePinnedHeaders(pinnedHeaders);
            }
            return statusCode;
        }
        private void SetUrlGroupProperty(UnsafeNclNativeMethods.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize) {
            uint statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;

            GlobalLog.Assert(m_UrlGroupId != 0, "SetUrlGroupProperty called with invalid url group id");
            GlobalLog.Assert(info != IntPtr.Zero, "SetUrlGroupProperty called with invalid pointer");

            //
            // Set the url group property using Http Api.
            //
            statusCode = UnsafeNclNativeMethods.HttpApi.HttpSetUrlGroupProperty(
                m_UrlGroupId, property, info, infosize);

            if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) {
                HttpListenerException exception = new HttpListenerException((int)statusCode);
                if (Logging.On) Logging.Exception(Logging.HttpListener, this, "HttpSetUrlGroupProperty:: Property: " +
                    property, exception);
                throw exception;
            }
        }
 private bool WinHttpGetProxyForUrl(string destination, ref UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out string proxyListString)
 {
     proxyListString = null;
     bool flag = false;
     UnsafeNclNativeMethods.WinHttp.WINHTTP_PROXY_INFO proxyInfo = new UnsafeNclNativeMethods.WinHttp.WINHTTP_PROXY_INFO();
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         flag = UnsafeNclNativeMethods.WinHttp.WinHttpGetProxyForUrl(this.session, destination, ref autoProxyOptions, out proxyInfo);
         if (flag)
         {
             proxyListString = Marshal.PtrToStringUni(proxyInfo.Proxy);
         }
     }
     finally
     {
         Marshal.FreeHGlobal(proxyInfo.Proxy);
         Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
     }
     return flag;
 }
 private TimeSpan GetTimeout(UnsafeNclNativeMethods.HttpApi.HTTP_TIMEOUT_TYPE type)
 {
     return new TimeSpan(0, 0, this.timeouts[(int) type]);
 }