crusher-eventmachine 0.12.11

Sign up to get free protection for your applications and to get access to all the features.
Files changed (162) hide show
  1. data/README +81 -0
  2. data/Rakefile +370 -0
  3. data/docs/COPYING +60 -0
  4. data/docs/ChangeLog +211 -0
  5. data/docs/DEFERRABLES +246 -0
  6. data/docs/EPOLL +141 -0
  7. data/docs/GNU +281 -0
  8. data/docs/INSTALL +13 -0
  9. data/docs/KEYBOARD +42 -0
  10. data/docs/LEGAL +25 -0
  11. data/docs/LIGHTWEIGHT_CONCURRENCY +130 -0
  12. data/docs/PURE_RUBY +75 -0
  13. data/docs/RELEASE_NOTES +94 -0
  14. data/docs/SMTP +4 -0
  15. data/docs/SPAWNED_PROCESSES +148 -0
  16. data/docs/TODO +8 -0
  17. data/eventmachine.gemspec +40 -0
  18. data/examples/ex_channel.rb +43 -0
  19. data/examples/ex_queue.rb +2 -0
  20. data/examples/ex_tick_loop_array.rb +15 -0
  21. data/examples/ex_tick_loop_counter.rb +32 -0
  22. data/examples/helper.rb +2 -0
  23. data/ext/binder.cpp +124 -0
  24. data/ext/binder.h +46 -0
  25. data/ext/cmain.cpp +852 -0
  26. data/ext/cplusplus.cpp +202 -0
  27. data/ext/ed.cpp +1884 -0
  28. data/ext/ed.h +418 -0
  29. data/ext/em.cpp +2377 -0
  30. data/ext/em.h +239 -0
  31. data/ext/emwin.cpp +300 -0
  32. data/ext/emwin.h +94 -0
  33. data/ext/epoll.cpp +26 -0
  34. data/ext/epoll.h +25 -0
  35. data/ext/eventmachine.h +124 -0
  36. data/ext/eventmachine_cpp.h +96 -0
  37. data/ext/extconf.rb +150 -0
  38. data/ext/fastfilereader/extconf.rb +85 -0
  39. data/ext/fastfilereader/mapper.cpp +214 -0
  40. data/ext/fastfilereader/mapper.h +59 -0
  41. data/ext/fastfilereader/rubymain.cpp +127 -0
  42. data/ext/files.cpp +94 -0
  43. data/ext/files.h +65 -0
  44. data/ext/kb.cpp +79 -0
  45. data/ext/page.cpp +107 -0
  46. data/ext/page.h +51 -0
  47. data/ext/pipe.cpp +347 -0
  48. data/ext/project.h +157 -0
  49. data/ext/rubymain.cpp +1215 -0
  50. data/ext/sigs.cpp +89 -0
  51. data/ext/sigs.h +32 -0
  52. data/ext/ssl.cpp +460 -0
  53. data/ext/ssl.h +94 -0
  54. data/java/.classpath +8 -0
  55. data/java/.project +17 -0
  56. data/java/src/com/rubyeventmachine/EmReactor.java +571 -0
  57. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  58. data/java/src/com/rubyeventmachine/EventableChannel.java +69 -0
  59. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +189 -0
  60. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
  61. data/java/src/com/rubyeventmachine/application/Application.java +194 -0
  62. data/java/src/com/rubyeventmachine/application/Connection.java +74 -0
  63. data/java/src/com/rubyeventmachine/application/ConnectionFactory.java +37 -0
  64. data/java/src/com/rubyeventmachine/application/DefaultConnectionFactory.java +46 -0
  65. data/java/src/com/rubyeventmachine/application/PeriodicTimer.java +38 -0
  66. data/java/src/com/rubyeventmachine/application/Timer.java +54 -0
  67. data/java/src/com/rubyeventmachine/tests/ApplicationTest.java +109 -0
  68. data/java/src/com/rubyeventmachine/tests/ConnectTest.java +148 -0
  69. data/java/src/com/rubyeventmachine/tests/EMTest.java +80 -0
  70. data/java/src/com/rubyeventmachine/tests/TestDatagrams.java +53 -0
  71. data/java/src/com/rubyeventmachine/tests/TestServers.java +75 -0
  72. data/java/src/com/rubyeventmachine/tests/TestTimers.java +90 -0
  73. data/lib/em/buftok.rb +138 -0
  74. data/lib/em/callback.rb +26 -0
  75. data/lib/em/channel.rb +57 -0
  76. data/lib/em/connection.rb +569 -0
  77. data/lib/em/deferrable.rb +206 -0
  78. data/lib/em/file_watch.rb +54 -0
  79. data/lib/em/future.rb +61 -0
  80. data/lib/em/iterator.rb +270 -0
  81. data/lib/em/messages.rb +66 -0
  82. data/lib/em/process_watch.rb +44 -0
  83. data/lib/em/processes.rb +119 -0
  84. data/lib/em/protocols.rb +36 -0
  85. data/lib/em/protocols/header_and_content.rb +138 -0
  86. data/lib/em/protocols/httpclient.rb +276 -0
  87. data/lib/em/protocols/httpclient2.rb +590 -0
  88. data/lib/em/protocols/line_and_text.rb +125 -0
  89. data/lib/em/protocols/linetext2.rb +161 -0
  90. data/lib/em/protocols/memcache.rb +323 -0
  91. data/lib/em/protocols/object_protocol.rb +45 -0
  92. data/lib/em/protocols/postgres3.rb +247 -0
  93. data/lib/em/protocols/saslauth.rb +175 -0
  94. data/lib/em/protocols/smtpclient.rb +357 -0
  95. data/lib/em/protocols/smtpserver.rb +640 -0
  96. data/lib/em/protocols/socks4.rb +66 -0
  97. data/lib/em/protocols/stomp.rb +200 -0
  98. data/lib/em/protocols/tcptest.rb +53 -0
  99. data/lib/em/pure_ruby.rb +1019 -0
  100. data/lib/em/queue.rb +62 -0
  101. data/lib/em/spawnable.rb +85 -0
  102. data/lib/em/streamer.rb +130 -0
  103. data/lib/em/tick_loop.rb +85 -0
  104. data/lib/em/timers.rb +57 -0
  105. data/lib/em/version.rb +3 -0
  106. data/lib/eventmachine.rb +1540 -0
  107. data/lib/evma.rb +32 -0
  108. data/lib/evma/callback.rb +32 -0
  109. data/lib/evma/container.rb +75 -0
  110. data/lib/evma/factory.rb +77 -0
  111. data/lib/evma/protocol.rb +87 -0
  112. data/lib/evma/reactor.rb +48 -0
  113. data/lib/jeventmachine.rb +257 -0
  114. data/setup.rb +1585 -0
  115. data/tasks/cpp.rake_example +77 -0
  116. data/tests/client.crt +31 -0
  117. data/tests/client.key +51 -0
  118. data/tests/test_attach.rb +136 -0
  119. data/tests/test_basic.rb +249 -0
  120. data/tests/test_channel.rb +63 -0
  121. data/tests/test_connection_count.rb +35 -0
  122. data/tests/test_defer.rb +49 -0
  123. data/tests/test_deferrable.rb +35 -0
  124. data/tests/test_epoll.rb +160 -0
  125. data/tests/test_error_handler.rb +35 -0
  126. data/tests/test_errors.rb +82 -0
  127. data/tests/test_exc.rb +55 -0
  128. data/tests/test_file_watch.rb +49 -0
  129. data/tests/test_futures.rb +198 -0
  130. data/tests/test_get_sock_opt.rb +30 -0
  131. data/tests/test_handler_check.rb +37 -0
  132. data/tests/test_hc.rb +190 -0
  133. data/tests/test_httpclient.rb +227 -0
  134. data/tests/test_httpclient2.rb +154 -0
  135. data/tests/test_inactivity_timeout.rb +50 -0
  136. data/tests/test_kb.rb +60 -0
  137. data/tests/test_ltp.rb +190 -0
  138. data/tests/test_ltp2.rb +317 -0
  139. data/tests/test_next_tick.rb +133 -0
  140. data/tests/test_object_protocol.rb +37 -0
  141. data/tests/test_pause.rb +70 -0
  142. data/tests/test_pending_connect_timeout.rb +48 -0
  143. data/tests/test_process_watch.rb +50 -0
  144. data/tests/test_processes.rb +128 -0
  145. data/tests/test_proxy_connection.rb +144 -0
  146. data/tests/test_pure.rb +134 -0
  147. data/tests/test_queue.rb +44 -0
  148. data/tests/test_running.rb +42 -0
  149. data/tests/test_sasl.rb +72 -0
  150. data/tests/test_send_file.rb +251 -0
  151. data/tests/test_servers.rb +76 -0
  152. data/tests/test_smtpclient.rb +83 -0
  153. data/tests/test_smtpserver.rb +85 -0
  154. data/tests/test_spawn.rb +322 -0
  155. data/tests/test_ssl_args.rb +79 -0
  156. data/tests/test_ssl_methods.rb +50 -0
  157. data/tests/test_ssl_verify.rb +82 -0
  158. data/tests/test_tick_loop.rb +59 -0
  159. data/tests/test_timers.rb +160 -0
  160. data/tests/test_ud.rb +36 -0
  161. data/tests/testem.rb +31 -0
  162. metadata +251 -0
