222 lines
4.7 KiB
Go
222 lines
4.7 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/zip"
|
|
"encoding/json"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
dataDir = "data/image-hoster"
|
|
sessionsDir = filepath.Join(dataDir, "sessions")
|
|
metaPath = filepath.Join(dataDir, "sessions.json")
|
|
govLock sync.Mutex
|
|
)
|
|
|
|
func initGovernance() {
|
|
if err := os.MkdirAll(sessionsDir, 0755); err != nil {
|
|
slog.Error("failed to create sessions storage directory", "err", err)
|
|
}
|
|
|
|
loadSessionsMetadata()
|
|
go runGovernanceWatchdog()
|
|
}
|
|
|
|
func loadSessionsMetadata() {
|
|
govLock.Lock()
|
|
defer govLock.Unlock()
|
|
|
|
b, err := os.ReadFile(metaPath)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
var stored map[string]*SessionMeta
|
|
if err := json.Unmarshal(b, &stored); err != nil {
|
|
slog.Warn("could not decode sessions.json", "err", err)
|
|
return
|
|
}
|
|
|
|
globalState.mu.Lock()
|
|
defer globalState.mu.Unlock()
|
|
|
|
now := time.Now()
|
|
for id, s := range stored {
|
|
// If expired while server was offline, mark or delete
|
|
if !s.ExpiresAt.IsZero() && now.After(s.ExpiresAt) {
|
|
slog.Info("session expired during downtime", "session_id", id)
|
|
// Cleanup background session files if on server
|
|
if s.Mode == ModeServerBg {
|
|
os.RemoveAll(filepath.Join(sessionsDir, id))
|
|
}
|
|
continue
|
|
}
|
|
// If mode was relay, reset channels (browser will re-connect)
|
|
if s.Mode == ModeRelay {
|
|
globalState.relaySessions[id] = make(chan map[string]interface{}, 100)
|
|
}
|
|
globalState.sessions[id] = s
|
|
}
|
|
}
|
|
|
|
func saveSessionsMetadata() {
|
|
govLock.Lock()
|
|
defer govLock.Unlock()
|
|
|
|
globalState.mu.RLock()
|
|
data, err := json.MarshalIndent(globalState.sessions, "", " ")
|
|
globalState.mu.RUnlock()
|
|
|
|
if err != nil {
|
|
slog.Error("failed to serialize sessions metadata", "err", err)
|
|
return
|
|
}
|
|
|
|
tmpPath := metaPath + ".tmp"
|
|
if err := os.WriteFile(tmpPath, data, 0644); err == nil {
|
|
os.Rename(tmpPath, metaPath)
|
|
}
|
|
}
|
|
|
|
// Background auto-expiration governance watchdog
|
|
func runGovernanceWatchdog() {
|
|
ticker := time.NewTicker(20 * time.Second)
|
|
defer ticker.Stop()
|
|
|
|
for range ticker.C {
|
|
now := time.Now()
|
|
var expiredIDs []string
|
|
|
|
globalState.mu.RLock()
|
|
for id, s := range globalState.sessions {
|
|
if !s.ExpiresAt.IsZero() && now.After(s.ExpiresAt) {
|
|
expiredIDs = append(expiredIDs, id)
|
|
}
|
|
}
|
|
globalState.mu.RUnlock()
|
|
|
|
if len(expiredIDs) > 0 {
|
|
for _, id := range expiredIDs {
|
|
slog.Info("enterprise governance: auto-terminating expired session", "session_id", id)
|
|
deleteSessionInternal(id)
|
|
}
|
|
saveSessionsMetadata()
|
|
}
|
|
}
|
|
}
|
|
|
|
func deleteSessionInternal(id string) {
|
|
globalState.mu.Lock()
|
|
s, exists := globalState.sessions[id]
|
|
if !exists {
|
|
globalState.mu.Unlock()
|
|
return
|
|
}
|
|
|
|
delete(globalState.sessions, id)
|
|
if ch, ok := globalState.relaySessions[id]; ok {
|
|
close(ch)
|
|
delete(globalState.relaySessions, id)
|
|
}
|
|
delete(globalState.accessLogs, id)
|
|
globalState.mu.Unlock()
|
|
|
|
// Clean up server-side files if hosted on server
|
|
if s.Mode == ModeServerBg {
|
|
targetDir := filepath.Join(sessionsDir, id)
|
|
os.RemoveAll(targetDir)
|
|
}
|
|
}
|
|
|
|
func recordAccessEvent(sessionID, ip, method, path string, status int, bytes int64, userAgent string) {
|
|
globalState.mu.Lock()
|
|
defer globalState.mu.Unlock()
|
|
|
|
s, exists := globalState.sessions[sessionID]
|
|
if exists {
|
|
s.Requests++
|
|
s.BytesServed += bytes
|
|
s.LastActive = time.Now()
|
|
}
|
|
|
|
ev := AccessEvent{
|
|
Timestamp: time.Now(),
|
|
IP: ip,
|
|
Method: method,
|
|
Path: path,
|
|
Status: status,
|
|
Bytes: bytes,
|
|
UserAgent: userAgent,
|
|
}
|
|
|
|
logs := globalState.accessLogs[sessionID]
|
|
if len(logs) >= 60 {
|
|
logs = logs[1:]
|
|
}
|
|
globalState.accessLogs[sessionID] = append(logs, ev)
|
|
}
|
|
|
|
// Stream zip archive of all hosted files in a session
|
|
func createSessionZip(sessionID string, w http.ResponseWriter) error {
|
|
globalState.mu.RLock()
|
|
s, exists := globalState.sessions[sessionID]
|
|
globalState.mu.RUnlock()
|
|
|
|
if !exists {
|
|
return os.ErrNotExist
|
|
}
|
|
|
|
basePath := s.Path
|
|
if s.Mode == ModeServerBg {
|
|
basePath = filepath.Join(sessionsDir, sessionID)
|
|
}
|
|
|
|
if basePath == "" {
|
|
return os.ErrNotExist
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/zip")
|
|
w.Header().Set("Content-Disposition", `attachment; filename="hosted_session_`+sessionID+`.zip"`)
|
|
|
|
zw := zip.NewWriter(w)
|
|
defer zw.Close()
|
|
|
|
return filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
|
|
if err != nil || info.IsDir() {
|
|
return nil
|
|
}
|
|
rel, err := filepath.Rel(basePath, path)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
rel = filepath.ToSlash(rel)
|
|
|
|
hdr, err := zip.FileInfoHeader(info)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
hdr.Name = rel
|
|
hdr.Method = zip.Deflate
|
|
|
|
writer, err := zw.CreateHeader(hdr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer f.Close()
|
|
|
|
_, err = io.Copy(writer, f)
|
|
return err
|
|
})
|
|
}
|