source: trunk/libtransmission/fdlimit.c @ 3753

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

update our #includes now that libevent has cleaned up event.h

  • Property svn:keywords set to Date Rev Author Id
File size: 10.5 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 3753 2007-11-07 18:26:19Z 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>
37
38#include <sys/queue.h> /* evhttp.h needs this */
39#include <event.h>
40#include <evhttp.h>
41#include <evutil.h>
42
43#include "transmission.h"
44#include "trcompat.h"
45#include "list.h"
46#include "net.h"
47#include "platform.h"
48#include "utils.h"
49
50#if SIZEOF_VOIDP==8
51#define TR_UINT_TO_PTR(i) (void*)((uint64_t)i)
52#else
53#define TR_UINT_TO_PTR(i) ((void*)((uint32_t)i))
54#endif
55
56/**
57***
58**/
59
60static void
61myDebug( const char * file, int line, const char * fmt, ... )
62{
63    FILE * fp = tr_getLog( );
64    if( fp != NULL )
65    {
66        va_list args;
67        char s[64];
68        struct evbuffer * buf = evbuffer_new( );
69        char * myfile = tr_strdup( file );
70
71        evbuffer_add_printf( buf, "[%s] ", tr_getLogTimeStr( s, sizeof(s) ) );
72        va_start( args, fmt );
73        evbuffer_add_vprintf( buf, fmt, args );
74        va_end( args );
75        evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line );
76        fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp );
77
78        tr_free( myfile );
79        evbuffer_free( buf );
80    }
81}
82
83#define dbgmsg(fmt...) myDebug(__FILE__, __LINE__, ##fmt )
84
85/**
86***
87**/
88
89enum
90{
91    TR_MAX_SOCKETS = 1024,
92
93    TR_MAX_OPEN_FILES = 16, /* real files, not sockets */
94
95    TR_RESERVED_FDS   = 16 /* sockets reserved for tracker connections */
96};
97
98struct tr_openfile
99{
100    unsigned int  isCheckedOut : 1;
101    unsigned int  isWritable : 1;
102    char          filename[MAX_PATH_LENGTH];
103    int           fd;
104    uint64_t      date;
105};
106
107struct tr_fd_s
108{
109    int                  reserved;
110    int                  normal;
111    int                  normalMax;
112    tr_lock            * lock;
113    tr_cond            * cond;
114    struct tr_openfile   open[TR_MAX_OPEN_FILES];
115};
116
117static struct tr_fd_s * gFd = NULL;
118
119/***
120****
121****  Local Files
122****
123***/
124
125static int
126TrOpenFile( int i, const char * filename, int write )
127{
128    struct tr_openfile * file = &gFd->open[i];
129    int flags;
130
131    tr_dbg( "Opening '%s' (%d)", filename, write );
132
133    /* create subfolders, if any */
134    if( write ) {
135        char * tmp = tr_strdup( filename );
136        const int val = tr_mkdirp( dirname(tmp), 0700 );
137        tr_free( tmp );
138        if( val )
139            return tr_ioErrorFromErrno( );
140    }
141
142    /* open the file */
143    flags = write ? (O_RDWR | O_CREAT) : O_RDONLY;
144#ifdef WIN32
145    flags |= O_BINARY;
146#endif
147    errno = 0;
148    file->fd = open( filename, flags, 0600 );
149    if( file->fd < 0 ) {
150        if( errno ) {
151            tr_err( "Couldn't open '%s': %s", filename, strerror(errno) );
152            return tr_ioErrorFromErrno();
153        } else {
154            tr_err( "Couldn't open '%s'", filename );
155            return TR_ERROR_IO_OTHER;
156        }
157    }
158
159    return TR_OK;
160}
161
162static int
163fileIsOpen( const struct tr_openfile * o )
164{
165    return o->fd >= 0;
166}
167
168static void
169TrCloseFile( int i )
170{
171    struct tr_openfile * o = &gFd->open[i];
172
173    assert( i >= 0 );
174    assert( i < TR_MAX_OPEN_FILES );
175    assert( fileIsOpen( o ) );
176
177    dbgmsg( "closing slot #%d, %s", i, o->filename );
178    close( o->fd );
179    o->fd = -1;
180    o->isCheckedOut = 0;
181    tr_condSignal( gFd->cond );
182}
183
184static int
185fileIsCheckedOut( const struct tr_openfile * o )
186{
187    return fileIsOpen(o) && o->isCheckedOut;
188}
189
190int
191tr_fdFileOpen( const char * filename, int write )
192{
193    int i, winner;
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_condWait( gFd->cond, 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        goto done;
230    }
231
232
233    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
234    for( ;; )
235    {
236        uint64_t date = tr_date( ) + 1;
237        winner = -1;
238
239        for( i=0; i<TR_MAX_OPEN_FILES; ++i )
240        {
241            o = &gFd->open[i];
242
243            if( !fileIsOpen( o ) ) {
244                winner = i;
245                dbgmsg( "found an empty slot in %d", winner );
246                goto done;
247            }
248
249            if( date > o->date ) {
250                date = o->date;
251                winner = i;
252            }
253        }
254
255        if( winner >= 0 ) {
256            dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
257            TrCloseFile( winner );
258            goto done;
259        }
260
261        /* All used! Wait a bit and try again */
262        dbgmsg( "everything's full!  waiting for someone else to finish something" );
263        tr_condWait( gFd->cond, gFd->lock );
264    }
265
266done:
267
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->date = tr_date( );
285    tr_lockUnlock( gFd->lock );
286    return o->fd;
287}
288
289void
290tr_fdFileRelease( int file )
291{
292    int i;
293    tr_lockLock( gFd->lock );
294
295    for( i=0; i<TR_MAX_OPEN_FILES; ++i ) {
296        struct tr_openfile * o = &gFd->open[i];
297        if( o->fd == file ) {
298            dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
299            fsync( o->fd );
300            o->isCheckedOut = 0;
301            break;
302        }
303    }
304   
305    tr_condSignal( gFd->cond );
306    tr_lockUnlock( gFd->lock );
307}
308
309/***
310****
311****  Sockets
312****
313***/
314
315static tr_list * reservedSockets = NULL;
316
317static void
318setSocketPriority( int fd, int isReserved )
319{
320    if( isReserved )
321        tr_list_append( &reservedSockets, TR_UINT_TO_PTR(fd) );
322}
323
324static int
325socketWasReserved( int fd )
326{
327    return tr_list_remove_data( &reservedSockets, TR_UINT_TO_PTR(fd) ) != NULL;
328}
329
330int
331tr_fdSocketCreate( int type, int isReserved )
332{
333    int s = -1;
334    tr_lockLock( gFd->lock );
335
336    if( isReserved && gFd->reserved >= TR_RESERVED_FDS )
337        isReserved = FALSE;
338
339    if( isReserved || ( gFd->normal < gFd->normalMax ) )
340        if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
341            tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
342
343    if( s > -1 )
344    {
345        setSocketPriority( s, isReserved );
346
347        if( isReserved )
348            ++gFd->reserved;
349        else
350            ++gFd->normal;
351    }
352
353    assert( gFd->reserved >= 0 );
354    assert( gFd->normal >= 0 );
355
356    tr_lockUnlock( gFd->lock );
357    return s;
358}
359
360int
361tr_fdSocketAccept( int b, struct in_addr * addr, tr_port_t * port )
362{
363    int s = -1;
364    unsigned int len;
365    struct sockaddr_in sock;
366
367    assert( addr != NULL );
368    assert( port != NULL );
369
370    tr_lockLock( gFd->lock );
371    if( gFd->normal < gFd->normalMax )
372    {
373        len = sizeof( sock );
374        s = accept( b, (struct sockaddr *) &sock, &len );
375    }
376    if( s > -1 )
377    {
378        setSocketPriority( s, FALSE );
379        *addr = sock.sin_addr;
380        *port = sock.sin_port;
381        gFd->normal++;
382    }
383    tr_lockUnlock( gFd->lock );
384
385    return s;
386}
387
388static void
389socketClose( int fd )
390{
391#ifdef BEOS_NETSERVER
392    closesocket( fd );
393#else
394    EVUTIL_CLOSESOCKET( fd );
395#endif
396}
397
398void
399tr_fdSocketClose( int s )
400{
401    tr_lockLock( gFd->lock );
402
403    if( s >= 0 ) {
404        socketClose( s );
405        if( socketWasReserved( s ) )
406            --gFd->reserved;
407        else
408            --gFd->normal;
409    }
410
411    assert( gFd->reserved >= 0 );
412    assert( gFd->normal >= 0 );
413
414    tr_lockUnlock( gFd->lock );
415}
416
417/***
418****
419****  Startup / Shutdown
420****
421***/
422
423void
424tr_fdInit( void )
425{
426    int i, j, s[TR_MAX_SOCKETS];
427
428    assert( gFd == NULL );
429
430    gFd = tr_new0( struct tr_fd_s, 1 );
431    gFd->lock = tr_lockNew( );
432    gFd->cond = tr_condNew( );
433
434    /* count the max number of sockets we can use */
435    for( i=0; i<TR_MAX_SOCKETS; ++i )
436        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
437            break;
438    for( j=0; j<i; ++j )
439        socketClose( s[j] );
440    tr_dbg( "%d usable file descriptors", i );
441
442    /* set some fds aside for the UI or daemon to use */
443    gFd->normalMax = i - TR_RESERVED_FDS - 10;
444
445    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
446        gFd->open[i].fd = -1;
447         
448}
449
450void
451tr_fdClose( void )
452{
453    int i = 0;
454
455    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
456        if( fileIsOpen( &gFd->open[i] ) )
457            TrCloseFile( i );
458
459    tr_lockFree( gFd->lock );
460    tr_condFree( gFd->cond );
461
462    tr_list_free( &reservedSockets, NULL );
463    tr_free( gFd );
464}
Note: See TracBrowser for help on using the repository browser.