diff --git a/README.md b/README.md index 5019f30..6f8efe1 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ What there is: - [chat](https://github.com/Neo-Desktop/bbs-sec/wiki/Chat-and-Paging): rooms, messages to a node, paging the sysop - [finger and gopher](https://github.com/Neo-Desktop/bbs-sec/wiki/Finger-and-Gopher): who is on, and chosen areas in gopherspace - [a web forum](https://github.com/Neo-Desktop/bbs-sec/wiki/Web-Forum): the message areas as a bulletin board in the browser, in the manner of Invision Power Board 3, or of IPB 5, 4, 2 or 1, Ikonboard, vBulletin 6 back to 2 or Lite, XenForo 2.3 back to 1, MyBB 1.8 back to 1.2, PunBB 1.4 and 1.2, FluxBB 1.5, YaBB 2.5 back to 1, Simple Machines Forum 3.0 back to 1, or phpBB 3.3 back to 1 (themes) +- [image boards](https://github.com/Neo-Desktop/bbs-sec/wiki/Image-Boards): anonymous boards of images and replies at /chan/, in the manner of kusaba x and 4chan: bumping, sage, tripcodes (2channel's, and secure ones), greentext and >>quotes, a catalog, staff's bans and reports, Yotsuba, Yotsuba B, Futaba, Burichan, Photon and Tomorrow styles, and 4chan's JSON - [a web terminal](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API#the-web-terminal): the BBS in a browser (xterm.js, built in) - [an HTTP API](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API): REST, server-sent events, and WebSockets (JSON or protobuf) where web clients chat with terminal callers; Prometheus metrics - [customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words @@ -140,6 +141,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/) | [Chat and paging](https://github.com/Neo-Desktop/bbs-sec/wiki/Chat-and-Paging) | chat rooms, node messages, paging the sysop | | [Finger and gopher](https://github.com/Neo-Desktop/bbs-sec/wiki/Finger-and-Gopher) | who is on, and the BBS in gopherspace | | [Web forum](https://github.com/Neo-Desktop/bbs-sec/wiki/Web-Forum) | the message areas as a web forum | +| [Image boards](https://github.com/Neo-Desktop/bbs-sec/wiki/Image-Boards) | anonymous image boards, as kusaba x and 4chan | | [HTTP API](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API) | REST, events, WebSockets in JSON and protobuf, tokens, metrics | | [Security](https://github.com/Neo-Desktop/bbs-sec/wiki/Security) | what is guarded, and how | | [Development](https://github.com/Neo-Desktop/bbs-sec/wiki/Development) | the source's layout, the tests | diff --git a/bbs.conf.sample b/bbs.conf.sample index 7e40acb..6f63a00 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -193,6 +193,13 @@ address = 127.0.0.1:2513 ; TLS is the default; tls = no only on 127.0.0.1 behind a proxy that has it ;cert_file = /etc/bbs/tls/cert.pem ;key_file = /etc/bbs/tls/key.pem +; behind a reverse proxy (nginx, Caddy): its addresses (or ranges), which +; are believed when they say whose a request is (X-Forwarded-For, +; Forwarded, X-Real-IP), for rate limits, logs, bans and the deny lists. +; secure_cookies: logins' cookies over HTTPS only (the default with tls = +; yes; say yes when the proxy has TLS) +;trusted_proxies = 127.0.0.1, ::1 +;secure_cookies = yes ; anonymous callers may see /system and /who ;anonymous = yes ; one browser origin allowed to call it (no *) @@ -228,6 +235,27 @@ address = 127.0.0.1:2513 ; 3.2, 3.1 and 3.0), phpbb2 (silver, as phpBB 2) or phpbb1 (dark, as phpBB ; 1) ;forum_theme = ipb3 +; the image boards at /chan/ (bbs chan board add b Random); see +; docs/wiki/Image-Boards.md +;chan = yes + +; How the image boards are run +;[chan] +; images and thumbnails, a directory a board; and the boards' secret +;dir = chan +; the largest image (a board can have its own: bbs chan board set) +;max_file = 4M +; flood control: seconds between an address's threads, and its posts +;thread_wait = 60 +;reply_wait = 15 +; the longest comment, in characters +;max_comment = 2000 +; JPEGs' EXIF (where a phone took the photo) taken out +;strip_metadata = yes +; the style callers get until they choose: by the board (yotsuba-b if it +; is worksafe, else yotsuba), or yotsuba, yotsuba-b, futaba, burichan, +; photon, tomorrow +;style = ; Access levels: a user's level (0-255) gets what the [level] at or ; below it says; areas, doors and menus may require a level and flags diff --git a/cmd/bbs/chan.go b/cmd/bbs/chan.go new file mode 100644 index 0000000..ecd3360 --- /dev/null +++ b/cmd/bbs/chan.go @@ -0,0 +1,259 @@ +package main + +import ( + "errors" + "fmt" + "net" + "strconv" + "strings" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/imageboard" + "github.com/Neo-Desktop/bbs-sec/internal/server" + "github.com/Neo-Desktop/bbs-sec/internal/store" +) + +// chanCmd runs the image boards' commands: boards and bans. +func chanCmd(cfg *server.Config, args []string) { + if len(args) < 2 { + usage() + } + switch args[0] { + case "board": + chanBoardCmd(cfg, args[1:]) + case "ban": + chanBanCmd(cfg, args[1:]) + default: + usage() + } +} + +func chanBoardCmd(cfg *server.Config, args []string) { + words, flags := split(args) + if len(words) == 0 { + usage() + } + st := open(cfg) + defer st.Close() + switch words[0] { + case "list": + bs, err := st.Boards() + if err != nil { + fatal(err) + } + for _, b := range bs { + var opts []string + for name, on := range map[string]bool{"nsfw": !b.Worksafe, "forced anon": b.ForcedAnon, "locked": b.Locked, + "users only": b.LoginToPost, "text only": b.TextOnly} { + if on { + opts = append(opts, name) + } + } + n, _ := st.ChanThreadCount(b.ID) + fmt.Printf("/%s/ %-20s %4d threads, %6d posts, %d pages of %d %s\n", b.Dir, b.Title, n, b.LastNo, b.Pages, + b.PerPage, strings.Join(opts, ", ")) + } + case "add": + if len(words) < 3 || len(words) > 4 { + usage() + } + if msg := imageboard.ValidDir(words[1]); msg != "" { + fatal(errors.New(msg)) + } + b := imageboard.NewBoard(words[1], bbs.Clean(words[2], 60)) + if len(words) == 4 { + b.Description = bbs.Clean(words[3], 200) + } + b.Worksafe = !flags["nsfw"] + b.ForcedAnon, b.Locked, b.LoginToPost, b.TextOnly = flags["forced-anon"], flags["locked"], flags["login"], flags["text-only"] + if _, err := st.CreateBoard(b); errors.Is(err, store.ErrExists) { + fatal(fmt.Errorf("there is a /%s/ already", b.Dir)) + } else if err != nil { + fatal(err) + } + fmt.Printf("added /%s/ - %s\n", b.Dir, b.Title) + case "set": + if len(words) != 4 { + usage() + } + b, err := st.Board(words[1]) + if err != nil { + fatal(fmt.Errorf("/%s/: %w", words[1], err)) + } + if err := setBoard(b, words[2], words[3]); err != nil { + fatal(err) + } + if err := st.UpdateBoard(b); err != nil { + fatal(err) + } + fmt.Printf("/%s/: %s = %s\n", b.Dir, words[2], words[3]) + case "del": + if len(words) != 2 { + usage() + } + b, err := st.Board(words[1]) + if err != nil { + fatal(fmt.Errorf("/%s/: %w", words[1], err)) + } + srv := &imageboard.Server{B: &bbs.BBS{Store: st}, S: cfg.Chan} + if err := srv.RemoveBoard(b); err != nil { + fatal(err) + } + fmt.Printf("deleted /%s/, its posts and its images\n", b.Dir) + default: + usage() + } +} + +// setBoard sets one of a board's settings. +func setBoard(b *store.Board, key, val string) error { + num := func(min, max int) (int, error) { + n, err := strconv.Atoi(val) + if err != nil || n < min || n > max { + return 0, fmt.Errorf("%s: a number from %d to %d", key, min, max) + } + return n, nil + } + yes := func() (bool, error) { + switch strings.ToLower(val) { + case "yes", "on", "true", "1": + return true, nil + case "no", "off", "false", "0": + return false, nil + } + return false, fmt.Errorf("%s: yes or no", key) + } + var err error + switch key { + case "title": + b.Title = bbs.Clean(val, 60) + case "description": + b.Description = bbs.Clean(val, 200) + case "default_name": + b.DefaultName = bbs.Clean(val, 75) + case "mods": + b.Mods = bbs.Clean(val, 500) + case "pages": + b.Pages, err = num(1, 100) + case "per_page": + b.PerPage, err = num(1, 50) + case "bump_limit": + b.BumpLimit, err = num(1, 100000) + case "image_limit": + b.ImageLimit, err = num(0, 100000) + case "sort": + b.Sort, err = num(-1000, 1000) + case "max_file": + var n int64 + if n, err = sizeArg(val); err == nil && (n < 0 || n > 1<<30) { + err = errors.New("max_file: up to 1G (0: [chan]'s)") + } + b.MaxFile = n + case "worksafe": + b.Worksafe, err = yes() + case "nsfw": + var v bool + v, err = yes() + b.Worksafe = !v + case "forced_anon": + b.ForcedAnon, err = yes() + case "locked": + b.Locked, err = yes() + case "login": + b.LoginToPost, err = yes() + case "text_only": + b.TextOnly, err = yes() + default: + return fmt.Errorf("%s: not a board's setting (title, description, default_name, mods, pages, per_page, "+ + "bump_limit, image_limit, max_file, sort, nsfw, forced_anon, locked, login, text_only)", key) + } + return err +} + +func chanBanCmd(cfg *server.Config, args []string) { + if len(args) == 0 { + usage() + } + st := open(cfg) + defer st.Close() + switch args[0] { + case "list": + bans, err := st.Bans() + if err != nil { + fatal(err) + } + for _, b := range bans { + board, exp := "every board", "never" + if b.Board != "" { + board = "/" + b.Board + "/" + } + if !b.Expires.IsZero() { + exp = b.Expires.Format("2006-01-02 15:04") + } + fmt.Printf("%4d %-20s %-12s until %-16s by %-10s %s\n", b.ID, b.IP, board, exp, b.By, b.Reason) + } + case "add": + // ban add ADDRESS DAYS [BOARD|-] [REASON...] + if len(args) < 3 { + usage() + } + ip := args[1] + if net.ParseIP(ip) == nil && !strings.HasSuffix(ip, ".") && !strings.HasSuffix(ip, ":") { + fatal(errors.New("an address (192.0.2.7), or a range ending in . or : (192.0.2.)")) + } + days, err := strconv.Atoi(args[2]) + if err != nil || days < 0 || days > 3650 { + fatal(errors.New("a ban is for 0 (for ever) to 3650 days")) + } + ban := &store.Ban{IP: ip, By: "sysop"} + if len(args) > 3 && args[3] != "-" { + if _, err := st.Board(args[3]); err != nil { + fatal(fmt.Errorf("/%s/: %w", args[3], err)) + } + ban.Board = args[3] + } + if len(args) > 4 { + ban.Reason = bbs.Clean(strings.Join(args[4:], " "), 200) + } + if days > 0 { + ban.Expires = time.Now().Add(time.Duration(days) * 24 * time.Hour) + } + id, err := st.AddBan(ban) + if err != nil { + fatal(err) + } + fmt.Printf("ban %d: %s\n", id, ip) + case "del": + if len(args) != 2 { + usage() + } + id, err := strconv.ParseInt(args[1], 10, 64) + if err != nil { + usage() + } + if err := st.DeleteBan(id); err != nil { + fatal(err) + } + fmt.Println("lifted ban", id) + default: + usage() + } +} + +// sizeArg is a size: bytes, or with K or M. +func sizeArg(v string) (int64, error) { + v = strings.ToUpper(strings.TrimSpace(v)) + mult := int64(1) + switch { + case strings.HasSuffix(v, "K"): + mult, v = 1<<10, strings.TrimSuffix(v, "K") + case strings.HasSuffix(v, "M"): + mult, v = 1<<20, strings.TrimSuffix(v, "M") + } + n, err := strconv.ParseInt(v, 10, 64) + if err != nil || n < 0 || n > 1<<30 { + return 0, errors.New("max_file: a size, as 4M or 512K (0: [chan]'s)") + } + return n * mult, nil +} diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 7552a07..25b2bea 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -33,6 +33,7 @@ // bbs [-config FILE] file add AREA PATH [DESCRIPTION] [-as NAME] // bbs [-config FILE] file list AREA // bbs [-config FILE] file del AREA NAME +// bbs [-config FILE] chan board add|set|list|del ... | chan ban add|list|del ... package main import ( @@ -125,6 +126,11 @@ func usage() { bbs [-config FILE] file add AREA PATH [DESCRIPTION] (as the first sysop) bbs [-config FILE] file list AREA bbs [-config FILE] file del AREA NAME + bbs [-config FILE] chan board add DIR TITLE [DESCRIPTION] [-nsfw] [-forced-anon] [-text-only] [-locked] [-login] + bbs [-config FILE] chan board set DIR KEY VALUE (pages, per_page, bump_limit, mods, nsfw...) + 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 `) os.Exit(2) } @@ -273,6 +279,8 @@ func main() { fileAreaCmd(cfg, args) case "file": fileCmd(cfg, args) + case "chan": + chanCmd(cfg, args) default: usage() } diff --git a/docs/wiki/Administration.md b/docs/wiki/Administration.md index 63b8bf3..96e61be 100644 --- a/docs/wiki/Administration.md +++ b/docs/wiki/Administration.md @@ -79,6 +79,19 @@ bbs file del AREA NAME See [Files and FTP](Files-and-FTP). +## Image boards + +``` +bbs chan board add DIR TITLE [DESCRIPTION] [-nsfw] # /DIR/ at /chan/DIR/ +bbs chan board set DIR KEY VALUE # pages, per_page, bump_limit, mods, nsfw... +bbs chan board list +bbs chan board del DIR # its posts and images too +bbs chan ban add ADDRESS DAYS [BOARD|-] [REASON...] +bbs chan ban list | del ID +``` + +See [Image boards](Image-Boards). + ## Mail exchange ``` diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 7be3990..a941b54 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -37,6 +37,7 @@ whether terminals are asked what they are: [Terminal identification](Terminal-Id | `database` (in `[general]`) | SQLite's file, or a PostgreSQL, MySQL or MariaDB server | [Databases](Databases) | | `[level N]`, `new_user_level`, `validated_level` (in `[general]`) | access levels | [Access levels](Access-Levels) | | `[http]` | the HTTP API, its WebSockets, the web forum, the web terminal and metrics | [HTTP API](HTTP-API), [Web forum](Web-Forum) | +| `[chan]`, `chan` (in `[http]`) | the image boards | [Image boards](Image-Boards) | | `page_command` (in `[general]`) | telling the sysop of a page when they are not on | [Chat and paging](Chat-and-Paging) | `bbs check` reads the file and says what it found, with a warning for diff --git a/docs/wiki/HTTP-API.md b/docs/wiki/HTTP-API.md index d7cdd48..8ce94ae 100644 --- a/docs/wiki/HTTP-API.md +++ b/docs/wiki/HTTP-API.md @@ -19,6 +19,8 @@ key_file = /etc/bbs/tls/key.pem |---|---|---| | `address` | `:8443` | where it listens | | `tls` | `yes` | TLS needs `cert_file` and `key_file`. `tls = no` is for `127.0.0.1` behind a proxy that has TLS; `bbs check` warns about it on any other address | +| `trusted_proxies` | (none) | reverse proxies in front (addresses or CIDR ranges, by spaces or commas), believed when they say whose a request is: [below](#behind-a-proxy) | +| `secure_cookies` | as `tls` | the forum's and image boards' login cookies go over HTTPS only; say `yes` when a proxy in front has the TLS | | `anonymous` | `yes` | `/system` and `/who` without a token | | `cors` | (none) | one browser origin allowed to call the API (no `*`); WebSockets are accepted only from it and the API's own host | | `metrics` | (none) | an address for Prometheus metrics, `/metrics` (keep it private) | @@ -27,9 +29,47 @@ key_file = /etc/bbs/tls/key.pem | `session_hours` | `24` | how long a login's token lasts | | `terminal` | `yes` | the web terminal page (below) | | `forum`, `forum_guests`, `forum_theme` | `yes`, `yes`, `ipb3` | the [web forum](Web-Forum), guests reading it, and its theme (`ipb3`, `ipb5`, `ipb4`, `ipb2`, `ipb1`, `ikon`, `vb6`, `vb5`, `vb4`, `vb3`, `vb2`, `vblite`, `xf23`, `xf2`, `xf1`, `mybb18`, `mybb16`, `mybb12`, `pun14`, `flux15`, `pun12`, `yabb25`, `yabb2`, `yabb1`, `smf30`, `smf21`, `smf20`, `smf1`, `phpbb33`, `phpbb32`, `phpbb31`, `phpbb30`, `phpbb2` or `phpbb1`) | +| `chan` | `yes` | the [image boards](Image-Boards) at `/chan/` (set up in `[chan]`) | The OpenAPI 3.1 description is at `/api/v1/openapi.json`. + +## Behind a proxy + +The server can sit behind a reverse proxy (nginx, Caddy, HAProxy, a load +balancer) that has the TLS. Every request then comes from the proxy's +address, so name it, and the server believes it when it says whose a +request is: + +```ini +[http] +address = 127.0.0.1:8080 +tls = no +trusted_proxies = 127.0.0.1, ::1 +secure_cookies = yes +``` + +```nginx +location / { + proxy_pass http://127.0.0.1:8080; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_http_version 1.1; # the WebSockets: streams + proxy_set_header Upgrade $http_upgrade; # and the web terminal + proxy_set_header Connection "upgrade"; + client_max_body_size 8m; # the image boards' images +} +``` + +The caller is the last address in `X-Forwarded-For` (else `Forwarded`'s +`for=`, else `X-Real-IP`) that is not a trusted proxy: the ones before it +are whatever the caller sent, and are not believed. That address is then +the request's everywhere: rate limits, logins and the logs, the forum, the +web terminal's throttling, the [image boards](Image-Boards)' flood control +and bans, and the `[security]` deny lists and bans (a refused caller gets +403). Connections from a trusted proxy are not held to `max_per_ip`: they +are many callers'. Requests from anywhere else are taken as they come, and +their forwarding headers ignored. + ## Tokens and scopes Every request but `/login`, `/openapi.json` and (when `anonymous = yes`) diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 517fbd8..0c96c33 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -85,6 +85,7 @@ What there is: BBSes' Multi Relay Chat - [finger and gopher](Finger-and-Gopher): who is on, and chosen areas in gopherspace - [a web forum](Web-Forum): the message areas as a bulletin board in the browser, in the manner of Invision Power Board 3, or of IPB 5, 4, 2 or 1, Ikonboard, vBulletin 6 back to 2 or Lite, XenForo 2.3 back to 1, MyBB 1.8 back to 1.2, PunBB 1.4 and 1.2, FluxBB 1.5, YaBB 2.5 back to 1, Simple Machines Forum 3.0 back to 1, or phpBB 3.3 back to 1 (themes) +- [image boards](Image-Boards): anonymous boards of images and replies at /chan/, in the manner of kusaba x and 4chan: bumping, sage, tripcodes (2channel's, and secure ones), greentext and >>quotes, a catalog, staff's bans and reports, Yotsuba, Yotsuba B, Futaba, Burichan, Photon and Tomorrow styles, and 4chan's JSON - [a web terminal](HTTP-API#the-web-terminal): the BBS in a browser (xterm.js, built in) - [an HTTP API](HTTP-API): REST, server-sent events, and WebSockets (JSON or protobuf) where web clients chat with terminal callers; Prometheus metrics - [customization](Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words @@ -121,6 +122,7 @@ What there is: | [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes | | [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace | | [Web forum](Web-Forum) | the message areas as a web forum | +| [Image boards](Image-Boards) | anonymous image boards, as kusaba x and 4chan | | [HTTP API](HTTP-API) | REST, events, WebSockets in JSON and protobuf, tokens, metrics | | [Security](Security) | what is guarded, and how | | [Development](Development) | the source's layout, the tests | diff --git a/docs/wiki/Image-Boards.md b/docs/wiki/Image-Boards.md new file mode 100644 index 0000000..e31e050 --- /dev/null +++ b/docs/wiki/Image-Boards.md @@ -0,0 +1,189 @@ +# Image boards + +The HTTP API's server also serves image boards, at `/chan/`, in the manner +of kusaba x and of 4chan that it followed (and Futaba before both): +boards by directory (`/chan/b/`, `/chan/g/`), threads that start with an +image, anonymous replies, bumping, sage and tripcodes. Nothing is needed +but the `bbs` binary: thumbnails are made in Go, and the pages load +nothing from elsewhere. + +Unlike the [web forum](Web-Forum), the image boards are a world of their +own: posters need no account, and their posts are not messages in the +BBS's areas. The BBS's accounts are for staff: sysops are admins of every +board, and each board can name its own mods. + +``` +bbs chan board add b Random "Anything goes." -nsfw +bbs chan board add g Technology "Computers, terminals and BBSes" +bbs chan board set g mods alice,bob +bbs chan board list +``` + +```ini +[http] +address = :8443 +;chan = yes + +[chan] +;dir = chan ; images and thumbnails, a directory a board +;max_file = 4M ; the largest image (a board can say otherwise) +;thread_wait = 60 ; seconds between an address's threads +;reply_wait = 15 ; and between its posts +;max_comment = 2000 ; characters +;strip_metadata = yes ; take EXIF (where a phone took it) out of JPEGs +;style = yotsuba-b ; the style everyone gets until they choose +``` + +| setting | default | | +|---|---|---| +| `chan` (in `[http]`) | `yes` | the image boards at `/chan/` | +| `dir` | `chan` | where images and thumbnails are kept, and the boards' secret (`dir/secret`, made the first time: keep it, or secure tripcodes change) | +| `max_file` | `4M` | the largest image; `bbs chan board set DIR max_file 8M` gives a board its own | +| `thread_wait`, `reply_wait` | `60`, `15` | flood control: staff are not held to it | +| `max_comment` | `2000` | characters in a comment (and 100 lines) | +| `strip_metadata` | `yes` | JPEGs' EXIF, XMP and comments taken out before they are kept | +| `style` | by the board | Yotsuba B on a worksafe board, Yotsuba on the rest, as 4chan does | + +## Posting + +A board's index has the post form at its top: name, options, subject, +comment, an image, and a password to delete the post by (filled in for +each browser, which keeps it in a cookie). A thread starts with an image +(unless the board is `text_only`); replies need a comment, an image, or +both. + +| typed | | +|---|---| +| `Name#password` | a tripcode: `Name !WokonZwxw2`. The same as 2channel's and 4chan's: `#tea` is `!WokonZwxw2` here too | +| `Name##password` | a secure tripcode, `!!...`, made with this site's secret: it cannot be found by trying passwords elsewhere | +| `sage` in Options | the reply does not bump its thread | +| `nonoko` in Options | back to the board after posting, not the thread | +| `>text` | greentext | +| `>>123` | a link to post 123, `(OP)` if it starts its thread, struck through if it is gone | +| `>>>/g/123`, `>>>/g/` | a post on another board, or the board | +| `[spoiler]...[/spoiler]` | hidden until hovered | +| `[code]...[/code]` | set as code | +| a link | made a link | + +**Spoiler?** shows the image's thumbnail as *Spoiler Image* until it is +opened. Names cannot be used on a `forced_anon` board. + +Images are JPEG, PNG, GIF or WebP, told by their bytes, not their names; +up to 10000 pixels a side. Thumbnails are JPEGs, 250 pixels for a thread's +first image and 125 for a reply's. The same image twice on a board is +refused, with a link to where it is (by its MD5, as 4chan does). JPEGs +lose their EXIF before they are kept, so a phone's photo does not say +where it was taken. + +## Threads + +A reply bumps its thread to the top of the board until the thread has +`bump_limit` replies (300); a thread takes `image_limit` images (150). +A board has `pages` pages of `per_page` threads (10 of 10); when a new +thread pushes the last one past them, it is pruned, its images with it. +Stickies stay at the top and are never pruned; closed threads take no +replies (but staff's). + +The index shows each thread's first post and its last five replies (one +under a sticky), with how many were left out; a comment longer than 15 +lines is cut there. A thread's page has all of it, and under each post +the posts that quote it. The **catalog** shows every thread at a glance: +its image, its replies and images, the start of its first post; by bump +order or by when it was made. + +With JavaScript (the pages work without it): clicking a post's number +quotes it in the reply form, clicking a thumbnail opens the image in place, +and hovering a `>>123` shows that post. + +## Deleting and reporting + +Tick posts, give the password they were posted with (the browser's own is +filled in), and **Delete**; **File Only** deletes their images and leaves +the posts. The ▸ beside a post reports it to staff. + +## Staff + +Sysops and a board's mods sign in at `/chan/login` with their BBS account +and get **Manage** at the top of each page, an `[M]` beside each post, and +the choice of posting as `## Admin` or `## Mod`. + +- **Reports** (`/chan/manage`): what has been reported on their boards, + how often, and why. +- **A post** (`[M]`): its address and that address's other posts; delete + the post (a thread's first: the thread) or its file; make a thread + sticky or closed; dismiss its reports; delete every post of the address + on the board; and ban. +- **Bans**: by address or by range (the /24 of IPv4, the /48 of IPv6), on + the board or (admins) on every board, for some days or for ever, + optionally saying `(USER WAS BANNED FOR THIS POST)` under the post. The + banned see why, until when, and what they posted, when they next post. + `/chan/manage/bans` lists them and lifts them. + +From the command line: + +``` +bbs chan board add DIR TITLE [DESCRIPTION] [-nsfw] [-forced-anon] [-text-only] [-locked] [-login] +bbs chan board set DIR KEY VALUE +bbs chan board list +bbs chan board del DIR ; its posts and images too +bbs chan ban add ADDRESS DAYS [BOARD|-] [REASON...] +bbs chan ban list +bbs chan ban del ID +``` + +| board setting | default | | +|---|---|---| +| `title`, `description` | | as the board's banner shows them | +| `pages`, `per_page` | 10, 10 | threads kept: pages of threads | +| `bump_limit`, `image_limit` | 300, 150 | a thread's | +| `max_file` | `[chan]`'s | the largest image | +| `default_name` | Anonymous | a post with no name | +| `nsfw` | no | not worksafe: Yotsuba, and left off the front page's images | +| `forced_anon` | no | no names or tripcodes | +| `text_only` | no | threads need no image | +| `locked` | no | only staff post | +| `login` | no | only the BBS's users post (signed in at `/chan/login`) | +| `mods` | | users who moderate it, by name | +| `sort` | 0 | where it comes in the lists of boards | + +## Styles + +Callers choose one at the top of each page (kept in a cookie): + +| style | | +|---|---| +| `yotsuba` | 4chan's, on boards not worksafe: cream and maroon | +| `yotsuba-b` | 4chan's worksafe blue | +| `futaba` | Futaba's, as kusaba had it | +| `burichan` | kusaba's blue | +| `photon` | kusaba's grey and orange | +| `tomorrow` | 4chan's dark style | + +## JSON + +The boards can be read as JSON, in the shapes of 4chan's read-only API +(github.com/4chan/4chan-API), so that its readers read these boards too: + +| | | +|---|---| +| `/chan/boards.json` | the boards and how they are run | +| `/chan/b/threads.json` | each page's threads, when each changed, their replies | +| `/chan/b/catalog.json` | each page's threads, with their last replies | +| `/chan/b/1.json` | a page of the index | +| `/chan/b/thread/123.json` | a thread | + +A post's image is at `/chan/b/src/{tim}{ext}` and its thumbnail at +`/chan/b/thumb/{tim}s.jpg` (where 4chan's are at `i.4cdn.org/b/`). +kusaba's addresses go where they should: `/chan/b/res/123.html` to the +thread, `/chan/b/1.html` to the index. + +## Not done + +Video and other files (WebM, PDF: 4chan's needs ffmpeg), the archive of +pruned threads, poster IDs, country flags, captchas, and Oekaki. + +Behind a reverse proxy, name it in `[http]`'s `trusted_proxies`: otherwise +every poster has the proxy's address, and flood control and bans reach +everyone. See [HTTP API: behind a proxy](HTTP-API#behind-a-proxy). + +**See also:** [Web forum](Web-Forum), [HTTP API](HTTP-API) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index e898eba..d5def18 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -33,6 +33,7 @@ - [MRC](MRC) - [Finger and gopher](Finger-and-Gopher) - [Web forum](Web-Forum) +- [Image boards](Image-Boards) - [HTTP API](HTTP-API) **More** diff --git a/internal/api/api.go b/internal/api/api.go index bf31952..95a74e1 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -21,6 +21,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/fido" + "github.com/Neo-Desktop/bbs-sec/internal/imageboard" "github.com/Neo-Desktop/bbs-sec/internal/nntp" "github.com/Neo-Desktop/bbs-sec/internal/qwknet" "github.com/Neo-Desktop/bbs-sec/internal/store" @@ -47,6 +48,15 @@ type Settings struct { Forum bool // the web forum, /forum/ Guests bool // the forum's guests read the areas anyone may Theme string // the forum's theme until a caller chooses ("": the default) + Chan bool // the image boards, /chan/ + // TrustedProxies are reverse proxies believed when they say whose a + // request is (X-Forwarded-For) + TrustedProxies []*net.IPNet + // SecureCookies: the forum's and image boards' cookies are sent over + // HTTPS only (TLS here, or at a proxy in front) + SecureCookies bool + // ChanSettings are how the image boards are run + ChanSettings imageboard.Settings } // Server serves the API. @@ -338,6 +348,15 @@ func (s *Server) Handler() http.Handler { }) } } + if s.S.Chan { + ch, err := s.imageboard() + if err != nil { + s.B.Log.Printf("http: the image boards: %v", err) + } else { + mux.Handle("/chan/", ch) + mux.Handle("/chan", ch) + } + } if s.terminalOn() { mux.HandleFunc("GET /terminal", s.terminalPage) mux.HandleFunc("GET /terminal/ws", s.terminalWS) @@ -351,7 +370,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fail(w, http.StatusNotFound, "no such endpoint: see /api/v1/openapi.json") }) - return securityHeaders(mux) + return securityHeaders(s.realAddr(mux)) } func securityHeaders(h http.Handler) http.Handler { @@ -386,6 +405,10 @@ func (l *limitListener) Accept() (net.Conn, error) { continue } h, _, _ := net.SplitHostPort(c.RemoteAddr().String()) + if ip := net.ParseIP(h); ip != nil && l.s.trusted(ip) { + // a proxy's connections are many callers': not limited + return c, nil + } l.s.mu.Lock() if l.s.S.MaxPerIP > 0 && l.s.perIP[h] >= l.s.S.MaxPerIP { l.s.mu.Unlock() diff --git a/internal/api/forum.go b/internal/api/forum.go index 3cb0668..6a13db2 100644 --- a/internal/api/forum.go +++ b/internal/api/forum.go @@ -6,6 +6,7 @@ import ( "time" "github.com/Neo-Desktop/bbs-sec/internal/forum" + "github.com/Neo-Desktop/bbs-sec/internal/imageboard" "github.com/Neo-Desktop/bbs-sec/internal/store" ) @@ -49,7 +50,7 @@ func (f forumSessions) Logout(secret string) { // forum is the web forum's handler, its requests counted against the // caller's address as the API's are. func (s *Server) forum() (http.Handler, error) { - f := &forum.Server{B: s.B, Sessions: forumSessions{s}, Guests: s.S.Guests, Secure: s.S.TLS, + f := &forum.Server{B: s.B, Sessions: forumSessions{s}, Guests: s.S.Guests, Secure: s.S.SecureCookies, Terminal: s.terminalOn(), TTL: s.S.SessionTTL, Theme: s.S.Theme} h, err := f.Handler() if err != nil { @@ -64,3 +65,22 @@ func (s *Server) forum() (http.Handler, error) { h.ServeHTTP(w, r) }), nil } + +// imageboard is the image boards' handler, its pages counted as the +// forum's are (not their images: a thread can have a hundred); their +// logins are the forum's sessions. +func (s *Server) imageboard() (http.Handler, error) { + ib := &imageboard.Server{B: s.B, Sessions: forumSessions{s}, S: s.S.ChanSettings, Secure: s.S.SecureCookies, TTL: s.S.SessionTTL} + h, err := ib.Handler() + if err != nil { + return nil, err + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !imageboard.IsAsset(r) && !s.allow("ip:"+hostOf(r)) { + w.Header().Set("Retry-After", "1") + http.Error(w, "too many requests: slow down", http.StatusTooManyRequests) + return + } + h.ServeHTTP(w, r) + }), nil +} diff --git a/internal/api/proxy.go b/internal/api/proxy.go new file mode 100644 index 0000000..ab05408 --- /dev/null +++ b/internal/api/proxy.go @@ -0,0 +1,128 @@ +package api + +import ( + "net" + "net/http" + "strings" +) + +// Behind a reverse proxy (nginx, Caddy, a load balancer) every request +// comes from the proxy's address. The proxies named in trusted_proxies +// are believed when they say whose request it is, by X-Forwarded-For (or +// Forwarded, or X-Real-IP); no one else is, since anyone can send those +// headers. + +// ParseProxies reads trusted_proxies: addresses and CIDR ranges, by spaces +// or commas. +func ParseProxies(s string) ([]*net.IPNet, error) { + var out []*net.IPNet + for _, f := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' }) { + if _, n, err := net.ParseCIDR(f); err == nil { + out = append(out, n) + continue + } + ip := net.ParseIP(f) + if ip == nil { + return nil, &net.ParseError{Type: "address or CIDR range", Text: f} + } + bits := 128 + if ip.To4() != nil { + ip, bits = ip.To4(), 32 + } + out = append(out, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)}) + } + return out, nil +} + +// trusted says whether an address is a trusted proxy's. +func (s *Server) trusted(ip net.IP) bool { + for _, n := range s.S.TrustedProxies { + if n.Contains(ip) { + return true + } + } + return false +} + +// parseHopIP is an address as a forwarding header gives it: bare, +// with a port, or in brackets ("[2001:db8::1]:443"). +func parseHopIP(s string) net.IP { + s = strings.Trim(strings.TrimSpace(s), `"`) + if h, _, err := net.SplitHostPort(s); err == nil { + s = h + } + return net.ParseIP(strings.Trim(s, "[]")) +} + +// forwardedFor is the hops a request came by, as its proxies say, the +// first (the client) first. +func forwardedFor(r *http.Request) []string { + var hops []string + for _, h := range r.Header.Values("X-Forwarded-For") { + hops = append(hops, strings.Split(h, ",")...) + } + if len(hops) > 0 { + return hops + } + // RFC 7239: Forwarded: for=192.0.2.60;proto=http, for="[2001:db8::1]" + for _, h := range r.Header.Values("Forwarded") { + for _, elem := range strings.Split(h, ",") { + for _, pair := range strings.Split(elem, ";") { + k, v, ok := strings.Cut(strings.TrimSpace(pair), "=") + if ok && strings.EqualFold(k, "for") { + hops = append(hops, v) + } + } + } + } + if len(hops) > 0 { + return hops + } + if v := r.Header.Get("X-Real-IP"); v != "" { + return []string{v} + } + return nil +} + +// clientIP is whom a trusted proxy's request is for: the last hop, from +// the end, that is not a trusted proxy (the ones before it could be +// anyone's invention); nil if the headers do not say. +func (s *Server) clientIP(r *http.Request) net.IP { + hops := forwardedFor(r) + var last net.IP + for i := len(hops) - 1; i >= 0; i-- { + ip := parseHopIP(hops[i]) + if ip == nil { + break // "unknown", an obfuscated name: no further back + } + last = ip + if !s.trusted(ip) { + return ip + } + } + return last +} + +// realAddr has requests from trusted proxies come from whom they are +// for, before anything else sees them: rate limits, logins, the logs, +// the forum and the image boards, the web terminal. The caller's +// address is then held to the [security] deny lists as a connection's +// is. +func (s *Server) realAddr(h http.Handler) http.Handler { + if len(s.S.TrustedProxies) == 0 { + return h + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + host, port, err := net.SplitHostPort(r.RemoteAddr) + if ip := net.ParseIP(host); err == nil && ip != nil && s.trusted(ip) { + if c := s.clientIP(r); c != nil { + if s.B.Refuse("http", &net.TCPAddr{IP: c}) { + http.Error(w, "refused", http.StatusForbidden) + return + } + r.RemoteAddr = net.JoinHostPort(c.String(), port) + } + } + h.ServeHTTP(w, r) + }) +} diff --git a/internal/api/proxy_test.go b/internal/api/proxy_test.go new file mode 100644 index 0000000..bd1094f --- /dev/null +++ b/internal/api/proxy_test.go @@ -0,0 +1,91 @@ +package api + +import ( + "net/http" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/guard" +) + +func TestClientIP(t *testing.T) { + proxies, err := ParseProxies("127.0.0.1, 10.0.0.0/8 ::1") + if err != nil { + t.Fatal(err) + } + s := &Server{S: Settings{TrustedProxies: proxies}} + for _, c := range []struct { + headers map[string]string + want string + }{ + {map[string]string{"X-Forwarded-For": "203.0.113.5"}, "203.0.113.5"}, + // a client's own X-Forwarded-For is not believed: the last hop + // before our proxies is + {map[string]string{"X-Forwarded-For": "1.2.3.4, 203.0.113.5, 10.1.2.3"}, "203.0.113.5"}, + {map[string]string{"X-Forwarded-For": "10.0.0.7"}, "10.0.0.7"}, + {map[string]string{"X-Forwarded-For": "garbage, 10.0.0.7"}, "10.0.0.7"}, + {map[string]string{"Forwarded": `for=192.0.2.60;proto=http, for="[2001:db8::1]:4711"`}, "2001:db8::1"}, + {map[string]string{"X-Real-IP": "198.51.100.9"}, "198.51.100.9"}, + {map[string]string{"X-Forwarded-For": "198.51.100.10:5555"}, "198.51.100.10"}, + {map[string]string{}, ""}, + } { + r, _ := http.NewRequest("GET", "/", nil) + for k, v := range c.headers { + r.Header.Set(k, v) + } + got := "" + if ip := s.clientIP(r); ip != nil { + got = ip.String() + } + if got != c.want { + t.Errorf("%v: %q, want %q", c.headers, got, c.want) + } + } + if _, err := ParseProxies("10.0.0.0/33"); err == nil { + t.Error("a bad range taken") + } +} + +// TestBehindProxy: through a trusted proxy each caller has their own +// rate limit, logins are logged from them, and the deny lists reach them; +// without trust, the headers are ignored. +func TestBehindProxy(t *testing.T) { + get := func(s *site, xff string) int { + req, _ := http.NewRequest("GET", s.ts.URL+"/api/v1/system", nil) + req.Header.Set("X-Forwarded-For", xff) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + return resp.StatusCode + } + proxies, _ := ParseProxies("127.0.0.1 ::1") + s := setup(t, Settings{Rate: 0.001, Burst: 1, TrustedProxies: proxies}) + if a, b := get(s, "203.0.113.5"), get(s, "203.0.113.6"); a != 200 || b != 200 { + t.Errorf("two callers: %d %d", a, b) + } + if c := get(s, "203.0.113.5"); c != 429 { + t.Errorf("the first again: %d", c) + } + req, _ := http.NewRequest("POST", s.ts.URL+"/api/v1/login", strings.NewReader(`{"name":"alice","password":"alicepass1"}`)) + req.Header.Set("X-Forwarded-For", "198.51.100.7") + resp, _ := http.DefaultClient.Do(req) + resp.Body.Close() + if !strings.Contains(s.logs.String(), "alice logged in from 198.51.100.7") { + t.Errorf("log:\n%s", s.logs) + } + s.b.Guard = &guard.Guard{HackLog: filepath.Join(t.TempDir(), "hack.log"), BanTime: time.Hour} + s.b.Guard.Ban("192.0.2.66", "test") + if c := get(s, "192.0.2.66"); c != 403 { + t.Errorf("a banned caller: %d", c) + } + + // not trusted: X-Forwarded-For is anyone's to send + plain := setup(t, Settings{Rate: 0.001, Burst: 1}) + if a, b := get(plain, "203.0.113.5"), get(plain, "203.0.113.6"); a != 200 || b != 429 { + t.Errorf("untrusted: %d %d", a, b) + } +} diff --git a/internal/api/terminal.go b/internal/api/terminal.go index 8046c46..b1f844f 100644 --- a/internal/api/terminal.go +++ b/internal/api/terminal.go @@ -108,8 +108,8 @@ func (s *Server) terminalWS(w http.ResponseWriter, r *http.Request) { c.SetReadLimit(64 << 10) nc := websocket.NetConn(r.Context(), c, websocket.MessageBinary) host := hostOf(r) - if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { - host = "" // a proxy in front: as a modem server's, not throttled as one + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() && len(s.S.TrustedProxies) == 0 { + host = "" // a proxy in front, not trusted to say whose: as a modem server's, not throttled as one } if err := s.Terminal(nc, r.RemoteAddr, host, cols, rows); err != nil { s.B.Log.Printf("web terminal %s: %v", r.RemoteAddr, err) diff --git a/internal/imageboard/api.go b/internal/imageboard/api.go new file mode 100644 index 0000000..c736bf5 --- /dev/null +++ b/internal/imageboard/api.go @@ -0,0 +1,294 @@ +package imageboard + +import ( + "encoding/json" + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/Neo-Desktop/bbs-sec/internal/store" +) + +// The read-only JSON, in 4chan's API's shapes (github.com/4chan/4chan-API) +// so that its readers read these boards too: /chan/boards.json, +// /chan/b/threads.json, /chan/b/catalog.json, /chan/b/1.json and +// /chan/b/thread/123.json. Images are at /chan/b/src/{tim}{ext}, their +// thumbnails at /chan/b/thumb/{tim}s.jpg. + +type apiPost struct { + No int64 `json:"no"` + Resto int64 `json:"resto"` + Sticky int `json:"sticky,omitempty"` + Closed int `json:"closed,omitempty"` + Now string `json:"now"` + Time int64 `json:"time"` + Name string `json:"name,omitempty"` + Trip string `json:"trip,omitempty"` + Capcode string `json:"capcode,omitempty"` + Sub string `json:"sub,omitempty"` + Com string `json:"com,omitempty"` + Filename string `json:"filename,omitempty"` + Ext string `json:"ext,omitempty"` + Fsize int64 `json:"fsize,omitempty"` + MD5 string `json:"md5,omitempty"` + W int `json:"w,omitempty"` + H int `json:"h,omitempty"` + TnW int `json:"tn_w,omitempty"` + TnH int `json:"tn_h,omitempty"` + Tim int64 `json:"tim,omitempty"` + FileDeleted int `json:"filedeleted,omitempty"` + Spoiler int `json:"spoiler,omitempty"` + Replies *int `json:"replies,omitempty"` + Images *int `json:"images,omitempty"` + BumpLimit int `json:"bumplimit,omitempty"` + ImageLimit int `json:"imagelimit,omitempty"` + SemanticURL string `json:"semantic_url,omitempty"` + LastModified int64 `json:"last_modified,omitempty"` + OmittedPosts int `json:"omitted_posts,omitempty"` + OmittedImages int `json:"omitted_images,omitempty"` + LastReplies []*apiPost `json:"last_replies,omitempty"` +} + +func flag(b bool) int { + if b { + return 1 + } + return 0 +} + +var slugPat = regexp.MustCompile(`[^a-z0-9]+`) + +// semanticURL is a thread's slug, as 4chan makes them. +func semanticURL(p *store.BoardPost) string { + s := p.Subject + if s == "" { + s = p.Comment + } + s = strings.Trim(slugPat.ReplaceAllString(strings.ToLower(s), "-"), "-") + if len(s) > 60 { + s = strings.TrimRight(s[:60], "-") + } + return s +} + +func (q *req) apiPost(b *store.Board, v *postView) *apiPost { + p := v.BoardPost + a := &apiPost{No: p.No, Resto: p.Thread, Now: postDate(p.Created), Time: p.Created.Unix(), + Name: v.Name, Trip: p.Trip, Capcode: p.Capcode, Sub: p.Subject, Com: string(v.Comment)} + if p.Ext != "" { + a.Filename, a.Ext, a.Fsize, a.MD5, a.W, a.H, a.TnW, a.TnH, a.Tim = p.FileName, p.Ext, p.FileSize, p.MD5, p.W, + p.H, p.TnW, p.TnH, p.Tim + a.Spoiler, a.FileDeleted = flag(p.Spoiler), flag(p.FileDeleted) + if p.FileDeleted { + a.Filename, a.Ext, a.Fsize, a.MD5, a.W, a.H, a.TnW, a.TnH, a.Tim = "", "", 0, "", 0, 0, 0, 0, 0 + } + } + if p.Thread == 0 { + a.Sticky, a.Closed = flag(p.Sticky), flag(p.Closed) + r, i := p.Replies, p.Images + a.Replies, a.Images = &r, &i + a.BumpLimit, a.ImageLimit = flag(r >= b.BumpLimit), flag(i >= b.ImageLimit) + a.SemanticURL = semanticURL(p) + a.LastModified = p.Bumped.Unix() + } + return a +} + +func (q *req) json(v any) { + h := q.w.Header() + h.Set("Content-Type", "application/json") + h.Set("Access-Control-Allow-Origin", "*") + h.Set("Cache-Control", "no-cache") + json.NewEncoder(q.w).Encode(v) +} + +func (q *req) jsonFail(status int) { + q.w.Header().Set("Content-Type", "application/json") + q.w.WriteHeader(status) + fmt.Fprintln(q.w, `{"error":"not found"}`) +} + +// boardsJSON is boards.json: each board and how it is run. +func (s *Server) boardsJSON(q *req) { + bs, err := s.B.Store.Boards() + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + type cooldowns struct { + Threads int `json:"threads"` + Replies int `json:"replies"` + Images int `json:"images"` + } + type board struct { + Board string `json:"board"` + Title string `json:"title"` + WSBoard int `json:"ws_board"` + PerPage int `json:"per_page"` + Pages int `json:"pages"` + MaxFilesize int64 `json:"max_filesize"` + MaxCommentChars int `json:"max_comment_chars"` + ImageLimit int `json:"image_limit"` + BumpLimit int `json:"bump_limit"` + MetaDescription string `json:"meta_description"` + Cooldowns cooldowns `json:"cooldowns"` + ForcedAnon int `json:"forced_anon,omitempty"` + TextOnly int `json:"text_only,omitempty"` + Spoilers int `json:"spoilers"` + CodeTags int `json:"code_tags"` + IsArchived int `json:"is_archived"` + } + out := struct { + Boards []board `json:"boards"` + }{Boards: []board{}} + for _, b := range bs { + cd := cooldowns{int(s.S.ThreadWait.Seconds()), int(s.S.ReplyWait.Seconds()), int(s.S.ReplyWait.Seconds())} + out.Boards = append(out.Boards, board{Board: b.Dir, Title: b.Title, WSBoard: flag(b.Worksafe), PerPage: b.PerPage, + Pages: b.Pages, MaxFilesize: s.maxFile(b), MaxCommentChars: s.S.MaxComment, ImageLimit: b.ImageLimit, + BumpLimit: b.BumpLimit, MetaDescription: b.Description, Cooldowns: cd, ForcedAnon: flag(b.ForcedAnon), + TextOnly: flag(b.TextOnly), Spoilers: 1, CodeTags: 1}) + } + q.json(out) +} + +// allThreads are a board's threads, a page's worth at a time. +func (s *Server) allThreads(b *store.Board) ([][]*store.BoardPost, error) { + ops, err := s.B.Store.ChanThreads(b.ID, 0, b.Pages*b.PerPage) + if err != nil { + return nil, err + } + var pages [][]*store.BoardPost + for len(ops) > 0 { + n := min(len(ops), b.PerPage) + pages = append(pages, ops[:n]) + ops = ops[n:] + } + return pages, nil +} + +// threadsJSON is threads.json: each page's threads, when each changed. +func (s *Server) threadsJSON(q *req, b *store.Board) { + pages, err := s.allThreads(b) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + type thread struct { + No int64 `json:"no"` + LastModified int64 `json:"last_modified"` + Replies int `json:"replies"` + } + type page struct { + Page int `json:"page"` + Threads []thread `json:"threads"` + } + out := []page{} + for i, ops := range pages { + pg := page{Page: i + 1, Threads: []thread{}} + for _, op := range ops { + pg.Threads = append(pg.Threads, thread{op.No, op.Bumped.Unix(), op.Replies}) + } + out = append(out, pg) + } + q.json(out) +} + +// catalogJSON is catalog.json: each page's threads, with their last +// replies. +func (s *Server) catalogJSON(q *req, b *store.Board) { + pages, err := s.allThreads(b) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + type page struct { + Page int `json:"page"` + Threads []*apiPost `json:"threads"` + } + out := []page{} + for i, ops := range pages { + tvs, err := q.threadViews(b, ops, 0) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + pg := page{Page: i + 1, Threads: []*apiPost{}} + for _, tv := range tvs { + pg.Threads = append(pg.Threads, q.apiThread(b, tv)) + } + out = append(out, pg) + } + q.json(out) +} + +// apiThread is a thread as an index has it: its first post, with its last +// replies. +func (q *req) apiThread(b *store.Board, tv *threadView) *apiPost { + a := q.apiPost(b, tv.OP) + a.OmittedPosts, a.OmittedImages = tv.OmittedPosts, tv.OmittedImages + for _, r := range tv.Replies { + a.LastReplies = append(a.LastReplies, q.apiPost(b, r)) + } + return a +} + +// pageJSON is a page of the index: its threads, each first post and its +// last replies, as {"threads": [{"posts": [...]}]}. +func (s *Server) pageJSON(q *req, b *store.Board, page int) { + if page > b.Pages { + q.jsonFail(http.StatusNotFound) + return + } + ops, err := s.B.Store.ChanThreads(b.ID, (page-1)*b.PerPage, b.PerPage) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + if len(ops) == 0 && page > 1 { + q.jsonFail(http.StatusNotFound) + return + } + tvs, err := q.threadViews(b, ops, 0) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + type thread struct { + Posts []*apiPost `json:"posts"` + } + out := struct { + Threads []thread `json:"threads"` + }{Threads: []thread{}} + for _, tv := range tvs { + op := q.apiPost(b, tv.OP) + op.OmittedPosts, op.OmittedImages = tv.OmittedPosts, tv.OmittedImages + t := thread{Posts: []*apiPost{op}} + for _, r := range tv.Replies { + t.Posts = append(t.Posts, q.apiPost(b, r)) + } + out.Threads = append(out.Threads, t) + } + q.json(out) +} + +// threadJSON is a thread: {"posts": [...]}, its first post first. +func (s *Server) threadJSON(q *req, b *store.Board, no int64) { + op, err := s.B.Store.ChanThread(b.ID, no) + if err != nil { + q.jsonFail(http.StatusNotFound) + return + } + tvs, err := q.threadViews(b, []*store.BoardPost{op}, no) + if err != nil { + q.jsonFail(http.StatusInternalServerError) + return + } + out := struct { + Posts []*apiPost `json:"posts"` + }{Posts: []*apiPost{q.apiPost(b, tvs[0].OP)}} + for _, r := range tvs[0].Replies { + out.Posts = append(out.Posts, q.apiPost(b, r)) + } + q.json(out) +} diff --git a/internal/imageboard/des.go b/internal/imageboard/des.go new file mode 100644 index 0000000..ef3ca83 --- /dev/null +++ b/internal/imageboard/des.go @@ -0,0 +1,188 @@ +package imageboard + +// The traditional Unix crypt(3): DES, its E expansion perturbed by a +// 12-bit salt, run 25 times over a block of zeros. It is what 2channel's +// tripcodes are made with, and so every image board's since: the same +// password gives the same tripcode on all of them. Its tables are DES's +// (FIPS 46-3), numbered from 1 as the standard numbers them. + +var desIP = [64]byte{ + 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, +} + +var desFP = [64]byte{ + 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, +} + +var desE = [48]byte{ + 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1, +} + +var desP = [32]byte{ + 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25, +} + +var desPC1 = [56]byte{ + 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4, +} + +var desPC2 = [48]byte{ + 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32, +} + +var desShifts = [16]byte{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1} + +var desS = [8][64]byte{ + {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, + 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, + 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, + 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, + {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, + 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, + 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, + 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, + {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, + 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, + 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, + 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, + {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, + 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, + 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, + 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, + {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, + 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, + 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, + 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, + {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, + 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, + 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, + 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, + {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, + 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, + 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, + 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, + {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, + 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, + 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, + 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}, +} + +const cryptChars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +// cryptValue is a salt character's value (an unknown one counts as '.'). +func cryptValue(c byte) uint { + switch { + case c >= 'a' && c <= 'z': + return uint(c-'a') + 38 + case c >= 'A' && c <= 'Z': + return uint(c-'A') + 12 + case c >= '.' && c <= '9': + return uint(c - '.') + } + return 0 +} + +// desCrypt is crypt(3) of a key (its first 8 bytes) with a 2-character +// salt: the salt, then 11 characters. +func desCrypt(key []byte, salt string) string { + if len(salt) < 2 { + salt += "..."[:2-len(salt)] + } + var kb [64]byte + for i := 0; i < 8 && i < len(key); i++ { + c := key[i] << 1 + for j := 0; j < 8; j++ { + kb[i*8+j] = c >> (7 - j) & 1 + } + } + // the 16 subkeys + var cd [56]byte + for i, p := range desPC1 { + cd[i] = kb[p-1] + } + var subkeys [16][48]byte + for r := 0; r < 16; r++ { + for n := byte(0); n < desShifts[r]; n++ { + c0, d0 := cd[0], cd[28] + copy(cd[0:27], cd[1:28]) + copy(cd[28:55], cd[29:56]) + cd[27], cd[55] = c0, d0 + } + for i, p := range desPC2 { + subkeys[r][i] = cd[p-1] + } + } + sv := cryptValue(salt[0]) | cryptValue(salt[1])<<6 + var block [64]byte + for it := 0; it < 25; it++ { + var lr [64]byte + for i, p := range desIP { + lr[i] = block[p-1] + } + l, r := lr[:32], lr[32:] + for round := 0; round < 16; round++ { + var e [48]byte + for i, p := range desE { + e[i] = r[p-1] + } + for i := 0; i < 12; i++ { + if sv>>i&1 == 1 { + e[i], e[i+24] = e[i+24], e[i] + } + } + for i := range e { + e[i] ^= subkeys[round][i] + } + var sOut [32]byte + for b := 0; b < 8; b++ { + x := e[b*6 : b*6+6] + row := x[0]<<1 | x[5] + col := x[1]<<3 | x[2]<<2 | x[3]<<1 | x[4] + v := desS[b][row*16+col] + for j := 0; j < 4; j++ { + sOut[b*4+j] = v >> (3 - j) & 1 + } + } + var nr [32]byte + for i, p := range desP { + nr[i] = l[i] ^ sOut[p-1] + } + copy(l, r) + copy(r, nr[:]) + } + var pre [64]byte + copy(pre[:32], r) + copy(pre[32:], l) + for i, p := range desFP { + block[i] = pre[p-1] + } + } + out := []byte{salt[0], salt[1]} + for i := 0; i < 66; i += 6 { + v := 0 + for j := 0; j < 6; j++ { + v <<= 1 + if i+j < 64 { + v |= int(block[i+j]) + } + } + out = append(out, cryptChars[v]) + } + return string(out) +} diff --git a/internal/imageboard/image.go b/internal/imageboard/image.go new file mode 100644 index 0000000..9aaa825 --- /dev/null +++ b/internal/imageboard/image.go @@ -0,0 +1,196 @@ +package imageboard + +import ( + "bytes" + "crypto/md5" + "encoding/base64" + "errors" + "fmt" + "image" + "image/color" + "image/gif" + "image/jpeg" + "image/png" + + "golang.org/x/image/draw" + "golang.org/x/image/font" + "golang.org/x/image/font/basicfont" + "golang.org/x/image/math/fixed" + "golang.org/x/image/webp" +) + +// The images taken: what they are is found from their bytes, never their +// names. +var imageTypes = map[string]string{ + ".jpg": "image/jpeg", + ".png": "image/png", + ".gif": "image/gif", + ".webp": "image/webp", +} + +const ( + maxSide = 10000 // pixels, an image's width or height + maxPixels = 25 << 20 // its width times its height + opThumb = 250 // a thread's first image's thumbnail, at most + replyThumb = 125 // a reply's +) + +// sniff is an image's extension by its first bytes ("": not one taken). +func sniff(b []byte) string { + switch { + case bytes.HasPrefix(b, []byte{0xff, 0xd8, 0xff}): + return ".jpg" + case bytes.HasPrefix(b, []byte("\x89PNG\r\n\x1a\n")): + return ".png" + case bytes.HasPrefix(b, []byte("GIF87a")), bytes.HasPrefix(b, []byte("GIF89a")): + return ".gif" + case len(b) >= 12 && string(b[:4]) == "RIFF" && string(b[8:12]) == "WEBP": + return ".webp" + } + return "" +} + +// picture is an uploaded image made ready to keep: its bytes (a JPEG's +// metadata taken out), what it is, and its thumbnail. +type picture struct { + Data []byte + Ext string + W, H int + MD5 string + Thumb []byte // a JPEG + TnW, TnH int +} + +var ( + errNotImage = errors.New("That file is not an image this board takes (JPEG, PNG, GIF or WebP).") + errTooLarge = fmt.Errorf("That image is too large: at most %d by %d pixels.", maxSide, maxSide) +) + +// decodeSlots limits the images decoded at once: each can take a hundred +// megabytes. +var decodeSlots = make(chan struct{}, 2) + +// prepare checks an upload and makes its thumbnail, no bigger than side +// on a side, on bg (what shows through a transparent image). +func prepare(data []byte, side int, bg color.Color, strip bool) (*picture, error) { + ext := sniff(data) + if ext == "" { + return nil, errNotImage + } + if ext == ".jpg" && strip { + data = stripJPEG(data) + } + var cfg image.Config + var err error + switch ext { + case ".jpg": + cfg, err = jpeg.DecodeConfig(bytes.NewReader(data)) + case ".png": + cfg, err = png.DecodeConfig(bytes.NewReader(data)) + case ".gif": + cfg, err = gif.DecodeConfig(bytes.NewReader(data)) + case ".webp": + cfg, err = webp.DecodeConfig(bytes.NewReader(data)) + } + if err != nil { + return nil, errNotImage + } + if cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxSide || cfg.Height > maxSide || cfg.Width*cfg.Height > maxPixels { + return nil, errTooLarge + } + decodeSlots <- struct{}{} + defer func() { <-decodeSlots }() + var img image.Image + switch ext { + case ".jpg": + img, err = jpeg.Decode(bytes.NewReader(data)) + case ".png": + img, err = png.Decode(bytes.NewReader(data)) + case ".gif": + img, err = gif.Decode(bytes.NewReader(data)) // the first frame + case ".webp": + img, err = webp.Decode(bytes.NewReader(data)) + } + if err != nil { + return nil, errNotImage + } + sum := md5.Sum(data) + p := &picture{Data: data, Ext: ext, W: cfg.Width, H: cfg.Height, MD5: base64.StdEncoding.EncodeToString(sum[:])} + p.TnW, p.TnH = fit(cfg.Width, cfg.Height, side) + tn := image.NewRGBA(image.Rect(0, 0, p.TnW, p.TnH)) + draw.Draw(tn, tn.Bounds(), image.NewUniform(bg), image.Point{}, draw.Src) + draw.BiLinear.Scale(tn, tn.Bounds(), img, img.Bounds(), draw.Over, nil) + var out bytes.Buffer + if err := jpeg.Encode(&out, tn, &jpeg.Options{Quality: 85}); err != nil { + return nil, err + } + p.Thumb = out.Bytes() + return p, nil +} + +// fit is w by h made to fit in side by side, never larger. +func fit(w, h, side int) (int, int) { + if w <= side && h <= side { + return w, h + } + if w >= h { + return side, max(1, h*side/w) + } + return max(1, w*side/h), side +} + +// stripJPEG takes a JPEG's metadata out (EXIF, with where a phone took +// it; XMP; Photoshop's; comments) and leaves the picture; a JPEG it +// cannot follow it leaves as it is. +func stripJPEG(b []byte) []byte { + if len(b) < 4 || b[0] != 0xff || b[1] != 0xd8 { + return b + } + out := []byte{0xff, 0xd8} + i := 2 + for i+4 <= len(b) { + if b[i] != 0xff { + return b + } + marker := b[i+1] + if marker == 0xff { // fill + i++ + continue + } + if marker == 0xda { // the scan: the rest is the picture + return append(out, b[i:]...) + } + if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 { + out = append(out, b[i:i+2]...) + i += 2 + continue + } + n := int(b[i+2])<<8 | int(b[i+3]) + if n < 2 || i+2+n > len(b) { + return b + } + switch marker { + case 0xe1, 0xed, 0xfe: // APP1 (EXIF, XMP), APP13 (Photoshop), COM + default: + out = append(out, b[i:i+2+n]...) + } + i += 2 + n + } + return b +} + +// spoilerImage is the thumbnail a spoilered image shows: grey, saying +// so. +func spoilerImage() []byte { + const w, h = 100, 100 + img := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.Draw(img, img.Bounds(), image.NewUniform(color.RGBA{0x88, 0x88, 0x88, 0xff}), image.Point{}, draw.Src) + d := &font.Drawer{Dst: img, Src: image.NewUniform(color.White), Face: basicfont.Face7x13} + for i, line := range []string{"Spoiler", "Image"} { + d.Dot = fixed.P((w-d.MeasureString(line).Round())/2, 46+i*16) + d.DrawString(line) + } + var out bytes.Buffer + png.Encode(&out, img) + return out.Bytes() +} diff --git a/internal/imageboard/imageboard.go b/internal/imageboard/imageboard.go new file mode 100644 index 0000000..e679c5f --- /dev/null +++ b/internal/imageboard/imageboard.go @@ -0,0 +1,599 @@ +// Package imageboard is the BBS's image boards, in the manner of +// kusaba-x and of 4chan that it followed (and Futallaby, Futaba before +// them): boards by directory (/b/), anonymous posts with an image each, +// threads bumped by their replies until a bump limit, pruned off the last +// page; tripcodes, sage, greentext, >>quotes, spoilers; a catalog, and +// 4chan's read-only JSON. It is served by the HTTP API's server at +// /chan/, staff being the BBS's sysops and each board's mods. +package imageboard + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "embed" + "encoding/hex" + "errors" + "fmt" + "html/template" + "image/color" + "io/fs" + "net" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/store" +) + +//go:embed templates/*.html static/* +var content embed.FS + +// Base is where the image boards are. +const Base = "/chan" + +// Sessions are the logins: the HTTP API's session tokens, as the web +// forum's are. +type Sessions interface { + Login(r *http.Request, name, password string) (secret string, u *store.User, err error) + User(secret string) *store.User + Logout(secret string) +} + +// Settings are how the image boards are run, all boards alike. +type Settings struct { + Dir string // where images and thumbnails are kept + MaxFile int64 // bytes, the largest image (a board may say less or more) + ThreadWait time.Duration // between an address's threads + ReplyWait time.Duration // between its posts + MaxComment int // characters + Strip bool // JPEGs' metadata (EXIF: where a phone took it) taken out + Style string // the style callers get until they choose ("": by the board, as 4chan's) +} + +// Defaults are the settings unless bbs.conf says otherwise. +func Defaults() Settings { + return Settings{Dir: "chan", MaxFile: 4 << 20, ThreadWait: 60 * time.Second, ReplyWait: 15 * time.Second, + MaxComment: 2000, Strip: true} +} + +// Style is a look the boards can wear: a stylesheet. +type Style struct { + Name, Title string +} + +// Styles are the boards' looks: 4chan's, then kusaba's. +var Styles = []Style{ + {"yotsuba", "Yotsuba"}, + {"yotsuba-b", "Yotsuba B"}, + {"futaba", "Futaba"}, + {"burichan", "Burichan"}, + {"photon", "Photon"}, + {"tomorrow", "Tomorrow"}, +} + +// KnownStyle says whether there is a style of the name. +func KnownStyle(name string) bool { + for _, s := range Styles { + if s.Name == name { + return true + } + } + return false +} + +// Server serves the image boards. +type Server struct { + B *bbs.BBS + Sessions Sessions + S Settings + Secure bool // cookies only over TLS + TTL time.Duration // a login's + + tmpl *template.Template + static http.Handler + key []byte // for tokens, passwords and secure tripcodes: kept in Dir + spoiler []byte +} + +const ( + sessionCookie = "chan_session" + passCookie = "chan_pass" + nameCookie = "chan_name" + styleCookie = "chan_style" +) + +// 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} + +// ValidDir says what is wrong with a board's directory ("": nothing). +func ValidDir(dir string) string { + if dir == "" || len(dir) > 16 || reserved[dir] { + return "a board's directory is 1 to 16 letters or digits, and not one of the image boards' own names" + } + for _, c := range dir { + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9') { + return "a board's directory is 1 to 16 lower-case letters or digits (b, g, tech)" + } + } + return "" +} + +// Handler is the image boards' routes, under Base. +func (s *Server) Handler() (http.Handler, error) { + if s.tmpl == nil { + t, err := template.New("").Funcs(funcs).ParseFS(content, "templates/*.html") + if err != nil { + return nil, err + } + s.tmpl = t + if err := os.MkdirAll(s.S.Dir, 0700); err != nil { + return nil, err + } + if s.key, err = loadKey(filepath.Join(s.S.Dir, "secret")); err != nil { + return nil, err + } + static, _ := fs.Sub(content, "static") + files := http.FileServer(http.FS(static)) + s.static = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "public, max-age=3600") + files.ServeHTTP(w, r) + }) + s.spoiler = spoilerImage() + } + return http.HandlerFunc(s.route), nil +} + +// loadKey is the image boards' secret, made the first time: it must last, +// or secure tripcodes and posts' passwords would change. +func loadKey(p string) ([]byte, error) { + b, err := os.ReadFile(p) + if err == nil && len(b) == 64 { + return hex.DecodeString(string(b)) + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + k := make([]byte, 32) + rand.Read(k) + return k, os.WriteFile(p, []byte(hex.EncodeToString(k)), 0600) +} + +// req is a request in hand. +type req struct { + w http.ResponseWriter + r *http.Request + s *Server + user *store.User // logged in (nil: anonymous) + secret string + pass string // the browser's posts' password (its cookie) +} + +// route finds a request's page: /chan/, /chan/b/, /chan/b/2, +// /chan/b/thread/123, /chan/b/catalog, the JSON beside them, and the +// image boards' own pages. +func (s *Server) route(w http.ResponseWriter, r *http.Request) { + defer func() { + if v := recover(); v != nil { + s.B.Log.Printf("chan %s %s: panic: %v", r.Method, r.URL.Path, v) + http.Error(w, "something went wrong", http.StatusInternalServerError) + } + }() + q := &req{w: w, r: r, s: s} + if c, err := r.Cookie(sessionCookie); err == nil { + q.secret = c.Value + q.user = s.Sessions.User(c.Value) + } + if c, err := r.Cookie(passCookie); err == nil && len(c.Value) >= 8 && len(c.Value) <= 64 { + q.pass = c.Value + } + hd := w.Header() + hd.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; form-action 'self'; base-uri 'none'") + hd.Set("X-Frame-Options", "DENY") + hd.Set("Referrer-Policy", "same-origin") + + path := strings.TrimPrefix(r.URL.Path, Base) + if path == "" { + http.Redirect(w, r, Base+"/", http.StatusMovedPermanently) + return + } + seg := strings.Split(strings.TrimPrefix(path, "/"), "/") + get, post := r.Method == http.MethodGet || r.Method == http.MethodHead, r.Method == http.MethodPost + switch { + case len(seg) == 1 && seg[0] == "" && get: + s.front(q) + return + case seg[0] == "static" && len(seg) == 2 && get: + if seg[1] == "spoiler.png" { + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Cache-Control", "public, max-age=86400") + w.Write(s.spoiler) + return + } + http.StripPrefix(Base+"/static/", s.static).ServeHTTP(w, r) + return + case len(seg) == 1 && seg[0] == "boards.json" && get: + s.boardsJSON(q) + return + case len(seg) == 1 && seg[0] == "login" && (get || post): + s.login(q) + return + case len(seg) == 1 && seg[0] == "logout" && post: + s.logout(q) + return + case len(seg) == 1 && seg[0] == "style" && post: + s.chooseStyle(q) + return + case seg[0] == "manage" && len(seg) <= 2: + sub := "" + if len(seg) == 2 { + sub = seg[1] + } + s.manage(q, sub) + return + case reserved[seg[0]]: + q.notFound() + return + } + b, err := s.B.Store.Board(seg[0]) + if err != nil { + q.notFound() + return + } + if len(seg) == 1 { // /chan/b + http.Redirect(w, r, Base+"/"+b.Dir+"/", http.StatusMovedPermanently) + return + } + switch rest := seg[1:]; { + case len(rest) == 1 && rest[0] == "" && get: + s.index(q, b, 1) + case len(rest) == 1 && rest[0] == "catalog" && get: + s.catalog(q, b) + case len(rest) == 1 && rest[0] == "catalog.json" && get: + s.catalogJSON(q, b) + case len(rest) == 1 && rest[0] == "threads.json" && get: + s.threadsJSON(q, b) + case len(rest) == 1 && rest[0] == "archive" && get: + http.Redirect(w, r, Base+"/"+b.Dir+"/catalog", http.StatusFound) + case len(rest) == 1 && rest[0] == "post" && post: + s.post(q, b) + case len(rest) == 1 && rest[0] == "delete" && post: + s.delete(q, b) + case len(rest) == 1 && rest[0] == "report" && (get || post): + s.report(q, b) + case len(rest) == 1 && get: + name, isJSON := strings.CutSuffix(rest[0], ".json") + name = strings.TrimSuffix(name, ".html") // kusaba's 1.html + page, err := strconv.Atoi(name) + switch { + case err != nil || page < 0 || page == 0 && isJSON: + q.notFound() + case isJSON: + s.pageJSON(q, b, page) + case page <= 1: + http.Redirect(w, r, Base+"/"+b.Dir+"/", http.StatusMovedPermanently) + default: + s.index(q, b, page) + } + case len(rest) == 2 && (rest[0] == "thread" || rest[0] == "res") && get: + name, isJSON := strings.CutSuffix(rest[1], ".json") + name = strings.TrimSuffix(name, ".html") // kusaba's res/123.html + no, err := strconv.ParseInt(name, 10, 64) + switch { + case err != nil || no < 1: + q.notFound() + case isJSON: + s.threadJSON(q, b, no) + case rest[0] == "res": + http.Redirect(w, r, fmt.Sprintf("%s/%s/thread/%d", Base, b.Dir, no), http.StatusMovedPermanently) + default: + s.thread(q, b, no) + } + case len(rest) == 2 && (rest[0] == "src" || rest[0] == "thumb") && get: + s.file(q, b, rest[0], rest[1]) + default: + if !get && !post { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + q.notFound() + } +} + +// host is the caller's address. +func (q *req) host() string { + h, _, err := net.SplitHostPort(q.r.RemoteAddr) + if err != nil { + return q.r.RemoteAddr + } + return h +} + +// staff is what the user is on a board: "admin" (a sysop), "mod" (one of +// its mods), or "". +func (q *req) staff(b *store.Board) string { + if q.user == nil { + return "" + } + if q.user.Sysop { + return "admin" + } + if b != nil && isMod(b, q.user.Name) { + return "mod" + } + return "" +} + +func isMod(b *store.Board, name string) bool { + for _, m := range strings.FieldsFunc(b.Mods, func(r rune) bool { return r == ',' || r == ' ' }) { + if strings.EqualFold(m, name) { + return true + } + } + return false +} + +// anyStaff says whether the user is staff anywhere. +func (q *req) anyStaff() bool { + if q.user == nil { + return false + } + if q.user.Sysop { + return true + } + bs, _ := q.s.B.Store.Boards() + for _, b := range bs { + if isMod(b, q.user.Name) { + return true + } + } + return false +} + +// mac is a keyed hash of what is given, in hex. +func (s *Server) mac(parts ...string) string { + m := hmac.New(sha256.New, s.key) + for _, p := range parts { + m.Write([]byte(p)) + m.Write([]byte{0}) + } + return hex.EncodeToString(m.Sum(nil))[:32] +} + +// token is what the forms carry, to show they are this site's: of the +// browser's password cookie, and of its login. +func (q *req) token() string { + return q.s.mac("form", q.pass, q.secret) +} + +// checkToken checks a form's token (after its form is read). +func (q *req) checkToken() bool { + return q.pass != "" && hmac.Equal([]byte(q.r.FormValue("tok")), []byte(q.token())) +} + +// ensurePass gives the browser a password for its posts if it has none: +// what deletes them, and what its forms' tokens are made of. +func (q *req) ensurePass() { + if q.pass != "" { + return + } + b := make([]byte, 8) + rand.Read(b) + q.pass = hex.EncodeToString(b) + http.SetCookie(q.w, &http.Cookie{Name: passCookie, Value: q.pass, Path: Base, MaxAge: 365 * 24 * 3600, + HttpOnly: true, Secure: q.s.Secure, SameSite: http.SameSiteLaxMode}) +} + +// page is what every page's layout shows. +type page struct { + Title string + BBS string + Boards []*store.Board + Board *store.Board // nil: none + User *store.User + Staff string // on this board + AnyStaff bool + Style string + Styles []Style + Token string + Pass string + Path string + Notice string + Body any +} + +func (q *req) render(status int, name, title string, b *store.Board, body any) { + q.ensurePass() + p := page{Title: title, BBS: q.s.B.Name, Board: b, User: q.user, Staff: q.staff(b), AnyStaff: q.anyStaff(), + Style: q.style(b), Styles: Styles, Token: q.token(), Pass: q.pass, Path: q.r.URL.RequestURI(), + Notice: q.r.URL.Query().Get("notice"), Body: body} + p.Boards, _ = q.s.B.Store.Boards() + var buf strings.Builder + if err := q.s.tmpl.ExecuteTemplate(&buf, name, p); err != nil { + q.s.B.Log.Printf("chan: %s: %v", name, err) + http.Error(q.w, "the page could not be made", http.StatusInternalServerError) + return + } + q.w.Header().Set("Content-Type", "text/html; charset=utf-8") + q.w.Header().Set("Cache-Control", "no-store") + q.w.WriteHeader(status) + fmt.Fprint(q.w, buf.String()) +} + +// style is the style the caller chose, else the image boards', else the +// board's: Yotsuba B for a worksafe one, Yotsuba for the rest. +func (q *req) style(b *store.Board) string { + if c, err := q.r.Cookie(styleCookie); err == nil && KnownStyle(c.Value) { + return c.Value + } + if KnownStyle(q.s.S.Style) { + return q.s.S.Style + } + if b != nil && !b.Worksafe { + return "yotsuba" + } + return "yotsuba-b" +} + +// thumbBG is what shows through a transparent image's thumbnail: the +// posts' colour in the board's own style. +func thumbBG(b *store.Board) color.Color { + if b.Worksafe { + return color.RGBA{0xd6, 0xda, 0xf0, 0xff} + } + return color.RGBA{0xf0, 0xe0, 0xd6, 0xff} +} + +// chooseStyle keeps a caller's style. +func (s *Server) chooseStyle(q *req) { + q.r.ParseForm() + name := q.r.PostForm.Get("style") + if name != "" && !KnownStyle(name) { + q.fail(http.StatusBadRequest, "There is no such style.") + return + } + c := &http.Cookie{Name: styleCookie, Value: name, Path: Base, MaxAge: 365 * 24 * 3600, HttpOnly: true, + Secure: s.Secure, SameSite: http.SameSiteLaxMode} + if name == "" { + c.MaxAge = -1 + } + http.SetCookie(q.w, c) + q.redirect(safeBack(q.r.PostForm.Get("back"))) +} + +// safeBack is a page of ours to go back to. +func safeBack(p string) string { + if !strings.HasPrefix(p, Base+"/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "\\\r\n") { + return Base + "/" + } + return p +} + +func (q *req) redirect(to string) { http.Redirect(q.w, q.r, to, http.StatusSeeOther) } + +// fail shows an error, as 4chan's: what is wrong, and the way back. +func (q *req) fail(status int, msg string) { + q.render(status, "error.html", "Error", nil, map[string]any{"Message": msg, "Back": q.r.Referer()}) +} + +func (q *req) notFound() { + q.fail(http.StatusNotFound, "There is nothing here: no such board, thread or page.") +} + +// login has a BBS user sign in: staff to moderate, and anyone where only +// users post. +func (s *Server) login(q *req) { + back := safeBack(q.r.FormValue("back")) + if q.r.Method == http.MethodGet { + q.render(http.StatusOK, "login.html", "Sign in", nil, map[string]any{"Back": back}) + return + } + q.r.ParseForm() + if !q.checkToken() { + q.fail(http.StatusForbidden, "That form has expired: go back, reload the page and try again.") + return + } + secret, _, err := s.Sessions.Login(q.r, q.r.PostForm.Get("name"), q.r.PostForm.Get("password")) + if err != nil { + q.render(http.StatusUnauthorized, "login.html", "Sign in", nil, map[string]any{"Back": back, "Error": err.Error()}) + return + } + http.SetCookie(q.w, &http.Cookie{Name: sessionCookie, Value: secret, Path: Base, HttpOnly: true, Secure: s.Secure, + SameSite: http.SameSiteLaxMode, Expires: time.Now().Add(s.TTL)}) + q.redirect(back) +} + +func (s *Server) logout(q *req) { + q.r.ParseForm() + if q.secret != "" && q.checkToken() { + s.Sessions.Logout(q.secret) + } + http.SetCookie(q.w, &http.Cookie{Name: sessionCookie, Value: "", Path: Base, MaxAge: -1, HttpOnly: true, + Secure: s.Secure, SameSite: http.SameSiteLaxMode}) + q.redirect(Base + "/") +} + +// file serves an image or a thumbnail: by the name it was stored as. +func (s *Server) file(q *req, b *store.Board, kind, name string) { + var ext string + if kind == "thumb" { + tim, ok := strings.CutSuffix(name, "s.jpg") + if _, err := strconv.ParseInt(tim, 10, 64); !ok || err != nil { + q.notFound() + return + } + ext = ".jpg" + } else { + ext = filepath.Ext(name) + if _, err := strconv.ParseInt(strings.TrimSuffix(name, ext), 10, 64); err != nil || imageTypes[ext] == "" { + q.notFound() + return + } + } + f, err := os.Open(filepath.Join(s.S.Dir, b.Dir, kind, 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", imageTypes[ext]) + 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) +} + +// paths are where a board's files are kept. +func (s *Server) srcPath(dir string, tim int64, ext string) string { + return filepath.Join(s.S.Dir, dir, "src", strconv.FormatInt(tim, 10)+ext) +} + +func (s *Server) thumbPath(dir string, tim int64) string { + return filepath.Join(s.S.Dir, dir, "thumb", strconv.FormatInt(tim, 10)+"s.jpg") +} + +// removeFiles takes away posts' files. +func (s *Server) removeFiles(dir string, ps []*store.BoardPost) { + for _, p := range ps { + if p.Ext != "" { + os.Remove(s.srcPath(dir, p.Tim, p.Ext)) + os.Remove(s.thumbPath(dir, p.Tim)) + } + } +} + +// RemoveBoard takes a board away, its posts and its files. +func (s *Server) RemoveBoard(b *store.Board) error { + if err := s.B.Store.DeleteBoard(b.ID); err != nil { + return err + } + return os.RemoveAll(filepath.Join(s.S.Dir, b.Dir)) +} + +// NewBoard is a board as 4chan sets one up: ten pages of ten threads, a +// thread bumped by its first 300 replies and taking 150 images, its +// posters Anonymous. +func NewBoard(dir, title string) *store.Board { + return &store.Board{Dir: dir, Title: title, Pages: 10, PerPage: 10, BumpLimit: 300, ImageLimit: 150, + DefaultName: "Anonymous", Worksafe: true} +} + +// IsAsset says whether a request is for a stylesheet, a script, an image +// or a thumbnail: files served as they are, which a page has many of. +func IsAsset(r *http.Request) bool { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + 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") +} diff --git a/internal/imageboard/imageboard_test.go b/internal/imageboard/imageboard_test.go new file mode 100644 index 0000000..217ca80 --- /dev/null +++ b/internal/imageboard/imageboard_test.go @@ -0,0 +1,492 @@ +package imageboard + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "image" + "image/color" + "image/jpeg" + "image/png" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/store" +) + +// sessions are logins kept in memory (the API's are tested there). +type sessions struct { + b *bbs.BBS + mu sync.Mutex + m map[string]int64 +} + +func (s *sessions) Login(r *http.Request, name, pw string) (string, *store.User, error) { + u, err := s.b.Authenticate("chan", "test", name, pw) + if err != nil { + return "", nil, err + } + var k [16]byte + rand.Read(k[:]) + secret := hex.EncodeToString(k[:]) + s.mu.Lock() + s.m[secret] = u.ID + s.mu.Unlock() + return secret, u, nil +} + +func (s *sessions) User(secret string) *store.User { + s.mu.Lock() + id, ok := s.m[secret] + s.mu.Unlock() + if !ok { + return nil + } + u, _ := s.b.Store.UserByID(id) + return u +} + +func (s *sessions) Logout(secret string) { + s.mu.Lock() + delete(s.m, secret) + s.mu.Unlock() +} + +type site struct { + t *testing.T + b *bbs.BBS + ts *httptest.Server + srv *Server + bd *store.Board + log *bytes.Buffer +} + +func setup(t *testing.T) *site { + t.Helper() + store.BcryptCost = 4 + dir := t.TempDir() + st, err := store.Open(filepath.Join(dir, "bbs.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + s := bbs.Defaults() + s.Name, s.FailDelay = "Test Board", 0 + lb := &bytes.Buffer{} + b := bbs.New(s, st, log.New(lb, "", 0)) + st.CreateUser("sysop", "password1", "Here", true) + st.CreateUser("mia", "password1", "Here", false) + bd, err := st.CreateBoard(NewBoard("b", "Random")) + if err != nil { + t.Fatal(err) + } + set := Defaults() + set.Dir, set.ThreadWait, set.ReplyWait = filepath.Join(dir, "chan"), 0, 0 + srv := &Server{B: b, Sessions: &sessions{b: b, m: map[string]int64{}}, S: set, TTL: time.Hour} + h, err := srv.Handler() + if err != nil { + t.Fatal(err) + } + ts := httptest.NewServer(h) + t.Cleanup(ts.Close) + t.Cleanup(func() { + if t.Failed() { + t.Logf("log:\n%s", lb) + } + }) + return &site{t: t, b: b, ts: ts, srv: srv, bd: bd, log: lb} +} + +type browser struct { + s *site + c *http.Client + tok string +} + +func (s *site) browser() *browser { + jar, _ := cookiejar.New(nil) + return &browser{s: s, c: &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }}} +} + +var tokPat = regexp.MustCompile(`name="tok" value="([0-9a-f]+)"`) + +// get fetches a page: its status, where it sends on to, and its body. +func (br *browser) get(path string) (int, string, string) { + br.s.t.Helper() + resp, err := br.c.Get(br.s.ts.URL + path) + if err != nil { + br.s.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + if m := tokPat.FindSubmatch(b); m != nil { + br.tok = string(m[1]) + } + return resp.StatusCode, resp.Header.Get("Location"), string(b) +} + +func (br *browser) postForm(path string, v url.Values) (int, string, string) { + br.s.t.Helper() + if v.Get("tok") == "" { + v.Set("tok", br.tok) + } + resp, err := br.c.PostForm(br.s.ts.URL+path, v) + if err != nil { + br.s.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, resp.Header.Get("Location"), string(b) +} + +// post posts to a board as its form does: fields, and an image (nil: +// none). +func (br *browser) post(dir string, fields map[string]string, file []byte, fileName string) (int, string, string) { + br.s.t.Helper() + if br.tok == "" { + br.get("/chan/" + dir + "/") + } + var body bytes.Buffer + w := multipart.NewWriter(&body) + w.WriteField("tok", br.tok) + for k, v := range fields { + w.WriteField(k, v) + } + if file != nil { + fw, _ := w.CreateFormFile("upfile", fileName) + fw.Write(file) + } + w.Close() + req, _ := http.NewRequest("POST", br.s.ts.URL+"/chan/"+dir+"/post", &body) + req.Header.Set("Content-Type", w.FormDataContentType()) + resp, err := br.c.Do(req) + if err != nil { + br.s.t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, resp.Header.Get("Location"), string(b) +} + +// pngOf is a w by h PNG, half transparent, of a colour. +func pngOf(w, h int, c color.RGBA) []byte { + img := image.NewNRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + if x < w/2 { + img.Set(x, y, c) + } + } + } + var b bytes.Buffer + png.Encode(&b, img) + return b.Bytes() +} + +func jpegWithExif() []byte { + img := image.NewRGBA(image.Rect(0, 0, 40, 30)) + var b bytes.Buffer + jpeg.Encode(&b, img, nil) + j := b.Bytes() + exif := []byte("Exif\x00\x00GPS-SECRET-PLACE") + seg := append([]byte{0xff, 0xe1, byte((len(exif) + 2) >> 8), byte(len(exif) + 2)}, exif...) + return append(append(append([]byte{}, j[:2]...), seg...), j[2:]...) +} + +func TestImageBoard(t *testing.T) { + s := setup(t) + anon := s.browser() + + if code, _, body := anon.get("/chan/"); code != 200 || !strings.Contains(body, "/b/ - Random") { + t.Fatalf("front page %d:\n%s", code, body) + } + if code, _, body := anon.get("/chan/b/"); code != 200 || !strings.Contains(body, "New Thread") || + !strings.Contains(body, "yotsuba-b.css") { + t.Fatalf("board %d:\n%s", code, body) + } + + // a thread needs an image + if code, _, body := anon.post("b", map[string]string{"com": "hello"}, nil, ""); code != 400 || + !strings.Contains(body, "You forgot to upload your image") { + t.Fatalf("no image: %d", code) + } + // not a forged form + other := s.browser() + other.tok = "00000000000000000000000000000000" + if code, _, _ := other.post("b", map[string]string{"com": "x"}, pngOf(10, 10, color.RGBA{255, 0, 0, 255}), "a.png"); code != 403 { + t.Fatalf("forged: %d", code) + } + // not a file that is not an image + if code, _, body := anon.post("b", map[string]string{"com": "x"}, []byte(""), "x.png"); code != 400 || + !strings.Contains(body, "not an image") { + t.Fatalf("not an image: %d", code) + } + + img1 := pngOf(600, 300, color.RGBA{255, 0, 0, 255}) + code, loc, body := anon.post("b", map[string]string{"name": "Anon#tea", "sub": "First", "pwd": "secret1", + "com": ">implying\n>>1 and >>99 and >>>/b/1\n[spoiler]hidden[/spoiler] https://example.org/x."}, img1, "red square.png") + if code != 303 || loc != "/chan/b/thread/1#p1" { + t.Fatalf("a new thread: %d %q\n%s", code, loc, body) + } + p1, err := s.b.Store.ChanPost(s.bd.ID, 1) + if err != nil || p1.Ext != ".png" || p1.W != 600 || p1.H != 300 || p1.TnW != 250 || p1.TnH != 125 || p1.Trip != "!WokonZwxw2" || + p1.Name != "Anon" || p1.FileName != "red square" { + t.Fatalf("the post: %+v", p1) + } + code, _, body = anon.get("/chan/b/thread/1") + for _, want := range []string{`!WokonZwxw2`, `>implying`, + `>>1 (OP)`, `>>99`, + `>>>/b/1`, `hidden`, + `https://example.org/x.`, + `/chan/b/thumb/` + itoa(p1.Tim) + `s.jpg`, `width="250" height="125"`, "Posting mode: Reply", "red square.png"} { + if !strings.Contains(body, want) { + t.Errorf("thread page: no %s", want) + } + } + if t.Failed() { + t.Fatalf("%d\n%s", code, body) + } + // the files, served as what they are + resp, _ := http.Get(s.ts.URL + "/chan/b/src/" + itoa(p1.Tim) + ".png") + if resp.StatusCode != 200 || resp.Header.Get("Content-Type") != "image/png" { + t.Errorf("image: %d %s", resp.StatusCode, resp.Header.Get("Content-Type")) + } + resp.Body.Close() + resp, _ = http.Get(s.ts.URL + "/chan/b/thumb/" + itoa(p1.Tim) + "s.jpg") + tb, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if th, err := jpeg.DecodeConfig(bytes.NewReader(tb)); err != nil || th.Width != 250 || th.Height != 125 { + t.Errorf("thumbnail: %v %+v", err, th) + } + for _, bad := range []string{"/chan/b/src/..%2fsecret", "/chan/b/src/1.svg", "/chan/b/thumb/1.png", "/chan/../bbs.db"} { + if code, _, _ := anon.get(bad); code != 404 && code != 301 && code != 400 { + t.Errorf("%s: %d", bad, code) + } + } + + // flood control + s.srv.S.ReplyWait = time.Hour + if code, _, body := anon.post("b", map[string]string{"resto": "1", "com": "too soon"}, nil, ""); code != 429 || + !strings.Contains(body, "Flood detected") { + t.Fatalf("flood: %d", code) + } + s.srv.S.ReplyWait = 0 + + // replies: one quoting the first (a backlink), one saged + if code, loc, _ := anon.post("b", map[string]string{"resto": "1", "com": ">>1\nagreed", "pwd": "secret2"}, nil, ""); code != 303 || + loc != "/chan/b/thread/1#p2" { + t.Fatalf("reply: %d %s", code, loc) + } + before, _ := s.b.Store.ChanThread(s.bd.ID, 1) + time.Sleep(1100 * time.Millisecond) + anon.post("b", map[string]string{"resto": "1", "com": "quiet", "email": "sage"}, nil, "") + after, _ := s.b.Store.ChanThread(s.bd.ID, 1) + if !after.Bumped.Equal(before.Bumped) || after.Replies != 2 { + t.Errorf("sage bumped it: %v %v, %d replies", before.Bumped, after.Bumped, after.Replies) + } + _, _, body = anon.get("/chan/b/thread/1") + if !strings.Contains(body, `