source: trunk/libtransmission/net.c @ 2573

Last change on this file since 2573 was 2573, checked in by charles, 15 years ago

continue whittling away at internal.h to reduce the global #include dependencies

  • Property svn:keywords set to Date Rev Author Id
File size: 12.1 KB
Line 
1/******************************************************************************
2 * $Id: net.c 2573 2007-07-31 14:26:44Z charles $
3 *
4 * Copyright (c) 2005-2006 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <errno.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29
30#include <sys/types.h>
31#include <netdb.h>
32#include <fcntl.h>
33
34#include "transmission.h"
35#include "fdlimit.h"
36#include "net.h"
37#include "platform.h"
38#include "utils.h"
39
40
41/***********************************************************************
42 * DNS resolution
43 **********************************************************************/
44
45/***********************************************************************
46 * tr_netResolve
47 ***********************************************************************
48 * Synchronous "resolution": only works with character strings
49 * representing numbers expressed in the Internet standard `.' notation.
50 * Returns a non-zero value if an error occurs.
51 **********************************************************************/
52int tr_netResolve( const char * address, struct in_addr * addr )
53{
54    addr->s_addr = inet_addr( address );
55    return ( addr->s_addr == 0xFFFFFFFF );
56}
57
58static tr_thread_t  * resolveThread;
59static tr_lock_t    * resolveLock;
60static tr_cond_t    * resolveCond;
61static volatile int   resolveDie;
62static tr_resolve_t * resolveQueue;
63
64static void resolveRelease ( tr_resolve_t * );
65static void resolveFunc    ( void * );
66
67struct tr_resolve_s
68{
69    tr_tristate_t  status;
70    char           * address;
71    struct in_addr addr;
72
73    int            refcount;
74    tr_resolve_t   * next;
75};
76
77/***********************************************************************
78 * tr_netResolveThreadInit
79 ***********************************************************************
80 * Initializes the static variables used for resolution and launch the
81 * gethostbyname thread.
82 **********************************************************************/
83void tr_netResolveThreadInit()
84{
85    resolveDie   = 0;
86    resolveQueue = NULL;
87    resolveLock = tr_lockNew( );
88    resolveCond = tr_condNew( );
89    resolveThread = tr_threadNew( resolveFunc, NULL, "resolve" );
90}
91
92/***********************************************************************
93 * tr_netResolveThreadClose
94 ***********************************************************************
95 * Notices the gethostbyname thread that is should terminate. Doesn't
96 * wait until it does, in case it is stuck in a resolution: we let it
97 * die and clean itself up.
98 **********************************************************************/
99void tr_netResolveThreadClose()
100{
101    tr_lockLock( resolveLock );
102    resolveDie = 1;
103    tr_lockUnlock( resolveLock );
104    tr_condSignal( resolveCond );
105    tr_wait( 200 );
106}
107
108/***********************************************************************
109 * tr_netResolveInit
110 ***********************************************************************
111 * Adds an address to the resolution queue.
112 **********************************************************************/
113tr_resolve_t * tr_netResolveInit( const char * address )
114{
115    tr_resolve_t * r = tr_new0( tr_resolve_t, 1 );
116    r->status   = TR_NET_WAIT;
117    r->address  = strdup( address );
118    r->refcount = 2;
119    r->next     = NULL;
120
121    tr_lockLock( resolveLock );
122    if( !resolveQueue )
123    {
124        resolveQueue = r;
125    }
126    else
127    {
128        tr_resolve_t * iter;
129        for( iter = resolveQueue; iter->next; iter = iter->next );
130        iter->next = r;
131    }
132    tr_lockUnlock( resolveLock );
133    tr_condSignal( resolveCond );
134
135    return r;
136}
137
138/***********************************************************************
139 * tr_netResolvePulse
140 ***********************************************************************
141 * Checks the current status of a resolution.
142 **********************************************************************/
143tr_tristate_t tr_netResolvePulse( tr_resolve_t * r, struct in_addr * addr )
144{
145    tr_tristate_t ret;
146
147    tr_lockLock( resolveLock );
148    ret = r->status;
149    if( ret == TR_NET_OK )
150    {
151        *addr = r->addr;
152    }
153    tr_lockUnlock( resolveLock );
154
155    return ret;
156}
157
158/***********************************************************************
159 * tr_netResolveClose
160 ***********************************************************************
161 *
162 **********************************************************************/
163void tr_netResolveClose( tr_resolve_t * r )
164{
165    resolveRelease( r );
166}
167
168/***********************************************************************
169 * resolveRelease
170 ***********************************************************************
171 * The allocated tr_resolve_t structures should be freed when
172 * tr_netResolveClose was called *and* it was removed from the queue.
173 * This can happen in any order, so we use a refcount to know we can
174 * take it out.
175 **********************************************************************/
176static void resolveRelease( tr_resolve_t * r )
177{
178    if( --r->refcount < 1 )
179    {
180        free( r->address );
181        free( r );
182    }
183}
184
185/***********************************************************************
186 * resolveFunc
187 ***********************************************************************
188 * Keeps waiting for addresses to resolve, and removes them from the
189 * queue once resolution is done.
190 **********************************************************************/
191static void resolveFunc( void * arg UNUSED )
192{
193    tr_resolve_t * r;
194    struct hostent * host;
195
196    tr_lockLock( resolveLock );
197
198    while( !resolveDie )
199    {
200        if( !( r = resolveQueue ) )
201        {
202            tr_condWait( resolveCond, resolveLock );
203            continue;
204        }
205
206        /* Blocking resolution */
207        tr_lockUnlock( resolveLock );
208        host = gethostbyname( r->address );
209        tr_lockLock( resolveLock );
210
211        if( host )
212        {
213            memcpy( &r->addr, host->h_addr, host->h_length );
214            r->status = TR_NET_OK;
215        }
216        else
217        {
218            r->status = TR_NET_ERROR;
219        }
220       
221        resolveQueue = r->next;
222        resolveRelease( r );
223    }
224
225    /* Clean up  */
226    tr_lockUnlock( resolveLock );
227    tr_lockFree( resolveLock );
228    resolveLock = NULL;
229    while( ( r = resolveQueue ) )
230    {
231        resolveQueue = r->next;
232        resolveRelease( r );
233    }
234}
235
236
237/***********************************************************************
238 * TCP/UDP sockets
239 **********************************************************************/
240
241static int makeSocketNonBlocking( int s )
242{
243    int flags;
244
245#ifdef SYS_BEOS
246    flags = 1;
247    if( setsockopt( s, SOL_SOCKET, SO_NONBLOCK,
248                    &flags, sizeof( int ) ) < 0 )
249#else
250    if( ( flags = fcntl( s, F_GETFL, 0 ) ) < 0 ||
251        fcntl( s, F_SETFL, flags | O_NONBLOCK ) < 0 )
252#endif
253    {
254        tr_err( "Could not set socket to non-blocking mode (%s)",
255                strerror( errno ) );
256        tr_netClose( s );
257        return -1;
258    }
259
260    return s;
261}
262
263static int createSocket( int type, int priority )
264{
265    int s;
266    if( ( s = tr_fdSocketCreate( type, priority ) ) < 0 )
267    {
268        return -1;
269    }
270    return makeSocketNonBlocking( s );
271}
272
273static int
274tr_netOpen( const struct in_addr * addr, tr_port_t port,
275            int type, int priority )
276{
277    int s;
278    struct sockaddr_in sock;
279
280    if( ( s = createSocket( type, priority ) ) < 0 )
281    {
282        return -1;
283    }
284
285    memset( &sock, 0, sizeof( sock ) );
286    sock.sin_family      = AF_INET;
287    sock.sin_addr.s_addr = addr->s_addr;
288    sock.sin_port        = port;
289
290    if( connect( s, (struct sockaddr *) &sock,
291                 sizeof( struct sockaddr_in ) ) < 0 &&
292        errno != EINPROGRESS )
293    {
294        tr_err( "Could not connect socket (%s)", strerror( errno ) );
295        tr_netClose( s );
296        return -1;
297    }
298
299    return s;
300}
301 
302int
303tr_netOpenTCP( const struct in_addr * addr, tr_port_t port, int priority )
304{
305    return tr_netOpen( addr, port, SOCK_STREAM, priority );
306}
307
308int
309tr_netOpenUDP( const struct in_addr * addr, tr_port_t port, int priority )
310{
311    return tr_netOpen( addr, port, SOCK_DGRAM, priority );
312}
313
314#ifdef IP_ADD_MEMBERSHIP
315int tr_netMcastOpen( int port, const struct in_addr * addr )
316{
317    int fd;
318    struct ip_mreq req;
319
320    fd = tr_netBindUDP( port );
321    if( 0 > fd )
322    {
323        return -1;
324    }
325
326    memset( &req, 0, sizeof( req ) );
327    req.imr_multiaddr.s_addr = addr->s_addr;
328    req.imr_interface.s_addr = htonl( INADDR_ANY );
329    if( setsockopt( fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &req, sizeof ( req ) ) )
330    {
331        tr_err( "Could not join multicast group (%s)", strerror( errno ) );
332        tr_netClose( fd );
333        return -1;
334    }
335
336    return fd;
337}
338#else /* IP_ADD_MEMBERSHIP */
339int tr_netMcastOpen( int port UNUSED, const struct in_addr * addr UNUSED )
340{
341    return -1;
342}
343#endif /* IP_ADD_MEMBERSHIP */
344
345static int
346tr_netBind( int port, int type )
347{
348    int s;
349    struct sockaddr_in sock;
350#if defined( SO_REUSEADDR ) || defined( SO_REUSEPORT )
351    int optval;
352#endif
353
354    if( ( s = createSocket( type, 1 ) ) < 0 )
355    {
356        return -1;
357    }
358
359#ifdef SO_REUSEADDR
360    optval = 1;
361    setsockopt( s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) );
362#endif
363
364#ifdef SO_REUSEPORT
365    if( SOCK_DGRAM == type )
366    {
367        optval = 1;
368        setsockopt( s, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof( optval ) );
369    }
370#endif
371
372    memset( &sock, 0, sizeof( sock ) );
373    sock.sin_family      = AF_INET;
374    sock.sin_addr.s_addr = INADDR_ANY;
375    sock.sin_port        = htons( port );
376
377    if( bind( s, (struct sockaddr *) &sock,
378               sizeof( struct sockaddr_in ) ) )
379    {
380        tr_err( "Could not bind port %d", port );
381        tr_netClose( s );
382        return -1;
383    }
384
385    return s;
386}
387
388int
389tr_netBindTCP( int port )
390{
391    return tr_netBind( port, SOCK_STREAM );
392}
393
394int
395tr_netBindUDP( int port )
396{
397    return tr_netBind( port, SOCK_DGRAM );
398}
399
400
401int tr_netAccept( int b, struct in_addr * addr, tr_port_t * port )
402{
403    int s;
404    if( ( s = tr_fdSocketAccept( b, addr, port ) ) < 0 )
405    {
406        return -1;
407    }
408    return makeSocketNonBlocking( s );
409}
410
411int
412tr_netSend( int s, const void * buf, int size )
413{
414    const int ret = send( s, buf, size, 0 );
415    if( ret >= 0 )
416        return ret;
417
418    if( errno == ENOTCONN || errno == EAGAIN || errno == EWOULDBLOCK )
419        return TR_NET_BLOCK;
420
421    return TR_NET_CLOSE;
422}
423
424int tr_netRecvFrom( int s, uint8_t * buf, int size, struct sockaddr_in * addr )
425{
426    socklen_t len;
427    int       ret;
428
429    len = ( NULL == addr ? 0 : sizeof( *addr ) );
430    ret = recvfrom( s, buf, size, 0, ( struct sockaddr * ) addr, &len );
431    if( ret < 0 )
432    {
433        if( errno == EAGAIN || errno == EWOULDBLOCK )
434        {
435            ret = TR_NET_BLOCK;
436        }
437        else
438        {
439            ret = TR_NET_CLOSE;
440        }
441    }
442    if( !ret )
443    {
444        ret = TR_NET_CLOSE;
445    }
446
447    return ret;
448}
449
450void tr_netClose( int s )
451{
452    tr_fdSocketClose( s );
453}
454
455void tr_netNtop( const struct in_addr * addr, char * buf, int len )
456{
457    const uint8_t * cast;
458
459    cast = (const uint8_t *)addr;
460    snprintf( buf, len, "%hhu.%hhu.%hhu.%hhu",
461              cast[0], cast[1], cast[2], cast[3] );
462}
Note: See TracBrowser for help on using the repository browser.