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