UdpSocket.cpp 15 KB

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