forked from yaosj2k/dnsforwarder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketpool.c
executable file
·147 lines (120 loc) · 2.94 KB
/
socketpool.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <string.h>
#include "socketpool.h"
#include "utils.h"
static int SocketPool_Add(SocketPool *sp,
SOCKET Sock,
const void *Data,
int DataLength
)
{
SocketUnit su;
su.Sock = Sock;
if( Data != NULL )
{
su.Data = sp->d.Add(&(sp->d), Data, DataLength, TRUE);
} else {
su.Data = NULL;
}
if( sp->t.Add(&(sp->t), &su) == NULL )
{
return -27;
}
return 0;
}
static int SocketPool_Del(SocketPool *sp, SOCKET Sock)
{
SocketUnit k = {Sock, NULL};
const SocketUnit *r;
r = sp->t.Search(&(sp->t), &k, NULL);
if( r != NULL )
{
sp->t.Delete(&(sp->t), r);
}
return 0;
}
typedef struct _SocketPool_Fetch_Arg
{
SOCKET Sock;
fd_set *fs;
void **DataOut;
} SocketPool_Fetch_Arg;
static int SocketPool_Fetch_Inner(Bst *t,
const SocketUnit *su,
SocketPool_Fetch_Arg *Arg)
{
if( FD_ISSET(su->Sock, Arg->fs) )
{
Arg->Sock = su->Sock;
if( Arg->DataOut != NULL )
{
*(Arg->DataOut) = (void *)su->Data;
}
return 1;
}
return 0;
}
static SOCKET SocketPool_FetchOnSet(SocketPool *sp,
fd_set *fs,
void **Data
)
{
SocketPool_Fetch_Arg ret = {INVALID_SOCKET, fs, Data};
sp->t.Enum(&(sp->t),
(Bst_Enum_Callback)SocketPool_Fetch_Inner,
&ret
);
return ret.Sock;
}
static int SocketPool_CloseAll_Inner(Bst *t,
const SocketUnit *Data,
SOCKET *ExceptFor
)
{
if( Data->Sock != INVALID_SOCKET && Data->Sock != *ExceptFor )
{
CLOSE_SOCKET(Data->Sock);
}
return 0;
}
static void SocketPool_CloseAll(SocketPool *sp, SOCKET ExceptFor)
{
sp->t.Enum(&(sp->t),
(Bst_Enum_Callback)SocketPool_CloseAll_Inner,
&ExceptFor
);
}
static void SocketPool_Free(SocketPool *sp, BOOL CloseAllSocket)
{
if( CloseAllSocket )
{
SocketPool_CloseAll(sp, INVALID_SOCKET);
}
sp->t.Free(&(sp->t));
sp->d.Free(&(sp->d));
}
static int Compare(const SocketUnit *_1, const SocketUnit *_2)
{
return (int)(_1->Sock) - (int)(_2->Sock);
}
int SocketPool_Init(SocketPool *sp)
{
if( Bst_Init(&(sp->t),
sizeof(SocketUnit),
(CompareFunc)Compare
)
!= 0 )
{
return -113;
}
if( StableBuffer_Init(&(sp->d)) != 0 )
{
sp->t.Free(&(sp->t));
return -119;
}
sp->Add = SocketPool_Add;
sp->Del = SocketPool_Del;
sp->CloseAll = SocketPool_CloseAll;
sp->FetchOnSet = SocketPool_FetchOnSet;
sp->Free = SocketPool_Free;
return 0;
}