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