source: trunk/libtransmission/fdlimit.c @ 4311

Last change on this file since 4311 was 4311, checked in by charles, 14 years ago

(gtk) fix startup port issue by hitting it with a damn big hammer

  • Property svn:keywords set to Date Rev Author Id
File size: 11.5 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 4311 2007-12-24 07:02:40Z 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 <assert.h>
26#include <errno.h>
27#include <inttypes.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31
32#include <sys/types.h>
33#include <sys/stat.h>
34#include <unistd.h>
35#include <libgen.h> /* basename, dirname */
36#include <fcntl.h> /* O_LARGEFILE */
37
38#include <event.h>
39#include <evutil.h>
40
41#include "transmission.h"
42#include "trcompat.h"
43#include "list.h"
44#include "net.h"
45#include "platform.h"
46#include "utils.h"
47
48#if SIZEOF_VOIDP==8
49#define TR_UINT_TO_PTR(i) (void*)((uint64_t)i)
50#else
51#define TR_UINT_TO_PTR(i) ((void*)((uint32_t)i))
52#endif
53
54/**
55***
56**/
57
58static void
59myDebug( const char * file, int line, const char * fmt, ... )
60{
61    FILE * fp = tr_getLog( );
62    if( fp != NULL )
63    {
64        va_list args;
65        char s[64];
66        struct evbuffer * buf = evbuffer_new( );
67        char * myfile = tr_strdup( file );
68
69        evbuffer_add_printf( buf, "[%s] ", tr_getLogTimeStr( s, sizeof(s) ) );
70        va_start( args, fmt );
71        evbuffer_add_vprintf( buf, fmt, args );
72        va_end( args );
73        evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line );
74        fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp );
75
76        tr_free( myfile );
77        evbuffer_free( buf );
78    }
79}
80
81#define dbgmsg(fmt...) myDebug(__FILE__, __LINE__, ##fmt )
82
83/**
84***
85**/
86
87enum
88{
89    TR_MAX_OPEN_FILES = 16, /* real files, not sockets */
90
91    TR_RESERVED_FDS = 16 /* sockets reserved for tracker connections */
92};
93
94struct tr_openfile
95{
96    unsigned int  isCheckedOut : 1;
97    unsigned int  isWritable : 1;
98    unsigned int  closeWhenDone : 1;
99    char          filename[MAX_PATH_LENGTH];
100    int           fd;
101    uint64_t      date;
102};
103
104struct tr_fd_s
105{
106    int                  reserved;
107    int                  normal;
108    int                  normalMax;
109    tr_lock            * lock;
110    struct tr_openfile   open[TR_MAX_OPEN_FILES];
111};
112
113static struct tr_fd_s * gFd = NULL;
114
115/***
116****
117****  Local Files
118****
119***/
120
121static int
122TrOpenFile( int i, const char * filename, int write )
123{
124    struct tr_openfile * file = &gFd->open[i];
125    int flags;
126
127    tr_dbg( "Opening '%s' (%d)", filename, write );
128
129    /* create subfolders, if any */
130    if( write ) {
131        char * tmp = tr_strdup( filename );
132        const int val = tr_mkdirp( dirname(tmp), 0777 );
133        tr_free( tmp );
134        if( val )
135            return tr_ioErrorFromErrno( );
136    }
137
138    /* open the file */
139    flags = write ? (O_RDWR | O_CREAT) : O_RDONLY;
140#ifdef O_LARGEFILE
141    flags |= O_LARGEFILE;
142#endif
143#ifdef WIN32
144    flags |= O_BINARY;
145#endif
146    errno = 0;
147    file->fd = open( filename, flags, 0666 );
148    if( file->fd < 0 ) {
149        if( errno ) {
150            tr_err( "Couldn't open '%s': %s", filename, strerror(errno) );
151            return tr_ioErrorFromErrno();
152        } else {
153            tr_err( "Couldn't open '%s'", filename );
154            return TR_ERROR_IO_OTHER;
155        }
156    }
157
158    return TR_OK;
159}
160
161static int
162fileIsOpen( const struct tr_openfile * o )
163{
164    return o->fd >= 0;
165}
166
167static void
168TrCloseFile( int i )
169{
170    struct tr_openfile * o = &gFd->open[i];
171
172    assert( i >= 0 );
173    assert( i < TR_MAX_OPEN_FILES );
174    assert( fileIsOpen( o ) );
175
176    dbgmsg( "closing slot #%d, %s", i, o->filename );
177    close( o->fd );
178    o->fd = -1;
179    o->isCheckedOut = 0;
180}
181
182static int
183fileIsCheckedOut( const struct tr_openfile * o )
184{
185    return fileIsOpen(o) && o->isCheckedOut;
186}
187
188int
189tr_fdFileCheckout( const char * filename, int write )
190{
191    int i, winner = -1;
192    struct tr_openfile * o;
193
194    assert( filename && *filename );
195    assert( write==0 || write==1 );
196
197    dbgmsg( "looking for file '%s', writable %c", filename, write?'y':'n' );
198
199    tr_lockLock( gFd->lock );
200
201    /* Is it already open? */
202    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
203    {
204        o = &gFd->open[i];
205
206        if( !fileIsOpen( o ) )
207            continue;
208
209        if( strcmp( filename, o->filename ) )
210            continue;
211
212        if( fileIsCheckedOut( o ) ) {
213            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
214            tr_lockUnlock( gFd->lock );
215            tr_wait( 200 );
216            tr_lockLock( gFd->lock );
217            i = -1; /* reloop */
218            continue;
219        }
220
221        if( write && !o->isWritable ) {
222            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
223            TrCloseFile( i );
224            break;
225        }
226
227        dbgmsg( "found it!  it's ready for use!" );
228        winner = i;
229        break;
230    }
231
232    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
233    while( winner < 0 )
234    {
235        uint64_t date = tr_date( ) + 1;
236
237        /* look for the file that's been open longest */
238        for( i=0; i<TR_MAX_OPEN_FILES; ++i )
239        {
240            o = &gFd->open[i];
241
242            if( !fileIsOpen( o ) ) {
243                winner = i;
244                dbgmsg( "found an empty slot in %d", winner );
245                break;
246            }
247
248            if( date > o->date ) {
249                date = o->date;
250                winner = i;
251            }
252        }
253
254        if( winner >= 0 ) {
255            if( fileIsOpen( &gFd->open[winner] ) ) {
256                dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
257                TrCloseFile( winner );
258            }
259        } else { 
260            dbgmsg( "everything's full!  waiting for someone else to finish something" );
261            tr_lockUnlock( gFd->lock );
262            tr_wait( 200 );
263            tr_lockLock( gFd->lock );
264        }
265    }
266
267    assert( winner >= 0 );
268    o = &gFd->open[winner];
269    if( !fileIsOpen( o ) )
270    {
271        const int ret = TrOpenFile( winner, filename, write );
272        if( ret ) {
273            tr_lockUnlock( gFd->lock );
274            return ret;
275        }
276
277        dbgmsg( "opened '%s' in slot %d, write %c", filename, winner, write?'y':'n' );
278        strlcpy( o->filename, filename, sizeof( o->filename ) );
279        o->isWritable = write;
280    }
281
282    dbgmsg( "checking out '%s' in slot %d", filename, winner );
283    o->isCheckedOut = 1;
284    o->closeWhenDone = 0;
285    o->date = tr_date( );
286    tr_lockUnlock( gFd->lock );
287    return o->fd;
288}
289
290void
291tr_fdFileReturn( int fd )
292{
293    int i;
294    tr_lockLock( gFd->lock );
295
296    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
297    {
298        struct tr_openfile * o = &gFd->open[i];
299        if( o->fd != fd )
300            continue;
301
302        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
303        o->isCheckedOut = 0;
304        if( o->closeWhenDone )
305            TrCloseFile( i );
306       
307        break;
308    }
309   
310    tr_lockUnlock( gFd->lock );
311}
312
313void
314tr_fdFileClose( const char * filename )
315{
316    int i;
317    tr_lockLock( gFd->lock );
318    dbgmsg( "tr_fdFileClose closing '%s'", filename );
319
320    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
321    {
322        struct tr_openfile * o = &gFd->open[i];
323        if( !fileIsOpen(o) || strcmp(filename,o->filename) )
324            continue;
325
326        if( !o->isCheckedOut ) {
327            dbgmsg( "not checked out, so closing it now... '%s'", filename );
328            TrCloseFile( i );
329        } else {
330            dbgmsg( "flagging file '%s', slot #%d to be closed when checked in", gFd->open[i].filename, i );
331            o->closeWhenDone = 1;
332        }
333    }
334   
335    tr_lockUnlock( gFd->lock );
336}
337
338/***
339****
340****  Sockets
341****
342***/
343
344static tr_list * reservedSockets = NULL;
345
346static void
347setSocketPriority( int fd, int isReserved )
348{
349    if( isReserved )
350        tr_list_append( &reservedSockets, TR_UINT_TO_PTR(fd) );
351}
352
353static int
354socketWasReserved( int fd )
355{
356    return tr_list_remove_data( &reservedSockets, TR_UINT_TO_PTR(fd) ) != NULL;
357}
358
359int
360tr_fdSocketCreate( int type, int isReserved )
361{
362    int s = -1;
363    tr_lockLock( gFd->lock );
364
365    if( isReserved && gFd->reserved >= TR_RESERVED_FDS )
366        isReserved = FALSE;
367
368    if( isReserved || ( gFd->normal < gFd->normalMax ) )
369        if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
370            tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
371
372    if( s > -1 )
373    {
374        setSocketPriority( s, isReserved );
375
376        if( isReserved )
377            ++gFd->reserved;
378        else
379            ++gFd->normal;
380    }
381
382    assert( gFd->reserved >= 0 );
383    assert( gFd->normal >= 0 );
384
385    tr_lockUnlock( gFd->lock );
386    return s;
387}
388
389int
390tr_fdSocketAccept( int b, struct in_addr * addr, tr_port_t * port )
391{
392    int s = -1;
393    unsigned int len;
394    struct sockaddr_in sock;
395
396    assert( addr != NULL );
397    assert( port != NULL );
398
399    tr_lockLock( gFd->lock );
400    if( gFd->normal < gFd->normalMax )
401    {
402        len = sizeof( sock );
403        s = accept( b, (struct sockaddr *) &sock, &len );
404    }
405    if( s > -1 )
406    {
407        setSocketPriority( s, FALSE );
408        *addr = sock.sin_addr;
409        *port = sock.sin_port;
410        gFd->normal++;
411    }
412    tr_lockUnlock( gFd->lock );
413
414    return s;
415}
416
417static void
418socketClose( int fd )
419{
420#ifdef BEOS_NETSERVER
421    closesocket( fd );
422#else
423    EVUTIL_CLOSESOCKET( fd );
424#endif
425}
426
427void
428tr_fdSocketClose( int s )
429{
430    tr_lockLock( gFd->lock );
431
432    if( s >= 0 ) {
433        socketClose( s );
434        if( socketWasReserved( s ) )
435            --gFd->reserved;
436        else
437            --gFd->normal;
438    }
439
440    assert( gFd->reserved >= 0 );
441    assert( gFd->normal >= 0 );
442
443    tr_lockUnlock( gFd->lock );
444}
445
446/***
447****
448****  Startup / Shutdown
449****
450***/
451
452void
453tr_fdInit( int globalPeerLimit )
454{
455    int i, j, *s;
456
457    assert( gFd == NULL );
458
459    gFd = tr_new0( struct tr_fd_s, 1 );
460    gFd->lock = tr_lockNew( );
461
462    s = tr_new( int, globalPeerLimit );
463
464    /* count the max number of sockets we can use */
465    for( i=0; i<globalPeerLimit; ++i )
466        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
467            break;
468    for( j=0; j<i; ++j )
469        socketClose( s[j] );
470    tr_dbg( "%d usable file descriptors", i );
471
472    /* set some fds aside for the UI or daemon to use */
473    gFd->normalMax = i - TR_RESERVED_FDS - 10;
474
475    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
476        gFd->open[i].fd = -1;
477
478    tr_free( s );
479}
480
481void
482tr_fdClose( void )
483{
484    int i = 0;
485
486    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
487        if( fileIsOpen( &gFd->open[i] ) )
488            TrCloseFile( i );
489
490    tr_lockFree( gFd->lock );
491
492    tr_list_free( &reservedSockets, NULL );
493    tr_free( gFd );
494}
495
496void
497tr_fdSetPeerLimit( uint16_t n )
498{
499    assert( gFd!=NULL && "tr_fdInit() must be called first!" );
500    gFd->normalMax = n;
501}
502
503uint16_t
504tr_fdGetPeerLimit( void )
505{
506    return gFd ? gFd->normalMax : -1;
507}
Note: See TracBrowser for help on using the repository browser.