]> git.sesse.net Git - vlc/blob - src/misc/netutils.c
* --chennels puts gtk/gnome in multi-channel network mode.
[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.46 2001/11/16 00:29:52 stef 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 #if defined( SYS_BEOS )
118     intf_ErrMsg( "error: channel changing is not yet supported under BeOS" );
119     return( 1 );
120
121 #else
122     char                psz_hostname[INPUT_MAX_SOURCE_LENGTH];
123     struct hostent    * p_hostent;
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 #endif
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 #if defined( SYS_BEOS )
177     intf_ErrMsg( "error: channel changing is not yet supported under BeOS" );
178     return( 1 );
179
180 #else
181     struct hostent            * p_hostent;
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 #endif
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         if( p_item )
406         {
407             free( p_item->psz_name );
408             p_item->psz_name = strdup( psz_mess );
409         }
410         else
411         {
412             intf_PlaylistAdd( p_main->p_playlist, 0, psz_mess );
413         }
414         vlc_mutex_unlock( &p_main->p_playlist->change_lock );
415     }
416
417     /* Close the socket and return nicely */
418     close( i_fd );
419
420     return 0;
421
422 #else
423     intf_ErrMsg( "network error: channels not supported on this platform" );
424     return -1; 
425
426 #endif
427 }
428
429 /* Following functions are local */
430
431 /*****************************************************************************
432  * GetMacAddress: extract the MAC Address
433  *****************************************************************************/
434 static int GetMacAddress( int i_fd, char *psz_mac )
435 {
436 #if defined( SYS_LINUX )
437     struct ifreq interface;
438     int i_ret;
439
440     /*
441      * Looking for information about the eth0 interface
442      */
443     interface.ifr_addr.sa_family = AF_INET;
444     strcpy( interface.ifr_name, 
445             main_GetPszVariable( INPUT_IFACE_VAR, INPUT_IFACE_DEFAULT ) );
446
447     i_ret = ioctl( i_fd, SIOCGIFHWADDR, &interface );
448
449     if( i_ret )
450     {
451         intf_ErrMsg( "network error: ioctl SIOCGIFHWADDR failed" );
452         return( i_ret );
453     }
454
455     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
456                       interface.ifr_hwaddr.sa_data[0] & 0xff,
457                       interface.ifr_hwaddr.sa_data[1] & 0xff,
458                       interface.ifr_hwaddr.sa_data[2] & 0xff,
459                       interface.ifr_hwaddr.sa_data[3] & 0xff,
460                       interface.ifr_hwaddr.sa_data[4] & 0xff,
461                       interface.ifr_hwaddr.sa_data[5] & 0xff );
462
463     return( 0 );
464
465 #elif defined( WIN32 )
466     int i, i_ret = -1;
467
468     /* Get adapter list - support for more than one adapter */
469     LANA_ENUM AdapterList;
470     NCB       Ncb;
471
472     intf_WarnMsg( 2, "network: looking for MAC address" );
473
474     memset( &Ncb, 0, sizeof( NCB ) );
475     Ncb.ncb_command = NCBENUM;
476     Ncb.ncb_buffer = (unsigned char *)&AdapterList;
477     Ncb.ncb_length = sizeof( AdapterList );
478     Netbios( &Ncb );
479
480     /* Get all of the local ethernet addresses */
481     for ( i = 0; i < AdapterList.length ; ++i )
482     {
483         if ( GetAdapterInfo ( AdapterList.lana[ i ], psz_mac ) == 0 )
484         {
485             i_ret = 0;
486         }
487     }
488
489     return( i_ret );
490
491 #else
492     return( -1);
493
494 #endif
495 }
496
497 #ifdef WIN32
498 /*****************************************************************************
499  * GetAdapterInfo : gets some informations about the interface using NETBIOS
500  *****************************************************************************/
501 static int GetAdapterInfo( int i_adapter, char *psz_string )
502 {
503     struct ASTAT
504     {
505         ADAPTER_STATUS adapt;
506         NAME_BUFFER    psz_name[30];
507     } Adapter;
508
509     /* Reset the LAN adapter so that we can begin querying it */
510     NCB Ncb;
511     memset( &Ncb, 0, sizeof ( Ncb ) );
512     Ncb.ncb_command  = NCBRESET;
513     Ncb.ncb_lana_num = i_adapter;
514
515     if( Netbios( &Ncb ) != NRC_GOODRET )
516     {
517         intf_ErrMsg( "network error: reset returned %i", Ncb.ncb_retcode );
518         return -1;
519     }
520
521     /* Prepare to get the adapter status block */
522     memset( &Ncb, 0, sizeof( Ncb ) ) ;     /* Initialization */
523     Ncb.ncb_command = NCBASTAT;
524     Ncb.ncb_lana_num = i_adapter;
525
526     strcpy( (char *)Ncb.ncb_callname, "*" );
527
528     memset( &Adapter, 0, sizeof ( Adapter ) );
529     Ncb.ncb_buffer = ( unsigned char * ) &Adapter;
530     Ncb.ncb_length = sizeof ( Adapter );
531
532     /* Get the adapter's info and, if this works, return it in standard,
533      * colon-delimited form. */
534     if ( Netbios( &Ncb ) == 0 )
535     {
536         sprintf ( psz_string, "%02X:%02X:%02X:%02X:%02X:%02X",
537                 (int) ( Adapter.adapt.adapter_address[0] ),
538                 (int) ( Adapter.adapt.adapter_address[1] ),
539                 (int) ( Adapter.adapt.adapter_address[2] ),
540                 (int) ( Adapter.adapt.adapter_address[3] ),
541                 (int) ( Adapter.adapt.adapter_address[4] ),
542                 (int) ( Adapter.adapt.adapter_address[5] ) );
543
544         intf_WarnMsg( 2, "network: found MAC address %s", psz_string );
545
546         return 0;
547     }
548     else
549     {
550         intf_ErrMsg( "network error: ASTAT returned %i", Ncb.ncb_retcode );
551         return -1;
552     }
553 }
554 #endif /* WIN32 */
555