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