Virtualization phase 2: ISOs, New VM from ISO, the VGA console in the browser, nightly exports, mounts, instance sensors

- Library: an ISO shelf in virt/isos: upload (the Files uploader), fetch by URL with an
  optional sha256, import a file from the machine by copying it in, rename, delete (refused
  while attached), attach to a VM as a CD-ROM live or stopped with boot-first, eject, and
  New VM from ISO: an empty VM with the ISO as first boot device, Secure Boot on or off.
- The VGA console: Ham Lab asks Incus for the VM's SPICE console over its unix socket and
  bridges the display websocket to the browser, where spice-html5 (vendored from upstream
  b372aab, LGPL, loaded on demand) draws it; Ctrl+Alt+Del, fit-to-window.
- Exports: every instance as a tarball in virt/exports/<name>/, kept to a count, as a cron
  line in /etc/cron.d/hamlab-virt calling hamlab virt-export, settings and the last run
  as files beside the data; Export now per instance or for all.
- Disks tab per instance: the root disk, attached ISOs with Eject, bind mounts in and out
  (shift for containers, virtiofs for VMs).
- instance.* sensors (running, down, state, cpu, mem) and the VM-or-container-down alert
  default, offered once to installs seeded before it existed.
- cloud-init: Use my SSH keys writes a cloud-config from the account's public keys.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mitchell-Johnson
2026-10-09 22:21:57 -07:00
co-authored by Claude Fable 5.1
parent 66498a58c5
commit 43ebacdd92
46 changed files with 14493 additions and 25 deletions
+21
View File
@@ -30,6 +30,7 @@ import (
"hamlab/internal/config"
"hamlab/internal/cron"
"hamlab/internal/files"
"hamlab/internal/incus"
"hamlab/internal/metrics"
"hamlab/internal/nodes"
"hamlab/internal/priv"
@@ -62,6 +63,7 @@ func main() {
passwd [user] set a user's password (makes the account if it is new; reads stdin when piped)
users list the accounts
zfs-snapshot <id> run one ZFS snapshot schedule (what its cron line calls)
virt-export [name…] export Incus instances to the library (what its cron line calls)
docker-update <id> run one image-update schedule (what its cron line calls)
user-rm <user> remove an account and sign it out everywhere
check verify the config and state load, then exit
@@ -143,6 +145,10 @@ func main() {
if err := zfsSnapshot(cfg, flag.Arg(1)); err != nil {
log.Fatal(err)
}
case "virt-export": // the nightly cron line from the Virtualization tab; optional instance names
if err := virtExport(cfg, flag.Args()[1:]); err != nil {
log.Fatal(err)
}
case "users":
migrateUsers(cfg)
if len(cfg.Users) == 0 {
@@ -293,6 +299,21 @@ func zfsSnapshot(cfg *config.Config, id string) error {
return nil
}
// virtExport runs the instance exports the Virtualization tab scheduled, as the account Ham
// Lab runs as (which is in incus-admin), and records the run beside the data.
func virtExport(cfg *config.Config, names []string) error {
who := os.Getenv("USER")
if u, err := user.Current(); err == nil && u.Username != "" {
who = u.Username
}
run := incus.New(cfg.DataDir(), who, version).RunExports(context.Background(), names, func(l string) { fmt.Println(l) })
fmt.Printf("exported %d, pruned %d, %.0f s\n", len(run.Exported), len(run.Pruned), run.Seconds)
if len(run.Errors) > 0 {
return errors.New(strings.Join(run.Errors, "; "))
}
return nil
}
func migrateUsers(cfg *config.Config) {
name := os.Getenv("USER")
if u, err := user.Current(); err == nil && u.Username != "" {
+21
View File
@@ -71,6 +71,9 @@ type alertSaved struct {
Channels []AlertChannel `json:"channels"`
Events []AlertEvent `json:"events"`
Seeded bool `json:"seeded"`
// SawInstanceRule marks that the instance-down default has been offered once; set so that
// removing it stays removed.
SawInstanceRule bool `json:"saw_instance_rule,omitempty"`
// Firing is what was firing when the hub last looked, so a restart (every deploy is one)
// carries on where it was and doesn't announce the same alerts all over again.
Firing map[string]alertKept `json:"firing,omitempty"`
@@ -102,6 +105,7 @@ var defaultRules = []AlertRule{
{ID: "machine-offline", Name: "Machine not answering", Sensor: "hamlab.reachable", Op: "==", Value: false, ForSec: 120, Severity: "crit", Enabled: true},
{ID: "container-down", Name: "Container down", Sensor: "container.*.down", Op: "==", Value: true, ForSec: 120, Severity: "crit", Enabled: true},
{ID: "container-unhealthy", Name: "Container unhealthy", Sensor: "container.*.health", Op: "==", Value: "unhealthy", ForSec: 180, Severity: "warn", Enabled: true},
{ID: "instance-down", Name: "VM or container down", Sensor: "instance.*.down", Op: "==", Value: true, ForSec: 120, Severity: "crit", Enabled: true},
{ID: "service-failed", Name: "A service has failed", Sensor: "services.failed", Op: ">", Value: 0.0, ForSec: 300, Severity: "warn", Enabled: true},
{ID: "disk-full", Name: "Filesystem nearly full", Sensor: "fs.*.used_pct", Op: ">=", Value: 90.0, ForSec: 300, Severity: "warn", Enabled: true},
{ID: "pool-unhealthy", Name: "ZFS pool not healthy", Sensor: "zfs.*.healthy", Op: "==", Value: false, ForSec: 60, Severity: "crit", Enabled: true},
@@ -122,6 +126,23 @@ func newAlertEngine(s *Server) *alertEngine {
for key, k := range e.saved.Firing {
e.state[key] = &alertState{pending: time.UnixMilli(k.Since), firing: true, since: time.UnixMilli(k.Since), value: k.Value}
}
// a default added after an install was seeded joins its rules once; removing it afterwards sticks
if e.saved.Seeded && !e.saved.SawInstanceRule {
has := false
for _, r := range e.saved.Rules {
if r.ID == "instance-down" {
has = true
}
}
if !has {
for _, d := range defaultRules {
if d.ID == "instance-down" {
e.saved.Rules = append(e.saved.Rules, d)
}
}
}
e.saved.SawInstanceRule = true
}
for i, r := range e.saved.Rules { // the first day's default watched "not running", which a container stopped on purpose also is
if r.ID == "container-down" && r.Sensor == "container.*.running" {
e.saved.Rules[i].Name, e.saved.Rules[i].Sensor, e.saved.Rules[i].Value = "Container down", "container.*.down", true
+15
View File
@@ -255,7 +255,22 @@ func (s *Server) routes() *http.ServeMux {
m.HandleFunc("PUT /api/virt/instances/{name}/config", s.auth(s.virtConfig))
m.HandleFunc("POST /api/virt/instances/{name}/snapshots", s.auth(s.virtSnapshotCreate))
m.HandleFunc("POST /api/virt/instances/{name}/snapshots/{snap}/{action}", s.auth(s.virtSnapshotAction))
m.HandleFunc("POST /api/virt/instances/from-iso", s.auth(s.virtFromISO))
m.HandleFunc("GET /api/virt/instances/{name}/vga", s.auth(s.virtVGA))
m.HandleFunc("POST /api/virt/instances/{name}/iso", s.auth(s.virtISOAttach))
m.HandleFunc("POST /api/virt/instances/{name}/iso/detach", s.auth(s.virtISODetach))
m.HandleFunc("POST /api/virt/instances/{name}/mounts", s.auth(s.virtMountAdd))
m.HandleFunc("POST /api/virt/instances/{name}/mounts/remove", s.auth(s.virtMountRemove))
m.HandleFunc("POST /api/virt/instances/{name}/{action}", s.auth(s.virtAction))
m.HandleFunc("POST /api/virt/isos/fetch", s.auth(s.virtISOFetch))
m.HandleFunc("POST /api/virt/isos/import", s.auth(s.virtISOImport))
m.HandleFunc("POST /api/virt/isos/delete", s.auth(s.virtISODelete))
m.HandleFunc("POST /api/virt/isos/rename", s.auth(s.virtISORename))
m.HandleFunc("GET /api/virt/exports", s.auth(s.virtExports))
m.HandleFunc("PUT /api/virt/exports", s.auth(s.virtExportsPut))
m.HandleFunc("POST /api/virt/exports/run", s.auth(s.virtExportsRun))
m.HandleFunc("POST /api/virt/exports/delete", s.auth(s.virtExportDelete))
m.HandleFunc("GET /api/virt/sshkeys", s.auth(s.virtSSHKeys))
m.HandleFunc("GET /api/alerts", s.auth(s.alertsGet))
m.HandleFunc("PUT /api/alerts", s.auth(s.alertsPut))
m.HandleFunc("POST /api/alerts/test", s.auth(s.alertsTest))
+39
View File
@@ -10,6 +10,7 @@ import (
"sync"
"time"
"hamlab/internal/incus"
"hamlab/internal/priv"
"hamlab/internal/sensors"
"hamlab/internal/storage"
@@ -54,6 +55,7 @@ func newStatusSensors(s *Server) *statusSensors {
p := &statusSensors{s: s, by: map[string][]sensors.Sensor{}, hist: map[string]*sensors.Series{}, acc: map[string]*bucket{}}
go p.loop("services", servicesEvery, p.services)
go p.loop("containers", containersEvery, p.containers)
go p.loop("instances", containersEvery, p.instances)
go p.loop("updates", updatesEvery, p.updates)
go p.loop("zfs", zfsEvery, p.zfs)
go p.loop("smart", smartEvery, p.smart)
@@ -320,6 +322,43 @@ type cpuMark struct {
t int64
}
// instances are Incus's containers and VMs. "Down" means it should be up and is not: an
// instance marked to start with the machine that is stopped, or one in Error — a stopped
// instance with no such mark was stopped on purpose, as with Docker containers.
func (p *statusSensors) instances(ctx context.Context, t int64) []sensors.Sensor {
if !incus.Installed() {
return nil
}
list, err := p.s.virt.InstancesFor(ctx, "sensors")
if err != nil {
return nil
}
var res []sensors.Sensor
var running, total float64
for _, in := range list {
total++
id := "instance." + sensors.Seg(in.Name)
l := map[string]string{"instance": in.Name, "type": in.Type, "image": in.Image}
up := in.Status == "Running"
if up {
running++
}
down := in.Status == "Error" || (!up && in.Config["boot.autostart"] == "true")
res = append(res,
sensors.Sensor{ID: id + ".running", Name: in.Name, Kind: "state", Value: up, T: t, Labels: l},
sensors.Sensor{ID: id + ".down", Name: in.Name + " down", Kind: "state", Value: down, T: t, Labels: l},
sensors.Sensor{ID: id + ".state", Name: in.Name + " state", Kind: "state", Value: strings.ToLower(in.Status), T: t, Labels: l})
if up {
res = append(res,
sensors.Sensor{ID: id + ".cpu", Name: in.Name + " CPU", Kind: "usage", Unit: "%", Value: float64(int(in.CPUPct*10+0.5)) / 10, T: t, Min: sensors.F(0), Labels: l},
sensors.Sensor{ID: id + ".mem", Name: in.Name + " memory", Kind: "bytes", Unit: "B", Value: float64(in.MemUsage), T: t, Labels: l})
}
}
return append(res,
sensors.Sensor{ID: "instances.total", Name: "Instances", Kind: "count", Value: total, T: t},
sensors.Sensor{ID: "instances.running", Name: "Running instances", Kind: "count", Value: running, T: t})
}
func (p *statusSensors) updates(ctx context.Context, t int64) []sensors.Sensor {
st := p.s.updates.Status(ctx)
if st.Manager == "" {
+605 -1
View File
@@ -13,12 +13,20 @@ import (
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/coder/websocket"
"hamlab/internal/incus"
"hamlab/internal/priv"
"hamlab/internal/sensors"
)
func readBody(r *http.Request, v any, max int64) error {
@@ -42,7 +50,14 @@ func (s *Server) virtOverview(w http.ResponseWriter, r *http.Request) {
out["pools"] = s.virt.Pools(ctx)
out["networks"] = s.virt.Networks(ctx)
}
out["library"] = map[string]any{"images": s.virt.Library(s.virt.ImagesDir()), "isos": s.virt.Library(s.virt.ISOsDir())}
isos := s.virt.Library(s.virt.ISOsDir())
if inst, ok := out["instances"].([]incus.Instance); ok {
users := s.isoUsers(inst)
for i := range isos {
isos[i].AttachedTo = users[isos[i].Name]
}
}
out["library"] = map[string]any{"images": s.virt.Library(s.virt.ImagesDir()), "isos": isos}
jsonOK(w, 200, out)
}
@@ -500,3 +515,592 @@ func (s *Server) virtSnapshotAction(w http.ResponseWriter, r *http.Request) {
log.Printf("virt: snapshot %s %s/%s (from %s)", action, name, snap, clientIP(r))
w.WriteHeader(204)
}
// ---- the graphical console ----
// virtVGA bridges the browser to the VM's SPICE display: the browser's websocket on one side,
// Incus's display websocket (dialled over its unix socket) on the other, frames copied both
// ways. spice-html5 in the page speaks SPICE; Ham Lab only carries it.
func (s *Server) virtVGA(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
if !incus.ValidName(name) {
jsonErr(w, 400, "bad name")
return
}
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled})
if err != nil {
return
}
conn.SetReadLimit(64 << 20)
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
display, control, err := s.virt.VGA(ctx, name)
if err != nil {
log.Printf("virt: vga %s refused: %v (from %s)", name, err, clientIP(r))
conn.Close(websocket.StatusInternalError, truncate(err.Error(), 120))
return
}
log.Printf("virt: vga console of %s opened (from %s)", name, clientIP(r))
defer display.Close(websocket.StatusNormalClosure, "")
if control != nil {
defer control.Close(websocket.StatusNormalClosure, "")
go func() { // the control channel carries nothing we send; keep it open and drain it
for {
if _, _, err := control.Read(ctx); err != nil {
return
}
}
}()
}
go func() {
defer cancel()
for {
_, data, err := display.Read(ctx)
if err != nil {
return
}
if err := conn.Write(ctx, websocket.MessageBinary, data); err != nil {
return
}
}
}()
for {
_, data, err := conn.Read(ctx)
if err != nil {
break
}
if err := display.Write(ctx, websocket.MessageBinary, data); err != nil {
break
}
}
cancel()
conn.Close(websocket.StatusNormalClosure, "")
log.Printf("virt: vga console of %s closed", name)
}
func truncate(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
// ---- ISOs ----
func (s *Server) isoPath(name string) (string, bool) {
if !incus.ValidISOName(name) {
return "", false
}
return filepath.Join(s.virt.ISOsDir(), name), true
}
// isoUsers says which instances have each ISO file attached, by its file name.
func (s *Server) isoUsers(list []incus.Instance) map[string][]string {
out := map[string][]string{}
dir := s.virt.ISOsDir() + "/"
for _, in := range list {
for _, d := range in.Devices {
if d["type"] == "disk" && strings.HasPrefix(d["source"], dir) {
n := strings.TrimPrefix(d["source"], dir)
out[n] = append(out[n], in.Name)
}
}
}
return out
}
// userShell runs a small script as the daemon's own account — file work in Ham Lab's folder
// needs no root — with positional parameters.
func userShell(script string, params ...string) *exec.Cmd {
return exec.Command("sh", append([]string{"-c", script, "hamlab"}, params...)...)
}
var urlRe = regexp.MustCompile(`^https?://[^\s"'<>]+$`)
func (s *Server) virtISOFetch(w http.ResponseWriter, r *http.Request) {
var body struct {
URL string `json:"url"`
SHA256 string `json:"sha256"`
Name string `json:"name"`
}
_ = readBody(r, &body, 8192)
u := strings.TrimSpace(body.URL)
if !urlRe.MatchString(u) {
jsonErr(w, 400, "url: http or https")
return
}
name := strings.TrimSpace(body.Name)
if name == "" {
if pu, err := url.Parse(u); err == nil {
name = path.Base(pu.Path)
}
}
dest, ok := s.isoPath(name)
if !ok {
jsonErr(w, 400, "name: a file name ending in .iso")
return
}
sum := strings.ToLower(strings.TrimSpace(body.SHA256))
if sum != "" && !regexp.MustCompile(`^[0-9a-f]{64}$`).MatchString(sum) {
jsonErr(w, 400, "sha256: 64 hex digits")
return
}
if _, err := os.Stat(dest); err == nil {
jsonErr(w, 409, name+" is already in the library")
return
}
if err := s.virt.EnsureDirs(); err != nil {
jsonErr(w, 500, err.Error())
return
}
script := `set -e; echo "fetching $1"; echo " to $2"; curl -fL --retry 3 -sS -o "$2.part" "$1"; if [ -n "$3" ]; then echo "$3 $2.part" | sha256sum -c - || { rm -f "$2.part"; exit 1; }; fi; mv "$2.part" "$2"; ls -l "$2" | awk '{print " " $5 " bytes"}'`
t, err := s.tasks.Start("virt:iso", "fetch "+name, userShell(script, u, dest, sum))
if err != nil {
jsonErr(w, 409, err.Error())
return
}
log.Printf("virt: iso fetch %s as task %s (from %s)", u, t.ID, clientIP(r))
jsonOK(w, 202, t.Snapshot(false))
}
func (s *Server) virtISOImport(w http.ResponseWriter, r *http.Request) {
var body struct {
Path string `json:"path"`
}
_ = readBody(r, &body, 8192)
p := filepath.Clean(body.Path)
st, err := os.Stat(p)
if !filepath.IsAbs(p) || err != nil || !st.Mode().IsRegular() {
jsonErr(w, 400, "path: a file on this machine")
return
}
dest, ok := s.isoPath(filepath.Base(p))
if !ok {
jsonErr(w, 400, "the file has to be a .iso or .img")
return
}
if _, err := os.Stat(dest); err == nil {
jsonErr(w, 409, filepath.Base(p)+" is already in the library")
return
}
if err := s.virt.EnsureDirs(); err != nil {
jsonErr(w, 500, err.Error())
return
}
script := `set -e; echo "copying $1"; echo " to $2"; cp --reflink=auto "$1" "$2.part" && mv "$2.part" "$2"; ls -l "$2" | awk '{print " " $5 " bytes"}'`
cmd := userShell(script, p, dest)
if f, err := os.Open(p); err != nil && priv.Available() { // readable only by root: copy as root and hand it over
argv := priv.Wrap("sh", "-c", script+`; chown "$3" "$2"`, "hamlab", p, dest, s.user)
cmd = exec.Command(argv[0], argv[1:]...)
} else if err == nil {
f.Close()
}
t, err := s.tasks.Start("virt:iso", "import "+filepath.Base(p), cmd)
if err != nil {
jsonErr(w, 409, err.Error())
return
}
log.Printf("virt: iso import %s as task %s (from %s)", p, t.ID, clientIP(r))
jsonOK(w, 202, t.Snapshot(false))
}
func (s *Server) virtISODelete(w http.ResponseWriter, r *http.Request) {
var body struct {
Name string `json:"name"`
}
_ = readBody(r, &body, 4096)
p, ok := s.isoPath(body.Name)
if !ok {
jsonErr(w, 400, "bad name")
return
}
if list, err := s.virt.Instances(r.Context()); err == nil {
if users := s.isoUsers(list)[body.Name]; len(users) > 0 {
jsonErr(w, 409, "attached to "+strings.Join(users, ", ")+" — detach it first")
return
}
}
if err := os.Remove(p); err != nil {
jsonErr(w, 404, "no such ISO")
return
}
log.Printf("virt: iso %s deleted (from %s)", body.Name, clientIP(r))
w.WriteHeader(204)
}
func (s *Server) virtISORename(w http.ResponseWriter, r *http.Request) {
var body struct {
Name string `json:"name"`
To string `json:"to"`
}
_ = readBody(r, &body, 4096)
from, ok1 := s.isoPath(body.Name)
to, ok2 := s.isoPath(body.To)
if !ok1 || !ok2 {
jsonErr(w, 400, "bad name")
return
}
if list, err := s.virt.Instances(r.Context()); err == nil {
if users := s.isoUsers(list)[body.Name]; len(users) > 0 {
jsonErr(w, 409, "attached to "+strings.Join(users, ", ")+" — detach it first")
return
}
}
if _, err := os.Stat(to); err == nil {
jsonErr(w, 409, body.To+" already exists")
return
}
if err := os.Rename(from, to); err != nil {
jsonErr(w, 404, "no such ISO")
return
}
w.WriteHeader(204)
}
func (s *Server) instanceByName(ctx context.Context, name string) (*incus.Instance, error) {
list, err := s.virt.Instances(ctx)
if err != nil {
return nil, err
}
for i := range list {
if list[i].Name == name {
return &list[i], nil
}
}
return nil, fmt.Errorf("no instance called %s", name)
}
// virtISOAttach puts an ISO in a VM's drive — live or stopped, Incus takes either — as a ROM
// device, first in the boot order when asked.
func (s *Server) virtISOAttach(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
var body struct {
ISO string `json:"iso"`
BootFirst bool `json:"boot_first"`
}
_ = readBody(r, &body, 4096)
p, ok := s.isoPath(body.ISO)
if !incus.ValidName(name) || !ok {
jsonErr(w, 400, "bad name")
return
}
if _, err := os.Stat(p); err != nil {
jsonErr(w, 404, "no such ISO in the library")
return
}
if !s.virtReady(w, r) {
return
}
in, err := s.instanceByName(r.Context(), name)
if err != nil {
jsonErr(w, 404, err.Error())
return
}
if in.Type != "virtual-machine" {
jsonErr(w, 409, "only a virtual machine takes an ISO")
return
}
dev := ""
for i := 0; i < 10; i++ {
if _, taken := in.Devices[fmt.Sprintf("iso%d", i)]; !taken {
dev = fmt.Sprintf("iso%d", i)
break
}
}
if dev == "" {
jsonErr(w, 409, "ten ISOs are already attached")
return
}
args := []string{"config", "device", "add", name, dev, "disk", "source=" + p}
if body.BootFirst {
args = append(args, "boot.priority=10")
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
if out, err := s.virt.Cmd(ctx, args...).CombinedOutput(); err != nil {
jsonErr(w, 409, strings.TrimPrefix(strings.TrimSpace(string(out)), "Error: "))
return
}
log.Printf("virt: %s attached to %s as %s (from %s)", body.ISO, name, dev, clientIP(r))
jsonOK(w, 200, map[string]string{"device": dev})
}
func (s *Server) virtISODetach(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
var body struct {
Device string `json:"device"`
}
_ = readBody(r, &body, 4096)
if !incus.ValidName(name) || !incus.ValidDevice(body.Device) {
jsonErr(w, 400, "bad name")
return
}
if !s.virtReady(w, r) {
return
}
in, err := s.instanceByName(r.Context(), name)
if err != nil {
jsonErr(w, 404, err.Error())
return
}
d, ok := in.Devices[body.Device]
if !ok || d["type"] != "disk" || !strings.HasPrefix(d["source"], s.virt.ISOsDir()+"/") {
jsonErr(w, 409, body.Device+" isn't an ISO from the library")
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
if out, err := s.virt.Cmd(ctx, "config", "device", "remove", name, body.Device).CombinedOutput(); err != nil {
jsonErr(w, 409, strings.TrimPrefix(strings.TrimSpace(string(out)), "Error: "))
return
}
log.Printf("virt: %s detached from %s (from %s)", body.Device, name, clientIP(r))
w.WriteHeader(204)
}
func (s *Server) virtFromISO(w http.ResponseWriter, r *http.Request) {
var sp incus.FromISOSpec
if err := readBody(r, &sp, 16<<10); err != nil {
jsonErr(w, 400, "bad request")
return
}
st := s.virt.Detect(r.Context())
if st.State != "ready" {
jsonErr(w, 409, "Incus isn't ready on this machine")
return
}
script, params, err := incus.FromISOScript(sp, st.KVM)
if err != nil {
jsonErr(w, 400, err.Error())
return
}
p, _ := s.isoPath(sp.ISO)
if _, err := os.Stat(p); err != nil {
jsonErr(w, 404, "no such ISO in the library")
return
}
params[1] = p
if _, err := s.instanceByName(r.Context(), sp.Name); err == nil {
jsonErr(w, 409, "there is already an instance called "+sp.Name)
return
}
t, err := s.tasks.Start("virt:create", "create VM "+sp.Name+" from "+sp.ISO, s.virt.ShellCmd(r.Context(), script, params...))
if err != nil {
jsonErr(w, 409, err.Error())
return
}
log.Printf("virt: VM %s from %s as task %s (from %s)", sp.Name, sp.ISO, t.ID, clientIP(r))
jsonOK(w, 202, t.Snapshot(false))
}
// ---- mounts: disk devices other than root ----
func (s *Server) virtMountAdd(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
var body struct {
Device string `json:"device"`
Source string `json:"source"`
Path string `json:"path"`
ReadOnly bool `json:"readonly"`
Shift bool `json:"shift"`
}
_ = readBody(r, &body, 8192)
src, dst := filepath.Clean(body.Source), filepath.Clean(body.Path)
dev := strings.TrimSpace(body.Device)
if dev == "" {
dev = "mnt-" + sensors.Seg(filepath.Base(src))
}
switch {
case !incus.ValidName(name):
jsonErr(w, 400, "bad name")
return
case !incus.ValidDevice(dev):
jsonErr(w, 400, "device: letters, digits, dashes")
return
case !filepath.IsAbs(src) || !filepath.IsAbs(dst) || dst == "/":
jsonErr(w, 400, "source and path: absolute paths; path not /")
return
}
if _, err := os.Stat(src); err != nil && os.IsNotExist(err) {
jsonErr(w, 404, src+" doesn't exist on this machine")
return
}
if !s.virtReady(w, r) {
return
}
in, err := s.instanceByName(r.Context(), name)
if err != nil {
jsonErr(w, 404, err.Error())
return
}
if _, taken := in.Devices[dev]; taken {
jsonErr(w, 409, "there is already a device called "+dev)
return
}
args := []string{"config", "device", "add", name, dev, "disk", "source=" + src, "path=" + dst}
if body.ReadOnly {
args = append(args, "readonly=true")
}
if body.Shift && in.Type == "container" {
args = append(args, "shift=true")
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
if out, err := s.virt.Cmd(ctx, args...).CombinedOutput(); err != nil {
jsonErr(w, 409, strings.TrimPrefix(strings.TrimSpace(string(out)), "Error: "))
return
}
log.Printf("virt: %s: mounted %s at %s as %s (from %s)", name, src, dst, dev, clientIP(r))
jsonOK(w, 200, map[string]string{"device": dev})
}
func (s *Server) virtMountRemove(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
var body struct {
Device string `json:"device"`
}
_ = readBody(r, &body, 4096)
if !incus.ValidName(name) || !incus.ValidDevice(body.Device) || body.Device == "root" {
jsonErr(w, 400, "bad name")
return
}
if !s.virtReady(w, r) {
return
}
in, err := s.instanceByName(r.Context(), name)
if err != nil {
jsonErr(w, 404, err.Error())
return
}
if d, ok := in.Devices[body.Device]; !ok || d["type"] != "disk" {
jsonErr(w, 409, body.Device+" isn't a disk device of "+name)
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
if out, err := s.virt.Cmd(ctx, "config", "device", "remove", name, body.Device).CombinedOutput(); err != nil {
jsonErr(w, 409, strings.TrimPrefix(strings.TrimSpace(string(out)), "Error: "))
return
}
log.Printf("virt: %s: device %s removed (from %s)", name, body.Device, clientIP(r))
w.WriteHeader(204)
}
// ---- exports ----
func (s *Server) virtExports(w http.ResponseWriter, r *http.Request) {
c := s.virt.ExportConfig()
out := map[string]any{"config": c, "cron": c.CronExpr(), "last": s.virt.LastExportRun(), "files": s.virt.ExportFiles(), "dir": s.virt.ExportsDir(), "cron_file": incus.CronFile}
if c.Enabled {
out["next"] = c.NextRun(time.Now())
}
jsonOK(w, 200, out)
}
func (s *Server) virtExportsPut(w http.ResponseWriter, r *http.Request) {
var c incus.ExportConfig
if err := readBody(r, &c, 16<<10); err != nil {
jsonErr(w, 400, "bad request")
return
}
if err := s.virt.SaveExportConfig(c); err != nil {
jsonErr(w, 400, err.Error())
return
}
exe, err := os.Executable()
if err == nil {
exe, _ = filepath.EvalSymlinks(exe)
}
if c.Enabled {
err = s.storage.WriteRootFile(r.Context(), incus.CronFile, c.CronText(s.user, exe, s.cfg.Path()))
} else {
err = s.storage.RemoveRootFile(r.Context(), incus.CronFile)
}
if err != nil {
jsonErr(w, 500, "schedule saved, but the cron file could not be written: "+err.Error())
return
}
log.Printf("virt: exports %v at %02d:%02d keep %d (from %s)", c.Enabled, c.Hour, c.Minute, c.Keep, clientIP(r))
w.WriteHeader(204)
}
func (s *Server) virtExportsRun(w http.ResponseWriter, r *http.Request) {
var body struct {
Instance string `json:"instance"`
}
_ = readBody(r, &body, 4096)
if body.Instance != "" && !incus.ValidName(body.Instance) {
jsonErr(w, 400, "bad name")
return
}
if !s.virtReady(w, r) {
return
}
exe, err := os.Executable()
if err != nil {
jsonErr(w, 500, err.Error())
return
}
args := []string{"-config", s.cfg.Path(), "virt-export"}
title := "export every instance"
if body.Instance != "" {
args = append(args, body.Instance)
title = "export " + body.Instance
}
t, err := s.tasks.Start("virt:export", title, exec.Command(exe, args...))
if err != nil {
jsonErr(w, 409, err.Error())
return
}
log.Printf("virt: %s as task %s (from %s)", title, t.ID, clientIP(r))
jsonOK(w, 202, t.Snapshot(false))
}
func (s *Server) virtExportDelete(w http.ResponseWriter, r *http.Request) {
var body struct {
Instance string `json:"instance"`
Name string `json:"name"`
}
_ = readBody(r, &body, 4096)
if !incus.ValidName(body.Instance) || body.Name != filepath.Base(body.Name) || !strings.HasSuffix(body.Name, ".tar.gz") {
jsonErr(w, 400, "bad name")
return
}
if err := os.Remove(filepath.Join(s.virt.ExportsDir(), body.Instance, body.Name)); err != nil {
jsonErr(w, 404, "no such export")
return
}
log.Printf("virt: export %s/%s deleted (from %s)", body.Instance, body.Name, clientIP(r))
w.WriteHeader(204)
}
// virtSSHKeys is the daemon account's public keys, for a cloud-init that lets him straight in.
func (s *Server) virtSSHKeys(w http.ResponseWriter, _ *http.Request) {
home, _ := os.UserHomeDir()
seen := map[string]bool{}
keys := []string{}
add := func(line string) {
f := strings.Fields(line)
if len(f) < 2 || !strings.HasPrefix(f[0], "ssh-") && !strings.HasPrefix(f[0], "ecdsa-") && !strings.HasPrefix(f[0], "sk-") {
return
}
k := f[0] + " " + f[1]
if seen[k] {
return
}
seen[k] = true
keys = append(keys, strings.TrimSpace(line))
}
if b, err := os.ReadFile(filepath.Join(home, ".ssh", "authorized_keys")); err == nil {
for _, l := range strings.Split(string(b), "\n") {
add(l)
}
}
pubs, _ := filepath.Glob(filepath.Join(home, ".ssh", "*.pub"))
for _, p := range pubs {
if b, err := os.ReadFile(p); err == nil {
add(string(b))
}
}
jsonOK(w, 200, map[string]any{"keys": keys, "user": s.user})
}
+231
View File
@@ -0,0 +1,231 @@
package incus
// Nightly exports: every instance as a tarball in virt/exports/<name>/, kept to a count, as a
// cron line like the ZFS schedules — `hamlab virt-export` in /etc/cron.d/hamlab-virt — so the
// backup runs whether or not the console is up. The settings and the last run's record are
// files beside the data, not state.json, because the cron job is a separate process.
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
)
const CronFile = "/etc/cron.d/hamlab-virt"
type ExportConfig struct {
Enabled bool `json:"enabled"`
Hour int `json:"hour"`
Minute int `json:"minute"`
Keep int `json:"keep"` // newest exports kept per instance
InstanceOnly bool `json:"instance_only"` // leave the snapshots out of the tarball
Instances []string `json:"instances,omitempty"` // empty: every instance
Updated time.Time `json:"updated,omitempty"`
}
func DefaultExportConfig() ExportConfig {
return ExportConfig{Hour: 2, Minute: 15, Keep: 3, InstanceOnly: true}
}
func (c ExportConfig) Validate() error {
if c.Hour < 0 || c.Hour > 23 || c.Minute < 0 || c.Minute > 59 {
return errors.New("time: hour 0–23, minute 0–59")
}
if c.Keep < 1 || c.Keep > 100 {
return errors.New("keep: between 1 and 100")
}
for _, n := range c.Instances {
if !ValidName(n) {
return errors.New("instance: " + n)
}
}
return nil
}
func (c ExportConfig) CronExpr() string { return fmt.Sprintf("%d %d * * *", c.Minute, c.Hour) }
// NextRun is the next time the line fires, for the page.
func (c ExportConfig) NextRun(now time.Time) time.Time {
n := time.Date(now.Year(), now.Month(), now.Day(), c.Hour, c.Minute, 0, 0, now.Location())
if !n.After(now) {
n = n.Add(24 * time.Hour)
}
return n
}
// CronText is the whole file; rewritten on every change, never edited.
func (c ExportConfig) CronText(user, exe, config string) string {
var b strings.Builder
b.WriteString("# Ham Lab instance exports — written by the Virtualization tab, rewritten whole on every change.\n")
b.WriteString("# Edit it there, not here.\n")
b.WriteString("SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n\n")
fmt.Fprintf(&b, "# every instance to virt/exports, keep %d each\n", c.Keep)
fmt.Fprintf(&b, "%s %s %s -config %s virt-export\n", c.CronExpr(), user, exe, config)
return b.String()
}
func (m *Manager) exportConfigPath() string { return filepath.Join(m.dir, "exports.json") }
func (m *Manager) exportRunPath() string { return filepath.Join(m.dir, "export-runs.json") }
func (m *Manager) ExportConfig() ExportConfig {
c := DefaultExportConfig()
if b, err := os.ReadFile(m.exportConfigPath()); err == nil {
_ = json.Unmarshal(b, &c)
}
return c
}
func (m *Manager) SaveExportConfig(c ExportConfig) error {
if err := c.Validate(); err != nil {
return err
}
if err := m.EnsureDirs(); err != nil {
return err
}
c.Updated = time.Now()
b, _ := json.MarshalIndent(c, "", " ")
return os.WriteFile(m.exportConfigPath(), b, 0o644)
}
type ExportRun struct {
At time.Time `json:"at"`
Exported []string `json:"exported"`
Pruned []string `json:"pruned"`
Errors []string `json:"errors,omitempty"`
Seconds float64 `json:"seconds"`
}
func (m *Manager) LastExportRun() *ExportRun {
b, err := os.ReadFile(m.exportRunPath())
if err != nil {
return nil
}
var r ExportRun
if json.Unmarshal(b, &r) != nil {
return nil
}
return &r
}
// ExportFile is one tarball in the exports tree.
type ExportFile struct {
Instance string `json:"instance"`
Name string `json:"name"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
func (m *Manager) ExportFiles() []ExportFile {
out := []ExportFile{}
dirs, _ := os.ReadDir(m.ExportsDir())
for _, d := range dirs {
if !d.IsDir() {
continue
}
files, _ := os.ReadDir(filepath.Join(m.ExportsDir(), d.Name()))
for _, f := range files {
if f.IsDir() || strings.HasSuffix(f.Name(), ".part") {
continue
}
if info, err := f.Info(); err == nil {
out = append(out, ExportFile{Instance: d.Name(), Name: f.Name(), Size: info.Size(), Modified: info.ModTime()})
}
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Instance != out[j].Instance {
return out[i].Instance < out[j].Instance
}
return out[i].Modified.After(out[j].Modified)
})
return out
}
// RunExports exports the named instances (or every one when names is empty) and prunes each
// instance's folder to the configured count. Output goes to w line by line for a task to show.
func (m *Manager) RunExports(ctx context.Context, names []string, w func(string)) ExportRun {
start := time.Now()
c := m.ExportConfig()
run := ExportRun{At: start, Exported: []string{}, Pruned: []string{}}
if err := m.EnsureDirs(); err != nil {
run.Errors = append(run.Errors, err.Error())
return run
}
all, err := m.Instances(ctx)
if err != nil {
run.Errors = append(run.Errors, "listing instances: "+err.Error())
return run
}
want := map[string]bool{}
for _, n := range names {
want[n] = true
}
if len(names) == 0 && len(c.Instances) > 0 {
for _, n := range c.Instances {
want[n] = true
}
}
for _, in := range all {
if len(want) > 0 && !want[in.Name] {
continue
}
dir := filepath.Join(m.ExportsDir(), in.Name)
if err := os.MkdirAll(dir, 0o755); err != nil {
run.Errors = append(run.Errors, in.Name+": "+err.Error())
continue
}
stamp := start.Format("2006-01-02_15.04")
final := filepath.Join(dir, fmt.Sprintf("%s-%s.tar.gz", in.Name, stamp))
part := final + ".part"
args := []string{"export", in.Name, part}
if c.InstanceOnly {
args = append(args, "--instance-only")
}
w(fmt.Sprintf("exporting %s …", in.Name))
cctx, cancel := context.WithTimeout(ctx, 2*time.Hour)
out, err := exec.CommandContext(cctx, "incus", args...).CombinedOutput()
cancel()
if err != nil {
_ = os.Remove(part)
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
run.Errors = append(run.Errors, in.Name+": "+msg)
w(" failed: " + msg)
continue
}
if err := os.Rename(part, final); err != nil {
run.Errors = append(run.Errors, in.Name+": "+err.Error())
continue
}
if st, err := os.Stat(final); err == nil {
w(fmt.Sprintf(" %s (%.1f MiB)", filepath.Base(final), float64(st.Size())/(1<<20)))
}
run.Exported = append(run.Exported, filepath.Base(final))
// prune: newest first, keep c.Keep
var files []ExportFile
for _, f := range m.ExportFiles() {
if f.Instance == in.Name {
files = append(files, f)
}
}
for i := c.Keep; i < len(files); i++ {
if err := os.Remove(filepath.Join(dir, files[i].Name)); err == nil {
run.Pruned = append(run.Pruned, files[i].Name)
w(" pruned " + files[i].Name)
}
}
}
run.Seconds = time.Since(start).Seconds()
b, _ := json.MarshalIndent(run, "", " ")
_ = os.WriteFile(m.exportRunPath(), b, 0o644)
return run
}
+80 -6
View File
@@ -57,7 +57,7 @@ type Manager struct {
version string
mu sync.Mutex
cpuPrev map[string]cpuMark
cpuPrev map[string]map[string]cpuMark // caller → instance → last reading, so two readers do not spoil each other's deltas
remote struct {
at time.Time
list []Image
@@ -75,7 +75,7 @@ type cpuMark struct {
}
func New(dataDir, user, version string) *Manager {
return &Manager{dir: filepath.Join(dataDir, "virt"), user: user, version: version, cpuPrev: map[string]cpuMark{}}
return &Manager{dir: filepath.Join(dataDir, "virt"), user: user, version: version, cpuPrev: map[string]map[string]cpuMark{}}
}
func (m *Manager) Dir() string { return m.dir }
@@ -512,6 +512,12 @@ func secretKey(k string) bool {
}
func (m *Manager) Instances(ctx context.Context) ([]Instance, error) {
return m.InstancesFor(ctx, "api")
}
// InstancesFor is Instances with its own CPU history per caller: the page and the sensors
// both read, at different rates, and a shared "previous reading" would give each the other's delta.
func (m *Manager) InstancesFor(ctx context.Context, caller string) ([]Instance, error) {
c, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
out, err := m.run(c, "list", "--format", "json")
@@ -525,6 +531,11 @@ func (m *Manager) Instances(ctx context.Context) ([]Instance, error) {
now := time.Now()
m.mu.Lock()
defer m.mu.Unlock()
prevs := m.cpuPrev[caller]
if prevs == nil {
prevs = map[string]cpuMark{}
m.cpuPrev[caller] = prevs
}
seen := map[string]bool{}
var list []Instance
for _, r := range raw {
@@ -577,18 +588,18 @@ func (m *Manager) Instances(ctx context.Context) ([]Instance, error) {
}
}
if r.Status == "Running" {
if prev, ok := m.cpuPrev[r.Name]; ok && now.After(prev.at) && r.State.CPU.Usage >= prev.ns {
if prev, ok := prevs[r.Name]; ok && now.After(prev.at) && r.State.CPU.Usage >= prev.ns {
in.CPUPct = float64(r.State.CPU.Usage-prev.ns) / float64(now.Sub(prev.at).Nanoseconds()) * 100
}
m.cpuPrev[r.Name] = cpuMark{ns: r.State.CPU.Usage, at: now}
prevs[r.Name] = cpuMark{ns: r.State.CPU.Usage, at: now}
seen[r.Name] = true
}
}
list = append(list, in)
}
for n := range m.cpuPrev {
for n := range prevs {
if !seen[n] {
delete(m.cpuPrev, n)
delete(prevs, n)
}
}
if list == nil {
@@ -800,8 +811,13 @@ type LibraryFile struct {
Name string `json:"name"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
AttachedTo []string `json:"attached_to,omitempty"`
}
// Installed reports whether the incus binary is on this machine at all; the cheap gate the
// sensors use before asking it anything.
func Installed() bool { return have("incus") }
func (m *Manager) Library(dir string) []LibraryFile {
ents, err := os.ReadDir(dir)
if err != nil {
@@ -829,9 +845,13 @@ var (
snapRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
cronRe = regexp.MustCompile(`^(@(hourly|daily|weekly|monthly|yearly|annually|startup|never)|[0-9*/,-]+( [0-9*/,-]+){4})$`)
expRe = regexp.MustCompile(`^[0-9]+[mHdwMy]( [0-9]+[mHdwMy])*$|^$`)
deviceRe = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{0,30}$`)
isoRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._ +-]{0,200}\.(?i:iso|img)$`)
)
func ValidName(s string) bool { return nameRe.MatchString(s) }
func ValidDevice(s string) bool { return deviceRe.MatchString(s) }
func ValidISOName(s string) bool { return isoRe.MatchString(s) && s == filepath.Base(s) }
func ValidImage(s string) bool { return imageRe.MatchString(s) }
func ValidSize(s string) bool { return s == "" || sizeRe.MatchString(s) }
func ValidCPU(s string) bool { return s == "" || cpuRe.MatchString(s) }
@@ -1075,3 +1095,57 @@ func (m *Manager) InstallScript(st Status, o InstallOpts) (string, Layout, error
w("if systemctl is-active --quiet %s; then systemd-run --quiet --on-active=3 --unit=hamlab-virt-restart systemctl restart %s; fi", HamlabUnit, HamlabUnit)
return b.String(), lay, nil
}
// FromISOSpec is the New VM from ISO form: an empty VM with the ISO as its first boot device.
type FromISOSpec struct {
Name string `json:"name"`
ISO string `json:"iso"` // a file name in virt/isos
CPU string `json:"cpu"`
Memory string `json:"memory"`
Disk string `json:"disk"`
Network string `json:"network"`
SecureBoot bool `json:"secureboot"`
Start bool `json:"start"`
}
// FromISOScript makes the VM in one shell script run through ShellCmd; the parameters carry
// the values so nothing is spliced into the text.
func FromISOScript(sp FromISOSpec, kvm bool) (script string, params []string, err error) {
switch {
case !kvm:
return "", nil, errors.New("this machine has no KVM")
case !ValidName(sp.Name):
return "", nil, errors.New("name: letters, digits and dashes, starting with a letter, up to 63")
case !ValidISOName(sp.ISO):
return "", nil, errors.New("iso: pick one from the library")
case !ValidCPU(sp.CPU) || !ValidSize(sp.Memory) || !ValidSize(sp.Disk) || !ValidNetwork(sp.Network):
return "", nil, errors.New("cpu, memory, disk: a count and two sizes, like 2, 2GiB, 20GiB")
}
cpu, mem, disk := sp.CPU, sp.Memory, sp.Disk
if cpu == "" {
cpu = "2"
}
if mem == "" {
mem = "2GiB"
}
if disk == "" {
disk = "20GiB"
}
sb := "true"
if !sp.SecureBoot {
sb = "false"
}
start := "0"
if sp.Start {
start = "1"
}
// $1 name $2 iso path $3 cpu $4 memory $5 disk $6 network $7 secureboot $8 start
script = `set -e
NET=""; [ -n "$6" ] && NET="-n $6"
incus init --empty --vm "$1" -c limits.cpu="$3" -c limits.memory="$4" -c security.secureboot="$7" -d root,size="$5" $NET
incus config device add "$1" iso0 disk source="$2" boot.priority=10
echo "made $1 with $2 as its first boot device"
[ "$8" = 1 ] && incus start "$1" && echo "started; open the VGA console to run the installer"
exit 0`
return script, []string{sp.Name, sp.ISO, cpu, mem, disk, sp.Network, sb, start}, nil
}
+116
View File
@@ -0,0 +1,116 @@
package incus
// The graphical console. Incus exposes a VM's SPICE display as a websocket: POST to the
// instance's console endpoint with type vga and it answers an operation with two secrets,
// one for the display stream and one for a control channel. Ham Lab dials both over Incus's
// unix socket and hands the display stream to the browser, where spice-html5 draws it.
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/coder/websocket"
)
// SocketPath is where Incus's API listens; the daemon's account reaches it by being in
// incus-admin, which Install arranges.
func SocketPath() string {
if p := os.Getenv("INCUS_SOCKET"); p != "" {
return p
}
for _, p := range []string{"/var/lib/incus/unix.socket", "/run/incus/unix.socket"} {
if _, err := os.Stat(p); err == nil {
return p
}
}
return "/var/lib/incus/unix.socket"
}
func (m *Manager) apiClient() *http.Client {
sock := SocketPath()
return &http.Client{Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "unix", sock)
},
ForceAttemptHTTP2: false,
}}
}
// VGA opens the display and control websockets for a running VM. The caller closes both.
func (m *Manager) VGA(ctx context.Context, name string) (display, control *websocket.Conn, err error) {
if !ValidName(name) {
return nil, nil, errors.New("bad name")
}
client := m.apiClient()
body, _ := json.Marshal(map[string]any{"type": "vga", "width": 0, "height": 0})
c, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(c, "POST", "http://incus/1.0/instances/"+name+"/console", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
if os.IsPermission(errors.Unwrap(err)) || isPermission(err) {
return nil, nil, errors.New("Ham Lab's account can't reach Incus's socket; Finish setup on the Virtualization tab puts it in incus-admin")
}
return nil, nil, err
}
defer resp.Body.Close()
var op struct {
Error string `json:"error"`
Operation string `json:"operation"`
Metadata struct {
ID string `json:"id"`
Metadata struct {
FDs map[string]string `json:"fds"`
} `json:"metadata"`
} `json:"metadata"`
}
if err := json.NewDecoder(resp.Body).Decode(&op); err != nil {
return nil, nil, errors.New("unreadable answer from incus")
}
if op.Error != "" {
return nil, nil, errors.New(op.Error)
}
data, control0 := op.Metadata.Metadata.FDs["0"], op.Metadata.Metadata.FDs["control"]
if op.Metadata.ID == "" || data == "" {
return nil, nil, errors.New("incus gave no console; is the VM running?")
}
dial := func(secret string) (*websocket.Conn, error) {
u := fmt.Sprintf("ws://incus/1.0/operations/%s/websocket?secret=%s", op.Metadata.ID, secret)
ws, _, err := websocket.Dial(ctx, u, &websocket.DialOptions{HTTPClient: client, CompressionMode: websocket.CompressionDisabled})
return ws, err
}
if control0 != "" {
if control, err = dial(control0); err != nil {
return nil, nil, err
}
}
if display, err = dial(data); err != nil {
if control != nil {
control.Close(websocket.StatusInternalError, "")
}
return nil, nil, err
}
display.SetReadLimit(64 << 20) // a SPICE frame can carry a whole screen
return display, control, nil
}
func isPermission(err error) bool {
var pe *os.PathError
if errors.As(err, &pe) {
return os.IsPermission(pe)
}
var oe *net.OpError
if errors.As(err, &oe) {
return os.IsPermission(oe.Err) || isPermission(oe.Err)
}
return false
}
+84
View File
@@ -0,0 +1,84 @@
// The graphical console of a VM: spice-html5 (vendored, loaded on demand) drawing the SPICE
// stream that Ham Lab bridges from Incus into a canvas. Used for installers from an ISO, and
// anything else with a screen rather than a serial line.
import { useEffect, useRef, useState } from 'react'
import { wsURLPath } from './api'
import { Btn, useEscape } from './ui'
import './vendor/spice-html5/spice.css'
type Spice = typeof import('./vendor/spice-html5/src/main.js')
export default function VgaConsole({ name, onClose }: { name: string; onClose: () => void }) {
const [state, setState] = useState<'loading' | 'connecting' | 'connected' | 'error'>('loading')
const [err, setErr] = useState('')
const [fit, setFit] = useState(true)
const [size, setSize] = useState('')
const conn = useRef<InstanceType<Spice['SpiceMainConn']> | null>(null)
const mod = useRef<Spice | null>(null)
const area = useRef<HTMLDivElement>(null)
const screen = useRef<HTMLDivElement>(null)
useEscape(onClose)
useEffect(() => {
let dead = false
import('./vendor/spice-html5/src/main.js').then((m) => {
if (dead) return
mod.current = m
setState('connecting')
try {
conn.current = new m.SpiceMainConn({
uri: wsURLPath(`/api/virt/instances/${encodeURIComponent(name)}/vga`),
screen_id: 'spice-screen', message_id: 'spice-message',
onerror: (e) => { setState('error'); setErr(e instanceof Error ? e.message : (e as Event & { reason?: string })?.reason || 'the console closed') },
onsuccess: () => setState('connected'),
onagent: () => { try { m.handle_resize() } catch { /* no agent in the guest yet */ } },
})
} catch (e) { setState('error'); setErr(String(e)) }
}).catch((e) => { setState('error'); setErr('could not load the SPICE viewer: ' + String(e)) })
return () => { dead = true; try { conn.current?.stop() } catch { /* already gone */ } conn.current = null }
}, [name])
// The guest draws at its own resolution; scale the canvas to the pane unless asked not to.
useEffect(() => {
const a = area.current, s = screen.current
if (!a || !s) return
const apply = () => {
const c = s.querySelector('canvas')
if (!c) return
setSize(`${c.width}×${c.height}`)
c.tabIndex = 1
if (!fit) { s.style.transform = ''; s.style.width = ''; s.style.height = ''; return }
const k = Math.min(1, (a.clientWidth - 8) / c.width, (a.clientHeight - 8) / c.height)
s.style.transformOrigin = 'top left'
s.style.transform = `scale(${k})`
s.style.width = `${c.width}px`; s.style.height = `${c.height}px`
}
apply()
const ro = new ResizeObserver(apply); ro.observe(a)
const mo = new MutationObserver(apply); mo.observe(s, { childList: true, attributes: true, subtree: true, attributeFilter: ['width', 'height'] })
return () => { ro.disconnect(); mo.disconnect() }
}, [fit, state])
const cad = () => { if (conn.current && mod.current) mod.current.sendCtrlAltDel(conn.current) }
const focus = () => screen.current?.querySelector('canvas')?.focus()
return (
<div className="modal-back vga-back" onClick={onClose}>
<div className="vga" onClick={(e) => e.stopPropagation()}>
<div className="logs-bar vga-bar">
<span className={'dot ' + (state === 'connected' ? 'ok' : state === 'error' ? 'bad' : 'warn')} />
<span className="dname">{name}</span>
<span className="muted small">{state === 'connected' ? `VGA · ${size || 'waiting for the first frame'}` : state === 'error' ? err : state === 'loading' ? 'loading the viewer…' : 'connecting…'}</span>
<span className="spacer" />
<Btn className="btn" disabled={state !== 'connected'} onClick={cad} title="send Ctrl+Alt+Del to the guest">Ctrl+Alt+Del</Btn>
<button className={'btn' + (fit ? ' on' : '')} onClick={() => setFit(!fit)} title="scale the screen to this window, or show it pixel for pixel">Fit</button>
<button className="btn" onClick={onClose}>Close</button>
</div>
<div className="vga-area" ref={area} onClick={focus}>
<div id="spice-area"><div id="spice-screen" ref={screen} /></div>
<div id="spice-message" className="spice-message vga-msg" />
</div>
<div className="muted small vga-hint">Click the screen to type into it. Keys go to the guest while it has focus; Escape with focus elsewhere closes this.</div>
</div>
</div>
)
}
+183 -7
View File
@@ -3,7 +3,8 @@
// selected machine can do, never by a rule about what should run where. Everything the
// tab makes lives under Ham Lab's own folder on that machine.
import { FormEvent, Fragment, useCallback, useEffect, useMemo, useState } from 'react'
import { api, LibraryFile, TaskInfo, VirtImage, VirtInstance, VirtOverview, VirtStatus } from './api'
import { api, ExportsView, LibraryFile, TaskInfo, VirtImage, VirtInstance, VirtOverview, VirtStatus } from './api'
import VgaConsole from './VgaConsole'
import TaskOutput from './TaskOutput'
import { useHashSel } from './hashsel'
import { useRefreshMs } from './prefs'
@@ -24,6 +25,7 @@ export default function Virtualization() {
const [tab, setTab] = useState<Tab>('instances')
const [sel, setSel] = useHashSel('virt')
const [making, setMaking] = useState<null | { image?: string; vm?: boolean }>(null)
const [fromIso, setFromIso] = useState<string | null>(null)
const [task, setTask] = useState<{ id: string; title: string } | null>(null)
const [filter, setFilter] = useState('')
const rate = useRefreshMs()
@@ -77,10 +79,11 @@ export default function Virtualization() {
</div>
)}
{tab === 'images' && <Images st={st} images={images} instances={instances} onTask={startTask} onNew={(image, vm) => { setTab('instances'); setMaking({ image, vm }) }} onChanged={load} />}
{tab === 'library' && <Library lib={ov.library} dir={st.dir} />}
{tab === 'library' && <Library st={st} ov={ov} onTask={startTask} onChanged={load} onNewVM={(iso) => setFromIso(iso)} />}
</div>
{tab === 'instances' && (cur ? <Detail i={cur} st={st} onBack={() => setSel('')} onChanged={load} onTask={startTask} /> : <Summary ov={ov} />)}
{making && <NewInstance st={st} ov={ov} preset={making} onClose={() => setMaking(null)} onStarted={(t) => { setMaking(null); startTask(t) }} />}
{fromIso !== null && <NewVMFromISO st={st} ov={ov} iso={fromIso} onClose={() => setFromIso(null)} onStarted={(t) => { setFromIso(null); startTask(t); setTab('instances') }} />}
</div>
)
}
@@ -209,8 +212,10 @@ function Summary({ ov }: { ov: VirtOverview }) {
// ---- one instance ----
function Detail({ i, st, onBack, onChanged, onTask }: { i: VirtInstance; st: VirtStatus; onBack: () => void; onChanged: () => void; onTask: (t: TaskInfo) => void }) {
const [tab, setTab] = useState<'overview' | 'snapshots' | 'config'>('overview')
const [tab, setTab] = useState<'overview' | 'snapshots' | 'mounts' | 'config'>('overview')
const [vga, setVga] = useState(false)
const running = i.status === 'Running'
const isVM = i.type === 'virtual-machine'
const stopped = i.status === 'Stopped'
const act = (a: 'start' | 'stop' | 'restart' | 'kill') => async () => { try { await api.virtAction(i.name, a); toast(`${i.name}: ${a} ok`); onChanged() } catch (e) { toast(`${i.name}: ${errMsg(e)}`, 'err') } }
const term = (k: 'console' | 'exec') => async () => {
@@ -251,10 +256,12 @@ function Detail({ i, st, onBack, onChanged, onTask }: { i: VirtInstance; st: Vir
{!running && <Btn className="btn on" onClick={act('start')}>Start</Btn>}
{running && <Btn className="btn" onClick={term('exec')}>Shell</Btn>}
<Btn className="btn" onClick={term('console')} title="the serial console: boot output, and a login prompt where the guest has one on it">Console</Btn>
{isVM && running && <Btn className="btn" onClick={() => setVga(true)} title="the VM's screen, keyboard and mouse — what an installer needs">VGA</Btn>}
{running && <Btn className="btn" confirm={`Restart ${i.name}?`} onClick={act('restart')}>Restart</Btn>}
{running && <Btn className="btn danger" confirm={`Stop ${i.name}? It is asked to shut down cleanly.`} onClick={act('stop')}>Stop</Btn>}
{running && <Btn className="btn danger" confirm={`Force stop ${i.name}? Like pulling the plug — anything unsaved inside is lost.`} onClick={act('kill')}>Force stop</Btn>}
<Btn className="btn" onClick={snap}>Snapshot</Btn>
<Btn className="btn" onClick={async () => { try { onTask(await api.virtExportsRun(i.name)) } catch (e) { toast(errMsg(e), 'err') } }} title="a tarball of it in the library's exports folder">Export</Btn>
{stopped && <Btn className="btn" onClick={rename}>Rename</Btn>}
{stopped && <Btn className="btn" onClick={publish} title="make an image of it, to launch more like it">Publish</Btn>}
<Btn className="btn danger" onClick={del}>Delete…</Btn>
@@ -262,8 +269,11 @@ function Detail({ i, st, onBack, onChanged, onTask }: { i: VirtInstance; st: Vir
<div className="tabs">
<button className={tab === 'overview' ? 'on' : ''} onClick={() => setTab('overview')}>Limits</button>
<button className={tab === 'snapshots' ? 'on' : ''} onClick={() => setTab('snapshots')}>Snapshots · {i.snapshots.length}</button>
<button className={tab === 'mounts' ? 'on' : ''} onClick={() => setTab('mounts')}>Disks · {Object.values(i.devices).filter((d) => d.type === 'disk').length}</button>
<button className={tab === 'config' ? 'on' : ''} onClick={() => setTab('config')}>Config</button>
</div>
{tab === 'mounts' && <Mounts i={i} st={st} onChanged={onChanged} />}
{vga && <VgaConsole name={i.name} onClose={() => setVga(false)} />}
{tab === 'overview' && <Limits i={i} st={st} onChanged={onChanged} />}
{tab === 'snapshots' && <Snapshots i={i} onChanged={onChanged} />}
{tab === 'config' && (
@@ -415,6 +425,7 @@ function NewInstance({ st, ov, preset, onClose, onStarted }: { st: VirtStatus; o
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<input type="checkbox" checked={showCloud} onChange={(e) => setShowCloud(e.target.checked)} style={{ width: 'auto' }} />cloud-init user-data (an SSH key, packages, a first command — needs a /cloud image)
</label>
{showCloud && <div className="svc-actions"><Btn className="btn" onClick={async () => { try { const k = await api.virtSSHKeys(); if (!k.keys.length) { toast('no public keys found for ' + k.user, 'info'); return } setCloud(`#cloud-config\nusers:\n - name: ${k.user}\n groups: [sudo]\n shell: /bin/bash\n sudo: ALL=(ALL) NOPASSWD:ALL\n ssh_authorized_keys:\n${k.keys.map((x) => ' - ' + x).join('\n')}\npackage_update: true\npackages: [curl, vim]\n`) } catch (e) { toast(errMsg(e), 'err') } }} title="a cloud-config that makes your account inside, with the public keys this machine's Ham Lab account holds">Use my SSH keys</Btn></div>}
{showCloud && <textarea className="mono" rows={6} value={cloud} onChange={(e) => setCloud(e.target.value)} placeholder={'#cloud-config\nusers:\n - name: core\n ssh_authorized_keys:\n - ssh-ed25519 AAAA…\n sudo: ALL=(ALL) NOPASSWD:ALL\npackages: [curl]'} spellCheck={false} />}
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<input type="checkbox" checked={start} onChange={(e) => setStart(e.target.checked)} style={{ width: 'auto' }} />Start it once made
@@ -493,17 +504,182 @@ function Images({ st, images, instances, onTask, onNew, onChanged }: { st: VirtS
)
}
function Library({ lib, dir }: { lib: { images: LibraryFile[]; isos: LibraryFile[] }; dir: string }) {
function Mounts({ i, st, onChanged }: { i: VirtInstance; st: VirtStatus; onChanged: () => void }) {
const [src, setSrc] = useState('')
const [dst, setDst] = useState('')
const [dev, setDev] = useState('')
const [ro, setRo] = useState(false)
const [shift, setShift] = useState(true)
const isos = st.dir + '/isos/'
const disks = Object.entries(i.devices).filter(([, d]) => d.type === 'disk').sort()
const add = async (e: FormEvent) => {
e.preventDefault()
try { const r = await api.virtMountAdd(i.name, { device: dev.trim(), source: src.trim(), path: dst.trim(), readonly: ro, shift }); toast(`mounted as ${r.device}`); setSrc(''); setDst(''); setDev(''); onChanged() } catch (er) { toast(errMsg(er), 'err') }
}
const remove = async (d: string, iso: boolean) => {
if (!(await askYes(iso ? `Eject ${d} from ${i.name}?` : `Remove the mount ${d} from ${i.name}? Nothing on the host is touched.`, iso ? 'Eject' : 'Remove'))) return
try { if (iso) await api.virtISODetach(i.name, d); else await api.virtMountRemove(i.name, d); toast('done'); onChanged() } catch (e) { toast(errMsg(e), 'err') }
}
return (
<>
<table className="virt-table"><thead><tr><th>Device</th><th>Source</th><th>Inside</th><th /></tr></thead>
<tbody>{disks.map(([name, d]) => { const iso = (d.source ?? '').startsWith(isos); return (
<tr key={name}><td className="mono">{name}{iso && <span className="badge">ISO</span>}{d['boot.priority'] && <span className="badge">boots first</span>}</td>
<td className="mono small">{name === 'root' ? `pool ${d.pool}${d.size ? ` · ${d.size}` : ''}` : iso ? (d.source ?? '').slice(isos.length) : d.source}</td>
<td className="mono small">{iso ? 'CD-ROM' : d.path}{d.readonly === 'true' ? ' · read only' : ''}{d.shift === 'true' ? ' · shifted' : ''}</td>
<td className="num">{name !== 'root' && <Btn className="btn danger" onClick={() => remove(name, iso)}>{iso ? 'Eject' : 'Remove'}</Btn>}</td></tr>) })}</tbody></table>
<section className="card">
<div className="sub-head"><span className="dname">Mount a folder from this machine</span></div>
<form onSubmit={add}>
<div className="virt-form-row">
<label className="muted">Host path<input className="mono" value={src} onChange={(e) => setSrc(e.target.value)} placeholder="/tank/media" spellCheck={false} required /></label>
<label className="muted">Path inside<input className="mono" value={dst} onChange={(e) => setDst(e.target.value)} placeholder="/mnt/media" spellCheck={false} required /></label>
<label className="muted">Device name — optional<input className="mono" value={dev} onChange={(e) => setDev(e.target.value)} placeholder="mnt-media" spellCheck={false} /></label>
</div>
<div className="virt-form-row" style={{ alignItems: 'center' }}>
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}><input type="checkbox" checked={ro} onChange={(e) => setRo(e.target.checked)} style={{ width: 'auto' }} />read only</label>
{i.type === 'container' && <label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }} title="map the host's file ownership into the container's user range, so files look owned by the same names inside"><input type="checkbox" checked={shift} onChange={(e) => setShift(e.target.checked)} style={{ width: 'auto' }} />shift ownership</label>}
<span className="spacer" />
<button className="btn on" disabled={!src.trim() || !dst.trim()}>Mount</button>
</div>
</form>
<div className="muted small">{i.type === 'container' ? 'A bind mount; it appears at once, running or not.' : 'Shared into the VM over virtiofs; its agent mounts it. Appears at once on a running VM with the agent, otherwise at the next start.'} The data stays where it is — this is the instance’s device, not a copy.</div>
</section>
</>
)
}
function NewVMFromISO({ st, ov, iso, onClose, onStarted }: { st: VirtStatus; ov: VirtOverview; iso: string; onClose: () => void; onStarted: (t: TaskInfo) => void }) {
const isos = ov.library.isos
const [pick, setPick] = useState(iso || isos[0]?.name || '')
const [name, setName] = useState('')
const [cpu, setCpu] = useState('2')
const [mem, setMem] = useState('2GiB')
const [disk, setDisk] = useState('20GiB')
const nets = (ov.networks ?? []).filter((n) => n.managed || n.type === 'bridge')
const [net, setNet] = useState(nets.find((n) => n.name === 'incusbr0')?.name ?? nets[0]?.name ?? '')
const [sb, setSb] = useState(true)
const [err, setErr] = useState('')
const [busy, setBusy] = useState(false)
useEscape(onClose)
const submit = async (e: FormEvent) => {
e.preventDefault(); setErr(''); setBusy(true)
try { onStarted(await api.virtFromISO({ name: name.trim(), iso: pick, cpu: cpu.trim(), memory: mem.trim(), disk: disk.trim(), network: net, secureboot: sb, start: true })) }
catch (e) { setErr(errMsg(e)); setBusy(false) }
}
return (
<div className="modal-back" onClick={onClose}>
<form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
<h3>New VM from an ISO</h3>
<label className="muted">ISO<select value={pick} onChange={(e) => setPick(e.target.value)}>{isos.map((f) => <option key={f.name} value={f.name}>{f.name} · {fmtBytes(f.size)}</option>)}</select></label>
<div className="virt-form-row">
<label className="muted">Name<input value={name} onChange={(e) => setName(e.target.value)} pattern="[a-zA-Z][a-zA-Z0-9\-]{0,62}" placeholder="win11" spellCheck={false} autoCapitalize="off" autoCorrect="off" required /></label>
<label className="muted">Network<select value={net} onChange={(e) => setNet(e.target.value)}>{nets.map((n) => <option key={n.name} value={n.name}>{n.name}{n.address ? ` · ${n.address}` : ''}</option>)}</select></label>
</div>
<div className="virt-form-row">
<label className="muted">CPUs<input className="mono" value={cpu} onChange={(e) => setCpu(e.target.value)} /></label>
<label className="muted">Memory<input className="mono" value={mem} onChange={(e) => setMem(e.target.value)} /></label>
<label className="muted">Disk<input className="mono" value={disk} onChange={(e) => setDisk(e.target.value)} /></label>
</div>
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<input type="checkbox" checked={sb} onChange={(e) => setSb(e.target.checked)} style={{ width: 'auto' }} />Secure Boot — Windows, Debian, Ubuntu and Fedora boot with it; Alpine, Arch, TrueNAS and most others need it off
</label>
<div className="muted small">An empty VM with the ISO as its first boot device, started, so the installer is on the VGA console. {fmtBytes(st.mem_avail)} free here; a VM’s memory is a reservation. Windows also wants the virtio drivers ISO attached as a second drive — add it from the VM’s Disks tab.</div>
{err && <div className="error">{err}</div>}
<div className="svc-actions">
<button type="submit" className="btn on" disabled={busy || !pick || !name.trim()}>{busy ? 'Starting…' : 'Create and boot the ISO'}</button>
<span className="spacer" />
<button type="button" className="btn" onClick={onClose}>Cancel</button>
</div>
</form>
</div>
)
}
function Library({ st, ov, onTask, onChanged, onNewVM }: { st: VirtStatus; ov: VirtOverview; onTask: (t: TaskInfo) => void; onChanged: () => void; onNewVM: (iso: string) => void }) {
const lib = ov.library
const vms = (ov.instances ?? []).filter((i) => i.type === 'virtual-machine')
const [url, setUrl] = useState(''); const [sha, setSha] = useState(''); const [path, setPath] = useState('')
const [upload, setUpload] = useState<{ name: string; pct: number } | null>(null)
const [exp, setExp] = useState<ExportsView | null>(null)
const [cfg, setCfg] = useState<ExportsView['config'] | null>(null)
const loadExports = useCallback(() => api.virtExports().then((v) => { setExp(v); setCfg(v.config) }).catch(() => setExp(null)), [])
useEffect(() => { loadExports() }, [loadExports])
const uploadFiles = async (files: FileList | null) => {
if (!files?.length) return
for (const f of Array.from(files)) {
if (!/\.(iso|img)$/i.test(f.name)) { toast(`${f.name}: only .iso or .img files`, 'err'); continue }
setUpload({ name: f.name, pct: 0 })
try { await api.fileUpload(st.dir + '/isos', f, false, (pct) => setUpload({ name: f.name, pct })); toast(`uploaded ${f.name}`) } catch (e) { toast(`${f.name}: ${errMsg(e)}`, 'err') }
}
setUpload(null); onChanged()
}
const fetchISO = async (e: FormEvent) => { e.preventDefault(); try { onTask(await api.virtISOFetch(url.trim(), sha.trim(), '')); setUrl(''); setSha('') } catch (er) { toast(errMsg(er), 'err') } }
const importISO = async (e: FormEvent) => { e.preventDefault(); try { onTask(await api.virtISOImport(path.trim())); setPath('') } catch (er) { toast(errMsg(er), 'err') } }
const attach = async (f: LibraryFile) => {
if (vms.length === 0) { toast('no VM to attach it to — make one first, or use New VM from ISO', 'info'); return }
const vm = vms.length === 1 ? vms[0].name : await askText(`Attach ${f.name} to which VM? (${vms.map((v) => v.name).join(', ')})`, vms[0].name, 'Attach')
if (!vm) return
const first = await askYes(`Boot ${vm} from ${f.name} first, ahead of its disk? Say no to just make it available as a CD-ROM.`, 'Boot first')
try { const r = await api.virtISOAttach(vm, f.name, first); toast(`${f.name} in ${vm} as ${r.device}`); onChanged() } catch (e) { toast(errMsg(e), 'err') }
}
const del = async (f: LibraryFile) => { if (!(await askYes(`Delete ${f.name} from the library?`, 'Delete'))) return; try { await api.virtISODelete(f.name); toast('deleted'); onChanged() } catch (e) { toast(errMsg(e), 'err') } }
const rename = async (f: LibraryFile) => { const to = await askText(`Rename ${f.name} to`, f.name, 'Rename'); if (!to || to === f.name) return; try { await api.virtISORename(f.name, to); toast('renamed'); onChanged() } catch (e) { toast(errMsg(e), 'err') } }
const saveExports = async () => { if (!cfg) return; try { await api.virtExportsPut(cfg); toast(cfg.enabled ? 'exports scheduled' : 'exports paused'); loadExports() } catch (e) { toast(errMsg(e), 'err') } }
const delExport = async (inst: string, name: string) => { if (!(await askYes(`Delete the export ${name}?`, 'Delete'))) return; try { await api.virtExportDelete(inst, name); loadExports() } catch (e) { toast(errMsg(e), 'err') } }
const table = (files: LibraryFile[]) => files.length === 0 ? <div className="muted small">empty</div> : (
<table className="virt-table"><thead><tr><th>File</th><th className="num">Size</th><th>Changed</th></tr></thead>
<tbody>{files.map((f) => <tr key={f.name}><td className="mono">{f.name}</td><td className="num">{fmtBytes(f.size)}</td><td>{when(f.modified)}</td></tr>)}</tbody></table>
)
return (
<div className="svc-rows" style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 14 }}>
<section className="card"><div className="sub-head"><span className="dname">Images</span><span className="spacer" /><span className="muted small mono">{dir}/images</span></div>{table(lib.images)}
<section className="card">
<div className="sub-head"><span className="dname">ISOs</span><span className="spacer" /><span className="muted small mono">{st.dir}/isos</span></div>
{lib.isos.length === 0 && <div className="muted small">No ISOs yet. Upload one, fetch one by URL, or import a file already on this machine.</div>}
{lib.isos.length > 0 && (
<table className="virt-table"><thead><tr><th>File</th><th className="num">Size</th><th>In</th><th /></tr></thead>
<tbody>{lib.isos.map((f) => (
<tr key={f.name}><td className="mono">{f.name}</td><td className="num">{fmtBytes(f.size)}</td><td className="small">{f.attached_to?.join(' ') || '—'}</td>
<td className="num" style={{ whiteSpace: 'normal' }}>
{st.kvm && <Btn className="btn on" onClick={() => onNewVM(f.name)}>New VM</Btn>} {st.kvm && <Btn className="btn" onClick={() => attach(f)}>Attach…</Btn>} <Btn className="btn" onClick={() => rename(f)}>Rename</Btn> <Btn className="btn danger" disabled={!!f.attached_to?.length} title={f.attached_to?.length ? 'attached — eject it first' : ''} onClick={() => del(f)}>Delete</Btn>
</td></tr>
))}</tbody></table>
)}
<div className="virt-form-row" style={{ flexWrap: 'wrap', marginTop: 8 }}>
<label className="btn" style={{ alignSelf: 'flex-end' }}>{upload ? `${upload.name} · ${upload.pct}%` : 'Upload…'}<input type="file" accept=".iso,.img" multiple style={{ display: 'none' }} onChange={(e) => uploadFiles(e.target.files)} /></label>
<form onSubmit={fetchISO} className="virt-form-row" style={{ flex: '2 1 320px' }}>
<label className="muted" style={{ flex: 3 }}>Fetch from a URL<input className="mono" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://…/something.iso" spellCheck={false} /></label>
<label className="muted" style={{ flex: 2 }}>sha256 — optional<input className="mono" value={sha} onChange={(e) => setSha(e.target.value)} spellCheck={false} /></label>
<button className="btn" style={{ alignSelf: 'flex-end' }} disabled={!url.trim()}>Fetch</button>
</form>
<form onSubmit={importISO} className="virt-form-row" style={{ flex: '1 1 260px' }}>
<label className="muted" style={{ flex: 1 }}>Import a file on this machine — copied in<input className="mono" value={path} onChange={(e) => setPath(e.target.value)} placeholder="/tank/software/isos/…/x.iso" spellCheck={false} /></label>
<button className="btn" style={{ alignSelf: 'flex-end' }} disabled={!path.trim()}>Import</button>
</form>
</div>
<div className="muted small">{st.kvm ? 'An ISO attaches to a VM as a CD-ROM, live or stopped; “New VM” makes an empty VM that boots it, for an installer on the VGA console.' : 'This machine has no KVM, so there is nothing here to boot an ISO.'}</div>
</section>
<section className="card">
<div className="sub-head"><span className="dname">Exports</span><span className="spacer" /><span className="muted small mono">{st.dir}/exports</span></div>
{cfg && (
<div className="virt-form-row" style={{ flexWrap: 'wrap', alignItems: 'flex-end' }}>
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8, flex: '0 0 auto' }}><input type="checkbox" checked={cfg.enabled} onChange={(e) => setCfg({ ...cfg, enabled: e.target.checked })} style={{ width: 'auto' }} />nightly</label>
<label className="muted" style={{ flex: '0 0 90px' }}>at<input className="mono" type="time" value={`${String(cfg.hour).padStart(2, '0')}:${String(cfg.minute).padStart(2, '0')}`} onChange={(e) => { const [h, m] = e.target.value.split(':').map(Number); if (!isNaN(h) && !isNaN(m)) setCfg({ ...cfg, hour: h, minute: m }) }} /></label>
<label className="muted" style={{ flex: '0 0 110px' }}>keep per instance<input className="mono" type="number" min={1} max={100} value={cfg.keep} onChange={(e) => setCfg({ ...cfg, keep: Number(e.target.value) || 1 })} /></label>
<label className="muted" style={{ flexDirection: 'row', alignItems: 'center', gap: 8, flex: '0 0 auto' }}><input type="checkbox" checked={!cfg.instance_only} onChange={(e) => setCfg({ ...cfg, instance_only: !e.target.checked })} style={{ width: 'auto' }} />include snapshots</label>
<span className="spacer" />
<Btn className="btn on" disabled={JSON.stringify(cfg) === JSON.stringify(exp?.config)} onClick={saveExports}>Save</Btn>
<Btn className="btn" onClick={async () => { try { onTask(await api.virtExportsRun()) } catch (e) { toast(errMsg(e), 'err') } }}>Export all now</Btn>
</div>
)}
{exp && <div className="muted small" style={{ marginTop: 6 }}>{exp.config.enabled ? <>Cron line in <span className="mono">{exp.cron_file}</span>, next {exp.next ? new Date(exp.next).toLocaleString() : '—'}.</> : 'Not scheduled.'} {exp.last ? <>Last run {when(exp.last.at)}: {exp.last.exported.length} exported, {exp.last.pruned.length} pruned{exp.last.errors?.length ? <span className="warn-text">, {exp.last.errors.length} failed: {exp.last.errors.join('; ')}</span> : ''}.</> : 'Never run.'} Every instance as a tarball Incus can import again; the folder is backed up with the rest of Ham Lab’s data.</div>}
{exp && exp.files.length > 0 && (
<table className="virt-table" style={{ marginTop: 8 }}><thead><tr><th>Instance</th><th>Export</th><th className="num">Size</th><th>Taken</th><th /></tr></thead>
<tbody>{exp.files.map((f) => <tr key={f.instance + f.name}><td>{f.instance}</td><td className="mono small">{f.name}</td><td className="num">{fmtBytes(f.size)}</td><td>{when(f.modified)}</td><td className="num"><Btn className="btn danger" onClick={() => delExport(f.instance, f.name)}>Delete</Btn></td></tr>)}</tbody></table>
)}
</section>
<section className="card"><div className="sub-head"><span className="dname">Images</span><span className="spacer" /><span className="muted small mono">{st.dir}/images</span></div>{table(lib.images)}
<div className="muted small">Every image downloaded, imported or published lands here as a file, so the library is whole without Incus and can be reloaded into a fresh install.</div></section>
<section className="card"><div className="sub-head"><span className="dname">ISOs</span><span className="spacer" /><span className="muted small mono">{dir}/isos</span></div>{table(lib.isos)}
<div className="muted small">ISO installs for VMs — upload, fetch by URL, attach, and the graphical console they need — are the next phase. Files put here now will be listed when it lands.</div></section>
</div>
)
}
+20 -1
View File
@@ -262,7 +262,12 @@ export interface VirtInstance { name: string; type: 'container' | 'virtual-machi
export interface VirtImage { fingerprint: string; aliases: string[]; arch: string; type: string; size: number; created: string; last_used: string; description: string; os?: string; release?: string; variant?: string; cached: boolean; source?: string; public: boolean }
export interface VirtPool { name: string; driver: string; source: string; used: number; total: number; used_by: number }
export interface VirtNetwork { name: string; type: string; managed: boolean; address?: string; nat: boolean; used_by: number }
export interface LibraryFile { name: string; size: number; modified: string }
export interface LibraryFile { name: string; size: number; modified: string; attached_to?: string[] }
export interface ExportConfig { enabled: boolean; hour: number; minute: number; keep: number; instance_only: boolean; instances?: string[]; updated?: string }
export interface ExportRun { at: string; exported: string[]; pruned: string[]; errors?: string[]; seconds: number }
export interface ExportFile { instance: string; name: string; size: number; modified: string }
export interface ExportsView { config: ExportConfig; cron: string; next?: string; last: ExportRun | null; files: ExportFile[]; dir: string; cron_file: string }
export interface FromISO { name: string; iso: string; cpu: string; memory: string; disk: string; network: string; secureboot: boolean; start: boolean }
export interface VirtOverview { status: VirtStatus; error?: string; instances?: VirtInstance[]; images?: VirtImage[]; pools?: VirtPool[]; networks?: VirtNetwork[]; library: { images: LibraryFile[]; isos: LibraryFile[] } }
export interface VirtInstallOpts { driver: string; pool_size_gib: number; subnet: string; docker_rules: boolean; arc_max_gib: number }
export interface VirtCreate { name: string; image: string; vm: boolean; cpu: string; memory: string; disk: string; network: string; cloud_init: string; profiles: string[]; description: string; start: boolean }
@@ -437,6 +442,20 @@ export const api = {
virtConfig: (name: string, cfg: Record<string, string>) => req<void>('PUT', `/api/virt/instances/${encodeURIComponent(name)}/config`, cfg),
virtSnapshot: (name: string, snap: string) => req<{ name: string }>('POST', `/api/virt/instances/${encodeURIComponent(name)}/snapshots`, { name: snap }),
virtSnapshotAction: (name: string, snap: string, action: 'restore' | 'delete') => req<void>('POST', `/api/virt/instances/${encodeURIComponent(name)}/snapshots/${encodeURIComponent(snap)}/${action}`),
virtISOFetch: (url: string, sha256: string, name: string) => req<TaskInfo>('POST', '/api/virt/isos/fetch', { url, sha256, name }),
virtISOImport: (path: string) => req<TaskInfo>('POST', '/api/virt/isos/import', { path }),
virtISODelete: (name: string) => req<void>('POST', '/api/virt/isos/delete', { name }),
virtISORename: (name: string, to: string) => req<void>('POST', '/api/virt/isos/rename', { name, to }),
virtISOAttach: (inst: string, iso: string, bootFirst: boolean) => req<{ device: string }>('POST', `/api/virt/instances/${encodeURIComponent(inst)}/iso`, { iso, boot_first: bootFirst }),
virtISODetach: (inst: string, device: string) => req<void>('POST', `/api/virt/instances/${encodeURIComponent(inst)}/iso/detach`, { device }),
virtFromISO: (f: FromISO) => req<TaskInfo>('POST', '/api/virt/instances/from-iso', f),
virtMountAdd: (inst: string, m: { device: string; source: string; path: string; readonly: boolean; shift: boolean }) => req<{ device: string }>('POST', `/api/virt/instances/${encodeURIComponent(inst)}/mounts`, m),
virtMountRemove: (inst: string, device: string) => req<void>('POST', `/api/virt/instances/${encodeURIComponent(inst)}/mounts/remove`, { device }),
virtExports: () => req<ExportsView>('GET', '/api/virt/exports'),
virtExportsPut: (c: ExportConfig) => req<void>('PUT', '/api/virt/exports', c),
virtExportsRun: (instance = '') => req<TaskInfo>('POST', '/api/virt/exports/run', { instance }),
virtExportDelete: (instance: string, name: string) => req<void>('POST', '/api/virt/exports/delete', { instance, name }),
virtSSHKeys: () => req<{ keys: string[]; user: string }>('GET', '/api/virt/sshkeys'),
}
export function wsURLPath(path: string): string {
+9
View File
@@ -902,3 +902,12 @@ pre.diff .add { color: var(--ok); background: color-mix(in srgb, var(--ok) 12%,
.virt-form-row { display: flex; gap: 8px; }
.virt-form-row > label { flex: 1; min-width: 0; }
.virt .modal { max-width: 640px; }
.vga-back { align-items: stretch; padding: 10px; }
.vga { display: flex; flex-direction: column; gap: 6px; width: 100%; height: 100%; max-width: none; max-height: none; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px; }
.vga-bar { flex-shrink: 0; }
.vga-area { flex: 1; min-height: 0; overflow: auto; background: #000; border-radius: 6px; display: flex; align-items: flex-start; justify-content: flex-start; padding: 4px; }
.vga-area #spice-area { display: inline-block; }
.vga-area #spice-screen { display: inline-block; line-height: 0; }
.vga-area canvas { outline: none; }
.vga-msg { display: none; }
.vga-hint { flex-shrink: 0; }
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+9
View File
@@ -0,0 +1,9 @@
# spice-html5, vendored
Upstream: https://gitlab.freedesktop.org/spice/spice-html5 — commit b372aab (2026-09-21),
copied unchanged on 2026-10-09 (`src/`, `thirdparty/`, `spice.css`). LGPL-3.0-or-later; the
licence text is beside this file. It draws a VM's SPICE display into a canvas from a websocket
carrying the raw SPICE stream — which is what Incus's VGA console websocket is — so Ham Lab's
daemon bridges the two and this does the rest. Loaded lazily by `VgaConsole.tsx`, so the main
bundle does not carry it. Not on npm in a current form (the `@spice-project/spice-html5`
package stopped at 0.2.1 in 2019), hence the copy.
+168
View File
@@ -0,0 +1,168 @@
body
{
background-color: #999999;
color: #000000;
margin: 0;
padding: 0;
font-family: "Lucida Grande", "Lucida Sans Unicode", "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif;
font-size: 12pt;
line-height: 1.5em;
}
* { margin: 0; }
button
{
cursor: pointer;
color: #000000;
background-color: #999999;
border: 1px solid #4a4a4a;
min-width: 150px;
border-radius: 10px;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#24414e));
background: -moz-linear-gradient(top, #fff, #24414e);
-ms-transform: translate(15%, -8%);
transform: translate(15%, -8%);
font-size: .90em;
font-weight: bolder;
padding: 0px 0px 3px 0px;
margin-top: 5px;
}
button:focus
{
outline: none;
}
button:hover
{
background-color: #24414e
}
button:active
{
background-color: #24414e;
transform: translate(14.85%, -7%);
}
.SidenavClosed
{
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #bbbbbb;
box-shadow: 1px 0px #00000040;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.SidenavOpen
{
height: 100%;
width: 200px !important;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #bbbbbb;
box-shadow: 1px 0px #00000040;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
#Sidenav label
{
color: #000000;
margin-left: 3%;
text-shadow: 1px 1px 0px rgba(175, 210, 220, 0.8);
position: absolute;
font-size: .9em;
}
#Sidenav input
{
padding: 3px;
background-color: #fAfAfA;
border: 1px inset #999999;
outline: none;
float: right;
margin-right: 3%;
-moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
position: relative;
max-width: 110px;
}
#Sidenav .closebtn
{
position: absolute;
top: 10px;
right: 10px;
font-size: 25px;
margin-left: 50px;
cursor: pointer;
color: #000000;
}
canvas
{
border: 1px solid #000000;
}
#login
{
background: #bbbbbb;
z-index: 1;
padding-top: 2px;
border-bottom: 2px solid #00000040;
}
#login p
{
margin-left: 27%;
display: inline;
font-size: large;
}
#spice-area
{
height: 100%;
width: 100%;
margin-left: auto;
margin-right: auto;
}
.spice-screen
{
min-height: 600px;
height: 100%;
text-align: center;
padding: 0;
background-color: #999999;
}
.spice-message
{
width: 90%;
height: 40%;
overflow: auto;
margin-left: auto;
margin-right: auto;
padding: 10px;
font-size: 8pt;
line-height: 1.1em;
font-family: 'Andale Mono', monospace;
background-color: #fAfAfA;
border: 1px inset #999999;
border-radius: 3px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
.spice-message p {
margin-bottom: 0em;
margin-top: 0em;
}
.spice-message-warning {
color: orange;
}
.spice-message-error {
color: red;
}
+189
View File
@@ -0,0 +1,189 @@
"use strict";
/*
Copyright (C) 2012 by Aric Stewart <aric@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Thomas Roell not be used in
* advertising or publicity pertaining to distribution of the software without
* specific, written prior permission. Thomas Roell makes no representations
* about the suitability of this software for any purpose. It is provided
* "as is" without express or implied warranty.
*
* THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
*/
/*
* Copyright (c) 1994-2003 by The XFree86 Project, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of the copyright holder(s)
* and author(s) shall not be used in advertising or otherwise to promote
* the sale, use or other dealings in this Software without prior written
* authorization from the copyright holder(s) and author(s).
*/
/*
* NOTE: The AT/MF keyboards can generate (via the 8042) two (MF: three)
* sets of scancodes. Set3 can only be generated by a MF keyboard.
* Set2 sends a makecode for keypress, and the same code prefixed by a
* F0 for keyrelease. This is a little bit ugly to handle. Thus we use
* here for X386 the PC/XT compatible Set1. This set uses 8bit scancodes.
* Bit 7 ist set if the key is released. The code E0 switches to a
* different meaning to add the new MF cursorkeys, while not breaking old
* applications. E1 is another special prefix. Since I assume that there
* will be further versions of PC/XT scancode compatible keyboards, we
* may be in trouble one day.
*
* IDEA: 1) Use Set2 on AT84 keyboards and translate it to MF Set3.
* 2) Use the keyboards native set and translate it to common keysyms.
*/
var KeyNames = {
/*
* definition of the AT84/MF101/MF102 Keyboard:
* ============================================================
* Defined Key Cap Glyphs Pressed value
* Key Name Main Also (hex) (dec)
* ---------------- ---------- ------- ------ ------
*/
KEY_Escape :/* Escape 0x01 */ 1,
KEY_1 :/* 1 ! 0x02 */ 2,
KEY_2 :/* 2 @ 0x03 */ 3,
KEY_3 :/* 3 # 0x04 */ 4,
KEY_4 :/* 4 $ 0x05 */ 5,
KEY_5 :/* 5 % 0x06 */ 6,
KEY_6 :/* 6 ^ 0x07 */ 7,
KEY_7 :/* 7 & 0x08 */ 8,
KEY_8 :/* 8 * 0x09 */ 9,
KEY_9 :/* 9 ( 0x0a */ 10,
KEY_0 :/* 0 ) 0x0b */ 11,
KEY_Minus :/* - (Minus) _ (Under) 0x0c */ 12,
KEY_Equal :/* = (Equal) + 0x0d */ 13,
KEY_BackSpace :/* Back Space 0x0e */ 14,
KEY_Tab :/* Tab 0x0f */ 15,
KEY_Q :/* Q 0x10 */ 16,
KEY_W :/* W 0x11 */ 17,
KEY_E :/* E 0x12 */ 18,
KEY_R :/* R 0x13 */ 19,
KEY_T :/* T 0x14 */ 20,
KEY_Y :/* Y 0x15 */ 21,
KEY_U :/* U 0x16 */ 22,
KEY_I :/* I 0x17 */ 23,
KEY_O :/* O 0x18 */ 24,
KEY_P :/* P 0x19 */ 25,
KEY_LBrace :/* [ { 0x1a */ 26,
KEY_RBrace :/* ] } 0x1b */ 27,
KEY_Enter :/* Enter 0x1c */ 28,
KEY_LCtrl :/* Ctrl(left) 0x1d */ 29,
KEY_A :/* A 0x1e */ 30,
KEY_S :/* S 0x1f */ 31,
KEY_D :/* D 0x20 */ 32,
KEY_F :/* F 0x21 */ 33,
KEY_G :/* G 0x22 */ 34,
KEY_H :/* H 0x23 */ 35,
KEY_J :/* J 0x24 */ 36,
KEY_K :/* K 0x25 */ 37,
KEY_L :/* L 0x26 */ 38,
KEY_SemiColon :/* ;(SemiColon) :(Colon) 0x27 */ 39,
KEY_Quote :/* ' (Apostr) " (Quote) 0x28 */ 40,
KEY_Tilde :/* ` (Accent) ~ (Tilde) 0x29 */ 41,
KEY_ShiftL :/* Shift(left) 0x2a */ 42,
KEY_BSlash :/* \(BckSlash) |(VertBar)0x2b */ 43,
KEY_Z :/* Z 0x2c */ 44,
KEY_X :/* X 0x2d */ 45,
KEY_C :/* C 0x2e */ 46,
KEY_V :/* V 0x2f */ 47,
KEY_B :/* B 0x30 */ 48,
KEY_N :/* N 0x31 */ 49,
KEY_M :/* M 0x32 */ 50,
KEY_Comma :/* , (Comma) < (Less) 0x33 */ 51,
KEY_Period :/* . (Period) >(Greater)0x34 */ 52,
KEY_Slash :/* / (Slash) ? 0x35 */ 53,
KEY_ShiftR :/* Shift(right) 0x36 */ 54,
KEY_KP_Multiply :/* * 0x37 */ 55,
KEY_Alt :/* Alt(left) 0x38 */ 56,
KEY_Space :/* (SpaceBar) 0x39 */ 57,
KEY_CapsLock :/* CapsLock 0x3a */ 58,
KEY_F1 :/* F1 0x3b */ 59,
KEY_F2 :/* F2 0x3c */ 60,
KEY_F3 :/* F3 0x3d */ 61,
KEY_F4 :/* F4 0x3e */ 62,
KEY_F5 :/* F5 0x3f */ 63,
KEY_F6 :/* F6 0x40 */ 64,
KEY_F7 :/* F7 0x41 */ 65,
KEY_F8 :/* F8 0x42 */ 66,
KEY_F9 :/* F9 0x43 */ 67,
KEY_F10 :/* F10 0x44 */ 68,
KEY_NumLock :/* NumLock 0x45 */ 69,
KEY_ScrollLock :/* ScrollLock 0x46 */ 70,
KEY_KP_7 :/* 7 Home 0x47 */ 71,
KEY_KP_8 :/* 8 Up 0x48 */ 72,
KEY_KP_9 :/* 9 PgUp 0x49 */ 73,
KEY_KP_Minus :/* - (Minus) 0x4a */ 74,
KEY_KP_4 :/* 4 Left 0x4b */ 75,
KEY_KP_5 :/* 5 0x4c */ 76,
KEY_KP_6 :/* 6 Right 0x4d */ 77,
KEY_KP_Plus :/* + (Plus) 0x4e */ 78,
KEY_KP_1 :/* 1 End 0x4f */ 79,
KEY_KP_2 :/* 2 Down 0x50 */ 80,
KEY_KP_3 :/* 3 PgDown 0x51 */ 81,
KEY_KP_0 :/* 0 Insert 0x52 */ 82,
KEY_KP_Decimal :/* . (Decimal) Delete 0x53 */ 83,
KEY_SysRequest :/* SysRequest 0x54 */ 84,
/* NOTUSED 0x55 */
KEY_Less :/* < (Less) >(Greater) 0x56 */ 86,
KEY_F11 :/* F11 0x57 */ 87,
KEY_F12 :/* F12 0x58 */ 88,
KEY_Prefix0 :/* special 0x60 */ 96,
KEY_Prefix1 :/* specail 0x61 */ 97,
};
export {
KeyNames,
};
+64
View File
@@ -0,0 +1,64 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** bitmap.js
** Handle SPICE_IMAGE_TYPE_BITMAP
**--------------------------------------------------------------------------*/
import { Constants } from './enums.js';
/* A 32-bit source pixel is B, G, R, A in memory. Read it as a little-endian
word, A R G B, rotate it left by eight to R G B A and store that word
big-endian, so the bytes land in the R, G, B, A order ImageData wants: one
load, one store and two shifts per pixel. A DataView takes either host
byte order and any alignment. Only 32BIT and RGBA are handled; 32BIT
ignores the source's high byte and is fully opaque. */
function convert_spice_bitmap_to_web(context, spice_bitmap)
{
if (spice_bitmap.format != Constants.SPICE_BITMAP_FMT_32BIT &&
spice_bitmap.format != Constants.SPICE_BITMAP_FMT_RGBA)
return undefined;
const w = spice_bitmap.x;
const h = spice_bitmap.y;
const stride = spice_bitmap.stride;
const ret = context.createImageData(w, h);
const opaque = spice_bitmap.format == Constants.SPICE_BITMAP_FMT_32BIT;
const top_down = spice_bitmap.flags & Constants.SPICE_BITMAP_FLAGS_TOP_DOWN;
const src = new DataView(spice_bitmap.data);
const dest = new DataView(ret.data.buffer);
let d = 0;
for (let y = 0; y < h; y++)
{
let s = (top_down ? y : h - 1 - y) * stride;
for (let x = 0; x < w; x++, d += 4, s += 4)
{
const v = src.getUint32(s, true);
dest.setUint32(d, (v << 8) | (opaque ? 0xff : v >>> 24), false);
}
}
return ret;
}
export {
convert_spice_bitmap_to_web,
};
+149
View File
@@ -0,0 +1,149 @@
/*
* @see https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values
*/
export const code_to_scancode = [];
code_to_scancode["Escape"] = 0x01;
code_to_scancode["Digit1"] = 0x02;
code_to_scancode["Digit2"] = 0x03;
code_to_scancode["Digit3"] = 0x04;
code_to_scancode["Digit4"] = 0x05;
code_to_scancode["Digit5"] = 0x06;
code_to_scancode["Digit6"] = 0x07;
code_to_scancode["Digit7"] = 0x08;
code_to_scancode["Digit8"] = 0x09;
code_to_scancode["Digit9"] = 0x0A;
code_to_scancode["Digit0"] = 0x0B;
code_to_scancode["Minus"] = 0x0C;
code_to_scancode["Equal"] = 0x0D;
code_to_scancode["Backspace"] = 0x0E;
code_to_scancode["Tab"] = 0x0F;
code_to_scancode["KeyQ"] = 0x10;
code_to_scancode["KeyW"] = 0x11;
code_to_scancode["KeyE"] = 0x12;
code_to_scancode["KeyR"] = 0x13;
code_to_scancode["KeyT"] = 0x14;
code_to_scancode["KeyY"] = 0x15;
code_to_scancode["KeyU"] = 0x16;
code_to_scancode["KeyI"] = 0x17;
code_to_scancode["KeyO"] = 0x18;
code_to_scancode["KeyP"] = 0x19;
code_to_scancode["BracketLeft"] = 0x1A;
code_to_scancode["BracketRight"] = 0x1B;
code_to_scancode["Enter"] = 0x1C;
code_to_scancode["ControlLeft"] = 0x1D;
code_to_scancode["KeyA"] = 0x1E;
code_to_scancode["KeyS"] = 0x1F;
code_to_scancode["KeyD"] = 0x20;
code_to_scancode["KeyF"] = 0x21;
code_to_scancode["KeyG"] = 0x22;
code_to_scancode["KeyH"] = 0x23;
code_to_scancode["KeyJ"] = 0x24;
code_to_scancode["KeyK"] = 0x25;
code_to_scancode["KeyL"] = 0x26;
code_to_scancode["Semicolon"] = 0x27;
code_to_scancode["Quote"] = 0x28;
code_to_scancode["Backquote"] = 0x29;
code_to_scancode["ShiftLeft"] = 0x2A;
code_to_scancode["Backslash"] = 0x2B;
code_to_scancode["KeyZ"] = 0x2C;
code_to_scancode["KeyX"] = 0x2D;
code_to_scancode["KeyC"] = 0x2E;
code_to_scancode["KeyV"] = 0x2F;
code_to_scancode["KeyB"] = 0x30;
code_to_scancode["KeyN"] = 0x31;
code_to_scancode["KeyM"] = 0x32;
code_to_scancode["Comma"] = 0x33;
code_to_scancode["Period"] = 0x34;
code_to_scancode["Slash"] = 0x35;
code_to_scancode["ShiftRight"] = 0x36;
code_to_scancode["NumpadMultiply"] = 0x37;
code_to_scancode["AltLeft"] = 0x38;
code_to_scancode["Space"] = 0x39;
code_to_scancode["CapsLock"] = 0x3A;
code_to_scancode["F1"] = 0x3B;
code_to_scancode["F2"] = 0x3C;
code_to_scancode["F3"] = 0x3D;
code_to_scancode["F4"] = 0x3E;
code_to_scancode["F5"] = 0x3F;
code_to_scancode["F6"] = 0x40;
code_to_scancode["F7"] = 0x41;
code_to_scancode["F8"] = 0x42;
code_to_scancode["F9"] = 0x43;
code_to_scancode["F10"] = 0x44;
code_to_scancode["Pause"] = 0x45;
code_to_scancode["ScrollLock"] = 0x46;
code_to_scancode["Numpad7"] = 0x47;
code_to_scancode["Numpad8"] = 0x48;
code_to_scancode["Numpad9"] = 0x49;
code_to_scancode["NumpadSubtract"] = 0x4A;
code_to_scancode["Numpad4"] = 0x4B;
code_to_scancode["Numpad5"] = 0x4C;
code_to_scancode["Numpad6"] = 0x4D;
code_to_scancode["NumpadAdd"] = 0x4E;
code_to_scancode["Numpad1"] = 0x4F;
code_to_scancode["Numpad2"] = 0x50;
code_to_scancode["Numpad3"] = 0x51;
code_to_scancode["Numpad0"] = 0x52;
code_to_scancode["NumpadDecimal"] = 0x53;
code_to_scancode["PrintScreen"] = 0x54;
code_to_scancode["IntlBackslash"] = 0x56;
code_to_scancode["F11"] = 0x57;
code_to_scancode["F12"] = 0x58;
code_to_scancode["NumpadEqual"] = 0x59;
code_to_scancode["F13"] = 0x64;
code_to_scancode["F14"] = 0x65;
code_to_scancode["F15"] = 0x66;
code_to_scancode["F16"] = 0x67;
code_to_scancode["F17"] = 0x68;
code_to_scancode["F18"] = 0x69;
code_to_scancode["F19"] = 0x6A;
code_to_scancode["F20"] = 0x6B;
code_to_scancode["F21"] = 0x6C;
code_to_scancode["F22"] = 0x6D;
code_to_scancode["F23"] = 0x6E;
code_to_scancode["KanaMode"] = 0x70;
code_to_scancode["IntlRo"] = 0x73;
code_to_scancode["F24"] = 0x76;
code_to_scancode["Convert"] = 0x79;
code_to_scancode["NonConvert"] = 0x7B;
code_to_scancode["IntlYen"] = 0x7D;
code_to_scancode["NumpadComma"] = 0x7E;
code_to_scancode["MediaTrackPrevious"] = 0xE0 | (0x10 << 8);
code_to_scancode["MediaTrackNext"] = 0xE0 | (0x19 << 8);
code_to_scancode["NumpadEnter"] = 0xE0 | (0x1C << 8);
code_to_scancode["ControlRight"] = 0xE0 | (0x1D << 8);
code_to_scancode["AudioVolumeMute"] = 0xE0 | (0x20 << 8);
code_to_scancode["LaunchApp2"] = 0xE0 | (0x21 << 8);
code_to_scancode["MediaPlayPause"] = 0xE0 | (0x22 << 8);
code_to_scancode["MediaStop"] = 0xE0 | (0x24 << 8);
code_to_scancode["VolumeDown"] = 0xE0 | (0x2E << 8);
code_to_scancode["VolumeUp"] = 0xE0 | (0x30 << 8);
code_to_scancode["BrowserHome"] = 0xE0 | (0x32 << 8);
code_to_scancode["NumpadDivide"] = 0xE0 | (0x35 << 8);
code_to_scancode["PrintScreen"] = 0xE0 | (0x37 << 8);
code_to_scancode["AltRight"] = 0xE0 | (0x38 << 8);
code_to_scancode["NumLock"] = 0xE0 | (0x45 << 8);
code_to_scancode["Pause"] = 0xE0 | (0x46 << 8);
code_to_scancode["Home"] = 0xE0 | (0x47 << 8);
code_to_scancode["ArrowUp"] = 0xE0 | (0x48 << 8);
code_to_scancode["PageUp"] = 0xE0 | (0x49 << 8);
code_to_scancode["ArrowLeft"] = 0xE0 | (0x4B << 8);
code_to_scancode["ArrowRight"] = 0xE0 | (0x4D << 8);
code_to_scancode["End"] = 0xE0 | (0x4F << 8);
code_to_scancode["ArrowDown"] = 0xE0 | (0x50 << 8);
code_to_scancode["PageDown"] = 0xE0 | (0x51 << 8);
code_to_scancode["Insert"] = 0xE0 | (0x52 << 8);
code_to_scancode["Delete"] = 0xE0 | (0x53 << 8);
code_to_scancode["MetaLeft"] = 0xE0 | (0x5B << 8);
code_to_scancode["MetaRight"] = 0xE0 | (0x5C << 8);
code_to_scancode["ContextMenu"] = 0xE0 | (0x5D << 8);
code_to_scancode["Power"] = 0xE0 | (0x5E << 8);
code_to_scancode["BrowserSearch"] = 0xE0 | (0x65 << 8);
code_to_scancode["BrowserFavorites"] = 0xE0 | (0x66 << 8);
code_to_scancode["BrowserRefresh"] = 0xE0 | (0x67 << 8);
code_to_scancode["BrowserStop"] = 0xE0 | (0x68 << 8);
code_to_scancode["BrowserForward"] = 0xE0 | (0x69 << 8);
code_to_scancode["BrowserBack"] = 0xE0 | (0x6A << 8);
code_to_scancode["LaunchApp1"] = 0xE0 | (0x6B << 8);
code_to_scancode["LaunchMail"] = 0xE0 | (0x6C << 8);
code_to_scancode["MediaSelect"] = 0xE0 | (0x6D << 8);
+317
View File
@@ -0,0 +1,317 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import { create_rgba_png } from './png.js';
import { Constants } from './enums.js';
import { DEBUG } from './utils.js';
import {
SpiceMsgCursorInit,
SpiceMsgCursorMove,
SpiceMsgCursorSet,
} from './spicemsg.js';
import { SpiceSimulateCursor } from './simulatecursor.js';
import { SpiceConn } from './spiceconn.js';
/*----------------------------------------------------------------------------
** SpiceCursorConn
** Drive the Spice Cursor Channel
**--------------------------------------------------------------------------*/
function SpiceCursorConn()
{
SpiceConn.apply(this, arguments);
}
/* The largest cursor image Chromium and Firefox will show. */
var MAX_CSS_CURSOR = 128;
SpiceCursorConn.prototype = Object.create(SpiceConn.prototype);
SpiceCursorConn.prototype.process_channel_message = function(msg)
{
if (msg.type == Constants.SPICE_MSG_CURSOR_INIT)
{
var cursor_init = new SpiceMsgCursorInit(msg.data);
DEBUG > 1 && console.log("SpiceMsgCursorInit");
if (this.parent && this.parent.inputs &&
this.parent.inputs.mouse_mode == Constants.SPICE_MOUSE_MODE_SERVER)
{
// FIXME - this imagines that the server actually
// provides the current cursor position,
// instead of 0,0. As of May 11, 2012,
// that assumption was false :-(.
this.parent.inputs.mousex = cursor_init.position.x;
this.parent.inputs.mousey = cursor_init.position.y;
}
// FIXME - We don't handle most of the parameters here...
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_SET)
{
var cursor_set = new SpiceMsgCursorSet(msg.data);
DEBUG > 1 && console.log("SpiceMsgCursorSet");
if (cursor_set.cursor.flags & Constants.SPICE_CURSOR_FLAGS_NONE)
{
this.hide_cursor();
return true;
}
if (cursor_set.cursor.flags > 0)
this.log_warn("FIXME: No support for cursor flags " + cursor_set.cursor.flags);
/* An unconvertible shape is not an unhandled message: returning
false here made the base class log a second, misleading
"Unknown message type 103" for every one of these. */
if (! this.set_cursor(cursor_set.cursor))
this.warn_once_per_cursor_type(cursor_set.cursor.header.type);
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_MOVE)
{
/* Only meaningful under server mouse mode, where the server owns
the pointer position and we track it for inputs. Under client
mode the browser draws the pointer and already knows where it
is, so there is nothing to do -- but it is handled either way,
rather than reported as unimplemented on every move. */
var cursor_move = new SpiceMsgCursorMove(msg.data);
if (this.parent && this.parent.inputs &&
this.parent.inputs.mouse_mode == Constants.SPICE_MOUSE_MODE_SERVER)
{
this.parent.inputs.mousex = cursor_move.position.x;
this.parent.inputs.mousey = cursor_move.position.y;
}
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_HIDE)
{
DEBUG > 1 && console.log("SpiceMsgCursorHide");
this.hide_cursor();
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_TRAIL)
{
this.known_unimplemented(msg.type, "Cursor Trail");
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_RESET)
{
DEBUG > 1 && console.log("SpiceMsgCursorReset");
document.getElementById(this.parent.screen_id).style.cursor = "auto";
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_INVAL_ONE)
{
this.known_unimplemented(msg.type, "Cursor Inval One");
return true;
}
if (msg.type == Constants.SPICE_MSG_CURSOR_INVAL_ALL)
{
DEBUG > 1 && console.log("SpiceMsgCursorInvalAll");
// FIXME - There may be something useful to do here...
return true;
}
return false;
}
/* One warning per shape type per connection. Windows sends a cursor on
nearly every hover, so an unconvertible type used to produce an
unbounded stream of identical warnings. */
SpiceCursorConn.prototype.warn_once_per_cursor_type = function(type)
{
if (! this.warned_cursor_types)
this.warned_cursor_types = {};
if (this.warned_cursor_types[type])
return;
this.warned_cursor_types[type] = true;
this.log_warn("No support for cursor type " + type + "; leaving the cursor as it was.");
}
/* SPICE cursor shapes to the RGBA the PNG writer expects.
Returns null for a type we cannot convert.
Layouts follow spice-gtk's set_cursor() (src/channel-cursor.c). */
function cursor_to_rgba(header, data)
{
var width = header.width;
var height = header.height;
var pixels = width * height;
var u8 = new Uint8Array(data);
var rgba = new Uint8Array(pixels * 4);
var i, at;
/* SPICE ships 32bpp shapes as native-endian ARGB, which on every
platform we run on is B,G,R,A in memory; PNG wants R,G,B,A. The
swap is invisible on the black/white/transparent cursors that
dominate, which is why it went unnoticed, but colour cursors came
out with red and blue exchanged. */
if (header.type == Constants.SPICE_CURSOR_TYPE_ALPHA)
{
if (u8.length < pixels * 4)
return null;
for (i = 0, at = 0; i < pixels; i++, at += 4)
{
rgba[at] = u8[at + 2];
rgba[at + 1] = u8[at + 1];
rgba[at + 2] = u8[at];
rgba[at + 3] = u8[at + 3];
}
return rgba;
}
/* Two 1bpp masks, AND then XOR, each row padded to a byte. The four
combinations are the classic ones:
AND=1 XOR=0 transparent
AND=1 XOR=1 invert the screen
AND=0 XOR=0 black
AND=0 XOR=1 white
A CSS cursor cannot invert what is under it, so those pixels are
drawn black -- the same choice every other HTML SPICE/VNC client
makes. It is what Windows' I-beam and resize cursors use, and
black-on-transparent reads correctly against the light backgrounds
those appear over. */
if (header.type == Constants.SPICE_CURSOR_TYPE_MONO)
{
var bpl = (width + 7) >> 3;
if (u8.length < bpl * height * 2)
return null;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var byte_at = y * bpl + (x >> 3);
var bit = 0x80 >> (x & 7);
var and_bit = (u8[byte_at] & bit) != 0;
var xor_bit = (u8[bpl * height + byte_at] & bit) != 0;
at = (y * width + x) * 4;
if (and_bit && ! xor_bit)
continue; /* transparent; rgba is zeroed */
var lum = xor_bit && ! and_bit ? 255 : 0;
rgba[at] = rgba[at + 1] = rgba[at + 2] = lum;
rgba[at + 3] = 255;
}
}
return rgba;
}
/* 32bpp BGRA followed by a 1bpp AND mask: mask set means the pixel
is transparent. spice-gtk renders the "white pixel that is also
masked" case as a dim checkerboard rather than a hole, because
that combination is how shapes encode invert; do the same. */
if (header.type == Constants.SPICE_CURSOR_TYPE_COLOR32)
{
var mask_at = pixels * 4;
if (u8.length < mask_at + ((width + 7) >> 3) * height)
return null;
for (i = 0, at = 0; i < pixels; i++, at += 4)
{
var masked = (u8[mask_at + (i >> 3)] & (0x80 >> (i & 7))) != 0;
var white = u8[at] == 0xff && u8[at + 1] == 0xff && u8[at + 2] == 0xff;
if (masked && white)
{
var dark = (((i % width) ^ ((i / width) | 0)) & 1) != 0;
rgba[at] = rgba[at + 1] = rgba[at + 2] = dark ? 0x30 : 0x50;
rgba[at + 3] = dark ? 0xc0 : 0x30;
continue;
}
rgba[at] = u8[at + 2];
rgba[at + 1] = u8[at + 1];
rgba[at + 2] = u8[at];
rgba[at + 3] = masked ? 0 : 255;
}
return rgba;
}
return null;
}
/* True if the shape was converted and applied. */
SpiceCursorConn.prototype.set_cursor = function(cursor)
{
var rgba = cursor_to_rgba(cursor.header, cursor.data);
if (! rgba)
return false;
var pngstr = create_rgba_png(cursor.header.width, cursor.header.height, rgba);
var curstr = 'url(data:image/png,' + pngstr + ') ' +
cursor.header.hot_spot_x + ' ' + cursor.header.hot_spot_y + ", default";
var screen = document.getElementById(this.parent.screen_id);
screen.style.cursor = 'auto';
screen.style.cursor = curstr;
/* Chromium and Firefox drop a cursor image over 128 px on a side
without saying so: the computed style still reads as the url,
and the pointer is the plain arrow, with the arrow's hot spot,
so it points somewhere other than the guest's cursor does. A
shape that size is drawn under the pointer instead. */
var too_large = cursor.header.width > MAX_CSS_CURSOR || cursor.header.height > MAX_CSS_CURSOR;
if (too_large || window.getComputedStyle(screen, null).cursor == 'auto')
SpiceSimulateCursor.simulate_cursor(this, cursor, screen, pngstr, too_large);
else
{
/* This cursor took effect natively, so drop the simulated one
left by an earlier browser-rejected cursor; the mousemove
handler would otherwise keep painting it alongside the real
cursor forever. */
this.remove_simulated_cursor();
}
return true;
}
/* A hidden pointer is hidden whichever way the last shape was shown:
the CSS cursor goes to none, and a simulated cursor image is removed,
or the mousemove handler would keep painting it. */
SpiceCursorConn.prototype.hide_cursor = function()
{
document.getElementById(this.parent.screen_id).style.cursor = "none";
this.remove_simulated_cursor();
}
SpiceCursorConn.prototype.remove_simulated_cursor = function()
{
if (! this.spice_simulated_cursor)
return;
if (this.spice_simulated_cursor.parentNode)
this.spice_simulated_cursor.parentNode.removeChild(this.spice_simulated_cursor);
delete this.spice_simulated_cursor;
}
SpiceCursorConn.prototype.cleanup = function()
{
/* The screen div outlives the connection: a simulated cursor left in
it would sit frozen over the next session, and a guest that ended
with its pointer hidden (or a custom shape) would leave the next
one without a visible pointer until it sends a shape of its own. */
this.remove_simulated_cursor();
var screen = document.getElementById(this.parent.screen_id);
if (screen)
screen.style.cursor = "auto";
SpiceConn.prototype.cleanup.call(this);
}
export {
SpiceCursorConn,
};
File diff suppressed because it is too large Load Diff
+384
View File
@@ -0,0 +1,384 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** enums.js
** 'constants' for Spice
**--------------------------------------------------------------------------*/
export var Constants = {
SPICE_MAGIC : "REDQ",
SPICE_VERSION_MAJOR : 2,
SPICE_VERSION_MINOR : 2,
SPICE_CONNECT_TIMEOUT : (30 * 1000),
SPICE_COMMON_CAP_PROTOCOL_AUTH_SELECTION : 0,
SPICE_COMMON_CAP_AUTH_SPICE : 1,
SPICE_COMMON_CAP_AUTH_SASL : 2,
SPICE_COMMON_CAP_MINI_HEADER : 3,
SPICE_TICKET_KEY_PAIR_LENGTH : 1024,
SPICE_TICKET_PUBKEY_BYTES : (1024 / 8 +34), // (SPICE_TICKET_KEY_PAIR_LENGTH / 8 + 34)
SPICE_LINK_ERR_OK : 0,
SPICE_LINK_ERR_ERROR : 1,
SPICE_LINK_ERR_INVALID_MAGIC : 2,
SPICE_LINK_ERR_INVALID_DATA : 3,
SPICE_LINK_ERR_VERSION_MISMATCH : 4,
SPICE_LINK_ERR_NEED_SECURED : 5,
SPICE_LINK_ERR_NEED_UNSECURED : 6,
SPICE_LINK_ERR_PERMISSION_DENIED : 7,
SPICE_LINK_ERR_BAD_CONNECTION_ID : 8,
SPICE_LINK_ERR_CHANNEL_NOT_AVAILABLE : 9,
SPICE_MSG_MIGRATE : 1,
SPICE_MSG_MIGRATE_DATA : 2,
SPICE_MSG_SET_ACK : 3,
SPICE_MSG_PING : 4,
SPICE_MSG_WAIT_FOR_CHANNELS : 5,
SPICE_MSG_DISCONNECTING : 6,
SPICE_MSG_NOTIFY : 7,
SPICE_MSG_LIST : 8,
SPICE_MSG_MAIN_MIGRATE_BEGIN : 101,
SPICE_MSG_MAIN_MIGRATE_CANCEL : 102,
SPICE_MSG_MAIN_INIT : 103,
SPICE_MSG_MAIN_CHANNELS_LIST : 104,
SPICE_MSG_MAIN_MOUSE_MODE : 105,
SPICE_MSG_MAIN_MULTI_MEDIA_TIME : 106,
SPICE_MSG_MAIN_AGENT_CONNECTED : 107,
SPICE_MSG_MAIN_AGENT_DISCONNECTED : 108,
SPICE_MSG_MAIN_AGENT_DATA : 109,
SPICE_MSG_MAIN_AGENT_TOKEN : 110,
SPICE_MSG_MAIN_MIGRATE_SWITCH_HOST : 111,
SPICE_MSG_MAIN_MIGRATE_END : 112,
SPICE_MSG_MAIN_NAME : 113,
SPICE_MSG_MAIN_UUID : 114,
SPICE_MSG_MAIN_AGENT_CONNECTED_TOKENS : 115,
SPICE_MSG_MAIN_MIGRATE_BEGIN_SEAMLESS : 116,
SPICE_MSG_MAIN_MIGRATE_DST_SEAMLESS_ACK : 117,
SPICE_MSG_MAIN_MIGRATE_DST_SEAMLESS_NACK : 118,
SPICE_MSG_END_MAIN : 119,
SPICE_MSGC_ACK_SYNC : 1,
SPICE_MSGC_ACK : 2,
SPICE_MSGC_PONG : 3,
SPICE_MSGC_MIGRATE_FLUSH_MARK : 4,
SPICE_MSGC_MIGRATE_DATA : 5,
SPICE_MSGC_DISCONNECTING : 6,
SPICE_MSGC_MAIN_CLIENT_INFO : 101,
SPICE_MSGC_MAIN_MIGRATE_CONNECTED : 102,
SPICE_MSGC_MAIN_MIGRATE_CONNECT_ERROR : 103,
SPICE_MSGC_MAIN_ATTACH_CHANNELS : 104,
SPICE_MSGC_MAIN_MOUSE_MODE_REQUEST : 105,
SPICE_MSGC_MAIN_AGENT_START : 106,
SPICE_MSGC_MAIN_AGENT_DATA : 107,
SPICE_MSGC_MAIN_AGENT_TOKEN : 108,
SPICE_MSGC_MAIN_MIGRATE_END : 109,
SPICE_MSGC_END_MAIN : 110,
SPICE_MSG_DISPLAY_MODE : 101,
SPICE_MSG_DISPLAY_MARK : 102,
SPICE_MSG_DISPLAY_RESET : 103,
SPICE_MSG_DISPLAY_COPY_BITS : 104,
SPICE_MSG_DISPLAY_INVAL_LIST : 105,
SPICE_MSG_DISPLAY_INVAL_ALL_PIXMAPS : 106,
SPICE_MSG_DISPLAY_INVAL_PALETTE : 107,
SPICE_MSG_DISPLAY_INVAL_ALL_PALETTES: 108,
SPICE_MSG_DISPLAY_STREAM_CREATE : 122,
SPICE_MSG_DISPLAY_STREAM_DATA : 123,
SPICE_MSG_DISPLAY_STREAM_CLIP : 124,
SPICE_MSG_DISPLAY_STREAM_DESTROY : 125,
SPICE_MSG_DISPLAY_STREAM_DESTROY_ALL: 126,
SPICE_MSG_DISPLAY_DRAW_FILL : 302,
SPICE_MSG_DISPLAY_DRAW_OPAQUE : 303,
SPICE_MSG_DISPLAY_DRAW_COPY : 304,
SPICE_MSG_DISPLAY_DRAW_BLEND : 305,
SPICE_MSG_DISPLAY_DRAW_BLACKNESS : 306,
SPICE_MSG_DISPLAY_DRAW_WHITENESS : 307,
SPICE_MSG_DISPLAY_DRAW_INVERS : 308,
SPICE_MSG_DISPLAY_DRAW_ROP3 : 309,
SPICE_MSG_DISPLAY_DRAW_STROKE : 310,
SPICE_MSG_DISPLAY_DRAW_TEXT : 311,
SPICE_MSG_DISPLAY_DRAW_TRANSPARENT : 312,
SPICE_MSG_DISPLAY_DRAW_ALPHA_BLEND : 313,
SPICE_MSG_DISPLAY_SURFACE_CREATE : 314,
SPICE_MSG_DISPLAY_SURFACE_DESTROY : 315,
SPICE_MSG_DISPLAY_STREAM_DATA_SIZED : 316,
SPICE_MSG_DISPLAY_MONITORS_CONFIG : 317,
SPICE_MSG_DISPLAY_DRAW_COMPOSITE : 318,
SPICE_MSG_DISPLAY_STREAM_ACTIVATE_REPORT : 319,
SPICE_MSGC_DISPLAY_INIT : 101,
SPICE_MSGC_DISPLAY_STREAM_REPORT : 102,
SPICE_MSG_INPUTS_INIT : 101,
SPICE_MSG_INPUTS_KEY_MODIFIERS : 102,
SPICE_MSG_INPUTS_MOUSE_MOTION_ACK : 111,
SPICE_MSGC_INPUTS_KEY_DOWN : 101,
SPICE_MSGC_INPUTS_KEY_UP : 102,
SPICE_MSGC_INPUTS_KEY_MODIFIERS : 103,
SPICE_MSGC_INPUTS_MOUSE_MOTION : 111,
SPICE_MSGC_INPUTS_MOUSE_POSITION : 112,
SPICE_MSGC_INPUTS_MOUSE_PRESS : 113,
SPICE_MSGC_INPUTS_MOUSE_RELEASE : 114,
SPICE_MSG_CURSOR_INIT : 101,
SPICE_MSG_CURSOR_RESET : 102,
SPICE_MSG_CURSOR_SET : 103,
SPICE_MSG_CURSOR_MOVE : 104,
SPICE_MSG_CURSOR_HIDE : 105,
SPICE_MSG_CURSOR_TRAIL : 106,
SPICE_MSG_CURSOR_INVAL_ONE : 107,
SPICE_MSG_CURSOR_INVAL_ALL : 108,
SPICE_MSG_PLAYBACK_DATA : 101,
SPICE_MSG_PLAYBACK_MODE : 102,
SPICE_MSG_PLAYBACK_START : 103,
SPICE_MSG_PLAYBACK_STOP : 104,
SPICE_MSG_PLAYBACK_VOLUME : 105,
SPICE_MSG_PLAYBACK_MUTE : 106,
SPICE_MSG_PLAYBACK_LATENCY : 107,
SPICE_MSG_SPICEVMC_DATA : 101,
SPICE_MSG_PORT_INIT : 201,
SPICE_MSG_PORT_EVENT : 202,
SPICE_MSG_END_PORT : 203,
SPICE_MSGC_SPICEVMC_DATA : 101,
SPICE_MSGC_PORT_EVENT : 201,
SPICE_MSGC_END_PORT : 202,
SPICE_PLAYBACK_CAP_CELT_0_5_1 : 0,
SPICE_PLAYBACK_CAP_VOLUME : 1,
SPICE_PLAYBACK_CAP_LATENCY : 2,
SPICE_PLAYBACK_CAP_OPUS : 3,
SPICE_MAIN_CAP_SEMI_SEAMLESS_MIGRATE : 0,
SPICE_MAIN_CAP_NAME_AND_UUID : 1,
SPICE_MAIN_CAP_AGENT_CONNECTED_TOKENS : 2,
SPICE_MAIN_CAP_SEAMLESS_MIGRATE : 3,
SPICE_DISPLAY_CAP_SIZED_STREAM : 0,
SPICE_DISPLAY_CAP_MONITORS_CONFIG : 1,
SPICE_DISPLAY_CAP_COMPOSITE : 2,
SPICE_DISPLAY_CAP_A8_SURFACE : 3,
SPICE_DISPLAY_CAP_STREAM_REPORT : 4,
SPICE_DISPLAY_CAP_LZ4_COMPRESSION : 5,
SPICE_DISPLAY_CAP_PREF_COMPRESSION : 6,
SPICE_DISPLAY_CAP_GL_SCANOUT : 7,
SPICE_DISPLAY_CAP_MULTI_CODEC : 8,
SPICE_DISPLAY_CAP_CODEC_MJPEG : 9,
SPICE_DISPLAY_CAP_CODEC_VP8 : 10,
SPICE_AUDIO_DATA_MODE_INVALID : 0,
SPICE_AUDIO_DATA_MODE_RAW : 1,
SPICE_AUDIO_DATA_MODE_CELT_0_5_1 : 2,
SPICE_AUDIO_DATA_MODE_OPUS : 3,
SPICE_AUDIO_FMT_INVALID : 0,
SPICE_AUDIO_FMT_S16 : 1,
SPICE_CHANNEL_MAIN : 1,
SPICE_CHANNEL_DISPLAY : 2,
SPICE_CHANNEL_INPUTS : 3,
SPICE_CHANNEL_CURSOR : 4,
SPICE_CHANNEL_PLAYBACK : 5,
SPICE_CHANNEL_RECORD : 6,
SPICE_CHANNEL_TUNNEL : 7,
SPICE_CHANNEL_SMARTCARD : 8,
SPICE_CHANNEL_USBREDIR : 9,
SPICE_CHANNEL_PORT : 10,
SPICE_CHANNEL_WEBDAV : 11,
SPICE_SURFACE_FLAGS_PRIMARY : (1 << 0),
SPICE_NOTIFY_SEVERITY_INFO : 0,
SPICE_NOTIFY_SEVERITY_WARN : 1,
SPICE_NOTIFY_SEVERITY_ERROR : 2,
SPICE_MOUSE_MODE_SERVER : (1 << 0),
SPICE_MOUSE_MODE_CLIENT : (1 << 1),
SPICE_MOUSE_MODE_MASK : 0x3,
SPICE_CLIP_TYPE_NONE : 0,
SPICE_CLIP_TYPE_RECTS : 1,
SPICE_IMAGE_SCALE_MODE_INTERPOLATE : 0,
SPICE_IMAGE_SCALE_MODE_NEAREST : 1,
SPICE_IMAGE_TYPE_BITMAP : 0,
SPICE_IMAGE_TYPE_QUIC : 1,
SPICE_IMAGE_TYPE_RESERVED : 2,
SPICE_IMAGE_TYPE_LZ_PLT : 100,
SPICE_IMAGE_TYPE_LZ_RGB : 101,
SPICE_IMAGE_TYPE_GLZ_RGB : 102,
SPICE_IMAGE_TYPE_FROM_CACHE : 103,
SPICE_IMAGE_TYPE_SURFACE : 104,
SPICE_IMAGE_TYPE_JPEG : 105,
SPICE_IMAGE_TYPE_FROM_CACHE_LOSSLESS : 106,
SPICE_IMAGE_TYPE_ZLIB_GLZ_RGB : 107,
SPICE_IMAGE_TYPE_JPEG_ALPHA : 108,
SPICE_IMAGE_FLAGS_CACHE_ME : (1 << 0),
SPICE_IMAGE_FLAGS_HIGH_BITS_SET : (1 << 1),
SPICE_IMAGE_FLAGS_CACHE_REPLACE_ME : (1 << 2),
SPICE_BITMAP_FLAGS_PAL_CACHE_ME : (1 << 0),
SPICE_BITMAP_FLAGS_PAL_FROM_CACHE : (1 << 1),
SPICE_BITMAP_FLAGS_TOP_DOWN : (1 << 2),
SPICE_BITMAP_FLAGS_MASK : 0x7,
SPICE_BITMAP_FMT_INVALID : 0,
SPICE_BITMAP_FMT_1BIT_LE : 1,
SPICE_BITMAP_FMT_1BIT_BE : 2,
SPICE_BITMAP_FMT_4BIT_LE : 3,
SPICE_BITMAP_FMT_4BIT_BE : 4,
SPICE_BITMAP_FMT_8BIT : 5,
SPICE_BITMAP_FMT_16BIT : 6,
SPICE_BITMAP_FMT_24BIT : 7,
SPICE_BITMAP_FMT_32BIT : 8,
SPICE_BITMAP_FMT_RGBA : 9,
SPICE_CURSOR_FLAGS_NONE : (1 << 0),
SPICE_CURSOR_FLAGS_CACHE_ME : (1 << 1),
SPICE_CURSOR_FLAGS_FROM_CACHE : (1 << 2),
SPICE_CURSOR_FLAGS_MASK : 0x7,
SPICE_MOUSE_BUTTON_MASK_LEFT : (1 << 0),
SPICE_MOUSE_BUTTON_MASK_MIDDLE : (1 << 1),
SPICE_MOUSE_BUTTON_MASK_RIGHT : (1 << 2),
SPICE_MOUSE_BUTTON_MASK_MASK : 0x7,
SPICE_MOUSE_BUTTON_INVALID : 0,
SPICE_MOUSE_BUTTON_LEFT : 1,
SPICE_MOUSE_BUTTON_MIDDLE : 2,
SPICE_MOUSE_BUTTON_RIGHT : 3,
SPICE_MOUSE_BUTTON_UP : 4,
SPICE_MOUSE_BUTTON_DOWN : 5,
SPICE_BRUSH_TYPE_NONE : 0,
SPICE_BRUSH_TYPE_SOLID : 1,
SPICE_BRUSH_TYPE_PATTERN : 2,
SPICE_SURFACE_FMT_INVALID : 0,
SPICE_SURFACE_FMT_1_A : 1,
SPICE_SURFACE_FMT_8_A : 8,
SPICE_SURFACE_FMT_16_555 : 16,
SPICE_SURFACE_FMT_32_xRGB : 32,
SPICE_SURFACE_FMT_16_565 : 80,
SPICE_SURFACE_FMT_32_ARGB : 96,
SPICE_ROPD_INVERS_SRC : (1 << 0),
SPICE_ROPD_INVERS_BRUSH : (1 << 1),
SPICE_ROPD_INVERS_DEST : (1 << 2),
SPICE_ROPD_OP_PUT : (1 << 3),
SPICE_ROPD_OP_OR : (1 << 4),
SPICE_ROPD_OP_AND : (1 << 5),
SPICE_ROPD_OP_XOR : (1 << 6),
SPICE_ROPD_OP_BLACKNESS : (1 << 7),
SPICE_ROPD_OP_WHITENESS : (1 << 8),
SPICE_ROPD_OP_INVERS : (1 << 9),
SPICE_ROPD_INVERS_RES : (1 << 10),
SPICE_ROPD_MASK : 0x7ff,
LZ_IMAGE_TYPE_INVALID : 0,
LZ_IMAGE_TYPE_PLT1_LE : 1,
LZ_IMAGE_TYPE_PLT1_BE : 2, // PLT stands for palette
LZ_IMAGE_TYPE_PLT4_LE : 3,
LZ_IMAGE_TYPE_PLT4_BE : 4,
LZ_IMAGE_TYPE_PLT8 : 5,
LZ_IMAGE_TYPE_RGB16 : 6,
LZ_IMAGE_TYPE_RGB24 : 7,
LZ_IMAGE_TYPE_RGB32 : 8,
LZ_IMAGE_TYPE_RGBA : 9,
LZ_IMAGE_TYPE_XXXA : 10,
SPICE_INPUT_MOTION_ACK_BUNCH : 4,
SPICE_CURSOR_TYPE_ALPHA : 0,
SPICE_CURSOR_TYPE_MONO : 1,
SPICE_CURSOR_TYPE_COLOR4 : 2,
SPICE_CURSOR_TYPE_COLOR8 : 3,
SPICE_CURSOR_TYPE_COLOR16 : 4,
SPICE_CURSOR_TYPE_COLOR24 : 5,
SPICE_CURSOR_TYPE_COLOR32 : 6,
SPICE_VIDEO_CODEC_TYPE_MJPEG : 1,
SPICE_VIDEO_CODEC_TYPE_VP8 : 2,
SPICE_STREAM_FLAGS_TOP_DOWN : (1 << 0),
VD_AGENT_PROTOCOL : 1,
VD_AGENT_MAX_DATA_SIZE : 2048,
VD_AGENT_MOUSE_STATE : 1,
VD_AGENT_MONITORS_CONFIG : 2,
VD_AGENT_REPLY : 3,
VD_AGENT_CLIPBOARD : 4,
VD_AGENT_DISPLAY_CONFIG : 5,
VD_AGENT_ANNOUNCE_CAPABILITIES : 6,
VD_AGENT_CLIPBOARD_GRAB : 7,
VD_AGENT_CLIPBOARD_REQUEST : 8,
VD_AGENT_CLIPBOARD_RELEASE : 9,
VD_AGENT_FILE_XFER_START :10,
VD_AGENT_FILE_XFER_STATUS :11,
VD_AGENT_FILE_XFER_DATA :12,
VD_AGENT_CLIENT_DISCONNECTED :13,
VD_AGENT_MAX_CLIPBOARD :14,
VD_AGENT_CAP_MOUSE_STATE : 0,
VD_AGENT_CAP_MONITORS_CONFIG : 1,
VD_AGENT_CAP_REPLY : 2,
VD_AGENT_CAP_CLIPBOARD : 3,
VD_AGENT_CAP_DISPLAY_CONFIG : 4,
VD_AGENT_CAP_CLIPBOARD_BY_DEMAND : 5,
VD_AGENT_CAP_CLIPBOARD_SELECTION : 6,
VD_AGENT_CAP_SPARSE_MONITORS_CONFIG : 7,
VD_AGENT_CAP_GUEST_LINEEND_LF : 8,
VD_AGENT_CAP_GUEST_LINEEND_CRLF : 9,
VD_AGENT_CAP_MAX_CLIPBOARD : 10,
VD_AGENT_END_CAP : 11,
VD_AGENT_FILE_XFER_STATUS_CAN_SEND_DATA : 0,
VD_AGENT_FILE_XFER_STATUS_CANCELLED : 1,
VD_AGENT_FILE_XFER_STATUS_ERROR : 2,
VD_AGENT_FILE_XFER_STATUS_SUCCESS : 3,
VD_AGENT_CLIPBOARD_NONE : 0,
VD_AGENT_CLIPBOARD_UTF8_TEXT : 1,
VD_AGENT_CLIPBOARD_IMAGE_PNG : 2,
VD_AGENT_CLIPBOARD_IMAGE_BMP : 3,
VD_AGENT_CLIPBOARD_IMAGE_TIFF : 4,
VD_AGENT_CLIPBOARD_IMAGE_JPG : 5,
};
+94
View File
@@ -0,0 +1,94 @@
"use strict";
/*
Copyright (C) 2014 Red Hat, Inc.
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
function SpiceFileXferTask(id, file)
{
this.id = id;
this.file = file;
}
SpiceFileXferTask.prototype.create_progressbar = function()
{
var _this = this;
var cancel = document.createElement("input");
this.progressbar_container = document.createElement("div");
this.progressbar = document.createElement("progress");
cancel.type = 'button';
cancel.value = 'Cancel';
cancel.style.float = 'right';
cancel.onclick = function()
{
_this.cancelled = true;
_this.remove_progressbar();
};
this.progressbar.setAttribute('max', this.file.size);
this.progressbar.setAttribute('value', 0);
this.progressbar.style.width = '100%';
this.progressbar.style.margin = '4px auto';
this.progressbar.style.display = 'inline-block';
this.progressbar_container.style.width = '90%';
this.progressbar_container.style.margin = 'auto';
this.progressbar_container.style.padding = '4px';
this.progressbar_container.textContent = this.file.name;
this.progressbar_container.appendChild(cancel);
this.progressbar_container.appendChild(this.progressbar);
document.getElementById('spice-xfer-area').appendChild(this.progressbar_container);
}
SpiceFileXferTask.prototype.update_progressbar = function(value)
{
this.progressbar.setAttribute('value', value);
}
SpiceFileXferTask.prototype.remove_progressbar = function()
{
if (this.progressbar_container && this.progressbar_container.parentNode)
this.progressbar_container.parentNode.removeChild(this.progressbar_container);
}
function handle_file_dragover(e)
{
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}
function handle_file_drop(e)
{
var sc = window.spice_connection;
var files = e.dataTransfer.files;
e.stopPropagation();
e.preventDefault();
for (var i = files.length - 1; i >= 0; i--)
{
if (files[i].type) // do not copy a directory
sc.file_xfer_start(files[i]);
}
}
export {
SpiceFileXferTask,
handle_file_dragover,
handle_file_drop,
};
+504
View File
@@ -0,0 +1,504 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import * as Messages from './spicemsg.js';
import { Constants } from './enums.js';
import { KeyNames } from './atKeynames.js';
import { SpiceConn } from './spiceconn.js';
import { DEBUG } from './utils.js';
import { code_to_scancode } from './code_to_scancode.js';
/*----------------------------------------------------------------------------
** Modifier Keystates
** These need to be tracked because focus in and out can get the keyboard
** out of sync.
**------------------------------------------------------------------------*/
var Shift_state = -1;
var Ctrl_state = -1;
var Alt_state = -1;
var Meta_state = -1;
/* Extended (0xE0-prefixed) scancodes for the Meta/Super keys, matching
the values in the scancode maps (utils.js / code_to_scancode.js). */
var META_L_SCAN = 0xE0 | (0x5B << 8);
var META_R_SCAN = 0xE0 | (0x5C << 8);
/*----------------------------------------------------------------------------
** SpiceInputsConn
** Drive the Spice Inputs channel (e.g. mouse + keyboard)
**--------------------------------------------------------------------------*/
function SpiceInputsConn()
{
SpiceConn.apply(this, arguments);
this.mousex = undefined;
this.mousey = undefined;
this.button_state = 0;
this.waiting_for_ack = 0;
/* Modifier tracking is module state; a page that tears down one
connection and creates another must not inherit the previous
session's held keys. */
Shift_state = Ctrl_state = Alt_state = Meta_state = -1;
}
SpiceInputsConn.prototype = Object.create(SpiceConn.prototype);
SpiceInputsConn.prototype.process_channel_message = function(msg)
{
if (msg.type == Constants.SPICE_MSG_INPUTS_INIT)
{
var inputs_init = new Messages.SpiceMsgInputsInit(msg.data);
this.keyboard_modifiers = inputs_init.keyboard_modifiers;
DEBUG > 1 && console.log("MsgInputsInit - modifier " + this.keyboard_modifiers);
// FIXME - We don't do anything with the keyboard modifiers...
return true;
}
if (msg.type == Constants.SPICE_MSG_INPUTS_KEY_MODIFIERS)
{
var key = new Messages.SpiceMsgInputsKeyModifiers(msg.data);
this.keyboard_modifiers = key.keyboard_modifiers;
DEBUG > 1 && console.log("MsgInputsKeyModifiers - modifier " + this.keyboard_modifiers);
// FIXME - We don't do anything with the keyboard modifiers...
return true;
}
if (msg.type == Constants.SPICE_MSG_INPUTS_MOUSE_MOTION_ACK)
{
DEBUG > 1 && console.log("mouse motion ack");
this.waiting_for_ack -= Constants.SPICE_INPUT_MOTION_ACK_BUNCH;
return true;
}
return false;
}
function handle_mousemove(e)
{
/* Only build the message once we know it will be sent; mousemove can
fire hundreds of times a second and the discarded-motion path was
paying for two allocations and a serialize per event. */
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
{
if (this.sc.inputs.waiting_for_ack < (2 * Constants.SPICE_INPUT_MOTION_ACK_BUNCH))
{
var msg = new Messages.SpiceMiniData();
var move;
if (this.sc.mouse_mode == Constants.SPICE_MOUSE_MODE_CLIENT)
{
move = new Messages.SpiceMsgcMousePosition(this.sc, e)
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_POSITION, move);
}
else
{
move = new Messages.SpiceMsgcMouseMotion(this.sc, e)
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_MOTION, move);
}
this.sc.inputs.send_msg(msg);
this.sc.inputs.waiting_for_ack++;
}
else
{
DEBUG > 0 && this.sc.log_info("Discarding mouse motion");
}
}
if (this.sc && this.sc.cursor && this.sc.cursor.spice_simulated_cursor)
{
/* The image sits inside the screen element, so it is placed in
that element's own coordinates: the pointer's position within
its box, undone for any CSS scale on it. Page coordinates put
it off by the screen's offset, and by the scale, on any page
that does not draw the screen at the top-left corner. */
var sim = this.sc.cursor.spice_simulated_cursor;
var screen = sim.spice_screen;
var rect = screen.getBoundingClientRect();
var scale_x = screen.offsetWidth ? rect.width / screen.offsetWidth : 1;
var scale_y = screen.offsetHeight ? rect.height / screen.offsetHeight : 1;
sim.style.display = 'block';
sim.style.left = (e.clientX - rect.left) / scale_x - sim.spice_hot_x + 'px';
sim.style.top = (e.clientY - rect.top) / scale_y - sim.spice_hot_y + 'px';
e.preventDefault();
}
}
function handle_mousedown(e)
{
var press = new Messages.SpiceMsgcMousePress(this.sc, e)
var msg = new Messages.SpiceMiniData();
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_PRESS, press);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
e.preventDefault();
}
function handle_contextmenu(e)
{
e.preventDefault();
return false;
}
function handle_mouseup(e)
{
var release = new Messages.SpiceMsgcMouseRelease(this.sc, e)
var msg = new Messages.SpiceMiniData();
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_RELEASE, release);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
e.preventDefault();
}
function handle_mousewheel(e)
{
var press = new Messages.SpiceMsgcMousePress;
var release = new Messages.SpiceMsgcMouseRelease;
if (e.deltaY < 0)
press.button = release.button = Constants.SPICE_MOUSE_BUTTON_UP;
else
press.button = release.button = Constants.SPICE_MOUSE_BUTTON_DOWN;
press.buttons_state = 0;
release.buttons_state = 0;
var msg = new Messages.SpiceMiniData();
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_PRESS, press);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
msg.build_msg(Constants.SPICE_MSGC_INPUTS_MOUSE_RELEASE, release);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
e.preventDefault();
}
function handle_keydown(e)
{
var key = new Messages.SpiceMsgcKeyDown(e)
var msg = new Messages.SpiceMiniData();
check_and_update_modifiers(e, key.code, this.sc);
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_DOWN, key);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
e.preventDefault();
}
function handle_keyup(e)
{
var key = new Messages.SpiceMsgcKeyUp(e)
var msg = new Messages.SpiceMiniData();
check_and_update_modifiers(e, key.code, this.sc);
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_UP, key);
if (this.sc && this.sc.inputs && this.sc.inputs.state === "ready")
this.sc.inputs.send_msg(msg);
e.preventDefault();
}
function sendCtrlAltDel(sc)
{
if (sc && sc.inputs && sc.inputs.state === "ready"){
var key = new Messages.SpiceMsgcKeyDown();
var msg = new Messages.SpiceMiniData();
update_modifier(true, KeyNames.KEY_LCtrl, sc);
update_modifier(true, KeyNames.KEY_Alt, sc);
key.code = KeyNames.KEY_KP_Decimal;
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_DOWN, key);
sc.inputs.send_msg(msg);
/* The server forwards scancode bytes verbatim, so the release must
carry the break bit itself, as keycode_to_end_scan does. */
key.code = 0x80 | KeyNames.KEY_KP_Decimal;
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_UP, key);
sc.inputs.send_msg(msg);
/* Release unless the key is positively known to be held: the state
starts as the -1 sentinel (no key seen yet), and -1 == false is
false, so testing against false left the synthetic Ctrl+Alt held
in the guest whenever this ran before the first real keydown. */
if(Ctrl_state !== true) update_modifier(false, KeyNames.KEY_LCtrl, sc);
if(Alt_state !== true) update_modifier(false, KeyNames.KEY_Alt, sc);
}
}
function update_modifier(state, code, sc)
{
var msg = new Messages.SpiceMiniData();
if (!state)
{
var key = new Messages.SpiceMsgcKeyUp()
/* Extended (two-byte) scancodes carry the break bit in their second
byte, as keycode_to_end_scan does; 0x80 would land in the 0xE0
prefix and corrupt it. */
key.code = code < 0x100 ? (0x80|code) : (0x8000|code);
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_UP, key);
}
else
{
var key = new Messages.SpiceMsgcKeyDown()
key.code = code;
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_DOWN, key);
}
sc.inputs.send_msg(msg);
}
function check_and_update_modifiers(e, code, sc)
{
if (Shift_state === -1)
{
Shift_state = e.shiftKey;
Ctrl_state = e.ctrlKey;
Alt_state = e.altKey;
Meta_state = e.metaKey;
}
if (code === KeyNames.KEY_ShiftL)
Shift_state = true;
else if (code === KeyNames.KEY_Alt)
Alt_state = true;
else if (code === KeyNames.KEY_LCtrl)
Ctrl_state = true;
else if (code === META_L_SCAN || code === META_R_SCAN)
Meta_state = true;
else if (code === (0x80|KeyNames.KEY_ShiftL))
Shift_state = false;
else if (code === (0x80|KeyNames.KEY_Alt))
Alt_state = false;
else if (code === (0x80|KeyNames.KEY_LCtrl))
Ctrl_state = false;
else if (code === (0x8000|META_L_SCAN) || code === (0x8000|META_R_SCAN))
Meta_state = false;
if (sc && sc.inputs && sc.inputs.state === "ready")
{
if (Shift_state != e.shiftKey)
{
console.log("Shift state out of sync");
update_modifier(e.shiftKey, KeyNames.KEY_ShiftL, sc);
Shift_state = e.shiftKey;
}
if (Alt_state != e.altKey)
{
console.log("Alt state out of sync");
update_modifier(e.altKey, KeyNames.KEY_Alt, sc);
Alt_state = e.altKey;
}
if (Ctrl_state != e.ctrlKey)
{
console.log("Ctrl state out of sync");
update_modifier(e.ctrlKey, KeyNames.KEY_LCtrl, sc);
Ctrl_state = e.ctrlKey;
}
if (Meta_state != e.metaKey)
{
console.log("Meta state out of sync");
update_modifier(e.metaKey, META_L_SCAN, sc);
Meta_state = e.metaKey;
}
}
}
/*----------------------------------------------------------------------------
** typeText
** Deliver a string to the guest as synthetic keystrokes on the inputs
** channel. The inputs channel speaks PC scancodes — positions on a physical
** keyboard, not characters — so this maps each character to the key that
** produces it on a US layout. A guest configured for another keymap will
** type different characters, and anything a US layout cannot produce with
** at most Shift (AltGr combinations, dead keys, non-ASCII) cannot be
** expressed at all; such characters are skipped and reported back.
**--------------------------------------------------------------------------*/
/* character → [KeyboardEvent.code, needs-shift] on a US layout. */
var US_TYPEABLE = (function ()
{
var map = {};
var i;
var letters = "abcdefghijklmnopqrstuvwxyz";
for (i = 0; i < letters.length; i++)
{
var code = "Key" + letters[i].toUpperCase();
map[letters[i]] = [code, false];
map[letters[i].toUpperCase()] = [code, true];
}
var digits = "1234567890";
var shifted_digits = "!@#$%^&*()";
for (i = 0; i < digits.length; i++)
{
map[digits[i]] = ["Digit" + digits[i], false];
map[shifted_digits[i]] = ["Digit" + digits[i], true];
}
var punctuation = [
["-", "_", "Minus"],
["=", "+", "Equal"],
["[", "{", "BracketLeft"],
["]", "}", "BracketRight"],
["\\", "|", "Backslash"],
[";", ":", "Semicolon"],
["'", "\"", "Quote"],
[",", "<", "Comma"],
[".", ">", "Period"],
["/", "?", "Slash"],
["`", "~", "Backquote"],
];
for (i = 0; i < punctuation.length; i++)
{
map[punctuation[i][0]] = [punctuation[i][2], false];
map[punctuation[i][1]] = [punctuation[i][2], true];
}
map[" "] = ["Space", false];
map["\n"] = ["Enter", false];
map["\t"] = ["Tab", false];
return map;
})();
function send_scancode(sc, scancode, down)
{
var msg = new Messages.SpiceMiniData();
var key;
if (down)
{
key = new Messages.SpiceMsgcKeyDown();
key.code = scancode;
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_DOWN, key);
}
else
{
key = new Messages.SpiceMsgcKeyUp();
/* Break code; every key this file types is a one-byte scancode. */
key.code = 0x80 | scancode;
msg.build_msg(Constants.SPICE_MSGC_INPUTS_KEY_UP, key);
}
sc.inputs.send_msg(msg);
}
/* A keystroke is a press and a release separated by time. Sending both in
the same tick, as this once did, makes a guest drop characters: Windows in
particular discards a key whose break code arrives in the same instant as
its make code, and the loss is silent and intermittent — a pasted URL or
password arrives subtly wrong. So hold each key down, and give Shift its
own settle time either side, before moving on. */
var KEY_HOLD_MS = 12;
var SHIFT_SETTLE_MS = 12;
/* A server-side close leaves the channel's state at "ready", since the
close handler only reports; the socket itself says whether keystrokes
can still reach the guest. */
function inputs_live(sc)
{
return sc && sc.inputs && sc.inputs.state === "ready" &&
sc.inputs.ws && sc.inputs.ws.readyState === WebSocket.OPEN;
}
/* Resolves to { typed, skipped, aborted }: how many characters went out,
which distinct characters had no US-layout key, and whether the inputs
channel died mid-string. delay_ms is the gap between characters, which
paces a large paste so a guest's keyboard buffer is not flooded. */
function typeText(sc, text, delay_ms)
{
var delay = typeof delay_ms === 'number' ? delay_ms : 25;
/* A CRLF must land as a single Enter, not Enter twice. */
var chars = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var skipped = [];
var typed = 0;
var at = 0;
return new Promise(function (resolve)
{
function step()
{
if (! inputs_live(sc))
{
resolve({ typed: typed, skipped: skipped, aborted: at < chars.length });
return;
}
if (at >= chars.length)
{
resolve({ typed: typed, skipped: skipped, aborted: false });
return;
}
var ch = chars[at++];
var entry = US_TYPEABLE[ch];
var scancode = entry && code_to_scancode[entry[0]];
if (!scancode)
{
if (skipped.indexOf(ch) === -1)
skipped.push(ch);
step();
return;
}
/* Each phase is [what to send, how long to wait after it], run in
order; the guest sees a press, a hold, and a release. */
var shifted = entry[1];
var phases = [];
if (shifted)
phases.push([function () { send_scancode(sc, KeyNames.KEY_ShiftL, true); }, SHIFT_SETTLE_MS]);
phases.push([function () { send_scancode(sc, scancode, true); }, KEY_HOLD_MS]);
phases.push([function () { send_scancode(sc, scancode, false); }, shifted ? SHIFT_SETTLE_MS : delay]);
if (shifted)
phases.push([function () { send_scancode(sc, KeyNames.KEY_ShiftL, false); }, delay]);
typed++;
var phase = 0;
(function run()
{
if (phase >= phases.length)
{
step();
return;
}
/* The channel can die mid-character; stop rather than send a
press whose release will never follow. */
if (!(sc && sc.inputs && sc.inputs.state === "ready"))
{
resolve({ typed: typed - 1, skipped: skipped, aborted: true });
return;
}
var current = phases[phase++];
current[0]();
window.setTimeout(run, current[1]);
})();
}
step();
});
}
export {
SpiceInputsConn,
handle_mousemove,
handle_mousedown,
handle_contextmenu,
handle_mouseup,
handle_mousewheel,
handle_keydown,
handle_keyup,
sendCtrlAltDel,
typeText,
};
+181
View File
@@ -0,0 +1,181 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import { Constants } from './enums.js';
/*----------------------------------------------------------------------------
** lz.js
** Functions for handling SPICE_IMAGE_TYPE_LZ_RGB
** Adapted from lz.c .
**--------------------------------------------------------------------------*/
function lz_rgb32_decompress(in_buf, at, out_buf, type, default_alpha)
{
var encoder = at;
var op = 0;
var ctrl;
var i = 0;
for (ctrl = in_buf[encoder++]; (op * 4) < out_buf.length; ctrl = in_buf[encoder++])
{
var ref = op;
var len = ctrl >> 5;
var ofs = (ctrl & 31) << 8;
if (ctrl >= 32) {
var code;
len--;
if (len == 7 - 1) {
do {
code = in_buf[encoder++];
len += code;
} while (code == 255);
}
code = in_buf[encoder++];
ofs += code;
if (code == 255) {
if ((ofs - code) == (31 << 8)) {
ofs = in_buf[encoder++] << 8;
ofs += in_buf[encoder++];
ofs += 8191;
}
}
len += 1;
if (type == Constants.LZ_IMAGE_TYPE_RGBA)
len += 2;
ofs += 1;
ref -= ofs;
if (ref == (op - 1)) {
var b = ref;
for (; len; --len) {
if (type == Constants.LZ_IMAGE_TYPE_RGBA)
{
out_buf[(op*4) + 3] = out_buf[(b*4)+3];
}
else
{
for (i = 0; i < 4; i++)
out_buf[(op*4) + i] = out_buf[(b*4)+i];
}
op++;
}
} else {
for (; len; --len) {
if (type == Constants.LZ_IMAGE_TYPE_RGBA)
{
out_buf[(op*4) + 3] = out_buf[(ref*4)+3];
}
else
{
for (i = 0; i < 4; i++)
out_buf[(op*4) + i] = out_buf[(ref*4)+i];
}
op++; ref++;
}
}
} else {
ctrl++;
if (type == Constants.LZ_IMAGE_TYPE_RGBA)
{
out_buf[(op*4) + 3] = in_buf[encoder++];
}
else
{
out_buf[(op*4) + 0] = in_buf[encoder + 2];
out_buf[(op*4) + 1] = in_buf[encoder + 1];
out_buf[(op*4) + 2] = in_buf[encoder + 0];
if (default_alpha)
out_buf[(op*4) + 3] = 255;
encoder += 3;
}
op++;
for (--ctrl; ctrl; ctrl--) {
if (type == Constants.LZ_IMAGE_TYPE_RGBA)
{
out_buf[(op*4) + 3] = in_buf[encoder++];
}
else
{
out_buf[(op*4) + 0] = in_buf[encoder + 2];
out_buf[(op*4) + 1] = in_buf[encoder + 1];
out_buf[(op*4) + 2] = in_buf[encoder + 0];
if (default_alpha)
out_buf[(op*4) + 3] = 255;
encoder += 3;
}
op++;
}
}
}
return encoder - 1;
}
function flip_image_data(img)
{
var wb = img.width * 4;
var h = img.height;
var temp_h = h;
var buff = new Uint8Array(img.width * img.height * 4);
while (temp_h--)
{
buff.set(img.data.subarray(temp_h * wb, (temp_h + 1) * wb), (h - temp_h - 1) * wb);
}
img.data.set(buff);
}
function convert_spice_lz_to_web(context, lz_image)
{
var at;
if (lz_image.type === Constants.LZ_IMAGE_TYPE_RGB32 || lz_image.type === Constants.LZ_IMAGE_TYPE_RGBA)
{
var u8 = new Uint8Array(lz_image.data);
var ret = context.createImageData(lz_image.width, lz_image.height);
at = lz_rgb32_decompress(u8, 0, ret.data, Constants.LZ_IMAGE_TYPE_RGB32, lz_image.type != Constants.LZ_IMAGE_TYPE_RGBA);
if (!lz_image.top_down)
flip_image_data(ret);
if (lz_image.type == Constants.LZ_IMAGE_TYPE_RGBA)
lz_rgb32_decompress(u8, at, ret.data, Constants.LZ_IMAGE_TYPE_RGBA, false);
}
else if (lz_image.type === Constants.LZ_IMAGE_TYPE_XXXA)
{
var u8 = new Uint8Array(lz_image.data);
var ret = context.createImageData(lz_image.width, lz_image.height);
lz_rgb32_decompress(u8, 0, ret.data, Constants.LZ_IMAGE_TYPE_RGBA, false);
}
else
return undefined;
return ret;
}
export {
convert_spice_lz_to_web,
};
+9
View File
@@ -0,0 +1,9 @@
// Types for what Ham Lab uses of the vendored spice-html5 (plain JavaScript beside this file).
export class SpiceMainConn {
constructor(opts: { uri: string; screen_id: string; password?: string; message_id?: string; dump_id?: string; onerror?: (e: Event | Error) => void; onsuccess?: () => void; onagent?: (sc: SpiceMainConn) => void })
stop(msg?: string): void
agent_connected?: boolean
}
export function resize_helper(sc: SpiceMainConn): void
export function handle_resize(e?: Event): void
export function sendCtrlAltDel(sc: SpiceMainConn): void
+669
View File
@@ -0,0 +1,669 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import * as Messages from './spicemsg.js';
import { Constants } from './enums.js';
import { SpiceCursorConn } from './cursor.js';
import { SpiceConn } from './spiceconn.js';
import { DEBUG } from './utils.js';
import { SpiceFileXferTask } from './filexfer.js';
import { SpiceInputsConn, sendCtrlAltDel, typeText } from './inputs.js';
import { SpiceDisplayConn } from './display.js';
import { SpicePlaybackConn } from './playback.js';
import { SpicePortConn } from './port.js';
import { handle_file_dragover, handle_file_drop } from './filexfer.js';
import { resize_helper, handle_resize } from './resize.js';
/*----------------------------------------------------------------------------
** SpiceMainConn
** This is the master Javascript class for establishing and
** managing a connection to a Spice Server.
**
** Invocation: You must pass an object with properties as follows:
** uri (required) Uri of a WebSocket listener that is
** connected to a spice server.
** password (required) Password to send to the spice server
** message_id (optional) Identifier of an element in the DOM
** where SpiceConn will write messages.
** It will use classes spice-messages-x,
** where x is one of info, warning, or error.
** screen_id (optional) Identifier of an element in the DOM
** where SpiceConn will create any new
** client screens. This is the main UI.
** dump_id (optional) If given, an element to use for
** dumping every single image + canvas drawn.
** Sometimes useful for debugging.
** onerror (optional) If given, a function to receive async
** errors. Note that you should also catch
** errors for ones that occur inline
** onagent (optional) If given, a function to be called when
** a VD agent is connected; a good opportunity
** to request a resize
** onsuccess (optional) If given, a function to be called when the
** session is successfully connected
**
** Throws error if there are troubles. Requires a modern (by 2012 standards)
** browser, including WebSocket and WebSocket.binaryType == arraybuffer
**
**--------------------------------------------------------------------------*/
function SpiceMainConn()
{
if (typeof WebSocket === "undefined")
throw new Error("WebSocket unavailable. You need to use a different browser.");
SpiceConn.apply(this, arguments);
this.agent_msg_queue = [];
this.file_xfer_tasks = {};
this.file_xfer_task_id = 0;
this.file_xfer_read_queue = [];
this.ports = [];
this.agent_caps = [0]
}
SpiceMainConn.prototype = Object.create(SpiceConn.prototype);
SpiceMainConn.prototype.process_channel_message = function(msg)
{
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_BEGIN)
{
this.known_unimplemented(msg.type, "Main Migrate Begin");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_CANCEL)
{
this.known_unimplemented(msg.type, "Main Migrate Cancel");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_INIT)
{
this.log_info("Connected to " + this.ws.url);
this.report_success("Connected")
this.main_init = new Messages.SpiceMsgMainInit(msg.data);
this.connection_id = this.main_init.session_id;
this.agent_tokens = this.main_init.agent_tokens;
if (DEBUG > 0)
{
// FIXME - there is a lot here we don't handle; mouse modes, agent,
// ram_hint, multi_media_time
this.log_info("session id " + this.main_init.session_id +
" ; display_channels_hint " + this.main_init.display_channels_hint +
" ; supported_mouse_modes " + this.main_init.supported_mouse_modes +
" ; current_mouse_mode " + this.main_init.current_mouse_mode +
" ; agent_connected " + this.main_init.agent_connected +
" ; agent_tokens " + this.main_init.agent_tokens +
" ; multi_media_time " + this.main_init.multi_media_time +
" ; ram_hint " + this.main_init.ram_hint);
}
this.our_mm_time = Date.now();
this.mm_time = this.main_init.multi_media_time;
this.handle_mouse_mode(this.main_init.current_mouse_mode,
this.main_init.supported_mouse_modes);
if (this.main_init.agent_connected)
this.connect_agent();
var attach = new Messages.SpiceMiniData;
attach.type = Constants.SPICE_MSGC_MAIN_ATTACH_CHANNELS;
attach.size = attach.buffer_size();
this.send_msg(attach);
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MOUSE_MODE)
{
var mode = new Messages.SpiceMsgMainMouseMode(msg.data);
DEBUG > 0 && this.log_info("Mouse supported modes " + mode.supported_modes + "; current " + mode.current_mode);
this.handle_mouse_mode(mode.current_mode, mode.supported_modes);
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MULTI_MEDIA_TIME)
{
/* The server's multimedia clock. relative_now() estimates it from
the value seeded at INIT plus elapsed wall time, which drifts as
the two clocks diverge, and stream frames are scheduled and
reported against that estimate. This message is the server
resynchronising it. */
var mm = new Messages.SpiceMsgMainMultiMediaTime(msg.data);
this.our_mm_time = Date.now();
this.mm_time = mm.time;
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_CHANNELS_LIST)
{
var i;
var chans;
DEBUG > 0 && console.log("channels");
chans = new Messages.SpiceMsgChannels(msg.data);
for (i = 0; i < chans.channels.length; i++)
{
var conn = {
uri: this.ws.url,
parent: this,
connection_id : this.connection_id,
type : chans.channels[i].type,
chan_id : chans.channels[i].id
};
if (chans.channels[i].type == Constants.SPICE_CHANNEL_DISPLAY)
{
if (chans.channels[i].id == 0) {
this.display = new SpiceDisplayConn(conn);
} else {
this.log_warn("The spice-html5 client does not handle multiple heads.");
}
}
else if (chans.channels[i].type == Constants.SPICE_CHANNEL_INPUTS)
{
this.inputs = new SpiceInputsConn(conn);
this.inputs.mouse_mode = this.mouse_mode;
}
else if (chans.channels[i].type == Constants.SPICE_CHANNEL_CURSOR)
this.cursor = new SpiceCursorConn(conn);
else if (chans.channels[i].type == Constants.SPICE_CHANNEL_PLAYBACK)
this.playback = new SpicePlaybackConn(conn);
else if (chans.channels[i].type == Constants.SPICE_CHANNEL_PORT)
this.ports.push(new SpicePortConn(conn));
else
{
if (! ("extra_channels" in this))
this.extra_channels = [];
this.extra_channels[i] = new SpiceConn(conn);
this.log_err("Channel type " + this.extra_channels[i].channel_type() + " not implemented");
}
}
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_AGENT_CONNECTED)
{
this.connect_agent();
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_AGENT_CONNECTED_TOKENS)
{
var connected_tokens = new Messages.SpiceMsgMainAgentTokens(msg.data);
this.agent_tokens = connected_tokens.num_tokens;
this.connect_agent();
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_AGENT_TOKEN)
{
var remaining_tokens, tokens = new Messages.SpiceMsgMainAgentTokens(msg.data);
this.agent_tokens += tokens.num_tokens;
this.send_agent_message_queue();
remaining_tokens = this.agent_tokens;
while (remaining_tokens > 0 && this.file_xfer_read_queue.length > 0)
{
var xfer_task = this.file_xfer_read_queue.shift();
this.file_xfer_read(xfer_task, xfer_task.read_bytes);
remaining_tokens--;
}
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_AGENT_DISCONNECTED)
{
this.agent_connected = false;
/* Fail transfers in flight rather than strand them: with the
agent gone their chunks are silently dropped, so they would
never complete, never error, and their progress bars would sit
on screen forever. */
this.agent_msg_queue = [];
this.file_xfer_read_queue = [];
for (var task_id in this.file_xfer_tasks)
this.file_xfer_completed(this.file_xfer_tasks[task_id],
new Error("Agent disconnected; file transfer aborted."));
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_AGENT_DATA)
{
var agent_data = new Messages.SpiceMsgMainAgentData(msg.data);
if (agent_data.type == Constants.VD_AGENT_ANNOUNCE_CAPABILITIES)
{
var agent_caps = new Messages.VDAgentAnnounceCapabilities(agent_data.data);
this.agent_caps = [agent_caps.caps];
if (agent_caps.request)
this.announce_agent_capabilities(0);
return true;
}
else if (agent_data.type == Constants.VD_AGENT_FILE_XFER_STATUS)
{
this.handle_file_xfer_status(new Messages.VDAgentFileXferStatusMessage(agent_data.data));
return true;
}
else if (agent_data.type == Constants.VD_AGENT_CLIPBOARD_GRAB)
{
this.handle_clipboard_grab();
return true;
}
else if (agent_data.type == Constants.VD_AGENT_CLIPBOARD)
{
this.handle_clipboard_receive(agent_data);
return true;
}
else if (agent_data.type == Constants.VD_AGENT_CLIPBOARD_REQUEST)
{
this.handle_clipboard_send();
return true;
}
else if (agent_data.type == Constants.VD_AGENT_CLIPBOARD_RELEASE)
{
// Currently we don't need to do anything when the agent releases the clipboard
return true;
}
/* An agent message we do not act on is still an agent message.
Returning false sent it back as an unhandled main-channel
message, so the console reported "Unknown message type 109"
-- naming the agent-data envelope rather than the thing
inside it, which is the part worth knowing. Name that once
per type instead. */
this.report_unhandled_agent_message(agent_data.type);
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_SWITCH_HOST)
{
this.known_unimplemented(msg.type, "Main Migrate Switch Host");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_END)
{
this.known_unimplemented(msg.type, "Main Migrate End");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_NAME)
{
this.known_unimplemented(msg.type, "Main Name");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_UUID)
{
this.known_unimplemented(msg.type, "Main UUID");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_BEGIN_SEAMLESS)
{
this.known_unimplemented(msg.type, "Main Migrate Begin Seamless");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_DST_SEAMLESS_ACK)
{
this.known_unimplemented(msg.type, "Main Migrate Dst Seamless ACK");
return true;
}
if (msg.type == Constants.SPICE_MSG_MAIN_MIGRATE_DST_SEAMLESS_NACK)
{
this.known_unimplemented(msg.type, "Main Migrate Dst Seamless NACK");
return true;
}
return false;
}
SpiceMainConn.prototype.stop = function(msg)
{
this.state = "closing";
if (this.inputs)
{
this.inputs.cleanup();
this.inputs = undefined;
}
if (this.cursor)
{
this.cursor.cleanup();
this.cursor = undefined;
}
if (this.playback)
{
this.playback.cleanup();
this.playback = undefined;
}
for (var p = 0; p < this.ports.length; p++)
this.ports[p].cleanup();
this.ports = [];
if (this.display)
{
this.display.cleanup();
this.display.destroy_surfaces();
this.display = undefined;
}
this.cleanup();
if ("extra_channels" in this)
for (var e in this.extra_channels)
this.extra_channels[e].cleanup();
this.extra_channels = undefined;
}
SpiceMainConn.prototype.send_agent_message_queue = function(message)
{
if (!this.agent_connected)
return;
if (message)
this.agent_msg_queue.push(message);
while (this.agent_tokens > 0 && this.agent_msg_queue.length > 0)
{
var mr = this.agent_msg_queue.shift();
this.send_msg(mr);
this.agent_tokens--;
}
}
SpiceMainConn.prototype.send_agent_message = function(type, message)
{
var agent_data = new Messages.SpiceMsgcMainAgentData(type, message);
var sb = 0, maxsize = Constants.VD_AGENT_MAX_DATA_SIZE - Messages.SpiceMiniData.prototype.buffer_size();
var data = new ArrayBuffer(agent_data.buffer_size());
agent_data.to_buffer(data);
while (sb < agent_data.buffer_size())
{
var eb = Math.min(sb + maxsize, agent_data.buffer_size());
var mr = new Messages.SpiceMiniData();
mr.type = Constants.SPICE_MSGC_MAIN_AGENT_DATA;
mr.size = eb - sb;
mr.data = data.slice(sb, eb);
this.send_agent_message_queue(mr);
sb = eb;
}
}
SpiceMainConn.prototype.announce_agent_capabilities = function(request)
{
var caps = new Messages.VDAgentAnnounceCapabilities(request, (1 << Constants.VD_AGENT_CAP_MOUSE_STATE) |
(1 << Constants.VD_AGENT_CAP_MONITORS_CONFIG) |
(1 << Constants.VD_AGENT_CAP_REPLY) |
(1 << Constants.VD_AGENT_CAP_CLIPBOARD_SELECTION) |
(1 << Constants.VD_AGENT_CAP_CLIPBOARD_BY_DEMAND));
this.send_agent_message(Constants.VD_AGENT_ANNOUNCE_CAPABILITIES, caps);
}
SpiceMainConn.prototype.resize_window = function(flags, width, height, depth, x, y)
{
var monitors_config = new Messages.VDAgentMonitorsConfig(flags, width, height, depth, x, y);
this.send_agent_message(Constants.VD_AGENT_MONITORS_CONFIG, monitors_config);
}
SpiceMainConn.prototype.file_xfer_start = function(file)
{
var task_id, xfer_start, task;
task_id = this.file_xfer_task_id++;
task = new SpiceFileXferTask(task_id, file);
task.create_progressbar();
this.file_xfer_tasks[task_id] = task;
xfer_start = new Messages.VDAgentFileXferStartMessage(task_id, file.name, file.size);
this.send_agent_message(Constants.VD_AGENT_FILE_XFER_START, xfer_start);
}
SpiceMainConn.prototype.handle_file_xfer_status = function(file_xfer_status)
{
var xfer_error, xfer_task;
if (!this.file_xfer_tasks[file_xfer_status.id])
{
return;
}
xfer_task = this.file_xfer_tasks[file_xfer_status.id];
switch (file_xfer_status.result)
{
case Constants.VD_AGENT_FILE_XFER_STATUS_CAN_SEND_DATA:
this.file_xfer_read(xfer_task);
return;
case Constants.VD_AGENT_FILE_XFER_STATUS_CANCELLED:
xfer_error = "transfer is cancelled by spice agent";
break;
case Constants.VD_AGENT_FILE_XFER_STATUS_ERROR:
xfer_error = "some errors occurred in the spice agent";
break;
case Constants.VD_AGENT_FILE_XFER_STATUS_SUCCESS:
break;
default:
xfer_error = "unhandled status type: " + file_xfer_status.result;
break;
}
this.file_xfer_completed(xfer_task, xfer_error)
}
SpiceMainConn.prototype.file_xfer_read = function(file_xfer_task, start_byte)
{
var FILE_XFER_CHUNK_SIZE = 32 * Constants.VD_AGENT_MAX_DATA_SIZE;
var _this = this;
var sb, eb;
var slice, reader;
if (!file_xfer_task ||
!this.file_xfer_tasks[file_xfer_task.id] ||
(start_byte > 0 && start_byte == file_xfer_task.file.size))
{
return;
}
if (file_xfer_task.cancelled)
{
var xfer_status = new Messages.VDAgentFileXferStatusMessage(file_xfer_task.id,
Constants.VD_AGENT_FILE_XFER_STATUS_CANCELLED);
this.send_agent_message(Constants.VD_AGENT_FILE_XFER_STATUS, xfer_status);
delete this.file_xfer_tasks[file_xfer_task.id];
return;
}
sb = start_byte || 0,
eb = Math.min(sb + FILE_XFER_CHUNK_SIZE, file_xfer_task.file.size);
if (!this.agent_tokens)
{
file_xfer_task.read_bytes = sb;
this.file_xfer_read_queue.push(file_xfer_task);
return;
}
reader = new FileReader();
reader.onload = function(e)
{
var xfer_data = new Messages.VDAgentFileXferDataMessage(file_xfer_task.id,
e.target.result.byteLength,
e.target.result);
_this.send_agent_message(Constants.VD_AGENT_FILE_XFER_DATA, xfer_data);
/* Only recurse while bytes remain. The old code always recursed
and relied on the start_byte > 0 guard above to terminate, which
a zero-byte file never satisfies — it looped forever, burning an
agent token per iteration. */
if (eb < file_xfer_task.file.size)
_this.file_xfer_read(file_xfer_task, eb);
file_xfer_task.update_progressbar(eb);
};
slice = file_xfer_task.file.slice(sb, eb);
reader.readAsArrayBuffer(slice);
}
SpiceMainConn.prototype.file_xfer_completed = function(file_xfer_task, error)
{
if (error)
this.log_err(error);
else
this.log_info("transfer of '" + file_xfer_task.file.name +"' was successful");
file_xfer_task.remove_progressbar();
delete this.file_xfer_tasks[file_xfer_task.id];
}
/* The guest agent sends more than this client acts on -- a reply
acknowledging our capabilities, mouse state under server mouse mode,
monitor and display configuration. None need handling, but each was
arriving as an anonymous "unknown message" on the main channel. */
SpiceMainConn.prototype.report_unhandled_agent_message = function(type)
{
var names = {};
names[Constants.VD_AGENT_MOUSE_STATE] = "Mouse State";
names[Constants.VD_AGENT_MONITORS_CONFIG] = "Monitors Config";
names[Constants.VD_AGENT_REPLY] = "Reply";
names[Constants.VD_AGENT_DISPLAY_CONFIG] = "Display Config";
names[Constants.VD_AGENT_FILE_XFER_START] = "File Xfer Start";
names[Constants.VD_AGENT_FILE_XFER_DATA] = "File Xfer Data";
names[Constants.VD_AGENT_CLIENT_DISCONNECTED] = "Client Disconnected";
names[Constants.VD_AGENT_MAX_CLIPBOARD] = "Max Clipboard";
if (! this.reported_agent_types)
this.reported_agent_types = {};
if (this.reported_agent_types[type])
return;
this.reported_agent_types[type] = true;
this.log_warn("Agent message not handled: " + (names[type] || "type " + type) +
" [ further notices suppressed ]");
}
SpiceMainConn.prototype.handle_clipboard_grab = function()
{
DEBUG > 1 && console.log("handling clipboard grab from agent");
// agent is requesting clipboard grab, so we send a message to request clipboard contents
const type = Constants.VD_AGENT_CLIPBOARD_UTF8_TEXT;
const clipboard_request = new Messages.SpiceMsgClipboardRequest(type, this.agent_caps);
this.send_agent_message(Constants.VD_AGENT_CLIPBOARD_REQUEST, clipboard_request);
}
SpiceMainConn.prototype.handle_clipboard_receive = function(agent_data)
{
DEBUG > 1 && console.log("received clipboard data from agent");
// received clipboard data from agent, copy it to browser clipboard
const received_clipboard = new Messages.SpiceMsgClipboardReceive(agent_data, this.agent_caps);
if (received_clipboard.type === Constants.VD_AGENT_CLIPBOARD_UTF8_TEXT)
{
// write it to the browser clipboard
if (navigator.clipboard && navigator.clipboard.writeText)
{
const text = received_clipboard.get_text();
navigator.clipboard.writeText(text).catch(err => {
console.warn("Failed to write to navigator clipboard:", err);
});
}
}
else
{
console.log("Unsupported clipboard type:", received_clipboard.type);
}
}
SpiceMainConn.prototype.handle_clipboard_send = function()
{
DEBUG > 1 && console.log("sending clipboard data to agent");
// agent is requesting clipboard data, read it from browser clipboard and send it.
if (navigator.clipboard && navigator.clipboard.readText)
{
navigator.clipboard.readText().then(text => {
const type = Constants.VD_AGENT_CLIPBOARD_UTF8_TEXT;
const clipboard_msg = new Messages.SpiceMsgClipboardSend(type, text, this.agent_caps);
this.send_agent_message(Constants.VD_AGENT_CLIPBOARD, clipboard_msg);
}).catch(err => {
console.log("Failed to read clipboard:", err);
});
}
}
SpiceMainConn.prototype.send_clipboard_grab = function()
{
DEBUG > 1 && console.log("browser is asking agent to grab clipboard");
// Send clipboard grab to agent. Agent will then ask for the host os clipboard contents in a dedicated message.
const type = Constants.VD_AGENT_CLIPBOARD_UTF8_TEXT;
const grab_message = new Messages.SpiceMsgClipboardGrab(type, this.agent_caps);
this.send_agent_message(Constants.VD_AGENT_CLIPBOARD_GRAB, grab_message)
}
SpiceMainConn.prototype.connect_agent = function()
{
this.agent_connected = true;
var agent_start = new Messages.SpiceMsgcMainAgentStart(~0);
var mr = new Messages.SpiceMiniData();
mr.build_msg(Constants.SPICE_MSGC_MAIN_AGENT_START, agent_start);
this.send_msg(mr);
this.announce_agent_capabilities(1);
if (this.onagent !== undefined)
this.onagent(this);
}
SpiceMainConn.prototype.handle_mouse_mode = function(current, supported)
{
this.mouse_mode = current;
if (current != Constants.SPICE_MOUSE_MODE_CLIENT && (supported & Constants.SPICE_MOUSE_MODE_CLIENT))
{
var mode_request = new Messages.SpiceMsgcMainMouseModeRequest(Constants.SPICE_MOUSE_MODE_CLIENT);
var mr = new Messages.SpiceMiniData();
mr.build_msg(Constants.SPICE_MSGC_MAIN_MOUSE_MODE_REQUEST, mode_request);
this.send_msg(mr);
}
if (this.inputs)
this.inputs.mouse_mode = current;
}
/* Shift current time to attempt to get a time matching that of the server */
SpiceMainConn.prototype.relative_now = function()
{
var ret = (Date.now() - this.our_mm_time) + this.mm_time;
return ret;
}
export {
SpiceMainConn,
handle_file_dragover,
handle_file_drop,
resize_helper,
handle_resize,
sendCtrlAltDel,
typeText,
};
+432
View File
@@ -0,0 +1,432 @@
"use strict";
/*
Copyright (C) 2014 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** SpicePlaybackConn
** Drive the Spice Playback channel (sound out)
**--------------------------------------------------------------------------*/
import * as Utils from './utils.js';
import * as Webm from './webm.js';
import * as Messages from './spicemsg.js';
import { Constants } from './enums.js';
import { SpiceConn } from './spiceconn.js';
function SpicePlaybackConn()
{
SpiceConn.apply(this, arguments);
this.queue = new Array();
this.append_okay = false;
this.start_time = 0;
}
SpicePlaybackConn.prototype = Object.create(SpiceConn.prototype);
SpicePlaybackConn.prototype.process_channel_message = function(msg)
{
if (!window.MediaSource)
{
this.log_err('MediaSource API is not available');
return false;
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_START)
{
var start = new Messages.SpiceMsgPlaybackStart(msg.data);
Utils.PLAYBACK_DEBUG > 0 && console.log("PlaybackStart; frequency " + start.frequency);
if (start.frequency != Webm.Constants.OPUS_FREQUENCY)
{
this.log_err('This player cannot handle frequency ' + start.frequency);
return false;
}
if (start.channels != Webm.Constants.OPUS_CHANNELS)
{
this.log_err('This player cannot handle ' + start.channels + ' channels');
return false;
}
if (start.format != Constants.SPICE_AUDIO_FMT_S16)
{
this.log_err('This player cannot format ' + start.format);
return false;
}
/* Keyed on the audio element, not source_buffer: source_buffer is
only set asynchronously in handle_source_open, so a second START
arriving before sourceopen would stack a second audio element. */
if (! this.audio)
{
this.media_source = new MediaSource();
this.media_source.spiceconn = this;
this.audio = document.createElement("audio");
this.audio.spiceconn = this;
this.audio.setAttribute('autoplay', true);
this.audio.src = window.URL.createObjectURL(this.media_source);
document.getElementById(this.parent.screen_id).appendChild(this.audio);
this.media_source.addEventListener('sourceopen', handle_source_open, false);
this.media_source.addEventListener('sourceended', handle_source_ended, false);
this.media_source.addEventListener('sourceclosed', handle_source_closed, false);
this.bytes_written = 0;
return true;
}
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_DATA)
{
var data = new Messages.SpiceMsgPlaybackData(msg.data);
if (! this.source_buffer)
return true;
if (this.audio.readyState >= 3 && this.audio.buffered.length > 1 &&
this.audio.currentTime == this.audio.buffered.end(0) &&
this.audio.currentTime < this.audio.buffered.start(this.audio.buffered.length - 1))
{
console.log("Audio underrun: we appear to have fallen behind; advancing to " +
this.audio.buffered.start(this.audio.buffered.length - 1));
this.audio.currentTime = this.audio.buffered.start(this.audio.buffered.length - 1);
}
/* Around version 45, Firefox started being very particular about the
time stamps put into the Opus stream. The time stamps from the Spice server are
somewhat irregular. They mostly arrive every 10 ms, but sometimes it is 11, or sometimes
with two time stamps the same in a row. The previous logic resulted in fuzzy and/or
distorted audio streams in Firefox in a row.
In theory, the sequence mode should be appropriate for us, but as of 09/27/2016,
I was unable to make sequence mode work with Firefox.
Thus, we end up with an inelegant hack. Essentially, we force every packet to have
a 10ms time delta, unless there is an obvious gap in time stream, in which case we
will resync.
*/
if (this.start_time != 0 && data.time != (this.last_data_time + Webm.Constants.EXPECTED_PACKET_DURATION))
{
if (Math.abs(data.time - (Webm.Constants.EXPECTED_PACKET_DURATION + this.last_data_time)) < Webm.Constants.MAX_CLUSTER_TIME)
{
Utils.PLAYBACK_DEBUG > 1 && console.log("Hacking time of " + data.time + " to " +
(this.last_data_time + Webm.Constants.EXPECTED_PACKET_DURATION));
data.time = this.last_data_time + Webm.Constants.EXPECTED_PACKET_DURATION;
}
else
{
Utils.PLAYBACK_DEBUG > 1 && console.log("Apparent gap in audio time; now is " + data.time + " last was " + this.last_data_time);
}
}
this.last_data_time = data.time;
Utils.PLAYBACK_DEBUG > 1 && console.log("PlaybackData; time " + data.time + "; length " + data.data.byteLength);
if (this.start_time == 0)
this.start_playback(data);
else if (data.time - this.cluster_time >= Webm.Constants.MAX_CLUSTER_TIME)
this.new_cluster(data);
else
this.simple_block(data, false);
return true;
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_MODE)
{
var mode = new Messages.SpiceMsgPlaybackMode(msg.data);
if (mode.mode != Constants.SPICE_AUDIO_DATA_MODE_OPUS)
{
this.log_err('This player cannot handle mode ' + mode.mode);
/* Deleting just source_buffer left the audio element and its
object URL orphaned with no guard left to reclaim them. */
this.destroy_audio();
}
return true;
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_STOP)
{
Utils.PLAYBACK_DEBUG > 0 && console.log("PlaybackStop");
if (this.audio)
{
this.destroy_audio();
return true;
}
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_VOLUME)
{
this.known_unimplemented(msg.type, "Playback Volume");
return true;
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_MUTE)
{
this.known_unimplemented(msg.type, "Playback Mute");
return true;
}
if (msg.type == Constants.SPICE_MSG_PLAYBACK_LATENCY)
{
this.known_unimplemented(msg.type, "Playback Latency");
return true;
}
return false;
}
SpicePlaybackConn.prototype.destroy_audio = function()
{
if (! this.audio)
return;
if (this.audio.parentNode)
this.audio.parentNode.removeChild(this.audio);
window.URL.revokeObjectURL(this.audio.src);
delete this.source_buffer;
delete this.media_source;
delete this.audio;
this.append_okay = false;
this.queue = new Array();
this.start_time = 0;
}
/* A client-side stop must reclaim the audio element, its object URL and
the MediaSource; without this they were only freed by a server STOP,
and an application that stops and recreates connections leaked one
set per cycle. */
SpicePlaybackConn.prototype.cleanup = function()
{
this.destroy_audio();
SpiceConn.prototype.cleanup.call(this);
}
SpicePlaybackConn.prototype.start_playback = function(data)
{
this.start_time = data.time;
var h = new Webm.Header();
var te = new Webm.AudioTrackEntry;
var t = new Webm.Tracks(te);
var mb = new ArrayBuffer(h.buffer_size() + t.buffer_size())
this.bytes_written = h.to_buffer(mb);
this.bytes_written = t.to_buffer(mb, this.bytes_written);
this.source_buffer.addEventListener('error', handle_sourcebuffer_error, false);
this.source_buffer.addEventListener('updateend', handle_append_buffer_done, false);
playback_append_buffer(this, mb);
this.new_cluster(data);
}
SpicePlaybackConn.prototype.new_cluster = function(data)
{
this.cluster_time = data.time;
var c = new Webm.Cluster(data.time - this.start_time);
var mb = new ArrayBuffer(c.buffer_size());
this.bytes_written += c.to_buffer(mb);
if (this.append_okay)
playback_append_buffer(this, mb);
else
this.queue.push(mb);
this.simple_block(data, true);
}
SpicePlaybackConn.prototype.simple_block = function(data, keyframe)
{
var sb = new Webm.SimpleBlock(data.time - this.cluster_time, data.data, keyframe);
var mb = new ArrayBuffer(sb.buffer_size());
this.bytes_written += sb.to_buffer(mb);
if (this.append_okay)
playback_append_buffer(this, mb);
else
this.queue.push(mb);
}
function handle_source_open(e)
{
var p = this.spiceconn;
if (p.source_buffer)
return;
p.source_buffer = this.addSourceBuffer(Webm.Constants.SPICE_PLAYBACK_CODEC);
if (! p.source_buffer)
{
p.log_err('Codec ' + Webm.Constants.SPICE_PLAYBACK_CODEC + ' not available.');
return;
}
if (Utils.PLAYBACK_DEBUG > 0)
playback_handle_event_debug.call(this, e);
listen_for_audio_events(p);
p.source_buffer.spiceconn = p;
p.source_buffer.mode = "segments";
// FIXME - Experimentation with segments and sequences was unsatisfying.
// Switching to sequence did not solve our gap problem,
// but the browsers didn't fully support the time seek capability
// we would expect to gain from 'segments'.
// Segments worked at the time of this patch, so segments it is for now.
}
function handle_source_ended(e)
{
var p = this.spiceconn;
p.log_err('Audio source unexpectedly ended.');
}
function handle_source_closed(e)
{
var p = this.spiceconn;
p.log_err('Audio source unexpectedly closed.');
}
function condense_playback_queue(queue)
{
if (queue.length == 1)
return queue.shift();
var len = 0;
var i = 0;
for (i = 0; i < queue.length; i++)
len += queue[i].byteLength;
var mb = new ArrayBuffer(len);
var tmp = new Uint8Array(mb);
len = 0;
for (i = 0; i < queue.length; i++)
{
tmp.set(new Uint8Array(queue[i]), len);
len += queue[i].byteLength;
}
queue.length = 0;
return mb;
}
function handle_append_buffer_done(e)
{
var p = this.spiceconn;
if (Utils.PLAYBACK_DEBUG > 1)
playback_handle_event_debug.call(this, e);
if (p.queue.length > 0)
{
var mb = condense_playback_queue(p.queue);
playback_append_buffer(p, mb);
}
else
p.append_okay = true;
}
function handle_sourcebuffer_error(e)
{
var p = this.spiceconn;
p.log_err('source_buffer error ' + e.message);
}
function playback_append_buffer(p, b)
{
try
{
p.source_buffer.appendBuffer(b);
p.append_okay = false;
}
catch (e)
{
p.log_err("Error invoking appendBuffer: " + e.message);
}
}
function playback_handle_event_debug(e)
{
var p = this.spiceconn;
if (p.audio)
{
if (Utils.PLAYBACK_DEBUG > 0 || p.audio.buffered.len > 1)
console.log(p.audio.currentTime + ": event " + e.type +
Utils.dump_media_element(p.audio));
}
if (Utils.PLAYBACK_DEBUG > 1 && p.media_source)
console.log(" media_source " + Utils.dump_media_source(p.media_source));
if (Utils.PLAYBACK_DEBUG > 1 && p.source_buffer)
console.log(" source_buffer " + Utils.dump_source_buffer(p.source_buffer));
if (Utils.PLAYBACK_DEBUG > 0 || p.queue.length > 1)
console.log(' queue len ' + p.queue.length + '; append_okay: ' + p.append_okay);
}
function playback_debug_listen_for_one_event(name)
{
this.addEventListener(name, playback_handle_event_debug);
}
function listen_for_audio_events(spiceconn)
{
var audio_0_events = [
"abort", "error"
];
var audio_1_events = [
"loadstart", "suspend", "emptied", "stalled", "loadedmetadata", "loadeddata", "canplay",
"canplaythrough", "playing", "waiting", "seeking", "seeked", "ended", "durationchange",
"timeupdate", "play", "pause", "ratechange"
];
var audio_2_events = [
"progress",
"resize",
"volumechange"
];
audio_0_events.forEach(playback_debug_listen_for_one_event, spiceconn.audio);
if (Utils.PLAYBACK_DEBUG > 0)
audio_1_events.forEach(playback_debug_listen_for_one_event, spiceconn.audio);
if (Utils.PLAYBACK_DEBUG > 1)
audio_2_events.forEach(playback_debug_listen_for_one_event, spiceconn.audio);
}
export {
SpicePlaybackConn,
};
+271
View File
@@ -0,0 +1,271 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** crc logic from rfc2083 ported to Javascript
**--------------------------------------------------------------------------*/
var rfc2083_crc_table = Array(256);
var rfc2083_crc_table_computed = 0;
/* Make the table for a fast CRC. */
function rfc2083_make_crc_table()
{
var c;
var n, k;
for (n = 0; n < 256; n++)
{
c = n;
for (k = 0; k < 8; k++)
{
if (c & 1)
c = ((0xedb88320 ^ (c >>> 1)) >>> 0) & 0xffffffff;
else
c = c >>> 1;
}
rfc2083_crc_table[n] = c;
}
rfc2083_crc_table_computed = 1;
}
/* Update a running CRC with the bytes buf[0..len-1]--the CRC
should be initialized to all 1's, and the transmitted value
is the 1's complement of the final running CRC (see the
crc() routine below)). */
function rfc2083_update_crc(crc, u8buf, at, len)
{
var c = crc;
var n;
if (!rfc2083_crc_table_computed)
rfc2083_make_crc_table();
for (n = 0; n < len; n++)
{
c = rfc2083_crc_table[(c ^ u8buf[at + n]) & 0xff] ^ (c >>> 8);
}
return c;
}
function rfc2083_crc(u8buf, at, len)
{
return rfc2083_update_crc(0xffffffff, u8buf, at, len) ^ 0xffffffff;
}
function crc32(mb, at, len)
{
var u8 = new Uint8Array(mb);
return rfc2083_crc(u8, at, len);
}
function PngIHDR(width, height)
{
this.width = width;
this.height = height;
this.depth = 8;
this.type = 6;
this.compression = 0;
this.filter = 0;
this.interlace = 0;
}
PngIHDR.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var orig = at;
var dv = new DataView(a);
dv.setUint32(at, this.buffer_size() - 12); at += 4;
dv.setUint8(at, 'I'.charCodeAt(0)); at++;
dv.setUint8(at, 'H'.charCodeAt(0)); at++;
dv.setUint8(at, 'D'.charCodeAt(0)); at++;
dv.setUint8(at, 'R'.charCodeAt(0)); at++;
dv.setUint32(at, this.width); at += 4;
dv.setUint32(at, this.height); at += 4;
dv.setUint8(at, this.depth); at++;
dv.setUint8(at, this.type); at++;
dv.setUint8(at, this.compression); at++;
dv.setUint8(at, this.filter); at++;
dv.setUint8(at, this.interlace); at++;
dv.setUint32(at, crc32(a, orig + 4, this.buffer_size() - 8)); at += 4;
return at;
},
buffer_size: function()
{
return 12 + 13;
}
}
function adler()
{
this.s1 = 1;
this.s2 = 0;
}
adler.prototype.update = function(b)
{
this.s1 += b;
this.s1 %= 65521;
this.s2 += this.s1;
this.s2 %= 65521;
}
/* The image as one IDAT chunk: a zlib stream of stored (uncompressed)
deflate blocks. A stored block holds at most 65535 bytes, so the
scanlines are cut into as many as it takes; a cursor larger than about
128 pixels square used to be refused here. */
var STORED_BLOCK_MAX = 65535;
function PngIDAT(width, height, bytes)
{
this.data = bytes;
this.width = width;
this.height = height;
/* Every scanline is filter type 0 followed by its pixels. */
this.raw_size = this.height * (1 + this.width * 4);
this.blocks = Math.max(1, Math.ceil(this.raw_size / STORED_BLOCK_MAX));
}
PngIDAT.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var orig = at;
var x, y, i;
var dv = new DataView(a);
var zsum = new adler();
dv.setUint32(at, this.buffer_size() - 12); at += 4;
dv.setUint8(at, 'I'.charCodeAt(0)); at++;
dv.setUint8(at, 'D'.charCodeAt(0)); at++;
dv.setUint8(at, 'A'.charCodeAt(0)); at++;
dv.setUint8(at, 'T'.charCodeAt(0)); at++;
/* zlib header: deflate, 32K window, no preset dictionary. */
dv.setUint8(at, 0x78); at++;
dv.setUint8(at, 0x01); at++;
var u8 = new Uint8Array(this.data);
var out = new Uint8Array(a);
var left = this.raw_size;
var block_left = 0;
var put = function(b)
{
if (block_left == 0)
{
/* Stored block: BFINAL in bit 0, BTYPE 00, then LEN and
its one's complement, little-endian. */
block_left = Math.min(left, STORED_BLOCK_MAX);
out[at++] = left <= STORED_BLOCK_MAX ? 1 : 0;
out[at++] = block_left & 0xff;
out[at++] = block_left >> 8;
out[at++] = ~block_left & 0xff;
out[at++] = (~block_left >> 8) & 0xff;
}
out[at++] = b;
zsum.update(b);
block_left--;
left--;
};
for (i = 0, y = 0; y < this.height; y++)
{
put(0);
for (x = 0; x < this.width; x++)
{
put(u8[i] || 0); i++;
put(u8[i] || 0); i++;
put(u8[i] || 0); i++;
put(u8[i] || 0); i++;
}
}
/* zlib checksum, big-endian. */
dv.setUint16(at, zsum.s2); at += 2;
dv.setUint16(at, zsum.s1); at += 2;
dv.setUint32(at, crc32(a, orig + 4, this.buffer_size() - 8)); at += 4;
return at;
},
buffer_size: function()
{
return 12 + 2 + this.blocks * 5 + this.raw_size + 4;
}
}
function PngIEND()
{
}
PngIEND.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var orig = at;
var dv = new DataView(a);
dv.setUint32(at, this.buffer_size() - 12); at += 4;
dv.setUint8(at, 'I'.charCodeAt(0)); at++;
dv.setUint8(at, 'E'.charCodeAt(0)); at++;
dv.setUint8(at, 'N'.charCodeAt(0)); at++;
dv.setUint8(at, 'D'.charCodeAt(0)); at++;
dv.setUint32(at, crc32(a, orig + 4, this.buffer_size() - 8)); at += 4;
return at;
},
buffer_size: function()
{
return 12;
}
}
function create_rgba_png(width, height, bytes)
{
var i;
var ihdr = new PngIHDR(width, height);
var idat = new PngIDAT(width, height, bytes);
var iend = new PngIEND;
var mb = new ArrayBuffer(ihdr.buffer_size() + idat.buffer_size() + iend.buffer_size());
var at = ihdr.to_buffer(mb);
at = idat.to_buffer(mb, at);
at = iend.to_buffer(mb, at);
var u8 = new Uint8Array(mb);
var str = "";
for (i = 0; i < at; i++)
{
str += "%";
if (u8[i] < 16)
str += "0";
str += u8[i].toString(16);
}
return "%89PNG%0D%0A%1A%0A" + str;
}
export {
create_rgba_png,
};
+94
View File
@@ -0,0 +1,94 @@
"use strict";
/*
Copyright (C) 2016 by Oliver Gutierrez <ogutsua@gmail.com>
Miroslav Chodil <mchodil@redhat.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import { Constants } from './enums.js';
import { DEBUG, arraybuffer_to_str } from './utils.js';
import { SpiceConn } from './spiceconn.js';
import { SpiceMsgPortInit } from './spicemsg.js';
/*----------------------------------------------------------------------------
** SpicePortConn
** Drive the Spice Port Channel
**--------------------------------------------------------------------------*/
function SpicePortConn()
{
DEBUG > 0 && console.log('SPICE port: created SPICE port channel. Args:', arguments);
SpiceConn.apply(this, arguments);
this.portName = null;
}
SpicePortConn.prototype = Object.create(SpiceConn.prototype);
SpicePortConn.prototype.process_channel_message = function(msg)
{
if (msg.type == Constants.SPICE_MSG_PORT_INIT)
{
if (this.portName === null)
{
var m = new SpiceMsgPortInit(msg.data);
this.portName = arraybuffer_to_str(new Uint8Array(m.name));
this.portOpened = m.opened
DEBUG > 0 && console.log('SPICE port: Port', this.portName, 'initialized');
return true;
}
DEBUG > 0 && console.log('SPICE port: Port', this.portName, 'is already initialized.');
}
else if (msg.type == Constants.SPICE_MSG_PORT_EVENT)
{
DEBUG > 0 && console.log('SPICE port: Port event received for', this.portName, msg);
var event = new CustomEvent('spice-port-event', {
detail: {
channel: this,
spiceEvent: new Uint8Array(msg.data)
},
bubbles: true,
cancelable: true
});
window.dispatchEvent(event);
return true;
}
else if (msg.type == Constants.SPICE_MSG_SPICEVMC_DATA)
{
DEBUG > 0 && console.log('SPICE port: Data received in port', this.portName, msg);
var event = new CustomEvent('spice-port-data', {
detail: {
channel: this,
data: msg.data
},
bubbles: true,
cancelable: true
});
window.dispatchEvent(event);
return true;
}
else
{
DEBUG > 0 && console.log('SPICE port: SPICE message type not recognized:', msg)
}
return false;
};
export {
SpicePortConn,
};
File diff suppressed because it is too large Load Diff
+87
View File
@@ -0,0 +1,87 @@
"use strict";
/*
Copyright (C) 2014 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** resize.js
** This bit of Javascript is a set of logic to help with window
** resizing, using the agent channel to request screen resizes.
**
** It's a bit tricky, as we want to wait for resizing to settle down
** before sending a size. Further, while horizontal resizing to use the whole
** browser width is fairly easy to arrange with css, resizing an element to use
** the whole vertical space (or to force a middle div to consume the bulk of the browser
** window size) is tricky, and the consensus seems to be that Javascript is
** the only right way to do it.
**--------------------------------------------------------------------------*/
function resize_helper(sc)
{
var w = document.getElementById(sc.screen_id).clientWidth;
var m = document.getElementById(sc.message_id);
/* Resize vertically; basically we leave a 20 pixel margin
at the bottom, and use the position of the message window
to figure out how to resize */
var h = window.innerHeight - 20;
/* Screen height based on message console visibility. A hidden console
occupies no space, so only a visible one reduces the screen; its
offsetHeight already includes the client area, so subtract it once. */
if (m != null &&
window.getComputedStyle(m).getPropertyValue("display") != 'none')
{
h = h - m.offsetHeight;
}
/* Xorg requires height be a multiple of 8; round down */
if (h % 8 > 0)
h -= (h % 8);
/* Xorg requires width be a multiple of 8; round down */
if (w % 8 > 0)
w -= (w % 8);
sc.resize_window(0, w, h, 32, 0, 0);
sc.spice_resize_timer = undefined;
}
function handle_resize(e)
{
var sc = window.spice_connection;
/* The listener can outlive the connection it was registered for. */
if (!sc)
return;
if (sc.spice_resize_timer)
{
window.clearTimeout(sc.spice_resize_timer);
sc.spice_resize_timer = undefined;
}
sc.spice_resize_timer = window.setTimeout(resize_helper, 200, sc);
}
export {
resize_helper,
handle_resize,
};
+206
View File
@@ -0,0 +1,206 @@
"use strict";
/*
Copyright (C) 2013 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** SpiceSimulateCursor
** Internet Explorer 10 does not support data uri's in cursor assignment.
** This file provides a number of gimmicks to compensate. First, if there
** is a preloaded cursor available, we will use that. Failing that, we will
** simulate a cursor using an image that is moved around the screen.
**--------------------------------------------------------------------------*/
import { hex_sha1 } from './thirdparty/sha1.js';
var SpiceSimulateCursor = {
cursors : new Array(),
unknown_cursors : new Array(),
warned: false,
add_cursor: function(sha1, value)
{
SpiceSimulateCursor.cursors[sha1] = value;
},
unknown_cursor: function(sha1, curdata)
{
if (! SpiceSimulateCursor.warned)
{
SpiceSimulateCursor.warned = true;
/* Once a modal alert; a console does not stop the session for it. */
console.warn("This browser does not take dynamic cursors; cursors will be " +
"simulated with images. See the console for how to supply static cursor files.");
}
if (! SpiceSimulateCursor.unknown_cursors[sha1])
{
SpiceSimulateCursor.unknown_cursors[sha1] = curdata;
console.log('Unknown cursor. Simulation required. To avoid simulation for this cursor, create and include a custom javascript file, and add the following line:');
console.log('SpiceSimulateCursor.add_cursor("' + sha1 + '", "<your filename here>.cur");');
console.log('And then run following command, redirecting output into <your filename here>.cur:');
console.log('php -r "echo urldecode(\'' + curdata + '\');"');
}
},
/* force: the browser cannot show this shape as a CSS cursor (too large),
so it is drawn under the pointer without consulting the computed style. */
simulate_cursor: function (spicecursor, cursor, screen, pngstr, force)
{
var cursor_sha = hex_sha1(pngstr + ' ' + cursor.header.hot_spot_x + ' ' + cursor.header.hot_spot_y);
if (! force && typeof SpiceSimulateCursor.cursors != 'undefined')
if (typeof SpiceSimulateCursor.cursors[cursor_sha] != 'undefined')
{
var curstr = 'url(' + SpiceSimulateCursor.cursors[cursor_sha] + '), default';
screen.style.cursor = curstr;
}
if (force || window.getComputedStyle(screen, null).cursor == 'auto')
{
if (! force)
SpiceSimulateCursor.unknown_cursor(cursor_sha,
SpiceSimulateCursor.create_icondir(cursor.header.width, cursor.header.height,
cursor.data.byteLength, cursor.header.hot_spot_x, cursor.header.hot_spot_y) + pngstr);
document.getElementById(spicecursor.parent.screen_id).style.cursor = 'none';
if (! spicecursor.spice_simulated_cursor)
{
spicecursor.spice_simulated_cursor = document.createElement('img');
spicecursor.spice_simulated_cursor.style.position = 'absolute';
spicecursor.spice_simulated_cursor.style.display = 'none';
spicecursor.spice_simulated_cursor.style.overflow = 'hidden';
spicecursor.spice_simulated_cursor.spice_screen = document.getElementById(spicecursor.parent.screen_id);
spicecursor.spice_simulated_cursor.addEventListener('mousemove', SpiceSimulateCursor.handle_sim_mousemove);
spicecursor.spice_simulated_cursor.spice_screen.appendChild(spicecursor.spice_simulated_cursor);
}
spicecursor.spice_simulated_cursor.src = 'data:image/png,' + pngstr;
spicecursor.spice_simulated_cursor.spice_hot_x = cursor.header.hot_spot_x;
spicecursor.spice_simulated_cursor.spice_hot_y = cursor.header.hot_spot_y;
spicecursor.spice_simulated_cursor.style.pointerEvents = "none";
}
else
{
if (spicecursor.spice_simulated_cursor)
{
spicecursor.spice_simulated_cursor.spice_screen.removeChild(spicecursor.spice_simulated_cursor);
delete spicecursor.spice_simulated_cursor;
}
}
},
handle_sim_mousemove: function(e)
{
var f = SpiceSimulateCursor.duplicate_mouse_event(e, this.spice_screen);
return this.spice_screen.dispatchEvent(f);
},
duplicate_mouse_event: function(e, target)
{
var evt = document.createEvent("mouseevent");
evt.initMouseEvent(e.type, true, true, e.view, e.detail,
e.screenX, e.screenY, e.clientX, e.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
return evt;
},
ICONDIR: function ()
{
},
ICONDIRENTRY: function(width, height, bytes, hot_x, hot_y)
{
this.width = width;
this.height = height;
this.bytes = bytes;
this.hot_x = hot_x;
this.hot_y = hot_y;
},
create_icondir: function (width, height, bytes, hot_x, hot_y)
{
var i;
var header = new SpiceSimulateCursor.ICONDIR();
var entry = new SpiceSimulateCursor.ICONDIRENTRY(width, height, bytes, hot_x, hot_y);
var mb = new ArrayBuffer(header.buffer_size() + entry.buffer_size());
var at = header.to_buffer(mb);
at = entry.to_buffer(mb, at);
var u8 = new Uint8Array(mb);
var str = "";
for (i = 0; i < at; i++)
{
str += "%";
if (u8[i] < 16)
str += "0";
str += u8[i].toString(16);
}
return str;
},
};
SpiceSimulateCursor.ICONDIR.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
dv.setUint16(at, 0, true); at += 2;
dv.setUint16(at, 2, true); at += 2;
dv.setUint16(at, 1, true); at += 2;
return at;
},
buffer_size: function()
{
return 6;
}
};
SpiceSimulateCursor.ICONDIRENTRY.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
dv.setUint8(at, this.width); at++;
dv.setUint8(at, this.height); at++;
dv.setUint8(at, 0); at++; /* color palette count, unused */
dv.setUint8(at, 0); at++; /* reserved */
dv.setUint16(at, this.hot_x, true); at += 2;
dv.setUint16(at, this.hot_y, true); at += 2;
dv.setUint32(at, this.bytes, true); at += 4;
dv.setUint32(at, at + 4, true); at += 4; /* Offset to bytes */
return at;
},
buffer_size: function()
{
return 16;
}
};
export { SpiceSimulateCursor };
+58
View File
@@ -0,0 +1,58 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** SpiceArrayBufferSlice
** This function is a work around for IE 10, which has no slice()
** method in it's subclass.
**--------------------------------------------------------------------------*/
function SpiceArrayBufferSlice(start, end)
{
start = start || 0;
end = end || this.byteLength;
if (end < 0)
end = this.byteLength + end;
if (start < 0)
start = this.byteLength + start;
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if (end > this.byteLength)
end = this.byteLength;
if (start > end)
start = end;
var ret = new ArrayBuffer(end - start);
var in1 = new Uint8Array(this, start, end - start);
var out = new Uint8Array(ret);
var i;
for (i = 0; i < end - start; i++)
out[i] = in1[i];
return ret;
}
if (! ArrayBuffer.prototype.slice)
{
ArrayBuffer.prototype.slice = SpiceArrayBufferSlice;
console.log("WARNING: ArrayBuffer.slice() is missing; we are extending ArrayBuffer to compensate");
}
+557
View File
@@ -0,0 +1,557 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** SpiceConn
** This is the base Javascript class for establishing and
** managing a connection to a Spice Server.
** It is used to provide core functionality to the Spice main,
** display, inputs, and cursor channels. See main.js for
** usage.
**--------------------------------------------------------------------------*/
import { Constants } from './enums.js';
import { SpiceWireReader } from './wire.js';
import {
SpiceLinkHeader,
SpiceLinkMess,
SpiceLinkReply,
SpiceLinkAuthTicket,
SpiceLinkAuthReply,
SpiceMiniData,
SpiceMsgcDisplayInit,
SpiceMsgSetAck,
SpiceMsgcAckSync,
SpiceMsgNotify,
} from './spicemsg.js';
import { DEBUG, hexdump_buffer } from './utils.js';
import * as Webm from './webm.js';
import { rsa_encrypt } from './ticket.js';
function SpiceConn(o)
{
if (o === undefined || o.uri === undefined || ! o.uri)
throw new Error("You must specify a uri");
this.ws = new WebSocket(o.uri, 'binary');
if (! this.ws.binaryType)
throw new Error("WebSocket doesn't support binaryType. Try a different browser.");
this.connection_id = o.connection_id !== undefined ? o.connection_id : 0;
this.type = o.type !== undefined ? o.type : Constants.SPICE_CHANNEL_MAIN;
this.chan_id = o.chan_id !== undefined ? o.chan_id : 0;
if (o.parent !== undefined)
{
this.parent = o.parent;
this.message_id = o.parent.message_id;
this.password = o.parent.password;
/* Without this a child channel that dies mid-session (display,
inputs, cursor...) reports nothing: the close handler requires
an onerror, and report_error without one throws uncaught inside
a WebSocket event handler. The application only ever hears
about the main channel. */
this.onerror = o.parent.onerror;
}
if (o.screen_id !== undefined)
this.screen_id = o.screen_id;
if (o.dump_id !== undefined)
this.dump_id = o.dump_id;
if (o.message_id !== undefined)
this.message_id = o.message_id;
if (o.password !== undefined)
this.password = o.password;
if (o.onerror !== undefined)
this.onerror = o.onerror;
if (o.onsuccess !== undefined)
this.onsuccess = o.onsuccess;
if (o.onagent !== undefined)
this.onagent = o.onagent;
this.state = "connecting";
this.ws.parent = this;
this.wire_reader = new SpiceWireReader(this, this.process_inbound);
this.messages_sent = 0;
this.warnings = [];
this.ws.addEventListener('open', function(e) {
DEBUG > 0 && console.log(">> WebSockets.onopen");
DEBUG > 0 && console.log("id " + this.parent.connection_id +"; type " + this.parent.type);
/***********************************************************************
** WHERE IT ALL REALLY BEGINS
***********************************************************************/
this.parent.send_hdr();
this.parent.wire_reader.request(SpiceLinkHeader.prototype.buffer_size());
this.parent.state = "start";
});
this.ws.addEventListener('error', function(e) {
if ('url' in e.target) {
this.parent.log_err("WebSocket error: Can't connect to websocket on URL: " + e.target.url);
}
this.parent.report_error(e);
});
this.ws.addEventListener('close', function(e) {
DEBUG > 0 && console.log(">> WebSockets.onclose");
DEBUG > 0 && console.log("id " + this.parent.connection_id +"; type " + this.parent.type);
DEBUG > 0 && console.log(e);
if (this.parent.state != "closing" && this.parent.state != "error" && this.parent.onerror !== undefined)
{
var e;
if (this.parent.state == "connecting")
e = new Error("Connection refused.");
else if (this.parent.state == "start" || this.parent.state == "link")
e = new Error("Unexpected protocol mismatch.");
else if (this.parent.state == "ticket")
e = new Error("Bad password.");
else
e = new Error("Unexpected close while " + this.parent.state);
this.parent.onerror(e);
this.parent.log_err(e.toString());
}
});
if (this.ws.readyState == 2 || this.ws.readyState == 3)
throw new Error("Unable to connect to " + o.uri);
this.timeout = window.setTimeout(spiceconn_timeout, Constants.SPICE_CONNECT_TIMEOUT, this);
}
SpiceConn.prototype =
{
send_hdr : function ()
{
var hdr = new SpiceLinkHeader;
var msg = new SpiceLinkMess;
msg.connection_id = this.connection_id;
msg.channel_type = this.type;
msg.channel_id = this.chan_id;
msg.common_caps.push(
(1 << Constants.SPICE_COMMON_CAP_PROTOCOL_AUTH_SELECTION) |
(1 << Constants.SPICE_COMMON_CAP_MINI_HEADER)
);
if (msg.channel_type == Constants.SPICE_CHANNEL_PLAYBACK)
{
var caps = 0;
if ('MediaSource' in window && MediaSource.isTypeSupported(Webm.Constants.SPICE_PLAYBACK_CODEC))
caps |= (1 << Constants.SPICE_PLAYBACK_CAP_OPUS);
msg.channel_caps.push(caps);
}
else if (msg.channel_type == Constants.SPICE_CHANNEL_MAIN)
{
msg.channel_caps.push(
(1 << Constants.SPICE_MAIN_CAP_AGENT_CONNECTED_TOKENS)
);
}
else if (msg.channel_type == Constants.SPICE_CHANNEL_DISPLAY)
{
var caps = (1 << Constants.SPICE_DISPLAY_CAP_SIZED_STREAM) |
(1 << Constants.SPICE_DISPLAY_CAP_STREAM_REPORT) |
(1 << Constants.SPICE_DISPLAY_CAP_MULTI_CODEC) |
(1 << Constants.SPICE_DISPLAY_CAP_CODEC_MJPEG);
if ('MediaSource' in window && MediaSource.isTypeSupported(Webm.Constants.SPICE_VP8_CODEC))
caps |= (1 << Constants.SPICE_DISPLAY_CAP_CODEC_VP8);
msg.channel_caps.push(caps);
}
hdr.size = msg.buffer_size();
var mb = new ArrayBuffer(hdr.buffer_size() + msg.buffer_size());
hdr.to_buffer(mb);
msg.to_buffer(mb, hdr.buffer_size());
DEBUG > 1 && console.log("Sending header:");
DEBUG > 2 && hexdump_buffer(mb);
this.ws.send(mb);
},
send_ticket: function(ticket)
{
var hdr = new SpiceLinkAuthTicket();
hdr.auth_mechanism = Constants.SPICE_COMMON_CAP_AUTH_SPICE;
// FIXME - we need to implement RSA to make this work right
hdr.encrypted_data = ticket;
var mb = new ArrayBuffer(hdr.buffer_size());
hdr.to_buffer(mb);
DEBUG > 1 && console.log("Sending ticket:");
DEBUG > 2 && hexdump_buffer(mb);
this.ws.send(mb);
},
send_msg: function(msg)
{
var mb = new ArrayBuffer(msg.buffer_size());
msg.to_buffer(mb);
this.messages_sent++;
DEBUG > 0 && console.log(">> hdr " + this.channel_type() + " type " + msg.type + " size " + mb.byteLength);
DEBUG > 2 && hexdump_buffer(mb);
this.ws.send(mb);
},
process_inbound: function(mb, saved_header)
{
DEBUG > 2 && console.log(this.type + ": processing message of size " + mb.byteLength + "; state is " + this.state);
if (this.state == "ready")
{
if (saved_header == undefined)
{
var msg = new SpiceMiniData(mb);
if (msg.type > 500)
{
if (DEBUG > 0)
{
alert("Something has gone very wrong; we think we have message of type " + msg.type);
debugger;
}
}
if (msg.size == 0)
{
this.process_message(msg);
this.wire_reader.request(SpiceMiniData.prototype.buffer_size());
}
else
{
this.wire_reader.request(msg.size);
this.wire_reader.save_header(msg);
}
}
else
{
saved_header.data = mb;
this.process_message(saved_header);
this.wire_reader.request(SpiceMiniData.prototype.buffer_size());
this.wire_reader.save_header(undefined);
}
}
else if (this.state == "start")
{
this.reply_hdr = new SpiceLinkHeader(mb);
if (this.reply_hdr.magic != Constants.SPICE_MAGIC)
{
this.state = "error";
var e = new Error('Error: magic mismatch: ' + this.reply_hdr.magic);
this.report_error(e);
}
else
{
// FIXME - Determine major/minor version requirements
this.wire_reader.request(this.reply_hdr.size);
this.state = "link";
}
}
else if (this.state == "link")
{
this.reply_link = new SpiceLinkReply(mb);
// FIXME - Screen the caps - require minihdr at least, right?
if (this.reply_link.error)
{
this.state = "error";
var e = new Error('Error: reply link error ' + this.reply_link.error);
this.report_error(e);
}
else
{
this.send_ticket(rsa_encrypt(this.reply_link.pub_key, this.password + String.fromCharCode(0)));
this.state = "ticket";
this.wire_reader.request(SpiceLinkAuthReply.prototype.buffer_size());
}
}
else if (this.state == "ticket")
{
this.auth_reply = new SpiceLinkAuthReply(mb);
if (this.auth_reply.auth_code == Constants.SPICE_LINK_ERR_OK)
{
DEBUG > 0 && console.log(this.type + ': Connected');
if (this.type == Constants.SPICE_CHANNEL_DISPLAY)
{
// FIXME - pixmap and glz dictionary config info?
var dinit = new SpiceMsgcDisplayInit();
var reply = new SpiceMiniData();
reply.build_msg(Constants.SPICE_MSGC_DISPLAY_INIT, dinit);
DEBUG > 0 && console.log("Request display init");
this.send_msg(reply);
}
this.state = "ready";
this.wire_reader.request(SpiceMiniData.prototype.buffer_size());
if (this.timeout)
{
window.clearTimeout(this.timeout);
delete this.timeout;
}
}
else
{
this.state = "error";
if (this.auth_reply.auth_code == Constants.SPICE_LINK_ERR_PERMISSION_DENIED)
{
var e = new Error("Permission denied.");
}
else
{
var e = new Error("Unexpected link error " + this.auth_reply.auth_code);
}
this.report_error(e);
}
}
},
process_common_messages : function(msg)
{
if (msg.type == Constants.SPICE_MSG_SET_ACK)
{
var ack = new SpiceMsgSetAck(msg.data);
// FIXME - what to do with generation?
this.ack_window = ack.window;
DEBUG > 1 && console.log(this.type + ": set ack to " + ack.window);
this.msgs_until_ack = this.ack_window;
var ackack = new SpiceMsgcAckSync(ack);
var reply = new SpiceMiniData();
reply.build_msg(Constants.SPICE_MSGC_ACK_SYNC, ackack);
this.send_msg(reply);
return true;
}
if (msg.type == Constants.SPICE_MSG_PING)
{
DEBUG > 1 && console.log("ping!");
var pong = new SpiceMiniData;
pong.type = Constants.SPICE_MSGC_PONG;
if (msg.data)
{
pong.data = msg.data.slice(0, 12);
}
pong.size = pong.buffer_size();
this.send_msg(pong);
return true;
}
if (msg.type == Constants.SPICE_MSG_NOTIFY)
{
// FIXME - Visibility + what
var notify = new SpiceMsgNotify(msg.data);
if (notify.severity == Constants.SPICE_NOTIFY_SEVERITY_ERROR)
this.log_err(notify.message);
else if (notify.severity == Constants.SPICE_NOTIFY_SEVERITY_WARN )
this.log_warn(notify.message);
else
this.log_info(notify.message);
return true;
}
return false;
},
process_message: function(msg)
{
var rc;
var start = Date.now();
DEBUG > 0 && console.log("<< hdr " + this.channel_type() + " type " + msg.type + " size " + (msg.data && msg.data.byteLength));
/* A handler that throws must not take the channel with it: the
caller re-arms the wire reader only after this returns, so an
escaped exception left every later byte read as a header and
the channel decoding garbage until it closed. Report it and
carry on with the next message. */
try
{
rc = this.process_common_messages(msg);
if (! rc)
{
if (this.process_channel_message)
{
rc = this.process_channel_message(msg);
if (! rc)
this.log_warn(this.channel_type() + ": Unknown message type " + msg.type + "!");
}
else
this.log_err(this.channel_type() + ": No message handlers for this channel; message " + msg.type);
}
}
catch (e)
{
this.log_err(this.channel_type() + ": exception handling message type " + msg.type + ": " + e.message);
DEBUG > 0 && console.error(e);
}
if (this.msgs_until_ack !== undefined && this.ack_window)
{
this.msgs_until_ack--;
if (this.msgs_until_ack <= 0)
{
this.msgs_until_ack = this.ack_window;
var ack = new SpiceMiniData();
ack.type = Constants.SPICE_MSGC_ACK;
this.send_msg(ack);
DEBUG > 1 && console.log(this.type + ": sent ack");
}
}
var delta = Date.now() - start;
if (DEBUG > 0 || delta > Webm.Constants.GAP_DETECTION_THRESHOLD)
console.log("delta " + this.channel_type() + ":" + msg.type + " " + delta);
return rc;
},
channel_type: function()
{
if (this.type == Constants.SPICE_CHANNEL_MAIN)
return "main";
else if (this.type == Constants.SPICE_CHANNEL_DISPLAY)
return "display";
else if (this.type == Constants.SPICE_CHANNEL_INPUTS)
return "inputs";
else if (this.type == Constants.SPICE_CHANNEL_CURSOR)
return "cursor";
else if (this.type == Constants.SPICE_CHANNEL_PLAYBACK)
return "playback";
else if (this.type == Constants.SPICE_CHANNEL_RECORD)
return "record";
else if (this.type == Constants.SPICE_CHANNEL_TUNNEL)
return "tunnel";
else if (this.type == Constants.SPICE_CHANNEL_SMARTCARD)
return "smartcard";
else if (this.type == Constants.SPICE_CHANNEL_USBREDIR)
return "usbredir";
else if (this.type == Constants.SPICE_CHANNEL_PORT)
return "port";
else if (this.type == Constants.SPICE_CHANNEL_WEBDAV)
return "webdav";
return "unknown-" + this.type;
},
log_info: function()
{
var msg = Array.prototype.join.call(arguments, " ");
console.log(msg);
if (this.message_id)
{
var p = document.createElement("p");
p.appendChild(document.createTextNode(msg));
p.className += "spice-message-info";
document.getElementById(this.message_id).appendChild(p);
}
},
log_warn: function()
{
var msg = Array.prototype.join.call(arguments, " ");
console.log("WARNING: " + msg);
if (this.message_id)
{
var p = document.createElement("p");
p.appendChild(document.createTextNode(msg));
p.className += "spice-message-warning";
document.getElementById(this.message_id).appendChild(p);
}
},
log_err: function()
{
var msg = Array.prototype.join.call(arguments, " ");
console.log("ERROR: " + msg);
if (this.message_id)
{
var p = document.createElement("p");
p.appendChild(document.createTextNode(msg));
p.className += "spice-message-error";
document.getElementById(this.message_id).appendChild(p);
}
},
known_unimplemented: function(type, msg)
{
if ( (!this.warnings[type]) || DEBUG > 1)
{
var str = "";
if (DEBUG <= 1)
str = " [ further notices suppressed ]";
this.log_warn("Unimplemented function " + type + "(" + msg + ")" + str);
this.warnings[type] = true;
}
},
report_error: function(e)
{
this.log_err(e.toString());
if (this.onerror != undefined)
this.onerror(e);
else
throw(e);
},
report_success: function(m)
{
if (this.onsuccess != undefined)
this.onsuccess(m);
},
cleanup: function()
{
/* Deliberate teardown: without this the ws close event arrives
with a live state and reports "Unexpected close" through
onerror. */
this.state = "closing";
if (this.timeout)
{
window.clearTimeout(this.timeout);
delete this.timeout;
}
if (this.ws)
{
this.ws.close();
this.ws = undefined;
}
},
handle_timeout: function()
{
var e = new Error("Connection timed out.");
/* Actually shut the connection down. Reporting alone left the
socket open, and a slow handshake could still complete after
the application had already given up on it — a zombie session
with its own inputs and display channels. Cleanup before
report so the socket dies even if report_error throws; the
error state also keeps the close event from double-reporting. */
this.cleanup();
this.state = "error";
this.report_error(e);
},
}
function spiceconn_timeout(sc)
{
SpiceConn.prototype.handle_timeout.call(sc);
}
export {
SpiceConn,
};
File diff suppressed because it is too large Load Diff
+497
View File
@@ -0,0 +1,497 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** Spice types
** This file contains classes for common spice types.
** Generally, they are used as helpers in reading and writing messages
** to and from the server.
**--------------------------------------------------------------------------*/
import { Constants } from './enums.js';
import { SpiceQuic } from './quic.js';
function SpiceChannelId()
{
}
SpiceChannelId.prototype =
{
from_dv: function(dv, at, mb)
{
this.type = dv.getUint8(at, true); at ++;
this.id = dv.getUint8(at, true); at ++;
return at;
},
}
function SpiceRect()
{
}
SpiceRect.prototype =
{
from_dv: function(dv, at, mb)
{
this.top = dv.getUint32(at, true); at += 4;
this.left = dv.getUint32(at, true); at += 4;
this.bottom = dv.getUint32(at, true); at += 4;
this.right = dv.getUint32(at, true); at += 4;
return at;
},
is_same_size : function(r)
{
if ((this.bottom - this.top) == (r.bottom - r.top) &&
(this.right - this.left) == (r.right - r.left) )
return true;
return false;
},
}
function SpiceClipRects()
{
}
SpiceClipRects.prototype =
{
from_dv: function(dv, at, mb)
{
var i;
this.num_rects = dv.getUint32(at, true); at += 4;
if (this.num_rects > 0)
this.rects = [];
for (i = 0; i < this.num_rects; i++)
{
this.rects[i] = new SpiceRect();
at = this.rects[i].from_dv(dv, at, mb);
}
return at;
},
}
function SpiceClip()
{
}
SpiceClip.prototype =
{
from_dv: function(dv, at, mb)
{
this.type = dv.getUint8(at, true); at ++;
if (this.type == Constants.SPICE_CLIP_TYPE_RECTS)
{
this.rects = new SpiceClipRects();
at = this.rects.from_dv(dv, at, mb);
}
return at;
},
}
function SpiceImageDescriptor()
{
}
SpiceImageDescriptor.prototype =
{
from_dv: function(dv, at, mb)
{
this.id = dv.getBigUint64(at, true); at += 8;
this.type = dv.getUint8(at, true); at ++;
this.flags = dv.getUint8(at, true); at ++;
this.width = dv.getUint32(at, true); at += 4;
this.height= dv.getUint32(at, true); at += 4;
return at;
},
}
function SpicePalette()
{
}
SpicePalette.prototype =
{
from_dv: function(dv, at, mb)
{
var i;
this.unique = dv.getBigUint64(at, true); at += 8;
this.num_ents = dv.getUint16(at, true); at += 2;
this.ents = [];
for (i = 0; i < this.num_ents; i++)
{
this.ents[i] = dv.getUint32(at, true); at += 4;
}
return at;
},
}
function SpiceBitmap()
{
}
SpiceBitmap.prototype =
{
from_dv: function(dv, at, mb)
{
this.format = dv.getUint8(at, true); at++;
this.flags = dv.getUint8(at, true); at++;
this.x = dv.getUint32(at, true); at += 4;
this.y = dv.getUint32(at, true); at += 4;
this.stride = dv.getUint32(at, true); at += 4;
if (this.flags & Constants.SPICE_BITMAP_FLAGS_PAL_FROM_CACHE)
{
this.palette_id = dv.getBigUint64(at, true); at += 8;
}
else
{
var offset = dv.getUint32(at, true); at += 4;
if (offset == 0)
this.palette = null;
else
{
this.palette = new SpicePalette;
this.palette.from_dv(dv, offset, mb);
}
}
// FIXME - should probably constrain this to the offset
// of palette, if non zero
this.data = mb.slice(at);
at += this.data.byteLength;
return at;
},
}
function SpiceImage()
{
}
SpiceImage.prototype =
{
from_dv: function(dv, at, mb)
{
this.descriptor = new SpiceImageDescriptor;
at = this.descriptor.from_dv(dv, at, mb);
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_LZ_RGB)
{
this.lz_rgb = new Object();
this.lz_rgb.length = dv.getUint32(at, true); at += 4;
var initial_at = at;
this.lz_rgb.magic = "";
for (var i = 3; i >= 0; i--)
this.lz_rgb.magic += String.fromCharCode(dv.getUint8(at + i));
at += 4;
// NOTE: The endian change is *correct*
this.lz_rgb.version = dv.getUint32(at); at += 4;
this.lz_rgb.type = dv.getUint32(at); at += 4;
this.lz_rgb.width = dv.getUint32(at); at += 4;
this.lz_rgb.height = dv.getUint32(at); at += 4;
this.lz_rgb.stride = dv.getUint32(at); at += 4;
this.lz_rgb.top_down = dv.getUint32(at); at += 4;
var header_size = at - initial_at;
this.lz_rgb.data = mb.slice(at, this.lz_rgb.length + at - header_size);
at += this.lz_rgb.data.byteLength;
}
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_BITMAP)
{
this.bitmap = new SpiceBitmap;
at = this.bitmap.from_dv(dv, at, mb);
}
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_SURFACE)
{
this.surface_id = dv.getUint32(at, true); at += 4;
}
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_JPEG)
{
this.jpeg = new Object;
this.jpeg.data_size = dv.getUint32(at, true); at += 4;
this.jpeg.data = mb.slice(at);
at += this.jpeg.data.byteLength;
}
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_JPEG_ALPHA)
{
this.jpeg_alpha = new Object;
this.jpeg_alpha.flags = dv.getUint8(at, true); at += 1;
this.jpeg_alpha.jpeg_size = dv.getUint32(at, true); at += 4;
this.jpeg_alpha.data_size = dv.getUint32(at, true); at += 4;
this.jpeg_alpha.data = mb.slice(at, this.jpeg_alpha.jpeg_size + at);
at += this.jpeg_alpha.data.byteLength;
// Alpha channel is an LZ image
this.jpeg_alpha.alpha = new Object();
this.jpeg_alpha.alpha.length = this.jpeg_alpha.data_size - this.jpeg_alpha.jpeg_size;
var initial_at = at;
this.jpeg_alpha.alpha.magic = "";
for (var i = 3; i >= 0; i--)
this.jpeg_alpha.alpha.magic += String.fromCharCode(dv.getUint8(at + i));
at += 4;
// NOTE: The endian change is *correct*
this.jpeg_alpha.alpha.version = dv.getUint32(at); at += 4;
this.jpeg_alpha.alpha.type = dv.getUint32(at); at += 4;
this.jpeg_alpha.alpha.width = dv.getUint32(at); at += 4;
this.jpeg_alpha.alpha.height = dv.getUint32(at); at += 4;
this.jpeg_alpha.alpha.stride = dv.getUint32(at); at += 4;
this.jpeg_alpha.alpha.top_down = dv.getUint32(at); at += 4;
var header_size = at - initial_at;
this.jpeg_alpha.alpha.data = mb.slice(at, this.jpeg_alpha.alpha.length + at - header_size);
at += this.jpeg_alpha.alpha.data.byteLength;
}
if (this.descriptor.type == Constants.SPICE_IMAGE_TYPE_QUIC)
{
this.quic = new SpiceQuic;
at = this.quic.from_dv(dv, at, mb);
}
return at;
},
}
function SpiceQMask()
{
}
SpiceQMask.prototype =
{
from_dv: function(dv, at, mb)
{
this.flags = dv.getUint8(at, true); at++;
this.pos = new SpicePoint;
at = this.pos.from_dv(dv, at, mb);
var offset = dv.getUint32(at, true); at += 4;
if (offset == 0)
{
this.bitmap = null;
return at;
}
this.bitmap = new SpiceImage;
return this.bitmap.from_dv(dv, offset, mb);
},
}
function SpicePattern()
{
}
SpicePattern.prototype =
{
from_dv: function(dv, at, mb)
{
var offset = dv.getUint32(at, true); at += 4;
if (offset == 0)
{
this.pat = null;
}
else
{
this.pat = new SpiceImage;
this.pat.from_dv(dv, offset, mb);
}
this.pos = new SpicePoint;
return this.pos.from_dv(dv, at, mb);
}
}
function SpiceBrush()
{
}
SpiceBrush.prototype =
{
from_dv: function(dv, at, mb)
{
this.type = dv.getUint8(at, true); at ++;
if (this.type == Constants.SPICE_BRUSH_TYPE_SOLID)
{
this.color = dv.getUint32(at, true); at += 4;
}
else if (this.type == Constants.SPICE_BRUSH_TYPE_PATTERN)
{
this.pattern = new SpicePattern;
at = this.pattern.from_dv(dv, at, mb);
}
return at;
},
}
function SpiceFill()
{
}
SpiceFill.prototype =
{
from_dv: function(dv, at, mb)
{
this.brush = new SpiceBrush;
at = this.brush.from_dv(dv, at, mb);
this.rop_descriptor = dv.getUint16(at, true); at += 2;
this.mask = new SpiceQMask;
return this.mask.from_dv(dv, at, mb);
},
}
function SpiceCopy()
{
}
SpiceCopy.prototype =
{
from_dv: function(dv, at, mb)
{
var offset = dv.getUint32(at, true); at += 4;
if (offset == 0)
{
this.src_bitmap = null;
}
else
{
this.src_bitmap = new SpiceImage;
this.src_bitmap.from_dv(dv, offset, mb);
}
this.src_area = new SpiceRect;
at = this.src_area.from_dv(dv, at, mb);
this.rop_descriptor = dv.getUint16(at, true); at += 2;
this.scale_mode = dv.getUint8(at, true); at ++;
this.mask = new SpiceQMask;
return this.mask.from_dv(dv, at, mb);
},
}
function SpicePoint16()
{
}
SpicePoint16.prototype =
{
from_dv: function(dv, at, mb)
{
this.x = dv.getUint16(at, true); at += 2;
this.y = dv.getUint16(at, true); at += 2;
return at;
},
}
function SpicePoint()
{
}
SpicePoint.prototype =
{
from_dv: function(dv, at, mb)
{
this.x = dv.getUint32(at, true); at += 4;
this.y = dv.getUint32(at, true); at += 4;
return at;
},
}
function SpiceCursorHeader()
{
}
SpiceCursorHeader.prototype =
{
from_dv: function(dv, at, mb)
{
this.unique = dv.getBigUint64(at, true); at += 8;
this.type = dv.getUint8(at, true); at ++;
this.width = dv.getUint16(at, true); at += 2;
this.height = dv.getUint16(at, true); at += 2;
this.hot_spot_x = dv.getUint16(at, true); at += 2;
this.hot_spot_y = dv.getUint16(at, true); at += 2;
return at;
},
}
function SpiceCursor()
{
}
SpiceCursor.prototype =
{
from_dv: function(dv, at, mb)
{
this.flags = dv.getUint16(at, true); at += 2;
if (this.flags & Constants.SPICE_CURSOR_FLAGS_NONE)
this.header = null;
else
{
this.header = new SpiceCursorHeader;
at = this.header.from_dv(dv, at, mb);
this.data = mb.slice(at);
at += this.data.byteLength;
}
return at;
},
}
function SpiceSurface()
{
}
SpiceSurface.prototype =
{
from_dv: function(dv, at, mb)
{
this.surface_id = dv.getUint32(at, true); at += 4;
this.width = dv.getUint32(at, true); at += 4;
this.height = dv.getUint32(at, true); at += 4;
this.format = dv.getUint32(at, true); at += 4;
this.flags = dv.getUint32(at, true); at += 4;
return at;
},
}
/* FIXME - SpiceImage types lz_plt, jpeg, zlib_glz, and jpeg_alpha are
completely unimplemented */
export {
SpiceChannelId,
SpiceRect,
SpiceClipRects,
SpiceClip,
SpiceImageDescriptor,
SpicePalette,
SpiceBitmap,
SpiceImage,
SpiceQMask,
SpicePattern,
SpiceBrush,
SpiceFill,
SpiceCopy,
SpicePoint16,
SpicePoint,
SpiceCursorHeader,
SpiceCursor,
SpiceSurface,
};
+593
View File
@@ -0,0 +1,593 @@
// Downloaded from http://www-cs-students.stanford.edu/~tjw/jsbn/ by Jeremy White on 6/1/2012
/*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
// Basic JavaScript BN library - subset useful for RSA encryption.
// Bits per digit
var dbits;
// JavaScript engine analysis
var canary = 0xdeadbeefcafe;
var j_lm = ((canary&0xffffff)==0xefcafe);
// (public) Constructor
function BigInteger(a,b,c) {
if(a != null)
if("number" == typeof a) this.fromNumber(a,b,c);
else if(b == null && "string" != typeof a) this.fromString(a,256);
else this.fromString(a,b);
}
// return new, unset BigInteger
function nbi() { return new BigInteger(null); }
// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
// We need to select the fastest one that works in this environment.
// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
function am1(i,x,w,j,c,n) {
while(--n >= 0) {
var v = x*this[i++]+w[j]+c;
c = Math.floor(v/0x4000000);
w[j++] = v&0x3ffffff;
}
return c;
}
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
function am2(i,x,w,j,c,n) {
var xl = x&0x7fff, xh = x>>15;
while(--n >= 0) {
var l = this[i]&0x7fff;
var h = this[i++]>>15;
var m = xh*l+h*xl;
l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
w[j++] = l&0x3fffffff;
}
return c;
}
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
function am3(i,x,w,j,c,n) {
var xl = x&0x3fff, xh = x>>14;
while(--n >= 0) {
var l = this[i]&0x3fff;
var h = this[i++]>>14;
var m = xh*l+h*xl;
l = xl*l+((m&0x3fff)<<14)+w[j]+c;
c = (l>>28)+(m>>14)+xh*h;
w[j++] = l&0xfffffff;
}
return c;
}
if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
BigInteger.prototype.am = am2;
dbits = 30;
}
else if(j_lm && (navigator.appName != "Netscape")) {
BigInteger.prototype.am = am1;
dbits = 26;
}
else { // Mozilla/Netscape seems to prefer am3
BigInteger.prototype.am = am3;
dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = ((1<<dbits)-1);
BigInteger.prototype.DV = (1<<dbits);
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2,BI_FP);
BigInteger.prototype.F1 = BI_FP-dbits;
BigInteger.prototype.F2 = 2*dbits-BI_FP;
// Digit conversions
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr,vv;
rr = "0".charCodeAt(0);
for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
function int2char(n) { return BI_RM.charAt(n); }
function intAt(s,i) {
var c = BI_RC[s.charCodeAt(i)];
return (c==null)?-1:c;
}
// (protected) copy this to r
function bnpCopyTo(r) {
for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
r.t = this.t;
r.s = this.s;
}
// (protected) set from integer value x, -DV <= x < DV
function bnpFromInt(x) {
this.t = 1;
this.s = (x<0)?-1:0;
if(x > 0) this[0] = x;
else if(x < -1) this[0] = x+DV;
else this.t = 0;
}
// return bigint initialized to value
function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
// (protected) set from string and radix
function bnpFromString(s,b) {
var k;
if(b == 16) k = 4;
else if(b == 8) k = 3;
else if(b == 256) k = 8; // byte array
else if(b == 2) k = 1;
else if(b == 32) k = 5;
else if(b == 4) k = 2;
else { this.fromRadix(s,b); return; }
this.t = 0;
this.s = 0;
var i = s.length, mi = false, sh = 0;
while(--i >= 0) {
var x = (k==8)?s[i]&0xff:intAt(s,i);
if(x < 0) {
if(s.charAt(i) == "-") mi = true;
continue;
}
mi = false;
if(sh == 0)
this[this.t++] = x;
else if(sh+k > this.DB) {
this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
this[this.t++] = (x>>(this.DB-sh));
}
else
this[this.t-1] |= x<<sh;
sh += k;
if(sh >= this.DB) sh -= this.DB;
}
if(k == 8 && (s[0]&0x80) != 0) {
this.s = -1;
if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
}
this.clamp();
if(mi) BigInteger.ZERO.subTo(this,this);
}
// (protected) clamp off excess high words
function bnpClamp() {
var c = this.s&this.DM;
while(this.t > 0 && this[this.t-1] == c) --this.t;
}
// (public) return string representation in given radix
function bnToString(b) {
if(this.s < 0) return "-"+this.negate().toString(b);
var k;
if(b == 16) k = 4;
else if(b == 8) k = 3;
else if(b == 2) k = 1;
else if(b == 32) k = 5;
else if(b == 4) k = 2;
else return this.toRadix(b);
var km = (1<<k)-1, d, m = false, r = "", i = this.t;
var p = this.DB-(i*this.DB)%k;
if(i-- > 0) {
if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
while(i >= 0) {
if(p < k) {
d = (this[i]&((1<<p)-1))<<(k-p);
d |= this[--i]>>(p+=this.DB-k);
}
else {
d = (this[i]>>(p-=k))&km;
if(p <= 0) { p += this.DB; --i; }
}
if(d > 0) m = true;
if(m) r += int2char(d);
}
}
return m?r:"0";
}
// (public) -this
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
// (public) |this|
function bnAbs() { return (this.s<0)?this.negate():this; }
// (public) return + if this > a, - if this < a, 0 if equal
function bnCompareTo(a) {
var r = this.s-a.s;
if(r != 0) return r;
var i = this.t;
r = i-a.t;
if(r != 0) return r;
while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
return 0;
}
// returns bit length of the integer x
function nbits(x) {
var r = 1, t;
if((t=x>>>16) != 0) { x = t; r += 16; }
if((t=x>>8) != 0) { x = t; r += 8; }
if((t=x>>4) != 0) { x = t; r += 4; }
if((t=x>>2) != 0) { x = t; r += 2; }
if((t=x>>1) != 0) { x = t; r += 1; }
return r;
}
// (public) return the number of bits in "this"
function bnBitLength() {
if(this.t <= 0) return 0;
return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
}
// (protected) r = this << n*DB
function bnpDLShiftTo(n,r) {
var i;
for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
for(i = n-1; i >= 0; --i) r[i] = 0;
r.t = this.t+n;
r.s = this.s;
}
// (protected) r = this >> n*DB
function bnpDRShiftTo(n,r) {
for(var i = n; i < this.t; ++i) r[i-n] = this[i];
r.t = Math.max(this.t-n,0);
r.s = this.s;
}
// (protected) r = this << n
function bnpLShiftTo(n,r) {
var bs = n%this.DB;
var cbs = this.DB-bs;
var bm = (1<<cbs)-1;
var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
for(i = this.t-1; i >= 0; --i) {
r[i+ds+1] = (this[i]>>cbs)|c;
c = (this[i]&bm)<<bs;
}
for(i = ds-1; i >= 0; --i) r[i] = 0;
r[ds] = c;
r.t = this.t+ds+1;
r.s = this.s;
r.clamp();
}
// (protected) r = this >> n
function bnpRShiftTo(n,r) {
r.s = this.s;
var ds = Math.floor(n/this.DB);
if(ds >= this.t) { r.t = 0; return; }
var bs = n%this.DB;
var cbs = this.DB-bs;
var bm = (1<<bs)-1;
r[0] = this[ds]>>bs;
for(var i = ds+1; i < this.t; ++i) {
r[i-ds-1] |= (this[i]&bm)<<cbs;
r[i-ds] = this[i]>>bs;
}
if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
r.t = this.t-ds;
r.clamp();
}
// (protected) r = this - a
function bnpSubTo(a,r) {
var i = 0, c = 0, m = Math.min(a.t,this.t);
while(i < m) {
c += this[i]-a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
if(a.t < this.t) {
c -= a.s;
while(i < this.t) {
c += this[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c += this.s;
}
else {
c += this.s;
while(i < a.t) {
c -= a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c -= a.s;
}
r.s = (c<0)?-1:0;
if(c < -1) r[i++] = this.DV+c;
else if(c > 0) r[i++] = c;
r.t = i;
r.clamp();
}
// (protected) r = this * a, r != this,a (HAC 14.12)
// "this" should be the larger one if appropriate.
function bnpMultiplyTo(a,r) {
var x = this.abs(), y = a.abs();
var i = x.t;
r.t = i+y.t;
while(--i >= 0) r[i] = 0;
for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
r.s = 0;
r.clamp();
if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
}
// (protected) r = this^2, r != this (HAC 14.16)
function bnpSquareTo(r) {
var x = this.abs();
var i = r.t = 2*x.t;
while(--i >= 0) r[i] = 0;
for(i = 0; i < x.t-1; ++i) {
var c = x.am(i,x[i],r,2*i,0,1);
if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
r[i+x.t] -= x.DV;
r[i+x.t+1] = 1;
}
}
if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
r.s = 0;
r.clamp();
}
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m. q or r may be null.
function bnpDivRemTo(m,q,r) {
var pm = m.abs();
if(pm.t <= 0) return;
var pt = this.abs();
if(pt.t < pm.t) {
if(q != null) q.fromInt(0);
if(r != null) this.copyTo(r);
return;
}
if(r == null) r = nbi();
var y = nbi(), ts = this.s, ms = m.s;
var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
else { pm.copyTo(y); pt.copyTo(r); }
var ys = y.t;
var y0 = y[ys-1];
if(y0 == 0) return;
var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
var i = r.t, j = i-ys, t = (q==null)?nbi():q;
y.dlShiftTo(j,t);
if(r.compareTo(t) >= 0) {
r[r.t++] = 1;
r.subTo(t,r);
}
BigInteger.ONE.dlShiftTo(ys,t);
t.subTo(y,y); // "negative" y so we can replace sub with am later
while(y.t < ys) y[y.t++] = 0;
while(--j >= 0) {
// Estimate quotient digit
var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
y.dlShiftTo(j,t);
r.subTo(t,r);
while(r[i] < --qd) r.subTo(t,r);
}
}
if(q != null) {
r.drShiftTo(ys,q);
if(ts != ms) BigInteger.ZERO.subTo(q,q);
}
r.t = ys;
r.clamp();
if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
if(ts < 0) BigInteger.ZERO.subTo(r,r);
}
// (public) this mod a
function bnMod(a) {
var r = nbi();
this.abs().divRemTo(a,null,r);
if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
return r;
}
// Modular reduction using "classic" algorithm
function Classic(m) { this.m = m; }
function cConvert(x) {
if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
else return x;
}
function cRevert(x) { return x; }
function cReduce(x) { x.divRemTo(this.m,null,x); }
function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
// justification:
// xy == 1 (mod m)
// xy = 1+km
// xy(2-xy) = (1+km)(1-km)
// x[y(2-xy)] = 1-k^2m^2
// x[y(2-xy)] == 1 (mod m^2)
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
// JS multiply "overflows" differently from C/C++, so care is needed here.
function bnpInvDigit() {
if(this.t < 1) return 0;
var x = this[0];
if((x&1) == 0) return 0;
var y = x&3; // y == 1/x mod 2^2
y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
// last step - calculate inverse mod DV directly;
// assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
// we really want the negative inverse, and -DV < y < DV
return (y>0)?this.DV-y:-y;
}
// Montgomery reduction
function Montgomery(m) {
this.m = m;
this.mp = m.invDigit();
this.mpl = this.mp&0x7fff;
this.mph = this.mp>>15;
this.um = (1<<(m.DB-15))-1;
this.mt2 = 2*m.t;
}
// xR mod m
function montConvert(x) {
var r = nbi();
x.abs().dlShiftTo(this.m.t,r);
r.divRemTo(this.m,null,r);
if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
return r;
}
// x/R mod m
function montRevert(x) {
var r = nbi();
x.copyTo(r);
this.reduce(r);
return r;
}
// x = x/R mod m (HAC 14.32)
function montReduce(x) {
while(x.t <= this.mt2) // pad x so am has enough room later
x[x.t++] = 0;
for(var i = 0; i < this.m.t; ++i) {
// faster way of calculating u0 = x[i]*mp mod DV
var j = x[i]&0x7fff;
var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
// use am to combine the multiply-shift-add into one call
j = i+this.m.t;
x[j] += this.m.am(0,u0,x,i,0,this.m.t);
// propagate carry
while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
}
x.clamp();
x.drShiftTo(this.m.t,x);
if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
}
// r = "x^2/R mod m"; x != r
function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
// r = "xy/R mod m"; x,y != r
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
// (protected) true iff this is even
function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
function bnpExp(e,z) {
if(e > 0xffffffff || e < 1) return BigInteger.ONE;
var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
g.copyTo(r);
while(--i >= 0) {
z.sqrTo(r,r2);
if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
else { var t = r; r = r2; r2 = t; }
}
return z.revert(r);
}
// (public) this^e % m, 0 <= e < 2^32
function bnModPowInt(e,m) {
var z;
if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
return this.exp(e,z);
}
// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
export {
BigInteger,
};
+84
View File
@@ -0,0 +1,84 @@
// Downloaded from http://www-cs-students.stanford.edu/~tjw/jsbn/ by Jeremy White on 6/1/2012
/*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
// prng4.js - uses Arcfour as a PRNG
function Arcfour() {
this.i = 0;
this.j = 0;
this.S = new Array();
}
// Initialize arcfour context from key, an array of ints, each from [0..255]
function ARC4init(key) {
var i, j, t;
for(i = 0; i < 256; ++i)
this.S[i] = i;
j = 0;
for(i = 0; i < 256; ++i) {
j = (j + this.S[i] + key[i % key.length]) & 255;
t = this.S[i];
this.S[i] = this.S[j];
this.S[j] = t;
}
this.i = 0;
this.j = 0;
}
function ARC4next() {
var t;
this.i = (this.i + 1) & 255;
this.j = (this.j + this.S[this.i]) & 255;
t = this.S[this.i];
this.S[this.i] = this.S[this.j];
this.S[this.j] = t;
return this.S[(t + this.S[this.i]) & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
// Plug in your RNG constructor here
function prng_newstate() {
return new Arcfour();
}
// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
var rng_psize = 256;
export {
prng_newstate,
rng_psize,
};
+107
View File
@@ -0,0 +1,107 @@
// Downloaded from http://www-cs-students.stanford.edu/~tjw/jsbn/ by Jeremy White on 6/1/2012
/*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
// Random number generator - requires a PRNG backend, e.g. prng4.js
import { prng_newstate, rng_psize } from './prng4.js';
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng_pool[rng_pptr++] ^= x & 255;
rng_pool[rng_pptr++] ^= (x >> 8) & 255;
rng_pool[rng_pptr++] ^= (x >> 16) & 255;
rng_pool[rng_pptr++] ^= (x >> 24) & 255;
if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
}
// Mix in the current time (w/milliseconds) into the pool
function rng_seed_time() {
rng_seed_int(new Date().getTime());
}
// Initialize the pool with junk if needed.
if(rng_pool == null) {
rng_pool = new Array();
rng_pptr = 0;
var t;
if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
// Extract entropy (256 bits) from NS4 RNG if available
var z = window.crypto.random(32);
for(t = 0; t < z.length; ++t)
rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
}
while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
t = Math.floor(65536 * Math.random());
rng_pool[rng_pptr++] = t >>> 8;
rng_pool[rng_pptr++] = t & 255;
}
rng_pptr = 0;
rng_seed_time();
//rng_seed_int(window.screenX);
//rng_seed_int(window.screenY);
}
function rng_get_byte() {
if(rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next();
}
function rng_get_bytes(ba) {
var i;
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
function SecureRandom() {}
SecureRandom.prototype.nextBytes = rng_get_bytes;
export {
SecureRandom,
};
+153
View File
@@ -0,0 +1,153 @@
// Downloaded from http://www-cs-students.stanford.edu/~tjw/jsbn/ by Jeremy White on 6/1/2012
// Converted into an ES6 module
/*
* Copyright (c) 2003-2005 Tom Wu
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* In addition, the following condition applies:
*
* All redistributions must retain an intact copy of this copyright notice
* and disclaimer.
*/
// Depends on jsbn.js and rng.js
import { BigInteger } from './jsbn.js';
import { SecureRandom } from './rng.js';
// Version 1.1: support utf-8 encoding in pkcs1pad2
// convert a (hex) string to a bignum object
function parseBigInt(str,r) {
return new BigInteger(str,r);
}
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N,E) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
//function RSAEncryptB64(text) {
// var h = this.encrypt(text);
// if(h) return hex2b64(h); else return null;
//}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
export {
RSAKey,
};
+351
View File
@@ -0,0 +1,351 @@
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS 180-1
* Version 2.2 Copyright Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/* Downloaded 6/1/2012 from the above address by Jeremy White.
License reproduce here for completeness:
Copyright (c) 1998 - 2009, Paul Johnston & Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s) { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }
function b64_sha1(s) { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
function hex_hmac_sha1(k, d)
{ return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_sha1(k, d)
{ return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_sha1(k, d, e)
{ return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA1 of a raw string
*/
function rstr_sha1(s)
{
return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));
}
/*
* Calculate the HMAC-SHA1 of a key and some data (raw strings)
*/
function rstr_hmac_sha1(key, data)
{
var bkey = rstr2binb(key);
if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input)
{
try { hexcase } catch(e) { hexcase=0; }
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var output = "";
var x;
for(var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt( x & 0x0F);
}
return output;
}
/*
* Convert a raw string to a base-64 string
*/
function rstr2b64(input)
{
try { b64pad } catch(e) { b64pad=''; }
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var output = "";
var len = input.length;
for(var i = 0; i < len; i += 3)
{
var triplet = (input.charCodeAt(i) << 16)
| (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
| (i + 2 < len ? input.charCodeAt(i+2) : 0);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > input.length * 8) output += b64pad;
else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
}
}
return output;
}
/*
* Convert a raw string to an arbitrary string encoding
*/
function rstr2any(input, encoding)
{
var divisor = encoding.length;
var remainders = Array();
var i, q, x, quotient;
/* Convert to an array of 16-bit big-endian values, forming the dividend */
var dividend = Array(Math.ceil(input.length / 2));
for(i = 0; i < dividend.length; i++)
{
dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
}
/*
* Repeatedly perform a long division. The binary array forms the dividend,
* the length of the encoding is the divisor. Once computed, the quotient
* forms the dividend for the next step. We stop when the dividend is zero.
* All remainders are stored for later use.
*/
while(dividend.length > 0)
{
quotient = Array();
x = 0;
for(i = 0; i < dividend.length; i++)
{
x = (x << 16) + dividend[i];
q = Math.floor(x / divisor);
x -= q * divisor;
if(quotient.length > 0 || q > 0)
quotient[quotient.length] = q;
}
remainders[remainders.length] = x;
dividend = quotient;
}
/* Convert the remainders to the output string */
var output = "";
for(i = remainders.length - 1; i >= 0; i--)
output += encoding.charAt(remainders[i]);
/* Append leading zero equivalents */
var full_length = Math.ceil(input.length * 8 /
(Math.log(encoding.length) / Math.log(2)))
for(i = output.length; i < full_length; i++)
output = encoding[0] + output;
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
function str2rstr_utf8(input)
{
var output = "";
var i = -1;
var x, y;
while(++i < input.length)
{
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
{
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if(x <= 0x7F)
output += String.fromCharCode(x);
else if(x <= 0x7FF)
output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
0x80 | ( x & 0x3F));
else if(x <= 0xFFFF)
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6 ) & 0x3F),
0x80 | ( x & 0x3F));
else if(x <= 0x1FFFFF)
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6 ) & 0x3F),
0x80 | ( x & 0x3F));
}
return output;
}
/*
* Encode a string as utf-16
*/
function str2rstr_utf16le(input)
{
var output = "";
for(var i = 0; i < input.length; i++)
output += String.fromCharCode( input.charCodeAt(i) & 0xFF,
(input.charCodeAt(i) >>> 8) & 0xFF);
return output;
}
function str2rstr_utf16be(input)
{
var output = "";
for(var i = 0; i < input.length; i++)
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
input.charCodeAt(i) & 0xFF);
return output;
}
/*
* Convert a raw string to an array of big-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binb(input)
{
var output = Array(input.length >> 2);
for(var i = 0; i < output.length; i++)
output[i] = 0;
for(var i = 0; i < input.length * 8; i += 8)
output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
return output;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2rstr(input)
{
var output = "";
for(var i = 0; i < input.length * 32; i += 8)
output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
return output;
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function binb_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for(var j = 0; j < 80; j++)
{
if(j < 16) w[j] = x[i + j];
else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = bit_rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
export {
hex_sha1,
rstr_sha1,
};
+268
View File
@@ -0,0 +1,268 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import { RSAKey } from './thirdparty/rsa.js';
import { BigInteger } from './thirdparty/jsbn.js';
import { SecureRandom } from './thirdparty/rng.js';
import { rstr_sha1 } from './thirdparty/sha1.js';
var SHA_DIGEST_LENGTH = 20;
/*----------------------------------------------------------------------------
** General ticket RSA encryption functions - just good enough to
** support what we need to send back an encrypted ticket.
**--------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
** OAEP padding functions. Inspired by the OpenSSL implementation.
**--------------------------------------------------------------------------*/
function MGF1(mask, seed)
{
var i, j, outlen;
for (i = 0, outlen = 0; outlen < mask.length; i++)
{
var combo_buf = new String;
for (j = 0; j < seed.length; j++)
combo_buf += String.fromCharCode(seed[j]);
combo_buf += String.fromCharCode((i >> 24) & 255);
combo_buf += String.fromCharCode((i >> 16) & 255);
combo_buf += String.fromCharCode((i >> 8) & 255);
combo_buf += String.fromCharCode((i) & 255);
var combo_hash = rstr_sha1(combo_buf);
for (j = 0; j < combo_hash.length && outlen < mask.length; j++, outlen++)
{
mask[outlen] = combo_hash.charCodeAt(j);
}
}
}
function RSA_padding_add_PKCS1_OAEP(tolen, from, param)
{
var seed = new Array(SHA_DIGEST_LENGTH);
var rand = new SecureRandom();
rand.nextBytes(seed);
var dblen = tolen - 1 - seed.length;
var db = new Array(dblen);
var padlen = dblen - from.length - 1;
var i;
if (param === undefined)
param = "";
if (padlen < SHA_DIGEST_LENGTH)
{
console.log("Error - data too large for key size.");
return null;
}
for (i = 0; i < padlen; i++)
db[i] = 0;
var param_hash = rstr_sha1(param);
for (i = 0; i < param_hash.length; i++)
db[i] = param_hash.charCodeAt(i);
db[padlen] = 1;
for (i = 0; i < from.length; i++)
db[i + padlen + 1] = from.charCodeAt(i);
var dbmask = new Array(dblen);
if (MGF1(dbmask, seed) < 0)
return null;
for (i = 0; i < dbmask.length; i++)
db[i] ^= dbmask[i];
var seedmask = Array(SHA_DIGEST_LENGTH);
if (MGF1(seedmask, db) < 0)
return null;
for (i = 0; i < seedmask.length; i++)
seed[i] ^= seedmask[i];
var ret = new String;
ret += String.fromCharCode(0);
for (i = 0; i < seed.length; i++)
ret += String.fromCharCode(seed[i]);
for (i = 0; i < db.length; i++)
ret += String.fromCharCode(db[i]);
return ret;
}
function asn_get_length(u8, at)
{
var len = u8[at++];
if (len > 0x80)
{
if (len != 0x81)
{
console.log("Error: we lazily don't support keys bigger than 255 bytes. It'd be easy to fix.");
return null;
}
len = u8[at++];
}
return [ at, len];
}
function find_sequence(u8, at)
{
var lenblock;
at = at || 0;
if (u8[at++] != 0x30)
{
console.log("Error: public key should start with a sequence flag.");
return null;
}
lenblock = asn_get_length(u8, at);
if (! lenblock)
return null;
return lenblock;
}
/*----------------------------------------------------------------------------
** Extract an RSA key from a memory buffer
**--------------------------------------------------------------------------*/
function create_rsa_from_mb(mb, at)
{
var u8 = new Uint8Array(mb);
var lenblock;
var seq;
var ba;
var i;
var ret;
/* We have a sequence which contains a sequence followed by a bit string */
seq = find_sequence(u8, at);
if (! seq)
return null;
at = seq[0];
seq = find_sequence(u8, at);
if (! seq)
return null;
/* Skip over the contained sequence */
at = seq[0] + seq[1];
if (u8[at++] != 0x3)
{
console.log("Error: expecting bit string next.");
return null;
}
/* Get the bit string, which is *itself* a sequence. Having fun yet? */
lenblock = asn_get_length(u8, at);
if (! lenblock)
return null;
at = lenblock[0];
/* Or, not and: the bit string is malformed if EITHER the unused-bits
byte is nonzero or the sequence tag is missing. Requiring both to
be wrong let malformed keys through to be garbage-parsed. */
if (u8[at] != 0 || u8[at + 1] != 0x30)
{
console.log("Error: unexpected values in bit string.");
return null;
}
/* Okay, now we have a sequence of two binary values, we hope. */
seq = find_sequence(u8, at + 1);
if (! seq)
return null;
at = seq[0];
if (u8[at++] != 0x02)
{
console.log("Error: expecting integer n next.");
return null;
}
lenblock = asn_get_length(u8, at);
if (! lenblock)
return null;
at = lenblock[0];
ba = new Array(lenblock[1]);
for (i = 0; i < lenblock[1]; i++)
ba[i] = u8[at + i];
ret = new RSAKey();
ret.n = new BigInteger(ba);
at += lenblock[1];
if (u8[at++] != 0x02)
{
console.log("Error: expecting integer e next.");
return null;
}
lenblock = asn_get_length(u8, at);
if (! lenblock)
return null;
at = lenblock[0];
ret.e = u8[at++];
for (i = 1; i < lenblock[1]; i++)
{
ret.e <<= 8;
ret.e |= u8[at++];
}
return ret;
}
function rsa_encrypt(rsa, str)
{
var i;
var ret = [];
var oaep = RSA_padding_add_PKCS1_OAEP((rsa.n.bitLength()+7)>>3, str);
if (! oaep)
return null;
var ba = new Array(oaep.length);
for (i = 0; i < oaep.length; i++)
ba[i] = oaep.charCodeAt(i);
var bigint = new BigInteger(ba);
var enc = rsa.doPublic(bigint);
var h = enc.toString(16);
/* BigInteger.toString() drops leading zeros, and the ticket field the
caller writes this into is padded at the tail, so a short result
would shift the whole ciphertext. Pad back to the modulus width. */
var hexlen = ((rsa.n.bitLength() + 7) >> 3) * 2;
while (h.length < hexlen)
h = "0" + h;
for (i = 0; i < h.length; i += 2)
ret[i / 2] = parseInt(h.substring(i, i + 2), 16);
return ret;
}
export {
create_rsa_from_mb,
rsa_encrypt,
};
+368
View File
@@ -0,0 +1,368 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
import { KeyNames } from './atKeynames.js';
import { code_to_scancode } from './code_to_scancode.js';
/*----------------------------------------------------------------------------
** Utility settings and functions for Spice
**--------------------------------------------------------------------------*/
var DEBUG = 0;
var PLAYBACK_DEBUG = 0;
var STREAM_DEBUG = 0;
var DUMP_DRAWS = false;
var DUMP_CANVASES = false;
/*----------------------------------------------------------------------------
** We use an Image temporarily, and the image/src does not get garbage
** collected as quickly as we might like. This blank image helps with that.
**--------------------------------------------------------------------------*/
var EMPTY_GIF_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
/*----------------------------------------------------------------------------
** combine_array_buffers
** Combine two array buffers.
** FIXME - this can't be optimal. See wire.js about eliminating the need.
**--------------------------------------------------------------------------*/
function combine_array_buffers(a1, a2)
{
var in1 = new Uint8Array(a1);
var in2 = new Uint8Array(a2);
var ret = new ArrayBuffer(a1.byteLength + a2.byteLength);
var out = new Uint8Array(ret);
var o = 0;
var i;
for (i = 0; i < in1.length; i++)
out[o++] = in1[i];
for (i = 0; i < in2.length; i++)
out[o++] = in2[i];
return ret;
}
/*----------------------------------------------------------------------------
** hexdump_buffer
**--------------------------------------------------------------------------*/
function hexdump_buffer(a)
{
var mg = new Uint8Array(a);
var hex = "";
var str = "";
var last_zeros = 0;
for (var i = 0; i < mg.length; i++)
{
var h = Number(mg[i]).toString(16);
if (h.length == 1)
hex += "0";
hex += h + " ";
if (mg[i] == 10 || mg[i] == 13 || mg[i] == 8)
str += ".";
else
str += String.fromCharCode(mg[i]);
if ((i % 16 == 15) || (i == (mg.length - 1)))
{
while (i % 16 != 15)
{
hex += " ";
i++;
}
if (last_zeros == 0)
console.log(hex + " | " + str);
if (hex == "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ")
{
if (last_zeros == 1)
{
console.log(".");
last_zeros++;
}
else if (last_zeros == 0)
last_zeros++;
}
else
last_zeros = 0;
hex = str = "";
}
}
}
/*----------------------------------------------------------------------------
** Convert arraybuffer to string
**--------------------------------------------------------------------------*/
function arraybuffer_to_str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
/*----------------------------------------------------------------------------
** Converting browser keycodes to AT scancodes is very hard.
** Spice transmits keys using the original AT scan codes, often
** described as 'Scan Code Set 1'.
** There is a confusion of other scan codes; Xorg synthesizes it's
** own in the same atKeynames.c file that has the XT codes.
** Scan code set 2 and 3 are more common, and use different values.
** Further, there is no formal specification for keycodes
** returned by browsers, so we have done our mapping largely with
** empirical testing.
** There has been little rigorous testing with International keyboards,
** and this would be an easy area for non English speakers to contribute.
**--------------------------------------------------------------------------*/
var common_scanmap = [];
/* The following appear to be keycodes that work in most browsers */
common_scanmap['1'.charCodeAt(0)] = KeyNames.KEY_1;
common_scanmap['2'.charCodeAt(0)] = KeyNames.KEY_2;
common_scanmap['3'.charCodeAt(0)] = KeyNames.KEY_3;
common_scanmap['4'.charCodeAt(0)] = KeyNames.KEY_4;
common_scanmap['5'.charCodeAt(0)] = KeyNames.KEY_5;
common_scanmap['6'.charCodeAt(0)] = KeyNames.KEY_6;
common_scanmap['7'.charCodeAt(0)] = KeyNames.KEY_7;
common_scanmap['8'.charCodeAt(0)] = KeyNames.KEY_8;
common_scanmap['9'.charCodeAt(0)] = KeyNames.KEY_9;
common_scanmap['0'.charCodeAt(0)] = KeyNames.KEY_0;
common_scanmap[145] = KeyNames.KEY_ScrollLock;
common_scanmap[103] = KeyNames.KEY_KP_7;
common_scanmap[104] = KeyNames.KEY_KP_8;
common_scanmap[105] = KeyNames.KEY_KP_9;
common_scanmap[100] = KeyNames.KEY_KP_4;
common_scanmap[101] = KeyNames.KEY_KP_5;
common_scanmap[102] = KeyNames.KEY_KP_6;
common_scanmap[107] = KeyNames.KEY_KP_Plus;
common_scanmap[97] = KeyNames.KEY_KP_1;
common_scanmap[98] = KeyNames.KEY_KP_2;
common_scanmap[99] = KeyNames.KEY_KP_3;
common_scanmap[96] = KeyNames.KEY_KP_0;
common_scanmap[109] = KeyNames.KEY_Minus;
common_scanmap[110] = KeyNames.KEY_KP_Decimal;
common_scanmap[191] = KeyNames.KEY_Slash;
common_scanmap[190] = KeyNames.KEY_Period;
common_scanmap[188] = KeyNames.KEY_Comma;
common_scanmap[220] = KeyNames.KEY_BSlash;
common_scanmap[192] = KeyNames.KEY_Tilde;
common_scanmap[222] = KeyNames.KEY_Quote;
common_scanmap[219] = KeyNames.KEY_LBrace;
common_scanmap[221] = KeyNames.KEY_RBrace;
common_scanmap['Q'.charCodeAt(0)] = KeyNames.KEY_Q;
common_scanmap['W'.charCodeAt(0)] = KeyNames.KEY_W;
common_scanmap['E'.charCodeAt(0)] = KeyNames.KEY_E;
common_scanmap['R'.charCodeAt(0)] = KeyNames.KEY_R;
common_scanmap['T'.charCodeAt(0)] = KeyNames.KEY_T;
common_scanmap['Y'.charCodeAt(0)] = KeyNames.KEY_Y;
common_scanmap['U'.charCodeAt(0)] = KeyNames.KEY_U;
common_scanmap['I'.charCodeAt(0)] = KeyNames.KEY_I;
common_scanmap['O'.charCodeAt(0)] = KeyNames.KEY_O;
common_scanmap['P'.charCodeAt(0)] = KeyNames.KEY_P;
common_scanmap['A'.charCodeAt(0)] = KeyNames.KEY_A;
common_scanmap['S'.charCodeAt(0)] = KeyNames.KEY_S;
common_scanmap['D'.charCodeAt(0)] = KeyNames.KEY_D;
common_scanmap['F'.charCodeAt(0)] = KeyNames.KEY_F;
common_scanmap['G'.charCodeAt(0)] = KeyNames.KEY_G;
common_scanmap['H'.charCodeAt(0)] = KeyNames.KEY_H;
common_scanmap['J'.charCodeAt(0)] = KeyNames.KEY_J;
common_scanmap['K'.charCodeAt(0)] = KeyNames.KEY_K;
common_scanmap['L'.charCodeAt(0)] = KeyNames.KEY_L;
common_scanmap['Z'.charCodeAt(0)] = KeyNames.KEY_Z;
common_scanmap['X'.charCodeAt(0)] = KeyNames.KEY_X;
common_scanmap['C'.charCodeAt(0)] = KeyNames.KEY_C;
common_scanmap['V'.charCodeAt(0)] = KeyNames.KEY_V;
common_scanmap['B'.charCodeAt(0)] = KeyNames.KEY_B;
common_scanmap['N'.charCodeAt(0)] = KeyNames.KEY_N;
common_scanmap['M'.charCodeAt(0)] = KeyNames.KEY_M;
common_scanmap[' '.charCodeAt(0)] = KeyNames.KEY_Space;
common_scanmap[13] = KeyNames.KEY_Enter;
common_scanmap[27] = KeyNames.KEY_Escape;
common_scanmap[8] = KeyNames.KEY_BackSpace;
common_scanmap[9] = KeyNames.KEY_Tab;
common_scanmap[16] = KeyNames.KEY_ShiftL;
common_scanmap[17] = KeyNames.KEY_LCtrl;
common_scanmap[18] = KeyNames.KEY_Alt;
common_scanmap[20] = KeyNames.KEY_CapsLock;
common_scanmap[44] = KeyNames.KEY_SysReqest;
common_scanmap[144] = KeyNames.KEY_NumLock;
common_scanmap[112] = KeyNames.KEY_F1;
common_scanmap[113] = KeyNames.KEY_F2;
common_scanmap[114] = KeyNames.KEY_F3;
common_scanmap[115] = KeyNames.KEY_F4;
common_scanmap[116] = KeyNames.KEY_F5;
common_scanmap[117] = KeyNames.KEY_F6;
common_scanmap[118] = KeyNames.KEY_F7;
common_scanmap[119] = KeyNames.KEY_F8;
common_scanmap[120] = KeyNames.KEY_F9;
common_scanmap[121] = KeyNames.KEY_F10;
common_scanmap[122] = KeyNames.KEY_F11;
common_scanmap[123] = KeyNames.KEY_F12;
/* TODO: Break and Print are complex scan codes. XSpice cheats and
uses Xorg synthesized codes to simplify them. Fixing this will
require XSpice to handle the scan codes correctly, and then
fix spice-html5 to send the complex scan codes. */
common_scanmap[42] = 99; // Print, XSpice only
common_scanmap[19] = 101;// Break, XSpice only
/* Handle the so called 'GREY' keys, for the extended keys that
were grey on the original AT keyboard. These are
prefixed, as they were on the PS/2 controller, with an
0xE0 byte to indicate that they are extended */
common_scanmap[111] = 0xE0 | (KeyNames.KEY_Slash << 8);// KP_Divide
common_scanmap[106] = 0xE0 | (KeyNames.KEY_KP_Multiply << 8); // KP_Multiply
common_scanmap[36] = 0xE0 | (KeyNames.KEY_KP_7 << 8); // Home
common_scanmap[38] = 0xE0 | (KeyNames.KEY_KP_8 << 8); // Up
common_scanmap[33] = 0xE0 | (KeyNames.KEY_KP_9 << 8); // PgUp
common_scanmap[37] = 0xE0 | (KeyNames.KEY_KP_4 << 8); // Left
common_scanmap[39] = 0xE0 | (KeyNames.KEY_KP_6 << 8); // Right
common_scanmap[35] = 0xE0 | (KeyNames.KEY_KP_1 << 8); // End
common_scanmap[40] = 0xE0 | (KeyNames.KEY_KP_2 << 8); // Down
common_scanmap[34] = 0xE0 | (KeyNames.KEY_KP_3 << 8); // PgDown
common_scanmap[45] = 0xE0 | (KeyNames.KEY_KP_0 << 8); // Insert
common_scanmap[46] = 0xE0 | (KeyNames.KEY_KP_Decimal << 8); // Delete
common_scanmap[91] = 0xE0 | (0x5B << 8); //KeyNames.KEY_LMeta
common_scanmap[92] = 0xE0 | (0x5C << 8); //KeyNames.KEY_RMeta
common_scanmap[93] = 0xE0 | (0x5D << 8); //KeyNames.KEY_Menu
/* Firefox/Mozilla codes */
var firefox_scanmap = [];
firefox_scanmap[173] = KeyNames.KEY_Minus;
firefox_scanmap[61] = KeyNames.KEY_Equal;
firefox_scanmap[59] = KeyNames.KEY_SemiColon;
/* DOM3 codes */
var DOM_scanmap = [];
DOM_scanmap[189] = KeyNames.KEY_Minus;
DOM_scanmap[187] = KeyNames.KEY_Equal;
DOM_scanmap[186] = KeyNames.KEY_SemiColon;
function get_scancode(keyCode, code)
{
if (code_to_scancode[code] !== undefined) {
return code_to_scancode[code];
}
if (common_scanmap[keyCode] === undefined)
{
if (navigator.userAgent.indexOf("Firefox") != -1)
return firefox_scanmap[keyCode];
else
return DOM_scanmap[keyCode];
}
else
return common_scanmap[keyCode];
}
function keycode_to_start_scan(keyCode, code)
{
var scancode = get_scancode(keyCode, code);
if (scancode === undefined)
{
/* Not an alert: a modal steals the keyboard mid-typing, and an
unmapped key (e.g. Firefox reports keyCode 224 for Meta) is
an ordinary event, not an emergency. */
console.warn('no map for ' + keyCode);
return 0;
}
return scancode;
}
function keycode_to_end_scan(keyCode, code)
{
var scancode = get_scancode(keyCode, code);
if (scancode === undefined)
return 0;
if (scancode < 0x100) {
return scancode | 0x80;
} else {
return scancode | 0x8000;
}
}
function dump_media_element(m)
{
var ret =
"[networkState " + m.networkState +
"|readyState " + m.readyState +
"|error " + m.error +
"|seeking " + m.seeking +
"|duration " + m.duration +
"|paused " + m.paused +
"|ended " + m.error +
"|buffered " + dump_timerange(m.buffered) +
"]";
return ret;
}
function dump_media_source(ms)
{
var ret =
"[duration " + ms.duration +
"|readyState " + ms.readyState + "]";
return ret;
}
function dump_source_buffer(sb)
{
var ret =
"[appendWindowStart " + sb.appendWindowStart +
"|appendWindowEnd " + sb.appendWindowEnd +
"|buffered " + dump_timerange(sb.buffered) +
"|timeStampOffset " + sb.timeStampOffset +
"|updating " + sb.updating +
"]";
return ret;
}
function dump_timerange(tr)
{
var ret;
if (tr)
{
var i = tr.length;
ret = "{len " + i;
if (i > 0)
ret += "; start " + tr.start(0) + "; end " + tr.end(i - 1);
ret += "}";
}
else
ret = "N/A";
return ret;
}
export {
DEBUG,
PLAYBACK_DEBUG,
STREAM_DEBUG,
DUMP_DRAWS,
DUMP_CANVASES,
EMPTY_GIF_IMAGE,
combine_array_buffers,
hexdump_buffer,
arraybuffer_to_str,
keycode_to_start_scan,
keycode_to_end_scan,
dump_media_element,
dump_media_source,
dump_source_buffer,
};
+673
View File
@@ -0,0 +1,673 @@
"use strict";
/*
Copyright (C) 2014 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*----------------------------------------------------------------------------
** EBML identifiers
**--------------------------------------------------------------------------*/
var EBML_HEADER = [ 0x1a, 0x45, 0xdf, 0xa3 ];
var EBML_HEADER_VERSION = [ 0x42, 0x86 ];
var EBML_HEADER_READ_VERSION = [ 0x42, 0xf7 ];
var EBML_HEADER_MAX_ID_LENGTH = [ 0x42, 0xf2 ];
var EBML_HEADER_MAX_SIZE_LENGTH = [ 0x42, 0xf3 ];
var EBML_HEADER_DOC_TYPE = [ 0x42, 0x82 ];
var EBML_HEADER_DOC_TYPE_VERSION = [ 0x42, 0x87 ];
var EBML_HEADER_DOC_TYPE_READ_VERSION = [ 0x42, 0x85 ];
var WEBM_SEGMENT_HEADER = [ 0x18, 0x53, 0x80, 0x67 ];
var WEBM_SEGMENT_INFORMATION = [ 0x15, 0x49, 0xA9, 0x66 ];
var WEBM_TIMECODE_SCALE = [ 0x2A, 0xD7, 0xB1 ];
var WEBM_MUXING_APP = [ 0x4D, 0x80 ];
var WEBM_WRITING_APP = [ 0x57, 0x41 ];
var WEBM_SEEK_HEAD = [ 0x11, 0x4D, 0x9B, 0x74 ];
var WEBM_SEEK = [ 0x4D, 0xBB ];
var WEBM_SEEK_ID = [ 0x53, 0xAB ];
var WEBM_SEEK_POSITION = [ 0x53, 0xAC ];
var WEBM_TRACKS = [ 0x16, 0x54, 0xAE, 0x6B ];
var WEBM_TRACK_ENTRY = [ 0xAE ];
var WEBM_TRACK_NUMBER = [ 0xD7 ];
var WEBM_TRACK_UID = [ 0x73, 0xC5 ];
var WEBM_TRACK_TYPE = [ 0x83 ];
var WEBM_FLAG_ENABLED = [ 0xB9 ];
var WEBM_FLAG_DEFAULT = [ 0x88 ];
var WEBM_FLAG_FORCED = [ 0x55, 0xAA ];
var WEBM_FLAG_LACING = [ 0x9C ];
var WEBM_MIN_CACHE = [ 0x6D, 0xE7 ];
var WEBM_MAX_BLOCK_ADDITION_ID = [ 0x55, 0xEE ];
var WEBM_CODEC_DECODE_ALL = [ 0xAA ];
var WEBM_SEEK_PRE_ROLL = [ 0x56, 0xBB ];
var WEBM_CODEC_DELAY = [ 0x56, 0xAA ];
var WEBM_CODEC_PRIVATE = [ 0x63, 0xA2 ];
var WEBM_CODEC_ID = [ 0x86 ];
var WEBM_VIDEO = [ 0xE0 ] ;
var WEBM_FLAG_INTERLACED = [ 0x9A ] ;
var WEBM_PIXEL_WIDTH = [ 0xB0 ] ;
var WEBM_PIXEL_HEIGHT = [ 0xBA ] ;
var WEBM_AUDIO = [ 0xE1 ] ;
var WEBM_SAMPLING_FREQUENCY = [ 0xB5 ] ;
var WEBM_CHANNELS = [ 0x9F ] ;
var WEBM_CLUSTER = [ 0x1F, 0x43, 0xB6, 0x75 ];
var WEBM_TIME_CODE = [ 0xE7 ] ;
var WEBM_SIMPLE_BLOCK = [ 0xA3 ] ;
/*----------------------------------------------------------------------------
** Various OPUS / Webm constants
**--------------------------------------------------------------------------*/
var Constants = {
CLUSTER_SIMPLEBLOCK_FLAG_KEYFRAME : 1 << 7,
OPUS_FREQUENCY : 48000,
OPUS_CHANNELS : 2,
SPICE_PLAYBACK_CODEC : 'audio/webm; codecs="opus"',
MAX_CLUSTER_TIME : 1000,
EXPECTED_PACKET_DURATION : 10,
GAP_DETECTION_THRESHOLD : 50,
SPICE_VP8_CODEC : 'video/webm; codecs="vp8"',
};
/*----------------------------------------------------------------------------
** EBML utility functions
** These classes can create the binary representation of a webm file
**--------------------------------------------------------------------------*/
function EBML_write_u1_data_len(len, dv, at)
{
var b = 0x80 | len;
dv.setUint8(at, b);
return at + 1;
}
function EBML_write_u8_value(id, val, dv, at)
{
at = EBML_write_array(id, dv, at);
at = EBML_write_u1_data_len(1, dv, at);
dv.setUint8(at, val);
return at + 1;
}
function EBML_write_u32_value(id, val, dv, at)
{
at = EBML_write_array(id, dv, at);
at = EBML_write_u1_data_len(4, dv, at);
dv.setUint32(at, val);
return at + 4;
}
function EBML_write_u16_value(id, val, dv, at)
{
at = EBML_write_array(id, dv, at);
at = EBML_write_u1_data_len(2, dv, at);
dv.setUint16(at, val);
return at + 2;
}
function EBML_write_float_value(id, val, dv, at)
{
at = EBML_write_array(id, dv, at);
at = EBML_write_u1_data_len(4, dv, at);
dv.setFloat32(at, val);
return at + 4;
}
function EBML_write_u64_data_len(len, dv, at)
{
/* Javascript doesn't do 64 bit ints, so this cheats and
just has a max of 32 bits. Fine for our purposes */
dv.setUint8(at++, 0x01);
dv.setUint8(at++, 0x00);
dv.setUint8(at++, 0x00);
dv.setUint8(at++, 0x00);
var val = len & 0xFFFFFFFF;
for (var shift = 24; shift >= 0; shift -= 8)
dv.setUint8(at++, val >> shift);
return at;
}
function EBML_write_array(arr, dv, at)
{
for (var i = 0; i < arr.length; i++)
dv.setUint8(at + i, arr[i]);
return at + arr.length;
}
function EBML_write_string(str, dv, at)
{
for (var i = 0; i < str.length; i++)
dv.setUint8(at + i, str.charCodeAt(i));
return at + str.length;
}
function EBML_write_data(id, data, dv, at)
{
at = EBML_write_array(id, dv, at);
if (data.length < 127)
at = EBML_write_u1_data_len(data.length, dv, at);
else
at = EBML_write_u64_data_len(data.length, dv, at);
if ((typeof data) == "string")
at = EBML_write_string(data, dv, at);
else
at = EBML_write_array(data, dv, at);
return at;
}
/*----------------------------------------------------------------------------
** Webm objects
** These classes can create the binary representation of a webm file
**--------------------------------------------------------------------------*/
function EBMLHeader()
{
this.id = EBML_HEADER;
this.Version = 1;
this.ReadVersion = 1;
this.MaxIDLength = 4;
this.MaxSizeLength = 8;
this.DocType = "webm";
this.DocTypeVersion = 2; /* Not well specified by the WebM guys, but functionally required for Firefox */
this.DocTypeReadVersion = 2;
}
EBMLHeader.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(0x1f, dv, at);
at = EBML_write_u8_value(EBML_HEADER_VERSION, this.Version, dv, at);
at = EBML_write_u8_value(EBML_HEADER_READ_VERSION, this.ReadVersion, dv, at);
at = EBML_write_u8_value(EBML_HEADER_MAX_ID_LENGTH, this.MaxIDLength, dv, at);
at = EBML_write_u8_value(EBML_HEADER_MAX_SIZE_LENGTH, this.MaxSizeLength, dv, at);
at = EBML_write_data(EBML_HEADER_DOC_TYPE, this.DocType, dv, at);
at = EBML_write_u8_value(EBML_HEADER_DOC_TYPE_VERSION, this.DocTypeVersion, dv, at);
at = EBML_write_u8_value(EBML_HEADER_DOC_TYPE_READ_VERSION, this.DocTypeReadVersion, dv, at);
return at;
},
buffer_size: function()
{
return 0x1f + 8 + this.id.length;
},
}
function webm_Segment()
{
this.id = WEBM_SEGMENT_HEADER;
}
webm_Segment.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
dv.setUint8(at++, 0xff);
return at;
},
buffer_size: function()
{
return this.id.length + 1;
},
}
function webm_SegmentInformation()
{
this.id = WEBM_SEGMENT_INFORMATION;
this.timecode_scale = 1000000; /* 1 ms */
this.muxing_app = "spice";
this.writing_app = "spice-html5";
}
webm_SegmentInformation.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = EBML_write_u32_value(WEBM_TIMECODE_SCALE, this.timecode_scale, dv, at);
at = EBML_write_data(WEBM_MUXING_APP, this.muxing_app, dv, at);
at = EBML_write_data(WEBM_WRITING_APP, this.writing_app, dv, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
WEBM_TIMECODE_SCALE.length + 1 + 4 +
WEBM_MUXING_APP.length + 1 + this.muxing_app.length +
WEBM_WRITING_APP.length + 1 + this.writing_app.length;
},
}
function webm_Audio(frequency)
{
this.id = WEBM_AUDIO;
this.sampling_frequency = frequency;
this.channels = Constants.OPUS_CHANNELS;
}
webm_Audio.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = EBML_write_u8_value(WEBM_CHANNELS, this.channels, dv, at);
at = EBML_write_float_value(WEBM_SAMPLING_FREQUENCY, this.sampling_frequency, dv, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
WEBM_SAMPLING_FREQUENCY.length + 1 + 4 +
WEBM_CHANNELS.length + 1 + 1;
},
}
function webm_Video(width, height)
{
this.id = WEBM_VIDEO;
this.flag_interlaced = 0;
this.width = width;
this.height = height;
}
webm_Video.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_INTERLACED, this.flag_interlaced, dv, at);
at = EBML_write_u16_value(WEBM_PIXEL_WIDTH, this.width, dv, at)
at = EBML_write_u16_value(WEBM_PIXEL_HEIGHT, this.height, dv, at)
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
WEBM_FLAG_INTERLACED.length + 1 + 1 +
WEBM_PIXEL_WIDTH.length + 1 + 2 +
WEBM_PIXEL_HEIGHT.length + 1 + 2;
},
}
/* ---------------------------
SeekHead not currently used. Hopefully not needed.
*/
function webm_Seek(seekid, pos)
{
this.id = WEBM_SEEK;
this.pos = pos;
this.seekid = seekid;
}
webm_Seek.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u1_data_len(this.buffer_size() - 1 - this.id.length, dv, at);
at = EBML_write_data(WEBM_SEEK_ID, this.seekid, dv, at)
at = EBML_write_u16_value(WEBM_SEEK_POSITION, this.pos, dv, at)
return at;
},
buffer_size: function()
{
return this.id.length + 1 +
WEBM_SEEK_ID.length + 1 + this.seekid.length +
WEBM_SEEK_POSITION.length + 1 + 2;
},
}
function webm_SeekHead(info_pos, track_pos)
{
this.id = WEBM_SEEK_HEAD;
this.info = new webm_Seek(WEBM_SEGMENT_INFORMATION, info_pos);
this.track = new webm_Seek(WEBM_TRACKS, track_pos);
}
webm_SeekHead.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = this.info.to_buffer(a, at);
at = this.track.to_buffer(a, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
this.info.buffer_size() +
this.track.buffer_size();
},
}
/* -------------------------------
End of Seek Head
*/
function webm_AudioTrackEntry()
{
this.id = WEBM_TRACK_ENTRY;
this.number = 1;
this.uid = 2; // Arbitrary id; most likely makes no difference
this.type = 2; // Audio
this.flag_enabled = 1;
this.flag_default = 1;
this.flag_forced = 1;
this.flag_lacing = 0;
this.min_cache = 0; // fixme - check
this.max_block_addition_id = 0;
this.codec_decode_all = 0; // fixme - check
this.seek_pre_roll = 0; // 80000000; // fixme - check
this.codec_delay = 80000000; // Must match codec_private.preskip
this.codec_id = "A_OPUS";
this.audio = new webm_Audio(Constants.OPUS_FREQUENCY);
// See: http://tools.ietf.org/html/draft-terriberry-oggopus-01
this.codec_private = [ 0x4f, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64, // OpusHead
0x01, // Version
Constants.OPUS_CHANNELS,
0x00, 0x0F, // Preskip - 3840 samples - should be 8ms at 48kHz
0x80, 0xbb, 0x00, 0x00, // 48000
0x00, 0x00, // Output gain
0x00 // Channel mapping family
];
}
webm_AudioTrackEntry.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_NUMBER, this.number, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_UID, this.uid, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_ENABLED, this.flag_enabled, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_DEFAULT, this.flag_default, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_FORCED, this.flag_forced, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_LACING, this.flag_lacing, dv, at);
at = EBML_write_data(WEBM_CODEC_ID, this.codec_id, dv, at);
at = EBML_write_u8_value(WEBM_MIN_CACHE, this.min_cache, dv, at);
at = EBML_write_u8_value(WEBM_MAX_BLOCK_ADDITION_ID, this.max_block_addition_id, dv, at);
at = EBML_write_u8_value(WEBM_CODEC_DECODE_ALL, this.codec_decode_all, dv, at);
at = EBML_write_u32_value(WEBM_CODEC_DELAY, this.codec_delay, dv, at);
at = EBML_write_u32_value(WEBM_SEEK_PRE_ROLL, this.seek_pre_roll, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_TYPE, this.type, dv, at);
at = EBML_write_data(WEBM_CODEC_PRIVATE, this.codec_private, dv, at);
at = this.audio.to_buffer(a, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
WEBM_TRACK_NUMBER.length + 1 + 1 +
WEBM_TRACK_UID.length + 1 + 1 +
WEBM_TRACK_TYPE.length + 1 + 1 +
WEBM_FLAG_ENABLED.length + 1 + 1 +
WEBM_FLAG_DEFAULT.length + 1 + 1 +
WEBM_FLAG_FORCED.length + 1 + 1 +
WEBM_FLAG_LACING.length + 1 + 1 +
WEBM_MIN_CACHE.length + 1 + 1 +
WEBM_MAX_BLOCK_ADDITION_ID.length + 1 + 1 +
WEBM_CODEC_DECODE_ALL.length + 1 + 1 +
WEBM_SEEK_PRE_ROLL.length + 1 + 4 +
WEBM_CODEC_DELAY.length + 1 + 4 +
WEBM_CODEC_ID.length + this.codec_id.length + 1 +
WEBM_CODEC_PRIVATE.length + 1 + this.codec_private.length +
this.audio.buffer_size();
},
}
function webm_VideoTrackEntry(width, height)
{
/*
** In general, we follow specifications found by looking here:
** https://www.webmproject.org/docs/container/
** which points here:
** https://www.matroska.org/technical/specs/index.html
** and here:
** https://datatracker.ietf.org/doc/draft-ietf-cellar-matroska/
** Our goal is to supply mandatory values, and note where we differ
** from the default.
*/
this.id = WEBM_TRACK_ENTRY;
this.number = 1;
this.uid = 1;
this.type = 1; // Video
this.flag_enabled = 1;
this.flag_default = 1;
this.flag_forced = 1; // Different than default; we wish to force
this.flag_lacing = 1;
this.min_cache = 0;
this.max_block_addition_id = 0;
this.codec_id = "V_VP8";
this.codec_decode_all = 1;
this.seek_pre_roll = 0;
this.video = new webm_Video(width, height);
}
webm_VideoTrackEntry.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_NUMBER, this.number, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_UID, this.uid, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_ENABLED, this.flag_enabled, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_DEFAULT, this.flag_default, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_FORCED, this.flag_forced, dv, at);
at = EBML_write_u8_value(WEBM_FLAG_LACING, this.flag_lacing, dv, at);
at = EBML_write_data(WEBM_CODEC_ID, this.codec_id, dv, at);
at = EBML_write_u8_value(WEBM_MIN_CACHE, this.min_cache, dv, at);
at = EBML_write_u8_value(WEBM_MAX_BLOCK_ADDITION_ID, this.max_block_addition_id, dv, at);
at = EBML_write_u8_value(WEBM_CODEC_DECODE_ALL, this.codec_decode_all, dv, at);
at = EBML_write_u32_value(WEBM_SEEK_PRE_ROLL, this.seek_pre_roll, dv, at);
at = EBML_write_u8_value(WEBM_TRACK_TYPE, this.type, dv, at);
at = this.video.to_buffer(a, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
WEBM_TRACK_NUMBER.length + 1 + 1 +
WEBM_TRACK_UID.length + 1 + 1 +
WEBM_FLAG_ENABLED.length + 1 + 1 +
WEBM_FLAG_DEFAULT.length + 1 + 1 +
WEBM_FLAG_FORCED.length + 1 + 1 +
WEBM_FLAG_LACING.length + 1 + 1 +
WEBM_CODEC_ID.length + this.codec_id.length + 1 +
WEBM_MIN_CACHE.length + 1 + 1 +
WEBM_MAX_BLOCK_ADDITION_ID.length + 1 + 1 +
WEBM_CODEC_DECODE_ALL.length + 1 + 1 +
WEBM_SEEK_PRE_ROLL.length + 1 + 4 +
WEBM_TRACK_TYPE.length + 1 + 1 +
this.video.buffer_size();
},
}
function webm_Tracks(entry)
{
this.id = WEBM_TRACKS;
this.track_entry = entry;
}
webm_Tracks.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.buffer_size() - 8 - this.id.length, dv, at);
at = this.track_entry.to_buffer(a, at);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
this.track_entry.buffer_size();
},
}
function webm_Cluster(timecode, data)
{
this.id = WEBM_CLUSTER;
this.timecode = timecode;
this.data = data;
}
webm_Cluster.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
dv.setUint8(at++, 0xff);
at = EBML_write_u32_value(WEBM_TIME_CODE, this.timecode, dv, at);
return at;
},
buffer_size: function()
{
return this.id.length + 1 +
WEBM_TIME_CODE.length + 1 + 4;
},
}
function webm_SimpleBlock(timecode, data, keyframe)
{
this.id = WEBM_SIMPLE_BLOCK;
this.timecode = timecode;
this.data = data;
this.keyframe = keyframe;
}
webm_SimpleBlock.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
var dv = new DataView(a);
at = EBML_write_array(this.id, dv, at);
at = EBML_write_u64_data_len(this.data.byteLength + 4, dv, at);
at = EBML_write_u1_data_len(1, dv, at); // Track #
dv.setUint16(at, this.timecode); at += 2; // timecode - relative to cluster
dv.setUint8(at, this.keyframe ? Constants.CLUSTER_SIMPLEBLOCK_FLAG_KEYFRAME : 0); at += 1; // flags
// FIXME - There should be a better way to copy
var u8 = new Uint8Array(this.data);
for (var i = 0; i < this.data.byteLength; i++)
dv.setUint8(at++, u8[i]);
return at;
},
buffer_size: function()
{
return this.id.length + 8 +
1 + 2 + 1 +
this.data.byteLength;
},
}
function webm_Header()
{
this.ebml = new EBMLHeader;
this.segment = new webm_Segment;
this.seek_head = new webm_SeekHead(0, 0);
this.seek_head.info.pos = this.segment.buffer_size() + this.seek_head.buffer_size();
this.info = new webm_SegmentInformation;
this.seek_head.track.pos = this.seek_head.info.pos + this.info.buffer_size();
}
webm_Header.prototype =
{
to_buffer: function(a, at)
{
at = at || 0;
at = this.ebml.to_buffer(a, at);
at = this.segment.to_buffer(a, at);
at = this.info.to_buffer(a, at);
return at;
},
buffer_size: function()
{
return this.ebml.buffer_size() +
this.segment.buffer_size() +
this.info.buffer_size();
},
}
export {
Constants,
webm_Audio as Audio,
webm_Video as Video,
webm_AudioTrackEntry as AudioTrackEntry,
webm_VideoTrackEntry as VideoTrackEntry,
webm_Tracks as Tracks,
webm_Cluster as Cluster,
webm_SimpleBlock as SimpleBlock,
webm_Header as Header,
};
+140
View File
@@ -0,0 +1,140 @@
"use strict";
/*
Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com>
This file is part of spice-html5.
spice-html5 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spice-html5 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spice-html5. If not, see <http://www.gnu.org/licenses/>.
*/
/*--------------------------------------------------------------------------------------
** SpiceWireReader
** This class will receive messages from a WebSocket and relay it to a given
** callback. It will optionally save and pass along a header, useful in processing
** the mini message format.
**--------------------------------------------------------------------------------------*/
import { DEBUG } from './utils.js';
import { combine_array_buffers } from './utils.js';
function SpiceWireReader(sc, callback)
{
this.sc = sc;
this.callback = callback;
this.needed = 0;
this.size = 0;
this.buffers = [];
this.sc.ws.wire_reader = this;
this.sc.ws.binaryType = "arraybuffer";
this.sc.ws.addEventListener('message', wire_blob_catcher);
}
SpiceWireReader.prototype =
{
/*------------------------------------------------------------------------
** Process messages coming in from our WebSocket
**----------------------------------------------------------------------*/
inbound: function (mb)
{
/* Just buffer if we don't need anything yet */
if (this.needed == 0)
{
this.buffers.push(mb);
this.size += mb.byteLength;
return;
}
/* Optimization - if we have just one inbound block, and it's
suitable for our needs, just use it. */
if (this.buffers.length == 0 && mb.byteLength >= this.needed)
{
if (mb.byteLength > this.needed)
{
this.size = mb.byteLength - this.needed;
this.buffers.push(mb.slice(this.needed));
mb = mb.slice(0, this.needed);
}
this.callback.call(this.sc, mb,
this.saved_msg_header || undefined);
}
else
{
this.buffers.push(mb);
this.size += mb.byteLength;
}
/* Optimization - All it takes is one combine */
while (this.size >= this.needed) {
var count = 0;
var frame = new ArrayBuffer(this.needed);
var view = new Uint8Array(frame);
while (count < frame.byteLength && this.buffers.length > 0) {
var buf = this.buffers.shift();
if (!buf) {
return;
}
var uint8 = new Uint8Array(buf);
var step = frame.byteLength - count;
/* Optimization - use dataview.set() instead of combine_array_buffers() */
if (uint8.length <= step) {
view.set(uint8, count);
count += uint8.length;
this.size -= uint8.length;
} else {
var temp = uint8.slice(0, step);
view.set(temp, count);
count += temp.length;
this.size -= temp.length;
this.buffers.unshift(uint8.slice(step));
}
}
this.callback.call(this.sc, frame, this.saved_msg_header || undefined);
}
},
request: function(n)
{
this.needed = n;
},
save_header: function(h)
{
this.saved_msg_header = h;
},
clear_header: function()
{
this.saved_msg_header = undefined;
},
}
function wire_blob_catcher(e)
{
DEBUG > 1 && console.log(">> WebSockets.onmessage");
DEBUG > 1 && console.log("id " + this.wire_reader.sc.connection_id +"; type " + this.wire_reader.sc.type);
SpiceWireReader.prototype.inbound.call(this.wire_reader, e.data);
}
export {
SpiceWireReader,
};