-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathProxyServer.cpp
More file actions
133 lines (114 loc) · 3.19 KB
/
ProxyServer.cpp
File metadata and controls
133 lines (114 loc) · 3.19 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
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
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <boost/bind.hpp>
#include "ProxyServer.h"
#include "ProxyWorker.h"
#include "ProxyException.h"
ProxyServer::ProxyServer():
m_socket(0)
{
int flag = 1;
int len = sizeof flag;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
throw ProxyException("Create socket failed");
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag, len) < 0)
{
close(sock);
throw ProxyException("socket error");
}
m_socket = sock;
}
ProxyServer::~ProxyServer()
{
if (m_socket)
close(m_socket);
}
void ProxyServer::Stop()
{
m_wanna_stop = true;
close(m_socket);
}
void WorkerThread(ProxyWorker* worker)
{
worker->Run();
}
void ProxyServer::Run(unsigned int port)
{
try
{
m_wanna_stop = false;
signal(SIGPIPE, SIG_IGN); //避免由于客户端发送Request之后就断开连接而导致的Broken_Pipe错误
std::map<size_t, ProxyWorker*>::iterator worker_iter;
sockaddr_in sa;
bzero(&sa, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = htons(port);
if (bind(m_socket, (sockaddr*)&sa, sizeof(sa)) < 0)
{
close(m_socket);
throw ProxyException("Bind failed");
}
if (listen(m_socket, 5) < 0)
{
close(m_socket);
throw ProxyException("Listen failed");
}
ProxyWorker::InitSSLCtx();
size_t sn = 1;
while(!m_wanna_stop)
{
sockaddr clientaddr;
socklen_t salen = sizeof(clientaddr);
int clientsock = accept(m_socket, &clientaddr, &salen);
if (m_wanna_stop)
break;
//remove terminated worker
worker_iter = m_workers.begin();
while(worker_iter != m_workers.end())
{
if (worker_iter->second && !worker_iter->second->IsRunning())
{
delete worker_iter->second;
worker_iter->second = NULL;
m_workers.erase(worker_iter++);
}
else
++worker_iter;
}
if (clientsock == 0)
continue;
ProxyWorker* pw = new ProxyWorker(clientsock, sn);
boost::thread(&ProxyWorker::Run, pw);
m_workers[sn] = pw;
++sn;
}
//关闭所有套接字
worker_iter = m_workers.begin();
while(worker_iter != m_workers.end())
{
worker_iter->second->ShutDown();
++worker_iter;
}
//等待所有线程退出,相当于join
worker_iter = m_workers.begin();
while(worker_iter != m_workers.end())
{
while(worker_iter->second->IsRunning())
sleep(0);
delete worker_iter->second;
m_workers.erase(worker_iter++);
}
ProxyWorker::DeleteSSLCtx();
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "unhandled error" << std::endl;
}
}