aboutsummaryrefslogtreecommitdiff
path: root/keyper.c
blob: 7595619aafe5a2a76118579dca2907eb5cc7b6d6 (plain) (blame)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

static int check_fname(const char* fname)
{
  while (*fname) {
    if (strchr("/.", *(fname++))) {
      return 0;
    }
  }
  return 1;
}

static int dump_file(const char* fname)
{
  int fd = open(fname, O_RDONLY);
  if (fd == -1) {
    fprintf(stderr, "Failed to open %s\n", fname);
    return 1;
  }
  char buf[1024];
  int buflen;
  while ((buflen = read(fd, buf, sizeof(buf))) > 0) {
    write(1, buf, buflen);
  }
  close(fd);
  return 0;
}

int main(int argc, char** argv)
{
  const char* file = getenv("KEYPER_FILE");
  const char* disable_file_env = getenv("KEYPER_DISABLE_FILE");
  char disable_file[4096];

  if (!disable_file_env) {
    const char* home = getenv("HOME");
    if (!home) {
      fprintf(stderr, "No $HOME environment variable\n");
      return 2;
    }
    snprintf(disable_file, sizeof(disable_file) - 1, "%s/keyper-disable", home);
  } else {
    strncpy(disable_file, disable_file_env, sizeof(disable_file) - 1);
  }

  if (!file) {
    fprintf(stderr, "No KEYPER_FILE value.\n");
    return 1;
  }

  if (disable_file[0] != '/') {
    fprintf(stderr, "$KEYPER_DISABLE_FILE must be an absolute path!\n");
    return 1;
  }

  if (file[0] != '/') {
    fprintf(stderr, "$KEYPER_FILE must be an absolute path!\n");
    return 1;
  }

  struct stat statbuf;
  if (!stat(disable_file, &statbuf)) {
    fprintf(stderr, "Keyper disabled because %s exists.\n", disable_file);
    return 127;
  }

  return dump_file(file);
}