]> git.sesse.net Git - vlc/blob - src/network/tcp.c
Factorize socket listen code
[vlc] / src / network / tcp.c
1 /*****************************************************************************
2  * tcp.c:
3  *****************************************************************************
4  * Copyright (C) 2004-2005 the VideoLAN team
5  * Copyright (C) 2005-2006 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@videolan.org>
9  *          Rémi Denis-Courmont <rem # videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdlib.h>
30 #include <vlc/vlc.h>
31
32 #include <errno.h>
33
34 #ifdef HAVE_FCNTL_H
35 #   include <fcntl.h>
36 #endif
37 #ifdef HAVE_SYS_TIME_H
38 #    include <sys/time.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 #   include <unistd.h>
42 #endif
43
44 #include "network.h"
45 #if defined (WIN32) || defined (UNDER_CE)
46 #   undef EINPROGRESS
47 #   define EINPROGRESS WSAEWOULDBLOCK
48 #   undef EINTR
49 #   define EINTR WSAEINTR
50 #   undef ETIMEDOUT
51 #   define ETIMEDOUT WSAETIMEDOUT
52 #endif
53
54 static int SocksNegociate( vlc_object_t *, int fd, int i_socks_version,
55                            char *psz_socks_user, char *psz_socks_passwd );
56 static int SocksHandshakeTCP( vlc_object_t *,
57                               int fd, int i_socks_version,
58                               char *psz_socks_user, char *psz_socks_passwd,
59                               const char *psz_host, int i_port );
60 extern int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
61                        int i_protocol );
62
63 /*****************************************************************************
64  * __net_ConnectTCP:
65  *****************************************************************************
66  * Open a TCP connection and return a handle
67  *****************************************************************************/
68 int __net_ConnectTCP( vlc_object_t *p_this, const char *psz_host, int i_port )
69 {
70     struct addrinfo hints, *res, *ptr;
71     const char      *psz_realhost;
72     char            *psz_socks;
73     int             i_realport, i_val, i_handle = -1, i_saved_errno = 0;
74     unsigned        u_errstep = 0;
75
76     if( i_port == 0 )
77         i_port = 80; /* historical VLC thing */
78
79     memset( &hints, 0, sizeof( hints ) );
80     hints.ai_socktype = SOCK_STREAM;
81
82     psz_socks = var_CreateGetString( p_this, "socks" );
83     if( *psz_socks && *psz_socks != ':' )
84     {
85         char *psz = strchr( psz_socks, ':' );
86
87         if( psz )
88             *psz++ = '\0';
89
90         psz_realhost = psz_socks;
91         i_realport = ( psz != NULL ) ? atoi( psz ) : 1080;
92
93         msg_Dbg( p_this, "net: connecting to %s port %d for %s port %d",
94                  psz_realhost, i_realport, psz_host, i_port );
95     }
96     else
97     {
98         psz_realhost = psz_host;
99         i_realport = i_port;
100
101         msg_Dbg( p_this, "net: connecting to %s port %d", psz_realhost,
102                  i_realport );
103     }
104
105     i_val = vlc_getaddrinfo( p_this, psz_realhost, i_realport, &hints, &res );
106     if( i_val )
107     {
108         msg_Err( p_this, "cannot resolve %s port %d : %s", psz_realhost,
109                  i_realport, vlc_gai_strerror( i_val ) );
110         free( psz_socks );
111         return -1;
112     }
113
114     for( ptr = res; ptr != NULL; ptr = ptr->ai_next )
115     {
116         int fd = net_Socket( p_this, ptr->ai_family, ptr->ai_socktype,
117                              ptr->ai_protocol );
118         if( fd == -1 )
119         {
120             if( u_errstep <= 0 )
121             {
122                 u_errstep = 1;
123                 i_saved_errno = net_errno;
124             }
125             msg_Dbg( p_this, "socket error: %s", strerror( net_errno ) );
126             continue;
127         }
128
129         if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) )
130         {
131             socklen_t i_val_size = sizeof( i_val );
132             div_t d;
133             struct timeval tv;
134             vlc_value_t timeout;
135
136             if( net_errno != EINPROGRESS )
137             {
138                 if( u_errstep <= 1 )
139                 {
140                     u_errstep = 2;
141                     i_saved_errno = net_errno;
142                 }
143                 msg_Dbg( p_this, "connect error: %s", strerror( net_errno ) );
144                 goto next_ai;
145             }
146
147             var_Create( p_this, "ipv4-timeout",
148                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
149             var_Get( p_this, "ipv4-timeout", &timeout );
150             if( timeout.i_int < 0 )
151             {
152                 msg_Err( p_this, "invalid negative value for ipv4-timeout" );
153                 timeout.i_int = 0;
154             }
155             d = div( timeout.i_int, 100 );
156
157             msg_Dbg( p_this, "connection in progress" );
158             for (;;)
159             {
160                 fd_set fds;
161                 int i_ret;
162
163                 if( p_this->b_die )
164                 {
165                     msg_Dbg( p_this, "connection aborted" );
166                     net_Close( fd );
167                     vlc_freeaddrinfo( res );
168                     free( psz_socks );
169                     return -1;
170                 }
171
172                 /* Initialize file descriptor set */
173                 FD_ZERO( &fds );
174                 FD_SET( fd, &fds );
175
176                 /*
177                  * We'll wait 0.1 second if nothing happens
178                  * NOTE:
179                  * time out will be shortened if we catch a signal (EINTR)
180                  */
181                 tv.tv_sec = 0;
182                 tv.tv_usec = (d.quot > 0) ? 100000 : (1000 * d.rem);
183
184                 i_ret = select( fd + 1, NULL, &fds, NULL, &tv );
185                 if( i_ret == 1 )
186                     break;
187
188                 if( ( i_ret == -1 ) && ( net_errno != EINTR ) )
189                 {
190                     msg_Warn( p_this, "select error: %s",
191                               strerror( net_errno ) );
192                     goto next_ai;
193                 }
194
195                 if( d.quot <= 0 )
196                 {
197                     msg_Dbg( p_this, "select timed out" );
198                     if( u_errstep <= 2 )
199                     {
200                         u_errstep = 3;
201                         i_saved_errno = ETIMEDOUT;
202                     }
203                     goto next_ai;
204                 }
205
206                 d.quot--;
207             }
208
209 #if !defined( SYS_BEOS ) && !defined( UNDER_CE )
210             if( getsockopt( fd, SOL_SOCKET, SO_ERROR, (void*)&i_val,
211                             &i_val_size ) == -1 || i_val != 0 )
212             {
213                 u_errstep = 4;
214                 i_saved_errno = i_val;
215                 msg_Dbg( p_this, "connect error (via getsockopt): %s",
216                          net_strerror( i_val ) );
217                 goto next_ai;
218             }
219 #endif
220         }
221
222         i_handle = fd; /* success! */
223         break;
224
225 next_ai: /* failure */
226         net_Close( fd );
227         continue;
228     }
229
230     vlc_freeaddrinfo( res );
231
232     if( i_handle == -1 )
233     {
234         msg_Err( p_this, "Connection to %s port %d failed: %s", psz_host,
235                  i_port, net_strerror( i_saved_errno ) );
236         free( psz_socks );
237         return -1;
238     }
239
240     if( *psz_socks && *psz_socks != ':' )
241     {
242         char *psz_user = var_CreateGetString( p_this, "socks-user" );
243         char *psz_pwd  = var_CreateGetString( p_this, "socks-pwd" );
244
245         if( SocksHandshakeTCP( p_this, i_handle, 5, psz_user, psz_pwd,
246                                psz_host, i_port ) )
247         {
248             msg_Err( p_this, "Failed to use the SOCKS server" );
249             net_Close( i_handle );
250             i_handle = -1;
251         }
252
253         free( psz_user );
254         free( psz_pwd );
255     }
256     free( psz_socks );
257
258     return i_handle;
259 }
260
261
262 /*****************************************************************************
263  * __net_ListenTCP:
264  *****************************************************************************
265  * Open TCP passive "listening" socket(s)
266  * This function returns NULL in case of error.
267  *****************************************************************************/
268 int *__net_ListenTCP (vlc_object_t *p_this, const char *psz_host, int i_port)
269 {
270     return net_Listen (p_this, psz_host, i_port, AF_UNSPEC, SOCK_STREAM,
271                        IPPROTO_TCP);
272 }
273
274 /*****************************************************************************
275  * __net_Accept:
276  *****************************************************************************
277  * Accept a connection on a set of listening sockets and return it
278  *****************************************************************************/
279 int __net_Accept( vlc_object_t *p_this, int *pi_fd, mtime_t i_wait )
280 {
281     vlc_bool_t b_die = p_this->b_die, b_block = (i_wait < 0);
282
283     while( p_this->b_die == b_die )
284     {
285         int i_val = -1, *pi, *pi_end;
286         struct timeval timeout;
287         fd_set fds_r, fds_e;
288
289         pi = pi_fd;
290
291         /* Initialize file descriptor set */
292         FD_ZERO( &fds_r );
293         FD_ZERO( &fds_e );
294
295         for( pi = pi_fd; *pi != -1; pi++ )
296         {
297             int i_fd = *pi;
298
299             if( i_fd > i_val )
300                 i_val = i_fd;
301
302             FD_SET( i_fd, &fds_r );
303             FD_SET( i_fd, &fds_e );
304         }
305         pi_end = pi;
306
307         timeout.tv_sec = 0;
308         timeout.tv_usec = b_block ? 500000 : i_wait;
309
310         i_val = select( i_val + 1, &fds_r, NULL, &fds_e, &timeout );
311         if( ( ( i_val < 0 ) && ( net_errno == EINTR ) ) || i_val == 0 )
312         {
313             if( b_block )
314                 continue;
315             else
316                 return -1;
317         }
318         else if( i_val < 0 )
319         {
320             msg_Err( p_this, "network select error (%s)",
321                      net_strerror( net_errno ) );
322             return -1;
323         }
324
325         for( pi = pi_fd; *pi != -1; pi++ )
326         {
327             int i_fd = *pi;
328
329             if( !FD_ISSET( i_fd, &fds_r ) && !FD_ISSET( i_fd, &fds_e ) )
330                 continue;
331
332             i_val = accept( i_fd, NULL, 0 );
333             if( i_val < 0 )
334                 msg_Err( p_this, "accept failed (%s)",
335                          net_strerror( net_errno ) );
336             else
337             {
338                 const int yes = 1;
339                 setsockopt( i_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( yes ));
340 #ifdef FD_CLOEXEC
341                 fcntl( i_fd, F_SETFD, FD_CLOEXEC );
342 #endif
343                 /*
344                  * This round-robin trick ensures that the first sockets in
345                  * pi_fd won't prevent the last ones from getting accept'ed.
346                  */
347                 --pi_end;
348                 memmove( pi, pi + 1, pi_end - pi );
349                 *pi_end = i_fd;
350                 return i_val;
351             }
352         }
353     }
354
355     return -1;
356 }
357
358
359 /*****************************************************************************
360  * SocksNegociate:
361  *****************************************************************************
362  * Negociate authentication with a SOCKS server.
363  *****************************************************************************/
364 static int SocksNegociate( vlc_object_t *p_obj,
365                            int fd, int i_socks_version,
366                            char *psz_socks_user,
367                            char *psz_socks_passwd )
368 {
369     uint8_t buffer[128+2*256];
370     int i_len;
371     vlc_bool_t b_auth = VLC_FALSE;
372
373     if( i_socks_version != 5 )
374         return VLC_SUCCESS;
375
376     /* We negociate authentication */
377
378     if( psz_socks_user && psz_socks_passwd &&
379         *psz_socks_user && *psz_socks_passwd )
380         b_auth = VLC_TRUE;
381
382     buffer[0] = i_socks_version;    /* SOCKS version */
383     if( b_auth )
384     {
385         buffer[1] = 2;                  /* Number of methods */
386         buffer[2] = 0x00;               /* - No auth required */
387         buffer[3] = 0x02;               /* - USer/Password */
388         i_len = 4;
389     }
390     else
391     {
392         buffer[1] = 1;                  /* Number of methods */
393         buffer[2] = 0x00;               /* - No auth required */
394         i_len = 3;
395     }
396
397     if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
398         return VLC_EGENERIC;
399     if( net_Read( p_obj, fd, NULL, buffer, 2, VLC_TRUE ) != 2 )
400         return VLC_EGENERIC;
401
402     msg_Dbg( p_obj, "socks: v=%d method=%x", buffer[0], buffer[1] );
403
404     if( buffer[1] == 0x00 )
405     {
406         msg_Dbg( p_obj, "socks: no authentication required" );
407     }
408     else if( buffer[1] == 0x02 )
409     {
410         int i_len1 = __MIN( strlen(psz_socks_user), 255 );
411         int i_len2 = __MIN( strlen(psz_socks_passwd), 255 );
412         msg_Dbg( p_obj, "socks: username/password authentication" );
413
414         /* XXX: we don't support user/pwd > 255 (truncated)*/
415         buffer[0] = i_socks_version;        /* Version */
416         buffer[1] = i_len1;                 /* User length */
417         memcpy( &buffer[2], psz_socks_user, i_len1 );
418         buffer[2+i_len1] = i_len2;          /* Password length */
419         memcpy( &buffer[2+i_len1+1], psz_socks_passwd, i_len2 );
420
421         i_len = 3 + i_len1 + i_len2;
422
423         if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
424             return VLC_EGENERIC;
425
426         if( net_Read( p_obj, fd, NULL, buffer, 2, VLC_TRUE ) != 2 )
427             return VLC_EGENERIC;
428
429         msg_Dbg( p_obj, "socks: v=%d status=%x", buffer[0], buffer[1] );
430         if( buffer[1] != 0x00 )
431         {
432             msg_Err( p_obj, "socks: authentication rejected" );
433             return VLC_EGENERIC;
434         }
435     }
436     else
437     {
438         if( b_auth )
439             msg_Err( p_obj, "socks: unsupported authentication method %x",
440                      buffer[0] );
441         else
442             msg_Err( p_obj, "socks: authentification needed" );
443         return VLC_EGENERIC;
444     }
445
446     return VLC_SUCCESS;
447 }
448
449 /*****************************************************************************
450  * SocksHandshakeTCP:
451  *****************************************************************************
452  * Open a TCP connection using a SOCKS server and return a handle (RFC 1928)
453  *****************************************************************************/
454 static int SocksHandshakeTCP( vlc_object_t *p_obj,
455                               int fd,
456                               int i_socks_version,
457                               char *psz_socks_user, char *psz_socks_passwd,
458                               const char *psz_host, int i_port )
459 {
460     uint8_t buffer[128+2*256];
461
462     if( i_socks_version != 4 && i_socks_version != 5 )
463     {
464         msg_Warn( p_obj, "invalid socks protocol version %d", i_socks_version );
465         i_socks_version = 5;
466     }
467
468     if( i_socks_version == 5 && 
469         SocksNegociate( p_obj, fd, i_socks_version,
470                         psz_socks_user, psz_socks_passwd ) )
471         return VLC_EGENERIC;
472
473     if( i_socks_version == 4 )
474     {
475         struct addrinfo hints, *p_res;
476
477         /* v4 only support ipv4 */
478         memset (&hints, 0, sizeof (hints));
479         hints.ai_family = AF_INET;
480         if( vlc_getaddrinfo( p_obj, psz_host, 0, &hints, &p_res ) )
481             return VLC_EGENERIC;
482
483         buffer[0] = i_socks_version;
484         buffer[1] = 0x01;               /* CONNECT */
485         SetWBE( &buffer[2], i_port );   /* Port */
486         memcpy( &buffer[4],             /* Address */
487                 &((struct sockaddr_in *)(p_res->ai_addr))->sin_addr, 4 );
488         vlc_freeaddrinfo( p_res );
489
490         buffer[8] = 0;                  /* Empty user id */
491
492         if( net_Write( p_obj, fd, NULL, buffer, 9 ) != 9 )
493             return VLC_EGENERIC;
494         if( net_Read( p_obj, fd, NULL, buffer, 8, VLC_TRUE ) != 8 )
495             return VLC_EGENERIC;
496
497         msg_Dbg( p_obj, "socks: v=%d cd=%d",
498                  buffer[0], buffer[1] );
499
500         if( buffer[1] != 90 )
501             return VLC_EGENERIC;
502     }
503     else if( i_socks_version == 5 )
504     {
505         int i_hlen = __MIN(strlen( psz_host ), 255);
506         int i_len;
507
508         buffer[0] = i_socks_version;    /* Version */
509         buffer[1] = 0x01;               /* Cmd: connect */
510         buffer[2] = 0x00;               /* Reserved */
511         buffer[3] = 3;                  /* ATYP: for now domainname */
512
513         buffer[4] = i_hlen;
514         memcpy( &buffer[5], psz_host, i_hlen );
515         SetWBE( &buffer[5+i_hlen], i_port );
516
517         i_len = 5 + i_hlen + 2;
518
519
520         if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
521             return VLC_EGENERIC;
522
523         /* Read the header */
524         if( net_Read( p_obj, fd, NULL, buffer, 5, VLC_TRUE ) != 5 )
525             return VLC_EGENERIC;
526
527         msg_Dbg( p_obj, "socks: v=%d rep=%d atyp=%d",
528                  buffer[0], buffer[1], buffer[3] );
529
530         if( buffer[1] != 0x00 )
531         {
532             msg_Err( p_obj, "socks: CONNECT request failed\n" );
533             return VLC_EGENERIC;
534         }
535
536         /* Read the remaining bytes */
537         if( buffer[3] == 0x01 )
538             i_len = 4-1 + 2;
539         else if( buffer[3] == 0x03 )
540             i_len = buffer[4] + 2;
541         else if( buffer[3] == 0x04 )
542             i_len = 16-1+2;
543         else 
544             return VLC_EGENERIC;
545
546         if( net_Read( p_obj, fd, NULL, buffer, i_len, VLC_TRUE ) != i_len )
547             return VLC_EGENERIC;
548     }
549
550     return VLC_SUCCESS;
551 }
552
553 void net_ListenClose( int *pi_fd )
554 {
555     if( pi_fd != NULL )
556     {
557         int *pi;
558
559         for( pi = pi_fd; *pi != -1; pi++ )
560             net_Close( *pi );
561         free( pi_fd );
562     }
563 }