]> git.sesse.net Git - vlc/blob - src/stream_output/sap.c
sap: remove session_descriptor_t and rename sap_session_t
[vlc] / src / stream_output / sap.c
1 /*****************************************************************************
2  * sap.c : SAP announce handler
3  *****************************************************************************
4  * Copyright (C) 2002-2008 VLC authors and VideoLAN
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 it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <vlc_common.h>
30
31 #include <stdlib.h>                                                /* free() */
32 #include <stdio.h>                                              /* sprintf() */
33 #include <string.h>
34 #include <assert.h>
35
36 #include <vlc_sout.h>
37 #include <vlc_network.h>
38
39 #include "stream_output.h"
40 #include "libvlc.h"
41
42 /* SAP is always on that port */
43 #define IPPORT_SAP 9875
44
45 /* A SAP session descriptor, enqueued in the SAP handler queue */
46 struct session_descriptor_t
47 {
48     struct session_descriptor_t *next;
49     size_t  length;
50     uint8_t data[];
51 };
52
53 /* A SAP announce address. For each of these, we run the
54  * control flow algorithm */
55 typedef struct sap_address_t
56 {
57     struct sap_address_t   *next;
58
59     vlc_thread_t            thread;
60     vlc_mutex_t             lock;
61     vlc_cond_t              wait;
62
63     char                    group[NI_MAXNUMERICHOST];
64     struct sockaddr_storage orig;
65     socklen_t               origlen;
66     int                     fd;
67     unsigned                interval;
68
69     unsigned                session_count;
70     session_descriptor_t   *first;
71 } sap_address_t;
72
73 /* The SAP handler, running in a separate thread */
74 struct sap_handler_t
75 {
76     VLC_COMMON_MEMBERS
77
78     vlc_mutex_t    lock;
79     sap_address_t *first;
80 };
81
82 #define SAP_MAX_BUFFER 65534
83 #define MIN_INTERVAL 2
84 #define MAX_INTERVAL 300
85
86 static void *RunThread (void *);
87
88 /**
89  * Create the SAP handler
90  *
91  * \param p_announce a VLC object
92  * \return the newly created SAP handler or NULL on error
93  */
94 static sap_handler_t *SAP_Create (vlc_object_t *p_announce)
95 {
96     sap_handler_t *p_sap;
97
98     p_sap = vlc_custom_create (p_announce, sizeof (*p_sap), "sap sender");
99     if (p_sap == NULL)
100         return NULL;
101
102     vlc_mutex_init (&p_sap->lock);
103     p_sap->first = NULL;
104     return p_sap;
105 }
106
107 static void SAP_Destroy (sap_handler_t *p_sap)
108 {
109     assert (p_sap->first == NULL);
110     vlc_mutex_destroy (&p_sap->lock);
111     vlc_object_release (p_sap);
112 }
113
114 static sap_address_t *AddressCreate (vlc_object_t *obj, const char *group)
115 {
116     int fd = net_ConnectUDP (obj, group, IPPORT_SAP, 255);
117     if (fd == -1)
118         return NULL;
119
120     sap_address_t *addr = malloc (sizeof (*addr));
121     if (addr == NULL)
122     {
123         net_Close (fd);
124         return NULL;
125     }
126
127     strlcpy (addr->group, group, sizeof (addr->group));
128     addr->fd = fd;
129     addr->origlen = sizeof (addr->orig);
130     getsockname (fd, (struct sockaddr *)&addr->orig, &addr->origlen);
131
132     addr->interval = var_CreateGetInteger (obj, "sap-interval");
133     vlc_mutex_init (&addr->lock);
134     vlc_cond_init (&addr->wait);
135     addr->session_count = 0;
136     addr->first = NULL;
137
138     if (vlc_clone (&addr->thread, RunThread, addr, VLC_THREAD_PRIORITY_LOW))
139     {
140         msg_Err (obj, "unable to spawn SAP announce thread");
141         net_Close (fd);
142         free (addr);
143         return NULL;
144     }
145     return addr;
146 }
147
148 static void AddressDestroy (sap_address_t *addr)
149 {
150     assert (addr->first == NULL);
151
152     vlc_cancel (addr->thread);
153     vlc_join (addr->thread, NULL);
154     vlc_cond_destroy (&addr->wait);
155     vlc_mutex_destroy (&addr->lock);
156     net_Close (addr->fd);
157     free (addr);
158 }
159
160 /**
161  * main SAP handler thread
162  * \param p_this the SAP Handler object
163  * \return nothing
164  */
165 VLC_NORETURN
166 static void *RunThread (void *self)
167 {
168     sap_address_t *addr = self;
169
170     vlc_mutex_lock (&addr->lock);
171     mutex_cleanup_push (&addr->lock);
172
173     for (;;)
174     {
175         session_descriptor_t *p_session;
176         mtime_t deadline;
177
178         while (addr->first == NULL)
179             vlc_cond_wait (&addr->wait, &addr->lock);
180
181         assert (addr->session_count > 0);
182
183         deadline = mdate ();
184         for (p_session = addr->first; p_session; p_session = p_session->next)
185         {
186             send (addr->fd, p_session->data, p_session->length, 0);
187             deadline += addr->interval * CLOCK_FREQ / addr->session_count;
188
189             if (vlc_cond_timedwait (&addr->wait, &addr->lock, deadline) == 0)
190                 break; /* list may have changed! */
191         }
192     }
193
194     vlc_cleanup_pop ();
195     assert (0);
196 }
197
198 /**
199  * Add a SAP announce
200  */
201 static session_descriptor_t *SAP_Add (sap_handler_t *p_sap,
202                                       const char *sdp, const char *dst)
203 {
204     int i;
205     char psz_addr[NI_MAXNUMERICHOST];
206     union
207     {
208         struct sockaddr     a;
209         struct sockaddr_in  in;
210         struct sockaddr_in6 in6;
211     } addr;
212     socklen_t addrlen = 0;
213     struct addrinfo *res;
214
215     if (vlc_getaddrinfo (dst, 0, NULL, &res) == 0)
216     {
217         if (res->ai_addrlen <= sizeof (addr))
218             memcpy (&addr, res->ai_addr, res->ai_addrlen);
219         addrlen = res->ai_addrlen;
220         freeaddrinfo (res);
221     }
222
223     if (addrlen == 0 || addrlen > sizeof (addr))
224     {
225         msg_Err( p_sap, "No/invalid address specified for SAP announce" );
226         return NULL;
227     }
228
229     /* Determine SAP multicast address automatically */
230     switch (addr.a.sa_family)
231     {
232 #if defined (HAVE_INET_PTON) || defined (_WIN32)
233         case AF_INET6:
234         {
235             /* See RFC3513 for list of valid IPv6 scopes */
236             struct in6_addr *a6 = &addr.in6.sin6_addr;
237
238             memcpy( a6->s6_addr + 2, "\x00\x00\x00\x00\x00\x00"
239                    "\x00\x00\x00\x00\x00\x02\x7f\xfe", 14 );
240             if( IN6_IS_ADDR_MULTICAST( a6 ) )
241                 /* force flags to zero, preserve scope */
242                 a6->s6_addr[1] &= 0xf;
243             else
244                 /* Unicast IPv6 - assume global scope */
245                 memcpy( a6->s6_addr, "\xff\x0e", 2 );
246             break;
247         }
248 #endif
249
250         case AF_INET:
251         {
252             /* See RFC2365 for IPv4 scopes */
253             uint32_t ipv4 = addr.in.sin_addr.s_addr;
254
255             /* 224.0.0.0/24 => 224.0.0.255 */
256             if ((ipv4 & htonl (0xffffff00)) == htonl (0xe0000000))
257                 ipv4 =  htonl (0xe00000ff);
258             else
259             /* 239.255.0.0/16 => 239.255.255.255 */
260             if ((ipv4 & htonl (0xffff0000)) == htonl (0xefff0000))
261                 ipv4 =  htonl (0xefffffff);
262             else
263             /* 239.192.0.0/14 => 239.195.255.255 */
264             if ((ipv4 & htonl (0xfffc0000)) == htonl (0xefc00000))
265                 ipv4 =  htonl (0xefc3ffff);
266             else
267             if ((ipv4 & htonl (0xff000000)) == htonl (0xef000000))
268                 ipv4 = 0;
269             else
270             /* other addresses => 224.2.127.254 */
271                 ipv4 = htonl (0xe0027ffe);
272
273             if( ipv4 == 0 )
274             {
275                 msg_Err( p_sap, "Out-of-scope multicast address "
276                          "not supported by SAP" );
277                 return NULL;
278             }
279
280             addr.in.sin_addr.s_addr = ipv4;
281             break;
282         }
283
284         default:
285             msg_Err( p_sap, "Address family %d not supported by SAP",
286                      addr.a.sa_family );
287             return NULL;
288     }
289
290     i = vlc_getnameinfo( &addr.a, addrlen,
291                          psz_addr, sizeof( psz_addr ), NULL, NI_NUMERICHOST );
292
293     if( i )
294     {
295         msg_Err( p_sap, "%s", gai_strerror( i ) );
296         return NULL;
297     }
298
299     /* Find/create SAP address thread */
300     msg_Dbg( p_sap, "using SAP address: %s", psz_addr);
301
302     vlc_mutex_lock (&p_sap->lock);
303     sap_address_t *sap_addr;
304     for (sap_addr = p_sap->first; sap_addr; sap_addr = sap_addr->next)
305         if (!strcmp (psz_addr, sap_addr->group))
306             break;
307
308     if (sap_addr == NULL)
309     {
310         sap_addr = AddressCreate (VLC_OBJECT(p_sap), psz_addr);
311         if (sap_addr == NULL)
312         {
313             vlc_mutex_unlock (&p_sap->lock);
314             return NULL;
315         }
316         sap_addr->next = p_sap->first;
317         p_sap->first = sap_addr;
318     }
319     /* Switch locks.
320      * NEVER take the global SAP lock when holding a SAP thread lock! */
321     vlc_mutex_lock (&sap_addr->lock);
322     vlc_mutex_unlock (&p_sap->lock);
323
324     size_t length = 20;
325     switch (sap_addr->orig.ss_family)
326     {
327 #ifdef AF_INET6
328         case AF_INET6:
329             length += 16;
330             break;
331 #endif
332         case AF_INET:
333             length += 4;
334             break;
335         default:
336             assert (0);
337     }
338
339     /* XXX: Check for dupes */
340     length += strlen (sdp);
341
342     session_descriptor_t *session = malloc (sizeof (*session) + length);
343     if (unlikely(session == NULL))
344     {
345         vlc_mutex_unlock (&sap_addr->lock);
346         return NULL; /* NOTE: we should destroy the thread if left unused */
347     }
348     session->next = sap_addr->first;
349     sap_addr->first = session;
350     session->length = length;
351
352     /* Build the SAP Headers */
353     uint8_t *buf = session->data;
354
355     /* SAPv1, not encrypted, not compressed */
356     buf[0] = 0x20;
357     buf[1] = 0x00; /* No authentication length */
358     SetWBE(buf + 2, mdate()); /* ID hash */
359
360     size_t offset = 4;
361     switch (sap_addr->orig.ss_family)
362     {
363 #ifdef AF_INET6
364         case AF_INET6:
365         {
366             const struct in6_addr *a6 =
367                 &((const struct sockaddr_in6 *)&sap_addr->orig)->sin6_addr;
368             memcpy (buf + offset, a6, 16);
369             buf[0] |= 0x10; /* IPv6 flag */
370             offset += 16;
371             break;
372         }
373 #endif
374         case AF_INET:
375         {
376             const struct in_addr *a4 =
377                 &((const struct sockaddr_in *)&sap_addr->orig)->sin_addr;
378             memcpy (buf + offset, a4, 4);
379             offset += 4;
380             break;
381         }
382
383     }
384
385     memcpy (buf + offset, "application/sdp", 16);
386     offset += 16;
387
388     /* Build the final message */
389     strcpy((char *)buf + offset, sdp);
390
391     sap_addr->session_count++;
392     vlc_cond_signal (&sap_addr->wait);
393     vlc_mutex_unlock (&sap_addr->lock);
394     return session;
395 }
396
397 /**
398  * Remove a SAP Announce
399  */
400 static void SAP_Del (sap_handler_t *p_sap, session_descriptor_t *session)
401 {
402     sap_address_t *addr, **paddr;
403     session_descriptor_t **psession;
404
405     vlc_mutex_lock (&p_sap->lock);
406     paddr = &p_sap->first;
407     for (;;)
408     {
409         addr = *paddr;
410         assert (addr != NULL);
411
412         psession = &addr->first;
413         vlc_mutex_lock (&addr->lock);
414         while (*psession != NULL)
415         {
416             if (*psession == session)
417                 goto found;
418             psession = &(*psession)->next;
419         }
420         vlc_mutex_unlock (&addr->lock);
421         paddr = &addr->next;
422     }
423
424 found:
425     *psession = session->next;
426
427     if (addr->first == NULL)
428         /* Last session for this address -> unlink the address */
429         *paddr = addr->next;
430     vlc_mutex_unlock (&p_sap->lock);
431
432     if (addr->first == NULL)
433     {
434         /* Last session for this address -> unlink the address */
435         vlc_mutex_unlock (&addr->lock);
436         AddressDestroy (addr);
437     }
438     else
439     {
440         addr->session_count--;
441         vlc_cond_signal (&addr->wait);
442         vlc_mutex_unlock (&addr->lock);
443     }
444
445     free (session);
446 }
447
448 /****************************************************************************
449  * Sout-side functions
450  ****************************************************************************/
451
452 static void sap_destroy (vlc_object_t *p_this)
453 {
454     libvlc_priv (p_this->p_libvlc)->p_sap = NULL;
455 }
456
457 #undef sout_AnnounceRegisterSDP
458
459 static vlc_mutex_t sap_mutex = VLC_STATIC_MUTEX;
460
461 /**
462  *  Registers a new session with the announce handler, using a pregenerated SDP
463  *
464  * \param obj a VLC object
465  * \param psz_sdp the SDP to register
466  * \param psz_dst session address (needed for SAP address auto detection)
467  * \return the new session descriptor structure
468  */
469 session_descriptor_t *
470 sout_AnnounceRegisterSDP( vlc_object_t *obj, const char *psz_sdp,
471                           const char *psz_dst )
472 {
473     vlc_mutex_lock (&sap_mutex);
474     sap_handler_t *p_sap = libvlc_priv (obj->p_libvlc)->p_sap;
475     if (p_sap == NULL)
476     {
477         p_sap = SAP_Create (VLC_OBJECT (obj->p_libvlc));
478         libvlc_priv (obj->p_libvlc)->p_sap = p_sap;
479         vlc_object_set_destructor ((vlc_object_t *)p_sap, sap_destroy);
480     }
481     else
482         vlc_object_hold ((vlc_object_t *)p_sap);
483     vlc_mutex_unlock (&sap_mutex);
484
485     if (p_sap == NULL)
486         return NULL;
487
488     msg_Dbg (obj, "adding SAP session");
489
490     session_descriptor_t *session = SAP_Add (p_sap, psz_sdp, psz_dst);
491     if (session == NULL)
492     {
493         vlc_mutex_lock (&sap_mutex);
494         vlc_object_release ((vlc_object_t *)p_sap);
495         vlc_mutex_unlock (&sap_mutex);
496     }
497     return session;
498 }
499
500 #undef sout_AnnounceUnRegister
501 /**
502  *  Unregisters an existing session
503  *
504  * \param obj a VLC object
505  * \param p_session the session descriptor
506  * \return VLC_SUCCESS or an error
507  */
508 int sout_AnnounceUnRegister( vlc_object_t *obj,
509                              session_descriptor_t *p_session )
510 {
511     sap_handler_t *p_sap = libvlc_priv (obj->p_libvlc)->p_sap;
512
513     msg_Dbg (obj, "removing SAP session");
514     SAP_Del (p_sap, p_session);
515
516     vlc_mutex_lock (&sap_mutex);
517     vlc_object_release ((vlc_object_t *)p_sap);
518     vlc_mutex_unlock (&sap_mutex);
519
520     return 0;
521 }