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