#!/bin/sh # Instala ou atualiza o test-medidor em Linux com systemd. # # curl -fsSL https://test.com.br/medidor.sh | sh # curl -fsSL https://test.com.br/medidor.sh | sh -s -- --domain medidor.seuprovedor.com.br # curl -fsSL https://test.com.br/medidor.sh | sh -s -- --domain medidor.seuprovedor.com.br:8443 # curl -fsSL https://test.com.br/medidor.sh | sh -s -- --domain medidor.seuprovedor.com.br --cert fullchain.pem --key privkey.pem # curl -fsSL https://test.com.br/medidor.sh | sh -s -- --domain medidor.seuprovedor.com.br --behind-proxy # curl -fsSL https://test.com.br/medidor.sh | sh -s -- --domain medidor.seuprovedor.com.br --account ID # # Sem --domain, pergunta o domínio no terminal (a menos que ele já esteja configurado). # Rodar de novo atualiza: o arquivo de configuração é mantido e o serviço é reiniciado. # O modo também é mantido: --behind-proxy (ou --listen) entra no modo proxy; --no-proxy, # ou --cert e --key, saem dele. A conta de --account também é mantida. # Só as etapas que precisam de root usam sudo. # # Opções: # --domain NOME[:PORTA] nome DNS público do servidor; com :PORTA, o mesmo que --https-port # --account ID conta do provedor no test.com.br; o servidor só aceita testes dela # --https-port PORTA porta HTTPS, quando a 443 não pode ser usada # --cert ARQUIVO certificado próprio (PEM, com a cadeia), usado com --key # --key ARQUIVO chave privada do certificado (PEM) # --behind-proxy HTTP simples atrás de um proxy reverso, que fica com o HTTPS e as portas 80 e 443 # --listen ENDEREÇO onde o proxy encontra o test-medidor (padrão 127.0.0.1:8080); implica --behind-proxy # --no-proxy sai do modo proxy: o test-medidor volta a atender HTTPS sozinho # -y aceito e ignorado (compatibilidade) # # Variáveis: # TEST_MEDIDOR_DOMAIN o mesmo que --domain # TEST_MEDIDOR_ACCOUNT o mesmo que --account # TEST_MEDIDOR_BASE_URL onde estão os arquivos (padrão abaixo) # TEST_MEDIDOR_VERSION versão, ex.: 0.1.0 (padrão: latest) # TEST_MEDIDOR_KEYS_URL de onde o servidor busca as chaves (padrão abaixo); o instalador confere o acesso set -eu BASE_URL="${TEST_MEDIDOR_BASE_URL:-https://downloads.test.com.br/test-medidor}" VERSION="${TEST_MEDIDOR_VERSION:-latest}" KEYS_URL="${TEST_MEDIDOR_KEYS_URL:-https://www.test.com.br/.well-known/jwks.json}" BIN=/usr/local/bin/test-medidor UNIT=/etc/systemd/system/test-medidor.service ENV_FILE=/etc/test-medidor/test-medidor.env CERT_FILE=/etc/test-medidor/cert.pem KEY_FILE=/etc/test-medidor/key.pem CERT_WAIT=120 DEFAULT_LISTEN=127.0.0.1:8080 SHORT_URL=https://test.com.br/medidor.sh PORTAL_URL=https://www.test.com.br/painel/servidor GUIDE_URL=https://test.com.br/provedores/servidor-de-medicao EXAMPLE=medidor.seuprovedor.com.br SUDO="" say() { printf '==> %s\n' "$*"; } die() { printf 'erro: %s\n' "$*" >&2 exit 1 } usage() { cat </dev/null; } ask_domain() { while :; do if [ "$proxy" = 1 ]; then printf 'Qual é o domínio deste servidor? (o nome que o seu proxy atende, ex.: %s) ' "$EXAMPLE" >/dev/tty else printf 'Qual é o domínio deste servidor? (ex.: %s, ou %s:8443 com HTTPS em outra porta) ' "$EXAMPLE" "$EXAMPLE" >/dev/tty fi IFS= read -r answer /dev/tty done } fetch() { if command -v curl >/dev/null 2>&1; then curl -fsSL -o "$2" "$1" else wget -q -O "$2" "$1" fi } # The server fetches the keys that validate tests here; without them it stops accepting tests. reaches_keys() { if command -v curl >/dev/null 2>&1; then curl -fsSL --max-time 15 "$KEYS_URL" 2>/dev/null else wget -q -O - -T 15 "$KEYS_URL" 2>/dev/null fi | grep -q '"keys"' } keys_unreachable() { cat >&2 </dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1 else shasum -a 256 "$1" | cut -d' ' -f1 fi } # The env file is readable only by root and the service group. configured() { [ -f "$ENV_FILE" ] || return 0 $SUDO sed -n "s/^$1=//p" "$ENV_FILE" | tail -n 1 | tr -d "\"' \r" } # The port of TEST_MEDIDOR_HTTPS_LISTEN, which is an address such as :8443 or 0.0.0.0:8443. configured_port() { listen=$(configured TEST_MEDIDOR_HTTPS_LISTEN) printf '%s\n' "${listen##*:}" } # Sets domain and domain_port from NAME or NAME:PORT, or dies with $1 as context. take_address() { a=$(validate_address "$2") || die "$1: $a" domain=${a%%:*} domain_port="" case "$a" in *:*) domain_port=${a#*:} ;; esac } reconcile_port() { [ -n "$domain_port" ] || return 0 [ -z "$port" ] || [ "$port" = "$domain_port" ] || die "a porta do domínio ($domain_port) e a de --https-port ($port) não conferem; use só uma das duas" port=$domain_port } check_pem() { $SUDO test -f "$2" || die "$1: arquivo não encontrado: $2" $SUDO grep -q -e "$3" "$2" || die "$1: $2 não parece $4 em PEM" } install_pem() { $SUDO test "$1" -ef "$2" && return 0 $SUDO install -m 0640 -o root -g test-medidor "$1" "$2" } # The value of a string field in one of the server's JSON log lines. json_field() { printf '%s\n' "$2" | sed -E -n 's/.*"'"$1"'":"(([^"\\]|\\.)*)".*/\1/p' | sed 's/\\"/"/g; s/\\\\/\\/g' } port_owner() { command -v ss >/dev/null 2>&1 || return 0 $SUDO ss -Hltnp "sport = :$1" 2>/dev/null | sed -n 's/.*users:((\(.*\)))$/ em uso por: \1/p' | head -n 3 } # Explains a start that failed because a port is taken, then the log. fail_start() { log=$($SUDO journalctl -u test-medidor --since "@$started" -n 20 --no-pager 2>/dev/null || true) printf '\nerro: o serviço test-medidor não ficou ativo.\n' >&2 case "$log" in *--http-listen*"address already in use"*) http_port=$(configured TEST_MEDIDOR_HTTP_LISTEN) http_port=${http_port##*:} [ -n "$http_port" ] || http_port=80 printf '\nA porta %s já está em uso por outro programa, e o certificado automático do Let'"'"'s Encrypt precisa dela.\n' "$http_port" >&2 port_owner "$http_port" >&2 cat >&2 <&2 port_owner "$https_port" >&2 cat >&2 <&2 port_owner "${listen##*:}" >&2 cat >&2 <&2 printf '\nCorrija e rode o instalador de novo. Guia: %s\n' "$GUIDE_URL" >&2 exit 1 } # Prints the server's certificate outcome line, or nothing if none came in time. wait_for_certificate() { waited=0 while :; do line=$($SUDO journalctl -u test-medidor --since "@$started" -o cat --no-pager 2>/dev/null | grep -F -e '"msg":"certificate ready"' -e '"msg":"certificate not issued"' | tail -n 1) if [ -n "$line" ]; then printf '%s\n' "$line" return fi $SUDO systemctl is-active --quiet test-medidor || fail_start [ "$waited" -lt "$CERT_WAIT" ] || return 0 sleep 2 waited=$((waited + 2)) done } certificate_not_issued() { { printf '\nerro: o Let'"'"'s Encrypt não emitiu o certificado para %s.\n' "$domain" printf 'O test-medidor %s está instalado e rodando, mas sem certificado nenhum cliente consegue conectar.\n' "$version" printf '\nErro do Let'"'"'s Encrypt:\n %s\n\n' "$1" printf 'O Let'"'"'s Encrypt só valida o nome pela porta 80 ou pela 443, nunca por outra porta.\n' if [ "$https_port" = 443 ]; then printf 'A porta 80 ou a 443 de %s precisa chegar da internet ao test-medidor, e não a outro servidor web.\n' "$domain" else printf 'Com HTTPS na porta %s, a validação é pela porta 80: ela precisa chegar da internet ao test-medidor, e não a outro servidor web.\n' "$https_port" fi printf 'Confira também se o DNS de %s aponta para este servidor.\n' "$domain" cat <&2 exit 1 } write_setting() { $SUDO cat "$ENV_FILE" | awk -v k="$2" -v v="$3" ' index($0, k "=") == 1 { if (!done) print k "=" v; done = 1; next } { print } END { if (!done) print k "=" v } ' >"$1/env" $SUDO cp "$1/env" "$ENV_FILE" } # Comments the setting out, so the file still shows what it was. unset_setting() { $SUDO cat "$ENV_FILE" | awk -v k="$2" ' index($0, k "=") == 1 { print "#" $0; next } { print } ' >"$1/env" $SUDO cp "$1/env" "$ENV_FILE" } local_health() { if command -v curl >/dev/null 2>&1; then curl -fsSg --noproxy '*' --max-time 5 "http://$1/health" 2>/dev/null else wget -q -O - --no-proxy -T 5 "http://$1/health" 2>/dev/null fi } account_note() { [ -z "$account" ] || return 0 cat <&2 fi target="http://$upstream" case "${listen%:*}" in "" | 0.0.0.0 | "[::]") target="$target (com o proxy em outra máquina, o IP desta na porta ${listen##*:})" ;; esac if [ "$update" -eq 1 ]; then printf '\ntest-medidor %s atualizado e rodando para %s, atrás de um proxy reverso.\n' "$version" "$domain" next="Se ainda não fez, cadastre" else printf '\ntest-medidor %s instalado e rodando para %s, atrás de um proxy reverso.\n' "$version" "$domain" next="Próximo passo: cadastre" fi cat <&2 die "opção desconhecida: $1" ;; esac done reconcile_port if [ -n "$cert_src" ] && [ -z "$key_src" ]; then die "--cert precisa de --key"; fi if [ -n "$key_src" ] && [ -z "$cert_src" ]; then die "--key precisa de --cert"; fi if [ "$want_proxy" = 1 ]; then [ "$no_proxy" = 0 ] || die "--behind-proxy (ou --listen) e --no-proxy não combinam; escolha um dos dois" [ -z "$cert_src" ] || die "no modo proxy, o certificado fica com o seu proxy; tire --cert e --key, ou tire --behind-proxy" [ -z "$port" ] || die "no modo proxy, a porta HTTPS é a do seu proxy; informe só o nome em --domain, sem --https-port nem :PORTA, e cadastre no painel o nome com a porta do proxy" fi proxy=$want_proxy [ "$(uname -s)" = Linux ] || die "este instalador é só para Linux. Para outros sistemas, veja $GUIDE_URL" command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ] || die "systemd não encontrado. Sem systemd, use o Docker ou o binário avulso: $GUIDE_URL" case "$(uname -m)" in x86_64 | amd64) arch=amd64 ;; aarch64 | arm64) arch=arm64 ;; armv7* | armv8l) arch=armv7 ;; *) die "arquitetura não suportada: $(uname -m). Veja as alternativas em $GUIDE_URL" ;; esac command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1 || die "instale curl ou wget" command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 || die "sha256sum não encontrado" if { command -v dpkg >/dev/null 2>&1 && dpkg -s test-medidor >/dev/null 2>&1; } || { command -v rpm >/dev/null 2>&1 && rpm -q test-medidor >/dev/null 2>&1; }; then die "o test-medidor deste servidor foi instalado por pacote (.deb/.rpm); atualize pelo pacote" fi keys_host=$(printf '%s\n' "$KEYS_URL" | sed -E 's#^[a-z]+://##; s#[/:].*##') say "conferindo o acesso a $keys_host" reaches_keys || keys_unreachable if [ "$(id -u)" -ne 0 ]; then command -v sudo >/dev/null 2>&1 || die "rode como root ou instale o sudo: este instalador precisa de root para instalar o serviço" SUDO=sudo fi # Asked before any password prompt when nothing is configured yet. if [ -z "$domain" ] && [ ! -f "$ENV_FILE" ]; then have_tty || die "sem terminal para perguntar o domínio. Rode assim: curl -fsSL $SHORT_URL | sh -s -- --domain $EXAMPLE" answer=$(ask_domain) take_address domínio "$answer" reconcile_port fi if [ -n "$SUDO" ]; then say "o sudo pode pedir a sua senha para instalar o serviço" sudo true || die "não foi possível usar o sudo" fi if [ -n "$cert_src" ]; then check_pem --cert "$cert_src" '-----BEGIN CERTIFICATE-----' "um certificado" check_pem --key "$key_src" '-----BEGIN .*PRIVATE KEY-----' "uma chave privada" fi previous=$(configured TEST_MEDIDOR_DOMAIN) was_proxy=0 if is_true "$(configured TEST_MEDIDOR_BEHIND_PROXY)"; then was_proxy=1; fi if [ "$want_proxy" = 0 ] && [ "$no_proxy" = 0 ] && [ -z "$cert_src" ]; then proxy=$was_proxy [ "$proxy" = 0 ] || [ -z "$port" ] || die "este servidor está no modo proxy, em que a porta HTTPS é a do seu proxy. Para sair do modo proxy e atender HTTPS na porta $port, acrescente --no-proxy" fi if [ -z "$domain" ] && [ -z "$previous" ]; then have_tty || die "sem terminal para perguntar o domínio. Rode assim: curl -fsSL $SHORT_URL | sh -s -- --domain $EXAMPLE" answer=$(ask_domain) take_address domínio "$answer" reconcile_port fi update=0 [ -x "$BIN" ] && [ -n "$previous" ] && update=1 tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT archive="test-medidor_linux_${arch}.tar.gz" url="$BASE_URL/$VERSION" say "baixando $url/$archive" fetch "$url/$archive" "$tmp/$archive" || die "não foi possível baixar $url/$archive" fetch "$url/checksums.txt" "$tmp/checksums.txt" || die "não foi possível baixar $url/checksums.txt" say "conferindo o SHA-256" expected=$(awk -v f="$archive" '$2 == f || $2 == "*" f { print $1 }' "$tmp/checksums.txt") [ -n "$expected" ] || die "$archive não aparece em checksums.txt" actual=$(sha256 "$tmp/$archive") [ "$expected" = "$actual" ] || die "SHA-256 não confere (esperado $expected, obtido $actual)" tar -xzf "$tmp/$archive" -C "$tmp" sed "s#^ExecStart=/usr/bin/test-medidor#ExecStart=$BIN#" "$tmp/packaging/test-medidor.service" >"$tmp/unit" say "instalando $BIN" $SUDO install -m 0755 "$tmp/test-medidor" "$BIN.new" $SUDO mv -f "$BIN.new" "$BIN" if ! getent passwd test-medidor >/dev/null 2>&1; then say "criando o usuário de sistema test-medidor" $SUDO useradd --system --user-group --no-create-home --home-dir /var/lib/test-medidor --shell /usr/sbin/nologin test-medidor fi say "instalando o serviço $UNIT" $SUDO install -m 0644 "$tmp/unit" "$UNIT" $SUDO install -d -m 0755 "$(dirname "$ENV_FILE")" if [ -f "$ENV_FILE" ]; then say "mantendo a configuração existente em $ENV_FILE" else say "criando $ENV_FILE" $SUDO install -m 0640 -g test-medidor "$tmp/packaging/test-medidor.env" "$ENV_FILE" fi if [ -n "$cert_src" ]; then say "instalando o certificado próprio em $CERT_FILE e $KEY_FILE" install_pem "$cert_src" "$CERT_FILE" install_pem "$key_src" "$KEY_FILE" [ "$(configured TEST_MEDIDOR_CERT)" = "$CERT_FILE" ] || write_setting "$tmp" TEST_MEDIDOR_CERT "$CERT_FILE" [ "$(configured TEST_MEDIDOR_KEY)" = "$KEY_FILE" ] || write_setting "$tmp" TEST_MEDIDOR_KEY "$KEY_FILE" fi if [ -n "$domain" ] && [ "$domain" != "$previous" ]; then say "definindo TEST_MEDIDOR_DOMAIN=$domain" write_setting "$tmp" TEST_MEDIDOR_DOMAIN "$domain" fi [ -n "$domain" ] || domain=$previous if [ -n "$account" ] && [ "$account" != "$(configured TEST_MEDIDOR_ACCOUNT)" ]; then say "definindo TEST_MEDIDOR_ACCOUNT=$account" write_setting "$tmp" TEST_MEDIDOR_ACCOUNT "$account" fi [ -n "$account" ] || account=$(configured TEST_MEDIDOR_ACCOUNT) if [ -n "$port" ] && [ "$port" != "$(configured_port)" ]; then say "definindo TEST_MEDIDOR_HTTPS_LISTEN=:$port" write_setting "$tmp" TEST_MEDIDOR_HTTPS_LISTEN ":$port" fi listen="" if [ "$proxy" = 1 ]; then if [ -n "$(configured TEST_MEDIDOR_CERT)" ] || [ -n "$(configured TEST_MEDIDOR_KEY)" ]; then say "no modo proxy o certificado fica com o proxy: desativando TEST_MEDIDOR_CERT e TEST_MEDIDOR_KEY (os arquivos continuam em /etc/test-medidor)" unset_setting "$tmp" TEST_MEDIDOR_CERT unset_setting "$tmp" TEST_MEDIDOR_KEY fi if [ "$was_proxy" = 0 ]; then say "definindo TEST_MEDIDOR_BEHIND_PROXY=true" write_setting "$tmp" TEST_MEDIDOR_BEHIND_PROXY true fi configured_listen=$(configured TEST_MEDIDOR_LISTEN) listen=$listen_arg [ -n "$listen" ] || listen=$configured_listen [ -n "$listen" ] || listen=$DEFAULT_LISTEN if [ "$listen" != "$configured_listen" ]; then say "definindo TEST_MEDIDOR_LISTEN=$listen" write_setting "$tmp" TEST_MEDIDOR_LISTEN "$listen" fi elif [ "$was_proxy" = 1 ]; then say "saindo do modo proxy: o test-medidor volta a atender HTTPS sozinho" unset_setting "$tmp" TEST_MEDIDOR_BEHIND_PROXY unset_setting "$tmp" TEST_MEDIDOR_LISTEN fi https_port=$(configured_port) [ -n "$https_port" ] || https_port=443 address=$domain [ "$https_port" = 443 ] || [ "$proxy" = 1 ] || address="$domain:$https_port" own_cert=$(configured TEST_MEDIDOR_CERT) $SUDO systemctl daemon-reload version=$("$BIN" --version) say "iniciando o serviço test-medidor" started=$(date +%s) $SUDO systemctl enable test-medidor >/dev/null 2>&1 $SUDO systemctl restart test-medidor tries=0 while [ "$tries" -lt 3 ]; do sleep 1 tries=$((tries + 1)) $SUDO systemctl is-active --quiet test-medidor || break done $SUDO systemctl is-active --quiet test-medidor || fail_start if [ "$proxy" = 1 ]; then proxy_done return fi certificate="" if [ -n "$own_cert" ]; then certificate="Certificado próprio: $own_cert. Para trocar, rode o instalador de novo com --cert e --key." else say "aguardando o certificado do Let's Encrypt para $domain (até $CERT_WAIT segundos)" line=$(wait_for_certificate) case "$line" in *'"msg":"certificate ready"'*) not_after=$(json_field not_after "$line") say "certificado emitido pelo Let's Encrypt" certificate="Certificado do Let's Encrypt emitido, válido até ${not_after%%T*}; a renovação é automática." ;; *'"msg":"certificate not issued"'*) certificate_not_issued "$(json_field err "$line")" ;; *) say "o certificado ainda não saiu depois de $CERT_WAIT segundos; o test-medidor continua tentando" certificate="Certificado do Let's Encrypt ainda pendente. Acompanhe com: sudo journalctl -u test-medidor -f A linha \"certificate ready\" indica que ele saiu; \"certificate not issued\" traz o erro do Let's Encrypt." ;; esac fi if [ "$update" -eq 1 ]; then printf '\ntest-medidor %s atualizado e rodando para %s.\n' "$version" "$address" next="Se ainda não fez, cadastre" else printf '\ntest-medidor %s instalado e rodando para %s.\n' "$version" "$address" next="Próximo passo: cadastre" fi [ -z "$certificate" ] || printf '%s\n' "$certificate" cat <