• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# EasyRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中EasyRequest的典型用法代码示例。如果您正苦于以下问题:C# EasyRequest类的具体用法?C# EasyRequest怎么用?C# EasyRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



EasyRequest类属于命名空间,在下文中一共展示了EasyRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Queue

 /// <summary>Queues a request for the multi handle to process.</summary>
 /// <param name="request"></param>
 public void Queue(EasyRequest request)
 {
     lock (_incomingRequests)
     {
         // Add the request, then initiate processing.
         _incomingRequests.Enqueue(request);
         EnsureWorkerIsRunning();
     }
 }
开发者ID:dmetzgar,项目名称:corefx,代码行数:11,代码来源:CurlHandler.MultiAgent.cs


示例2: SetSslOptions

            internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
            {
                // Disable SSLv2/SSLv3, allow TLSv1.*
                easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1);

                IntPtr userPointer = IntPtr.Zero;
                if (clientCertOption == ClientCertificateOption.Automatic)
                {
                    ClientCertificateProvider certProvider = new ClientCertificateProvider();
                    userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
                    easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(),
                                           certProvider,
                                           CancellationToken.None,
                                           TaskContinuationOptions.ExecuteSynchronously,
                                           TaskScheduler.Default);
                }
                else
                {
                    Debug.Assert(clientCertOption == ClientCertificateOption.Manual, "ClientCertificateOption is manual or automatic");
                }

                CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);

                switch (answer)
                {
                    case CURLcode.CURLE_OK:
                        break;
                    // Curl 7.38 and prior
                    case CURLcode.CURLE_UNKNOWN_OPTION:
                    // Curl 7.39 and later
                    case CURLcode.CURLE_NOT_BUILT_IN:
                        EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported. Platform default HTTPS chain building in use");
                        if (clientCertOption == ClientCertificateOption.Automatic)
                        {
                            throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option);
                        }

                        break;
                    default:
                        ThrowIfCURLEError(answer);
                        break;
                }
            }
开发者ID:kkurni,项目名称:corefx,代码行数:43,代码来源:CurlHandler.SslProvider.cs


示例3: SetSslOptions

            internal static void SetSslOptions(EasyRequest easy)
            {
                CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback);

                switch (answer)
                {
                    case CURLcode.CURLE_OK:
                        break;
                    // Curl 7.38 and prior
                    case CURLcode.CURLE_UNKNOWN_OPTION:
                    // Curl 7.39 and later
                    case CURLcode.CURLE_NOT_BUILT_IN:
                        VerboseTrace("CURLOPT_SSL_CTX_FUNCTION is not supported, platform default https chain building in use");
                        break;
                    default:
                        ThrowIfCURLEError(answer);
                        break;
                }
            }
开发者ID:ReedKimble,项目名称:corefx,代码行数:19,代码来源:CurlHandler.SslProvider.cs


示例4: SetSslOptions

            internal static void SetSslOptions(EasyRequest easy)
            {
                int answer = Interop.libcurl.curl_easy_setopt(
                    easy._easyHandle,
                    Interop.libcurl.CURLoption.CURLOPT_SSL_CTX_FUNCTION,
                    s_sslCtxCallback);

                switch (answer)
                {
                    case Interop.libcurl.CURLcode.CURLE_OK:
                        break;
                    case Interop.libcurl.CURLcode.CURLE_NOT_BUILT_IN:
                        VerboseTrace("CURLOPT_SSL_CTX_FUNCTION is not supported, platform default https chain building in use");
                        break;
                    default:
                        ThrowIfCURLEError(answer);
                        break;
                }
            }
开发者ID:nadyalo,项目名称:corefx,代码行数:19,代码来源:CurlHandler.SslProvider.cs


