MattHulse-eventmachine 0.0.1

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