source: trunk/libtransmission/fdlimit.c @ 7543

Last change on this file since 7543 was 7543, checked in by charles, 12 years ago

(trunk libT) eliminate a couple more unnecessary malloc() + free() pairs

  • Property svn:keywords set to Date Rev Author Id
File size: 14.0 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 7543 2008-12-30 03:29:09Z charles $
3 *
4 * Copyright (c) 2005-2008 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#ifndef WIN32
26 #define HAVE_GETRLIMIT
27#endif
28
29#include <assert.h>
30#include <errno.h>
31#include <inttypes.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#ifdef SYS_DARWIN
36#include <fcntl.h>
37#endif
38
39#ifdef HAVE_FALLOCATE
40 #include <linux/falloc.h>
41#endif
42
43#include <sys/types.h>
44#include <sys/stat.h>
45#ifdef HAVE_GETRLIMIT
46 #include <sys/time.h> /* getrlimit */
47 #include <sys/resource.h> /* getrlimit */
48#endif
49#include <unistd.h>
50#include <fcntl.h> /* O_LARGEFILE */
51
52#include <event.h>
53#include <evutil.h>
54
55#include "transmission.h"
56#include "fdlimit.h"
57#include "list.h"
58#include "net.h"
59#include "platform.h" /* tr_lock */
60#include "utils.h"
61
62#define dbgmsg( ... ) \
63    do { \
64        if( tr_deepLoggingIsActive( ) ) \
65            tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \
66    } while( 0 )
67
68/**
69***
70**/
71
72enum
73{
74    TR_MAX_OPEN_FILES = 16, /* real files, not sockets */
75
76    NOFILE_BUFFER = 512, /* the process' number of open files is
77                            globalMaxPeers + NOFILE_BUFFER */
78};
79
80struct tr_openfile
81{
82    tr_bool    isCheckedOut;
83    tr_bool    isWritable;
84    tr_bool    closeWhenDone;
85    char       filename[MAX_PATH_LENGTH];
86    int        fd;
87    uint64_t   date;
88};
89
90struct tr_fd_s
91{
92    int                   socketCount;
93    int                   socketMax;
94    tr_lock *             lock;
95    struct tr_openfile    open[TR_MAX_OPEN_FILES];
96};
97
98static struct tr_fd_s * gFd = NULL;
99
100/***
101****
102****  Local Files
103****
104***/
105
106#ifndef O_LARGEFILE
107#define O_LARGEFILE 0
108#endif
109
110static int
111preallocateFile( const char * filename, uint64_t length )
112{
113    int success = 0;
114
115#ifdef WIN32
116
117    HANDLE hFile = CreateFile( filename, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0 );
118    if( hFile != INVALID_HANDLE_VALUE )
119    {
120        LARGE_INTEGER li;
121        li.QuadPart = length;
122        success = SetFilePointerEx( hFile, li, NULL, FILE_BEGIN ) && SetEndOfFile( hFile );
123        CloseHandle( hFile );
124    }
125
126#else
127
128    int flags = O_RDWR | O_CREAT | O_LARGEFILE;
129    int fd = open( filename, flags, 0666 );
130    if( fd >= 0 )
131    {
132       
133# ifdef HAVE_FALLOCATE
134
135        success = !fallocate( fd, FALLOC_FL_KEEP_SIZE, 0, length );
136
137# elif defined(HAVE_POSIX_FALLOCATE)
138
139        success = !posix_fallocate( fd, 0, length );
140
141# elif defined(SYS_DARWIN)
142
143        fstore_t fst;
144        fst.fst_flags = F_ALLOCATECONTIG;
145        fst.fst_posmode = F_PEOFPOSMODE;
146        fst.fst_offset = 0;
147        fst.fst_length = length;
148        fst.fst_bytesalloc = 0;
149        success = !fcntl( fd, F_PREALLOCATE, &fst );
150
151# else
152
153        #warning no known method to preallocate files on this platform
154        success = 0;
155
156# endif
157
158        close( fd );
159    }
160
161#endif
162
163    return success;
164}
165
166/**
167 * returns 0 on success, or an errno value on failure.
168 * errno values include ENOENT if the parent folder doesn't exist,
169 * plus the errno values set by tr_mkdirp() and open().
170 */
171static int
172TrOpenFile( int          i,
173            const char * folder,
174            const char * torrentFile,
175            int          doWrite,
176            int          doPreallocate,
177            uint64_t     desiredFileSize )
178{
179    struct tr_openfile * file = &gFd->open[i];
180    int                  flags;
181    char               * filename;
182    struct stat          sb;
183    int                  alreadyExisted;
184
185    /* confirm the parent folder exists */
186    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
187        return ENOENT;
188
189    /* create subfolders, if any */
190    filename = tr_buildPath( folder, torrentFile, NULL );
191    if( doWrite )
192    {
193        char * tmp = tr_dirname( filename );
194        const int err = tr_mkdirp( tmp, 0777 ) ? errno : 0;
195        tr_free( tmp );
196        if( err ) {
197            tr_free( filename );
198            return err;
199        }
200    }
201
202    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
203
204    if( doWrite && !alreadyExisted && doPreallocate )
205        if( preallocateFile( filename, desiredFileSize ) )
206            tr_inf( _( "Preallocated file \"%s\"" ), filename );
207   
208    /* open the file */
209    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
210#ifdef O_LARGEFILE
211    flags |= O_LARGEFILE;
212#endif
213#ifdef WIN32
214    flags |= O_BINARY;
215#endif
216    file->fd = open( filename, flags, 0666 );
217    if( file->fd == -1 )
218    {
219        const int err = errno;
220        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename,
221               tr_strerror( err ) );
222        tr_free( filename );
223        return err;
224    }
225
226    tr_free( filename );
227    return 0;
228}
229
230static int
231fileIsOpen( const struct tr_openfile * o )
232{
233    return o->fd >= 0;
234}
235
236static void
237TrCloseFile( int i )
238{
239    struct tr_openfile * o = &gFd->open[i];
240
241    assert( i >= 0 );
242    assert( i < TR_MAX_OPEN_FILES );
243    assert( fileIsOpen( o ) );
244
245    close( o->fd );
246    o->fd = -1;
247    o->isCheckedOut = 0;
248}
249
250static int
251fileIsCheckedOut( const struct tr_openfile * o )
252{
253    return fileIsOpen( o ) && o->isCheckedOut;
254}
255
256/* returns an fd on success, or a -1 on failure and sets errno */
257int
258tr_fdFileCheckout( const char * folder,
259                   const char * torrentFile,
260                   int          doWrite,
261                   int          doPreallocate,
262                   uint64_t     desiredFileSize )
263{
264    int i, winner = -1;
265    struct tr_openfile * o;
266    char filename[MAX_PATH_LENGTH];
267
268    assert( folder && *folder );
269    assert( torrentFile && *torrentFile );
270    assert( doWrite == 0 || doWrite == 1 );
271
272    tr_snprintf( filename, sizeof( filename ), "%s%c%s", folder, TR_PATH_DELIMITER, torrentFile );
273    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
274
275    tr_lockLock( gFd->lock );
276
277    /* Is it already open? */
278    for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
279    {
280        o = &gFd->open[i];
281
282        if( !fileIsOpen( o ) )
283            continue;
284
285        if( strcmp( filename, o->filename ) )
286            continue;
287
288        if( fileIsCheckedOut( o ) )
289        {
290            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
291            tr_lockUnlock( gFd->lock );
292            tr_wait( 200 );
293            tr_lockLock( gFd->lock );
294            i = -1; /* reloop */
295            continue;
296        }
297
298        if( doWrite && !o->isWritable )
299        {
300            dbgmsg(
301                "found it!  it's open and available, but isn't writable. closing..." );
302            TrCloseFile( i );
303            break;
304        }
305
306        dbgmsg( "found it!  it's ready for use!" );
307        winner = i;
308        break;
309    }
310
311    dbgmsg(
312        "it's not already open.  looking for an open slot or an old file." );
313    while( winner < 0 )
314    {
315        uint64_t date = tr_date( ) + 1;
316
317        /* look for the file that's been open longest */
318        for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
319        {
320            o = &gFd->open[i];
321
322            if( !fileIsOpen( o ) )
323            {
324                winner = i;
325                dbgmsg( "found an empty slot in %d", winner );
326                break;
327            }
328
329            if( date > o->date )
330            {
331                date = o->date;
332                winner = i;
333            }
334        }
335
336        if( winner >= 0 )
337        {
338            if( fileIsOpen( &gFd->open[winner] ) )
339            {
340                dbgmsg( "closing file '%s', slot #%d",
341                        gFd->open[winner].filename,
342                        winner );
343                TrCloseFile( winner );
344            }
345        }
346        else
347        {
348            dbgmsg(
349                "everything's full!  waiting for someone else to finish something" );
350            tr_lockUnlock( gFd->lock );
351            tr_wait( 200 );
352            tr_lockLock( gFd->lock );
353        }
354    }
355
356    assert( winner >= 0 );
357    o = &gFd->open[winner];
358    if( !fileIsOpen( o ) )
359    {
360        const int err = TrOpenFile( winner, folder, torrentFile, doWrite, doPreallocate, desiredFileSize );
361        if( err ) {
362            tr_lockUnlock( gFd->lock );
363            errno = err;
364            return -1;
365        }
366
367        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
368                doWrite ? 'y' : 'n' );
369        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
370        o->isWritable = doWrite;
371    }
372
373    dbgmsg( "checking out '%s' in slot %d", filename, winner );
374    o->isCheckedOut = 1;
375    o->closeWhenDone = 0;
376    o->date = tr_date( );
377    tr_lockUnlock( gFd->lock );
378    return o->fd;
379}
380
381void
382tr_fdFileReturn( int fd )
383{
384    int i;
385
386    tr_lockLock( gFd->lock );
387
388    for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
389    {
390        struct tr_openfile * o = &gFd->open[i];
391        if( o->fd != fd )
392            continue;
393
394        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
395        o->isCheckedOut = 0;
396        if( o->closeWhenDone )
397            TrCloseFile( i );
398
399        break;
400    }
401
402    tr_lockUnlock( gFd->lock );
403}
404
405void
406tr_fdFileClose( const char * filename )
407{
408    int i;
409
410    tr_lockLock( gFd->lock );
411
412    for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
413    {
414        struct tr_openfile * o = &gFd->open[i];
415        if( !fileIsOpen( o ) || strcmp( filename, o->filename ) )
416            continue;
417
418        dbgmsg( "tr_fdFileClose closing '%s'", filename );
419
420        if( !o->isCheckedOut )
421        {
422            dbgmsg( "not checked out, so closing it now... '%s'", filename );
423            TrCloseFile( i );
424        }
425        else
426        {
427            dbgmsg(
428                "flagging file '%s', slot #%d to be closed when checked in",
429                gFd->open[i].filename, i );
430            o->closeWhenDone = 1;
431        }
432    }
433
434    tr_lockUnlock( gFd->lock );
435}
436
437/***
438****
439****  Sockets
440****
441***/
442
443static int
444getSocketMax( struct tr_fd_s * gFd )
445{
446    return gFd->socketMax;
447}
448
449int
450tr_fdSocketCreate( int domain, int type )
451{
452    int s = -1;
453
454    tr_lockLock( gFd->lock );
455
456    if( gFd->socketCount < getSocketMax( gFd ) )
457        if( ( s = socket( domain, type, 0 ) ) < 0 )
458        {
459#ifdef SYS_DARWIN
460            if( sockerrno != EAFNOSUPPORT )
461#endif
462            tr_err( _( "Couldn't create socket: %s" ),
463                   tr_strerror( sockerrno ) );
464            s = -sockerrno;
465        }
466
467    if( s > -1 )
468        ++gFd->socketCount;
469
470    assert( gFd->socketCount >= 0 );
471
472    tr_lockUnlock( gFd->lock );
473    return s;
474}
475
476int
477tr_fdSocketAccept( int           b,
478                   tr_address  * addr,
479                   tr_port     * port )
480{
481    int                s = -1;
482    unsigned int       len;
483    struct sockaddr_storage sock;
484
485    assert( addr );
486    assert( port );
487
488    tr_lockLock( gFd->lock );
489    if( gFd->socketCount < getSocketMax( gFd ) )
490    {
491        len = sizeof( struct sockaddr_storage );
492        s = accept( b, (struct sockaddr *) &sock, &len );
493    }
494    if( s > -1 )
495    {
496        /* "The ss_family field of the sockaddr_storage structure will always
497         * align with the family field of any protocol-specific structure." */ 
498        if( sock.ss_family == AF_INET ) 
499        { 
500            struct sockaddr_in * sock4 = (struct sockaddr_in *)&sock; 
501            addr->type = TR_AF_INET; 
502            addr->addr.addr4.s_addr = sock4->sin_addr.s_addr; 
503            *port = sock4->sin_port; 
504        } 
505        else 
506        { 
507            struct sockaddr_in6 * sock6 = (struct sockaddr_in6 *)&sock; 
508            addr->type = TR_AF_INET6; 
509            addr->addr.addr6 = sock6->sin6_addr;
510            *port = sock6->sin6_port; 
511        } 
512        ++gFd->socketCount;
513    }
514    tr_lockUnlock( gFd->lock );
515
516    return s;
517}
518
519static void
520socketClose( int fd )
521{
522    EVUTIL_CLOSESOCKET( fd );
523}
524
525void
526tr_fdSocketClose( int s )
527{
528    tr_lockLock( gFd->lock );
529
530    if( s >= 0 )
531    {
532        socketClose( s );
533        --gFd->socketCount;
534    }
535
536    assert( gFd->socketCount >= 0 );
537
538    tr_lockUnlock( gFd->lock );
539}
540
541/***
542****
543****  Startup / Shutdown
544****
545***/
546
547void
548tr_fdInit( int globalPeerLimit )
549{
550    int i;
551
552    assert( gFd == NULL );
553    gFd = tr_new0( struct tr_fd_s, 1 );
554    gFd->lock = tr_lockNew( );
555
556#ifdef HAVE_GETRLIMIT
557    {
558        struct rlimit rlim;
559        getrlimit( RLIMIT_NOFILE, &rlim );
560        rlim.rlim_cur = MIN( rlim.rlim_max,
561                            (rlim_t)( globalPeerLimit + NOFILE_BUFFER ) );
562        setrlimit( RLIMIT_NOFILE, &rlim );
563        gFd->socketMax = rlim.rlim_cur - NOFILE_BUFFER;
564        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
565    }
566#else
567    gFd->socketMax = globalPeerLimit;
568#endif
569    tr_dbg( "%d usable file descriptors", globalPeerLimit );
570
571    for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
572        gFd->open[i].fd = -1;
573}
574
575void
576tr_fdClose( void )
577{
578    int i = 0;
579
580    for( i = 0; i < TR_MAX_OPEN_FILES; ++i )
581        if( fileIsOpen( &gFd->open[i] ) )
582            TrCloseFile( i );
583
584    tr_lockFree( gFd->lock );
585
586    tr_free( gFd );
587    gFd = NULL;
588}
589
590void
591tr_fdSetPeerLimit( uint16_t n )
592{
593    assert( gFd != NULL && "tr_fdInit() must be called first!" );
594    gFd->socketMax = n;
595}
596
597uint16_t
598tr_fdGetPeerLimit( void )
599{
600    return gFd ? gFd->socketMax : -1;
601}
602
Note: See TracBrowser for help on using the repository browser.