UdpSocket.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 <vector>
  27. #include <algorithm>
  28. #include <stdexcept>
  29. #include <assert.h>
  30. #include <signal.h>
  31. #include <math.h>
  32. #include <errno.h>
  33. #include <string.h> // for memset
  34. #include <pthread.h>
  35. #include <unistd.h>
  36. #include <stdlib.h>
  37. #include <stdio.h>
  38. #include <netdb.h>
  39. #include <sys/types.h>
  40. #include <sys/socket.h>
  41. #include <sys/time.h>
  42. #include <netinet/in.h> // for sockaddr_in
  43. #include "ip/PacketListener.h"
  44. #include "ip/TimerListener.h"
  45. #if defined(__APPLE__) && !defined(_SOCKLEN_T)
  46. // pre system 10.3 didn have socklen_t
  47. typedef ssize_t socklen_t;
  48. #endif
  49. static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint )
  50. {
  51. 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. ? 0
  60. : htons( 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. bool isBound_;
  75. bool isConnected_;
  76. int socket_;
  77. struct sockaddr_in connectedAddr_;
  78. struct sockaddr_in sendToAddr_;
  79. public:
  80. Implementation()
  81. : isBound_( false )
  82. , isConnected_( false )
  83. , socket_( -1 )
  84. {
  85. if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == -1 ){
  86. throw std::runtime_error("unable to create udp socket\n");
  87. }
  88. int on=1;
  89. setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, (char*)&on, sizeof(on));
  90. memset( &sendToAddr_, 0, sizeof(sendToAddr_) );
  91. sendToAddr_.sin_family = AF_INET;
  92. }
  93. ~Implementation()
  94. {
  95. if (socket_ != -1) close(socket_);
  96. }
  97. IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
  98. {
  99. assert( isBound_ );
  100. // first connect the socket to the remote server
  101. struct sockaddr_in connectSockAddr;
  102. SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint );
  103. if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) {
  104. throw std::runtime_error("unable to connect udp socket\n");
  105. }
  106. // get the address
  107. struct sockaddr_in sockAddr;
  108. memset( (char *)&sockAddr, 0, sizeof(sockAddr ) );
  109. socklen_t length = sizeof(sockAddr);
  110. if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) {
  111. throw std::runtime_error("unable to getsockname\n");
  112. }
  113. if( isConnected_ ){
  114. // reconnect to the connected address
  115. if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
  116. throw std::runtime_error("unable to connect udp socket\n");
  117. }
  118. }else{
  119. // unconnect from the remote address
  120. struct sockaddr_in unconnectSockAddr;
  121. memset( (char *)&unconnectSockAddr, 0, sizeof(unconnectSockAddr ) );
  122. unconnectSockAddr.sin_family = AF_UNSPEC;
  123. // address fields are zero
  124. int connectResult = connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr));
  125. if ( connectResult < 0 && errno != EAFNOSUPPORT ) {
  126. throw std::runtime_error("unable to un-connect udp socket\n");
  127. }
  128. }
  129. return IpEndpointNameFromSockaddr( sockAddr );
  130. }
  131. void Connect( const IpEndpointName& remoteEndpoint )
  132. {
  133. SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint );
  134. if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
  135. throw std::runtime_error("unable to connect udp socket\n");
  136. }
  137. isConnected_ = true;
  138. }
  139. void Send( const char *data, int size )
  140. {
  141. assert( isConnected_ );
  142. send( socket_, data, size, 0 );
  143. }
  144. void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size )
  145. {
  146. sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address );
  147. sendToAddr_.sin_port = htons( remoteEndpoint.port );
  148. sendto( socket_, data, size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) );
  149. }
  150. void Bind( const IpEndpointName& localEndpoint )
  151. {
  152. struct sockaddr_in bindSockAddr;
  153. SockaddrFromIpEndpointName( bindSockAddr, localEndpoint );
  154. if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) {
  155. throw std::runtime_error("unable to bind udp socket\n");
  156. }
  157. isBound_ = true;
  158. }
  159. bool IsBound() const { return isBound_; }
  160. int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size )
  161. {
  162. assert( isBound_ );
  163. struct sockaddr_in fromAddr;
  164. socklen_t fromAddrLen = sizeof(fromAddr);
  165. int result = recvfrom(socket_, data, size, 0,
  166. (struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen);
  167. if( result < 0 )
  168. return 0;
  169. remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr);
  170. remoteEndpoint.port = ntohs(fromAddr.sin_port);
  171. return result;
  172. }
  173. int Socket() { return socket_; }
  174. };
  175. UdpSocket::UdpSocket()
  176. {
  177. impl_ = new Implementation();
  178. }
  179. UdpSocket::~UdpSocket()
  180. {
  181. delete impl_;
  182. }
  183. IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
  184. {
  185. return impl_->LocalEndpointFor( remoteEndpoint );
  186. }
  187. void UdpSocket::Connect( const IpEndpointName& remoteEndpoint )
  188. {
  189. impl_->Connect( remoteEndpoint );
  190. }
  191. void UdpSocket::Send( const char *data, int size )
  192. {
  193. impl_->Send( data, size );
  194. }
  195. void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size )
  196. {
  197. impl_->SendTo( remoteEndpoint, data, size );
  198. }
  199. void UdpSocket::Bind( const IpEndpointName& localEndpoint )
  200. {
  201. impl_->Bind( localEndpoint );
  202. }
  203. bool UdpSocket::IsBound() const
  204. {
  205. return impl_->IsBound();
  206. }
  207. int UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size )
  208. {
  209. return impl_->ReceiveFrom( remoteEndpoint, data, size );
  210. }
  211. struct AttachedTimerListener{
  212. AttachedTimerListener( int id, int p, TimerListener *tl )
  213. : initialDelayMs( id )
  214. , periodMs( p )
  215. , listener( tl ) {}
  216. int initialDelayMs;
  217. int periodMs;
  218. TimerListener *listener;
  219. };
  220. static bool CompareScheduledTimerCalls(
  221. const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs )
  222. {
  223. return lhs.first < rhs.first;
  224. }
  225. SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0;
  226. extern "C" /*static*/ void InterruptSignalHandler( int );
  227. /*static*/ void InterruptSignalHandler( int )
  228. {
  229. multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak();
  230. signal( SIGINT, SIG_DFL );
  231. }
  232. class SocketReceiveMultiplexer::Implementation{
  233. std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_;
  234. std::vector< AttachedTimerListener > timerListeners_;
  235. volatile bool break_;
  236. int breakPipe_[2]; // [0] is the reader descriptor and [1] the writer
  237. double GetCurrentTimeMs() const
  238. {
  239. struct timeval t;
  240. gettimeofday( &t, 0 );
  241. return ((double)t.tv_sec*1000.) + ((double)t.tv_usec / 1000.);
  242. }
  243. public:
  244. Implementation()
  245. {
  246. if( pipe(breakPipe_) != 0 )
  247. throw std::runtime_error( "creation of asynchronous break pipes failed\n" );
  248. }
  249. ~Implementation()
  250. {
  251. close( breakPipe_[0] );
  252. close( breakPipe_[1] );
  253. }
  254. void AttachSocketListener( UdpSocket *socket, PacketListener *listener )
  255. {
  256. assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() );
  257. // we don't check that the same socket has been added multiple times, even though this is an error
  258. socketListeners_.push_back( std::make_pair( listener, socket ) );
  259. }
  260. void DetachSocketListener( UdpSocket *socket, PacketListener *listener )
  261. {
  262. std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i =
  263. std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) );
  264. assert( i != socketListeners_.end() );
  265. socketListeners_.erase( i );
  266. }
  267. void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
  268. {
  269. timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) );
  270. }
  271. void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
  272. {
  273. timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) );
  274. }
  275. void DetachPeriodicTimerListener( TimerListener *listener )
  276. {
  277. std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
  278. while( i != timerListeners_.end() ){
  279. if( i->listener == listener )
  280. break;
  281. ++i;
  282. }
  283. assert( i != timerListeners_.end() );
  284. timerListeners_.erase( i );
  285. }
  286. void Run()
  287. {
  288. break_ = false;
  289. // configure the master fd_set for select()
  290. fd_set masterfds, tempfds;
  291. FD_ZERO( &masterfds );
  292. FD_ZERO( &tempfds );
  293. // in addition to listening to the inbound sockets we
  294. // also listen to the asynchronous break pipe, so that AsynchronousBreak()
  295. // can break us out of select() from another thread.
  296. FD_SET( breakPipe_[0], &masterfds );
  297. int fdmax = breakPipe_[0];
  298. for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
  299. i != socketListeners_.end(); ++i ){
  300. if( fdmax < i->second->impl_->Socket() )
  301. fdmax = i->second->impl_->Socket();
  302. FD_SET( i->second->impl_->Socket(), &masterfds );
  303. }
  304. // configure the timer queue
  305. double currentTimeMs = GetCurrentTimeMs();
  306. // expiry time ms, listener
  307. std::vector< std::pair< double, AttachedTimerListener > > timerQueue_;
  308. for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
  309. i != timerListeners_.end(); ++i )
  310. timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) );
  311. std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
  312. const int MAX_BUFFER_SIZE = 4098;
  313. char *data = new char[ MAX_BUFFER_SIZE ];
  314. IpEndpointName remoteEndpoint;
  315. struct timeval timeout;
  316. while( !break_ ){
  317. tempfds = masterfds;
  318. struct timeval *timeoutPtr = 0;
  319. if( !timerQueue_.empty() ){
  320. double timeoutMs = timerQueue_.front().first - GetCurrentTimeMs();
  321. if( timeoutMs < 0 )
  322. timeoutMs = 0;
  323. // 1000000 microseconds in a second
  324. timeout.tv_sec = (long)(timeoutMs * .001);
  325. timeout.tv_usec = (long)((timeoutMs - (timeout.tv_sec * 1000)) * 1000);
  326. timeoutPtr = &timeout;
  327. }
  328. if( select( fdmax + 1, &tempfds, 0, 0, timeoutPtr ) < 0 && errno != EINTR ){
  329. if (!break_) throw std::runtime_error("select failed\n");
  330. else break;
  331. }
  332. if ( FD_ISSET( breakPipe_[0], &tempfds ) ){
  333. // clear pending data from the asynchronous break pipe
  334. char c;
  335. ssize_t ret;
  336. ret = read( breakPipe_[0], &c, 1 );
  337. }
  338. if( break_ )
  339. break;
  340. for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
  341. i != socketListeners_.end(); ++i ){
  342. if( FD_ISSET( i->second->impl_->Socket(), &tempfds ) ){
  343. int size = i->second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE );
  344. if( size > 0 ){
  345. i->first->ProcessPacket( data, size, remoteEndpoint );
  346. if( break_ )
  347. break;
  348. }
  349. }
  350. }
  351. // execute any expired timers
  352. currentTimeMs = GetCurrentTimeMs();
  353. bool resort = false;
  354. for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin();
  355. i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){
  356. i->second.listener->TimerExpired();
  357. if( break_ )
  358. break;
  359. i->first += i->second.periodMs;
  360. resort = true;
  361. }
  362. if( resort )
  363. std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
  364. }
  365. delete [] data;
  366. }
  367. void Break()
  368. {
  369. break_ = true;
  370. }
  371. void AsynchronousBreak()
  372. {
  373. break_ = true;
  374. // Send a termination message to the asynchronous break pipe, so select() will return
  375. ssize_t ret;
  376. ret = write( breakPipe_[1], "!", 1 );
  377. }
  378. };
  379. SocketReceiveMultiplexer::SocketReceiveMultiplexer()
  380. {
  381. impl_ = new Implementation();
  382. }
  383. SocketReceiveMultiplexer::~SocketReceiveMultiplexer()
  384. {
  385. delete impl_;
  386. }
  387. void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener )
  388. {
  389. impl_->AttachSocketListener( socket, listener );
  390. }
  391. void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener )
  392. {
  393. impl_->DetachSocketListener( socket, listener );
  394. }
  395. void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
  396. {
  397. impl_->AttachPeriodicTimerListener( periodMilliseconds, listener );
  398. }
  399. void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
  400. {
  401. impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener );
  402. }
  403. void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener )
  404. {
  405. impl_->DetachPeriodicTimerListener( listener );
  406. }
  407. void SocketReceiveMultiplexer::Run()
  408. {
  409. impl_->Run();
  410. }
  411. void SocketReceiveMultiplexer::RunUntilSigInt()
  412. {
  413. assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */
  414. multiplexerInstanceToAbortWithSigInt_ = this;
  415. signal( SIGINT, InterruptSignalHandler );
  416. impl_->Run();
  417. signal( SIGINT, SIG_DFL );
  418. multiplexerInstanceToAbortWithSigInt_ = 0;
  419. }
  420. void SocketReceiveMultiplexer::Break()
  421. {
  422. impl_->Break();
  423. }
  424. void SocketReceiveMultiplexer::AsynchronousBreak()
  425. {
  426. impl_->AsynchronousBreak();
  427. }