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.

572 lines
16KB

  1. /*
  2. oscpack -- Open Sound Control (OSC) packet manipulation library
  3. http://www.rossbencina.com/code/oscpack
  4. Copyright (c) 2004-2013 Ross Bencina <rossb@audiomulch.com>
  5. Permission is hereby granted, free of charge, to any person obtaining
  6. a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  17. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  18. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. */
  22. /*
  23. The text above constitutes the entire oscpack license; however,
  24. the oscpack developer(s) also make the following non-binding requests:
  25. Any person wishing to distribute modifications to the Software is
  26. requested to send the modifications to the original developer so that
  27. they can be incorporated into the canonical version. It is also
  28. requested that these non-binding requests be included whenever the
  29. above license is reproduced.
  30. */
  31. #include <winsock2.h> // this must come first to prevent errors with MSVC7
  32. #include <windows.h>
  33. #include <mmsystem.h> // for timeGetTime()
  34. #ifndef WINCE
  35. #include <signal.h>
  36. #endif
  37. #include <algorithm>
  38. #include <cassert>
  39. #include <cstring> // for memset
  40. #include <stdexcept>
  41. #include <vector>
  42. #include "../UdpSocket.h" // usually I'd include the module header first
  43. // but this is causing conflicts with BCB4 due to
  44. // std::size_t usage.
  45. #include "../NetworkingUtils.h"
  46. #include "../PacketListener.h"
  47. #include "../TimerListener.h"
  48. typedef int socklen_t;
  49. static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint )
  50. {
  51. std::memset( (char *)&sockAddr, 0, sizeof(sockAddr ) );
  52. sockAddr.sin_family = AF_INET;
  53. sockAddr.sin_addr.s_addr =
  54. (endpoint.address == IpEndpointName::ANY_ADDRESS)
  55. ? INADDR_ANY
  56. : htonl( endpoint.address );
  57. sockAddr.sin_port =
  58. (endpoint.port == IpEndpointName::ANY_PORT)
  59. ? (short)0
  60. : htons( (short)endpoint.port );
  61. }
  62. static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr )
  63. {
  64. return IpEndpointName(
  65. (sockAddr.sin_addr.s_addr == INADDR_ANY)
  66. ? IpEndpointName::ANY_ADDRESS
  67. : ntohl( sockAddr.sin_addr.s_addr ),
  68. (sockAddr.sin_port == 0)
  69. ? IpEndpointName::ANY_PORT
  70. : ntohs( sockAddr.sin_port )
  71. );
  72. }
  73. class UdpSocket::Implementation{
  74. NetworkInitializer networkInitializer_;
  75. bool isBound_;
  76. bool isConnected_;
  77. SOCKET socket_;
  78. struct sockaddr_in connectedAddr_;
  79. struct sockaddr_in sendToAddr_;
  80. public:
  81. Implementation()
  82. : isBound_( false )
  83. , isConnected_( false )
  84. , socket_( INVALID_SOCKET )
  85. {
  86. if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == INVALID_SOCKET ){
  87. throw std::runtime_error("unable to create udp socket\n");
  88. }
  89. std::memset( &sendToAddr_, 0, sizeof(sendToAddr_) );
  90. sendToAddr_.sin_family = AF_INET;
  91. }
  92. ~Implementation()
  93. {
  94. if (socket_ != INVALID_SOCKET) closesocket(socket_);
  95. }
  96. void SetEnableBroadcast( bool enableBroadcast )
  97. {
  98. char broadcast = (char)((enableBroadcast) ? 1 : 0); // char on win32
  99. setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
  100. }
  101. void SetAllowReuse( bool allowReuse )
  102. {
  103. // Note: SO_REUSEADDR is non-deterministic for listening sockets on Win32. See MSDN article:
  104. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  105. // http://msdn.microsoft.com/en-us/library/ms740621%28VS.85%29.aspx
  106. char reuseAddr = (char)((allowReuse) ? 1 : 0); // char on win32
  107. setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr));
  108. }
  109. IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
  110. {
  111. assert( isBound_ );
  112. // first connect the socket to the remote server
  113. struct sockaddr_in connectSockAddr;
  114. SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint );
  115. if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) {
  116. throw std::runtime_error("unable to connect udp socket\n");
  117. }
  118. // get the address
  119. struct sockaddr_in sockAddr;
  120. std::memset( (char *)&sockAddr, 0, sizeof(sockAddr ) );
  121. socklen_t length = sizeof(sockAddr);
  122. if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) {
  123. throw std::runtime_error("unable to getsockname\n");
  124. }
  125. if( isConnected_ ){
  126. // reconnect to the connected address
  127. if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
  128. throw std::runtime_error("unable to connect udp socket\n");
  129. }
  130. }else{
  131. // unconnect from the remote address
  132. struct sockaddr_in unconnectSockAddr;
  133. SockaddrFromIpEndpointName( unconnectSockAddr, IpEndpointName() );
  134. if( connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr)) < 0
  135. && WSAGetLastError() != WSAEADDRNOTAVAIL ){
  136. throw std::runtime_error("unable to un-connect udp socket\n");
  137. }
  138. }
  139. return IpEndpointNameFromSockaddr( sockAddr );
  140. }
  141. void Connect( const IpEndpointName& remoteEndpoint )
  142. {
  143. SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint );
  144. if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
  145. throw std::runtime_error("unable to connect udp socket\n");
  146. }
  147. isConnected_ = true;
  148. }
  149. void Send( const char *data, std::size_t size )
  150. {
  151. assert( isConnected_ );
  152. send( socket_, data, (int)size, 0 );
  153. }
  154. void SendTo( const IpEndpointName& remoteEndpoint, const char *data, std::size_t size )
  155. {
  156. sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address );
  157. sendToAddr_.sin_port = htons( (short)remoteEndpoint.port );
  158. sendto( socket_, data, (int)size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) );
  159. }
  160. void Bind( const IpEndpointName& localEndpoint )
  161. {
  162. struct sockaddr_in bindSockAddr;
  163. SockaddrFromIpEndpointName( bindSockAddr, localEndpoint );
  164. if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) {
  165. throw std::runtime_error("unable to bind udp socket\n");
  166. }
  167. isBound_ = true;
  168. }
  169. bool IsBound() const { return isBound_; }
  170. std::size_t ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, std::size_t size )
  171. {
  172. assert( isBound_ );
  173. struct sockaddr_in fromAddr;
  174. socklen_t fromAddrLen = sizeof(fromAddr);
  175. int result = recvfrom(socket_, data, (int)size, 0,
  176. (struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen);
  177. if( result < 0 )
  178. return 0;
  179. remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr);
  180. remoteEndpoint.port = ntohs(fromAddr.sin_port);
  181. return result;
  182. }
  183. SOCKET& Socket() { return socket_; }
  184. };
  185. UdpSocket::UdpSocket()
  186. {
  187. impl_ = new Implementation();
  188. }
  189. UdpSocket::~UdpSocket()
  190. {
  191. delete impl_;
  192. }
  193. void UdpSocket::SetEnableBroadcast( bool enableBroadcast )
  194. {
  195. impl_->SetEnableBroadcast( enableBroadcast );
  196. }
  197. void UdpSocket::SetAllowReuse( bool allowReuse )
  198. {
  199. impl_->SetAllowReuse( allowReuse );
  200. }
  201. IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
  202. {
  203. return impl_->LocalEndpointFor( remoteEndpoint );
  204. }
  205. void UdpSocket::Connect( const IpEndpointName& remoteEndpoint )
  206. {
  207. impl_->Connect( remoteEndpoint );
  208. }
  209. void UdpSocket::Send( const char *data, std::size_t size )
  210. {
  211. impl_->Send( data, size );
  212. }
  213. void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, std::size_t size )
  214. {
  215. impl_->SendTo( remoteEndpoint, data, size );
  216. }
  217. void UdpSocket::Bind( const IpEndpointName& localEndpoint )
  218. {
  219. impl_->Bind( localEndpoint );
  220. }
  221. bool UdpSocket::IsBound() const
  222. {
  223. return impl_->IsBound();
  224. }
  225. std::size_t UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, std::size_t size )
  226. {
  227. return impl_->ReceiveFrom( remoteEndpoint, data, size );
  228. }
  229. struct AttachedTimerListener{
  230. AttachedTimerListener( int id, int p, TimerListener *tl )
  231. : initialDelayMs( id )
  232. , periodMs( p )
  233. , listener( tl ) {}
  234. int initialDelayMs;
  235. int periodMs;
  236. TimerListener *listener;
  237. };
  238. static bool CompareScheduledTimerCalls(
  239. const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs )
  240. {
  241. return lhs.first < rhs.first;
  242. }
  243. SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0;
  244. extern "C" /*static*/ void InterruptSignalHandler( int );
  245. /*static*/ void InterruptSignalHandler( int )
  246. {
  247. multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak();
  248. #ifndef WINCE
  249. signal( SIGINT, SIG_DFL );
  250. #endif
  251. }
  252. class SocketReceiveMultiplexer::Implementation{
  253. NetworkInitializer networkInitializer_;
  254. std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_;
  255. std::vector< AttachedTimerListener > timerListeners_;
  256. volatile bool break_;
  257. HANDLE breakEvent_;
  258. double GetCurrentTimeMs() const
  259. {
  260. #ifndef WINCE
  261. return timeGetTime(); // FIXME: bad choice if you want to run for more than 40 days
  262. #else
  263. return 0;
  264. #endif
  265. }
  266. public:
  267. Implementation()
  268. {
  269. breakEvent_ = CreateEvent( NULL, FALSE, FALSE, NULL );
  270. }
  271. ~Implementation()
  272. {
  273. CloseHandle( breakEvent_ );
  274. }
  275. void AttachSocketListener( UdpSocket *socket, PacketListener *listener )
  276. {
  277. assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() );
  278. // we don't check that the same socket has been added multiple times, even though this is an error
  279. socketListeners_.push_back( std::make_pair( listener, socket ) );
  280. }
  281. void DetachSocketListener( UdpSocket *socket, PacketListener *listener )
  282. {
  283. std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i =
  284. std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) );
  285. assert( i != socketListeners_.end() );
  286. socketListeners_.erase( i );
  287. }
  288. void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
  289. {
  290. timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) );
  291. }
  292. void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
  293. {
  294. timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) );
  295. }
  296. void DetachPeriodicTimerListener( TimerListener *listener )
  297. {
  298. std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
  299. while( i != timerListeners_.end() ){
  300. if( i->listener == listener )
  301. break;
  302. ++i;
  303. }
  304. assert( i != timerListeners_.end() );
  305. timerListeners_.erase( i );
  306. }
  307. void Run()
  308. {
  309. break_ = false;
  310. // prepare the window events which we use to wake up on incoming data
  311. // we use this instead of select() primarily to support the AsyncBreak()
  312. // mechanism.
  313. std::vector<HANDLE> events( socketListeners_.size() + 1, 0 );
  314. int j=0;
  315. for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
  316. i != socketListeners_.end(); ++i, ++j ){
  317. HANDLE event = CreateEvent( NULL, FALSE, FALSE, NULL );
  318. WSAEventSelect( i->second->impl_->Socket(), event, FD_READ ); // note that this makes the socket non-blocking which is why we can safely call RecieveFrom() on all sockets below
  319. events[j] = event;
  320. }
  321. events[ socketListeners_.size() ] = breakEvent_; // last event in the collection is the break event
  322. // configure the timer queue
  323. double currentTimeMs = GetCurrentTimeMs();
  324. // expiry time ms, listener
  325. std::vector< std::pair< double, AttachedTimerListener > > timerQueue_;
  326. for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
  327. i != timerListeners_.end(); ++i )
  328. timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) );
  329. std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
  330. const int MAX_BUFFER_SIZE = 4098;
  331. char *data = new char[ MAX_BUFFER_SIZE ];
  332. IpEndpointName remoteEndpoint;
  333. while( !break_ ){
  334. double currentTimeMs = GetCurrentTimeMs();
  335. DWORD waitTime = INFINITE;
  336. if( !timerQueue_.empty() ){
  337. waitTime = (DWORD)( timerQueue_.front().first >= currentTimeMs
  338. ? timerQueue_.front().first - currentTimeMs
  339. : 0 );
  340. }
  341. DWORD waitResult = WaitForMultipleObjects( (DWORD)socketListeners_.size() + 1, &events[0], FALSE, waitTime );
  342. if( break_ )
  343. break;
  344. if( waitResult != WAIT_TIMEOUT ){
  345. for( int i = waitResult - WAIT_OBJECT_0; i < (int)socketListeners_.size(); ++i ){
  346. std::size_t size = socketListeners_[i].second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE );
  347. if( size > 0 ){
  348. socketListeners_[i].first->ProcessPacket( data, (int)size, remoteEndpoint );
  349. if( break_ )
  350. break;
  351. }
  352. }
  353. }
  354. // execute any expired timers
  355. currentTimeMs = GetCurrentTimeMs();
  356. bool resort = false;
  357. for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin();
  358. i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){
  359. i->second.listener->TimerExpired();
  360. if( break_ )
  361. break;
  362. i->first += i->second.periodMs;
  363. resort = true;
  364. }
  365. if( resort )
  366. std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
  367. }
  368. delete [] data;
  369. // free events
  370. j = 0;
  371. for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
  372. i != socketListeners_.end(); ++i, ++j ){
  373. WSAEventSelect( i->second->impl_->Socket(), events[j], 0 ); // remove association between socket and event
  374. CloseHandle( events[j] );
  375. unsigned long enableNonblocking = 0;
  376. ioctlsocket( i->second->impl_->Socket(), FIONBIO, &enableNonblocking ); // make the socket blocking again
  377. }
  378. }
  379. void Break()
  380. {
  381. break_ = true;
  382. }
  383. void AsynchronousBreak()
  384. {
  385. break_ = true;
  386. SetEvent( breakEvent_ );
  387. }
  388. };
  389. SocketReceiveMultiplexer::SocketReceiveMultiplexer()
  390. {
  391. impl_ = new Implementation();
  392. }
  393. SocketReceiveMultiplexer::~SocketReceiveMultiplexer()
  394. {
  395. delete impl_;
  396. }
  397. void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener )
  398. {
  399. impl_->AttachSocketListener( socket, listener );
  400. }
  401. void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener )
  402. {
  403. impl_->DetachSocketListener( socket, listener );
  404. }
  405. void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
  406. {
  407. impl_->AttachPeriodicTimerListener( periodMilliseconds, listener );
  408. }
  409. void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
  410. {
  411. impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener );
  412. }
  413. void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener )
  414. {
  415. impl_->DetachPeriodicTimerListener( listener );
  416. }
  417. void SocketReceiveMultiplexer::Run()
  418. {
  419. impl_->Run();
  420. }
  421. void SocketReceiveMultiplexer::RunUntilSigInt()
  422. {
  423. assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */
  424. multiplexerInstanceToAbortWithSigInt_ = this;
  425. #ifndef WINCE
  426. signal( SIGINT, InterruptSignalHandler );
  427. #endif
  428. impl_->Run();
  429. #ifndef WINCE
  430. signal( SIGINT, SIG_DFL );
  431. #endif
  432. multiplexerInstanceToAbortWithSigInt_ = 0;
  433. }
  434. void SocketReceiveMultiplexer::Break()
  435. {
  436. impl_->Break();
  437. }
  438. void SocketReceiveMultiplexer::AsynchronousBreak()
  439. {
  440. impl_->AsynchronousBreak();
  441. }