summaryrefslogtreecommitdiff
path: root/bin/slave-build-connect
blob: 40a227cac836c5606d87915f668adcdfa7f36c3a (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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/bin/sh

# shellcheck disable=SC2119,SC2120

# shellcheck source=../lib/load-configuration
. "${0%/*}/../lib/load-configuration"

if [ "${SSH_ORIGINAL_COMMAND%% *}" = 'get-assignment' ] || \
  [ "${SSH_ORIGINAL_COMMAND%% *}" = 'return-assignment' ] || \
  [ "${SSH_ORIGINAL_COMMAND%% *}" = 'ping-from-slave' ]; then

  # small check to prevent some shell-injections
  if printf '%s\n' "${SSH_ORIGINAL_COMMAND}" | \
    grep -q '[^-a-zA-Z0-9.+_ ]'; then

    >&2 printf 'Invalid command: "%s".\n' "${SSH_ORIGINAL_COMMAND}"
    exit 42

  fi

  # shellcheck disable=SC2016
  infos=$(
    {
      printf 'SELECT'
      printf ' `build_slaves`.`id`,'
      printf ' `persons`.`name`'
      printf ' FROM `build_slaves`'
      mysql_join_build_slaves_ssh_keys
      mysql_join_ssh_keys_persons
      printf ' WHERE `build_slaves`.`name`=from_base64("%s")' \
        "$(
          printf '%s' "$1" | \
            base64 -w0
        )"
      printf ' AND `build_slaves`.`access_allowed`;\n'
    } | \
      mysql_run_query | \
      tr '\t' ' '
  )
  if [ -z "${infos}" ]; then
    >&2 printf 'Build slave "%s" is unnknown to the database.\n' "$1"
    exit 42
  fi
  slave_id="${infos%% *}"
  operator="${infos#* }"

  ssh_log_id=$(
    # shellcheck disable=SC2016
    {
      printf 'INSERT INTO `ssh_log` (`build_slave`,`action`,`parameters`)'
      printf ' VALUES (%s' \
        "${slave_id}"
      printf ',from_base64("%s")' \
        "$(
          printf '%s' "${SSH_ORIGINAL_COMMAND%% *}" | \
            base64 -w0
        )" \
        "$(
          printf '%s' "${SSH_ORIGINAL_COMMAND#* }" | \
            base64 -w0
        )"
      printf ');\n'
      printf 'SELECT LAST_INSERT_ID();\n'
    } | \
      mysql_run_query 'unimportant'
  )
  exit_code=0

  slave="$1" slave_id="${slave_id}" operator="${operator}" SKIP_COMMAND_LOG=1 /bin/sh -c "${base_dir}/bin/${SSH_ORIGINAL_COMMAND}" \
  || exit_code=$?

  if [ -n "${ssh_log_id}" ]; then
    # shellcheck disable=SC2016
    {
      printf 'UPDATE `ssh_log`'
      printf ' SET `ssh_log`.`duration`=TIME_TO_SEC(TIMEDIFF(NOW(),`ssh_log`.`date`)),'
      printf '`ssh_log`.`exit_code`=%s' \
        "${exit_code}"
      printf ' WHERE `ssh_log`.`id`=%s' \
        "${ssh_log_id}"
      printf ';\n'
    } | \
      mysql_run_query 'unimportant'
  fi

  exit ${exit_code}

else

  >&2 printf 'Invalid command: "%s".\n' "${SSH_ORIGINAL_COMMAND}"
  exit 42

fi