~ubuntu-branches/ubuntu/jaunty/transmission/jaunty-security

« back to all changes in this revision

Viewing changes to libtransmission/fdlimit.c

  • Committer: Bazaar Package Importer
  • Author(s): Philipp Benner
  • Date: 2007-11-22 12:37:14 UTC
  • mfrom: (1.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20071122123714-b0xi4zxhgk5qwbmc
Tags: 0.93.dfsg-2
* Added missing build-dependency (python).
* debian/control: switching to Homepage, Vcs-Browser and Vcs-Svn official
  fields (Leo "costela" Antunes)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/******************************************************************************
2
 
 * $Id: fdlimit.c 3171 2007-09-25 23:10:34Z charles $
 
2
 * $Id: fdlimit.c 3811 2007-11-12 15:22:20Z charles $
3
3
 *
4
4
 * Copyright (c) 2005-2006 Transmission authors and contributors
5
5
 *
24
24
 
25
25
#include <assert.h>
26
26
#include <errno.h>
 
27
#include <inttypes.h>
27
28
#include <stdio.h>
28
29
#include <stdlib.h>
29
30
#include <string.h>
31
32
#include <sys/types.h>
32
33
#include <sys/stat.h>
33
34
#include <unistd.h>
34
 
#include <fcntl.h>
 
35
#include <libgen.h> /* basename, dirname */
 
36
#include <fcntl.h> /* O_LARGEFILE */
35
37
 
 
38
#include <sys/queue.h> /* libevent needs this */
 
39
#include <sys/types.h> /* libevent needs this */
 
40
#include <event.h>
 
41
#include <evhttp.h>
36
42
#include <evutil.h>
37
43
 
38
44
#include "transmission.h"
 
45
#include "trcompat.h"
 
46
#include "list.h"
39
47
#include "net.h"
40
48
#include "platform.h"
41
49
#include "utils.h"
42
50
 
43
 
#define TR_MAX_OPEN_FILES 16 /* That is, real files, not sockets */
44
 
#define TR_RESERVED_FDS   16 /* Number of sockets reserved for
45
 
                                connections to trackers */
46
 
 
47
 
/***********************************************************************
48
 
 * Structures
49
 
 **********************************************************************/
50
 
typedef struct tr_openFile_s
51
 
{
52
 
    char       folder[MAX_PATH_LENGTH];
53
 
    char       name[MAX_PATH_LENGTH];
54
 
    int        file;
55
 
    int        write;
56
 
 
57
 
#define STATUS_INVALID 1
58
 
#define STATUS_UNUSED  2
59
 
#define STATUS_USED    4
60
 
#define STATUS_CLOSING 8
61
 
    int        status;
62
 
 
63
 
    uint64_t   date;
64
 
}
65
 
tr_openFile_t;
66
 
 
67
 
typedef struct tr_fd_s
68
 
{
69
 
    tr_lock       * lock;
70
 
    tr_cond       * cond;
71
 
    
72
 
    int             reserved;
73
 
 
74
 
    int             normal;
75
 
    int             normalMax;
76
 
 
77
 
    tr_openFile_t   open[TR_MAX_OPEN_FILES];
78
 
}
79
 
tr_fd_t;
80
 
 
81
 
static tr_fd_t * gFd = NULL;
82
 
 
83
 
/***********************************************************************
84
 
 * Local prototypes
85
 
 **********************************************************************/
86
 
static int  TrOpenFile( int i, const char * folder, const char * name, int write );
87
 
static void TrCloseFile( int i );
88
 
 
89
 
 
90
 
/***********************************************************************
91
 
 * tr_fdInit
92
 
 **********************************************************************/
93
 
void tr_fdInit( void )
94
 
{
95
 
    int i, j, s[4096];
96
 
 
97
 
    if( gFd )
98
 
    {
99
 
        tr_err( "tr_fdInit was called before!" );
100
 
        return;
101
 
    }
102
 
 
103
 
    gFd = calloc( 1, sizeof( tr_fd_t ) );
104
 
 
105
 
    /* Init lock and cond */
106
 
    gFd->lock = tr_lockNew( );
107
 
    gFd->cond = tr_condNew( );
108
 
 
109
 
    /* Detect the maximum number of open files or sockets */
110
 
    for( i = 0; i < 4096; i++ )
111
 
    {
112
 
        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
113
 
        {
114
 
            break;
 
51
#if SIZEOF_VOIDP==8
 
52
#define TR_UINT_TO_PTR(i) (void*)((uint64_t)i)
 
53
#else
 
54
#define TR_UINT_TO_PTR(i) ((void*)((uint32_t)i))
 
55
#endif
 
56
 
 
57
/**
 
58
***
 
59
**/
 
60
 
 
61
static void
 
62
myDebug( const char * file, int line, const char * fmt, ... )
 
63
{
 
64
    FILE * fp = tr_getLog( );
 
65
    if( fp != NULL )
 
66
    {
 
67
        va_list args;
 
68
        char s[64];
 
69
        struct evbuffer * buf = evbuffer_new( );
 
70
        char * myfile = tr_strdup( file );
 
71
 
 
72
        evbuffer_add_printf( buf, "[%s] ", tr_getLogTimeStr( s, sizeof(s) ) );
 
73
        va_start( args, fmt );
 
74
        evbuffer_add_vprintf( buf, fmt, args );
 
75
        va_end( args );
 
76
        evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line );
 
77
        fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp );
 
78
 
 
79
        tr_free( myfile );
 
80
        evbuffer_free( buf );
 
81
    }
 
82
}
 
83
 
 
84
#define dbgmsg(fmt...) myDebug(__FILE__, __LINE__, ##fmt )
 
85
 
 
86
/**
 
87
***
 
88
**/
 
89
 
 
90
enum
 
91
{
 
92
    TR_MAX_SOCKETS = 512,
 
93
 
 
94
    TR_MAX_OPEN_FILES = 16, /* real files, not sockets */
 
95
 
 
96
    TR_RESERVED_FDS   = 16 /* sockets reserved for tracker connections */
 
97
};
 
98
 
 
99
struct tr_openfile
 
100
{
 
101
    unsigned int  isCheckedOut : 1;
 
102
    unsigned int  isWritable : 1;
 
103
    char          filename[MAX_PATH_LENGTH];
 
104
    int           fd;
 
105
    uint64_t      date;
 
106
};
 
107
 
 
108
struct tr_fd_s
 
109
{
 
110
    int                  reserved;
 
111
    int                  normal;
 
112
    int                  normalMax;
 
113
    tr_lock            * lock;
 
114
    tr_cond            * cond;
 
115
    struct tr_openfile   open[TR_MAX_OPEN_FILES];
 
116
};
 
117
 
 
118
static struct tr_fd_s * gFd = NULL;
 
119
 
 
120
/***
 
121
****
 
122
****  Local Files
 
123
****
 
124
***/
 
125
 
 
126
static int
 
127
TrOpenFile( int i, const char * filename, int write )
 
128
{
 
129
    struct tr_openfile * file = &gFd->open[i];
 
130
    int flags;
 
131
 
 
132
    tr_dbg( "Opening '%s' (%d)", filename, write );
 
133
 
 
134
    /* create subfolders, if any */
 
135
    if( write ) {
 
136
        char * tmp = tr_strdup( filename );
 
137
        const int val = tr_mkdirp( dirname(tmp), 0700 );
 
138
        tr_free( tmp );
 
139
        if( val )
 
140
            return tr_ioErrorFromErrno( );
 
141
    }
 
142
 
 
143
    /* open the file */
 
144
    flags = write ? (O_RDWR | O_CREAT) : O_RDONLY;
 
145
#ifdef O_LARGEFILE
 
146
    flags |= O_LARGEFILE;
 
147
#endif
 
148
#ifdef WIN32
 
149
    flags |= O_BINARY;
 
150
#endif
 
151
    errno = 0;
 
152
    file->fd = open( filename, flags, 0600 );
 
153
    if( file->fd < 0 ) {
 
154
        if( errno ) {
 
155
            tr_err( "Couldn't open '%s': %s", filename, strerror(errno) );
 
156
            return tr_ioErrorFromErrno();
 
157
        } else {
 
158
            tr_err( "Couldn't open '%s'", filename );
 
159
            return TR_ERROR_IO_OTHER;
115
160
        }
116
161
    }
117
 
    for( j = 0; j < i; j++ )
118
 
    {
119
 
#ifdef BEOS_NETSERVER
120
 
        closesocket( s[j] );
121
 
#else
122
 
        EVUTIL_CLOSESOCKET( s[j] );
123
 
#endif
124
 
    }
125
 
 
126
 
    tr_dbg( "%d usable file descriptors", i );
127
 
 
128
 
    gFd->reserved  = 0;
129
 
    gFd->normal    = 0;
130
 
 
131
 
    gFd->normalMax = i - TR_RESERVED_FDS - 10;
132
 
        /* To be safe, in case the UI needs to write a preferences file
133
 
           or something */
134
 
 
135
 
    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
136
 
    {
137
 
        gFd->open[i].status = STATUS_INVALID;
138
 
    }
139
 
}
140
 
 
141
 
/***********************************************************************
142
 
 * tr_fdFileOpen
143
 
 **********************************************************************/
144
 
int tr_fdFileOpen( const char * folder, const char * name, int write )
145
 
{
146
 
    int i, winner, ret;
147
 
    uint64_t date;
 
162
 
 
163
    return TR_OK;
 
164
}
 
165
 
 
166
static int
 
167
fileIsOpen( const struct tr_openfile * o )
 
168
{
 
169
    return o->fd >= 0;
 
170
}
 
171
 
 
172
static void
 
173
TrCloseFile( int i )
 
174
{
 
175
    struct tr_openfile * o = &gFd->open[i];
 
176
 
 
177
    assert( i >= 0 );
 
178
    assert( i < TR_MAX_OPEN_FILES );
 
179
    assert( fileIsOpen( o ) );
 
180
 
 
181
    dbgmsg( "closing slot #%d, %s", i, o->filename );
 
182
    close( o->fd );
 
183
    o->fd = -1;
 
184
    o->isCheckedOut = 0;
 
185
    tr_condSignal( gFd->cond );
 
186
}
 
187
 
 
188
static int
 
189
fileIsCheckedOut( const struct tr_openfile * o )
 
190
{
 
191
    return fileIsOpen(o) && o->isCheckedOut;
 
192
}
 
193
 
 
194
int
 
195
tr_fdFileOpen( const char * filename, int write )
 
196
{
 
197
    int i, winner;
 
198
    struct tr_openfile * o;
 
199
 
 
200
    assert( filename && *filename );
 
201
    assert( write==0 || write==1 );
 
202
 
 
203
    dbgmsg( "looking for file '%s', writable %c", filename, write?'y':'n' );
148
204
 
149
205
    tr_lockLock( gFd->lock );
150
206
 
151
207
    /* Is it already open? */
152
 
    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
 
208
    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
153
209
    {
154
 
        if( gFd->open[i].status & STATUS_INVALID ||
155
 
            strcmp( folder, gFd->open[i].folder ) ||
156
 
            strcmp( name, gFd->open[i].name ) )
157
 
        {
158
 
            continue;
159
 
        }
160
 
        if( gFd->open[i].status & STATUS_CLOSING )
161
 
        {
162
 
            /* File is being closed by another thread, wait until
163
 
             * it's done before we reopen it */
 
210
        o = &gFd->open[i];
 
211
 
 
212
        if( !fileIsOpen( o ) )
 
213
            continue;
 
214
 
 
215
        if( strcmp( filename, o->filename ) )
 
216
            continue;
 
217
 
 
218
        if( fileIsCheckedOut( o ) ) {
 
219
            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
164
220
            tr_condWait( gFd->cond, gFd->lock );
165
 
            i = -1;
 
221
            i = -1; /* reloop */
166
222
            continue;
167
223
        }
168
 
        if( gFd->open[i].write < write )
169
 
        {
170
 
            /* File is open read-only and needs to be closed then
171
 
             * re-opened read-write */
 
224
 
 
225
        if( write && !o->isWritable ) {
 
226
            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
172
227
            TrCloseFile( i );
173
 
            continue;
 
228
            break;
174
229
        }
 
230
 
 
231
        dbgmsg( "found it!  it's ready for use!" );
175
232
        winner = i;
176
233
        goto done;
177
234
    }
178
235
 
179
 
    /* Can we open one more file? */
180
 
    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
181
 
    {
182
 
        if( gFd->open[i].status & STATUS_INVALID )
183
 
        {
184
 
            winner = i;
185
 
            goto open;
186
 
        }
187
 
    }
188
236
 
189
 
    /* All slots taken - close the oldest currently unused file */
 
237
    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
190
238
    for( ;; )
191
239
    {
192
 
        date   = tr_date() + 1;
 
240
        uint64_t date = tr_date( ) + 1;
193
241
        winner = -1;
194
242
 
195
 
        for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
 
243
        for( i=0; i<TR_MAX_OPEN_FILES; ++i )
196
244
        {
197
 
            if( !( gFd->open[i].status & STATUS_UNUSED ) )
198
 
            {
199
 
                continue;
 
245
            o = &gFd->open[i];
 
246
 
 
247
            if( !fileIsOpen( o ) ) {
 
248
                winner = i;
 
249
                dbgmsg( "found an empty slot in %d", winner );
 
250
                goto done;
200
251
            }
201
 
            if( gFd->open[i].date < date )
202
 
            {
 
252
 
 
253
            if( date > o->date ) {
 
254
                date = o->date;
203
255
                winner = i;
204
 
                date   = gFd->open[i].date;
205
256
            }
206
257
        }
207
258
 
208
 
        if( winner >= 0 )
209
 
        {
 
259
        if( winner >= 0 ) {
 
260
            dbgmsg( "closing file '%s', slot #%d", gFd->open[winner].filename, winner );
210
261
            TrCloseFile( winner );
211
 
            goto open;
 
262
            goto done;
212
263
        }
213
264
 
214
265
        /* All used! Wait a bit and try again */
 
266
        dbgmsg( "everything's full!  waiting for someone else to finish something" );
215
267
        tr_condWait( gFd->cond, gFd->lock );
216
268
    }
217
269
 
218
 
open:
219
 
    if( ( ret = TrOpenFile( winner, folder, name, write ) ) )
220
 
    {
221
 
        tr_lockUnlock( gFd->lock );
222
 
        return ret;
223
 
    }
224
 
    snprintf( gFd->open[winner].folder, MAX_PATH_LENGTH, "%s", folder );
225
 
    snprintf( gFd->open[winner].name, MAX_PATH_LENGTH, "%s", name );
226
 
    gFd->open[winner].write = write;
227
 
 
228
270
done:
229
 
    gFd->open[winner].status = STATUS_USED;
230
 
    gFd->open[winner].date   = tr_date();
 
271
 
 
272
    o = &gFd->open[winner];
 
273
    if( !fileIsOpen( o ) )
 
274
    {
 
275
        const int ret = TrOpenFile( winner, filename, write );
 
276
        if( ret ) {
 
277
            tr_lockUnlock( gFd->lock );
 
278
            return ret;
 
279
        }
 
280
 
 
281
        dbgmsg( "opened '%s' in slot %d, write %c", filename, winner, write?'y':'n' );
 
282
        strlcpy( o->filename, filename, sizeof( o->filename ) );
 
283
        o->isWritable = write;
 
284
    }
 
285
 
 
286
    dbgmsg( "checking out '%s' in slot %d", filename, winner );
 
287
    o->isCheckedOut = 1;
 
288
    o->date = tr_date( );
231
289
    tr_lockUnlock( gFd->lock );
232
 
    
233
 
    return gFd->open[winner].file;
 
290
    return o->fd;
234
291
}
235
292
 
236
 
/***********************************************************************
237
 
 * tr_fdFileRelease
238
 
 **********************************************************************/
239
 
void tr_fdFileRelease( int file )
 
293
void
 
294
tr_fdFileRelease( int file )
240
295
{
241
296
    int i;
242
297
    tr_lockLock( gFd->lock );
243
298
 
244
 
    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
245
 
    {
246
 
        if( gFd->open[i].file == file )
247
 
        {
248
 
            gFd->open[i].status = STATUS_UNUSED;
 
299
    for( i=0; i<TR_MAX_OPEN_FILES; ++i ) {
 
300
        struct tr_openfile * o = &gFd->open[i];
 
301
        if( o->fd == file ) {
 
302
            dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
 
303
            /* fsync( o->fd ); */
 
304
            o->isCheckedOut = 0;
249
305
            break;
250
306
        }
251
307
    }
254
310
    tr_lockUnlock( gFd->lock );
255
311
}
256
312
 
257
 
/***********************************************************************
258
 
 * tr_fdFileClose
259
 
 **********************************************************************/
260
 
void tr_fdFileClose( const char * folder, const char * name )
261
 
{
262
 
    int i;
263
 
 
264
 
    tr_lockLock( gFd->lock );
265
 
 
266
 
    for( i = 0; i < TR_MAX_OPEN_FILES; i++ )
267
 
    {
268
 
        if( gFd->open[i].status & STATUS_INVALID )
269
 
        {
270
 
            continue;
271
 
        }
272
 
        if( !strcmp( folder, gFd->open[i].folder ) &&
273
 
            !strcmp( name, gFd->open[i].name ) )
274
 
        {
275
 
            TrCloseFile( i );
276
 
        }
277
 
    }
278
 
 
279
 
    tr_lockUnlock( gFd->lock );
280
 
}
281
 
 
282
 
 
283
 
/***********************************************************************
284
 
 * Sockets
285
 
 **********************************************************************/
286
 
typedef struct
287
 
{
288
 
    int socket;
289
 
    int priority;
290
 
}
291
 
tr_socket_t;
292
 
 
293
 
/* Remember the priority of every socket we open, so that we can keep
294
 
 * track of how many reserved file descriptors we are using */
295
 
static tr_socket_t * gSockets = NULL;
296
 
static int gSocketsSize = 0;
297
 
static int gSocketsCount = 0;
298
 
static void SocketSetPriority( int s, int priority )
299
 
{
300
 
    if( gSocketsSize < 1 )
301
 
    {
302
 
        gSocketsSize = 256;
303
 
        gSockets = malloc( gSocketsSize * sizeof( tr_socket_t ) );
304
 
    }
305
 
    if( gSocketsSize <= gSocketsCount )
306
 
    {
307
 
        gSocketsSize *= 2;
308
 
        gSockets = realloc( gSockets, gSocketsSize * sizeof( tr_socket_t ) );
309
 
    }
310
 
    gSockets[gSocketsCount].socket = s;
311
 
    gSockets[gSocketsCount].priority = priority;
312
 
    gSocketsCount++;
313
 
}
314
 
static int SocketGetPriority( int s )
315
 
{
316
 
    int i, ret;
317
 
    for( i = 0; i < gSocketsCount; i++ )
318
 
        if( gSockets[i].socket == s )
319
 
            break;
320
 
    if( i >= gSocketsCount )
321
 
    {
322
 
        tr_err( "could not find that socket (%d)!", s );
323
 
        return -1;
324
 
    }
325
 
    ret = gSockets[i].priority;
326
 
    gSocketsCount--;
327
 
    memmove( &gSockets[i], &gSockets[i+1],
328
 
            ( gSocketsCount - i ) * sizeof( tr_socket_t ) );
329
 
    return ret;
330
 
}
331
 
 
332
 
/***********************************************************************
333
 
 * tr_fdSocketCreate
334
 
 **********************************************************************/
335
 
int tr_fdSocketCreate( int type, int priority )
 
313
/***
 
314
****
 
315
****  Sockets
 
316
****
 
317
***/
 
318
 
 
319
static tr_list * reservedSockets = NULL;
 
320
 
 
321
static void
 
322
setSocketPriority( int fd, int isReserved )
 
323
{
 
324
    if( isReserved )
 
325
        tr_list_append( &reservedSockets, TR_UINT_TO_PTR(fd) );
 
326
}
 
327
 
 
328
static int
 
329
socketWasReserved( int fd )
 
330
{
 
331
    return tr_list_remove_data( &reservedSockets, TR_UINT_TO_PTR(fd) ) != NULL;
 
332
}
 
333
 
 
334
int
 
335
tr_fdSocketCreate( int type, int isReserved )
336
336
{
337
337
    int s = -1;
338
 
 
339
338
    tr_lockLock( gFd->lock );
340
339
 
341
 
    if( priority && gFd->reserved >= TR_RESERVED_FDS )
342
 
        priority = FALSE;
 
340
    if( isReserved && gFd->reserved >= TR_RESERVED_FDS )
 
341
        isReserved = FALSE;
343
342
 
344
 
    if( priority || ( gFd->normal < gFd->normalMax ) )
345
 
       if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
346
 
           tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
 
343
    if( isReserved || ( gFd->normal < gFd->normalMax ) )
 
344
        if( ( s = socket( AF_INET, type, 0 ) ) < 0 )
 
345
            tr_err( "Couldn't create socket (%s)", strerror( sockerrno ) );
347
346
 
348
347
    if( s > -1 )
349
348
    {
350
 
        SocketSetPriority( s, priority );
351
 
        if( priority )
352
 
            gFd->reserved++;
 
349
        setSocketPriority( s, isReserved );
 
350
 
 
351
        if( isReserved )
 
352
            ++gFd->reserved;
353
353
        else
354
 
            gFd->normal++;
 
354
            ++gFd->normal;
355
355
    }
 
356
 
 
357
    assert( gFd->reserved >= 0 );
 
358
    assert( gFd->normal >= 0 );
 
359
 
356
360
    tr_lockUnlock( gFd->lock );
357
 
 
358
361
    return s;
359
362
}
360
363
 
362
365
tr_fdSocketAccept( int b, struct in_addr * addr, tr_port_t * port )
363
366
{
364
367
    int s = -1;
365
 
    unsigned len;
 
368
    unsigned int len;
366
369
    struct sockaddr_in sock;
367
370
 
368
371
    assert( addr != NULL );
376
379
    }
377
380
    if( s > -1 )
378
381
    {
379
 
        SocketSetPriority( s, 0 );
 
382
        setSocketPriority( s, FALSE );
380
383
        *addr = sock.sin_addr;
381
384
        *port = sock.sin_port;
382
385
        gFd->normal++;
386
389
    return s;
387
390
}
388
391
 
389
 
/***********************************************************************
390
 
 * tr_fdSocketClose
391
 
 **********************************************************************/
392
 
void tr_fdSocketClose( int s )
 
392
static void
 
393
socketClose( int fd )
393
394
{
394
 
    if( s >= 0 )
395
 
    {
396
 
        tr_lockLock( gFd->lock );
397
395
#ifdef BEOS_NETSERVER
398
 
        closesocket( s );
 
396
    closesocket( fd );
399
397
#else
400
 
        EVUTIL_CLOSESOCKET( s );
 
398
    EVUTIL_CLOSESOCKET( fd );
401
399
#endif
402
 
        if( SocketGetPriority( s ) )
403
 
            gFd->reserved--;
 
400
}
 
401
 
 
402
void
 
403
tr_fdSocketClose( int s )
 
404
{
 
405
    tr_lockLock( gFd->lock );
 
406
 
 
407
    if( s >= 0 ) {
 
408
        socketClose( s );
 
409
        if( socketWasReserved( s ) )
 
410
            --gFd->reserved;
404
411
        else
405
 
            gFd->normal--;
406
 
        tr_lockUnlock( gFd->lock );
 
412
            --gFd->normal;
407
413
    }
408
 
}
409
 
 
410
 
/***********************************************************************
411
 
 * tr_fdClose
412
 
 **********************************************************************/
413
 
void tr_fdClose( void )
414
 
{
 
414
 
 
415
    assert( gFd->reserved >= 0 );
 
416
    assert( gFd->normal >= 0 );
 
417
 
 
418
    tr_lockUnlock( gFd->lock );
 
419
}
 
420
 
 
421
/***
 
422
****
 
423
****  Startup / Shutdown
 
424
****
 
425
***/
 
426
 
 
427
void
 
428
tr_fdInit( void )
 
429
{
 
430
    int i, j, s[TR_MAX_SOCKETS];
 
431
 
 
432
    assert( gFd == NULL );
 
433
 
 
434
    gFd = tr_new0( struct tr_fd_s, 1 );
 
435
    gFd->lock = tr_lockNew( );
 
436
    gFd->cond = tr_condNew( );
 
437
 
 
438
    /* count the max number of sockets we can use */
 
439
    for( i=0; i<TR_MAX_SOCKETS; ++i )
 
440
        if( ( s[i] = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
 
441
            break;
 
442
    for( j=0; j<i; ++j )
 
443
        socketClose( s[j] );
 
444
    tr_dbg( "%d usable file descriptors", i );
 
445
 
 
446
    /* set some fds aside for the UI or daemon to use */
 
447
    gFd->normalMax = i - TR_RESERVED_FDS - 10;
 
448
 
 
449
    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
 
450
        gFd->open[i].fd = -1;
 
451
          
 
452
}
 
453
 
 
454
void
 
455
tr_fdClose( void )
 
456
{
 
457
    int i = 0;
 
458
 
 
459
    for( i=0; i<TR_MAX_OPEN_FILES; ++i )
 
460
        if( fileIsOpen( &gFd->open[i] ) )
 
461
            TrCloseFile( i );
 
462
 
415
463
    tr_lockFree( gFd->lock );
416
464
    tr_condFree( gFd->cond );
417
 
    free( gFd );
418
 
}
419
 
 
420
 
 
421
 
/***********************************************************************
422
 
 * Local functions
423
 
 **********************************************************************/
424
 
 
425
 
/***********************************************************************
426
 
 * CheckFolder
427
 
 ***********************************************************************
428
 
 *
429
 
 **********************************************************************/
430
 
static int TrOpenFile( int i, const char * folder, const char * name, int write )
431
 
{
432
 
    tr_openFile_t * file = &gFd->open[i];
433
 
    struct stat sb;
434
 
    char path[MAX_PATH_LENGTH];
435
 
    int ret;
436
 
    int flags;
437
 
 
438
 
    tr_dbg( "Opening %s in %s (%d)", name, folder, write );
439
 
 
440
 
    /* Make sure the parent folder exists */
441
 
    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
442
 
    {
443
 
        return TR_ERROR_IO_PARENT;
444
 
    }
445
 
 
446
 
    snprintf( path, sizeof(path), "%s" TR_PATH_DELIMITER_STR "%s",
447
 
              folder,
448
 
              name );
449
 
 
450
 
    /* Create subfolders, if any */
451
 
    if( write )
452
 
    {
453
 
        char * p = path + strlen( folder ) + 1;
454
 
        char * s;
455
 
 
456
 
        while( ( s = strchr( p, TR_PATH_DELIMITER ) ) )
457
 
        {
458
 
            *s = '\0';
459
 
            if( stat( path, &sb ) )
460
 
            {
461
 
                if( tr_mkdir( path, 0777 ) )
462
 
                {
463
 
                    ret = tr_ioErrorFromErrno();
464
 
                    tr_err( "Couldn't create folder '%s'", path );
465
 
                    return ret;
466
 
                }
467
 
            }
468
 
            else
469
 
            {
470
 
                if( !S_ISDIR( sb.st_mode ) )
471
 
                {
472
 
                    tr_err( "Is not a folder: '%s'", path );
473
 
                    return TR_ERROR_IO_OTHER;
474
 
                }
475
 
            }
476
 
            *s = TR_PATH_DELIMITER;
477
 
            p = s + 1;
478
 
        }
479
 
    }
480
 
 
481
 
    /* Now try to really open the file */
482
 
    errno = 0;
483
 
    flags = 0;
484
 
#ifdef WIN32
485
 
    flags |= O_BINARY;
486
 
#endif
487
 
    flags |= write ? (O_RDWR | O_CREAT) : O_RDONLY;
488
 
    file->file = open( path, flags, 0666 );
489
 
    if( write && ( file->file < 0 ) )
490
 
    {
491
 
        ret = tr_ioErrorFromErrno();
492
 
        if( errno )
493
 
            tr_err( "Couldn't open %s in %s: %s", name, folder, strerror(errno) );
494
 
        else
495
 
            tr_err( "Couldn't open %s in %s", name, folder );
496
 
        return ret;
497
 
    }
498
 
 
499
 
    return TR_OK;
500
 
}
501
 
 
502
 
/***********************************************************************
503
 
 * TrCloseFile
504
 
 ***********************************************************************
505
 
 * We first mark it as closing then release the lock while doing so,
506
 
 * because close() may take same time and we don't want to block other
507
 
 * threads.
508
 
 **********************************************************************/
509
 
static void TrCloseFile( int i )
510
 
{
511
 
    tr_openFile_t * file = &gFd->open[i];
512
 
 
513
 
    /* If it's already being closed by another thread, just wait till
514
 
     * it is done */
515
 
    while( file->status & STATUS_CLOSING )
516
 
    {
517
 
        tr_condWait( gFd->cond, gFd->lock );
518
 
    }
519
 
    if( file->status & STATUS_INVALID )
520
 
    {
521
 
        return;
522
 
    }
523
 
 
524
 
    /* Nobody is closing it already, so let's do it */
525
 
    if( file->status & STATUS_USED )
526
 
    {
527
 
        tr_err( "TrCloseFile: closing a file that's being used!" );
528
 
    }
529
 
    tr_dbg( "Closing %s in %s (%d)", file->name, file->folder, file->write );
530
 
    file->status = STATUS_CLOSING;
531
 
    tr_lockUnlock( gFd->lock );
532
 
    close( file->file );
533
 
    tr_lockLock( gFd->lock );
534
 
    file->status = STATUS_INVALID;
535
 
    tr_condSignal( gFd->cond );
536
 
}
537
 
 
 
465
 
 
466
    tr_list_free( &reservedSockets, NULL );
 
467
    tr_free( gFd );
 
468
}