forked from eventmachine/eventmachine
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ed.cpp
1988 lines (1612 loc) · 52.3 KB
/
ed.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
$Id$
File: ed.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
#include "project.h"
/********************
SetSocketNonblocking
********************/
bool SetSocketNonblocking (SOCKET sd)
{
#ifdef OS_UNIX
int val = fcntl (sd, F_GETFL, 0);
return (fcntl (sd, F_SETFL, val | O_NONBLOCK) != SOCKET_ERROR) ? true : false;
#endif
#ifdef OS_WIN32
#ifdef BUILD_FOR_RUBY
// 14Jun09 Ruby provides its own wrappers for ioctlsocket. On 1.8 this is a simple wrapper,
// however, 1.9 keeps its own state about the socket.
// NOTE: F_GETFL is not supported
return (fcntl (sd, F_SETFL, O_NONBLOCK) == 0) ? true : false;
#else
unsigned long one = 1;
return (ioctlsocket (sd, FIONBIO, &one) == 0) ? true : false;
#endif
#endif
}
/****************************************
EventableDescriptor::EventableDescriptor
****************************************/
EventableDescriptor::EventableDescriptor (int sd, EventMachine_t *em):
bCloseNow (false),
bCloseAfterWriting (false),
MySocket (sd),
bAttached (false),
bWatchOnly (false),
EventCallback (NULL),
bCallbackUnbind (true),
UnbindReasonCode (0),
ProxyTarget(NULL),
ProxiedFrom(NULL),
ProxiedBytes(0),
MaxOutboundBufSize(0),
MyEventMachine (em),
PendingConnectTimeout(20000000),
InactivityTimeout (0),
bPaused (false)
{
/* There are three ways to close a socket, all of which should
* automatically signal to the event machine that this object
* should be removed from the polling scheduler.
* First is a hard close, intended for bad errors or possible
* security violations. It immediately closes the connection
* and puts this object into an error state.
* Second is to set bCloseNow, which will cause the event machine
* to delete this object (and thus close the connection in our
* destructor) the next chance it gets. bCloseNow also inhibits
* the writing of new data on the socket (but not necessarily
* the reading of new data).
* The third way is to set bCloseAfterWriting, which inhibits
* the writing of new data and converts to bCloseNow as soon
* as everything in the outbound queue has been written.
* bCloseAfterWriting is really for use only by protocol handlers
* (for example, HTTP writes an HTML page and then closes the
* connection). All of the error states we generate internally
* cause an immediate close to be scheduled, which may have the
* effect of discarding outbound data.
*/
if (sd == INVALID_SOCKET)
throw std::runtime_error ("bad eventable descriptor");
if (MyEventMachine == NULL)
throw std::runtime_error ("bad em in eventable descriptor");
CreatedAt = MyEventMachine->GetCurrentLoopTime();
#ifdef HAVE_EPOLL
EpollEvent.events = 0;
EpollEvent.data.ptr = this;
#endif
LastActivity = MyEventMachine->GetCurrentLoopTime();
}
/*****************************************
EventableDescriptor::~EventableDescriptor
*****************************************/
EventableDescriptor::~EventableDescriptor()
{
if (NextHeartbeat)
MyEventMachine->ClearHeartbeat(NextHeartbeat, this);
if (EventCallback && bCallbackUnbind)
(*EventCallback)(GetBinding(), EM_CONNECTION_UNBOUND, NULL, UnbindReasonCode);
if (ProxiedFrom) {
(*EventCallback)(ProxiedFrom->GetBinding(), EM_PROXY_TARGET_UNBOUND, NULL, 0);
ProxiedFrom->StopProxy();
}
MyEventMachine->NumCloseScheduled--;
StopProxy();
Close();
}
/*************************************
EventableDescriptor::SetEventCallback
*************************************/
void EventableDescriptor::SetEventCallback (EMCallback cb)
{
EventCallback = cb;
}
/**************************
EventableDescriptor::Close
**************************/
void EventableDescriptor::Close()
{
/* EventMachine relies on the fact that when close(fd)
* is called that the fd is removed from any
* epoll event queues.
*
* However, this is not *always* the behavior of close(fd)
*
* See man 4 epoll Q6/A6 and then consider what happens
* when using pipes with eventmachine.
* (As is often done when communicating with a subprocess)
*
* The pipes end up looking like:
*
* ls -l /proc/<pid>/fd
* ...
* lr-x------ 1 root root 64 2011-08-19 21:31 3 -> pipe:[940970]
* l-wx------ 1 root root 64 2011-08-19 21:31 4 -> pipe:[940970]
*
* This meets the critera from man 4 epoll Q6/A4 for not
* removing fds from epoll event queues until all fds
* that reference the underlying file have been removed.
*
* If the EventableDescriptor associated with fd 3 is deleted,
* its dtor will call EventableDescriptor::Close(),
* which will call ::close(int fd).
*
* However, unless the EventableDescriptor associated with fd 4 is
* also deleted before the next call to epoll_wait, events may fire
* for fd 3 that were registered with an already deleted
* EventableDescriptor.
*
* Therefore, it is necessary to notify EventMachine that
* the fd associated with this EventableDescriptor is
* closing.
*
* EventMachine also never closes fds for STDIN, STDOUT and
* STDERR (0, 1 & 2)
*/
// Close the socket right now. Intended for emergencies.
if (MySocket != INVALID_SOCKET) {
MyEventMachine->Deregister (this);
// Do not close STDIN, STDOUT, STDERR
if (MySocket > 2 && !bAttached) {
shutdown (MySocket, 1);
close (MySocket);
}
MySocket = INVALID_SOCKET;
}
}
/*********************************
EventableDescriptor::ShouldDelete
*********************************/
bool EventableDescriptor::ShouldDelete()
{
/* For use by a socket manager, which needs to know if this object
* should be removed from scheduling events and deleted.
* Has an immediate close been scheduled, or are we already closed?
* If either of these are the case, return true. In theory, the manager will
* then delete us, which in turn will make sure the socket is closed.
* Note, if bCloseAfterWriting is true, we check a virtual method to see
* if there is outbound data to write, and only request a close if there is none.
*/
return ((MySocket == INVALID_SOCKET) || bCloseNow || (bCloseAfterWriting && (GetOutboundDataSize() <= 0)));
}
/**********************************
EventableDescriptor::ScheduleClose
**********************************/
void EventableDescriptor::ScheduleClose (bool after_writing)
{
if (IsCloseScheduled())
return;
MyEventMachine->NumCloseScheduled++;
// KEEP THIS SYNCHRONIZED WITH ::IsCloseScheduled.
if (after_writing)
bCloseAfterWriting = true;
else
bCloseNow = true;
}
/*************************************
EventableDescriptor::IsCloseScheduled
*************************************/
bool EventableDescriptor::IsCloseScheduled()
{
// KEEP THIS SYNCHRONIZED WITH ::ScheduleClose.
return (bCloseNow || bCloseAfterWriting);
}
/*******************************
EventableDescriptor::StartProxy
*******************************/
void EventableDescriptor::StartProxy(const unsigned long to, const unsigned long bufsize, const unsigned long length)
{
EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (to));
if (ed) {
StopProxy();
ProxyTarget = ed;
BytesToProxy = length;
ProxiedBytes = 0;
ed->SetProxiedFrom(this, bufsize);
return;
}
throw std::runtime_error ("Tried to proxy to an invalid descriptor");
}
/******************************
EventableDescriptor::StopProxy
******************************/
void EventableDescriptor::StopProxy()
{
if (ProxyTarget) {
ProxyTarget->SetProxiedFrom(NULL, 0);
ProxyTarget = NULL;
}
}
/***********************************
EventableDescriptor::SetProxiedFrom
***********************************/
void EventableDescriptor::SetProxiedFrom(EventableDescriptor *from, const unsigned long bufsize)
{
if (from != NULL && ProxiedFrom != NULL)
throw std::runtime_error ("Tried to proxy to a busy target");
ProxiedFrom = from;
MaxOutboundBufSize = bufsize;
}
/********************************************
EventableDescriptor::_GenericInboundDispatch
********************************************/
void EventableDescriptor::_GenericInboundDispatch(const char *buf, int size)
{
assert(EventCallback);
if (ProxyTarget) {
if (BytesToProxy > 0) {
unsigned long proxied = min(BytesToProxy, (unsigned long) size);
ProxyTarget->SendOutboundData(buf, proxied);
ProxiedBytes += (unsigned long) proxied;
BytesToProxy -= proxied;
if (BytesToProxy == 0) {
StopProxy();
(*EventCallback)(GetBinding(), EM_PROXY_COMPLETED, NULL, 0);
if (proxied < size) {
(*EventCallback)(GetBinding(), EM_CONNECTION_READ, buf + proxied, size - proxied);
}
}
} else {
ProxyTarget->SendOutboundData(buf, size);
ProxiedBytes += (unsigned long) size;
}
} else {
(*EventCallback)(GetBinding(), EM_CONNECTION_READ, buf, size);
}
}
/*********************************************
EventableDescriptor::GetPendingConnectTimeout
*********************************************/
uint64_t EventableDescriptor::GetPendingConnectTimeout()
{
return PendingConnectTimeout / 1000;
}
/*********************************************
EventableDescriptor::SetPendingConnectTimeout
*********************************************/
int EventableDescriptor::SetPendingConnectTimeout (uint64_t value)
{
if (value > 0) {
PendingConnectTimeout = value * 1000;
MyEventMachine->QueueHeartbeat(this);
return 1;
}
return 0;
}
/*************************************
EventableDescriptor::GetNextHeartbeat
*************************************/
uint64_t EventableDescriptor::GetNextHeartbeat()
{
if (NextHeartbeat)
MyEventMachine->ClearHeartbeat(NextHeartbeat, this);
NextHeartbeat = 0;
if (!ShouldDelete()) {
uint64_t time_til_next = InactivityTimeout;
if (IsConnectPending()) {
if (time_til_next == 0 || PendingConnectTimeout < time_til_next)
time_til_next = PendingConnectTimeout;
}
if (time_til_next == 0)
return 0;
NextHeartbeat = time_til_next + MyEventMachine->GetRealTime();
}
return NextHeartbeat;
}
/******************************************
ConnectionDescriptor::ConnectionDescriptor
******************************************/
ConnectionDescriptor::ConnectionDescriptor (int sd, EventMachine_t *em):
EventableDescriptor (sd, em),
bConnectPending (false),
bNotifyReadable (false),
bNotifyWritable (false),
bReadAttemptedAfterClose (false),
bWriteAttemptedAfterClose (false),
OutboundDataSize (0),
#ifdef WITH_SSL
SslBox (NULL),
bHandshakeSignaled (false),
bSslVerifyPeer (false),
bSslPeerAccepted(false),
#endif
#ifdef HAVE_KQUEUE
bGotExtraKqueueEvent(false),
#endif
bIsServer (false)
{
// 22Jan09: Moved ArmKqueueWriter into SetConnectPending() to fix assertion failure in _WriteOutboundData()
// 5May09: Moved EPOLLOUT into SetConnectPending() so it doesn't happen for attached read pipes
}
/*******************************************
ConnectionDescriptor::~ConnectionDescriptor
*******************************************/
ConnectionDescriptor::~ConnectionDescriptor()
{
// Run down any stranded outbound data.
for (size_t i=0; i < OutboundPages.size(); i++)
OutboundPages[i].Free();
#ifdef WITH_SSL
if (SslBox)
delete SslBox;
#endif
}
/***********************************
ConnectionDescriptor::_UpdateEvents
************************************/
void ConnectionDescriptor::_UpdateEvents()
{
_UpdateEvents(true, true);
}
void ConnectionDescriptor::_UpdateEvents(bool read, bool write)
{
if (MySocket == INVALID_SOCKET)
return;
#ifdef HAVE_EPOLL
unsigned int old = EpollEvent.events;
if (read) {
if (SelectForRead())
EpollEvent.events |= EPOLLIN;
else
EpollEvent.events &= ~EPOLLIN;
}
if (write) {
if (SelectForWrite())
EpollEvent.events |= EPOLLOUT;
else
EpollEvent.events &= ~EPOLLOUT;
}
if (old != EpollEvent.events)
MyEventMachine->Modify (this);
#endif
#ifdef HAVE_KQUEUE
if (read && SelectForRead())
MyEventMachine->ArmKqueueReader (this);
if (write && SelectForWrite())
MyEventMachine->ArmKqueueWriter (this);
#endif
}
/***************************************
ConnectionDescriptor::SetConnectPending
****************************************/
void ConnectionDescriptor::SetConnectPending(bool f)
{
bConnectPending = f;
MyEventMachine->QueueHeartbeat(this);
_UpdateEvents();
}
/**********************************
ConnectionDescriptor::SetAttached
***********************************/
void ConnectionDescriptor::SetAttached(bool state)
{
bAttached = state;
}
/**********************************
ConnectionDescriptor::SetWatchOnly
***********************************/
void ConnectionDescriptor::SetWatchOnly(bool watching)
{
bWatchOnly = watching;
_UpdateEvents();
}
/*********************************
ConnectionDescriptor::HandleError
*********************************/
void ConnectionDescriptor::HandleError()
{
if (bWatchOnly) {
// An EPOLLHUP | EPOLLIN condition will call Read() before HandleError(), in which case the
// socket is already detached and invalid, so we don't need to do anything.
if (MySocket == INVALID_SOCKET) return;
// HandleError() is called on WatchOnly descriptors by the epoll reactor
// when it gets a EPOLLERR | EPOLLHUP. Usually this would show up as a readable and
// writable event on other reactors, so we have to fire those events ourselves.
if (bNotifyReadable) Read();
if (bNotifyWritable) Write();
} else {
ScheduleClose (false);
}
}
/***********************************
ConnectionDescriptor::ScheduleClose
***********************************/
void ConnectionDescriptor::ScheduleClose (bool after_writing)
{
if (bWatchOnly)
throw std::runtime_error ("cannot close 'watch only' connections");
EventableDescriptor::ScheduleClose(after_writing);
}
/***************************************
ConnectionDescriptor::SetNotifyReadable
****************************************/
void ConnectionDescriptor::SetNotifyReadable(bool readable)
{
if (!bWatchOnly)
throw std::runtime_error ("notify_readable must be on 'watch only' connections");
bNotifyReadable = readable;
_UpdateEvents(true, false);
}
/***************************************
ConnectionDescriptor::SetNotifyWritable
****************************************/
void ConnectionDescriptor::SetNotifyWritable(bool writable)
{
if (!bWatchOnly)
throw std::runtime_error ("notify_writable must be on 'watch only' connections");
bNotifyWritable = writable;
_UpdateEvents(false, true);
}
/**************************************
ConnectionDescriptor::SendOutboundData
**************************************/
int ConnectionDescriptor::SendOutboundData (const char *data, int length)
{
if (bWatchOnly)
throw std::runtime_error ("cannot send data on a 'watch only' connection");
if (ProxiedFrom && MaxOutboundBufSize && (unsigned int)(GetOutboundDataSize() + length) > MaxOutboundBufSize)
ProxiedFrom->Pause();
#ifdef WITH_SSL
if (SslBox) {
if (length > 0) {
int w = SslBox->PutPlaintext (data, length);
if (w < 0)
ScheduleClose (false);
else
_DispatchCiphertext();
}
// TODO: What's the correct return value?
return 1; // That's a wild guess, almost certainly wrong.
}
else
#endif
return _SendRawOutboundData (data, length);
}
/******************************************
ConnectionDescriptor::_SendRawOutboundData
******************************************/
int ConnectionDescriptor::_SendRawOutboundData (const char *data, int length)
{
/* This internal method is called to schedule bytes that
* will be sent out to the remote peer.
* It's not directly accessed by the caller, who hits ::SendOutboundData,
* which may or may not filter or encrypt the caller's data before
* sending it here.
*/
// Highly naive and incomplete implementation.
// There's no throttle for runaways (which should abort only this connection
// and not the whole process), and no coalescing of small pages.
// (Well, not so bad, small pages are coalesced in ::Write)
if (IsCloseScheduled())
return 0;
// 25Mar10: Ignore 0 length packets as they are not meaningful in TCP (as opposed to UDP)
// and can cause the assert(nbytes>0) to fail when OutboundPages has a bunch of 0 length pages.
if (length == 0)
return 0;
if (!data && (length > 0))
throw std::runtime_error ("bad outbound data");
char *buffer = (char *) malloc (length + 1);
if (!buffer)
throw std::runtime_error ("no allocation for outbound data");
memcpy (buffer, data, length);
buffer [length] = 0;
OutboundPages.push_back (OutboundPage (buffer, length));
OutboundDataSize += length;
_UpdateEvents(false, true);
return length;
}
/***********************************
ConnectionDescriptor::SelectForRead
***********************************/
bool ConnectionDescriptor::SelectForRead()
{
/* A connection descriptor is always scheduled for read,
* UNLESS it's in a pending-connect state.
* On Linux, unlike Unix, a nonblocking socket on which
* connect has been called, does NOT necessarily select
* both readable and writable in case of error.
* The socket will select writable when the disposition
* of the connect is known. On the other hand, a socket
* which successfully connects and selects writable may
* indeed have some data available on it, so it will
* select readable in that case, violating expectations!
* So we will not poll for readability until the socket
* is known to be in a connected state.
*/
if (bPaused)
return false;
else if (bConnectPending)
return false;
else if (bWatchOnly)
return bNotifyReadable ? true : false;
else
return true;
}
/************************************
ConnectionDescriptor::SelectForWrite
************************************/
bool ConnectionDescriptor::SelectForWrite()
{
/* Cf the notes under SelectForRead.
* In a pending-connect state, we ALWAYS select for writable.
* In a normal state, we only select for writable when we
* have outgoing data to send.
*/
if (bPaused)
return false;
else if (bConnectPending)
return true;
else if (bWatchOnly)
return bNotifyWritable ? true : false;
else
return (GetOutboundDataSize() > 0);
}
/***************************
ConnectionDescriptor::Pause
***************************/
bool ConnectionDescriptor::Pause()
{
if (bWatchOnly)
throw std::runtime_error ("cannot pause/resume 'watch only' connections, set notify readable/writable instead");
bool old = bPaused;
bPaused = true;
_UpdateEvents();
return old == false;
}
/****************************
ConnectionDescriptor::Resume
****************************/
bool ConnectionDescriptor::Resume()
{
if (bWatchOnly)
throw std::runtime_error ("cannot pause/resume 'watch only' connections, set notify readable/writable instead");
bool old = bPaused;
bPaused = false;
_UpdateEvents();
return old == true;
}
/**************************
ConnectionDescriptor::Read
**************************/
void ConnectionDescriptor::Read()
{
/* Read and dispatch data on a socket that has selected readable.
* It's theoretically possible to get and dispatch incoming data on
* a socket that has already been scheduled for closing or close-after-writing.
* In those cases, we'll leave it up the to protocol handler to "do the
* right thing" (which probably means to ignore the incoming data).
*
* 22Aug06: Chris Ochs reports that on FreeBSD, it's possible to come
* here with the socket already closed, after the process receives
* a ctrl-C signal (not sure if that's TERM or INT on BSD). The application
* was one in which network connections were doing a lot of interleaved reads
* and writes.
* Since we always write before reading (in order to keep the outbound queues
* as light as possible), I think what happened is that an interrupt caused
* the socket to be closed in ConnectionDescriptor::Write. We'll then
* come here in the same pass through the main event loop, and won't get
* cleaned up until immediately after.
* We originally asserted that the socket was valid when we got here.
* To deal properly with the possibility that we are closed when we get here,
* I removed the assert. HOWEVER, the potential for an infinite loop scares me,
* so even though this is really clunky, I added a flag to assert that we never
* come here more than once after being closed. (FCianfrocca)
*/
int sd = GetSocket();
//assert (sd != INVALID_SOCKET); (original, removed 22Aug06)
if (sd == INVALID_SOCKET) {
assert (!bReadAttemptedAfterClose);
bReadAttemptedAfterClose = true;
return;
}
if (bWatchOnly) {
if (bNotifyReadable && EventCallback)
(*EventCallback)(GetBinding(), EM_CONNECTION_NOTIFY_READABLE, NULL, 0);
return;
}
LastActivity = MyEventMachine->GetCurrentLoopTime();
int total_bytes_read = 0;
char readbuffer [16 * 1024 + 1];
for (int i=0; i < 10; i++) {
// Don't read just one buffer and then move on. This is faster
// if there is a lot of incoming.
// But don't read indefinitely. Give other sockets a chance to run.
// NOTICE, we're reading one less than the buffer size.
// That's so we can put a guard byte at the end of what we send
// to user code.
int r = read (sd, readbuffer, sizeof(readbuffer) - 1);
#ifdef OS_WIN32
int e = WSAGetLastError();
#else
int e = errno;
#endif
//cerr << "<R:" << r << ">";
if (r > 0) {
total_bytes_read += r;
// Add a null-terminator at the the end of the buffer
// that we will send to the callback.
// DO NOT EVER CHANGE THIS. We want to explicitly allow users
// to be able to depend on this behavior, so they will have
// the option to do some things faster. Additionally it's
// a security guard against buffer overflows.
readbuffer [r] = 0;
_DispatchInboundData (readbuffer, r);
if (bPaused)
break;
}
else if (r == 0) {
break;
}
else {
#ifdef OS_UNIX
if ((e != EINPROGRESS) && (e != EWOULDBLOCK) && (e != EAGAIN) && (e != EINTR)) {
#endif
#ifdef OS_WIN32
if ((e != WSAEINPROGRESS) && (e != WSAEWOULDBLOCK)) {
#endif
// 26Mar11: Previously, all read errors were assumed to be EWOULDBLOCK and ignored.
// Now, instead, we call Close() on errors like ECONNRESET and ENOTCONN.
UnbindReasonCode = e;
Close();
break;
} else {
// Basically a would-block, meaning we've read everything there is to read.
break;
}
}
}
if (total_bytes_read == 0) {
// If we read no data on a socket that selected readable,
// it generally means the other end closed the connection gracefully.
ScheduleClose (false);
//bCloseNow = true;
}
}
/******************************************
ConnectionDescriptor::_DispatchInboundData
******************************************/
void ConnectionDescriptor::_DispatchInboundData (const char *buffer, int size)
{
#ifdef WITH_SSL
if (SslBox) {
SslBox->PutCiphertext (buffer, size);
int s;
char B [2048];
while ((s = SslBox->GetPlaintext (B, sizeof(B) - 1)) > 0) {
_CheckHandshakeStatus();
B [s] = 0;
_GenericInboundDispatch(B, s);
}
// If our SSL handshake had a problem, shut down the connection.
if (s == -2) {
ScheduleClose(false);
return;
}
_CheckHandshakeStatus();
_DispatchCiphertext();
}
else {
_GenericInboundDispatch(buffer, size);
}
#endif
#ifdef WITHOUT_SSL
_GenericInboundDispatch(buffer, size);
#endif
}
/*******************************************
ConnectionDescriptor::_CheckHandshakeStatus
*******************************************/
void ConnectionDescriptor::_CheckHandshakeStatus()
{
#ifdef WITH_SSL
if (SslBox && (!bHandshakeSignaled) && SslBox->IsHandshakeCompleted()) {
bHandshakeSignaled = true;
if (EventCallback)
(*EventCallback)(GetBinding(), EM_SSL_HANDSHAKE_COMPLETED, NULL, 0);
}
#endif
}
/***************************
ConnectionDescriptor::Write
***************************/
void ConnectionDescriptor::Write()
{
/* A socket which is in a pending-connect state will select
* writable when the disposition of the connect is known.
* At that point, check to be sure there are no errors,
* and if none, then promote the socket out of the pending
* state.
* TODO: I haven't figured out how Windows signals errors on
* unconnected sockets. Maybe it does the untraditional but
* logical thing and makes the socket selectable for error.
* If so, it's unsupported here for the time being, and connect
* errors will have to be caught by the timeout mechanism.
*/
if (bConnectPending) {
int error;
socklen_t len;
len = sizeof(error);
#ifdef OS_UNIX
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, &error, &len);
#endif
#ifdef OS_WIN32
int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, (char*)&error, &len);
#endif
if ((o == 0) && (error == 0)) {
if (EventCallback)
(*EventCallback)(GetBinding(), EM_CONNECTION_COMPLETED, "", 0);
// 5May09: Moved epoll/kqueue read/write arming into SetConnectPending, so it can be called
// from EventMachine_t::AttachFD as well.
SetConnectPending (false);
}
else {
if (o == 0)
UnbindReasonCode = error;
ScheduleClose (false);
//bCloseNow = true;
}
}
else {
if (bNotifyWritable) {
if (EventCallback)
(*EventCallback)(GetBinding(), EM_CONNECTION_NOTIFY_WRITABLE, NULL, 0);
_UpdateEvents(false, true);
return;
}
assert(!bWatchOnly);
/* 5May09: Kqueue bugs on OSX cause one extra writable event to fire even though we're using
EV_ONESHOT. We ignore this extra event once, but only the first time. If it happens again,
we should fall through to the assert(nbytes>0) failure to catch any EM bugs which might cause
::Write to be called in a busy-loop.
*/
#ifdef HAVE_KQUEUE
if (MyEventMachine->UsingKqueue()) {
if (OutboundDataSize == 0 && !bGotExtraKqueueEvent) {
bGotExtraKqueueEvent = true;
return;
} else if (OutboundDataSize > 0) {
bGotExtraKqueueEvent = false;
}
}
#endif
_WriteOutboundData();
}
}
/****************************************
ConnectionDescriptor::_WriteOutboundData
****************************************/
void ConnectionDescriptor::_WriteOutboundData()
{
/* This is a helper function called by ::Write.
* It's possible for a socket to select writable and then no longer
* be writable by the time we get around to writing. The kernel might
* have used up its available output buffers between the select call
* and when we get here. So this condition is not an error.
*
* 20Jul07, added the same kind of protection against an invalid socket
* that is at the top of ::Read. Not entirely how this could happen in
* real life (connection-reset from the remote peer, perhaps?), but I'm
* doing it to address some reports of crashing under heavy loads.
*/
int sd = GetSocket();
//assert (sd != INVALID_SOCKET);
if (sd == INVALID_SOCKET) {
assert (!bWriteAttemptedAfterClose);
bWriteAttemptedAfterClose = true;
return;
}
LastActivity = MyEventMachine->GetCurrentLoopTime();
size_t nbytes = 0;
#ifdef HAVE_WRITEV
int iovcnt = OutboundPages.size();
// Max of 16 outbound pages at a time
if (iovcnt > 16) iovcnt = 16;
iovec iov[16];
for(int i = 0; i < iovcnt; i++){
OutboundPage *op = &(OutboundPages[i]);
#ifdef CC_SUNWspro
iov[i].iov_base = (char *)(op->Buffer + op->Offset);
#else
iov[i].iov_base = (void *)(op->Buffer + op->Offset);
#endif