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