Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ linters:
- wsl
- tagliatelle
- noinlineerr
- ireturn
settings:
depguard:
rules:
Expand Down
38 changes: 30 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,49 @@
# SoL - Shutdown on LAN

SoL is a service that listens for Wake-on-LAN magic packets and shuts down the system when received.
SoL is a service that listens for Wake-on-LAN magic packets and triggers power actions (shutdown or reboot) when received.

## Inspiration

This project was inspired by the article ["Выключаем компьютер через Wake-on-Lan"](https://habr.com/ru/articles/816765/) on Habr, which demonstrates how to repurpose Wake-on-LAN packets for shutdown functionality instead of wake-up.

## Description of the service
## Description

The sol service is built using [cobra](https://github.com/spf13/cobra) CLI framework and Go standard library.

### Listen
The listen command listens for Wake-on-LAN magic packets on the specified network interface and shuts down the system when a matching packet is received.

The listen command listens for Wake-on-LAN magic packets on the specified network interface and triggers a power action when a matching packet is received.

### Protocol
The service listens for Wake-on-LAN magic packets on UDP ports (commonly 7 or 9). When a magic packet containing the target MAC address is received, the system is shut down.

The service listens for Wake-on-LAN magic packets on UDP ports. When a magic packet containing the target MAC address is received, the configured power action is executed.

### Supported Actions

- **shutdown** — shut down the system (`shutdown -h now` on Linux/macOS, `shutdown -s -t 0 -f` on Windows)
- **reboot** — restart the system (`shutdown -r now` on Linux/macOS, `shutdown -r -t 0 -f` on Windows)

## Run the service

### Simple mode

```bash
sol listen --iface eth0 --port 9
```

### Advanced mode (multiple ports)

Listen on multiple ports with different actions:

```bash
sol listen --iface eth0
sol listen --iface eth0 --port 9 --port 8:reboot
```

### Options

- `--iface`: Network interface name to bind to (required)
- `--port`: UDP port to listen on (default: 9)
- `--dry-run`: Log when a matching packet is received instead of shutting down
- `--port`: UDP port to listen on, optionally with action (e.g. `9` for shutdown, `8:reboot` for specific action). Can be specified multiple times
- `--dry-run`: Log when a matching packet is received instead of executing the power action

## Installation

Expand Down Expand Up @@ -85,7 +102,7 @@ To run SoL as a systemd service that starts automatically:
Wants=network-online.target

[Service]
ExecStart=/usr/local/bin/sol listen --iface enp2s0 --port 9
ExecStart=/usr/local/bin/sol listen --iface enp2s0 --port 9 --port 8:reboot
Restart=always
RestartSec=5
User=root
Expand Down Expand Up @@ -132,3 +149,8 @@ To run SoL as a systemd service that starts automatically:
- `Restart=always` automatically restarts the service if it crashes
- For production use, remove `--dry-run` flag from the ExecStart command
- Consider creating a dedicated user instead of running as root for better security
- When using multiple ports, separate them with multiple `--port` flags

### Security Note

Any device on the same network segment can send Wake-on-LAN magic packets. This means any device that can reach the listening ports can trigger shutdown or reboot. Use firewall rules or network segmentation to restrict access.
81 changes: 70 additions & 11 deletions cmd/listen.go
Original file line number Diff line number Diff line change
@@ -1,41 +1,100 @@
package cmd

import (
"errors"
"fmt"
"strings"

"github.com/spf13/cobra"

"github.com/bavix/sol/internal/app"
"github.com/bavix/sol/internal/config"
"github.com/bavix/sol/internal/deps"
"github.com/bavix/sol/internal/domain/wol"
)

var errNoPorts = errors.New("at least one --port flag is required")

const portPartsCount = 2

var listenCmd = &cobra.Command{
Use: "listen",
Short: "Listen for magic packets and shutdown system",
Long: "Listen for Wake-on-LAN magic packets on the specified network interface and shutdown the system when received.",
RunE: func(_ *cobra.Command, _ []string) error {
Short: "Listen for magic packets and trigger power action",
Long: "Listen for Wake-on-LAN magic packets on the specified network interface and trigger power action (shutdown/reboot) when received.",
RunE: func(command *cobra.Command, _ []string) error {
parsedRules, err := parsePorts()
if err != nil {
return err
}

cfg := &config.Config{
InterfaceName: interfaceName,
Port: port,
DryRun: dryRun,
Rules: parsedRules,
}

application := app.New(cfg)
builder := deps.NewBuilder(cfg)

return application.Run()
application, buildErr := builder.BuildListenService()
if buildErr != nil {
return buildErr
}

return application.Run(command.Context(), cfg.InterfaceName)
},
}

var (
interfaceName string
port int
dryRun bool
portStrings []string
)

func init() {
rootCmd.AddCommand(listenCmd)

listenCmd.Flags().StringVar(&interfaceName, "iface", "", "Network interface name to bind to (e.g., 'Ethernet 4', 'eth0')")
listenCmd.Flags().IntVar(&port, "port", app.WoLPortDefault, "UDP port to listen on (7 or 9 are common for WoL)")
listenCmd.Flags().BoolVar(&dryRun, "dry-run", false, "Log when a matching packet is received instead of shutting down")
listenCmd.Flags().StringVar(&interfaceName, "iface", "", "Network interface name to bind to (required)")
listenCmd.Flags().BoolVar(&dryRun, "dry-run", false, "Log when a matching packet is received instead of executing the power action")
listenCmd.Flags().StringArrayVar(&portStrings, "port", nil,
"UDP port to listen on, optionally with action (e.g. '9' for shutdown, '8:reboot' for specific action). Can be specified multiple times")

_ = listenCmd.MarkFlagRequired("iface")
}

func parsePorts() ([]wol.Rule, error) {
if len(portStrings) == 0 {
return nil, errNoPorts
}

defaultAction := wol.ActionShutdown

rules := make([]wol.Rule, 0, len(portStrings))
for _, ps := range portStrings {
parts := strings.Split(ps, ":")
portStr := parts[0]
actionStr := ""

if len(parts) == portPartsCount {
actionStr = parts[1]
}

var port int
if _, err := fmt.Sscanf(portStr, "%d", &port); err != nil {
return nil, fmt.Errorf("invalid port %s: %w", portStr, err)
}

action := defaultAction

if actionStr != "" {
var err error

action, err = wol.ParseAction(actionStr)
if err != nil {
return nil, fmt.Errorf("invalid action in port %s: %w", ps, err)
}
}

rules = append(rules, wol.Rule{Port: port, Action: action})
}

return rules, nil
}
8 changes: 7 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@ module github.com/bavix/sol

go 1.26

require github.com/spf13/cobra v1.10.2
require (
github.com/spf13/cobra v1.10.2
github.com/stretchr/testify v1.11.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
9 changes: 9 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading