summaryrefslogtreecommitdiff
path: root/src/libunixonacid/atomic_symlink.c
blob: d438263a131c5ec3979ee4e7a8ba63ae87a1c20c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* ISC license. */

#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <skalibs/random.h>
#include <skalibs/unix-transactional.h>

int atomic_symlink (char const *target, char const *name, char const *suffix)
{
  {
    int e = errno ;
    if (symlink(target, name) == 0) return 1 ;
    if (errno != EEXIST) return 0 ;
    errno = e ;
  }
  {
    size_t namelen = strlen(name) ;
    size_t suffixlen = suffix ? strlen(suffix) : 25 ;
    char tmp[namelen + suffixlen + 2] ;
    memcpy(tmp, name, namelen) ;
    tmp[namelen] = ':' ;
    if (suffix)
      memcpy(tmp + namelen + 1, suffix, suffixlen + 1) ;
    else
    {
      memcpy(tmp + namelen + 1, "atomic_symlink:", 15) ;
      random_name(tmp + namelen + 16, 8) ;
      tmp[namelen + 24] = 0 ;
    }
    {
      int e = errno ;
      if (unlink(tmp) < 0 && errno != ENOENT) return 0 ;
      errno = e ;
    }
    if (symlink(target, tmp) < 0) return 0 ;
    if (rename(tmp, name) < 0)
    {
      int e = errno ;
      unlink(tmp) ;
      errno = e ;
      return 0 ;
    }
  }
  return 1 ;
}