source: trunk/libtransmission/net.c @ 1425

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

More simplifications

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