Compare commits

..

18 Commits

Author SHA1 Message Date
Maxi Quoß 445b735b11 dont use v 2023-01-29 16:31:46 +01:00
Maxi Quoß fb30405396 dont use v 2023-01-29 16:30:51 +01:00
Maxi Quoß 49cf2b2607 try tag 2023-01-29 16:23:31 +01:00
Maxi Quoß 57bef8bb7e rawversion 2023-01-29 16:10:28 +01:00
Maxi Quoß 51e071bf22 try again with v 2023-01-29 15:58:48 +01:00
Maxi Quoß 4ce90f1f5f try again with v 2023-01-29 15:54:10 +01:00
Maxi Quoß 6fd289e1a7 workflow: tags 2023-01-29 15:47:56 +01:00
Maxi Quoß 8e7d4e814f workflow: env is broken 2023-01-29 15:37:54 +01:00
Maxi Quoß eb311bf289 workflow: env 2023-01-29 15:30:44 +01:00
Maxi Quoß fea958c4fc workflow: env 2023-01-29 15:26:54 +01:00
Maxi Quoß 8f59fb448f workflow: env 2023-01-29 15:22:46 +01:00
Maxi Quoß e303e7af64 workflow: docker meta image name 2023-01-29 15:20:43 +01:00
Maxi Quoß d47c21c3db docker: fix unzip 2023-01-29 15:15:03 +01:00
Maxi Quoß 4eb1c98729 docker: unzip -q 2023-01-29 15:05:48 +01:00
Maxi Quoß fe042e0003 workflow: remove v from version 2023-01-29 14:58:12 +01:00
Maxi Quoß dd4bc6c1e7 workflow: fix url 2023-01-29 14:54:19 +01:00
Maxi Quoß 5ee9b43aff workflow: remove v 2023-01-29 14:49:08 +01:00
Maxi Quoß 9d598b4c09 event tag 2023-01-29 14:46:01 +01:00
187 changed files with 13609 additions and 18876 deletions
-2
View File
@@ -2,8 +2,6 @@
.gitignore
.dockerignore
Dockerfile
Dockerfile.dev
data
README.md
frontend/.svelte-kit
-1
View File
@@ -1 +0,0 @@
* text=auto eol=lf
@@ -1,10 +0,0 @@
title: "<feature-name-goes-here>"
labels: ["feature-request"]
body:
- type: textarea
id: feature
attributes:
label: The feature
validations:
required: true
-2
View File
@@ -1,2 +0,0 @@
github: seriousm4x
ko_fi: seriousm4x
-70
View File
@@ -1,70 +0,0 @@
name: 🕷️ Bug report
description: Create a bug report to help the project improve
labels: ["bug"]
title: "[BUG] <title>"
body:
- type: markdown
attributes:
value: |
This issue form is for reporting bugs only!
If you have a feature or enhancement request, please use the [feature request][fr] section of our [GitHub Discussions][fr].
[fr]: https://github.com/seriousm4x/UpSnap/discussions/new?category=feature-requests
- type: textarea
validations:
required: true
attributes:
label: The bug
description: >-
Describe the issue you are experiencing here. Tell us what you were trying to do and what happened.
Provide a clear and concise description of what the problem is.
- type: markdown
attributes:
value: |
## Environment
- type: input
validations:
required: true
attributes:
label: The OS that UpSnap is running on
placeholder: Ubuntu 22.10, Debian, Arch...
- type: input
id: version
validations:
required: true
attributes:
label: Version of UpSnap
placeholder: 4.2.0
- type: textarea
validations:
required: true
attributes:
label: Your docker-compose.yml content
render: YAML
- type: textarea
id: repro
attributes:
label: Reproduction steps
description: "How do you trigger this bug? Please walk us through it step by step."
value: |
1.
2.
3.
...
render: bash
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: >
If you have any additional information for us, use the field below.
-8
View File
@@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: I have a question or need support
url: https://github.com/seriousm4x/UpSnap/discussions/categories/help-wanted
about: Please use our GitHub Discussion if you need help.
- name: Feature Request
url: https://github.com/seriousm4x/UpSnap/discussions/categories/feature-requests
about: Please use our GitHub Discussion for making feature requests.
-19
View File
@@ -1,19 +0,0 @@
# Sync repo to the Codeberg mirror
name: codeberg mirror
on:
push:
branches: ["master"]
tags:
- "*"
workflow_dispatch:
jobs:
codeberg:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: pixta-dev/repository-mirroring-action@v1
with:
target_repo_url: "git@codeberg.org:seriousm4x/UpSnap.git"
ssh_private_key: ${{ secrets.CODEBERG_SSH }}
+98
View File
@@ -0,0 +1,98 @@
name: Deploy release
on:
push:
tags:
- "3.*.*"
workflow_dispatch:
jobs:
goreleaser:
runs-on: self-hosted
steps:
# pull code
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
# install latest node
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: latest
# build sveltekit frontend
- name: Build frontend
run: |
npm --prefix=./frontend i
npm --prefix=./frontend run build
cp -r ./frontend/build/* ./backend/pb_public/
# setup go
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ">=1.19.5"
# build
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v4
with:
distribution: goreleaser
version: latest
args: release --rm-dist
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
docker:
needs: goreleaser
runs-on: self-hosted
steps:
# pull code
- name: Check Out Repo
uses: actions/checkout@v3
# image tags
- name: Docker meta
id: meta
uses: docker/metadata-action@v4
with:
images: |
ghcr.io/seriousm4x/UpSnap
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
# qemu
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
# docker buildx
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
# ghcr.io login
- name: Log in to the Container registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# build and push
- name: Build and push
id: docker_build
uses: docker/build-push-action@v3
with:
context: .
platforms: linux/amd64,linux/arm64,linux/arm/v7
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.meta.outputs.tags }}
build-args: |
VERSION=${{github.ref_name}}
-37
View File
@@ -1,37 +0,0 @@
name: go test
on:
push:
paths: backend/**
jobs:
check-runner:
runs-on: ubuntu-latest
outputs:
runner-label: ${{ steps.set-runner.outputs.runner-label }}
steps:
- name: Set runner
id: set-runner
run: |
runners=$(curl -s -H "Accept: application/vnd.github+json" -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" "https://api.github.com/repos/${{ github.repository }}/actions/runners")
available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ -n "$available" ]; then
echo "runner-label=self-hosted" >> "$GITHUB_OUTPUT"
else
echo "runner-label=ubuntu-latest" >> "$GITHUB_OUTPUT"
fi
build:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: "./backend/go.mod"
cache-dependency-path: "./backend/go.sum"
- name: Test
run: |
cd backend
go test -exec sudo -v ./...
-185
View File
@@ -1,185 +0,0 @@
name: release
on:
push:
tags:
- "*.*.*"
workflow_dispatch:
jobs:
check-runner:
runs-on: ubuntu-latest
outputs:
runner-label: ${{ steps.set-runner.outputs.runner-label }}
steps:
- name: Set runner
id: set-runner
run: |
runners=$(curl -s -H "Accept: application/vnd.github+json" \
-H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" \
"https://api.github.com/repos/${{ github.repository }}/actions/runners")
available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ -n "$available" ]; then
echo "runner-label=self-hosted" >> "$GITHUB_OUTPUT"
else
echo "runner-label=ubuntu-latest" >> "$GITHUB_OUTPUT"
fi
frontend:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: pnpm/action-setup@v6
with:
version: latest
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: latest
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Cache frontend build
uses: actions/cache@v5
with:
path: |
frontend/node_modules
frontend/.svelte-kit
key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-
- name: Build frontend
run: |
pnpm --prefix=./frontend install --frozen-lockfile --prefer-offline
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
tar -czf frontend-dist.tar.gz -C frontend/build .
- name: Upload frontend artifact
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend-dist.tar.gz
goreleaser:
needs:
- check-runner
- frontend
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download frontend artifact
uses: actions/download-artifact@v8
with:
name: frontend-dist
- name: Extract frontend into backend
run: |
mkdir -p backend/pb_public
tar -xzf frontend-dist.tar.gz -C backend/pb_public
git reset --hard
git clean -fd
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Cache Go build
uses: actions/cache@v5
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('backend/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
distribution: goreleaser
version: "~> v2"
args: release --clean
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUR_KEY: ${{ secrets.AUR_KEY }}
- name: Upload backend artifact
uses: actions/upload-artifact@v7
with:
name: backend-dist
path: backend/dist
docker:
needs:
- check-runner
- frontend
- goreleaser
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download backend artifact
uses: actions/download-artifact@v8
with:
name: backend-dist
path: backend/dist
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: |
ghcr.io/seriousm4x/UpSnap
seriousm4x/UpSnap
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ github.ref_name }}
+3 -41
View File
@@ -1,5 +1,5 @@
# Created by https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
# Edit at https://www.toptal.com/developers/gitignore?templates=go,node,svelte,visualstudiocode,macos
# Created by https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
# Edit at https://www.toptal.com/developers/gitignore?templates=go,visualstudiocode,svelte,node
### Go ###
# If you prefer the allow list template instead of the deny list, see community template:
@@ -24,43 +24,9 @@
# Go workspace file
go.work
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Node ###
# Logs
logs
!frontend/src/routes/logs/
*.log
npm-debug.log*
yarn-debug.log*
@@ -224,16 +190,12 @@ package
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
# End of https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
build
data
backend/pb_data
backend/pb_public/*
!backend/pb_public/.gitkeep
dist/
vite.config.js.timestamp*
frontend/src/lib/paraglide
+4 -17
View File
@@ -1,4 +1,4 @@
FROM alpine:3 AS downloader
FROM alpine:3 as downloader
ARG TARGETOS
ARG TARGETARCH
ARG TARGETVARIANT
@@ -8,25 +8,12 @@ WORKDIR /app
RUN wget https://github.com/seriousm4x/UpSnap/releases/download/${VERSION}/UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
unzip UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
rm -f UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
chmod +x upsnap &&\
apk update &&\
apk add --no-cache libcap &&\
setcap 'cap_net_raw=+p' ./upsnap
chmod +x upsnap
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
apk add --no-cache ca-certificates nmap samba-common-tools &&\
rm -rf /var/cache/apk/*
RUN addgroup -g 1000 upsnap &&\
adduser -G upsnap -D -H -u 1000 upsnap -s /sbin/nologin
WORKDIR /app
COPY --from=downloader /app/upsnap upsnap
LABEL org.opencontainers.image.source="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.url="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.licenses="MIT"
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
CMD ["serve","--http","${UPSNAP_HTTP_LISTEN}"]
ENTRYPOINT ["/app/upsnap"]
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
-29
View File
@@ -1,29 +0,0 @@
FROM node:bookworm AS node
WORKDIR /app
COPY frontend/ .
RUN npm i -g pnpm &&\
pnpm i &&\
pnpm run build
FROM golang:alpine AS go
WORKDIR /app
COPY backend/ .
COPY --from=node /app/build ./pb_public
ENV CGO_ENABLED=0
RUN go build -o upsnap main.go &&\
chmod +x upsnap &&\
apk update &&\
apk add --no-cache libcap &&\
setcap 'cap_net_raw=+ep' ./upsnap
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=go /app/upsnap upsnap
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
ENTRYPOINT ["sh", "-c", "./upsnap serve --http ${UPSNAP_HTTP_LISTEN}"]
+36 -173
View File
@@ -1,193 +1,56 @@
<div align="center" width="100%">
<img src="frontend/static/gopher.svg" width="150" />
</div>
# UpSnap v3
<div align="center" width="100%">
<h2>UpSnap</h2>
<p>A simple wake on lan web app written with SvelteKit, Go and PocketBase.</p>
<div>
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/UpSnap?style=flat&label=Stars" /></a>
<a target="_blank" href="https://hub.docker.com/r/seriousm4x/upsnap"><img src="https://img.shields.io/docker/pulls/seriousm4x/upsnap?label=docker%20hub%20pulls" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total?label=binary%20downloads" /></a>
</div>
<div>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag&label=Latest%20release" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
</div>
</div>
## Stable version can be found on [v2 branch](https://github.com/seriousm4x/UpSnap/tree/v2)
## ✨ Features
> This is the dev branch for v3. It's very much in progress but will have a release candidate once all boxes below are checked.
- 🚀 One-Click Device Wake-Up Dashboard
- ⏰ Timed Events via Cron for Automation
- 🔌 Ping Any Port You Choose
- 🔍 Discover Devices with Network Scanning (nmap required)
- 📌 Optional IP Address Tracking per Device via periodic ARP scan (nmap required, no extra privileges beyond network scanning)
- 📡 Support using a Fully Qualified Domain Name for a device (refer to the Wiki: [Use FQDN](https://github.com/seriousm4x/UpSnap/wiki/Use-FQDN))
- ❎️ Shutdown Devices with a Custom Command
- 👤 Secured User Management
- 📋 Superuser Logs Page
- 🌐 i18n support for [these](/frontend/translations) languages
- 🎨 35 Themes
- 🐳 [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
- 🏠 Self-Hostable
## 📸 Screenshots
| Silk | Dim |
| ---------------------------------- | --------------------------------- |
| ![](/assets/home-light.webp) | ![](/assets/home-dark.webp) |
| ![](/assets/account-light.webp) | ![](/assets/account-dark.webp) |
| ![](/assets/new-manual-light.webp) | ![](/assets/new-manual-dark.webp) |
| ![](/assets/new-scan-light.webp) | ![](/assets/new-scan-dark.webp) |
| ![](/assets/settings-light.webp) | ![](/assets/settings-dark.webp) |
| ![](/assets/users-light.webp) | ![](/assets/users-dark.webp) |
## 🚀 Run the binary
Just download the latest binary from the [release page](https://github.com/seriousm4x/UpSnap/releases) and run it.
```bash
sudo ./upsnap serve --http=0.0.0.0:8090
```
To run as non-root (Linux only), refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
## 🐳 Run in Docker
Just pull and run the image: `docker run --network=host seriousm4x/upsnap:latest` or you can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
To run as non-root, refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
Set `UPSNAP_LOG_LEVEL` to `DEBUG`, `INFO`, `WARN`, `ERROR`, or `OFF` to control UpSnap console logs. Default is `INFO`. PocketBase log persistence and retention remain configurable in PocketBase settings. PocketBase's `--dev` mode prints all logs regardless of this setting.
### Change port (Docker)
If you want to change the port from 8090 to something else, change the following (5000 in this case):
```yml
environment:
- UPSNAP_HTTP_LISTEN=0.0.0.0:5000
```
## ❎️ Shutting Down Devices
To shutdown devices, refer to the Wiki: [How to use shutdowns](https://github.com/seriousm4x/UpSnap/wiki/How-to-use-shutdowns)
## Reverse Proxy
**Caddy example**
```
upsnap.example.com {
reverse_proxy localhost:8090
}
```
## Run in sub path
You can run UpSnap on a different path than `/`, e.g. `/upsnap-sub-path/`. To do this in caddy, set the following:
```
http://localhost:8091 {
handle /upsnap-sub-path/* {
uri strip_prefix /upsnap-sub-path
reverse_proxy localhost:8090
}
}
```
Or nginx:
```
http {
server {
listen 8091;
server_name localhost;
location /upsnap-sub-path/ {
proxy_pass http://localhost:8090/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
```
Paths must end with a trailing `/`.
## 🐧 Install from the [AUR](https://aur.archlinux.org/packages/upsnap-bin)
```bash
yay -Sy upsnap-bin
```
## 🔒 User permissions
UpSnap offers unique access for each user, per device. While admins have all permissions, they can assign specific rights to users such as displaying/hiding a device, accessing device editing, deleting and powering devices on/off. See the last screenshot in the [📸 Screenshots section](#-screenshots).
## 🌍 Exposing to the open web
Although UpSnap has user authorisation, it is **not recommended to expose it to the open web** and make it accessible by everyone!
**Reason**: The shutdown device command is basically a command piped to #sh (possibly as root user). If anyone gains unauthorized access and can abuse this API route in any way, the attacker has access to a (root) shell on your local network.
**Recommended**: If you need access from outside your network, please use a VPN. Wireguard or OpenVPN is your way to go.
## 🌐 Help translating
UpSnap is available in the following languages so far:
- 🇸🇦 **Arabic (Saudi Arabia)** (ar-SA)
- 🇧🇬 **Bulgarian (Bulgaria)** (bg-BG)
- 🇨🇿 **Czech (Czech republic)** (cs-CZ)
- 🇩🇪 **German (Germany)** (de-DE)
- 🇬🇷 **Greek (Greece)** (el-GR)
- 🇺🇸 **English (United States)** (en-US)
- 🇪🇸 **Spanish (Spain)** (es-ES)
- 🇫🇷 **French (France)** (fr-FR)
- 🇮🇳 **Hindi (India)** (hi-IN)
- 🇮🇩 **Bahasa (Indonesia)** (id-ID)
- 🇮🇹 **Italian (Italy)** (it-IT)
- 🇯🇵 **Japanese (Japan)** (ja-JP)
- 🇰🇷 **Korean (Republic of Korea)** (ko-KR)
- 🇳🇴 **Norwegian (Norway)** (nb-NO)
- 🇳🇱 **Dutch (Netherlands)** (nl-NL)
- 🇵🇱 **Polish (Poland)** (pl-PL)
- 🇧🇷 **Portuguese (Brazil)** (pt-BR)
- 🇵🇹 **Portuguese (Portugal)** (pt-PT)
- 🇷🇺 **Russian (Russia)** (ru-RU)
- 🇺🇦 **Ukrainian (Ukrain)** (uk-UA)
- 🇻🇳 **Vietnamese (Vietnam)** (vi-VN)
- 🇨🇳 **Chinese (China)** (zh-CN)
- 🇹🇼 **Chinese (Taiwan)** (zh-TW)
**If you want to contribute and help translating, check the wiki: [How to add languages](https://github.com/seriousm4x/UpSnap/wiki/How-to-add-languages)**
## 🔧 Help developing
## Help developing
Fork this branch and clone it.
1. Start backend
```bash
```sh
cd backend
go mod tidy
go run main.go serve
```
Log in to [http://127.0.0.1:8090/\_/](http://127.0.0.1:8090/_/), create an admin user and add some devices.
2. Start frontend
```bash
```sh
cd frontend
pnpm i
pnpm run dev
```
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
Open up [http://localhost:5173/](http://localhost:5173/)
## To do
- frontend
- [x] ~~add rest of settings page~~
- [x] ~~form for adding new devices~~
- [x] ~~add per device settings~~
- [x] ~~theme toggle button~~
- [x] ~~add device ports to cards~~
- [x] ~~settings: add network scan~~
- [x] ~~settings: add option for website title~~
- backend
- [x] ~~make sure ping works~~
- [x] ~~make sure arp works~~
- [x] ~~make sure wake works~~
- [x] ~~add shutdown command~~
- [x] ~~add scheduled wake~~
- [x] [~~#34 Add support for WOL passwords~~](https://github.com/seriousm4x/UpSnap/issues/34)
- [x] [~~#33 Seemingly High Ram usage~~](https://github.com/seriousm4x/UpSnap/issues/33)
- [x] [~~#32 API available?~~](https://github.com/seriousm4x/UpSnap/issues/32)
- [x] ~~add db import from v2~~
- [x] ~~move docker images to github packages and setup new workflow file~~
- [x] ~~create dockerfile and docker-compose.yml~~
Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

-6
View File
@@ -1,6 +0,0 @@
#!/usr/bin/env bash
for i in *.png; do
magick -quality 100 "$i" "$(basename "$i" .png)".webp
rm "$i"
done
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Executable → Regular
+5 -50
View File
@@ -1,6 +1,5 @@
version: 2
release:
draft: false
# draft: true
prerelease: auto
before:
hooks:
@@ -10,71 +9,27 @@ builds:
env:
- CGO_ENABLED=0
ldflags:
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Tag }}
- -s -w
goos:
- linux
- windows
- darwin
- freebsd
goarch:
- amd64
- arm64
- arm
- riscv64
goarm:
- "6"
- "7"
- 7
ignore:
- goos: windows
goarch: arm
- goos: darwin
goarch: arm
- goos: freebsd
goarch: arm
archives:
- formats: ["zip"]
- format: zip
checksum:
name_template: "checksums.txt"
snapshot:
version_template: "{{ .Version }}"
name_template: "{{ .Version }}"
changelog:
use: github
sort: asc
groups:
- title: Features
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 0
- title: "Bug fixes"
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
order: 1
- title: "Go dependencies"
regexp: '^.*?go-dep(\([[:word:]]+\))??!?:.+$'
order: 3
- title: "Npm dependencies"
regexp: '^.*?npm-dep(\([[:word:]]+\))??!?:.+$'
order: 4
- title: "Github Actions"
regexp: '^.*?gh-action(\([[:word:]]+\))??!?:.+$'
order: 5
- title: Others
order: 2
git:
ignore_tags:
- "{{ if not .Prerelease}}*beta*{{ end }}"
# aurs:
# - name: upsnap-bin
# homepage: https://github.com/seriousm4x/UpSnap
# description: "A simple wake on lan web app written with SvelteKit, Go and PocketBase."
# maintainers:
# - "SeriousM4x <maxi at quoss dot org>"
# license: "MIT"
# private_key: "{{ .Env.AUR_KEY }}"
# git_url: "ssh://aur@aur.archlinux.org/upsnap-bin.git"
# package: |-
# install -Dm755 "./upsnap" "${pkgdir}/usr/bin/upsnap"
# skip_upload: auto
# optdepends:
# - "nmap: to scan for network devices"
# commit_author:
# name: goreleaserbot
# email: bot@goreleaser.com
+53 -217
View File
@@ -1,266 +1,102 @@
package cronjobs
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/models"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
"github.com/seriousm4x/upsnap/backend/logger"
"github.com/seriousm4x/upsnap/backend/networking"
)
var (
PingRunning = false
WakeShutdownRunning = false
CronPing = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
CronWakeShutdown = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
)
var Devices []*models.Record
var CronPing *cron.Cron
var CronWakeShutdown *cron.Cron
func SetPingJobs(app core.App) {
log := logging.Logger(app)
// remove existing jobs
for _, job := range CronPing.Entries() {
CronPing.Remove(job.ID)
}
settingsPrivateRecords, err := app.FindAllRecords("settings_private")
func RunPing(app *pocketbase.PocketBase) {
settingsRecords, err := app.Dao().FindRecordsByExpr("settings")
if err != nil {
log.Error("Failed to load private settings", "error", err)
return
logger.Error.Println(err)
}
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
// skip cron if no realtime clients connected and lazy_ping is turned on
// init cronjob
CronPing = cron.New()
CronPing.AddFunc(settingsRecords[0].GetString("interval"), func() {
// skip cron if no realtime clients connected
realtimeClients := len(app.SubscriptionsBroker().Clients())
if realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping") {
if realtimeClients == 0 {
return
}
devices, err := app.FindAllRecords("devices")
if err != nil {
log.Error("Failed to load devices for ping job", "error", err)
return
}
// expand ports field
expandFetchFunc := func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
expandFetchFunc := func(c *models.Collection, ids []string) ([]*models.Record, error) {
return app.Dao().FindRecordsByIds(c.Id, ids, nil)
}
merr := app.ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
merr := app.Dao().ExpandRecords(Devices, []string{"ports"}, expandFetchFunc)
if len(merr) > 0 {
log.Error("Failed to expand device ports", "errors", merr)
return
}
for _, device := range devices {
// ping device
go func(d *core.Record) {
status := d.GetString("status")
if status == "pending" {
return
}
isUp, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device", "device", d.GetString("name"), "error", err)
}
if isUp {
if status == "online" {
return
}
d.Set("status", "online")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned on", "device", d.GetString("name"))
for _, device := range Devices {
// ping
go func(device *models.Record) {
oldStatus := device.Get("status")
newStatus := networking.PingDevice(device)
if newStatus {
if oldStatus == "offline" || oldStatus == "" {
device.Set("status", "online")
app.Dao().SaveRecord(device)
}
} else {
if status == "offline" {
return
}
d.Set("status", "offline")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned off", "device", d.GetString("name"))
if oldStatus == "online" || oldStatus == "" {
device.Set("status", "offline")
app.Dao().SaveRecord(device)
}
}
}(device)
// ping ports
go func(d *core.Record) {
ports, err := app.FindRecordsByIds("ports", d.GetStringSlice("ports"))
// scan ports
go func(device *models.Record) {
ports, err := app.Dao().FindRecordsByIds("ports", device.GetStringSlice("ports"))
if err != nil {
log.Error("Failed to load device ports", "device", d.GetString("name"), "error", err)
return
}
deviceIP, resolveErr := networking.ResolveToIPAddr(d.GetString("ip"))
if resolveErr != nil {
log.Error("Failed to resolve device IP", "device", d.GetString("name"), "error", resolveErr)
logger.Error.Println(err)
}
for _, port := range ports {
isUp := false
// No IP found means the device is down.
if resolveErr == nil && deviceIP != "" {
var checkErr error
isUp, checkErr = networking.CheckPort(deviceIP, port.GetString("number"))
if checkErr != nil {
log.Error("Failed to check port", "device", d.GetString("name"), "port", port.GetString("number"), "error", checkErr)
}
}
isUp := networking.CheckPort(device.GetString("ip"), port.GetString("number"))
if isUp != port.GetBool("status") {
port.Set("status", isUp)
if err := app.Save(port); err != nil {
log.Error("Failed to save port status", "device", d.GetString("name"), "port", port.GetString("number"), "error", err)
}
app.Dao().SaveRecord(port)
device.RefreshUpdated()
app.Dao().SaveRecord(device)
}
}
}(device)
}
})
// update ip addresses of opted-in devices from a periodic arp scan
trackIpInterval := settingsPrivateRecords[0].GetString("track_ip_interval")
if trackIpInterval != "" {
if _, err := CronPing.AddFunc(trackIpInterval, func() {
// pause scans if no realtime clients connected and lazy_ping is
// turned on; a catch-up sweep runs when the next client connects
realtimeClients := len(app.SubscriptionsBroker().Clients())
iptracking.PeriodicSweep(app, realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping"))
}); err != nil {
log.Error("Failed to add IP tracking cron job", "error", err)
}
}
CronPing.Run()
}
func SetWakeShutdownJobs(app core.App) {
log := logging.Logger(app)
// remove existing jobs
for _, job := range CronWakeShutdown.Entries() {
CronWakeShutdown.Remove(job.ID)
}
devices, err := app.FindAllRecords("devices")
if err != nil {
log.Error("Failed to load devices for wake and shutdown jobs", "error", err)
return
}
for _, dev := range devices {
wake_cron := dev.GetString("wake_cron")
wake_cron_enabled := dev.GetBool("wake_cron_enabled")
shutdown_cron := dev.GetString("shutdown_cron")
shutdown_cron_enabled := dev.GetBool("shutdown_cron_enabled")
func RunWakeShutdown() {
CronWakeShutdown = cron.New()
for _, device := range Devices {
wake_cron := device.GetString("wake_cron")
wake_cron_enabled := device.GetBool("wake_cron_enabled")
shutdown_cron := device.GetString("shutdown_cron")
shutdown_cron_enabled := device.GetBool("shutdown_cron_enabled")
if wake_cron_enabled && wake_cron != "" {
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for wake job", "device", dev.GetString("name"), "error", err)
return
}
if d.GetString("status") == "pending" {
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before wake", "device", d.GetString("name"), "error", err)
return
}
if isOnline {
return
}
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
return
}
if err := networking.WakeDevice(app, d, "cron"); err != nil {
log.Error("Wake job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "offline")
} else {
d.Set("status", "online")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after wake", "device", d.GetString("name"), "error", err)
CronWakeShutdown.AddFunc(wake_cron, func() {
if err := networking.WakeDevice(device); err != nil {
logger.Error.Println(err)
}
})
if err != nil {
log.Error("Failed to add wake cron job", "device", dev.GetString("name"), "error", err)
}
}
if shutdown_cron_enabled && shutdown_cron != "" {
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for shutdown job", "device", dev.GetString("name"), "error", err)
return
}
if d.GetString("status") == "pending" {
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before shutdown", "device", d.GetString("name"), "error", err)
return
}
if !isOnline {
return
}
// The status can be stale when lazy ping marks devices offline after
// the last client disconnects. The reachability check above is the
// authoritative signal for whether a shutdown command may run.
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
}
if err := networking.ShutdownDevice(app, d, "cron"); err != nil {
log.Error("Shutdown job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "online")
} else {
d.Set("status", "offline")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after shutdown", "device", d.GetString("name"), "error", err)
CronWakeShutdown.AddFunc(shutdown_cron, func() {
if err := networking.ShutdownDevice(device); err != nil {
logger.Error.Println(err)
}
})
if err != nil {
log.Error("Failed to add shutdown cron job", "device", dev.GetString("name"), "error", err)
}
}
}
}
func StartWakeShutdown() {
WakeShutdownRunning = true
go CronWakeShutdown.Run()
}
func StopWakeShutdown(app core.App) {
if WakeShutdownRunning {
logging.Logger(app).Info("Stopping wake and shutdown cron jobs")
CronWakeShutdown.Stop()
}
WakeShutdownRunning = false
}
func StartPing() {
PingRunning = true
go CronPing.Run()
}
func StopPing(app core.App) {
if PingRunning {
logging.Logger(app).Info("Stopping ping cron jobs")
CronPing.Stop()
}
PingRunning = false
}
func StopAll(app core.App) {
StopPing(app)
StopWakeShutdown(app)
CronWakeShutdown.Run()
}
+85 -42
View File
@@ -1,53 +1,96 @@
module github.com/seriousm4x/upsnap
module github.com/seriousm4x/upsnap/backend
go 1.27
go 1.19
require (
ganigeorgiev.com/pocketbase/dbx v1.13.0
ganigeorgiev.com/pocketbase/pocketbase v0.41.1
github.com/godbus/dbus/v5 v5.2.2
github.com/holoplot/go-avahi v1.0.1
github.com/go-ping/ping v1.1.0
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/prometheus-community/pro-bing v0.9.1
github.com/pocketbase/dbx v1.8.0
github.com/pocketbase/pocketbase v0.11.2
github.com/robfig/cron/v3 v3.0.1
golang.org/x/net v0.62.0
golang.org/x/sys v0.49.0
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78
)
require (
ganigeorgiev.com/fexpr v0.7.0 // indirect
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/AlecAivazis/survey/v2 v2.3.6 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/aws/aws-sdk-go v1.44.178 // indirect
github.com/aws/aws-sdk-go-v2 v1.17.3 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.10 // indirect
github.com/aws/aws-sdk-go-v2/config v1.18.8 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.13.8 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.21 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.47 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.27 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.28 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.11 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.22 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.30.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.12.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.18.0 // indirect
github.com/aws/smithy-go v1.13.5 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/domodwyer/mailyak/v3 v3.3.4 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.1 // indirect
github.com/ganigeorgiev/fexpr v0.3.0 // indirect
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
github.com/golang-jwt/jwt/v4 v4.4.3 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/google/wire v0.5.0 // indirect
github.com/googleapis/gax-go/v2 v2.7.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.2.0 // indirect
github.com/mdlayher/socket v0.7.0 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/stretchr/testify v1.11.1 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/image v0.47.0 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/text v0.43.0 // indirect
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.60.1 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/josharian/native v1.0.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-sqlite3 v1.14.16 // indirect
github.com/mdlayher/ethernet v0.0.0-20190313224307-5b5fc417d966 // indirect
github.com/mdlayher/packet v1.0.0 // indirect
github.com/mdlayher/socket v0.2.1 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/remyoudompheng/bigfft v0.0.0-20220927061507-ef77025ab5aa // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.6.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.28.0 // indirect
golang.org/x/crypto v0.5.0 // indirect
golang.org/x/image v0.3.0 // indirect
golang.org/x/mod v0.7.0 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/oauth2 v0.4.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/term v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.5.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/api v0.106.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
google.golang.org/grpc v1.52.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
lukechampine.com/uint128 v1.2.0 // indirect
modernc.org/cc/v3 v3.40.0 // indirect
modernc.org/ccgo/v3 v3.16.13 // indirect
modernc.org/libc v1.22.2 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/opt v0.1.3 // indirect
modernc.org/sqlite v1.20.2 // indirect
modernc.org/strutil v1.1.3 // indirect
modernc.org/token v1.1.0 // indirect
)
+2761 -115
View File
File diff suppressed because it is too large Load Diff
-136
View File
@@ -1,136 +0,0 @@
// Package iptracking updates the stored ip addresses of opted-in devices by
// scanning their local subnets for their mac addresses.
package iptracking
import (
"net"
"sync/atomic"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
)
var sweepRunning atomic.Bool
// sweepOwed marks that a periodic sweep was skipped while no realtime
// clients were connected, so the next client to connect gets a catch-up
// sweep. Starts true so the first client after boot gets fresh ips.
var sweepOwed atomic.Bool
func init() {
sweepOwed.Store(true)
}
// nmapScan is a seam for tests to stub out the privileged nmap invocation
var nmapScan = networking.NmapScan
// TrackAllSubnets scans the local subnets of devices with ip tracking enabled
// and updates their ip address if their mac address is found at a different
// one. Non-scannable subnets are silently skipped, but their devices can
// still be updated by another subnet's scan that finds their mac address,
// as long as the new ip stays within the device's own subnet.
func TrackAllSubnets(app core.App) {
log := logging.Logger(app)
// skip if the previous sweep is still running
if !sweepRunning.CompareAndSwap(false, true) {
return
}
defer sweepRunning.Store(false)
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
log.Error("Failed to load devices for IP tracking", "error", err)
return
}
// collect the unique scannable subnets of the tracked devices
subnets := make(map[string]*net.IPNet)
for _, device := range devices {
subnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil {
log.Error("Failed to determine device subnet for IP tracking", "device", device.GetString("name"), "error", err)
continue
}
if networking.ValidateScannableSubnet(subnet) != nil {
continue
}
subnets[subnet.String()] = subnet
}
for cidr, subnet := range subnets {
if err := TrackOneSubnet(app, subnet); err != nil {
log.Error("IP tracking scan failed", "subnet", cidr, "error", err)
}
}
}
// PeriodicSweep runs the scheduled sweep, or skips it when paused — no
// realtime clients connected while lazy_ping is on — owing a catch-up
// sweep to the next client that connects.
func PeriodicSweep(app core.App, pause bool) {
if pause {
sweepOwed.Store(true)
return
}
TrackAllSubnets(app)
}
// CatchUpSweep runs a sweep if one is owed, i.e. the periodic sweep was
// skipped while nobody was connected or hasn't run since boot. Clients
// connecting while sweeps run on schedule trigger nothing.
func CatchUpSweep(app core.App) {
if !sweepOwed.CompareAndSwap(true, false) {
return
}
TrackAllSubnets(app)
}
// TrackOneSubnet runs an nmap scan of the given subnet and updates the ip
// address of any ip-tracked device whose mac address is found at a new
// address within its own subnet. Returns an error for a non-scannable subnet.
func TrackOneSubnet(app core.App, subnet *net.IPNet) error {
log := logging.Logger(app)
if err := networking.ValidateScannableSubnet(subnet); err != nil {
return err
}
scan, err := nmapScan(subnet.String())
if err != nil {
return err
}
macToIp := scan.MacToIP()
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
return err
}
for _, device := range devices {
parsedMac, err := net.ParseMAC(device.GetString("mac"))
if err != nil {
continue
}
newIp, ok := macToIp[parsedMac.String()]
if !ok || newIp == device.GetString("ip") {
continue
}
// only move a device within its own subnet, so that a scan can't
// relocate devices tracked on other subnets that see the same mac
deviceSubnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil || !deviceSubnet.Contains(net.ParseIP(newIp)) {
continue
}
oldIP := device.GetString("ip")
device.Set("ip", newIp)
// only write the changed ip field to avoid clobbering concurrent
// status updates from the ping and wake/shutdown cronjobs
device.IgnoreUnchangedFields(true)
if err := app.Save(device); err != nil {
log.Error("Failed to save tracked device IP", "device", device.GetString("name"), "error", err)
} else {
log.Info("Device IP changed", "device", device.GetString("name"), "from", oldIP, "to", newIp)
}
}
return nil
}
-347
View File
@@ -1,347 +0,0 @@
package iptracking
import (
"encoding/xml"
"fmt"
"net"
"strings"
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
"github.com/seriousm4x/upsnap/networking"
// register the app migrations so test apps get the real schema
_ "github.com/seriousm4x/upsnap/migrations"
)
// newTestApp returns a throwaway app with all migrations applied.
func newTestApp(t *testing.T) *tests.TestApp {
t.Helper()
app, err := tests.NewTestApp(t.TempDir())
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
t.Cleanup(app.Cleanup)
return app
}
func buildDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
collection, err := app.FindCollectionByNameOrId("devices")
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
device := core.NewRecord(collection)
device.Set("name", name)
device.Set("ip", ip)
device.Set("netmask", netmask)
device.Set("mac", mac)
device.Set("track_ip", trackIp)
return device
}
func newDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.Save(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// newLegacyDevice saves a device bypassing field validation, like rows
// created before the ip and mac format rules existed.
func newLegacyDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.SaveNoValidate(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// stubScan replaces the nmap seam with a canned scan reporting the given
// mac addresses at the given ips, and returns the list of scanned ranges.
func stubScan(t *testing.T, macToHostIp map[string]string) *[]string {
t.Helper()
var sample strings.Builder
sample.WriteString("<nmaprun>")
for mac, ip := range macToHostIp {
fmt.Fprintf(&sample, `<host><address addr=%q addrtype="ipv4"/><address addr=%q addrtype="mac"/></host>`, ip, mac)
}
sample.WriteString("</nmaprun>")
scan := networking.Nmaprun{}
if err := xml.Unmarshal([]byte(sample.String()), &scan); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
var scanned []string
orig := nmapScan
nmapScan = func(scanRange string) (networking.Nmaprun, error) {
scanned = append(scanned, scanRange)
return scan, nil
}
t.Cleanup(func() { nmapScan = orig })
return &scanned
}
func mustSubnet(t *testing.T, cidr string) *net.IPNet {
t.Helper()
_, subnet, err := net.ParseCIDR(cidr)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return subnet
}
// The loopback /16 passes the scannable checks on any host, making it the
// only subnet a test can scan without depending on the environment.
const (
testSubnet = "127.0.0.0/16"
testNetmask = "255.255.0.0"
)
func TestTrackOneSubnetSkipsUntrackedDevices(t *testing.T) {
app := newTestApp(t)
device := newDevice(t, app, "untracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:EE:01", false)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != "127.0.0.50" {
t.Errorf("Ip of device without track_ip changed to %s", ip)
}
}
func TestTrackOneSubnetSkipPaths(t *testing.T) {
app := newTestApp(t)
saves := 0
app.OnRecordUpdate("devices").BindFunc(func(e *core.RecordEvent) error {
saves++
return e.Next()
})
testCases := []struct {
name string
ip string
mac string
legacy bool
}{
// A device mac that can't be parsed never matches
{
name: "Invalid Mac",
ip: "127.0.0.50",
mac: "not-a-mac",
legacy: true,
},
// A device mac missing from the scan results is left alone
{
name: "Mac Not In Scan",
ip: "127.0.0.50",
mac: "AA:BB:CC:DD:EE:02",
},
// A device ip without a computable subnet is never moved
{
name: "Invalid Device Ip",
ip: "999.999.999.999",
mac: "AA:BB:CC:DD:EE:01",
legacy: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
create := newDevice
if tc.legacy {
create = newLegacyDevice
}
device := create(t, app, tc.name, tc.ip, testNetmask, tc.mac, true)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.ip {
t.Errorf("Ip mismatch: expected %s, got %s", tc.ip, ip)
}
if saves != 0 {
t.Errorf("Expected no record updates, got %d", saves)
}
})
}
}
func TestTrackOneSubnetUnscannable(t *testing.T) {
app := newTestApp(t)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
scanned := stubScan(t, nil)
if err := TrackOneSubnet(app, mustSubnet(t, "192.0.2.0/24")); err == nil {
t.Error("Expected error but got none")
}
if len(*scanned) != 0 {
t.Errorf("Expected no scans of an unscannable subnet, got %v", *scanned)
}
}
func TestTrackOneSubnetSameSubnetGuard(t *testing.T) {
app := newTestApp(t)
testCases := []struct {
name string
ip string
netmask string
mac string
scanMac string
foundIp string
wantIp string
}{
// A move within the device's own subnet is applied, with the
// stored dashed lower case mac matching the scanned
// colon-separated upper case one
{
name: "Within Own Subnet",
ip: "127.0.0.50",
netmask: testNetmask,
mac: "aa-bb-cc-dd-01-01",
scanMac: "AA:BB:CC:DD:01:01",
foundIp: "127.0.0.99",
wantIp: "127.0.0.99",
},
// The device's own subnet bounds the move, not the scanned one
{
name: "Narrower Subnet Within Scan",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:02",
foundIp: "127.0.5.9",
wantIp: "127.0.5.9",
},
// A found ip outside the device's narrower subnet is not applied,
// even though it is inside the scanned subnet
{
name: "Outside Own Subnet",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:03",
foundIp: "127.0.6.9",
wantIp: "127.0.5.5",
},
// A device from a disjoint subnet is never moved into the scanned one
{
name: "Disjoint Subnet",
ip: "10.9.9.9",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:04",
foundIp: "127.0.0.99",
wantIp: "10.9.9.9",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := newDevice(t, app, tc.name, tc.ip, tc.netmask, tc.mac, true)
scanMac := tc.scanMac
if scanMac == "" {
scanMac = tc.mac
}
stubScan(t, map[string]string{scanMac: tc.foundIp})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.wantIp {
t.Errorf("Ip mismatch: expected %s, got %s", tc.wantIp, ip)
}
})
}
}
// A paused periodic sweep scans nothing and owes a catch-up sweep, which
// runs at most once until the next pause; an unpaused sweep scans directly.
func TestPeriodicSweepAndCatchUp(t *testing.T) {
app := newTestApp(t)
newDevice(t, app, "tracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:09:01", true)
scanned := stubScan(t, map[string]string{"AA:BB:CC:DD:09:01": "127.0.0.99"})
PeriodicSweep(app, true)
if len(*scanned) != 0 {
t.Fatalf("Expected no scans while paused, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Fatalf("Expected one scan after a paused sweep, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Errorf("Expected no scan when none is owed, got %v", *scanned)
}
PeriodicSweep(app, false)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to scan, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to owe nothing, got %v", *scanned)
}
}
// TrackAllSubnets scans each unique scannable subnet once, silently skips the
// rest, and updates any tracked device found at a new ip within its own
// subnet — even one whose own subnet couldn't be scanned.
func TestTrackAllSubnets(t *testing.T) {
app := newTestApp(t)
first := newDevice(t, app, "first", "127.0.0.10", testNetmask, "AA:BB:CC:DD:02:01", true)
second := newDevice(t, app, "second", "127.0.0.20", testNetmask, "AA:BB:CC:DD:02:02", true)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
unscannable := newDevice(t, app, "unscannable", "192.0.2.5", "255.255.255.0", "AA:BB:CC:DD:02:03", true)
// a /8 subnet is too large to scan but contains the found ip
wide := newDevice(t, app, "wide", "127.0.0.60", "255.0.0.0", "AA:BB:CC:DD:02:04", true)
scanned := stubScan(t, map[string]string{
"AA:BB:CC:DD:02:01": "127.0.0.11",
"AA:BB:CC:DD:02:02": "127.0.0.21",
"AA:BB:CC:DD:02:04": "127.0.0.61",
})
TrackAllSubnets(app)
if len(*scanned) != 1 || (*scanned)[0] != testSubnet {
t.Errorf("Expected a single scan of %s, got %v", testSubnet, *scanned)
}
wantIps := map[string]string{
first.Id: "127.0.0.11",
second.Id: "127.0.0.21",
unscannable.Id: "192.0.2.5",
wide.Id: "127.0.0.61",
}
for id, wantIp := range wantIps {
fresh, err := app.FindRecordById("devices", id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != wantIp {
t.Errorf("Ip mismatch for %s: expected %s, got %s", fresh.GetString("name"), wantIp, ip)
}
}
}
+30
View File
@@ -0,0 +1,30 @@
package logger
import (
"log"
"os"
)
const (
flags = log.Ldate | log.Ltime | log.Lshortfile
)
var (
Info = log.New(os.Stdout, "[INFO] ", flags)
Debug = log.New(os.Stdout, "[DEBUG] ", flags)
Warning = log.New(os.Stdout, "[WARNING] ", flags)
Error = log.New(os.Stderr, "[ERROR] ", flags)
)
func init() {
// TODO: decide if you want to log to a file to max
// output := io.MultiWriter(os.Stdout, logFile)
output := os.Stdout
Info.SetOutput(output)
Error.SetOutput(output)
Debug.SetOutput(output)
log.SetOutput(Debug.Writer())
log.SetPrefix("[DEBUG]")
log.SetFlags(flags)
}
-102
View File
@@ -1,102 +0,0 @@
package logging
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"runtime"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
var consoleHandler slog.Handler
// ConfigureConsole sets console output for UpSnap logs. PocketBase persistence
// remains controlled by PocketBase's built-in log settings.
func ConfigureConsole(level string) error {
level = strings.TrimSpace(level)
if level == "" {
level = "INFO"
}
if strings.EqualFold(level, "OFF") {
consoleHandler = nil
return nil
}
var parsed slog.Level
if err := parsed.UnmarshalText([]byte(strings.ToUpper(level))); err != nil {
return fmt.Errorf("invalid UPSNAP_LOG_LEVEL %q (expected DEBUG, INFO, WARN, ERROR, or OFF)", level)
}
consoleHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: parsed,
})
return nil
}
func relativeSource(file string) string {
file = strings.ReplaceAll(file, "\\", "/")
if index := strings.LastIndex(file, "/backend/"); index >= 0 {
return file[index+1:]
}
return file
}
// Logger writes through PocketBase's logger and mirrors UpSnap logs to stdout.
func Logger(app core.App) *slog.Logger {
handlers := []slog.Handler{app.Logger().Handler()}
if consoleHandler != nil && !app.IsDev() {
handlers = append(handlers, consoleHandler)
}
return slog.New(multiHandler(handlers)).With("upsnap", true)
}
type multiHandler []slog.Handler
func (h multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range h {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
func (h multiHandler) Handle(ctx context.Context, record slog.Record) error {
if record.PC != 0 {
frames := runtime.CallersFrames([]uintptr{record.PC})
frame, _ := frames.Next()
record.AddAttrs(slog.String(slog.SourceKey, relativeSource(frame.File)+":"+strconv.Itoa(frame.Line)))
}
var errs []error
for _, handler := range h {
if handler.Enabled(ctx, record.Level) {
if err := handler.Handle(ctx, record.Clone()); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
func (h multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithAttrs(attrs)
}
return handlers
}
func (h multiHandler) WithGroup(name string) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithGroup(name)
}
return handlers
}
+4 -7
View File
@@ -2,18 +2,15 @@ package main
import (
"embed"
"log"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"github.com/seriousm4x/upsnap/pb"
"github.com/labstack/echo/v5"
"github.com/seriousm4x/upsnap/backend/pb"
)
//go:embed all:pb_public
var distDir embed.FS
var distDirFS = apis.MustSubFS(distDir, "pb_public")
var distDirFS = echo.MustSubFS(distDir, "pb_public")
func main() {
if err := pb.StartPocketBase(distDirFS); err != nil {
log.Fatal(err)
}
pb.StartPocketBase(distDirFS)
}
@@ -0,0 +1,207 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "z5lghx2r3tm45n1",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "devices",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "tiqcmnjo",
"name": "name",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "1si6ajha",
"name": "ip",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "fyqmpon6",
"name": "mac",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "s8c5z7n0",
"name": "netmask",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "qqvyfrex",
"name": "status",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "ilrwvlev",
"name": "ports",
"type": "relation",
"required": false,
"unique": false,
"options": {
"maxSelect": null,
"collectionId": "cti4l8f4mz8df3r",
"cascadeDelete": false
}
},
{
"system": false,
"id": "gdctb8hj",
"name": "link",
"type": "url",
"required": false,
"unique": false,
"options": {
"exceptDomains": null,
"onlyDomains": null
}
},
{
"system": false,
"id": "kzvdbbws",
"name": "wake_cron",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "dcd3vuc3",
"name": "wake_cron_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "91bs6clw",
"name": "shutdown_cron",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "vnlymcuw",
"name": "shutdown_cron_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "1a7yrwo9",
"name": "shutdown_cmd",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "iarksm3l",
"name": "password",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,81 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "cti4l8f4mz8df3r",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "ports",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": null,
"max": 65535
}
},
{
"system": false,
"id": "o0he3pu6",
"name": "name",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "w0bh39gv",
"name": "status",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,86 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "nmj3ko20gzkg8n3",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "settings",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "ph88gaa5",
"name": "interval",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "agw2fyd1",
"name": "scan_range",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "slrjkipw",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,90 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("_pb_users_auth_")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
}, func(db dbx.Builder) error {
jsonData := `{
"id": "_pb_users_auth_",
"created": "2023-01-28 19:10:12.835Z",
"updated": "2023-01-28 19:10:12.835Z",
"name": "users",
"type": "auth",
"system": false,
"schema": [
{
"system": false,
"id": "users_name",
"name": "name",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "users_avatar",
"name": "avatar",
"type": "file",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"maxSize": 5242880,
"mimeTypes": [
"image/jpg",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/gif",
"image/webp"
],
"thumbs": null
}
}
],
"listRule": "id = @request.auth.id",
"viewRule": "id = @request.auth.id",
"createRule": "",
"updateRule": "id = @request.auth.id",
"deleteRule": "id = @request.auth.id",
"options": {
"allowEmailAuth": true,
"allowOAuth2Auth": true,
"allowUsernameAuth": true,
"exceptEmailDomains": null,
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": null,
"requireEmail": false
}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
})
}
File diff suppressed because it is too large Load Diff
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number376926767")
return app.Save(collection)
})
}
@@ -1,56 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,40 +0,0 @@
package migrations
import (
"encoding/json"
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": ""
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.body.password:isset = false"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,106 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
// Up migration: Change `url` field type from URL to string
collectionName := "devices"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new text field
newField := &core.TextField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(6, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
url := record.GetString("link")
record.Set("new_field", url)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
}, func(app core.App) error {
// Down migration: Restore the `url` field
collectionName := "devices"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new `url` field
newField := &core.URLField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(6, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
text := record.GetString("link")
record.Set("new_field", text)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
})
}
@@ -1,106 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
// Up migration: Change `url` field type from URL to string
collectionName := "ports"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new text field
newField := &core.TextField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(5, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
url := record.GetString("link")
record.Set("new_field", url)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
}, func(app core.App) error {
// Down migration: Restore the `url` field
collectionName := "ports"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new `url` field
newField := &core.URLField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(5, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
text := record.GetString("link")
record.Set("new_field", text)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(5, []byte(`{
"autogeneratePattern": "",
"hidden": false,
"id": "text1843675174",
"max": 0,
"min": 0,
"name": "description",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("text1843675174")
return app.Save(collection)
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(8, []byte(`{
"hidden": false,
"id": "select355930381",
"maxSelect": 1,
"name": "link_open",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"same_tab",
"new_tab"
]
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("select355930381")
return app.Save(collection)
})
}
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(11, []byte(`{
"hidden": false,
"id": "number361076486",
"max": null,
"min": 1,
"name": "wake_timeout",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number361076486")
return app.Save(collection)
})
}
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(15, []byte(`{
"hidden": false,
"id": "number2068100152",
"max": null,
"min": 1,
"name": "shutdown_timeout",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number2068100152")
return app.Save(collection)
})
}
@@ -1,100 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "fyqmpon6",
"max": 0,
"min": 0,
"name": "mac",
"pattern": "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "fyqmpon6",
"max": 0,
"min": 0,
"name": "mac",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,62 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,62 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,40 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "bool2618032555",
"name": "track_ip",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("bool2618032555")
return app.Save(collection)
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"hidden": false,
"id": "text3846109882",
"max": 0,
"min": 0,
"name": "track_ip_interval",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("text3846109882")
return app.Save(collection)
})
}
@@ -1,100 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(?:(?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.)+[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?|(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(?:255\\.255\\.255\\.(?:255|254|252|248|240|224|192|128|0)|255\\.255\\.(?:255|254|252|248|240|224|192|128|0)\\.0|255\\.(?:255|254|252|248|240|224|192|128|0)\\.0\\.0|(?:255|254|252|248|240|224|192|128|0)\\.0\\.0\\.0)$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
+33 -125
View File
@@ -1,166 +1,74 @@
package networking
import (
"encoding/binary"
"errors"
"fmt"
"net"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/mdlayher/wol"
"github.com/pocketbase/pocketbase/models"
)
func SendMagicPacket(device *core.Record) error {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return err
}
func SendMagicPacket(device *models.Record) error {
ip := device.GetString("ip")
mac := device.GetString("mac")
netmask := device.GetString("netmask")
password := device.GetString("password")
// parse inputs
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return fmt.Errorf("error: invalid ip address")
}
parsedMac, err := net.ParseMAC(mac)
if err != nil {
return err
}
if !ValidateSubnetMask(netmask) {
return fmt.Errorf("%q is not a valid subnet mask", netmask)
parsedNetmask := net.ParseIP(netmask)
if parsedNetmask == nil {
return fmt.Errorf("error: invalid netmask")
}
// calculate broadcast IP, if possible
var broadcastIp string
// an IP was provided or FQDN resolved to an IP so calculate broadcast destination based on that
if ip != "" {
broadcastIp, err = getBroadcastIp(ip, netmask)
if err != nil {
return err
}
} else {
// No IP available, so no broadcast IP can be calculated. This occurs if FQDN is .local and the device is powered off
broadcastIp = ""
}
var bytePassword []byte
if len(password) == 0 || len(password) == 4 || len(password) == 6 {
bytePassword = []byte(password)
} else {
return errors.New("error: password must be 0, 4 or 6 characters long")
return fmt.Errorf("error: password must be 0, 4 or 6 characters long")
}
// an IP was provided or FQDN resolved to an IP so calculate broadcast destination based on that
if ip != "" {
broadcastIp, err = getBroadcastIp(ip, netmask)
if err != nil {
return err
}
} else {
// No IP available, so no broadcast IP can be calculated. This occurs if FQDN is .local and the device is powered off
broadcastIp = ""
// get target addr
ipNet := &net.IPNet{
IP: parsedIP,
Mask: parsedNetmask.DefaultMask(),
}
// send wake
if err := wakeUDP(broadcastIp, ip, parsedMac, bytePassword); err != nil {
broadcastIp, err := getBroadcastIp(ipNet)
if err != nil {
return err
}
targetAddr := fmt.Sprintf("%s:%d", broadcastIp, 9)
// send wake via udp port 9
if err := wakeUDP(targetAddr, parsedMac, bytePassword); err != nil {
return err
}
return nil
}
func wakeUDP(broadcastIp string, deviceIp string, target net.HardwareAddr, password []byte) error {
func wakeUDP(addr string, target net.HardwareAddr, password []byte) error {
c, err := wol.NewClient()
if err != nil {
return err
}
defer c.Close()
var destinations []string
// Broadcast IP available, add to destinations
if broadcastIp != "" {
// user-calculated broadcast packet to port 9 and alternative port 7
destinations = append(destinations,
fmt.Sprintf("%s:9", broadcastIp),
fmt.Sprintf("%s:7", broadcastIp),
)
}
if deviceIp != "" {
// For routed network WOL, send a unicast packet to device IP on port 9 and alternative port 7
destinations = append(destinations,
fmt.Sprintf("%s:9", deviceIp),
fmt.Sprintf("%s:7", deviceIp),
)
}
// No IP for the device is available, broadcast WOL packet to all interfaces
if deviceIp == "" {
allBroadcastDests, err := getAllBroadcastDests()
if err != nil {
return err
}
destinations = append(destinations, allBroadcastDests...)
}
for _, dest := range destinations {
if err := c.WakePassword(dest, target, password); err != nil {
return err
}
}
return nil
return c.WakePassword(addr, target, password)
}
func getBroadcastIp(ipStr, maskStr string) (string, error) {
ip := net.ParseIP(ipStr).To4()
if ip == nil {
return "", errors.New("ip not a valid ipv4 address")
func getBroadcastIp(n *net.IPNet) (net.IP, error) {
if n.IP.To4() == nil {
return net.IP{}, errors.New("does not support IPv6 addresses")
}
mask := net.ParseIP(maskStr).To4()
if mask == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
broadcast := make(net.IP, 4)
for i := range ip {
broadcast[i] = ip[i] | ^mask[i]
}
return broadcast.String(), nil
}
// Returns a slice of all broadcast addresses for ports 9 and 7 using local interfaces
func getAllBroadcastDests() ([]string, error) {
var allIps []string
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
// Iterate through all the interfaces
for _, iface := range interfaces {
isRunning := iface.Flags&net.FlagRunning != 0
isLoopback := iface.Flags&net.FlagLoopback != 0
isNotBroadcast := iface.Flags&net.FlagBroadcast == 0
// exclude interfaces that are not running, are loopback, or can't broadcast
if !isRunning || isLoopback || isNotBroadcast {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
// Iterate through each interface's address
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok {
ip := ipNet.IP
// Only use IPv4
if ip.To4() != nil {
bcastip, err := getBroadcastIp(ip.String(), net.IP(ipNet.Mask).String())
if err != nil {
return nil, err
}
allIps = append(allIps, fmt.Sprintf("%s:9", bcastip), fmt.Sprintf("%s:7", bcastip))
}
}
}
}
return allIps, nil
ip := make(net.IP, len(n.IP.To4()))
binary.BigEndian.PutUint32(ip, binary.BigEndian.Uint32(n.IP.To4())|^binary.BigEndian.Uint32(net.IP(n.Mask).To4()))
return ip, nil
}
-236
View File
@@ -1,236 +0,0 @@
package networking
import (
"net"
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
type Device struct {
IP string
MAC string
Netmask string
Password string
ExpectFailPassword bool
}
func TestSendMagicPacket(t *testing.T) {
testCases := []struct {
name string
ip string
mac string
netmask string
password string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "secret",
wantError: false,
},
// Invalid MAC address
{
name: "Invalid MAC",
ip: "192.168.1.100",
mac: "invalid",
netmask: "255.255.255.0",
password: "secret",
wantError: true,
},
// Password too short
{
name: "Password Too Short",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "s", // length 1
wantError: true,
},
// Password too long
{
name: "Password Too Long",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "password", // length 9
wantError: true,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "secret",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "300.255.255.0", // invalid
password: "secret",
wantError: true,
},
}
collection := &core.Collection{}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := core.NewRecord(collection)
device.Set("ip", tc.ip)
device.Set("mac", tc.mac)
device.Set("netmask", tc.netmask)
device.Set("password", tc.password)
err := SendMagicPacket(device)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Got unexpected error: %v", err)
}
}
})
}
}
func TestWakeUDP(t *testing.T) {
testCases := []struct {
name string
ip string
broadcastIp string
targetMac string
password string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "secret",
wantError: false,
},
// Invalid MAC address
{
name: "Invalid MAC",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "invalid",
password: "secret",
wantError: true,
},
// Password too short
{
name: "Password Too Short",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "s", // length 1
wantError: true,
},
// Password too long
{
name: "Password Too Long",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "password", // length 9
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
mac, err := net.ParseMAC(tc.targetMac)
if err != nil && !tc.wantError {
t.Errorf("Unexpected error parsing MAC: %v", err)
} else if err != nil {
return
}
// Now test the wakeUDP function
err = wakeUDP(tc.broadcastIp, tc.ip, mac, []byte(tc.password))
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
}
})
}
}
func TestGetBroadcastIp(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantIp string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
ip: "192.168.1.100",
netmask: "255.255.255.0",
wantIp: "192.168.1.255",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
netmask: "255.255.255.0",
wantIp: "",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
netmask: "300.255.255.0", // invalid
wantIp: "",
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ip := net.ParseIP(tc.ip)
if ip == nil && !tc.wantError {
t.Errorf("Unexpected error parsing IP: %v", ip)
} else if ip == nil {
return
}
mask := net.ParseIP(tc.netmask)
if mask == nil && !tc.wantError {
t.Errorf("Unexpected error parsing netmask: %v", mask)
} else if mask == nil {
return
}
broadcast, err := getBroadcastIp(tc.ip, tc.netmask)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if broadcast != tc.wantIp {
t.Errorf("Broadcast IP mismatch: expected %s, got %s", tc.wantIp, broadcast)
}
}
})
}
}
+30 -21
View File
@@ -1,39 +1,48 @@
package networking
import (
"errors"
"net"
"os"
"syscall"
"runtime"
"time"
"github.com/go-ping/ping"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/backend/logger"
)
func isNoRouteOrDownError(err error) bool {
opErr, ok := err.(*net.OpError)
if !ok {
func PingDevice(device *models.Record) bool {
pinger, err := ping.NewPinger(device.GetString("ip"))
if err != nil {
logger.Error.Println(err)
return false
}
syscallErr, ok := opErr.Err.(*os.SyscallError)
if !ok {
pinger.Count = 1
pinger.Timeout = 500 * 1000000 // 500ms
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
err = pinger.Run()
if err != nil {
logger.Error.Println(err)
return false
}
return syscallErr.Err == syscall.EHOSTUNREACH || syscallErr.Err == syscall.EHOSTDOWN
stats := pinger.Statistics()
if stats.PacketLoss > 0 {
return false
} else {
return true
}
}
func CheckPort(host string, port string) (bool, error) {
func CheckPort(host string, port string) bool {
timeout := 500 * time.Millisecond
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
// treat "host unreachable", "connection refused" and "timeout" as no error
if netErr, ok := errors.AsType[*net.OpError](err); ok {
if errors.Is(netErr.Err, syscall.EHOSTUNREACH) ||
errors.Is(netErr.Err, syscall.ECONNREFUSED) ||
netErr.Timeout() {
return false, nil
}
}
return false, err
return false
}
defer conn.Close()
return conn != nil, nil
if conn != nil {
defer conn.Close()
return true
}
return false
}
-90
View File
@@ -1,90 +0,0 @@
package networking
import (
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
func TestPingDevice(t *testing.T) {
testCases := []struct {
name string
ip string
ping_cmd string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
ip: "8.8.8.8",
ping_cmd: "exit 0",
wantError: false,
},
// Invalid ping command
{
name: "Invalid Ping Command",
ip: "8.8.8.8",
ping_cmd: "exit 1",
wantError: false,
},
}
collection := &core.Collection{}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := core.NewRecord(collection)
device.Set("ip", tc.ip)
device.Set("ping_cmd", tc.ping_cmd)
_, err := PingDevice(device)
if err == nil && tc.wantError {
t.Errorf("Expected error but got none")
} else if err != nil && !tc.wantError {
t.Errorf("Got unexpected error: %v", err)
}
})
}
}
func TestCheckPort(t *testing.T) {
testCases := []struct {
name string
host string
port string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
host: "0.0.0.0",
port: "443",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
host: "256.1.1.1", // invalid
port: "443",
wantError: true,
},
// Invalid port number
{
name: "Invalid Port",
host: "0.0.0.0",
port: "70000", // invalid
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, err := CheckPort(tc.host, tc.port)
if err == nil && tc.wantError {
t.Errorf("Expected error but got none")
} else if err != nil && !tc.wantError {
t.Errorf("Got unexpected error: %v", err)
}
})
}
}
-92
View File
@@ -1,92 +0,0 @@
//go:build linux
package networking
import (
"fmt"
"os"
"os/exec"
"strconv"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
probing "github.com/prometheus-community/pro-bing"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func PingDevice(device *core.Record) (bool, error) {
ping_cmd := device.GetString("ping_cmd")
if ping_cmd == "" {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return false, err
}
if ip == "" {
return false, nil
}
pinger, err := probing.NewPinger(ip)
if err != nil {
return false, err
}
pinger.Count = 1
pinger.Timeout = 500 * time.Millisecond
privileged := true
privilegedEnv := os.Getenv("UPSNAP_PING_PRIVILEGED")
if privilegedEnv != "" {
privileged, err = strconv.ParseBool(privilegedEnv)
if err != nil {
privileged = false
}
}
if privileged {
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return false, fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return false, fmt.Errorf("Privileged ping selected but NET_RAW capability not permitted")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return false, fmt.Errorf("unable to set NET_RAW capability")
}
if err := c.SetProc(); err != nil {
return false, fmt.Errorf("unable to raise NET_RAW capability")
}
}
pinger.SetPrivileged(privileged)
err = pinger.Run()
if err != nil {
if isNoRouteOrDownError(err) {
return false, nil
}
return false, err
}
stats := pinger.Statistics()
return stats.PacketLoss == 0, nil
} else {
var shell string
var shell_arg string
shell = "/bin/sh"
shell_arg = "-c"
cmd := exec.Command(shell, shell_arg, ping_cmd)
err := cmd.Run()
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
return false, nil
}
return false, err
}
return true, nil
}
}
-75
View File
@@ -1,75 +0,0 @@
//go:build !linux
package networking
import (
"os"
"os/exec"
"runtime"
"strconv"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
probing "github.com/prometheus-community/pro-bing"
)
func PingDevice(device *core.Record) (bool, error) {
ping_cmd := device.GetString("ping_cmd")
if ping_cmd == "" {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || ip == "" {
return false, err
}
pinger, err := probing.NewPinger(ip)
if err != nil {
return false, err
}
pinger.Count = 1
pinger.Timeout = 500 * time.Millisecond
privileged := true // default to privileged ping, required by Windows
if runtime.GOOS == "darwin" {
// macOS pings will fail when using privileged ping as non root, but works with non-privileged.
privileged = false
}
privilegedEnv := os.Getenv("UPSNAP_PING_PRIVILEGED")
if privilegedEnv != "" {
privileged, err = strconv.ParseBool(privilegedEnv)
if err != nil {
privileged = false
}
}
pinger.SetPrivileged(privileged)
err = pinger.Run()
if err != nil {
if isNoRouteOrDownError(err) {
return false, nil
}
return false, err
}
stats := pinger.Statistics()
return stats.PacketLoss == 0, nil
} else {
var shell string
var shell_arg string
if runtime.GOOS == "windows" {
shell = "cmd"
shell_arg = "/C"
} else {
shell = "/bin/sh"
shell_arg = "-c"
}
cmd := exec.Command(shell, shell_arg, ping_cmd)
err := cmd.Run()
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
return false, nil
}
return false, err
}
return true, nil
}
}
-57
View File
@@ -1,57 +0,0 @@
//go:build windows || darwin
package networking
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"strings"
"time"
)
/*
Takes one parameter 'host' and returns its IP. If 'host' is already formatted
as an IP, simply return it. If 'host' is formatted as an FQDN, attempt to
resolve it with mDNS (if .local suffix) or else use a DNS lookup with
net.DefaultResolver
Windows and MacOS can resolve mDNS/DNS with one call to net.DefaultResolver
*/
func ResolveToIPAddr(host string) (string, error) {
// If host is already an IP, simply return it
addr, err := netip.ParseAddr(host)
if err == nil && addr.Is4() {
return host, nil
}
if err := ValidateFQDN(host); err != nil {
return "", fmt.Errorf("%q is the host", host)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host)
if err != nil {
if strings.HasSuffix(strings.ToLower(host), ".local") {
var dnsErr *net.DNSError
isNotFound := errors.As(err, &dnsErr) && dnsErr.IsNotFound
isTimeout := errors.Is(err, context.DeadlineExceeded) || ctx.Err() == context.DeadlineExceeded
if isTimeout || isNotFound {
return "", nil
}
}
return "", err
}
if len(ips) > 0 {
// only return one result
return ips[0].String(), nil
}
// No results, but it's expected for a .local FQDN device that is offline. Don't return an error.
if strings.HasSuffix(strings.ToLower(host), ".local") {
return "", nil
} else {
// No results, but FQDN should have resolved since it's not .local. Return an error.
return "", fmt.Errorf("No IP address found for %s", host)
}
}
-133
View File
@@ -1,133 +0,0 @@
//go:build linux || freebsd
package networking
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"strings"
"sync"
"time"
"github.com/godbus/dbus/v5"
"github.com/holoplot/go-avahi"
)
var (
avahiServer *avahi.Server
avahiErr error
avahiOnce sync.Once
)
// getAvahiServer initializes and returns a shared, long-lived Avahi client.
// It handles high throughput gracefully by using a single D-Bus socket connection.
func getAvahiServer() (*avahi.Server, error) {
avahiOnce.Do(func() {
// Using the cached system bus here is safe because we never call server.Close() on it.
conn, err := dbus.SystemBus()
if err != nil {
avahiErr = fmt.Errorf("failed to connect to dbus: %w", err)
return
}
server, err := avahi.ServerNew(conn)
if err != nil {
avahiErr = fmt.Errorf("failed to create avahi server: %w", err)
return
}
avahiServer = server
})
return avahiServer, avahiErr
}
/*
Takes one parameter 'host' and returns its IP. If 'host' is already formatted
as an IP, simply return it. If 'host' is formatted as an FQDN, attempt to
resolve it with mDNS (if .local suffix) or else use a DNS lookup with
net.DefaultResolver
Linux and FreeBSD require dbus and avahi for mDNS lookups
*/
func ResolveToIPAddr(host string) (string, error) {
// If host is already an IP, simply return it
addr, err := netip.ParseAddr(host)
if err == nil && addr.Is4() {
return host, nil
}
if err := ValidateFQDN(host); err != nil {
return "", err
}
// attempt mDNS query first
if strings.HasSuffix(strings.ToLower(host), ".local") {
// conn, err := dbus.Dial("unix:path=/var/run/dbus/system_bus_socket")
server, err := getAvahiServer()
if err != nil {
return "", fmt.Errorf("Failed to create connection: %w", err)
}
// defer conn.Close()
// server, err := avahi.ServerNew(conn)
// if err != nil {
// return "", fmt.Errorf("Failed to create avahi server: %w", err)
// }
// defer server.Close()
// set a context with 2 secs and only wait that long for an mDNS response. otherwise, avahi takes 5 secs
ctx1, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
type result struct {
address string
err error
}
ch := make(chan result, 1)
go func() {
resolved, err := server.ResolveHostName(
avahi.InterfaceUnspec,
avahi.ProtoInet,
host,
avahi.ProtoInet,
0,
)
if err != nil {
ch <- result{"", err}
return
}
// mDNS result received
ch <- result{resolved.Address, nil}
}()
select {
case <-ctx1.Done():
// 2 second timeout reached,
return "", nil
case res := <-ch:
if res.err != nil {
var dbusErr *dbus.Error
// in theory we shouldn't encounter this error since the 2 second context always beats the race
if errors.As(res.err, &dbusErr) && dbusErr.Name == "org.freedesktop.Avahi.TimeoutError" {
return "", nil
}
return "", fmt.Errorf("%s: %w", host, res.err)
}
return res.address, nil
}
}
// Not .local, attempt unicast (regular) DNS lookup
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel2()
ips, err := net.DefaultResolver.LookupNetIP(ctx2, "ip4", host)
if err != nil {
return "", err
}
if len(ips) > 0 {
// only return one result
return ips[0].String(), nil
}
// No results, but FQDN should have resolved since it's not .local. Return an error.
return "", err
}
-65
View File
@@ -1,65 +0,0 @@
package networking
import (
"encoding/xml"
"net"
"os"
"os/exec"
)
type Nmaprun struct {
Host []struct {
Address []struct {
Addr string `xml:"addr,attr" binding:"required"`
Addrtype string `xml:"addrtype,attr" binding:"required"`
Vendor string `xml:"vendor,attr"`
} `xml:"address"`
} `xml:"host"`
}
// MacToIP maps each scanned host's normalized mac address to its ipv4
// address, skipping hosts that lack either.
func (n Nmaprun) MacToIP() map[string]string {
macToIp := make(map[string]string)
for _, host := range n.Host {
var hostIp, hostMac string
for _, addr := range host.Address {
switch addr.Addrtype {
case "ipv4":
hostIp = addr.Addr
case "mac":
hostMac = addr.Addr
}
}
if parsedMac, err := net.ParseMAC(hostMac); hostIp != "" && err == nil {
macToIp[parsedMac.String()] = hostIp
}
}
return macToIp
}
func runNmap(scanRange string) (Nmaprun, error) {
nmapOutput := Nmaprun{}
nmap, err := exec.LookPath("nmap")
if err != nil {
return nmapOutput, err
}
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout, "--privileged")
cmdOutput, err := cmd.Output()
if err != nil {
return nmapOutput, err
}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return nmapOutput, err
}
return nmapOutput, nil
}
-41
View File
@@ -1,41 +0,0 @@
//go:build linux
package networking
import (
"fmt"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func NmapScan(scanRange string) (Nmaprun, error) {
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return Nmaprun{}, fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return Nmaprun{}, fmt.Errorf("unable to get NET_RAW permissions")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability effective")
}
if err := c.SetFlag(cap.Inheritable, true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability inheritable")
}
if err := c.SetProc(); err != nil {
return Nmaprun{}, fmt.Errorf("unable to raise NET_RAW capability")
}
if err := cap.SetAmbient(true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability ambient")
}
return runNmap(scanRange)
}
-7
View File
@@ -1,7 +0,0 @@
//go:build !linux
package networking
func NmapScan(scanRange string) (Nmaprun, error) {
return runNmap(scanRange)
}
-65
View File
@@ -1,65 +0,0 @@
package networking
import (
"encoding/xml"
"testing"
)
// Trimmed from real `nmap -sn -oX -` output: one host with a mac (scanned
// with raw socket privileges), one without (the scanning host itself).
const nmapSample = `<?xml version="1.0" encoding="UTF-8"?>
<nmaprun scanner="nmap" args="nmap -sn -oX - 10.1.10.0/24" version="7.94">
<host><status state="up" reason="arp-response"/>
<address addr="10.1.10.1" addrtype="ipv4"/>
<address addr="AA:BB:CC:DD:EE:FF" addrtype="mac" vendor="Ubiquiti Networks"/>
<hostnames></hostnames>
</host>
<host><status state="up" reason="localhost-response"/>
<address addr="10.1.10.9" addrtype="ipv4"/>
<hostnames></hostnames>
</host>
<runstats><finished time="1754000000" exit="success"/></runstats>
</nmaprun>`
func TestNmaprunUnmarshal(t *testing.T) {
nmapOutput := Nmaprun{}
if err := xml.Unmarshal([]byte(nmapSample), &nmapOutput); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if len(nmapOutput.Host) != 2 {
t.Fatalf("Host count mismatch: expected 2, got %d", len(nmapOutput.Host))
}
first := nmapOutput.Host[0].Address
if len(first) != 2 {
t.Fatalf("Address count mismatch: expected 2, got %d", len(first))
}
if first[0].Addrtype != "ipv4" || first[0].Addr != "10.1.10.1" {
t.Errorf("Unexpected ipv4 address: %+v", first[0])
}
if first[1].Addrtype != "mac" || first[1].Addr != "AA:BB:CC:DD:EE:FF" || first[1].Vendor != "Ubiquiti Networks" {
t.Errorf("Unexpected mac address: %+v", first[1])
}
second := nmapOutput.Host[1].Address
if len(second) != 1 || second[0].Addrtype != "ipv4" {
t.Errorf("Unexpected addresses for mac-less host: %+v", second)
}
}
func TestNmaprunMacToIP(t *testing.T) {
nmapOutput := Nmaprun{}
if err := xml.Unmarshal([]byte(nmapSample), &nmapOutput); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
macToIp := nmapOutput.MacToIP()
if len(macToIp) != 1 {
t.Fatalf("Entry count mismatch: expected 1, got %d", len(macToIp))
}
// the mac address is normalized to lower case, the mac-less host is skipped
if ip := macToIp["aa:bb:cc:dd:ee:ff"]; ip != "10.1.10.1" {
t.Errorf("Unexpected ip for aa:bb:cc:dd:ee:ff: %q", ip)
}
}
+15 -87
View File
@@ -1,25 +1,19 @@
package networking
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"os/exec"
"runtime"
"strings"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/pocketbase/pocketbase/models"
)
func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
log := logging.Logger(app)
log.Info("Shutdown triggered", "device", device.GetString("name"), "trigger", trigger)
func ShutdownDevice(device *models.Record) error {
shutdown_cmd := device.GetString("shutdown_cmd")
if shutdown_cmd == "" {
return fmt.Errorf("%s: no shutdown_cmd defined", device.GetString("name"))
return fmt.Errorf("%s: no shutdown_cmd definded", device.GetString("name"))
}
var shell string
@@ -32,88 +26,22 @@ func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
shell_arg = "-c"
}
// Validate IP or resolve FQDN to IP
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || deviceIP == "" {
return fmt.Errorf("Unable to resolve %s to an IP address", device.GetString("ip"))
}
// Validate MAC address before replacing placeholder to prevent command injection
deviceMAC := device.GetString("mac")
if _, err := net.ParseMAC(deviceMAC); err != nil {
return fmt.Errorf("invalid device MAC address: %q", deviceMAC)
}
shutdown_cmd = strings.ReplaceAll(shutdown_cmd, "{{ DEVICE_IP }}", deviceIP)
shutdown_cmd = strings.ReplaceAll(shutdown_cmd, "{{ DEVICE_MAC }}", deviceMAC)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
cmd := exec.CommandContext(ctx, shell, shell_arg, shutdown_cmd)
SetProcessAttributes(cmd)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
cmd := exec.Command(shell, shell_arg, shutdown_cmd)
if err := cmd.Run(); err != nil {
return err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
shutdownTimeout := device.GetInt("shutdown_timeout")
if shutdownTimeout <= 0 {
shutdownTimeout = 120
}
// check state every second for 2 min
start := time.Now()
for {
select {
case err := <-done:
if err != nil {
return fmt.Errorf("%s", stderr.String())
} else {
for {
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device during shutdown", "error", err)
return err
}
if isOnline {
if time.Since(start) >= time.Duration(shutdownTimeout)*time.Second {
return fmt.Errorf("%s not offline after %d seconds", device.GetString("name"), shutdownTimeout)
}
}
if !isOnline {
return nil
}
time.Sleep(1 * time.Second)
}
}
default:
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device during shutdown", "error", err)
return err
}
if time.Since(start) >= time.Duration(shutdownTimeout)*time.Second {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill shutdown command", "error", err)
}
return fmt.Errorf("%s not offline after %d seconds", device.GetString("name"), shutdownTimeout)
}
if !isOnline {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill shutdown command", "error", err)
}
return nil
}
time.Sleep(1 * time.Second)
time.Sleep(1 * time.Second)
isOnline := PingDevice(device)
if !isOnline {
return nil
}
if time.Since(start) >= 2*time.Minute {
break
}
}
return errors.New("device not offline after 2 min")
}
-33
View File
@@ -1,33 +0,0 @@
//go:build !windows
package networking
import (
"os"
"os/exec"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"golang.org/x/sys/unix"
)
// Set platform specifiy custom process attributes
func SetProcessAttributes(cmd *exec.Cmd) {
cmd.SysProcAttr = &unix.SysProcAttr{Setpgid: true}
}
// Kills child processes on Linux. Windows doesn't provide a direct way to kill child processes, so we kill just the main process.
func KillProcess(app core.App, process *os.Process) error {
logging.Logger(app).Warn("Command did not finish in time and will be killed")
pgid, err := unix.Getpgid(process.Pid)
if err != nil {
return err
}
err = unix.Kill(-pgid, unix.SIGTERM)
if err != nil {
return unix.Kill(-pgid, unix.SIGKILL)
}
return err
}
-20
View File
@@ -1,20 +0,0 @@
//go:build windows
package networking
import (
"os"
"os/exec"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"golang.org/x/sys/windows"
)
// Set platform specifiy custom process attributes
func SetProcessAttributes(cmd *exec.Cmd) {}
// Kills child processes on Linux. Windows doesn't provide a direct way to kill child processes, so we kill just the main process.
func KillProcess(_ core.App, process *os.Process) error {
return windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(process.Pid))
}
-56
View File
@@ -1,56 +0,0 @@
package networking
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
)
type SolResponse struct {
Message string `json:"message"`
}
func SleepDevice(app core.App, device *core.Record) (SolResponse, error) {
logging.Logger(app).Info("Sleep triggered", "device", device.GetString("name"))
var solResp SolResponse
var url string
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || deviceIP == "" {
return solResp, fmt.Errorf("Unable to resolve %s to an IP address: %w", device.GetString("ip"), err)
}
if device.GetBool("sol_auth") {
url = fmt.Sprintf("http://%s:%s@%s:%d/sleep?format=JSON",
device.GetString("sol_user"), device.GetString("sol_password"), deviceIP, device.GetInt("sol_port"))
} else {
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", deviceIP, device.GetInt("sol_port"))
}
resp, err := http.Get(url)
if err != nil {
return solResp, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return solResp, err
}
var solResp SolResponse
if err := json.Unmarshal(body, &solResp); err != nil {
return solResp, err
}
return solResp, errors.New("status code was not 200")
}
return solResp, nil
}
-59
View File
@@ -1,59 +0,0 @@
package networking
import (
"errors"
"net"
)
// DeviceSubnet returns the device's IPv4 subnet computed from its ip and netmask.
func DeviceSubnet(ipStr, maskStr string) (*net.IPNet, error) {
ip := net.ParseIP(ipStr)
if ip == nil || ip.To4() == nil {
return nil, errors.New("ip not a valid ipv4 address")
}
ip = ip.To4()
mask := net.ParseIP(maskStr)
if mask == nil || mask.To4() == nil {
return nil, errors.New("subnet mask not a valid ipv4 address")
}
ipMask := net.IPMask(mask.To4())
return &net.IPNet{IP: ip.Mask(ipMask), Mask: ipMask}, nil
}
// ValidateScannableSubnet returns nil if the subnet is suitable for an nmap
// scan, or an error explaining why it isn't.
func ValidateScannableSubnet(subnet *net.IPNet) error {
ones, bits := subnet.Mask.Size()
if ones == 0 && bits == 0 {
// Size() returns 0,0 for a non-contiguous mask, which has no cidr
// notation to hand to nmap
return errors.New("netmask is not contiguous")
}
if ones == bits {
return errors.New("a single address has nothing to scan")
}
if ones < 16 {
return errors.New("subnets larger than a /16 take too long to scan")
}
// arp only answers on-link, so the subnet must overlap one of the
// host's attached ipv4 networks for a scan to find mac addresses
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, addr := range addrs {
attached, ok := addr.(*net.IPNet)
if !ok || attached.IP.To4() == nil {
continue
}
// subnets are either disjoint or nested, so checking containment
// in both directions covers overlap
if attached.Contains(subnet.IP) || subnet.Contains(attached.IP) {
return nil
}
}
return errors.New("subnet does not overlap a directly attached network")
}
-146
View File
@@ -1,146 +0,0 @@
package networking
import (
"testing"
)
func TestDeviceSubnet(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantCidr string
wantError bool
}{
// Valid case: address is masked down to the network
{
name: "Valid Case",
ip: "192.168.1.100",
netmask: "255.255.255.0",
wantCidr: "192.168.1.0/24",
wantError: false,
},
// Valid case: wider mask
{
name: "Valid /16",
ip: "10.1.10.142",
netmask: "255.255.0.0",
wantCidr: "10.1.0.0/16",
wantError: false,
},
// Valid case: host mask
{
name: "Valid /32",
ip: "192.168.1.5",
netmask: "255.255.255.255",
wantCidr: "192.168.1.5/32",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
netmask: "255.255.255.0",
wantCidr: "",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
netmask: "300.255.255.0", // invalid
wantCidr: "",
wantError: true,
},
// IPv6 address is not a valid device ip
{
name: "IPv6 IP",
ip: "fe80::1",
netmask: "255.255.255.0",
wantCidr: "",
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
subnet, err := DeviceSubnet(tc.ip, tc.netmask)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Got unexpected error: %v", err)
} else if subnet.String() != tc.wantCidr {
t.Errorf("Subnet mismatch: expected %s, got %s", tc.wantCidr, subnet.String())
}
}
})
}
}
func TestValidateScannableSubnet(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantError bool
}{
// A /32 has nothing to scan
{
name: "Host Mask",
ip: "192.168.1.5",
netmask: "255.255.255.255",
wantError: true,
},
// A non-contiguous mask has no cidr notation to scan
{
name: "Non-contiguous Mask",
ip: "10.0.1.5",
netmask: "255.0.255.0",
wantError: true,
},
// Anything larger than a /16 takes too long to scan
{
name: "Too Large",
ip: "10.0.0.1",
netmask: "255.0.0.0",
wantError: true,
},
// The loopback address as a /16 is within limits and always attached
{
name: "Local /16",
ip: "127.0.0.1",
netmask: "255.255.0.0",
wantError: false,
},
// A sub-block of the attached loopback /8 is on-link even though
// it doesn't contain the host's own 127.0.0.1
{
name: "Nested In Attached",
ip: "127.0.1.5",
netmask: "255.255.255.0",
wantError: false,
},
// TEST-NET-1 (RFC 5737) is never assigned to an interface
{
name: "No Overlap",
ip: "192.0.2.1",
netmask: "255.255.255.0",
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
subnet, err := DeviceSubnet(tc.ip, tc.netmask)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if err := ValidateScannableSubnet(subnet); (err != nil) != tc.wantError {
t.Errorf("ValidateScannableSubnet(%s): expected error=%v, got %v", subnet.String(), tc.wantError, err)
}
})
}
}
-50
View File
@@ -1,50 +0,0 @@
package networking
import (
"fmt"
"net/netip"
"regexp"
"strings"
"golang.org/x/net/idna"
)
var fqdnRegex = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z0-9-]{2,63}$`)
/*
Validate's FQDN by converting it to Punycode and checking it against several criteria
*/
func ValidateFQDN(host string) error {
// Remove trailing . just in case, but DB and form validation should already prevent that
trimmedHost := strings.TrimSuffix(host, ".")
if len(trimmedHost) == 0 {
return fmt.Errorf("%q: invalid length of 0. original %q", trimmedHost, host)
}
// convert to punycode
punycodeHost, err := idna.Lookup.ToASCII(trimmedHost)
if err != nil {
return fmt.Errorf("%q: failed to convert to punycode - %w", trimmedHost, err)
}
if len(punycodeHost) < 1 || len(punycodeHost) > 253 {
return fmt.Errorf("%q -> %q: invalid length %d bytes. Must be 1-253 bytes (chars) after conversion.", trimmedHost, punycodeHost, len(punycodeHost))
}
if !fqdnRegex.MatchString(punycodeHost) {
return fmt.Errorf("%q -> %q: Failed validation.", trimmedHost, punycodeHost)
}
return nil
}
func ValidateSubnetMask(mask string) bool {
addr, err := netip.ParseAddr(mask)
if err != nil || !addr.Is4() {
return false
}
byteArray := addr.As4()
maskInt := uint32(byteArray[0])<<24 | uint32(byteArray[1])<<16 | uint32(byteArray[2])<<8 | uint32(byteArray[3])
inverted := ^maskInt
return (inverted & (inverted + 1)) == 0
}
+16 -124
View File
@@ -1,137 +1,29 @@
package networking
import (
"bytes"
"context"
"fmt"
"net"
"os/exec"
"runtime"
"strings"
"errors"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/pocketbase/pocketbase/models"
)
func WakeDevice(app core.App, device *core.Record, trigger string) error {
log := logging.Logger(app)
log.Info("Wake triggered", "device", device.GetString("name"), "trigger", trigger)
wakeTimeout := device.GetInt("wake_timeout")
if wakeTimeout <= 0 {
wakeTimeout = 120
func WakeDevice(device *models.Record) error {
err := SendMagicPacket(device)
if err != nil {
return err
}
wake_cmd := device.GetString("wake_cmd")
if wake_cmd != "" {
var shell string
var shell_arg string
if runtime.GOOS == "windows" {
shell = "cmd"
shell_arg = "/C"
} else {
shell = "/bin/sh"
shell_arg = "-c"
// check state every second for 2 min
start := time.Now()
for {
time.Sleep(1 * time.Second)
isOnline := PingDevice(device)
if isOnline {
return nil
}
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return err
if time.Since(start) >= 2*time.Minute {
break
}
if deviceIP == "" {
deviceIP = device.GetString("ip")
}
// Validate MAC address before replacing placeholders to prevent command injection
deviceMAC := device.GetString("mac")
if _, err := net.ParseMAC(deviceMAC); err != nil {
return fmt.Errorf("invalid device MAC address: %q", deviceMAC)
}
wake_cmd = strings.ReplaceAll(wake_cmd, "{{ DEVICE_IP }}", deviceIP)
wake_cmd = strings.ReplaceAll(wake_cmd, "{{ DEVICE_MAC }}", deviceMAC)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
cmd := exec.CommandContext(ctx, shell, shell_arg, wake_cmd)
SetProcessAttributes(cmd)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
log.Error("Failed to start wake command", "error", err)
return err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
start := time.Now()
commandFinished := false
for {
select {
case <-time.After(1 * time.Second):
if time.Since(start) >= time.Duration(wakeTimeout)*time.Second {
if !commandFinished && cmd.Process != nil {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill wake command", "error", err)
}
}
return fmt.Errorf("%s not online after %d seconds", device.GetString("name"), wakeTimeout)
}
// Reachability alone does not mean a custom wake command has finished.
// For example, a Mac can respond to ping while it is still in DarkWake.
if !commandFinished {
continue
}
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device after wake", "error", err)
return err
}
if isOnline {
return nil
}
case err := <-done:
if err != nil {
if cmd.Process != nil {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill wake command", "error", err)
}
}
return fmt.Errorf("%s", stderr.String())
}
commandFinished = true
done = nil
// Command finished successfully, but we continue the loop until device is online or timeout
}
}
} else {
err := SendMagicPacket(device)
if err != nil {
return err
}
start := time.Now()
for {
time.Sleep(1 * time.Second)
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device after wake", "error", err)
return err
}
if isOnline {
return nil
}
if time.Since(start) >= time.Duration(wakeTimeout)*time.Second {
break
}
}
return fmt.Errorf("%s not online after %d seconds", device.GetString("name"), wakeTimeout)
}
return errors.New("device not online after 2 min")
}
-92
View File
@@ -1,92 +0,0 @@
//go:build !windows
package networking
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
)
func newWakeTestDevice(t *testing.T, command, pingCommand string, timeout int) (core.App, *core.Record) {
t.Helper()
app, err := tests.NewTestApp(t.TempDir())
if err != nil {
t.Fatal(err)
}
t.Cleanup(app.Cleanup)
device := core.NewRecord(&core.Collection{})
device.Set("name", "test-device")
device.Set("ip", "127.0.0.1")
device.Set("mac", "02:00:00:00:00:01")
device.Set("wake_cmd", command)
device.Set("ping_cmd", pingCommand)
device.Set("wake_timeout", timeout)
return app, device
}
func TestCustomWakeWaitsForCommandWhenDeviceIsAlreadyOnline(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t,
`sleep 2; printf done > "$UPSNAP_WAKE_TEST_DIR/completed"`, "exit 0", 10)
if err := WakeDevice(app, device, "test"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(dir, "completed"))
if err != nil || string(data) != "done" {
t.Fatalf("wake command was interrupted despite successful ping: data=%q err=%v", data, err)
}
}
func TestCustomWakeReturnsFailureWhenDeviceIsAlreadyOnline(t *testing.T) {
app, device := newWakeTestDevice(t, "sleep 2; echo wake-failed >&2; exit 7", "exit 0", 10)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "wake-failed") {
t.Fatalf("expected wake command failure despite successful ping, got %v", err)
}
}
func TestCustomWakeStillWaitsForReachabilityAfterCommandFinishes(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t, "exit 0",
`if [ -f "$UPSNAP_WAKE_TEST_DIR/pinged" ]; then exit 0; fi; touch "$UPSNAP_WAKE_TEST_DIR/pinged"; exit 1`, 10)
if err := WakeDevice(app, device, "test"); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "pinged")); err != nil {
t.Fatalf("wake returned without checking reachability: %v", err)
}
}
func TestCustomWakeTimesOutWhenCommandSucceedsButDeviceStaysOffline(t *testing.T) {
app, device := newWakeTestDevice(t, "exit 0", "exit 1", 2)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "not online after 2 seconds") {
t.Fatalf("expected reachability timeout, got %v", err)
}
}
func TestCustomWakeTimeoutStillStopsRunningCommand(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t,
`sleep 3; touch "$UPSNAP_WAKE_TEST_DIR/completed"`, "exit 0", 1)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "not online after 1 seconds") {
t.Fatalf("expected command timeout even though ping succeeds, got %v", err)
}
// A surviving shell/child would write this file after its sleep finishes.
time.Sleep(3 * time.Second)
if _, err := os.Stat(filepath.Join(dir, "completed")); !os.IsNotExist(err) {
t.Fatalf("timed-out wake command continued running: %v", err)
}
}
+111 -369
View File
@@ -1,239 +1,51 @@
package pb
import (
"encoding/json"
"fmt"
"encoding/xml"
"errors"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tools/router"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/backend/logger"
"github.com/seriousm4x/upsnap/backend/networking"
)
func HandlerWake(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
func HandlerWake(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device", "device", record.GetString("name"), "error", err)
go func(*models.Record) {
record.Set("status", "pending")
App.Dao().SaveRecord(record)
if err := networking.WakeDevice(record); err != nil {
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
} else {
record.Set("status", "online")
}
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, record)
App.Dao().SaveRecord(record)
}(record)
return c.JSON(http.StatusOK, record)
}
func HandlerSleep(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
func HandlerShutdown(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
if err := networking.ShutdownDevice(record); err != nil {
logger.Error.Println(err)
return apis.NewBadRequestError(err.Error(), record)
}
if err := asyncCall(e, func() *router.ApiError {
resp, err := networking.SleepDevice(e.App, record)
if err != nil {
logging.Logger(e.App).Error("Failed to sleep device", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(resp.Message, nil)
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, nil)
}
func HandlerReboot(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device for reboot", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
}
// if this code is reached, the device is shutting down and not responding to pings anymore.
// this does not mean it is ready to boot again, it might still be in the process of shutting down.
// so we wait a little to make sure the device has shut down completely and is ready to receive wake requests.
time.Sleep(15 * time.Second)
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device after reboot", "device", record.GetString("name"), "error", err)
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
}
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, record)
}
func HandlerShutdown(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device", "device", record.GetString("name"), "error", strings.ReplaceAll(err.Error(), "\n", ""))
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, record)
}
func HandlerWakeGroup(e *core.RequestEvent) error {
records, err := e.App.FindRecordsByFilter("devices", "groups.id ?= {:grpId} && status = 'offline'", "", 0, 0,
dbx.Params{"grpId": e.Request.PathValue("id")},
)
if err != nil {
return apis.NewNotFoundError("No devices in group", err)
}
for _, record := range records {
go func() {
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device", "device", record.GetString("name"), "error", err)
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return
}
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
}()
}
return e.JSON(http.StatusOK, records)
}
func HandlerShutdownGroup(e *core.RequestEvent) error {
records, err := e.App.FindRecordsByFilter("devices", "groups.id ?= {:grpId} && status = 'online'", "", 0, 0,
dbx.Params{"grpId": e.Request.PathValue("id")},
)
if err != nil {
return apis.NewNotFoundError("No devices in group", err)
}
for _, record := range records {
go func() {
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
}()
}
return e.JSON(http.StatusOK, records)
return nil
}
type Nmaprun struct {
@@ -246,161 +58,91 @@ type Nmaprun struct {
} `xml:"host"`
}
func HandlerInitSuperuser(e *core.RequestEvent) error {
superusersCollection, err := e.App.FindCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
return e.NotFoundError("Failed to retrieve superusers collection", err)
}
totalSuperusers, err := e.App.CountRecords(superusersCollection)
if err != nil {
return e.InternalServerError("Failed to retrieve superusers count", err)
}
if totalSuperusers > 0 {
return e.BadRequestError("An initial superuser already exists", nil)
}
data := struct {
Email string `json:"email" form:"email"`
Password string `json:"password" form:"password"`
PasswordConfirm string `json:"password_confirm" form:"password-confirm"`
}{}
err = e.BindBody(&data)
if err != nil {
return e.BadRequestError("Failed to read request data", err)
}
if data.Password != data.PasswordConfirm {
return e.BadRequestError("Password don't match", err)
}
record := core.NewRecord(superusersCollection)
record.SetEmail(data.Email)
record.SetPassword(data.Password)
err = e.App.Save(record)
if err != nil {
return e.BadRequestError("Failed to create initial superuser", err)
}
return apis.RecordAuthResponse(e, record, "", nil)
}
type ValidateCronRequest struct {
Cron string `json:"cron"`
}
func HandlerValidateCron(e *core.RequestEvent) error {
var body ValidateCronRequest
if err := e.BindBody(&body); err != nil {
logging.Logger(e.App).Error("Failed to bind cron validation request", "error", err)
return e.BadRequestError("invalid request", err)
}
p := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
if _, err := p.Parse(body.Cron); err != nil {
return e.BadRequestError("failed to parse cron expression", err)
}
return e.JSON(200, "valid")
}
func asyncCall(e *core.RequestEvent, fn func() *router.ApiError) *router.ApiError {
isAsync, err := strconv.ParseBool(e.Request.URL.Query().Get("async"))
if err != nil {
isAsync = false
}
if !isAsync {
return fn()
}
go func() {
_ = fn()
}()
return nil
}
func HandlerWebsiteManifest(e *core.RequestEvent) error {
scheme := "http"
if e.Request.TLS != nil || e.Request.Header.Get("X-Forwarded-Proto") == "https" {
scheme = "https"
}
baseUrl := fmt.Sprintf("%s://%s", scheme, e.Request.Host)
manifest := map[string]any{
"name": "UpSnap",
"short_name": "UpSnap",
"description": "A simple wake on lan web app written with SvelteKit, Go and PocketBase.",
"theme_color": "#55BCD9",
"background_color": "#55BCD9",
"display": "standalone",
"scope": baseUrl,
"start_url": baseUrl,
"icons": []map[string]string{
{
"src": "/icon_192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any",
},
{
"src": "/icon_512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any",
},
{
"src": "/maskable_192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable",
},
{
"src": "/maskable_512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable",
},
{
"src": "/gopher.svg",
"sizes": "any",
"type": "image/svg+xml",
},
},
}
publicSettings, err := e.App.FindFirstRecordByFilter("settings_public", "")
if err != nil {
return writeManifest(e, manifest)
}
// override title if set
if title := publicSettings.GetString("website_title"); title != "" {
manifest["name"] = title
manifest["short_name"] = title
}
// override icons if set
if favicon := publicSettings.GetString("favicon"); favicon != "" {
manifest["icons"] = []map[string]string{
{
"src": fmt.Sprintf("%s/api/files/settings_public/%s/%s", baseUrl, publicSettings.Id, favicon),
"sizes": "any",
"purpose": "any",
},
func HandlerScan(c echo.Context) error {
if runtime.GOOS == "windows" {
// check for admin on windows by trying to open physicaldrive
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
if err != nil {
err := errors.New("network scan requires upsnap to be run as administrator")
return apis.NewBadRequestError(err.Error(), nil)
}
} else {
// check for root on anything else
sudoUID := os.Getenv("SUDO_UID")
if sudoUID == "" {
err := errors.New("network scan requires upsnap to be run as root")
return apis.NewBadRequestError(err.Error(), nil)
}
}
return writeManifest(e, manifest)
}
// check if nmap installed
if _, err := exec.LookPath("nmap"); err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
func writeManifest(e *core.RequestEvent, manifest map[string]any) error {
e.Response.Header().Set("Content-Type", "application/manifest+json")
e.Response.Header().Set("Cache-Control", "no-cache, no-store")
enc := json.NewEncoder(e.Response)
return enc.Encode(manifest)
// check if scan range is valid
allSettings, err := App.Dao().FindRecordsByExpr("settings")
if err != nil {
return err
}
settings := allSettings[0]
scanRange := settings.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// run nmap
cmd := exec.Command("nmap", "-sn", "-oX", "-", scanRange, "--host-timeout", "500ms")
cmdOutput, err := cmd.Output()
if err != nil {
return err
}
// unmarshal xml
nmapOutput := Nmaprun{}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return err
}
type Device struct {
Name string `json:"name"`
IP string `json:"ip"`
MAC string `json:"mac"`
}
// extract info from struct into data
type Response struct {
Netmask string `json:"netmask"`
Devices []Device `json:"devices"`
}
res := Response{}
var nm []string
for _, octet := range ipNet.Mask {
nm = append(nm, strconv.Itoa(int(octet)))
}
res.Netmask = strings.Join(nm, ".")
for _, host := range nmapOutput.Host {
dev := Device{}
for _, addr := range host.Address {
if addr.Addrtype == "ipv4" {
dev.IP = addr.Addr
} else if addr.Addrtype == "mac" {
dev.MAC = addr.Addr
}
if addr.Vendor != "" {
dev.Name = addr.Vendor
}
}
if dev.IP == "" || dev.MAC == "" {
continue
}
if dev.Name == "" {
dev.Name = "Unknown"
}
res.Devices = append(res.Devices, dev)
}
return c.JSON(http.StatusOK, res)
}
-137
View File
@@ -1,137 +0,0 @@
//go:build linux
package pb
import (
"encoding/xml"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func HandlerScan(e *core.RequestEvent) error {
// check if nmap installed
nmap, err := exec.LookPath("nmap")
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// check if scan range is valid
allPrivateSettings, err := e.App.FindAllRecords("settings_private")
if err != nil {
return err
}
settingsPrivate := allPrivateSettings[0]
scanRange := settingsPrivate.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// run nmap
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return fmt.Errorf("unable to get NET_RAW permissions")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability effective")
}
if err := c.SetFlag(cap.Inheritable, true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability inheritable")
}
if err := c.SetProc(); err != nil {
return fmt.Errorf("unable to raise NET_RAW capability")
}
if err := cap.SetAmbient(true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability ambient")
}
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout, "--privileged")
cmdOutput, err := cmd.Output()
if err != nil {
return err
}
// unmarshal xml
nmapOutput := Nmaprun{}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return err
}
type Device struct {
Name string `json:"name"`
IP string `json:"ip"`
MAC string `json:"mac"`
MACVendor string `json:"mac_vendor"`
}
// extract info from struct into data
type Response struct {
Netmask string `json:"netmask"`
Devices []Device `json:"devices"`
}
res := Response{}
var nm []string
for _, octet := range ipNet.Mask {
nm = append(nm, strconv.Itoa(int(octet)))
}
res.Netmask = strings.Join(nm, ".")
for _, host := range nmapOutput.Host {
dev := Device{}
for _, addr := range host.Address {
if addr.Addrtype == "ipv4" {
dev.IP = addr.Addr
} else if addr.Addrtype == "mac" {
dev.MAC = addr.Addr
}
if addr.Vendor != "" {
dev.MACVendor = addr.Vendor
} else {
dev.MACVendor = "Unknown"
}
}
if dev.IP == "" || dev.MAC == "" {
continue
}
names, err := net.LookupAddr(dev.IP)
if err != nil || len(names) == 0 {
dev.Name = dev.MACVendor
} else {
dev.Name = strings.TrimSuffix(names[0], ".")
}
if dev.Name == "" && dev.MACVendor == "" {
continue
}
res.Devices = append(res.Devices, dev)
}
return e.JSON(http.StatusOK, res)
}
-107
View File
@@ -1,107 +0,0 @@
//go:build !linux
package pb
import (
"encoding/xml"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
func HandlerScan(e *core.RequestEvent) error {
// check if nmap installed
nmap, err := exec.LookPath("nmap")
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// check if scan range is valid
allPrivateSettings, err := e.App.FindAllRecords("settings_private")
if err != nil {
return err
}
settingsPrivate := allPrivateSettings[0]
scanRange := settingsPrivate.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// run nmap
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout, "--privileged")
cmdOutput, err := cmd.Output()
if err != nil {
return err
}
// unmarshal xml
nmapOutput := Nmaprun{}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return err
}
type Device struct {
Name string `json:"name"`
IP string `json:"ip"`
MAC string `json:"mac"`
MACVendor string `json:"mac_vendor"`
}
// extract info from struct into data
type Response struct {
Netmask string `json:"netmask"`
Devices []Device `json:"devices"`
}
res := Response{}
var nm []string
for _, octet := range ipNet.Mask {
nm = append(nm, strconv.Itoa(int(octet)))
}
res.Netmask = strings.Join(nm, ".")
for _, host := range nmapOutput.Host {
dev := Device{}
for _, addr := range host.Address {
if addr.Addrtype == "ipv4" {
dev.IP = addr.Addr
} else if addr.Addrtype == "mac" {
dev.MAC = addr.Addr
}
if addr.Vendor != "" {
dev.MACVendor = addr.Vendor
} else {
dev.MACVendor = "Unknown"
}
}
if dev.IP == "" || dev.MAC == "" {
continue
}
names, err := net.LookupAddr(dev.IP)
if err != nil || len(names) == 0 {
dev.Name = dev.MACVendor
} else {
dev.Name = strings.TrimSuffix(names[0], ".")
}
if dev.Name == "" && dev.MACVendor == "" {
continue
}
res.Devices = append(res.Devices, dev)
}
return e.JSON(http.StatusOK, res)
}
-72
View File
@@ -1,72 +0,0 @@
package pb
import (
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tools/hook"
)
// SkipSuccessfulHealthCheckLog prevents routine Docker health checks from being
// persisted while retaining failed health checks for diagnostics.
func SkipSuccessfulHealthCheckLog(e *core.RequestEvent) error {
if e.Request.URL.Path == "/api/health" {
return apis.SkipSuccessActivityLog().Func(e)
}
return e.Next()
}
func RequireScanDevicesPermission() *hook.Handler[*core.RequestEvent] {
return &hook.Handler[*core.RequestEvent]{
Func: func(e *core.RequestEvent) error {
if e.HasSuperuserAuth() {
return e.Next()
}
user := e.Auth
if user == nil {
return apis.NewUnauthorizedError("The request requires superuser or record authorization token to be set.", nil)
}
res, err := e.App.FindFirstRecordByFilter(
"permissions",
"user.id = {:userId} && create = true",
dbx.Params{"userId": user.Id},
)
if res == nil || err != nil {
return apis.NewForbiddenError("You are not allowed to perform this request.", nil)
}
return e.Next()
},
}
}
func RequireUpSnapPermission() *hook.Handler[*core.RequestEvent] {
return &hook.Handler[*core.RequestEvent]{
Func: func(e *core.RequestEvent) error {
if e.HasSuperuserAuth() {
return e.Next()
}
user := e.Auth
if user == nil {
return apis.NewUnauthorizedError("The request requires superuser or record authorization token to be set.", nil)
}
deviceId := e.Request.PathValue("id")
// find record where user has device with power permission
res, err := e.App.FindFirstRecordByFilter("permissions", "user.id = {:userId} && power.id ?= {:deviceId}", dbx.Params{
"userId": user.Id,
"deviceId": deviceId,
})
if res == nil || err != nil {
return apis.NewForbiddenError("You are not allowed to perform this request.", nil)
}
return e.Next()
},
}
}
+105 -338
View File
@@ -1,415 +1,182 @@
package pb
import (
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path"
"time"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/plugins/ghupdate"
"ganigeorgiev.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/cronjobs"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logging"
_ "github.com/seriousm4x/upsnap/migrations"
"github.com/seriousm4x/upsnap/networking"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/seriousm4x/upsnap/backend/cronjobs"
"github.com/seriousm4x/upsnap/backend/logger"
_ "github.com/seriousm4x/upsnap/backend/migrations"
)
var Version = "(untracked)"
var App *pocketbase.PocketBase
func StartPocketBase(distDirFS fs.FS) error {
if err := logging.ConfigureConsole(os.Getenv("UPSNAP_LOG_LEVEL")); err != nil {
return err
}
// set data dir
// use "./pb_data" if it's in the same dir as upsnap binary
// else use os.UserConfigDir() / upsnap
var dataDir string
baseDir, err := os.Getwd()
if err != nil {
return err
}
pb_data := path.Join(baseDir, "pb_data")
if _, err = os.Stat(pb_data); err == nil {
dataDir = pb_data
} else if os.IsNotExist(err) {
userConfigDir, err := os.UserConfigDir()
if err != nil {
return err
}
upsnap_data := path.Join(userConfigDir, "upsnap")
if _, err = os.Stat(upsnap_data); err == nil {
dataDir = upsnap_data
} else if os.IsNotExist(err) {
if err := os.MkdirAll(upsnap_data, 0700); err != nil {
return err
}
}
}
// create app
app := pocketbase.NewWithConfig(pocketbase.Config{
DefaultDataDir: dataDir,
})
app.RootCmd.Short = "UpSnap CLI"
app.RootCmd.Version = Version
func StartPocketBase(distDirFS fs.FS) {
App = pocketbase.New()
App.RootCmd.Short = "UpSnap CLI"
App.RootCmd.Version = "3.0.0b1"
// auto migrate db
migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
migratecmd.MustRegister(App, App.RootCmd, &migratecmd.Options{
Automigrate: true,
})
// GitHub selfupdate
ghupdate.MustRegister(app, app.RootCmd, ghupdate.Config{
Owner: "seriousm4x",
Repo: "UpSnap",
ArchiveExecutable: "upsnap",
})
// event hooks
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
se.Router.BindFunc(SkipSuccessfulHealthCheckLog)
se.Router.GET("/{path...}", apis.Static(distDirFS, true))
se.Router.GET("/api/upsnap/wake/{id}", HandlerWake).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/wakegroup/{id}", HandlerWakeGroup).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/sleep/{id}", HandlerSleep).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/reboot/{id}", HandlerReboot).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/shutdown/{id}", HandlerShutdown).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/shutdowngroup/{id}", HandlerShutdownGroup).Bind(RequireUpSnapPermission())
se.Router.GET("/api/upsnap/scan", HandlerScan).Bind(RequireScanDevicesPermission())
se.Router.POST("/api/upsnap/validate-cron", HandlerValidateCron)
se.Router.GET("/api/upsnap/manifest.webmanifest", HandlerWebsiteManifest)
App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
// set static website path
e.Router.GET("/*", apis.StaticDirectoryHandler(distDirFS, true))
if err := importSettings(app); err != nil {
// add wake route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/wake/:id",
Handler: HandlerWake,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
},
})
// add shutdown route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/shutdown/:id",
Handler: HandlerShutdown,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
},
})
// add network scan route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/scan",
Handler: HandlerScan,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
},
})
// import environment and set settings
if err := importSettings(); err != nil {
return err
}
if err := resetDeviceStates(app); err != nil {
// reset device states and run ping cronjob
if err := resetDeviceStates(); err != nil {
return err
}
cronjobs.SetPingJobs(app)
cronjobs.StartPing()
cronjobs.SetWakeShutdownJobs(app)
cronjobs.StartWakeShutdown()
// run cronjobs
go cronjobs.RunPing(App)
go cronjobs.RunWakeShutdown()
// restart ping cronjobs or wake/shutdown cronjobs on model update
// add event hook before starting server.
// using this outside App.OnBeforeServe() would not work
app.OnModelAfterUpdateSuccess("settings_private", "devices").BindFunc(func(e *core.ModelEvent) error {
if e.Model.TableName() == "settings_private" {
cronjobs.SetPingJobs(app)
App.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
if e.Model.TableName() == "settings" {
for _, job := range cronjobs.CronPing.Entries() {
cronjobs.CronPing.Remove(job.ID)
}
go cronjobs.RunPing(App)
} else if e.Model.TableName() == "devices" {
// only restart wake/shutdown cronjobs if new model's cron changed
record := e.Model.(*core.Record)
newRecord := record.Fresh()
oldRecord := record.Original()
newWakeCron := newRecord.GetString("wake_cron")
newWakeCmd := newRecord.GetString("wake_cmd")
newWakeCronEnabled := newRecord.GetBool("wake_cron_enabled")
newShutdownCron := newRecord.GetString("shutdown_cron")
newShutdownCmd := newRecord.GetString("shutdown_cmd")
newShutdownCronEnabled := newRecord.GetBool("shutdown_cron_enabled")
oldWakeCron := oldRecord.GetString("wake_cron")
oldWakeCmd := oldRecord.GetString("wake_cmd")
oldWakeCronEnabled := oldRecord.GetBool("wake_cron_enabled")
oldShutdownCron := oldRecord.GetString("shutdown_cron")
oldShutdownCmd := oldRecord.GetString("shutdown_cmd")
oldShutdownCronEnabled := oldRecord.GetBool("shutdown_cron_enabled")
newIp := newRecord.GetString("ip")
oldIp := oldRecord.GetString("ip")
newPingCmd := newRecord.GetString("ping_cmd")
oldPingCmd := oldRecord.GetString("ping_cmd")
if newWakeCron != oldWakeCron ||
newWakeCmd != oldWakeCmd ||
newWakeCronEnabled != oldWakeCronEnabled ||
newShutdownCron != oldShutdownCron ||
newShutdownCronEnabled != oldShutdownCronEnabled ||
newShutdownCmd != oldShutdownCmd ||
newIp != oldIp ||
newPingCmd != oldPingCmd {
cronjobs.SetWakeShutdownJobs(app)
refreshDeviceList()
for _, job := range cronjobs.CronWakeShutdown.Entries() {
cronjobs.CronWakeShutdown.Remove(job.ID)
}
go cronjobs.RunWakeShutdown()
}
return e.Next()
return nil
})
return se.Next()
return nil
})
app.OnModelAfterCreateSuccess("_superusers", "devices").BindFunc(func(e *core.ModelEvent) error {
if e.Model.TableName() == "_superusers" {
// when pocketbase creates it's default superuser, do not trigger setSetupCompleted()
if e.Model.(*core.Record).Email() == core.DefaultInstallerEmail {
return e.Next()
}
if err := setSetupCompleted(e.App); err != nil {
logging.Logger(e.App).Error("Failed to update setup state", "error", err)
return err
}
return e.Next()
} else if e.Model.TableName() == "devices" {
// when a device is created, give the user all rights to the device he just created
deviceRec := e.Model.(*core.Record)
userId := deviceRec.GetString("created_by")
var permissionRec *core.Record
permissionRec, err := app.FindFirstRecordByFilter("permissions",
fmt.Sprintf("user.id = '%s'", userId))
if err != nil && err.Error() != "sql: no rows in result set" {
logging.Logger(e.App).Error("Failed to load permissions for new device", "error", err)
return err
} else if permissionRec != nil {
permissionRec.Set("read", append(permissionRec.GetStringSlice("read"), deviceRec.Id))
permissionRec.Set("update", append(permissionRec.GetStringSlice("update"), deviceRec.Id))
permissionRec.Set("delete", append(permissionRec.GetStringSlice("delete"), deviceRec.Id))
permissionRec.Set("power", append(permissionRec.GetStringSlice("power"), deviceRec.Id))
if err := app.Save(permissionRec); err != nil {
logging.Logger(e.App).Error("Failed to grant permissions for new device", "error", err)
return err
}
}
}
return e.Next()
// refresh the device list on database events
App.OnModelAfterCreate().Add(func(e *core.ModelEvent) error {
refreshDeviceList()
return nil
})
App.OnModelAfterDelete().Add(func(e *core.ModelEvent) error {
refreshDeviceList()
return nil
})
app.OnModelAfterDeleteSuccess("_superusers").BindFunc(func(e *core.ModelEvent) error {
if err := setSetupCompleted(e.App); err != nil {
logging.Logger(e.App).Error("Failed to update setup state", "error", err)
return err
}
return e.Next()
})
app.OnRecordValidate("devices").BindFunc(func(e *core.RecordEvent) error {
if !networking.ValidateSubnetMask(e.Record.GetString("netmask")) {
logging.Logger(e.App).Warn("Device has invalid netmask; using broadcast default", "device", e.Record.GetString("name"), "netmask", "255.255.255.255")
e.Record.Set("netmask", "255.255.255.255")
saveErr := e.App.Save(e.Record)
if saveErr != nil {
return saveErr
}
}
return e.Next()
})
app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
// a client just became active: catch up on any tracking sweep that
// was skipped while nobody was connected
settings, err := e.App.FindFirstRecordByFilter("settings_private", "")
if err != nil {
logging.Logger(e.App).Error("Failed to load private settings on realtime connection", "error", err)
} else if settings.GetBool("lazy_ping") && settings.GetString("track_ip_interval") != "" {
go iptracking.CatchUpSweep(e.App)
}
return e.Next()
})
app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
// PocketBase has no realtime disconnect hook. When a browser refreshes,
// the old client may disappear before the new connection is registered.
// Delay the offline transition and use the connecting client's id to
// distinguish a refresh from a genuine disconnect.
clientID := e.Client.Id()
defer func() {
// with lazy ping disabled the ping cron keeps updating device
// statuses while no clients are connected, so there is nothing
// to compensate for here
settings, err := e.App.FindFirstRecordByFilter("settings_private", "")
if err != nil {
logging.Logger(e.App).Error("Failed to load private settings for offline transition", "error", err)
return
}
if !settings.GetBool("lazy_ping") {
return
}
if len(e.App.SubscriptionsBroker().Clients()) != 0 {
return
}
time.AfterFunc(2*time.Second, func() {
if _, err := e.App.SubscriptionsBroker().ClientById(clientID); err == nil {
return
}
if len(e.App.SubscriptionsBroker().Clients()) != 0 {
return
}
allDevices, err := app.FindAllRecords("devices", dbx.NewExp("shutdown_cmd != ''"))
if err != nil {
logging.Logger(app).Error("Failed to load devices for offline transition", "error", err)
return
}
marked := 0
for _, device := range allDevices {
// leave devices that are already offline alone so the
// "offline since" timestamp keeps its real meaning
if device.GetString("status") == "offline" {
continue
}
device.Set("status", "offline")
if err := app.Save(device); err != nil {
logging.Logger(app).Error("Failed to save offline device status", "device", device.GetString("name"), "error", err)
return
}
marked++
}
if marked > 0 {
logging.Logger(app).Info("Marked devices offline after the last client disconnected", "count", marked)
}
})
}()
return e.Next()
})
app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error {
cronjobs.StopAll(e.App)
return e.Next()
})
// check for custom http listen address in env var, else use default
httpListen := os.Getenv("UPSNAP_HTTP_LISTEN")
if httpListen != "" {
if err := app.Bootstrap(); err != nil {
return err
}
if err := apis.Serve(app, apis.ServeConfig{
HttpAddr: httpListen,
ShowStartBanner: true,
}); err != nil {
return err
}
} else {
if err := app.Start(); err != nil {
return err
}
// start pocketbase
if err := App.Start(); err != nil {
log.Fatal(err)
}
return nil
}
func importSettings(app core.App) error {
settingsPrivateRecords, err := app.FindAllRecords("settings_private")
func importSettings() error {
// get first settings record
settingsRecords, err := App.Dao().FindRecordsByExpr("settings")
if err != nil {
return err
}
settingsPrivateCollection, err := app.FindCollectionByNameOrId("settings_private")
settingsCollection, err := App.Dao().FindCollectionByNameOrId("settings")
if err != nil {
return err
}
settingsPrivate := core.NewRecord(settingsPrivateCollection)
if len(settingsPrivateRecords) > 0 {
settingsPrivate = settingsPrivateRecords[0]
}
settingsPublicRecords, err := app.FindAllRecords("settings_public")
if err != nil {
return err
}
settingsPublicCollection, err := app.FindCollectionByNameOrId("settings_public")
if err != nil {
return err
}
settingsPublic := core.NewRecord(settingsPublicCollection)
if len(settingsPublicRecords) > 0 {
settingsPublic = settingsPublicRecords[0]
settings := models.NewRecord(settingsCollection)
if len(settingsRecords) > 0 {
settings = settingsRecords[0]
}
// set ping interval settings. priority:
// 1st: env var
// 2nd: database entry
// 3rd: default values
defaultInterval := "*/3 * * * * *"
interval := defaultInterval
if settingsPrivate.GetString("interval") != "" {
interval = settingsPrivate.GetString("interval")
interval := "@every 3s"
if settings.GetString("interval") != "" {
interval = settings.GetString("interval")
}
if os.Getenv("UPSNAP_INTERVAL") != "" {
interval = os.Getenv("UPSNAP_INTERVAL")
}
// validate interval before saving
p := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
if _, err := p.Parse(interval); err != nil {
if interval == "*/3 * * * *" || interval == "@every 3s" {
settingsPrivate.Set("interval", defaultInterval)
if e := app.Save(settingsPrivate); e != nil {
logging.Logger(app).Error("Failed to save default ping interval", "error", e)
}
} else {
logging.Logger(app).Error("Invalid ping interval; using default", "interval", interval, "default", defaultInterval)
}
interval = defaultInterval
}
settingsPrivate.Set("interval", interval)
// save settings to db
settings.Set("interval", interval)
if scanRange := os.Getenv("UPSNAP_SCAN_RANGE"); scanRange != "" {
settingsPrivate.Set("scan_range", scanRange)
settings.Set("scan_range", scanRange)
}
if websiteTitle := os.Getenv("UPSNAP_WEBSITE_TITLE"); websiteTitle != "" {
settingsPublic.Set("website_title", websiteTitle)
if scanRange := os.Getenv("UPSNAP_WEBSITE_TITLE"); scanRange != "" {
settings.Set("website_title", scanRange)
}
if err := app.Save(settingsPrivate); err != nil {
return err
}
if err := app.Save(settingsPublic); err != nil {
return err
}
if err := setSetupCompleted(app); err != nil {
logging.Logger(app).Error("Failed to update setup state", "error", err)
if err := App.Dao().SaveRecord(settings); err != nil {
return err
}
logger.Info.Println("Ping interval set to", interval)
return nil
}
func resetDeviceStates(app core.App) error {
devices, err := app.FindAllRecords("devices")
func resetDeviceStates() error {
devices, err := App.Dao().FindRecordsByExpr("devices")
if err != nil {
return err
}
for _, device := range devices {
device.Set("status", "offline")
if err := app.Save(device); err != nil {
if err := App.Dao().SaveRecord(device); err != nil {
return err
}
}
cronjobs.Devices = devices
return nil
}
func setSetupCompleted(app core.App) error {
allSuperusers, err := app.FindAllRecords(core.CollectionNameSuperusers)
func refreshDeviceList() {
var err error
cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices")
if err != nil {
return err
logger.Error.Println(err)
}
realSuperusers := 0
for _, r := range allSuperusers {
// exclude the temporary PocketBase installer account from the count
if r.Email() != core.DefaultInstallerEmail {
realSuperusers++
}
}
settingsPublicRecords, err := app.FindAllRecords("settings_public")
if err != nil {
return err
}
if realSuperusers > 0 {
settingsPublicRecords[0].Set("setup_completed", true)
} else {
settingsPublicRecords[0].Set("setup_completed", false)
}
if err := app.Save(settingsPublicRecords[0]); err != nil {
return err
}
return nil
}
-38
View File
@@ -1,38 +0,0 @@
services:
upsnap:
cap_add:
- NET_RAW # Required for privileged ping, network device scan, and IP address tracking (nmap)
cap_drop:
- ALL
container_name: upsnap
build:
dockerfile: Dockerfile.dev
network_mode: host
restart: unless-stopped
volumes:
- ./data:/app/pb_data
# # If you want to use FQDN instead of an IP and it is a ".local" domain, avahi and dbus must be installed on
# # the host, and the host dbus must be mounted in the container.
# # Before uncommmenting, ensure you are familiar with potential security implications of mounting dbus
# - /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket:ro
# # To use a non-root user, create the mountpoint first before starting
# # the container (mkdir data) so that it has the right permissions.
# user: 1000:1000
# environment:
# - TZ=Europe/Berlin # Set container timezone for cron schedules
# - UPSNAP_HTTP_LISTEN=127.0.0.1:8090
# - UPSNAP_INTERVAL=*/10 * * * * * # Sets the interval in which the devices are pinged
# - UPSNAP_LOG_LEVEL=INFO # Console level for UpSnap logs: DEBUG, INFO, WARN, ERROR, or OFF
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
# # dns is used for name resolution during network scan
# dns:
# - 192.18.0.1
# - 192.18.0.2
# # you can change the listen ip:port inside the container like this:
# entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
# healthcheck:
# test: curl -fs "http://localhost:5000/api/health" || exit 1
# interval: 10s
# # or install custom packages for shutdown
# entrypoint: /bin/sh -c "apk update && apk add --no-cache <YOUR_PACKAGE> && rm -rf /var/cache/apk/* && ./upsnap serve"
+9 -34
View File
@@ -1,36 +1,11 @@
version: "3"
services:
upsnap:
cap_add:
- NET_RAW # NET_RAW is required for privileged ping, network device scan and ip address tracking (nmap)
cap_drop:
- ALL
container_name: upsnap
image: ghcr.io/seriousm4x/upsnap:5 # images are also available on docker hub: seriousm4x/upsnap:5
network_mode: host # host is required for WOL magic packets
restart: unless-stopped
volumes:
- ./data:/app/pb_data
# # If you want to use FQDN instead of an IP and it is a ".local" domain, avahi and dbus must be installed on
# # the host, and the host dbus must be mounted in the container.
# # Before uncommmenting, ensure you are familiar with potential security implications of mounting dbus
# - /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket:ro
# # To use a non-root user, create the mountpoint first (mkdir data) so that it has the right permission.
# user: 1000:1000
# environment:
# - TZ=Europe/Berlin # Set container timezone for cron schedules
# - UPSNAP_HTTP_LISTEN=127.0.0.1:8090
# - UPSNAP_INTERVAL=*/10 * * * * * # Sets the interval in which the devices are pinged
# - UPSNAP_LOG_LEVEL=INFO # Console level for UpSnap logs: DEBUG, INFO, WARN, ERROR, or OFF
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
# - UPSNAP_SCAN_TIMEOUT=500ms # Scan timeout is nmap's --host-timeout value to wait for devices (https://nmap.org/book/man-performance.html)
# - UPSNAP_PING_PRIVILEGED=true # Default is true. Set to false for unprivileged ping
# For Linux hosts, unprivileged pings REQUIRES the host to set 'sysctl net.ipv4.ping_group_range="0 2147483647"'
# or another suitable value to grant the group access to send ping and WOL magic packets.
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
# security_opt:
# - no-new-privileges=true
# # dns is used for name resolution during network scan
# dns:
# - 192.18.0.1
# - 192.18.0.2
image: ghcr.io/seriousm4x/UpSnap
network_mode: host
command: ["./upsnap", "serve", "--http", "0.0.0.0:8090"]
healthcheck:
test: wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
interval: 1m
timeout: 10s
retries: 3
-1
View File
@@ -1 +0,0 @@
PUBLIC_VERSION=""
+14
View File
@@ -0,0 +1,14 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.\*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
+15
View File
@@ -0,0 +1,15 @@
module.exports = {
root: true,
extends: ['eslint:recommended', 'prettier'],
plugins: ['svelte3'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};
-9
View File
@@ -1,9 +0,0 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
-1
View File
@@ -1 +0,0 @@
_
+3
View File
@@ -1 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
cd frontend && npx lint-staged
-1
View File
@@ -1,2 +1 @@
engine-strict=true
resolution-mode=highest
+6 -7
View File
@@ -1,9 +1,8 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }],
"endOfLine": "lf"
"useTabs": false,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "none",
"semi": true,
"printWidth": 100
}
-41
View File
@@ -1,41 +0,0 @@
import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
import { includeIgnoreFile } from '@eslint/compat';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const gitignorePath = path.resolve(__dirname, '.gitignore');
/** @type {import('eslint').Linter.Config[]} */
export default [
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: ts.parser
}
}
},
{
ignores: ['build/', '.svelte-kit/', 'dist/']
}
];
+6363
View File
File diff suppressed because it is too large Load Diff
+42 -55
View File
@@ -1,57 +1,44 @@
{
"name": "upsnap-frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"vite": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "eslint --fix --cache .",
"format": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore .",
"prepare": "svelte-kit sync && cd .. && husky frontend/.husky",
"machine-translate": "inlang machine translate --project project.inlang"
},
"devDependencies": {
"@eslint/compat": "^2.1.1",
"@eslint/js": "^10.0.1",
"@inlang/cli": "^3.6.0",
"@inlang/paraglide-js": "^2.29.3",
"@sveltejs/adapter-static": "^3.0.11",
"@sveltejs/kit": "^2.70.4",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"daisyui": "^5.7.50",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.24.0",
"globals": "^17.14.0",
"husky": "^9.1.7",
"prettier": "^3.9.10",
"prettier-plugin-svelte": "^4.1.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"svelte": "^5.57.3",
"svelte-check": "^4.7.8",
"tailwindcss": "^4.3.4",
"tslib": "^2.9.1",
"typescript": "^6.0.3",
"typescript-eslint": "^8.72.1",
"vite": "^8.3.6"
},
"type": "module",
"lint-staged": {
"*.{js,svelte}": "eslint --fix --cache .",
"*.{js,css,md,svelte,scss}": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore ."
},
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^7.3.1",
"@tailwindcss/vite": "^4.3.4",
"cron-parser": "^5.10.3",
"date-fns": "^4.4.0",
"pocketbase": "^0.28.2",
"svelte-fa": "^4.0.4",
"svelte-french-toast": "github:seriousm4x/svelte-french-toast#fix-72-build",
"theme-change": "^2.5.2"
}
"name": "frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "cd .. && husky install frontend/.husky",
"lint": "prettier --ignore-path ../.gitignore --check --plugin-search-dir=. . && eslint --fix .",
"format": "prettier --ignore-path ../.gitignore --write --plugin-search-dir=. ."
},
"devDependencies": {
"@sveltejs/adapter-static": "^1.0.5",
"@sveltejs/kit": "^1.3.2",
"@typescript-eslint/eslint-plugin": "^5.49.0",
"@typescript-eslint/parser": "^5.49.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-svelte3": "^3.4.1",
"husky": "^8.0.3",
"lint-staged": "^13.1.0",
"prettier": "^2.8.3",
"prettier-plugin-svelte": "^2.9.0",
"svelte": "^3.55.1",
"svelte-preprocess": "^4.10.7",
"typescript": "^4.9.4",
"vite": "^4.0.4"
},
"type": "module",
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@popperjs/core": "^2.11.6",
"bootstrap": "5.3.0-alpha1",
"date-fns": "^2.29.3",
"pocketbase": "^0.10.1",
"sass": "^1.57.1",
"svelte-fa": "^3.0.3"
},
"lint-staged": {
"*.{js,svelte}": "eslint --fix --ignore-path ../.gitignore .",
"*.{js,css,md,svelte,scss}": "prettier --write --ignore-path ../.gitignore --plugin-search-dir=. ."
}
}
+1942 -2521
View File
File diff suppressed because it is too large Load Diff
-4
View File
@@ -1,4 +0,0 @@
allowBuilds:
esbuild: true
svelte-french-toast: true
svelte-french-toast@https://codeload.github.com/seriousm4x/svelte-french-toast/tar.gz/fbf89b9952cf11e15174b1841a6eb1ad23770349: true
-24
View File
@@ -1,24 +0,0 @@
# IF GIT SHOWED THAT THIS FILE CHANGED
#
# 1. RUN THE FOLLOWING COMMAND
#
# ---
# git rm --cached '**/*.inlang/.gitignore'
# ---
#
# 2. COMMIT THE CHANGE
#
# ---
# git commit -m "fix: remove tracked .gitignore from inlang project"
# ---
#
# Inlang handles the gitignore itself starting with version ^2.5.
#
# everything is ignored except settings.json and Paraglide configuration
*
!settings.json
!descriptions.json
!paraglide.config.js
!paraglide.config.mjs
!paraglide.config.ts
!paraglide.config.cjs
-1
View File
@@ -1 +0,0 @@
StfXY3tZWvr4FQntlM

Some files were not shown because too many files have changed in this diff Show More