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