-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAsync.cpp
More file actions
105 lines (77 loc) · 2.57 KB
/
Copy pathAsync.cpp
File metadata and controls
105 lines (77 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "Async.hpp"
#include "Logger.hpp"
#include <cassert>
#include "Debug.hpp"
//////////////////////////////////////////////////////////////////////////
AsyncResolver::QueryContext::QueryContext
(AsyncResolver *resolver, const Request &request) {
memset(this, 0, sizeof(QueryContext));
port = request.port;
const char *p = (const char *) request.host;
std::mbstate_t state = std::mbstate_t();
auto len = std::mbsrtowcs(NULL, &p, 0, &state) + 1;
host = new wchar_t[len];
std::mbsrtowcs(host, &p, len, &state);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// swprintf_s 不能用
swprintf(service, sizeof(service), L"%u", port);
ts = time(nullptr);
this->resolver = resolver;
userData = request.userData;
}
AsyncResolver::QueryContext::~QueryContext() {
delete [] host;
if (results) {
FreeAddrInfoEx(results);
}
}
//////////////////////////////////////////////////////////////////////////
AsyncResolver::AsyncResolver(Callback *callback)
: m_callback(callback) {
}
AsyncResolver::~AsyncResolver() {
}
void AsyncResolver::Cancel() {
m_ts = 0;
}
bool AsyncResolver::PostResolve(const Request &request) {
QueryContext *context = new QueryContext(this, request);
m_ts = context->ts;
int error = GetAddrInfoExW(context->host,
context->service,
NS_DNS,
nullptr,
&context->hints,
&context->results,
nullptr,
&context->ol,
OnDnsResolved,
nullptr);
//
// If GetAddrInfoExW() returns WSA_IO_PENDING, GetAddrInfoExW will
// invoke the completion routine. If GetAddrInfoExW returned anything
// else we must invoke the completion directly.
//
// 当主机名为 IP 地址时,会直接成功
if (error != WSA_IO_PENDING) {
OnDnsResolved(error, 0, &context->ol);
return error == ERROR_SUCCESS;
}
return true;
}
/*static*/
void CALLBACK AsyncResolver::OnDnsResolved
(DWORD error, DWORD, LPWSAOVERLAPPED ol) {
QueryContext *context = (QueryContext *) ol;
// 用户取消了请求
if (context->ts != context->resolver->m_ts) {
return;
}
if (error != ERROR_SUCCESS) {
Logger::LogError(__FUNC__ "GetAddrInfoExW() failed");
}
context->resolver->m_callback->OnQueryCompleted(context);
context->resolver->m_ts = 0;
}