]> git.sesse.net Git - vlc/blob - src/stream_output/sap.c
Restore some kind of SAP support
[vlc] / src / stream_output / sap.c
1 /*****************************************************************************
2  * sap.c : SAP announce handler
3  *****************************************************************************
4  * Copyright (C) 2002-2005 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 #include <vlc/vlc.h>
30
31 #include <stdlib.h>                                                /* free() */
32 #include <stdio.h>                                              /* sprintf() */
33 #include <string.h>                                            /* strerror() */
34 #include <ctype.h>                                  /* tolower(), isxdigit() */
35
36 #include <vlc_sout.h>
37 #include <vlc_network.h>
38 #include <vlc_charset.h>
39
40 #include "stream_output.h"
41
42 /* SAP is always on that port */
43 #define SAP_PORT 9875
44
45 #define DEFAULT_PORT "1234"
46
47 #undef EXTRA_DEBUG
48
49 /* SAP Specific structures */
50
51 /* 100ms */
52 #define SAP_IDLE ((mtime_t)(0.100*CLOCK_FREQ))
53 #define SAP_MAX_BUFFER 65534
54 #define MIN_INTERVAL 2
55 #define MAX_INTERVAL 300
56
57 /* A SAP announce address. For each of these, we run the
58  * control flow algorithm */
59 struct sap_address_t
60 {
61     char *psz_address;
62     struct sockaddr_storage orig;
63     socklen_t origlen;
64     int i_rfd; /* Read socket */
65     int i_wfd; /* Write socket */
66
67     /* Used for flow control */
68     mtime_t t1;
69     vlc_bool_t b_enabled;
70     vlc_bool_t b_ready;
71     int i_interval;
72     int i_buff;
73     int i_limit;
74 };
75
76 /* A SAP session descriptor, enqueued in the SAP handler queue */
77 struct sap_session_t {
78     uint8_t       *psz_data;
79     unsigned      i_length;
80     sap_address_t *p_address;
81     session_descriptor_t *p_sd;
82
83     /* Last and next send */
84     mtime_t        i_last;
85     mtime_t        i_next;
86 };
87
88 /*****************************************************************************
89  * Local prototypes
90  *****************************************************************************/
91 static void RunThread( vlc_object_t *p_this);
92 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address );
93 static char *SDPGenerate( sap_handler_t *p_sap,
94                           const session_descriptor_t *p_session,
95                           const sap_address_t *p_addr, vlc_bool_t b_ssm );
96
97 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
98                                      sap_session_t *p_session );
99
100
101 static int announce_SAPAnnounceAdd( sap_handler_t *p_sap,
102                              session_descriptor_t *p_session );
103
104 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
105                              session_descriptor_t *p_session );
106
107
108 /**
109  * Create the SAP handler
110  *
111  * \param p_announce the parent announce_handler
112  * \return the newly created SAP handler or NULL on error
113  */
114 sap_handler_t *announce_SAPHandlerCreate( announce_handler_t *p_announce )
115 {
116     sap_handler_t *p_sap;
117
118     p_sap = vlc_object_create( p_announce, sizeof( sap_handler_t ) );
119
120     if( !p_sap )
121     {
122         msg_Err( p_announce, "out of memory" );
123         return NULL;
124     }
125
126     vlc_mutex_init( p_sap, &p_sap->object_lock );
127
128     p_sap->pf_add = announce_SAPAnnounceAdd;
129     p_sap->pf_del = announce_SAPAnnounceDel;
130
131     p_sap->i_sessions = 0;
132     p_sap->i_addresses = 0;
133     p_sap->i_current_session = 0;
134
135     p_sap->b_control = config_GetInt( p_sap, "sap-flow-control");
136
137     if( vlc_thread_create( p_sap, "sap handler", RunThread,
138                        VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
139     {
140         msg_Dbg( p_announce, "unable to spawn SAP handler thread");
141         free( p_sap );
142         return NULL;
143     };
144     msg_Dbg( p_announce, "thread created, %i sessions", p_sap->i_sessions);
145     return p_sap;
146 }
147
148 /**
149  *  Destroy the SAP handler
150  *  \param p_this the SAP Handler to destroy
151  *  \return nothing
152  */
153 void announce_SAPHandlerDestroy( sap_handler_t *p_sap )
154 {
155     int i;
156
157     vlc_mutex_destroy( &p_sap->object_lock );
158
159     /* Free the remaining sessions */
160     for( i = 0 ; i< p_sap->i_sessions ; i++)
161     {
162         sap_session_t *p_session = p_sap->pp_sessions[i];
163         FREENULL( p_session->psz_data );
164         REMOVE_ELEM( p_sap->pp_sessions, p_sap->i_sessions , i );
165         FREENULL( p_session );
166     }
167
168     /* Free the remaining addresses */
169     for( i = 0 ; i< p_sap->i_addresses ; i++)
170     {
171         sap_address_t *p_address = p_sap->pp_addresses[i];
172         FREENULL( p_address->psz_address );
173         if( p_address->i_rfd > -1 )
174         {
175             net_Close( p_address->i_rfd );
176         }
177         if( p_address->i_wfd > -1 && p_sap->b_control )
178         {
179             net_Close( p_address->i_wfd );
180         }
181         REMOVE_ELEM( p_sap->pp_addresses, p_sap->i_addresses, i );
182         FREENULL( p_address );
183     }
184
185     /* Free the structure */
186     vlc_object_destroy( p_sap );
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                     CalculateRate( p_sap, 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             /* FIXME FIXME FIXME */
325             if( ipv4 == 0 )
326             {
327                 msg_Err( p_sap, "Out-of-scope multicast address "
328                          "not supported by SAP" );
329                 vlc_mutex_unlock( &p_sap->object_lock );
330                 return VLC_EGENERIC;
331             }
332
333             ((struct sockaddr_in *)&addr)->sin_addr.s_addr = htonl( ipv4 );
334             break;
335         }
336
337         default:
338             vlc_mutex_unlock( &p_sap->object_lock );
339             msg_Err( p_sap, "Address family %d not supported by SAP",
340                      addr.ss_family );
341             return VLC_EGENERIC;
342     }
343
344     i = vlc_getnameinfo( (struct sockaddr *)&addr, addrlen,
345                          psz_addr, sizeof( psz_addr ), NULL, NI_NUMERICHOST );
346
347     if( i )
348     {
349         vlc_mutex_unlock( &p_sap->object_lock );
350         msg_Err( p_sap, "%s", vlc_gai_strerror( i ) );
351         return VLC_EGENERIC;
352     }
353
354     msg_Dbg( p_sap, "using SAP address: %s", psz_addr);
355
356     /* XXX: Check for dupes */
357     p_sap_session = (sap_session_t*)malloc(sizeof(sap_session_t));
358     p_sap_session->p_sd = p_session;
359     p_sap_session->p_address = NULL;
360
361     /* Add the address to the buffer */
362     for( i = 0; i < p_sap->i_addresses; i++)
363     {
364         if( !strcmp( psz_addr, p_sap->pp_addresses[i]->psz_address ) )
365         {
366             p_sap_session->p_address = p_sap->pp_addresses[i];
367             break;
368         }
369     }
370
371     if( p_sap_session->p_address == NULL )
372     {
373         sap_address_t *p_address = (sap_address_t *)
374                                     malloc( sizeof(sap_address_t) );
375         if( !p_address )
376         {
377             vlc_mutex_unlock( &p_sap->object_lock );
378             return VLC_ENOMEM;
379         }
380         p_address->psz_address = strdup( psz_addr );
381         p_address->i_wfd = net_ConnectUDP( VLC_OBJECT(p_sap), psz_addr, SAP_PORT, 255 );
382         if( p_address->i_wfd != -1 )
383         {
384             net_StopRecv( p_address->i_wfd );
385             p_address->origlen = sizeof (p_address->orig);
386             getsockname (p_address->i_wfd, (struct sockaddr *)&p_address->orig,
387                          &p_address->origlen);
388         }
389
390         if( p_sap->b_control == VLC_TRUE )
391         {
392             p_address->i_rfd = net_ListenUDP1( (vlc_object_t*)p_sap, psz_addr, SAP_PORT );
393             if( p_address->i_rfd != -1 )
394                 net_StopSend( p_address->i_rfd );
395             p_address->i_buff = 0;
396             p_address->b_enabled = VLC_TRUE;
397             p_address->b_ready = VLC_FALSE;
398             p_address->i_limit = 10000; /* 10000 bps */
399             p_address->t1 = 0;
400         }
401         else
402         {
403             p_address->b_enabled = VLC_TRUE;
404             p_address->b_ready = VLC_TRUE;
405             p_address->i_interval = config_GetInt( p_sap,"sap-interval");
406             p_address->i_rfd = -1;
407         }
408
409         if( p_address->i_wfd == -1 || (p_address->i_rfd == -1
410                                         && p_sap->b_control ) )
411         {
412             msg_Warn( p_sap, "disabling address" );
413             p_address->b_enabled = VLC_FALSE;
414         }
415
416         INSERT_ELEM( p_sap->pp_addresses,
417                      p_sap->i_addresses,
418                      p_sap->i_addresses,
419                      p_address );
420         p_sap_session->p_address = p_address;
421     }
422
423     if (p_session->origlen == 0)
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     if( p_session->psz_sdp == NULL )
447     {
448         p_session->psz_sdp = SDPGenerate( p_sap, p_session,
449                                           p_sap_session->p_address, b_ssm );
450         if( p_session->psz_sdp == NULL )
451         {
452             vlc_mutex_unlock( &p_sap->object_lock );
453             return VLC_ENOMEM;
454         }
455     }
456
457     p_sap_session->i_last = 0;
458     p_sap_session->i_length = headsize + strlen (p_session->psz_sdp);
459     p_sap_session->psz_data = malloc (p_sap_session->i_length + 1);
460     if (p_sap_session->psz_data == NULL)
461     {
462         free (p_session->psz_sdp);
463         vlc_mutex_unlock( &p_sap->object_lock );
464         return VLC_ENOMEM;
465     }
466
467     /* Build the SAP Headers */
468     uint8_t *psz_head = p_sap_session->psz_data;
469
470     /* SAPv1, not encrypted, not compressed */
471     psz_head[0] = 0x20;
472     psz_head[1] = 0x00; /* No authentification length */
473
474     i_hash = mdate();
475     psz_head[2] = i_hash >> 8; /* Msg id hash */
476     psz_head[3] = i_hash;      /* Msg id hash 2 */
477
478     headsize = 4;
479     switch (p_session->orig.ss_family)
480     {
481 #ifdef AF_INET6
482         case AF_INET6:
483         {
484             struct in6_addr *a6 =
485                 &((struct sockaddr_in6 *)&p_session->orig)->sin6_addr;
486             memcpy (psz_head + headsize, a6, 16);
487             psz_head[0] |= 0x10; /* IPv6 flag */
488             headsize += 16;
489             break;
490         }
491 #endif
492         case AF_INET:
493         {
494             uint32_t ipv4 =
495                 (((struct sockaddr_in *)&p_session->orig)->sin_addr.s_addr);
496             memcpy (psz_head + headsize, &ipv4, 4);
497             headsize += 4;
498             break;
499         }
500
501     }
502
503     memcpy (psz_head + headsize, "application/sdp", 16);
504     headsize += 16;
505
506     /* Build the final message */
507     strcpy( (char *)psz_head + headsize, p_session->psz_sdp);
508
509     /* Enqueue the announce */
510     INSERT_ELEM( p_sap->pp_sessions,
511                  p_sap->i_sessions,
512                  p_sap->i_sessions,
513                  p_sap_session );
514     msg_Dbg( p_sap,"%i addresses, %i sessions",
515                    p_sap->i_addresses,p_sap->i_sessions);
516
517     vlc_mutex_unlock( &p_sap->object_lock );
518
519     return VLC_SUCCESS;
520 }
521
522 /* Remove a SAP Announce */
523 static int announce_SAPAnnounceDel( sap_handler_t *p_sap,
524                              session_descriptor_t *p_session )
525 {
526     int i;
527     vlc_mutex_lock( &p_sap->object_lock );
528
529     msg_Dbg( p_sap, "removing session %p from SAP", p_session);
530
531     /* Dequeue the announce */
532     for( i = 0; i< p_sap->i_sessions; i++)
533     {
534         if( p_session == p_sap->pp_sessions[i]->p_sd )
535         {
536             sap_session_t *p_mysession = p_sap->pp_sessions[i];
537             REMOVE_ELEM( p_sap->pp_sessions,
538                          p_sap->i_sessions,
539                          i );
540
541             free( p_mysession->psz_data );
542             free( p_mysession );
543             break;
544         }
545     }
546
547     /* XXX: Dequeue the address too if it is not used anymore
548      * TODO: - address refcount
549              - send a SAP deletion packet */
550
551     msg_Dbg( p_sap,"%i announcements remaining", p_sap->i_sessions );
552
553     vlc_mutex_unlock( &p_sap->object_lock );
554
555     return VLC_SUCCESS;
556 }
557
558 static int announce_SendSAPAnnounce( sap_handler_t *p_sap,
559                                      sap_session_t *p_session )
560 {
561     int i_ret;
562
563     /* This announce has never been sent yet */
564     if( p_session->i_last == 0 )
565     {
566         p_session->i_next = mdate()+ p_session->p_address->i_interval*1000000;
567         p_session->i_last = 1;
568         return VLC_SUCCESS;
569     }
570
571     if( p_session->i_next < mdate() )
572     {
573 #ifdef EXTRA_DEBUG
574         msg_Dbg( p_sap, "sending announce");
575 #endif
576         i_ret = net_Write( p_sap, p_session->p_address->i_wfd, NULL,
577                            p_session->psz_data,
578                            p_session->i_length );
579         if( i_ret != (int)p_session->i_length )
580         {
581             msg_Warn( p_sap, "SAP send failed on address %s (%i %i)",
582                       p_session->p_address->psz_address,
583                       i_ret, p_session->i_length );
584         }
585         p_session->i_last = p_session->i_next;
586         p_session->i_next = p_session->i_last
587                             + p_session->p_address->i_interval*1000000;
588     }
589     else
590     {
591         return VLC_SUCCESS;
592     }
593     return VLC_SUCCESS;
594 }
595
596 static char *SDPGenerate( sap_handler_t *p_sap,
597                           const session_descriptor_t *p_session,
598                           const sap_address_t *p_addr, vlc_bool_t b_ssm )
599 {
600     char *psz_group, *psz_name, *psz_sdp;
601
602      char *head = StartSDP (p_session->psz_name, p_session->description,
603         p_session->url, p_session->email, p_session->phone,
604         (const struct sockaddr *)&p_session->orig, p_session->origlen,
605         (const struct sockaddr *)&p_session->addr, p_session->addrlen);
606     if (head == NULL)
607         return NULL;
608
609     psz_group = p_session->psz_group;
610     psz_name = p_session->psz_name;
611
612     char *plgroup;
613     if ((psz_group == NULL)
614      || (asprintf (&plgroup, "a=x-plgroup:%s\r\n", psz_group) == -1))
615         plgroup = NULL;
616
617     char *sfilter;
618 #if 0
619     if ((!b_ssm)
620      || (asprintf (&sfilter, "a=source-filter: incl IN IP%c * %s\r\n",
621                    ipv, p_addr->psz_machine) == -1))
622 #else
623 # warning FIXME: repair Source Specific Multicast
624 #endif
625         sfilter = NULL;
626
627     int res = asprintf (&psz_sdp, "%s" "%s" "%s"
628                         "m=video %d %s\r\n",
629                         head,
630                         plgroup ?: "",
631                         sfilter ?: "",
632                         net_GetPort ((const struct sockaddr *)&p_session->addr),
633                         p_session->sdpformat);
634     free (plgroup);
635     free (sfilter);
636
637     if (res == -1)
638         return NULL;
639
640     msg_Dbg( p_sap, "Generated SDP (%i bytes):\n%s", strlen(psz_sdp),
641              psz_sdp );
642     return psz_sdp;
643 }
644
645 static int CalculateRate( sap_handler_t *p_sap, sap_address_t *p_address )
646 {
647     int i_read;
648     uint8_t buffer[SAP_MAX_BUFFER];
649     int i_tot = 0;
650     mtime_t i_temp;
651     int i_rate;
652
653     if( p_address->t1 == 0 )
654     {
655         p_address->t1 = mdate();
656         return VLC_SUCCESS;
657     }
658     do
659     {
660         /* Might be too slow if we have huge data */
661         i_read = net_ReadNonBlock( p_sap, p_address->i_rfd, NULL, buffer,
662                                    SAP_MAX_BUFFER, 0 );
663         i_tot += i_read;
664     } while( i_read > 0 );
665
666     i_temp = mdate();
667
668     /* We calculate the rate every 5 seconds */
669     if( i_temp - p_address->t1 < 5000000 )
670     {
671         p_address->i_buff += i_tot;
672         return VLC_SUCCESS;
673     }
674
675     /* Bits/second */
676     i_rate = (int)(8*1000000*((mtime_t)p_address->i_buff + (mtime_t)i_tot ) /
677                         (i_temp - p_address->t1 ));
678
679     p_address->i_limit = 10000;
680
681     p_address->i_interval = ((1000*i_rate / p_address->i_limit) *
682                             (MAX_INTERVAL - MIN_INTERVAL))/1000 + MIN_INTERVAL;
683
684     if( p_address->i_interval > MAX_INTERVAL || p_address->i_interval < 0 )
685     {
686         p_address->i_interval = MAX_INTERVAL;
687     }
688 #ifdef EXTRA_DEBUG
689     msg_Dbg( p_sap,"%s:%i: rate=%i, interval = %i s",
690              p_address->psz_address,SAP_PORT, i_rate, p_address->i_interval );
691 #endif
692
693     p_address->b_ready = VLC_TRUE;
694
695     p_address->t1 = i_temp;
696     p_address->i_buff = 0;
697
698     return VLC_SUCCESS;
699 }