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