示例5: SetCurlCallbacks

            private static void SetCurlCallbacks(EasyRequest easy, IntPtr easyGCHandle)
            {
                // Add callback for processing headers
                easy.SetCurlOption(CURLoption.CURLOPT_HEADERFUNCTION, s_receiveHeadersCallback);
                easy.SetCurlOption(CURLoption.CURLOPT_HEADERDATA, easyGCHandle);

                // If we're sending data as part of the request, add callbacks for sending request data
                if (easy._requestMessage.Content != null)
                {
                    easy.SetCurlOption(CURLoption.CURLOPT_READFUNCTION, s_sendCallback);
                    easy.SetCurlOption(CURLoption.CURLOPT_READDATA, easyGCHandle);

                    easy.SetCurlOption(CURLoption.CURLOPT_SEEKFUNCTION, s_seekCallback);
                    easy.SetCurlOption(CURLoption.CURLOPT_SEEKDATA, easyGCHandle);
                }

                // If we're expecting any data in response, add a callback for receiving body data
                if (easy._requestMessage.Method != HttpMethod.Head)
                {
                    easy.SetCurlOption(CURLoption.CURLOPT_WRITEFUNCTION, s_receiveBodyCallback);
                    easy.SetCurlOption(CURLoption.CURLOPT_WRITEDATA, easyGCHandle);
                }
            }
开发者ID:RendleLabs,项目名称:corefx,代码行数:23,代码来源:CurlHandler.MultiAgent.cs


示例6: FinishRequest

            private void FinishRequest(EasyRequest completedOperation, int messageResult)
            {
                VerboseTrace("messageResult: " + messageResult, easy: completedOperation);

                if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized && completedOperation._handler.PreAuthenticate)
                {
                    ulong availedAuth;
                    if (Interop.libcurl.curl_easy_getinfo(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out availedAuth) == CURLcode.CURLE_OK)
                    {
                        // TODO: fix locking in AddCredentialToCache
                        completedOperation._handler.AddCredentialToCache(
                            completedOperation._requestMessage.RequestUri, availedAuth, completedOperation._networkCredential);
                    }
                    // Ignore errors: no need to fail for the sake of putting the credentials into the cache
                }

                switch (messageResult)
                {
                    case CURLcode.CURLE_OK:
                        completedOperation.EnsureResponseMessagePublished();
                        break;
                    default:
                        completedOperation.FailRequest(CreateHttpRequestException(new CurlException(messageResult, isMulti: false)));
                        break;
                }

                // At this point, we've completed processing the entire request, either due to error
                // or due to completing the entire response.
                completedOperation.Cleanup();
            }
开发者ID:RendleLabs,项目名称:corefx,代码行数:30,代码来源:CurlHandler.MultiAgent.cs


示例7: FindActiveRequest

 private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
 {
     // We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
     // expensive to look up by EasyRequest.  If we find this becoming a bottleneck, we can add a reverse
     // map that stores the other direction as well.
     foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
     {
         if (pair.Value.Easy == easy)
         {
             gcHandlePtr = pair.Key;
             activeRequest = pair.Value;
             return true;
         }
     }
     gcHandlePtr = IntPtr.Zero;
     activeRequest = default(ActiveRequest);
     return false;
 }
开发者ID:RendleLabs,项目名称:corefx,代码行数:18,代码来源:CurlHandler.MultiAgent.cs


