]> git.sesse.net Git - vlc/blob - modules/services_discovery/sap.c
sap: Don't release when not needed.
[vlc] / modules / services_discovery / sap.c
1 /*****************************************************************************
2  * sap.c :  SAP interface module
3  *****************************************************************************
4  * Copyright (C) 2004-2005 the VideoLAN team
5  * Copyright © 2007 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Clément Stenac <zorglub@videolan.org>
9  *          Rémi Denis-Courmont
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Includes
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <assert.h>
36
37 #include <vlc_demux.h>
38 #include <vlc_services_discovery.h>
39
40 #include <vlc_network.h>
41 #include <vlc_charset.h>
42
43 #include <ctype.h>
44 #include <errno.h>
45
46 #ifdef HAVE_UNISTD_H
47 #    include <unistd.h>
48 #endif
49 #ifdef HAVE_SYS_TIME_H
50 #    include <sys/time.h>
51 #endif
52 #ifdef HAVE_POLL
53 # include <poll.h>
54 #endif
55
56 #ifdef HAVE_ZLIB_H
57 #   include <zlib.h>
58 #endif
59
60 #ifndef WIN32
61 #   include <net/if.h>
62 #endif
63
64 /************************************************************************
65  * Macros and definitions
66  ************************************************************************/
67
68 #define MAX_LINE_LENGTH 256
69
70 /* SAP is always on that port */
71 #define SAP_PORT 9875
72 /* Global-scope SAP address */
73 #define SAP_V4_GLOBAL_ADDRESS   "224.2.127.254"
74 /* Organization-local SAP address */
75 #define SAP_V4_ORG_ADDRESS      "239.195.255.255"
76 /* Local (smallest non-link-local scope) SAP address */
77 #define SAP_V4_LOCAL_ADDRESS    "239.255.255.255"
78 /* Link-local SAP address */
79 #define SAP_V4_LINK_ADDRESS     "224.0.0.255"
80 #define ADD_SESSION 1
81
82 /*****************************************************************************
83  * Module descriptor
84  *****************************************************************************/
85 #define SAP_ADDR_TEXT N_( "SAP multicast address" )
86 #define SAP_ADDR_LONGTEXT N_( "The SAP module normally chooses itself the " \
87                               "right addresses to listen to. However, you " \
88                               "can specify a specific address." )
89 #define SAP_IPV4_TEXT N_( "IPv4 SAP" )
90 #define SAP_IPV4_LONGTEXT N_( \
91       "Listen to IPv4 announcements on the standard addresses." )
92 #define SAP_IPV6_TEXT N_( "IPv6 SAP" )
93 #define SAP_IPV6_LONGTEXT N_( \
94       "Listen to IPv6 announcements on the standard addresses." )
95 #define SAP_SCOPE_TEXT N_( "IPv6 SAP scope" )
96 #define SAP_SCOPE_LONGTEXT N_( \
97        "Scope for IPv6 announcements (default is 8)." )
98 #define SAP_TIMEOUT_TEXT N_( "SAP timeout (seconds)" )
99 #define SAP_TIMEOUT_LONGTEXT N_( \
100        "Delay after which SAP items get deleted if no new announcement " \
101        "is received." )
102 #define SAP_PARSE_TEXT N_( "Try to parse the announce" )
103 #define SAP_PARSE_LONGTEXT N_( \
104        "This enables actual parsing of the announces by the SAP module. " \
105        "Otherwise, all announcements are parsed by the \"live555\" " \
106        "(RTP/RTSP) module." )
107 #define SAP_STRICT_TEXT N_( "SAP Strict mode" )
108 #define SAP_STRICT_LONGTEXT N_( \
109        "When this is set, the SAP parser will discard some non-compliant " \
110        "announcements." )
111 #define SAP_CACHE_TEXT N_("Use SAP cache")
112 #define SAP_CACHE_LONGTEXT N_( \
113        "This enables a SAP caching mechanism. " \
114        "This will result in lower SAP startup time, but you could end up " \
115        "with items corresponding to legacy streams." )
116 #define SAP_TIMESHIFT_TEXT N_("Allow timeshifting")
117 #define SAP_TIMESHIFT_LONGTEXT N_( "This automatically enables timeshifting " \
118         "for streams discovered through SAP announcements." )
119
120 /* Callbacks */
121     static int  Open ( vlc_object_t * );
122     static void Close( vlc_object_t * );
123     static int  OpenDemux ( vlc_object_t * );
124     static void CloseDemux ( vlc_object_t * );
125
126 vlc_module_begin();
127     set_shortname( N_("SAP"));
128     set_description( N_("SAP Announcements") );
129     set_category( CAT_PLAYLIST );
130     set_subcategory( SUBCAT_PLAYLIST_SD );
131
132     add_string( "sap-addr", NULL, NULL,
133                 SAP_ADDR_TEXT, SAP_ADDR_LONGTEXT, true );
134     add_bool( "sap-ipv4", 1 , NULL,
135                SAP_IPV4_TEXT,SAP_IPV4_LONGTEXT, true );
136     add_bool( "sap-ipv6", 1 , NULL,
137               SAP_IPV6_TEXT, SAP_IPV6_LONGTEXT, true );
138     add_integer( "sap-timeout", 1800, NULL,
139                  SAP_TIMEOUT_TEXT, SAP_TIMEOUT_LONGTEXT, true );
140     add_bool( "sap-parse", 1 , NULL,
141                SAP_PARSE_TEXT,SAP_PARSE_LONGTEXT, true );
142     add_bool( "sap-strict", 0 , NULL,
143                SAP_STRICT_TEXT,SAP_STRICT_LONGTEXT, true );
144 #if 0
145     add_bool( "sap-cache", 0 , NULL,
146                SAP_CACHE_TEXT,SAP_CACHE_LONGTEXT, true );
147 #endif
148     add_bool( "sap-timeshift", 0 , NULL,
149               SAP_TIMESHIFT_TEXT,SAP_TIMESHIFT_LONGTEXT, true );
150
151     set_capability( "services_discovery", 0 );
152     set_callbacks( Open, Close );
153
154     add_submodule();
155         set_description( N_("SDP Descriptions parser") );
156         add_shortcut( "sdp" );
157         set_capability( "demux", 51 );
158         set_callbacks( OpenDemux, CloseDemux );
159 vlc_module_end();
160
161
162 /*****************************************************************************
163  * Local structures
164  *****************************************************************************/
165
166 typedef struct sdp_t sdp_t;
167 typedef struct attribute_t attribute_t;
168 typedef struct sap_announce_t sap_announce_t;
169
170
171 struct sdp_media_t
172 {
173     struct sdp_t           *parent;
174     char                   *fmt;
175     struct sockaddr_storage addr;
176     socklen_t               addrlen;
177     unsigned                n_addr;
178     int           i_attributes;
179     attribute_t  **pp_attributes;
180 };
181
182
183 /* The structure that contains sdp information */
184 struct  sdp_t
185 {
186     const char *psz_sdp;
187
188     /* o field */
189     char     username[64];
190     uint64_t session_id;
191     uint64_t session_version;
192     unsigned orig_ip_version;
193     char     orig_host[1024];
194
195     /* s= field */
196     char *psz_sessionname;
197
198     /* old cruft */
199     /* "computed" URI */
200     char *psz_uri;
201     int           i_media_type;
202
203     /* a= global attributes */
204     int           i_attributes;
205     attribute_t  **pp_attributes;
206
207     /* medias (well, we only support one atm) */
208     unsigned            mediac;
209     struct sdp_media_t *mediav;
210 };
211
212 struct attribute_t
213 {
214     const char *value;
215     char name[0];
216 };
217
218 struct sap_announce_t
219 {
220     mtime_t i_last;
221     mtime_t i_period;
222     uint8_t i_period_trust;
223
224     uint16_t    i_hash;
225     uint32_t    i_source[4];
226
227     /* SAP annnounces must only contain one SDP */
228     sdp_t       *p_sdp;
229
230     input_item_t * p_item;
231 };
232
233 struct services_discovery_sys_t
234 {
235     /* Socket descriptors */
236     int i_fd;
237     int *pi_fd;
238
239     /* Table of announces */
240     int i_announces;
241     struct sap_announce_t **pp_announces;
242
243     /* Modes */
244     bool  b_strict;
245     bool  b_parse;
246     bool  b_timeshift;
247
248     int i_timeout;
249 };
250
251 struct demux_sys_t
252 {
253     sdp_t *p_sdp;
254 };
255
256 /*****************************************************************************
257  * Local prototypes
258  *****************************************************************************/
259
260
261 /* Main functions */
262     static int Demux( demux_t *p_demux );
263     static int Control( demux_t *, int, va_list );
264     static void Run    ( services_discovery_t *p_sd );
265
266 /* Main parsing functions */
267     static int ParseConnection( vlc_object_t *p_obj, sdp_t *p_sdp );
268     static int ParseSAP( services_discovery_t *p_sd, const uint8_t *p_buffer, size_t i_read );
269     static sdp_t *ParseSDP (vlc_object_t *p_sd, const char *psz_sdp);
270     static sap_announce_t *CreateAnnounce( services_discovery_t *, uint16_t, sdp_t * );
271     static int RemoveAnnounce( services_discovery_t *p_sd, sap_announce_t *p_announce );
272
273 /* Helper functions */
274     static inline attribute_t *MakeAttribute (const char *str);
275     static const char *GetAttribute (attribute_t **tab, unsigned n, const char *name);
276     static inline void FreeAttribute (attribute_t *a);
277     static const char *FindAttribute (const sdp_t *sdp, unsigned media,
278                                       const char *name);
279
280     static bool IsSameSession( sdp_t *p_sdp1, sdp_t *p_sdp2 );
281     static int InitSocket( services_discovery_t *p_sd, const char *psz_address, int i_port );
282     static int Decompress( const unsigned char *psz_src, unsigned char **_dst, int i_len );
283     static void FreeSDP( sdp_t *p_sdp );
284
285 static inline int min_int( int a, int b )
286 {
287     return a > b ? b : a;
288 }
289
290 /*****************************************************************************
291  * Open: initialize and create stuff
292  *****************************************************************************/
293 static int Open( vlc_object_t *p_this )
294 {
295     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
296     services_discovery_sys_t *p_sys  = (services_discovery_sys_t *)
297                                 malloc( sizeof( services_discovery_sys_t ) );
298     if( !p_sys )
299         return VLC_ENOMEM;
300
301     p_sys->i_timeout = var_CreateGetInteger( p_sd, "sap-timeout" );
302
303     p_sd->pf_run = Run;
304     p_sd->p_sys  = p_sys;
305
306     p_sys->pi_fd = NULL;
307     p_sys->i_fd = 0;
308
309     p_sys->b_strict = var_CreateGetInteger( p_sd, "sap-strict");
310     p_sys->b_parse = var_CreateGetInteger( p_sd, "sap-parse" );
311
312 #if 0
313     if( var_CreateGetInteger( p_sd, "sap-cache" ) )
314     {
315         CacheLoad( p_sd );
316     }
317 #endif
318
319     /* Cache sap_timeshift value */
320     p_sys->b_timeshift = var_CreateGetInteger( p_sd, "sap-timeshift" );
321
322     /* Set our name */
323     services_discovery_SetLocalizedName( p_sd, _("SAP") );
324
325     p_sys->i_announces = 0;
326     p_sys->pp_announces = NULL;
327
328     return VLC_SUCCESS;
329 }
330
331 /*****************************************************************************
332  * OpenDemux: initialize and create stuff
333  *****************************************************************************/
334 static int OpenDemux( vlc_object_t *p_this )
335 {
336     demux_t *p_demux = (demux_t *)p_this;
337     const uint8_t *p_peek;
338     char *psz_sdp = NULL;
339     sdp_t *p_sdp = NULL;
340     int errval = VLC_EGENERIC;
341     size_t i_len;
342
343     if( !var_CreateGetInteger( p_demux, "sap-parse" ) )
344     {
345         /* We want livedotcom module to parse this SDP file */
346         return VLC_EGENERIC;
347     }
348
349     assert( p_demux->s ); /* this is NOT an access_demux */
350
351     /* Probe for SDP */
352     if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 )
353         return VLC_EGENERIC;
354
355     if( memcmp( p_peek, "v=0\r\no=", 7 ) && memcmp( p_peek, "v=0\no=", 6 ) )
356         return VLC_EGENERIC;
357
358     /* Gather the complete sdp file */
359     for( i_len = 0, psz_sdp = NULL; i_len < 65536; )
360     {
361         const int i_read_max = 1024;
362         char *psz_sdp_new = realloc( psz_sdp, i_len + i_read_max );
363         size_t i_read;
364         if( psz_sdp_new == NULL )
365         {
366             errval = VLC_ENOMEM;
367             goto error;
368         }
369         psz_sdp = psz_sdp_new;
370
371         i_read = stream_Read( p_demux->s, &psz_sdp[i_len], i_read_max );
372         if( (int)i_read < 0 )
373         {
374             msg_Err( p_demux, "cannot read SDP" );
375             goto error;
376         }
377         i_len += i_read;
378
379         psz_sdp[i_len] = '\0';
380
381         if( (int)i_read < i_read_max )
382             break; // EOF
383     }
384
385     p_sdp = ParseSDP( VLC_OBJECT(p_demux), psz_sdp );
386
387     if( !p_sdp )
388     {
389         msg_Warn( p_demux, "invalid SDP");
390         goto error;
391     }
392
393     if( ParseConnection( VLC_OBJECT( p_demux ), p_sdp ) )
394     {
395         p_sdp->psz_uri = NULL;
396     }
397     switch (p_sdp->i_media_type)
398     {   /* Should be in sync with modules/demux/rtp.c */
399         case  0: /* PCMU/8000 */
400         case  8: /* PCMA/8000 */
401         case 10: /* L16/44100/2 */
402         case 11: /* L16/44100 */
403         case 14: /* MPA/90000 */
404         case 32: /* MPV/90000 */
405         case 33: /* MP2/90000 */
406             break;
407         default:
408             goto error;
409     }
410     if( p_sdp->psz_uri == NULL ) goto error;
411
412     p_demux->p_sys = (demux_sys_t *)malloc( sizeof(demux_sys_t) );
413     p_demux->p_sys->p_sdp = p_sdp;
414     p_demux->pf_control = Control;
415     p_demux->pf_demux = Demux;
416
417     FREENULL( psz_sdp );
418     return VLC_SUCCESS;
419
420 error:
421     FREENULL( psz_sdp );
422     if( p_sdp ) FreeSDP( p_sdp ); p_sdp = NULL;
423     stream_Seek( p_demux->s, 0 );
424     return errval;
425 }
426
427 /*****************************************************************************
428  * Close:
429  *****************************************************************************/
430 static void Close( vlc_object_t *p_this )
431 {
432     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
433     services_discovery_sys_t    *p_sys  = p_sd->p_sys;
434
435     int i;
436
437     for( i = p_sys->i_fd-1 ; i >= 0 ; i-- )
438     {
439         net_Close( p_sys->pi_fd[i] );
440     }
441     FREENULL( p_sys->pi_fd );
442
443 #if 0
444     if( config_GetInt( p_sd, "sap-cache" ) )
445     {
446         CacheSave( p_sd );
447     }
448 #endif
449
450     for( i = p_sys->i_announces  - 1;  i>= 0; i-- )
451     {
452         RemoveAnnounce( p_sd, p_sys->pp_announces[i] );
453     }
454     FREENULL( p_sys->pp_announces );
455
456     free( p_sys );
457 }
458
459 /*****************************************************************************
460  * CloseDemux: Close the demuxer
461  *****************************************************************************/
462 static void CloseDemux( vlc_object_t *p_this )
463 {
464     demux_t *p_demux = (demux_t *)p_this;
465     if( p_demux->p_sys )
466     {
467         if( p_demux->p_sys->p_sdp ) { FreeSDP( p_demux->p_sys->p_sdp ); p_demux->p_sys->p_sdp = NULL; }
468         free( p_demux->p_sys );
469     }
470 }
471
472 /*****************************************************************************
473  * Run: main SAP thread
474  *****************************************************************************
475  * Listens to SAP packets, and sends them to packet_handle
476  *****************************************************************************/
477 #define MAX_SAP_BUFFER 5000
478
479 static void Run( services_discovery_t *p_sd )
480 {
481     char *psz_addr;
482     int i;
483     int timeout = -1;
484
485     /* Braindead Winsock DNS resolver will get stuck over 2 seconds per failed
486      * DNS queries, even if the DNS server returns an error with milliseconds.
487      * You don't want to know why the bug (as of XP SP2) wasn't fixed since
488      * Winsock 1.1 from Windows 95, if not Windows 3.1.
489      * Anyway, to avoid a 30 seconds delay for failed IPv6 socket creation,
490      * we have to open sockets in Run() rather than Open(). */
491     if( var_CreateGetInteger( p_sd, "sap-ipv4" ) )
492     {
493         InitSocket( p_sd, SAP_V4_GLOBAL_ADDRESS, SAP_PORT );
494         InitSocket( p_sd, SAP_V4_ORG_ADDRESS, SAP_PORT );
495         InitSocket( p_sd, SAP_V4_LOCAL_ADDRESS, SAP_PORT );
496         InitSocket( p_sd, SAP_V4_LINK_ADDRESS, SAP_PORT );
497     }
498     if( var_CreateGetInteger( p_sd, "sap-ipv6" ) )
499     {
500         char psz_address[NI_MAXNUMERICHOST] = "ff02::2:7ffe%";
501
502 #ifndef WIN32
503         struct if_nameindex *l = if_nameindex ();
504         if (l != NULL)
505         {
506             char *ptr = strchr (psz_address, '%') + 1;
507             for (unsigned i = 0; l[i].if_index; i++)
508             {
509                 strcpy (ptr, l[i].if_name);
510                 InitSocket (p_sd, psz_address, SAP_PORT);
511             }
512             if_freenameindex (l);
513         }
514 #else
515         /* this is the Winsock2 equivalant of SIOCGIFCONF on BSD stacks,
516            which if_nameindex uses internally anyway */
517
518         // first create a dummy socket to pin down the protocol family
519         SOCKET s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
520         if( s != INVALID_SOCKET )
521         {
522             INTERFACE_INFO ifaces[10]; // Assume there will be no more than 10 IP interfaces
523             size_t len = sizeof(ifaces);
524
525             if( SOCKET_ERROR != WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0, &ifaces, len, &len, NULL, NULL) )
526             {
527                 unsigned ifcount = len/sizeof(INTERFACE_INFO);
528                 char *ptr = strchr (psz_address, '%') + 1;
529                 for(unsigned i = 1; i<=ifcount; ++i )
530                 {
531                     // append link-local zone identifier
532                     sprintf(ptr, "%d", i);
533                 }
534             }
535             closesocket(s);
536         }
537 #endif
538         *strchr (psz_address, '%') = '\0';
539
540         static const char ipv6_scopes[] = "1456789ABCDE";
541         for (const char *c_scope = ipv6_scopes; *c_scope; c_scope++)
542         {
543             psz_address[3] = *c_scope;
544             InitSocket( p_sd, psz_address, SAP_PORT );
545         }
546     }
547
548     psz_addr = var_CreateGetString( p_sd, "sap-addr" );
549     if( psz_addr && *psz_addr )
550     {
551         InitSocket( p_sd, psz_addr, SAP_PORT );
552         free( psz_addr );
553     }
554
555     if( p_sd->p_sys->i_fd == 0 )
556     {
557         msg_Err( p_sd, "unable to listen on any address" );
558         return;
559     }
560
561     vlc_object_lock( p_sd );
562
563     /* read SAP packets */
564     while( vlc_object_alive( p_sd ) )
565     {
566         unsigned n = p_sd->p_sys->i_fd;
567         struct pollfd ufd[n+1];
568
569         for (unsigned i = 0; i < n; i++)
570         {
571             ufd[i].fd = p_sd->p_sys->pi_fd[i];
572             ufd[i].events = POLLIN;
573             ufd[i].revents = 0;
574         }
575
576         /* Make sure we track vlc_object_signal() */
577         ufd[n].fd = vlc_object_waitpipe( p_sd );
578         ufd[n].events = POLLIN | POLLHUP;
579         ufd[n].revents = 0;
580
581         if( ufd[n].fd == -1 )
582         {
583             /* On windows, fd will be -1, as we can't select on a pipe()-ed
584              * fildes. Because we have no other solution to track that
585              * object is killed, we make sure the timeout won't be to long. */
586             if( timeout > 1000 || timeout == -1 )
587                 timeout = 1000;
588         }
589
590         vlc_object_unlock( p_sd );
591
592         if (poll (ufd, n+1, timeout) > 0)
593         {
594             for (unsigned i = 0; i < n; i++)
595             {
596                 if (ufd[i].revents)
597                 {
598                     uint8_t p_buffer[MAX_SAP_BUFFER+1];
599                     ssize_t i_read;
600
601                     i_read = net_Read (p_sd, ufd[i].fd, NULL, p_buffer,
602                                        MAX_SAP_BUFFER, false);
603                     if (i_read < 0)
604                         msg_Warn (p_sd, "receive error: %m");
605                     if (i_read > 6)
606                     {
607                         /* Parse the packet */
608                         p_buffer[i_read] = '\0';
609                         ParseSAP (p_sd, p_buffer, i_read);
610                     }
611                 }
612             }
613         }
614
615         mtime_t now = mdate();
616
617         /* A 1 hour timeout correspong to the RFC Implicit timeout.
618          * This timeout is tuned in the following loop. */
619         timeout = 1000 * 60 * 60;
620
621         /* Check for items that need deletion */
622         for( i = 0; i < p_sd->p_sys->i_announces; i++ )
623         {
624             mtime_t i_timeout = ( mtime_t ) 1000000 * p_sd->p_sys->i_timeout;
625             sap_announce_t * p_announce = p_sd->p_sys->pp_announces[i];
626             mtime_t i_last_period = now - p_announce->i_last;
627
628             /* Remove the annoucement, if the last announcement was 1 hour ago
629              * or if the last packet emitted was 3 times the average time
630              * between two packets */
631             if( ( p_announce->i_period_trust > 5 && i_last_period > 3 * p_announce->i_period ) ||
632                 i_last_period > i_timeout )
633             {
634                 RemoveAnnounce( p_sd, p_announce );
635             }
636             else
637             {
638                 /* Compute next timeout */
639                 if( p_announce->i_period_trust > 5 )
640                     timeout = min_int((3 * p_announce->i_period - i_last_period) / 1000, timeout);
641                 timeout = min_int((i_timeout - i_last_period)/1000, timeout);
642             }
643         }
644
645         if( !p_sd->p_sys->i_announces )
646             timeout = -1; /* We can safely poll indefinitly. */
647         else if( timeout < 200 )
648             timeout = 200; /* Don't wakeup too fast. */
649
650         vlc_object_lock( p_sd );
651     }
652     vlc_object_unlock( p_sd );
653 }
654
655 /**********************************************************************
656  * Demux: reads and demuxes data packets
657  * Return -1 if error, 0 if EOF, 1 else
658  **********************************************************************/
659 static int Demux( demux_t *p_demux )
660 {
661     sdp_t *p_sdp = p_demux->p_sys->p_sdp;
662     input_thread_t *p_input;
663     input_item_t *p_parent_input;
664
665     p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT,
666                                                  FIND_PARENT );
667     assert( p_input );
668     if( !p_input )
669     {
670         msg_Err( p_demux, "parent input could not be found" );
671         return VLC_EGENERIC;
672     }
673
674     /* This item hasn't been yield by input_GetItem
675      * don't release it */
676     p_parent_input = input_GetItem( p_input );
677
678     input_item_SetURI( p_parent_input, p_sdp->psz_uri );
679     input_item_SetName( p_parent_input, p_sdp->psz_sessionname );
680
681     vlc_mutex_lock( &p_parent_input->lock );
682
683     p_parent_input->i_type = ITEM_TYPE_NET;
684
685     vlc_mutex_unlock( &p_parent_input->lock );
686     return VLC_SUCCESS;
687 }
688
689 static int Control( demux_t *p_demux, int i_query, va_list args )
690 {
691     VLC_UNUSED(p_demux); VLC_UNUSED(i_query); VLC_UNUSED(args);
692     return VLC_EGENERIC;
693 }
694
695 /**************************************************************
696  * Local functions
697  **************************************************************/
698
699 /* i_read is at least > 6 */
700 static int ParseSAP( services_discovery_t *p_sd, const uint8_t *buf,
701                      size_t len )
702 {
703     int i;
704     const char          *psz_sdp;
705     const uint8_t *end = buf + len;
706     sdp_t               *p_sdp;
707
708     assert (buf[len] == '\0');
709
710     if (len < 4)
711         return VLC_EGENERIC;
712
713     uint8_t flags = buf[0];
714
715     /* First, check the sap announce is correct */
716     if ((flags >> 5) != 1)
717         return VLC_EGENERIC;
718
719     bool b_ipv6 = (flags & 0x10) != 0;
720     bool b_need_delete = (flags & 0x04) != 0;
721
722     if (flags & 0x02)
723     {
724         msg_Dbg( p_sd, "encrypted packet, unsupported" );
725         return VLC_EGENERIC;
726     }
727
728     bool b_compressed = (flags & 0x01) != 0;
729
730     uint16_t i_hash = U16_AT (buf + 2);
731
732     if( p_sd->p_sys->b_strict && i_hash == 0 )
733     {
734         msg_Dbg( p_sd, "strict mode, discarding announce with null id hash");
735         return VLC_EGENERIC;
736     }
737
738     // Skips source address and auth data
739     buf += 4 + (b_ipv6 ? 16 : 4) + buf[1];
740     if (buf > end)
741         return VLC_EGENERIC;
742
743     uint8_t *decomp = NULL;
744     if( b_compressed )
745     {
746         int newsize = Decompress (buf, &decomp, end - buf);
747         if (newsize < 0)
748         {
749             msg_Dbg( p_sd, "decompression of SAP packet failed" );
750             return VLC_EGENERIC;
751         }
752
753         decomp = realloc (decomp, newsize + 1);
754         decomp[newsize] = '\0';
755         psz_sdp = (const char *)decomp;
756         len = newsize;
757     }
758     else
759     {
760         psz_sdp = (const char *)buf;
761         len = end - buf;
762     }
763
764     /* len is a strlen here here. both buf and decomp are len+1 where the 1 should be a \0 */
765     assert( psz_sdp[len] == '\0');
766
767     /* Skip payload type */
768     /* SAPv1 has implicit "application/sdp" payload type: first line is v=0 */
769     if (strncmp (psz_sdp, "v=0", 3))
770     {
771         size_t clen = strlen (psz_sdp) + 1;
772
773         if (strcmp (psz_sdp, "application/sdp"))
774         {
775             msg_Dbg (p_sd, "unsupported content type: %s", psz_sdp);
776             return VLC_EGENERIC;
777         }
778
779         // skips content type
780         if (len <= clen)
781             return VLC_EGENERIC;
782
783         len -= clen;
784         psz_sdp += clen;
785     }
786
787     /* Parse SDP info */
788     p_sdp = ParseSDP( VLC_OBJECT(p_sd), psz_sdp );
789
790     if( p_sdp == NULL )
791         return VLC_EGENERIC;
792
793     p_sdp->psz_sdp = psz_sdp;
794
795     /* Decide whether we should add a playlist item for this SDP */
796     /* Parse connection information (c= & m= ) */
797     if( ParseConnection( VLC_OBJECT(p_sd), p_sdp ) )
798         p_sdp->psz_uri = NULL;
799
800     /* Multi-media or no-parse -> pass to LIVE.COM */
801     if( ( p_sdp->i_media_type != 14
802        && p_sdp->i_media_type != 32
803        && p_sdp->i_media_type != 33)
804      || p_sd->p_sys->b_parse == false )
805     {
806         free( p_sdp->psz_uri );
807         if (asprintf( &p_sdp->psz_uri, "sdp://%s", p_sdp->psz_sdp ) == -1)
808             p_sdp->psz_uri = NULL;
809     }
810
811     if( p_sdp->psz_uri == NULL )
812     {
813         FreeSDP( p_sdp );
814         return VLC_EGENERIC;
815     }
816
817     for( i = 0 ; i< p_sd->p_sys->i_announces ; i++ )
818     {
819         sap_announce_t * p_announce = p_sd->p_sys->pp_announces[i];
820         /* FIXME: slow */
821         /* FIXME: we create a new announce each time the sdp changes */
822         if( IsSameSession( p_announce->p_sdp, p_sdp ) )
823         {
824             /* We don't support delete announcement as they can easily
825              * Be used to highjack an announcement by a third party.
826              * Intead we cleverly implement Implicit Announcement removal.
827              *
828              * if( b_need_delete )
829              *    RemoveAnnounce( p_sd, p_sd->p_sys->pp_announces[i]);
830              * else
831              */
832
833             if( !b_need_delete )
834             {
835                 /* No need to go after six, as we start to trust the
836                  * average period at six */
837                 if( p_announce->i_period_trust <= 5 )
838                     p_announce->i_period_trust++;
839
840                 /* Compute the average period */
841                 p_announce->i_period = (p_announce->i_period + (mdate() - p_announce->i_last)) / 2;
842                 p_announce->i_last = mdate();
843             }
844             FreeSDP( p_sdp ); p_sdp = NULL;
845             return VLC_SUCCESS;
846         }
847     }
848
849     CreateAnnounce( p_sd, i_hash, p_sdp );
850
851     FREENULL (decomp);
852     return VLC_SUCCESS;
853 }
854
855 sap_announce_t *CreateAnnounce( services_discovery_t *p_sd, uint16_t i_hash,
856                                 sdp_t *p_sdp )
857 {
858     input_item_t *p_input;
859     const char *psz_value;
860     sap_announce_t *p_sap = (sap_announce_t *)malloc(
861                                         sizeof(sap_announce_t ) );
862     services_discovery_sys_t *p_sys;
863     if( p_sap == NULL )
864         return NULL;
865
866     p_sys = p_sd->p_sys;
867
868     p_sap->i_last = mdate();
869     p_sap->i_period = 0;
870     p_sap->i_period_trust = 0;
871     p_sap->i_hash = i_hash;
872     p_sap->p_sdp = p_sdp;
873
874     /* Released in RemoveAnnounce */
875     p_input = input_ItemNewWithType( VLC_OBJECT(p_sd),
876                                      p_sap->p_sdp->psz_uri,
877                                      p_sdp->psz_sessionname,
878                                      0, NULL, -1, ITEM_TYPE_NET );
879     p_sap->p_item = p_input;
880     if( !p_input )
881     {
882         free( p_sap );
883         return NULL;
884     }
885
886     if( p_sys->b_timeshift )
887         input_ItemAddOption( p_input, ":access-filter=timeshift" );
888
889     psz_value = GetAttribute( p_sap->p_sdp->pp_attributes, p_sap->p_sdp->i_attributes, "tool" );
890     if( psz_value != NULL )
891     {
892         input_ItemAddInfo( p_input, _("Session"), _("Tool"), "%s", psz_value );
893     }
894     if( strcmp( p_sdp->username, "-" ) )
895     {
896         input_ItemAddInfo( p_input, _("Session"), _("User"), "%s",
897                            p_sdp->username );
898     }
899
900     /* Handle group */
901     if (p_sap->p_sdp->mediac >= 1)
902         psz_value = FindAttribute (p_sap->p_sdp, 0, "x-plgroup");
903     else
904         psz_value = GetAttribute( p_sap->p_sdp->pp_attributes, p_sap->p_sdp->i_attributes, "x-plgroup" );
905
906     services_discovery_AddItem( p_sd, p_input, psz_value /* category name */ );
907
908     TAB_APPEND( p_sys->i_announces, p_sys->pp_announces, p_sap );
909
910     return p_sap;
911 }
912
913
914 static const char *FindAttribute (const sdp_t *sdp, unsigned media,
915                                   const char *name)
916 {
917     /* Look for media attribute, and fallback to session */
918     return GetAttribute (sdp->mediav[media].pp_attributes,
919                          sdp->mediav[media].i_attributes, name)
920         ?: GetAttribute (sdp->pp_attributes, sdp->i_attributes, name);
921 }
922
923
924 /* Fill p_sdp->psz_uri */
925 static int ParseConnection( vlc_object_t *p_obj, sdp_t *p_sdp )
926 {
927     if (p_sdp->mediac == 0)
928     {
929         msg_Dbg (p_obj, "Ignoring SDP with no media");
930         return VLC_EGENERIC;
931     }
932
933     for (unsigned i = 1; i < p_sdp->mediac; i++)
934     {
935         if ((p_sdp->mediav[i].n_addr != p_sdp->mediav->n_addr)
936          || (p_sdp->mediav[i].addrlen != p_sdp->mediav->addrlen)
937          || memcmp (&p_sdp->mediav[i].addr, &p_sdp->mediav->addr,
938                     p_sdp->mediav->addrlen))
939         {
940             msg_Dbg (p_obj, "Multiple media ports not supported -> live555");
941             return VLC_EGENERIC;
942         }
943     }
944
945     if (p_sdp->mediav->n_addr != 1)
946     {
947         msg_Dbg (p_obj, "Layered encoding not supported -> live555");
948         return VLC_EGENERIC;
949     }
950
951     char psz_uri[1026];
952     const char *host;
953     int port;
954
955     psz_uri[0] = '[';
956     if (vlc_getnameinfo ((struct sockaddr *)&(p_sdp->mediav->addr),
957                          p_sdp->mediav->addrlen, psz_uri + 1,
958                          sizeof (psz_uri) - 2, &port, NI_NUMERICHOST))
959         return VLC_EGENERIC;
960
961     if (strchr (psz_uri + 1, ':'))
962     {
963         host = psz_uri;
964         strcat (psz_uri, "]");
965     }
966     else
967         host = psz_uri + 1;
968
969     /* Parse m= field */
970     char *sdp_proto = strdup (p_sdp->mediav[0].fmt);
971     if (sdp_proto == NULL)
972         return VLC_ENOMEM;
973
974     char *subtype = strchr (sdp_proto, ' ');
975     if (subtype == NULL)
976     {
977         msg_Dbg (p_obj, "missing SDP media subtype: %s", sdp_proto);
978         free (sdp_proto);
979         return VLC_EGENERIC;
980     }
981     else
982     {
983         *subtype++ = '\0';
984         /* FIXME: check for multiple payload types in RTP/AVP case.
985          * FIXME: check for "mpeg" subtype in raw udp case. */
986         if (!strcasecmp (sdp_proto, "udp"))
987             p_sdp->i_media_type = 33;
988         else
989             p_sdp->i_media_type = atoi (subtype);
990     }
991
992     /* RTP protocol, nul, VLC shortcut, nul, flags byte as follow:
993      * 0x1: Connection-Oriented media. */
994     static const char proto_match[] =
995         "udp\0"             "udp\0\0"
996         "RTP/AVP\0"         "rtp\0\0"
997         "UDPLite/RTP/AVP\0" "udplite\0\0"
998         "DCCP/RTP/AVP\0"    "dccp\0\1"
999         "TCP/RTP/AVP\0"     "rtptcp\0\1"
1000         "\0";
1001
1002     const char *vlc_proto = NULL;
1003     uint8_t flags = 0;
1004     for (const char *proto = proto_match; *proto;)
1005     {
1006         if (strcasecmp (proto, sdp_proto) == 0)
1007         {
1008             vlc_proto = proto + strlen (proto) + 1;
1009             flags = vlc_proto[strlen (vlc_proto) + 1];
1010             break;
1011         }
1012         proto += strlen (proto) + 1;
1013         proto += strlen (proto) + 2;
1014     }
1015
1016     free (sdp_proto);
1017     if (vlc_proto == NULL)
1018     {
1019         msg_Dbg (p_obj, "unknown SDP media protocol: %s",
1020                  p_sdp->mediav[0].fmt);
1021         return VLC_EGENERIC;
1022     }
1023
1024     if (flags & 1)
1025     {
1026         /* Connection-oriented media */
1027         const char *setup = FindAttribute (p_sdp, 0, "setup");
1028         if (setup == NULL)
1029             setup = "active"; /* default value */
1030
1031         if (strcmp (setup, "actpass") && strcmp (setup, "passive"))
1032         {
1033             msg_Dbg (p_obj, "unsupported COMEDIA mode: %s", setup);
1034             return VLC_EGENERIC;
1035         }
1036
1037         if (asprintf (&p_sdp->psz_uri, "%s://%s:%d", vlc_proto,
1038                       host, port) == -1)
1039             return VLC_ENOMEM;
1040     }
1041     else
1042     {
1043         /* Non-connected (normally multicast) media */
1044
1045         char psz_source[258] = "";
1046         const char *sfilter = FindAttribute (p_sdp, 0, "source-filter");
1047         if (sfilter != NULL)
1048         {
1049             char psz_source_ip[256];
1050             unsigned ipv;
1051
1052             if (sscanf (sfilter, " incl IN IP%u %*s %255s ", &ipv,
1053                         psz_source_ip) == 2)
1054             {
1055                 /* According to RFC4570, FQDNs can be used for source-filters,
1056                  * but -seriously- this is impractical */
1057                 switch (ipv)
1058                 {
1059 #ifdef AF_INET6
1060                     case 6:
1061                     {
1062                         struct in6_addr addr;
1063                         if ((inet_pton (AF_INET6, psz_source_ip, &addr) > 0)
1064                         && (inet_ntop (AF_INET6, &addr, psz_source + 1,
1065                                         sizeof (psz_source) - 2) != NULL))
1066                         {
1067                             psz_source[0] = '[';
1068                             psz_source[strlen (psz_source)] = ']';
1069                         }
1070                         break;
1071                     }
1072 #endif
1073                     case 4:
1074                     {
1075                         struct in_addr addr;
1076                         if ((inet_pton (AF_INET, psz_source_ip, &addr) > 0)
1077                         && (inet_ntop (AF_INET, &addr, psz_source,
1078                                         sizeof (psz_source)) == NULL))
1079                             *psz_source = '\0';
1080                         break;
1081                     }
1082                 }
1083             }
1084         }
1085
1086         if (asprintf (&p_sdp->psz_uri, "%s://%s@%s:%i", vlc_proto, psz_source,
1087                      host, port) == -1)
1088             return VLC_ENOMEM;
1089     }
1090
1091     return VLC_SUCCESS;
1092 }
1093
1094
1095 static int ParseSDPConnection (const char *str, struct sockaddr_storage *addr,
1096                                socklen_t *addrlen, unsigned *number)
1097 {
1098     char host[60];
1099     unsigned fam, n1, n2;
1100
1101     int res = sscanf (str, "IN IP%u %59[^/]/%u/%u", &fam, host, &n1, &n2);
1102     if (res < 2)
1103         return -1;
1104
1105     switch (fam)
1106     {
1107 #ifdef AF_INET6
1108         case 6:
1109             addr->ss_family = AF_INET6;
1110 # ifdef HAVE_SA_LEN
1111             addr->ss_len =
1112 # endif
1113            *addrlen = sizeof (struct sockaddr_in6);
1114
1115             if (inet_pton (AF_INET6, host,
1116                            &((struct sockaddr_in6 *)addr)->sin6_addr) <= 0)
1117                 return -1;
1118
1119             *number = (res >= 3) ? n1 : 1;
1120             break;
1121 #endif
1122
1123         case 4:
1124             addr->ss_family = AF_INET;
1125 # ifdef HAVE_SA_LEN
1126             addr->ss_len =
1127 # endif
1128            *addrlen = sizeof (struct sockaddr_in);
1129
1130             if (inet_pton (AF_INET, host,
1131                            &((struct sockaddr_in *)addr)->sin_addr) <= 0)
1132                 return -1;
1133
1134             *number = (res >= 4) ? n2 : 1;
1135             break;
1136
1137         default:
1138             return -1;
1139     }
1140     return 0;
1141 }
1142
1143
1144 /***********************************************************************
1145  * ParseSDP : SDP parsing
1146  * *********************************************************************
1147  * Validate SDP and parse all fields
1148  ***********************************************************************/
1149 static sdp_t *ParseSDP (vlc_object_t *p_obj, const char *psz_sdp)
1150 {
1151     if( psz_sdp == NULL )
1152         return NULL;
1153
1154     sdp_t *p_sdp = calloc (1, sizeof (*p_sdp));
1155     if (p_sdp == NULL)
1156         return NULL;
1157
1158     char expect = 'V';
1159     struct sockaddr_storage glob_addr;
1160     memset (&glob_addr, 0, sizeof (glob_addr));
1161     socklen_t glob_len = 0;
1162     unsigned glob_count = 1;
1163     int port = 0;
1164
1165     /* TODO: use iconv and charset attribute instead of EnsureUTF8 */
1166     while (*psz_sdp)
1167     {
1168         /* Extract one line */
1169         char *eol = strchr (psz_sdp, '\n');
1170         size_t linelen = eol ? (size_t)(eol - psz_sdp) : strlen (psz_sdp);
1171         char line[linelen + 1];
1172         memcpy (line, psz_sdp, linelen);
1173         line[linelen] = '\0';
1174
1175         psz_sdp += linelen + 1;
1176
1177         /* Remove carriage return if present */
1178         eol = strchr (line, '\r');
1179         if (eol != NULL)
1180         {
1181             linelen = eol - line;
1182             line[linelen] = '\0';
1183         }
1184
1185         /* Validate line */
1186         char cat = line[0], *data = line + 2;
1187         if (!cat || (strchr ("vosiuepcbtrzkam", cat) == NULL))
1188         {
1189             /* MUST ignore SDP with unknown line type */
1190             msg_Dbg (p_obj, "unknown SDP line type: 0x%02x", (int)cat);
1191             goto error;
1192         }
1193         if (line[1] != '=')
1194         {
1195             msg_Dbg (p_obj, "invalid SDP line: %s", line);
1196             goto error;
1197         }
1198
1199         assert (linelen >= 2);
1200
1201         /* SDP parsing state machine
1202          * We INTERNALLY use uppercase for session, lowercase for media
1203          */
1204         switch (expect)
1205         {
1206             /* Session description */
1207             case 'V':
1208                 expect = 'O';
1209                 if (cat != 'v')
1210                 {
1211                     msg_Dbg (p_obj, "missing SDP version");
1212                     goto error;
1213                 }
1214                 if (strcmp (data, "0"))
1215                 {
1216                     msg_Dbg (p_obj, "unknown SDP version: %s", data);
1217                     goto error;
1218                 }
1219                 break;
1220
1221             case 'O':
1222             {
1223                 expect = 'S';
1224                 if (cat != 'o')
1225                 {
1226                     msg_Dbg (p_obj, "missing SDP originator");
1227                     goto error;
1228                 }
1229
1230                 if ((sscanf (data, "%63s %"PRIu64" %"PRIu64" IN IP%u %1023s",
1231                              p_sdp->username, &p_sdp->session_id,
1232                              &p_sdp->session_version, &p_sdp->orig_ip_version,
1233                              p_sdp->orig_host) != 5)
1234                  || ((p_sdp->orig_ip_version != 4)
1235                   && (p_sdp->orig_ip_version != 6)))
1236                 {
1237                     msg_Dbg (p_obj, "SDP origin not supported: %s\n", data);
1238                     /* Or maybe out-of-range, but this looks suspicious */
1239                     return NULL;
1240                 }
1241                 EnsureUTF8 (p_sdp->orig_host);
1242                 break;
1243             }
1244
1245             case 'S':
1246             {
1247                 expect = 'I';
1248                 if ((cat != 's') || !*data)
1249                 {
1250                     /* MUST be present AND non-empty */
1251                     msg_Dbg (p_obj, "missing SDP session name");
1252                     goto error;
1253                 }
1254                 assert (p_sdp->psz_sessionname == NULL); // no memleak here
1255                 p_sdp->psz_sessionname = strdup (data);
1256                 EnsureUTF8 (p_sdp->psz_sessionname);
1257                 if (p_sdp->psz_sessionname == NULL)
1258                     goto error;
1259                 break;
1260             }
1261
1262             case 'I':
1263                 expect = 'U';
1264                 if (cat == 'i')
1265                     break;
1266             case 'U':
1267                 expect = 'E';
1268                 if (cat == 'u')
1269                     break;
1270             case 'E':
1271                 expect = 'E';
1272                 if (cat == 'e')
1273                     break;
1274             case 'P':
1275                 expect = 'P';
1276                 if (cat == 'p')
1277                     break;
1278             case 'C':
1279                 expect = 'B';
1280                 if (cat == 'c')
1281                 {
1282                     if (ParseSDPConnection (data, &glob_addr, &glob_len,
1283                                             &glob_count))
1284                     {
1285                         msg_Dbg (p_obj, "SDP connection infos not supported: "
1286                                  "%s", data);
1287                         goto error;
1288                     }
1289                     break;
1290                 }
1291             case 'B':
1292                 assert (expect == 'B');
1293                 if (cat == 'b')
1294                     break;
1295             case 'T':
1296                 expect = 'R';
1297                 if (cat != 't')
1298                 {
1299                     msg_Dbg (p_obj, "missing SDP time description");
1300                     goto error;
1301                 }
1302                 break;
1303
1304             case 'R':
1305                 if ((cat == 't') || (cat == 'r'))
1306                     break;
1307
1308             case 'Z':
1309                 expect = 'K';
1310                 if (cat == 'z')
1311                     break;
1312             case 'K':
1313                 expect = 'A';
1314                 if (cat == 'k')
1315                     break;
1316             case 'A':
1317                 //expect = 'A';
1318                 if (cat == 'a')
1319                 {
1320                     attribute_t *p_attr = MakeAttribute (data);
1321                     TAB_APPEND( p_sdp->i_attributes, p_sdp->pp_attributes, p_attr );
1322                     break;
1323                 }
1324
1325             /* Media description */
1326             case 'm':
1327             media:
1328             {
1329                 expect = 'i';
1330                 if (cat != 'm')
1331                 {
1332                     msg_Dbg (p_obj, "missing SDP media description");
1333                     goto error;
1334                 }
1335                 struct sdp_media_t *m;
1336                 m = realloc (p_sdp->mediav, (p_sdp->mediac + 1) * sizeof (*m));
1337                 if (m == NULL)
1338                     goto error;
1339
1340                 p_sdp->mediav = m;
1341                 m += p_sdp->mediac;
1342                 p_sdp->mediac++;
1343
1344                 memset (m, 0, sizeof (*m));
1345                 memcpy (&m->addr, &glob_addr, m->addrlen = glob_len);
1346                 m->n_addr = glob_count;
1347
1348                 /* TODO: remember media type (if we need multiple medias) */
1349                 data = strchr (data, ' ');
1350                 if (data == NULL)
1351                 {
1352                     msg_Dbg (p_obj, "missing SDP media port");
1353                     goto error;
1354                 }
1355                 port = atoi (++data);
1356                 if (port <= 0 || port >= 65536)
1357                 {
1358                     msg_Dbg (p_obj, "invalid transport port %d", port);
1359                     goto error;
1360                 }
1361                 net_SetPort ((struct sockaddr *)&m->addr, htons (port));
1362
1363                 data = strchr (data, ' ');
1364                 if (data == NULL)
1365                 {
1366                     msg_Dbg (p_obj, "missing SDP media format");
1367                     goto error;
1368                 }
1369                 m->fmt = strdup (++data);
1370                 if (m->fmt == NULL)
1371                     goto error;
1372
1373                 break;
1374             }
1375             case 'i':
1376                 expect = 'c';
1377                 if (cat == 'i')
1378                     break;
1379             case 'c':
1380                 expect = 'b';
1381                 if (cat == 'c')
1382                 {
1383                     struct sdp_media_t *m = p_sdp->mediav + p_sdp->mediac - 1;
1384                     if (ParseSDPConnection (data, &m->addr, &m->addrlen,
1385                                             &m->n_addr))
1386                     {
1387                         msg_Dbg (p_obj, "SDP connection infos not supported: "
1388                                  "%s", data);
1389                         goto error;
1390                     }
1391                     net_SetPort ((struct sockaddr *)&m->addr, htons (port));
1392                     break;
1393                 }
1394             case 'b':
1395                 expect = 'b';
1396                 if (cat == 'b')
1397                     break;
1398             case 'k':
1399                 expect = 'a';
1400                 if (cat == 'k')
1401                     break;
1402             case 'a':
1403                 assert (expect == 'a');
1404                 if (cat == 'a')
1405                 {
1406                     attribute_t *p_attr = MakeAttribute (data);
1407                     if (p_attr == NULL)
1408                         goto error;
1409
1410                     TAB_APPEND (p_sdp->mediav[p_sdp->mediac - 1].i_attributes,
1411                                 p_sdp->mediav[p_sdp->mediac - 1].pp_attributes, p_attr);
1412                     break;
1413                 }
1414
1415                 if (cat == 'm')
1416                     goto media;
1417
1418                 if (cat != 'm')
1419                 {
1420                     msg_Dbg (p_obj, "unexpected SDP line: 0x%02x", (int)cat);
1421                     goto error;
1422                 }
1423                 break;
1424
1425             default:
1426                 msg_Err (p_obj, "*** BUG in SDP parser! ***");
1427                 goto error;
1428         }
1429     }
1430
1431     return p_sdp;
1432
1433 error:
1434     FreeSDP (p_sdp);
1435     return NULL;
1436 }
1437
1438 static int InitSocket( services_discovery_t *p_sd, const char *psz_address,
1439                        int i_port )
1440 {
1441     int i_fd = net_ListenUDP1 ((vlc_object_t *)p_sd, psz_address, i_port);
1442     if (i_fd == -1)
1443         return VLC_EGENERIC;
1444
1445     shutdown( i_fd, SHUT_WR );
1446     INSERT_ELEM (p_sd->p_sys->pi_fd, p_sd->p_sys->i_fd,
1447                  p_sd->p_sys->i_fd, i_fd);
1448     return VLC_SUCCESS;
1449 }
1450
1451 static int Decompress( const unsigned char *psz_src, unsigned char **_dst, int i_len )
1452 {
1453 #ifdef HAVE_ZLIB_H
1454     int i_result, i_dstsize, n = 0;
1455     unsigned char *psz_dst = NULL;
1456     z_stream d_stream;
1457
1458     memset (&d_stream, 0, sizeof (d_stream));
1459
1460     i_result = inflateInit(&d_stream);
1461     if( i_result != Z_OK )
1462         return( -1 );
1463
1464     d_stream.next_in = (Bytef *)psz_src;
1465     d_stream.avail_in = i_len;
1466
1467     do
1468     {
1469         n++;
1470         psz_dst = (unsigned char *)realloc( psz_dst, n * 1000 );
1471         d_stream.next_out = (Bytef *)&psz_dst[(n - 1) * 1000];
1472         d_stream.avail_out = 1000;
1473
1474         i_result = inflate(&d_stream, Z_NO_FLUSH);
1475         if( ( i_result != Z_OK ) && ( i_result != Z_STREAM_END ) )
1476         {
1477             inflateEnd( &d_stream );
1478             return( -1 );
1479         }
1480     }
1481     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
1482            ( i_result != Z_STREAM_END ) );
1483
1484     i_dstsize = d_stream.total_out;
1485     inflateEnd( &d_stream );
1486
1487     *_dst = (unsigned char *)realloc( psz_dst, i_dstsize );
1488
1489     return i_dstsize;
1490 #else
1491     (void)psz_src;
1492     (void)_dst;
1493     (void)i_len;
1494     return -1;
1495 #endif
1496 }
1497
1498
1499 static void FreeSDP( sdp_t *p_sdp )
1500 {
1501     free( p_sdp->psz_sessionname );
1502     free( p_sdp->psz_uri );
1503
1504     for (unsigned j = 0; j < p_sdp->mediac; j++)
1505     {
1506         free (p_sdp->mediav[j].fmt);
1507         for (int i = 0; i < p_sdp->mediav[j].i_attributes; i++)
1508             FreeAttribute (p_sdp->mediav[j].pp_attributes[i]);
1509         free (p_sdp->mediav[j].pp_attributes);
1510     }
1511     free (p_sdp->mediav);
1512
1513     for (int i = 0; i < p_sdp->i_attributes; i++)
1514         FreeAttribute (p_sdp->pp_attributes[i]);
1515
1516     free (p_sdp->pp_attributes);
1517     free (p_sdp);
1518 }
1519
1520 static int RemoveAnnounce( services_discovery_t *p_sd,
1521                            sap_announce_t *p_announce )
1522 {
1523     int i;
1524
1525     if( p_announce->p_sdp )
1526     {
1527         FreeSDP( p_announce->p_sdp );
1528         p_announce->p_sdp = NULL;
1529     }
1530
1531     if( p_announce->p_item )
1532     {
1533         services_discovery_RemoveItem( p_sd, p_announce->p_item );
1534         vlc_gc_decref( p_announce->p_item );
1535         p_announce->p_item = NULL;
1536     }
1537
1538     for( i = 0; i< p_sd->p_sys->i_announces; i++)
1539     {
1540         if( p_sd->p_sys->pp_announces[i] == p_announce )
1541         {
1542             REMOVE_ELEM( p_sd->p_sys->pp_announces, p_sd->p_sys->i_announces,
1543                          i);
1544             break;
1545         }
1546     }
1547
1548     free( p_announce );
1549
1550     return VLC_SUCCESS;
1551 }
1552
1553 static bool IsSameSession( sdp_t *p_sdp1, sdp_t *p_sdp2 )
1554 {
1555     /* A session is identified by
1556      * - username,
1557      * - session_id,
1558      * - network type (which is always IN),
1559      * - address type (currently, this means IP version),
1560      * - and hostname.
1561      */
1562     if (strcmp (p_sdp1->username, p_sdp2->username)
1563      || (p_sdp1->session_id != p_sdp2->session_id)
1564      || (p_sdp1->orig_ip_version != p_sdp2->orig_ip_version)
1565      || strcmp (p_sdp1->orig_host, p_sdp2->orig_host))
1566         return false;
1567
1568     return true;
1569 }
1570
1571
1572 static inline attribute_t *MakeAttribute (const char *str)
1573 {
1574     attribute_t *a = malloc (sizeof (*a) + strlen (str) + 1);
1575     if (a == NULL)
1576         return NULL;
1577
1578     strcpy (a->name, str);
1579     EnsureUTF8 (a->name);
1580     char *value = strchr (a->name, ':');
1581     if (value != NULL)
1582     {
1583         *value++ = '\0';
1584         a->value = value;
1585     }
1586     else
1587         a->value = "";
1588     return a;
1589 }
1590
1591
1592 static const char *GetAttribute (attribute_t **tab, unsigned n,
1593                                  const char *name)
1594 {
1595     for (unsigned i = 0; i < n; i++)
1596         if (strcasecmp (tab[i]->name, name) == 0)
1597             return tab[i]->value;
1598     return NULL;
1599 }
1600
1601
1602 static inline void FreeAttribute (attribute_t *a)
1603 {
1604     free (a);
1605 }