source: trunk/libtransmission/fdlimit.c @ 4177

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

raise the maximum connection limit a bit.

  • Property svn:keywords set to Date Rev Author Id
File size: 11.3 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 4177 2007-12-15 16:36:43Z 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 = 512,
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            if( fileIsOpen( &gFd->open[winner] ) ) {
258                dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
259                TrCloseFile( winner );
260            }
261        } else { 
262            dbgmsg( "everything's full!  waiting for someone else to finish something" );
263            tr_lockUnlock( gFd->lock );
264            tr_wait( 200 );
265            tr_lockLock( gFd->lock );
266        }
267    }
268
269    assert( winner >= 0 );
270    o = &gFd->open[winner];
271    if( !fileIsOpen( o ) )
272    {
273        const int ret = TrOpenFile( winner, filename, write );
274        if( ret ) {
275            tr_lockUnlock( gFd->lock );
276            return ret;
277        }
278
279        dbgmsg( "opened '%s' in slot %d, write %c", filename, winner, write?'y':'n' );
280        strlcpy( o->filename, filename, sizeof( o->filename ) );
281        o->isWritable = write;
282    }
283
284    dbgmsg( "checking out '%s' in slot %d", filename, winner );
285    o->isCheckedOut = 1;
286    o->closeWhenDone = 0;
287    o->date = tr_date( );
288    tr_lockUnlock( gFd->lock );
289    return o->fd;
290}
291
292void
293tr_fdFileReturn( int fd )
294{
295    int i;
296    tr_lockLock( gFd->lock );
297
298    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
299    {
300        struct tr_openfile * o = &gFd->open[i];
301        if( o->fd != fd )
302            continue;
303
304        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
305        o->isCheckedOut = 0;
306        if( o->closeWhenDone )
307            TrCloseFile( i );
308       
309        break;
310    }
311   
312    tr_lockUnlock( gFd->lock );
313}
314
315void
316tr_fdFileClose( const char * filename )
317{
318    int i;
319    tr_lockLock( gFd->lock );
320    dbgmsg( "tr_fdFileClose closing '%s'", filename );
321
322    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
323    {
324        struct tr_openfile * o = &gFd->open[i];
325        if( !fileIsOpen(o) || strcmp(filename,o->filename) )
326            continue;
327
328        if( !o->isCheckedOut ) {
329            dbgmsg( "not checked out, so closing it now... '%s'", filename );
330            TrCloseFile( i );
331        } else {
332            dbgmsg( "flagging file '%s', slot #%d to be closed when checked in", gFd->open[i].filename, i );
333            o->closeWhenDone = 1;
334        }
335    }
336   
337    tr_lockUnlock( gFd->lock );
338}
339
340/***
341****
342****  Sockets
343****
344***/
345
346static tr_list * reservedSockets = NULL;
347
348static void
349setSocketPriority( int fd, int isReserved )
350{
351    if( isReserved )
352        tr_list_append( &reservedSockets, TR_UINT_TO_PTR(fd) );
353}
354
355static int
356socketWasReserved( int fd )
357{
358    return tr_list_remove_data( &reservedSockets, TR_UINT_TO_PTR(fd) ) != NULL;
359}
360
361int
362tr_fdSocketCreate( int type, int isReserved )
363{
364    int s = -1;
365    tr_lockLock( gFd->lock );
366
367    if( isReserved && gFd->reserved >= TR_RESERVED_FDS )
368        isReserved = FALSE;
369
370    if( isReserved || ( gFd->normal < gFd->normalMax ) )
371        if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
372            tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
373
374    if( s > -1 )
375    {
376        setSocketPriority( s, isReserved );
377
378        if( isReserved )
379            ++gFd->reserved;
380        else
381            ++gFd->normal;
382    }
383
384    assert( gFd->reserved >= 0 );
385    assert( gFd->normal >= 0 );
386
387    tr_lockUnlock( gFd->lock );
388    return s;
389}
390
391int
392tr_fdSocketAccept( int b, struct in_addr * addr, tr_port_t * port )
393{
394    int s = -1;
395    unsigned int len;
396    struct sockaddr_in sock;
397
398    assert( addr != NULL );
399    assert( port != NULL );
400
401    tr_lockLock( gFd->lock );
402    if( gFd->normal < gFd->normalMax )
403    {
404        len = sizeof( sock );
405        s = accept( b, (struct sockaddr *) &sock, &len );
406    }
407    if( s > -1 )
408    {
409        setSocketPriority( s, FALSE );
410        *addr = sock.sin_addr;
411        *port = sock.sin_port;
412        gFd->normal++;
413    }
414    tr_lockUnlock( gFd->lock );
415
416    return s;
417}
418
419static void
420socketClose( int fd )
421{
422#ifdef BEOS_NETSERVER
423    closesocket( fd );
424#else
425    EVUTIL_CLOSESOCKET( fd );
426#endif
427}
428
429void
430tr_fdSocketClose( int s )
431{
432    tr_lockLock( gFd->lock );
433
434    if( s >= 0 ) {
435        socketClose( s );
436        if( socketWasReserved( s ) )
437            --gFd->reserved;
438        else
439            --gFd->normal;
440    }
441
442    assert( gFd->reserved >= 0 );
443    assert( gFd->normal >= 0 );
444
445    tr_lockUnlock( gFd->lock );
446}
447
448/***
449****
450****  Startup / Shutdown
451****
452***/
453
454void
455tr_fdInit( void )
456{
457    int i, j, s[TR_MAX_SOCKETS];
458
459    assert( gFd == NULL );
460
461    gFd = tr_new0( struct tr_fd_s, 1 );
462    gFd->lock = tr_lockNew( );
463
464    /* count the max number of sockets we can use */
465    for( i=0; i<TR_MAX_SOCKETS; ++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}
479
480void
481tr_fdClose( void )
482{
483    int i = 0;
484
485    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
486        if( fileIsOpen( &gFd->open[i] ) )
487            TrCloseFile( i );
488
489    tr_lockFree( gFd->lock );
490
491    tr_list_free( &reservedSockets, NULL );
492    tr_free( gFd );
493}
Note: See TracBrowser for help on using the repository browser.