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.

603 lines
18KB

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