eventmachine 0.12.6-x86-mswin32-60 → 0.12.8-x86-mswin32-60

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