MattHulse-eventmachine 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. data/.gitignore +14 -0
  2. data/README +82 -0
  3. data/Rakefile +279 -0
  4. data/docs/COPYING +60 -0
  5. data/docs/ChangeLog +211 -0
  6. data/docs/DEFERRABLES +133 -0
  7. data/docs/EPOLL +141 -0
  8. data/docs/GNU +281 -0
  9. data/docs/INSTALL +13 -0
  10. data/docs/KEYBOARD +38 -0
  11. data/docs/LEGAL +25 -0
  12. data/docs/LIGHTWEIGHT_CONCURRENCY +70 -0
  13. data/docs/PURE_RUBY +75 -0
  14. data/docs/RELEASE_NOTES +94 -0
  15. data/docs/SMTP +2 -0
  16. data/docs/SPAWNED_PROCESSES +89 -0
  17. data/docs/TODO +8 -0
  18. data/eventmachine.gemspec +41 -0
  19. data/examples/ex_channel.rb +43 -0
  20. data/examples/ex_queue.rb +2 -0
  21. data/examples/helper.rb +2 -0
  22. data/ext/binder.cpp +125 -0
  23. data/ext/binder.h +46 -0
  24. data/ext/cmain.cpp +821 -0
  25. data/ext/cplusplus.cpp +202 -0
  26. data/ext/ed.cpp +1868 -0
  27. data/ext/ed.h +416 -0
  28. data/ext/em.cpp +2270 -0
  29. data/ext/em.h +228 -0
  30. data/ext/emwin.cpp +300 -0
  31. data/ext/emwin.h +94 -0
  32. data/ext/epoll.cpp +26 -0
  33. data/ext/epoll.h +25 -0
  34. data/ext/eventmachine.h +122 -0
  35. data/ext/eventmachine_cpp.h +96 -0
  36. data/ext/extconf.rb +138 -0
  37. data/ext/fastfilereader/extconf.rb +84 -0
  38. data/ext/fastfilereader/mapper.cpp +214 -0
  39. data/ext/fastfilereader/mapper.h +59 -0
  40. data/ext/fastfilereader/rubymain.cpp +127 -0
  41. data/ext/files.cpp +94 -0
  42. data/ext/files.h +65 -0
  43. data/ext/kb.cpp +81 -0
  44. data/ext/page.cpp +107 -0
  45. data/ext/page.h +51 -0
  46. data/ext/pipe.cpp +349 -0
  47. data/ext/project.h +147 -0
  48. data/ext/rubymain.cpp +1152 -0
  49. data/ext/sigs.cpp +89 -0
  50. data/ext/sigs.h +32 -0
  51. data/ext/ssl.cpp +460 -0
  52. data/ext/ssl.h +94 -0
  53. data/java/.classpath +8 -0
  54. data/java/.project +17 -0
  55. data/java/src/com/rubyeventmachine/Application.java +192 -0
  56. data/java/src/com/rubyeventmachine/Connection.java +74 -0
  57. data/java/src/com/rubyeventmachine/ConnectionFactory.java +37 -0
  58. data/java/src/com/rubyeventmachine/DefaultConnectionFactory.java +46 -0
  59. data/java/src/com/rubyeventmachine/EmReactor.java +557 -0
  60. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  61. data/java/src/com/rubyeventmachine/EventableChannel.java +69 -0
  62. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +189 -0
  63. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
  64. data/java/src/com/rubyeventmachine/PeriodicTimer.java +38 -0
  65. data/java/src/com/rubyeventmachine/Timer.java +54 -0
  66. data/java/src/com/rubyeventmachine/tests/ApplicationTest.java +108 -0
  67. data/java/src/com/rubyeventmachine/tests/ConnectTest.java +146 -0
  68. data/java/src/com/rubyeventmachine/tests/EMTest.java +80 -0
  69. data/java/src/com/rubyeventmachine/tests/TestDatagrams.java +53 -0
  70. data/java/src/com/rubyeventmachine/tests/TestServers.java +74 -0
  71. data/java/src/com/rubyeventmachine/tests/TestTimers.java +89 -0
  72. data/lib/em/buftok.rb +138 -0
  73. data/lib/em/callback.rb +26 -0
  74. data/lib/em/channel.rb +57 -0
  75. data/lib/em/connection.rb +564 -0
  76. data/lib/em/deferrable.rb +187 -0
  77. data/lib/em/file_watch.rb +54 -0
  78. data/lib/em/future.rb +61 -0
  79. data/lib/em/messages.rb +66 -0
  80. data/lib/em/process_watch.rb +44 -0
  81. data/lib/em/processes.rb +119 -0
  82. data/lib/em/protocols.rb +35 -0
  83. data/lib/em/protocols/header_and_content.rb +138 -0
  84. data/lib/em/protocols/httpclient.rb +263 -0
  85. data/lib/em/protocols/httpclient2.rb +582 -0
  86. data/lib/em/protocols/line_and_text.rb +126 -0
  87. data/lib/em/protocols/linetext2.rb +160 -0
  88. data/lib/em/protocols/memcache.rb +323 -0
  89. data/lib/em/protocols/object_protocol.rb +45 -0
  90. data/lib/em/protocols/postgres3.rb +247 -0
  91. data/lib/em/protocols/saslauth.rb +175 -0
  92. data/lib/em/protocols/smtpclient.rb +350 -0
  93. data/lib/em/protocols/smtpserver.rb +547 -0
  94. data/lib/em/protocols/stomp.rb +200 -0
  95. data/lib/em/protocols/tcptest.rb +53 -0
  96. data/lib/em/queue.rb +61 -0
  97. data/lib/em/spawnable.rb +85 -0
  98. data/lib/em/streamer.rb +130 -0
  99. data/lib/em/timers.rb +55 -0
  100. data/lib/em/version.rb +3 -0
  101. data/lib/eventmachine.rb +1698 -0
  102. data/lib/evma.rb +32 -0
  103. data/lib/evma/callback.rb +32 -0
  104. data/lib/evma/container.rb +75 -0
  105. data/lib/evma/factory.rb +77 -0
  106. data/lib/evma/protocol.rb +87 -0
  107. data/lib/evma/reactor.rb +48 -0
  108. data/lib/jeventmachine.rb +246 -0
  109. data/lib/pr_eventmachine.rb +1022 -0
  110. data/setup.rb +1585 -0
  111. data/tasks/cpp.rake +77 -0
  112. data/tasks/project.rake +79 -0
  113. data/tasks/tests.rake +193 -0
  114. data/tests/client.crt +31 -0
  115. data/tests/client.key +51 -0
  116. data/tests/test_attach.rb +126 -0
  117. data/tests/test_basic.rb +284 -0
  118. data/tests/test_channel.rb +63 -0
  119. data/tests/test_connection_count.rb +35 -0
  120. data/tests/test_defer.rb +47 -0
  121. data/tests/test_epoll.rb +160 -0
  122. data/tests/test_error_handler.rb +35 -0
  123. data/tests/test_errors.rb +82 -0
  124. data/tests/test_exc.rb +55 -0
  125. data/tests/test_file_watch.rb +49 -0
  126. data/tests/test_futures.rb +198 -0
  127. data/tests/test_handler_check.rb +37 -0
  128. data/tests/test_hc.rb +218 -0
  129. data/tests/test_httpclient.rb +218 -0
  130. data/tests/test_httpclient2.rb +153 -0
  131. data/tests/test_inactivity_timeout.rb +50 -0
  132. data/tests/test_kb.rb +60 -0
  133. data/tests/test_ltp.rb +182 -0
  134. data/tests/test_ltp2.rb +317 -0
  135. data/tests/test_next_tick.rb +133 -0
  136. data/tests/test_object_protocol.rb +37 -0
  137. data/tests/test_process_watch.rb +48 -0
  138. data/tests/test_processes.rb +128 -0
  139. data/tests/test_proxy_connection.rb +92 -0
  140. data/tests/test_pure.rb +125 -0
  141. data/tests/test_queue.rb +44 -0
  142. data/tests/test_running.rb +42 -0
  143. data/tests/test_sasl.rb +72 -0
  144. data/tests/test_send_file.rb +242 -0
  145. data/tests/test_servers.rb +76 -0
  146. data/tests/test_smtpclient.rb +83 -0
  147. data/tests/test_smtpserver.rb +85 -0
  148. data/tests/test_spawn.rb +322 -0
  149. data/tests/test_ssl_args.rb +68 -0
  150. data/tests/test_ssl_methods.rb +50 -0
  151. data/tests/test_ssl_verify.rb +82 -0
  152. data/tests/test_timers.rb +162 -0
  153. data/tests/test_ud.rb +36 -0
  154. data/tests/testem.rb +31 -0
  155. data/web/whatis +7 -0
  156. metadata +223 -0
