]> git.sesse.net Git - vlc/blob - src/misc/netutils.c
* Fixed the vlcs communication for real now.
[vlc] / src / misc / netutils.c
1 /*****************************************************************************
2  * netutils.c: various network functions
3  *****************************************************************************
4  * Copyright (C) 1999, 2000, 2001 VideoLAN
5  * $Id: netutils.c,v 1.44 2001/11/12 23:56:53 sam Exp $
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Benoit Steiner <benny@via.ecp.fr>
9  *          Henri Fallon <henri@videolan.org>
10  *          Xavier Marchesini <xav@via.ecp.fr>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include "defs.h"
31
32 #include <stdlib.h>                             /* free(), realloc(), atoi() */
33 #include <errno.h>                                                /* errno() */
34 #include <string.h>                                              /* memset() */
35
36 #ifdef STRNCASECMP_IN_STRINGS_H
37 #   include <strings.h>
38 #endif
39
40 #ifdef HAVE_UNISTD_H
41 #   include <unistd.h>                                      /* gethostname() */
42 #elif defined( _MSC_VER ) && defined( _WIN32 )
43 #   include <io.h>
44 #endif
45
46 #if !defined( _MSC_VER )
47 #include <sys/time.h>                                        /* gettimeofday */
48 #endif
49
50 #ifdef WIN32
51 #   include <winsock2.h>
52 #elif !defined( SYS_BEOS ) && !defined( SYS_NTO )
53 #   include <netdb.h>                                         /* hostent ... */
54 #   include <sys/socket.h>                           /* BSD: struct sockaddr */
55 #   include <netinet/in.h>                            /* BSD: struct in_addr */
56 #   ifdef HAVE_ARPA_INET_H
57 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
58 #   endif
59 #endif
60
61 #ifdef SYS_LINUX
62 #include <sys/ioctl.h>                                            /* ioctl() */
63 #endif
64
65 #if defined( WIN32 )                    /* tools to get the MAC adress from  */
66 #include <windows.h>                    /* the interface under Windows       */
67 #include <stdio.h>
68 #endif
69
70 #ifdef HAVE_NET_IF_H
71 #include <net/if.h>                            /* interface (arch-dependent) */
72 #endif
73
74 #ifdef HAVE_SYS_SOCKIO_H
75 #include <sys/sockio.h>
76 #endif
77
78 #include "config.h"
79 #include "common.h"
80 #include "mtime.h"
81 #include "threads.h"
82 #include "main.h"
83
84 #include "intf_msg.h"
85 #include "intf_playlist.h"
86
87 #include "netutils.h"
88
89 /*****************************************************************************
90  * input_channel_t: channel library data
91  *****************************************************************************
92  * Store global channel library data.
93  * The part of the code concerning the channel changing process is unstable
94  * as it depends on the VideoLAN channel server, which isn't frozen for
95  * the time being.
96  *****************************************************************************/
97 typedef struct input_channel_s
98 {
99     int         i_channel;                         /* current channel number */
100     mtime_t     last_change;                             /* last change date */
101 } input_channel_t;
102
103 /*****************************************************************************
104  * Local prototypes
105  *****************************************************************************/
106 static int GetMacAddress   ( int i_fd, char *psz_mac );
107 #ifdef WIN32
108 static int GetAdapterInfo  ( int i_adapter, char *psz_string );
109 #endif
110
111 /*****************************************************************************
112  * network_BuildLocalAddr : fill a sockaddr_in structure for local binding
113  *****************************************************************************/
114 int network_BuildLocalAddr( struct sockaddr_in * p_socket, int i_port,
115                             char * psz_broadcast )
116 {
117
118     char                psz_hostname[INPUT_MAX_SOURCE_LENGTH];
119     struct hostent    * p_hostent;
120
121 #if defined( SYS_BEOS )
122     intf_ErrMsg( "error: channel changing is not yet supported under BeOS" );
123     return( 1 );
124 #endif
125
126     /* Reset struct */
127     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
128     p_socket->sin_family = AF_INET;                                /* family */
129     p_socket->sin_port = htons( i_port );
130     if( psz_broadcast == NULL )
131     {
132         /* Try to get our own IP */
133         if( gethostname( psz_hostname, sizeof(psz_hostname) ) )
134         {
135             intf_ErrMsg( "BuildLocalAddr : unable to resolve local name : %s",
136                          strerror( errno ) );
137             return( -1 );
138         }
139
140     }
141     else
142     {
143         /* I didn't manage to make INADDR_ANYT work, even with setsockopt
144          * so, as it's kludgy to try and determine the broadcast addr
145          * it is passed as an argument in the command line */
146         strncpy( psz_hostname, psz_broadcast, INPUT_MAX_SOURCE_LENGTH );
147     }
148
149     /* Try to convert address directly from in_addr - this will work if
150      * psz_in_addr is dotted decimal. */
151 #ifdef HAVE_ARPA_INET_H
152     if( !inet_aton( psz_hostname, &p_socket->sin_addr) )
153 #else
154     if( (p_socket->sin_addr.s_addr = inet_addr( psz_hostname )) == -1 )
155 #endif
156     {
157         /* We have a fqdn, try to find its address */
158         if ( (p_hostent = gethostbyname( psz_hostname )) == NULL )
159         {
160             intf_ErrMsg( "BuildLocalAddr: unknown host %s", psz_hostname );
161             return( -1 );
162         }
163
164         /* Copy the first address of the host in the socket address */
165         memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
166                  p_hostent->h_length );
167     }
168     return( 0 );
169 }
170
171 /*****************************************************************************
172  * network_BuildRemoteAddr : fill a sockaddr_in structure for remote host
173  *****************************************************************************/
174 int network_BuildRemoteAddr( struct sockaddr_in * p_socket, char * psz_server )
175 {
176
177     struct hostent            * p_hostent;
178
179 #if defined( SYS_BEOS )
180     intf_ErrMsg( "error: channel changing is not yet supported under BeOS" );
181     return( 1 );
182 #endif
183
184     /* Reset structure */
185     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
186     p_socket->sin_family = AF_INET;                                /* family */
187     p_socket->sin_port = htons( 0 );               /* This is for remote end */
188
189      /* Try to convert address directly from in_addr - this will work if
190       * psz_in_addr is dotted decimal. */
191
192 #ifdef HAVE_ARPA_INET_H
193     if( !inet_aton( psz_server, &p_socket->sin_addr) )
194 #else
195     if( (p_socket->sin_addr.s_addr = inet_addr( psz_server )) == -1 )
196 #endif
197     {
198         /* We have a fqdn, try to find its address */
199         if ( (p_hostent = gethostbyname(psz_server)) == NULL )
200         {
201             intf_ErrMsg( "BuildRemoteAddr: unknown host %s",
202                          psz_server );
203             return( -1 );
204         }
205
206         /* Copy the first address of the host in the socket address */
207         memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
208                  p_hostent->h_length );
209     }
210     return( 0 );
211 }
212
213 /*****************************************************************************
214  * network_ChannelCreate: initialize global channel method data
215  *****************************************************************************
216  * Initialize channel input method global data. This function should be called
217  * once before any input thread is created or any call to other
218  * input_Channel*() function is attempted.
219  *****************************************************************************/
220 int network_ChannelCreate( void )
221 {
222 #if defined( SYS_LINUX ) || defined( WIN32 )
223
224     /* Allocate structure */
225     p_main->p_channel = malloc( sizeof( input_channel_t ) );
226     if( p_main->p_channel == NULL )
227     {
228         intf_ErrMsg( "network error: could not create channel bank" );
229         return( -1 );
230     }
231
232     /* Initialize structure */
233     p_main->p_channel->i_channel   = 0;
234     p_main->p_channel->last_change = 0;
235
236     intf_WarnMsg( 2, "network: channels initialized" );
237     return( 0 );
238
239 #else
240     intf_ErrMsg( "network error : channels not supported on this platform" );
241     return( 1 );
242
243 #endif
244 }
245
246 /*****************************************************************************
247  * network_ChannelJoin: join a channel
248  *****************************************************************************
249  * This function will try to join a channel. If the relevant interface is
250  * already on the good channel, nothing will be done. Else, and if possible
251  * (if the interface is not locked), the channel server will be contacted
252  * and a change will be requested. The function will block until the change
253  * is effective. Note that once a channel is no more used, its interface
254  * should be unlocked using input_ChannelLeave().
255  * Non 0 will be returned in case of error.
256  *****************************************************************************/
257 int network_ChannelJoin( int i_channel )
258 {
259 #if defined( SYS_LINUX ) || defined( WIN32 )
260
261 #define VLCS_VERSION 12
262 #define MESSAGE_LENGTH 256
263
264     char psz_mess[ MESSAGE_LENGTH ];
265     char psz_mac[ 40 ];
266     int i_fd, i_dummy, i_port;
267     char *psz_vlcs;
268     struct sockaddr_in sa_server;
269     struct sockaddr_in sa_client;
270     struct timeval delay;
271     fd_set fds;
272
273     if( !main_GetIntVariable( INPUT_NETWORK_CHANNEL_VAR,
274                               INPUT_NETWORK_CHANNEL_DEFAULT  ) )
275     {
276         intf_ErrMsg( "network: channels disabled, to enable them, use the"
277                      "--channels option" );
278         return -1;
279     }
280
281     /* If last change is too recent, wait a while */
282     if( mdate() - p_main->p_channel->last_change < INPUT_CHANNEL_CHANGE_DELAY )
283     {
284         intf_WarnMsg( 2, "network: waiting before changing channel" );
285         /* XXX Isn't this completely brain-damaged ??? -- Sam */
286         mwait( p_main->p_channel->last_change + INPUT_CHANNEL_CHANGE_DELAY );
287     }
288
289     /* Initializing the socket */
290     i_fd = socket( AF_INET, SOCK_DGRAM, 0 );
291     if( i_fd < 0 )
292     {
293         intf_ErrMsg( "network error: unable to create vlcs socket (%s)",
294                      strerror( errno ) );
295         return -1;
296     }
297
298     i_dummy = 1;
299     if( setsockopt( i_fd, SOL_SOCKET, SO_REUSEADDR,
300                     (void *) &i_dummy, sizeof( i_dummy ) ) == -1 )
301     {
302         intf_ErrMsg( "network error: can't SO_REUSEADDR vlcs socket (%s)",
303                      strerror(errno));
304         close( i_fd );
305         return -1;
306     }
307
308     /* Getting information about the channel server */
309     psz_vlcs = main_GetPszVariable( INPUT_CHANNEL_SERVER_VAR,
310                                     INPUT_CHANNEL_SERVER_DEFAULT );
311     i_port = main_GetIntVariable( INPUT_CHANNEL_PORT_VAR,
312                                   INPUT_CHANNEL_PORT_DEFAULT );
313
314     intf_WarnMsg( 5, "network: socket %i, vlcs '%s', port %d",
315                      i_fd, psz_vlcs, i_port );
316
317     memset( &sa_client, 0x00, sizeof(struct sockaddr_in) );
318     memset( &sa_server, 0x00, sizeof(struct sockaddr_in) );
319     sa_client.sin_family      = AF_INET;
320     sa_server.sin_family      = AF_INET;
321     sa_client.sin_port        = htons( 4312 );
322     sa_server.sin_port        = htons( i_port );
323     sa_client.sin_addr.s_addr = INADDR_ANY;
324 #ifdef HAVE_ARPA_INET_H
325     inet_aton( psz_vlcs, &sa_server.sin_addr );
326 #else
327     sa_server.sin_addr.s_addr = inet_addr( psz_vlcs );
328 #endif
329
330     /* Bind the socket */
331     if( bind( i_fd, (struct sockaddr*)(&sa_client), sizeof(sa_client) ) )
332     {
333         intf_ErrMsg( "network: unable to bind vlcs socket (%s)",
334                      strerror( errno ) );
335         close( i_fd );
336         return -1;
337     }
338
339     /* Look for the interface MAC address */
340     if( GetMacAddress( i_fd, psz_mac ) )
341     {
342         intf_ErrMsg( "network error: failed getting MAC address" );
343         close( i_fd );
344         return -1;
345     }
346
347     intf_WarnMsg( 6, "network: MAC address is %s", psz_mac );
348
349     /* Build the message */
350     sprintf( psz_mess, "%d %u %lu %s \n", i_channel, VLCS_VERSION,
351                        (unsigned long)(mdate() / (unsigned long long)1000000),
352                        psz_mac );
353
354     /* Send the message */
355     sendto( i_fd, psz_mess, MESSAGE_LENGTH, 0,
356             (struct sockaddr *)(&sa_server), sizeof(struct sockaddr) );
357
358     intf_WarnMsg( 2, "network: attempting to join channel %d", i_channel );
359
360     /* We have changed channels ! (or at least, we tried) */
361     p_main->p_channel->last_change = mdate();
362     p_main->p_channel->i_channel = i_channel;
363
364     /* Wait 5 sec for an answer from the server */
365     delay.tv_sec = 5;
366     delay.tv_usec = 0;
367     FD_ZERO( &fds );
368     FD_SET( i_fd, &fds );
369
370     switch( select( i_fd + 1, &fds, NULL, NULL, &delay ) )
371     {
372         case 0:
373             intf_ErrMsg( "network error: no answer from vlcs" );
374             close( i_fd );
375             return -1;
376             break;
377
378         case -1:
379             intf_ErrMsg( "network error: error while listening to vlcs" );
380             close( i_fd );
381             return -1;
382             break;
383     }
384
385     i_dummy = sizeof( struct sockaddr );
386     recvfrom( i_fd, psz_mess, MESSAGE_LENGTH, 0,
387               (struct sockaddr *)(&sa_client), &i_dummy);
388     psz_mess[ MESSAGE_LENGTH - 1 ] = 0;
389
390     if( !strncasecmp( psz_mess, "E: ", 3 ) )
391     {
392         intf_ErrMsg( "network error: vlcs said '%s'", psz_mess + 3 );
393         close( i_fd );
394         return -1;
395     }
396     else if( !strncasecmp( psz_mess, "I: ", 3 ) )
397     {
398         intf_WarnMsg( 2, "network info: vlcs said '%s'", psz_mess + 3 );
399     }
400     else /* We got something to play ! FIXME: not very nice */
401     {
402 #   define p_item \
403         (&p_main->p_playlist->p_item[ p_main->p_playlist->i_index + 1])
404         vlc_mutex_lock( &p_main->p_playlist->change_lock );
405         free( p_item->psz_name );
406         p_item->psz_name = strdup( psz_mess );
407         vlc_mutex_unlock( &p_main->p_playlist->change_lock );
408     }
409
410     /* Close the socket and return nicely */
411     close( i_fd );
412
413     return 0;
414
415 #else
416     intf_ErrMsg( "network error: channels not supported on this platform" );
417     return -1; 
418
419 #endif
420 }
421
422 /* Following functions are local */
423
424 /*****************************************************************************
425  * GetMacAddress: extract the MAC Address
426  *****************************************************************************/
427 static int GetMacAddress( int i_fd, char *psz_mac )
428 {
429 #if defined( SYS_LINUX )
430     struct ifreq interface;
431     int i_ret;
432
433     /*
434      * Looking for information about the eth0 interface
435      */
436     interface.ifr_addr.sa_family = AF_INET;
437     strcpy( interface.ifr_name, 
438             main_GetPszVariable( INPUT_IFACE_VAR, INPUT_IFACE_DEFAULT ) );
439
440     i_ret = ioctl( i_fd, SIOCGIFHWADDR, &interface );
441
442     if( i_ret )
443     {
444         intf_ErrMsg( "network error: ioctl SIOCGIFHWADDR failed" );
445         return( i_ret );
446     }
447
448     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
449                       interface.ifr_hwaddr.sa_data[0] & 0xff,
450                       interface.ifr_hwaddr.sa_data[1] & 0xff,
451                       interface.ifr_hwaddr.sa_data[2] & 0xff,
452                       interface.ifr_hwaddr.sa_data[3] & 0xff,
453                       interface.ifr_hwaddr.sa_data[4] & 0xff,
454                       interface.ifr_hwaddr.sa_data[5] & 0xff );
455
456     return( 0 );
457
458 #elif defined( WIN32 )
459     int i, i_ret = -1;
460
461     /* Get adapter list - support for more than one adapter */
462     LANA_ENUM AdapterList;
463     NCB       Ncb;
464
465     intf_WarnMsg( 2, "network: looking for MAC address" );
466
467     memset( &Ncb, 0, sizeof( NCB ) );
468     Ncb.ncb_command = NCBENUM;
469     Ncb.ncb_buffer = (unsigned char *)&AdapterList;
470     Ncb.ncb_length = sizeof( AdapterList );
471     Netbios( &Ncb );
472
473     /* Get all of the local ethernet addresses */
474     for ( i = 0; i < AdapterList.length ; ++i )
475     {
476         if ( GetAdapterInfo ( AdapterList.lana[ i ], psz_mac ) == 0 )
477         {
478             i_ret = 0;
479         }
480     }
481
482     return( i_ret );
483
484 #else
485     return( -1);
486
487 #endif
488 }
489
490 #ifdef WIN32
491 /*****************************************************************************
492  * GetAdapterInfo : gets some informations about the interface using NETBIOS
493  *****************************************************************************/
494 static int GetAdapterInfo( int i_adapter, char *psz_string )
495 {
496     struct ASTAT
497     {
498         ADAPTER_STATUS adapt;
499         NAME_BUFFER    psz_name[30];
500     } Adapter;
501
502     /* Reset the LAN adapter so that we can begin querying it */
503     NCB Ncb;
504     memset( &Ncb, 0, sizeof ( Ncb ) );
505     Ncb.ncb_command  = NCBRESET;
506     Ncb.ncb_lana_num = i_adapter;
507
508     if( Netbios( &Ncb ) != NRC_GOODRET )
509     {
510         intf_ErrMsg( "network error: reset returned %i", Ncb.ncb_retcode );
511         return -1;
512     }
513
514     /* Prepare to get the adapter status block */
515     memset( &Ncb, 0, sizeof( Ncb ) ) ;     /* Initialization */
516     Ncb.ncb_command = NCBASTAT;
517     Ncb.ncb_lana_num = i_adapter;
518
519     strcpy( (char *)Ncb.ncb_callname, "*" );
520
521     memset( &Adapter, 0, sizeof ( Adapter ) );
522     Ncb.ncb_buffer = ( unsigned char * ) &Adapter;
523     Ncb.ncb_length = sizeof ( Adapter );
524
525     /* Get the adapter's info and, if this works, return it in standard,
526      * colon-delimited form. */
527     if ( Netbios( &Ncb ) == 0 )
528     {
529         sprintf ( psz_string, "%02X:%02X:%02X:%02X:%02X:%02X",
530                 (int) ( Adapter.adapt.adapter_address[0] ),
531                 (int) ( Adapter.adapt.adapter_address[1] ),
532                 (int) ( Adapter.adapt.adapter_address[2] ),
533                 (int) ( Adapter.adapt.adapter_address[3] ),
534                 (int) ( Adapter.adapt.adapter_address[4] ),
535                 (int) ( Adapter.adapt.adapter_address[5] ) );
536
537         intf_WarnMsg( 2, "network: found MAC address %s", psz_string );
538
539         return 0;
540     }
541     else
542     {
543         intf_ErrMsg( "network error: ASTAT returned %i", Ncb.ncb_retcode );
544         return -1;
545     }
546 }
547 #endif /* WIN32 */
548