-
Notifications
You must be signed in to change notification settings - Fork 41
/
socket_manager.cpp
81 lines (68 loc) · 1.88 KB
/
socket_manager.cpp
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
#include "socket_manager.h"
int SocketManager::Find(SOCKET sock) {
for (size_t i = 0; i < items.size(); i++) {
if (items[i].sock == sock) {
return (int)i;
}
}
return -1;
}
void SocketManager::Delete(int index) {
if (index < (int)items.size() - 1) {
items[index] = items.back();
}
items.pop_back();
}
void SocketManager::ClearTimeoutSock() {
DWORD tick = GetTickCount64() - 30000;
for (int i = (int)items.size() - 1; i >= 0; i--) {
if (items[i].createdAt < tick) {
Delete(i);
}
}
}
void SocketManager::Add(SOCKET sock, int sockType, int sockProtocol) {
SocketManagerItem item = {
sock,
(sockType == SOCK_STREAM) && (sockProtocol == IPPROTO_TCP || sockProtocol == 0),
(sockType == SOCK_DGRAM) && (sockProtocol == IPPROTO_UDP || sockProtocol == 0),
false,
false,
GetTickCount64()
};
std::lock_guard<std::mutex> lock(mtx);
ClearTimeoutSock();
int index = Find(sock);
if (index == -1) {
items.push_back(item);
}
else {
items[index] = item;
}
}
bool SocketManager::IsFirstSend(SOCKET sock, SocketManagerItem& item) {
std::lock_guard<std::mutex> lock(mtx);
int index = Find(sock);
if (index == -1 || items[index].hasSent) {
return false;
}
items[index].hasSent = true;
item = items[index];
return true;
}
void SocketManager::SetFakeHttpProxyFlag(SOCKET sock) {
std::lock_guard<std::mutex> lock(mtx);
int index = Find(sock);
if (index >= 0) {
items[index].fakeHttpProxyFlag = true;
}
}
bool SocketManager::ClearFakeHttpProxyFlag(SOCKET sock) {
std::lock_guard<std::mutex> lock(mtx);
int index = Find(sock);
if (index == -1 || !items[index].fakeHttpProxyFlag) {
return false;
}
items[index].fakeHttpProxyFlag = false;
return true;
}