在本文中,我们将给您介绍关于SysInternal的WinObj设备列表机制的详细内容,并且为您解答win10设备列表的相关问题,此外,我们还将为您提供关于ASP.NETMVC"SignInManag
在本文中,我们将给您介绍关于SysInternal的WinObj设备列表机制的详细内容,并且为您解答win10设备列表的相关问题,此外,我们还将为您提供关于ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);"一直返回失败、c# – Internals,InternalsVisibleTo和测试共享行为、c# – “ceq”MSIL命令和object.InternalEquals之间的区别、com.squareup.okhttp.internal.Internal的实例源码的知识。
本文目录一览:- SysInternal的WinObj设备列表机制(win10设备列表)
- ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);"一直返回失败
- c# – Internals,InternalsVisibleTo和测试共享行为
- c# – “ceq”MSIL命令和object.InternalEquals之间的区别
- com.squareup.okhttp.internal.Internal的实例源码
SysInternal的WinObj设备列表机制(win10设备列表)
SysInternals的WinObj可以列出所有设备对象。
我想知道如何列出设备。
有没有我们可以阅读的开源代码?(或代码片段)
什么是我应该知道的最重要的function?
虚拟内存中的两个进程
如何找出物理内存的哪些部分包含哪些进程的数据/指令?
杀-9和生产应用程序
从Powershell确定操作系统版本,Linux和Windows
OpenELEC上apt-get的等价物
操作系统如何知道物理内存的真实大小?
16位内核有错误
Windows和Mac的窗口pipe理器
为什么不能直接与对方进行沟通?
使用waitpid还是sigaction?
WinObj使用NT系统调用NtOpenDirectoryObject和NtQueryDirectoryObject 。 没有需要的驱动程序或内核代码。 您将不会看到导入,因为这些NT函数通过LoadLibrary / GetProcAddress加载。
您不必枚举整个对象名称空间。 如果您对设备对象感兴趣,请使用"Device"调用NtQueryDirectoryObject ,然后在返回的句柄上调用NtQueryDirectoryObject 。
根据SysInternals的网页 :
本地NT API提供的例程允许用户模式程序浏览命名空间并查询位于那里的对象的状态,但是这些接口是未记录的。
我试着看WinObj的导入表( dumpbin /imports winobj.exe ),但没有明显的嫌疑人:-(
您可以使用NtOpenDirectoryObject和NtQueryDirectoryObject来增加给定目录中的对象列表。
要获取对象命名空间的详细信息,您必须使用Windows NT未记录的API。 这也是由WinObj使用,因为它在这里描述WinOBj如何得到所有的结果..以及那些谁说我们需要一个驱动程序来做到这一点,请阅读给定的页面上的这些行。
“一个显而易见的方法是使用驱动程序 – 在内核模式下,一切都可以访问 – 所以客户端应用程序可以通过与自己的驱动程序进行通信来获取所需的信息。然而,WinObj不使用驱动程序(这是它能够执行的一个原因没有管理员权限,尽管管理员权限显示所有对象,而不是部分结果)“。
根据user1575778的答案,可以使用NtOpenDirectoryObject和NtQueryDirectoryObject (它们分别来自用户模式和ZwQueryDirectoryObject和ZwQueryDirectoryObject )来列出对象管理器名称空间中的对象。
看一下NT对象objmgr.hpp ( 又名ntobjx) ,特别是NtObjMgr::Directory (或DirectoryT )类。 它提供了很好的包装到C ++类中的相同功能。 整个公用程序是自由许可的开放源代码(由于WTL使用:MIT和MS-PL的双重许可),所以只要遵守许可条款,就可以重复使用零碎的碎片。
但是这里有一个简单的C ++代码示例, 仅仅是您的用例:
#include <Windows.h> #include <tchar.h> #include <cstdio> #include <winternl.h> NTSTATUS (NTAPI* NtOpenDirectoryObject)(PHANDLE,ACCESS_MASK,POBJECT_ATTRIBUTES); NTSTATUS (NTAPI* NtQueryDirectoryObject)(HANDLE,PVOID,ULONG,BOOLEAN,PULONG,PULONG); VOID (NTAPI* RtlInitUnicodeString_)(PUNICODE_STRING,PCWSTR); NTSTATUS (NTAPI* NtClose_)(HANDLE); #define DIRECTORY_QUERY (0x0001) #define DIRECTORY_TRAVERSE (0x0002) typedef struct _OBJECT_DIRECTORY_informatION { UNICODE_STRING Name; UNICODE_STRING TypeName; } OBJECT_DIRECTORY_informatION,*POBJECT_DIRECTORY_informatION; #ifndef STATUS_SUCCESS #define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth #endif // STATUS_SUCCESS #ifndef STATUS_MORE_ENTRIES #define STATUS_MORE_ENTRIES ((NTSTATUS)0x00000105L) #endif // STATUS_MORE_ENTRIES #ifndef STATUS_NO_MORE_ENTRIES #define STATUS_NO_MORE_ENTRIES ((NTSTATUS)0x8000001AL) #endif // STATUS_NO_MORE_ENTRIES int PrintDevices() { NTSTATUS ntStatus; OBJECT_ATTRIBUTES oa; UNICODE_STRING objname; HANDLE hDeviceDir = NULL; RtlInitUnicodeString_(&objname,L"\Device"); InitializeObjectAttributes(&oa,&objname,NULL,NULL); ntStatus = NtOpenDirectoryObject(&hDeviceDir,DIRECTORY_QUERY | DIRECTORY_TRAVERSE,&oa); if(NT_SUCCESS(ntStatus)) { size_t const bufSize = 0x10000; BYTE buf[bufSize] = {0}; ULONG start = 0,idx = 0,bytes; BOOLEAN restart = TRUE; for(;;) { ntStatus = NtQueryDirectoryObject(hDeviceDir,PBYTE(buf),bufSize,FALSE,restart,&idx,&bytes); if(NT_SUCCESS(ntStatus)) { POBJECT_DIRECTORY_informatION const pdilist = reinterpret_cast<POBJECT_DIRECTORY_informatION>(PBYTE(buf)); for(ULONG i = 0; i < idx - start; i++) { if(0 == wcsncmp(pdilist[i].TypeName.Buffer,L"Device",pdilist[i].TypeName.Length / sizeof(WCHAR))) { _tprintf(_T("%sn"),pdilist[i].Name.Buffer); } } } if(STATUS_MORE_ENTRIES == ntStatus) { start = idx; restart = FALSE; continue; } if((STATUS_SUCCESS == ntStatus) || (STATUS_NO_MORE_ENTRIES == ntStatus)) { break; } } (void)NtClose_(hDeviceDir); return 0; } _tprintf(_T("Failed NtOpenDirectoryObject with 0x%08X"),ntStatus); return 1; } int _tmain(int /*argc*/,_TCHAR** /*argv*/) { HMODULE hNtDll = ::GetmoduleeHandle(_T("ntdll.dll")); *(FARPROC*)&NtOpenDirectoryObject = ::GetProcAddress(hNtDll,"NtOpenDirectoryObject"); *(FARPROC*)&NtQueryDirectoryObject = ::GetProcAddress(hNtDll,"NtQueryDirectoryObject"); *(FARPROC*)&RtlInitUnicodeString_ = ::GetProcAddress(hNtDll,"RtlInitUnicodeString"); *(FARPROC*)&NtClose_ = ::GetProcAddress(hNtDll,"NtClose"); if (!NtOpenDirectoryObject || !NtQueryDirectoryObject || !RtlInitUnicodeString_ || !NtClose_) { _tprintf(_T("Failed to retrieve ntdll.dll function pointersn")); return 1; } return PrintDevices(); }
一些注释:这不会深入子目录,它不会列出任何类型的Device ,它不会解析符号链接,如果有的话。 对于任何这些功能,请查看上述实用程序的源代码并根据需要进行调整。 winternl.h应该可以在任何最近的Windows SDK中使用。
函数RtlInitUnicodeString_和NtClose_具有尾部下划线,以避免与在winternl.h中声明的这些本地API函数发生冲突,但使用__declspec(dllimport) 。
披露:我是ntobjx的作者。
您可以从SetupDiCreateDeviceInfoList开始,使用其他相关函数来枚举所有设备。 这东西是痛苦的使用。
ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);"一直返回失败
如何解决ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);"一直返回失败?
我对 ExternalLogin 操作进行了一些更改。我在我的用户表中添加了一个新字段,作为名字,并添加了代码以从 facebook 请求名字。这可能是我收到错误的原因。我不会在这里发布用于 facebook 外部登录的应用程序机密,但您知道它存在于我的代码中。当我向 facebook 注册一个新用户时,它会工作并保持用户登录状态,并将用户添加到数据库中,也会得到正确的名字。但是,当我注销并尝试使用 facebook 登录时,它会强制我注册而不是登录(它重定向到使用 facebook 页面的注册,说“您已成功通过 facebook 进行身份验证。请输入此站点的用户名”并单击注册按钮完成登录。”) 这是我所做更改的代码: 在 Startup.Auth 类中:
app.UseFacebookAuthentication(new FacebookAuthenticationoptions()
{
AppId = "2737863089761791",AppSecret = "",BackchannelHttpHandler = new httpclienthandler(),UserinformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",Scope = { "email" },Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccesstoken",context.Accesstoken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}",claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType,claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType,claimValue,"XmlSchemaString","Facebook"));
}
}
}
});
在我的 AccountController 中的 ExternalLoginCallback 操作中:
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
var firstName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name").Value;
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo,isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Requiresverification:
return RedirectToAction("SendCode",new { ReturnUrl = returnUrl,RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account,then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation",new ExternalLoginConfirmationviewmodel { Email = loginInfo.Email,Name = firstName });
}
我认为它会将我重定向到注册页面,因为该行
var result = await SignInManager.ExternalSignInAsync(loginInfo,isPersistent: false);
在 ExternalLoginCallback 内部返回失败,我不知道为什么。它必须返回成功才能进入案例:
case SignInStatus.Success
我的 ExternalLoginConfirmation 操作出错,所以我将一些代码放在 try-catch 块中。它解决了我的问题,但我仍然不知道错误来自哪里:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationviewmodel model,string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index","Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Name,Email = model.Email,Name = model.Name};
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
try
{
var useraux = await UserManager.FindByEmailAsync(model.Email);
result = await UserManager.AddLoginAsync(useraux.Id,info.Login);
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",eve.Entry.Entity.GetType().Name,eve.Entry.State);
Response.Write("Object: " + eve.Entry.Entity.ToString());
Response.Write(" " +
"");
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\",Error: \"{1}\"",ve.PropertyName,ve.ErrorMessage);
Response.Write(ve.ErrorMessage + "" +
"");
}
}
//throw;
}
if (result.Succeeded)
{
//--
//await StoreFacebookAuthToken(user);
await SignInManager.SignInAsync(user,isPersistent: false,rememberbrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
c# – Internals,InternalsVisibleTo和测试共享行为
我们还对所有这些实现进行了测试,所有这些实现都继承自名为TestOperationCommon的基类,这些基类使用实际操作类进行模板化,并将Create方法的类型模板化为新的此类操作.我们为TestOperationCommon实现了一个最多五个模板参数(这对所有操作都足够了).
现在,最近决定将所有操作实现内部并且只公开IOperation,这似乎是一个好主意,因为那些操作是实现细节.而[InternalsVisibleto(…)]测试似乎也解决了.
但是,现在我看到我们不能再使用我们的测试结构,因为公共测试类的通用参数现在是内部的(至少是测试中的实际类),这导致
可访问性不一致….比…更难访问
错误.下面的代码,公共测试类不能从TestOperationCommon继承内部的泛型参数T.但是将所有这些共享行为测试复制到特定测试中似乎也是一个坏主意.
>有没有办法让vstest框架(VS2013)测试内部的[TestClass]?
>或者还有另一种方法可以保持共享测试而不必复制大量代码吗?
>或者我们做错了(将那些’实现细节 – 类’内部化)?
代码示例作为评论中的请求:
public interface IOperation { ... } internal class SomeOperation : IOperation { public SomeOperation(A a,B b,C c) {...} } public abstract TestOperationCommon<T,A,B,C> where T : IOperation where ... { protected abstract T Create(A a,C c); [TestMethod] public void TestCommonoperationBehavior() { var op = Create(Mock.Of<A>(),Mock.Of<B>(),Mock.Of<C>); ... } } [TestClass] public class TestSomeOperation : TestOperationCommon<SomeOperation,...> { [TestMethod] public void TestSpecificSomeOperationStuff() {} }
解决方法
就像是:
[TestClass] public class AnnoyingTestSomeOperationWrapper { [TestMethod] public void TestSpecificSomeOperationStuff() { new TestSomeOperation().TestSpecificSomeOperationStuff() } } internal class TestSomeOperation : TestOperationCommon<SomeOperation,...> { public void TestSpecificSomeOperationStuff() {} }
c# – “ceq”MSIL命令和object.InternalEquals之间的区别
> ==被编译为“ceq”MSIL命令
> object.Equals保持不变
> object.Equals调用
object.InternalEquals
This问题告诉我如何找出InternalEquals如何实现,即在.cpp类中(或者在CLR中的某个地方).
我的问题是:
ceq成为什么?另一个.cpp类中的另一种方法?即它们是完全不同的代码?因此,虽然==和Equals的默认行为看起来是相同的,但它是不同的代码?
解决方法
您将使用Reflector作为Decimal.op_Equality()方法找回它.这将引导您进入FCallCompare,这是一种归因于MethodImplOptions.InternalCall的方法.这些方法很特殊,抖动对它们有秘密的了解.您可以通过Rotor中的clr / src / vm / ecall.cpp源代码文件找到它们的实现.它包含所有内部调用函数的表,抖动通过方法名称查找表条目.然后将表中提供的相应C函数的地址编译为调用指令.请注意,自Rotor发布以来,函数名称已更改,搜索FCallAdd,它是表中的下一个条目.这将带您到COMDecimal :: Compare.这将带您到comdecimal.cpp源代码文件.
x86和x64抖动知道如何直接将ceq操作码转换为机器代码而无需辅助函数,它会内联生成本机机器指令.实际生成的代码取决于要比较的值的类型.目标,x64抖动使用SSE指令,x86使用FPU指令来比较浮点值.当然,其他的紧张情绪会以不同的方式实现它们.
像Object.InternalEquals()这样的辅助函数也是一个内部方法,就像FCallCompare一样.您将使用相同的策略来查找实现.
com.squareup.okhttp.internal.Internal的实例源码
private int pruneAndGetAllocationCount(RealConnection connection,long Now) { List<Reference<StreamAllocation>> references = connection.allocations; int i = 0; while (i < references.size()) { if (((Reference) references.get(i)).get() != null) { i++; } else { Internal.logger.warning("A connection to " + connection.getRoute().getAddress() .url() + " was leaked. Did you forget to close a response body?"); references.remove(i); connection.noNewStreams = true; if (references.isEmpty()) { connection.idleAtNanos = Now - this.keepAliveDurationNs; return 0; } } } return references.size(); }
protected void execute() { boolean signalledCallback = false; try { Response response = Call.this.getResponseWithInterceptorChain(this.forWebSocket); if (Call.this.canceled) { this.responseCallback.onFailure(Call.this.originalRequest,new IOException ("Canceled")); } else { signalledCallback = true; this.responseCallback.onResponse(response); } Call.this.client.getdispatcher().finished(this); } catch (IOException e) { if (signalledCallback) { Internal.logger.log(Level.INFO,"Callback failure for " + Call.this .toLoggableString(),e); } else { this.responseCallback.onFailure(Call.this.engine == null ? Call.this .originalRequest : Call.this.engine.getRequest(),e); } Call.this.client.getdispatcher().finished(this); } catch (Throwable th) { Call.this.client.getdispatcher().finished(this); } }
protected final void endOfInput(boolean paramBoolean) throws IOException { if (httpconnection.this.state != 5) { throw new IllegalStateException("state: " + httpconnection.this.state); } httpconnection.access$402(httpconnection.this,0); if ((paramBoolean) && (httpconnection.this.onIdle == 1)) { httpconnection.access$902$76e0d70f(httpconnection.this); Internal.instance.recycle(httpconnection.this.pool,httpconnection.this.connection); } while (httpconnection.this.onIdle != 2) { return; } httpconnection.access$402(httpconnection.this,6); httpconnection.this.connection.socket.close(); }
public RouteSelector(Address paramAddress,URI paramURI,OkHttpClient paramOkHttpClient,Request paramRequest) { this.address = paramAddress; this.uri = paramURI; this.client = paramOkHttpClient; this.pool = paramOkHttpClient.connectionPool; this.routeDatabase = Internal.instance.routeDatabase(paramOkHttpClient); this.network = Internal.instance.network(paramOkHttpClient); this.request = paramRequest; Proxy localProxy = paramAddress.proxy; if (localProxy != null) { this.proxies = Collections.singletonList(localProxy); } for (;;) { this.nextProxyIndex = 0; return; this.proxies = new ArrayList(); List localList = this.client.proxySelector.select(paramURI); if (localList != null) { this.proxies.addAll(localList); } this.proxies.removeAll(Collections.singleton(Proxy.NO_PROXY)); this.proxies.add(Proxy.NO_PROXY); } }
public final void connectFailed(Connection paramConnection,IOException paramIOException) { if (Internal.instance.recycleCount(paramConnection) > 0) {} for (;;) { return; Route localRoute1 = paramConnection.route; if ((localRoute1.proxy.type() != Proxy.Type.DIRECT) && (this.address.proxySelector != null)) { this.address.proxySelector.connectFailed(this.uri,localRoute1.proxy.address(),paramIOException); } this.routeDatabase.Failed(localRoute1); if ((!(paramIOException instanceof SSLHandshakeException)) && (!(paramIOException instanceof SSLProtocolException))) { while (this.nextSpecIndex < this.connectionSpecs.size()) { List localList = this.connectionSpecs; int i = this.nextSpecIndex; this.nextSpecIndex = (i + 1); ConnectionSpec localConnectionSpec = (ConnectionSpec)localList.get(i); boolean bool = shouldSendTlsFallbackIndicator(localConnectionSpec); Route localRoute2 = new Route(this.address,this.lastProxy,this.lastInetSocketAddress,localConnectionSpec,bool); this.routeDatabase.Failed(localRoute2); } } } }
public HttpEngine(OkHttpClient paramOkHttpClient,Request paramRequest,boolean paramBoolean1,boolean paramBoolean2,boolean paramBoolean3,Connection paramConnection,RouteSelector paramRouteSelector,RetryableSink paramRetryableSink,Response paramResponse) { this.client = paramOkHttpClient; this.userRequest = paramRequest; this.bufferRequestBody = paramBoolean1; this.callerWritesRequestBody = paramBoolean2; this.forWebSocket = paramBoolean3; this.connection = paramConnection; this.routeSelector = paramRouteSelector; this.requestBodyOut = null; this.priorResponse = paramResponse; if (paramConnection != null) { Internal.instance.setowner(paramConnection,this); this.route = paramConnection.route; return; } this.route = null; }
public final Response readNetworkResponse() throws IOException { this.transport.finishRequest(); Response.Builder localBuilder1 = this.transport.readResponseHeaders(); localBuilder1.request = this.networkRequest; localBuilder1.handshake = this.connection.handshake; Response localResponse = localBuilder1.header(OkHeaders.SENT_MILLIS,Long.toString(this.sentRequestMillis)).header(OkHeaders.RECEIVED_MILLIS,Long.toString(System.currentTimeMillis())).build(); if (!this.forWebSocket) { Response.Builder localBuilder2 = localResponse.newBuilder(); localBuilder2.body = this.transport.openResponseBody(localResponse); localResponse = localBuilder2.build(); } Internal.instance.setProtocol(this.connection,localResponse.protocol); return localResponse; }
public final void releaseConnectionOnIdle() throws IOException { if (canReuseConnection()) { httpconnection localhttpconnection2 = this.httpconnection; localhttpconnection2.onIdle = 1; if (localhttpconnection2.state == 0) { localhttpconnection2.onIdle = 0; Internal.instance.recycle(localhttpconnection2.pool,localhttpconnection2.connection); } } httpconnection localhttpconnection1; do { return; localhttpconnection1 = this.httpconnection; localhttpconnection1.onIdle = 2; } while (localhttpconnection1.state != 0); localhttpconnection1.state = 6; localhttpconnection1.connection.socket.close(); }
/** * Closes the cache entry and makes the socket available for reuse. This * should be invoked when the end of the body has been reached. */ protected final void endOfInput(boolean recyclable) throws IOException { if (state != STATE_READING_RESPONSE_BODY) throw new IllegalStateException("state: " + state); if (cacheRequest != null) { cacheBody.close(); } state = STATE_IDLE; if (recyclable && onIdle == ON_IDLE_POOL) { onIdle = ON_IDLE_HOLD; // Set the on idle policy back to the default. Internal.instance.recycle(pool,connection); } else if (onIdle == ON_IDLE_CLOSE) { state = STATE_CLOSED; connection.getSocket().close(); } }
/** * Clients should invoke this method when they encounter a connectivity * failure on a connection returned by this route selector. */ public void connectFailed(Connection connection,IOException failure) { // If this is a recycled connection,don't count its failure against the route. if (Internal.instance.recycleCount(connection) > 0) return; Route FailedRoute = connection.getRoute(); if (FailedRoute.getProxy().type() != Proxy.Type.DIRECT && proxySelector != null) { // Tell the proxy selector when we fail to connect on a fresh connection. proxySelector.connectFailed(uri,FailedRoute.getProxy().address(),failure); } routeDatabase.Failed(FailedRoute); // If the prevIoUsly returned route's problem was not related to TLS,and // the next route only changes the TLS mode,we shouldn't even attempt it. // This suppresses it in both this selector and also in the route database. if (!(failure instanceof SSLHandshakeException) && !(failure instanceof SSLProtocolException)) { while (hasNextTlsversion()) { Route toSuppress = new Route(address,lastProxy,lastInetSocketAddress,nextTlsversion()); routeDatabase.Failed(toSuppress); } } }
/** * @param request the HTTP request without a body. The body must be * written via the engine's request body stream. * @param connection the connection used for an intermediate response * immediately prior to this request/response pair,such as a same-host * redirect. This engine assumes ownership of the connection and must * release it when it is unneeded. * @param routeSelector the route selector used for a Failed attempt * immediately preceding this attempt,or null if this request doesn't * recover from a failure. */ public HttpEngine(OkHttpClient client,Request request,boolean bufferRequestBody,Connection connection,RouteSelector routeSelector,RetryableSink requestBodyOut,Response priorResponse) { this.client = client; this.userRequest = request; this.bufferRequestBody = bufferRequestBody; this.connection = connection; this.routeSelector = routeSelector; this.requestBodyOut = requestBodyOut; this.priorResponse = priorResponse; if (connection != null) { Internal.instance.setowner(connection,this); this.route = connection.getRoute(); } else { this.route = null; } }
private void maybeCache() throws IOException { InternalCache responsecache = Internal.instance.internalCache(client); if (responsecache == null) return; // Should we cache this response for this request? if (!CacheStrategy.isCacheable(userResponse,networkRequest)) { if (HttpMethod.invalidatesCache(networkRequest.method())) { try { responsecache.remove(networkRequest); } catch (IOException ignored) { // The cache cannot be written. } } return; } // Offer this request to the cache. storeRequest = responsecache.put(stripBody(userResponse)); }
/** * @return a new http client */ private OkHttpClient createHttpClient() { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(connectorOptions.getReadTimeout(),TimeUnit.SECONDS); client.setWriteTimeout(connectorOptions.getWriteTimeout(),TimeUnit.SECONDS); client.setConnectTimeout(connectorOptions.getConnectTimeout(),TimeUnit.SECONDS); client.setFollowRedirects(connectorOptions.isFollowRedirects()); client.setFollowSslRedirects(connectorOptions.isFollowRedirects()); client.setProxySelector(ProxySelector.getDefault()); client.setCookieHandler(CookieHandler.getDefault()); client.setCertificatePinner(CertificatePinner.DEFAULT); client.setAuthenticator(AuthenticatorAdapter.INSTANCE); client.setConnectionPool(ConnectionPool.getDefault()); client.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); client.setConnectionSpecs(DEFAULT_CONNECTION_Specs); client.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(client,Network.DEFAULT); return client; }
/** * Constructor. * @param metricsServer */ public HawkularMetricsClient(URL metricsServer) { this.serverUrl = metricsServer; httpClient = new OkHttpClient(); httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT,TimeUnit.SECONDS); httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT,TimeUnit.SECONDS); httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT,TimeUnit.SECONDS); httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); httpClient.setProxySelector(ProxySelector.getDefault()); httpClient.setCookieHandler(CookieHandler.getDefault()); httpClient.setCertificatePinner(CertificatePinner.DEFAULT); httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE); httpClient.setConnectionPool(ConnectionPool.getDefault()); httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); httpClient.setConnectionSpecs(DEFAULT_CONNECTION_Specs); httpClient.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(httpClient,Network.DEFAULT); }
public Headers readHeaders() throws IOException { Builder headers = new Builder(); while (true) { String line = this.source.readUtf8Linestrict(); if (line.length() == 0) { return headers.build(); } Internal.instance.addLenient(headers,line); } }
private void maybeCache() throws IOException { InternalCache responsecache = Internal.instance.internalCache(this.client); if (responsecache != null) { if (CacheStrategy.isCacheable(this.userResponse,this.networkRequest)) { this.storeRequest = responsecache.put(stripBody(this.userResponse)); } else if (HttpMethod.invalidatesCache(this.networkRequest.method())) { try { responsecache.remove(this.networkRequest); } catch (IOException e) { } } } }
private void deallocate(boolean noNewStreams,boolean released,boolean streamFinished) { RealConnection connectionToClose = null; synchronized (this.connectionPool) { if (streamFinished) { this.stream = null; } if (released) { this.released = true; } if (this.connection != null) { if (noNewStreams) { this.connection.noNewStreams = true; } if (this.stream == null && (this.released || this.connection.noNewStreams)) { release(this.connection); if (this.connection.streamCount > 0) { this.routeSelector = null; } if (this.connection.allocations.isEmpty()) { this.connection.idleAtNanos = System.nanoTime(); if (Internal.instance.connectionBecameIdle(this.connectionPool,this .connection)) { connectionToClose = this.connection; } } this.connection = null; } } } if (connectionToClose != null) { Util.closeQuietly(connectionToClose.getSocket()); } }
private HttpEngine newHttpEngine(String method,StreamAllocation streamAllocation,RetryableSink requestBody,Response priorResponse) throws MalformedURLException,UnkNownHostException { Request.Builder builder = new Request.Builder().url(Internal.instance.getHttpUrlChecked (getURL().toString())).method(method,HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null); Headers headers = this.requestHeaders.build(); int size = headers.size(); for (int i = 0; i < size; i++) { builder.addHeader(headers.name(i),headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.permitsRequestBody(method)) { if (this.fixedContentLength != -1) { builder.header("Content-Length",Long.toString(this.fixedContentLength)); } else if (this.chunkLength > 0) { builder.header("transfer-encoding","chunked"); } else { bufferRequestBody = true; } if (headers.get("Content-Type") == null) { builder.header("Content-Type",Client.FormMime); } } if (headers.get(Network.USER_AGENT) == null) { builder.header(Network.USER_AGENT,defaultUserAgent()); } Request request = builder.build(); OkHttpClient engineClient = this.client; if (!(Internal.instance.internalCache(engineClient) == null || getUseCaches())) { engineClient = this.client.clone().setCache(null); } return new HttpEngine(engineClient,request,bufferRequestBody,true,false,streamAllocation,requestBody,priorResponse); }
public final void readHeaders(Headers.Builder paramBuilder) throws IOException { for (;;) { String str = this.source.readUtf8Linestrict(); if (str.length() == 0) { break; } Internal.instance.addLine(paramBuilder,str); } }
public final Connection close() { if (this.bufferedRequestBody != null) { Util.closeQuietly(this.bufferedRequestBody); } while (this.userResponse == null) { if (this.connection != null) { Util.closeQuietly(this.connection.socket); } this.connection = null; return null; if (this.requestBodyOut != null) { Util.closeQuietly(this.requestBodyOut); } } Util.closeQuietly(this.userResponse.body); if ((this.transport != null) && (this.connection != null) && (!this.transport.canReuseConnection())) { Util.closeQuietly(this.connection.socket); this.connection = null; return null; } if ((this.connection != null) && (!Internal.instance.clearOwner(this.connection))) { this.connection = null; } Connection localConnection = this.connection; this.connection = null; return localConnection; }
/** * Configure this connection to put itself back into the connection pool when * the HTTP response body is exhausted. */ public void poolOnIdle() { onIdle = ON_IDLE_POOL; // If we're already idle,go to the pool immediately. if (state == STATE_IDLE) { onIdle = ON_IDLE_HOLD; // Set the on idle policy back to the default. Internal.instance.recycle(pool,connection); } }
/** Reads headers or trailers into {@code builder}. */ public void readHeaders(Headers.Builder builder) throws IOException { // parse the result headers until the first blank line for (String line; (line = source.readUtf8Linestrict()).length() != 0; ) { Internal.instance.addLine(builder,line); } }
/** * Returns the next route address to attempt. * * @throws NoSuchElementException if there are no more routes to attempt. */ public Connection next(String method) throws IOException { // Always prefer pooled connections over new connections. for (Connection pooled; (pooled = pool.get(address)) != null; ) { if (method.equals("GET") || Internal.instance.isReadable(pooled)) return pooled; pooled.getSocket().close(); } // Compute the next route to attempt. if (!hasNextTlsversion()) { if (!hasNextInetSocketAddress()) { if (!hasNextProxy()) { if (!hasNextPostponed()) { throw new NoSuchElementException(); } return new Connection(pool,nextPostponed()); } lastProxy = nextProxy(); resetNextInetSocketAddress(lastProxy); } lastInetSocketAddress = nextInetSocketAddress(); resetNextTlsversion(); } String tlsversion = nextTlsversion(); Route route = new Route(address,tlsversion); if (routeDatabase.shouldPostpone(route)) { postponedRoutes.add(route); // We will only recurse in order to skip prevIoUsly Failed routes. They will be // tried last. return next(method); } return new Connection(pool,route); }
/** Connect to the origin server either directly or via a proxy. */ private void connect(Request request) throws IOException { if (connection != null) throw new IllegalStateException(); if (routeSelector == null) { String uriHost = request.url().getHost(); if (uriHost == null || uriHost.length() == 0) { throw new UnkNownHostException(request.url().toString()); } SSLSocketFactory sslSocketFactory = null; HostnameVerifier hostnameVerifier = null; if (request.isHttps()) { sslSocketFactory = client.getSslSocketFactory(); } hostnameVerifier = client.getHostnameVerifier(); Address address = new Address(uriHost,getEffectivePort(request.url()),client.getSocketFactory(),sslSocketFactory,hostnameVerifier,client.getAuthenticator(),client.getProxy(),client.getProtocols()); routeSelector = new RouteSelector(address,request.uri(),client.getProxySelector(),client.getConnectionPool(),Dns.DEFAULT,Internal.instance.routeDatabase(client)); } connection = routeSelector.next(request.method()); Internal.instance.setowner(connection,this); if (!Internal.instance.isConnected(connection)) { Internal.instance.connect(connection,client.getConnectTimeout(),client.getReadTimeout(),client.getWriteTimeout(),tunnelRequest(connection,request)); if (Internal.instance.isspdy(connection)) { Internal.instance.share(client.getConnectionPool(),connection); } Internal.instance.routeDatabase(client).connected(connection.getRoute()); } Internal.instance.setTimeouts(connection,client.getWriteTimeout()); route = connection.getRoute(); }
/** * Release any resources held by this engine. If a connection is still held by * this engine,it is returned. */ public Connection close() { if (bufferedRequestBody != null) { // This also closes the wrapped requestBodyOut. closeQuietly(bufferedRequestBody); } else if (requestBodyOut != null) { closeQuietly(requestBodyOut); } // If this engine never achieved a response body,its connection cannot be reused. if (responseBody == null) { if (connection != null) closeQuietly(connection.getSocket()); // Todo: does this break SPDY? connection = null; return null; } // Close the response body. This will recycle the connection if it is eligible. closeQuietly(responseBody); // Clear the buffer held by the response body input stream adapter. closeQuietly(responseBodyBytes); // Close the connection if it cannot be reused. if (transport != null && connection != null && !transport.canReuseConnection()) { closeQuietly(connection.getSocket()); connection = null; return null; } // Prevent this engine from disconnecting a connection it no longer owns. if (connection != null && !Internal.instance.clearOwner(connection)) { connection = null; } Connection result = connection; connection = null; return result; }
public void sendRequest() throws RequestException,RouteException,IOException { if (this.cacheStrategy == null) { if (this.httpStream != null) { throw new IllegalStateException(); } Request request = networkRequest(this.userRequest); InternalCache responsecache = Internal.instance.internalCache(this.client); Response cacheCandidate = responsecache != null ? responsecache.get(request) : null; this.cacheStrategy = new Factory(System.currentTimeMillis(),cacheCandidate) .get(); this.networkRequest = this.cacheStrategy.networkRequest; this.cacheResponse = this.cacheStrategy.cacheResponse; if (responsecache != null) { responsecache.trackResponse(this.cacheStrategy); } if (cacheCandidate != null && this.cacheResponse == null) { Util.closeQuietly(cacheCandidate.body()); } if (this.networkRequest != null) { this.httpStream = connect(); this.httpStream.setHttpEngine(this); if (this.callerWritesRequestBody && permitsRequestBody(this.networkRequest) && this.requestBodyOut == null) { long contentLength = OkHeaders.contentLength(request); if (!this.bufferRequestBody) { this.httpStream.writeRequestHeaders(this.networkRequest); this.requestBodyOut = this.httpStream.createRequestBody(this .networkRequest,contentLength); return; } else if (contentLength > 2147483647L) { throw new IllegalStateException("Use setFixedLengthStreamingMode() or " + "setChunkedStreamingMode() for requests larger than 2 GiB."); } else if (contentLength != -1) { this.httpStream.writeRequestHeaders(this.networkRequest); this.requestBodyOut = new RetryableSink((int) contentLength); return; } else { this.requestBodyOut = new RetryableSink(); return; } } return; } if (this.cacheResponse != null) { this.userResponse = this.cacheResponse.newBuilder().request(this.userRequest) .priorResponse(stripBody(this.priorResponse)).cacheResponse(stripBody (this.cacheResponse)).build(); } else { this.userResponse = new Builder().request(this.userRequest).priorResponse (stripBody(this.priorResponse)).protocol(Protocol.HTTP_1_1).code(504) .message("Unsatisfiable Request (only-if-cached)").body(EMPTY_BODY).build(); } this.userResponse = unzip(this.userResponse); } }
public void readResponse() throws IOException { if (this.userResponse == null) { if (this.networkRequest == null && this.cacheResponse == null) { throw new IllegalStateException("call sendRequest() first!"); } else if (this.networkRequest != null) { Response networkResponse; if (this.forWebSocket) { this.httpStream.writeRequestHeaders(this.networkRequest); networkResponse = readNetworkResponse(); } else if (this.callerWritesRequestBody) { if (this.bufferedRequestBody != null && this.bufferedRequestBody.buffer() .size() > 0) { this.bufferedRequestBody.emit(); } if (this.sentRequestMillis == -1) { if (OkHeaders.contentLength(this.networkRequest) == -1 && (this .requestBodyOut instanceof RetryableSink)) { this.networkRequest = this.networkRequest.newBuilder().header ("Content-Length",Long.toString(((RetryableSink) this .requestBodyOut).contentLength())).build(); } this.httpStream.writeRequestHeaders(this.networkRequest); } if (this.requestBodyOut != null) { if (this.bufferedRequestBody != null) { this.bufferedRequestBody.close(); } else { this.requestBodyOut.close(); } if (this.requestBodyOut instanceof RetryableSink) { this.httpStream.writeRequestBody((RetryableSink) this.requestBodyOut); } } networkResponse = readNetworkResponse(); } else { networkResponse = new NetworkInterceptorChain(this,this.networkRequest) .proceed(this.networkRequest); } receiveHeaders(networkResponse.headers()); if (this.cacheResponse != null) { if (validate(this.cacheResponse,networkResponse)) { this.userResponse = this.cacheResponse.newBuilder().request(this .userRequest).priorResponse(stripBody(this.priorResponse)) .headers(combine(this.cacheResponse.headers(),networkResponse .headers())).cacheResponse(stripBody(this.cacheResponse)) .networkResponse(stripBody(networkResponse)).build(); networkResponse.body().close(); releaseStreamAllocation(); InternalCache responsecache = Internal.instance.internalCache(this.client); responsecache.trackConditionalCacheHit(); responsecache.update(this.cacheResponse,stripBody(this.userResponse)); this.userResponse = unzip(this.userResponse); return; } Util.closeQuietly(this.cacheResponse.body()); } this.userResponse = networkResponse.newBuilder().request(this.userRequest) .priorResponse(stripBody(this.priorResponse)).cacheResponse(stripBody (this.cacheResponse)).networkResponse(stripBody(networkResponse)) .build(); if (hasBody(this.userResponse)) { maybeCache(); this.userResponse = unzip(cacheWritingResponse(this.storeRequest,this .userResponse)); } } } }
private RouteDatabase routeDatabase() { return Internal.instance.routeDatabase(this.connectionPool); }
public void closeIfOwnedBy(Object owner) throws IOException { Internal.instance.closeIfOwnedBy(connection,owner); }
/** * figures out what the response source will be,and opens a socket to that * source if necessary. Prepares the request headers and gets ready to start * writing the request body if it exists. */ public void sendRequest() throws IOException { if (cacheStrategy != null) return; // Already sent. if (transport != null) throw new IllegalStateException(); Request request = networkRequest(userRequest); InternalCache responsecache = Internal.instance.internalCache(client); Response cacheCandidate = responsecache != null ? responsecache.get(request) : null; long Now = System.currentTimeMillis(); cacheStrategy = new CacheStrategy.Factory(Now,cacheCandidate).get(); networkRequest = cacheStrategy.networkRequest; cacheResponse = cacheStrategy.cacheResponse; if (responsecache != null) { responsecache.trackResponse(cacheStrategy); } if (cacheCandidate != null && cacheResponse == null) { closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it. } if (networkRequest != null) { // Open a connection unless we inherited one from a redirect. if (connection == null) { connect(networkRequest); } // Blow up if we aren't the current owner of the connection. if (Internal.instance.getowner(connection) != this && !Internal.instance.isspdy(connection)) { throw new AssertionError(); } transport = Internal.instance.newTransport(connection,this); // Create a request body if we don't have one already. We'll already have // one if we're retrying a Failed POST. if (hasRequestBody() && requestBodyOut == null) { requestBodyOut = transport.createRequestBody(request); } } else { // We aren't using the network. Recycle a connection we may have inherited from a redirect. if (connection != null) { Internal.instance.recycle(client.getConnectionPool(),connection); connection = null; } if (cacheResponse != null) { // We have a valid cached response. Promote it to the user response immediately. this.userResponse = cacheResponse.newBuilder() .request(userRequest) .priorResponse(stripBody(priorResponse)) .cacheResponse(stripBody(cacheResponse)) .build(); } else { // We're forbidden from using the network,and the cache is insufficient. this.userResponse = new Response.Builder() .request(userRequest) .priorResponse(stripBody(priorResponse)) .protocol(Protocol.HTTP_1_1) .code(504) .message("Unsatisfiable Request (only-if-cached)") .body(EMPTY_BODY) .build(); } if (userResponse.body() != null) { initContentStream(userResponse.body().source()); } } }
private HttpEngine newHttpEngine(String method,Response priorResponse) { Request.Builder builder = new Request.Builder() .url(getURL()) .method(method,null /* No body; that's passed separately. */); Headers headers = requestHeaders.build(); for (int i = 0; i < headers.size(); i++) { builder.addHeader(headers.name(i),headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.hasRequestBody(method)) { // Specify how the request body is terminated. if (fixedContentLength != -1) { builder.header("Content-Length",Long.toString(fixedContentLength)); } else if (chunkLength > 0) { builder.header("transfer-encoding","chunked"); } else { bufferRequestBody = true; } // Add a content type for the request body,if one isn't already present. if (headers.get("Content-Type") == null) { builder.header("Content-Type","application/x-www-form-urlencoded"); } } if (headers.get("User-Agent") == null) { builder.header("User-Agent",defaultUserAgent()); } Request request = builder.build(); // If we're currently not using caches,make sure the engine's client doesn't have one. OkHttpClient engineClient = client; if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) { engineClient = client.clone().setCache(null); } request = client.preConfigRequest(request); return new HttpEngine(engineClient,connection,null,priorResponse); }
private HttpEngine newHttpEngine(String method,Response priorResponse) { // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. RequestBody placeholderBody = HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null; Request.Builder builder = new Request.Builder() .url(getURL()) .method(method,placeholderBody); Headers headers = requestHeaders.build(); for (int i = 0,size = headers.size(); i < size; i++) { builder.addHeader(headers.name(i),headers.value(i)); } boolean bufferRequestBody = false; if (HttpMethod.permitsRequestBody(method)) { // Specify how the request body is terminated. if (fixedContentLength != -1) { builder.header("Content-Length",make sure the engine's client doesn't have one. OkHttpClient engineClient = client; if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) { engineClient = client.clone().setCache(null); } return new HttpEngine(engineClient,priorResponse); }
今天关于SysInternal的WinObj设备列表机制和win10设备列表的讲解已经结束,谢谢您的阅读,如果想了解更多关于ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);"一直返回失败、c# – Internals,InternalsVisibleTo和测试共享行为、c# – “ceq”MSIL命令和object.InternalEquals之间的区别、com.squareup.okhttp.internal.Internal的实例源码的相关知识,请在本站搜索。
本文标签: