]> git.sesse.net Git - vlc/blob - src/misc/netutils.c
* Added error checking in pthread wrapper ; as a result, intf_msg.h must
[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.52 2001/11/28 15:08:06 massiot 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  *          Christophe Massiot <massiot@via.ecp.fr>
12  *          Samuel Hocevar <sam@via.ecp.fr>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
27  *****************************************************************************/
28
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32 #include "defs.h"
33
34 #include <stdlib.h>                             /* free(), realloc(), atoi() */
35 #include <errno.h>                                                /* errno() */
36 #include <string.h>                                              /* memset() */
37
38 #ifdef STRNCASECMP_IN_STRINGS_H
39 #   include <strings.h>
40 #endif
41
42 #ifdef HAVE_UNISTD_H
43 #   include <unistd.h>                                      /* gethostname() */
44 #elif defined( _MSC_VER ) && defined( _WIN32 )
45 #   include <io.h>
46 #endif
47
48 #if !defined( _MSC_VER )
49 #include <sys/time.h>                                        /* gettimeofday */
50 #endif
51
52 #ifdef WIN32
53 #   include <winsock2.h>
54 #elif !defined( SYS_BEOS ) && !defined( SYS_NTO )
55 #   include <netdb.h>                                         /* hostent ... */
56 #   include <sys/socket.h>                           /* BSD: struct sockaddr */
57 #   include <netinet/in.h>                            /* BSD: struct in_addr */
58 #   ifdef HAVE_ARPA_INET_H
59 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
60 #   endif
61 #endif
62
63 #ifdef SYS_LINUX
64 #include <sys/ioctl.h>                                            /* ioctl() */
65 #endif
66
67 #if defined( WIN32 )                    /* tools to get the MAC adress from  */
68 #include <windows.h>                    /* the interface under Windows       */
69 #include <stdio.h>
70 #endif
71
72 #ifdef HAVE_NET_IF_H
73 #include <net/if.h>                            /* interface (arch-dependent) */
74 #endif
75
76 #ifdef HAVE_SYS_SOCKIO_H
77 #include <sys/sockio.h>
78 #endif
79
80 #include "config.h"
81 #include "common.h"
82 #include "mtime.h"
83 #include "intf_msg.h"
84 #include "threads.h"
85 #include "main.h"
86
87 #include "intf_playlist.h"
88
89 #include "netutils.h"
90
91 /*****************************************************************************
92  * input_channel_t: channel library data
93  *****************************************************************************
94  * Store global channel library data.
95  * The part of the code concerning the channel changing process is unstable
96  * as it depends on the VideoLAN channel server, which isn't frozen for
97  * the time being.
98  *****************************************************************************/
99 typedef struct input_channel_s
100 {
101     int         i_channel;                         /* current channel number */
102     mtime_t     last_change;                             /* last change date */
103 } input_channel_t;
104
105 /*****************************************************************************
106  * Local prototypes
107  *****************************************************************************/
108 static int GetMacAddress   ( int i_fd, char *psz_mac );
109 #ifdef WIN32
110 static int GetAdapterInfo  ( int i_adapter, char *psz_string );
111 #endif
112
113 /*****************************************************************************
114  * network_BuildAddr : fill a sockaddr_in structure
115  *****************************************************************************/
116 int network_BuildAddr( struct sockaddr_in * p_socket,
117                        char * psz_address, int i_port )
118 {
119 #if defined( SYS_BEOS )
120     intf_ErrMsg( "error: networking is not yet supported under BeOS" );
121     return( 1 );
122
123 #else
124     /* Reset struct */
125     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
126     p_socket->sin_family = AF_INET;                                /* family */
127     p_socket->sin_port = htons( i_port );
128     if( psz_address == NULL )
129     {
130         p_socket->sin_addr.s_addr = INADDR_ANY;
131     }
132     else
133     {
134         struct hostent    * p_hostent;
135
136         /* Try to convert address directly from in_addr - this will work if
137          * psz_broadcast is dotted decimal. */
138 #ifdef HAVE_ARPA_INET_H
139         if( !inet_aton( psz_address, &p_socket->sin_addr) )
140 #else
141         if( (p_socket->sin_addr.s_addr = inet_addr( psz_address )) == -1 )
142 #endif
143         {
144             /* We have a fqdn, try to find its address */
145             if ( (p_hostent = gethostbyname( psz_address )) == NULL )
146             {
147                 intf_ErrMsg( "BuildLocalAddr: unknown host %s", psz_address );
148                 return( -1 );
149             }
150
151             /* Copy the first address of the host in the socket address */
152             memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
153                      p_hostent->h_length );
154         }
155     }
156     return( 0 );
157 #endif
158 }
159
160 /*****************************************************************************
161  * network_ChannelCreate: initialize global channel method data
162  *****************************************************************************
163  * Initialize channel input method global data. This function should be called
164  * once before any input thread is created or any call to other
165  * input_Channel*() function is attempted.
166  *****************************************************************************/
167 int network_ChannelCreate( void )
168 {
169 #if defined( SYS_LINUX ) || defined( WIN32 )
170
171     /* Allocate structure */
172     p_main->p_channel = malloc( sizeof( input_channel_t ) );
173     if( p_main->p_channel == NULL )
174     {
175         intf_ErrMsg( "network error: could not create channel bank" );
176         return( -1 );
177     }
178
179     /* Initialize structure */
180     p_main->p_channel->i_channel   = 0;
181     p_main->p_channel->last_change = 0;
182
183     intf_WarnMsg( 2, "network: channels initialized" );
184     return( 0 );
185
186 #else
187     intf_ErrMsg( "network error : channels not supported on this platform" );
188     return( 1 );
189
190 #endif
191 }
192
193 /*****************************************************************************
194  * network_ChannelJoin: join a channel
195  *****************************************************************************
196  * This function will try to join a channel. If the relevant interface is
197  * already on the good channel, nothing will be done. Else, and if possible
198  * (if the interface is not locked), the channel server will be contacted
199  * and a change will be requested. The function will block until the change
200  * is effective. Note that once a channel is no more used, its interface
201  * should be unlocked using input_ChannelLeave().
202  * Non 0 will be returned in case of error.
203  *****************************************************************************/
204 int network_ChannelJoin( int i_channel )
205 {
206 #if defined( SYS_LINUX ) || defined( WIN32 )
207
208 #define VLCS_VERSION 13
209 #define MESSAGE_LENGTH 256
210
211     char psz_mess[ MESSAGE_LENGTH ];
212     char psz_mac[ 40 ];
213     int i_fd, i_dummy, i_port;
214     char *psz_vlcs;
215     struct sockaddr_in sa_server;
216     struct sockaddr_in sa_client;
217     struct timeval delay;
218     fd_set fds;
219
220     if( !main_GetIntVariable( INPUT_NETWORK_CHANNEL_VAR,
221                               INPUT_NETWORK_CHANNEL_DEFAULT  ) )
222     {
223         intf_ErrMsg( "network: channels disabled, to enable them, use the"
224                      "--channels option" );
225         return -1;
226     }
227
228     /* If last change is too recent, wait a while */
229     if( mdate() - p_main->p_channel->last_change < INPUT_CHANNEL_CHANGE_DELAY )
230     {
231         intf_WarnMsg( 2, "network: waiting before changing channel" );
232         /* XXX Isn't this completely brain-damaged ??? -- Sam */
233         mwait( p_main->p_channel->last_change + INPUT_CHANNEL_CHANGE_DELAY );
234     }
235
236     /* Initializing the socket */
237     i_fd = socket( AF_INET, SOCK_DGRAM, 0 );
238     if( i_fd < 0 )
239     {
240         intf_ErrMsg( "network error: unable to create vlcs socket (%s)",
241                      strerror( errno ) );
242         return -1;
243     }
244
245     i_dummy = 1;
246     if( setsockopt( i_fd, SOL_SOCKET, SO_REUSEADDR,
247                     (void *) &i_dummy, sizeof( i_dummy ) ) == -1 )
248     {
249         intf_ErrMsg( "network error: can't SO_REUSEADDR vlcs socket (%s)",
250                      strerror(errno));
251         close( i_fd );
252         return -1;
253     }
254
255     /* Getting information about the channel server */
256     psz_vlcs = main_GetPszVariable( INPUT_CHANNEL_SERVER_VAR,
257                                     INPUT_CHANNEL_SERVER_DEFAULT );
258     i_port = main_GetIntVariable( INPUT_CHANNEL_PORT_VAR,
259                                   INPUT_CHANNEL_PORT_DEFAULT );
260
261     intf_WarnMsg( 5, "network: socket %i, vlcs '%s', port %d",
262                      i_fd, psz_vlcs, i_port );
263
264     memset( &sa_client, 0x00, sizeof(struct sockaddr_in) );
265     memset( &sa_server, 0x00, sizeof(struct sockaddr_in) );
266     sa_client.sin_family      = AF_INET;
267     sa_server.sin_family      = AF_INET;
268     sa_client.sin_port        = htons( 4312 );
269     sa_server.sin_port        = htons( i_port );
270     sa_client.sin_addr.s_addr = INADDR_ANY;
271 #ifdef HAVE_ARPA_INET_H
272     inet_aton( psz_vlcs, &sa_server.sin_addr );
273 #else
274     sa_server.sin_addr.s_addr = inet_addr( psz_vlcs );
275 #endif
276
277     /* Bind the socket */
278     if( bind( i_fd, (struct sockaddr*)(&sa_client), sizeof(sa_client) ) )
279     {
280         intf_ErrMsg( "network: unable to bind vlcs socket (%s)",
281                      strerror( errno ) );
282         close( i_fd );
283         return -1;
284     }
285
286     /* Look for the interface MAC address */
287     if( GetMacAddress( i_fd, psz_mac ) )
288     {
289         intf_ErrMsg( "network error: failed getting MAC address" );
290         close( i_fd );
291         return -1;
292     }
293
294     intf_WarnMsg( 6, "network: MAC address is %s", psz_mac );
295
296     /* Build the message */
297     sprintf( psz_mess, "%d %u %lu %s \n", i_channel, VLCS_VERSION,
298                        (unsigned long)(mdate() / (u64)1000000),
299                        psz_mac );
300
301     /* Send the message */
302     sendto( i_fd, psz_mess, MESSAGE_LENGTH, 0,
303             (struct sockaddr *)(&sa_server), sizeof(struct sockaddr) );
304
305     intf_WarnMsg( 2, "network: attempting to join channel %d", i_channel );
306
307     /* We have changed channels ! (or at least, we tried) */
308     p_main->p_channel->last_change = mdate();
309     p_main->p_channel->i_channel = i_channel;
310
311     /* Wait 5 sec for an answer from the server */
312     delay.tv_sec = 5;
313     delay.tv_usec = 0;
314     FD_ZERO( &fds );
315     FD_SET( i_fd, &fds );
316
317     switch( select( i_fd + 1, &fds, NULL, NULL, &delay ) )
318     {
319         case 0:
320             intf_ErrMsg( "network error: no answer from vlcs" );
321             close( i_fd );
322             return -1;
323             break;
324
325         case -1:
326             intf_ErrMsg( "network error: error while listening to vlcs" );
327             close( i_fd );
328             return -1;
329             break;
330     }
331
332     i_dummy = sizeof( struct sockaddr );
333     recvfrom( i_fd, psz_mess, MESSAGE_LENGTH, 0,
334               (struct sockaddr *)(&sa_client), &i_dummy);
335     psz_mess[ MESSAGE_LENGTH - 1 ] = 0;
336
337     if( !strncasecmp( psz_mess, "E: ", 3 ) )
338     {
339         intf_ErrMsg( "network error: vlcs said '%s'", psz_mess + 3 );
340         close( i_fd );
341         return -1;
342     }
343     else if( !strncasecmp( psz_mess, "I: ", 3 ) )
344     {
345         intf_WarnMsg( 2, "network info: vlcs said '%s'", psz_mess + 3 );
346     }
347     else /* We got something to play ! FIXME: not very nice */
348     {
349 #   define p_item \
350         (&p_main->p_playlist->p_item[ p_main->p_playlist->i_index + 1])
351         vlc_mutex_lock( &p_main->p_playlist->change_lock );
352         if( p_item )
353         {
354             free( p_item->psz_name );
355             p_item->psz_name = strdup( psz_mess );
356             /* Unlock _afterwards_ */
357             vlc_mutex_unlock( &p_main->p_playlist->change_lock );
358         }
359         else
360         {
361             /* Unlock _before_ */
362             vlc_mutex_unlock( &p_main->p_playlist->change_lock );
363             intf_PlaylistAdd( p_main->p_playlist, 0, psz_mess );
364         }
365     }
366
367     /* Close the socket and return nicely */
368     close( i_fd );
369
370     return 0;
371
372 #else
373     intf_ErrMsg( "network error: channels not supported on this platform" );
374     return -1; 
375
376 #endif
377 }
378
379 /* Following functions are local */
380
381 /*****************************************************************************
382  * GetMacAddress: extract the MAC Address
383  *****************************************************************************/
384 static int GetMacAddress( int i_fd, char *psz_mac )
385 {
386 #if defined( SYS_LINUX )
387     struct ifreq interface;
388     int i_ret;
389
390     /*
391      * Looking for information about the eth0 interface
392      */
393     interface.ifr_addr.sa_family = AF_INET;
394     strcpy( interface.ifr_name, 
395             main_GetPszVariable( INPUT_IFACE_VAR, INPUT_IFACE_DEFAULT ) );
396
397     i_ret = ioctl( i_fd, SIOCGIFHWADDR, &interface );
398
399     if( i_ret )
400     {
401         intf_ErrMsg( "network error: ioctl SIOCGIFHWADDR failed" );
402         return( i_ret );
403     }
404
405     sprintf( psz_mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
406                       interface.ifr_hwaddr.sa_data[0] & 0xff,
407                       interface.ifr_hwaddr.sa_data[1] & 0xff,
408                       interface.ifr_hwaddr.sa_data[2] & 0xff,
409                       interface.ifr_hwaddr.sa_data[3] & 0xff,
410                       interface.ifr_hwaddr.sa_data[4] & 0xff,
411                       interface.ifr_hwaddr.sa_data[5] & 0xff );
412
413     return( 0 );
414
415 #elif defined( WIN32 )
416     int i, i_ret = -1;
417
418     /* Get adapter list - support for more than one adapter */
419     LANA_ENUM AdapterList;
420     NCB       Ncb;
421
422     intf_WarnMsg( 2, "network: looking for MAC address" );
423
424     memset( &Ncb, 0, sizeof( NCB ) );
425     Ncb.ncb_command = NCBENUM;
426     Ncb.ncb_buffer = (unsigned char *)&AdapterList;
427     Ncb.ncb_length = sizeof( AdapterList );
428     Netbios( &Ncb );
429
430     /* Get all of the local ethernet addresses */
431     for ( i = 0; i < AdapterList.length ; ++i )
432     {
433         if ( GetAdapterInfo ( AdapterList.lana[ i ], psz_mac ) == 0 )
434         {
435             i_ret = 0;
436         }
437     }
438
439     return( i_ret );
440
441 #else
442     return( -1);
443
444 #endif
445 }
446
447 #ifdef WIN32
448 /*****************************************************************************
449  * GetAdapterInfo : gets some informations about the interface using NETBIOS
450  *****************************************************************************/
451 static int GetAdapterInfo( int i_adapter, char *psz_string )
452 {
453     struct ASTAT
454     {
455         ADAPTER_STATUS adapt;
456         NAME_BUFFER    psz_name[30];
457     } Adapter;
458
459     /* Reset the LAN adapter so that we can begin querying it */
460     NCB Ncb;
461     memset( &Ncb, 0, sizeof ( Ncb ) );
462     Ncb.ncb_command  = NCBRESET;
463     Ncb.ncb_lana_num = i_adapter;
464
465     if( Netbios( &Ncb ) != NRC_GOODRET )
466     {
467         intf_ErrMsg( "network error: reset returned %i", Ncb.ncb_retcode );
468         return -1;
469     }
470
471     /* Prepare to get the adapter status block */
472     memset( &Ncb, 0, sizeof( Ncb ) ) ;     /* Initialization */
473     Ncb.ncb_command = NCBASTAT;
474     Ncb.ncb_lana_num = i_adapter;
475
476     strcpy( (char *)Ncb.ncb_callname, "*" );
477
478     memset( &Adapter, 0, sizeof ( Adapter ) );
479     Ncb.ncb_buffer = ( unsigned char * ) &Adapter;
480     Ncb.ncb_length = sizeof ( Adapter );
481
482     /* Get the adapter's info and, if this works, return it in standard,
483      * colon-delimited form. */
484     if ( Netbios( &Ncb ) == 0 )
485     {
486         sprintf ( psz_string, "%02X:%02X:%02X:%02X:%02X:%02X",
487                 (int) ( Adapter.adapt.adapter_address[0] ),
488                 (int) ( Adapter.adapt.adapter_address[1] ),
489                 (int) ( Adapter.adapt.adapter_address[2] ),
490                 (int) ( Adapter.adapt.adapter_address[3] ),
491                 (int) ( Adapter.adapt.adapter_address[4] ),
492                 (int) ( Adapter.adapt.adapter_address[5] ) );
493
494         intf_WarnMsg( 2, "network: found MAC address %s", psz_string );
495
496         return 0;
497     }
498     else
499     {
500         intf_ErrMsg( "network error: ASTAT returned %i", Ncb.ncb_retcode );
501         return -1;
502     }
503 }
504 #endif /* WIN32 */
505