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