]> git.sesse.net Git - vlc/blob - src/network/tcp.c
Include assert.h when needed
[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 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc/vlc.h>
34
35 #include <errno.h>
36 #include <assert.h>
37
38 #ifdef HAVE_FCNTL_H
39 #   include <fcntl.h>
40 #endif
41 #ifdef HAVE_SYS_TIME_H
42 #    include <sys/time.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #   include <unistd.h>
46 #endif
47 #ifdef HAVE_POLL
48 # include <poll.h>
49 #endif
50
51 #include <vlc_network.h>
52 #if defined (WIN32) || defined (UNDER_CE)
53 #   undef EINPROGRESS
54 #   define EINPROGRESS WSAEWOULDBLOCK
55 #   undef EINTR
56 #   define EINTR WSAEINTR
57 #   undef ETIMEDOUT
58 #   define ETIMEDOUT WSAETIMEDOUT
59 #endif
60
61 static int SocksNegociate( vlc_object_t *, int fd, int i_socks_version,
62                            const char *psz_user, const char *psz_passwd );
63 static int SocksHandshakeTCP( vlc_object_t *,
64                               int fd, int i_socks_version,
65                               const char *psz_user, const char *psz_passwd,
66                               const char *psz_host, int i_port );
67 extern int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
68                        int i_protocol );
69
70 /*****************************************************************************
71  * __net_Connect:
72  *****************************************************************************
73  * Open a network connection.
74  * @return socket handler or -1 on error.
75  *****************************************************************************/
76 int __net_Connect( vlc_object_t *p_this, const char *psz_host, int i_port,
77                    int type, int proto )
78 {
79     struct addrinfo hints, *res, *ptr;
80     const char      *psz_realhost;
81     char            *psz_socks;
82     int             i_realport, i_val, i_handle = -1;
83
84     if( i_port == 0 )
85         i_port = 80; /* historical VLC thing */
86
87     memset( &hints, 0, sizeof( hints ) );
88     hints.ai_socktype = SOCK_STREAM;
89
90     psz_socks = var_CreateGetNonEmptyString( p_this, "socks" );
91     if( psz_socks != NULL )
92     {
93         char *psz = strchr( psz_socks, ':' );
94
95         if( psz )
96             *psz++ = '\0';
97
98         psz_realhost = psz_socks;
99         i_realport = ( psz != NULL ) ? atoi( psz ) : 1080;
100         hints.ai_flags &= ~AI_NUMERICHOST;
101
102         msg_Dbg( p_this, "net: connecting to %s port %d (SOCKS) "
103                  "for %s port %d", psz_realhost, i_realport,
104                  psz_host, i_port );
105
106         /* We only implement TCP with SOCKS */
107         switch( type )
108         {
109             case 0:
110                 type = SOCK_STREAM;
111             case SOCK_STREAM:
112                 break;
113             default:
114                 msg_Err( p_this, "Socket type not supported through SOCKS" );
115                 free( psz_socks );
116                 return -1;
117         }
118         switch( proto )
119         {
120             case 0:
121                 proto = IPPROTO_TCP;
122             case IPPROTO_TCP:
123                 break;
124             default:
125                 msg_Err( p_this, "Transport not supported through SOCKS" );
126                 free( psz_socks );
127                 return -1;
128         }
129     }
130     else
131     {
132         psz_realhost = psz_host;
133         i_realport = i_port;
134
135         msg_Dbg( p_this, "net: connecting to %s port %d", psz_realhost,
136                  i_realport );
137     }
138
139     i_val = vlc_getaddrinfo( p_this, psz_realhost, i_realport, &hints, &res );
140     free( psz_socks );
141
142     if( i_val )
143     {
144         msg_Err( p_this, "cannot resolve %s port %d : %s", psz_realhost,
145                  i_realport, vlc_gai_strerror( i_val ) );
146         return -1;
147     }
148
149     for( ptr = res; ptr != NULL; ptr = ptr->ai_next )
150     {
151         int fd = net_Socket( p_this, ptr->ai_family, type ?: ptr->ai_socktype,
152                              proto ?: ptr->ai_protocol );
153         if( fd == -1 )
154         {
155             msg_Dbg( p_this, "socket error: %m" );
156             continue;
157         }
158
159         if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) )
160         {
161             socklen_t i_val_size = sizeof( i_val );
162             div_t d;
163             vlc_value_t timeout;
164
165             if( net_errno != EINPROGRESS )
166             {
167                 msg_Err( p_this, "connection failed: %m" );
168                 goto next_ai;
169             }
170             msg_Dbg( p_this, "connection: %m" );
171
172             var_Create( p_this, "ipv4-timeout",
173                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
174             var_Get( p_this, "ipv4-timeout", &timeout );
175             if( timeout.i_int < 0 )
176             {
177                 msg_Err( p_this, "invalid negative value for ipv4-timeout" );
178                 timeout.i_int = 0;
179             }
180             d = div( timeout.i_int, 100 );
181
182             for (;;)
183             {
184                 struct pollfd ufd = { .fd = fd, .events = POLLOUT };
185                 int i_ret;
186
187                 if( p_this->b_die )
188                 {
189                     msg_Dbg( p_this, "connection aborted" );
190                     net_Close( fd );
191                     vlc_freeaddrinfo( res );
192                     return -1;
193                 }
194
195                 /*
196                  * We'll wait 0.1 second if nothing happens
197                  * NOTE:
198                  * time out will be shortened if we catch a signal (EINTR)
199                  */
200                 i_ret = poll (&ufd, 1, (d.quot > 0) ? 100 : d.rem);
201                 if( i_ret == 1 )
202                     break;
203
204                 if( ( i_ret == -1 ) && ( net_errno != EINTR ) )
205                 {
206                     msg_Err( p_this, "connection polling error: %m" );
207                     goto next_ai;
208                 }
209
210                 if( d.quot <= 0 )
211                 {
212                     msg_Warn( p_this, "connection timed out" );
213                     goto next_ai;
214                 }
215
216                 d.quot--;
217             }
218
219 #if !defined( SYS_BEOS ) && !defined( UNDER_CE )
220             if( getsockopt( fd, SOL_SOCKET, SO_ERROR, (void*)&i_val,
221                             &i_val_size ) == -1 || i_val != 0 )
222             {
223                 errno = i_val;
224                 msg_Err( p_this, "connection failed: %m" );
225                 goto next_ai;
226             }
227 #endif
228         }
229
230         msg_Dbg( p_this, "connection succeeded (socket = %d)", fd );
231         i_handle = fd; /* success! */
232         break;
233
234 next_ai: /* failure */
235         net_Close( fd );
236         continue;
237     }
238
239     vlc_freeaddrinfo( res );
240
241     if( i_handle == -1 )
242         return -1;
243
244     if( psz_socks != NULL )
245     {
246         /* NOTE: psz_socks already free'd! */
247         char *psz_user = var_CreateGetNonEmptyString( p_this, "socks-user" );
248         char *psz_pwd  = var_CreateGetNonEmptyString( p_this, "socks-pwd" );
249
250         if( SocksHandshakeTCP( p_this, i_handle, 5, psz_user, psz_pwd,
251                                psz_host, i_port ) )
252         {
253             msg_Err( p_this, "SOCKS handshake failed" );
254             net_Close( i_handle );
255             i_handle = -1;
256         }
257
258         free( psz_user );
259         free( psz_pwd );
260     }
261
262     return i_handle;
263 }
264
265
266 int net_AcceptSingle (vlc_object_t *obj, int lfd)
267 {
268     int fd = accept (lfd, NULL, NULL);
269     if (fd == -1)
270     {
271         if (net_errno != EAGAIN)
272             msg_Err (obj, "accept failed (from socket %d): %m", lfd);
273         return -1;
274     }
275
276     msg_Dbg (obj, "accepted socket %d (from socket %d)", fd, lfd);
277     net_SetupSocket (fd);
278     return 0;
279 }
280
281
282 /*****************************************************************************
283  * __net_Accept:
284  *****************************************************************************
285  * Accept a connection on a set of listening sockets and return it
286  *****************************************************************************/
287 int __net_Accept( vlc_object_t *p_this, int *pi_fd, mtime_t i_wait )
288 {
289     int timeout = (i_wait < 0) ? -1 : i_wait / 1000;
290     int evfd;
291
292     assert( pi_fd != NULL );
293
294     evfd = vlc_object_waitpipe (p_this);
295
296     for (;;)
297     {
298         unsigned n = 0;
299         while (pi_fd[n] != -1)
300             n++;
301         struct pollfd ufd[n + 1];
302
303         /* Initialize file descriptor set */
304         for (unsigned i = 0; i <= n; i++)
305         {
306             ufd[i].fd = (i < n) ? pi_fd[i] : evfd;
307             ufd[i].events = POLLIN;
308             ufd[i].revents = 0;
309         }
310         if (evfd == -1)
311             n--; /* avoid EBADF */
312
313         switch (poll (ufd, n, timeout))
314         {
315             case -1:
316                 if (net_errno != EINTR)
317                     msg_Err (p_this, "poll error: %m");
318             case 0:
319                 return -1; /* NOTE: p_this already unlocked */
320         }
321
322         if (ufd[n].revents)
323         {
324             errno = EINTR;
325             break;
326         }
327
328         for (unsigned i = 0; i < n; i++)
329         {
330             if (ufd[i].revents == 0)
331                 continue;
332
333             int sfd = ufd[i].fd;
334             int fd = net_AcceptSingle (p_this, sfd);
335             if (fd == -1)
336                 continue;
337
338             /*
339              * Move listening socket to the end to let the others in the
340              * set a chance next time.
341              */
342             memmove (pi_fd + i, pi_fd + i + 1, n - (i + 1));
343             pi_fd[n - 1] = sfd;
344             return fd;
345         }
346     }
347     return -1;
348 }
349
350
351 /*****************************************************************************
352  * SocksNegociate:
353  *****************************************************************************
354  * Negociate authentication with a SOCKS server.
355  *****************************************************************************/
356 static int SocksNegociate( vlc_object_t *p_obj,
357                            int fd, int i_socks_version,
358                            const char *psz_socks_user,
359                            const char *psz_socks_passwd )
360 {
361     uint8_t buffer[128+2*256];
362     int i_len;
363     vlc_bool_t b_auth = VLC_FALSE;
364
365     if( i_socks_version != 5 )
366         return VLC_SUCCESS;
367
368     /* We negociate authentication */
369
370     if( ( psz_socks_user == NULL ) && ( psz_socks_passwd == NULL ) )
371         b_auth = VLC_TRUE;
372
373     buffer[0] = i_socks_version;    /* SOCKS version */
374     if( b_auth )
375     {
376         buffer[1] = 2;                  /* Number of methods */
377         buffer[2] = 0x00;               /* - No auth required */
378         buffer[3] = 0x02;               /* - USer/Password */
379         i_len = 4;
380     }
381     else
382     {
383         buffer[1] = 1;                  /* Number of methods */
384         buffer[2] = 0x00;               /* - No auth required */
385         i_len = 3;
386     }
387
388     if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
389         return VLC_EGENERIC;
390     if( net_Read( p_obj, fd, NULL, buffer, 2, VLC_TRUE ) != 2 )
391         return VLC_EGENERIC;
392
393     msg_Dbg( p_obj, "socks: v=%d method=%x", buffer[0], buffer[1] );
394
395     if( buffer[1] == 0x00 )
396     {
397         msg_Dbg( p_obj, "socks: no authentication required" );
398     }
399     else if( buffer[1] == 0x02 )
400     {
401         int i_len1 = __MIN( strlen(psz_socks_user), 255 );
402         int i_len2 = __MIN( strlen(psz_socks_passwd), 255 );
403         msg_Dbg( p_obj, "socks: username/password authentication" );
404
405         /* XXX: we don't support user/pwd > 255 (truncated)*/
406         buffer[0] = i_socks_version;        /* Version */
407         buffer[1] = i_len1;                 /* User length */
408         memcpy( &buffer[2], psz_socks_user, i_len1 );
409         buffer[2+i_len1] = i_len2;          /* Password length */
410         memcpy( &buffer[2+i_len1+1], psz_socks_passwd, i_len2 );
411
412         i_len = 3 + i_len1 + i_len2;
413
414         if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
415             return VLC_EGENERIC;
416
417         if( net_Read( p_obj, fd, NULL, buffer, 2, VLC_TRUE ) != 2 )
418             return VLC_EGENERIC;
419
420         msg_Dbg( p_obj, "socks: v=%d status=%x", buffer[0], buffer[1] );
421         if( buffer[1] != 0x00 )
422         {
423             msg_Err( p_obj, "socks: authentication rejected" );
424             return VLC_EGENERIC;
425         }
426     }
427     else
428     {
429         if( b_auth )
430             msg_Err( p_obj, "socks: unsupported authentication method %x",
431                      buffer[0] );
432         else
433             msg_Err( p_obj, "socks: authentification needed" );
434         return VLC_EGENERIC;
435     }
436
437     return VLC_SUCCESS;
438 }
439
440 /*****************************************************************************
441  * SocksHandshakeTCP:
442  *****************************************************************************
443  * Open a TCP connection using a SOCKS server and return a handle (RFC 1928)
444  *****************************************************************************/
445 static int SocksHandshakeTCP( vlc_object_t *p_obj,
446                               int fd,
447                               int i_socks_version,
448                               const char *psz_user, const char *psz_passwd,
449                               const char *psz_host, int i_port )
450 {
451     uint8_t buffer[128+2*256];
452
453     if( i_socks_version != 4 && i_socks_version != 5 )
454     {
455         msg_Warn( p_obj, "invalid socks protocol version %d", i_socks_version );
456         i_socks_version = 5;
457     }
458
459     if( i_socks_version == 5 &&
460         SocksNegociate( p_obj, fd, i_socks_version,
461                         psz_user, psz_passwd ) )
462         return VLC_EGENERIC;
463
464     if( i_socks_version == 4 )
465     {
466         struct addrinfo hints, *p_res;
467
468         /* v4 only support ipv4 */
469         memset (&hints, 0, sizeof (hints));
470         hints.ai_family = AF_INET;
471         if( vlc_getaddrinfo( p_obj, psz_host, 0, &hints, &p_res ) )
472             return VLC_EGENERIC;
473
474         buffer[0] = i_socks_version;
475         buffer[1] = 0x01;               /* CONNECT */
476         SetWBE( &buffer[2], i_port );   /* Port */
477         memcpy( &buffer[4],             /* Address */
478                 &((struct sockaddr_in *)(p_res->ai_addr))->sin_addr, 4 );
479         vlc_freeaddrinfo( p_res );
480
481         buffer[8] = 0;                  /* Empty user id */
482
483         if( net_Write( p_obj, fd, NULL, buffer, 9 ) != 9 )
484             return VLC_EGENERIC;
485         if( net_Read( p_obj, fd, NULL, buffer, 8, VLC_TRUE ) != 8 )
486             return VLC_EGENERIC;
487
488         msg_Dbg( p_obj, "socks: v=%d cd=%d",
489                  buffer[0], buffer[1] );
490
491         if( buffer[1] != 90 )
492             return VLC_EGENERIC;
493     }
494     else if( i_socks_version == 5 )
495     {
496         int i_hlen = __MIN(strlen( psz_host ), 255);
497         int i_len;
498
499         buffer[0] = i_socks_version;    /* Version */
500         buffer[1] = 0x01;               /* Cmd: connect */
501         buffer[2] = 0x00;               /* Reserved */
502         buffer[3] = 3;                  /* ATYP: for now domainname */
503
504         buffer[4] = i_hlen;
505         memcpy( &buffer[5], psz_host, i_hlen );
506         SetWBE( &buffer[5+i_hlen], i_port );
507
508         i_len = 5 + i_hlen + 2;
509
510
511         if( net_Write( p_obj, fd, NULL, buffer, i_len ) != i_len )
512             return VLC_EGENERIC;
513
514         /* Read the header */
515         if( net_Read( p_obj, fd, NULL, buffer, 5, VLC_TRUE ) != 5 )
516             return VLC_EGENERIC;
517
518         msg_Dbg( p_obj, "socks: v=%d rep=%d atyp=%d",
519                  buffer[0], buffer[1], buffer[3] );
520
521         if( buffer[1] != 0x00 )
522         {
523             msg_Err( p_obj, "socks: CONNECT request failed\n" );
524             return VLC_EGENERIC;
525         }
526
527         /* Read the remaining bytes */
528         if( buffer[3] == 0x01 )
529             i_len = 4-1 + 2;
530         else if( buffer[3] == 0x03 )
531             i_len = buffer[4] + 2;
532         else if( buffer[3] == 0x04 )
533             i_len = 16-1+2;
534         else
535             return VLC_EGENERIC;
536
537         if( net_Read( p_obj, fd, NULL, buffer, i_len, VLC_TRUE ) != i_len )
538             return VLC_EGENERIC;
539     }
540
541     return VLC_SUCCESS;
542 }
543
544 void net_ListenClose( int *pi_fd )
545 {
546     if( pi_fd != NULL )
547     {
548         int *pi;
549
550         for( pi = pi_fd; *pi != -1; pi++ )
551             net_Close( *pi );
552         free( pi_fd );
553     }
554 }