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