--- libaitsync/src/tool.c 2011/05/08 00:49:45 1.1.1.1.2.1 +++ libaitsync/src/tool.c 2011/05/09 13:46:12 1.1.1.1.2.2 @@ -3,7 +3,7 @@ * by Michael Pounov * * $Author: misho $ -* $Id: tool.c,v 1.1.1.1.2.1 2011/05/08 00:49:45 misho Exp $ +* $Id: tool.c,v 1.1.1.1.2.2 2011/05/09 13:46:12 misho Exp $ * *************************************************************************/ #include "global.h" @@ -59,4 +59,43 @@ inline int syncWriteNum(int f, u_long ulNum, int nNumL } #ifndef HAVE_MKSTEMPS +#define TEMPCHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +#define NUM_CHARS (sizeof(TEMPCHARS) - 1) + +int +mkstemps(char *path, int slen) +{ + char *start, *cp, *ep; + const char *tempchars = TEMPCHARS; + unsigned int tries = 1; + size_t len; + int fd; + + assert(path); + len = strlen(path); + if (len == 0 || slen >= len) { + errno = EINVAL; + goto end; + } else + ep = path + len - slen; + + for (start = ep; start > path && start[-1] == 'X'; start--) { + if (tries < INT_MAX / NUM_CHARS) + tries *= NUM_CHARS; + } + tries *= 2; + + do { + for (cp = start; cp != ep; cp++) + *cp = tempchars[arc4random_uniform(NUM_CHARS)]; + + fd = open(path, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); + if (fd != -1 || errno != EEXIST) + return fd; + } while (--tries); + + errno = EEXIST; +end: + return -1; +} #endif