示例8: ActivateNewRequest

            private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
            {
                Debug.Assert(easy != null, "We should never get a null request");
                Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");

                // If cancellation has been requested, complete the request proactively
                if (easy._cancellationToken.IsCancellationRequested)
                {
                    easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
                    easy.Cleanup(); // no active processing remains, so cleanup
                    return;
                }

                // Otherwise, configure it.  Most of the configuration was already done when the EasyRequest
                // was created, but there's additional configuration we need to do specific to this
                // multi agent, specifically telling the easy request about its own GCHandle and setting
                // up callbacks for data processing.  Once it's configured, add it to the multi handle.
                GCHandle gcHandle = GCHandle.Alloc(easy);
                IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
                try
                {
                    easy._associatedMultiAgent = this;
                    easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
                    SetCurlCallbacks(easy, gcHandlePtr);
                    ThrowIfCURLMError(Interop.libcurl.curl_multi_add_handle(multiHandle, easy._easyHandle));
                }
                catch (Exception exc)
                {
                    gcHandle.Free();
                    easy.FailRequest(exc);
                    easy.Cleanup();  // no active processing remains, so cleanup
                    return;
                }

                // And if cancellation can be requested, hook up a cancellation callback.
                // This callback will put the easy request back into the queue, which will
                // ensure that a wake-up request has been issued.  When we pull
                // the easy request out of the request queue, we'll see that it's already
                // associated with this agent, meaning that it's a cancellation request,
                // and we'll deal with it appropriately.
                var cancellationReg = default(CancellationTokenRegistration);
                if (easy._cancellationToken.CanBeCanceled)
                {
                    cancellationReg = easy._cancellationToken.Register(s =>
                    {
                        var state = (Tuple<MultiAgent, EasyRequest>)s;
                        state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
                    }, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
                }

                // Finally, add it to our map.
                _activeOperations.Add(
                    gcHandlePtr, 
                    new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
            }
开发者ID:RendleLabs,项目名称:corefx,代码行数:55,代码来源:CurlHandler.MultiAgent.cs


示例9: TransferDataFromRequestStream

            /// <summary>
            /// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
            /// request content (non-memory) stream to the buffer.
            /// </summary>
            /// <returns>The number of bytes transferred.</returns>
            private static size_t TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
            {
                MultiAgent multi = easy._associatedMultiAgent;

                // First check to see whether there's any data available from a previous asynchronous read request.
                // If there is, the transfer state's Task field will be non-null, with its Result representing
                // the number of bytes read.  The Buffer will then contain all of that read data.  If the Count
                // is 0, then this is the first time we're checking that Task, and so we populate the Count
                // from that read result.  After that, we can transfer as much data remains between Offset and
                // Count.  Multiple callbacks may pull from that one read.

                EasyRequest.SendTransferState sts = easy._sendTransferState;
                if (sts != null)
                {
                    // Is there a previous read that may still have data to be consumed?
                    if (sts._task != null)
                    {
                        Debug.Assert(sts._task.IsCompleted, "The task must have completed if we're getting called back.");

                        // Determine how many bytes were read on the last asynchronous read.
                        // If nothing was read, then we're done and can simply return 0 to indicate
                        // the end of the stream.
                        int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
                        Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
                        if (bytesRead == 0)
                        {
                            multi.VerboseTrace("End of stream from stored task", easy: easy);
                            sts.SetTaskOffsetCount(null, 0, 0);
                            return 0;
                        }

                        // If Count is still 0, then this is the first time after the task completed
                        // that we're examining the data: transfer the bytesRead to the Count.
                        if (sts._count == 0)
                        {
                            multi.VerboseTrace("ReadAsync completed with bytes: " + bytesRead, easy: easy);
                            sts._count = bytesRead;
                        }

                        // Now Offset and Count are both accurate.  Determine how much data we can copy to libcurl...
                        int availableData = sts._count - sts._offset;
                        Debug.Assert(availableData > 0, "There must be some data still available.");

                        // ... and copy as much of that as libcurl will allow.
                        int bytesToCopy = Math.Min(availableData, length);
                        Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
                        multi.VerboseTrace("Copied " + bytesToCopy + " bytes from request stream", easy: easy);

                        // Update the offset.  If we've gone through all of the data, reset the state 
                        // so that the next time we're called back we'll do a new read.
                        sts._offset += bytesToCopy;
                        Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
                        if (sts._offset == sts._count)
                        {
                            sts.SetTaskOffsetCount(null, 0, 0);
                        }

                        // Return the amount of data copied
                        Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
                        return (size_t)bytesToCopy;
                    }

                    // sts was non-null but sts.Task was null, meaning there was no previous task/data
                    // from which to satisfy any of this request.
                }
                else // sts == null
                {
                    // Allocate a transfer state object to use for the remainder of this request.
                    easy._sendTransferState = sts = new EasyRequest.SendTransferState();
                }

                Debug.Assert(sts != null, "By this point we should have a transfer object");
                Debug.Assert(sts._task == null, "There shouldn't be a task now.");
                Debug.Assert(sts._count == 0, "Count should be zero.");
                Debug.Assert(sts._offset == 0, "Offset should be zero.");

                // If we get here, there was no previously read data available to copy.
                // Initiate a new asynchronous read.
                Task<int> asyncRead = easy._requestContentStream.ReadAsyncInternal(
                    sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
                Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");

                // Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.  
                // Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
                if (asyncRead.IsCompleted)
                {
                    multi.VerboseTrace("ReadAsync completed immediately", easy: easy);

                    // Get the amount of data read.
                    int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
                    if (bytesRead == 0)
                    {
                        multi.VerboseTrace("End of stream from quick returning ReadAsync", easy: easy);
                        return 0;
                    }
//.........这里部分代码省略.........
开发者ID:Cvoid94,项目名称:corefx,代码行数:101,代码来源:CurlHandler.MultiAgent.cs


示例10: RequestUnpause

 /// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
 internal void RequestUnpause(EasyRequest easy)
 {
     VerboseTrace(easy: easy);
     Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
 }
开发者ID:Cvoid94,项目名称:corefx,代码行数:6,代码来源:CurlHandler.MultiAgent.cs


示例11: TryGetEasyRequest

            private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
            {
                Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
                IntPtr gcHandlePtr;
                CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
                Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
                if (getInfoResult == CURLcode.CURLE_OK)
                {
                    try
                    {
                        GCHandle handle = GCHandle.FromIntPtr(gcHandlePtr);
                        easy = (EasyRequest)handle.Target;
                        Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
                        return easy != null;
                    }
                    catch (Exception e)
                    {
                        EventSourceTrace("Error getting state from GCHandle: {0}", e);
                        Debug.Fail($"Exception in {nameof(TryGetEasyRequest)}", e.ToString());
                    }
                }

                easy = null;
                return false;
            }
开发者ID:Dmitry-Me,项目名称:corefx,代码行数:25,代码来源:CurlHandler.SslProvider.cs


示例12: QueueOperationWithRequestContentAsync

        /// <summary>
        /// Loads the request's request content stream asynchronously and 
        /// then submits the request to the multi agent.
        /// </summary>
        private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy)
        {
            Debug.Assert(easy._requestMessage.Content != null, "Expected request to have non-null request content");

            easy._requestContentStream = await easy._requestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
            if (easy._cancellationToken.IsCancellationRequested)
            {
                easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
                easy.Cleanup(); // no active processing remains, so we can cleanup
            }
            else
            {
                ConfigureAndQueue(easy);
            }
            return await easy.Task.ConfigureAwait(false);
        }
开发者ID:hanzhu101,项目名称:corefx,代码行数:20,代码来源:CurlHandler.cs


示例13: ConfigureAndQueue

 private void ConfigureAndQueue(EasyRequest easy)
 {
     try
     {
         easy.InitializeCurl();
         _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
     }
     catch (Exception exc)
     {
         easy.FailRequest(exc);
         easy.Cleanup(); // no active processing remains, so we can cleanup
     }
 }
开发者ID:hanzhu101,项目名称:corefx,代码行数:13,代码来源:CurlHandler.cs


示例14: SendAsync

        protected internal override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", SR.net_http_handler_norequest);
            }

            if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps))
            {
                throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required);
            }

            if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL)
            {
                throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
            }

            if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
            {
                throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
            }

            if (_useCookie && _cookieContainer == null)
            {
                throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
            }

            // TODO: Check that SendAsync is not being called again for same request object.
            //       Probably fix is needed in WinHttpHandler as well

            CheckDisposed();
            SetOperationStarted();

            // Do an initial cancellation check to avoid initiating the async operation if
            // cancellation has already been requested.  After this, we'll rely on CancellationToken.Register
            // to notify us of cancellation requests and shut down the operation if possible.
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
            }

            // Create the easy request.  This associates the easy request with this handler and configures
            // it based on the settings configured for the handler.
            var easy = new EasyRequest(this, request, cancellationToken);

            // Submit the easy request to the multi agent.
            if (request.Content != null)
            {
                // If there is request content to be sent, preload the stream
                // and submit the request to the multi agent.  This is separated
                // out into a separate async method to avoid associated overheads
                // in the case where there is no request content stream.
                return QueueOperationWithRequestContentAsync(easy);
            }
            else
            {
                // Otherwise, just submit the request.
                ConfigureAndQueue(easy);
                return easy.Task;
            }
        }
