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