Compare commits

..

3 commits

Author SHA1 Message Date
f209c52b61 use catppuccin-mocha
Some checks failed
continuous-integration/drone/push Build is failing
2023-09-16 13:48:21 +02:00
5ad1f6ae43 tmp to fixup for main
Some checks failed
continuous-integration/drone/push Build is failing
2023-09-01 18:42:37 +02:00
2ae7327f6b Improve web interface and allow setting boot option 2023-08-19 13:49:13 +02:00
12 changed files with 251 additions and 123 deletions

View file

@ -3,9 +3,8 @@ package bootoption
import "github.com/google/uuid"
type EFIApp struct {
Name string `json:"name"`
Path string `json:"path"`
DiskID string `json:"disk_id"`
Name string `json:"name"`
DevicePath string `json:"device_path"`
}
type Client struct {

View file

@ -6,6 +6,7 @@ import (
"encoding"
"errors"
"fmt"
"strings"
"github.com/google/uuid"
)
@ -20,7 +21,7 @@ const (
)
var spaceByte = []byte(" ")
var commaByte = []byte(",")
var commaByte = []byte(";")
const (
keyID = "id"
@ -140,9 +141,13 @@ func (am *acceptMessage) UnmarshalBinary(data []byte) error {
func (am *acceptMessage) MarshalBinary() (data []byte, err error) {
action := []byte(am.Action().String())
// efiApp := strings.ReplaceAll(am.efiApp, `\`, `\\`)
// efiApp = strings.ReplaceAll(efiApp, "File(", "")
efiApp := strings.ReplaceAll(am.efiApp, "File(", "")
efiApp, _ = strings.CutSuffix(efiApp, ")")
params := [][]byte{
[]byte(fmt.Sprintf("%s=%s", keyID, am.id.String())),
[]byte(fmt.Sprintf("%s=%s", keyEfiApp, am.efiApp)),
[]byte(fmt.Sprintf("%s=%s", keyEfiApp, efiApp)),
}
param_bytes := bytes.Join(params, commaByte)
return bytes.Join([][]byte{action, param_bytes}, spaceByte), nil

View file

@ -55,6 +55,7 @@ type jsonConf struct {
Iface string `json:"interface"`
Port int `json:"port"`
McastGroup string `json:"multicast_group"`
SrcAddr string `json:"src_addr"`
} `json:"boot_provider"`
}
@ -68,6 +69,7 @@ type AppConfig struct {
UPDMcastGroup string
UDPPort int
UDPIface string
UDPSrcAddr string
}
func parseLevel(lvlStr string) logrus.Level {
@ -97,6 +99,7 @@ func (ac *AppConfig) UnmarshalJSON(data []byte) error {
ac.UPDMcastGroup = jsonConf.BootProvider.McastGroup
ac.UDPIface = jsonConf.BootProvider.Iface
ac.UDPPort = jsonConf.BootProvider.Port
ac.UDPSrcAddr = jsonConf.BootProvider.SrcAddr
ac.DataFilepath = jsonConf.Storage.Path
return nil
}

View file

@ -1,85 +1,110 @@
package client
// import (
// "encoding/json"
// "fmt"
// "io"
// "net"
// "net/http"
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
// "git.faercol.me/faercol/http-boot-server/bootserver/helpers"
// "git.faercol.me/faercol/http-boot-server/bootserver/services"
// "github.com/sirupsen/logrus"
// )
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
"git.faercol.me/faercol/http-boot-server/bootserver/services"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
// const BootRoute = "/boot"
const SetBootRoute = "/config/boot"
// type BootController struct {
// clientService *services.ClientHandlerService
// l *logrus.Logger
// }
type setBootOptionPayload struct {
ClientID string `json:"client_id"`
OptionID string `json:"option_id"`
}
// func NewBootController(logger *logrus.Logger, service *services.ClientHandlerService) *BootController {
// return &BootController{
// clientService: service,
// l: logger,
// }
// }
type BootController struct {
clientService *services.ClientHandlerService
l *logrus.Logger
}
// func (bc *BootController) getBootOption(clientIP string, w http.ResponseWriter, r *http.Request) (int, []byte, error) {
// bootOption, err := bc.clientService.GetClientSelectedBootOption(clientIP)
// if err != nil {
// return http.StatusInternalServerError, nil, fmt.Errorf("failed to get boot option: %w", err)
// }
func NewBootController(logger *logrus.Logger, service *services.ClientHandlerService) *BootController {
return &BootController{
clientService: service,
l: logger,
}
}
// dat, err := json.Marshal(bootOption)
// if err != nil {
// return http.StatusInternalServerError, nil, fmt.Errorf("failed to serialize body")
// }
func (bc *BootController) setBootOption(w http.ResponseWriter, r *http.Request) (int, []byte, error) {
dat, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to read body: %w", err)
}
var payload setBootOptionPayload
if err := json.Unmarshal(dat, &payload); err != nil {
return http.StatusBadRequest, nil, fmt.Errorf("failed to parse body: %w", err)
}
// w.Header().Add("Content-Type", "application/json")
// return http.StatusOK, dat, nil
// }
clientID, err := uuid.Parse(payload.ClientID)
if err != nil {
return http.StatusBadRequest, []byte("bad client ID"), fmt.Errorf("invalid format for client ID: %w", err)
}
optionID, err := uuid.Parse(payload.OptionID)
if err != nil {
return http.StatusBadRequest, []byte("bad option ID"), fmt.Errorf("invalid format for option ID: %w", err)
}
// func (bc *BootController) setBootOption(clientIP string, w http.ResponseWriter, r *http.Request) (int, error) {
// dat, err := io.ReadAll(r.Body)
// if err != nil {
// return http.StatusInternalServerError, fmt.Errorf("failed to read body: %w", err)
// }
// var option string
// if err := json.Unmarshal(dat, &option); err != nil {
// return http.StatusInternalServerError, fmt.Errorf("failed to parse body: %w", err)
// }
if err := bc.clientService.SetClientBootOption(clientID, optionID.String()); err != nil {
if errors.Is(err, services.ErrUnknownClient) {
return http.StatusNotFound, []byte("unknown client"), err
}
if errors.Is(err, services.ErrUnknownBootOption) {
return http.StatusNotFound, []byte("unknown boot option"), err
}
return http.StatusInternalServerError, nil, fmt.Errorf("failed to set boot option for client: %w", err)
}
// if err := bc.clientService.SetClientBootOption(clientIP, option); err != nil {
// return http.StatusInternalServerError, fmt.Errorf("failed to set boot option for client: %w", err)
// }
return http.StatusAccepted, nil, nil
}
// return http.StatusAccepted, nil
// }
func (bc *BootController) deleteClient(w http.ResponseWriter, r *http.Request) (int, []byte, error) {
dat, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to read body: %w", err)
}
var payload setBootOptionPayload
if err := json.Unmarshal(dat, &payload); err != nil {
return http.StatusBadRequest, nil, fmt.Errorf("failed to parse body: %w", err)
}
// func (bc *BootController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
// if err != nil {
// bc.l.Errorf("Failed to read remote IP: %s", err.Error())
// helpers.HandleResponse(w, r, http.StatusInternalServerError, nil, bc.l)
// return
// }
clientID, err := uuid.Parse(payload.ClientID)
if err != nil {
return http.StatusBadRequest, []byte("bad client ID"), fmt.Errorf("invalid format for client ID: %w", err)
}
if err := bc.clientService.DeleteClient(clientID); err != nil {
return http.StatusInternalServerError, []byte("failed to delete client"), fmt.Errorf("failed to delete client: %w", err)
}
// var returncode int
// var content []byte
return http.StatusOK, nil, nil
}
// switch r.Method {
// case http.MethodGet:
// returncode, content, err = bc.getBootOption(clientIP, w, r)
// case http.MethodPut:
// returncode, err = bc.setBootOption(clientIP, w, r)
// default:
// returncode = http.StatusMethodNotAllowed
// }
func (bc *BootController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var returncode int
var content []byte
var err error
// if err != nil {
// bc.l.Errorf("An error occured while handling boot request: %q", err.Error())
// }
// helpers.HandleResponse(w, r, returncode, content, bc.l)
// }
switch r.Method {
case http.MethodPut:
returncode, content, err = bc.setBootOption(w, r)
if err != nil {
bc.l.Errorf("Error setting boot option for client: %s", err.Error())
}
case http.MethodDelete:
returncode, content, err = bc.deleteClient(w, r)
if err != nil {
bc.l.Errorf("Error setting boot option for client: %s", err.Error())
}
default:
helpers.HandleResponse(w, r, http.StatusMethodNotAllowed, nil, bc.l)
return
}
helpers.HandleResponse(w, r, returncode, content, bc.l)
}

View file

@ -15,18 +15,25 @@ import (
const EnrollRoute = "/enroll"
type newClientPayload struct {
ID string `json:"ID"`
ID string `json:"ID"`
MulticastGroup string `json:"multicast_group"`
MulticastPort int `json:"multicast_port"`
}
type EnrollController struct {
clientService *services.ClientHandlerService
l *logrus.Logger
clientService *services.ClientHandlerService
l *logrus.Logger
multicastPort int
multicastGroup string
}
func NewEnrollController(l *logrus.Logger, service *services.ClientHandlerService) *EnrollController {
func NewEnrollController(l *logrus.Logger, service *services.ClientHandlerService, mcastPort int, mcastGroup string) *EnrollController {
return &EnrollController{
clientService: service,
l: l,
clientService: service,
l: l,
multicastPort: mcastPort,
multicastGroup: mcastGroup,
}
}
@ -50,12 +57,13 @@ func (ec *EnrollController) enrollMachine(w http.ResponseWriter, r *http.Request
return http.StatusInternalServerError, nil, fmt.Errorf("failed to create client %w", err)
}
payload, err := json.Marshal(newClientPayload{ID: cltID.String()})
payload, err := json.Marshal(newClientPayload{ID: cltID.String(), MulticastGroup: ec.multicastGroup, MulticastPort: ec.multicastPort})
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to serialize payload: %w", err)
}
ec.l.Infof("Added client")
w.Header().Add("Content-Type", "application/json")
return http.StatusOK, payload, nil
}

View file

@ -7,6 +7,7 @@ import (
"io"
"net/http"
"path/filepath"
"sort"
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
"git.faercol.me/faercol/http-boot-server/bootserver/services"
@ -63,10 +64,13 @@ func (uc *UIController) serveUI(w http.ResponseWriter, r *http.Request) (int, in
for id, bo := range clt.Options {
tplBO = append(tplBO, templateBootOption{
Name: bo.Name,
Path: bo.Path,
Path: bo.DevicePath,
ID: id,
Selected: id == clt.SelectedOption,
})
sort.Slice(tplBO, func(i, j int) bool {
return tplBO[i].ID < tplBO[j].ID
})
}
dat.Clients = append(dat.Clients, templateClient{
ID: clt.ID.String(),
@ -87,10 +91,16 @@ func (uc *UIController) serveUI(w http.ResponseWriter, r *http.Request) (int, in
}
func (uc *UIController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
uc.l.Errorf("Unhandled route %q", r.RequestURI)
helpers.HandleResponse(w, r, http.StatusNotFound, nil, uc.l)
return
}
returncode, contentLength, err := uc.serveUI(w, r)
if err != nil {
uc.l.Errorf("Error serving UI: %s", err.Error())
helpers.HandleResponse(w, r, returncode, nil, uc.l)
} else {
helpers.AddToContext(r, returncode, contentLength)
}
helpers.AddToContext(r, returncode, contentLength)
}

View file

@ -67,10 +67,11 @@ func New(appConf *config.AppConfig, logger *logrus.Logger) (*Server, error) {
}
service := services.NewClientHandlerService(appConf.DataFilepath, logger)
controllers := map[string]http.Handler{
client.EnrollRoute: middlewares.WithLogger(client.NewEnrollController(logger, service), logger),
client.ConfigRoute: middlewares.WithLogger(client.NewGetConfigController(logger, service, appConf), logger),
ui.StaticRoute: &ui.StaticController{},
ui.UIRoute: middlewares.WithLogger(ui.NewUIController(logger, service), logger),
client.EnrollRoute: middlewares.WithLogger(client.NewEnrollController(logger, service, appConf.UDPPort, appConf.UPDMcastGroup), logger),
client.ConfigRoute: middlewares.WithLogger(client.NewGetConfigController(logger, service, appConf), logger),
client.SetBootRoute: middlewares.WithLogger(client.NewBootController(logger, service), logger),
ui.StaticRoute: &ui.StaticController{},
ui.UIRoute: middlewares.WithLogger(ui.NewUIController(logger, service), logger),
}
m := http.NewServeMux()

View file

@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"sort"
"time"
"git.faercol.me/faercol/http-boot-server/bootserver/bootoption"
@ -111,6 +112,9 @@ func (chs *ClientHandlerService) GetAllClientConfig() ([]*bootoption.Client, err
clt.ID = id
clientList = append(clientList, clt)
}
sort.Slice(clientList, func(i, j int) bool {
return clientList[i].ID.String() < clientList[j].ID.String()
})
return clientList, nil
}
@ -152,6 +156,20 @@ func (chs *ClientHandlerService) GetClientSelectedBootOption(client uuid.UUID) (
}
}
func (chs *ClientHandlerService) DeleteClient(client uuid.UUID) error {
var err error
clients, err := chs.load()
if err != nil {
return fmt.Errorf("failed to load current config: %w", err)
}
delete(clients, client)
if err := chs.unload(clients); err != nil {
return fmt.Errorf("failed to save current config: %w", err)
}
return nil
}
func (chs *ClientHandlerService) SetClientBootOption(client uuid.UUID, option string) error {
var err error

View file

@ -0,0 +1,20 @@
function selectBootOption(clientID, bootID) {
const Http = new XMLHttpRequest;
var host = window.location.protocol + "//" + window.location.host;
const url = host + "/config/boot"
console.debug(`Sending request to ${url}`);
Http.open("PUT", url);
Http.setRequestHeader("Content-Type", "application/json");
const body = JSON.stringify({
client_id: clientID,
option_id: bootID,
});
Http.onload = () => {
if (Http.readyState === 4 && Http.status === 202) {
location.reload();
} else {
console.error(`Unexpected returncode ${Http.status}`)
}
};
Http.send(body);
}

View file

@ -1,24 +1,45 @@
:root {
--base: #1e1e2e;
--text: #cdd6f4;
--subtext1: #bac2de;
--surface0: #313244;
--surface1: #45475a;
--red: #f38ba8;
--blue: #89b4fa;
}
body {
background-color: black;
color: white;
background-color: var(--base);
color: var(--text);
}
.page-content {
width: 90%;
max-width: 1200px;
margin: auto;
}
.container {
border-radius: 5px;
background-color: var(--surface0);
padding: 5px;
border-radius: 5px 5px;
margin: 5px auto;
}
.main-container {
border-radius: 5px;
background-color: #121212;
padding: 20px;
}
.title-container {
border-radius: 5px 5px 0px 0px;
padding: 5px;
background-color: #1A3A5D;
background-color: var(--surface0);
}
.client-list-container {
border-radius: 0px 0px 5px 5px;
padding: 10px;
background-color: #232323;
background-color: var(--surface0);
}
.client-container {
@ -36,7 +57,7 @@ body {
.client-uuid {
font-size: smaller;
color: #9B9B9B;
color: var(--subtext1);
}
}
@ -48,9 +69,16 @@ body {
.client-boot-option {
margin: 3px auto;
padding: 8px 8px;
cursor: pointer;
&.selected {
background-color: #3E4042;
background-color: var(--surface-active);
cursor: default;
}
&:hover {
background-color: var(--surface-hover);
--text-variant: #000000;
}
}
@ -61,7 +89,7 @@ body {
.boot-option-uuid {
font-size: smaller;
color: #9B9B9B;
color: var(--text-variant);
}
.boot-option-path {

View file

@ -5,43 +5,47 @@
<meta charset="utf-8">
<title>HTTP boot server</title>
<link rel="stylesheet" href="/static/stylesheets/main.css">
<script src="/static/scripts/index.js"></script>
</head>
<body>
<div class="main-container">
<div class="page-content">
<div class="title-container">
<div class="title-container container">
<h1>HTTP boot server admin page</h1>
</div>
<div class="client-list-container">
<h2>Currently enrolled clients</h2>
<div class="main-container container">
<div class="client-list">
<h2>{{len .Clients}} enrolled clients</h2>
{{range .Clients}}
<div class="client-container">
<div class="client-header">
<span class="client-name">{{.Name}}</span>
<span class="client-uuid">{{.ID}}</span>
</div>
<div class="client-content">
<div class="client-boot-options">
{{range .BootOptions}}
<div class="client-boot-option{{if .Selected}} selected{{end}}">
<div>
<span class="boot-option-name">{{.Name}}</span>
<span class="boot-option-uuid">{{.ID}}</span>
</div>
<div>
<span class="boot-option-path">{{.Path}}</span>
{{range .Clients}}
<div class="client-container">
<div class="client-header">
<span class="client-name">{{.Name}}</span>
<span class="client-uuid">{{.ID}}</span>
</div>
<div class="client-content">
<div class="client-boot-options">
{{$cid := .ID}}{{range .BootOptions}}
<div class="client-boot-option{{if .Selected}} selected{{end}}"
onclick="selectBootOption('{{$cid}}', '{{.ID}}')">
<div>
<span class="boot-option-name">{{.Name}}</span>
<span class="boot-option-uuid">{{.ID}}</span>
</div>
<div>
<span class="boot-option-path">{{.Path}}</span>
</div>
</div>
{{end}}
</div>
{{end}}
</div>
</div>
{{end}}
</div>
{{end}}
</div>
</div>
</div>
</body>

View file

@ -22,6 +22,7 @@ type udpMessage struct {
type UDPListener struct {
addr *net.UDPAddr
laddr *net.UDPAddr
iface *net.Interface
l *net.UDPConn
log *logrus.Logger
@ -41,9 +42,15 @@ func New(conf *config.AppConfig, log *logrus.Logger) (*UDPListener, error) {
return nil, fmt.Errorf("failed to resolve interface name %s: %w", conf.UDPIface, err)
}
laddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("[%s%%%s]:0", conf.UDPSrcAddr, conf.UDPIface))
if err != nil {
return nil, fmt.Errorf("failed to resolve UDP source address: %w", err)
}
return &UDPListener{
addr: addr,
iface: iface,
laddr: laddr,
ctx: context.TODO(),
service: services.NewClientHandlerService(conf.DataFilepath, log),
log: log,
@ -78,7 +85,7 @@ func (l *UDPListener) handleBootRequest(msg bootprotocol.Message, subLogger logr
requestLogger.Errorf("Failed to get config for client: %s", err.Error())
return bootprotocol.Deny(msg.ID(), "unknown server error")
}
return bootprotocol.Accept(msg.ID(), bootOption.Path)
return bootprotocol.Accept(msg.ID(), bootOption.DevicePath)
}
func (l *UDPListener) handleClient(msg *udpMessage) error {
@ -88,7 +95,7 @@ func (l *UDPListener) handleClient(msg *udpMessage) error {
response := l.handleBootRequest(msg.message, clientLogger)
clientLogger.Debug("Dialing client for answer")
con, err := net.DialUDP("udp", nil, msg.sourceAddr)
con, err := net.DialUDP("udp", l.laddr, msg.sourceAddr)
if err != nil {
return fmt.Errorf("failed to dialed client: %w", err)
}