source: trunk/libtransmission/fdlimit.c @ 4381

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

turn off a debugging message gone wild

  • Property svn:keywords set to Date Rev Author Id
File size: 11.4 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 4381 2007-12-30 18:46:18Z 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    /* create subfolders, if any */
128    if( write ) {
129        char * tmp = tr_strdup( filename );
130        const int val = tr_mkdirp( dirname(tmp), 0777 );
131        tr_free( tmp );
132        if( val )
133            return tr_ioErrorFromErrno( );
134    }
135
136    /* open the file */
137    flags = write ? (O_RDWR | O_CREAT) : O_RDONLY;
138#ifdef O_LARGEFILE
139    flags |= O_LARGEFILE;
140#endif
141#ifdef WIN32
142    flags |= O_BINARY;
143#endif
144    errno = 0;
145    file->fd = open( filename, flags, 0666 );
146    if( file->fd < 0 ) {
147        if( errno ) {
148            tr_err( "Couldn't open '%s': %s", filename, strerror(errno) );
149            return tr_ioErrorFromErrno();
150        } else {
151            tr_err( "Couldn't open '%s'", filename );
152            return TR_ERROR_IO_OTHER;
153        }
154    }
155
156    return TR_OK;
157}
158
159static int
160fileIsOpen( const struct tr_openfile * o )
161{
162    return o->fd >= 0;
163}
164
165static void
166TrCloseFile( int i )
167{
168    struct tr_openfile * o = &gFd->open[i];
169
170    assert( i >= 0 );
171    assert( i < TR_MAX_OPEN_FILES );
172    assert( fileIsOpen( o ) );
173
174    close( o->fd );
175    o->fd = -1;
176    o->isCheckedOut = 0;
177}
178
179static int
180fileIsCheckedOut( const struct tr_openfile * o )
181{
182    return fileIsOpen(o) && o->isCheckedOut;
183}
184
185int
186tr_fdFileCheckout( const char * filename, int write )
187{
188    int i, winner = -1;
189    struct tr_openfile * o;
190
191    assert( filename && *filename );
192    assert( write==0 || write==1 );
193
194    dbgmsg( "looking for file '%s', writable %c", filename, write?'y':'n' );
195
196    tr_lockLock( gFd->lock );
197
198    /* Is it already open? */
199    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
200    {
201        o = &gFd->open[i];
202
203        if( !fileIsOpen( o ) )
204            continue;
205
206        if( strcmp( filename, o->filename ) )
207            continue;
208
209        if( fileIsCheckedOut( o ) ) {
210            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
211            tr_lockUnlock( gFd->lock );
212            tr_wait( 200 );
213            tr_lockLock( gFd->lock );
214            i = -1; /* reloop */
215            continue;
216        }
217
218        if( write && !o->isWritable ) {
219            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
220            TrCloseFile( i );
221            break;
222        }
223
224        dbgmsg( "found it!  it's ready for use!" );
225        winner = i;
226        break;
227    }
228
229    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
230    while( winner < 0 )
231    {
232        uint64_t date = tr_date( ) + 1;
233
234        /* look for the file that's been open longest */
235        for( i=0; i<TR_MAX_OPEN_FILES; ++i )
236        {
237            o = &gFd->open[i];
238
239            if( !fileIsOpen( o ) ) {
240                winner = i;
241                dbgmsg( "found an empty slot in %d", winner );
242                break;
243            }
244
245            if( date > o->date ) {
246                date = o->date;
247                winner = i;
248            }
249        }
250
251        if( winner >= 0 ) {
252            if( fileIsOpen( &gFd->open[winner] ) ) {
253                dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
254                TrCloseFile( winner );
255            }
256        } else { 
257            dbgmsg( "everything's full!  waiting for someone else to finish something" );
258            tr_lockUnlock( gFd->lock );
259            tr_wait( 200 );
260            tr_lockLock( gFd->lock );
261        }
262    }
263
264    assert( winner >= 0 );
265    o = &gFd->open[winner];
266    if( !fileIsOpen( o ) )
267    {
268        const int ret = TrOpenFile( winner, filename, write );
269        if( ret ) {
270            tr_lockUnlock( gFd->lock );
271            return ret;
272        }
273
274        dbgmsg( "opened '%s' in slot %d, write %c", filename, winner, write?'y':'n' );
275        strlcpy( o->filename, filename, sizeof( o->filename ) );
276        o->isWritable = write;
277    }
278
279    dbgmsg( "checking out '%s' in slot %d", filename, winner );
280    o->isCheckedOut = 1;
281    o->closeWhenDone = 0;
282    o->date = tr_date( );
283    tr_lockUnlock( gFd->lock );
284    return o->fd;
285}
286
287void
288tr_fdFileReturn( int fd )
289{
290    int i;
291    tr_lockLock( gFd->lock );
292
293    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
294    {
295        struct tr_openfile * o = &gFd->open[i];
296        if( o->fd != fd )
297            continue;
298
299        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
300        o->isCheckedOut = 0;
301        if( o->closeWhenDone )
302            TrCloseFile( i );
303       
304        break;
305    }
306   
307    tr_lockUnlock( gFd->lock );
308}
309
310void
311tr_fdFileClose( const char * filename )
312{
313    int i;
314    tr_lockLock( gFd->lock );
315    dbgmsg( "tr_fdFileClose closing '%s'", filename );
316
317    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
318    {
319        struct tr_openfile * o = &gFd->open[i];
320        if( !fileIsOpen(o) || strcmp(filename,o->filename) )
321            continue;
322
323        if( !o->isCheckedOut ) {
324            dbgmsg( "not checked out, so closing it now... '%s'", filename );
325            TrCloseFile( i );
326        } else {
327            dbgmsg( "flagging file '%s', slot #%d to be closed when checked in", gFd->open[i].filename, i );
328            o->closeWhenDone = 1;
329        }
330    }
331   
332    tr_lockUnlock( gFd->lock );
333}
334
335/***
336****
337****  Sockets
338****
339***/
340
341static tr_list * reservedSockets = NULL;
342
343static void
344setSocketPriority( int fd, int isReserved )
345{
346    if( isReserved )
347        tr_list_append( &reservedSockets, TR_UINT_TO_PTR(fd) );
348}
349
350static int
351socketWasReserved( int fd )
352{
353    return tr_list_remove_data( &reservedSockets, TR_UINT_TO_PTR(fd) ) != NULL;
354}
355
356int
357tr_fdSocketCreate( int type, int isReserved )
358{
359    int s = -1;
360    tr_lockLock( gFd->lock );
361
362    if( isReserved && gFd->reserved >= TR_RESERVED_FDS )
363        isReserved = FALSE;
364
365    if( isReserved || ( gFd->normal < gFd->normalMax ) )
366        if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
367            tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
368
369    if( s > -1 )
370    {
371        setSocketPriority( s, isReserved );
372
373        if( isReserved )
374            ++gFd->reserved;
375        else
376            ++gFd->normal;
377    }
378
379    assert( gFd->reserved >= 0 );
380    assert( gFd->normal >= 0 );
381
382    tr_lockUnlock( gFd->lock );
383    return s;
384}
385
386int
387tr_fdSocketAccept( int b, struct in_addr * addr, tr_port_t * port )
388{
389    int s = -1;
390    unsigned int len;
391    struct sockaddr_in sock;
392
393    assert( addr != NULL );
394    assert( port != NULL );
395
396    tr_lockLock( gFd->lock );
397    if( gFd->normal < gFd->normalMax )
398    {
399        len = sizeof( sock );
400        s = accept( b, (struct sockaddr *) &sock, &len );
401    }
402    if( s > -1 )
403    {
404        setSocketPriority( s, FALSE );
405        *addr = sock.sin_addr;
406        *port = sock.sin_port;
407        gFd->normal++;
408    }
409    tr_lockUnlock( gFd->lock );
410
411    return s;
412}
413
414static void
415socketClose( int fd )
416{
417#ifdef BEOS_NETSERVER
418    closesocket( fd );
419#else
420    EVUTIL_CLOSESOCKET( fd );
421#endif
422}
423
424void
425tr_fdSocketClose( int s )
426{
427    tr_lockLock( gFd->lock );
428
429    if( s >= 0 ) {
430        socketClose( s );
431        if( socketWasReserved( s ) )
432            --gFd->reserved;
433        else
434            --gFd->normal;
435    }
436
437    assert( gFd->reserved >= 0 );
438    assert( gFd->normal >= 0 );
439
440    tr_lockUnlock( gFd->lock );
441}
442
443/***
444****
445****  Startup / Shutdown
446****
447***/
448
449void
450tr_fdInit( int globalPeerLimit )
451{
452    int i, j, *s;
453
454    assert( gFd == NULL );
455
456    gFd = tr_new0( struct tr_fd_s, 1 );
457    gFd->lock = tr_lockNew( );
458
459    s = tr_new( int, globalPeerLimit );
460
461    /* count the max number of sockets we can use */
462    for( i=0; i<globalPeerLimit; ++i )
463        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
464            break;
465    for( j=0; j<i; ++j )
466        socketClose( s[j] );
467    tr_dbg( "%d usable file descriptors", i );
468
469    /* set some fds aside for the UI or daemon to use */
470    gFd->normalMax = i - TR_RESERVED_FDS - 10;
471
472    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
473        gFd->open[i].fd = -1;
474
475    tr_free( s );
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}
492
493void
494tr_fdSetPeerLimit( uint16_t n )
495{
496    assert( gFd!=NULL && "tr_fdInit() must be called first!" );
497    gFd->normalMax = n;
498}
499
500uint16_t
501tr_fdGetPeerLimit( void )
502{
503    return gFd ? gFd->normalMax : -1;
504}
Note: See TracBrowser for help on using the repository browser.