source: branches/0.9x/libtransmission/fdlimit.c @ 4045

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

backport the [4040...4044] mutex fix to 0.9x

  • Property svn:keywords set to Date Rev Author Id
File size: 11.2 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 4045 2007-12-03 16:26:02Z 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_SOCKETS = 320,
90
91    TR_MAX_OPEN_FILES = 8, /* real files, not sockets */
92
93    TR_RESERVED_FDS = 16 /* sockets reserved for tracker connections */
94};
95
96struct tr_openfile
97{
98    unsigned int  isCheckedOut : 1;
99    unsigned int  isWritable : 1;
100    unsigned int  closeWhenDone : 1;
101    char          filename[MAX_PATH_LENGTH];
102    int           fd;
103    uint64_t      date;
104};
105
106struct tr_fd_s
107{
108    int                  reserved;
109    int                  normal;
110    int                  normalMax;
111    tr_lock            * lock;
112    struct tr_openfile   open[TR_MAX_OPEN_FILES];
113};
114
115static struct tr_fd_s * gFd = NULL;
116
117/***
118****
119****  Local Files
120****
121***/
122
123static int
124TrOpenFile( int i, const char * filename, int write )
125{
126    struct tr_openfile * file = &gFd->open[i];
127    int flags;
128
129    tr_dbg( "Opening '%s' (%d)", filename, write );
130
131    /* create subfolders, if any */
132    if( write ) {
133        char * tmp = tr_strdup( filename );
134        const int val = tr_mkdirp( dirname(tmp), 0777 );
135        tr_free( tmp );
136        if( val )
137            return tr_ioErrorFromErrno( );
138    }
139
140    /* open the file */
141    flags = write ? (O_RDWR | O_CREAT) : O_RDONLY;
142#ifdef O_LARGEFILE
143    flags |= O_LARGEFILE;
144#endif
145#ifdef WIN32
146    flags |= O_BINARY;
147#endif
148    errno = 0;
149    file->fd = open( filename, flags, 0666 );
150    if( file->fd < 0 ) {
151        if( errno ) {
152            tr_err( "Couldn't open '%s': %s", filename, strerror(errno) );
153            return tr_ioErrorFromErrno();
154        } else {
155            tr_err( "Couldn't open '%s'", filename );
156            return TR_ERROR_IO_OTHER;
157        }
158    }
159
160    return TR_OK;
161}
162
163static int
164fileIsOpen( const struct tr_openfile * o )
165{
166    return o->fd >= 0;
167}
168
169static void
170TrCloseFile( int i )
171{
172    struct tr_openfile * o = &gFd->open[i];
173
174    assert( i >= 0 );
175    assert( i < TR_MAX_OPEN_FILES );
176    assert( fileIsOpen( o ) );
177
178    dbgmsg( "closing slot #%d, %s", i, o->filename );
179    close( o->fd );
180    o->fd = -1;
181    o->isCheckedOut = 0;
182}
183
184static int
185fileIsCheckedOut( const struct tr_openfile * o )
186{
187    return fileIsOpen(o) && o->isCheckedOut;
188}
189
190int
191tr_fdFileCheckout( const char * filename, int write )
192{
193    int i, winner = -1;
194    struct tr_openfile * o;
195
196    assert( filename && *filename );
197    assert( write==0 || write==1 );
198
199    dbgmsg( "looking for file '%s', writable %c", filename, write?'y':'n' );
200
201    tr_lockLock( gFd->lock );
202
203    /* Is it already open? */
204    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
205    {
206        o = &gFd->open[i];
207
208        if( !fileIsOpen( o ) )
209            continue;
210
211        if( strcmp( filename, o->filename ) )
212            continue;
213
214        if( fileIsCheckedOut( o ) ) {
215            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
216            tr_lockUnlock( gFd->lock );
217            tr_wait( 200 );
218            tr_lockLock( gFd->lock );
219            i = -1; /* reloop */
220            continue;
221        }
222
223        if( write && !o->isWritable ) {
224            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
225            TrCloseFile( i );
226            break;
227        }
228
229        dbgmsg( "found it!  it's ready for use!" );
230        winner = i;
231        break;
232    }
233
234    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
235    while( winner < 0 )
236    {
237        uint64_t date = tr_date( ) + 1;
238
239        /* look for the file that's been open longest */
240        for( i=0; i<TR_MAX_OPEN_FILES; ++i )
241        {
242            o = &gFd->open[i];
243
244            if( !fileIsOpen( o ) ) {
245                winner = i;
246                dbgmsg( "found an empty slot in %d", winner );
247                break;
248            }
249
250            if( date > o->date ) {
251                date = o->date;
252                winner = i;
253            }
254        }
255
256        if( winner >= 0 ) {
257            dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
258            TrCloseFile( winner );
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( void )
454{
455    int i, j, s[TR_MAX_SOCKETS];
456
457    assert( gFd == NULL );
458
459    gFd = tr_new0( struct tr_fd_s, 1 );
460    gFd->lock = tr_lockNew( );
461
462    /* count the max number of sockets we can use */
463    for( i=0; i<TR_MAX_SOCKETS; ++i )
464        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
465            break;
466    for( j=0; j<i; ++j )
467        socketClose( s[j] );
468    tr_dbg( "%d usable file descriptors", i );
469
470    /* set some fds aside for the UI or daemon to use */
471    gFd->normalMax = i - TR_RESERVED_FDS - 10;
472
473    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
474        gFd->open[i].fd = -1;
475         
476}
477
478void
479tr_fdClose( void )
480{
481    int i = 0;
482
483    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
484        if( fileIsOpen( &gFd->open[i] ) )
485            TrCloseFile( i );
486
487    tr_lockFree( gFd->lock );
488
489    tr_list_free( &reservedSockets, NULL );
490    tr_free( gFd );
491}
Note: See TracBrowser for help on using the repository browser.