mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Image boards: Flash (SWF and FLV), played by Ruffle
A board takes Flash when its files say swf or flv (bbs chan board set f files swf,flv), as 4chan's /f/ did, and [chan] ruffle names Ruffle's self-hosted package (make ruffle fetches it from npm into ruffle/). - SWF: FWS and CWS read for the stage, frames, rate and sounds, the tags walked as they unpack with nothing kept (a zlib bomb costs no memory and is refused); ZWS (LZMA) taken as 550x400 with sound - FLV: onMetaData (AMF0) for size and length, the tags for sound and the video codec (Sorenson, Screen, VP6, VP6 alpha, H.264); ffmpeg thumbnails it, a movie gets a card - sound needs the board's sound; an FLV is held to max_video Clicking a Flash thumbnail plays it in a sandboxed frame (/chan/flash: allow-scripts alone, by its CSP and the frame's attribute): no origin, no cookies, nothing of the page. The page fetches the file with its own cookies and hands the bytes over; Ruffle runs with networking, scripting and links off. Ruffle 0.7.1 does not play a standalone FLV, so the BBS makes a small AVM1 movie of its own (/chan/flvplayer.swf: NetStream into a Video of the FLV's size) that plays it from a blob of the frame. Ruffle's files are served at /chan/ruffle/ with CORS open (the frame has no origin), only the package's .js, .wasm and .map. Played in Chromium with Ruffle 0.7.1: a movie, and a Sorenson FLV with sound through the player; both frames of origin "null", cookies refused, no CSP violations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
20 files changed
+915
-24
No files matched your search
@@ -2,3 +2,4 @@
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
/ruffle/
|
||||
@@ -36,7 +36,15 @@ NANPA ?= npa_report.csv
|
||||
phone-data:
|
||||
$(GO) run ./internal/phone/gen -src $(LIBPHONENUMBER) -nanpa $(NANPA)
|
||||
|
||||
# fetches Ruffle's self-hosted package (Flash for the image boards: [chan]
|
||||
# ruffle = ./ruffle) from npm, unpacked into ruffle/
|
||||
RUFFLE_VERSION ?= 0.7.1
|
||||
ruffle:
|
||||
rm -rf ruffle && mkdir ruffle
|
||||
curl -fsSL https://registry.npmjs.org/@ruffle-rs/ruffle/-/ruffle-$(RUFFLE_VERSION).tgz | tar xz -C ruffle --strip-components=1
|
||||
@ls ruffle/ruffle.js
|
||||
|
||||
clean:
|
||||
rm -f bbs
|
||||
|
||||
.PHONY: all bbs test install clean doors-image proto phone-data
|
||||
.PHONY: all bbs test install clean doors-image proto phone-data ruffle
|
||||
@@ -292,6 +292,9 @@ address = 127.0.0.1:2513
|
||||
;ffmpeg = ffmpeg
|
||||
;pdftoppm = pdftoppm
|
||||
;max_video = 120
|
||||
; Flash (files swf,flv), played in the page by Ruffle: its self-hosted
|
||||
; package's directory (make ruffle fetches it into ruffle/)
|
||||
;ruffle = /opt/bbs/ruffle
|
||||
; a country database for the boards with flags (bbs chan board set DIR
|
||||
; flags yes): a MaxMind DB (.mmdb: GeoLite2 Country, DB-IP Lite...) or a
|
||||
; CSV of ranges; read again when it changes. By default [general]'s
|
||||
|
||||
+1
-1
@@ -129,7 +129,7 @@ func usage() {
|
||||
bbs [-config FILE] file del AREA NAME
|
||||
bbs [-config FILE] chan board add DIR TITLE [DESCRIPTION] [-nsfw] [-forced-anon] [-text-only] [-locked] [-login] [-oekaki]
|
||||
[-ids] [-flags]
|
||||
bbs [-config FILE] chan board set DIR KEY VALUE (pages, per_page, mods, nsfw, login, captcha, options, files, sound...)
|
||||
bbs [-config FILE] chan board set DIR KEY VALUE (pages, per_page, mods, nsfw, login, captcha, options, files, sound...: files webm,mp4,pdf,swf,flv)
|
||||
bbs [-config FILE] chan board list | del DIR del takes its posts and images too
|
||||
bbs [-config FILE] chan ban add ADDRESS DAYS [BOARD|-] [REASON...] (0 days: for ever)
|
||||
bbs [-config FILE] chan ban list | del ID
|
||||
|
||||
@@ -43,6 +43,7 @@ address = :8443
|
||||
;ffmpeg = ffmpeg ; videos' thumbnails, a frame (else a card saying what it is)
|
||||
;pdftoppm = pdftoppm ; PDFs' thumbnails, the first page
|
||||
;max_video = 120 ; seconds a video may run (0: any)
|
||||
;ruffle = /usr/share/ruffle ; Ruffle's self-hosted files: Flash played in the page
|
||||
```
|
||||
|
||||
| setting | default | |
|
||||
@@ -61,6 +62,7 @@ address = :8443
|
||||
| `style` | by the board | Yotsuba B on a worksafe board, Yotsuba on the rest, as 4chan does |
|
||||
| `ffmpeg`, `pdftoppm` | none | the programs that make videos' and PDFs' thumbnails (by name on the PATH, or a path); without them, a card saying what the file is ([below](#videos-and-pdfs)) |
|
||||
| `max_video` | `120` | seconds a video may run (0: any length) |
|
||||
| `ruffle` | none | the directory of Ruffle's self-hosted package (`ruffle.js` and its `.wasm`): SWFs and FLVs played in the page ([below](#flash)); without it they are only downloaded |
|
||||
|
||||
## On the terminals
|
||||
|
||||
@@ -245,8 +247,8 @@ bbs chan ban del ID
|
||||
| `oekaki` | no | posters can draw their pictures in the page ([below](#oekaki)) |
|
||||
| `ids` | no | each poster has an ID in a thread ([below](#poster-ids-and-flags)) |
|
||||
| `flags` | no | posts show their country's flag (with `[chan] geoip`) |
|
||||
| `files` | none | files taken besides images: `webm`, `mp4`, `pdf`, as many as wanted (`webm,pdf`); `none` for images only ([below](#videos-and-pdfs)) |
|
||||
| `sound` | no | videos may have sound (an audio track) |
|
||||
| `files` | none | files taken besides images: `webm`, `mp4`, `pdf`, `swf`, `flv`, as many as wanted (`webm,pdf`); `none` for images only ([below](#videos-and-pdfs)) |
|
||||
| `sound` | no | videos and Flash may have sound |
|
||||
| `locked` | no | only staff post |
|
||||
| `login` | `no` | `post`: only the BBS's users post (signed in at `/chan/login`); `all`: only they see the board at all (its pages, images and JSON; others are sent to sign in, and the front page marks it *(members)*) |
|
||||
| `captcha` | `default` | `yes` or `no` for this board, else `[chan]`'s |
|
||||
@@ -292,6 +294,49 @@ Without them, the thumbnail is a card saying what it is (*WEBM 0:05*,
|
||||
*PDF 2 pages*). On the terminals a video or PDF shows as its thumbnail;
|
||||
the file itself is for the browser.
|
||||
|
||||
## Flash
|
||||
|
||||
A board can take Flash too, as 4chan's /f/ did, played by
|
||||
[Ruffle](https://ruffle.rs), the Flash Player emulator, in the page:
|
||||
|
||||
```
|
||||
make ruffle # Ruffle's self-hosted package, into ruffle/ (or unpack a release's)
|
||||
bbs chan board set f files swf,flv
|
||||
bbs chan board set f sound yes
|
||||
```
|
||||
|
||||
```ini
|
||||
[chan]
|
||||
ruffle = /opt/bbs/ruffle ; the directory with ruffle.js (some 30 MB, not in the BBS)
|
||||
```
|
||||
|
||||
| | read for | |
|
||||
|---|---|---|
|
||||
| SWF (`FWS`, `CWS`, `ZWS`) | its stage's size, frames and rate, sounds | compressed ones are walked as they unpack, nothing kept (a small file that unpacks to much is refused at no cost); an LZMA one (`ZWS`) Ruffle unpacks, so it is taken as 550x400 with sound |
|
||||
| FLV | its `onMetaData` (size, length), its tags (sound, the video's codec: Sorenson H.263, Screen, VP6, VP6 alpha, H.264) | without metadata its length is its last tag's time, its size Flash's 320x240 |
|
||||
|
||||
A movie or FLV with sound needs the board's `sound`; an FLV is held to
|
||||
`max_video` as videos are. The thumbnail of an FLV is its first frame
|
||||
with `[chan] ffmpeg`; a movie's is a card (*FLASH 550x400*): nothing here
|
||||
draws Flash but the browser.
|
||||
|
||||
Clicking the thumbnail plays it in place, with *[Close]*. The player is a
|
||||
frame of `/chan/flash`, **sandboxed** (`allow-scripts` alone, by its
|
||||
Content Security Policy as by the frame): it has no origin of the
|
||||
site's, so no cookies, and nothing of the page. The page fetches the file
|
||||
(with its own cookies, so a board for members only works) and hands its
|
||||
bytes to the frame, which hands them to Ruffle with the network,
|
||||
scripting and links off (`allowNetworking: "none"`, `allowScriptAccess:
|
||||
false`, `openUrlMode: "deny"`). Ruffle does not play an FLV by itself,
|
||||
as Flash Player did not: the BBS makes a small movie of its own
|
||||
(`/chan/flvplayer.swf?w=&h=`, a `NetStream` played into a `Video` of the
|
||||
FLV's size) that plays it from a `blob:` of the frame's. Ruffle's files
|
||||
are served at `/chan/ruffle/` to anyone (the frame has no origin to send),
|
||||
only those of the package (`.js`, `.wasm`, `.map`, no directories).
|
||||
Ruffle decodes H.264 with the browser's own decoder (WebCodecs), which
|
||||
Chrome, Edge and Safari have; Sorenson, VP6 and Screen video it decodes
|
||||
itself.
|
||||
|
||||
## Oekaki
|
||||
|
||||
An oekaki board (お絵かき, doodling: `bbs chan board set oe oekaki yes`)
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
package imageboard
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Flash, played by Ruffle (ruffle.rs) where [chan] ruffle names its files:
|
||||
// SWF movies, and FLV videos (which Ruffle plays in a movie of ours that
|
||||
// streams them, as Flash players did). Each runs in a sandboxed frame of
|
||||
// its own, without the page's origin; a movie may not reach the network
|
||||
// or the page's scripts.
|
||||
|
||||
// ---- SWF ----
|
||||
|
||||
// maxSWF is the most a compressed movie may unpack to.
|
||||
const maxSWF = 128 << 20
|
||||
|
||||
// readSWF reads a movie's header: its stage, frame rate and frames; and
|
||||
// whether it has sounds. Its tags are walked as it unpacks, nothing
|
||||
// kept, so a small file that unpacks to much costs no memory.
|
||||
func readSWF(b []byte) (*media, error) {
|
||||
if len(b) < 8 {
|
||||
return nil, errFlash
|
||||
}
|
||||
length := int64(binary.LittleEndian.Uint32(b[4:8]))
|
||||
if length < 21 || length > maxSWF {
|
||||
return nil, errFlash
|
||||
}
|
||||
var in io.Reader
|
||||
switch string(b[:3]) {
|
||||
case "FWS":
|
||||
in = bytes.NewReader(b[8:])
|
||||
case "CWS":
|
||||
z, err := zlib.NewReader(bytes.NewReader(b[8:]))
|
||||
if err != nil {
|
||||
return nil, errFlash
|
||||
}
|
||||
in = z
|
||||
case "ZWS":
|
||||
// LZMA: the stage is packed with the rest; Ruffle unpacks it
|
||||
return &media{W: 550, H: 400, Sound: true}, nil
|
||||
default:
|
||||
return nil, errFlash
|
||||
}
|
||||
body := bufio.NewReaderSize(io.LimitReader(in, length-8), 64)
|
||||
head, _ := body.Peek(21) // a RECT is 17 bytes at most; then rate and frames
|
||||
r := bitReader{b: head}
|
||||
n := int(r.bits(5))
|
||||
var v [4]int64
|
||||
for i := range v {
|
||||
v[i] = r.signed(n)
|
||||
}
|
||||
at := r.byteOffset()
|
||||
if r.err || at+4 > len(head) {
|
||||
return nil, errFlash
|
||||
}
|
||||
m := &media{W: int((v[1] - v[0]) / 20), H: int((v[3] - v[2]) / 20)}
|
||||
rate := float64(binary.LittleEndian.Uint16(head[at:])) / 256
|
||||
frames := int(binary.LittleEndian.Uint16(head[at+2:]))
|
||||
if rate > 0 && frames > 1 {
|
||||
m.DurationMS = int64(float64(frames) / rate * 1000)
|
||||
}
|
||||
read := int64(8 + at + 4)
|
||||
body.Discard(at + 4)
|
||||
// the tags: sounds, and that they run to their end
|
||||
var hb [6]byte
|
||||
for {
|
||||
if _, err := io.ReadFull(body, hb[:2]); err != nil {
|
||||
break
|
||||
}
|
||||
h := binary.LittleEndian.Uint16(hb[:])
|
||||
code, size := int(h>>6), int64(h&0x3f)
|
||||
read += 2
|
||||
if size == 0x3f {
|
||||
if _, err := io.ReadFull(body, hb[2:6]); err != nil {
|
||||
break
|
||||
}
|
||||
size = int64(binary.LittleEndian.Uint32(hb[2:6]))
|
||||
read += 4
|
||||
}
|
||||
if code == 0 {
|
||||
break
|
||||
}
|
||||
switch code {
|
||||
case 14, 18, 45: // DefineSound, SoundStreamHead, SoundStreamHead2
|
||||
m.Sound = true
|
||||
}
|
||||
got, _ := io.CopyN(io.Discard, body, size)
|
||||
read += got
|
||||
if got < size {
|
||||
break
|
||||
}
|
||||
}
|
||||
if read < length-64 { // cut short (some tools pad; none fall short by much)
|
||||
return nil, errors.New("That Flash movie is cut short.")
|
||||
}
|
||||
if m.W < 1 || m.H < 1 || m.W > 8192 || m.H > 8192 {
|
||||
return nil, errFlash
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var errFlash = errors.New("That Flash movie could not be read.")
|
||||
|
||||
// bitReader reads a SWF's bit fields, most significant first.
|
||||
type bitReader struct {
|
||||
b []byte
|
||||
pos int // in bits
|
||||
err bool
|
||||
}
|
||||
|
||||
func (r *bitReader) bits(n int) uint64 {
|
||||
var v uint64
|
||||
for ; n > 0; n-- {
|
||||
if r.pos/8 >= len(r.b) {
|
||||
r.err = true
|
||||
return 0
|
||||
}
|
||||
v = v<<1 | uint64(r.b[r.pos/8]>>(7-r.pos%8)&1)
|
||||
r.pos++
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (r *bitReader) signed(n int) int64 {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
v := int64(r.bits(n))
|
||||
if v&(1<<(n-1)) != 0 {
|
||||
v -= 1 << n
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (r *bitReader) byteOffset() int { return (r.pos + 7) / 8 }
|
||||
|
||||
// ---- FLV ----
|
||||
|
||||
// readFLV reads a video's header, its metadata (onMetaData: size,
|
||||
// length) and its tags (its codecs; its length, if the metadata does not
|
||||
// say).
|
||||
func readFLV(b []byte) (*media, error) {
|
||||
if len(b) < 13 || string(b[:3]) != "FLV" || b[3] != 1 {
|
||||
return nil, errFLV
|
||||
}
|
||||
off := int(binary.BigEndian.Uint32(b[5:9]))
|
||||
if off < 9 || off+4 > len(b) {
|
||||
return nil, errFLV
|
||||
}
|
||||
m := &media{}
|
||||
var meta map[string]any
|
||||
var last uint32
|
||||
video, tags := -1, 0
|
||||
for i := off + 4; i+11 <= len(b); {
|
||||
typ := b[i] & 0x1f
|
||||
size := int(b[i+1])<<16 | int(b[i+2])<<8 | int(b[i+3])
|
||||
ts := uint32(b[i+4])<<16 | uint32(b[i+5])<<8 | uint32(b[i+6]) | uint32(b[i+7])<<24
|
||||
data := i + 11
|
||||
if size > len(b)-data {
|
||||
break // cut short at the end: what is there plays
|
||||
}
|
||||
d := b[data : data+size]
|
||||
switch typ {
|
||||
case 8:
|
||||
m.Sound = true
|
||||
case 9:
|
||||
if video < 0 && len(d) > 0 {
|
||||
video = int(d[0] & 0x0f)
|
||||
}
|
||||
case 18:
|
||||
if meta == nil {
|
||||
meta = amfMeta(d)
|
||||
}
|
||||
}
|
||||
last = max(last, ts)
|
||||
tags++
|
||||
i = data + size + 4
|
||||
}
|
||||
switch {
|
||||
case tags == 0:
|
||||
return nil, errFLV
|
||||
case video < 0:
|
||||
return nil, errors.New("That FLV has no video in it.")
|
||||
case video < 2 || video > 7:
|
||||
return nil, fmt.Errorf("That FLV's video is in a codec Flash did not have (%d).", video)
|
||||
}
|
||||
num := func(k string) float64 {
|
||||
f, _ := meta[k].(float64)
|
||||
if math.IsNaN(f) || math.IsInf(f, 0) || f < 0 || f > 1e9 {
|
||||
return 0
|
||||
}
|
||||
return f
|
||||
}
|
||||
m.W, m.H = int(num("width")), int(num("height"))
|
||||
if d := num("duration"); d > 0 {
|
||||
m.DurationMS = int64(d * 1000)
|
||||
} else {
|
||||
m.DurationMS = int64(last)
|
||||
}
|
||||
if m.W < 1 || m.H < 1 {
|
||||
m.W, m.H = 320, 240 // not said: Flash's own default
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var errFLV = errors.New("That FLV could not be read.")
|
||||
|
||||
// amfMeta reads an onMetaData script tag (AMF0) for its top level's
|
||||
// numbers and strings.
|
||||
func amfMeta(d []byte) map[string]any {
|
||||
r := amf{b: d}
|
||||
if name, ok := r.value(0).(string); !ok || name != "onMetaData" {
|
||||
return nil
|
||||
}
|
||||
out, _ := r.value(0).(map[string]any)
|
||||
return out
|
||||
}
|
||||
|
||||
type amf struct {
|
||||
b []byte
|
||||
i int
|
||||
bad bool
|
||||
}
|
||||
|
||||
func (r *amf) take(n int) []byte {
|
||||
if r.bad || n < 0 || r.i+n > len(r.b) {
|
||||
r.bad = true
|
||||
return nil
|
||||
}
|
||||
s := r.b[r.i : r.i+n]
|
||||
r.i += n
|
||||
return s
|
||||
}
|
||||
|
||||
func (r *amf) str(long bool) string {
|
||||
n := 2
|
||||
if long {
|
||||
n = 4
|
||||
}
|
||||
h := r.take(n)
|
||||
if h == nil {
|
||||
return ""
|
||||
}
|
||||
if long {
|
||||
return string(r.take(int(binary.BigEndian.Uint32(h))))
|
||||
}
|
||||
return string(r.take(int(binary.BigEndian.Uint16(h))))
|
||||
}
|
||||
|
||||
// value reads one AMF0 value: numbers, booleans and strings as they are,
|
||||
// objects and arrays as maps (nested ones read and passed over).
|
||||
func (r *amf) value(depth int) any {
|
||||
t := r.take(1)
|
||||
if t == nil || depth > 16 {
|
||||
r.bad = true
|
||||
return nil
|
||||
}
|
||||
switch t[0] {
|
||||
case 0: // number
|
||||
if b := r.take(8); b != nil {
|
||||
return math.Float64frombits(binary.BigEndian.Uint64(b))
|
||||
}
|
||||
case 1: // boolean
|
||||
if b := r.take(1); b != nil {
|
||||
return b[0] != 0
|
||||
}
|
||||
case 2:
|
||||
return r.str(false)
|
||||
case 12:
|
||||
return r.str(true)
|
||||
case 3, 8: // object, ECMA array
|
||||
if t[0] == 8 {
|
||||
r.take(4)
|
||||
}
|
||||
out := map[string]any{}
|
||||
for !r.bad && len(out) < 4096 {
|
||||
k := r.str(false)
|
||||
if k == "" {
|
||||
if e := r.take(1); e == nil || e[0] != 9 {
|
||||
r.bad = true
|
||||
}
|
||||
break
|
||||
}
|
||||
out[k] = r.value(depth + 1)
|
||||
}
|
||||
return out
|
||||
case 10: // strict array
|
||||
h := r.take(4)
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
for n := binary.BigEndian.Uint32(h); n > 0 && !r.bad; n-- {
|
||||
r.value(depth + 1)
|
||||
}
|
||||
case 11: // date
|
||||
r.take(10)
|
||||
case 5, 6: // null, undefined
|
||||
default:
|
||||
r.bad = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- the FLV player: a movie of ours ----
|
||||
|
||||
// flvPlayer is a movie w by h pixels that plays the FLV its src
|
||||
// parameter names, stretched to its stage:
|
||||
//
|
||||
// nc = new NetConnection(); nc.connect(null);
|
||||
// ns = new NetStream(nc); vid.attachVideo(ns); ns.play(src);
|
||||
func flvPlayer(w, h int) []byte {
|
||||
w, h = min(max(w, 16), 4096), min(max(h, 16), 4096)
|
||||
var tags bytes.Buffer
|
||||
tag := func(code int, body []byte) {
|
||||
if len(body) < 0x3f {
|
||||
binary.Write(&tags, binary.LittleEndian, uint16(code<<6|len(body)))
|
||||
} else {
|
||||
binary.Write(&tags, binary.LittleEndian, uint16(code<<6|0x3f))
|
||||
binary.Write(&tags, binary.LittleEndian, uint32(len(body)))
|
||||
}
|
||||
tags.Write(body)
|
||||
}
|
||||
le16 := func(v int) []byte { return []byte{byte(v), byte(v >> 8)} }
|
||||
tag(69, []byte{0, 0, 0, 0}) // FileAttributes: AVM1
|
||||
tag(9, []byte{0, 0, 0}) // SetBackgroundColor: black
|
||||
// DefineVideoStream 1: no frames of its own, w by h, smoothed
|
||||
tag(60, append(append(append(le16(1), le16(0)...), append(le16(w), le16(h)...)...), 0x01, 0))
|
||||
// PlaceObject2: it, at depth 1, named vid
|
||||
tag(26, append(append([]byte{0x26}, append(le16(1), le16(1)...)...), append([]byte{0x00}, "vid\x00"...)...))
|
||||
var as bytes.Buffer
|
||||
push := func(items ...any) {
|
||||
var p bytes.Buffer
|
||||
for _, it := range items {
|
||||
switch v := it.(type) {
|
||||
case string:
|
||||
p.WriteByte(0)
|
||||
p.WriteString(v)
|
||||
p.WriteByte(0)
|
||||
case int:
|
||||
p.WriteByte(7)
|
||||
binary.Write(&p, binary.LittleEndian, uint32(v))
|
||||
case nil:
|
||||
p.WriteByte(2)
|
||||
}
|
||||
}
|
||||
as.WriteByte(0x96)
|
||||
as.Write(le16(p.Len()))
|
||||
as.Write(p.Bytes())
|
||||
}
|
||||
const (
|
||||
getVar = 0x1c
|
||||
setVar = 0x1d
|
||||
newObject = 0x40
|
||||
callMethod = 0x52
|
||||
pop = 0x17
|
||||
)
|
||||
push("nc", 0, "NetConnection")
|
||||
as.Write([]byte{newObject, setVar})
|
||||
push(nil, 1, "nc")
|
||||
as.WriteByte(getVar)
|
||||
push("connect")
|
||||
as.Write([]byte{callMethod, pop})
|
||||
push("ns", "nc")
|
||||
as.WriteByte(getVar)
|
||||
push(1, "NetStream")
|
||||
as.Write([]byte{newObject, setVar})
|
||||
push("ns")
|
||||
as.WriteByte(getVar)
|
||||
push(1, "vid")
|
||||
as.WriteByte(getVar)
|
||||
push("attachVideo")
|
||||
as.Write([]byte{callMethod, pop})
|
||||
push("src")
|
||||
as.WriteByte(getVar)
|
||||
push(1, "ns")
|
||||
as.WriteByte(getVar)
|
||||
push("play")
|
||||
as.Write([]byte{callMethod, pop})
|
||||
as.WriteByte(0) // end
|
||||
tag(12, as.Bytes())
|
||||
tag(1, nil) // ShowFrame
|
||||
tag(0, nil) // End
|
||||
|
||||
// the stage: a RECT of four 16-bit fields, in twips
|
||||
var rect bytes.Buffer
|
||||
bw := bitWriter{w: &rect}
|
||||
bw.put(16, 5)
|
||||
for _, v := range []int{0, w * 20, 0, h * 20} {
|
||||
bw.put(uint64(v), 16)
|
||||
}
|
||||
bw.flush()
|
||||
var out bytes.Buffer
|
||||
out.WriteString("FWS")
|
||||
out.WriteByte(8)
|
||||
binary.Write(&out, binary.LittleEndian, uint32(8+rect.Len()+4+tags.Len()))
|
||||
out.Write(rect.Bytes())
|
||||
out.Write([]byte{0, 30}) // 30 frames a second
|
||||
out.Write(le16(1)) // one frame
|
||||
out.Write(tags.Bytes())
|
||||
return out.Bytes()
|
||||
}
|
||||
|
||||
type bitWriter struct {
|
||||
w *bytes.Buffer
|
||||
cur byte
|
||||
n int
|
||||
}
|
||||
|
||||
func (b *bitWriter) put(v uint64, n int) {
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
b.cur = b.cur<<1 | byte(v>>i&1)
|
||||
if b.n++; b.n == 8 {
|
||||
b.w.WriteByte(b.cur)
|
||||
b.cur, b.n = 0, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *bitWriter) flush() {
|
||||
if b.n > 0 {
|
||||
b.w.WriteByte(b.cur << (8 - b.n))
|
||||
b.cur, b.n = 0, 0
|
||||
}
|
||||
}
|
||||
|
||||
// ---- serving ----
|
||||
|
||||
// ruffleName is a file of Ruffle's self-hosted package: no directories.
|
||||
var ruffleName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*\.(js|wasm|map)$`)
|
||||
|
||||
// serveRuffle serves Ruffle's files, from [chan] ruffle. The player's
|
||||
// frame is sandboxed, of no origin, so they are fetched from elsewhere:
|
||||
// anyone may (they are Ruffle's, the same for every site).
|
||||
func (s *Server) serveRuffle(q *req, name string) {
|
||||
if s.S.Ruffle == "" || !ruffleName.MatchString(name) {
|
||||
q.notFound()
|
||||
return
|
||||
}
|
||||
f, err := os.Open(filepath.Join(s.S.Ruffle, name))
|
||||
if err != nil {
|
||||
q.notFound()
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
q.notFound()
|
||||
return
|
||||
}
|
||||
h := q.w.Header()
|
||||
h.Set("Content-Type", map[string]string{".js": "text/javascript", ".wasm": "application/wasm",
|
||||
".map": "application/json"}[filepath.Ext(name)])
|
||||
h.Set("Access-Control-Allow-Origin", "*")
|
||||
h.Set("Cross-Origin-Resource-Policy", "cross-origin")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'")
|
||||
h.Set("Cache-Control", "public, max-age=86400")
|
||||
http.ServeContent(q.w, q.r, "", fi.ModTime(), f)
|
||||
}
|
||||
|
||||
// flashPage is the player's frame: Ruffle, and a script that takes the
|
||||
// movie from the page that framed it. It is sandboxed (allow-scripts
|
||||
// alone): no origin of ours, no cookies, nothing of the page's.
|
||||
const flashPage = `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>Flash</title>
|
||||
<link rel="stylesheet" href="/chan/static/flash.css">
|
||||
<script src="/chan/static/flash.js"></script>
|
||||
<script src="/chan/ruffle/ruffle.js"></script>
|
||||
</head><body><div id="player"></div></body></html>
|
||||
`
|
||||
|
||||
func (s *Server) serveFlashPage(q *req) {
|
||||
if s.S.Ruffle == "" {
|
||||
q.notFound()
|
||||
return
|
||||
}
|
||||
h := q.w.Header()
|
||||
h.Del("X-Frame-Options")
|
||||
h.Set("Content-Security-Policy", "sandbox allow-scripts; default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; "+
|
||||
"style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; "+
|
||||
"connect-src 'self' data: blob:; worker-src 'self' blob:; font-src 'self' data:; "+
|
||||
"frame-ancestors 'self'; base-uri 'none'; form-action 'none'")
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "public, max-age=3600")
|
||||
io.WriteString(q.w, flashPage)
|
||||
}
|
||||
|
||||
// serveFLVPlayer is the movie that plays an FLV, for a stage w by h.
|
||||
func (s *Server) serveFLVPlayer(q *req) {
|
||||
w, _ := strconv.Atoi(q.r.URL.Query().Get("w"))
|
||||
hh, _ := strconv.Atoi(q.r.URL.Query().Get("h"))
|
||||
h := q.w.Header()
|
||||
h.Set("Content-Type", "application/x-shockwave-flash")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'")
|
||||
h.Set("Cache-Control", "public, max-age=86400")
|
||||
q.w.Write(flvPlayer(w, hh))
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package imageboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// cws is a movie compressed, as Flash's own were.
|
||||
func cws(fws []byte) []byte {
|
||||
var z bytes.Buffer
|
||||
w := zlib.NewWriter(&z)
|
||||
w.Write(fws[8:])
|
||||
w.Close()
|
||||
return append(append([]byte("CWS"), fws[3:8]...), z.Bytes()...)
|
||||
}
|
||||
|
||||
// noMeta is an FLV without its onMetaData tag.
|
||||
func noMeta(b []byte) []byte {
|
||||
off := int(binary.BigEndian.Uint32(b[5:9]))
|
||||
out := append([]byte{}, b[:off+4]...)
|
||||
for i := off + 4; i+11 <= len(b); {
|
||||
size := int(b[i+1])<<16 | int(b[i+2])<<8 | int(b[i+3])
|
||||
end := i + 11 + size + 4
|
||||
if b[i] != 18 {
|
||||
out = append(out, b[i:end]...)
|
||||
}
|
||||
i = end
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestReadFlash(t *testing.T) {
|
||||
swf := testFile(t, "tiny.swf")
|
||||
for name, b := range map[string][]byte{"FWS": swf, "CWS": cws(swf)} {
|
||||
m, err := readSWF(b)
|
||||
if err != nil || m.W != 32 || m.H != 24 || m.DurationMS != 1000 || m.Sound {
|
||||
t.Errorf("%s: %+v %v", name, m, err)
|
||||
}
|
||||
}
|
||||
if _, err := readSWF(swf[:len(swf)/2]); err == nil {
|
||||
t.Error("a movie cut in half read")
|
||||
}
|
||||
if m, err := readSWF([]byte("ZWS\x0d\x00\x10\x00\x00junkjunkjunk")); err != nil || !m.Sound {
|
||||
t.Errorf("an LZMA movie: %+v %v", m, err)
|
||||
}
|
||||
for _, bad := range []string{"FWS", "FWS\x08\xff\xff\xff\xff", "CWS\x08\x40\x00\x00\x00not zlib at all"} {
|
||||
if _, err := readSWF([]byte(bad)); err == nil {
|
||||
t.Errorf("%q read", bad)
|
||||
}
|
||||
}
|
||||
|
||||
flv := testFile(t, "tiny.flv")
|
||||
if m, err := readFLV(flv); err != nil || m.W != 32 || m.H != 24 || !m.Sound || m.DurationMS < 900 || m.DurationMS > 1100 {
|
||||
t.Errorf("tiny.flv: %+v %v", m, err)
|
||||
}
|
||||
// without its metadata: the length from the tags, the size Flash's default
|
||||
if m, err := readFLV(noMeta(flv)); err != nil || m.W != 320 || m.DurationMS < 700 {
|
||||
t.Errorf("without metadata: %+v %v", m, err)
|
||||
}
|
||||
if _, err := readFLV(flv[:13]); err == nil {
|
||||
t.Error("an FLV of no tags read")
|
||||
}
|
||||
|
||||
// the player is a movie of the size asked, that plays src
|
||||
p := flvPlayer(640, 360)
|
||||
m, err := readSWF(p)
|
||||
if err != nil || m.W != 640 || m.H != 360 {
|
||||
t.Fatalf("the player: %+v %v", m, err)
|
||||
}
|
||||
for _, s := range []string{"NetConnection", "NetStream", "attachVideo", "play", "src", "vid"} {
|
||||
if !bytes.Contains(p, []byte(s+"\x00")) {
|
||||
t.Errorf("the player has no %s", s)
|
||||
}
|
||||
}
|
||||
if int(binary.LittleEndian.Uint32(p[4:8])) != len(p) {
|
||||
t.Errorf("the player's length: %d, is %d", binary.LittleEndian.Uint32(p[4:8]), len(p))
|
||||
}
|
||||
}
|
||||
|
||||
// Flash on a board: taken as the board says, played by Ruffle where it
|
||||
// is, in a sandboxed frame; its files served to that frame.
|
||||
func TestFlashPosts(t *testing.T) {
|
||||
s := setup(t)
|
||||
anon := s.browser()
|
||||
s.bd.FileTypes = "swf,flv"
|
||||
s.b.Store.UpdateBoard(s.bd)
|
||||
post := func(name string, b []byte) (int, string) {
|
||||
code, _, body := anon.post("b", map[string]string{"com": name}, b, name)
|
||||
return code, body
|
||||
}
|
||||
if code, body := post("tiny.flv", testFile(t, "tiny.flv")); code != 400 || !strings.Contains(body, "without sound") {
|
||||
t.Fatalf("an FLV with sound: %d %s", code, body)
|
||||
}
|
||||
if code, body := post("tiny.swf", testFile(t, "tiny.swf")); code != 303 && code != 200 {
|
||||
t.Fatalf("a movie: %d %s", code, body)
|
||||
}
|
||||
s.bd.Sound = true
|
||||
s.b.Store.UpdateBoard(s.bd)
|
||||
if code, body := post("tiny.flv", testFile(t, "tiny.flv")); code != 303 && code != 200 {
|
||||
t.Fatalf("an FLV: %d %s", code, body)
|
||||
}
|
||||
get := func(u string) (*http.Response, string) {
|
||||
resp, err := http.Get(s.ts.URL + u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return resp, string(b)
|
||||
}
|
||||
// without Ruffle: links to the files, no player
|
||||
_, _, page := anon.get("/chan/b/")
|
||||
if strings.Contains(page, "flashThumb") || !strings.Contains(page, "32x24, Flash)") || !strings.Contains(page, "32x24, 0:01)") {
|
||||
t.Errorf("without Ruffle: %s", page)
|
||||
}
|
||||
if r, _ := get("/chan/flash"); r.StatusCode != 404 {
|
||||
t.Errorf("/chan/flash without Ruffle: %d", r.StatusCode)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
os.WriteFile(filepath.Join(dir, "ruffle.js"), []byte("// ruffle"), 0644)
|
||||
os.WriteFile(filepath.Join(dir, "core.wasm"), []byte("\x00asm"), 0644)
|
||||
os.WriteFile(filepath.Join(t.TempDir(), "secret.js"), []byte("no"), 0644)
|
||||
s.srv.S.Ruffle = dir
|
||||
_, _, page = anon.get("/chan/b/")
|
||||
for _, want := range []string{`class="fileThumb flashThumb" href="/chan/b/src/`, `data-flash=".swf" data-w="32" data-h="24"`, `data-flash=".flv"`} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Errorf("the index has no %q", want)
|
||||
}
|
||||
}
|
||||
r, body := get("/chan/flash")
|
||||
csp := r.Header.Get("Content-Security-Policy")
|
||||
if r.StatusCode != 200 || !strings.HasPrefix(csp, "sandbox allow-scripts;") || !strings.Contains(csp, "frame-ancestors 'self'") ||
|
||||
r.Header.Get("X-Frame-Options") != "" || !strings.Contains(body, "/chan/ruffle/ruffle.js") {
|
||||
t.Errorf("the player's page: %d %q %q", r.StatusCode, csp, r.Header.Get("X-Frame-Options"))
|
||||
}
|
||||
for u, typ := range map[string]string{"/chan/ruffle/ruffle.js": "text/javascript", "/chan/ruffle/core.wasm": "application/wasm"} {
|
||||
if r, _ := get(u); r.StatusCode != 200 || r.Header.Get("Content-Type") != typ || r.Header.Get("Access-Control-Allow-Origin") != "*" {
|
||||
t.Errorf("%s: %d %s", u, r.StatusCode, r.Header.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
for _, u := range []string{"/chan/ruffle/..%2fsecret.js", "/chan/ruffle/README.md", "/chan/ruffle/", "/chan/ruffle/sub/ruffle.js"} {
|
||||
if r, _ := get(u); r.StatusCode != 404 {
|
||||
t.Errorf("%s: %d", u, r.StatusCode)
|
||||
}
|
||||
}
|
||||
r, body = get("/chan/flvplayer.swf?w=32&h=24")
|
||||
if m, err := readSWF([]byte(body)); r.StatusCode != 200 || err != nil || m.W != 32 {
|
||||
t.Errorf("the FLV player: %d %v %v", r.StatusCode, m, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A small movie that unpacks to a great deal is read as it unpacks:
|
||||
// refused (it is no movie), and nothing much kept meanwhile.
|
||||
func TestSWFBomb(t *testing.T) {
|
||||
var z bytes.Buffer
|
||||
w := zlib.NewWriter(&z)
|
||||
head := []byte{0x50, 0x00, 0x05, 0xdc, 0x00, 0x05, 0xdc, 0x00, 0x00, 0x18, 0x01, 0x00} // a stage, 24 fps, 1 frame
|
||||
w.Write(head)
|
||||
tag := []byte{0x3f, 0x03, 0xff, 0xff, 0xff, 0x07} // a tag of 128 MB: zeros
|
||||
w.Write(tag)
|
||||
zeros := make([]byte, 1<<20)
|
||||
for i := 0; i < 100; i++ {
|
||||
w.Write(zeros)
|
||||
}
|
||||
w.Close()
|
||||
b := append([]byte{'C', 'W', 'S', 10}, 0, 0, 0, 0)
|
||||
binary.LittleEndian.PutUint32(b[4:], 120<<20)
|
||||
b = append(b, z.Bytes()...)
|
||||
if len(b) > 1<<20 {
|
||||
t.Fatalf("the bomb is %d bytes", len(b))
|
||||
}
|
||||
var before, after runtime.MemStats
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&before)
|
||||
_, err := readSWF(b)
|
||||
runtime.ReadMemStats(&after)
|
||||
if err == nil {
|
||||
t.Error("the bomb read as a movie")
|
||||
}
|
||||
if grew := after.TotalAlloc - before.TotalAlloc; grew > 8<<20 {
|
||||
t.Errorf("reading it took %d MB", grew>>20)
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,9 @@ type Settings struct {
|
||||
// and a video's longest length (0: any)
|
||||
FFmpeg, PDFToPPM string
|
||||
MaxVideo time.Duration
|
||||
// Ruffle's self-hosted files (ruffle.js and its .wasm), to play Flash
|
||||
// in the page ("": SWFs and FLVs are only downloaded)
|
||||
Ruffle string
|
||||
}
|
||||
|
||||
// Defaults are the settings unless bbs.conf says otherwise.
|
||||
@@ -134,7 +137,7 @@ const (
|
||||
|
||||
// reserved are the names no board may have: the image boards' own.
|
||||
var reserved = map[string]bool{"static": true, "manage": true, "login": true, "logout": true, "banned": true,
|
||||
"style": true, "boards.json": true,
|
||||
"style": true, "boards.json": true, "ruffle": true, "flash": true, "flvplayer.swf": true,
|
||||
"captcha": true, "captcha.png": true, "captcha.json": true}
|
||||
|
||||
// ValidDir says what is wrong with a board's directory ("": nothing).
|
||||
@@ -256,6 +259,15 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
http.StripPrefix(Base+"/static/", s.static).ServeHTTP(w, r)
|
||||
return
|
||||
case seg[0] == "ruffle" && len(seg) == 2 && get:
|
||||
s.serveRuffle(q, seg[1])
|
||||
return
|
||||
case len(seg) == 1 && seg[0] == "flash" && get:
|
||||
s.serveFlashPage(q)
|
||||
return
|
||||
case len(seg) == 1 && seg[0] == "flvplayer.swf" && get:
|
||||
s.serveFLVPlayer(q)
|
||||
return
|
||||
case len(seg) == 1 && seg[0] == "boards.json" && get:
|
||||
s.boardsJSON(q)
|
||||
return
|
||||
@@ -657,5 +669,5 @@ func IsAsset(r *http.Request) bool {
|
||||
return false
|
||||
}
|
||||
seg := strings.Split(strings.TrimPrefix(r.URL.Path, Base+"/"), "/")
|
||||
return len(seg) == 2 && seg[0] == "static" || len(seg) == 3 && (seg[1] == "src" || seg[1] == "thumb")
|
||||
return len(seg) == 2 && (seg[0] == "static" || seg[0] == "ruffle") || len(seg) == 3 && (seg[1] == "src" || seg[1] == "thumb")
|
||||
}
|
||||
@@ -40,10 +40,15 @@ var mediaTypes = map[string]struct{ mime, kind string }{
|
||||
".webm": {"video/webm", "webm"},
|
||||
".mp4": {"video/mp4", "mp4"},
|
||||
".pdf": {"application/pdf", "pdf"},
|
||||
".swf": {"application/x-shockwave-flash", "swf"},
|
||||
".flv": {"video/x-flv", "flv"},
|
||||
}
|
||||
|
||||
// FileKinds are the file types a board may take besides images.
|
||||
var FileKinds = []string{"webm", "mp4", "pdf"}
|
||||
var FileKinds = []string{"webm", "mp4", "pdf", "swf", "flv"}
|
||||
|
||||
// kindNames are the kinds as the post form says them.
|
||||
var kindNames = map[string]string{"webm": "WebM", "mp4": "MP4", "pdf": "PDF", "swf": "SWF", "flv": "FLV"}
|
||||
|
||||
// fileType is any file's MIME type by its extension ("": none kept).
|
||||
func fileType(ext string) string {
|
||||
@@ -63,6 +68,10 @@ func sniffMedia(b []byte) string {
|
||||
return ".mp4"
|
||||
case bytes.HasPrefix(b, []byte("%PDF-")):
|
||||
return ".pdf"
|
||||
case len(b) >= 8 && (string(b[:3]) == "FWS" || string(b[:3]) == "CWS" || string(b[:3]) == "ZWS"):
|
||||
return ".swf"
|
||||
case bytes.HasPrefix(b, []byte("FLV\x01")):
|
||||
return ".flv"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -451,7 +460,7 @@ func taken(b *store.Board) error {
|
||||
kinds := "JPEG, PNG, GIF, WebP"
|
||||
for _, k := range FileKinds {
|
||||
if takes(b, k) {
|
||||
kinds += ", " + map[string]string{"webm": "WebM", "mp4": "MP4", "pdf": "PDF"}[k]
|
||||
kinds += ", " + kindNames[k]
|
||||
}
|
||||
}
|
||||
if i := strings.LastIndex(kinds, ", "); i >= 0 {
|
||||
@@ -479,11 +488,18 @@ func (s *Server) prepareFile(b *store.Board, data []byte, side int, bg color.Col
|
||||
m, err = readMP4(data)
|
||||
case ".pdf":
|
||||
m, err = readPDF(data)
|
||||
case ".swf":
|
||||
m, err = readSWF(data)
|
||||
case ".flv":
|
||||
m, err = readFLV(data)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
video := ext != ".pdf"
|
||||
if ext == ".swf" && m.Sound && !b.Sound {
|
||||
return nil, errors.New("This board takes Flash without sound.")
|
||||
}
|
||||
video := fileKind(ext) == "video" || ext == ".flv"
|
||||
if video {
|
||||
switch {
|
||||
case m.W < 1 || m.H < 1:
|
||||
@@ -509,13 +525,12 @@ func (s *Server) prepareFile(b *store.Board, data []byte, side int, bg color.Col
|
||||
}
|
||||
if img == nil {
|
||||
w, h := fit(m.W, m.H, side)
|
||||
if video {
|
||||
label := "WEBM"
|
||||
if ext == ".mp4" {
|
||||
label = "MP4"
|
||||
}
|
||||
img = card(w, h, label, clock(m.DurationMS))
|
||||
} else {
|
||||
switch {
|
||||
case ext == ".swf":
|
||||
img = card(w, h, "FLASH", fmt.Sprintf("%dx%d", m.W, m.H))
|
||||
case video:
|
||||
img = card(w, h, strings.ToUpper(strings.TrimPrefix(ext, ".")), clock(m.DurationMS))
|
||||
default:
|
||||
pages := "PDF"
|
||||
if m.Pages > 0 {
|
||||
pages = strconv.Itoa(m.Pages) + " " + plural(m.Pages, "page", "pages")
|
||||
@@ -549,7 +564,7 @@ const helperTimeout = 30 * time.Second
|
||||
func (s *Server) frame(data []byte, ext string) (image.Image, error) {
|
||||
var tool string
|
||||
switch ext {
|
||||
case ".webm", ".mp4":
|
||||
case ".webm", ".mp4", ".flv":
|
||||
tool = s.S.FFmpeg
|
||||
case ".pdf":
|
||||
tool = s.S.PDFToPPM
|
||||
@@ -576,7 +591,7 @@ func (s *Server) frame(data []byte, ext string) (image.Image, error) {
|
||||
cmd = exec.CommandContext(ctx, tool, "-f", "1", "-l", "1", "-png", "-scale-to", "500", "-singlefile", in, out)
|
||||
} else {
|
||||
// the container named, not guessed: nothing but the file is read
|
||||
format := map[string]string{".webm": "matroska", ".mp4": "mov"}[ext]
|
||||
format := map[string]string{".webm": "matroska", ".mp4": "mov", ".flv": "flv"}[ext]
|
||||
cmd = exec.CommandContext(ctx, tool, "-nostdin", "-v", "error", "-protocol_whitelist", "file",
|
||||
"-f", format, "-i", in, "-frames:v", "1", "-an", "-vf", "scale='min(500,iw)':-2", "-f", "image2", out+".png")
|
||||
}
|
||||
@@ -627,6 +642,8 @@ func fileKind(ext string) string {
|
||||
return "video"
|
||||
case ".pdf":
|
||||
return "pdf"
|
||||
case ".swf", ".flv":
|
||||
return "flash"
|
||||
}
|
||||
return "image"
|
||||
}
|
||||
@@ -186,7 +186,7 @@ func TestMediaPosts(t *testing.T) {
|
||||
// Whatever is uploaded, reading it ends: an answer or a refusal, never a
|
||||
// panic or a hang.
|
||||
func FuzzReadMedia(f *testing.F) {
|
||||
for _, name := range []string{"quiet.webm", "sound.webm", "live.webm", "quiet.mp4", "hevc.mp4", "plain.mkv", "two.pdf"} {
|
||||
for _, name := range []string{"quiet.webm", "sound.webm", "live.webm", "quiet.mp4", "hevc.mp4", "plain.mkv", "two.pdf", "tiny.swf", "tiny.flv"} {
|
||||
b, _ := os.ReadFile(filepath.Join("testdata", name))
|
||||
f.Add(b)
|
||||
}
|
||||
@@ -194,5 +194,7 @@ func FuzzReadMedia(f *testing.F) {
|
||||
readWebM(b)
|
||||
readMP4(b)
|
||||
readPDF(b)
|
||||
readSWF(b)
|
||||
readFLV(b)
|
||||
})
|
||||
}
|
||||
@@ -82,6 +82,7 @@ type postView struct {
|
||||
Index bool // shown on a board's index (a thread's first gets [Reply])
|
||||
Draw bool // its board is an oekaki board: its drawing can be drawn over
|
||||
IDCount int // the posts by its poster's ID in the thread (on a thread's page)
|
||||
Play bool // its file is Flash, and Ruffle is here to play it
|
||||
}
|
||||
|
||||
// threadView is a thread as a board's index or its own page shows it.
|
||||
@@ -163,6 +164,7 @@ func (q *req) view(b *store.Board, p *store.BoardPost, l *links, here int64, cut
|
||||
if p.HasFile() {
|
||||
v.SrcURL = fmt.Sprintf("%s/%s/src/%d%s", Base, b.Dir, p.Tim, p.Ext)
|
||||
v.ThumbURL = fmt.Sprintf("%s/%s/thumb/%ds.jpg", Base, b.Dir, p.Tim)
|
||||
v.Play = fileKind(p.Ext) == "flash" && q.s.S.Ruffle != ""
|
||||
}
|
||||
v.Staff = q.staff(b) != ""
|
||||
v.Index = here == 0
|
||||
@@ -400,8 +402,8 @@ func (q *req) form(b *store.Board, op *store.BoardPost) formView {
|
||||
for _, k := range FileKinds {
|
||||
if takes(b, k) {
|
||||
f.Accept += "," + mediaTypes["."+k].mime
|
||||
words = append(words, map[string]string{"webm": "WebM", "mp4": "MP4", "pdf": "PDF"}[k])
|
||||
video = video || k != "pdf"
|
||||
words = append(words, kindNames[k])
|
||||
video = video || k == "webm" || k == "mp4" || k == "flv"
|
||||
}
|
||||
}
|
||||
for i, w := range words {
|
||||
|
||||
@@ -51,6 +51,7 @@ ul.rules { margin: 4px 0 0; padding-left: 16px; font-size: 8pt; max-width: 420px
|
||||
.fileThumb { float: left; margin: 3px 20px 5px; }
|
||||
.post.reply .fileThumb { margin: 3px 20px 5px 20px; }
|
||||
.fileThumb img.expanded { max-width: calc(100vw - 80px); height: auto; }
|
||||
iframe.expandedFlash { display: block; float: left; margin: 3px 20px 5px; border: 0; background: #000; }
|
||||
video.expandedVideo { display: block; float: left; margin: 3px 20px 5px; max-width: calc(100vw - 80px); max-height: 90vh; }
|
||||
.fileDeleted { display: inline-block; font-size: 8pt; font-weight: bold; padding: 20px 10px; margin: 3px 20px; border: 1px dashed; }
|
||||
blockquote.postMessage { margin: 13px 40px 13px 40px; overflow-wrap: anywhere; }
|
||||
|
||||
@@ -48,12 +48,53 @@
|
||||
file.querySelector(".fileText").append(close);
|
||||
return;
|
||||
}
|
||||
// Flash: Ruffle, in a sandboxed frame of no origin, handed the movie
|
||||
// (fetched here, with this page's cookies) and nothing else
|
||||
if (a.classList.contains("flashThumb") && !e.ctrlKey && !e.metaKey && !e.shiftKey && e.button === 0) {
|
||||
e.preventDefault();
|
||||
var ffile = a.closest(".file");
|
||||
var w = +a.dataset.w || 550, h = +a.dataset.h || 400;
|
||||
var room = Math.min(window.innerWidth - 80, w * 2), scale = Math.min(1, room / w, (window.innerHeight * 0.85) / h);
|
||||
var frame = document.createElement("iframe");
|
||||
frame.className = "expandedFlash";
|
||||
frame.setAttribute("sandbox", "allow-scripts");
|
||||
frame.setAttribute("allow", "autoplay; fullscreen");
|
||||
frame.width = Math.round(w * scale);
|
||||
frame.height = Math.round(h * scale);
|
||||
frame.src = "/chan/flash";
|
||||
var flv = a.dataset.flash === ".flv";
|
||||
var files = [fetch(a.href, {credentials: "same-origin"}).then(function (r) { return r.arrayBuffer(); })];
|
||||
if (flv) files.push(fetch("/chan/flvplayer.swf?w=" + w + "&h=" + h).then(function (r) { return r.arrayBuffer(); }));
|
||||
var onMessage = function (m) {
|
||||
if (m.source !== frame.contentWindow || m.data !== "ready") return;
|
||||
window.removeEventListener("message", onMessage);
|
||||
Promise.all(files).then(function (got) {
|
||||
var msg = flv ? {flv: got[0], player: got[1]} : {swf: got[0]};
|
||||
frame.contentWindow.postMessage(msg, "*", got);
|
||||
});
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
a.hidden = true;
|
||||
a.after(frame);
|
||||
var fclose = document.createElement("span");
|
||||
fclose.className = "videoClose";
|
||||
fclose.append(" [");
|
||||
var fx = document.createElement("a");
|
||||
fx.href = "#";
|
||||
fx.className = "closeVideo";
|
||||
fx.textContent = "Close";
|
||||
fclose.append(fx, "]");
|
||||
ffile.querySelector(".fileText").append(fclose);
|
||||
return;
|
||||
}
|
||||
if (a.classList.contains("closeVideo")) {
|
||||
e.preventDefault();
|
||||
var f = a.closest(".file");
|
||||
var vid = f.querySelector("video.expandedVideo");
|
||||
if (vid) { vid.pause(); vid.remove(); }
|
||||
f.querySelector(".videoThumb").hidden = false;
|
||||
var fl = f.querySelector("iframe.expandedFlash");
|
||||
if (fl) fl.remove();
|
||||
f.querySelector(".fileThumb").hidden = false;
|
||||
a.closest(".videoClose").remove();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
|
||||
#player, ruffle-player { display: block; width: 100%; height: 100%; }
|
||||
@@ -0,0 +1,39 @@
|
||||
// The Flash player's frame: sandboxed (no origin, no cookies, nothing of
|
||||
// the page's), it takes a movie from the page that framed it and plays it
|
||||
// in Ruffle. A movie may not reach the network, open pages or call any
|
||||
// script; an FLV is played by the board's own player movie, from a blob
|
||||
// of this frame's.
|
||||
(function () {
|
||||
"use strict";
|
||||
window.RufflePlayer = window.RufflePlayer || {};
|
||||
window.RufflePlayer.config = {
|
||||
publicPath: "/chan/ruffle/",
|
||||
polyfills: false,
|
||||
autoplay: "on",
|
||||
unmuteOverlay: "visible",
|
||||
splashScreen: false,
|
||||
letterbox: "on",
|
||||
allowScriptAccess: false,
|
||||
allowNetworking: "none",
|
||||
openUrlMode: "deny",
|
||||
showSwfDownload: false,
|
||||
upgradeToHttps: true,
|
||||
warnOnUnsupportedContent: false,
|
||||
logLevel: "error"
|
||||
};
|
||||
window.addEventListener("message", function (e) {
|
||||
if (e.source !== window.parent || !e.data || typeof e.data !== "object") return;
|
||||
var p = window.RufflePlayer.newest().createPlayer();
|
||||
document.getElementById("player").append(p);
|
||||
if (e.data.swf instanceof ArrayBuffer) {
|
||||
p.ruffle().load({data: new Uint8Array(e.data.swf)});
|
||||
} else if (e.data.flv instanceof ArrayBuffer && e.data.player instanceof ArrayBuffer) {
|
||||
var src = URL.createObjectURL(new Blob([e.data.flv], {type: "video/x-flv"}));
|
||||
// the player is ours: it may load the FLV (a blob of this frame)
|
||||
p.ruffle().load({data: new Uint8Array(e.data.player), parameters: {src: src}, allowNetworking: "all"});
|
||||
}
|
||||
});
|
||||
window.addEventListener("DOMContentLoaded", function () {
|
||||
window.parent.postMessage("ready", "*");
|
||||
});
|
||||
})();
|
||||
@@ -41,8 +41,8 @@
|
||||
|
||||
{{define "file"}}<div class="file" id="f{{.No}}">
|
||||
{{if .FileDeleted}}<span class="fileDeleted">File deleted.</span>
|
||||
{{else}}{{$kind := kind .Ext}}<div class="fileText">File: <a href="{{.SrcURL}}" target="_blank" title="{{.FileName}}{{.Ext}}">{{short (print .FileName .Ext)}}</a> ({{if .Spoiler}}Spoiler {{if eq $kind "image"}}Image{{else if eq $kind "video"}}Video{{else}}File{{end}}, {{end}}{{size .FileSize}}, {{if eq $kind "pdf"}}PDF{{with .PageCount}}, {{.}} {{if eq . 1}}page{{else}}pages{{end}}{{end}}{{else}}{{.W}}x{{.H}}{{end}}{{if and (eq $kind "video") .DurationMS}}, {{clock .DurationMS}}{{end}}){{if .Replay}} <span class="oekakiInfo">· drawn in {{dur .DrawMS}} <span class="jsonly">[<a href="{{.SrcURL}}" class="replayLink" data-no="{{.No}}">Replay</a>]{{if .Draw}} [<a href="/chan/{{.Dir}}/thread/{{.Thread}}?draw={{.No}}#postForm" class="drawOver" data-src="{{.SrcURL}}" data-thread="{{.Thread}}">Draw over</a>]{{end}}</span></span>{{end}}</div>
|
||||
<a class="fileThumb{{if .Spoiler}} imgspoiler{{end}}{{if ne $kind "image"}} {{$kind}}Thumb{{end}}" href="{{.SrcURL}}" target="_blank"{{if eq $kind "pdf"}} rel="noopener"{{end}}>{{if .Spoiler}}<img src="/chan/static/spoiler.png" alt="Spoiler Image" width="100" height="100">{{else}}<img src="{{.ThumbURL}}" alt="{{size .FileSize}}" width="{{.TnW}}" height="{{.TnH}}" loading="lazy">{{end}}</a>
|
||||
{{else}}{{$kind := kind .Ext}}<div class="fileText">File: <a href="{{.SrcURL}}" target="_blank" title="{{.FileName}}{{.Ext}}">{{short (print .FileName .Ext)}}</a> ({{if .Spoiler}}Spoiler {{if eq $kind "image"}}Image{{else if eq $kind "video"}}Video{{else}}File{{end}}, {{end}}{{size .FileSize}}, {{if eq $kind "pdf"}}PDF{{with .PageCount}}, {{.}} {{if eq . 1}}page{{else}}pages{{end}}{{end}}{{else}}{{.W}}x{{.H}}{{end}}{{if eq .Ext ".swf"}}, Flash{{end}}{{if and (or (eq $kind "video") (eq .Ext ".flv")) .DurationMS}}, {{clock .DurationMS}}{{end}}){{if .Replay}} <span class="oekakiInfo">· drawn in {{dur .DrawMS}} <span class="jsonly">[<a href="{{.SrcURL}}" class="replayLink" data-no="{{.No}}">Replay</a>]{{if .Draw}} [<a href="/chan/{{.Dir}}/thread/{{.Thread}}?draw={{.No}}#postForm" class="drawOver" data-src="{{.SrcURL}}" data-thread="{{.Thread}}">Draw over</a>]{{end}}</span></span>{{end}}</div>
|
||||
<a class="fileThumb{{if .Spoiler}} imgspoiler{{end}}{{if and (ne $kind "image") (or (ne $kind "flash") .Play)}} {{$kind}}Thumb{{end}}" href="{{.SrcURL}}" target="_blank"{{if eq $kind "pdf"}} rel="noopener"{{end}}{{if .Play}} data-flash="{{.Ext}}" data-w="{{.W}}" data-h="{{.H}}"{{end}}>{{if .Spoiler}}<img src="/chan/static/spoiler.png" alt="Spoiler Image" width="100" height="100">{{else}}<img src="{{.ThumbURL}}" alt="{{size .FileSize}}" width="{{.TnW}}" height="{{.TnH}}" loading="lazy">{{end}}</a>
|
||||
{{end}}</div>{{end}}
|
||||
|
||||
{{define "post"}}<div class="postContainer {{if .OP}}opContainer{{else}}replyContainer{{end}}" id="pc{{.No}}">
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/config"
|
||||
@@ -77,6 +78,12 @@ func (c *Config) chanSection(s *config.Section) error {
|
||||
if ch.MaxVideo, err = s.Seconds("max_video", int(ch.MaxVideo.Seconds()), 0, 86400); err != nil {
|
||||
return err
|
||||
}
|
||||
// Ruffle's self-hosted package, unpacked: Flash played in the page
|
||||
if ch.Ruffle = s.String("ruffle", ""); ch.Ruffle != "" {
|
||||
if _, err := os.Stat(filepath.Join(ch.Ruffle, "ruffle.js")); err != nil {
|
||||
return fmt.Errorf("ruffle: %s has no ruffle.js (Ruffle's self-hosted package, unpacked): %w", ch.Ruffle, err)
|
||||
}
|
||||
}
|
||||
if ch.Style = s.String("style", ""); ch.Style != "" && !imageboard.KnownStyle(ch.Style) {
|
||||
var names []string
|
||||
for _, st := range imageboard.Styles {
|
||||
|
||||
@@ -27,4 +27,12 @@ func TestChanMediaConfig(t *testing.T) {
|
||||
if _, err := load("[chan]\npdftoppm = no-such-helper-here\n"); err == nil || !strings.Contains(err.Error(), "pdftoppm") {
|
||||
t.Errorf("a helper not there: %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if _, err := load("[chan]\nruffle = " + dir + "\n"); err == nil || !strings.Contains(err.Error(), "no ruffle.js") {
|
||||
t.Errorf("ruffle without its files: %v", err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "ruffle.js"), []byte("//"), 0644)
|
||||
if c, err := load("[chan]\nruffle = " + dir + "\n"); err != nil || c.Chan.Ruffle != dir {
|
||||
t.Errorf("ruffle: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user