]> git.sesse.net Git - vlc/blob - src/misc/netutils.c
5d163c2dfefaf4dcdf5e26bc0d7976d3f13107bb
[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.36 2001/05/31 01:37:08 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 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     char                psz_hostname[INPUT_MAX_SOURCE_LENGTH];
112     struct hostent    * p_hostent;
113
114     /* Reset struct */
115     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
116     p_socket->sin_family = AF_INET;                                /* family */
117     p_socket->sin_port = htons( i_port );
118     if( psz_broadcast == NULL )
119     {
120         /* Try to get our own IP */
121         if( gethostname( psz_hostname, sizeof(psz_hostname) ) )
122         {
123             intf_ErrMsg( "BuildLocalAddr : unable to resolve local name : %s",
124                          strerror( errno ) );
125             return( -1 );
126         }
127
128     }
129     else
130     {
131         /* I didn't manage to make INADDR_ANYT work, even with setsockopt
132          * so, as it's kludgy to try and determine the broadcast addr
133          * it is passed as an argument in the command line */
134         strncpy( psz_hostname, psz_broadcast, INPUT_MAX_SOURCE_LENGTH );
135     }
136
137     /* Try to convert address directly from in_addr - this will work if
138      * psz_in_addr is dotted decimal. */
139 #ifdef HAVE_ARPA_INET_H
140     if( !inet_aton( psz_hostname, &p_socket->sin_addr) )
141 #else
142     if( (p_socket->sin_addr.s_addr = inet_addr( psz_hostname )) == -1 )
143 #endif
144     {
145         /* We have a fqdn, try to find its address */
146         if ( (p_hostent = gethostbyname( psz_hostname )) == NULL )
147         {
148             intf_ErrMsg( "BuildLocalAddr: unknown host %s", psz_hostname );
149             return( -1 );
150         }
151
152         /* Copy the first address of the host in the socket address */
153         memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
154                  p_hostent->h_length );
155     }
156     return( 0 );
157 }
158
159 /*****************************************************************************
160  * network_BuildRemoteAddr : fill a sockaddr_in structure for remote host
161  *****************************************************************************/
162 int network_BuildRemoteAddr( struct sockaddr_in * p_socket, char * psz_server )
163 {
164     struct hostent            * p_hostent;
165
166     /* Reset structure */
167     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
168     p_socket->sin_family = AF_INET;                                /* family */
169     p_socket->sin_port = htons( 0 );               /* This is for remote end */
170
171      /* Try to convert address directly from in_addr - this will work if
172       * psz_in_addr is dotted decimal. */
173
174 #ifdef HAVE_ARPA_INET_H
175     if( !inet_aton( psz_server, &p_socket->sin_addr) )
176 #else
177     if( (p_socket->sin_addr.s_addr = inet_addr( psz_server )) == -1 )
178 #endif
179     {
180         /* We have a fqdn, try to find its address */
181         if ( (p_hostent = gethostbyname(psz_server)) == NULL )
182         {
183             intf_ErrMsg( "BuildRemoteAddr: unknown host %s",
184                          psz_server );
185             return( -1 );
186         }
187
188         /* Copy the first address of the host in the socket address */
189         memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
190                  p_hostent->h_length );
191     }
192     return( 0 );
193 }
194
195 /*****************************************************************************
196  * network_ChannelCreate: initialize global channel method data
197  *****************************************************************************
198  * Initialize channel input method global data. This function should be called
199  * once before any input thread is created or any call to other
200  * input_Channel*() function is attempted.
201  *****************************************************************************/
202 int network_ChannelCreate( void )
203 {
204 /* Even when BSD are supported, BeOS is not likely to be supported, so
205  * I prefer to put it apart */
206 #if defined( SYS_BEOS )
207     intf_ErrMsg( "error: channel changing is not yet supported under BeOS" );
208     return( 1 );
209
210 #elif defined( SYS_LINUX ) || defined( WIN32 )
211 /* FIXME : channels handling only work for linux */
212     /* Allocate structure */
213     p_main->p_channel = malloc( sizeof( input_channel_t ) );
214     if( p_main->p_channel == NULL )
215     {
216         intf_ErrMsg( "network error: could not create channel bank" );
217         return( -1 );
218     }
219
220     /* Initialize structure */
221     p_main->p_channel->i_channel   = 0;
222     p_main->p_channel->last_change = 0;
223
224     intf_Msg( "network: channels initialized" );
225     return( 0 );
226
227 #else
228     intf_ErrMsg( "network error : channels not supported" );
229     return( 1 );
230
231 #endif
232 }
233
234 /*****************************************************************************
235  * network_ChannelJoin: join a channel
236  *****************************************************************************
237  * This function will try to join a channel. If the relevant interface is
238  * already on the good channel, nothing will be done. Else, and if possible
239  * (if the interface is not locked), the channel server will be contacted
240  * and a change will be requested. The function will block until the change
241  * is effective. Note that once a channel is no more used, it's interface
242  * should be unlocked using input_ChannelLeave().
243  * Non 0 will be returned in case of error.
244  *****************************************************************************/
245 int network_ChannelJoin( int i_channel )
246 {
247 /* I still prefer to put BeOS a bit apart */
248 #if defined( SYS_BEOS )
249     intf_ErrMsg( "network error: channels are not yet supported under BeOS" );
250     return( -1 );
251
252 #elif defined( SYS_LINUX ) || defined( WIN32 )
253     int                 i_socket;
254     int                 i_fromlen;
255     struct sockaddr_in  sa_server;
256     struct sockaddr_in  sa_client;
257     unsigned int        i_version = 12;
258     char                psz_mess[ 80 ];
259     char                psz_mac[ 40 ];
260     char                i_mess_length = 80;
261     unsigned long int   i_date;
262     struct timeval      answer_delay;
263     int                 i_nbanswer;
264     char                i_answer;
265     fd_set              fd;
266     unsigned int        i_rc;
267     char *              psz_channel_server;
268
269     if( !main_GetIntVariable( INPUT_NETWORK_CHANNEL_VAR,
270                               INPUT_NETWORK_CHANNEL_DEFAULT  ) )
271     {
272         intf_ErrMsg( "network: channels disabled, to enable them, use the"
273                      "--channels option" );
274         return( -1 );
275     }
276
277     /* debug */
278     intf_DbgMsg( "network: ChannelJoin : %d", i_channel );
279     /* If last change is too recent, wait a while */
280     if( mdate() - p_main->p_channel->last_change < INPUT_CHANNEL_CHANGE_DELAY )
281     {
282         intf_WarnMsg( 2, "network: waiting before changing channel" );
283         mwait( p_main->p_channel->last_change + INPUT_CHANNEL_CHANGE_DELAY );
284     }
285
286     p_main->p_channel->last_change = mdate();
287     p_main->p_channel->i_channel   = i_channel;
288
289     intf_WarnMsg( 2, "network: joining channel %d", i_channel );
290
291     /*
292      * Initializing the socket
293      */
294     i_socket = socket( AF_INET, SOCK_DGRAM, 0 );
295
296     /*
297      * Getting the server's information
298      */
299     intf_WarnMsg( 6, "Channel server: %s port: %d",
300             main_GetPszVariable( INPUT_CHANNEL_SERVER_VAR,
301                                  INPUT_CHANNEL_SERVER_DEFAULT ),
302             main_GetIntVariable( INPUT_CHANNEL_PORT_VAR,
303                                  INPUT_CHANNEL_PORT_DEFAULT ) );
304
305     memset( &sa_server, 0x00, sizeof(struct sockaddr_in) );
306     sa_server.sin_family = AF_INET;
307     sa_server.sin_port   = htons( main_GetIntVariable( INPUT_CHANNEL_PORT_VAR,
308                                   INPUT_CHANNEL_PORT_DEFAULT ) );
309
310     psz_channel_server = strdup( main_GetPszVariable( INPUT_CHANNEL_SERVER_VAR,
311                                  INPUT_CHANNEL_SERVER_DEFAULT ) );
312 #ifdef HAVE_ARPA_INET_H
313     inet_aton( psz_channel_server, &sa_server.sin_addr );
314 #else
315     sa_server.sin_addr.s_addr = inet_addr( psz_channel_server );
316 #endif
317     free( psz_channel_server );
318
319     /*
320      * Looking for the interface MAC address
321      */
322     if( GetMacAddress( i_socket, psz_mac ) )
323     {
324         intf_ErrMsg( "network error: failed getting MAC address" );
325         return( -1 );
326     }
327
328     /*
329      * Getting date of the client in seconds
330      */
331     i_date = mdate() / 1000000;
332     intf_DbgMsg( "vlcs: date %lu", i_date );
333
334     /*
335      * Build of the message
336      */
337     sprintf( psz_mess, "%d %u %lu %s \n",
338              i_channel, i_version, i_date, psz_mac );
339
340     intf_DbgMsg( "vlcs: The message is %s", psz_mess );
341
342     /*
343      * Open the socket 2
344      */
345     memset( &sa_client, 0x00, sizeof(struct sockaddr_in) );
346     sa_client.sin_family = AF_INET;
347     sa_client.sin_port   = htons(4312);
348     sa_client.sin_addr.s_addr = INADDR_ANY;
349     i_fromlen = sizeof( struct sockaddr );
350     i_rc = bind( i_socket, (struct sockaddr *)(&sa_client),\
351                  sizeof(struct sockaddr) );
352     if ( i_rc )
353     {
354         intf_ErrMsg( "vlcs: Unable to bind socket:%u ", i_rc );
355     /* TODO put CS_R_BIND in types.h*/
356     /*    return CS_R_SOCKET;*/
357         return -1;
358     }
359
360     /*
361      * Send the message
362      */
363     sendto( i_socket, psz_mess, i_mess_length, 0, \
364             (struct sockaddr *)(&sa_server),   \
365             sizeof(struct sockaddr) );
366
367      /*
368      * Waiting 5 sec for one answer from the server
369      */
370     answer_delay.tv_sec  = 5;
371     answer_delay.tv_usec = 0;
372     FD_ZERO( &fd );
373     FD_SET( i_socket, &fd );
374     i_nbanswer = select( i_socket + 1, &fd, NULL, NULL, &answer_delay );
375
376     switch( i_nbanswer )
377     {
378     case 0:
379         intf_DbgMsg( "vlcs: no answer" );
380         break;
381
382     case -1:
383         intf_DbgMsg( "vlcs: unable to receive the answer ");
384         break;
385
386     default:
387         recvfrom( i_socket, &i_answer, sizeof(char), 0,\
388                   (struct sockaddr *)(&sa_client), &i_fromlen);
389
390         intf_DbgMsg( "vlcs: the answer : %i", i_answer );
391
392         switch( i_answer )
393         {
394             case -1:
395                 intf_DbgMsg( "vlcs: the server failed to create the thread" );
396                 break;
397             case 0:
398                 intf_DbgMsg( "vlcs: the server tries to change the channel" );
399                 break;
400             default:
401                 intf_DbgMsg( "vlcs: unknown answer !" );
402                 break;
403         }
404         break;
405     }
406
407     /*
408      * Close the socket
409      */
410     close( i_socket );
411
412     return( 0 );
413
414 #else
415     intf_ErrMsg( "network error: channels not supported" );
416     return( -1 );
417
418 #endif
419 }
420
421 /* Following functions are local */
422
423 /*****************************************************************************
424  * GetMacAddress: extract the MAC Address
425  *****************************************************************************/
426 static int GetMacAddress( int i_socket, char *psz_mac )
427 {
428 #if defined( SYS_LINUX )
429     struct ifreq interface;
430     int i_ret;
431
432     /*
433      * Looking for information about the eth0 interface
434      */
435     interface.ifr_addr.sa_family = AF_INET;
436     strcpy( interface.ifr_name, INPUT_IFACE_DEFAULT );
437
438     i_ret = ioctl( i_socket, SIOCGIFHWADDR, &interface );
439
440     if( i_ret )
441     {
442         intf_ErrMsg( "network error: ioctl SIOCGIFHWADDR failed" );
443         return( i_ret );
444     }
445
446     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
447                       interface.ifr_hwaddr.sa_data[0] & 0xff,
448                       interface.ifr_hwaddr.sa_data[1] & 0xff,
449                       interface.ifr_hwaddr.sa_data[2] & 0xff,
450                       interface.ifr_hwaddr.sa_data[3] & 0xff,
451                       interface.ifr_hwaddr.sa_data[4] & 0xff,
452                       interface.ifr_hwaddr.sa_data[5] & 0xff );
453
454     return( 0 );
455
456 #elif defined( WIN32 )
457     int i, i_ret = -1;
458
459     /* Get adapter list - support for more than one adapter */
460     LANA_ENUM AdapterList;
461     NCB       Ncb;
462
463     intf_WarnMsg( 2, "network: looking for MAC address" );
464
465     memset( &Ncb, 0, sizeof( NCB ) );
466     Ncb.ncb_command = NCBENUM;
467     Ncb.ncb_buffer = (unsigned char *)&AdapterList;
468     Ncb.ncb_length = sizeof( AdapterList );
469     Netbios( &Ncb );
470
471     /* Get all of the local ethernet addresses */
472     for ( i = 0; i < AdapterList.length ; ++i )
473     {
474         if ( GetAdapterInfo ( AdapterList.lana[ i ], psz_mac ) == 0 )
475         {
476             i_ret = 0;
477         }
478     }
479
480     return( i_ret );
481
482 #else
483     return( -1);
484
485 #endif
486 }
487
488 #ifdef WIN32
489 /*****************************************************************************
490  * GetAdapterInfo : gets some informations about the interface using NETBIOS
491  *****************************************************************************/
492 static int GetAdapterInfo( int i_adapter, char *psz_string )
493 {
494     struct ASTAT
495     {
496         ADAPTER_STATUS adapt;
497         NAME_BUFFER    psz_name[30];
498     } Adapter;
499
500     /* Reset the LAN adapter so that we can begin querying it */
501     NCB Ncb;
502     memset( &Ncb, 0, sizeof ( Ncb ) );
503     Ncb.ncb_command  = NCBRESET;
504     Ncb.ncb_lana_num = i_adapter;
505
506     if( Netbios( &Ncb ) != NRC_GOODRET )
507     {
508         intf_ErrMsg( "network error: reset returned %i", Ncb.ncb_retcode );
509         return -1;
510     }
511
512     /* Prepare to get the adapter status block */
513     memset( &Ncb, 0, sizeof( Ncb ) ) ;     /* Initialization */
514     Ncb.ncb_command = NCBASTAT;
515     Ncb.ncb_lana_num = i_adapter;
516
517     strcpy( (char *)Ncb.ncb_callname, "*" );
518
519     memset( &Adapter, 0, sizeof ( Adapter ) );
520     Ncb.ncb_buffer = ( unsigned char * ) &Adapter;
521     Ncb.ncb_length = sizeof ( Adapter );
522
523     /* Get the adapter's info and, if this works, return it in standard,
524      * colon-delimited form. */
525     if ( Netbios( &Ncb ) == 0 )
526     {
527         sprintf ( psz_string, "%02X:%02X:%02X:%02X:%02X:%02X",
528                 (int) ( Adapter.adapt.adapter_address[0] ),
529                 (int) ( Adapter.adapt.adapter_address[1] ),
530                 (int) ( Adapter.adapt.adapter_address[2] ),
531                 (int) ( Adapter.adapt.adapter_address[3] ),
532                 (int) ( Adapter.adapt.adapter_address[4] ),
533                 (int) ( Adapter.adapt.adapter_address[5] ) );
534
535         intf_WarnMsg( 2, "network: found MAC address %s", psz_string );
536
537         return 0;
538     }
539     else
540     {
541         intf_ErrMsg( "network error: ASTAT returned %i", Ncb.ncb_retcode );
542         return -1;
543     }
544 }
545 #endif /* WIN32 */
546