开发者ID:hanzhu101,项目名称:corefx,代码行数:63,代码来源:CurlHandler.cs


示例15: TryParseStatusLine

        private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
        {
            if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
            response.Headers.Clear();

            response.Content.Headers.Clear();

            int responseHeaderLength = responseHeader.Length;

            // Check if line begins with HTTP/1.1 or HTTP/1.0
            int prefixLength = HttpPrefix.Length;
            int versionIndex = prefixLength + 2;

            if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
            {
                response.Version =
                    responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
                    responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
                    new Version(0, 0);
            }
            else
            {
                response.Version = new Version(0, 0);
            }

            // TODO: Parsing errors are treated as fatal. Find right behaviour

            int spaceIndex = responseHeader.IndexOf(SpaceChar);

            if (spaceIndex > -1)
            {
                int codeStartIndex = spaceIndex + 1;
                int statusCode = 0;

                // Parse first 3 characters after a space as status code
                if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
                {
                    response.StatusCode = (HttpStatusCode)statusCode;

                    // For security reasons, we drop the server credential if it is a
                    // NetworkCredential.  But we allow credentials in a CredentialCache
                    // since they are specifically tied to URI's.
                    if ((response.StatusCode == HttpStatusCode.Redirect) && !(state._handler.Credentials is CredentialCache))
                    {
                        state.SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.None);
                        state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
                        state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
                        state._networkCredential = null;
                    }

                    int codeEndIndex = codeStartIndex + StatusCodeLength;

                    int reasonPhraseIndex = codeEndIndex + 1;

                    if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
                    {
                        int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
                        int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
                        response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
                    }
                }
            }

            return true;
        }
