-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.cpp
More file actions
240 lines (205 loc) · 5.83 KB
/
server.cpp
File metadata and controls
240 lines (205 loc) · 5.83 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#include "server.hpp"
std::string Server::hostname = "";
std::string Server::password = "";
std::vector<pollfd> Server::pfds = std::vector<pollfd>();
std::vector<pollfd> &Server::getPfds()
{
return Server::pfds;
}
Server::Server(Context *context, const std::string passw, const std::string &port)
: context(context)
{
Server::password = passw;
char hostbuffer[256];
if (gethostname(hostbuffer, sizeof(hostbuffer)) == -1)
{
perror("gethostname");
exit(1);
}
Server::hostname = hostbuffer;
this->listener_sock = get_listener_socket(port);
if (listener_sock < 0)
{
std::cerr << "failed getting listener socket, maybe port already in use." << std::endl;
exit(1);
}
add_to_pfds(listener_sock);
}
int Server::get_listener_socket(const std::string &port)
{
int status, listener_sock, yes = 1;
struct addrinfo hints;
struct addrinfo *servinfo, *p;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
// hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_family = AF_INET; // handle IPV4 only
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
if ((status = getaddrinfo(NULL, port.c_str(), &hints, &servinfo)) != 0)
{
std::cerr << "getaddrinfo: " << gai_strerror(status) << std::endl;
exit(1);
}
for (p = servinfo; p != NULL; p = p->ai_next)
{
listener_sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (listener_sock < 0)
{
continue;
}
// Lose the pesky "address already in use" error message
setsockopt(listener_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if (bind(listener_sock, servinfo->ai_addr, servinfo->ai_addrlen) < 0)
{
close(listener_sock);
continue;
}
break;
}
freeaddrinfo(servinfo); // free the linked-list
if (p == NULL)
{
return -1;
}
if (listen(listener_sock, BACKLOG) < 0)
{
return -1;
}
return listener_sock;
}
// Add a new file descriptor to the set
void Server::add_to_pfds(int newfd)
{
struct pollfd pfd;
pfd.fd = newfd;
pfd.events = POLLIN;
pfds.push_back(pfd);
}
// Remove an index from the set
void Server::del_from_pfds(int fdToDelete)
{
std::vector<struct pollfd>::iterator it = pfds.begin();
for (; it != pfds.end(); it++)
{
if ((*it).fd == fdToDelete)
break;
}
if (it == pfds.end())
return;
pfds.erase(it);
}
std::string Server::getHostname()
{
return Server::hostname;
}
std::string Server::getPassword()
{
return Server::password;
}
void Server::onNewConnection()
{
struct sockaddr_in addr;
socklen_t addr_size = sizeof addr;
int newClientFd = accept(listener_sock, (struct sockaddr *)&addr, &addr_size);
if (newClientFd < 0)
{
perror("accept");
}
else
{
add_to_pfds(newClientFd);
unsigned char *_ip = (unsigned char *)&addr.sin_addr.s_addr;
std::ostringstream oss;
oss << (int)_ip[0] << "." << (int)_ip[1] << "." << (int)_ip[2] << "." << (int)_ip[3];
std::string ip(oss.str());
ip = (ip == "localhost" || ip == "127.0.0.1") ? Server::hostname : ip;
std::cout << "new connection from " << ip << " on socket " << newClientFd << std::endl;
context->addNewUser(newClientFd, ip);
// send a welcome message to the client
std::string welcomeMsg = "Welcome to the server!\n";
if (send(newClientFd, welcomeMsg.c_str(), welcomeMsg.length(), 0) == -1)
{
perror("send");
}
}
}
void Server::onNewMessage(int clientFd)
{
const int buffer_len = 1024;
char buffer[buffer_len];
// regular client
int nb_bytes = recv(clientFd, buffer, buffer_len, 0);
User *user = context->getSocketHandler(clientFd);
if (!user)
{
std::cerr << "failed to find user" << std::endl;
}
else if (nb_bytes <= 0)
{
// error or connection closed by the client
if (nb_bytes == 0)
{
std::cout << "connection closed, socket " << clientFd << std::endl;
}
else
{
perror("recv");
}
std::string message("QUIT");
user->handleSocket(Command::fromMessage(message));
del_from_pfds(clientFd);
}
else
{
buffer[nb_bytes] = 0;
std::string message(buffer);
size_t pos = message.find_last_of("\n");
if (pos != std::string::npos)
{
user->buffer += message.substr(0, pos);
std::queue<std::string> q = splitChunks(user->buffer, '\n');
user->buffer = message.substr(pos + 1);
while (!q.empty())
{
message = q.front();
q.pop();
Command cmd = Command::fromMessage(message);
user->handleSocket(cmd);
}
}
else
{
user->buffer += message;
}
}
}
void Server::run()
{
for (;;)
{
try
{
int p_count = poll(pfds.data(), pfds.size(), -1); // -1 timeout -> wait forever
if (p_count < 0)
{
perror("poll");
exit(1);
}
for (size_t i = 0; i < pfds.size(); i++)
{
if (!(pfds[i].revents & POLLIN))
{
continue;
}
if (pfds[i].fd == listener_sock)
this->onNewConnection();
else
this->onNewMessage(pfds[i].fd);
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
}