#include "fcint.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define NEW_NAME ".NEW"
#define LCK_NAME ".LCK"
#define TMP_NAME ".TMP-XXXXXX"
FcAtomic *
FcAtomicCreate (const FcChar8 *file)
{
int file_len = strlen ((char *) file);
int new_len = file_len + sizeof (NEW_NAME);
int lck_len = file_len + sizeof (LCK_NAME);
int tmp_len = file_len + sizeof (TMP_NAME);
int total_len = (sizeof (FcAtomic) +
file_len + 1 +
new_len + 1 +
lck_len + 1 +
tmp_len + 1);
FcAtomic *atomic = malloc (total_len);
if (!atomic)
return 0;
FcMemAlloc (FC_MEM_ATOMIC, total_len);
atomic->file = (FcChar8 *) (atomic + 1);
strcpy ((char *) atomic->file, (char *) file);
atomic->new = atomic->file + file_len + 1;
strcpy ((char *) atomic->new, (char *) file);
strcat ((char *) atomic->new, NEW_NAME);
atomic->lck = atomic->new + new_len + 1;
strcpy ((char *) atomic->lck, (char *) file);
strcat ((char *) atomic->lck, LCK_NAME);
atomic->tmp = atomic->lck + lck_len + 1;
return atomic;
}
FcBool
FcAtomicLock (FcAtomic *atomic)
{
int fd = -1;
FILE *f = 0;
int ret;
struct stat lck_stat;
strcpy ((char *) atomic->tmp, (char *) atomic->file);
strcat ((char *) atomic->tmp, TMP_NAME);
fd = mkstemp ((char *) atomic->tmp);
if (fd < 0)
return FcFalse;
f = fdopen (fd, "w");
if (!f)
{
close (fd);
unlink ((char *) atomic->tmp);
return FcFalse;
}
ret = fprintf (f, "%ld\n", (long)getpid());
if (ret <= 0)
{
fclose (f);
unlink ((char *) atomic->tmp);
return FcFalse;
}
if (fclose (f) == EOF)
{
unlink ((char *) atomic->tmp);
return FcFalse;
}
ret = link ((char *) atomic->tmp, (char *) atomic->lck);
(void) unlink ((char *) atomic->tmp);
if (ret < 0)
{
if (stat ((char *) atomic->lck, &lck_stat) >= 0)
{
time_t now = time (0);
if ((long int) (now - lck_stat.st_mtime) > 10 * 60)
{
if (unlink ((char *) atomic->lck) == 0)
return FcAtomicLock (atomic);
}
}
return FcFalse;
}
(void) unlink ((char *) atomic->new);
return FcTrue;
}
FcChar8 *
FcAtomicNewFile (FcAtomic *atomic)
{
return atomic->new;
}
FcChar8 *
FcAtomicOrigFile (FcAtomic *atomic)
{
return atomic->file;
}
FcBool
FcAtomicReplaceOrig (FcAtomic *atomic)
{
if (rename ((char *) atomic->new, (char *) atomic->file) < 0)
return FcFalse;
return FcTrue;
}
void
FcAtomicDeleteNew (FcAtomic *atomic)
{
unlink ((char *) atomic->new);
}
void
FcAtomicUnlock (FcAtomic *atomic)
{
unlink ((char *) atomic->lck);
}
void
FcAtomicDestroy (FcAtomic *atomic)
{
FcMemFree (FC_MEM_ATOMIC, sizeof (FcAtomic) +
strlen ((char *) atomic->file) * 4 + 1 +
sizeof (NEW_NAME) + sizeof (LCK_NAME) +
sizeof (TMP_NAME));
free (atomic);
}