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