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