-
Notifications
You must be signed in to change notification settings - Fork 0
/
Port.cpp
165 lines (131 loc) · 2.35 KB
/
Port.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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#include "Debug.h"
#include "Port.h"
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#define GDB_DEFAULT_TCP_PORT (1234)
namespace gdb {
class TcpPort: public Port
{
int sd;
void
close();
public:
TcpPort(const string& params);
virtual
~TcpPort();
virtual Socket*
accept();
};
class StdioPort: public Port
{
public:
StdioPort();
virtual
~StdioPort();
virtual Socket*
accept();
};
//////////////////////////////////////////////////////////////////
//
// class Port
//
Port*
Port::createInstance(const string& name, const string& params)
{
if(name == "tcp") {
return new TcpPort(params);
}
if(name == "stdio") {
return new StdioPort();
}
return NULL;
}
Port::Port()
{
}
Port::~Port()
{
}
//////////////////////////////////////////////////////////////////
//
// class TcpPort
//
TcpPort::TcpPort(const string& params)
{
int port = ::atoi(params.c_str());
int n = 1;
struct sockaddr_in addr;
if(port == 0) {
port = GDB_DEFAULT_TCP_PORT;
}
sd = ::socket(AF_INET, SOCK_STREAM, 0);
if(sd < 0) {
LOG("socket error: %m");
goto failure;
}
::fcntl(sd, F_SETFD, FD_CLOEXEC);
::setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
::memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if(::bind(sd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
LOG("bind error: %m");
goto failure;
}
if(::listen(sd, 1) < 0) {
LOG("listen error: %m\n");
goto failure;
}
return;
failure:
close();
}
TcpPort::~TcpPort()
{
close();
}
void
TcpPort::close()
{
if(sd >= 0) {
::close(sd);
sd = -1;
}
}
Socket*
TcpPort::accept()
{
struct sockaddr_in addr;
socklen_t n = sizeof(addr);
int client = ::accept(sd, (struct sockaddr*) &addr, (socklen_t*) &n);
if(client < 0) {
LOG("accept error: %m");
return NULL;
}
::fcntl(n, F_SETFD, FD_CLOEXEC);
return Socket::createInstance("tcp", client);
}
//////////////////////////////////////////////////////////////////
//
// class StdioPort
//
StdioPort::StdioPort()
{
}
StdioPort::~StdioPort()
{
}
Socket*
StdioPort::accept()
{
return Socket::createInstance("stdio", -1);
}
}; //end of namespace gdb