-
Notifications
You must be signed in to change notification settings - Fork 3
/
TcpSocket.cpp
executable file
·666 lines (567 loc) · 15.9 KB
/
TcpSocket.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
#include "Coconut.h"
#include "IOService.h"
#include "TcpSocket.h"
#include "dep/kbuffer.h"
#include "BaseSocket.h"
#include "Timer.h"
#include "Exception.h"
#include "Logger.h"
#include <string>
#include <event2/dns.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <errno.h>
#if ! defined(WIN32)
#include <arpa/inet.h>
#include <sys/un.h>
#endif
#define _KBUFFER_ 1
namespace coconut {
class TcpSocketImpl : private Timer::EventHandler {
public:
static const int TIMERID_CONNECT = (1|INTERNAL_TIMER_BIT);
TcpSocketImpl(TcpSocket *owner) : owner_(owner)
, errorDetected_(false)
, pendingWriteSupported_(true)
, bev_(NULL)
, ev_read_(NULL)
, ev_write_(NULL)
, host_("")
, port_(0)
, timeout_(0)
, write_evbuffer_(NULL)
, write_kbuffer_(NULL)
, dnsbase_(NULL)
, conn_timer_(NULL) {
write_kbuffer_ = NULL;
LOG_TRACE("TcpSocketImpl() %p\n", this);
}
~TcpSocketImpl() {
LOG_TRACE("~TcpSocketImpl : %p\n", this);
_deleteTimer();
if(write_evbuffer_) {
evbuffer_free(write_evbuffer_);
write_evbuffer_ = NULL;
}
if(write_kbuffer_) {
kbuffer_free(write_kbuffer_);
write_kbuffer_ = NULL;
}
close();
}
static void bufevent_cb(struct bufferevent *bev, short events, void *ptr) {
TcpSocketImpl *SELF = (TcpSocketImpl *)ptr;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
if (events & BEV_EVENT_CONNECTED) {
bufferevent_enable(bev, EV_READ|EV_WRITE);
SELF->fire_onSocket_Connected();
} else if (events & BEV_EVENT_ERROR) {
SELF->fire_onSocket_Error(EVUTIL_SOCKET_ERROR());
} else if (events & BEV_EVENT_EOF) {
LOG_INFO("got BEV_EVENT_EOF flag(0x%x), socket close = error %d\n", events, EVUTIL_SOCKET_ERROR());
SELF->fire_onSocket_Close();
}
}
static void event_cb(coconut_socket_t fd, short what, void *arg) {
TcpSocketImpl *SELF = (TcpSocketImpl *)arg;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
if(what & EV_READ) {
SELF->_onReadEvent(fd);
}
if(what & EV_WRITE){
SELF->_onWriteEvent(fd);
}
}
static void read_cb(struct bufferevent *bev, void *ptr) {
#define READ_MODE_3
#if defined(READ_MODE_1)
// BEST PERFOMANCE!!, BUT ONLY FOR ECHO SERVER..
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
evbuffer_add_buffer(output, input);
#elif defined(READ_MODE_2)
struct evbuffer *readBuffer = bufferevent_get_input(bev);
size_t buffer_len = evbuffer_get_length(readBuffer);
const void *data = evbuffer_pullup(readBuffer, buffer_len);
hexdump((const unsigned char*)data, buffer_len, stdout);
TcpSocketImpl *SELF = (TcpSocketImpl *)ptr;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
SELF->fire_onSocket_Read(data, buffer_len);
evbuffer_drain(readBuffer, buffer_len);
#elif defined(READ_MODE_3)
TcpSocketImpl *SELF = (TcpSocketImpl *)ptr;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
SELF->fire_onSocket_ReadEvent(bufferevent_getfd(bev));
#else
// WORST PERFOMANCE!!!
TcpSocketImpl *SELF = (TcpSocketImpl *)ptr;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
struct evbuffer *readBuffer = bufferevent_get_input(bev);
size_t buffer_len = evbuffer_get_length(readBuffer);
char *buffer = new char[buffer_len];
evbuffer_remove(readBuffer, buffer, buffer_len);
SELF->fire_onSocket_Read((const void *)buffer, buffer_len);
delete [] buffer;
#endif
}
static void timer_cb(coconut_socket_t fd, short what, void *arg) {
TcpSocketImpl *SELF = (TcpSocketImpl *)arg;
CHECK_IOSERVICE_STOP_VOID_RETURN(SELF->ioService());
SELF->fire_onSocket_Error(COOKIE_ETIMEDOUT);
}
public:
boost::shared_ptr<IOService> ioService() {
return owner_->ioService();
}
coconut_socket_t socketFD() {
if(bev_)
return bufferevent_getfd(bev_);
if(ev_read_)
return event_get_fd(ev_read_);
return COOKIE_INVALID_SOCKET; // TODO rename!!!
}
void _makeTimer() {
if(NULL == conn_timer_) {
conn_timer_ = new Timer(owner_->ioService());
conn_timer_->setEventHandler(this);
}
}
void _deleteTimer() {
if(conn_timer_) {
delete conn_timer_;
conn_timer_ = NULL;
}
}
void _throwExceptionIfNotInitState() {
if(BaseSocket::Disconnected != owner_->state())
throw IllegalStateException("Already starting connection");
if(ev_read_ || ev_write_ || bev_)
throw IllegalStateException("Already starting connection");
}
void attachSocketHandle(coconut_socket_t fd, bool doInstallFlag) {
ScopedIOServiceLock(owner_->ioService());
_throwExceptionIfNotInitState();
#if defined(WIN32) // for IOCP support
_createBufferEvent(fd);
#else
_createEvent(fd);
#endif
owner_->setState(BaseSocket::Connected);
if(doInstallFlag) {
install();
} else {
// Must call install() later!
}
}
void connect(const char *host, int port, int timeout) {
ScopedIOServiceLock(owner_->ioService());
host_ = host;
port_ = port;
timeout_ = timeout;
path_.clear();
connect();
}
void connectUnix(const char *path, int timeout) {
ScopedIOServiceLock(owner_->ioService());
path_ = path;
timeout_ = timeout;
connect();
}
void connect() {
ScopedIOServiceLock(owner_->ioService());
_throwExceptionIfNotInitState();
if(timeout_ > 0) {
_makeTimer();
conn_timer_->setTimer(TIMERID_CONNECT, timeout_ * 1000, false);
}
errorDetected_ = false;
owner_->setState(BaseSocket::Connecting);
close();
_connect();
install();
}
void _connect() {
if(path_.size() > 0) {
_connectUnix();
} else {
_connectTcp();
}
}
void _connectTcp() {
LOG_DEBUG("TCP CONNECT START: host = %s, port = %d\n", host_.c_str(), port_);
_createBufferEvent(-1);
dnsbase_ = evdns_base_new(owner_->ioService()->coreHandle(), 1);
int ret = bufferevent_socket_connect_hostname(bev_, dnsbase_, AF_UNSPEC, host_.c_str(), port_);
if(0 != ret) {
close();
throw SocketException("Error starting connection");
}
}
void _connectUnix() {
#if ! defined(WIN32)
LOG_DEBUG("UNIX CONNECT START: path = %s\n", path_.c_str());
coconut_socket_t sock;
if((sock = ::socket(AF_LOCAL, SOCK_STREAM, 0)) < 0)
throw SocketException("Error creating unix domain socket");
_createEvent(sock);
struct sockaddr_un sun;
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_LOCAL;
strcpy(sun.sun_path, path_.c_str());
evutil_make_socket_nonblocking(sock);
if(::connect(sock, (struct sockaddr *)&sun, sizeof(sun)) < 0) {
close();
throw SocketException("Error starting connection");
}
#else
assert(false && "Windows not support Unix Domain Socket");
#endif
}
void _createEvent(coconut_socket_t fd) {
if(NULL == ev_read_)
ev_read_ = event_new(owner_->ioService()->coreHandle(), fd, EV_READ|EV_PERSIST, event_cb, this);
if(NULL == ev_write_)
ev_write_ = event_new(owner_->ioService()->coreHandle(), fd, EV_WRITE|EV_PERSIST, event_cb, this);
if(NULL == write_evbuffer_)
write_evbuffer_ = evbuffer_new();
if(NULL == write_kbuffer_)
write_kbuffer_ = kbuffer_new();
owner_->fire_onSocket_Initialized();
}
void _createBufferEvent(coconut_socket_t fd) {
if(NULL == bev_) {
bev_ = bufferevent_socket_new(owner_->ioService()->coreHandle(), fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_enable(bev_, EV_READ|EV_WRITE);
}
if(NULL == write_evbuffer_)
write_evbuffer_ = evbuffer_new();
if(NULL == write_kbuffer_)
write_kbuffer_ = kbuffer_new();
owner_->fire_onSocket_Initialized();
}
void install() {
ScopedIOServiceLock(owner_->ioService());
if(bev_) {
bufferevent_setcb(bev_, read_cb, NULL, bufevent_cb, this);
struct evbuffer *readBuffer = bufferevent_get_input(bev_);
if(readBuffer) {
size_t buffer_len = evbuffer_get_length(readBuffer);
if(buffer_len > 0) {
read_cb(bev_, this);
}
}
}
if(ev_read_) {
event_add(ev_read_, NULL);
}
if(ev_write_) {
event_add(ev_write_, NULL);
}
}
const void* _readBufferEvent(struct evbuffer *buffer, size_t &size) {
size_t buffer_len = evbuffer_get_length(buffer);
if(buffer_len <= 0) {
errno = EAGAIN; // TODO multi platform EAGAIN SETTING.. but this code may work on Win32 by CRT..
return NULL;
}
if(buffer_len < size)
size = buffer_len;
const void *pulled_data = evbuffer_pullup(buffer, size);
logger::hexdump((const unsigned char*)pulled_data, buffer_len, stdout);
return pulled_data;
}
void checkResponseSocket(int res) {
if (res == -1) {
int err = evutil_socket_geterror(socketFD());
if (!SOCKET_ERR_RW_RETRIABLE(err)) {
fire_onSocket_Error(err);
close();
}
} else if (res == 0) {
/* eof case */
LOG_INFO("checkResponseSocket res is 0, socket close = error %d\n", EVUTIL_SOCKET_ERROR());
fire_onSocket_Close();
close();
}
}
int read(std::string &data, size_t size) {
if(bev_) {
struct evbuffer *readBuffer = bufferevent_get_input(bev_);
const char *pulled_data = (const char *)_readBufferEvent(readBuffer, size);
if(pulled_data)
data.assign(pulled_data, size);
else
return -1;
evbuffer_drain(readBuffer, size);
return size;
} else {
char *p = (char *)malloc(size);
if(NULL == p)
return -1;
#if defined(WIN32)
int res = ::recv(socketFD(), (char *)p, size, 0);
#else
int res = ::read(socketFD(), p, size);
#endif
if(res > 0)
data.assign(p, res);
else
checkResponseSocket(res);
free(p);
return res;
}
}
int read(void *data, size_t size) {
if(bev_) {
struct evbuffer *readBuffer = bufferevent_get_input(bev_);
const char *pulled_data = (const char *)_readBufferEvent(readBuffer, size);
if(pulled_data)
memcpy(data, pulled_data, size);
else
return -1;
evbuffer_drain(readBuffer, size);
return size;
} else {
#if defined(WIN32)
int res = ::recv(socketFD(), (char *)data, size, 0);
#else
int res = ::read(socketFD(), data, size);
#endif
if(res <= 0)
checkResponseSocket(res);
return res;
}
}
int write(const void *data, size_t size) {
ScopedIOServiceLock(owner_->ioService());
int ret;
if(BaseSocket::Connected != owner_->state()) {
if(pendingWriteSupported_) {
#if defined(_KBUFFER_)
ret = kbuffer_add(write_kbuffer_, data, size);
#else
// pending data collected for reconnect.
ret = evbuffer_add(write_evbuffer_, data, size);
if(ret == 0) {
ret = size;
}
#endif
} else {
return -1;
}
}
if(bev_) {
// DO NOT USE write_evbuffer_, just use bufferevent
struct evbuffer *output = bufferevent_get_output(bev_);
ret = evbuffer_add(output, data, size);
if(ret == 0) {
//bufferevent_enable(bev_, EV_WRITE);
ret = size;
}
} else {
#if defined(_KBUFFER_)
LOG_DEBUG("WW %d %d", socketFD(), size);
ret = kbuffer_add(write_kbuffer_, data, size);
#else
ret = evbuffer_add(write_evbuffer_, data, size);
if(ret == 0) {
ret = size;
}
#endif
event_add(ev_write_, NULL);
}
return ret;
}
void close() {
ScopedIOServiceLock(owner_->ioService());
LOG_DEBUG("close() this=%p threadid=%p >> %d %p %p %p\n",
this, owner_->ioService()->nativeThreadHandle(), socketFD(),
bev_, ev_read_, ev_write_);
if(dnsbase_) {
evdns_base_free(dnsbase_, 0);
dnsbase_ = NULL;
}
if(bev_) {
bufferevent_free(bev_);
bev_ = NULL;
}
if(ev_read_) {
coconut_socket_t fd = event_get_fd(ev_read_);
event_free(ev_read_);
evutil_closesocket(fd);
ev_read_ = NULL;
}
if(ev_write_) {
event_free(ev_write_);
ev_write_ = NULL;
}
}
void _onReadEvent(coconut_socket_t fd) {
fire_onSocket_ReadEvent(fd);
}
void _onWriteEvent(coconut_socket_t fd) {
ScopedIOServiceLock(owner_->ioService());
if(BaseSocket::Connecting != owner_->state()) {
#if defined(_KBUFFER_)
#define _AE_CLOSE 1
#define _AE_ERROR 2
int size;
int destroy = 0;
do {
if(kbuffer_get_size(write_kbuffer_) <= 0) {
event_del(ev_write_);
break;
}
const void *data = kbuffer_get_contiguous_data(write_kbuffer_, &size);
#if defined(WIN32)
int nwrite = ::send(fd, (const char *)data, size, 0);
#else
int nwrite = ::write(fd, data, size);
#endif
if(nwrite > 0) {
kbuffer_drain(write_kbuffer_, nwrite);
} else if(nwrite == 0) {
destroy = _AE_CLOSE;
break;
} else if(nwrite < 0) {
if(errno == EAGAIN) {
nwrite = 0;
} else {
destroy = _AE_ERROR;
}
break;
}
} while(false);
if(destroy) {
LOG_FATAL("write error size = %d, reason = %d, fd = %d, errno = %d", size, destroy, socketFD(), EVUTIL_SOCKET_ERROR())
close();
}
#else
evbuffer_write(write_evbuffer_, fd);
if(evbuffer_get_length(write_evbuffer_) <= 0) {
event_del(ev_write_);
}
#endif
} else {
event_del(ev_write_);
fire_onSocket_Connected();
}
}
void onTimer_Timer(int id) {
fire_onSocket_Error(COOKIE_ETIMEDOUT);
}
private: // fire event callback
inline void fire_onSocket_ReadEvent(int fd) {
owner_->fire_onSocket_ReadEvent(fd);
}
/*
void fire_onSocket_Read(const void *data, int size) {
owner_->eventHandler()->onSocket_Read(data, size);
}
*/
void fire_onSocket_Close() {
LOG_DEBUG("fire_onSocket_Close : this = %p, fd = %d, handler = %p, errno = %d",
this, socketFD(), owner_->eventHandler(), EVUTIL_SOCKET_ERROR());
_deleteTimer();
owner_->setState(BaseSocket::Disconnected);
owner_->fire_onSocket_Close();
close();
}
void fire_onSocket_Error(int error) {
LOG_DEBUG("fire_onSocket_Error : this = %p, fd = %d, error = %d, %s, handler = %p\n",
this, socketFD(), EVUTIL_SOCKET_ERROR(), evutil_socket_error_to_string(error), owner_->eventHandler());
errorDetected_ = true;
owner_->setLastErrorString(evutil_socket_error_to_string(error));
if(BaseSocket::Connecting == owner_->state()) {
int err = bufferevent_socket_get_dns_error(bev_);
if(err) {
owner_->setLastErrorString(evutil_gai_strerror(err));
}
}
owner_->setState(BaseSocket::Disconnected);
owner_->fire_onSocket_Error(error, owner_->lastErrorString());
close();
}
void fire_onSocket_Connected() {
if(errorDetected_) {
return;
}
owner_->setState(BaseSocket::Connected);
if(pendingWriteSupported_) {
ScopedIOServiceLock(owner_->ioService());
#if defined(_KBUFFER_)
if(write_kbuffer_ && kbuffer_get_size(write_kbuffer_) > 0) {
if(ev_write_)
event_add(ev_write_, NULL);
}
#else
if(write_evbuffer_ && evbuffer_get_length(write_evbuffer_) > 0) {
if(bev_) {
// send pending data
struct evbuffer *output = bufferevent_get_output(bev_);
evbuffer_add_buffer(output, write_evbuffer_);
}
}
#endif
}
_deleteTimer();
owner_->fire_onSocket_Connected();
}
private:
TcpSocket *owner_;
bool errorDetected_;
bool pendingWriteSupported_;
struct bufferevent *bev_;
struct event *ev_read_;
struct event *ev_write_;
std::string host_;
int port_;
std::string path_;
int timeout_;
struct evbuffer *write_evbuffer_;
kbuffer *write_kbuffer_;
struct evdns_base *dnsbase_;
Timer *conn_timer_;
};
//----------------------------------------------------------------------------------------------------------------
TcpSocket::TcpSocket(boost::shared_ptr<IOService> ioService) : BaseSocket(ioService, TCP) {
impl_ = new TcpSocketImpl(this);
}
TcpSocket::~TcpSocket() {
delete impl_;
}
coconut_socket_t TcpSocket::socketFD() {
return impl_->socketFD();
}
void TcpSocket::attachSocketHandle(coconut_socket_t fd, bool doInstallFlag) {
impl_->attachSocketHandle(fd, doInstallFlag);
}
void TcpSocket::connect(const char *host, int port, int timeout) {
impl_->connect(host, port, timeout);
}
void TcpSocket::connectUnix(const char *path, int timeout) {
impl_->connectUnix(path, timeout);
}
void TcpSocket::connect() {
impl_->connect();
}
void TcpSocket::install() {
impl_->install();
}
void TcpSocket::checkResponseSocket(int res) {
impl_->checkResponseSocket(res);
}
int TcpSocket::read(std::string &data, size_t size) {
return impl_->read(data, size);
}
int TcpSocket::read(void *data, size_t size) {
return impl_->read(data, size);
}
int TcpSocket::write(const void *data, size_t size) {
return impl_->write(data, size);
}
void TcpSocket::close() {
return impl_->close();
}
}