source: trunk/libtransmission/net.c @ 1401

Last change on this file since 1401 was 1401, checked in by titer, 15 years ago

clean up

  • Property svn:keywords set to Date Rev Author Id
File size: 11.7 KB
Line 
1/******************************************************************************
2 * $Id: net.c 1401 2007-01-19 01:39:33Z titer $
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 "transmission.h"
26
27/***********************************************************************
28 * DNS resolution
29 **********************************************************************/
30
31/***********************************************************************
32 * tr_netResolve
33 ***********************************************************************
34 * Synchronous "resolution": only works with character strings
35 * representing numbers expressed in the Internet standard `.' notation.
36 * Returns a non-zero value if an error occurs.
37 **********************************************************************/
38int tr_netResolve( const char * address, struct in_addr * addr )
39{
40    addr->s_addr = inet_addr( address );
41    return ( addr->s_addr == 0xFFFFFFFF );
42}
43
44/* TODO: Make this code reentrant */
45static tr_thread_t  resolveThread;
46static tr_lock_t    resolveLock;
47static tr_cond_t    resolveCond;
48static volatile int resolveDie;
49static tr_resolve_t * resolveQueue;
50
51static void resolveRelease ( tr_resolve_t * );
52static void resolveFunc    ( void * );
53
54struct tr_resolve_s
55{
56    tr_tristate_t  status;
57    char           * address;
58    struct in_addr addr;
59
60    int            refcount;
61    tr_resolve_t   * next;
62};
63
64/***********************************************************************
65 * tr_netResolveThreadInit
66 ***********************************************************************
67 * Initializes the static variables used for resolution and launch the
68 * gethostbyname thread.
69 **********************************************************************/
70void tr_netResolveThreadInit()
71{
72    resolveDie   = 0;
73    resolveQueue = NULL;
74    tr_lockInit( &resolveLock );
75    tr_condInit( &resolveCond );
76    tr_threadCreate( &resolveThread, resolveFunc, NULL, "resolve" );
77}
78
79/***********************************************************************
80 * tr_netResolveThreadClose
81 ***********************************************************************
82 * Notices the gethostbyname thread that is should terminate. Doesn't
83 * wait until it does, in case it is stuck in a resolution: we let it
84 * die and clean itself up.
85 **********************************************************************/
86void tr_netResolveThreadClose()
87{
88    tr_lockLock( &resolveLock );
89    resolveDie = 1;
90    tr_lockUnlock( &resolveLock );
91    tr_condSignal( &resolveCond );
92    tr_wait( 200 );
93}
94
95/***********************************************************************
96 * tr_netResolveInit
97 ***********************************************************************
98 * Adds an address to the resolution queue.
99 **********************************************************************/
100tr_resolve_t * tr_netResolveInit( const char * address )
101{
102    tr_resolve_t * r;
103
104    r           = malloc( sizeof( tr_resolve_t ) );
105    r->status   = TR_NET_WAIT;
106    r->address  = strdup( address );
107    r->refcount = 2;
108    r->next     = NULL;
109
110    tr_lockLock( &resolveLock );
111    if( !resolveQueue )
112    {
113        resolveQueue = r;
114    }
115    else
116    {
117        tr_resolve_t * iter;
118        for( iter = resolveQueue; iter->next; iter = iter->next );
119        iter->next = r;
120    }
121    tr_lockUnlock( &resolveLock );
122    tr_condSignal( &resolveCond );
123
124    return r;
125}
126
127/***********************************************************************
128 * tr_netResolvePulse
129 ***********************************************************************
130 * Checks the current status of a resolution.
131 **********************************************************************/
132tr_tristate_t tr_netResolvePulse( tr_resolve_t * r, struct in_addr * addr )
133{
134    tr_tristate_t ret;
135
136    tr_lockLock( &resolveLock );
137    ret = r->status;
138    if( ret == TR_NET_OK )
139    {
140        *addr = r->addr;
141    }
142    tr_lockUnlock( &resolveLock );
143
144    return ret;
145}
146
147/***********************************************************************
148 * tr_netResolveClose
149 ***********************************************************************
150 *
151 **********************************************************************/
152void tr_netResolveClose( tr_resolve_t * r )
153{
154    resolveRelease( r );
155}
156
157/***********************************************************************
158 * resolveRelease
159 ***********************************************************************
160 * The allocated tr_resolve_t structures should be freed when
161 * tr_netResolveClose was called *and* it was removed from the queue.
162 * This can happen in any order, so we use a refcount to know we can
163 * take it out.
164 **********************************************************************/
165static void resolveRelease( tr_resolve_t * r )
166{
167    if( --r->refcount < 1 )
168    {
169        free( r->address );
170        free( r );
171    }
172}
173
174/***********************************************************************
175 * resolveFunc
176 ***********************************************************************
177 * Keeps waiting for addresses to resolve, and removes them from the
178 * queue once resolution is done.
179 **********************************************************************/
180static void resolveFunc( void * arg UNUSED )
181{
182    tr_resolve_t * r;
183    struct hostent * host;
184
185    tr_lockLock( &resolveLock );
186
187    while( !resolveDie )
188    {
189        if( !( r = resolveQueue ) )
190        {
191            tr_condWait( &resolveCond, &resolveLock );
192            continue;
193        }
194
195        /* Blocking resolution */
196        tr_lockUnlock( &resolveLock );
197        host = gethostbyname( r->address );
198        tr_lockLock( &resolveLock );
199
200        if( host )
201        {
202            memcpy( &r->addr, host->h_addr, host->h_length );
203            r->status = TR_NET_OK;
204        }
205        else
206        {
207            r->status = TR_NET_ERROR;
208        }
209       
210        resolveQueue = r->next;
211        resolveRelease( r );
212    }
213
214    /* Clean up  */
215    tr_lockUnlock( &resolveLock );
216    tr_lockClose( &resolveLock );
217    while( ( r = resolveQueue ) )
218    {
219        resolveQueue = r->next;
220        resolveRelease( r );
221    }
222}
223
224
225/***********************************************************************
226 * TCP sockets
227 **********************************************************************/
228
229static int makeSocketNonBlocking( int s )
230{
231    int flags;
232
233#ifdef SYS_BEOS
234    flags = 1;
235    if( setsockopt( s, SOL_SOCKET, SO_NONBLOCK,
236                    &flags, sizeof( int ) ) < 0 )
237#else
238    if( ( flags = fcntl( s, F_GETFL, 0 ) ) < 0 ||
239        fcntl( s, F_SETFL, flags | O_NONBLOCK ) < 0 )
240#endif
241    {
242        tr_err( "Could not set socket to non-blocking mode (%s)",
243                strerror( errno ) );
244        tr_netClose( s );
245        return -1;
246    }
247
248    return s;
249}
250
251static int createSocket( int type )
252{
253    int s;
254
255    s = socket( AF_INET, type, 0 );
256    if( s < 0 )
257    {
258        tr_err( "Could not create socket (%s)", strerror( errno ) );
259        return -1;
260    }
261
262    return makeSocketNonBlocking( s );
263}
264
265int tr_netOpen( struct in_addr addr, in_port_t port, int type )
266{
267    int s;
268    struct sockaddr_in sock;
269
270    s = createSocket( type );
271    if( s < 0 )
272    {
273        return -1;
274    }
275
276    memset( &sock, 0, sizeof( sock ) );
277    sock.sin_family      = AF_INET;
278    sock.sin_addr.s_addr = addr.s_addr;
279    sock.sin_port        = port;
280
281    if( connect( s, (struct sockaddr *) &sock,
282                 sizeof( struct sockaddr_in ) ) < 0 &&
283        errno != EINPROGRESS )
284    {
285        tr_err( "Could not connect socket (%s)", strerror( errno ) );
286        tr_netClose( s );
287        return -1;
288    }
289
290    return s;
291}
292
293#ifdef IP_ADD_MEMBERSHIP
294int tr_netMcastOpen( int port, struct in_addr addr )
295{
296    int fd;
297    struct ip_mreq req;
298
299    fd = tr_netBindUDP( port );
300    if( 0 > fd )
301    {
302        return -1;
303    }
304
305    memset( &req, 0, sizeof( req ) );
306    req.imr_multiaddr.s_addr = addr.s_addr;
307    req.imr_interface.s_addr = htonl( INADDR_ANY );
308    if( setsockopt( fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &req, sizeof ( req ) ) )
309    {
310        tr_err( "Could not join multicast group (%s)", strerror( errno ) );
311        tr_netClose( fd );
312        return -1;
313    }
314
315    return fd;
316}
317#else /* IP_ADD_MEMBERSHIP */
318int tr_netMcastOpen( int port UNUSED, struct in_addr addr UNUSED )
319{
320    return -1;
321}
322#endif /* IP_ADD_MEMBERSHIP */
323
324int tr_netBind( int port, int type )
325{
326    int s;
327    struct sockaddr_in sock;
328#if defined( SO_REUSEADDR ) || defined( SO_REUSEPORT )
329    int optval;
330#endif
331
332    s = createSocket( type );
333    if( s < 0 )
334    {
335        return -1;
336    }
337
338#ifdef SO_REUSEADDR
339    optval = 1;
340    setsockopt( s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) );
341#endif
342
343#ifdef SO_REUSEPORT
344    if( SOCK_DGRAM == type )
345    {
346        optval = 1;
347        setsockopt( s, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof( optval ) );
348    }
349#endif
350
351    memset( &sock, 0, sizeof( sock ) );
352    sock.sin_family      = AF_INET;
353    sock.sin_addr.s_addr = INADDR_ANY;
354    sock.sin_port        = htons( port );
355
356    if( bind( s, (struct sockaddr *) &sock,
357               sizeof( struct sockaddr_in ) ) )
358    {
359        tr_err( "Could not bind port %d", port );
360        tr_netClose( s );
361        return -1;
362    }
363
364    return s;
365}
366
367int tr_netAccept( int s, struct in_addr * addr, in_port_t * port )
368{
369    int t;
370    unsigned len;
371    struct sockaddr_in sock;
372
373    len = sizeof( sock );
374    t   = accept( s, (struct sockaddr *) &sock, &len );
375
376    if( t < 0 )
377    {
378        return -1;
379    }
380   
381    *addr = sock.sin_addr;
382    *port = sock.sin_port;
383
384    return makeSocketNonBlocking( t );
385}
386
387int tr_netSend( int s, uint8_t * buf, int size )
388{
389    int ret;
390
391    ret = send( s, buf, size, 0 );
392    if( ret < 0 )
393    {
394        if( errno == ENOTCONN || errno == EAGAIN || errno == EWOULDBLOCK )
395        {
396            ret = TR_NET_BLOCK;
397        }
398        else
399        {
400            ret = TR_NET_CLOSE;
401        }
402    }
403
404    return ret;
405}
406
407int tr_netRecvFrom( int s, uint8_t * buf, int size, struct sockaddr_in * addr )
408{
409    socklen_t len;
410    int       ret;
411
412    len = ( NULL == addr ? 0 : sizeof( *addr ) );
413    ret = recvfrom( s, buf, size, 0, ( struct sockaddr * ) addr, &len );
414    if( ret < 0 )
415    {
416        if( errno == EAGAIN || errno == EWOULDBLOCK )
417        {
418            ret = TR_NET_BLOCK;
419        }
420        else
421        {
422            ret = TR_NET_CLOSE;
423        }
424    }
425    if( !ret )
426    {
427        ret = TR_NET_CLOSE;
428    }
429
430    return ret;
431}
432
433void tr_netClose( int s )
434{
435#ifdef BEOS_NETSERVER
436    closesocket( s );
437#else
438    close( s );
439#endif
440}
441
442void tr_netNtop( const struct in_addr * addr, char * buf, int len )
443{
444    const uint8_t * cast;
445
446    cast = (const uint8_t *)addr;
447    snprintf( buf, len, "%hhu.%hhu.%hhu.%hhu",
448              cast[0], cast[1], cast[2], cast[3] );
449}
Note: See TracBrowser for help on using the repository browser.