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