source: trunk/libtransmission/fdlimit.c @ 2331

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

add #include files for stat()

  • Property svn:keywords set to Date Rev Author Id
File size: 13.6 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 2331 2007-07-13 00:15:45Z 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 <fcntl.h>
26#include <sys/types.h>
27#include <sys/stat.h>
28#include <unistd.h>
29#include "transmission.h"
30
31#define TR_MAX_OPEN_FILES 16 /* That is, real files, not sockets */
32#define TR_RESERVED_FDS   16 /* Number of sockets reserved for
33                                connections to trackers */
34
35/***********************************************************************
36 * Structures
37 **********************************************************************/
38typedef struct tr_openFile_s
39{
40    char       folder[MAX_PATH_LENGTH];
41    char       name[MAX_PATH_LENGTH];
42    int        file;
43    int        write;
44
45#define STATUS_INVALID 1
46#define STATUS_UNUSED  2
47#define STATUS_USED    4
48#define STATUS_CLOSING 8
49    int        status;
50
51    uint64_t   date;
52}
53tr_openFile_t;
54
55typedef struct tr_fd_s
56{
57    tr_lock_t       lock;
58    tr_cond_t       cond;
59   
60    int             reserved;
61
62    int             normal;
63    int             normalMax;
64
65    tr_openFile_t   open[TR_MAX_OPEN_FILES];
66}
67tr_fd_t;
68
69static tr_fd_t * gFd = NULL;
70
71/***********************************************************************
72 * Local prototypes
73 **********************************************************************/
74static int  OpenFile( int i, const char * folder, const char * name, int write );
75static void CloseFile( int i );
76
77
78/***********************************************************************
79 * tr_fdInit
80 **********************************************************************/
81void tr_fdInit()
82{
83    int i, j, s[4096];
84
85    if( gFd )
86    {
87        tr_err( "tr_fdInit was called before!" );
88        return;
89    }
90
91    gFd = calloc( 1, sizeof( tr_fd_t ) );
92
93    /* Init lock and cond */
94    tr_lockInit( &gFd->lock );
95    tr_condInit( &gFd->cond );
96
97    /* Detect the maximum number of open files or sockets */
98    for( i = 0; i < 4096; i++ )
99    {
100        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
101        {
102            break;
103        }
104    }
105    for( j = 0; j < i; j++ )
106    {
107#ifdef BEOS_NETSERVER
108            closesocket( s[j] );
109#else
110            close( s[j] );
111#endif
112    }
113
114    tr_dbg( "%d usable file descriptors", i );
115
116    gFd->reserved  = 0;
117    gFd->normal    = 0;
118
119    gFd->normalMax = i - TR_RESERVED_FDS - 10;
120        /* To be safe, in case the UI needs to write a preferences file
121           or something */
122
123    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
124    {
125        gFd->open[i].status = STATUS_INVALID;
126    }
127}
128
129/***********************************************************************
130 * tr_fdFileOpen
131 **********************************************************************/
132int tr_fdFileOpen( const char * folder, const char * name, int write )
133{
134    int i, winner, ret;
135    uint64_t date;
136
137    tr_lockLock( &gFd->lock );
138
139    /* Is it already open? */
140    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
141    {
142        if( gFd->open[i].status & STATUS_INVALID ||
143            strcmp( folder, gFd->open[i].folder ) ||
144            strcmp( name, gFd->open[i].name ) )
145        {
146            continue;
147        }
148        if( gFd->open[i].status & STATUS_CLOSING )
149        {
150            /* File is being closed by another thread, wait until
151             * it's done before we reopen it */
152            tr_condWait( &gFd->cond, &gFd->lock );
153            i = -1;
154            continue;
155        }
156        if( gFd->open[i].write < write )
157        {
158            /* File is open read-only and needs to be closed then
159             * re-opened read-write */
160            CloseFile( i );
161            continue;
162        }
163        winner = i;
164        goto done;
165    }
166
167    /* Can we open one more file? */
168    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
169    {
170        if( gFd->open[i].status & STATUS_INVALID )
171        {
172            winner = i;
173            goto open;
174        }
175    }
176
177    /* All slots taken - close the oldest currently unused file */
178    for( ;; )
179    {
180        date   = tr_date() + 1;
181        winner = -1;
182
183        for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
184        {
185            if( !( gFd->open[i].status & STATUS_UNUSED ) )
186            {
187                continue;
188            }
189            if( gFd->open[i].date < date )
190            {
191                winner = i;
192                date   = gFd->open[i].date;
193            }
194        }
195
196        if( winner >= 0 )
197        {
198            CloseFile( winner );
199            goto open;
200        }
201
202        /* All used! Wait a bit and try again */
203        tr_condWait( &gFd->cond, &gFd->lock );
204    }
205
206open:
207    if( ( ret = OpenFile( winner, folder, name, write ) ) )
208    {
209        tr_lockUnlock( &gFd->lock );
210        return ret;
211    }
212    snprintf( gFd->open[winner].folder, MAX_PATH_LENGTH, "%s", folder );
213    snprintf( gFd->open[winner].name, MAX_PATH_LENGTH, "%s", name );
214    gFd->open[winner].write = write;
215
216done:
217    gFd->open[winner].status = STATUS_USED;
218    gFd->open[winner].date   = tr_date();
219    tr_lockUnlock( &gFd->lock );
220   
221    return gFd->open[winner].file;
222}
223
224/***********************************************************************
225 * tr_fdFileRelease
226 **********************************************************************/
227void tr_fdFileRelease( int file )
228{
229    int i;
230    tr_lockLock( &gFd->lock );
231
232    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
233    {
234        if( gFd->open[i].file == file )
235        {
236            gFd->open[i].status = STATUS_UNUSED;
237            break;
238        }
239    }
240   
241    tr_condSignal( &gFd->cond );
242    tr_lockUnlock( &gFd->lock );
243}
244
245/***********************************************************************
246 * tr_fdFileClose
247 **********************************************************************/
248void tr_fdFileClose( const char * folder, const char * name )
249{
250    int i;
251
252    tr_lockLock( &gFd->lock );
253
254    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
255    {
256        if( gFd->open[i].status & STATUS_INVALID )
257        {
258            continue;
259        }
260        if( !strcmp( folder, gFd->open[i].folder ) &&
261            !strcmp( name, gFd->open[i].name ) )
262        {
263            CloseFile( i );
264        }
265    }
266
267    tr_lockUnlock( &gFd->lock );
268}
269
270
271/***********************************************************************
272 * Sockets
273 **********************************************************************/
274typedef struct
275{
276    int socket;
277    int priority;
278}
279tr_socket_t;
280
281/* Remember the priority of every socket we open, so that we can keep
282 * track of how many reserved file descriptors we are using */
283static tr_socket_t * gSockets = NULL;
284static int gSocketsSize = 0;
285static int gSocketsCount = 0;
286static void SocketSetPriority( int s, int priority )
287{
288    if( gSocketsSize < 1 )
289    {
290        gSocketsSize = 256;
291        gSockets = malloc( gSocketsSize * sizeof( tr_socket_t ) );
292    }
293    if( gSocketsSize <= gSocketsCount )
294    {
295        gSocketsSize *= 2;
296        gSockets = realloc( gSockets, gSocketsSize * sizeof( tr_socket_t ) );
297    }
298    gSockets[gSocketsCount].socket = s;
299    gSockets[gSocketsCount].priority = priority;
300    gSocketsCount++;
301}
302static int SocketGetPriority( int s )
303{
304    int i, ret;
305    for( i = 0; i < gSocketsCount; i++ )
306        if( gSockets[i].socket == s )
307            break;
308    if( i >= gSocketsCount )
309    {
310        tr_err( "could not find that socket (%d)!", s );
311        return -1;
312    }
313    ret = gSockets[i].priority;
314    gSocketsCount--;
315    memmove( &gSockets[i], &gSockets[i+1],
316            ( gSocketsCount - i ) * sizeof( tr_socket_t ) );
317    return ret;
318}
319
320/***********************************************************************
321 * tr_fdSocketCreate
322 **********************************************************************/
323int tr_fdSocketCreate( int type, int priority )
324{
325    int s = -1;
326
327    tr_lockLock( &gFd->lock );
328    if( ( priority && gFd->reserved < TR_RESERVED_FDS ) ||
329        ( !priority && gFd->normal < gFd->normalMax ) )
330    {
331       if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
332       {
333           tr_err( "Could not create socket (%s)", strerror( errno ) );
334       }
335    }
336    if( s > -1 )
337    {
338        SocketSetPriority( s, priority );
339        if( priority )
340            gFd->reserved++;
341        else
342            gFd->normal++;
343    }
344    tr_lockUnlock( &gFd->lock );
345
346    return s;
347}
348
349int tr_fdSocketAccept( int b, struct in_addr * addr, in_port_t * port )
350{
351    int s = -1;
352    unsigned len;
353    struct sockaddr_in sock;
354
355    tr_lockLock( &gFd->lock );
356    if( gFd->normal < gFd->normalMax )
357    {
358        len = sizeof( sock );
359        s = accept( b, (struct sockaddr *) &sock, &len );
360    }
361    if( s > -1 )
362    {
363        SocketSetPriority( s, 0 );
364        if( NULL != addr )
365        {
366            *addr = sock.sin_addr;
367        }
368        if( NULL != port )
369        {
370            *port = sock.sin_port;
371        }
372        gFd->normal++;
373    }
374    tr_lockUnlock( &gFd->lock );
375
376    return s;
377}
378
379/***********************************************************************
380 * tr_fdSocketClose
381 **********************************************************************/
382void tr_fdSocketClose( int s )
383{
384    tr_lockLock( &gFd->lock );
385#ifdef BEOS_NETSERVER
386    closesocket( s );
387#else
388    close( s );
389#endif
390    if( SocketGetPriority( s ) )
391        gFd->reserved--;
392    else
393        gFd->normal--;
394    tr_lockUnlock( &gFd->lock );
395}
396
397/***********************************************************************
398 * tr_fdClose
399 **********************************************************************/
400void tr_fdClose()
401{
402    tr_lockClose( &gFd->lock );
403    tr_condClose( &gFd->cond );
404    free( gFd );
405}
406
407
408/***********************************************************************
409 * Local functions
410 **********************************************************************/
411
412/***********************************************************************
413 * CheckFolder
414 ***********************************************************************
415 *
416 **********************************************************************/
417static int OpenFile( int i, const char * folder, const char * name, int write )
418{
419    tr_openFile_t * file = &gFd->open[i];
420    struct stat sb;
421    char path[MAX_PATH_LENGTH];
422    int ret;
423
424    tr_dbg( "Opening %s in %s (%d)", name, folder, write );
425
426    /* Make sure the parent folder exists */
427    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
428    {
429        return TR_ERROR_IO_PARENT;
430    }
431
432    snprintf( path, sizeof(path), "%s" TR_PATH_DELIMITER_STR "%s",
433              folder,
434              name );
435
436    /* Create subfolders, if any */
437    if( write )
438    {
439        char * p = path + strlen( folder ) + 1;
440        char * s;
441
442        while( ( s = strchr( p, '/' ) ) )
443        {
444            *s = '\0';
445            if( stat( path, &sb ) )
446            {
447                if( mkdir( path, 0777 ) )
448                {
449                    ret = tr_ioErrorFromErrno();
450                    tr_err( "Could not create folder '%s'", path );
451                    return ret;
452                }
453            }
454            else
455            {
456                if( !S_ISDIR( sb.st_mode ) )
457                {
458                    tr_err( "Is not a folder: '%s'", path );
459                    return TR_ERROR_IO_OTHER;
460                }
461            }
462            *s = '/';
463            p = s + 1;
464        }
465    }
466
467    /* Now try to really open the file */
468    file->file = open( path, write ? ( O_RDWR | O_CREAT ) : O_RDONLY, 0666 );
469    if( file->file < 0 )
470    {
471        ret = tr_ioErrorFromErrno();
472        tr_err( "Could not open %s in %s (%d, %d)", name, folder, write, ret );
473        return ret;
474    }
475
476    return TR_OK;
477}
478
479/***********************************************************************
480 * CloseFile
481 ***********************************************************************
482 * We first mark it as closing then release the lock while doing so,
483 * because close() may take same time and we don't want to block other
484 * threads.
485 **********************************************************************/
486static void CloseFile( int i )
487{
488    tr_openFile_t * file = &gFd->open[i];
489
490    /* If it's already being closed by another thread, just wait till
491     * it is done */
492    while( file->status & STATUS_CLOSING )
493    {
494        tr_condWait( &gFd->cond, &gFd->lock );
495    }
496    if( file->status & STATUS_INVALID )
497    {
498        return;
499    }
500
501    /* Nobody is closing it already, so let's do it */
502    if( file->status & STATUS_USED )
503    {
504        tr_err( "CloseFile: closing a file that's being used!" );
505    }
506    tr_dbg( "Closing %s in %s (%d)", file->name, file->folder, file->write );
507    file->status = STATUS_CLOSING;
508    tr_lockUnlock( &gFd->lock );
509    close( file->file );
510    tr_lockLock( &gFd->lock );
511    file->status = STATUS_INVALID;
512    tr_condSignal( &gFd->cond );
513}
514
Note: See TracBrowser for help on using the repository browser.