开发者ID:blueszs,项目名称:corefx,代码行数:70,代码来源:CurlHandler.cs


示例16: SetSslOptions

            internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
            {
                Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);

                // Create a client certificate provider if client certs may be used.
                X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
                ClientCertificateProvider certProvider =
                    clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
                    clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
                    null; // manual without certs
                IntPtr userPointer = IntPtr.Zero;
                if (certProvider != null)
                {
                    // The client cert provider needs to be passed through to the callback, and thus
                    // we create a GCHandle to keep it rooted.  This handle needs to be cleaned up
                    // when the request has completed, and a simple and pay-for-play way to do that
                    // is by cleaning it up in a continuation off of the request.
                    userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
                    easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
                        CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                }

                // Register the callback with libcurl.  We need to register even if there's no user-provided
                // server callback and even if there are no client certificates, because we support verifying
                // server certificates against more than those known to OpenSSL.
                CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
                switch (answer)
                {
                    case CURLcode.CURLE_OK:
                        // We successfully registered.  If we'll be invoking a user-provided callback to verify the server
                        // certificate as part of that, disable libcurl's verification of the host name.  The user's callback
                        // needs to be given the opportunity to examine the cert, and our logic will determine whether
                        // the host name matches and will inform the callback of that.
                        if (easy._handler.ServerCertificateValidationCallback != null)
                        {
                            easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname
                            // We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause
                            // SSL and libcurl to ignore the result of the server callback.
                        }

                        // The allowed SSL protocols will be set in the configuration callback.
                        break;

                    case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
                    case CURLcode.CURLE_NOT_BUILT_IN:   // Curl 7.39 and later
                        // It's ok if we failed to register the callback if all of the defaults are in play
                        // with relation to handling of certificates.  But if that's not the case, failing to 
                        // register the callback will result in those options not being factored in, which is
                        // a significant enough error that we need to fail.
                        EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer, easy: easy);
                        if (certProvider != null ||
                            easy._handler.ServerCertificateValidationCallback != null ||
                            easy._handler.CheckCertificateRevocationList)
                        {
                            throw new PlatformNotSupportedException(
                                SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription));
                        }

                        // Since there won't be a callback to configure the allowed SSL protocols, configure them here.
                        SetSslVersion(easy);

                        break;

                    default:
                        ThrowIfCURLEError(answer);
                        break;
                }
            }