data/ext/ed.h ADDED
@@ -0,0 +1,418 @@
1
+ /*****************************************************************************
2
+
3
+ $Id$
4
+
5
+ File: ed.h
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
+ #ifndef __EventableDescriptor__H_
21
+ #define __EventableDescriptor__H_
22
+
23
+
24
+ class EventMachine_t; // forward reference
25
+ #ifdef WITH_SSL
26
+ class SslBox_t; // forward reference
27
+ #endif
28
+
29
+ bool SetSocketNonblocking (SOCKET);
30
+
31
+
32
+ /*************************
33
+ class EventableDescriptor
34
+ *************************/
35
+
36
+ class EventableDescriptor: public Bindable_t
37
+ {
38
+ public:
39
+ EventableDescriptor (int, EventMachine_t*);
40
+ virtual ~EventableDescriptor();
41
+
42
+ int GetSocket() {return MySocket;}
43
+ void SetSocketInvalid() { MySocket = INVALID_SOCKET; }
44
+ void Close();
45
+
46
+ virtual void Read() = 0;
47
+ virtual void Write() = 0;
48
+ virtual void Heartbeat() = 0;
49
+
50
+ // These methods tell us whether the descriptor
51
+ // should be selected or polled for read/write.
52
+ virtual bool SelectForRead() = 0;
53
+ virtual bool SelectForWrite() = 0;
54
+
55
+ // are we scheduled for a close, or in an error state, or already closed?
56
+ bool ShouldDelete();
57
+ // Do we have any data to write? This is used by ShouldDelete.
58
+ virtual int GetOutboundDataSize() {return 0;}
59
+ virtual bool IsWatchOnly(){ return false; }
60
+
61
+ virtual void ScheduleClose (bool after_writing);
62
+ bool IsCloseScheduled();
63
+ virtual void HandleError(){ ScheduleClose (false); }
64
+
65
+ void SetEventCallback (EMCallback);
66
+
67
+ virtual bool GetPeername (struct sockaddr*) {return false;}
68
+ virtual bool GetSockname (struct sockaddr*) {return false;}
69
+ virtual bool GetSubprocessPid (pid_t*) {return false;}
70
+
71
+ virtual void StartTls() {}
72
+ virtual void SetTlsParms (const char *privkey_filename, const char *certchain_filename, bool verify_peer) {}
73
+
74
+ #ifdef WITH_SSL
75
+ virtual X509 *GetPeerCert() {return NULL;}
76
+ #endif
77
+
78
+ virtual uint64_t GetCommInactivityTimeout() {return 0;}
79
+ virtual int SetCommInactivityTimeout (uint64_t value) {return 0;}
80
+ uint64_t GetPendingConnectTimeout();
81
+ int SetPendingConnectTimeout (uint64_t value);
82
+
83
+ #ifdef HAVE_EPOLL
84
+ struct epoll_event *GetEpollEvent() { return &EpollEvent; }
85
+ #endif
86
+
87
+ virtual void StartProxy(const unsigned long, const unsigned long, const unsigned long);
88
+ virtual void StopProxy();
89
+ virtual void SetProxiedFrom(EventableDescriptor*, const unsigned long);
90
+ virtual int SendOutboundData(const char*,int){ return -1; }
91
+ virtual bool IsPaused(){ return false; }
92
+ virtual bool Pause(){ return false; }
93
+ virtual bool Resume(){ return false; }
94
+
95
+ virtual int ReportErrorStatus(){ return 0; }
96
+ virtual bool IsConnectPending(){ return false; }
97
+ virtual uint64_t GetNextHeartbeat();
98
+
99
+ private:
100
+ bool bCloseNow;
101
+ bool bCloseAfterWriting;
102
+
103
+ protected:
104
+ int MySocket;
105
+
106
+ EMCallback EventCallback;
107
+ void _GenericInboundDispatch(const char*, int);
108
+
109
+ uint64_t CreatedAt;
110
+ bool bCallbackUnbind;
111
+ int UnbindReasonCode;
112
+
113
+ unsigned long BytesToProxy;
114
+ EventableDescriptor *ProxyTarget;
115
+ EventableDescriptor *ProxiedFrom;
116
+
117
+ unsigned long MaxOutboundBufSize;
118
+
119
+ #ifdef HAVE_EPOLL
120
+ struct epoll_event EpollEvent;
121
+ #endif
122
+
123
+ EventMachine_t *MyEventMachine;
124
+ uint64_t PendingConnectTimeout;
125
+ uint64_t InactivityTimeout;
126
+ uint64_t LastActivity;
127
+ uint64_t NextHeartbeat;
128
+ };
129
+
130
+
131
+
132
+ /*************************
133
+ class LoopbreakDescriptor
134
+ *************************/
135
+
136
+ class LoopbreakDescriptor: public EventableDescriptor
137
+ {
138
+ public:
139
+ LoopbreakDescriptor (int, EventMachine_t*);
140
+ virtual ~LoopbreakDescriptor() {}
141
+
142
+ virtual void Read();
143
+ virtual void Write();
144
+ virtual void Heartbeat() {}
145
+
146
+ virtual bool SelectForRead() {return true;}
147
+ virtual bool SelectForWrite() {return false;}
148
+ };
149
+
150
+
151
+ /**************************
152
+ class ConnectionDescriptor
153
+ **************************/
154
+
155
+ class ConnectionDescriptor: public EventableDescriptor
156
+ {
157
+ public:
158
+ ConnectionDescriptor (int, EventMachine_t*);
159
+ virtual ~ConnectionDescriptor();
160
+
161
+ int SendOutboundData (const char*, int);
162
+
163
+ void SetConnectPending (bool f);
164
+ virtual void ScheduleClose (bool after_writing);
165
+ virtual void HandleError();
166
+
167
+ void SetNotifyReadable (bool);
168
+ void SetNotifyWritable (bool);
169
+ void SetWatchOnly (bool);
170
+
171
+ bool IsPaused(){ return bPaused; }
172
+ bool Pause();
173
+ bool Resume();
174
+
175
+ bool IsNotifyReadable(){ return bNotifyReadable; }
176
+ bool IsNotifyWritable(){ return bNotifyWritable; }
177
+ virtual bool IsWatchOnly(){ return bWatchOnly; }
178
+
179
+ virtual void Read();
180
+ virtual void Write();
181
+ virtual void Heartbeat();
182
+
183
+ virtual bool SelectForRead();
184
+ virtual bool SelectForWrite();
185
+
186
+ // Do we have any data to write? This is used by ShouldDelete.
187
+ virtual int GetOutboundDataSize() {return OutboundDataSize;}
188
+
189
+ virtual void StartTls();
190
+ virtual void SetTlsParms (const char *privkey_filename, const char *certchain_filename, bool verify_peer);
191
+
192
+ #ifdef WITH_SSL
193
+ virtual X509 *GetPeerCert();
194
+ virtual bool VerifySslPeer(const char*);
195
+ virtual void AcceptSslPeer();
196
+ #endif
197
+
198
+ void SetServerMode() {bIsServer = true;}
199
+
200
+ virtual bool GetPeername (struct sockaddr*);
201
+ virtual bool GetSockname (struct sockaddr*);
202
+
203
+ virtual uint64_t GetCommInactivityTimeout();
204
+ virtual int SetCommInactivityTimeout (uint64_t value);
205
+
206
+ virtual int ReportErrorStatus();
207
+ virtual bool IsConnectPending(){ return bConnectPending; }
208
+
209
+ protected:
210
+ struct OutboundPage {
211
+ OutboundPage (const char *b, int l, int o=0): Buffer(b), Length(l), Offset(o) {}
212
+ void Free() {if (Buffer) free ((char*)Buffer); }
213
+ const char *Buffer;
214
+ int Length;
215
+ int Offset;
216
+ };
217
+
218
+ protected:
219
+ bool bPaused;
220
+ bool bConnectPending;
221
+
222
+ bool bNotifyReadable;
223
+ bool bNotifyWritable;
224
+ bool bWatchOnly;
225
+
226
+ bool bReadAttemptedAfterClose;
227
+ bool bWriteAttemptedAfterClose;
228
+
229
+ deque<OutboundPage> OutboundPages;
230
+ int OutboundDataSize;
231
+
232
+ #ifdef WITH_SSL
233
+ SslBox_t *SslBox;
234
+ std::string CertChainFilename;
235
+ std::string PrivateKeyFilename;
236
+ bool bHandshakeSignaled;
237
+ bool bSslVerifyPeer;
238
+ bool bSslPeerAccepted;
239
+ #endif
240
+
241
+ #ifdef HAVE_KQUEUE
242
+ bool bGotExtraKqueueEvent;
243
+ #endif
244
+
245
+ bool bIsServer;
246
+
247
+ private:
248
+ void _UpdateEvents();
249
+ void _UpdateEvents(bool, bool);
250
+ void _WriteOutboundData();
251
+ void _DispatchInboundData (const char *buffer, int size);
252
+ void _DispatchCiphertext();
253
+ int _SendRawOutboundData (const char*, int);
254
+ void _CheckHandshakeStatus();
255
+
256
+ };
257
+
258
+
259
+ /************************
260
+ class DatagramDescriptor
261
+ ************************/
262
+
263
+ class DatagramDescriptor: public EventableDescriptor
264
+ {
265
+ public:
266
+ DatagramDescriptor (int, EventMachine_t*);
267
+ virtual ~DatagramDescriptor();
268
+
269
+ virtual void Read();
270
+ virtual void Write();
271
+ virtual void Heartbeat();
272
+
273
+ virtual bool SelectForRead() {return true;}
274
+ virtual bool SelectForWrite();
275
+
276
+ int SendOutboundData (const char*, int);
277
+ int SendOutboundDatagram (const char*, int, const char*, int);
278
+
279
+ // Do we have any data to write? This is used by ShouldDelete.
280
+ virtual int GetOutboundDataSize() {return OutboundDataSize;}
281
+
282
+ virtual bool GetPeername (struct sockaddr*);
283
+ virtual bool GetSockname (struct sockaddr*);
284
+
285
+ virtual uint64_t GetCommInactivityTimeout();
286
+ virtual int SetCommInactivityTimeout (uint64_t value);
287
+
288
+ protected:
289
+ struct OutboundPage {
290
+ OutboundPage (const char *b, int l, struct sockaddr_in f, int o=0): Buffer(b), Length(l), Offset(o), From(f) {}
291
+ void Free() {if (Buffer) free ((char*)Buffer); }
292
+ const char *Buffer;
293
+ int Length;
294
+ int Offset;
295
+ struct sockaddr_in From;
296
+ };
297
+
298
+ deque<OutboundPage> OutboundPages;
299
+ int OutboundDataSize;
300
+
301
+ struct sockaddr_in ReturnAddress;
302
+ };
303
+
304
+
305
+ /************************
306
+ class AcceptorDescriptor
307
+ ************************/
308
+
309
+ class AcceptorDescriptor: public EventableDescriptor
310
+ {
311
+ public:
312
+ AcceptorDescriptor (int, EventMachine_t*);
313
+ virtual ~AcceptorDescriptor();
314
+
315
+ virtual void Read();
316
+ virtual void Write();
317
+ virtual void Heartbeat();
318
+
319
+ virtual bool SelectForRead() {return true;}
320
+ virtual bool SelectForWrite() {return false;}
321
+
322
+ virtual bool GetSockname (struct sockaddr*);
323
+
324
+ static void StopAcceptor (const unsigned long binding);
325
+ };
326
+
327
+ /********************
328
+ class PipeDescriptor
329
+ ********************/
330
+
331
+ #ifdef OS_UNIX
332
+ class PipeDescriptor: public EventableDescriptor
333
+ {
334
+ public:
335
+ PipeDescriptor (int, pid_t, EventMachine_t*);
336
+ virtual ~PipeDescriptor();
337
+
338
+ virtual void Read();
339
+ virtual void Write();
340
+ virtual void Heartbeat();
341
+
342
+ virtual bool SelectForRead();
343
+ virtual bool SelectForWrite();
344
+
345
+ int SendOutboundData (const char*, int);
346
+ virtual int GetOutboundDataSize() {return OutboundDataSize;}
347
+
348
+ virtual bool GetSubprocessPid (pid_t*);
349
+
350
+ protected:
351
+ struct OutboundPage {
352
+ OutboundPage (const char *b, int l, int o=0): Buffer(b), Length(l), Offset(o) {}
353
+ void Free() {if (Buffer) free ((char*)Buffer); }
354
+ const char *Buffer;
355
+ int Length;
356
+ int Offset;
357
+ };
358
+
359
+ protected:
360
+ bool bReadAttemptedAfterClose;
361
+
362
+ deque<OutboundPage> OutboundPages;
363
+ int OutboundDataSize;
364
+
365
+ pid_t SubprocessPid;
366
+
367
+ private:
368
+ void _DispatchInboundData (const char *buffer, int size);
369
+ };
370
+ #endif // OS_UNIX
371
+
372
+
373
+ /************************
374
+ class KeyboardDescriptor
375
+ ************************/
376
+
377
+ class KeyboardDescriptor: public EventableDescriptor
378
+ {
379
+ public:
380
+ KeyboardDescriptor (EventMachine_t*);
381
+ virtual ~KeyboardDescriptor();
382
+
383
+ virtual void Read();
384
+ virtual void Write();
385
+ virtual void Heartbeat();
386
+
387
+ virtual bool SelectForRead() {return true;}
388
+ virtual bool SelectForWrite() {return false;}
389
+
390
+ protected:
391
+ bool bReadAttemptedAfterClose;
392
+
393
+ private:
394
+ void _DispatchInboundData (const char *buffer, int size);
395
+ };
396
+
397
+
398
+ /***********************
399
+ class InotifyDescriptor
400
+ ************************/
401
+
402
+ class InotifyDescriptor: public EventableDescriptor
403
+ {
404
+ public:
405
+ InotifyDescriptor (EventMachine_t*);
406
+ virtual ~InotifyDescriptor();
407
+
408
+ void Read();
409
+ void Write();
410
+
411
+ virtual void Heartbeat() {}
412
+ virtual bool SelectForRead() {return true;}
413
+ virtual bool SelectForWrite() {return false;}
414
+ };
415
+
416
+ #endif // __EventableDescriptor__H_
417
+
418
+
data/ext/em.cpp ADDED
@@ -0,0 +1,2377 @@
1
+ /*****************************************************************************
2
+
3
+ $Id$
4
+
5
+ File: em.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
+ // THIS ENTIRE FILE WILL EVENTUALLY BE FOR UNIX BUILDS ONLY.
21
+ //#ifdef OS_UNIX
22
+
23
+ #include "project.h"
24
+
25
+ /* The numer of max outstanding timers was once a const enum defined in em.h.
26
+ * Now we define it here so that users can change its value if necessary.
27
+ */
28
+ static unsigned int MaxOutstandingTimers = 10000;
29
+
30
+
31
+ /* Internal helper to convert strings to internet addresses. IPv6-aware.
32
+ * Not reentrant or threadsafe, optimized for speed.
33
+ */
34
+ static struct sockaddr *name2address (const char *server, int port, int *family, int *bind_size);
35
+
36
+ /***************************************
37
+ STATIC EventMachine_t::GetMaxTimerCount
38
+ ***************************************/
39
+
40
+ int EventMachine_t::GetMaxTimerCount()
41
+ {
42
+ return MaxOutstandingTimers;
43
+ }
44
+
45
+
46
+ /***************************************
47
+ STATIC EventMachine_t::SetMaxTimerCount
48
+ ***************************************/
49
+
50
+ void EventMachine_t::SetMaxTimerCount (int count)
51
+ {
52
+ /* Allow a user to increase the maximum number of outstanding timers.
53
+ * If this gets "too high" (a metric that is of course platform dependent),
54
+ * bad things will happen like performance problems and possible overuse
55
+ * of memory.
56
+ * The actual timer mechanism is very efficient so it's hard to know what
57
+ * the practical max, but 100,000 shouldn't be too problematical.
58
+ */
59
+ if (count < 100)
60
+ count = 100;
61
+ MaxOutstandingTimers = count;
62
+ }
63
+
64
+
65
+
66
+ /******************************
67
+ EventMachine_t::EventMachine_t
68
+ ******************************/
69
+
70
+ EventMachine_t::EventMachine_t (EMCallback event_callback):
71
+ HeartbeatInterval(2000000),
72
+ EventCallback (event_callback),
73
+ NextHeartbeatTime (0),
74
+ LoopBreakerReader (-1),
75
+ LoopBreakerWriter (-1),
76
+ bEpoll (false),
77
+ epfd (-1),
78
+ bKqueue (false),
79
+ kqfd (-1),
80
+ inotify (NULL)
81
+ {
82
+ // Default time-slice is just smaller than one hundred mills.
83
+ Quantum.tv_sec = 0;
84
+ Quantum.tv_usec = 90000;
85
+
86
+ gTerminateSignalReceived = false;
87
+ // Make sure the current loop time is sane, in case we do any initializations of
88
+ // objects before we start running.
89
+ _UpdateTime();
90
+
91
+ /* We initialize the network library here (only on Windows of course)
92
+ * and initialize "loop breakers." Our destructor also does some network-level
93
+ * cleanup. There's thus an implicit assumption that any given instance of EventMachine_t
94
+ * will only call ::Run once. Is that a good assumption? Should we move some of these
95
+ * inits and de-inits into ::Run?
96
+ */
97
+ #ifdef OS_WIN32
98
+ WSADATA w;
99
+ WSAStartup (MAKEWORD (1, 1), &w);
100
+ #endif
101
+
102
+ _InitializeLoopBreaker();
103
+ }
104
+
105
+
106
+ /*******************************
107
+ EventMachine_t::~EventMachine_t
108
+ *******************************/
109
+
110
+ EventMachine_t::~EventMachine_t()
111
+ {
112
+ // Run down descriptors
113
+ size_t i;
114
+ for (i = 0; i < NewDescriptors.size(); i++)
115
+ delete NewDescriptors[i];
116
+ for (i = 0; i < Descriptors.size(); i++)
117
+ delete Descriptors[i];
118
+
119
+ close (LoopBreakerReader);
120
+ close (LoopBreakerWriter);
121
+
122
+ // Remove any file watch descriptors
123
+ while(!Files.empty()) {
124
+ map<int, Bindable_t*>::iterator f = Files.begin();
125
+ UnwatchFile (f->first);
126
+ }
127
+
128
+ if (epfd != -1)
129
+ close (epfd);
130
+ if (kqfd != -1)
131
+ close (kqfd);
132
+ }
133
+
134
+
135
+ /*************************
136
+ EventMachine_t::_UseEpoll
137
+ *************************/
138
+
139
+ void EventMachine_t::_UseEpoll()
140
+ {
141
+ /* Temporary.
142
+ * Use an internal flag to switch in epoll-based functionality until we determine
143
+ * how it should be integrated properly and the extent of the required changes.
144
+ * A permanent solution needs to allow the integration of additional technologies,
145
+ * like kqueue and Solaris's events.
146
+ */
147
+
148
+ #ifdef HAVE_EPOLL
149
+ bEpoll = true;
150
+ #endif
151
+ }
152
+
153
+ /**************************
154
+ EventMachine_t::_UseKqueue
155
+ **************************/
156
+
157
+ void EventMachine_t::_UseKqueue()
158
+ {
159
+ /* Temporary.
160
+ * See comments under _UseEpoll.
161
+ */
162
+
163
+ #ifdef HAVE_KQUEUE
164
+ bKqueue = true;
165
+ #endif
166
+ }
167
+
168
+
169
+ /****************************
170
+ EventMachine_t::ScheduleHalt
171
+ ****************************/
172
+
173
+ void EventMachine_t::ScheduleHalt()
174
+ {
175
+ /* This is how we stop the machine.
176
+ * This can be called by clients. Signal handlers will probably
177
+ * set the global flag.
178
+ * For now this means there can only be one EventMachine ever running at a time.
179
+ *
180
+ * IMPORTANT: keep this light, fast, and async-safe. Don't do anything frisky in here,
181
+ * because it may be called from signal handlers invoked from code that we don't
182
+ * control. At this writing (20Sep06), EM does NOT install any signal handlers of
183
+ * its own.
184
+ *
185
+ * We need a FAQ. And one of the questions is: how do I stop EM when Ctrl-C happens?
186
+ * The answer is to call evma_stop_machine, which calls here, from a SIGINT handler.
187
+ */
188
+ gTerminateSignalReceived = true;
189
+ }
190
+
191
+
192
+
193
+ /*******************************
194
+ EventMachine_t::SetTimerQuantum
195
+ *******************************/
196
+
197
+ void EventMachine_t::SetTimerQuantum (int interval)
198
+ {
199
+ /* We get a timer-quantum expressed in milliseconds.
200
+ * Don't set a quantum smaller than 5 or larger than 2500.
201
+ */
202
+
203
+ if ((interval < 5) || (interval > 2500))
204
+ throw std::runtime_error ("invalid timer-quantum");
205
+
206
+ Quantum.tv_sec = interval / 1000;
207
+ Quantum.tv_usec = (interval % 1000) * 1000;
208
+ }
209
+
210
+
211
+ /*************************************
212
+ (STATIC) EventMachine_t::SetuidString
213
+ *************************************/
214
+
215
+ void EventMachine_t::SetuidString (const char *username)
216
+ {
217
+ /* This method takes a caller-supplied username and tries to setuid
218
+ * to that user. There is no meaningful implementation (and no error)
219
+ * on Windows. On Unix, a failure to setuid the caller-supplied string
220
+ * causes a fatal abort, because presumably the program is calling here
221
+ * in order to fulfill a security requirement. If we fail silently,
222
+ * the user may continue to run with too much privilege.
223
+ *
224
+ * TODO, we need to decide on and document a way of generating C++ level errors
225
+ * that can be wrapped in documented Ruby exceptions, so users can catch
226
+ * and handle them. And distinguish it from errors that we WON'T let the Ruby
227
+ * user catch (like security-violations and resource-overallocation).
228
+ * A setuid failure here would be in the latter category.
229
+ */
230
+
231
+ #ifdef OS_UNIX
232
+ if (!username || !*username)
233
+ throw std::runtime_error ("setuid_string failed: no username specified");
234
+
235
+ struct passwd *p = getpwnam (username);
236
+ if (!p)
237
+ throw std::runtime_error ("setuid_string failed: unknown username");
238
+
239
+ if (setuid (p->pw_uid) != 0)
240
+ throw std::runtime_error ("setuid_string failed: no setuid");
241
+
242
+ // Success.
243
+ #endif
244
+ }
245
+
246
+
247
+ /****************************************
248
+ (STATIC) EventMachine_t::SetRlimitNofile
249
+ ****************************************/
250
+
251
+ int EventMachine_t::SetRlimitNofile (int nofiles)
252
+ {
253
+ #ifdef OS_UNIX
254
+ struct rlimit rlim;
255
+ getrlimit (RLIMIT_NOFILE, &rlim);
256
+ if (nofiles >= 0) {
257
+ rlim.rlim_cur = nofiles;
258
+ if ((unsigned int)nofiles > rlim.rlim_max)
259
+ rlim.rlim_max = nofiles;
260
+ setrlimit (RLIMIT_NOFILE, &rlim);
261
+ // ignore the error return, for now at least.
262
+ // TODO, emit an error message someday when we have proper debug levels.
263
+ }
264
+ getrlimit (RLIMIT_NOFILE, &rlim);
265
+ return rlim.rlim_cur;
266
+ #endif
267
+
268
+ #ifdef OS_WIN32
269
+ // No meaningful implementation on Windows.
270
+ return 0;
271
+ #endif
272
+ }
273
+
274
+
275
+ /*********************************
276
+ EventMachine_t::SignalLoopBreaker
277
+ *********************************/
278
+
279
+ void EventMachine_t::SignalLoopBreaker()
280
+ {
281
+ #ifdef OS_UNIX
282
+ write (LoopBreakerWriter, "", 1);
283
+ #endif
284
+ #ifdef OS_WIN32
285
+ sendto (LoopBreakerReader, "", 0, 0, (struct sockaddr*)&(LoopBreakerTarget), sizeof(LoopBreakerTarget));
286
+ #endif
287
+ }
288
+
289
+
290
+ /**************************************
291
+ EventMachine_t::_InitializeLoopBreaker
292
+ **************************************/
293
+
294
+ void EventMachine_t::_InitializeLoopBreaker()
295
+ {
296
+ /* A "loop-breaker" is a socket-descriptor that we can write to in order
297
+ * to break the main select loop. Primarily useful for things running on
298
+ * threads other than the main EM thread, so they can trigger processing
299
+ * of events that arise exogenously to the EM.
300
+ * Keep the loop-breaker pipe out of the main descriptor set, otherwise
301
+ * its events will get passed on to user code.
302
+ */
303
+
304
+ #ifdef OS_UNIX
305
+ int fd[2];
306
+ if (pipe (fd))
307
+ throw std::runtime_error (strerror(errno));
308
+
309
+ LoopBreakerWriter = fd[1];
310
+ LoopBreakerReader = fd[0];
311
+ #endif
312
+
313
+ #ifdef OS_WIN32
314
+ int sd = socket (AF_INET, SOCK_DGRAM, 0);
315
+ if (sd == INVALID_SOCKET)
316
+ throw std::runtime_error ("no loop breaker socket");
317
+ SetSocketNonblocking (sd);
318
+
319
+ memset (&LoopBreakerTarget, 0, sizeof(LoopBreakerTarget));
320
+ LoopBreakerTarget.sin_family = AF_INET;
321
+ LoopBreakerTarget.sin_addr.s_addr = inet_addr ("127.0.0.1");
322
+
323
+ srand ((int)time(NULL));
324
+ int i;
325
+ for (i=0; i < 100; i++) {
326
+ int r = (rand() % 10000) + 20000;
327
+ LoopBreakerTarget.sin_port = htons (r);
328
+ if (bind (sd, (struct sockaddr*)&LoopBreakerTarget, sizeof(LoopBreakerTarget)) == 0)
329
+ break;
330
+ }
331
+
332
+ if (i == 100)
333
+ throw std::runtime_error ("no loop breaker");
334
+ LoopBreakerReader = sd;
335
+ #endif
336
+ }
337
+
338
+ /***************************
339
+ EventMachine_t::_UpdateTime
340
+ ***************************/
341
+
342
+ void EventMachine_t::_UpdateTime()
343
+ {
344
+ MyCurrentLoopTime = GetRealTime();
345
+ }
346
+
347
+ /***************************
348
+ EventMachine_t::GetRealTime
349
+ ***************************/
350
+
351
+ uint64_t EventMachine_t::GetRealTime()
352
+ {
353
+ uint64_t current_time;
354
+ #if defined(OS_UNIX)
355
+ struct timeval tv;
356
+ gettimeofday (&tv, NULL);
357
+ current_time = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)(tv.tv_usec));
358
+
359
+ #elif defined(OS_WIN32)
360
+ unsigned tick = GetTickCount();
361
+ if (tick < LastTickCount)
362
+ TickCountTickover += 1;
363
+ LastTickCount = tick;
364
+ current_time = ((uint64_t)TickCountTickover << 32) + (uint64_t)tick;
365
+
366
+ #else
367
+ current_time = (uint64_t)time(NULL) * 1000000LL;
368
+ #endif
369
+ return current_time;
370
+ }
371
+
372
+ /***********************************
373
+ EventMachine_t::_DispatchHeartbeats
374
+ ***********************************/
375
+
376
+ void EventMachine_t::_DispatchHeartbeats()
377
+ {
378
+ while (true) {
379
+ multimap<uint64_t,EventableDescriptor*>::iterator i = Heartbeats.begin();
380
+ if (i == Heartbeats.end())
381
+ break;
382
+ if (i->first > MyCurrentLoopTime)
383
+ break;
384
+ EventableDescriptor *ed = i->second;
385
+ ed->Heartbeat();
386
+ QueueHeartbeat(ed);
387
+ }
388
+ }
389
+
390
+ /******************************
391
+ EventMachine_t::QueueHeartbeat
392
+ ******************************/
393
+
394
+ void EventMachine_t::QueueHeartbeat(EventableDescriptor *ed)
395
+ {
396
+ uint64_t heartbeat = ed->GetNextHeartbeat();
397
+
398
+ if (heartbeat) {
399
+ #ifndef HAVE_MAKE_PAIR
400
+ Heartbeats.insert (multimap<uint64_t,EventableDescriptor*>::value_type (heartbeat, ed));
401
+ #else
402
+ Heartbeats.insert (make_pair (heartbeat, ed));
403
+ #endif
404
+ }
405
+ }
406
+
407
+ /******************************
408
+ EventMachine_t::ClearHeartbeat
409
+ ******************************/
410
+
411
+ void EventMachine_t::ClearHeartbeat(uint64_t key)
412
+ {
413
+ Heartbeats.erase(key);
414
+ }
415
+
416
+ /*******************
417
+ EventMachine_t::Run
418
+ *******************/
419
+
420
+ void EventMachine_t::Run()
421
+ {
422
+ #ifdef OS_WIN32
423
+ HookControlC (true);
424
+ #endif
425
+
426
+ #ifdef HAVE_EPOLL
427
+ if (bEpoll) {
428
+ epfd = epoll_create (MaxEpollDescriptors);
429
+ if (epfd == -1) {
430
+ char buf[200];
431
+ snprintf (buf, sizeof(buf)-1, "unable to create epoll descriptor: %s", strerror(errno));
432
+ throw std::runtime_error (buf);
433
+ }
434
+ int cloexec = fcntl (epfd, F_GETFD, 0);
435
+ assert (cloexec >= 0);
436
+ cloexec |= FD_CLOEXEC;
437
+ fcntl (epfd, F_SETFD, cloexec);
438
+
439
+ assert (LoopBreakerReader >= 0);
440
+ LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
441
+ assert (ld);
442
+ Add (ld);
443
+ }
444
+ #endif
445
+
446
+ #ifdef HAVE_KQUEUE
447
+ if (bKqueue) {
448
+ kqfd = kqueue();
449
+ if (kqfd == -1) {
450
+ char buf[200];
451
+ snprintf (buf, sizeof(buf)-1, "unable to create kqueue descriptor: %s", strerror(errno));
452
+ throw std::runtime_error (buf);
453
+ }
454
+ // cloexec not needed. By definition, kqueues are not carried across forks.
455
+
456
+ assert (LoopBreakerReader >= 0);
457
+ LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
458
+ assert (ld);
459
+ Add (ld);
460
+ }
461
+ #endif
462
+
463
+ while (true) {
464
+ _UpdateTime();
465
+ if (!_RunTimers())
466
+ break;
467
+
468
+ /* _Add must precede _Modify because the same descriptor might
469
+ * be on both lists during the same pass through the machine,
470
+ * and to modify a descriptor before adding it would fail.
471
+ */
472
+ _AddNewDescriptors();
473
+ _ModifyDescriptors();
474
+
475
+ if (!_RunOnce())
476
+ break;
477
+ if (gTerminateSignalReceived)
478
+ break;
479
+ }
480
+
481
+ #ifdef OS_WIN32
482
+ HookControlC (false);
483
+ #endif
484
+ }
485
+
486
+
487
+ /************************
488
+ EventMachine_t::_RunOnce
489
+ ************************/
490
+
491
+ bool EventMachine_t::_RunOnce()
492
+ {
493
+ bool ret;
494
+ if (bEpoll)
495
+ ret = _RunEpollOnce();
496
+ else if (bKqueue)
497
+ ret = _RunKqueueOnce();
498
+ else
499
+ ret = _RunSelectOnce();
500
+ _DispatchHeartbeats();
501
+ _CleanupSockets();
502
+ return ret;
503
+ }
504
+
505
+
506
+
507
+ /*****************************
508
+ EventMachine_t::_RunEpollOnce
509
+ *****************************/
510
+
511
+ bool EventMachine_t::_RunEpollOnce()
512
+ {
513
+ #ifdef HAVE_EPOLL
514
+ assert (epfd != -1);
515
+ int s;
516
+
517
+ timeval tv = _TimeTilNextEvent();
518
+
519
+ #ifdef BUILD_FOR_RUBY
520
+ int ret = 0;
521
+ fd_set fdreads;
522
+
523
+ FD_ZERO(&fdreads);
524
+ FD_SET(epfd, &fdreads);
525
+
526
+ if ((ret = rb_thread_select(epfd + 1, &fdreads, NULL, NULL, &tv)) < 1) {
527
+ if (ret == -1) {
528
+ assert(errno != EINVAL);
529
+ assert(errno != EBADF);
530
+ }
531
+ return true;
532
+ }
533
+
534
+ TRAP_BEG;
535
+ s = epoll_wait (epfd, epoll_events, MaxEvents, 0);
536
+ TRAP_END;
537
+ #else
538
+ int duration = 0;
539
+ duration = duration + (tv.tv_sec * 1000);
540
+ duration = duration + (tv.tv_usec / 1000);
541
+ s = epoll_wait (epfd, epoll_events, MaxEvents, duration);
542
+ #endif
543
+
544
+ if (s > 0) {
545
+ for (int i=0; i < s; i++) {
546
+ EventableDescriptor *ed = (EventableDescriptor*) epoll_events[i].data.ptr;
547
+
548
+ if (ed->IsWatchOnly() && ed->GetSocket() == INVALID_SOCKET)
549
+ continue;
550
+
551
+ assert(ed->GetSocket() != INVALID_SOCKET);
552
+
553
+ if (epoll_events[i].events & EPOLLIN)
554
+ ed->Read();
555
+ if (epoll_events[i].events & EPOLLOUT)
556
+ ed->Write();
557
+ if (epoll_events[i].events & (EPOLLERR | EPOLLHUP))
558
+ ed->HandleError();
559
+ }
560
+ }
561
+ else if (s < 0) {
562
+ // epoll_wait can fail on error in a handful of ways.
563
+ // If this happens, then wait for a little while to avoid busy-looping.
564
+ // If the error was EINTR, we probably caught SIGCHLD or something,
565
+ // so keep the wait short.
566
+ timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
567
+ EmSelect (0, NULL, NULL, NULL, &tv);
568
+ }
569
+
570
+ return true;
571
+ #else
572
+ throw std::runtime_error ("epoll is not implemented on this platform");
573
+ #endif
574
+ }
575
+
576
+
577
+ /******************************
578
+ EventMachine_t::_RunKqueueOnce
579
+ ******************************/
580
+
581
+ bool EventMachine_t::_RunKqueueOnce()
582
+ {
583
+ #ifdef HAVE_KQUEUE
584
+ assert (kqfd != -1);
585
+ int k;
586
+
587
+ timeval tv = _TimeTilNextEvent();
588
+
589
+ #ifdef BUILD_FOR_RUBY
590
+ int ret = 0;
591
+ fd_set fdreads;
592
+
593
+ FD_ZERO(&fdreads);
594
+ FD_SET(kqfd, &fdreads);
595
+
596
+ if ((ret = rb_thread_select(kqfd + 1, &fdreads, NULL, NULL, &tv)) < 1) {
597
+ return true;
598
+ }
599
+
600
+ TRAP_BEG;
601
+ k = kevent (kqfd, NULL, 0, Karray, MaxEvents, NULL);
602
+ TRAP_END;
603
+ #else
604
+ struct timespec ts;
605
+ ts.tv_sec = tv.tv_sec;
606
+ ts.tv_nsec = tv.tv_usec * 1000;
607
+ k = kevent (kqfd, NULL, 0, Karray, MaxEvents, &ts);
608
+ #endif
609
+
610
+ struct kevent *ke = Karray;
611
+ while (k > 0) {
612
+ switch (ke->filter)
613
+ {
614
+ case EVFILT_VNODE:
615
+ _HandleKqueueFileEvent (ke);
616
+ break;
617
+
618
+ case EVFILT_PROC:
619
+ _HandleKqueuePidEvent (ke);
620
+ break;
621
+
622
+ case EVFILT_READ:
623
+ case EVFILT_WRITE:
624
+ EventableDescriptor *ed = (EventableDescriptor*) (ke->udata);
625
+ assert (ed);
626
+
627
+ if (ed->IsWatchOnly() && ed->GetSocket() == INVALID_SOCKET)
628
+ break;
629
+
630
+ if (ke->filter == EVFILT_READ)
631
+ ed->Read();
632
+ else if (ke->filter == EVFILT_WRITE)
633
+ ed->Write();
634
+ else
635
+ cerr << "Discarding unknown kqueue event " << ke->filter << endl;
636
+
637
+ break;
638
+ }
639
+
640
+ --k;
641
+ ++ke;
642
+ }
643
+
644
+ // TODO, replace this with rb_thread_blocking_region for 1.9 builds.
645
+ #ifdef BUILD_FOR_RUBY
646
+ if (!rb_thread_alone()) {
647
+ rb_thread_schedule();
648
+ }
649
+ #endif
650
+
651
+ return true;
652
+ #else
653
+ throw std::runtime_error ("kqueue is not implemented on this platform");
654
+ #endif
655
+ }
656
+
657
+
658
+ /*********************************
659
+ EventMachine_t::_TimeTilNextEvent
660
+ *********************************/
661
+
662
+ timeval EventMachine_t::_TimeTilNextEvent()
663
+ {
664
+ uint64_t next_event = 0;
665
+
666
+ if (!Heartbeats.empty()) {
667
+ multimap<uint64_t,EventableDescriptor*>::iterator heartbeats = Heartbeats.begin();
668
+ next_event = heartbeats->first;
669
+ }
670
+
671
+ if (!Timers.empty()) {
672
+ multimap<uint64_t,Timer_t>::iterator timers = Timers.begin();
673
+ if (next_event == 0 || timers->first < next_event)
674
+ next_event = timers->first;
675
+ }
676
+
677
+ if (!NewDescriptors.empty() || !ModifiedDescriptors.empty()) {
678
+ next_event = MyCurrentLoopTime;
679
+ }
680
+
681
+ timeval tv;
682
+
683
+ if (next_event == 0) {
684
+ tv = Quantum;
685
+ } else {
686
+ if (next_event > MyCurrentLoopTime) {
687
+ uint64_t duration = next_event - MyCurrentLoopTime;
688
+ tv.tv_sec = duration / 1000000;
689
+ tv.tv_usec = duration % 1000000;
690
+ } else {
691
+ tv.tv_sec = tv.tv_usec = 0;
692
+ }
693
+ }
694
+
695
+ return tv;
696
+ }
697
+
698
+ /*******************************
699
+ EventMachine_t::_CleanupSockets
700
+ *******************************/
701
+
702
+ void EventMachine_t::_CleanupSockets()
703
+ {
704
+ // TODO, rip this out and only delete the descriptors we know have died,
705
+ // rather than traversing the whole list.
706
+ // Modified 05Jan08 per suggestions by Chris Heath. It's possible that
707
+ // an EventableDescriptor will have a descriptor value of -1. That will
708
+ // happen if EventableDescriptor::Close was called on it. In that case,
709
+ // don't call epoll_ctl to remove the socket's filters from the epoll set.
710
+ // According to the epoll docs, this happens automatically when the
711
+ // descriptor is closed anyway. This is different from the case where
712
+ // the socket has already been closed but the descriptor in the ED object
713
+ // hasn't yet been set to INVALID_SOCKET.
714
+ // In kqueue, closing a descriptor automatically removes its event filters.
715
+ int i, j;
716
+ int nSockets = Descriptors.size();
717
+ for (i=0, j=0; i < nSockets; i++) {
718
+ EventableDescriptor *ed = Descriptors[i];
719
+ assert (ed);
720
+ if (ed->ShouldDelete()) {
721
+ #ifdef HAVE_EPOLL
722
+ if (bEpoll) {
723
+ assert (epfd != -1);
724
+ if (ed->GetSocket() != INVALID_SOCKET) {
725
+ int e = epoll_ctl (epfd, EPOLL_CTL_DEL, ed->GetSocket(), ed->GetEpollEvent());
726
+ // ENOENT or EBADF are not errors because the socket may be already closed when we get here.
727
+ if (e && (errno != ENOENT) && (errno != EBADF) && (errno != EPERM)) {
728
+ char buf [200];
729
+ snprintf (buf, sizeof(buf)-1, "unable to delete epoll event: %s", strerror(errno));
730
+ throw std::runtime_error (buf);
731
+ }
732
+ }
733
+ ModifiedDescriptors.erase(ed);
734
+ }
735
+ #endif
736
+ delete ed;
737
+ }
738
+ else
739
+ Descriptors [j++] = ed;
740
+ }
741
+ while ((size_t)j < Descriptors.size())
742
+ Descriptors.pop_back();
743
+ }
744
+
745
+ /*********************************
746
+ EventMachine_t::_ModifyEpollEvent
747
+ *********************************/
748
+
749
+ void EventMachine_t::_ModifyEpollEvent (EventableDescriptor *ed)
750
+ {
751
+ #ifdef HAVE_EPOLL
752
+ if (bEpoll) {
753
+ assert (epfd != -1);
754
+ assert (ed);
755
+ assert (ed->GetSocket() != INVALID_SOCKET);
756
+ int e = epoll_ctl (epfd, EPOLL_CTL_MOD, ed->GetSocket(), ed->GetEpollEvent());
757
+ if (e) {
758
+ char buf [200];
759
+ snprintf (buf, sizeof(buf)-1, "unable to modify epoll event: %s", strerror(errno));
760
+ throw std::runtime_error (buf);
761
+ }
762
+ }
763
+ #endif
764
+ }
765
+
766
+
767
+
768
+ /**************************
769
+ SelectData_t::SelectData_t
770
+ **************************/
771
+
772
+ SelectData_t::SelectData_t()
773
+ {
774
+ maxsocket = 0;
775
+ FD_ZERO (&fdreads);
776
+ FD_ZERO (&fdwrites);
777
+ FD_ZERO (&fderrors);
778
+ }
779
+
780
+
781
+ #ifdef BUILD_FOR_RUBY
782
+ /*****************
783
+ _SelectDataSelect
784
+ *****************/
785
+
786
+ #ifdef HAVE_TBR
787
+ static VALUE _SelectDataSelect (void *v)
788
+ {
789
+ SelectData_t *sd = (SelectData_t*)v;
790
+ sd->nSockets = select (sd->maxsocket+1, &(sd->fdreads), &(sd->fdwrites), &(sd->fderrors), &(sd->tv));
791
+ return Qnil;
792
+ }
793
+ #endif
794
+
795
+ /*********************
796
+ SelectData_t::_Select
797
+ *********************/
798
+
799
+ int SelectData_t::_Select()
800
+ {
801
+ #ifdef HAVE_TBR
802
+ rb_thread_blocking_region (_SelectDataSelect, (void*)this, RUBY_UBF_IO, 0);
803
+ return nSockets;
804
+ #endif
805
+
806
+ #ifndef HAVE_TBR
807
+ return EmSelect (maxsocket+1, &fdreads, &fdwrites, &fderrors, &tv);
808
+ #endif
809
+ }
810
+ #endif
811
+
812
+
813
+
814
+ /******************************
815
+ EventMachine_t::_RunSelectOnce
816
+ ******************************/
817
+
818
+ bool EventMachine_t::_RunSelectOnce()
819
+ {
820
+ // Crank the event machine once.
821
+ // If there are no descriptors to process, then sleep
822
+ // for a few hundred mills to avoid busy-looping.
823
+ // Return T/F to indicate whether we should continue.
824
+ // This is based on a select loop. Alternately provide epoll
825
+ // if we know we're running on a 2.6 kernel.
826
+ // epoll will be effective if we provide it as an alternative,
827
+ // however it has the same problem interoperating with Ruby
828
+ // threads that select does.
829
+
830
+ //cerr << "X";
831
+
832
+ /* This protection is now obsolete, because we will ALWAYS
833
+ * have at least one descriptor (the loop-breaker) to read.
834
+ */
835
+ /*
836
+ if (Descriptors.size() == 0) {
837
+ #ifdef OS_UNIX
838
+ timeval tv = {0, 200 * 1000};
839
+ EmSelect (0, NULL, NULL, NULL, &tv);
840
+ return true;
841
+ #endif
842
+ #ifdef OS_WIN32
843
+ Sleep (200);
844
+ return true;
845
+ #endif
846
+ }
847
+ */
848
+
849
+ SelectData_t SelectData;
850
+ /*
851
+ fd_set fdreads, fdwrites;
852
+ FD_ZERO (&fdreads);
853
+ FD_ZERO (&fdwrites);
854
+
855
+ int maxsocket = 0;
856
+ */
857
+
858
+ // Always read the loop-breaker reader.
859
+ // Changed 23Aug06, provisionally implemented for Windows with a UDP socket
860
+ // running on localhost with a randomly-chosen port. (*Puke*)
861
+ // Windows has a version of the Unix pipe() library function, but it doesn't
862
+ // give you back descriptors that are selectable.
863
+ FD_SET (LoopBreakerReader, &(SelectData.fdreads));
864
+ if (SelectData.maxsocket < LoopBreakerReader)
865
+ SelectData.maxsocket = LoopBreakerReader;
866
+
867
+ // prepare the sockets for reading and writing
868
+ size_t i;
869
+ for (i = 0; i < Descriptors.size(); i++) {
870
+ EventableDescriptor *ed = Descriptors[i];
871
+ assert (ed);
872
+ int sd = ed->GetSocket();
873
+ if (ed->IsWatchOnly() && sd == INVALID_SOCKET)
874
+ continue;
875
+ assert (sd != INVALID_SOCKET);
876
+
877
+ if (ed->SelectForRead())
878
+ FD_SET (sd, &(SelectData.fdreads));
879
+ if (ed->SelectForWrite())
880
+ FD_SET (sd, &(SelectData.fdwrites));
881
+
882
+ #ifdef OS_WIN32
883
+ /* 21Sep09: on windows, a non-blocking connect() that fails does not come up as writable.
884
+ Instead, it is added to the error set. See http://www.mail-archive.com/openssl-users@openssl.org/msg58500.html
885
+ */
886
+ FD_SET (sd, &(SelectData.fderrors));
887
+ #endif
888
+
889
+ if (SelectData.maxsocket < sd)
890
+ SelectData.maxsocket = sd;
891
+ }
892
+
893
+
894
+ { // read and write the sockets
895
+ //timeval tv = {1, 0}; // Solaris fails if the microseconds member is >= 1000000.
896
+ //timeval tv = Quantum;
897
+ SelectData.tv = _TimeTilNextEvent();
898
+ int s = SelectData._Select();
899
+ //rb_thread_blocking_region(xxx,(void*)&SelectData,RUBY_UBF_IO,0);
900
+ //int s = EmSelect (SelectData.maxsocket+1, &(SelectData.fdreads), &(SelectData.fdwrites), NULL, &(SelectData.tv));
901
+ //int s = SelectData.nSockets;
902
+ if (s > 0) {
903
+ /* Changed 01Jun07. We used to handle the Loop-breaker right here.
904
+ * Now we do it AFTER all the regular descriptors. There's an
905
+ * incredibly important and subtle reason for this. Code on
906
+ * loop breakers is sometimes used to cause the reactor core to
907
+ * cycle (for example, to allow outbound network buffers to drain).
908
+ * If a loop-breaker handler reschedules itself (say, after determining
909
+ * that the write buffers are still too full), then it will execute
910
+ * IMMEDIATELY if _ReadLoopBreaker is done here instead of after
911
+ * the other descriptors are processed. That defeats the whole purpose.
912
+ */
913
+ for (i=0; i < Descriptors.size(); i++) {
914
+ EventableDescriptor *ed = Descriptors[i];
915
+ assert (ed);
916
+ int sd = ed->GetSocket();
917
+ if (ed->IsWatchOnly() && sd == INVALID_SOCKET)
918
+ continue;
919
+ assert (sd != INVALID_SOCKET);
920
+
921
+ if (FD_ISSET (sd, &(SelectData.fdwrites)))
922
+ ed->Write();
923
+ if (FD_ISSET (sd, &(SelectData.fdreads)))
924
+ ed->Read();
925
+ if (FD_ISSET (sd, &(SelectData.fderrors)))
926
+ ed->HandleError();
927
+ }
928
+
929
+ if (FD_ISSET (LoopBreakerReader, &(SelectData.fdreads)))
930
+ _ReadLoopBreaker();
931
+ }
932
+ else if (s < 0) {
933
+ switch (errno) {
934
+ case EBADF:
935
+ _CleanBadDescriptors();
936
+ break;
937
+ case EINVAL:
938
+ throw std::runtime_error ("Somehow EM passed an invalid nfds or invalid timeout to select(2), please report this!");
939
+ break;
940
+ default:
941
+ // select can fail on error in a handful of ways.
942
+ // If this happens, then wait for a little while to avoid busy-looping.
943
+ // If the error was EINTR, we probably caught SIGCHLD or something,
944
+ // so keep the wait short.
945
+ timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
946
+ EmSelect (0, NULL, NULL, NULL, &tv);
947
+ }
948
+ }
949
+ }
950
+
951
+ return true;
952
+ }
953
+
954
+ void EventMachine_t::_CleanBadDescriptors()
955
+ {
956
+ size_t i;
957
+
958
+ for (i = 0; i < Descriptors.size(); i++) {
959
+ EventableDescriptor *ed = Descriptors[i];
960
+ if (ed->ShouldDelete())
961
+ continue;
962
+
963
+ int sd = ed->GetSocket();
964
+
965
+ struct timeval tv;
966
+ tv.tv_sec = 0;
967
+ tv.tv_usec = 0;
968
+
969
+ fd_set fds;
970
+ FD_ZERO(&fds);
971
+ FD_SET(sd, &fds);
972
+
973
+ int ret = select(sd + 1, &fds, NULL, NULL, &tv);
974
+
975
+ if (ret == -1) {
976
+ if (errno == EBADF)
977
+ ed->ScheduleClose(false);
978
+ }
979
+ }
980
+ }
981
+
982
+ /********************************
983
+ EventMachine_t::_ReadLoopBreaker
984
+ ********************************/
985
+
986
+ void EventMachine_t::_ReadLoopBreaker()
987
+ {
988
+ /* The loop breaker has selected readable.
989
+ * Read it ONCE (it may block if we try to read it twice)
990
+ * and send a loop-break event back to user code.
991
+ */
992
+ char buffer [1024];
993
+ read (LoopBreakerReader, buffer, sizeof(buffer));
994
+ if (EventCallback)
995
+ (*EventCallback)(0, EM_LOOPBREAK_SIGNAL, "", 0);
996
+ }
997
+
998
+
999
+ /**************************
1000
+ EventMachine_t::_RunTimers
1001
+ **************************/
1002
+
1003
+ bool EventMachine_t::_RunTimers()
1004
+ {
1005
+ // These are caller-defined timer handlers.
1006
+ // Return T/F to indicate whether we should continue the main loop.
1007
+ // We rely on the fact that multimaps sort by their keys to avoid
1008
+ // inspecting the whole list every time we come here.
1009
+ // Just keep inspecting and processing the list head until we hit
1010
+ // one that hasn't expired yet.
1011
+
1012
+ while (true) {
1013
+ multimap<uint64_t,Timer_t>::iterator i = Timers.begin();
1014
+ if (i == Timers.end())
1015
+ break;
1016
+ if (i->first > MyCurrentLoopTime)
1017
+ break;
1018
+ if (EventCallback)
1019
+ (*EventCallback) (0, EM_TIMER_FIRED, NULL, i->second.GetBinding());
1020
+ Timers.erase (i);
1021
+ }
1022
+ return true;
1023
+ }
1024
+
1025
+
1026
+
1027
+ /***********************************
1028
+ EventMachine_t::InstallOneshotTimer
1029
+ ***********************************/
1030
+
1031
+ const unsigned long EventMachine_t::InstallOneshotTimer (int milliseconds)
1032
+ {
1033
+ if (Timers.size() > MaxOutstandingTimers)
1034
+ return false;
1035
+ // Don't use the global loop-time variable here, because we might
1036
+ // get called before the main event machine is running.
1037
+
1038
+ // XXX This should be replaced with a call to _GetRealTime(), but I don't
1039
+ // understand if this is a bug or not? For OS_UNIX we multiply the argument
1040
+ // milliseconds by 1000, but for OS_WIN32 we do not? This needs to be sorted out.
1041
+ #ifdef OS_UNIX
1042
+ struct timeval tv;
1043
+ gettimeofday (&tv, NULL);
1044
+ uint64_t fire_at = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)(tv.tv_usec));
1045
+ fire_at += ((uint64_t)milliseconds) * 1000LL;
1046
+ #endif
1047
+
1048
+ #ifdef OS_WIN32
1049
+ unsigned tick = GetTickCount();
1050
+ if (tick < LastTickCount)
1051
+ TickCountTickover += 1;
1052
+ LastTickCount = tick;
1053
+
1054
+ uint64_t fire_at = ((uint64_t)TickCountTickover << 32) + (uint64_t)tick;
1055
+ fire_at += (uint64_t)milliseconds;
1056
+ #endif
1057
+
1058
+ Timer_t t;
1059
+ #ifndef HAVE_MAKE_PAIR
1060
+ multimap<uint64_t,Timer_t>::iterator i = Timers.insert (multimap<uint64_t,Timer_t>::value_type (fire_at, t));
1061
+ #else
1062
+ multimap<uint64_t,Timer_t>::iterator i = Timers.insert (make_pair (fire_at, t));
1063
+ #endif
1064
+ return i->second.GetBinding();
1065
+ }
1066
+
1067
+
1068
+ /*******************************
1069
+ EventMachine_t::ConnectToServer
1070
+ *******************************/
1071
+
1072
+ const unsigned long EventMachine_t::ConnectToServer (const char *bind_addr, int bind_port, const char *server, int port)
1073
+ {
1074
+ /* We want to spend no more than a few seconds waiting for a connection
1075
+ * to a remote host. So we use a nonblocking connect.
1076
+ * Linux disobeys the usual rules for nonblocking connects.
1077
+ * Per Stevens (UNP p.410), you expect a nonblocking connect to select
1078
+ * both readable and writable on error, and not to return EINPROGRESS
1079
+ * if the connect can be fulfilled immediately. Linux violates both
1080
+ * of these expectations.
1081
+ * Any kind of nonblocking connect on Linux returns EINPROGRESS.
1082
+ * The socket will then return writable when the disposition of the
1083
+ * connect is known, but it will not also be readable in case of
1084
+ * error! Weirdly, it will be readable in case there is data to read!!!
1085
+ * (Which can happen with protocols like SSH and SMTP.)
1086
+ * I suppose if you were so inclined you could consider this logical,
1087
+ * but it's not the way Unix has historically done it.
1088
+ * So we ignore the readable flag and read getsockopt to see if there
1089
+ * was an error connecting. A select timeout works as expected.
1090
+ * In regard to getsockopt: Linux does the Berkeley-style thing,
1091
+ * not the Solaris-style, and returns zero with the error code in
1092
+ * the error parameter.
1093
+ * Return the binding-text of the newly-created pending connection,
1094
+ * or NULL if there was a problem.
1095
+ */
1096
+
1097
+ if (!server || !*server || !port)
1098
+ throw std::runtime_error ("invalid server or port");
1099
+
1100
+ int family, bind_size;
1101
+ struct sockaddr bind_as, *bind_as_ptr = name2address (server, port, &family, &bind_size);
1102
+ if (!bind_as_ptr)
1103
+ throw std::runtime_error ("unable to resolve server address");
1104
+ bind_as = *bind_as_ptr; // copy because name2address points to a static
1105
+
1106
+ int sd = socket (family, SOCK_STREAM, 0);
1107
+ if (sd == INVALID_SOCKET) {
1108
+ char buf [200];
1109
+ snprintf (buf, sizeof(buf)-1, "unable to create new socket: %s", strerror(errno));
1110
+ throw std::runtime_error (buf);
1111
+ }
1112
+
1113
+ /*
1114
+ sockaddr_in pin;
1115
+ unsigned long HostAddr;
1116
+
1117
+ HostAddr = inet_addr (server);
1118
+ if (HostAddr == INADDR_NONE) {
1119
+ hostent *hp = gethostbyname ((char*)server); // Windows requires (char*)
1120
+ if (!hp) {
1121
+ // TODO: This gives the caller a fatal error. Not good.
1122
+ // They can respond by catching RuntimeError (blecch).
1123
+ // Possibly we need to fire an unbind event and provide
1124
+ // a status code so user code can detect the cause of the
1125
+ // failure.
1126
+ return NULL;
1127
+ }
1128
+ HostAddr = ((in_addr*)(hp->h_addr))->s_addr;
1129
+ }
1130
+
1131
+ memset (&pin, 0, sizeof(pin));
1132
+ pin.sin_family = AF_INET;
1133
+ pin.sin_addr.s_addr = HostAddr;
1134
+ pin.sin_port = htons (port);
1135
+
1136
+ int sd = socket (AF_INET, SOCK_STREAM, 0);
1137
+ if (sd == INVALID_SOCKET)
1138
+ return NULL;
1139
+ */
1140
+
1141
+ // From here on, ALL error returns must close the socket.
1142
+ // Set the new socket nonblocking.
1143
+ if (!SetSocketNonblocking (sd)) {
1144
+ close (sd);
1145
+ throw std::runtime_error ("unable to set socket as non-blocking");
1146
+ }
1147
+ // Disable slow-start (Nagle algorithm).
1148
+ int one = 1;
1149
+ setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (char*) &one, sizeof(one));
1150
+ // Set reuseaddr to improve performance on restarts
1151
+ setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char*) &one, sizeof(one));
1152
+
1153
+ if (bind_addr) {
1154
+ int bind_to_size, bind_to_family;
1155
+ struct sockaddr *bind_to = name2address (bind_addr, bind_port, &bind_to_family, &bind_to_size);
1156
+ if (!bind_to) {
1157
+ close (sd);
1158
+ throw std::runtime_error ("invalid bind address");
1159
+ }
1160
+ if (bind (sd, bind_to, bind_to_size) < 0) {
1161
+ close (sd);
1162
+ throw std::runtime_error ("couldn't bind to address");
1163
+ }
1164
+ }
1165
+
1166
+ unsigned long out = 0;
1167
+
1168
+ #ifdef OS_UNIX
1169
+ //if (connect (sd, (sockaddr*)&pin, sizeof pin) == 0) {
1170
+ if (connect (sd, &bind_as, bind_size) == 0) {
1171
+ // This is a connect success, which Linux appears
1172
+ // never to give when the socket is nonblocking,
1173
+ // even if the connection is intramachine or to
1174
+ // localhost.
1175
+
1176
+ /* Changed this branch 08Aug06. Evidently some kernels
1177
+ * (FreeBSD for example) will actually return success from
1178
+ * a nonblocking connect. This is a pretty simple case,
1179
+ * just set up the new connection and clear the pending flag.
1180
+ * Thanks to Chris Ochs for helping track this down.
1181
+ * This branch never gets taken on Linux or (oddly) OSX.
1182
+ * The original behavior was to throw an unimplemented,
1183
+ * which the user saw as a fatal exception. Very unfriendly.
1184
+ *
1185
+ * Tweaked 10Aug06. Even though the connect disposition is
1186
+ * known, we still set the connect-pending flag. That way
1187
+ * some needed initialization will happen in the ConnectionDescriptor.
1188
+ * (To wit, the ConnectionCompleted event gets sent to the client.)
1189
+ */
1190
+ ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
1191
+ if (!cd)
1192
+ throw std::runtime_error ("no connection allocated");
1193
+ cd->SetConnectPending (true);
1194
+ Add (cd);
1195
+ out = cd->GetBinding();
1196
+ }
1197
+ else if (errno == EINPROGRESS) {
1198
+ // Errno will generally always be EINPROGRESS, but on Linux
1199
+ // we have to look at getsockopt to be sure what really happened.
1200
+ int error;
1201
+ socklen_t len;
1202
+ len = sizeof(error);
1203
+ int o = getsockopt (sd, SOL_SOCKET, SO_ERROR, &error, &len);
1204
+ if ((o == 0) && (error == 0)) {
1205
+ // Here, there's no disposition.
1206
+ // Put the connection on the stack and wait for it to complete
1207
+ // or time out.
1208
+ ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
1209
+ if (!cd)
1210
+ throw std::runtime_error ("no connection allocated");
1211
+ cd->SetConnectPending (true);
1212
+ Add (cd);
1213
+ out = cd->GetBinding();
1214
+ }
1215
+ }
1216
+ else {
1217
+ // The error from connect was something other then EINPROGRESS (EHOSTDOWN, etc).
1218
+ // Fall through to the !out case below
1219
+ }
1220
+
1221
+ if (!out) {
1222
+ /* This could be connection refused or some such thing.
1223
+ * We will come here on Linux if a localhost connection fails.
1224
+ * Changed 16Jul06: Originally this branch was a no-op, and
1225
+ * we'd drop down to the end of the method, close the socket,
1226
+ * and return NULL, which would cause the caller to GET A
1227
+ * FATAL EXCEPTION. Now we keep the socket around but schedule an
1228
+ * immediate close on it, so the caller will get a close-event
1229
+ * scheduled on it. This was only an issue for localhost connections
1230
+ * to non-listening ports. We may eventually need to revise this
1231
+ * revised behavior, in case it causes problems like making it hard
1232
+ * for people to know that a failure occurred.
1233
+ */
1234
+ ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
1235
+ if (!cd)
1236
+ throw std::runtime_error ("no connection allocated");
1237
+ cd->ScheduleClose (false);
1238
+ Add (cd);
1239
+ out = cd->GetBinding();
1240
+ }
1241
+ #endif
1242
+
1243
+ #ifdef OS_WIN32
1244
+ //if (connect (sd, (sockaddr*)&pin, sizeof pin) == 0) {
1245
+ if (connect (sd, &bind_as, bind_size) == 0) {
1246
+ // This is a connect success, which Windows appears
1247
+ // never to give when the socket is nonblocking,
1248
+ // even if the connection is intramachine or to
1249
+ // localhost.
1250
+ throw std::runtime_error ("unimplemented");
1251
+ }
1252
+ else if (WSAGetLastError() == WSAEWOULDBLOCK) {
1253
+ // Here, there's no disposition.
1254
+ // Windows appears not to surface refused connections or
1255
+ // such stuff at this point.
1256
+ // Put the connection on the stack and wait for it to complete
1257
+ // or time out.
1258
+ ConnectionDescriptor *cd = new ConnectionDescriptor (sd, this);
1259
+ if (!cd)
1260
+ throw std::runtime_error ("no connection allocated");
1261
+ cd->SetConnectPending (true);
1262
+ Add (cd);
1263
+ out = cd->GetBinding();
1264
+ }
1265
+ else {
1266
+ // The error from connect was something other then WSAEWOULDBLOCK.
1267
+ }
1268
+
1269
+ #endif
1270
+
1271
+ if (!out)
1272
+ close (sd);
1273
+ return out;
1274
+ }
1275
+
1276
+ /***********************************
1277
+ EventMachine_t::ConnectToUnixServer
1278
+ ***********************************/
1279
+
1280
+ const unsigned long EventMachine_t::ConnectToUnixServer (const char *server)
1281
+ {
1282
+ /* Connect to a Unix-domain server, which by definition is running
1283
+ * on the same host.
1284
+ * There is no meaningful implementation on Windows.
1285
+ * There's no need to do a nonblocking connect, since the connection
1286
+ * is always local and can always be fulfilled immediately.
1287
+ */
1288
+
1289
+ #ifdef OS_WIN32
1290
+ throw std::runtime_error ("unix-domain connection unavailable on this platform");
1291
+ return NULL;
1292
+ #endif
1293
+
1294
+ // The whole rest of this function is only compiled on Unix systems.
1295
+ #ifdef OS_UNIX
1296
+
1297
+ unsigned long out = 0;
1298
+
1299
+ if (!server || !*server)
1300
+ return 0;
1301
+
1302
+ sockaddr_un pun;
1303
+ memset (&pun, 0, sizeof(pun));
1304
+ pun.sun_family = AF_LOCAL;
1305
+
1306
+ // You ordinarily expect the server name field to be at least 1024 bytes long,
1307
+ // but on Linux it can be MUCH shorter.
1308
+ if (strlen(server) >= sizeof(pun.sun_path))
1309
+ throw std::runtime_error ("unix-domain server name is too long");
1310
+
1311
+
1312
+ strcpy (pun.sun_path, server);
1313
+
1314
+ int fd = socket (AF_LOCAL, SOCK_STREAM, 0);
1315
+ if (fd == INVALID_SOCKET)
1316
+ return 0;
1317
+
1318
+ // From here on, ALL error returns must close the socket.
1319
+ // NOTE: At this point, the socket is still a blocking socket.
1320
+ if (connect (fd, (struct sockaddr*)&pun, sizeof(pun)) != 0) {
1321
+ close (fd);
1322
+ return 0;
1323
+ }
1324
+
1325
+ // Set the newly-connected socket nonblocking.
1326
+ if (!SetSocketNonblocking (fd)) {
1327
+ close (fd);
1328
+ return 0;
1329
+ }
1330
+
1331
+ // Set up a connection descriptor and add it to the event-machine.
1332
+ // Observe, even though we know the connection status is connect-success,
1333
+ // we still set the "pending" flag, so some needed initializations take
1334
+ // place.
1335
+ ConnectionDescriptor *cd = new ConnectionDescriptor (fd, this);
1336
+ if (!cd)
1337
+ throw std::runtime_error ("no connection allocated");
1338
+ cd->SetConnectPending (true);
1339
+ Add (cd);
1340
+ out = cd->GetBinding();
1341
+
1342
+ if (!out)
1343
+ close (fd);
1344
+
1345
+ return out;
1346
+ #endif
1347
+ }
1348
+
1349
+ /************************
1350
+ EventMachine_t::AttachFD
1351
+ ************************/
1352
+
1353
+ const unsigned long EventMachine_t::AttachFD (int fd, bool watch_mode)
1354
+ {
1355
+ #ifdef OS_UNIX
1356
+ if (fcntl(fd, F_GETFL, 0) < 0)
1357
+ throw std::runtime_error ("invalid file descriptor");
1358
+ #endif
1359
+
1360
+ #ifdef OS_WIN32
1361
+ // TODO: add better check for invalid file descriptors (see ioctlsocket or getsockopt)
1362
+ if (fd == INVALID_SOCKET)
1363
+ throw std::runtime_error ("invalid file descriptor");
1364
+ #endif
1365
+
1366
+ {// Check for duplicate descriptors
1367
+ size_t i;
1368
+ for (i = 0; i < Descriptors.size(); i++) {
1369
+ EventableDescriptor *ed = Descriptors[i];
1370
+ assert (ed);
1371
+ if (ed->GetSocket() == fd)
1372
+ throw std::runtime_error ("adding existing descriptor");
1373
+ }
1374
+
1375
+ for (i = 0; i < NewDescriptors.size(); i++) {
1376
+ EventableDescriptor *ed = NewDescriptors[i];
1377
+ assert (ed);
1378
+ if (ed->GetSocket() == fd)
1379
+ throw std::runtime_error ("adding existing new descriptor");
1380
+ }
1381
+ }
1382
+
1383
+ if (!watch_mode)
1384
+ SetSocketNonblocking(fd);
1385
+
1386
+ ConnectionDescriptor *cd = new ConnectionDescriptor (fd, this);
1387
+ if (!cd)
1388
+ throw std::runtime_error ("no connection allocated");
1389
+
1390
+ cd->SetWatchOnly(watch_mode);
1391
+ cd->SetConnectPending (false);
1392
+
1393
+ Add (cd);
1394
+
1395
+ const unsigned long out = cd->GetBinding();
1396
+ return out;
1397
+ }
1398
+
1399
+ /************************
1400
+ EventMachine_t::DetachFD
1401
+ ************************/
1402
+
1403
+ int EventMachine_t::DetachFD (EventableDescriptor *ed)
1404
+ {
1405
+ if (!ed)
1406
+ throw std::runtime_error ("detaching bad descriptor");
1407
+
1408
+ int fd = ed->GetSocket();
1409
+
1410
+ #ifdef HAVE_EPOLL
1411
+ if (bEpoll) {
1412
+ if (ed->GetSocket() != INVALID_SOCKET) {
1413
+ assert (epfd != -1);
1414
+ int e = epoll_ctl (epfd, EPOLL_CTL_DEL, ed->GetSocket(), ed->GetEpollEvent());
1415
+ // ENOENT or EBADF are not errors because the socket may be already closed when we get here.
1416
+ if (e && (errno != ENOENT) && (errno != EBADF)) {
1417
+ char buf [200];
1418
+ snprintf (buf, sizeof(buf)-1, "unable to delete epoll event: %s", strerror(errno));
1419
+ throw std::runtime_error (buf);
1420
+ }
1421
+ }
1422
+ }
1423
+ #endif
1424
+
1425
+ #ifdef HAVE_KQUEUE
1426
+ if (bKqueue) {
1427
+ // remove any read/write events for this fd
1428
+ struct kevent k;
1429
+ EV_SET (&k, ed->GetSocket(), EVFILT_READ | EVFILT_WRITE, EV_DELETE, 0, 0, ed);
1430
+ int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
1431
+ if (t < 0 && (errno != ENOENT) && (errno != EBADF)) {
1432
+ char buf [200];
1433
+ snprintf (buf, sizeof(buf)-1, "unable to delete kqueue event: %s", strerror(errno));
1434
+ throw std::runtime_error (buf);
1435
+ }
1436
+ }
1437
+ #endif
1438
+
1439
+ // Prevent the descriptor from being modified, in case DetachFD was called from a timer or next_tick
1440
+ ModifiedDescriptors.erase (ed);
1441
+
1442
+ // Set MySocket = INVALID_SOCKET so ShouldDelete() is true (and the descriptor gets deleted and removed),
1443
+ // and also to prevent anyone from calling close() on the detached fd
1444
+ ed->SetSocketInvalid();
1445
+
1446
+ return fd;
1447
+ }
1448
+
1449
+ /************
1450
+ name2address
1451
+ ************/
1452
+
1453
+ struct sockaddr *name2address (const char *server, int port, int *family, int *bind_size)
1454
+ {
1455
+ // THIS IS NOT RE-ENTRANT OR THREADSAFE. Optimize for speed.
1456
+ // Check the more-common cases first.
1457
+ // Return NULL if no resolution.
1458
+
1459
+ static struct sockaddr_in in4;
1460
+ #ifndef __CYGWIN__
1461
+ static struct sockaddr_in6 in6;
1462
+ #endif
1463
+ struct hostent *hp;
1464
+
1465
+ if (!server || !*server)
1466
+ server = "0.0.0.0";
1467
+
1468
+ memset (&in4, 0, sizeof(in4));
1469
+ if ( (in4.sin_addr.s_addr = inet_addr (server)) != INADDR_NONE) {
1470
+ if (family)
1471
+ *family = AF_INET;
1472
+ if (bind_size)
1473
+ *bind_size = sizeof(in4);
1474
+ in4.sin_family = AF_INET;
1475
+ in4.sin_port = htons (port);
1476
+ return (struct sockaddr*)&in4;
1477
+ }
1478
+
1479
+ #if defined(OS_UNIX) && !defined(__CYGWIN__)
1480
+ memset (&in6, 0, sizeof(in6));
1481
+ if (inet_pton (AF_INET6, server, in6.sin6_addr.s6_addr) > 0) {
1482
+ if (family)
1483
+ *family = AF_INET6;
1484
+ if (bind_size)
1485
+ *bind_size = sizeof(in6);
1486
+ in6.sin6_family = AF_INET6;
1487
+ in6.sin6_port = htons (port);
1488
+ return (struct sockaddr*)&in6;
1489
+ }
1490
+ #endif
1491
+
1492
+ #ifdef OS_WIN32
1493
+ // TODO, must complete this branch. Windows doesn't have inet_pton.
1494
+ // A possible approach is to make a getaddrinfo call with the supplied
1495
+ // server address, constraining the hints to ipv6 and seeing if we
1496
+ // get any addresses.
1497
+ // For the time being, Ipv6 addresses aren't supported on Windows.
1498
+ #endif
1499
+
1500
+ hp = gethostbyname ((char*)server); // Windows requires the cast.
1501
+ if (hp) {
1502
+ in4.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
1503
+ if (family)
1504
+ *family = AF_INET;
1505
+ if (bind_size)
1506
+ *bind_size = sizeof(in4);
1507
+ in4.sin_family = AF_INET;
1508
+ in4.sin_port = htons (port);
1509
+ return (struct sockaddr*)&in4;
1510
+ }
1511
+
1512
+ return NULL;
1513
+ }
1514
+
1515
+
1516
+ /*******************************
1517
+ EventMachine_t::CreateTcpServer
1518
+ *******************************/
1519
+
1520
+ const unsigned long EventMachine_t::CreateTcpServer (const char *server, int port)
1521
+ {
1522
+ /* Create a TCP-acceptor (server) socket and add it to the event machine.
1523
+ * Return the binding of the new acceptor to the caller.
1524
+ * This binding will be referenced when the new acceptor sends events
1525
+ * to indicate accepted connections.
1526
+ */
1527
+
1528
+
1529
+ int family, bind_size;
1530
+ struct sockaddr *bind_here = name2address (server, port, &family, &bind_size);
1531
+ if (!bind_here)
1532
+ return 0;
1533
+
1534
+ unsigned long output_binding = 0;
1535
+
1536
+ //struct sockaddr_in sin;
1537
+
1538
+ int sd_accept = socket (family, SOCK_STREAM, 0);
1539
+ if (sd_accept == INVALID_SOCKET) {
1540
+ goto fail;
1541
+ }
1542
+
1543
+ /*
1544
+ memset (&sin, 0, sizeof(sin));
1545
+ sin.sin_family = AF_INET;
1546
+ sin.sin_addr.s_addr = INADDR_ANY;
1547
+ sin.sin_port = htons (port);
1548
+
1549
+ if (server && *server) {
1550
+ sin.sin_addr.s_addr = inet_addr (server);
1551
+ if (sin.sin_addr.s_addr == INADDR_NONE) {
1552
+ hostent *hp = gethostbyname ((char*)server); // Windows requires the cast.
1553
+ if (hp == NULL) {
1554
+ //__warning ("hostname not resolved: ", server);
1555
+ goto fail;
1556
+ }
1557
+ sin.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
1558
+ }
1559
+ }
1560
+ */
1561
+
1562
+ { // set reuseaddr to improve performance on restarts.
1563
+ int oval = 1;
1564
+ if (setsockopt (sd_accept, SOL_SOCKET, SO_REUSEADDR, (char*)&oval, sizeof(oval)) < 0) {
1565
+ //__warning ("setsockopt failed while creating listener","");
1566
+ goto fail;
1567
+ }
1568
+ }
1569
+
1570
+ { // set CLOEXEC. Only makes sense on Unix
1571
+ #ifdef OS_UNIX
1572
+ int cloexec = fcntl (sd_accept, F_GETFD, 0);
1573
+ assert (cloexec >= 0);
1574
+ cloexec |= FD_CLOEXEC;
1575
+ fcntl (sd_accept, F_SETFD, cloexec);
1576
+ #endif
1577
+ }
1578
+
1579
+
1580
+ //if (bind (sd_accept, (struct sockaddr*)&sin, sizeof(sin))) {
1581
+ if (bind (sd_accept, bind_here, bind_size)) {
1582
+ //__warning ("binding failed");
1583
+ goto fail;
1584
+ }
1585
+
1586
+ if (listen (sd_accept, 100)) {
1587
+ //__warning ("listen failed");
1588
+ goto fail;
1589
+ }
1590
+
1591
+ {
1592
+ // Set the acceptor non-blocking.
1593
+ // THIS IS CRUCIALLY IMPORTANT because we read it in a select loop.
1594
+ if (!SetSocketNonblocking (sd_accept)) {
1595
+ //int val = fcntl (sd_accept, F_GETFL, 0);
1596
+ //if (fcntl (sd_accept, F_SETFL, val | O_NONBLOCK) == -1) {
1597
+ goto fail;
1598
+ }
1599
+ }
1600
+
1601
+ { // Looking good.
1602
+ AcceptorDescriptor *ad = new AcceptorDescriptor (sd_accept, this);
1603
+ if (!ad)
1604
+ throw std::runtime_error ("unable to allocate acceptor");
1605
+ Add (ad);
1606
+ output_binding = ad->GetBinding();
1607
+ }
1608
+
1609
+ return output_binding;
1610
+
1611
+ fail:
1612
+ if (sd_accept != INVALID_SOCKET)
1613
+ close (sd_accept);
1614
+ return 0;
1615
+ }
1616
+
1617
+
1618
+ /**********************************
1619
+ EventMachine_t::OpenDatagramSocket
1620
+ **********************************/
1621
+
1622
+ const unsigned long EventMachine_t::OpenDatagramSocket (const char *address, int port)
1623
+ {
1624
+ unsigned long output_binding = 0;
1625
+
1626
+ int sd = socket (AF_INET, SOCK_DGRAM, 0);
1627
+ if (sd == INVALID_SOCKET)
1628
+ goto fail;
1629
+ // from here on, early returns must close the socket!
1630
+
1631
+
1632
+ struct sockaddr_in sin;
1633
+ memset (&sin, 0, sizeof(sin));
1634
+ sin.sin_family = AF_INET;
1635
+ sin.sin_port = htons (port);
1636
+
1637
+
1638
+ if (address && *address) {
1639
+ sin.sin_addr.s_addr = inet_addr (address);
1640
+ if (sin.sin_addr.s_addr == INADDR_NONE) {
1641
+ hostent *hp = gethostbyname ((char*)address); // Windows requires the cast.
1642
+ if (hp == NULL)
1643
+ goto fail;
1644
+ sin.sin_addr.s_addr = ((in_addr*)(hp->h_addr))->s_addr;
1645
+ }
1646
+ }
1647
+ else
1648
+ sin.sin_addr.s_addr = htonl (INADDR_ANY);
1649
+
1650
+
1651
+ // Set the new socket nonblocking.
1652
+ {
1653
+ if (!SetSocketNonblocking (sd))
1654
+ //int val = fcntl (sd, F_GETFL, 0);
1655
+ //if (fcntl (sd, F_SETFL, val | O_NONBLOCK) == -1)
1656
+ goto fail;
1657
+ }
1658
+
1659
+ if (bind (sd, (struct sockaddr*)&sin, sizeof(sin)) != 0)
1660
+ goto fail;
1661
+
1662
+ { // Looking good.
1663
+ DatagramDescriptor *ds = new DatagramDescriptor (sd, this);
1664
+ if (!ds)
1665
+ throw std::runtime_error ("unable to allocate datagram-socket");
1666
+ Add (ds);
1667
+ output_binding = ds->GetBinding();
1668
+ }
1669
+
1670
+ return output_binding;
1671
+
1672
+ fail:
1673
+ if (sd != INVALID_SOCKET)
1674
+ close (sd);
1675
+ return 0;
1676
+ }
1677
+
1678
+
1679
+
1680
+ /*******************
1681
+ EventMachine_t::Add
1682
+ *******************/
1683
+
1684
+ void EventMachine_t::Add (EventableDescriptor *ed)
1685
+ {
1686
+ if (!ed)
1687
+ throw std::runtime_error ("added bad descriptor");
1688
+ ed->SetEventCallback (EventCallback);
1689
+ NewDescriptors.push_back (ed);
1690
+ }
1691
+
1692
+
1693
+ /*******************************
1694
+ EventMachine_t::ArmKqueueWriter
1695
+ *******************************/
1696
+
1697
+ void EventMachine_t::ArmKqueueWriter (EventableDescriptor *ed)
1698
+ {
1699
+ #ifdef HAVE_KQUEUE
1700
+ if (bKqueue) {
1701
+ if (!ed)
1702
+ throw std::runtime_error ("added bad descriptor");
1703
+ struct kevent k;
1704
+ EV_SET (&k, ed->GetSocket(), EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, ed);
1705
+ int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
1706
+ if (t < 0) {
1707
+ char buf [200];
1708
+ snprintf (buf, sizeof(buf)-1, "arm kqueue writer failed on %d: %s", ed->GetSocket(), strerror(errno));
1709
+ throw std::runtime_error (buf);
1710
+ }
1711
+ }
1712
+ #endif
1713
+ }
1714
+
1715
+ /*******************************
1716
+ EventMachine_t::ArmKqueueReader
1717
+ *******************************/
1718
+
1719
+ void EventMachine_t::ArmKqueueReader (EventableDescriptor *ed)
1720
+ {
1721
+ #ifdef HAVE_KQUEUE
1722
+ if (bKqueue) {
1723
+ if (!ed)
1724
+ throw std::runtime_error ("added bad descriptor");
1725
+ struct kevent k;
1726
+ EV_SET (&k, ed->GetSocket(), EVFILT_READ, EV_ADD, 0, 0, ed);
1727
+ int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
1728
+ if (t < 0) {
1729
+ char buf [200];
1730
+ snprintf (buf, sizeof(buf)-1, "arm kqueue reader failed on %d: %s", ed->GetSocket(), strerror(errno));
1731
+ throw std::runtime_error (buf);
1732
+ }
1733
+ }
1734
+ #endif
1735
+ }
1736
+
1737
+ /**********************************
1738
+ EventMachine_t::_AddNewDescriptors
1739
+ **********************************/
1740
+
1741
+ void EventMachine_t::_AddNewDescriptors()
1742
+ {
1743
+ /* Avoid adding descriptors to the main descriptor list
1744
+ * while we're actually traversing the list.
1745
+ * Any descriptors that are added as a result of processing timers
1746
+ * or acceptors should go on a temporary queue and then added
1747
+ * while we're not traversing the main list.
1748
+ * Also, it (rarely) happens that a newly-created descriptor
1749
+ * is immediately scheduled to close. It might be a good
1750
+ * idea not to bother scheduling these for I/O but if
1751
+ * we do that, we might bypass some important processing.
1752
+ */
1753
+
1754
+ for (size_t i = 0; i < NewDescriptors.size(); i++) {
1755
+ EventableDescriptor *ed = NewDescriptors[i];
1756
+ if (ed == NULL)
1757
+ throw std::runtime_error ("adding bad descriptor");
1758
+
1759
+ #if HAVE_EPOLL
1760
+ if (bEpoll) {
1761
+ assert (epfd != -1);
1762
+ int e = epoll_ctl (epfd, EPOLL_CTL_ADD, ed->GetSocket(), ed->GetEpollEvent());
1763
+ if (e) {
1764
+ char buf [200];
1765
+ snprintf (buf, sizeof(buf)-1, "unable to add new descriptor: %s", strerror(errno));
1766
+ throw std::runtime_error (buf);
1767
+ }
1768
+ }
1769
+ #endif
1770
+
1771
+ #if HAVE_KQUEUE
1772
+ /*
1773
+ if (bKqueue) {
1774
+ // INCOMPLETE. Some descriptors don't want to be readable.
1775
+ assert (kqfd != -1);
1776
+ struct kevent k;
1777
+ EV_SET (&k, ed->GetSocket(), EVFILT_READ, EV_ADD, 0, 0, ed);
1778
+ int t = kevent (kqfd, &k, 1, NULL, 0, NULL);
1779
+ assert (t == 0);
1780
+ }
1781
+ */
1782
+ #endif
1783
+
1784
+ QueueHeartbeat(ed);
1785
+ Descriptors.push_back (ed);
1786
+ }
1787
+ NewDescriptors.clear();
1788
+ }
1789
+
1790
+
1791
+ /**********************************
1792
+ EventMachine_t::_ModifyDescriptors
1793
+ **********************************/
1794
+
1795
+ void EventMachine_t::_ModifyDescriptors()
1796
+ {
1797
+ /* For implementations which don't level check every descriptor on
1798
+ * every pass through the machine, as select does.
1799
+ * If we're not selecting, then descriptors need a way to signal to the
1800
+ * machine that their readable or writable status has changed.
1801
+ * That's what the ::Modify call is for. We do it this way to avoid
1802
+ * modifying descriptors during the loop traversal, where it can easily
1803
+ * happen that an object (like a UDP socket) gets data written on it by
1804
+ * the application during #post_init. That would take place BEFORE the
1805
+ * descriptor even gets added to the epoll descriptor, so the modify
1806
+ * operation will crash messily.
1807
+ * Another really messy possibility is for a descriptor to put itself
1808
+ * on the Modified list, and then get deleted before we get here.
1809
+ * Remember, deletes happen after the I/O traversal and before the
1810
+ * next pass through here. So we have to make sure when we delete a
1811
+ * descriptor to remove it from the Modified list.
1812
+ */
1813
+
1814
+ #ifdef HAVE_EPOLL
1815
+ if (bEpoll) {
1816
+ set<EventableDescriptor*>::iterator i = ModifiedDescriptors.begin();
1817
+ while (i != ModifiedDescriptors.end()) {
1818
+ assert (*i);
1819
+ _ModifyEpollEvent (*i);
1820
+ ++i;
1821
+ }
1822
+ }
1823
+ #endif
1824
+
1825
+ ModifiedDescriptors.clear();
1826
+ }
1827
+
1828
+
1829
+ /**********************
1830
+ EventMachine_t::Modify
1831
+ **********************/
1832
+
1833
+ void EventMachine_t::Modify (EventableDescriptor *ed)
1834
+ {
1835
+ if (!ed)
1836
+ throw std::runtime_error ("modified bad descriptor");
1837
+ ModifiedDescriptors.insert (ed);
1838
+ }
1839
+
1840
+
1841
+ /***********************************
1842
+ EventMachine_t::_OpenFileForWriting
1843
+ ***********************************/
1844
+
1845
+ const unsigned long EventMachine_t::_OpenFileForWriting (const char *filename)
1846
+ {
1847
+ /*
1848
+ * Return the binding-text of the newly-opened file,
1849
+ * or NULL if there was a problem.
1850
+ */
1851
+
1852
+ if (!filename || !*filename)
1853
+ return 0;
1854
+
1855
+ int fd = open (filename, O_CREAT|O_TRUNC|O_WRONLY|O_NONBLOCK, 0644);
1856
+
1857
+ FileStreamDescriptor *fsd = new FileStreamDescriptor (fd, this);
1858
+ if (!fsd)
1859
+ throw std::runtime_error ("no file-stream allocated");
1860
+ Add (fsd);
1861
+ return fsd->GetBinding();
1862
+
1863
+ }
1864
+
1865
+
1866
+ /**************************************
1867
+ EventMachine_t::CreateUnixDomainServer
1868
+ **************************************/
1869
+
1870
+ const unsigned long EventMachine_t::CreateUnixDomainServer (const char *filename)
1871
+ {
1872
+ /* Create a UNIX-domain acceptor (server) socket and add it to the event machine.
1873
+ * Return the binding of the new acceptor to the caller.
1874
+ * This binding will be referenced when the new acceptor sends events
1875
+ * to indicate accepted connections.
1876
+ * THERE IS NO MEANINGFUL IMPLEMENTATION ON WINDOWS.
1877
+ */
1878
+
1879
+ #ifdef OS_WIN32
1880
+ throw std::runtime_error ("unix-domain server unavailable on this platform");
1881
+ #endif
1882
+
1883
+ // The whole rest of this function is only compiled on Unix systems.
1884
+ #ifdef OS_UNIX
1885
+ unsigned long output_binding = 0;
1886
+
1887
+ struct sockaddr_un s_sun;
1888
+
1889
+ int sd_accept = socket (AF_LOCAL, SOCK_STREAM, 0);
1890
+ if (sd_accept == INVALID_SOCKET) {
1891
+ goto fail;
1892
+ }
1893
+
1894
+ if (!filename || !*filename)
1895
+ goto fail;
1896
+ unlink (filename);
1897
+
1898
+ bzero (&s_sun, sizeof(s_sun));
1899
+ s_sun.sun_family = AF_LOCAL;
1900
+ strncpy (s_sun.sun_path, filename, sizeof(s_sun.sun_path)-1);
1901
+
1902
+ // don't bother with reuseaddr for a local socket.
1903
+
1904
+ { // set CLOEXEC. Only makes sense on Unix
1905
+ #ifdef OS_UNIX
1906
+ int cloexec = fcntl (sd_accept, F_GETFD, 0);
1907
+ assert (cloexec >= 0);
1908
+ cloexec |= FD_CLOEXEC;
1909
+ fcntl (sd_accept, F_SETFD, cloexec);
1910
+ #endif
1911
+ }
1912
+
1913
+ if (bind (sd_accept, (struct sockaddr*)&s_sun, sizeof(s_sun))) {
1914
+ //__warning ("binding failed");
1915
+ goto fail;
1916
+ }
1917
+
1918
+ if (listen (sd_accept, 100)) {
1919
+ //__warning ("listen failed");
1920
+ goto fail;
1921
+ }
1922
+
1923
+ {
1924
+ // Set the acceptor non-blocking.
1925
+ // THIS IS CRUCIALLY IMPORTANT because we read it in a select loop.
1926
+ if (!SetSocketNonblocking (sd_accept)) {
1927
+ //int val = fcntl (sd_accept, F_GETFL, 0);
1928
+ //if (fcntl (sd_accept, F_SETFL, val | O_NONBLOCK) == -1) {
1929
+ goto fail;
1930
+ }
1931
+ }
1932
+
1933
+ { // Looking good.
1934
+ AcceptorDescriptor *ad = new AcceptorDescriptor (sd_accept, this);
1935
+ if (!ad)
1936
+ throw std::runtime_error ("unable to allocate acceptor");
1937
+ Add (ad);
1938
+ output_binding = ad->GetBinding();
1939
+ }
1940
+
1941
+ return output_binding;
1942
+
1943
+ fail:
1944
+ if (sd_accept != INVALID_SOCKET)
1945
+ close (sd_accept);
1946
+ return 0;
1947
+ #endif // OS_UNIX
1948
+ }
1949
+
1950
+
1951
+ /*********************
1952
+ EventMachine_t::Popen
1953
+ *********************/
1954
+ #if OBSOLETE
1955
+ const char *EventMachine_t::Popen (const char *cmd, const char *mode)
1956
+ {
1957
+ #ifdef OS_WIN32
1958
+ throw std::runtime_error ("popen is currently unavailable on this platform");
1959
+ #endif
1960
+
1961
+ // The whole rest of this function is only compiled on Unix systems.
1962
+ // Eventually we need this functionality (or a full-duplex equivalent) on Windows.
1963
+ #ifdef OS_UNIX
1964
+ const char *output_binding = NULL;
1965
+
1966
+ FILE *fp = popen (cmd, mode);
1967
+ if (!fp)
1968
+ return NULL;
1969
+
1970
+ // From here, all early returns must pclose the stream.
1971
+
1972
+ // According to the pipe(2) manpage, descriptors returned from pipe have both
1973
+ // CLOEXEC and NONBLOCK clear. Do NOT set CLOEXEC. DO set nonblocking.
1974
+ if (!SetSocketNonblocking (fileno (fp))) {
1975
+ pclose (fp);
1976
+ return NULL;
1977
+ }
1978
+
1979
+ { // Looking good.
1980
+ PipeDescriptor *pd = new PipeDescriptor (fp, this);
1981
+ if (!pd)
1982
+ throw std::runtime_error ("unable to allocate pipe");
1983
+ Add (pd);
1984
+ output_binding = pd->GetBinding();
1985
+ }
1986
+
1987
+ return output_binding;
1988
+ #endif
1989
+ }
1990
+ #endif // OBSOLETE
1991
+
1992
+ /**************************
1993
+ EventMachine_t::Socketpair
1994
+ **************************/
1995
+
1996
+ const unsigned long EventMachine_t::Socketpair (char * const*cmd_strings)
1997
+ {
1998
+ #ifdef OS_WIN32
1999
+ throw std::runtime_error ("socketpair is currently unavailable on this platform");
2000
+ #endif
2001
+
2002
+ // The whole rest of this function is only compiled on Unix systems.
2003
+ // Eventually we need this functionality (or a full-duplex equivalent) on Windows.
2004
+ #ifdef OS_UNIX
2005
+ // Make sure the incoming array of command strings is sane.
2006
+ if (!cmd_strings)
2007
+ return 0;
2008
+ int j;
2009
+ for (j=0; j < 2048 && cmd_strings[j]; j++)
2010
+ ;
2011
+ if ((j==0) || (j==2048))
2012
+ return 0;
2013
+
2014
+ unsigned long output_binding = 0;
2015
+
2016
+ int sv[2];
2017
+ if (socketpair (AF_LOCAL, SOCK_STREAM, 0, sv) < 0)
2018
+ return 0;
2019
+ // from here, all early returns must close the pair of sockets.
2020
+
2021
+ // Set the parent side of the socketpair nonblocking.
2022
+ // We don't care about the child side, and most child processes will expect their
2023
+ // stdout to be blocking. Thanks to Duane Johnson and Bill Kelly for pointing this out.
2024
+ // Obviously DON'T set CLOEXEC.
2025
+ if (!SetSocketNonblocking (sv[0])) {
2026
+ close (sv[0]);
2027
+ close (sv[1]);
2028
+ return 0;
2029
+ }
2030
+
2031
+ pid_t f = fork();
2032
+ if (f > 0) {
2033
+ close (sv[1]);
2034
+ PipeDescriptor *pd = new PipeDescriptor (sv[0], f, this);
2035
+ if (!pd)
2036
+ throw std::runtime_error ("unable to allocate pipe");
2037
+ Add (pd);
2038
+ output_binding = pd->GetBinding();
2039
+ }
2040
+ else if (f == 0) {
2041
+ close (sv[0]);
2042
+ dup2 (sv[1], STDIN_FILENO);
2043
+ close (sv[1]);
2044
+ dup2 (STDIN_FILENO, STDOUT_FILENO);
2045
+ execvp (cmd_strings[0], cmd_strings+1);
2046
+ exit (-1); // end the child process if the exec doesn't work.
2047
+ }
2048
+ else
2049
+ throw std::runtime_error ("no fork");
2050
+
2051
+ return output_binding;
2052
+ #endif
2053
+ }
2054
+
2055
+
2056
+ /****************************
2057
+ EventMachine_t::OpenKeyboard
2058
+ ****************************/
2059
+
2060
+ const unsigned long EventMachine_t::OpenKeyboard()
2061
+ {
2062
+ KeyboardDescriptor *kd = new KeyboardDescriptor (this);
2063
+ if (!kd)
2064
+ throw std::runtime_error ("no keyboard-object allocated");
2065
+ Add (kd);
2066
+ return kd->GetBinding();
2067
+ }
2068
+
2069
+
2070
+ /**********************************
2071
+ EventMachine_t::GetConnectionCount
2072
+ **********************************/
2073
+
2074
+ int EventMachine_t::GetConnectionCount ()
2075
+ {
2076
+ return Descriptors.size() + NewDescriptors.size();
2077
+ }
2078
+
2079
+
2080
+ /************************
2081
+ EventMachine_t::WatchPid
2082
+ ************************/
2083
+
2084
+ const unsigned long EventMachine_t::WatchPid (int pid)
2085
+ {
2086
+ #ifdef HAVE_KQUEUE
2087
+ if (!bKqueue)
2088
+ throw std::runtime_error("must enable kqueue (EM.kqueue=true) for pid watching support");
2089
+
2090
+ struct kevent event;
2091
+ int kqres;
2092
+
2093
+ EV_SET(&event, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT | NOTE_FORK, 0, 0);
2094
+
2095
+ // Attempt to register the event
2096
+ kqres = kevent(kqfd, &event, 1, NULL, 0, NULL);
2097
+ if (kqres == -1) {
2098
+ char errbuf[200];
2099
+ sprintf(errbuf, "failed to register file watch descriptor with kqueue: %s", strerror(errno));
2100
+ throw std::runtime_error(errbuf);
2101
+ }
2102
+ #endif
2103
+
2104
+ #ifdef HAVE_KQUEUE
2105
+ Bindable_t* b = new Bindable_t();
2106
+ Pids.insert(make_pair (pid, b));
2107
+
2108
+ return b->GetBinding();
2109
+ #endif
2110
+
2111
+ throw std::runtime_error("no pid watching support on this system");
2112
+ }
2113
+
2114
+ /**************************
2115
+ EventMachine_t::UnwatchPid
2116
+ **************************/
2117
+
2118
+ void EventMachine_t::UnwatchPid (int pid)
2119
+ {
2120
+ Bindable_t *b = Pids[pid];
2121
+ assert(b);
2122
+ Pids.erase(pid);
2123
+
2124
+ #ifdef HAVE_KQUEUE
2125
+ struct kevent k;
2126
+
2127
+ EV_SET(&k, pid, EVFILT_PROC, EV_DELETE, 0, 0, 0);
2128
+ /*int t =*/ kevent (kqfd, &k, 1, NULL, 0, NULL);
2129
+ // t==-1 if the process already exited; ignore this for now
2130
+ #endif
2131
+
2132
+ if (EventCallback)
2133
+ (*EventCallback)(b->GetBinding(), EM_CONNECTION_UNBOUND, NULL, 0);
2134
+
2135
+ delete b;
2136
+ }
2137
+
2138
+ void EventMachine_t::UnwatchPid (const unsigned long sig)
2139
+ {
2140
+ for(map<int, Bindable_t*>::iterator i=Pids.begin(); i != Pids.end(); i++)
2141
+ {
2142
+ if (i->second->GetBinding() == sig) {
2143
+ UnwatchPid (i->first);
2144
+ return;
2145
+ }
2146
+ }
2147
+
2148
+ throw std::runtime_error("attempted to remove invalid pid signature");
2149
+ }
2150
+
2151
+
2152
+ /*************************
2153
+ EventMachine_t::WatchFile
2154
+ *************************/
2155
+
2156
+ const unsigned long EventMachine_t::WatchFile (const char *fpath)
2157
+ {
2158
+ struct stat sb;
2159
+ int sres;
2160
+ int wd = -1;
2161
+
2162
+ sres = stat(fpath, &sb);
2163
+
2164
+ if (sres == -1) {
2165
+ char errbuf[300];
2166
+ sprintf(errbuf, "error registering file %s for watching: %s", fpath, strerror(errno));
2167
+ throw std::runtime_error(errbuf);
2168
+ }
2169
+
2170
+ #ifdef HAVE_INOTIFY
2171
+ if (!inotify) {
2172
+ inotify = new InotifyDescriptor(this);
2173
+ assert (inotify);
2174
+ Add(inotify);
2175
+ }
2176
+
2177
+ wd = inotify_add_watch(inotify->GetSocket(), fpath,
2178
+ IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF | IN_CREATE | IN_DELETE | IN_MOVE) ;
2179
+ if (wd == -1) {
2180
+ char errbuf[300];
2181
+ sprintf(errbuf, "failed to open file %s for registering with inotify: %s", fpath, strerror(errno));
2182
+ throw std::runtime_error(errbuf);
2183
+ }
2184
+ #endif
2185
+
2186
+ #ifdef HAVE_KQUEUE
2187
+ if (!bKqueue)
2188
+ throw std::runtime_error("must enable kqueue (EM.kqueue=true) for file watching support");
2189
+
2190
+ // With kqueue we have to open the file first and use the resulting fd to register for events
2191
+ wd = open(fpath, O_RDONLY);
2192
+ if (wd == -1) {
2193
+ char errbuf[300];
2194
+ sprintf(errbuf, "failed to open file %s for registering with kqueue: %s", fpath, strerror(errno));
2195
+ throw std::runtime_error(errbuf);
2196
+ }
2197
+ _RegisterKqueueFileEvent(wd);
2198
+ #endif
2199
+
2200
+ if (wd != -1) {
2201
+ Bindable_t* b = new Bindable_t();
2202
+ Files.insert(make_pair (wd, b));
2203
+
2204
+ return b->GetBinding();
2205
+ }
2206
+
2207
+ throw std::runtime_error("no file watching support on this system"); // is this the right thing to do?
2208
+ }
2209
+
2210
+
2211
+ /***************************
2212
+ EventMachine_t::UnwatchFile
2213
+ ***************************/
2214
+
2215
+ void EventMachine_t::UnwatchFile (int wd)
2216
+ {
2217
+ Bindable_t *b = Files[wd];
2218
+ assert(b);
2219
+ Files.erase(wd);
2220
+
2221
+ #ifdef HAVE_INOTIFY
2222
+ inotify_rm_watch(inotify->GetSocket(), wd);
2223
+ #elif HAVE_KQUEUE
2224
+ // With kqueue, closing the monitored fd automatically clears all registered events for it
2225
+ close(wd);
2226
+ #endif
2227
+
2228
+ if (EventCallback)
2229
+ (*EventCallback)(b->GetBinding(), EM_CONNECTION_UNBOUND, NULL, 0);
2230
+
2231
+ delete b;
2232
+ }
2233
+
2234
+ void EventMachine_t::UnwatchFile (const unsigned long sig)
2235
+ {
2236
+ for(map<int, Bindable_t*>::iterator i=Files.begin(); i != Files.end(); i++)
2237
+ {
2238
+ if (i->second->GetBinding() == sig) {
2239
+ UnwatchFile (i->first);
2240
+ return;
2241
+ }
2242
+ }
2243
+ throw std::runtime_error("attempted to remove invalid watch signature");
2244
+ }
2245
+
2246
+
2247
+ /***********************************
2248
+ EventMachine_t::_ReadInotify_Events
2249
+ ************************************/
2250
+
2251
+ void EventMachine_t::_ReadInotifyEvents()
2252
+ {
2253
+ #ifdef HAVE_INOTIFY
2254
+ char buffer[1024];
2255
+
2256
+ assert(EventCallback);
2257
+
2258
+ for (;;) {
2259
+ int returned = read(inotify->GetSocket(), buffer, sizeof(buffer));
2260
+ assert(!(returned == 0 || returned == -1 && errno == EINVAL));
2261
+ if (returned <= 0) {
2262
+ break;
2263
+ }
2264
+ int current = 0;
2265
+ while (current < returned) {
2266
+ struct inotify_event* event = (struct inotify_event*)(buffer+current);
2267
+ map<int, Bindable_t*>::const_iterator bindable = Files.find(event->wd);
2268
+ if (bindable != Files.end()) {
2269
+ if (event->mask & (IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE)){
2270
+ (*EventCallback)(bindable->second->GetBinding(), EM_CONNECTION_READ, "modified", 8);
2271
+ }
2272
+ if (event->mask & IN_MOVE_SELF){
2273
+ (*EventCallback)(bindable->second->GetBinding(), EM_CONNECTION_READ, "moved", 5);
2274
+ }
2275
+ if (event->mask & IN_DELETE_SELF) {
2276
+ (*EventCallback)(bindable->second->GetBinding(), EM_CONNECTION_READ, "deleted", 7);
2277
+ UnwatchFile ((int)event->wd);
2278
+ }
2279
+ }
2280
+ current += sizeof(struct inotify_event) + event->len;
2281
+ }
2282
+ }
2283
+ #endif
2284
+ }
2285
+
2286
+
2287
+ /*************************************
2288
+ EventMachine_t::_HandleKqueuePidEvent
2289
+ *************************************/
2290
+
2291
+ #ifdef HAVE_KQUEUE
2292
+ void EventMachine_t::_HandleKqueuePidEvent(struct kevent *event)
2293
+ {
2294
+ assert(EventCallback);
2295
+
2296
+ if (event->fflags & NOTE_FORK)
2297
+ (*EventCallback)(Pids [(int) event->ident]->GetBinding(), EM_CONNECTION_READ, "fork", 4);
2298
+ if (event->fflags & NOTE_EXIT) {
2299
+ (*EventCallback)(Pids [(int) event->ident]->GetBinding(), EM_CONNECTION_READ, "exit", 4);
2300
+ // stop watching the pid if it died
2301
+ UnwatchPid ((int)event->ident);
2302
+ }
2303
+ }
2304
+ #endif
2305
+
2306
+
2307
+ /**************************************
2308
+ EventMachine_t::_HandleKqueueFileEvent
2309
+ ***************************************/
2310
+
2311
+ #ifdef HAVE_KQUEUE
2312
+ void EventMachine_t::_HandleKqueueFileEvent(struct kevent *event)
2313
+ {
2314
+ assert(EventCallback);
2315
+
2316
+ if (event->fflags & NOTE_WRITE)
2317
+ (*EventCallback)(Files [(int) event->ident]->GetBinding(), EM_CONNECTION_READ, "modified", 8);
2318
+ if (event->fflags & NOTE_RENAME)
2319
+ (*EventCallback)(Files [(int) event->ident]->GetBinding(), EM_CONNECTION_READ, "moved", 5);
2320
+ if (event->fflags & NOTE_DELETE) {
2321
+ (*EventCallback)(Files [(int) event->ident]->GetBinding(), EM_CONNECTION_READ, "deleted", 7);
2322
+ UnwatchFile ((int)event->ident);
2323
+ }
2324
+ }
2325
+ #endif
2326
+
2327
+
2328
+ /****************************************
2329
+ EventMachine_t::_RegisterKqueueFileEvent
2330
+ *****************************************/
2331
+
2332
+ #ifdef HAVE_KQUEUE
2333
+ void EventMachine_t::_RegisterKqueueFileEvent(int fd)
2334
+ {
2335
+ struct kevent newevent;
2336
+ int kqres;
2337
+
2338
+ // Setup the event with our fd and proper flags
2339
+ EV_SET(&newevent, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_DELETE | NOTE_RENAME | NOTE_WRITE, 0, 0);
2340
+
2341
+ // Attempt to register the event
2342
+ kqres = kevent(kqfd, &newevent, 1, NULL, 0, NULL);
2343
+ if (kqres == -1) {
2344
+ char errbuf[200];
2345
+ sprintf(errbuf, "failed to register file watch descriptor with kqueue: %s", strerror(errno));
2346
+ close(fd);
2347
+ throw std::runtime_error(errbuf);
2348
+ }
2349
+ }
2350
+ #endif
2351
+
2352
+
2353
+ /************************************
2354
+ EventMachine_t::GetHeartbeatInterval
2355
+ *************************************/
2356
+
2357
+ float EventMachine_t::GetHeartbeatInterval()
2358
+ {
2359
+ return ((float)HeartbeatInterval / 1000000);
2360
+ }
2361
+
2362
+
2363
+ /************************************
2364
+ EventMachine_t::SetHeartbeatInterval
2365
+ *************************************/
2366
+
2367
+ int EventMachine_t::SetHeartbeatInterval(float interval)
2368
+ {
2369
+ int iv = (int)(interval * 1000000);
2370
+ if (iv > 0) {
2371
+ HeartbeatInterval = iv;
2372
+ return 1;
2373
+ }
2374
+ return 0;
2375
+ }
2376
+ //#endif // OS_UNIX
2377
+