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