]> git.sesse.net Git - vlc/blob - src/stream_output/sap.c
sap: Set the sap announcer object name.
[vlc] / src / stream_output / sap.c
1 /*****************************************************************************
2  * sap.c : SAP announce handler
3  *****************************************************************************
4  * Copyright (C) 2002-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Clément Stenac <zorglub@videolan.org>
8  *          Rémi Denis-Courmont <rem # videolan.org>
9  *
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.
14  *
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.
19  *
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc/vlc.h>
34
35 #include <stdlib.h>                                                /* free() */
36 #include <stdio.h>                                              /* sprintf() */
37 #include <string.h>
38 #include <ctype.h>                                  /* tolower(), isxdigit() */
39 #include <assert.h>
40
41 #include <vlc_sout.h>
42 #include <vlc_network.h>
43 #include <vlc_charset.h>
44
45 #include "stream_output.h"
46
47 /* SAP is always on that port */
48 #define SAP_PORT 9875
49
50 #define DEFAULT_PORT "1234"
51
52 #undef EXTRA_DEBUG
53
54 /* SAP Specific structures */
55
56 /* 100ms */
57 #define SAP_IDLE ((mtime_t)(0.100*CLOCK_FREQ))
58 #define SAP_MAX_BUFFER 65534
59 #define MIN_INTERVAL 2
60 #define MAX_INTERVAL 300
61
62 /* A SAP announce address. For each of these, we run the
63  * control flow algorithm */
64 struct sap_address_t
65 {
66     char *psz_address;
67     struct sockaddr_storage orig;
68     socklen_t origlen;
69     int i_rfd; /* Read socket */
70     int i_wfd; /* Write socket */
71
72     /* Used for flow control */
73     mtime_t t1;
74     vlc_bool_t b_enabled;
75     vlc_bool_t b_ready;
76     int i_interval;
77     int i_buff;
78     int i_limit;
79 };
80
81 /* A SAP session descriptor, enqueued in the SAP handler queue */
82 struct sap_session_t {
83     uint8_t       *psz_data;
84     unsigned      i_length;
85     sap_address_t *p_address;
86     session_descriptor_t *p_sd;
87
88     /* Last and next send */
89     mtime_t        i_last;
90     mtime_t        i_next;
91 };
92
93 /*****************************************************************************
94  * Local prototypes
95  *****************************************************************************/
96 static void RunThread( vlc_object_t *p_this);
97 static int ComputeRate( sap_address_t *p_address );
98
99 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
100                                      sap_session_t *p_session );
101
102
103 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
104                              session_descriptor_t *p_session );
105
106 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
107                              session_descriptor_t *p_session );
108
109 static void announce_SAPHandlerDestructor( vlc_object_t *p_this );
110
111
112 /**
113  * Create the SAP handler
114  *
115  * \param p_announce the parent announce_handler
116  * \return the newly created SAP handler or NULL on error
117  */
118 sap_handler_t *announce_SAPHandlerCreate( announce_handler_t *p_announce )
119 {
120     sap_handler_t *p_sap;
121
122     p_sap = vlc_object_create( p_announce, sizeof( sap_handler_t ) );
123     if( !p_sap )
124     {
125         msg_Err( p_announce, "out of memory" );
126         return NULL;
127     }
128
129     p_sap->psz_object_name = "sap announcer";
130
131     vlc_mutex_init( p_sap, &p_sap->object_lock );
132
133     p_sap->pf_add = announce_SAPAnnounceAdd;
134     p_sap->pf_del = announce_SAPAnnounceDel;
135
136     p_sap->i_sessions = 0;
137     p_sap->i_addresses = 0;
138     p_sap->i_current_session = 0;
139
140     p_sap->b_control = config_GetInt( p_sap, "sap-flow-control");
141
142     if( vlc_thread_create( p_sap, "sap handler", RunThread,
143                        VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
144     {
145         msg_Dbg( p_announce, "unable to spawn SAP handler thread");
146         vlc_object_release( p_sap );
147         return NULL;
148     }
149
150     vlc_object_set_destructor( p_sap, announce_SAPHandlerDestructor );
151
152     msg_Dbg( p_announce, "thread created, %i sessions", p_sap->i_sessions);
153
154     return p_sap;
155 }
156
157 static void announce_SAPHandlerDestructor( vlc_object_t * p_this )
158 {
159     sap_handler_t *p_sap = (sap_handler_t *)p_this;
160     int i;
161
162     /* Free the remaining sessions */
163     for( i = 0 ; i< p_sap->i_sessions ; i++)
164     {
165         sap_session_t *p_session = p_sap->pp_sessions[i];
166         FREENULL( p_session->psz_data );
167         REMOVE_ELEM( p_sap->pp_sessions, p_sap->i_sessions , i );
168         FREENULL( p_session );
169     }
170
171     /* Free the remaining addresses */
172     for( i = 0 ; i< p_sap->i_addresses ; i++)
173     {
174         sap_address_t *p_address = p_sap->pp_addresses[i];
175         FREENULL( p_address->psz_address );
176         if( p_address->i_rfd > -1 )
177         {
178             net_Close( p_address->i_rfd );
179         }
180         if( p_address->i_wfd > -1 && p_sap->b_control )
181         {
182             net_Close( p_address->i_wfd );
183         }
184         REMOVE_ELEM( p_sap->pp_addresses, p_sap->i_addresses, i );
185         FREENULL( p_address );
186     }
187 }
188
189 /**
190  * main SAP handler thread
191  * \param p_this the SAP Handler object
192  * \return nothing
193  */
194 static void RunThread( vlc_object_t *p_this)
195 {
196     sap_handler_t *p_sap = (sap_handler_t*)p_this;
197     sap_session_t *p_session;
198
199     while( !p_sap->b_die )
200     {
201         int i;
202
203         /* If needed, get the rate info */
204         if( p_sap->b_control == VLC_TRUE )
205         {
206             for( i = 0 ; i< p_sap->i_addresses ; i++)
207             {
208                 if( p_sap->pp_addresses[i]->b_enabled == VLC_TRUE )
209                 {
210                     ComputeRate( p_sap->pp_addresses[i] );
211                 }
212             }
213         }
214
215         /* Find the session to announce */
216         vlc_mutex_lock( &p_sap->object_lock );
217         if( p_sap->i_sessions > p_sap->i_current_session + 1)
218         {
219             p_sap->i_current_session++;
220         }
221         else if( p_sap->i_sessions > 0)
222         {
223             p_sap->i_current_session = 0;
224         }
225         else
226         {
227             vlc_mutex_unlock( &p_sap->object_lock );
228             msleep( SAP_IDLE );
229             continue;
230         }
231         p_session = p_sap->pp_sessions[p_sap->i_current_session];
232         vlc_mutex_unlock( &p_sap->object_lock );
233
234         /* And announce it */
235         if( p_session->p_address->b_enabled == VLC_TRUE &&
236             p_session->p_address->b_ready == VLC_TRUE )
237         {
238             announce_SendSAPAnnounce( p_sap, p_session );
239         }
240
241         msleep( SAP_IDLE );
242     }
243 }
244
245 /* Add a SAP announce */
246 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
247                              session_descriptor_t *p_session )
248 {
249     int i;
250     char psz_addr[NI_MAXNUMERICHOST];
251     vlc_bool_t b_ipv6 = VLC_FALSE, b_ssm = VLC_FALSE;
252     sap_session_t *p_sap_session;
253     mtime_t i_hash;
254     struct sockaddr_storage addr;
255     socklen_t addrlen;
256
257     vlc_mutex_lock( &p_sap->object_lock );
258     addrlen = p_session->addrlen;
259     if ((addrlen == 0) || (addrlen > sizeof (addr)))
260     {
261         vlc_mutex_unlock( &p_sap->object_lock );
262         msg_Err( p_sap, "No/invalid address specified for SAP announce" );
263         return VLC_EGENERIC;
264     }
265
266     /* Determine SAP multicast address automatically */
267     memcpy (&addr, &p_session->addr, addrlen);
268
269     switch( p_session->addr.ss_family )
270     {
271 #if defined (HAVE_INET_PTON) || defined (WIN32)
272         case AF_INET6:
273         {
274             /* See RFC3513 for list of valid IPv6 scopes */
275             struct in6_addr *a6 = &((struct sockaddr_in6 *)&addr)->sin6_addr;
276
277             memcpy( a6->s6_addr + 2, "\x00\x00\x00\x00\x00\x00"
278                    "\x00\x00\x00\x00\x00\x02\x7f\xfe", 14 );
279             if( IN6_IS_ADDR_MULTICAST( a6 ) )
280             {
281                 /* SSM <=> ff3x::/32 */
282                 b_ssm = (U32_AT (a6->s6_addr) & 0xfff0ffff) == 0xff300000;
283
284                 /* force flags to zero, preserve scope */
285                 a6->s6_addr[1] &= 0xf;
286             }
287             else
288                 /* Unicast IPv6 - assume global scope */
289                 memcpy( a6->s6_addr, "\xff\x0e", 2 );
290
291             b_ipv6 = VLC_TRUE;
292             break;
293         }
294 #endif
295
296         case AF_INET:
297         {
298             /* See RFC2365 for IPv4 scopes */
299             uint32_t ipv4;
300
301             ipv4 = ntohl( ((struct sockaddr_in *)&addr)->sin_addr.s_addr );
302             /* 224.0.0.0/24 => 224.0.0.255 */
303             if ((ipv4 & 0xffffff00) == 0xe0000000)
304                 ipv4 =  0xe00000ff;
305             else
306             /* 239.255.0.0/16 => 239.255.255.255 */
307             if ((ipv4 & 0xffff0000) == 0xefff0000)
308                 ipv4 =  0xefffffff;
309             else
310             /* 239.192.0.0/14 => 239.195.255.255 */
311             if ((ipv4 & 0xfffc0000) == 0xefc00000)
312                 ipv4 =  0xefc3ffff;
313             else
314             if ((ipv4 & 0xff000000) == 0xef000000)
315                 ipv4 = 0;
316             else
317             /* other addresses => 224.2.127.254 */
318             {
319                 /* SSM: 232.0.0.0/8 */
320                 b_ssm = (ipv4 >> 24) == 232;
321                 ipv4 = 0xe0027ffe;
322             }
323
324             if( ipv4 == 0 )
325             {
326                 msg_Err( p_sap, "Out-of-scope multicast address "
327                          "not supported by SAP" );
328                 vlc_mutex_unlock( &p_sap->object_lock );
329                 return VLC_EGENERIC;
330             }
331
332             ((struct sockaddr_in *)&addr)->sin_addr.s_addr = htonl( ipv4 );
333             break;
334         }
335
336         default:
337             vlc_mutex_unlock( &p_sap->object_lock );
338             msg_Err( p_sap, "Address family %d not supported by SAP",
339                      addr.ss_family );
340             return VLC_EGENERIC;
341     }
342
343     i = vlc_getnameinfo( (struct sockaddr *)&addr, addrlen,
344                          psz_addr, sizeof( psz_addr ), NULL, NI_NUMERICHOST );
345
346     if( i )
347     {
348         vlc_mutex_unlock( &p_sap->object_lock );
349         msg_Err( p_sap, "%s", vlc_gai_strerror( i ) );
350         return VLC_EGENERIC;
351     }
352
353     msg_Dbg( p_sap, "using SAP address: %s", psz_addr);
354
355     /* XXX: Check for dupes */
356     p_sap_session = (sap_session_t*)malloc(sizeof(sap_session_t));
357     p_sap_session->p_sd = p_session;
358     p_sap_session->p_address = NULL;
359
360     /* Add the address to the buffer */
361     for( i = 0; i < p_sap->i_addresses; i++)
362     {
363         if( !strcmp( psz_addr, p_sap->pp_addresses[i]->psz_address ) )
364         {
365             p_sap_session->p_address = p_sap->pp_addresses[i];
366             break;
367         }
368     }
369
370     if( p_sap_session->p_address == NULL )
371     {
372         sap_address_t *p_address = (sap_address_t *)
373                                     malloc( sizeof(sap_address_t) );
374         if( !p_address )
375         {
376             vlc_mutex_unlock( &p_sap->object_lock );
377             return VLC_ENOMEM;
378         }
379         p_address->psz_address = strdup( psz_addr );
380         p_address->i_wfd = net_ConnectUDP( VLC_OBJECT(p_sap), psz_addr, SAP_PORT, 255 );
381         if( p_address->i_wfd != -1 )
382         {
383             shutdown( p_address->i_wfd, SHUT_RD );
384             p_address->origlen = sizeof (p_address->orig);
385             getsockname (p_address->i_wfd, (struct sockaddr *)&p_address->orig,
386                          &p_address->origlen);
387         }
388
389         if( p_sap->b_control == VLC_TRUE )
390         {
391             p_address->i_rfd = net_ListenUDP1( (vlc_object_t*)p_sap, psz_addr, SAP_PORT );
392             if( p_address->i_rfd != -1 )
393                 shutdown( p_address->i_rfd, SHUT_WR );
394             p_address->i_buff = 0;
395             p_address->b_enabled = VLC_TRUE;
396             p_address->b_ready = VLC_FALSE;
397             p_address->i_limit = 10000; /* 10000 bps */
398             p_address->t1 = 0;
399         }
400         else
401         {
402             p_address->b_enabled = VLC_TRUE;
403             p_address->b_ready = VLC_TRUE;
404             p_address->i_interval = config_GetInt( p_sap,"sap-interval");
405             p_address->i_rfd = -1;
406         }
407
408         if( p_address->i_wfd == -1 || (p_address->i_rfd == -1
409                                         && p_sap->b_control ) )
410         {
411             msg_Warn( p_sap, "disabling address" );
412             p_address->b_enabled = VLC_FALSE;
413         }
414
415         INSERT_ELEM( p_sap->pp_addresses,
416                      p_sap->i_addresses,
417                      p_sap->i_addresses,
418                      p_address );
419         p_sap_session->p_address = p_address;
420     }
421
422     memcpy (&p_session->orig, &p_sap_session->p_address->orig,
423              p_session->origlen = p_sap_session->p_address->origlen);
424
425     size_t headsize = 20;
426     switch (p_session->orig.ss_family)
427     {
428 #ifdef AF_INET6
429         case AF_INET6:
430             headsize += 16;
431             break;
432 #endif
433         case AF_INET:
434             headsize += 4;
435             break;
436         default:
437             msg_Err( p_sap, "Address family %d not supported by SAP",
438                      addr.ss_family );
439             vlc_mutex_unlock( &p_sap->object_lock );
440             return VLC_EGENERIC;
441     }
442
443     /* If needed, build the SDP */
444     assert( p_session->psz_sdp != NULL );
445
446     p_sap_session->i_last = 0;
447     p_sap_session->i_length = headsize + strlen (p_session->psz_sdp);
448     p_sap_session->psz_data = malloc (p_sap_session->i_length + 1);
449     if (p_sap_session->psz_data == NULL)
450     {
451         free (p_session->psz_sdp);
452         vlc_mutex_unlock( &p_sap->object_lock );
453         return VLC_ENOMEM;
454     }
455
456     /* Build the SAP Headers */
457     uint8_t *psz_head = p_sap_session->psz_data;
458
459     /* SAPv1, not encrypted, not compressed */
460     psz_head[0] = 0x20;
461     psz_head[1] = 0x00; /* No authentification length */
462
463     i_hash = mdate();
464     psz_head[2] = i_hash >> 8; /* Msg id hash */
465     psz_head[3] = i_hash;      /* Msg id hash 2 */
466
467     headsize = 4;
468     switch (p_session->orig.ss_family)
469     {
470 #ifdef AF_INET6
471         case AF_INET6:
472         {
473             struct in6_addr *a6 =
474                 &((struct sockaddr_in6 *)&p_session->orig)->sin6_addr;
475             memcpy (psz_head + headsize, a6, 16);
476             psz_head[0] |= 0x10; /* IPv6 flag */
477             headsize += 16;
478             break;
479         }
480 #endif
481         case AF_INET:
482         {
483             uint32_t ipv4 =
484                 (((struct sockaddr_in *)&p_session->orig)->sin_addr.s_addr);
485             memcpy (psz_head + headsize, &ipv4, 4);
486             headsize += 4;
487             break;
488         }
489
490     }
491
492     memcpy (psz_head + headsize, "application/sdp", 16);
493     headsize += 16;
494
495     /* Build the final message */
496     strcpy( (char *)psz_head + headsize, p_session->psz_sdp);
497
498     /* Enqueue the announce */
499     INSERT_ELEM( p_sap->pp_sessions,
500                  p_sap->i_sessions,
501                  p_sap->i_sessions,
502                  p_sap_session );
503     msg_Dbg( p_sap,"%i addresses, %i sessions",
504                    p_sap->i_addresses,p_sap->i_sessions);
505
506     vlc_mutex_unlock( &p_sap->object_lock );
507
508     return VLC_SUCCESS;
509 }
510
511 /* Remove a SAP Announce */
512 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
513                              session_descriptor_t *p_session )
514 {
515     int i;
516     vlc_mutex_lock( &p_sap->object_lock );
517
518     msg_Dbg( p_sap, "removing session %p from SAP", p_session);
519
520     /* Dequeue the announce */
521     for( i = 0; i< p_sap->i_sessions; i++)
522     {
523         if( p_session == p_sap->pp_sessions[i]->p_sd )
524         {
525             sap_session_t *p_mysession = p_sap->pp_sessions[i];
526             REMOVE_ELEM( p_sap->pp_sessions,
527                          p_sap->i_sessions,
528                          i );
529
530             free( p_mysession->psz_data );
531             free( p_mysession );
532             break;
533         }
534     }
535
536     /* XXX: Dequeue the address too if it is not used anymore
537      * TODO: - address refcount
538              - send a SAP deletion packet */
539
540     msg_Dbg( p_sap,"%i announcements remaining", p_sap->i_sessions );
541
542     vlc_mutex_unlock( &p_sap->object_lock );
543
544     return VLC_SUCCESS;
545 }
546
547 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
548                                      sap_session_t *p_session )
549 {
550     int i_ret;
551
552     /* This announce has never been sent yet */
553     if( p_session->i_last == 0 )
554     {
555         p_session->i_next = mdate()+ p_session->p_address->i_interval*1000000;
556         p_session->i_last = 1;
557         return VLC_SUCCESS;
558     }
559
560     if( p_session->i_next < mdate() )
561     {
562 #ifdef EXTRA_DEBUG
563         msg_Dbg( p_sap, "sending announce");
564 #endif
565         i_ret = net_Write( p_sap, p_session->p_address->i_wfd, NULL,
566                            p_session->psz_data,
567                            p_session->i_length );
568         if( i_ret != (int)p_session->i_length )
569         {
570             msg_Warn( p_sap, "SAP send failed on address %s (%i %i)",
571                       p_session->p_address->psz_address,
572                       i_ret, p_session->i_length );
573         }
574         p_session->i_last = p_session->i_next;
575         p_session->i_next = p_session->i_last
576                             + p_session->p_address->i_interval*1000000;
577     }
578     return VLC_SUCCESS;
579 }
580
581 static int ComputeRate( sap_address_t *p_address )
582 {
583     uint8_t buffer[SAP_MAX_BUFFER];
584     ssize_t i_tot = 0;
585     mtime_t i_temp;
586     int i_rate;
587
588     if( p_address->t1 == 0 )
589     {
590         p_address->t1 = mdate();
591         return VLC_SUCCESS;
592     }
593     for (;;)
594     {
595         /* Might be too slow if we have huge data */
596         ssize_t i_read = recv( p_address->i_rfd, buffer, SAP_MAX_BUFFER, 0 );
597         if (i_read == -1)
598             break;
599         i_tot += i_read;
600     }
601
602     i_temp = mdate();
603
604     /* We calculate the rate every 5 seconds */
605     if( i_temp - p_address->t1 < 5000000 )
606     {
607         p_address->i_buff += i_tot;
608         return VLC_SUCCESS;
609     }
610
611     /* Bits/second */
612     i_rate = (int)(8*1000000*((mtime_t)p_address->i_buff + (mtime_t)i_tot ) /
613                         (i_temp - p_address->t1 ));
614
615     p_address->i_limit = 10000;
616
617     p_address->i_interval = ((1000*i_rate / p_address->i_limit) *
618                             (MAX_INTERVAL - MIN_INTERVAL))/1000 + MIN_INTERVAL;
619
620     if( p_address->i_interval > MAX_INTERVAL || p_address->i_interval < 0 )
621     {
622         p_address->i_interval = MAX_INTERVAL;
623     }
624 #ifdef EXTRA_DEBUG
625     msg_Dbg( p_sap,"%s:%i: rate=%i, interval = %i s",
626              p_address->psz_address,SAP_PORT, i_rate, p_address->i_interval );
627 #endif
628
629     p_address->b_ready = VLC_TRUE;
630
631     p_address->t1 = i_temp;
632     p_address->i_buff = 0;
633
634     return VLC_SUCCESS;
635 }