You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
11 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "talk/base/macsocketserver.h"
  2. #include "talk/base/common.h"
  3. #include "talk/base/logging.h"
  4. #include "talk/base/macasyncsocket.h"
  5. #include "talk/base/macutils.h"
  6. #include "talk/base/thread.h"
  7. namespace talk_base {
  8. ///////////////////////////////////////////////////////////////////////////////
  9. // MacBaseSocketServer
  10. ///////////////////////////////////////////////////////////////////////////////
  11. MacBaseSocketServer::MacBaseSocketServer() {
  12. }
  13. MacBaseSocketServer::~MacBaseSocketServer() {
  14. }
  15. AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int type) {
  16. return CreateAsyncSocket(AF_INET, type);
  17. }
  18. AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int family, int type) {
  19. if (SOCK_STREAM != type)
  20. return NULL;
  21. MacAsyncSocket* socket = new MacAsyncSocket(this, family);
  22. if (!socket->valid()) {
  23. delete socket;
  24. return NULL;
  25. }
  26. return socket;
  27. }
  28. void MacBaseSocketServer::RegisterSocket(MacAsyncSocket* s) {
  29. sockets_.insert(s);
  30. }
  31. void MacBaseSocketServer::UnregisterSocket(MacAsyncSocket* s) {
  32. VERIFY(1 == sockets_.erase(s)); // found 1
  33. }
  34. bool MacBaseSocketServer::SetPosixSignalHandler(int signum,
  35. void (*handler)(int)) {
  36. Dispatcher* dispatcher = signal_dispatcher();
  37. if (!PhysicalSocketServer::SetPosixSignalHandler(signum, handler)) {
  38. return false;
  39. }
  40. // Only register the FD once, when the first custom handler is installed.
  41. if (!dispatcher && (dispatcher = signal_dispatcher())) {
  42. CFFileDescriptorContext ctx = { 0 };
  43. ctx.info = this;
  44. CFFileDescriptorRef desc = CFFileDescriptorCreate(
  45. kCFAllocatorDefault,
  46. dispatcher->GetDescriptor(),
  47. false,
  48. &MacBaseSocketServer::FileDescriptorCallback,
  49. &ctx);
  50. if (!desc) {
  51. return false;
  52. }
  53. CFFileDescriptorEnableCallBacks(desc, kCFFileDescriptorReadCallBack);
  54. CFRunLoopSourceRef ref =
  55. CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, desc, 0);
  56. if (!ref) {
  57. CFRelease(desc);
  58. return false;
  59. }
  60. CFRunLoopAddSource(CFRunLoopGetCurrent(), ref, kCFRunLoopCommonModes);
  61. CFRelease(desc);
  62. CFRelease(ref);
  63. }
  64. return true;
  65. }
  66. // Used to disable socket events from waking our message queue when
  67. // process_io is false. Does not disable signal event handling though.
  68. void MacBaseSocketServer::EnableSocketCallbacks(bool enable) {
  69. for (std::set<MacAsyncSocket*>::iterator it = sockets().begin();
  70. it != sockets().end(); ++it) {
  71. if (enable) {
  72. (*it)->EnableCallbacks();
  73. } else {
  74. (*it)->DisableCallbacks();
  75. }
  76. }
  77. }
  78. void MacBaseSocketServer::FileDescriptorCallback(CFFileDescriptorRef fd,
  79. CFOptionFlags flags,
  80. void* context) {
  81. MacBaseSocketServer* this_ss =
  82. reinterpret_cast<MacBaseSocketServer*>(context);
  83. ASSERT(this_ss);
  84. Dispatcher* signal_dispatcher = this_ss->signal_dispatcher();
  85. ASSERT(signal_dispatcher);
  86. signal_dispatcher->OnPreEvent(DE_READ);
  87. signal_dispatcher->OnEvent(DE_READ, 0);
  88. CFFileDescriptorEnableCallBacks(fd, kCFFileDescriptorReadCallBack);
  89. }
  90. ///////////////////////////////////////////////////////////////////////////////
  91. // MacCFSocketServer
  92. ///////////////////////////////////////////////////////////////////////////////
  93. void WakeUpCallback(void* info) {
  94. MacCFSocketServer* server = static_cast<MacCFSocketServer*>(info);
  95. ASSERT(NULL != server);
  96. server->OnWakeUpCallback();
  97. }
  98. MacCFSocketServer::MacCFSocketServer()
  99. : run_loop_(CFRunLoopGetCurrent()),
  100. wake_up_(NULL) {
  101. CFRunLoopSourceContext ctx;
  102. memset(&ctx, 0, sizeof(ctx));
  103. ctx.info = this;
  104. ctx.perform = &WakeUpCallback;
  105. wake_up_ = CFRunLoopSourceCreate(NULL, 0, &ctx);
  106. ASSERT(NULL != wake_up_);
  107. if (wake_up_) {
  108. CFRunLoopAddSource(run_loop_, wake_up_, kCFRunLoopCommonModes);
  109. }
  110. }
  111. MacCFSocketServer::~MacCFSocketServer() {
  112. if (wake_up_) {
  113. CFRunLoopSourceInvalidate(wake_up_);
  114. CFRelease(wake_up_);
  115. }
  116. }
  117. bool MacCFSocketServer::Wait(int cms, bool process_io) {
  118. ASSERT(CFRunLoopGetCurrent() == run_loop_);
  119. if (!process_io && cms == 0) {
  120. // No op.
  121. return true;
  122. }
  123. if (!process_io) {
  124. // No way to listen to common modes and not get socket events, unless
  125. // we disable each one's callbacks.
  126. EnableSocketCallbacks(false);
  127. }
  128. SInt32 result;
  129. if (kForever == cms) {
  130. do {
  131. // Would prefer to run in a custom mode that only listens to wake_up,
  132. // but we have qtkit sending work to the main thread which is effectively
  133. // blocked here, causing deadlock. Thus listen to the common modes.
  134. // TODO: If QTKit becomes thread safe, do the above.
  135. result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10000000, false);
  136. } while (result != kCFRunLoopRunFinished && result != kCFRunLoopRunStopped);
  137. } else {
  138. // TODO: In the case of 0ms wait, this will only process one event, so we
  139. // may want to loop until it returns TimedOut.
  140. CFTimeInterval seconds = cms / 1000.0;
  141. result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, false);
  142. }
  143. if (!process_io) {
  144. // Reenable them. Hopefully this won't cause spurious callbacks or
  145. // missing ones while they were disabled.
  146. EnableSocketCallbacks(true);
  147. }
  148. if (kCFRunLoopRunFinished == result) {
  149. return false;
  150. }
  151. return true;
  152. }
  153. void MacCFSocketServer::WakeUp() {
  154. if (wake_up_) {
  155. CFRunLoopSourceSignal(wake_up_);
  156. CFRunLoopWakeUp(run_loop_);
  157. }
  158. }
  159. void MacCFSocketServer::OnWakeUpCallback() {
  160. ASSERT(run_loop_ == CFRunLoopGetCurrent());
  161. CFRunLoopStop(run_loop_);
  162. }
  163. ///////////////////////////////////////////////////////////////////////////////
  164. // MacCarbonSocketServer
  165. ///////////////////////////////////////////////////////////////////////////////
  166. #ifndef CARBON_DEPRECATED
  167. const UInt32 kEventClassSocketServer = 'MCSS';
  168. const UInt32 kEventWakeUp = 'WAKE';
  169. const EventTypeSpec kEventWakeUpSpec[] = {
  170. { kEventClassSocketServer, kEventWakeUp }
  171. };
  172. std::string DecodeEvent(EventRef event) {
  173. std::string str;
  174. DecodeFourChar(::GetEventClass(event), &str);
  175. str.push_back(':');
  176. DecodeFourChar(::GetEventKind(event), &str);
  177. return str;
  178. }
  179. MacCarbonSocketServer::MacCarbonSocketServer()
  180. : event_queue_(GetCurrentEventQueue()), wake_up_(NULL) {
  181. VERIFY(noErr == CreateEvent(NULL, kEventClassSocketServer, kEventWakeUp, 0,
  182. kEventAttributeUserEvent, &wake_up_));
  183. }
  184. MacCarbonSocketServer::~MacCarbonSocketServer() {
  185. if (wake_up_) {
  186. ReleaseEvent(wake_up_);
  187. }
  188. }
  189. bool MacCarbonSocketServer::Wait(int cms, bool process_io) {
  190. ASSERT(GetCurrentEventQueue() == event_queue_);
  191. // Listen to all events if we're processing I/O.
  192. // Only listen for our wakeup event if we're not.
  193. UInt32 num_types = 0;
  194. const EventTypeSpec* events = NULL;
  195. if (!process_io) {
  196. num_types = GetEventTypeCount(kEventWakeUpSpec);
  197. events = kEventWakeUpSpec;
  198. }
  199. EventTargetRef target = GetEventDispatcherTarget();
  200. EventTimeout timeout =
  201. (kForever == cms) ? kEventDurationForever : cms / 1000.0;
  202. EventTimeout end_time = GetCurrentEventTime() + timeout;
  203. bool done = false;
  204. while (!done) {
  205. EventRef event;
  206. OSStatus result = ReceiveNextEvent(num_types, events, timeout, true,
  207. &event);
  208. if (noErr == result) {
  209. if (wake_up_ != event) {
  210. LOG_F(LS_VERBOSE) << "Dispatching event: " << DecodeEvent(event);
  211. result = SendEventToEventTarget(event, target);
  212. if ((noErr != result) && (eventNotHandledErr != result)) {
  213. LOG_E(LS_ERROR, OS, result) << "SendEventToEventTarget";
  214. }
  215. } else {
  216. done = true;
  217. }
  218. ReleaseEvent(event);
  219. } else if (eventLoopTimedOutErr == result) {
  220. ASSERT(cms != kForever);
  221. done = true;
  222. } else if (eventLoopQuitErr == result) {
  223. // Ignore this... we get spurious quits for a variety of reasons.
  224. LOG_E(LS_VERBOSE, OS, result) << "ReceiveNextEvent";
  225. } else {
  226. // Some strange error occurred. Log it.
  227. LOG_E(LS_WARNING, OS, result) << "ReceiveNextEvent";
  228. return false;
  229. }
  230. if (kForever != cms) {
  231. timeout = end_time - GetCurrentEventTime();
  232. }
  233. }
  234. return true;
  235. }
  236. void MacCarbonSocketServer::WakeUp() {
  237. if (!IsEventInQueue(event_queue_, wake_up_)) {
  238. RetainEvent(wake_up_);
  239. OSStatus result = PostEventToQueue(event_queue_, wake_up_,
  240. kEventPriorityStandard);
  241. if (noErr != result) {
  242. LOG_E(LS_ERROR, OS, result) << "PostEventToQueue";
  243. }
  244. }
  245. }
  246. ///////////////////////////////////////////////////////////////////////////////
  247. // MacCarbonAppSocketServer
  248. ///////////////////////////////////////////////////////////////////////////////
  249. MacCarbonAppSocketServer::MacCarbonAppSocketServer()
  250. : event_queue_(GetCurrentEventQueue()) {
  251. // Install event handler
  252. VERIFY(noErr == InstallApplicationEventHandler(
  253. NewEventHandlerUPP(WakeUpEventHandler), 1, kEventWakeUpSpec, this,
  254. &event_handler_));
  255. // Install a timer and set it idle to begin with.
  256. VERIFY(noErr == InstallEventLoopTimer(GetMainEventLoop(),
  257. kEventDurationForever,
  258. kEventDurationForever,
  259. NewEventLoopTimerUPP(TimerHandler),
  260. this,
  261. &timer_));
  262. }
  263. MacCarbonAppSocketServer::~MacCarbonAppSocketServer() {
  264. RemoveEventLoopTimer(timer_);
  265. RemoveEventHandler(event_handler_);
  266. }
  267. OSStatus MacCarbonAppSocketServer::WakeUpEventHandler(
  268. EventHandlerCallRef next, EventRef event, void *data) {
  269. QuitApplicationEventLoop();
  270. return noErr;
  271. }
  272. void MacCarbonAppSocketServer::TimerHandler(
  273. EventLoopTimerRef timer, void *data) {
  274. QuitApplicationEventLoop();
  275. }
  276. bool MacCarbonAppSocketServer::Wait(int cms, bool process_io) {
  277. if (!process_io && cms == 0) {
  278. // No op.
  279. return true;
  280. }
  281. if (kForever != cms) {
  282. // Start a timer.
  283. OSStatus error =
  284. SetEventLoopTimerNextFireTime(timer_, cms / 1000.0);
  285. if (error != noErr) {
  286. LOG(LS_ERROR) << "Failed setting next fire time.";
  287. }
  288. }
  289. if (!process_io) {
  290. // No way to listen to common modes and not get socket events, unless
  291. // we disable each one's callbacks.
  292. EnableSocketCallbacks(false);
  293. }
  294. RunApplicationEventLoop();
  295. if (!process_io) {
  296. // Reenable them. Hopefully this won't cause spurious callbacks or
  297. // missing ones while they were disabled.
  298. EnableSocketCallbacks(true);
  299. }
  300. return true;
  301. }
  302. void MacCarbonAppSocketServer::WakeUp() {
  303. // TODO: No-op if there's already a WakeUp in flight.
  304. EventRef wake_up;
  305. VERIFY(noErr == CreateEvent(NULL, kEventClassSocketServer, kEventWakeUp, 0,
  306. kEventAttributeUserEvent, &wake_up));
  307. OSStatus result = PostEventToQueue(event_queue_, wake_up,
  308. kEventPriorityStandard);
  309. if (noErr != result) {
  310. LOG_E(LS_ERROR, OS, result) << "PostEventToQueue";
  311. }
  312. ReleaseEvent(wake_up);
  313. }
  314. #endif
  315. } // namespace talk_base