source: trunk/libtransmission/platform.c @ 5171

Last change on this file since 5171 was 5171, checked in by charles, 13 years ago

fix r5164 thread timing issue reported by pea_

  • Property svn:keywords set to Date Rev Author Id
File size: 11.3 KB
Line 
1/******************************************************************************
2 * $Id: platform.c 5171 2008-02-29 01:58:46Z 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#ifdef __BEOS__
26  #include <signal.h> 
27  #include <fs_info.h>
28  #include <FindDirectory.h>
29  #include <kernel/OS.h>
30  #define BEOS_MAX_THREADS 256
31#elif defined(WIN32)
32  #include <windows.h>
33  #include <shlobj.h> /* for CSIDL_APPDATA, CSIDL_PROFILE */
34#else
35  #define _XOPEN_SOURCE 500 /* needed for recursive locks. */
36  #ifndef __USE_UNIX98
37  #define __USE_UNIX98 /* some older Linuxes need it spelt out for them */
38  #endif
39  #include <pthread.h>
40#endif
41
42#include <assert.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <string.h>
46
47#include <sys/types.h>
48#include <dirent.h>
49#include <fcntl.h>
50#include <unistd.h> /* getuid getpid close */
51
52#include "transmission.h"
53#include "platform.h"
54#include "trcompat.h"
55#include "utils.h"
56
57/***
58****  THREADS
59***/
60
61#ifdef __BEOS__
62typedef thread_id tr_thread_id;
63#elif defined(WIN32)
64typedef DWORD tr_thread_id;
65#else
66typedef pthread_t tr_thread_id;
67#endif
68
69static tr_thread_id
70tr_getCurrentThread( void )
71{
72#ifdef __BEOS__
73    return find_thread( NULL );
74#elif defined(WIN32)
75    return GetCurrentThreadId();
76#else
77    return pthread_self( );
78#endif
79}
80
81static int
82tr_areThreadsEqual( tr_thread_id a, tr_thread_id b )
83{
84#ifdef __BEOS__
85    return a == b;
86#elif defined(WIN32)
87    return a == b;
88#else
89    return pthread_equal( a, b );
90#endif
91}
92
93struct tr_thread
94{
95    void          (* func ) ( void * );
96    void           * arg;
97    const char     * name;
98    tr_thread_id     thread;
99#ifdef WIN32
100    HANDLE           thread_handle;
101#endif
102};
103
104int
105tr_amInThread ( const tr_thread * t )
106{
107    return tr_areThreadsEqual( tr_getCurrentThread(), t->thread );
108}
109
110#ifdef WIN32
111#define ThreadFuncReturnType unsigned WINAPI
112#else
113#define ThreadFuncReturnType void
114#endif
115
116static ThreadFuncReturnType
117ThreadFunc( void * _t )
118{
119    tr_thread * t = _t;
120    const char * name = t->name;
121
122#ifdef __BEOS__
123    /* This is required because on BeOS, SIGINT is sent to each thread,
124       which kills them not nicely */
125    signal( SIGINT, SIG_IGN );
126#endif
127
128    tr_dbg( "Thread '%s' started", name );
129    t->func( t->arg );
130    tr_dbg( "Thread '%s' exited", name );
131
132#ifdef WIN32
133    _endthreadex( 0 );
134    return 0;
135#endif
136}
137
138tr_thread *
139tr_threadNew( void (*func)(void *),
140              void * arg,
141              const char * name )
142{
143    tr_thread * t = tr_new0( tr_thread, 1 );
144    t->func = func;
145    t->arg  = arg;
146    t->name = name;
147
148#ifdef __BEOS__
149    t->thread = spawn_thread( (void*)ThreadFunc, name, B_NORMAL_PRIORITY, t );
150    resume_thread( t->thread );
151#elif defined(WIN32)
152    {
153        unsigned int id;
154        t->thread_handle = (HANDLE) _beginthreadex( NULL, 0, &ThreadFunc, t, 0, &id );
155        t->thread = (DWORD) id;
156    }
157#else
158    pthread_create( &t->thread, NULL, (void * (*) (void *)) ThreadFunc, t );
159#endif
160
161    return t;
162}
163   
164void
165tr_threadJoin( tr_thread * t )
166{
167    if( t != NULL )
168    {
169#ifdef __BEOS__
170        long exit;
171        wait_for_thread( t->thread, &exit );
172#elif defined(WIN32)
173        WaitForSingleObject( t->thread_handle, INFINITE );
174        CloseHandle( t->thread_handle );
175#else
176        pthread_join( t->thread, NULL );
177#endif
178
179        tr_dbg( "Thread '%s' joined", t->name );
180        t->name = NULL;
181        t->func = NULL;
182        tr_free( t );
183    }
184}
185
186/***
187****  LOCKS
188***/
189
190struct tr_lock
191{
192    int depth;
193#ifdef __BEOS__
194    sem_id lock;
195    thread_id lockThread;
196#elif defined(WIN32)
197    CRITICAL_SECTION lock;
198    DWORD lockThread;
199#else
200    pthread_mutex_t lock;
201    pthread_t lockThread;
202#endif
203};
204
205tr_lock*
206tr_lockNew( void )
207{
208    tr_lock * l = tr_new0( tr_lock, 1 );
209
210#ifdef __BEOS__
211    l->lock = create_sem( 1, "" );
212#elif defined(WIN32)
213    InitializeCriticalSection( &l->lock ); /* critical sections support recursion */
214#else
215    pthread_mutexattr_t attr;
216    pthread_mutexattr_init( &attr );
217    pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
218    pthread_mutex_init( &l->lock, &attr );
219#endif
220
221    return l;
222}
223
224void
225tr_lockFree( tr_lock * l )
226{
227#ifdef __BEOS__
228    delete_sem( l->lock );
229#elif defined(WIN32)
230    DeleteCriticalSection( &l->lock );
231#else
232    pthread_mutex_destroy( &l->lock );
233#endif
234    tr_free( l );
235}
236
237void
238tr_lockLock( tr_lock * l )
239{
240#ifdef __BEOS__
241    acquire_sem( l->lock );
242#elif defined(WIN32)
243    EnterCriticalSection( &l->lock );
244#else
245    pthread_mutex_lock( &l->lock );
246#endif
247    assert( l->depth >= 0 );
248    if( l->depth )
249        assert( tr_areThreadsEqual( l->lockThread, tr_getCurrentThread() ) );
250    l->lockThread = tr_getCurrentThread( );
251    ++l->depth;
252}
253
254int
255tr_lockHave( const tr_lock * l )
256{
257    return ( l->depth > 0 )
258        && ( tr_areThreadsEqual( l->lockThread, tr_getCurrentThread() ) );
259}
260
261void
262tr_lockUnlock( tr_lock * l )
263{
264    assert( l->depth > 0 );
265    assert( tr_areThreadsEqual( l->lockThread, tr_getCurrentThread() ));
266
267    --l->depth;
268    assert( l->depth >= 0 );
269#ifdef __BEOS__
270    release_sem( l->lock );
271#elif defined(WIN32)
272    LeaveCriticalSection( &l->lock );
273#else
274    pthread_mutex_unlock( &l->lock );
275#endif
276}
277
278/***
279****  PATHS
280***/
281
282#if !defined(WIN32) && !defined(__BEOS__) && !defined(__AMIGAOS4__)
283#include <pwd.h>
284#endif
285
286static const char *
287tr_getHomeDirectory( void )
288{
289    static char buf[MAX_PATH_LENGTH];
290    static int init = 0;
291    const char * envHome;
292
293    if( init )
294        return buf;
295
296    envHome = getenv( "HOME" );
297    if( envHome )
298        snprintf( buf, sizeof(buf), "%s", envHome );
299    else {
300#ifdef WIN32
301        SHGetFolderPath( NULL, CSIDL_PROFILE, NULL, 0, buf );
302#elif defined(__BEOS__) || defined(__AMIGAOS4__)
303        *buf = '\0';
304#else
305        struct passwd * pw = getpwuid( getuid() );
306        endpwent();
307        if( pw != NULL )
308            snprintf( buf, sizeof(buf), "%s", pw->pw_dir );
309#endif
310    }
311
312    init = 1;
313    return buf;
314}
315
316
317static void
318tr_migrateResume( const char *oldDirectory, const char *newDirectory )
319{
320    DIR * dirh = opendir( oldDirectory );
321
322    if( dirh != NULL )
323    {
324        struct dirent * dirp;
325
326        while( ( dirp = readdir( dirh ) ) )
327        {
328            if( !strncmp( "resume.", dirp->d_name, 7 ) )
329            {
330                char o[MAX_PATH_LENGTH];
331                char n[MAX_PATH_LENGTH];
332                tr_buildPath( o, sizeof(o), oldDirectory, dirp->d_name, NULL );
333                tr_buildPath( n, sizeof(n), newDirectory, dirp->d_name, NULL );
334                rename( o, n );
335            }
336        }
337
338        closedir( dirh );
339    }
340}
341
342const char *
343tr_getPrefsDirectory( void )
344{
345    static char   buf[MAX_PATH_LENGTH];
346    static int    init = 0;
347    const char * trhome;
348
349    if( init )
350        return buf;
351
352    trhome = getenv( "TRANSMISSION_HOME" );
353    if( trhome != NULL )
354    {
355        strlcpy( buf, trhome, sizeof( buf ) );
356    }
357    else
358    {
359#ifdef __BEOS__
360        find_directory( B_USER_SETTINGS_DIRECTORY,
361                        dev_for_path("/boot"), true,
362                        buf, sizeof( buf ) );
363        strcat( buf, "/Transmission" );
364#elif defined( SYS_DARWIN )
365        tr_buildPath ( buf, sizeof( buf ),
366                       tr_getHomeDirectory( ),
367                       "Library",
368                       "Application Support",
369                       "Transmission",
370                       NULL );
371#elif defined(__AMIGAOS4__)
372        strlcpy( buf, "PROGDIR:.transmission", sizeof( buf ) );
373#elif defined(WIN32)
374        char appdata[MAX_PATH_LENGTH];
375        SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, appdata );
376        tr_buildPath( buf, sizeof(buf),
377                      appdata,
378                      "Transmission",
379                      NULL );
380#else
381        tr_buildPath ( buf, sizeof(buf), tr_getHomeDirectory( ), ".transmission", NULL );
382#endif
383    }
384
385    tr_mkdirp( buf, 0777 );
386    init = 1;
387
388#ifdef SYS_DARWIN
389    char old[MAX_PATH_LENGTH];
390    tr_buildPath ( old, sizeof(old),
391                   tr_getHomeDirectory(), ".transmission", NULL );
392    tr_migrateResume( old, buf );
393    rmdir( old );
394#endif
395
396    return buf;
397}
398
399const char *
400tr_getCacheDirectory( void )
401{
402    static char buf[MAX_PATH_LENGTH];
403    static int  init = 0;
404    static const size_t buflen = sizeof(buf);
405    const char * p;
406
407    if( init )
408        return buf;
409
410    p = tr_getPrefsDirectory();
411#if defined(__BEOS__) || defined(WIN32)
412    tr_buildPath( buf, buflen, p, "Cache", NULL );
413#elif defined( SYS_DARWIN )
414    tr_buildPath( buf, buflen, tr_getHomeDirectory(),
415                  "Library", "Caches", "Transmission", NULL );
416#else
417    tr_buildPath( buf, buflen, p, "cache", NULL );
418#endif
419
420    tr_mkdirp( buf, 0777 );
421    init = 1;
422
423    if( strcmp( p, buf ) )
424        tr_migrateResume( p, buf );
425
426    return buf;
427}
428
429const char *
430tr_getTorrentsDirectory( void )
431{
432    static char buf[MAX_PATH_LENGTH];
433    static int  init = 0;
434    static const size_t buflen = sizeof(buf);
435    const char * p;
436
437    if( init )
438        return buf;
439
440    p = tr_getPrefsDirectory ();
441
442#if defined(__BEOS__) || defined(WIN32)
443    tr_buildPath( buf, buflen, p, "Torrents", NULL );
444#elif defined( SYS_DARWIN )
445    tr_buildPath( buf, buflen, p, "Torrents", NULL );
446#else
447    tr_buildPath( buf, buflen, p, "torrents", NULL );
448#endif
449
450    tr_mkdirp( buf, 0777 );
451    init = 1;
452    return buf;
453}
454
455/***
456****
457***/
458
459int
460tr_lockfile( const char * filename )
461{
462    int ret;
463
464#ifdef WIN32
465
466    HANDLE file = CreateFile( filename,
467                              GENERIC_READ|GENERIC_WRITE,
468                              FILE_SHARE_READ|FILE_SHARE_WRITE,
469                              NULL,
470                              OPEN_ALWAYS,
471                              FILE_ATTRIBUTE_NORMAL,
472                              NULL );
473    if( file == INVALID_HANDLE_VALUE )
474        ret = TR_LOCKFILE_EOPEN;
475    else if( !LockFile( file, 0, 0, 1, 1 ) )
476        ret = TR_LOCKFILE_ELOCK;
477    else
478        ret = TR_LOCKFILE_SUCCESS;
479
480#else
481
482    int fd = open( filename, O_RDWR | O_CREAT, 0666 );
483    if( fd < 0 )
484        ret = TR_LOCKFILE_EOPEN;
485    else {
486        struct flock lk;
487        memset( &lk, 0,  sizeof( lk ) );
488        lk.l_start = 0;
489        lk.l_len = 0;
490        lk.l_type = F_WRLCK;
491        lk.l_whence = SEEK_SET;
492        if( -1 == fcntl( fd, F_SETLK, &lk ) )
493            ret = TR_LOCKFILE_ELOCK;
494        else
495            ret = TR_LOCKFILE_SUCCESS;
496    }
497
498#endif
499
500    return ret;
501}
Note: See TracBrowser for help on using the repository browser.