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