]> git.sesse.net Git - vlc/blob - src/misc/netutils.c
./src/misc/netutils.c: GetMacAddress Darwin support
[vlc] / src / misc / netutils.c
1 /*****************************************************************************
2  * netutils.c: various network functions
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VideoLAN
5  * $Id: netutils.c,v 1.74 2002/10/05 19:26:23 jlj 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@alarue.net>
11  *          Christophe Massiot <massiot@via.ecp.fr>
12  *          Samuel Hocevar <sam@via.ecp.fr>
13  *          Jon Lech Johansen <jon-vl@nanocrew.net>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #include <stdlib.h>                             /* free(), realloc(), atoi() */
34 #include <errno.h>                                                /* errno() */
35 #include <string.h>                                              /* memset() */
36
37 #include <vlc/vlc.h>
38
39 #ifdef HAVE_UNISTD_H
40 #   include <unistd.h>                                      /* gethostname() */
41 #elif defined( _MSC_VER ) && defined( _WIN32 )
42 #   include <io.h>
43 #endif
44
45 #if !defined( _MSC_VER )
46 #include <sys/time.h>                                        /* gettimeofday */
47 #endif
48
49 #ifdef WIN32
50 #   include <winsock2.h>
51 #else
52 #   include <netdb.h>                                         /* hostent ... */
53 #   include <sys/socket.h>                           /* BSD: struct sockaddr */
54 #   include <netinet/in.h>                            /* BSD: struct in_addr */
55 #   ifdef HAVE_ARPA_INET_H
56 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
57 #   endif
58 #endif
59
60 #ifdef SYS_LINUX
61 #include <sys/ioctl.h>                                            /* ioctl() */
62 #endif
63
64 #ifdef SYS_DARWIN
65 #include <IOKit/IOKitLib.h>
66 #include <IOKit/network/IOEthernetInterface.h>
67 #include <IOKit/network/IOEthernetController.h>
68 #endif
69
70 #if defined( WIN32 )                    /* tools to get the MAC adress from  */
71 #include <windows.h>                    /* the interface under Windows       */
72 #include <stdio.h>
73 #include <nb30.h>
74 #endif
75
76 #ifdef HAVE_NET_IF_H
77 #include <net/if.h>                            /* interface (arch-dependent) */
78 #endif
79
80 #ifdef HAVE_SYS_SOCKIO_H
81 #include <sys/sockio.h>
82 #endif
83
84 #include "netutils.h"
85 #include "vlc_playlist.h"
86
87 #include "network.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 struct input_channel_t
98 {
99     int         i_channel;                         /* current channel number */
100     mtime_t     last_change;                             /* last change date */
101 };
102
103 /*****************************************************************************
104  * Local prototypes
105  *****************************************************************************/
106 static int GetMacAddress   ( vlc_object_t *, int i_fd, char *psz_mac );
107 #ifdef SYS_DARWIN
108 static int GetNetIntfCtrl  ( const char *psz_interface, 
109                              io_object_t *ctrl_service );
110 #elif defined( WIN32 )
111 static int GetAdapterInfo  ( int i_adapter, char *psz_string );
112 #endif
113
114 /*****************************************************************************
115  * network_ChannelCreate: initialize global channel method data
116  *****************************************************************************
117  * Initialize channel input method global data. This function should be called
118  * once before any input thread is created or any call to other
119  * input_Channel*() function is attempted.
120  *****************************************************************************/
121 int __network_ChannelCreate( vlc_object_t *p_this )
122 {
123 #if !defined( SYS_LINUX ) && !defined( WIN32 )
124     msg_Err( p_this, "VLAN-based channels are not supported "
125                      "on this architecture" );
126 #endif
127
128     /* Allocate structure */
129     p_this->p_vlc->p_channel = malloc( sizeof( input_channel_t ) );
130     if( p_this->p_vlc->p_channel == NULL )
131     {
132         msg_Err( p_this, "out of memory" );
133         return( -1 );
134     }
135
136     /* Initialize structure */
137     p_this->p_vlc->p_channel->i_channel   = 0;
138     p_this->p_vlc->p_channel->last_change = 0;
139
140     msg_Dbg( p_this, "channels initialized" );
141     return( 0 );
142 }
143
144 /*****************************************************************************
145  * network_ChannelJoin: join a channel
146  *****************************************************************************
147  * This function will try to join a channel. If the relevant interface is
148  * already on the good channel, nothing will be done. Else, and if possible
149  * (if the interface is not locked), the channel server will be contacted
150  * and a change will be requested. The function will block until the change
151  * is effective. Note that once a channel is no more used, its interface
152  * should be unlocked using input_ChannelLeave().
153  * Non 0 will be returned in case of error.
154  *****************************************************************************/
155 int __network_ChannelJoin( vlc_object_t *p_this, int i_channel )
156 {
157 #define VLCS_VERSION 13
158 #define MESSAGE_LENGTH 256
159
160     module_t *       p_network;
161     char *           psz_network = NULL;
162     network_socket_t socket_desc;
163     char psz_mess[ MESSAGE_LENGTH ];
164     char psz_mac[ 40 ];
165     int i_fd, i_port;
166     char *psz_vlcs;
167     struct timeval delay;
168     fd_set fds;
169
170     if( p_this->p_vlc->p_channel->i_channel == i_channel )
171     {
172         return 0;
173     }
174
175     if( !config_GetInt( p_this, "network-channel" ) )
176     {
177         msg_Err( p_this, "channels disabled, to enable them, use the"
178                          " --channels option" );
179         return -1;
180     }
181
182     if( config_GetInt( p_this, "ipv4" ) )
183     {
184         psz_network = "ipv4";
185     }
186     if( config_GetInt( p_this, "ipv6" ) )
187     {
188         psz_network = "ipv6";
189     }
190
191     /* Getting information about the channel server */
192     if( !(psz_vlcs = config_GetPsz( p_this, "channel-server" )) )
193     {
194         msg_Err( p_this, "configuration variable channel-server empty" );
195         return -1;
196     }
197
198     i_port = config_GetInt( p_this, "channel-port" );
199
200     msg_Dbg( p_this, "connecting to %s:%d", psz_vlcs, i_port );
201
202     /* Prepare the network_socket_t structure */
203     socket_desc.i_type = NETWORK_UDP;
204     socket_desc.psz_bind_addr = "";
205     socket_desc.i_bind_port = 4321;
206     socket_desc.psz_server_addr = psz_vlcs;
207     socket_desc.i_server_port = i_port;
208
209     /* Find an appropriate network module */
210     p_network = module_Need( p_this, "network", psz_network/*, &socket_desc*/ );
211     if( p_network == NULL )
212     {
213         return( -1 );
214     }
215     module_Unneed( p_this, p_network );
216
217     free( psz_vlcs ); /* Do we really need this ? -- Meuuh */
218     i_fd = socket_desc.i_handle;
219
220     /* Look for the interface MAC address */
221     if( GetMacAddress( p_this, i_fd, psz_mac ) )
222     {
223         msg_Err( p_this, "failed getting MAC address" );
224         close( i_fd );
225         return -1;
226     }
227
228     msg_Dbg( p_this, "MAC address is %s", psz_mac );
229
230     /* Build the message */
231     sprintf( psz_mess, "%d %u %lu %s \n", i_channel, VLCS_VERSION,
232                        (unsigned long)(mdate() / (u64)1000000),
233                        psz_mac );
234
235     /* Send the message */
236     send( i_fd, psz_mess, MESSAGE_LENGTH, 0 );
237
238     msg_Dbg( p_this, "attempting to join channel %d", i_channel );
239
240     /* We have changed channels ! (or at least, we tried) */
241     p_this->p_vlc->p_channel->last_change = mdate();
242     p_this->p_vlc->p_channel->i_channel = i_channel;
243
244     /* Wait 5 sec for an answer from the server */
245     delay.tv_sec = 5;
246     delay.tv_usec = 0;
247     FD_ZERO( &fds );
248     FD_SET( i_fd, &fds );
249
250     switch( select( i_fd + 1, &fds, NULL, NULL, &delay ) )
251     {
252         case 0:
253             msg_Err( p_this, "no answer from vlcs" );
254             close( i_fd );
255             return -1;
256
257         case -1:
258             msg_Err( p_this, "error while listening to vlcs" );
259             close( i_fd );
260             return -1;
261     }
262
263     recv( i_fd, psz_mess, MESSAGE_LENGTH, 0 );
264     psz_mess[ MESSAGE_LENGTH - 1 ] = '\0';
265
266     if( !strncasecmp( psz_mess, "E:", 2 ) )
267     {
268         msg_Err( p_this, "vlcs said '%s'", psz_mess + 2 );
269         close( i_fd );
270         return -1;
271     }
272     else if( !strncasecmp( psz_mess, "I:", 2 ) )
273     {
274         msg_Dbg( p_this, "vlcs said '%s'", psz_mess + 2 );
275     }
276     else
277     {
278         /* We got something to play ! */
279         playlist_t *p_playlist;
280         p_playlist = vlc_object_find( p_this, VLC_OBJECT_PLAYLIST,
281                                               FIND_ANYWHERE );
282         if( p_playlist != NULL )
283         {
284             playlist_Add( p_playlist, psz_mess,
285                           PLAYLIST_APPEND | PLAYLIST_GO, PLAYLIST_END );
286             vlc_object_release( p_playlist );
287         }
288     }
289
290     /* Close the socket and return nicely */
291 #ifndef WIN32
292     close( i_fd );
293 #else
294     closesocket( i_fd );
295 #endif
296
297     return 0;
298 }
299
300 /* Following functions are local */
301
302 /*****************************************************************************
303  * GetMacAddress: extract the MAC Address
304  *****************************************************************************/
305 static int GetMacAddress( vlc_object_t *p_this, int i_fd, char *psz_mac )
306 {
307 #if defined( SYS_LINUX )
308     struct ifreq interface;
309     int i_ret;
310     char *psz_interface;
311
312     /*
313      * Looking for information about the eth0 interface
314      */
315     interface.ifr_addr.sa_family = AF_INET;
316     if( !(psz_interface = config_GetPsz( p_this, "iface" )) )
317     {
318         msg_Err( p_this, "configuration variable iface empty" );
319         return -1;
320     }
321     strcpy( interface.ifr_name, psz_interface );
322     free( psz_interface );
323
324     i_ret = ioctl( i_fd, SIOCGIFHWADDR, &interface );
325
326     if( i_ret )
327     {
328         msg_Err( p_this, "ioctl SIOCGIFHWADDR failed" );
329         return( i_ret );
330     }
331
332     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
333                       interface.ifr_hwaddr.sa_data[0] & 0xff,
334                       interface.ifr_hwaddr.sa_data[1] & 0xff,
335                       interface.ifr_hwaddr.sa_data[2] & 0xff,
336                       interface.ifr_hwaddr.sa_data[3] & 0xff,
337                       interface.ifr_hwaddr.sa_data[4] & 0xff,
338                       interface.ifr_hwaddr.sa_data[5] & 0xff );
339
340     return( 0 );
341
342 #elif defined( SYS_DARWIN )
343     char *psz_interface;
344     io_object_t ctrl_service;
345     CFTypeRef cfd_mac_address;
346     UInt8 ui_mac_address[kIOEthernetAddressSize];
347
348     if( !(psz_interface = config_GetPsz( p_this, "iface" )) )
349     {
350         msg_Err( p_this, "configuration variable iface empty" );
351         return( -1 );
352     }
353
354     if( GetNetIntfCtrl( psz_interface, &ctrl_service ) )
355     {
356         msg_Err( p_this, "GetNetIntfCtrl failed" );
357         return( -1 );
358     }
359
360     cfd_mac_address = IORegistryEntryCreateCFProperty( ctrl_service,
361                                                        CFSTR(kIOMACAddress),
362                                                        kCFAllocatorDefault,
363                                                        0 ); 
364     IOObjectRelease( ctrl_service );
365     if( cfd_mac_address == NULL )
366     {
367         msg_Err( p_this, "IORegistryEntryCreateCFProperty failed" );
368         return( -1 );
369     }
370
371     CFDataGetBytes( cfd_mac_address, 
372                     CFRangeMake(0, kIOEthernetAddressSize), 
373                     ui_mac_address );
374     CFRelease( cfd_mac_address );
375
376     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
377                       ui_mac_address[0], ui_mac_address[1],
378                       ui_mac_address[2], ui_mac_address[3],
379                       ui_mac_address[4], ui_mac_address[5] ); 
380
381     return( 0 );
382
383 #elif defined( WIN32 )
384     int i, i_ret = -1;
385
386     /* Get adapter list - support for more than one adapter */
387     LANA_ENUM AdapterList;
388     NCB       Ncb;
389
390     msg_Dbg( p_this, "looking for MAC address" );
391
392     memset( &Ncb, 0, sizeof( NCB ) );
393     Ncb.ncb_command = NCBENUM;
394     Ncb.ncb_buffer = (unsigned char *)&AdapterList;
395     Ncb.ncb_length = sizeof( AdapterList );
396     Netbios( &Ncb );
397
398     /* Get all of the local ethernet addresses */
399     for ( i = 0; i < AdapterList.length ; ++i )
400     {
401         if ( GetAdapterInfo ( AdapterList.lana[ i ], psz_mac ) == 0 )
402         {
403             i_ret = 0;
404         }
405     }
406
407     return( i_ret );
408
409 #else
410     strcpy( psz_mac, "00:00:00:00:00:00" );
411     return( 0 );
412
413 #endif
414 }
415
416 #ifdef SYS_DARWIN
417 /*****************************************************************************
418  * GetNetIntfCtrl : get parent controller for network interface 
419  *****************************************************************************/
420 static int GetNetIntfCtrl( const char *psz_interface,
421                            io_object_t *ctrl_service )
422 {
423     mach_port_t port;
424     kern_return_t ret;
425     io_object_t intf_service;
426     io_iterator_t intf_iterator;
427
428     /* get port for IOKit communication */
429     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
430     {
431         return( -1 );
432     }
433
434     /* look up the IOService object for the interface */
435     ret = IOServiceGetMatchingServices( port, IOBSDNameMatching( port, 0, 
436                                         psz_interface ), &intf_iterator ); 
437     if( ret != KERN_SUCCESS )
438     {
439         return( -1 );
440     }
441
442     intf_service = IOIteratorNext( intf_iterator );
443     if( intf_service == NULL )
444     {
445         return( -1 );
446     }
447
448     ret = IORegistryEntryGetParentEntry( intf_service,
449                                          kIOServicePlane,
450                                          ctrl_service );
451     IOObjectRelease( intf_service );
452     if( ret != KERN_SUCCESS )
453     {
454         return( -1 );
455     }
456
457     return( 0 );
458 }
459
460 #elif defined( WIN32 )
461 /*****************************************************************************
462  * GetAdapterInfo : gets some informations about the interface using NETBIOS
463  *****************************************************************************/
464 static int GetAdapterInfo( int i_adapter, char *psz_string )
465 {
466     struct ASTAT
467     {
468         ADAPTER_STATUS adapt;
469         NAME_BUFFER    psz_name[30];
470     } Adapter;
471
472     /* Reset the LAN adapter so that we can begin querying it */
473     NCB Ncb;
474     memset( &Ncb, 0, sizeof ( Ncb ) );
475     Ncb.ncb_command  = NCBRESET;
476     Ncb.ncb_lana_num = i_adapter;
477
478     if( Netbios( &Ncb ) != NRC_GOODRET )
479     {
480 //X        intf_ErrMsg( "network error: reset returned %i", Ncb.ncb_retcode );
481         return -1;
482     }
483
484     /* Prepare to get the adapter status block */
485     memset( &Ncb, 0, sizeof( Ncb ) ) ;     /* Initialization */
486     Ncb.ncb_command = NCBASTAT;
487     Ncb.ncb_lana_num = i_adapter;
488
489     strcpy( (char *)Ncb.ncb_callname, "*" );
490
491     memset( &Adapter, 0, sizeof ( Adapter ) );
492     Ncb.ncb_buffer = ( unsigned char * ) &Adapter;
493     Ncb.ncb_length = sizeof ( Adapter );
494
495     /* Get the adapter's info and, if this works, return it in standard,
496      * colon-delimited form. */
497     if ( Netbios( &Ncb ) == 0 )
498     {
499         sprintf ( psz_string, "%02X:%02X:%02X:%02X:%02X:%02X",
500                 (int) ( Adapter.adapt.adapter_address[0] ),
501                 (int) ( Adapter.adapt.adapter_address[1] ),
502                 (int) ( Adapter.adapt.adapter_address[2] ),
503                 (int) ( Adapter.adapt.adapter_address[3] ),
504                 (int) ( Adapter.adapt.adapter_address[4] ),
505                 (int) ( Adapter.adapt.adapter_address[5] ) );
506
507 //X        intf_WarnMsg( 2, "network: found MAC address %s", psz_string );
508
509         return 0;
510     }
511     else
512     {
513 //X        intf_ErrMsg( "network error: ASTAT returned %i", Ncb.ncb_retcode );
514         return -1;
515     }
516 }
517 #endif /* WIN32 */
518