/
EpollServer.cpp
620 lines (460 loc) · 12.9 KB
/
EpollServer.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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
* Copyright 2010-2020 DatasysLab@iit.edu(http://datasys.cs.iit.edu/index.html)
* Director: Ioan Raicu(iraicu@cs.iit.edu)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of ZHT library(http://datasys.cs.iit.edu/projects/ZHT/index.html).
* Tonglin Li(tli13@hawk.iit.edu) with nickname Tony,
* Xiaobing Zhou(xzhou40@hawk.iit.edu) with nickname Xiaobingo,
* Ke Wang(kwang22@hawk.iit.edu) with nickname KWang,
* Dongfang Zhao(dzhao8@@hawk.iit.edu) with nickname DZhao,
* Ioan Raicu(iraicu@cs.iit.edu).
*
* EpollServer.cpp
*
* Created on: Aug 9, 2012
* Author: Xiaobingo
* Contributor: Tony, KWang, DZhao
*/
#include "EpollServer.h"
#include "Env.h"
#include "Const-impl.h"
#include "ConfHandler.h"
#include <stdlib.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <queue>
using namespace std;
namespace iit {
namespace datasys {
namespace zht {
namespace dm {
EventData::EventData(int fd, const char* buf, size_t bufsize, sockaddr addr) {
_fd = fd;
int len = strlen((const char*) buf);
_buf = (char*) calloc(len + 1, sizeof(char));
memcpy(_buf, buf, len + 1);
_bufsize = bufsize;
_fromaddr = addr;
}
EventData::~EventData() {
// free(_buf);
}
int EventData::fd() const {
return _fd;
}
char* EventData::buf() const {
return _buf;
}
size_t EventData::bufsize() const {
return _bufsize;
}
sockaddr EventData::fromaddr() {
return _fromaddr;
}
EpollData::EpollData(const int& fd, const sockaddr * const sender) :
_fd(fd), _sender(sender) {
}
EpollData::~EpollData() {
if (_sender != NULL) {
free((void*) _sender);
_sender = NULL;
}
}
const int EpollServer::MAX_EVENTS = 4096;
EpollServer::EpollServer(const char *port, ZProcessor *processor) :
_port(port), _ZProcessor(processor), pbrb(new BdRecvFromClient()), _eventQueue() {
string protocol = ConfHandler::getProtocolFromConf();
if (protocol == Const::PROTO_VAL_TCP) {
_tcp = true;
} else if (protocol == Const::PROTO_VAL_UDP) {
_tcp = false;
} else {
fprintf(stderr,
"EpollServer::EpollServer(): <%s>, unrecognized IP family protocol\n",
protocol.c_str());
exit(1);
}
}
EpollServer::~EpollServer() {
if (_ZProcessor != NULL) {
delete _ZProcessor;
_ZProcessor == NULL;
}
if (pbrb != NULL) {
delete pbrb;
pbrb = NULL;
}
}
int EpollData::fd() const {
return _fd;
}
const sockaddr * const EpollData::sender() const {
return _sender;
}
int EpollServer::create_and_bind(const char *port) {
return create_and_bind(NULL, port);
}
int EpollServer::create_and_bind(const char *host, const char *port) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int s, sfd;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
hints.ai_flags = AI_PASSIVE; /* All interfaces */
s = getaddrinfo(host, port, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
s = bind(sfd, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
}
close(sfd);
}
if (rp == NULL) {
fprintf(stderr, "Could not bind\n");
return -1;
}
freeaddrinfo(result);
return sfd;
}
int EpollServer::make_socket_non_blocking(const int& sfd) {
int flags, s;
flags = fcntl(sfd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl");
return -1;
}
flags |= O_NONBLOCK;
s = fcntl(sfd, F_SETFL, flags);
if (s == -1) {
perror("fcntl");
return -1;
}
return 0;
}
int EpollServer::makeSvrSocket() { //only for svr
int port = atoi(_port);
struct sockaddr_in svrAdd_in; /* socket info about our server */
int svrSock = -1;
try {
memset(&svrAdd_in, 0, sizeof(struct sockaddr_in)); /* zero the struct before filling the fields */
svrAdd_in.sin_family = AF_INET; /* set the type of connection to TCP/IP */
svrAdd_in.sin_addr.s_addr = INADDR_ANY; /* set our address to any interface */
svrAdd_in.sin_port = htons(port); /* set the server port number */
if (_tcp == true) { //make socket
svrSock = socket(AF_INET, SOCK_STREAM, 0); /* OS will return a fd for network stream connection*/
} else { //UDP
svrSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
if (svrSock < 0) {
printf(
"Error occurred when creating the socket:%d to the server port:%d\n",
svrSock, port);
printf("%s\n", strerror(errno));
close(svrSock);
return -1;
}
if (bind(svrSock, (struct sockaddr*) &svrAdd_in,
sizeof(struct sockaddr)) < 0) {
printf(
"Error occurred binding the socket:%d to the server port:%d\n",
svrSock, port);
printf("%s", strerror(errno));
close(svrSock);
return -1;
}
if (_tcp == true) { //TCP needs listen, UDP does not.
/* start listening, allowing a queue of up to 1 pending connection */
if (listen(svrSock, SOMAXCONN) < 0) {
printf(
"Error occurred while enabling listen on the socket:%d\n",
svrSock);
printf("%s", strerror(errno));
close(svrSock);
return -1;
}
}
} catch (exception& e) {
fprintf(stderr, "exception caught:\n\t%s", e.what());
}
return svrSock;
}
int EpollServer::reuseSock(int sock) {
int reuse_addr = 1;
int ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr,
sizeof(reuse_addr));
if (ret < 0) {
cerr << "resuse socket failed: " << strerror(errno) << endl;
return -1;
} else
return 0;
}
void* EpollServer::threadedServe(void *arg) {
EpollServer *pes = (EpollServer*) arg;
while (true) {
while (!pes->_eventQueue.empty()) {
EventData eventData = pes->_eventQueue.front();
pes->_ZProcessor->process(eventData.fd(), eventData.buf(),
eventData.fromaddr());
pes->_eventQueue.pop();
}
}
}
void EpollServer::init_thread() {
pthread_t thread;
pthread_create(&thread, NULL, threadedServe, this);
}
void EpollServer::serve() {
#ifdef THREADED_SERVE
init_thread();
#endif
int sfd, s;
int efd;
struct epoll_event event;
struct epoll_event *events;
sfd = makeSvrSocket();
if (sfd == -1)
abort();
s = make_socket_non_blocking(sfd);
if (s == -1)
abort();
reuseSock(sfd);
efd = epoll_create(1);
if (efd == -1) {
perror("epoll_create");
abort();
}
event.data.ptr = new EpollData(sfd, NULL);
event.events = EPOLLIN | EPOLLET;
s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
if (s == -1) {
perror("epoll_ctl");
abort();
}
/* Buffer where events are returned */
events = (epoll_event *) calloc(MAX_EVENTS, sizeof event);
/* The event loop */
while (1) {
int n, i;
n = epoll_wait(efd, events, MAX_EVENTS, -1);
for (i = 0; i < n; i++) {
EpollData *edata = (EpollData*) events[i].data.ptr;
if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)
|| (!(events[i].events & EPOLLIN))) {
/* An error has occured on this fd, or the socket is not
ready for reading (why were we notified then?) */
fprintf(stderr, "epoll error\n");
close(edata->fd());
delete edata;
continue;
} else if (sfd == edata->fd()) {
if (_tcp == true) {
/* We have a notification on the listening socket, which
means one or more incoming connections. */
while (1) {
sockaddr *in_addr = (sockaddr *) calloc(1,
sizeof(struct sockaddr));
socklen_t in_len = sizeof(struct sockaddr);
int infd = accept(sfd, in_addr, &in_len);
if (infd == -1) {
free(in_addr);
if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
/* We have processed all incoming connections. */
break;
} else {
perror("accept");
break;
}
}
/* fprintf(stdout,
"sin_family[%hu], sin_zero[%s], sin_addr.s_addr[%u], sin_port[%hu]\n",
in_addr.sin_family, in_addr.sin_zero,
in_addr.sin_addr.s_addr, in_addr.sin_port);
*/
/*
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
getnameinfo(in_addr, in_len, hbuf, sizeof hbuf, sbuf,
sizeof sbuf, 0);
if (s == 0) {
printf("Accepted connection on descriptor %d "
"(host=%s, _port=%s)\n", infd, hbuf, sbuf);
}*/
/* Make the incoming socket non-blocking and add it to the
list of fds to monitor. */
s = make_socket_non_blocking(infd);
if (s == -1) {
free(in_addr);
abort();
}
reuseSock(infd);
event.data.ptr = new EpollData(infd, in_addr);
event.events = EPOLLIN | EPOLLET;
s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event);
if (s == -1) {
free(in_addr);
perror("epoll_ctl");
abort();
}
}
continue;
} else {
int done = 0;
while (1) {
char buf[Env::BUF_SIZE];
memset(buf, 0, sizeof(buf));
//char *buf = (char*) calloc(Env::BUF_SIZE, sizeof(char));
sockaddr fromaddr;
socklen_t sender_len = sizeof(struct sockaddr);
ssize_t count = recvfrom(edata->fd(), buf, sizeof buf,
0, &fromaddr, &sender_len);
//cout << "EpollServer.cpp: serve(): received "<< count << " bytes."<<endl;
if (count == -1) {
if (errno != EAGAIN) {
perror("read");
done = 1;
}
} else if (count == 0) {
done = 1;
break;
} else {
#ifdef BIG_MSG
bool ready = false;
string bd = pbrb->getBdStr(sfd, buf, count, ready);
if (ready) {
#ifdef THREADED_SERVE
EventData eventData(edata->fd(), bd.c_str(), bd.size(),
fromaddr);
_eventQueue.push(eventData);
#else
_ZProcessor->process(edata->fd(), bd.c_str(),
fromaddr);
#endif
}
#endif
#ifdef SML_MSG
#ifdef THREADED_SERVE
EventData eventData(edata->fd(), buf, sizeof(buf),
fromaddr);
_eventQueue.push(eventData);
#else
string bufstr(buf);
_ZProcessor->process(edata->fd(), bufstr.c_str(),
fromaddr);
#endif
#endif
}
//memset(buf, 0, sizeof(buf));
//free(buf);
}
/*if (done) {
close(edata->fd());
delete edata;
}*/
}
} else {
if (_tcp == true) {
/* We have data on the fd waiting to be read. Read and
display it. We must read whatever data is available
completely, as we are running in edge-triggered mode
and won't get a notification again for the same
data. */
int done = 0;
while (1) {
char buf[Env::BUF_SIZE];
memset(buf, 0, sizeof(buf));
//char *buf = (char*) calloc(Env::BUF_SIZE, sizeof(char));
ssize_t count = recv(edata->fd(), buf, sizeof(buf), 0);
if (count == -1) {
/* If errno == EAGAIN, that means we have read all
data. So go back to the main loop. */
if (errno != EAGAIN) {
perror("read");
done = 1;
} /*else {
printf(
"Closed connection on descriptor %d, -1<--recv\n",
edata->fd());
close(edata->fd());
delete edata;
}*/
break;
} else if (count == 0) {
/* End of file. The remote has closed the
connection. */
done = 1;
break;
} else {
#ifdef BIG_MSG
bool ready = false;
string bd = pbrb->getBdStr(sfd, buf, count, ready);
if (ready) {
#ifdef THREADED_SERVE
EventData eventData(edata->fd(), bd.c_str(), bd.size(),
*edata->sender());
_eventQueue.push(eventData);
#else
_ZProcessor->process(edata->fd(), bd.c_str(),
*edata->sender());
#endif
}
#endif
#ifdef SML_MSG
#ifdef THREADED_SERVE
EventData eventData(edata->fd(), buf, sizeof(buf),
*edata->sender());
_eventQueue.push(eventData);
#else
string bufstr(buf);
_ZProcessor->process(edata->fd(), bufstr.c_str(),
*edata->sender());
#endif
#endif
}
//memset(buf, 0, sizeof(buf));
//free(buf);
}
if (done) {
/*printf("Closed connection on descriptor %d, done.\n",
edata->fd());*/
/* Closing the descriptor will make epoll remove it
from the set of descriptors which are monitored. */
close(edata->fd());
delete edata;
}
} //if TCP == true
}
}
}
free(events);
close(sfd);
EpollData *edata = (EpollData*) event.data.ptr;
delete edata;
}
} /* namespace dm */
} /* namespace zht */
} /* namespace datasys */
} /* namespace iit */