data/ext/cplusplus.cpp ADDED
@@ -0,0 +1,202 @@
1
+ /*****************************************************************************
2
+
3
+ $Id$
4
+
5
+ File: cplusplus.cpp
6
+ Date: 27Jul07
7
+
8
+ Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
9
+ Gmail: blackhedd
10
+
11
+ This program is free software; you can redistribute it and/or modify
12
+ it under the terms of either: 1) the GNU General Public License
13
+ as published by the Free Software Foundation; either version 2 of the
14
+ License, or (at your option) any later version; or 2) Ruby's License.
15
+
16
+ See the file COPYING for complete licensing information.
17
+
18
+ *****************************************************************************/
19
+
20
+
21
+ #include "project.h"
22
+
23
+
24
+ namespace EM {
25
+ static map<unsigned long, Eventable*> Eventables;
26
+ static map<unsigned long, void(*)()> Timers;
27
+ }
28
+
29
+
30
+ /*******
31
+ EM::Run
32
+ *******/
33
+
34
+ void EM::Run (void (*start_func)())
35
+ {
36
+ evma_set_epoll (1);
37
+ evma_initialize_library (EM::Callback);
38
+ if (start_func)
39
+ AddTimer (0, start_func);
40
+ evma_run_machine();
41
+ evma_release_library();
42
+ }
43
+
44
+ /************
45
+ EM::AddTimer
46
+ ************/
47
+
48
+ void EM::AddTimer (int milliseconds, void (*func)())
49
+ {
50
+ if (func) {
51
+ const unsigned long sig = evma_install_oneshot_timer (milliseconds);
52
+ #ifdef OS_SOLARIS8
53
+ Timers.insert (map<unsigned long, void(*)()>::value_type (sig, func));
54
+ #else
55
+ Timers.insert (make_pair (sig, func));
56
+ #endif
57
+ }
58
+ }
59
+
60
+
61
+ /***************
62
+ EM::StopReactor
63
+ ***************/
64
+
65
+ void EM::StopReactor()
66
+ {
67
+ evma_stop_machine();
68
+ }
69
+
70
+
71
+ /********************
72
+ EM::Acceptor::Accept
73
+ ********************/
74
+
75
+ void EM::Acceptor::Accept (const unsigned long signature)
76
+ {
77
+ Connection *c = MakeConnection();
78
+ c->Signature = signature;
79
+ #ifdef OS_SOLARIS8
80
+ Eventables.insert (std::map<unsigned long,EM::Eventable*>::value_type (c->Signature, c));
81
+ #else
82
+ Eventables.insert (make_pair (c->Signature, c));
83
+ #endif
84
+ c->PostInit();
85
+ }
86
+
87
+ /************************
88
+ EM::Connection::SendData
89
+ ************************/
90
+
91
+ void EM::Connection::SendData (const char *data)
92
+ {
93
+ if (data)
94
+ SendData (data, strlen (data));
95
+ }
96
+
97
+
98
+ /************************
99
+ EM::Connection::SendData
100
+ ************************/
101
+
102
+ void EM::Connection::SendData (const char *data, int length)
103
+ {
104
+ evma_send_data_to_connection (Signature, data, length);
105
+ }
106
+
107
+
108
+ /*********************
109
+ EM::Connection::Close
110
+ *********************/
111
+
112
+ void EM::Connection::Close (bool afterWriting)
113
+ {
114
+ evma_close_connection (Signature, afterWriting);
115
+ }
116
+
117
+
118
+ /***************************
119
+ EM::Connection::BindConnect
120
+ ***************************/
121
+
122
+ void EM::Connection::BindConnect (const char *bind_addr, int bind_port, const char *host, int port)
123
+ {
124
+ Signature = evma_connect_to_server (bind_addr, bind_port, host, port);
125
+ #ifdef OS_SOLARIS8
126
+ Eventables.insert( std::map<unsigned long,EM::Eventable*>::value_type (Signature, this));
127
+ #else
128
+ Eventables.insert( make_pair (Signature, this));
129
+ #endif
130
+ }
131
+
132
+ /***********************
133
+ EM::Connection::Connect
134
+ ***********************/
135
+
136
+ void EM::Connection::Connect (const char *host, int port)
137
+ {
138
+ this->BindConnect(NULL, 0, host, port);
139
+ }
140
+
141
+ /*******************
142
+ EM::Acceptor::Start
143
+ *******************/
144
+
145
+ void EM::Acceptor::Start (const char *host, int port)
146
+ {
147
+ Signature = evma_create_tcp_server (host, port);
148
+ #ifdef OS_SOLARIS8
149
+ Eventables.insert( std::map<std::string,EM::Eventable*>::value_type (Signature, this));
150
+ #else
151
+ Eventables.insert( make_pair (Signature, this));
152
+ #endif
153
+ }
154
+
155
+
156
+
157
+ /************
158
+ EM::Callback
159
+ ************/
160
+
161
+ void EM::Callback (const unsigned long sig, int ev, const char *data, const unsigned long length)
162
+ {
163
+ EM::Eventable *e;
164
+ void (*f)();
165
+
166
+ switch (ev) {
167
+ case EM_TIMER_FIRED:
168
+ f = Timers [length]; // actually a binding
169
+ if (f)
170
+ (*f)();
171
+ Timers.erase (length);
172
+ break;
173
+
174
+ case EM_CONNECTION_READ:
175
+ e = EM::Eventables [sig];
176
+ e->ReceiveData (data, length);
177
+ break;
178
+
179
+ case EM_CONNECTION_COMPLETED:
180
+ e = EM::Eventables [sig];
181
+ e->ConnectionCompleted();
182
+ break;
183
+
184
+ case EM_CONNECTION_ACCEPTED:
185
+ e = EM::Eventables [sig];
186
+ e->Accept (length); // actually a binding
187
+ break;
188
+
189
+ case EM_CONNECTION_UNBOUND:
190
+ e = EM::Eventables [sig];
191
+ e->Unbind();
192
+ EM::Eventables.erase (sig);
193
+ delete e;
194
+ break;
195
+
196
+ case EM_SSL_HANDSHAKE_COMPLETED:
197
+ e = EM::Eventables [sig];
198
+ e->SslHandshakeCompleted();
199
+ break;
200
+ }
201
+ }
202
+
data/ext/ed.cpp ADDED
@@ -0,0 +1,1868 @@
1
+ /*****************************************************************************
2
+
3
+ $Id$
4
+
5
+ File: ed.cpp
6
+ Date: 06Apr06
7
+
8
+ Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
9
+ Gmail: blackhedd
10
+
11
+ This program is free software; you can redistribute it and/or modify
12
+ it under the terms of either: 1) the GNU General Public License
13
+ as published by the Free Software Foundation; either version 2 of the
14
+ License, or (at your option) any later version; or 2) Ruby's License.
15
+
16
+ See the file COPYING for complete licensing information.
17
+
18
+ *****************************************************************************/
19
+
20
+ #include "project.h"
21
+
22
+
23
+
24
+ /********************
25
+ SetSocketNonblocking
26
+ ********************/
27
+
28
+ bool SetSocketNonblocking (SOCKET sd)
29
+ {
30
+ #ifdef OS_UNIX
31
+ int val = fcntl (sd, F_GETFL, 0);
32
+ return (fcntl (sd, F_SETFL, val | O_NONBLOCK) != SOCKET_ERROR) ? true : false;
33
+ #endif
34
+
35
+ #ifdef OS_WIN32
36
+ #ifdef BUILD_FOR_RUBY
37
+ // 14Jun09 Ruby provides its own wrappers for ioctlsocket. On 1.8 this is a simple wrapper,
38
+ // however, 1.9 keeps its own state about the socket.
39
+ // NOTE: F_GETFL is not supported
40
+ return (fcntl (sd, F_SETFL, O_NONBLOCK) == 0) ? true : false;
41
+ #else
42
+ unsigned long one = 1;
43
+ return (ioctlsocket (sd, FIONBIO, &one) == 0) ? true : false;
44
+ #endif
45
+ #endif
46
+ }
47
+
48
+
49
+ /****************************************
50
+ EventableDescriptor::EventableDescriptor
51
+ ****************************************/
52
+
53
+ EventableDescriptor::EventableDescriptor (int sd, EventMachine_t *em):
54
+ bCloseNow (false),
55
+ bCloseAfterWriting (false),
56
+ MySocket (sd),
57
+ EventCallback (NULL),
58
+ bCallbackUnbind (true),
59
+ UnbindReasonCode (0),
60
+ ProxyTarget(NULL),
61
+ MyEventMachine (em),
62
+ PendingConnectTimeout(20000000)
63
+ {
64
+ /* There are three ways to close a socket, all of which should
65
+ * automatically signal to the event machine that this object
66
+ * should be removed from the polling scheduler.
67
+ * First is a hard close, intended for bad errors or possible
68
+ * security violations. It immediately closes the connection
69
+ * and puts this object into an error state.
70
+ * Second is to set bCloseNow, which will cause the event machine
71
+ * to delete this object (and thus close the connection in our
72
+ * destructor) the next chance it gets. bCloseNow also inhibits
73
+ * the writing of new data on the socket (but not necessarily
74
+ * the reading of new data).
75
+ * The third way is to set bCloseAfterWriting, which inhibits
76
+ * the writing of new data and converts to bCloseNow as soon
77
+ * as everything in the outbound queue has been written.
78
+ * bCloseAfterWriting is really for use only by protocol handlers
79
+ * (for example, HTTP writes an HTML page and then closes the
80
+ * connection). All of the error states we generate internally
81
+ * cause an immediate close to be scheduled, which may have the
82
+ * effect of discarding outbound data.
83
+ */
84
+
85
+ if (sd == INVALID_SOCKET)
86
+ throw std::runtime_error ("bad eventable descriptor");
87
+ if (MyEventMachine == NULL)
88
+ throw std::runtime_error ("bad em in eventable descriptor");
89
+ CreatedAt = gCurrentLoopTime;
90
+
91
+ #ifdef HAVE_EPOLL
92
+ EpollEvent.events = 0;
93
+ EpollEvent.data.ptr = this;
94
+ #endif
95
+ }
96
+
97
+
98
+ /*****************************************
99
+ EventableDescriptor::~EventableDescriptor
100
+ *****************************************/
101
+
102
+ EventableDescriptor::~EventableDescriptor()
103
+ {
104
+ if (EventCallback && bCallbackUnbind)
105
+ (*EventCallback)(GetBinding(), EM_CONNECTION_UNBOUND, NULL, UnbindReasonCode);
106
+ StopProxy();
107
+ Close();
108
+ }
109
+
110
+
111
+ /*************************************
112
+ EventableDescriptor::SetEventCallback
113
+ *************************************/
114
+
115
+ void EventableDescriptor::SetEventCallback (void(*cb)(const unsigned long, int, const char*, const unsigned long))
116
+ {
117
+ EventCallback = cb;
118
+ }
119
+
120
+
121
+ /**************************
122
+ EventableDescriptor::Close
123
+ **************************/
124
+
125
+ void EventableDescriptor::Close()
126
+ {
127
+ // Close the socket right now. Intended for emergencies.
128
+ if (MySocket != INVALID_SOCKET) {
129
+ shutdown (MySocket, 1);
130
+ closesocket (MySocket);
131
+ MySocket = INVALID_SOCKET;
132
+ }
133
+ }
134
+
135
+
136
+ /*********************************
137
+ EventableDescriptor::ShouldDelete
138
+ *********************************/
139
+
140
+ bool EventableDescriptor::ShouldDelete()
141
+ {
142
+ /* For use by a socket manager, which needs to know if this object
143
+ * should be removed from scheduling events and deleted.
144
+ * Has an immediate close been scheduled, or are we already closed?
145
+ * If either of these are the case, return true. In theory, the manager will
146
+ * then delete us, which in turn will make sure the socket is closed.
147
+ * Note, if bCloseAfterWriting is true, we check a virtual method to see
148
+ * if there is outbound data to write, and only request a close if there is none.
149
+ */
150
+
151
+ return ((MySocket == INVALID_SOCKET) || bCloseNow || (bCloseAfterWriting && (GetOutboundDataSize() <= 0)));
152
+ }
153
+
154
+
155
+ /**********************************
156
+ EventableDescriptor::ScheduleClose
157
+ **********************************/
158
+
159
+ void EventableDescriptor::ScheduleClose (bool after_writing)
160
+ {
161
+ // KEEP THIS SYNCHRONIZED WITH ::IsCloseScheduled.
162
+ if (after_writing)
163
+ bCloseAfterWriting = true;
164
+ else
165
+ bCloseNow = true;
166
+ }
167
+
168
+
169
+ /*************************************
170
+ EventableDescriptor::IsCloseScheduled
171
+ *************************************/
172
+
173
+ bool EventableDescriptor::IsCloseScheduled()
174
+ {
175
+ // KEEP THIS SYNCHRONIZED WITH ::ScheduleClose.
176
+ return (bCloseNow || bCloseAfterWriting);
177
+ }
178
+
179
+
180
+ /*******************************
181
+ EventableDescriptor::StartProxy
182
+ *******************************/
183
+
184
+ void EventableDescriptor::StartProxy(unsigned long to)
185
+ {
186
+ EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (to));
187
+ if (ed) {
188
+ StopProxy();
189
+ ProxyTarget = to;
190
+ return;
191
+ }
192
+ throw std::runtime_error ("Tried to proxy to an invalid descriptor");
193
+ }
194
+
195
+
196
+ /******************************
197
+ EventableDescriptor::StopProxy
198
+ ******************************/
199
+
200
+ void EventableDescriptor::StopProxy()
201
+ {
202
+ if (ProxyTarget) {
203
+ ProxyTarget = NULL;
204
+ }
205
+ }
206
+
207
+
208
+ /********************************************
209
+ EventableDescriptor::_GenericInboundDispatch
210
+ ********************************************/
211
+
212
+ void EventableDescriptor::_GenericInboundDispatch(const char *buf, int size)
213
+ {
214
+ assert(EventCallback);
215
+
216
+ if (!ProxyTarget)
217
+ (*EventCallback)(GetBinding(), EM_CONNECTION_READ, buf, size);
218
+ else if (ConnectionDescriptor::SendDataToConnection(ProxyTarget, buf, size) == -1) {
219
+ (*EventCallback)(GetBinding(), EM_PROXY_TARGET_UNBOUND, NULL, 0);
220
+ StopProxy();
221
+ }
222
+ }
223
+
224
+
225
+ /*********************************************
226
+ EventableDescriptor::GetPendingConnectTimeout
227
+ *********************************************/
228
+
229
+ float EventableDescriptor::GetPendingConnectTimeout()
230
+ {
231
+ return ((float)PendingConnectTimeout / 1000000);
232
+ }
233
+
234
+
235
+ /*********************************************
236
+ EventableDescriptor::SetPendingConnectTimeout
237
+ *********************************************/
238
+
239
+ int EventableDescriptor::SetPendingConnectTimeout (float value)
240
+ {
241
+ if (value > 0) {
242
+ PendingConnectTimeout = (Int64)(value * 1000000);
243
+ return 1;
244
+ }
245
+ return 0;
246
+ }
247
+
248
+
249
+ /******************************************
250
+ ConnectionDescriptor::ConnectionDescriptor
251
+ ******************************************/
252
+
253
+ ConnectionDescriptor::ConnectionDescriptor (int sd, EventMachine_t *em):
254
+ EventableDescriptor (sd, em),
255
+ bPaused (false),
256
+ bConnectPending (false),
257
+ bNotifyReadable (false),
258
+ bNotifyWritable (false),
259
+ bWatchOnly (false),
260
+ bReadAttemptedAfterClose (false),
261
+ bWriteAttemptedAfterClose (false),
262
+ OutboundDataSize (0),
263
+ #ifdef WITH_SSL
264
+ SslBox (NULL),
265
+ bHandshakeSignaled (false),
266
+ bSslVerifyPeer (false),
267
+ bSslPeerAccepted(false),
268
+ #endif
269
+ #ifdef HAVE_KQUEUE
270
+ bGotExtraKqueueEvent(false),
271
+ #endif
272
+ bIsServer (false),
273
+ LastIo (gCurrentLoopTime),
274
+ InactivityTimeout (0)
275
+ {
276
+ // 22Jan09: Moved ArmKqueueWriter into SetConnectPending() to fix assertion failure in _WriteOutboundData()
277
+ // 5May09: Moved EPOLLOUT into SetConnectPending() so it doesn't happen for attached read pipes
278
+ }
279
+
280
+
281
+ /*******************************************
282
+ ConnectionDescriptor::~ConnectionDescriptor
283
+ *******************************************/
284
+
285
+ ConnectionDescriptor::~ConnectionDescriptor()
286
+ {
287
+ // Run down any stranded outbound data.
288
+ for (size_t i=0; i < OutboundPages.size(); i++)
289
+ OutboundPages[i].Free();
290
+
291
+ #ifdef WITH_SSL
292
+ if (SslBox)
293
+ delete SslBox;
294
+ #endif
295
+ }
296
+
297
+
298
+ /**************************************************
299
+ STATIC: ConnectionDescriptor::SendDataToConnection
300
+ **************************************************/
301
+
302
+ int ConnectionDescriptor::SendDataToConnection (const unsigned long binding, const char *data, int data_length)
303
+ {
304
+ // TODO: This is something of a hack, or at least it's a static method of the wrong class.
305
+ // TODO: Poor polymorphism here. We should be calling one virtual method
306
+ // instead of hacking out the runtime information of the target object.
307
+ ConnectionDescriptor *cd = dynamic_cast <ConnectionDescriptor*> (Bindable_t::GetObject (binding));
308
+ if (cd)
309
+ return cd->SendOutboundData (data, data_length);
310
+ DatagramDescriptor *ds = dynamic_cast <DatagramDescriptor*> (Bindable_t::GetObject (binding));
311
+ if (ds)
312
+ return ds->SendOutboundData (data, data_length);
313
+ #ifdef OS_UNIX
314
+ PipeDescriptor *ps = dynamic_cast <PipeDescriptor*> (Bindable_t::GetObject (binding));
315
+ if (ps)
316
+ return ps->SendOutboundData (data, data_length);
317
+ #endif
318
+ return -1;
319
+ }
320
+
321
+
322
+ /*********************************************
323
+ STATIC: ConnectionDescriptor::CloseConnection
324
+ *********************************************/
325
+
326
+ void ConnectionDescriptor::CloseConnection (const unsigned long binding, bool after_writing)
327
+ {
328
+ // TODO: This is something of a hack, or at least it's a static method of the wrong class.
329
+ EventableDescriptor *ed = dynamic_cast <EventableDescriptor*> (Bindable_t::GetObject (binding));
330
+ if (ed)
331
+ ed->ScheduleClose (after_writing);
332
+ }
333
+
334
+ /***********************************************
335
+ STATIC: ConnectionDescriptor::ReportErrorStatus
336
+ ***********************************************/
337
+
338
+ int ConnectionDescriptor::ReportErrorStatus (const unsigned long binding)
339
+ {
340
+ // TODO: This is something of a hack, or at least it's a static method of the wrong class.
341
+ // TODO: Poor polymorphism here. We should be calling one virtual method
342
+ // instead of hacking out the runtime information of the target object.
343
+ ConnectionDescriptor *cd = dynamic_cast <ConnectionDescriptor*> (Bindable_t::GetObject (binding));
344
+ if (cd)
345
+ return cd->_ReportErrorStatus();
346
+ return -1;
347
+ }
348
+
349
+ /***********************************
350
+ ConnectionDescriptor::_UpdateEvents
351
+ ************************************/
352
+
353
+ void ConnectionDescriptor::_UpdateEvents()
354
+ {
355
+ _UpdateEvents(true, true);
356
+ }
357
+
358
+ void ConnectionDescriptor::_UpdateEvents(bool read, bool write)
359
+ {
360
+ if (MySocket == INVALID_SOCKET)
361
+ return;
362
+
363
+ #ifdef HAVE_EPOLL
364
+ unsigned int old = EpollEvent.events;
365
+
366
+ if (read) {
367
+ if (SelectForRead())
368
+ EpollEvent.events |= EPOLLIN;
369
+ else
370
+ EpollEvent.events &= ~EPOLLIN;
371
+ }
372
+
373
+ if (write) {
374
+ if (SelectForWrite())
375
+ EpollEvent.events |= EPOLLOUT;
376
+ else
377
+ EpollEvent.events &= ~EPOLLOUT;
378
+ }
379
+
380
+ if (old != EpollEvent.events)
381
+ MyEventMachine->Modify (this);
382
+ #endif
383
+
384
+ #ifdef HAVE_KQUEUE
385
+ if (read && SelectForRead())
386
+ MyEventMachine->ArmKqueueReader (this);
387
+ if (write && SelectForWrite())
388
+ MyEventMachine->ArmKqueueWriter (this);
389
+ #endif
390
+ }
391
+
392
+ /***************************************
393
+ ConnectionDescriptor::SetConnectPending
394
+ ****************************************/
395
+
396
+ void ConnectionDescriptor::SetConnectPending(bool f)
397
+ {
398
+ bConnectPending = f;
399
+ _UpdateEvents();
400
+ }
401
+
402
+
403
+ /**********************************
404
+ ConnectionDescriptor::SetWatchOnly
405
+ ***********************************/
406
+
407
+ void ConnectionDescriptor::SetWatchOnly(bool watching)
408
+ {
409
+ bWatchOnly = watching;
410
+ _UpdateEvents();
411
+ }
412
+
413
+
414
+ /*********************************
415
+ ConnectionDescriptor::HandleError
416
+ *********************************/
417
+
418
+ void ConnectionDescriptor::HandleError()
419
+ {
420
+ if (bWatchOnly) {
421
+ // An EPOLLHUP | EPOLLIN condition will call Read() before HandleError(), in which case the
422
+ // socket is already detached and invalid, so we don't need to do anything.
423
+ if (MySocket == INVALID_SOCKET) return;
424
+
425
+ // HandleError() is called on WatchOnly descriptors by the epoll reactor
426
+ // when it gets a EPOLLERR | EPOLLHUP. Usually this would show up as a readable and
427
+ // writable event on other reactors, so we have to fire those events ourselves.
428
+ if (bNotifyReadable) Read();
429
+ if (bNotifyWritable) Write();
430
+ } else {
431
+ ScheduleClose (false);
432
+ }
433
+ }
434
+
435
+
436
+ /***********************************
437
+ ConnectionDescriptor::ScheduleClose
438
+ ***********************************/
439
+
440
+ void ConnectionDescriptor::ScheduleClose (bool after_writing)
441
+ {
442
+ if (bWatchOnly)
443
+ throw std::runtime_error ("cannot close 'watch only' connections");
444
+
445
+ EventableDescriptor::ScheduleClose(after_writing);
446
+ }
447
+
448
+
449
+ /***************************************
450
+ ConnectionDescriptor::SetNotifyReadable
451
+ ****************************************/
452
+
453
+ void ConnectionDescriptor::SetNotifyReadable(bool readable)
454
+ {
455
+ if (!bWatchOnly)
456
+ throw std::runtime_error ("notify_readable must be on 'watch only' connections");
457
+
458
+ bNotifyReadable = readable;
459
+ _UpdateEvents(true, false);
460
+ }
461
+
462
+
463
+ /***************************************
464
+ ConnectionDescriptor::SetNotifyWritable
465
+ ****************************************/
466
+
467
+ void ConnectionDescriptor::SetNotifyWritable(bool writable)
468
+ {
469
+ if (!bWatchOnly)
470
+ throw std::runtime_error ("notify_writable must be on 'watch only' connections");
471
+
472
+ bNotifyWritable = writable;
473
+ _UpdateEvents(false, true);
474
+ }
475
+
476
+
477
+ /**************************************
478
+ ConnectionDescriptor::SendOutboundData
479
+ **************************************/
480
+
481
+ int ConnectionDescriptor::SendOutboundData (const char *data, int length)
482
+ {
483
+ if (bWatchOnly)
484
+ throw std::runtime_error ("cannot send data on a 'watch only' connection");
485
+
486
+ #ifdef WITH_SSL
487
+ if (SslBox) {
488
+ if (length > 0) {
489
+ int w = SslBox->PutPlaintext (data, length);
490
+ if (w < 0)
491
+ ScheduleClose (false);
492
+ else
493
+ _DispatchCiphertext();
494
+ }
495
+ // TODO: What's the correct return value?
496
+ return 1; // That's a wild guess, almost certainly wrong.
497
+ }
498
+ else
499
+ #endif
500
+ return _SendRawOutboundData (data, length);
501
+ }
502
+
503
+
504
+
505
+ /******************************************
506
+ ConnectionDescriptor::_SendRawOutboundData
507
+ ******************************************/
508
+
509
+ int ConnectionDescriptor::_SendRawOutboundData (const char *data, int length)
510
+ {
511
+ /* This internal method is called to schedule bytes that
512
+ * will be sent out to the remote peer.
513
+ * It's not directly accessed by the caller, who hits ::SendOutboundData,
514
+ * which may or may not filter or encrypt the caller's data before
515
+ * sending it here.
516
+ */
517
+
518
+ // Highly naive and incomplete implementation.
519
+ // There's no throttle for runaways (which should abort only this connection
520
+ // and not the whole process), and no coalescing of small pages.
521
+ // (Well, not so bad, small pages are coalesced in ::Write)
522
+
523
+ if (IsCloseScheduled())
524
+ //if (bCloseNow || bCloseAfterWriting)
525
+ return 0;
526
+
527
+ if (!data && (length > 0))
528
+ throw std::runtime_error ("bad outbound data");
529
+ char *buffer = (char *) malloc (length + 1);
530
+ if (!buffer)
531
+ throw std::runtime_error ("no allocation for outbound data");
532
+
533
+ memcpy (buffer, data, length);
534
+ buffer [length] = 0;
535
+ OutboundPages.push_back (OutboundPage (buffer, length));
536
+ OutboundDataSize += length;
537
+
538
+ _UpdateEvents(false, true);
539
+
540
+ return length;
541
+ }
542
+
543
+
544
+
545
+ /***********************************
546
+ ConnectionDescriptor::SelectForRead
547
+ ***********************************/
548
+
549
+ bool ConnectionDescriptor::SelectForRead()
550
+ {
551
+ /* A connection descriptor is always scheduled for read,
552
+ * UNLESS it's in a pending-connect state.
553
+ * On Linux, unlike Unix, a nonblocking socket on which
554
+ * connect has been called, does NOT necessarily select
555
+ * both readable and writable in case of error.
556
+ * The socket will select writable when the disposition
557
+ * of the connect is known. On the other hand, a socket
558
+ * which successfully connects and selects writable may
559
+ * indeed have some data available on it, so it will
560
+ * select readable in that case, violating expectations!
561
+ * So we will not poll for readability until the socket
562
+ * is known to be in a connected state.
563
+ */
564
+
565
+ if (bPaused)
566
+ return false;
567
+ else if (bConnectPending)
568
+ return false;
569
+ else if (bWatchOnly)
570
+ return bNotifyReadable ? true : false;
571
+ else
572
+ return true;
573
+ }
574
+
575
+
576
+ /************************************
577
+ ConnectionDescriptor::SelectForWrite
578
+ ************************************/
579
+
580
+ bool ConnectionDescriptor::SelectForWrite()
581
+ {
582
+ /* Cf the notes under SelectForRead.
583
+ * In a pending-connect state, we ALWAYS select for writable.
584
+ * In a normal state, we only select for writable when we
585
+ * have outgoing data to send.
586
+ */
587
+
588
+ if (bPaused)
589
+ return false;
590
+ else if (bConnectPending)
591
+ return true;
592
+ else if (bWatchOnly)
593
+ return bNotifyWritable ? true : false;
594
+ else
595
+ return (GetOutboundDataSize() > 0);
596
+ }
597
+
598
+ /***************************
599
+ ConnectionDescriptor::Pause
600
+ ***************************/
601
+
602
+ bool ConnectionDescriptor::Pause()
603
+ {
604
+ if (bWatchOnly)
605
+ throw std::runtime_error ("cannot pause/resume 'watch only' connections, set notify readable/writable instead");
606
+
607
+ bool old = bPaused;
608
+ bPaused = true;
609
+ return old == false;
610
+ }
611
+
612
+ /****************************
613
+ ConnectionDescriptor::Resume
614
+ ****************************/
615
+
616
+ bool ConnectionDescriptor::Resume()
617
+ {
618
+ if (bWatchOnly)
619
+ throw std::runtime_error ("cannot pause/resume 'watch only' connections, set notify readable/writable instead");
620
+
621
+ bool old = bPaused;
622
+ bPaused = false;
623
+ return old == true;
624
+ }
625
+
626
+ /**************************
627
+ ConnectionDescriptor::Read
628
+ **************************/
629
+
630
+ void ConnectionDescriptor::Read()
631
+ {
632
+ /* Read and dispatch data on a socket that has selected readable.
633
+ * It's theoretically possible to get and dispatch incoming data on
634
+ * a socket that has already been scheduled for closing or close-after-writing.
635
+ * In those cases, we'll leave it up the to protocol handler to "do the
636
+ * right thing" (which probably means to ignore the incoming data).
637
+ *
638
+ * 22Aug06: Chris Ochs reports that on FreeBSD, it's possible to come
639
+ * here with the socket already closed, after the process receives
640
+ * a ctrl-C signal (not sure if that's TERM or INT on BSD). The application
641
+ * was one in which network connections were doing a lot of interleaved reads
642
+ * and writes.
643
+ * Since we always write before reading (in order to keep the outbound queues
644
+ * as light as possible), I think what happened is that an interrupt caused
645
+ * the socket to be closed in ConnectionDescriptor::Write. We'll then
646
+ * come here in the same pass through the main event loop, and won't get
647
+ * cleaned up until immediately after.
648
+ * We originally asserted that the socket was valid when we got here.
649
+ * To deal properly with the possibility that we are closed when we get here,
650
+ * I removed the assert. HOWEVER, the potential for an infinite loop scares me,
651
+ * so even though this is really clunky, I added a flag to assert that we never
652
+ * come here more than once after being closed. (FCianfrocca)
653
+ */
654
+
655
+ int sd = GetSocket();
656
+ //assert (sd != INVALID_SOCKET); (original, removed 22Aug06)
657
+ if (sd == INVALID_SOCKET) {
658
+ assert (!bReadAttemptedAfterClose);
659
+ bReadAttemptedAfterClose = true;
660
+ return;
661
+ }
662
+
663
+ if (bWatchOnly) {
664
+ if (bNotifyReadable && EventCallback)
665
+ (*EventCallback)(GetBinding(), EM_CONNECTION_NOTIFY_READABLE, NULL, 0);
666
+ return;
667
+ }
668
+
669
+ LastIo = gCurrentLoopTime;
670
+
671
+ int total_bytes_read = 0;
672
+ char readbuffer [16 * 1024 + 1];
673
+
674
+ for (int i=0; i < 1; i++) {
675
+ // Don't read just one buffer and then move on. This is faster
676
+ // if there is a lot of incoming.
677
+ // But don't read indefinitely. Give other sockets a chance to run.
678
+ // NOTICE, we're reading one less than the buffer size.
679
+ // That's so we can put a guard byte at the end of what we send
680
+ // to user code.
681
+
682
+
683
+ int r = read (sd, readbuffer, sizeof(readbuffer) - 1);
684
+ //cerr << "<R:" << r << ">";
685
+
686
+ if (r > 0) {
687
+ total_bytes_read += r;
688
+
689
+ // Add a null-terminator at the the end of the buffer
690
+ // that we will send to the callback.
691
+ // DO NOT EVER CHANGE THIS. We want to explicitly allow users
692
+ // to be able to depend on this behavior, so they will have
693
+ // the option to do some things faster. Additionally it's
694
+ // a security guard against buffer overflows.
695
+ readbuffer [r] = 0;
696
+ _DispatchInboundData (readbuffer, r);
697
+ }
698
+ else if (r == 0) {
699
+ break;
700
+ }
701
+ else {
702
+ // Basically a would-block, meaning we've read everything there is to read.
703
+ break;
704
+ }
705
+
706
+ }
707
+
708
+
709
+ if (total_bytes_read == 0) {
710
+ // If we read no data on a socket that selected readable,
711
+ // it generally means the other end closed the connection gracefully.
712
+ ScheduleClose (false);
713
+ //bCloseNow = true;
714
+ }
715
+
716
+ }
717
+
718
+
719
+
720
+ /******************************************
721
+ ConnectionDescriptor::_DispatchInboundData
722
+ ******************************************/
723
+
724
+ void ConnectionDescriptor::_DispatchInboundData (const char *buffer, int size)
725
+ {
726
+ #ifdef WITH_SSL
727
+ if (SslBox) {
728
+ SslBox->PutCiphertext (buffer, size);
729
+
730
+ int s;
731
+ char B [2048];
732
+ while ((s = SslBox->GetPlaintext (B, sizeof(B) - 1)) > 0) {
733
+ _CheckHandshakeStatus();
734
+ B [s] = 0;
735
+ _GenericInboundDispatch(B, s);
736
+ }
737
+
738
+ // If our SSL handshake had a problem, shut down the connection.
739
+ if (s == -2) {
740
+ ScheduleClose(false);
741
+ return;
742
+ }
743
+
744
+ _CheckHandshakeStatus();
745
+ _DispatchCiphertext();
746
+ }
747
+ else {
748
+ _GenericInboundDispatch(buffer, size);
749
+ }
750
+ #endif
751
+
752
+ #ifdef WITHOUT_SSL
753
+ _GenericInboundDispatch(buffer, size);
754
+ #endif
755
+ }
756
+
757
+
758
+
759
+ /*******************************************
760
+ ConnectionDescriptor::_CheckHandshakeStatus
761
+ *******************************************/
762
+
763
+ void ConnectionDescriptor::_CheckHandshakeStatus()
764
+ {
765
+ #ifdef WITH_SSL
766
+ if (SslBox && (!bHandshakeSignaled) && SslBox->IsHandshakeCompleted()) {
767
+ bHandshakeSignaled = true;
768
+ if (EventCallback)
769
+ (*EventCallback)(GetBinding(), EM_SSL_HANDSHAKE_COMPLETED, NULL, 0);
770
+ }
771
+ #endif
772
+ }
773
+
774
+
775
+
776
+ /***************************
777
+ ConnectionDescriptor::Write
778
+ ***************************/
779
+
780
+ void ConnectionDescriptor::Write()
781
+ {
782
+ /* A socket which is in a pending-connect state will select
783
+ * writable when the disposition of the connect is known.
784
+ * At that point, check to be sure there are no errors,
785
+ * and if none, then promote the socket out of the pending
786
+ * state.
787
+ * TODO: I haven't figured out how Windows signals errors on
788
+ * unconnected sockets. Maybe it does the untraditional but
789
+ * logical thing and makes the socket selectable for error.
790
+ * If so, it's unsupported here for the time being, and connect
791
+ * errors will have to be caught by the timeout mechanism.
792
+ */
793
+
794
+ if (bConnectPending) {
795
+ int error;
796
+ socklen_t len;
797
+ len = sizeof(error);
798
+ #ifdef OS_UNIX
799
+ int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, &error, &len);
800
+ #endif
801
+ #ifdef OS_WIN32
802
+ int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, (char*)&error, &len);
803
+ #endif
804
+ if ((o == 0) && (error == 0)) {
805
+ if (EventCallback)
806
+ (*EventCallback)(GetBinding(), EM_CONNECTION_COMPLETED, "", 0);
807
+
808
+ // 5May09: Moved epoll/kqueue read/write arming into SetConnectPending, so it can be called
809
+ // from EventMachine_t::AttachFD as well.
810
+ SetConnectPending (false);
811
+ }
812
+ else
813
+ ScheduleClose (false);
814
+ //bCloseNow = true;
815
+ }
816
+ else {
817
+
818
+ if (bNotifyWritable) {
819
+ if (EventCallback)
820
+ (*EventCallback)(GetBinding(), EM_CONNECTION_NOTIFY_WRITABLE, NULL, 0);
821
+
822
+ _UpdateEvents(false, true);
823
+ return;
824
+ }
825
+
826
+ assert(!bWatchOnly);
827
+
828
+ /* 5May09: Kqueue bugs on OSX cause one extra writable event to fire even though we're using
829
+ EV_ONESHOT. We ignore this extra event once, but only the first time. If it happens again,
830
+ we should fall through to the assert(nbytes>0) failure to catch any EM bugs which might cause
831
+ ::Write to be called in a busy-loop.
832
+ */
833
+ #ifdef HAVE_KQUEUE
834
+ if (MyEventMachine->UsingKqueue()) {
835
+ if (OutboundDataSize == 0 && !bGotExtraKqueueEvent) {
836
+ bGotExtraKqueueEvent = true;
837
+ return;
838
+ } else if (OutboundDataSize > 0) {
839
+ bGotExtraKqueueEvent = false;
840
+ }
841
+ }
842
+ #endif
843
+
844
+ _WriteOutboundData();
845
+ }
846
+ }
847
+
848
+
849
+ /****************************************
850
+ ConnectionDescriptor::_WriteOutboundData
851
+ ****************************************/
852
+
853
+ void ConnectionDescriptor::_WriteOutboundData()
854
+ {
855
+ /* This is a helper function called by ::Write.
856
+ * It's possible for a socket to select writable and then no longer
857
+ * be writable by the time we get around to writing. The kernel might
858
+ * have used up its available output buffers between the select call
859
+ * and when we get here. So this condition is not an error.
860
+ *
861
+ * 20Jul07, added the same kind of protection against an invalid socket
862
+ * that is at the top of ::Read. Not entirely how this could happen in
863
+ * real life (connection-reset from the remote peer, perhaps?), but I'm
864
+ * doing it to address some reports of crashing under heavy loads.
865
+ */
866
+
867
+ int sd = GetSocket();
868
+ //assert (sd != INVALID_SOCKET);
869
+ if (sd == INVALID_SOCKET) {
870
+ assert (!bWriteAttemptedAfterClose);
871
+ bWriteAttemptedAfterClose = true;
872
+ return;
873
+ }
874
+
875
+ LastIo = gCurrentLoopTime;
876
+ size_t nbytes = 0;
877
+
878
+ #ifdef HAVE_WRITEV
879
+ int iovcnt = OutboundPages.size();
880
+ // Max of 16 outbound pages at a time
881
+ if (iovcnt > 16) iovcnt = 16;
882
+
883
+ struct iovec iov[ iovcnt ];
884
+
885
+ for(int i = 0; i < iovcnt; i++){
886
+ OutboundPage *op = &(OutboundPages[i]);
887
+ iov[i].iov_base = (void *)(op->Buffer + op->Offset);
888
+ iov[i].iov_len = op->Length - op->Offset;
889
+
890
+ nbytes += iov[i].iov_len;
891
+ }
892
+ #else
893
+ char output_buffer [16 * 1024];
894
+
895
+ while ((OutboundPages.size() > 0) && (nbytes < sizeof(output_buffer))) {
896
+ OutboundPage *op = &(OutboundPages[0]);
897
+ if ((nbytes + op->Length - op->Offset) < sizeof (output_buffer)) {
898
+ memcpy (output_buffer + nbytes, op->Buffer + op->Offset, op->Length - op->Offset);
899
+ nbytes += (op->Length - op->Offset);
900
+ op->Free();
901
+ OutboundPages.pop_front();
902
+ }
903
+ else {
904
+ int len = sizeof(output_buffer) - nbytes;
905
+ memcpy (output_buffer + nbytes, op->Buffer + op->Offset, len);
906
+ op->Offset += len;
907
+ nbytes += len;
908
+ }
909
+ }
910
+ #endif
911
+
912
+ // We should never have gotten here if there were no data to write,
913
+ // so assert that as a sanity check.
914
+ // Don't bother to make sure nbytes is less than output_buffer because
915
+ // if it were we probably would have crashed already.
916
+ assert (nbytes > 0);
917
+
918
+ assert (GetSocket() != INVALID_SOCKET);
919
+ #ifdef HAVE_WRITEV
920
+ int bytes_written = writev (GetSocket(), iov, iovcnt);
921
+ #else
922
+ int bytes_written = write (GetSocket(), output_buffer, nbytes);
923
+ #endif
924
+
925
+ bool err = false;
926
+ if (bytes_written < 0) {
927
+ err = true;
928
+ bytes_written = 0;
929
+ }
930
+
931
+ assert (bytes_written >= 0);
932
+ OutboundDataSize -= bytes_written;
933
+
934
+ #ifdef HAVE_WRITEV
935
+ if (!err) {
936
+ unsigned int sent = bytes_written;
937
+ deque<OutboundPage>::iterator op = OutboundPages.begin();
938
+
939
+ for (int i = 0; i < iovcnt; i++) {
940
+ if (iov[i].iov_len <= sent) {
941
+ // Sent this page in full, free it.
942
+ op->Free();
943
+ OutboundPages.pop_front();
944
+
945
+ sent -= iov[i].iov_len;
946
+ } else {
947
+ // Sent part (or none) of this page, increment offset to send the remainder
948
+ op->Offset += sent;
949
+ break;
950
+ }
951
+
952
+ // Shouldn't be possible run out of pages before the loop ends
953
+ assert(op != OutboundPages.end());
954
+ *op++;
955
+ }
956
+ }
957
+ #else
958
+ if ((size_t)bytes_written < nbytes) {
959
+ int len = nbytes - bytes_written;
960
+ char *buffer = (char*) malloc (len + 1);
961
+ if (!buffer)
962
+ throw std::runtime_error ("bad alloc throwing back data");
963
+ memcpy (buffer, output_buffer + bytes_written, len);
964
+ buffer [len] = 0;
965
+ OutboundPages.push_front (OutboundPage (buffer, len));
966
+ }
967
+ #endif
968
+
969
+ _UpdateEvents(false, true);
970
+
971
+ if (err) {
972
+ #ifdef OS_UNIX
973
+ if ((errno != EINPROGRESS) && (errno != EWOULDBLOCK) && (errno != EINTR))
974
+ #endif
975
+ #ifdef OS_WIN32
976
+ if ((errno != WSAEINPROGRESS) && (errno != WSAEWOULDBLOCK))
977
+ #endif
978
+ Close();
979
+ }
980
+ }
981
+
982
+
983
+ /****************************************
984
+ ConnectionDescriptor::_ReportErrorStatus
985
+ ****************************************/
986
+
987
+ int ConnectionDescriptor::_ReportErrorStatus()
988
+ {
989
+ int error;
990
+ socklen_t len;
991
+ len = sizeof(error);
992
+ #ifdef OS_UNIX
993
+ int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, &error, &len);
994
+ #endif
995
+ #ifdef OS_WIN32
996
+ int o = getsockopt (GetSocket(), SOL_SOCKET, SO_ERROR, (char*)&error, &len);
997
+ #endif
998
+ if ((o == 0) && (error == 0))
999
+ return 0;
1000
+ else
1001
+ return 1;
1002
+ }
1003
+
1004
+
1005
+ /******************************
1006
+ ConnectionDescriptor::StartTls
1007
+ ******************************/
1008
+
1009
+ void ConnectionDescriptor::StartTls()
1010
+ {
1011
+ #ifdef WITH_SSL
1012
+ if (SslBox)
1013
+ throw std::runtime_error ("SSL/TLS already running on connection");
1014
+
1015
+ SslBox = new SslBox_t (bIsServer, PrivateKeyFilename, CertChainFilename, bSslVerifyPeer, GetBinding());
1016
+ _DispatchCiphertext();
1017
+ #endif
1018
+
1019
+ #ifdef WITHOUT_SSL
1020
+ throw std::runtime_error ("Encryption not available on this event-machine");
1021
+ #endif
1022
+ }
1023
+
1024
+
1025
+ /*********************************
1026
+ ConnectionDescriptor::SetTlsParms
1027
+ *********************************/
1028
+
1029
+ void ConnectionDescriptor::SetTlsParms (const char *privkey_filename, const char *certchain_filename, bool verify_peer)
1030
+ {
1031
+ #ifdef WITH_SSL
1032
+ if (SslBox)
1033
+ throw std::runtime_error ("call SetTlsParms before calling StartTls");
1034
+ if (privkey_filename && *privkey_filename)
1035
+ PrivateKeyFilename = privkey_filename;
1036
+ if (certchain_filename && *certchain_filename)
1037
+ CertChainFilename = certchain_filename;
1038
+ bSslVerifyPeer = verify_peer;
1039
+ #endif
1040
+
1041
+ #ifdef WITHOUT_SSL
1042
+ throw std::runtime_error ("Encryption not available on this event-machine");
1043
+ #endif
1044
+ }
1045
+
1046
+
1047
+ /*********************************
1048
+ ConnectionDescriptor::GetPeerCert
1049
+ *********************************/
1050
+
1051
+ #ifdef WITH_SSL
1052
+ X509 *ConnectionDescriptor::GetPeerCert()
1053
+ {
1054
+ if (!SslBox)
1055
+ throw std::runtime_error ("SSL/TLS not running on this connection");
1056
+ return SslBox->GetPeerCert();
1057
+ }
1058
+ #endif
1059
+
1060
+
1061
+ /***********************************
1062
+ ConnectionDescriptor::VerifySslPeer
1063
+ ***********************************/
1064
+
1065
+ #ifdef WITH_SSL
1066
+ bool ConnectionDescriptor::VerifySslPeer(const char *cert)
1067
+ {
1068
+ bSslPeerAccepted = false;
1069
+
1070
+ if (EventCallback)
1071
+ (*EventCallback)(GetBinding(), EM_SSL_VERIFY, cert, strlen(cert));
1072
+
1073
+ return bSslPeerAccepted;
1074
+ }
1075
+ #endif
1076
+
1077
+
1078
+ /***********************************
1079
+ ConnectionDescriptor::AcceptSslPeer
1080
+ ***********************************/
1081
+
1082
+ #ifdef WITH_SSL
1083
+ void ConnectionDescriptor::AcceptSslPeer()
1084
+ {
1085
+ bSslPeerAccepted = true;
1086
+ }
1087
+ #endif
1088
+
1089
+
1090
+ /*****************************************
1091
+ ConnectionDescriptor::_DispatchCiphertext
1092
+ *****************************************/
1093
+
1094
+ #ifdef WITH_SSL
1095
+ void ConnectionDescriptor::_DispatchCiphertext()
1096
+ {
1097
+ assert (SslBox);
1098
+
1099
+
1100
+ char BigBuf [2048];
1101
+ bool did_work;
1102
+
1103
+ do {
1104
+ did_work = false;
1105
+
1106
+ // try to drain ciphertext
1107
+ while (SslBox->CanGetCiphertext()) {
1108
+ int r = SslBox->GetCiphertext (BigBuf, sizeof(BigBuf));
1109
+ assert (r > 0);
1110
+ _SendRawOutboundData (BigBuf, r);
1111
+ did_work = true;
1112
+ }
1113
+
1114
+ // Pump the SslBox, in case it has queued outgoing plaintext
1115
+ // This will return >0 if data was written,
1116
+ // 0 if no data was written, and <0 if there was a fatal error.
1117
+ bool pump;
1118
+ do {
1119
+ pump = false;
1120
+ int w = SslBox->PutPlaintext (NULL, 0);
1121
+ if (w > 0) {
1122
+ did_work = true;
1123
+ pump = true;
1124
+ }
1125
+ else if (w < 0)
1126
+ ScheduleClose (false);
1127
+ } while (pump);
1128
+
1129
+ // try to put plaintext. INCOMPLETE, doesn't belong here?
1130
+ // In SendOutboundData, we're spooling plaintext directly
1131
+ // into SslBox. That may be wrong, we may need to buffer it
1132
+ // up here!
1133
+ /*
1134
+ const char *ptr;
1135
+ int ptr_length;
1136
+ while (OutboundPlaintext.GetPage (&ptr, &ptr_length)) {
1137
+ assert (ptr && (ptr_length > 0));
1138
+ int w = SslMachine.PutPlaintext (ptr, ptr_length);
1139
+ if (w > 0) {
1140
+ OutboundPlaintext.DiscardBytes (w);
1141
+ did_work = true;
1142
+ }
1143
+ else
1144
+ break;
1145
+ }
1146
+ */
1147
+
1148
+ } while (did_work);
1149
+
1150
+ }
1151
+ #endif
1152
+
1153
+
1154
+
1155
+ /*******************************
1156
+ ConnectionDescriptor::Heartbeat
1157
+ *******************************/
1158
+
1159
+ void ConnectionDescriptor::Heartbeat()
1160
+ {
1161
+ /* Only allow a certain amount of time to go by while waiting
1162
+ * for a pending connect. If it expires, then kill the socket.
1163
+ * For a connected socket, close it if its inactivity timer
1164
+ * has expired.
1165
+ */
1166
+
1167
+ if (bConnectPending) {
1168
+ if ((gCurrentLoopTime - CreatedAt) >= PendingConnectTimeout)
1169
+ ScheduleClose (false);
1170
+ //bCloseNow = true;
1171
+ }
1172
+ else {
1173
+ if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
1174
+ ScheduleClose (false);
1175
+ //bCloseNow = true;
1176
+ }
1177
+ }
1178
+
1179
+
1180
+ /****************************************
1181
+ LoopbreakDescriptor::LoopbreakDescriptor
1182
+ ****************************************/
1183
+
1184
+ LoopbreakDescriptor::LoopbreakDescriptor (int sd, EventMachine_t *parent_em):
1185
+ EventableDescriptor (sd, parent_em)
1186
+ {
1187
+ /* This is really bad and ugly. Change someday if possible.
1188
+ * We have to know about an event-machine (probably the one that owns us),
1189
+ * so we can pass newly-created connections to it.
1190
+ */
1191
+
1192
+ bCallbackUnbind = false;
1193
+
1194
+ #ifdef HAVE_EPOLL
1195
+ EpollEvent.events = EPOLLIN;
1196
+ #endif
1197
+ #ifdef HAVE_KQUEUE
1198
+ MyEventMachine->ArmKqueueReader (this);
1199
+ #endif
1200
+ }
1201
+
1202
+
1203
+
1204
+
1205
+ /*************************
1206
+ LoopbreakDescriptor::Read
1207
+ *************************/
1208
+
1209
+ void LoopbreakDescriptor::Read()
1210
+ {
1211
+ // TODO, refactor, this code is probably in the wrong place.
1212
+ assert (MyEventMachine);
1213
+ MyEventMachine->_ReadLoopBreaker();
1214
+ }
1215
+
1216
+
1217
+ /**************************
1218
+ LoopbreakDescriptor::Write
1219
+ **************************/
1220
+
1221
+ void LoopbreakDescriptor::Write()
1222
+ {
1223
+ // Why are we here?
1224
+ throw std::runtime_error ("bad code path in loopbreak");
1225
+ }
1226
+
1227
+ /**************************************
1228
+ AcceptorDescriptor::AcceptorDescriptor
1229
+ **************************************/
1230
+
1231
+ AcceptorDescriptor::AcceptorDescriptor (int sd, EventMachine_t *parent_em):
1232
+ EventableDescriptor (sd, parent_em)
1233
+ {
1234
+ #ifdef HAVE_EPOLL
1235
+ EpollEvent.events = EPOLLIN;
1236
+ #endif
1237
+ #ifdef HAVE_KQUEUE
1238
+ MyEventMachine->ArmKqueueReader (this);
1239
+ #endif
1240
+ }
1241
+
1242
+
1243
+ /***************************************
1244
+ AcceptorDescriptor::~AcceptorDescriptor
1245
+ ***************************************/
1246
+
1247
+ AcceptorDescriptor::~AcceptorDescriptor()
1248
+ {
1249
+ }
1250
+
1251
+ /****************************************
1252
+ STATIC: AcceptorDescriptor::StopAcceptor
1253
+ ****************************************/
1254
+
1255
+ void AcceptorDescriptor::StopAcceptor (const unsigned long binding)
1256
+ {
1257
+ // TODO: This is something of a hack, or at least it's a static method of the wrong class.
1258
+ AcceptorDescriptor *ad = dynamic_cast <AcceptorDescriptor*> (Bindable_t::GetObject (binding));
1259
+ if (ad)
1260
+ ad->ScheduleClose (false);
1261
+ else
1262
+ throw std::runtime_error ("failed to close nonexistent acceptor");
1263
+ }
1264
+
1265
+
1266
+ /************************
1267
+ AcceptorDescriptor::Read
1268
+ ************************/
1269
+
1270
+ void AcceptorDescriptor::Read()
1271
+ {
1272
+ /* Accept up to a certain number of sockets on the listening connection.
1273
+ * Don't try to accept all that are present, because this would allow a DoS attack
1274
+ * in which no data were ever read or written. We should accept more than one,
1275
+ * if available, to keep the partially accepted sockets from backing up in the kernel.
1276
+ */
1277
+
1278
+ /* Make sure we use non-blocking i/o on the acceptor socket, since we're selecting it
1279
+ * for readability. According to Stevens UNP, it's possible for an acceptor to select readable
1280
+ * and then block when we call accept. For example, the other end resets the connection after
1281
+ * the socket selects readable and before we call accept. The kernel will remove the dead
1282
+ * socket from the accept queue. If the accept queue is now empty, accept will block.
1283
+ */
1284
+
1285
+
1286
+ struct sockaddr_in pin;
1287
+ socklen_t addrlen = sizeof (pin);
1288
+
1289
+ for (int i=0; i < 10; i++) {
1290
+ int sd = accept (GetSocket(), (struct sockaddr*)&pin, &addrlen);
1291
+ if (sd == INVALID_SOCKET) {
1292
+ // This breaks the loop when we've accepted everything on the kernel queue,
1293
+ // up to 10 new connections. But what if the *first* accept fails?
1294
+ // Does that mean anything serious is happening, beyond the situation
1295
+ // described in the note above?
1296
+ break;
1297
+ }
1298
+
1299
+ // Set the newly-accepted socket non-blocking.
1300
+ // On Windows, this may fail because, weirdly, Windows inherits the non-blocking
1301
+ // attribute that we applied to the acceptor socket into the accepted one.
1302
+ if (!SetSocketNonblocking (sd)) {
1303
+ //int val = fcntl (sd, F_GETFL, 0);
1304
+ //if (fcntl (sd, F_SETFL, val | O_NONBLOCK) == -1) {
1305
+ shutdown (sd, 1);
1306
+ closesocket (sd);
1307
+ continue;
1308
+ }
1309
+
1310
+
1311
+ // Disable slow-start (Nagle algorithm). Eventually make this configurable.
1312
+ int one = 1;
1313
+ setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (char*) &one, sizeof(one));
1314
+
1315
+
1316
+ ConnectionDescriptor *cd = new ConnectionDescriptor (sd, MyEventMachine);
1317
+ if (!cd)
1318
+ throw std::runtime_error ("no newly accepted connection");
1319
+ cd->SetServerMode();
1320
+ if (EventCallback) {
1321
+ (*EventCallback) (GetBinding(), EM_CONNECTION_ACCEPTED, NULL, cd->GetBinding());
1322
+ }
1323
+ #ifdef HAVE_EPOLL
1324
+ cd->GetEpollEvent()->events = EPOLLIN | (cd->SelectForWrite() ? EPOLLOUT : 0);
1325
+ #endif
1326
+ assert (MyEventMachine);
1327
+ MyEventMachine->Add (cd);
1328
+ #ifdef HAVE_KQUEUE
1329
+ if (cd->SelectForWrite())
1330
+ MyEventMachine->ArmKqueueWriter (cd);
1331
+ MyEventMachine->ArmKqueueReader (cd);
1332
+ #endif
1333
+ }
1334
+
1335
+ }
1336
+
1337
+
1338
+ /*************************
1339
+ AcceptorDescriptor::Write
1340
+ *************************/
1341
+
1342
+ void AcceptorDescriptor::Write()
1343
+ {
1344
+ // Why are we here?
1345
+ throw std::runtime_error ("bad code path in acceptor");
1346
+ }
1347
+
1348
+
1349
+ /*****************************
1350
+ AcceptorDescriptor::Heartbeat
1351
+ *****************************/
1352
+
1353
+ void AcceptorDescriptor::Heartbeat()
1354
+ {
1355
+ // No-op
1356
+ }
1357
+
1358
+
1359
+ /*******************************
1360
+ AcceptorDescriptor::GetSockname
1361
+ *******************************/
1362
+
1363
+ bool AcceptorDescriptor::GetSockname (struct sockaddr *s)
1364
+ {
1365
+ bool ok = false;
1366
+ if (s) {
1367
+ socklen_t len = sizeof(*s);
1368
+ int gp = getsockname (GetSocket(), s, &len);
1369
+ if (gp == 0)
1370
+ ok = true;
1371
+ }
1372
+ return ok;
1373
+ }
1374
+
1375
+
1376
+
1377
+ /**************************************
1378
+ DatagramDescriptor::DatagramDescriptor
1379
+ **************************************/
1380
+
1381
+ DatagramDescriptor::DatagramDescriptor (int sd, EventMachine_t *parent_em):
1382
+ EventableDescriptor (sd, parent_em),
1383
+ OutboundDataSize (0),
1384
+ LastIo (gCurrentLoopTime),
1385
+ InactivityTimeout (0)
1386
+ {
1387
+ memset (&ReturnAddress, 0, sizeof(ReturnAddress));
1388
+
1389
+ /* Provisionally added 19Oct07. All datagram sockets support broadcasting.
1390
+ * Until now, sending to a broadcast address would give EACCES (permission denied)
1391
+ * on systems like Linux and BSD that require the SO_BROADCAST socket-option in order
1392
+ * to accept a packet to a broadcast address. Solaris doesn't require it. I think
1393
+ * Windows DOES require it but I'm not sure.
1394
+ *
1395
+ * Ruby does NOT do what we're doing here. In Ruby, you have to explicitly set SO_BROADCAST
1396
+ * on a UDP socket in order to enable broadcasting. The reason for requiring the option
1397
+ * in the first place is so that applications don't send broadcast datagrams by mistake.
1398
+ * I imagine that could happen if a user of an application typed in an address that happened
1399
+ * to be a broadcast address on that particular subnet.
1400
+ *
1401
+ * This is provisional because someone may eventually come up with a good reason not to
1402
+ * do it for all UDP sockets. If that happens, then we'll need to add a usercode-level API
1403
+ * to set the socket option, just like Ruby does. AND WE'LL ALSO BREAK CODE THAT DOESN'T
1404
+ * EXPLICITLY SET THE OPTION.
1405
+ */
1406
+
1407
+ int oval = 1;
1408
+ setsockopt (GetSocket(), SOL_SOCKET, SO_BROADCAST, (char*)&oval, sizeof(oval));
1409
+
1410
+ #ifdef HAVE_EPOLL
1411
+ EpollEvent.events = EPOLLIN;
1412
+ #endif
1413
+ #ifdef HAVE_KQUEUE
1414
+ MyEventMachine->ArmKqueueReader (this);
1415
+ #endif
1416
+ }
1417
+
1418
+
1419
+ /***************************************
1420
+ DatagramDescriptor::~DatagramDescriptor
1421
+ ***************************************/
1422
+
1423
+ DatagramDescriptor::~DatagramDescriptor()
1424
+ {
1425
+ // Run down any stranded outbound data.
1426
+ for (size_t i=0; i < OutboundPages.size(); i++)
1427
+ OutboundPages[i].Free();
1428
+ }
1429
+
1430
+
1431
+ /*****************************
1432
+ DatagramDescriptor::Heartbeat
1433
+ *****************************/
1434
+
1435
+ void DatagramDescriptor::Heartbeat()
1436
+ {
1437
+ // Close it if its inactivity timer has expired.
1438
+
1439
+ if (InactivityTimeout && ((gCurrentLoopTime - LastIo) >= InactivityTimeout))
1440
+ ScheduleClose (false);
1441
+ //bCloseNow = true;
1442
+ }
1443
+
1444
+
1445
+ /************************
1446
+ DatagramDescriptor::Read
1447
+ ************************/
1448
+
1449
+ void DatagramDescriptor::Read()
1450
+ {
1451
+ int sd = GetSocket();
1452
+ assert (sd != INVALID_SOCKET);
1453
+ LastIo = gCurrentLoopTime;
1454
+
1455
+ // This is an extremely large read buffer.
1456
+ // In many cases you wouldn't expect to get any more than 4K.
1457
+ char readbuffer [16 * 1024];
1458
+
1459
+ for (int i=0; i < 1; i++) {
1460
+ // Don't read just one buffer and then move on. This is faster
1461
+ // if there is a lot of incoming.
1462
+ // But don't read indefinitely. Give other sockets a chance to run.
1463
+ // NOTICE, we're reading one less than the buffer size.
1464
+ // That's so we can put a guard byte at the end of what we send
1465
+ // to user code.
1466
+
1467
+ struct sockaddr_in sin;
1468
+ socklen_t slen = sizeof (sin);
1469
+ memset (&sin, 0, slen);
1470
+
1471
+ int r = recvfrom (sd, readbuffer, sizeof(readbuffer) - 1, 0, (struct sockaddr*)&sin, &slen);
1472
+ //cerr << "<R:" << r << ">";
1473
+
1474
+ // In UDP, a zero-length packet is perfectly legal.
1475
+ if (r >= 0) {
1476
+
1477
+ // Add a null-terminator at the the end of the buffer
1478
+ // that we will send to the callback.
1479
+ // DO NOT EVER CHANGE THIS. We want to explicitly allow users
1480
+ // to be able to depend on this behavior, so they will have
1481
+ // the option to do some things faster. Additionally it's
1482
+ // a security guard against buffer overflows.
1483
+ readbuffer [r] = 0;
1484
+
1485
+
1486
+ // Set up a "temporary" return address so that callers can "reply" to us
1487
+ // from within the callback we are about to invoke. That means that ordinary
1488
+ // calls to "send_data_to_connection" (which is of course misnamed in this
1489
+ // case) will result in packets being sent back to the same place that sent
1490
+ // us this one.
1491
+ // There is a different call (evma_send_datagram) for cases where the caller
1492
+ // actually wants to send a packet somewhere else.
1493
+
1494
+ memset (&ReturnAddress, 0, sizeof(ReturnAddress));
1495
+ memcpy (&ReturnAddress, &sin, slen);
1496
+
1497
+ _GenericInboundDispatch(readbuffer, r);
1498
+
1499
+ }
1500
+ else {
1501
+ // Basically a would-block, meaning we've read everything there is to read.
1502
+ break;
1503
+ }
1504
+
1505
+ }
1506
+
1507
+
1508
+ }
1509
+
1510
+
1511
+ /*************************
1512
+ DatagramDescriptor::Write
1513
+ *************************/
1514
+
1515
+ void DatagramDescriptor::Write()
1516
+ {
1517
+ /* It's possible for a socket to select writable and then no longer
1518
+ * be writable by the time we get around to writing. The kernel might
1519
+ * have used up its available output buffers between the select call
1520
+ * and when we get here. So this condition is not an error.
1521
+ * This code is very reminiscent of ConnectionDescriptor::_WriteOutboundData,
1522
+ * but differs in the that the outbound data pages (received from the
1523
+ * user) are _message-structured._ That is, we send each of them out
1524
+ * one message at a time.
1525
+ * TODO, we are currently suppressing the EMSGSIZE error!!!
1526
+ */
1527
+
1528
+ int sd = GetSocket();
1529
+ assert (sd != INVALID_SOCKET);
1530
+ LastIo = gCurrentLoopTime;
1531
+
1532
+ assert (OutboundPages.size() > 0);
1533
+
1534
+ // Send out up to 10 packets, then cycle the machine.
1535
+ for (int i = 0; i < 10; i++) {
1536
+ if (OutboundPages.size() <= 0)
1537
+ break;
1538
+ OutboundPage *op = &(OutboundPages[0]);
1539
+
1540
+ // The nasty cast to (char*) is needed because Windows is brain-dead.
1541
+ int s = sendto (sd, (char*)op->Buffer, op->Length, 0, (struct sockaddr*)&(op->From), sizeof(op->From));
1542
+ int e = errno;
1543
+
1544
+ OutboundDataSize -= op->Length;
1545
+ op->Free();
1546
+ OutboundPages.pop_front();
1547
+
1548
+ if (s == SOCKET_ERROR) {
1549
+ #ifdef OS_UNIX
1550
+ if ((e != EINPROGRESS) && (e != EWOULDBLOCK) && (e != EINTR)) {
1551
+ #endif
1552
+ #ifdef OS_WIN32
1553
+ if ((e != WSAEINPROGRESS) && (e != WSAEWOULDBLOCK)) {
1554
+ #endif
1555
+ Close();
1556
+ break;
1557
+ }
1558
+ }
1559
+ }
1560
+
1561
+ #ifdef HAVE_EPOLL
1562
+ EpollEvent.events = (EPOLLIN | (SelectForWrite() ? EPOLLOUT : 0));
1563
+ assert (MyEventMachine);
1564
+ MyEventMachine->Modify (this);
1565
+ #endif
1566
+ #ifdef HAVE_KQUEUE
1567
+ if (SelectForWrite())
1568
+ MyEventMachine->ArmKqueueWriter (this);
1569
+ #endif
1570
+ }
1571
+
1572
+
1573
+ /**********************************
1574
+ DatagramDescriptor::SelectForWrite
1575
+ **********************************/
1576
+
1577
+ bool DatagramDescriptor::SelectForWrite()
1578
+ {
1579
+ /* Changed 15Nov07, per bug report by Mark Zvillius.
1580
+ * The outbound data size will be zero if there are zero-length outbound packets,
1581
+ * so we now select writable in case the outbound page buffer is not empty.
1582
+ * Note that the superclass ShouldDelete method still checks for outbound data size,
1583
+ * which may be wrong.
1584
+ */
1585
+ //return (GetOutboundDataSize() > 0); (Original)
1586
+ return (OutboundPages.size() > 0);
1587
+ }
1588
+
1589
+
1590
+ /************************************
1591
+ DatagramDescriptor::SendOutboundData
1592
+ ************************************/
1593
+
1594
+ int DatagramDescriptor::SendOutboundData (const char *data, int length)
1595
+ {
1596
+ // This is an exact clone of ConnectionDescriptor::SendOutboundData.
1597
+ // That means it needs to move to a common ancestor.
1598
+
1599
+ if (IsCloseScheduled())
1600
+ //if (bCloseNow || bCloseAfterWriting)
1601
+ return 0;
1602
+
1603
+ if (!data && (length > 0))
1604
+ throw std::runtime_error ("bad outbound data");
1605
+ char *buffer = (char *) malloc (length + 1);
1606
+ if (!buffer)
1607
+ throw std::runtime_error ("no allocation for outbound data");
1608
+ memcpy (buffer, data, length);
1609
+ buffer [length] = 0;
1610
+ OutboundPages.push_back (OutboundPage (buffer, length, ReturnAddress));
1611
+ OutboundDataSize += length;
1612
+
1613
+ #ifdef HAVE_EPOLL
1614
+ EpollEvent.events = (EPOLLIN | EPOLLOUT);
1615
+ assert (MyEventMachine);
1616
+ MyEventMachine->Modify (this);
1617
+ #endif
1618
+ #ifdef HAVE_KQUEUE
1619
+ MyEventMachine->ArmKqueueWriter (this);
1620
+ #endif
1621
+
1622
+ return length;
1623
+ }
1624
+
1625
+
1626
+ /****************************************
1627
+ DatagramDescriptor::SendOutboundDatagram
1628
+ ****************************************/
1629
+
1630
+ int DatagramDescriptor::SendOutboundDatagram (const char *data, int length, const char *address, int port)
1631
+ {
1632
+ // This is an exact clone of ConnectionDescriptor::SendOutboundData.
1633
+ // That means it needs to move to a common ancestor.
1634
+ // TODO: Refactor this so there's no overlap with SendOutboundData.
1635
+
1636
+ if (IsCloseScheduled())
1637
+ //if (bCloseNow || bCloseAfterWriting)
1638
+ return 0;
1639
+
1640
+ if (!address || !*address || !port)
1641
+ return 0;
1642
+
1643
+ sockaddr_in pin;
1644
+ unsigned long HostAddr;
1645
+
1646
+ HostAddr = inet_addr (address);
1647
+ if (HostAddr == INADDR_NONE) {
1648
+ // The nasty cast to (char*) is because Windows is brain-dead.
1649
+ hostent *hp = gethostbyname ((char*)address);
1650
+ if (!hp)
1651
+ return 0;
1652
+ HostAddr = ((in_addr*)(hp->h_addr))->s_addr;
1653
+ }
1654
+
1655
+ memset (&pin, 0, sizeof(pin));
1656
+ pin.sin_family = AF_INET;
1657
+ pin.sin_addr.s_addr = HostAddr;
1658
+ pin.sin_port = htons (port);
1659
+
1660
+
1661
+ if (!data && (length > 0))
1662
+ throw std::runtime_error ("bad outbound data");
1663
+ char *buffer = (char *) malloc (length + 1);
1664
+ if (!buffer)
1665
+ throw std::runtime_error ("no allocation for outbound data");
1666
+ memcpy (buffer, data, length);
1667
+ buffer [length] = 0;
1668
+ OutboundPages.push_back (OutboundPage (buffer, length, pin));
1669
+ OutboundDataSize += length;
1670
+
1671
+ #ifdef HAVE_EPOLL
1672
+ EpollEvent.events = (EPOLLIN | EPOLLOUT);
1673
+ assert (MyEventMachine);
1674
+ MyEventMachine->Modify (this);
1675
+ #endif
1676
+ #ifdef HAVE_KQUEUE
1677
+ MyEventMachine->ArmKqueueWriter (this);
1678
+ #endif
1679
+
1680
+ return length;
1681
+ }
1682
+
1683
+
1684
+ /****************************************
1685
+ STATIC: DatagramDescriptor::SendDatagram
1686
+ ****************************************/
1687
+
1688
+ int DatagramDescriptor::SendDatagram (const unsigned long binding, const char *data, int length, const char *address, int port)
1689
+ {
1690
+ DatagramDescriptor *dd = dynamic_cast <DatagramDescriptor*> (Bindable_t::GetObject (binding));
1691
+ if (dd)
1692
+ return dd->SendOutboundDatagram (data, length, address, port);
1693
+ else
1694
+ return -1;
1695
+ }
1696
+
1697
+
1698
+ /*********************************
1699
+ ConnectionDescriptor::GetPeername
1700
+ *********************************/
1701
+
1702
+ bool ConnectionDescriptor::GetPeername (struct sockaddr *s)
1703
+ {
1704
+ bool ok = false;
1705
+ if (s) {
1706
+ socklen_t len = sizeof(*s);
1707
+ int gp = getpeername (GetSocket(), s, &len);
1708
+ if (gp == 0)
1709
+ ok = true;
1710
+ }
1711
+ return ok;
1712
+ }
1713
+
1714
+ /*********************************
1715
+ ConnectionDescriptor::GetSockname
1716
+ *********************************/
1717
+
1718
+ bool ConnectionDescriptor::GetSockname (struct sockaddr *s)
1719
+ {
1720
+ bool ok = false;
1721
+ if (s) {
1722
+ socklen_t len = sizeof(*s);
1723
+ int gp = getsockname (GetSocket(), s, &len);
1724
+ if (gp == 0)
1725
+ ok = true;
1726
+ }
1727
+ return ok;
1728
+ }
1729
+
1730
+
1731
+ /**********************************************
1732
+ ConnectionDescriptor::GetCommInactivityTimeout
1733
+ **********************************************/
1734
+
1735
+ float ConnectionDescriptor::GetCommInactivityTimeout()
1736
+ {
1737
+ return ((float)InactivityTimeout / 1000000);
1738
+ }
1739
+
1740
+
1741
+ /**********************************************
1742
+ ConnectionDescriptor::SetCommInactivityTimeout
1743
+ **********************************************/
1744
+
1745
+ int ConnectionDescriptor::SetCommInactivityTimeout (float value)
1746
+ {
1747
+ if (value > 0) {
1748
+ InactivityTimeout = (Int64)(value * 1000000);
1749
+ return 1;
1750
+ }
1751
+ return 0;
1752
+ }
1753
+
1754
+ /*******************************
1755
+ DatagramDescriptor::GetPeername
1756
+ *******************************/
1757
+
1758
+ bool DatagramDescriptor::GetPeername (struct sockaddr *s)
1759
+ {
1760
+ bool ok = false;
1761
+ if (s) {
1762
+ memset (s, 0, sizeof(struct sockaddr));
1763
+ memcpy (s, &ReturnAddress, sizeof(ReturnAddress));
1764
+ ok = true;
1765
+ }
1766
+ return ok;
1767
+ }
1768
+
1769
+ /*******************************
1770
+ DatagramDescriptor::GetSockname
1771
+ *******************************/
1772
+
1773
+ bool DatagramDescriptor::GetSockname (struct sockaddr *s)
1774
+ {
1775
+ bool ok = false;
1776
+ if (s) {
1777
+ socklen_t len = sizeof(*s);
1778
+ int gp = getsockname (GetSocket(), s, &len);
1779
+ if (gp == 0)
1780
+ ok = true;
1781
+ }
1782
+ return ok;
1783
+ }
1784
+
1785
+
1786
+
1787
+ /********************************************
1788
+ DatagramDescriptor::GetCommInactivityTimeout
1789
+ ********************************************/
1790
+
1791
+ float DatagramDescriptor::GetCommInactivityTimeout()
1792
+ {
1793
+ return ((float)InactivityTimeout / 1000000);
1794
+ }
1795
+
1796
+ /********************************************
1797
+ DatagramDescriptor::SetCommInactivityTimeout
1798
+ ********************************************/
1799
+
1800
+ int DatagramDescriptor::SetCommInactivityTimeout (float value)
1801
+ {
1802
+ if (value > 0) {
1803
+ InactivityTimeout = (Int64)(value * 1000000);
1804
+ return 1;
1805
+ }
1806
+ return 0;
1807
+ }
1808
+
1809
+
1810
+ /************************************
1811
+ InotifyDescriptor::InotifyDescriptor
1812
+ *************************************/
1813
+
1814
+ InotifyDescriptor::InotifyDescriptor (EventMachine_t *em):
1815
+ EventableDescriptor(0, em)
1816
+ {
1817
+ bCallbackUnbind = false;
1818
+
1819
+ #ifndef HAVE_INOTIFY
1820
+ throw std::runtime_error("no inotify support on this system");
1821
+ #else
1822
+
1823
+ int fd = inotify_init();
1824
+ if (fd == -1) {
1825
+ char buf[200];
1826
+ snprintf (buf, sizeof(buf)-1, "unable to create inotify descriptor: %s", strerror(errno));
1827
+ throw std::runtime_error (buf);
1828
+ }
1829
+
1830
+ MySocket = fd;
1831
+ SetSocketNonblocking(MySocket);
1832
+ #ifdef HAVE_EPOLL
1833
+ EpollEvent.events = EPOLLIN;
1834
+ #endif
1835
+
1836
+ #endif
1837
+ }
1838
+
1839
+
1840
+ /*************************************
1841
+ InotifyDescriptor::~InotifyDescriptor
1842
+ **************************************/
1843
+
1844
+ InotifyDescriptor::~InotifyDescriptor()
1845
+ {
1846
+ close(MySocket);
1847
+ MySocket = INVALID_SOCKET;
1848
+ }
1849
+
1850
+ /***********************
1851
+ InotifyDescriptor::Read
1852
+ ************************/
1853
+
1854
+ void InotifyDescriptor::Read()
1855
+ {
1856
+ assert (MyEventMachine);
1857
+ MyEventMachine->_ReadInotifyEvents();
1858
+ }
1859
+
1860
+
1861
+ /************************
1862
+ InotifyDescriptor::Write
1863
+ *************************/
1864
+
1865
+ void InotifyDescriptor::Write()
1866
+ {
1867
+ throw std::runtime_error("bad code path in inotify");
1868
+ }