sensu-em 2.0.0-java

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