]> git.sesse.net Git - vlc/blob - modules/services_discovery/sap.c
* forgot about the strings rules for menu-items.
[vlc] / modules / services_discovery / sap.c
1 /*****************************************************************************
2  * sap.c :  SAP interface module
3  *****************************************************************************
4  * Copyright (C) 2004-2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Includes
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30 #include <vlc/input.h>
31 #include <vlc/intf.h>
32
33 #include <network.h>
34 #include <charset.h>
35
36 #include <ctype.h>
37 #include <errno.h>
38
39 #ifdef HAVE_UNISTD_H
40 #    include <unistd.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 #    include <sys/time.h>
44 #endif
45
46 #ifdef HAVE_ZLIB_H
47 #   include <zlib.h>
48 #endif
49
50 /************************************************************************
51  * Macros and definitions
52  ************************************************************************/
53
54 #define MAX_LINE_LENGTH 256
55
56 /* SAP is always on that port */
57 #define SAP_PORT 9875
58 /* Global-scope SAP address */
59 #define SAP_V4_GLOBAL_ADDRESS   "224.2.127.254"
60 /* Organization-local SAP address */
61 #define SAP_V4_ORG_ADDRESS      "239.195.255.255"
62 /* Local (smallest non-link-local scope) SAP address */
63 #define SAP_V4_LOCAL_ADDRESS    "239.255.255.255"
64 /* Link-local SAP address */
65 #define SAP_V4_LINK_ADDRESS     "224.0.0.255"
66 #define ADD_SESSION 1
67
68 #define SAP_V6_1 "FF0"
69 /* Scope is inserted between them */
70 #define SAP_V6_2 "::2:7FFE"
71 /* See RFC3513 for list of valid scopes */
72 /* FIXME: find a way to listen to link-local scope */
73 static const char ipv6_scopes[] = "1456789ABCDE";
74
75
76 /*****************************************************************************
77  * Module descriptor
78  *****************************************************************************/
79 #define SAP_ADDR_TEXT N_( "SAP multicast address" )
80 #define SAP_ADDR_LONGTEXT N_( "Listen for SAP announcements on another address" )
81 #define SAP_IPV4_TEXT N_( "IPv4-SAP listening" )
82 #define SAP_IPV4_LONGTEXT N_( \
83       "Set this if you want the SAP module to listen to IPv4 announcements " \
84       "on the standard address." )
85 #define SAP_IPV6_TEXT N_( "IPv6-SAP listening" )
86 #define SAP_IPV6_LONGTEXT N_( \
87       "Set this if you want the SAP module to listen to IPv6 announcements " \
88       "on the standard address." )
89 #define SAP_SCOPE_TEXT N_( "IPv6 SAP scope" )
90 #define SAP_SCOPE_LONGTEXT N_( \
91        "Sets the scope for IPv6 announcements (default is 8)." )
92 #define SAP_TIMEOUT_TEXT N_( "SAP timeout (seconds)" )
93 #define SAP_TIMEOUT_LONGTEXT N_( \
94        "Sets the time before SAP items get deleted if no new announcement " \
95        "is received." )
96 #define SAP_PARSE_TEXT N_( "Try to parse the SAP" )
97 #define SAP_PARSE_LONGTEXT N_( \
98        "When SAP can it will try to parse the SAP. If you don't select " \
99        "this, all announcements will be parsed by the livedotcom module." )
100 #define SAP_STRICT_TEXT N_( "SAP Strict mode" )
101 #define SAP_STRICT_LONGTEXT N_( \
102        "When this is set, the SAP parser will discard some non-compliant " \
103        "announcements." )
104 #define SAP_CACHE_TEXT N_("Use SAP cache")
105 #define SAP_CACHE_LONGTEXT N_( \
106        "If this option is selected, a SAP caching mechanism will be used. " \
107        "This will result in lower SAP startup time, but you could end up " \
108         "with items corresponding to legacy streams." )
109
110 /* Callbacks */
111     static int  Open ( vlc_object_t * );
112     static void Close( vlc_object_t * );
113     static int  OpenDemux ( vlc_object_t * );
114     static void CloseDemux ( vlc_object_t * );
115
116 vlc_module_begin();
117     set_shortname( _("SAP"));
118     set_description( _("SAP Announcements") );
119     set_category( CAT_PLAYLIST );
120     set_subcategory( SUBCAT_PLAYLIST_SD );
121
122     add_string( "sap-addr", NULL, NULL,
123                 SAP_ADDR_TEXT, SAP_ADDR_LONGTEXT, VLC_TRUE );
124     add_bool( "sap-ipv4", 1 , NULL,
125                SAP_IPV4_TEXT,SAP_IPV4_LONGTEXT, VLC_TRUE );
126     add_bool( "sap-ipv6", 1 , NULL,
127               SAP_IPV6_TEXT, SAP_IPV6_LONGTEXT, VLC_TRUE );
128     add_integer( "sap-timeout", 1800, NULL,
129                  SAP_TIMEOUT_TEXT, SAP_TIMEOUT_LONGTEXT, VLC_TRUE );
130     add_bool( "sap-parse", 1 , NULL,
131                SAP_PARSE_TEXT,SAP_PARSE_LONGTEXT, VLC_TRUE );
132     add_bool( "sap-strict", 0 , NULL,
133                SAP_STRICT_TEXT,SAP_STRICT_LONGTEXT, VLC_TRUE );
134     add_bool( "sap-cache", 0 , NULL,
135                SAP_CACHE_TEXT,SAP_CACHE_LONGTEXT, VLC_TRUE );
136
137     set_capability( "services_discovery", 0 );
138     set_callbacks( Open, Close );
139
140     add_submodule();
141         set_description( _("SDP file parser for UDP") );
142         add_shortcut( "sdp" );
143         set_capability( "demux2", 51 );
144         set_callbacks( OpenDemux, CloseDemux );
145 vlc_module_end();
146
147
148 /*****************************************************************************
149  * Local structures
150  *****************************************************************************/
151
152 typedef struct sdp_t sdp_t;
153 typedef struct attribute_t attribute_t;
154 typedef struct sap_announce_t sap_announce_t;
155
156 /* The structure that contains sdp information */
157 struct  sdp_t
158 {
159     char *psz_sdp;
160
161     /* s= field */
162     char *psz_sessionname;
163
164     /* Raw m= and c= fields */
165     char *psz_connection;
166     char *psz_media;
167
168     /* o field */
169     char *psz_username;
170     char *psz_network_type;
171     char *psz_address_type;
172     char *psz_address;
173     int64_t i_session_id;
174
175     /* "computed" URI */
176     char *psz_uri;
177
178     int           i_in; /* IP version */
179
180     int           i_media;
181     int           i_media_type;
182
183     int           i_attributes;
184     attribute_t  **pp_attributes;
185 };
186
187 struct attribute_t
188 {
189     char *psz_field;
190     char *psz_value;
191 };
192
193 struct sap_announce_t
194 {
195     mtime_t i_last;
196
197     uint16_t    i_hash;
198     uint32_t    i_source[4];
199
200     /* SAP annnounces must only contain one SDP */
201     sdp_t       *p_sdp;
202
203     int i_item_id;
204 //    playlist_item_t *p_item;
205 };
206
207 struct services_discovery_sys_t
208 {
209     /* Socket descriptors */
210     int i_fd;
211     int *pi_fd;
212
213     /* playlist node */
214     playlist_item_t *p_node;
215     playlist_t *p_playlist;
216
217     /* Table of announces */
218     int i_announces;
219     struct sap_announce_t **pp_announces;
220
221     /* Modes */
222     vlc_bool_t  b_strict;
223     vlc_bool_t  b_parse;
224
225     int i_timeout;
226 };
227
228 struct demux_sys_t
229 {
230     sdp_t *p_sdp;
231 };
232
233 /*****************************************************************************
234  * Local prototypes
235  *****************************************************************************/
236
237
238 /* Main functions */
239     static int Demux( demux_t *p_demux );
240     static int Control( demux_t *, int, va_list );
241     static void Run    ( services_discovery_t *p_sd );
242
243 /* Main parsing functions */
244     static int ParseConnection( vlc_object_t *p_obj, sdp_t *p_sdp );
245     static int ParseSAP( services_discovery_t *p_sd, uint8_t *p_buffer, int i_read );
246     static sdp_t *  ParseSDP( vlc_object_t *p_sd, char* psz_sdp );
247     static sap_announce_t *CreateAnnounce( services_discovery_t *, uint16_t, sdp_t * );
248     static int RemoveAnnounce( services_discovery_t *p_sd, sap_announce_t *p_announce );
249
250 /* Cache */
251     static void CacheLoad( services_discovery_t *p_sd );
252     static void CacheSave( services_discovery_t *p_sd );
253 /* Helper functions */
254     static char *GetAttribute( sdp_t *p_sdp, const char *psz_search );
255     static vlc_bool_t IsSameSession( sdp_t *p_sdp1, sdp_t *p_sdp2 );
256     static int InitSocket( services_discovery_t *p_sd, char *psz_address, int i_port );
257 #ifdef HAVE_ZLIB_H
258     static int Decompress( unsigned char *psz_src, unsigned char **_dst, int i_len );
259 #endif
260     static void FreeSDP( sdp_t *p_sdp );
261
262
263 #define FREE( p ) \
264     if( p ) { free( p ); (p) = NULL; }
265 /*****************************************************************************
266  * Open: initialize and create stuff
267  *****************************************************************************/
268 static int Open( vlc_object_t *p_this )
269 {
270     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
271     services_discovery_sys_t *p_sys  = (services_discovery_sys_t *)
272                                 malloc( sizeof( services_discovery_sys_t ) );
273
274     playlist_view_t     *p_view;
275     char                *psz_addr;
276     vlc_value_t         val;
277
278     p_sys->i_timeout = var_CreateGetInteger( p_sd, "sap-timeout" );
279
280     p_sd->pf_run = Run;
281     p_sd->p_sys  = p_sys;
282
283     p_sys->pi_fd = NULL;
284     p_sys->i_fd = 0;
285
286     p_sys->b_strict = var_CreateGetInteger( p_sd, "sap-strict");
287     p_sys->b_parse = var_CreateGetInteger( p_sd, "sap-parse" );
288
289     if( var_CreateGetInteger( p_sd, "sap-cache" ) )
290     {
291         CacheLoad( p_sd );
292     }
293
294     if( var_CreateGetInteger( p_sd, "sap-ipv4" ) )
295     {
296         InitSocket( p_sd, SAP_V4_GLOBAL_ADDRESS, SAP_PORT );
297         InitSocket( p_sd, SAP_V4_ORG_ADDRESS, SAP_PORT );
298         InitSocket( p_sd, SAP_V4_LOCAL_ADDRESS, SAP_PORT );
299         InitSocket( p_sd, SAP_V4_LINK_ADDRESS, SAP_PORT );
300     }
301     if( var_CreateGetInteger( p_sd, "sap-ipv6" ) )
302     {
303         char psz_address[] = SAP_V6_1"0"SAP_V6_2;
304         const char *c_scope;
305
306         for( c_scope = ipv6_scopes; *c_scope; c_scope++ )
307         {
308             psz_address[sizeof(SAP_V6_1) - 1] = *c_scope;
309             InitSocket( p_sd, psz_address, SAP_PORT );
310         }
311     }
312
313     psz_addr = var_CreateGetString( p_sd, "sap-addr" );
314     if( psz_addr && *psz_addr )
315     {
316         InitSocket( p_sd, psz_addr, SAP_PORT );
317     }
318
319     if( p_sys->i_fd == 0 )
320     {
321         msg_Err( p_sd, "unable to read on any address" );
322         return VLC_EGENERIC;
323     }
324
325     /* Create our playlist node */
326     p_sys->p_playlist = (playlist_t *)vlc_object_find( p_sd,
327                                                        VLC_OBJECT_PLAYLIST,
328                                                        FIND_ANYWHERE );
329     if( !p_sys->p_playlist )
330     {
331         msg_Warn( p_sd, "unable to find playlist, cancelling SAP listening");
332         return VLC_EGENERIC;
333     }
334
335     p_view = playlist_ViewFind( p_sys->p_playlist, VIEW_CATEGORY );
336     p_sys->p_node = playlist_NodeCreate( p_sys->p_playlist, VIEW_CATEGORY,
337                                          _("Session Announcements (SAP)"), p_view->p_root );
338     p_sys->p_node->i_flags |= PLAYLIST_RO_FLAG;
339     p_sys->p_node->i_flags &= ~PLAYLIST_SKIP_FLAG;
340     val.b_bool = VLC_TRUE;
341     var_Set( p_sys->p_playlist, "intf-change", val );
342
343     p_sys->i_announces = 0;
344     p_sys->pp_announces = NULL;
345
346     return VLC_SUCCESS;
347 }
348
349 /*****************************************************************************
350  * OpenDemux: initialize and create stuff
351  *****************************************************************************/
352 static int OpenDemux( vlc_object_t *p_this )
353 {
354     demux_t *p_demux = (demux_t *)p_this;
355     uint8_t *p_peek;
356     int i_max_sdp = 1024;
357     int i_sdp = 0;
358     char *psz_sdp = NULL;
359     sdp_t *p_sdp = NULL;
360
361     if( !var_CreateGetInteger( p_demux, "sap-parse" ) )
362     {
363         /* We want livedotcom module to parse this SDP file */
364         return VLC_EGENERIC;
365     }
366
367     /* Probe for SDP */
368     if( p_demux->s )
369     {
370         if( stream_Peek( p_demux->s, &p_peek, 7 ) < 7 ) return VLC_EGENERIC;
371
372         if( strncmp( (char*)p_peek, "v=0\r\n", 5 ) &&
373             strncmp( (char*)p_peek, "v=0\n", 4 ) &&
374             ( p_peek[0] < 'a' || p_peek[0] > 'z' || p_peek[1] != '=' ) )
375         {
376             return VLC_EGENERIC;
377         }
378     }
379
380     psz_sdp = (char *)malloc( i_max_sdp );
381     if( !psz_sdp ) return VLC_EGENERIC;
382
383     /* Gather the complete sdp file */
384     for( ;; )
385     {
386         int i_read = stream_Read( p_demux->s,
387                                   &psz_sdp[i_sdp], i_max_sdp - i_sdp - 1 );
388
389         if( i_read < 0 )
390         {
391             msg_Err( p_demux, "failed to read SDP" );
392             goto error;
393         }
394
395         i_sdp += i_read;
396
397         if( i_read < i_max_sdp - i_sdp - 1 )
398         {
399             psz_sdp[i_sdp] = '\0';
400             break;
401         }
402
403         i_max_sdp += 1000;
404         psz_sdp = (char *)realloc( psz_sdp, i_max_sdp );
405     }
406
407     p_sdp = ParseSDP( VLC_OBJECT(p_demux), psz_sdp );
408
409     if( !p_sdp )
410     {
411         msg_Warn( p_demux, "invalid SDP");
412         goto error;
413     }
414
415     if( p_sdp->i_media > 1 )
416     {
417         goto error;
418     }
419
420     if( ParseConnection( VLC_OBJECT( p_demux ), p_sdp ) )
421     {
422         p_sdp->psz_uri = NULL;
423     }
424     if( p_sdp->i_media_type != 33 && p_sdp->i_media_type != 32 &&
425         p_sdp->i_media_type != 14 )
426         goto error;
427
428     if( p_sdp->psz_uri == NULL ) goto error;
429
430     p_demux->p_sys = (demux_sys_t *)malloc( sizeof(demux_sys_t) );
431     p_demux->p_sys->p_sdp = p_sdp;
432     p_demux->pf_control = Control;
433     p_demux->pf_demux = Demux;
434
435     free( psz_sdp );
436     return VLC_SUCCESS;
437
438 error:
439     free( psz_sdp );
440     if( p_sdp ) FreeSDP( p_sdp );
441     stream_Seek( p_demux->s, 0 );
442     return VLC_EGENERIC;    
443 }
444
445 /*****************************************************************************
446  * Close:
447  *****************************************************************************/
448 static void Close( vlc_object_t *p_this )
449 {
450     services_discovery_t *p_sd = ( services_discovery_t* )p_this;
451     services_discovery_sys_t    *p_sys  = p_sd->p_sys;
452
453     int i;
454
455     for( i = p_sys->i_fd-1 ; i >= 0 ; i-- )
456     {
457         net_Close( p_sys->pi_fd[i] );
458     }
459     FREE( p_sys->pi_fd );
460
461     if( config_GetInt( p_sd, "sap-cache" ) )
462     {
463         CacheSave( p_sd );
464     }
465
466     for( i = p_sys->i_announces  - 1;  i>= 0; i-- )
467     {
468         RemoveAnnounce( p_sd, p_sys->pp_announces[i] );
469     }
470     FREE( p_sys->pp_announces );
471
472     if( p_sys->p_playlist )
473     {
474         playlist_NodeDelete( p_sys->p_playlist, p_sys->p_node, VLC_TRUE,
475                              VLC_TRUE );
476         vlc_object_release( p_sys->p_playlist );
477     }
478
479     free( p_sys );
480 }
481
482 /*****************************************************************************
483  * CloseDemux: Close the demuxer
484  *****************************************************************************/
485 static void CloseDemux( vlc_object_t *p_this )
486 {
487
488 }
489
490 /*****************************************************************************
491  * Run: main SAP thread
492  *****************************************************************************
493  * Listens to SAP packets, and sends them to packet_handle
494  *****************************************************************************/
495 #define MAX_SAP_BUFFER 5000
496
497 static void Run( services_discovery_t *p_sd )
498 {
499     int i;
500
501     /* read SAP packets */
502     while( !p_sd->b_die )
503     {
504         int i_read;
505         uint8_t p_buffer[MAX_SAP_BUFFER+1];
506
507         i_read = net_Select( p_sd, p_sd->p_sys->pi_fd, NULL,
508                              p_sd->p_sys->i_fd, p_buffer,
509                              MAX_SAP_BUFFER, 500000 );
510
511         /* Check for items that need deletion */
512         for( i = 0; i < p_sd->p_sys->i_announces; i++ )
513         {
514             mtime_t i_timeout = ( mtime_t ) 1000000 * p_sd->p_sys->i_timeout;
515
516             if( mdate() - p_sd->p_sys->pp_announces[i]->i_last > i_timeout )
517             {
518                 struct sap_announce_t *p_announce;
519                 p_announce = p_sd->p_sys->pp_announces[i];
520
521                 /* Remove the playlist item */
522                 playlist_LockDelete( p_sd->p_sys->p_playlist,
523                                      p_announce->i_item_id );
524
525                 /* Remove the sap_announce from the array */
526                 REMOVE_ELEM( p_sd->p_sys->pp_announces,
527                            p_sd->p_sys->i_announces, i );
528
529                 free( p_announce );
530             }
531         }
532
533         /* Minimum length is > 6 */
534         if( i_read <= 6 )
535         {
536             if( i_read < 0 )
537             {
538                 msg_Warn( p_sd, "socket read error" );
539             }
540             continue;
541         }
542
543         p_buffer[i_read] = '\0';
544
545         /* Parse the packet */
546         ParseSAP( p_sd, p_buffer, i_read );
547     }
548 }
549
550 /**********************************************************************
551  * Demux: reads and demuxes data packets
552  * Return -1 if error, 0 if EOF, 1 else
553  **********************************************************************/
554 static int Demux( demux_t *p_demux )
555 {
556     sdp_t *p_sdp = p_demux->p_sys->p_sdp;
557     playlist_t *p_playlist;
558
559     p_playlist = (playlist_t *)vlc_object_find( p_demux, VLC_OBJECT_PLAYLIST,
560                                                FIND_ANYWHERE );
561
562     p_playlist->status.p_item->i_flags |= PLAYLIST_DEL_FLAG;
563
564     playlist_Add( p_playlist, p_sdp->psz_uri, p_sdp->psz_sessionname,
565                  PLAYLIST_APPEND, PLAYLIST_END );
566
567     vlc_object_release( p_playlist );
568     if( p_sdp ) FreeSDP( p_sdp );
569
570     return VLC_SUCCESS;
571 }
572
573 static int Control( demux_t *p_demux, int i_query, va_list args )
574 {
575     return VLC_EGENERIC;
576 }
577
578 /**************************************************************
579  * Local functions
580  **************************************************************/
581
582 /* i_read is at least > 6 */
583 static int ParseSAP( services_discovery_t *p_sd, uint8_t *p_buffer, int i_read )
584 {
585     int                 i_version, i_address_type, i_hash, i;
586     char                *psz_sdp, *psz_foo, *psz_initial_sdp;
587     sdp_t               *p_sdp;
588     vlc_bool_t          b_compressed;
589     vlc_bool_t          b_need_delete = VLC_FALSE;
590
591     /* First, check the sap announce is correct */
592     i_version = p_buffer[0] >> 5;
593     if( i_version != 1 )
594     {
595        msg_Dbg( p_sd, "strange sap version %d found", i_version );
596     }
597
598     i_address_type = p_buffer[0] & 0x10;
599
600     if( (p_buffer[0] & 0x08) != 0 )
601     {
602         msg_Dbg( p_sd, "reserved bit incorrectly set" );
603         return VLC_EGENERIC;
604     }
605
606     if( (p_buffer[0] & 0x04) != 0 )
607     {
608         msg_Dbg( p_sd, "session deletion packet" );
609         b_need_delete = VLC_TRUE;
610     }
611
612     if( p_buffer[0] & 0x02  )
613     {
614         msg_Dbg( p_sd, "encrypted packet, unsupported" );
615         return VLC_EGENERIC;
616     }
617
618     b_compressed = p_buffer[0] & 0x01;
619
620     i_hash = ( p_buffer[2] << 8 ) + p_buffer[3];
621
622     if( p_sd->p_sys->b_strict && i_hash == 0 )
623     {
624         msg_Dbg( p_sd, "strict mode, discarding announce with null id hash");
625         return VLC_EGENERIC;
626     }
627
628     psz_sdp  = (char *)p_buffer + 4;
629     psz_initial_sdp = psz_sdp;
630
631     if( i_address_type == 0 ) /* ipv4 source address */
632     {
633         psz_sdp += 4;
634         if( i_read <= 9 )
635         {
636             msg_Warn( p_sd, "too short SAP packet\n" );
637             return VLC_EGENERIC;
638         }
639     }
640     else /* ipv6 source address */
641     {
642         psz_sdp += 16;
643         if( i_read <= 21 )
644         {
645             msg_Warn( p_sd, "too short SAP packet\n" );
646             return VLC_EGENERIC;
647         }
648     }
649
650     if( b_compressed )
651     {
652 #ifdef HAVE_ZLIB_H
653         uint8_t *p_decompressed_buffer = NULL;
654         int      i_decompressed_size;
655
656         i_decompressed_size = Decompress( (uint8_t *)psz_sdp,
657                    &p_decompressed_buffer, i_read - ( psz_sdp - (char *)p_buffer ) );
658         if( i_decompressed_size > 0 && i_decompressed_size < MAX_SAP_BUFFER )
659         {
660             memcpy( psz_sdp, p_decompressed_buffer, i_decompressed_size );
661             psz_sdp[i_decompressed_size] = '\0';
662             free( p_decompressed_buffer );
663         }
664 #else
665         msg_Warn( p_sd, "Ignoring compressed sap packet" );
666         return VLC_EGENERIC;
667 #endif
668     }
669
670     /* Add the size of authentification info */
671     if( i_read < p_buffer[1] + (psz_sdp - psz_initial_sdp ) )
672     {
673         msg_Warn( p_sd, "too short SAP packet\n");
674         return VLC_EGENERIC;
675     }
676     psz_sdp += p_buffer[1];
677     psz_foo = psz_sdp;
678
679     /* Skip payload type */
680     /* Handle announces without \0 between SAP and SDP */
681     while( *psz_sdp != '\0' && ( psz_sdp[0] != 'v' && psz_sdp[1] != '=' ) )
682     {
683         if( psz_sdp - psz_initial_sdp >= i_read - 5 )
684         {
685             msg_Warn( p_sd, "empty SDP ?");
686         }
687         psz_sdp++;
688     }
689
690     if( *psz_sdp == '\0' )
691     {
692         psz_sdp++;
693     }
694     if( ( psz_sdp != psz_foo ) && strcasecmp( psz_foo, "application/sdp" ) )
695     {
696         msg_Dbg( p_sd, "unhandled content type: %s", psz_foo );        
697     }
698     if( ( psz_sdp - (char *)p_buffer ) >= i_read )
699     {
700         msg_Warn( p_sd, "package without content" );
701         return VLC_EGENERIC;
702     }
703
704     /* Parse SDP info */
705     p_sdp = ParseSDP( VLC_OBJECT(p_sd), psz_sdp );
706
707     if( p_sdp == NULL )
708     {
709         return VLC_EGENERIC;
710     }
711
712     /* Decide whether we should add a playlist item for this SDP */
713     /* Parse connection information (c= & m= ) */
714     if( ParseConnection( VLC_OBJECT(p_sd), p_sdp ) )
715     {
716         p_sdp->psz_uri = NULL;
717     }
718
719     /* Multi-media or no-parse -> pass to LIVE.COM */
720     if( p_sdp->i_media > 1 || ( p_sdp->i_media_type != 14 &&
721                                 p_sdp->i_media_type != 32 &&
722                                 p_sdp->i_media_type != 33) ||
723         p_sd->p_sys->b_parse == VLC_FALSE )
724     {
725         if( p_sdp->psz_uri ) free( p_sdp->psz_uri );
726         asprintf( &p_sdp->psz_uri, "sdp://%s", p_sdp->psz_sdp );
727     }
728
729     if( p_sdp->psz_uri == NULL ) return VLC_EGENERIC;
730
731     for( i = 0 ; i< p_sd->p_sys->i_announces ; i++ )
732     {
733         /* FIXME: slow */
734         /* FIXME: we create a new announce each time the sdp changes */
735         if( IsSameSession( p_sd->p_sys->pp_announces[i]->p_sdp, p_sdp ) )
736         {
737             if( b_need_delete )
738             {
739                 RemoveAnnounce( p_sd, p_sd->p_sys->pp_announces[i]);
740                 return VLC_SUCCESS;
741             }
742             else
743             {
744                 p_sd->p_sys->pp_announces[i]->i_last = mdate();
745                 FreeSDP( p_sdp );
746                 return VLC_SUCCESS;
747             }
748         }
749     }
750     /* Add item */
751     if( p_sdp->i_media > 1 )
752     {
753         msg_Dbg( p_sd, "passing to LIVE.COM" );
754     }
755
756     CreateAnnounce( p_sd, i_hash, p_sdp );
757
758     return VLC_SUCCESS;
759 }
760
761 sap_announce_t *CreateAnnounce( services_discovery_t *p_sd, uint16_t i_hash,
762                                 sdp_t *p_sdp )
763 {
764     playlist_item_t     *p_item, *p_child;
765     char *psz_value;
766     sap_announce_t *p_sap = (sap_announce_t *)malloc(
767                                         sizeof(sap_announce_t ) );
768     if( p_sap == NULL )
769         return NULL;
770
771     EnsureUTF8( p_sdp->psz_sessionname );
772     p_sap->i_last = mdate();
773     p_sap->i_hash = i_hash;
774     p_sap->p_sdp = p_sdp;
775     p_sap->i_item_id = -1;
776
777     /* Create the playlist item here */
778     p_item = playlist_ItemNew( p_sd, p_sap->p_sdp->psz_uri,
779                                p_sdp->psz_sessionname );
780
781     if( !p_item )
782     {
783         free( p_sap );
784         return NULL;
785     }
786
787     psz_value = GetAttribute( p_sap->p_sdp, "tool" );
788     if( psz_value != NULL )
789     {
790         vlc_input_item_AddInfo( &p_item->input, _("Session"),
791                                 _("Tool"), psz_value );
792     }
793     if( strcmp( p_sdp->psz_username, "-" ) )
794     {
795         vlc_input_item_AddInfo( &p_item->input, _("Session"),
796                                 _("User"), p_sdp->psz_username );
797     }
798
799     psz_value = GetAttribute( p_sap->p_sdp, "x-plgroup" );
800
801     if( psz_value == NULL )
802     {
803         psz_value = GetAttribute( p_sap->p_sdp, "plgroup" );
804     }
805
806     if( psz_value != NULL )
807     {
808         EnsureUTF8( psz_value );
809
810         p_child = playlist_ChildSearchName( p_sd->p_sys->p_node, psz_value );
811
812         if( p_child == NULL )
813         {
814             p_child = playlist_NodeCreate( p_sd->p_sys->p_playlist,
815                                            VIEW_CATEGORY, psz_value,
816                                            p_sd->p_sys->p_node );
817             p_child->i_flags &= ~PLAYLIST_SKIP_FLAG;
818         }
819     }
820     else
821     {
822         p_child = p_sd->p_sys->p_node;
823     }
824
825     p_item->i_flags &= ~PLAYLIST_SKIP_FLAG;
826     p_item->i_flags &= ~PLAYLIST_SAVE_FLAG;
827
828     playlist_NodeAddItem( p_sd->p_sys->p_playlist, p_item, VIEW_CATEGORY,
829                               p_child, PLAYLIST_APPEND, PLAYLIST_END );
830
831     p_sap->i_item_id = p_item->input.i_id;
832
833     TAB_APPEND( p_sd->p_sys->i_announces,
834                 p_sd->p_sys->pp_announces, p_sap );
835
836     return p_sap;
837 }
838
839 static char *GetAttribute( sdp_t *p_sdp, const char *psz_search )
840 {
841     int i;
842
843     for( i = 0 ; i< p_sdp->i_attributes; i++ )
844     {
845         if( !strncmp( p_sdp->pp_attributes[i]->psz_field, psz_search,
846                       strlen( p_sdp->pp_attributes[i]->psz_field ) ) )
847         {
848             return p_sdp->pp_attributes[i]->psz_value;
849         }
850     }
851     return NULL;
852 }
853
854
855 /* Fill p_sdp->psz_uri */
856 static int ParseConnection( vlc_object_t *p_obj, sdp_t *p_sdp )
857 {
858     char *psz_eof;
859     char *psz_parse;
860     char *psz_uri = NULL;
861     char *psz_proto = NULL;
862     int i_port = 0;
863
864     /* Parse c= field */
865     if( p_sdp->psz_connection )
866     {
867         psz_parse = p_sdp->psz_connection;
868
869         psz_eof = strchr( psz_parse, ' ' );
870
871         if( psz_eof )
872         {
873             *psz_eof = '\0';
874             psz_parse = psz_eof + 1;
875         }
876         else
877         {
878             msg_Warn( p_obj, "unable to parse c field (1)");
879             return VLC_EGENERIC;
880         }
881
882         psz_eof = strchr( psz_parse, ' ' );
883
884         if( psz_eof )
885         {
886             *psz_eof = '\0';
887             if( !strncmp( psz_parse, "IP4", 3 ) )
888             {
889                 p_sdp->i_in = 4;
890             }
891             else if( !strncmp( psz_parse, "IP6", 3 ) )
892             {
893                 p_sdp->i_in = 6;
894             }
895             else
896             {
897                 p_sdp->i_in = 0;
898             }
899             psz_parse = psz_eof + 1;
900         }
901         else
902         {
903             msg_Warn( p_obj, "unable to parse c field (2)");
904             return VLC_EGENERIC;
905         }
906
907         psz_eof = strchr( psz_parse, '/' );
908
909         if( psz_eof )
910         {
911             *psz_eof = '\0';
912         }
913         else
914         {
915             msg_Dbg( p_obj, "incorrect c field, %s", p_sdp->psz_connection );
916         }
917         if( p_sdp->i_in == 6 && ( isxdigit( *psz_parse ) || *psz_parse == ':' ) )
918         {
919             asprintf( &psz_uri, "[%s]", psz_parse );
920         }
921         else psz_uri = strdup( psz_parse );
922
923     }
924
925     /* Parse m= field */
926     if( p_sdp->psz_media )
927     {
928         psz_parse = p_sdp->psz_media;
929
930         psz_eof = strchr( psz_parse, ' ' );
931
932         if( psz_eof )
933         {
934             *psz_eof = '\0';
935
936             if( strncmp( psz_parse, "audio", 5 )  &&
937                 strncmp( psz_parse, "video", 5 ) )
938             {
939                 msg_Warn( p_obj, "unhandled media type -%s-", psz_parse );
940                 FREE( psz_uri );
941                 return VLC_EGENERIC;
942             }
943
944             psz_parse = psz_eof + 1;
945         }
946         else
947         {
948             msg_Warn( p_obj, "unable to parse m field (1)");
949             FREE( psz_uri );
950             return VLC_EGENERIC;
951         }
952
953         psz_eof = strchr( psz_parse, ' ' );
954
955         if( psz_eof )
956         {
957             *psz_eof = '\0';
958
959             /* FIXME : multiple port ! */
960             i_port = atoi( psz_parse );
961
962             if( i_port <= 0 || i_port >= 65536 )
963             {
964                 msg_Warn( p_obj, "invalid transport port %i", i_port );
965             }
966
967             psz_parse = psz_eof + 1;
968         }
969         else
970         {
971             msg_Warn( p_obj, "unable to parse m field (2)");
972             FREE( psz_uri );
973             return VLC_EGENERIC;
974         }
975
976         psz_eof = strchr( psz_parse, ' ' );
977
978         if( psz_eof )
979         {
980             *psz_eof = '\0';
981             psz_proto = strdup( psz_parse );
982
983             psz_parse = psz_eof + 1;
984             p_sdp->i_media_type = atoi( psz_parse );
985             
986         }
987         else
988         {
989             msg_Dbg( p_obj, "incorrect m field, %s", p_sdp->psz_media );
990             p_sdp->i_media_type = 33;
991             psz_proto = strdup( psz_parse );
992         }
993     }
994
995     if( psz_proto && !strncmp( psz_proto, "RTP/AVP", 7 ) )
996     {
997         free( psz_proto );
998         psz_proto = strdup( "rtp" );
999     }
1000     if( psz_proto && !strncasecmp( psz_proto, "UDP", 3 ) )
1001     {
1002         free( psz_proto );
1003         psz_proto = strdup( "udp" );
1004     }
1005
1006     /* FIXME: HTTP support */
1007
1008     if( i_port == 0 )
1009     {
1010         i_port = 1234;
1011     }
1012
1013     asprintf( &p_sdp->psz_uri, "%s://@%s:%i", psz_proto, psz_uri, i_port );
1014
1015     FREE( psz_uri );
1016     FREE( psz_proto );
1017     return VLC_SUCCESS;
1018 }
1019
1020 /***********************************************************************
1021  * ParseSDP : SDP parsing
1022  * *********************************************************************
1023  * Validate SDP and parse all fields
1024  ***********************************************************************/
1025 static sdp_t *  ParseSDP( vlc_object_t *p_obj, char* psz_sdp )
1026 {
1027     sdp_t *p_sdp;
1028     vlc_bool_t b_invalid = VLC_FALSE;
1029     vlc_bool_t b_end = VLC_FALSE;
1030     if( psz_sdp == NULL )
1031     {
1032         return NULL;
1033     }
1034
1035     if( psz_sdp[0] != 'v' || psz_sdp[1] != '=' )
1036     {
1037         msg_Warn( p_obj, "Bad packet" );
1038         return NULL;
1039     }
1040
1041     p_sdp = (sdp_t *)malloc( sizeof( sdp_t ) );
1042     if( p_sdp == NULL )
1043         return NULL;
1044
1045     p_sdp->psz_sdp = strdup( psz_sdp );
1046     if( p_sdp->psz_sdp == NULL )
1047     {
1048         free( p_sdp );
1049         return NULL;
1050     }
1051
1052     p_sdp->psz_sessionname = NULL;
1053     p_sdp->psz_media       = NULL;
1054     p_sdp->psz_connection  = NULL;
1055     p_sdp->psz_uri         = NULL;
1056     p_sdp->psz_address     = NULL;
1057     p_sdp->psz_address_type= NULL;
1058
1059     p_sdp->i_media         = 0;
1060     p_sdp->i_attributes    = 0;
1061     p_sdp->pp_attributes   = NULL;
1062
1063     while( *psz_sdp != '\0' && b_end == VLC_FALSE  )
1064     {
1065         char *psz_eol;
1066         char *psz_eof;
1067         char *psz_parse;
1068         char *psz_sess_id;
1069
1070         while( *psz_sdp == '\r' || *psz_sdp == '\n' ||
1071                *psz_sdp == ' ' || *psz_sdp == '\t' )
1072         {
1073             psz_sdp++;
1074         }
1075
1076         if( ( psz_eol = strchr( psz_sdp, '\n' ) ) == NULL )
1077         {
1078             psz_eol = psz_sdp + strlen( psz_sdp );
1079             b_end = VLC_TRUE;
1080         }
1081         if( psz_eol > psz_sdp && *( psz_eol - 1 ) == '\r' )
1082         {
1083             psz_eol--;
1084         }
1085
1086         if( psz_eol <= psz_sdp )
1087         {
1088             break;
1089         }
1090         *psz_eol++ = '\0';
1091
1092         /* no space allowed between fields */
1093         if( psz_sdp[1] != '=' )
1094         {
1095             msg_Warn( p_obj, "invalid packet" ) ;
1096             FreeSDP( p_sdp );
1097             return NULL;
1098         }
1099
1100         /* Now parse each line */
1101         switch( psz_sdp[0] )
1102         {
1103             case( 'v' ):
1104                 break;
1105             case( 's' ):
1106                 p_sdp->psz_sessionname = strdup( &psz_sdp[2] );
1107                 break;
1108             case ( 'o' ):
1109             {
1110                 int i_field = 0;
1111                 /* o field is <username> <session id> <version>
1112                  *  <network type> <address type> <address> */
1113
1114 #define GET_FIELD( store ) \
1115                 psz_eof = strchr( psz_parse, ' ' ); \
1116                 if( psz_eof ) \
1117                 { \
1118                     *psz_eof=0; store = strdup( psz_parse ); \
1119                 } \
1120                 else \
1121                 { \
1122                     if( i_field != 5 ) \
1123                     { \
1124                         b_invalid = VLC_TRUE; break; \
1125                     } \
1126                     else \
1127                     { \
1128                         store = strdup( psz_parse ); \
1129                     } \
1130                 }; \
1131                 psz_parse = psz_eof + 1; i_field++;
1132
1133
1134                 psz_parse = &psz_sdp[2];
1135                 GET_FIELD( p_sdp->psz_username );
1136                 GET_FIELD( psz_sess_id );
1137
1138                 p_sdp->i_session_id = atoll( psz_sess_id );
1139
1140                 FREE( psz_sess_id );
1141
1142                 GET_FIELD( psz_sess_id );
1143                 FREE( psz_sess_id );
1144
1145                 GET_FIELD( p_sdp->psz_network_type );
1146                 GET_FIELD( p_sdp->psz_address_type );
1147                 GET_FIELD( p_sdp->psz_address );
1148
1149                 break;
1150             }
1151             case( 'i' ):
1152             case( 'u' ):
1153             case( 'e' ):
1154             case( 'p' ):
1155             case( 't' ):
1156             case( 'r' ):
1157                 break;
1158             case( 'a' ): /* attribute */
1159             {
1160                 char *psz_eon = strchr( &psz_sdp[2], ':' );
1161                 attribute_t *p_attr = malloc( sizeof( attribute_t ) );
1162
1163                 /* Attribute with value */
1164                 if( psz_eon )
1165                 {
1166                     *psz_eon++ = '\0';
1167
1168                     p_attr->psz_field = strdup( &psz_sdp[2] );
1169                     p_attr->psz_value = strdup( psz_eon );
1170                 }
1171                 else /* Attribute without value */
1172                 {
1173                     p_attr->psz_field = strdup( &psz_sdp[2] );
1174                     p_attr->psz_value = NULL;
1175                 }
1176
1177                 TAB_APPEND( p_sdp->i_attributes, p_sdp->pp_attributes, p_attr );
1178                 break;
1179             }
1180
1181             case( 'm' ): /* Media announcement */
1182             {
1183                 /* If we have several medias, we pass the announcement to
1184                  * LIVE.COM, so just count them */
1185                 p_sdp->i_media++;
1186                 if( p_sdp->i_media == 1 )
1187                 {
1188                     p_sdp->psz_media = strdup( &psz_sdp[2] );
1189                 }
1190                 break;
1191             }
1192
1193             case( 'c' ):
1194             {
1195                 if( p_sdp->i_media > 1 )
1196                     break;
1197
1198                 p_sdp->psz_connection = strdup( &psz_sdp[2] );
1199                 break;
1200             }
1201
1202             default:
1203                break;
1204         }
1205
1206         if( b_invalid )
1207         {
1208             FreeSDP( p_sdp );
1209             return NULL;
1210         }
1211
1212         psz_sdp = psz_eol;
1213     }
1214
1215     return p_sdp;
1216 }
1217
1218 static int InitSocket( services_discovery_t *p_sd, char *psz_address,
1219                        int i_port )
1220 {
1221     int i_fd = net_OpenUDP( p_sd, psz_address, i_port, "", 0 );
1222
1223     if( i_fd != -1 )
1224     {
1225         net_StopSend( i_fd );
1226         INSERT_ELEM(  p_sd->p_sys->pi_fd, p_sd->p_sys->i_fd,
1227                       p_sd->p_sys->i_fd, i_fd );
1228         return VLC_SUCCESS;
1229     }
1230
1231     return VLC_EGENERIC;
1232 }
1233
1234 #ifdef HAVE_ZLIB_H
1235 static int Decompress( unsigned char *psz_src, unsigned char **_dst, int i_len )
1236 {
1237     int i_result, i_dstsize, n;
1238     unsigned char *psz_dst;
1239     z_stream d_stream;
1240
1241     d_stream.zalloc = (alloc_func)0;
1242     d_stream.zfree = (free_func)0;
1243     d_stream.opaque = (voidpf)0;
1244
1245     i_result = inflateInit(&d_stream);
1246     if( i_result != Z_OK )
1247     {
1248         printf( "inflateInit() failed. Result: %d\n", i_result );
1249         return( -1 );
1250     }
1251 #if 0
1252     p_playlist->pp_items[p_playlist->i_index]->b_autodeletion = VLC_TRUE;
1253     i_position = p_playlist->i_index;
1254
1255     /* Gather the complete sdp file */
1256     for( ;; )
1257     {
1258         int i_read = stream_Read( p_demux->s, &p_sdp[i_sdp], i_sdp_max - i_sdp - 1 );
1259 #endif
1260     d_stream.next_in = (Bytef *)psz_src;
1261     d_stream.avail_in = i_len;
1262     n = 0;
1263
1264     psz_dst = NULL;
1265
1266     do
1267     {
1268         n++;
1269         psz_dst = (unsigned char *)realloc( psz_dst, n * 1000 );
1270         d_stream.next_out = (Bytef *)&psz_dst[(n - 1) * 1000];
1271         d_stream.avail_out = 1000;
1272
1273         i_result = inflate(&d_stream, Z_NO_FLUSH);
1274         if( ( i_result != Z_OK ) && ( i_result != Z_STREAM_END ) )
1275         {
1276             printf( "Zlib decompression failed. Result: %d\n", i_result );
1277             return( -1 );
1278         }
1279     }
1280     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
1281            ( i_result != Z_STREAM_END ) );
1282
1283     i_dstsize = d_stream.total_out;
1284     inflateEnd( &d_stream );
1285
1286     *_dst = (unsigned char *)realloc( psz_dst, i_dstsize );
1287
1288     return i_dstsize;
1289 }
1290 #endif
1291
1292
1293 static void FreeSDP( sdp_t *p_sdp )
1294 {
1295     int i;
1296     FREE( p_sdp->psz_sdp );
1297     FREE( p_sdp->psz_sessionname );
1298     FREE( p_sdp->psz_connection );
1299     FREE( p_sdp->psz_media );
1300     FREE( p_sdp->psz_uri );
1301     FREE( p_sdp->psz_username );
1302     FREE( p_sdp->psz_network_type );
1303
1304     FREE( p_sdp->psz_address );
1305     FREE( p_sdp->psz_address_type );
1306
1307     for( i= p_sdp->i_attributes - 1; i >= 0 ; i-- )
1308     {
1309         struct attribute_t *p_attr = p_sdp->pp_attributes[i];
1310         FREE( p_sdp->pp_attributes[i]->psz_field );
1311         FREE( p_sdp->pp_attributes[i]->psz_value );
1312         REMOVE_ELEM( p_sdp->pp_attributes, p_sdp->i_attributes, i);
1313         FREE( p_attr );
1314     }
1315     free( p_sdp );
1316 }
1317
1318 static int RemoveAnnounce( services_discovery_t *p_sd,
1319                            sap_announce_t *p_announce )
1320 {
1321     int i;
1322
1323     if( p_announce->p_sdp ) FreeSDP( p_announce->p_sdp );
1324
1325     if( p_announce->i_item_id > -1 )
1326     {
1327         playlist_LockDelete( p_sd->p_sys->p_playlist, p_announce->i_item_id );
1328     }
1329
1330     for( i = 0; i< p_sd->p_sys->i_announces; i++)
1331     {
1332         if( p_sd->p_sys->pp_announces[i] == p_announce )
1333         {
1334             REMOVE_ELEM( p_sd->p_sys->pp_announces, p_sd->p_sys->i_announces,
1335                          i);
1336             break;
1337         }
1338     }
1339
1340     free( p_announce );
1341
1342     return VLC_SUCCESS;
1343 }
1344
1345 static vlc_bool_t IsSameSession( sdp_t *p_sdp1, sdp_t *p_sdp2 )
1346 {
1347     /* A session is identified by
1348      * username, session_id, network type, address type and address */
1349     if( p_sdp1->psz_username && p_sdp2->psz_username &&
1350         p_sdp1->psz_network_type && p_sdp2->psz_network_type &&
1351         p_sdp1->psz_address_type && p_sdp2->psz_address_type &&
1352         p_sdp1->psz_address &&  p_sdp2->psz_address )
1353     {
1354         if(!strcmp( p_sdp1->psz_username , p_sdp2->psz_username ) &&
1355            !strcmp( p_sdp1->psz_network_type , p_sdp2->psz_network_type ) &&
1356            !strcmp( p_sdp1->psz_address_type , p_sdp2->psz_address_type ) &&
1357            !strcmp( p_sdp1->psz_address , p_sdp2->psz_address ) &&
1358            p_sdp1->i_session_id == p_sdp2->i_session_id )
1359         {
1360             return VLC_TRUE;
1361         }
1362         else
1363         {
1364             return VLC_FALSE;
1365         }
1366     }
1367     else
1368     {
1369         return VLC_FALSE;
1370     }
1371 }
1372
1373
1374 static void CacheLoad( services_discovery_t *p_sd )
1375 {
1376     msg_Warn( p_sd, "Cache not implemented") ;
1377 }
1378
1379 static void CacheSave( services_discovery_t *p_sd )
1380 {
1381     msg_Warn( p_sd, "Cache not implemented") ;
1382 }