1 /*****************************************************************************
2 * sap.c : SAP announce handler
3 *****************************************************************************
4 * Copyright (C) 2002-2005 the VideoLAN team
7 * Authors: Clément Stenac <zorglub@videolan.org>
8 * Rémi Denis-Courmont <rem # videolan.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
28 #include <stdlib.h> /* free() */
29 #include <stdio.h> /* sprintf() */
30 #include <string.h> /* strerror() */
31 #include <ctype.h> /* tolower(), isxdigit() */
37 #if defined( WIN32 ) || defined( UNDER_CE )
38 # if defined(UNDER_CE) && defined(sockaddr_storage)
39 # undef sockaddr_storage
41 # include <winsock2.h>
42 # include <ws2tcpip.h>
45 # include <arpa/inet.h>
49 /* SAP is always on that port */
52 #define DEFAULT_PORT "1234"
56 /* SAP Specific structures */
59 #define SAP_IDLE ((mtime_t)(0.100*CLOCK_FREQ))
60 #define SAP_MAX_BUFFER 65534
61 #define MIN_INTERVAL 2
62 #define MAX_INTERVAL 300
64 /* A SAP announce address. For each of these, we run the
65 * control flow algorithm */
69 char psz_machine[NI_MAXNUMERICHOST];
71 int i_rfd; /* Read socket */
72 int i_wfd; /* Write socket */
74 /* Used for flow control */
83 /*****************************************************************************
85 *****************************************************************************/
86 static void RunThread( vlc_object_t *p_this);
87 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address );
88 static char *SDPGenerate( sap_handler_t *p_sap,
89 const session_descriptor_t *p_session,
90 const sap_address_t *p_addr );
92 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
93 sap_session_t *p_session );
96 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
97 session_descriptor_t *p_session );
99 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
100 session_descriptor_t *p_session );
101 static char *convert_to_utf8( struct sap_handler_t *p_this, char *psz_local );
103 #define FREE( p ) if( p ) { free( p ); (p) = NULL; }
107 * Create the SAP handler
109 * \param p_announce the parent announce_handler
110 * \return the newly created SAP handler or NULL on error
112 sap_handler_t *announce_SAPHandlerCreate( announce_handler_t *p_announce )
114 sap_handler_t *p_sap;
117 p_sap = vlc_object_create( p_announce, sizeof( sap_handler_t ) );
121 msg_Err( p_announce, "out of memory" );
125 vlc_mutex_init( p_sap, &p_sap->object_lock );
127 vlc_current_charset( &psz_charset );
128 p_sap->iconvHandle = vlc_iconv_open( "UTF-8", psz_charset );
130 if( p_sap->iconvHandle == (vlc_iconv_t)(-1) )
131 msg_Warn( p_sap, "Unable to do requested conversion" );
133 p_sap->pf_add = announce_SAPAnnounceAdd;
134 p_sap->pf_del = announce_SAPAnnounceDel;
136 p_sap->i_sessions = 0;
137 p_sap->i_addresses = 0;
138 p_sap->i_current_session = 0;
140 p_sap->b_control = config_GetInt( p_sap, "sap-flow-control");
142 if( vlc_thread_create( p_sap, "sap handler", RunThread,
143 VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
145 msg_Dbg( p_announce, "Unable to spawn SAP handler thread");
149 msg_Dbg( p_announce, "thread created, %i sessions", p_sap->i_sessions);
154 * Destroy the SAP handler
155 * \param p_this the SAP Handler to destroy
158 void announce_SAPHandlerDestroy( sap_handler_t *p_sap )
162 vlc_mutex_destroy( &p_sap->object_lock );
164 /* Free the remaining sessions */
165 for( i = 0 ; i< p_sap->i_sessions ; i++)
167 sap_session_t *p_session = p_sap->pp_sessions[i];
168 FREE( p_session->psz_sdp );
169 FREE( p_session->psz_data );
170 REMOVE_ELEM( p_sap->pp_sessions, p_sap->i_sessions , i );
174 /* Free the remaining addresses */
175 for( i = 0 ; i< p_sap->i_addresses ; i++)
177 sap_address_t *p_address = p_sap->pp_addresses[i];
178 FREE( p_address->psz_address );
179 if( p_address->i_rfd > -1 )
181 net_Close( p_address->i_rfd );
183 if( p_address->i_wfd > -1 && p_sap->b_control )
185 net_Close( p_address->i_wfd );
187 REMOVE_ELEM( p_sap->pp_addresses, p_sap->i_addresses, i );
191 if( p_sap->iconvHandle != (vlc_iconv_t)(-1) )
192 vlc_iconv_close( p_sap->iconvHandle );
194 /* Free the structure */
195 vlc_object_destroy( p_sap );
199 * main SAP handler thread
200 * \param p_this the SAP Handler object
203 static void RunThread( vlc_object_t *p_this)
205 sap_handler_t *p_sap = (sap_handler_t*)p_this;
206 sap_session_t *p_session;
208 while( !p_sap->b_die )
212 /* If needed, get the rate info */
213 if( p_sap->b_control == VLC_TRUE )
215 for( i = 0 ; i< p_sap->i_addresses ; i++)
217 if( p_sap->pp_addresses[i]->b_enabled == VLC_TRUE )
219 CalculateRate( p_sap, p_sap->pp_addresses[i] );
224 /* Find the session to announce */
225 vlc_mutex_lock( &p_sap->object_lock );
226 if( p_sap->i_sessions > p_sap->i_current_session + 1)
228 p_sap->i_current_session++;
230 else if( p_sap->i_sessions > 0)
232 p_sap->i_current_session = 0;
236 vlc_mutex_unlock( &p_sap->object_lock );
240 p_session = p_sap->pp_sessions[p_sap->i_current_session];
241 vlc_mutex_unlock( &p_sap->object_lock );
243 /* And announce it */
244 if( p_session->p_address->b_enabled == VLC_TRUE &&
245 p_session->p_address->b_ready == VLC_TRUE )
247 announce_SendSAPAnnounce( p_sap, p_session );
254 /* Add a SAP announce */
255 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
256 session_descriptor_t *p_session )
258 int i_header_size, i;
259 char *psz_head, psz_addr[NI_MAXNUMERICHOST];
260 vlc_bool_t b_ipv6 = VLC_FALSE;
261 sap_session_t *p_sap_session;
263 struct addrinfo hints, *res;
264 struct sockaddr_storage addr;
266 vlc_mutex_lock( &p_sap->object_lock );
268 if( p_session->psz_uri == NULL )
270 vlc_mutex_unlock( &p_sap->object_lock );
271 msg_Err( p_sap, "*FIXME* Unexpected NULL URI for SAP announce" );
272 msg_Err( p_sap, "This should not happen. VLC needs fixing." );
276 /* Determine SAP multicast address automatically */
277 memset( &hints, 0, sizeof( hints ) );
278 hints.ai_socktype = SOCK_DGRAM;
279 hints.ai_flags = AI_NUMERICHOST;
281 i = vlc_getaddrinfo( (vlc_object_t *)p_sap, p_session->psz_uri, 0,
285 vlc_mutex_unlock( &p_sap->object_lock );
286 msg_Err( p_sap, "Invalid URI for SAP announce: %s: %s",
287 p_session->psz_uri, vlc_gai_strerror( i ) );
291 if( (unsigned)res->ai_addrlen > sizeof( addr ) )
293 vlc_mutex_unlock( &p_sap->object_lock );
294 vlc_freeaddrinfo( res );
295 msg_Err( p_sap, "Unsupported address family of size %d > %u",
296 res->ai_addrlen, sizeof( addr ) );
300 memcpy( &addr, res->ai_addr, res->ai_addrlen );
302 switch( addr.ss_family )
304 #if defined (HAVE_INET_PTON) || defined (WIN32)
307 /* See RFC3513 for list of valid IPv6 scopes */
308 struct in6_addr *a6 = &((struct sockaddr_in6 *)&addr)->sin6_addr;
310 memcpy( a6->s6_addr + 2, "\x00\x00\x00\x00\x00\x00"
311 "\x00\x00\x00\x00\x00\x02\x7f\xfe", 14 );
312 if( IN6_IS_ADDR_MULTICAST( a6 ) )
313 /* force flags to zero, preserve scope */
314 a6->s6_addr[1] &= 0xf;
316 /* Unicast IPv6 - assume global scope */
317 memcpy( a6->s6_addr, "\xff\x0e", 2 );
326 /* See RFC2365 for IPv4 scopes */
329 ipv4 = ntohl( ((struct sockaddr_in *)&addr)->sin_addr.s_addr );
330 /* 224.0.0.0/24 => 224.0.0.255 */
331 if ((ipv4 & 0xffffff00) == 0xe0000000)
334 /* 239.255.0.0/16 => 239.255.255.255 */
335 if ((ipv4 & 0xffff0000) == 0xefff0000)
338 /* 239.192.0.0/14 => 239.195.255.255 */
339 if ((ipv4 & 0xfffc0000) == 0xefc00000)
342 /* other addresses => 224.2.127.254 */
348 vlc_mutex_unlock( &p_sap->object_lock );
349 vlc_freeaddrinfo( res );
350 msg_Err( p_sap, "Address family %d not supported by SAP",
355 i = vlc_getnameinfo( (struct sockaddr *)&addr, res->ai_addrlen,
356 psz_addr, sizeof( psz_addr ), NULL, NI_NUMERICHOST );
357 vlc_freeaddrinfo( res );
361 vlc_mutex_unlock( &p_sap->object_lock );
362 msg_Err( p_sap, "%s", vlc_gai_strerror( i ) );
366 msg_Dbg( p_sap, "using SAP address: %s", psz_addr);
368 /* XXX: Check for dupes */
369 p_sap_session = (sap_session_t*)malloc(sizeof(sap_session_t));
370 p_sap_session->p_address = NULL;
372 /* Add the address to the buffer */
373 for( i = 0; i < p_sap->i_addresses; i++)
375 if( !strcmp( psz_addr, p_sap->pp_addresses[i]->psz_address ) )
377 p_sap_session->p_address = p_sap->pp_addresses[i];
382 if( p_sap_session->p_address == NULL )
384 sap_address_t *p_address = (sap_address_t *)
385 malloc( sizeof(sap_address_t) );
388 msg_Err( p_sap, "out of memory" );
391 p_address->psz_address = strdup( psz_addr );
392 p_address->i_port = 9875;
393 p_address->i_wfd = net_OpenUDP( p_sap, "", 0, psz_addr,
395 if( p_address->i_wfd != -1 )
399 net_StopRecv( p_address->i_wfd );
400 net_GetSockAddress( p_address->i_wfd, p_address->psz_machine,
403 /* removes scope if present */
404 ptr = strchr( p_address->psz_machine, '%' );
409 if( p_sap->b_control == VLC_TRUE )
411 p_address->i_rfd = net_OpenUDP( p_sap, psz_addr,
412 p_address->i_port, "", 0 );
413 if( p_address->i_rfd != -1 )
414 net_StopSend( p_address->i_rfd );
415 p_address->i_buff = 0;
416 p_address->b_enabled = VLC_TRUE;
417 p_address->b_ready = VLC_FALSE;
418 p_address->i_limit = 10000; /* 10000 bps */
423 p_address->b_enabled = VLC_TRUE;
424 p_address->b_ready = VLC_TRUE;
425 p_address->i_interval = config_GetInt( p_sap,"sap-interval");
426 p_address->i_rfd = -1;
429 if( p_address->i_wfd == -1 || (p_address->i_rfd == -1
430 && p_sap->b_control ) )
432 msg_Warn( p_sap, "disabling address" );
433 p_address->b_enabled = VLC_FALSE;
436 INSERT_ELEM( p_sap->pp_addresses,
440 p_sap_session->p_address = p_address;
444 /* Build the SAP Headers */
445 i_header_size = ( b_ipv6 ? 16 : 4 ) + 20;
446 psz_head = (char *) malloc( i_header_size * sizeof( char ) );
447 if( psz_head == NULL )
449 msg_Err( p_sap, "out of memory" );
453 /* SAPv1, not encrypted, not compressed */
454 psz_head[0] = b_ipv6 ? 0x30 : 0x20;
455 psz_head[1] = 0x00; /* No authentification length */
458 psz_head[2] = (i_hash & 0xFF00) >> 8; /* Msg id hash */
459 psz_head[3] = (i_hash & 0xFF); /* Msg id hash 2 */
461 inet_pton( b_ipv6 ? AF_INET6 : AF_INET, /* can't fail */
462 p_sap_session->p_address->psz_machine, psz_head + 4 );
464 memcpy( psz_head + (b_ipv6 ? 20 : 8), "application/sdp", 15 );
466 /* If needed, build the SDP */
467 if( p_session->psz_sdp == NULL )
469 p_session->psz_sdp = SDPGenerate( p_sap, p_session,
470 p_sap_session->p_address );
471 if( p_session->psz_sdp == NULL )
473 vlc_mutex_unlock( &p_sap->object_lock );
478 p_sap_session->psz_sdp = strdup( p_session->psz_sdp );
479 p_sap_session->i_last = 0;
481 psz_head[ i_header_size-1 ] = '\0';
482 p_sap_session->i_length = i_header_size + strlen( p_sap_session->psz_sdp);
484 p_sap_session->psz_data = (uint8_t *)malloc( sizeof(char)*
485 p_sap_session->i_length );
487 /* Build the final message */
488 memcpy( p_sap_session->psz_data, psz_head, i_header_size );
489 memcpy( p_sap_session->psz_data+i_header_size, p_sap_session->psz_sdp,
490 strlen( p_sap_session->psz_sdp) );
494 /* Enqueue the announce */
495 INSERT_ELEM( p_sap->pp_sessions,
499 msg_Dbg( p_sap,"Addresses: %i Sessions: %i",
500 p_sap->i_addresses,p_sap->i_sessions);
502 /* Remember the SAP session for later deletion */
503 p_session->p_sap = p_sap_session;
505 vlc_mutex_unlock( &p_sap->object_lock );
510 /* Remove a SAP Announce */
511 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
512 session_descriptor_t *p_session )
515 vlc_mutex_lock( &p_sap->object_lock );
517 msg_Dbg( p_sap,"removing SAP announce %p",p_session->p_sap);
519 /* Dequeue the announce */
520 for( i = 0; i< p_sap->i_sessions; i++)
522 if( p_session->p_sap == p_sap->pp_sessions[i] )
524 REMOVE_ELEM( p_sap->pp_sessions,
528 FREE( p_session->p_sap->psz_sdp );
529 FREE( p_session->p_sap->psz_data );
530 free( p_session->p_sap );
535 /* XXX: Dequeue the address too if it is not used anymore
536 * TODO: - address refcount
537 - send a SAP deletion packet */
539 msg_Dbg( p_sap,"%i announces remaining", p_sap->i_sessions );
541 vlc_mutex_unlock( &p_sap->object_lock );
546 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
547 sap_session_t *p_session )
551 /* This announce has never been sent yet */
552 if( p_session->i_last == 0 )
554 p_session->i_next = mdate()+ p_session->p_address->i_interval*1000000;
555 p_session->i_last = 1;
559 if( p_session->i_next < mdate() )
562 msg_Dbg( p_sap, "Sending announce");
564 i_ret = net_Write( p_sap, p_session->p_address->i_wfd, NULL,
566 p_session->i_length );
567 if( i_ret != (int)p_session->i_length )
569 msg_Warn( p_sap, "SAP send failed on address %s (%i %i)",
570 p_session->p_address->psz_address,
571 i_ret, p_session->i_length );
573 p_session->i_last = p_session->i_next;
574 p_session->i_next = p_session->i_last
575 + p_session->p_address->i_interval*1000000;
584 static char *SDPGenerate( sap_handler_t *p_sap,
585 const session_descriptor_t *p_session,
586 const sap_address_t *p_addr )
588 int64_t i_sdp_id = mdate();
589 int i_sdp_version = 1 + p_sap->i_sessions + (rand()&0xfff);
590 char *psz_group, *psz_name, psz_uribuf[NI_MAXNUMERICHOST], *psz_uri,
594 psz_group = convert_to_utf8( p_sap, p_session->psz_group );
595 psz_name = convert_to_utf8( p_sap, p_session->psz_name );
596 if( psz_name == NULL )
602 /* FIXME: really check that psz_uri is a real IP address
603 * FIXME: make a common function to obtain a canonical IP address */
604 ipv = ( strchr( p_session->psz_uri, ':' ) != NULL) ? '6' : '4';
605 if( *p_session->psz_uri == '[' )
609 strncpy( psz_uribuf, p_session->psz_uri + 1, sizeof( psz_uribuf ) );
610 psz_uribuf[sizeof( psz_uribuf ) - 1] = '\0';
611 ptr = strchr( psz_uribuf, '%' );
614 ptr = strchr( psz_uribuf, ']' );
617 psz_uri = psz_uribuf;
620 psz_uri = p_session->psz_uri;
622 /* see the lists in modules/stream_out/rtp.c for compliance stuff */
623 if( asprintf( &psz_sdp,
625 "o=- "I64Fd" %d IN IP%c %s\r\n"
628 "c=IN IP%c %s/%d\r\n"
629 "m=video %d udp %d\r\n"
630 "a=tool:"PACKAGE_STRING"\r\n"
631 "a=type:broadcast\r\n",
632 i_sdp_id, i_sdp_version,
633 ipv, p_addr->psz_machine,
635 psz_uri, p_session->i_ttl,
636 p_session->i_port, p_session->i_payload ) == -1 )
647 /* FIXME: this is illegal use of sprintf */
648 sprintf( psz_sdp, "%sa=x-plgroup:%s\r\n", psz_sdp, psz_group );
652 msg_Dbg( p_sap, "Generated SDP (%i bytes):\n%s", strlen(psz_sdp),
657 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address )
660 uint8_t buffer[SAP_MAX_BUFFER];
665 if( p_address->t1 == 0 )
667 p_address->t1 = mdate();
672 /* Might be too slow if we have huge data */
673 i_read = net_ReadNonBlock( p_sap, p_address->i_rfd, NULL, buffer,
676 } while( i_read > 0 && i_tot < SAP_MAX_BUFFER );
680 /* We calculate the rate every 5 seconds */
681 if( i_temp - p_address->t1 < 5000000 )
683 p_address->i_buff += i_tot;
688 i_rate = (int)(8*1000000*((mtime_t)p_address->i_buff + (mtime_t)i_tot ) /
689 (i_temp - p_address->t1 ));
691 p_address->i_limit = 10000;
693 p_address->i_interval = ((1000*i_rate / p_address->i_limit) *
694 (MAX_INTERVAL - MIN_INTERVAL))/1000 + MIN_INTERVAL;
696 if( p_address->i_interval > MAX_INTERVAL || p_address->i_interval < 0 )
698 p_address->i_interval = MAX_INTERVAL;
701 msg_Dbg( p_sap,"%s:%i : Rate=%i, Interval = %i s",
702 p_address->psz_address,p_address->i_port,
704 p_address->i_interval );
707 p_address->b_ready = VLC_TRUE;
709 p_address->t1 = i_temp;
710 p_address->i_buff = 0;
716 static char *convert_to_utf8( struct sap_handler_t *p_this, char *psz_local )
718 char *psz_unicode, *psz_in, *psz_out;
719 size_t ret, i_in, i_out;
721 if( psz_local == NULL )
723 if ( p_this->iconvHandle == (vlc_iconv_t)(-1) )
724 return strdup( psz_local );
727 i_in = strlen( psz_local );
730 psz_unicode = malloc( i_out + 1 );
731 if( psz_unicode == NULL )
732 return strdup( psz_local );
733 psz_out = psz_unicode;
735 ret = vlc_iconv( p_this->iconvHandle,
736 &psz_in, &i_in, &psz_out, &i_out);
737 if( ret == (size_t)(-1) || i_in )
739 msg_Warn( p_this, "Failed to convert \"%s\" to UTF-8", psz_local );
741 return strdup( psz_local );