开发者ID:ESgarbi,项目名称:corefx,代码行数:68,代码来源:CurlHandler.SslProvider.cs


示例17: SetSslVersion

            private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
            {
                // Get the requested protocols.
                System.Security.Authentication.SslProtocols protocols = easy._handler.ActualSslProtocols;

                // We explicitly disallow choosing SSL2/3. Make sure they were filtered out.
                Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0, 
                    "Disallowed protocols should have been filtered out.");

                // libcurl supports options for either enabling all of the TLS1.* protocols or enabling 
                // just one of them; it doesn't currently support enabling two of the three, e.g. you can't 
                // pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
                Interop.Http.CurlSslVersion curlSslVersion;
                switch (protocols)
                {
                    case System.Security.Authentication.SslProtocols.Tls:
                        curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
                        break;
                    case System.Security.Authentication.SslProtocols.Tls11:
                        curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
                        break;
                    case System.Security.Authentication.SslProtocols.Tls12:
                        curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
                        break;

                    case System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12:
                        curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
                        break;

                    default:
                        throw new NotSupportedException(SR.net_securityprotocolnotsupported);
                }

                try
                {
                    easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
                }
                catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
                {
                    throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
                }
            }
开发者ID:ESgarbi,项目名称:corefx,代码行数:42,代码来源:CurlHandler.SslProvider.cs


示例18: TryParseStatusLine

        private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
        {
            if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
            response.Headers.Clear();

            response.Content.Headers.Clear();

            int responseHeaderLength = responseHeader.Length;

            // Check if line begins with HTTP/1.1 or HTTP/1.0
            int prefixLength = HttpPrefix.Length;
            int versionIndex = prefixLength + 2;

            if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
            {
                response.Version =
                    responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
                    responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
                    new Version(0, 0);
            }
            else
            {
                response.Version = new Version(0, 0);
            }

            // TODO: Parsing errors are treated as fatal. Find right behaviour

            int spaceIndex = responseHeader.IndexOf(SpaceChar);

            if (spaceIndex > -1)
            {
                int codeStartIndex = spaceIndex + 1;
                int statusCode = 0;

                // Parse first 3 characters after a space as status code
                if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
                {
                    response.StatusCode = (HttpStatusCode)statusCode;

                    int codeEndIndex = codeStartIndex + StatusCodeLength;

                    int reasonPhraseIndex = codeEndIndex + 1;

                    if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
                    {
                        int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
                        int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
                        response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
                    }
                    state._isRedirect = state._handler.AutomaticRedirection &&
                         (response.StatusCode == HttpStatusCode.Redirect ||
                         response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
                         response.StatusCode == HttpStatusCode.RedirectMethod) ;
                }
            }

            return true;
        }
开发者ID:antonfirsov,项目名称:corefx,代码行数:63,代码来源:CurlHandler.cs


示例19: FinishRequest

            private void FinishRequest(EasyRequest completedOperation, CURLcode messageResult)
            {
                VerboseTrace("messageResult: " + messageResult, easy: completedOperation);

                if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized)
                {
                    if (completedOperation._handler.PreAuthenticate)
                    {
                        long authAvailable;
                        if (Interop.Http.EasyGetInfoLong(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out authAvailable) == CURLcode.CURLE_OK)
                        {
                            completedOperation._handler.AddCredentialToCache(
                               completedOperation._requestMessage.RequestUri, (CURLAUTH)authAvailable, completedOperation._networkCredential);
                        }
                        // Ignore errors: no need to fail for the sake of putting the credentials into the cache
                    }

                    completedOperation._handler.AddResponseCookies(
                        completedOperation._requestMessage.RequestUri, completedOperation._responseMessage);
                }

                // Complete or fail the request
                try
                {
                    bool unsupportedProtocolRedirect = messageResult == CURLcode.CURLE_UNSUPPORTED_PROTOCOL && completedOperation._isRedirect;
                    if (!unsupportedProtocolRedirect)
                    {
                     

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# EcasAction类代码示例发布时间:2022-05-24
下一篇:
C# EasingType类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap