Files
ssw-mvp/scard/code/connector/easytier/client.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

243 lines
6.3 KiB
Go

// EasyTier client for connector
package easytier
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
"strings"
"time"
"security-connector/connector/tlsutil"
)
// Client is the EasyTier client for the connector
type Client struct {
serverURL string
deviceID string
networkID string
credential string
caCert string
insecure bool
process *exec.Cmd
done chan struct{}
}
// Option configures the EasyTier client.
type Option func(*Client)
// WithCA makes the client trust the given PEM CA (soft-PKI lab runs).
func WithCA(caCert string) Option { return func(c *Client) { c.caCert = caCert } }
// WithInsecure disables server certificate verification (lab only).
func WithInsecure(insecure bool) Option { return func(c *Client) { c.insecure = insecure } }
// JoinRequest is the request payload for EasyTier join
type JoinRequest struct {
NetworkID string `json:"network_id"`
NodeID string `json:"node_id"`
DeviceID string `json:"device_id"`
}
// JoinResponse is the response from EasyTier join API
type JoinResponse struct {
Code string `json:"code"`
Credential string `json:"credential"` // Format: "device_id:temp_key"
ServerAddr string `json:"server_addr"`
NetworkID string `json:"network_id"`
}
// NewClient creates a new EasyTier client
func NewClient(serverURL, deviceID, networkID string, opts ...Option) *Client {
// Don't modify serverURL - we add "/" in URL construction
c := &Client{
serverURL: serverURL,
deviceID: deviceID,
networkID: networkID,
done: make(chan struct{}),
}
for _, opt := range opts {
opt(c)
}
return c
}
// RequestJoin requests credentials from the server to join EasyTier network
func (c *Client) RequestJoin(ctx context.Context) error {
reqBody := JoinRequest{
NetworkID: c.networkID,
NodeID: c.deviceID,
DeviceID: c.deviceID,
}
data, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
url := c.serverURL + "/api/v1/easytier/join"
log.Printf("[EasyTier] Requesting join to network %s (URL: %s)", c.networkID, url)
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(string(data)))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
client := tlsutil.NewClient(c.caCert, c.insecure, 10*time.Second)
resp, err := client.Do(httpReq)
if err != nil {
return fmt.Errorf("HTTP request failed: %w", err)
}
defer resp.Body.Close()
var joinResp JoinResponse
if err := json.NewDecoder(resp.Body).Decode(&joinResp); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
log.Printf("[EasyTier] Join response: code=%s, credential=%s", joinResp.Code, joinResp.Credential)
if joinResp.Code != "success" {
return fmt.Errorf("server returned error: %s", joinResp.Code)
}
c.credential = joinResp.Credential
return nil
}
// Start launches the easytier-node process
func (c *Client) Start(ctx context.Context) error {
if c.credential == "" {
return fmt.Errorf("credential not set, call RequestJoin first")
}
log.Printf("[EasyTier] Starting with network=%s, credential=%s", c.networkID, c.credential)
// Check if easytier-core exists (Zynq boards) or easytier-node
binaryPath := c.findEasytierBinary()
if binaryPath == "" {
log.Printf("[EasyTier] easytier-core/node not found, running in simulation mode")
return c.runSimulation(ctx)
}
// Command: easytier-core --credential <cred> --network-name <network>
cmd := exec.CommandContext(ctx, binaryPath,
"--credential", c.credential,
"--network-name", c.networkID,
)
c.process = cmd
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start easytier-node: %w", err)
}
go func() {
cmd.Wait()
close(c.done)
}()
log.Printf("[EasyTier] easytier-node started successfully")
return nil
}
// Stop terminates the easytier-node process
func (c *Client) Stop() error {
if c.process != nil && c.process.Process != nil {
log.Printf("[EasyTier] Stopping easytier-node")
return c.process.Process.Kill()
}
return nil
}
// waitDone blocks until the process exits
func (c *Client) waitDone(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c.done:
return nil
}
}
// runSimulation simulates EasyTier for environments without easytier-node binary
func (c *Client) runSimulation(ctx context.Context) error {
log.Printf("[EasyTier] Simulation: easytier-node --enable-creds -n %s -c %s",
c.networkID, c.credential)
// In simulation mode, just mark done after a delay
go func() {
select {
case <-ctx.Done():
case <-time.After(60 * time.Second):
}
close(c.done)
}()
return nil
}
// checkEasytierExists checks if easytier binary exists
func (c *Client) checkEasytierExists() bool {
return c.findEasytierBinary() != ""
}
// findEasytierBinary locates easytier-core or easytier-node
func (c *Client) findEasytierBinary() string {
// Common locations on Zynq boards and VMs
paths := []string{
"/opt/easytier/easytier-core",
"/opt/easytier/easytier-node",
"/usr/local/bin/easytier-core",
"/usr/local/bin/easytier-node",
"/home/ssw/easytier-core",
"/home/ssw/easytier-node",
"./easytier-core",
"./easytier-node",
}
// Try direct paths first
for _, p := range paths {
cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("test -x %s && echo yes", p))
if cmd.Run() == nil {
output, _ := exec.Command("/bin/sh", "-c", fmt.Sprintf("test -x %s && echo yes", p)).Output()
if len(output) > 0 && output[0] == 'y' {
log.Printf("[EasyTier] Found binary at: %s", p)
return p
}
}
}
// Fallback: check PATH for easytier-core or easytier-node
for _, name := range []string{"easytier-core", "easytier-node"} {
cmd := exec.Command("which", name)
if cmd.Run() == nil {
out, _ := exec.Command("which", name).Output()
path := strings.TrimSpace(string(out))
if path != "" {
log.Printf("[EasyTier] Found binary in PATH: %s", path)
return path
}
}
}
log.Printf("[EasyTier] No easytier binary found in any location")
return ""
}
// GetCredential returns the current credential
func (c *Client) GetCredential() string {
return c.credential
}
// IsRunning returns true if easytier is running (or in simulation)
func (c *Client) IsRunning() bool {
select {
case <-c.done:
return false
default:
return true
}
}