Image boards at /chan/, after kusaba x and 4chan; trusted proxies

Boards by directory with anonymous posts and images: thumbnails made
in Go (JPEG, PNG, GIF, WebP, told by their bytes), JPEG metadata
stripped, duplicates refused by MD5. Threads bump until a bump limit,
sage, image limits, pruning off the last page, stickies and closed
threads. Tripcodes are 2channel's (a DES crypt(3) of our own, checked
against libc's) and secure ones; greentext, >>quotes with backlinks,
cross-board links, spoilers and code. Index, thread pages, catalog,
password deletion, reports; staff (sysops, a board's mods) delete,
ban by address or range, and post with capcodes. Yotsuba, Yotsuba B,
Futaba, Burichan, Photon and Tomorrow styles, and 4chan's read-only
JSON. bbs chan board|ban on the command line; [chan] in bbs.conf.

[http] trusted_proxies: requests from those take their caller's
address from X-Forwarded-For (Forwarded, X-Real-IP), the last hop that
is not a trusted proxy, for rate limits, logs, the deny lists and the
image boards' bans; a proxy's connections are not held to max_per_ip.
secure_cookies for TLS at the proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-14 00:53:47 +00:00
1 parent 83e7a56cf8
commit 67eecc7b4e
51 files changed
+5296 -7

No files matched your search

+2
View File
@@ -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 |
+28
View File
@@ -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
+259
View File
@@ -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
}
+8
View File
@@ -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()
}
+13
View File
@@ -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
```
+1
View File
@@ -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
+40
View File
@@ -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`)
+2
View File
@@ -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 |
+189
View File
@@ -0,0 +1,189 @@
# Image boards
The HTTP API's server also serves image boards, at `/chan/`, in the manner
of kusaba&nbsp;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)
+1
View File
@@ -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**
+24 -1
View File
@@ -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()
+21 -1
View File
@@ -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
}
+128
View File
@@ -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)
})
}
+91
View File
@@ -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)
}
}
+2 -2
View File
@@ -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)
+294
View File
@@ -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)
}
+188
View File
@@ -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)
}
+196
View File
@@ -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()
}
+599
View File
@@ -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")
}
+492
View File
@@ -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("<svg onload=alert(1)>"), "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{`<span class="postertrip">!WokonZwxw2</span>`, `<span class="quote">&gt;implying</span>`,
`<a href="#p1" class="quotelink" data-no="1">&gt;&gt;1 (OP)</a>`, `<span class="deadlink">&gt;&gt;99</span>`,
`<a href="/chan/b/thread/1#p1" class="quotelink">&gt;&gt;&gt;/b/1</a>`, `<s>hidden</s>`,
`<a href="https://example.org/x" rel="nofollow noreferrer noopener" target="_blank">https://example.org/x</a>.`,
`/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, `<div class="backlink"><span><a href="#p2" class="quotelink" data-no="2">&gt;&gt;2</a></span>`) {
t.Errorf("no backlink:\n%s", body)
}
// the same image again
if code, _, body := anon.post("b", map[string]string{"resto": "1"}, img1, "again.png"); code != 409 ||
!strings.Contains(body, "/chan/b/thread/1#p1") {
t.Errorf("duplicate: %d", code)
}
// a JPEG's EXIF is taken out
code, _, _ = anon.post("b", map[string]string{"resto": "1", "spoiler": "on"}, jpegWithExif(), "phone.jpg")
p4, _ := s.b.Store.ChanPost(s.bd.ID, 4)
if code != 303 || p4 == nil || !p4.Spoiler {
t.Fatalf("jpeg: %d %+v", code, p4)
}
kept, _ := os.ReadFile(s.srv.srcPath("b", p4.Tim, ".jpg"))
if bytes.Contains(kept, []byte("GPS-SECRET")) || len(kept) == 0 {
t.Error("the EXIF was kept")
}
// the index: the thread with its last replies; the catalog
_, _, body = anon.get("/chan/b/")
if !strings.Contains(body, `[<a href="/chan/b/thread/1" class="replylink">Reply</a>]`) || !strings.Contains(body, "spoiler.png") {
t.Errorf("index:\n%s", body)
}
if code, _, body := anon.get("/chan/b/catalog"); code != 200 || !strings.Contains(body, "R: <b>3</b> / I: <b>1</b>") {
t.Errorf("catalog %d:\n%s", code, body)
}
// JSON as 4chan's
var boards struct {
Boards []struct {
Board string `json:"board"`
Pages int `json:"pages"`
} `json:"boards"`
}
getJSON(t, s.ts.URL+"/chan/boards.json", &boards)
if len(boards.Boards) != 1 || boards.Boards[0].Board != "b" || boards.Boards[0].Pages != 10 {
t.Errorf("boards.json: %+v", boards)
}
var thread struct {
Posts []apiPost `json:"posts"`
}
getJSON(t, s.ts.URL+"/chan/b/thread/1.json", &thread)
if len(thread.Posts) != 4 || thread.Posts[0].No != 1 || thread.Posts[0].Tim != p1.Tim || thread.Posts[0].MD5 != p1.MD5 ||
*thread.Posts[0].Replies != 3 || thread.Posts[0].SemanticURL != "first" || thread.Posts[1].Resto != 1 ||
thread.Posts[3].Spoiler != 1 {
t.Errorf("thread.json: %+v", thread.Posts)
}
var catalog []struct {
Page int `json:"page"`
Threads []apiPost `json:"threads"`
}
getJSON(t, s.ts.URL+"/chan/b/catalog.json", &catalog)
if len(catalog) != 1 || len(catalog[0].Threads) != 1 || len(catalog[0].Threads[0].LastReplies) != 3 {
t.Errorf("catalog.json: %+v", catalog)
}
var page struct {
Threads []struct {
Posts []apiPost `json:"posts"`
} `json:"threads"`
}
getJSON(t, s.ts.URL+"/chan/b/1.json", &page)
if len(page.Threads) != 1 || len(page.Threads[0].Posts) != 4 {
t.Errorf("1.json: %+v", page)
}
// deleting: by its password, not by another's
if code, _, _ := other.postForm("/chan/b/delete", url.Values{"2": {"delete"}, "pwd": {"wrong"}, "tok": {otherTok(other)}}); code != 403 {
t.Errorf("deleted with the wrong password: %d", code)
}
if code, _, _ := anon.postForm("/chan/b/delete", url.Values{"2": {"delete"}, "pwd": {"secret2"}}); code != 303 {
t.Errorf("delete: %d", code)
}
if _, err := s.b.Store.ChanPost(s.bd.ID, 2); err == nil {
t.Error("not deleted")
}
anon.postForm("/chan/b/delete", url.Values{"1": {"delete"}, "pwd": {"secret1"}, "onlyimgdel": {"on"}})
if p, _ := s.b.Store.ChanPost(s.bd.ID, 1); !p.FileDeleted {
t.Error("its file not deleted")
}
if _, err := os.Stat(s.srv.srcPath("b", p1.Tim, ".png")); err == nil {
t.Error("the image is still there")
}
if _, _, body := anon.get("/chan/b/thread/1"); !strings.Contains(body, "File deleted.") {
t.Error("not shown deleted")
}
// reports, and staff: sticky, close, ban
anon.get("/chan/b/report?no=3")
if code, _, body := anon.postForm("/chan/b/report", url.Values{"no": {"3"}, "reason": {reportReasons[2]}}); code != 200 ||
!strings.Contains(body, "staff will see it") {
t.Errorf("report: %d", code)
}
if code, _, _ := anon.get("/chan/manage"); code != 303 {
t.Errorf("manage without a login: %d", code)
}
mod := s.browser()
mod.get("/chan/login")
if code, _, _ := mod.postForm("/chan/login", url.Values{"name": {"sysop"}, "password": {"password1"}, "back": {"/chan/manage"}}); code != 303 {
t.Fatalf("login: %d", code)
}
code, _, body = mod.get("/chan/manage")
if code != 200 || !strings.Contains(body, "/b/3") || !strings.Contains(body, reportReasons[2]) {
t.Fatalf("reports %d:\n%s", code, body)
}
mod.get("/chan/manage/post?b=b&no=1")
mod.postForm("/chan/manage/post", url.Values{"b": {"b"}, "no": {"1"}, "action": {"close"}})
mod.postForm("/chan/manage/post", url.Values{"b": {"b"}, "no": {"1"}, "action": {"sticky"}})
if p, _ := s.b.Store.ChanPost(s.bd.ID, 1); !p.Closed || !p.Sticky {
t.Errorf("not closed and sticky: %+v", p)
}
if code, _, _ := anon.post("b", map[string]string{"resto": "1", "com": "closed?"}, nil, ""); code != 403 {
t.Errorf("reply to a closed thread: %d", code)
}
// staff may, as ## Admin
if code, _, _ := mod.post("b", map[string]string{"resto": "1", "com": "Closed.", "capcode": "on"}, nil, ""); code != 303 {
t.Errorf("staff reply: %d", code)
}
_, _, body = anon.get("/chan/b/thread/1")
if !strings.Contains(body, `<strong class="capcode">## Admin</strong>`) || !strings.Contains(body, "Sticky") {
t.Error("no capcode or sticky")
}
// a ban, said under the post: the poster is shown why
mod.postForm("/chan/manage/post", url.Values{"b": {"b"}, "no": {"3"}, "action": {"ban"}, "reason": {"Being quiet"},
"days": {"1"}, "public": {"on"}})
if _, _, body := anon.get("/chan/b/thread/1"); !strings.Contains(body, "(USER WAS BANNED FOR THIS POST)") {
t.Error("the ban is not said")
}
code, _, body = anon.post("b", map[string]string{"com": "hi"}, pngOf(5, 5, color.RGBA{0, 0, 255, 255}), "b.png")
if code != 403 || !strings.Contains(body, "You are banned") || !strings.Contains(body, "Being quiet") {
t.Errorf("banned: %d\n%s", code, body)
}
if code, _, body := mod.get("/chan/manage/bans"); code != 200 || !strings.Contains(body, "Being quiet") {
t.Errorf("bans %d", code)
}
}
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
func otherTok(br *browser) string {
br.get("/chan/b/")
return br.tok
}
func getJSON(t *testing.T, u string, v any) {
t.Helper()
resp, err := http.Get(u)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 || resp.Header.Get("Content-Type") != "application/json" {
t.Fatalf("%s: %d %s", u, resp.StatusCode, resp.Header.Get("Content-Type"))
}
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
t.Fatalf("%s: %v", u, err)
}
}
// TestPrune: past its pages, a board's oldest threads go, files and all;
// stickies stay.
func TestPrune(t *testing.T) {
s := setup(t)
s.bd.Pages, s.bd.PerPage = 1, 2
s.b.Store.UpdateBoard(s.bd)
br := s.browser()
var tims []int64
for i := 0; i < 3; i++ {
code, _, body := br.post("b", map[string]string{"com": "thread"}, pngOf(20+i, 20, color.RGBA{uint8(i * 50), 0, 0, 255}), "x.png")
if code != 303 {
t.Fatalf("thread %d: %d\n%s", i, code, body)
}
p, _ := s.b.Store.ChanPost(s.bd.ID, int64(i+1))
tims = append(tims, p.Tim)
}
if _, err := s.b.Store.ChanPost(s.bd.ID, 1); err == nil {
t.Error("the oldest thread was not pruned")
}
if _, err := os.Stat(s.srv.srcPath("b", tims[0], ".png")); err == nil {
t.Error("its image was not removed")
}
if n, _ := s.b.Store.ChanThreadCount(s.bd.ID); n != 2 {
t.Errorf("%d threads", n)
}
if code, _, _ := br.get("/chan/b/2"); code != 404 {
t.Errorf("page 2: %d", code)
}
}
+290
View File
@@ -0,0 +1,290 @@
package imageboard
import (
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// manage is the staff's pages: reports, a post's moderation, bans.
func (s *Server) manage(q *req, sub string) {
if q.user == nil {
http.Redirect(q.w, q.r, Base+"/login?back="+Base+"/manage", http.StatusSeeOther)
return
}
if !q.anyStaff() {
q.fail(http.StatusForbidden, "That is for the image boards' staff.")
return
}
if q.r.Method == http.MethodPost {
q.r.Body = http.MaxBytesReader(q.w, q.r.Body, 64<<10)
if err := q.r.ParseForm(); err != nil || !q.checkToken() {
q.fail(http.StatusForbidden, "That form has expired: go back, reload the page and try again.")
return
}
} else if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
http.Error(q.w, "method not allowed", http.StatusMethodNotAllowed)
return
}
switch sub {
case "":
s.reports(q)
case "post":
s.modPost(q)
case "bans":
s.bans(q)
default:
q.notFound()
}
}
// boardsModded are the boards the user may moderate.
func (q *req) boardsModded() map[int64]*store.Board {
out := map[int64]*store.Board{}
bs, _ := q.s.B.Store.Boards()
for _, b := range bs {
if q.staff(b) != "" {
out[b.ID] = b
}
}
return out
}
// reports lists what has been reported on the user's boards.
func (s *Server) reports(q *req) {
mine := q.boardsModded()
all, err := s.B.Store.Reports()
if err != nil {
q.fail(http.StatusInternalServerError, "The reports could not be read.")
return
}
type item struct {
*store.Report
Post *store.BoardPost
Count int
}
var items []*item
byPost := map[string]*item{}
for _, r := range all {
if mine[r.BoardID] == nil {
continue
}
key := fmt.Sprintf("%d/%d", r.BoardID, r.No)
if it := byPost[key]; it != nil {
it.Count++
continue
}
p, err := s.B.Store.ChanPost(r.BoardID, r.No)
if err != nil {
continue
}
it := &item{Report: r, Post: p, Count: 1}
byPost[key] = it
items = append(items, it)
}
q.render(http.StatusOK, "manage.html", "Manage", nil, map[string]any{"Reports": items})
}
// modPost is a post as staff see it, and what they can do to it.
func (s *Server) modPost(q *req) {
b, err := s.B.Store.Board(q.r.FormValue("b"))
if err != nil || q.staff(b) == "" {
q.fail(http.StatusForbidden, "That board is not yours to moderate.")
return
}
no, _ := strconv.ParseInt(q.r.FormValue("no"), 10, 64)
p, err := s.B.Store.ChanPost(b.ID, no)
if err != nil {
q.fail(http.StatusNotFound, "That post is not here: it has been deleted.")
return
}
if q.r.Method == http.MethodPost {
s.modAction(q, b, p)
return
}
l := q.newLinks(b, []*store.BoardPost{p})
v := q.view(b, p, l, 0, 0)
byIP, _ := s.B.Store.PostsByIP(p.IP, 50)
var thread *store.BoardPost
if p.Thread == 0 {
thread = p
}
q.render(http.StatusOK, "modpost.html", "Manage /"+b.Dir+"/"+strconv.FormatInt(no, 10), b,
map[string]any{"Post": v, "Thread": thread, "ByIP": byIP, "Range": ipRange(p.IP)})
}
// ipRange is the range an address is banned by with "range": its /24
// (IPv4) or /48 (IPv6), as a prefix.
func ipRange(ip string) string {
a := net.ParseIP(ip)
if a == nil {
return ip
}
if v4 := a.To4(); v4 != nil {
return fmt.Sprintf("%d.%d.%d.", v4[0], v4[1], v4[2])
}
parts := strings.Split(a.String(), ":")
if len(parts) >= 3 {
return strings.Join(parts[:3], ":") + ":"
}
return ip
}
// modAction does what staff chose to a post.
func (s *Server) modAction(q *req, b *store.Board, p *store.BoardPost) {
f := q.r.PostForm
back := fmt.Sprintf("%s/manage/post?b=%s&no=%d", Base, b.Dir, p.No)
who := q.user.Name
switch f.Get("action") {
case "delete", "deletefile":
if err := s.deletePost(b, p, f.Get("action") == "deletefile"); err != nil {
q.fail(http.StatusInternalServerError, "It could not be deleted.")
return
}
s.B.Log.Printf("chan: %s deleted /%s/%d%s", who, b.Dir, p.No, map[bool]string{true: "'s file"}[f.Get("action") == "deletefile"])
if f.Get("action") == "delete" {
back = Base + "/manage"
}
case "sticky", "unsticky", "close", "open":
if p.Thread != 0 {
q.fail(http.StatusBadRequest, "Only a thread's first post is made sticky or closed.")
return
}
sticky, closed := p.Sticky, p.Closed
switch f.Get("action") {
case "sticky", "unsticky":
sticky = f.Get("action") == "sticky"
default:
closed = f.Get("action") == "close"
}
if err := s.B.Store.SetChanThread(b.ID, p.No, sticky, closed); err != nil {
q.fail(http.StatusInternalServerError, "It could not be changed.")
return
}
s.B.Log.Printf("chan: %s made /%s/%d %s", who, b.Dir, p.No, f.Get("action"))
case "ban":
ban := &store.Ban{IP: p.IP, Reason: field(f.Get("reason"), 200), By: who, Post: p.Comment}
if f.Get("range") != "" {
ban.IP = ipRange(p.IP)
}
if f.Get("everywhere") == "" || q.staff(nil) != "admin" {
ban.Board = b.Dir
}
days, err := strconv.Atoi(f.Get("days"))
if err != nil || days < 0 || days > 3650 {
q.fail(http.StatusBadRequest, "A ban is for 0 (for ever) to 3650 days.")
return
}
if days > 0 {
ban.Expires = time.Now().Add(time.Duration(days) * 24 * time.Hour)
}
if _, err := s.B.Store.AddBan(ban); err != nil {
q.fail(http.StatusInternalServerError, "The ban could not be made.")
return
}
s.B.Log.Printf("chan: %s banned %s (/%s/%d) for %d days: %s", who, ban.IP, b.Dir, p.No, days, ban.Reason)
if f.Get("delete") != "" {
s.deletePost(b, p, false)
back = Base + "/manage"
} else if f.Get("public") != "" {
s.B.Store.MarkChanBanned(b.ID, p.No) // "(USER WAS BANNED FOR THIS POST)"
}
s.B.Store.DismissReports(b.ID, p.No)
case "dismiss":
s.B.Store.DismissReports(b.ID, p.No)
back = Base + "/manage"
case "purge":
// every post of the address on this board
ps, _ := s.B.Store.PostsByIP(p.IP, 500)
n := 0
for _, o := range ps {
if o.BoardID == b.ID {
if s.deletePost(b, o, false) == nil {
n++
}
}
}
s.B.Log.Printf("chan: %s deleted %d posts of %s on /%s/", who, n, p.IP, b.Dir)
back = Base + "/manage"
default:
q.fail(http.StatusBadRequest, "There is no such thing to do.")
return
}
q.redirect(back)
}
// bans lists the bans in force, and lifts or adds them.
func (s *Server) bans(q *req) {
admin := q.staff(nil) == "admin"
mine := map[string]bool{}
for _, b := range q.boardsModded() {
mine[b.Dir] = true
}
mayLift := func(b *store.Ban) bool { return admin || b.Board != "" && mine[b.Board] }
if q.r.Method == http.MethodPost {
f := q.r.PostForm
switch {
case f.Get("lift") != "":
id, _ := strconv.ParseInt(f.Get("lift"), 10, 64)
all, _ := s.B.Store.Bans()
for _, b := range all {
if b.ID == id && mayLift(b) {
s.B.Store.DeleteBan(id)
s.B.Log.Printf("chan: %s lifted the ban on %s", q.user.Name, b.IP)
}
}
case f.Get("ip") != "":
ip := strings.TrimSpace(f.Get("ip"))
if net.ParseIP(ip) == nil && !(strings.HasSuffix(ip, ".") || strings.HasSuffix(ip, ":")) {
q.fail(http.StatusBadRequest, "An address (192.0.2.7), or a range ending in . or : (192.0.2.)")
return
}
board := f.Get("board")
if !admin && !mine[board] {
q.fail(http.StatusForbidden, "Ban on a board you moderate.")
return
}
days, err := strconv.Atoi(f.Get("days"))
if err != nil || days < 0 || days > 3650 {
q.fail(http.StatusBadRequest, "A ban is for 0 (for ever) to 3650 days.")
return
}
ban := &store.Ban{IP: ip, Board: board, Reason: field(f.Get("reason"), 200), By: q.user.Name}
if days > 0 {
ban.Expires = time.Now().Add(time.Duration(days) * 24 * time.Hour)
}
if _, err := s.B.Store.AddBan(ban); err != nil {
q.fail(http.StatusInternalServerError, "The ban could not be made.")
return
}
s.B.Log.Printf("chan: %s banned %s", q.user.Name, ip)
}
q.redirect(Base + "/manage/bans")
return
}
all, err := s.B.Store.Bans()
if err != nil {
q.fail(http.StatusInternalServerError, "The bans could not be read.")
return
}
type item struct {
*store.Ban
CanLift bool
}
var items []item
for _, b := range all {
if admin || mine[b.Board] {
items = append(items, item{b, mayLift(b)})
}
}
var dirs []string
for d := range mine {
dirs = append(dirs, d)
}
q.render(http.StatusOK, "bans.html", "Bans", nil, map[string]any{"Bans": items, "Admin": admin, "Mine": dirs})
}
+200
View File
@@ -0,0 +1,200 @@
package imageboard
import (
"fmt"
"html"
"html/template"
"regexp"
"strconv"
"strings"
)
// A comment is kept as it was typed and marked up as it is shown, as
// 4chan marks it up: >>123 links to a post, >>>/b/123 to one on another
// board (>>>/b/ to the board), a line that starts with > is quoted
// (greentext), [spoiler]...[/spoiler] hides text until it is hovered,
// [code]...[/code] is set as code, and links are links.
var tokenPat = regexp.MustCompile(`>>>/([a-z0-9]{1,16})/(\d{1,12})?|>>(\d{1,12})|https?://[^\s<>"'\x60]+|\[/?spoiler\]`)
// Linker finds what a comment's quotes point at.
type linker interface {
// thread is the thread a post of this board is in (ok false: it is
// not there)
thread(no int64) (int64, bool)
// cross is the same for a post of another board; a board alone (no
// 0) is ok if it is there
cross(dir string, no int64) (int64, bool)
}
// quotes are the numbers of this board's posts a comment quotes, and the
// others' by board.
func quotes(text string) (nos []int64, cross map[string][]int64) {
for _, m := range tokenPat.FindAllStringSubmatch(text, -1) {
switch {
case m[3] != "":
n, _ := strconv.ParseInt(m[3], 10, 64)
nos = append(nos, n)
case m[1] != "":
if cross == nil {
cross = map[string][]int64{}
}
n, _ := strconv.ParseInt(m[2], 10, 64)
cross[m[1]] = append(cross[m[1]], n)
}
}
return nos, cross
}
// markup is a comment as HTML: here is the thread being shown (0: a
// board's index, where every quote links to its thread's page), dir the
// board's.
func markup(text, dir string, here int64, l linker) template.HTML {
var b strings.Builder
parts := strings.Split(text, "[code]")
spoilers := 0
for i, part := range parts {
if i > 0 {
code, rest, closed := strings.Cut(part, "[/code]")
if !closed {
code, rest = part, ""
}
b.WriteString(`<pre class="code">`)
b.WriteString(html.EscapeString(strings.Trim(code, "\n")))
b.WriteString(`</pre>`)
part = strings.TrimPrefix(rest, "\n")
}
lines := strings.Split(part, "\n")
for j, line := range lines {
quoted := strings.HasPrefix(line, ">") && !quoteAt(line)
if quoted {
b.WriteString(`<span class="quote">`)
}
last := 0
for _, m := range tokenPat.FindAllStringSubmatchIndex(line, -1) {
b.WriteString(html.EscapeString(line[last:m[0]]))
last = m[1]
tok := line[m[0]:m[1]]
switch {
case tok == "[spoiler]":
spoilers++
b.WriteString(`<s>`)
case tok == "[/spoiler]":
if spoilers > 0 {
spoilers--
b.WriteString(`</s>`)
} else {
b.WriteString(html.EscapeString(tok))
}
case m[6] >= 0: // >>123
n, _ := strconv.ParseInt(line[m[6]:m[7]], 10, 64)
b.WriteString(postLink(tok, dir, n, here, l))
case m[2] >= 0: // >>>/b/123, >>>/b/
board := line[m[2]:m[3]]
var n int64
if m[4] >= 0 {
n, _ = strconv.ParseInt(line[m[4]:m[5]], 10, 64)
}
t, ok := l.cross(board, n)
switch {
case !ok:
fmt.Fprintf(&b, `<span class="deadlink">%s</span>`, html.EscapeString(tok))
case n == 0:
fmt.Fprintf(&b, `<a href="%s/%s/" class="quotelink">%s</a>`, Base, board, html.EscapeString(tok))
default:
fmt.Fprintf(&b, `<a href="%s/%s/thread/%d#p%d" class="quotelink">%s</a>`, Base, board, t, n,
html.EscapeString(tok))
}
default: // a link
u := strings.TrimRight(tok, ".,;:!?)")
fmt.Fprintf(&b, `<a href="%s" rel="nofollow noreferrer noopener" target="_blank">%s</a>`,
html.EscapeString(u), html.EscapeString(u))
b.WriteString(html.EscapeString(tok[len(u):]))
}
}
b.WriteString(html.EscapeString(line[last:]))
if quoted {
b.WriteString(`</span>`)
}
if j < len(lines)-1 {
b.WriteString("<br>")
}
}
}
b.WriteString(strings.Repeat("</s>", spoilers))
return template.HTML(b.String())
}
// quoteAt says whether a line starts with a post's link (>>123), which
// does not make it greentext.
func quoteAt(line string) bool {
m := tokenPat.FindStringIndex(line)
return m != nil && m[0] == 0 && strings.HasPrefix(line, ">>")
}
// postLink is >>123 as a link: to the post in this thread, or to its
// thread's page; struck through if it is not there.
func postLink(tok, dir string, n, here int64, l linker) string {
t, ok := l.thread(n)
if !ok {
return `<span class="deadlink">` + html.EscapeString(tok) + `</span>`
}
text := html.EscapeString(tok)
if n == t {
text += " (OP)"
}
if here != 0 && t == here {
return fmt.Sprintf(`<a href="#p%d" class="quotelink" data-no="%d">%s</a>`, n, n, text)
}
if here != 0 {
text += " &rarr;"
}
return fmt.Sprintf(`<a href="%s/%s/thread/%d#p%d" class="quotelink" data-no="%d">%s</a>`, Base, dir, t, n, n, text)
}
// abbreviate cuts a comment for a board's index: its first lines, and
// whether it was cut.
func abbreviate(text string, lines int) (string, bool) {
n := 0
for i, c := range text {
if c == '\n' {
if n++; n == lines {
return text[:i], true
}
}
if i >= 1500 {
if j := strings.LastIndexAny(text[:i], " \n"); j > 1000 {
i = j
}
return text[:i], true
}
}
return text, false
}
// cleanComment is a comment as kept: lines ended by \n, control
// characters gone, blank lines at its ends trimmed, runs of blank lines
// cut to two.
func cleanComment(s string) string {
s = strings.ReplaceAll(s, "\r\n", "\n")
s = strings.Map(func(r rune) rune {
switch {
case r == '\n', r == '\t':
return r
case r == '\r':
return '\n'
case r < 0x20, r == 0x7f, r >= 0x80 && r < 0xa0, r == '‮', r == '‭', r == '⁦', r == '⁧', r == '⁨':
return -1
}
return r
}, s)
lines := strings.Split(s, "\n")
for i := range lines {
lines[i] = strings.TrimRight(lines[i], " \t")
}
s = strings.Trim(strings.Join(lines, "\n"), "\n")
for strings.Contains(s, "\n\n\n\n") {
s = strings.ReplaceAll(s, "\n\n\n\n", "\n\n\n")
}
return s
}
+389
View File
@@ -0,0 +1,389 @@
package imageboard
import (
"fmt"
"html/template"
"net/http"
"sort"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
var funcs = template.FuncMap{
"size": humanSize,
"date": postDate,
"iso": func(t time.Time) string { return t.UTC().Format(time.RFC3339) },
"add": func(a, b int) int { return a + b },
"short": shortName,
"seq": func(n int) []int {
out := make([]int, n)
for i := range out {
out[i] = i + 1
}
return out
},
}
// postDate is when a post was made, as 4chan writes it.
func postDate(t time.Time) string { return t.Local().Format("01/02/06(Mon)15:04:05") }
// humanSize is a file's size as 4chan shows it.
func humanSize(n int64) string {
switch {
case n >= 1<<20:
return fmt.Sprintf("%.2f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%d KB", n>>10)
}
return fmt.Sprintf("%d B", n)
}
// shortName is a long file name cut, as 4chan cuts them.
func shortName(s string) string {
r := []rune(s)
if len(r) > 30 {
return string(r[:25]) + "(...)"
}
return s
}
// postView is a post as a page shows it.
type postView struct {
*store.BoardPost
Dir string
Name string // its name, or the board's default
Thread int64 // its thread's number (its own, for a first post)
OP bool
Comment template.HTML
Cut bool // the comment is cut, on an index
Backlinks []int64
SrcURL string
ThumbURL string
Staff bool // the viewer may moderate it
Index bool // shown on a board's index (a thread's first gets [Reply])
}
// threadView is a thread as a board's index or its own page shows it.
type threadView struct {
OP *postView
Replies []*postView
OmittedPosts int
OmittedImages int
BumpLimit bool
ImageLimit bool
Teaser template.HTML // the catalog's
}
// links finds what a page's quotes point at, all in a few queries.
type links struct {
q *req
board *store.Board
local map[int64]int64
others map[string]map[int64]int64
boards map[string]bool
}
func (l *links) thread(no int64) (int64, bool) {
t, ok := l.local[no]
return t, ok
}
func (l *links) cross(dir string, no int64) (int64, bool) {
if no == 0 {
return 0, l.boards[dir]
}
t, ok := l.others[dir][no]
return t, ok
}
// newLinks looks up the quotes of the posts.
func (q *req) newLinks(b *store.Board, posts []*store.BoardPost) *links {
l := &links{q: q, board: b, local: map[int64]int64{}, others: map[string]map[int64]int64{}, boards: map[string]bool{}}
var nos []int64
others := map[string][]int64{}
for _, p := range posts {
n, c := quotes(p.Comment)
nos = append(nos, n...)
for d, ns := range c {
others[d] = append(others[d], ns...)
}
}
if len(nos) > 0 {
l.local, _ = q.s.B.Store.ChanPostThreads(b.ID, nos)
}
for d, ns := range others {
ob, err := q.s.B.Store.Board(d)
if err != nil {
continue
}
l.boards[d] = true
l.others[d], _ = q.s.B.Store.ChanPostThreads(ob.ID, ns)
}
return l
}
// view makes a post's view: here is the thread being shown (0: an
// index), cut the lines an index shows of a comment (0: all of it).
func (q *req) view(b *store.Board, p *store.BoardPost, l *links, here int64, cut int) *postView {
v := &postView{BoardPost: p, Dir: b.Dir, Name: p.Name, Thread: p.Thread, OP: p.Thread == 0}
if v.OP {
v.Thread = p.No
}
if v.Name == "" && p.Capcode == "" {
v.Name = b.DefaultName
}
text := p.Comment
if cut > 0 {
text, v.Cut = abbreviate(text, cut)
}
v.Comment = markup(text, b.Dir, here, l)
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.Staff = q.staff(b) != ""
v.Index = here == 0
return v
}
// front is the image boards' front page: the boards, the latest images,
// and how much there is.
func (s *Server) front(q *req) {
recent, _ := s.B.Store.RecentImages(8)
boards, _ := s.B.Store.Boards()
byID := map[int64]*store.Board{}
for _, b := range boards {
byID[b.ID] = b
}
type thumb struct {
Dir string
URL string
Thumb string
Title string
TnW, TnH int
}
var thumbs []thumb
for _, p := range recent {
b := byID[p.BoardID]
if b == nil || !b.Worksafe {
continue // as 4chan's front page: worksafe boards' only
}
t := p.Thread
if t == 0 {
t = p.No
}
w, h := fit(p.TnW, p.TnH, 150)
thumbs = append(thumbs, thumb{Dir: b.Dir, URL: fmt.Sprintf("%s/%s/thread/%d#p%d", Base, b.Dir, t, p.No),
Thumb: fmt.Sprintf("%s/%s/thumb/%ds.jpg", Base, b.Dir, p.Tim), Title: b.Title, TnW: w, TnH: h})
}
posts, bytes, _ := s.B.Store.ChanStats()
q.render(http.StatusOK, "front.html", s.B.Name, nil, map[string]any{"Boards": boards, "Recent": thumbs,
"Posts": posts, "Bytes": bytes})
}
// replies shown under each thread on an index: 5, and 1 under a sticky.
const (
indexReplies = 5
stickyReplies = 1
indexLines = 15
)
// index is a page of a board: its threads, the last bumped first, each
// with its last replies.
func (s *Server) index(q *req, b *store.Board, page int) {
threads, err := s.B.Store.ChanThreads(b.ID, (page-1)*b.PerPage, b.PerPage)
if err != nil {
q.fail(http.StatusInternalServerError, "The board could not be read.")
return
}
total, _ := s.B.Store.ChanThreadCount(b.ID)
pages := max(1, min(b.Pages, (total+b.PerPage-1)/b.PerPage))
if page > pages {
q.notFound()
return
}
views, err := q.threadViews(b, threads, 0)
if err != nil {
q.fail(http.StatusInternalServerError, "The board could not be read.")
return
}
q.render(http.StatusOK, "board.html", "/"+b.Dir+"/ - "+b.Title, b, map[string]any{"Threads": views,
"Page": page, "Pages": pages, "Form": q.form(b, nil)})
}
// threadViews are threads with their last replies (here 0), or all of
// them (here the thread).
func (q *req) threadViews(b *store.Board, ops []*store.BoardPost, here int64) ([]*threadView, error) {
var all []*store.BoardPost
replies := map[int64][]*store.BoardPost{}
for _, op := range ops {
n := indexReplies
if op.Sticky {
n = stickyReplies
}
if here != 0 {
n = 0
}
rs, err := q.s.B.Store.ChanReplies(b.ID, op.No, n)
if err != nil {
return nil, err
}
replies[op.No] = rs
all = append(all, op)
all = append(all, rs...)
}
l := q.newLinks(b, all)
cut := indexLines
if here != 0 {
cut = 0
}
var out []*threadView
for _, op := range ops {
tv := &threadView{OP: q.view(b, op, l, here, cut), BumpLimit: op.Replies >= b.BumpLimit,
ImageLimit: op.Images >= b.ImageLimit}
images := 0
for _, r := range replies[op.No] {
tv.Replies = append(tv.Replies, q.view(b, r, l, here, cut))
if r.Ext != "" {
images++
}
}
tv.OmittedPosts = op.Replies - len(tv.Replies)
tv.OmittedImages = op.Images - images
if here != 0 {
backlinks(tv)
}
out = append(out, tv)
}
return out, nil
}
// backlinks are, under each post's number, the posts in the thread that
// quote it.
func backlinks(tv *threadView) {
posts := append([]*postView{tv.OP}, tv.Replies...)
byNo := map[int64]*postView{}
for _, p := range posts {
byNo[p.No] = p
}
for _, p := range posts {
nos, _ := quotes(p.BoardPost.Comment)
seen := map[int64]bool{}
for _, n := range nos {
if t := byNo[n]; t != nil && !seen[n] && n != p.No {
seen[n] = true
t.Backlinks = append(t.Backlinks, p.No)
}
}
}
}
// thread is a thread's own page: all of it, and the form to reply.
func (s *Server) thread(q *req, b *store.Board, no int64) {
op, err := s.B.Store.ChanThread(b.ID, no)
if err != nil {
// a reply's number: to its post in its thread
if p, err := s.B.Store.ChanPost(b.ID, no); err == nil {
http.Redirect(q.w, q.r, fmt.Sprintf("%s/%s/thread/%d#p%d", Base, b.Dir, p.Thread, p.No), http.StatusFound)
return
}
q.fail(http.StatusNotFound, "That thread is not here: it has been pruned or deleted.")
return
}
views, err := q.threadViews(b, []*store.BoardPost{op}, no)
if err != nil {
q.fail(http.StatusInternalServerError, "The thread could not be read.")
return
}
title := "/" + b.Dir + "/ - "
if op.Subject != "" {
title += op.Subject
} else {
title += firstWords(op.Comment, b.Title)
}
q.render(http.StatusOK, "board.html", title, b, map[string]any{"Threads": views, "Thread": views[0],
"Form": q.form(b, op)})
}
// firstWords are a comment's first words, for a thread's title.
func firstWords(s, otherwise string) string {
s = strings.Join(strings.Fields(s), " ")
if r := []rune(s); len(r) > 50 {
s = string(r[:50]) + "..."
}
if s == "" {
return otherwise
}
return s
}
// formView is the post form.
type formView struct {
Reply *store.BoardPost // the thread replied to (nil: a new thread)
Name string
Quote string
Closed bool // no one but staff may reply
CanPost bool
NeedLogin bool
Capcode string // the staff's
MaxFile int64
Image bool // an image is needed
}
func (q *req) form(b *store.Board, op *store.BoardPost) formView {
f := formView{Reply: op, MaxFile: q.s.maxFile(b), Capcode: q.staff(b), CanPost: true}
if c, err := q.r.Cookie(nameCookie); err == nil {
f.Name = c.Value
}
if n := q.r.URL.Query().Get("quote"); n != "" && len(n) < 13 {
f.Quote = ">>" + strings.TrimLeft(n, ">") + "\n"
}
switch {
case op != nil && op.Closed && f.Capcode == "":
f.Closed, f.CanPost = true, false
case b.Locked && f.Capcode == "":
f.CanPost = false
case b.LoginToPost && q.user == nil:
f.CanPost, f.NeedLogin = false, true
}
f.Image = op == nil && !b.TextOnly
return f
}
// maxFile is the largest image a board takes.
func (s *Server) maxFile(b *store.Board) int64 {
if b.MaxFile > 0 {
return b.MaxFile
}
return s.S.MaxFile
}
// catalog is a board's threads at a glance: each first post's thumbnail,
// its counts, and the start of its comment.
func (s *Server) catalog(q *req, b *store.Board) {
ops, err := s.B.Store.ChanThreads(b.ID, 0, b.Pages*b.PerPage)
if err != nil {
q.fail(http.StatusInternalServerError, "The board could not be read.")
return
}
if q.r.URL.Query().Get("order") == "new" {
sort.SliceStable(ops, func(i, j int) bool { return ops[i].No > ops[j].No })
}
l := q.newLinks(b, ops)
var views []*threadView
for _, op := range ops {
v := q.view(b, op, l, 0, 0)
text, _ := abbreviate(op.Comment, 4)
if r := []rune(text); len(r) > 200 {
text = string(r[:200]) + "..."
}
w, h := fit(op.TnW, op.TnH, 150)
v.TnW, v.TnH = w, h
views = append(views, &threadView{OP: v, Teaser: markup(text, b.Dir, 0, l),
BumpLimit: op.Replies >= b.BumpLimit, ImageLimit: op.Images >= b.ImageLimit})
}
q.render(http.StatusOK, "catalog.html", "/"+b.Dir+"/ - "+b.Title+" - Catalog", b, map[string]any{"Threads": views,
"New": q.r.URL.Query().Get("order") == "new"})
}
+419
View File
@@ -0,0 +1,419 @@
package imageboard
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
const (
maxName = 75
maxEmail = 75
maxSubject = 100
maxLines = 100
)
// field is a one-line field as kept: control characters out, cut.
func field(s string, n int) string {
s = strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f || r >= 0x80 && r < 0xa0 || r >= 0x202a && r <= 0x202e || r >= 0x2066 && r <= 0x2069 {
return -1
}
return r
}, s)
s = strings.TrimSpace(s)
if r := []rune(s); len(r) > n {
s = string(r[:n])
}
return s
}
// banned shows the banned what they were banned for.
func (q *req) banned(b *store.Ban) {
q.render(http.StatusForbidden, "banned.html", "Banned", nil, map[string]any{"Ban": b, "IP": q.host()})
}
// checkBan shows the banned page if the caller is banned on the board.
func (q *req) checkBan(dir string) bool {
ban, err := q.s.B.Store.BanFor(q.host(), dir)
if err != nil {
q.fail(http.StatusInternalServerError, "The system is in trouble: try again later.")
return true
}
if ban != nil {
q.banned(ban)
return true
}
return false
}
// post takes a post: a new thread, or a reply (resto).
func (s *Server) post(q *req, b *store.Board) {
q.r.Body = http.MaxBytesReader(q.w, q.r.Body, s.maxFile(b)+256<<10)
if err := q.r.ParseMultipartForm(1 << 20); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
q.fail(http.StatusRequestEntityTooLarge, fmt.Sprintf("That file is too large: at most %s.", humanSize(s.maxFile(b))))
return
}
q.fail(http.StatusBadRequest, "That form could not be read.")
return
}
defer q.r.MultipartForm.RemoveAll()
if !q.checkToken() {
q.fail(http.StatusForbidden, "That form has expired: go back, reload the page and try again.")
return
}
if q.checkBan(b.Dir) {
return
}
staff := q.staff(b)
f := q.r.MultipartForm.Value
val := func(k string) string {
if v := f[k]; len(v) > 0 {
return v[0]
}
return ""
}
switch {
case b.Locked && staff == "":
q.fail(http.StatusForbidden, "This board is locked: only staff post here.")
return
case b.LoginToPost && q.user == nil:
q.fail(http.StatusForbidden, "Only this BBS's users post here: sign in first.")
return
}
var resto int64
if v := val("resto"); v != "" {
var err error
if resto, err = strconv.ParseInt(v, 10, 64); err != nil || resto < 1 {
q.fail(http.StatusBadRequest, "There is no such thread.")
return
}
}
var op *store.BoardPost
if resto != 0 {
var err error
if op, err = s.B.Store.ChanThread(b.ID, resto); err != nil {
q.fail(http.StatusNotFound, "That thread is not here: it has been pruned or deleted.")
return
}
if op.Closed && staff == "" {
q.fail(http.StatusForbidden, "You cannot reply to this thread anymore: it is closed.")
return
}
}
// flood control: staff are not held to it
if staff == "" {
last, lastThread, err := s.B.Store.LastPostBy(q.host())
if err != nil {
q.fail(http.StatusInternalServerError, "The system is in trouble: try again later.")
return
}
wait := s.S.ReplyWait - time.Since(last)
if resto == 0 {
wait = max(wait, s.S.ThreadWait-time.Since(lastThread))
}
if wait > 0 {
q.fail(http.StatusTooManyRequests, fmt.Sprintf("Flood detected: wait %d seconds before posting again.",
int(wait.Seconds())+1))
return
}
}
typed := val("name")
p := &store.BoardPost{BoardID: b.ID, Thread: resto, IP: q.host(), Subject: field(val("sub"), maxSubject)}
if !b.ForcedAnon {
p.Name, p.Trip = splitName(field(typed, maxName+40), s.key)
p.Name = field(p.Name, maxName)
}
email := field(val("email"), maxEmail)
sage := strings.EqualFold(email, "sage")
nonoko := strings.EqualFold(email, "nonoko")
if !strings.EqualFold(email, "noko") && !nonoko {
p.Email = email
}
if q.user != nil {
p.UserID = q.user.ID
}
if staff != "" && val("capcode") != "" {
p.Capcode = staff
}
if pw := val("pwd"); pw != "" {
p.Password = s.mac("pw", pw)
}
p.Comment = cleanComment(val("com"))
if n := utf8.RuneCountInString(p.Comment); n > s.S.MaxComment {
q.fail(http.StatusBadRequest, fmt.Sprintf("Your comment is too long: %d characters, at most %d.", n, s.S.MaxComment))
return
}
if strings.Count(p.Comment, "\n") >= maxLines {
q.fail(http.StatusBadRequest, fmt.Sprintf("Your comment has too many lines: at most %d.", maxLines))
return
}
// the image
var pic *picture
if fhs := q.r.MultipartForm.File["upfile"]; len(fhs) > 0 && fhs[0].Size > 0 {
fh := fhs[0]
if fh.Size > s.maxFile(b) {
q.fail(http.StatusRequestEntityTooLarge, fmt.Sprintf("That file is too large: at most %s.", humanSize(s.maxFile(b))))
return
}
if op != nil && op.Images >= b.ImageLimit {
q.fail(http.StatusForbidden, "This thread has as many images as it may: reply without one.")
return
}
in, err := fh.Open()
if err != nil {
q.fail(http.StatusBadRequest, "That file could not be read.")
return
}
data, err := io.ReadAll(io.LimitReader(in, s.maxFile(b)+1))
in.Close()
if err != nil || int64(len(data)) > s.maxFile(b) {
q.fail(http.StatusBadRequest, "That file could not be read.")
return
}
side := opThumb
if resto != 0 {
side = replyThumb
}
if pic, err = prepare(data, side, thumbBG(b), s.S.Strip); err != nil {
q.fail(http.StatusBadRequest, err.Error())
return
}
if dup, err := s.B.Store.PostByMD5(b.ID, pic.MD5); err == nil {
t := dup.Thread
if t == 0 {
t = dup.No
}
q.render(http.StatusConflict, "error.html", "Error", b, map[string]any{
"Message": "Duplicate file: it is here already.",
"Link": fmt.Sprintf("%s/%s/thread/%d#p%d", Base, b.Dir, t, dup.No), "Back": q.r.Referer()})
return
}
name := filepath.Base(strings.ReplaceAll(fh.Filename, "\\", "/"))
name = strings.TrimSuffix(name, filepath.Ext(name))
if p.FileName = field(name, 100); p.FileName == "" {
p.FileName = "image"
}
p.Ext, p.W, p.H, p.TnW, p.TnH, p.MD5 = pic.Ext, pic.W, pic.H, pic.TnW, pic.TnH, pic.MD5
p.FileSize = int64(len(pic.Data))
p.Spoiler = val("spoiler") != ""
}
switch {
case resto == 0 && pic == nil && !b.TextOnly:
q.fail(http.StatusBadRequest, "You forgot to upload your image: a thread starts with one.")
return
case pic == nil && p.Comment == "":
q.fail(http.StatusBadRequest, "You wrote nothing: a post needs a comment or an image.")
return
}
// its files first, then the post
if pic != nil {
if err := s.keepFiles(b.Dir, p, pic); err != nil {
s.B.Log.Printf("chan: /%s/: keeping an image: %v", b.Dir, err)
q.fail(http.StatusInternalServerError, "The image could not be kept: try again later.")
return
}
}
bump := !sage && (op == nil || op.Replies < b.BumpLimit)
if err := s.B.Store.AddPost(p, bump); err != nil {
s.removeFiles(b.Dir, []*store.BoardPost{p})
if errors.Is(err, store.ErrThreadGone) {
q.fail(http.StatusNotFound, "That thread is not here: it has been pruned or deleted.")
return
}
s.B.Log.Printf("chan: /%s/: posting: %v", b.Dir, err)
q.fail(http.StatusInternalServerError, "The post could not be made: try again later.")
return
}
if resto == 0 {
gone, err := s.B.Store.PruneChanThreads(b.ID, b.Pages*b.PerPage)
if err != nil {
s.B.Log.Printf("chan: /%s/: pruning: %v", b.Dir, err)
}
s.removeFiles(b.Dir, gone)
}
what := "a reply in " + strconv.FormatInt(resto, 10)
if resto == 0 {
what = "a new thread"
}
s.B.Log.Printf("chan: /%s/%d, %s, from %s", b.Dir, p.No, what, q.host())
if typed != "" && !b.ForcedAnon {
http.SetCookie(q.w, &http.Cookie{Name: nameCookie, Value: field(typed, maxName+40), Path: Base,
MaxAge: 30 * 24 * 3600, HttpOnly: true, Secure: s.Secure, SameSite: http.SameSiteLaxMode})
}
thread := resto
if thread == 0 {
thread = p.No
}
if nonoko {
q.redirect(Base + "/" + b.Dir + "/")
return
}
q.redirect(fmt.Sprintf("%s/%s/thread/%d#p%d", Base, b.Dir, thread, p.No))
}
// keepFiles writes an image and its thumbnail, naming them by the time
// in milliseconds (4chan's tim), the next free one.
func (s *Server) keepFiles(dir string, p *store.BoardPost, pic *picture) error {
for _, d := range []string{"src", "thumb"} {
if err := os.MkdirAll(filepath.Join(s.S.Dir, dir, d), 0700); err != nil {
return err
}
}
tim := time.Now().UnixMilli()
for {
f, err := os.OpenFile(s.srcPath(dir, tim, pic.Ext), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if errors.Is(err, os.ErrExist) {
tim++
continue
}
if err != nil {
return err
}
p.Tim = tim
_, err = f.Write(pic.Data)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.WriteFile(s.thumbPath(dir, tim), pic.Thumb, 0600)
}
if err != nil {
os.Remove(s.srcPath(dir, tim, pic.Ext))
}
return err
}
}
// delete deletes the posts ticked, by their password (staff need none):
// whole posts, or only their files.
func (s *Server) delete(q *req, b *store.Board) {
q.r.Body = http.MaxBytesReader(q.w, q.r.Body, 64<<10)
if err := q.r.ParseForm(); err != nil || !q.checkToken() {
q.fail(http.StatusForbidden, "That form has expired: go back, reload the page and try again.")
return
}
pw := q.r.PostForm.Get("pwd")
fileOnly := q.r.PostForm.Get("onlyimgdel") != ""
staff := q.staff(b) != ""
var nos []int64
for k, v := range q.r.PostForm {
// 4chan's form: a box named by each post's number
if n, err := strconv.ParseInt(k, 10, 64); err == nil && len(v) > 0 && v[0] == "delete" {
nos = append(nos, n)
}
}
if len(nos) == 0 {
q.fail(http.StatusBadRequest, "Tick the posts to delete first.")
return
}
if len(nos) > 50 {
nos = nos[:50]
}
var done, wrong int
for _, n := range nos {
p, err := s.B.Store.ChanPost(b.ID, n)
if err != nil {
continue
}
if !staff && (pw == "" || p.Password == "" || p.Password != s.mac("pw", pw)) {
wrong++
continue
}
if err := s.deletePost(b, p, fileOnly); err == nil {
done++
}
}
if wrong > 0 && done == 0 {
q.fail(http.StatusForbidden, "Wrong password: nothing was deleted.")
return
}
back := safeBack(q.r.PostForm.Get("back"))
if back == Base+"/" {
back = Base + "/" + b.Dir + "/"
}
q.redirect(back)
}
// deletePost deletes a post (a thread's first: the thread) or its file.
func (s *Server) deletePost(b *store.Board, p *store.BoardPost, fileOnly bool) error {
if fileOnly {
if !p.HasFile() {
return nil
}
if err := s.B.Store.DeleteChanFile(b.ID, p.No); err != nil {
return err
}
s.removeFiles(b.Dir, []*store.BoardPost{p})
s.B.Log.Printf("chan: /%s/%d: its file deleted", b.Dir, p.No)
return nil
}
gone, err := s.B.Store.DeleteChanPost(b.ID, p.No)
if err != nil {
return err
}
s.removeFiles(b.Dir, gone)
s.B.Log.Printf("chan: /%s/%d deleted (%d posts)", b.Dir, p.No, len(gone))
return nil
}
// reasons a post can be reported for.
var reportReasons = []string{"It breaks this board's rules", "It is illegal", "It is spam or advertising"}
// report has a post reported to staff.
func (s *Server) report(q *req, b *store.Board) {
q.r.Body = http.MaxBytesReader(q.w, q.r.Body, 16<<10)
no, err := strconv.ParseInt(q.r.FormValue("no"), 10, 64)
if err != nil {
q.notFound()
return
}
p, err := s.B.Store.ChanPost(b.ID, no)
if err != nil {
q.fail(http.StatusNotFound, "That post is not here: it has been deleted.")
return
}
if q.r.Method == http.MethodGet {
q.render(http.StatusOK, "report.html", "Report /"+b.Dir+"/"+strconv.FormatInt(no, 10), b,
map[string]any{"Post": p, "Reasons": reportReasons})
return
}
if !q.checkToken() {
q.fail(http.StatusForbidden, "That form has expired: go back, reload the page and try again.")
return
}
if q.checkBan(b.Dir) {
return
}
reason := q.r.PostForm.Get("reason")
ok := false
for _, r := range reportReasons {
ok = ok || r == reason
}
if !ok {
q.fail(http.StatusBadRequest, "Choose why it should be reported.")
return
}
err = s.B.Store.AddReport(&store.Report{BoardID: b.ID, No: p.No, Reason: reason, IP: q.host()})
if err != nil && !errors.Is(err, store.ErrExists) {
q.fail(http.StatusInternalServerError, "The report could not be made: try again later.")
return
}
q.render(http.StatusOK, "error.html", "Reported", b, map[string]any{"Message": "Thank you: staff will see it.",
"Done": true})
}
+15
View File
@@ -0,0 +1,15 @@
/* burichan */
body { background: #eef2ff; color: #000; font-family: serif; }
a, .backlink a, a.quotelink { color: #34345c; }
a:hover, a.quotelink:hover { color: #d00; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #b7c5d9; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #af0a0f; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #d6daf0; }
.post.reply { border-color: #b7c5d9; }
.post.reply:target, .post.reply.highlight { background: #d6bad0; }
table.postForm td:first-child, table.manage th { background: #ccaaff; border-color: #000; color: #000; }
.subject { color: #0f0c5d; }
.name, .postertrip { color: #117743; }
.quote { color: #789922; }
.sideArrows { color: #b7c5d9; }
.boardTitle { font-family: serif; letter-spacing: 0; }
+118
View File
@@ -0,0 +1,118 @@
/* the image boards' layout, every style alike: the styles set colours */
body { margin: 0; padding: 0 8px 8px; font: 10pt arial, helvetica, sans-serif; }
a { text-decoration: none; }
a:hover { text-decoration: underline; }
hr { border: none; border-top: 1px solid; clear: both; height: 0; margin: 4px 0; }
img { border: none; }
form.inline { display: inline; margin: 0; }
button.linkish { background: none; border: none; padding: 0; font: inherit; color: inherit; cursor: pointer; text-decoration: underline; }
.boardNav { font-size: 9pt; padding: 3px 0; overflow: hidden; }
.boardNav .navRight { float: right; }
.boardNav select, .boardNav button { font-size: 8pt; }
.js .styleSwitch .go { display: none; }
.notice { text-align: center; font-weight: bold; padding: 4px; }
.boardBanner { text-align: center; clear: both; margin: 8px 0 4px; }
.boardTitle { font-family: Tahoma, sans-serif; font-size: 28px; font-weight: bold; letter-spacing: -2px; margin-top: 0; }
.boardSubtitle { font-size: 10px; margin-top: 2px; }
.postingMode { text-align: center; font-weight: bold; font-size: 16px; padding: 3px; margin: 4px 0; }
.navLinks { font-size: 9pt; margin: 4px 0; }
.navLinks .sortBy { float: right; }
form.postForm { margin: 0 auto; width: max-content; max-width: 100%; }
table.postForm { border-spacing: 1px; margin: 0 auto; }
table.postForm td:first-child { font-weight: bold; padding: 0 5px; font-size: 10pt; border: 1px solid; }
table.postForm input[type=text], table.postForm input[type=password], table.postForm textarea { width: 290px; box-sizing: border-box; font-size: 10pt; margin: 0; }
table.postForm input[name=sub] { width: 220px; }
table.postForm textarea { height: 6em; resize: both; }
table.postForm tr.rules td { border: none; padding: 0; font-weight: normal; background: none; color: inherit; }
ul.rules { margin: 4px 0 0; padding-left: 16px; font-size: 8pt; max-width: 420px; }
.passNotice { font-size: 8pt; }
.closedNotice { text-align: center; font-size: 14pt; font-weight: bold; margin: 8px 0; }
.thread { clear: both; overflow: hidden; margin: 4px 0; }
.postContainer { margin: 4px 0; }
.replyContainer { display: table; }
.sideArrows { display: table-cell; padding-right: 2px; vertical-align: top; }
.post.reply { display: table-cell; padding: 2px 4px 4px; border: 1px solid; border-left: none; border-top: none; }
.post.op { overflow: visible; }
.postInfo { display: block; }
.postInfo input[type=checkbox] { margin: 0 2px 0 0; vertical-align: middle; }
.subject { font-weight: bold; }
.name { font-weight: bold; }
.postertrip { font-weight: normal; }
.capcode { font-weight: bold; }
.capcode-admin .name, .capcode-admin .capcode { color: #f00 !important; }
.capcode-mod .name, .capcode-mod .capcode { color: #800080 !important; }
.postNum a { color: inherit; }
.badge { font-size: 8pt; border: 1px solid; padding: 0 3px; border-radius: 3px; }
.reportLink, .modLink { font-size: 8pt; margin-left: 4px; }
.backlink { font-size: 8pt; display: inline; }
.backlink a { margin-left: 2px; }
.file { margin: 2px 0 2px 0; }
.fileText { font-size: 8pt; margin-left: 2px; }
.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; }
.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; }
.quote { }
.deadlink { text-decoration: line-through; }
s { background: #000; color: #000; text-decoration: none; }
s:hover, s:focus { color: #fff; }
s a { color: inherit; }
pre.code { white-space: pre-wrap; font-family: monospace; font-size: 9pt; padding: 5px; border: 1px solid; max-width: 800px; overflow-x: auto; }
.banMessage { color: #f00; }
.abbr { font-size: 9pt; }
.summary { display: block; margin: 0 0 4px 30px; font-size: 9pt; }
.threadStats { text-align: right; font-size: 9pt; }
.warning { color: #d00; }
form.deleteForm { float: right; text-align: right; font-size: 9pt; margin: 8px 0; }
form.deleteForm input[type=password] { width: 100px; }
.pagelist { clear: both; display: inline-block; padding: 4px 8px; margin: 8px 0; border: 1px solid; font-size: 10pt; }
.pagelist .pageButton { margin: 0 6px; }
.pagelist strong { font-weight: bold; }
.empty { text-align: center; }
.footer { clear: both; text-align: center; font-size: 9pt; margin-top: 16px; }
.footer .credit { margin-top: 6px; font-size: 8pt; }
/* the front page */
.frontTitle { text-align: center; margin: 16px 0; }
.frontTitle h1 { font-family: Tahoma, sans-serif; letter-spacing: -1px; margin: 0; }
.box { border: 1px solid; margin: 12px auto; max-width: 800px; padding: 0 0 8px; }
.box h2 { margin: 0; padding: 3px 8px; font-size: 11pt; }
.box > p, .box > form, .box > table, .box > ul, .box > div, .box > h3 { margin-left: 10px; margin-right: 10px; }
.box.narrow { max-width: 420px; }
.box.wide { max-width: 1000px; }
ul.boards { list-style: none; padding: 0; columns: 2; }
ul.boards li { margin: 4px 0; break-inside: avoid; }
ul.boards .desc { font-size: 8pt; }
.nws { font-size: 8pt; color: #d00; }
.recent { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; align-items: center; padding-top: 8px; }
/* the catalog */
.catalog { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px; }
.catThread { width: 165px; text-align: center; overflow: hidden; padding: 4px 2px; font-size: 9pt; max-height: 320px; }
.catThread .thumb { box-shadow: 0 0 5px rgba(0, 0, 0, 0.25); }
.catThread .noFile { display: inline-block; width: 100px; padding: 40px 0; border: 1px dashed; font-size: 8pt; }
.catThread .meta { font-size: 8pt; margin: 2px 0; }
.catThread .teaser { overflow-wrap: anywhere; }
/* staff */
table.manage { border-collapse: collapse; width: calc(100% - 20px); font-size: 9pt; }
table.manage td, table.manage th { border: 1px solid; padding: 2px 4px; text-align: left; vertical-align: top; }
td.excerpt { max-width: 400px; overflow-wrap: anywhere; }
.actions form { margin-right: 6px; }
.errorBox { text-align: center; margin: 24px 0; }
.errorBox h2.error { color: #f00; }
.banned { max-width: 600px; }
.banned h2 { color: #d00; }
.bannedPost blockquote { border-left: 2px solid; padding-left: 8px; white-space: pre-wrap; }
label.reason { display: block; margin: 4px 0; }
/* hovering a quote */
#quotePreview { position: absolute; z-index: 10; max-width: 70vw; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35); }
#quotePreview .post { display: block; border: 1px solid; }
@media (max-width: 640px) {
.boardNav .navRight { float: none; display: block; }
table.postForm input[type=text], table.postForm input[type=password], table.postForm textarea { width: 100%; }
blockquote.postMessage { margin: 8px 10px; }
.fileThumb { margin: 3px 8px 5px; }
.post.op > .file .fileThumb { float: none; display: inline-block; }
table.postForm input[name=sub] { width: calc(100% - 60px); }
form.deleteForm { float: none; }
ul.boards { columns: 1; }
}
+86
View File
@@ -0,0 +1,86 @@
// The image boards work without this; with it, as 4chan's do: a post's
// number quotes it in the reply form, a thumbnail opens the image in
// place, a quote shows the post it quotes when hovered, and choosing a
// style needs no button.
(function () {
"use strict";
document.documentElement.classList.add("js");
document.addEventListener("click", function (e) {
var a = e.target.closest ? e.target.closest("a") : null;
if (!a) return;
// No.123: quote it in this page's form (one for this thread)
if (a.classList.contains("quotePost")) {
var com = document.getElementById("com");
var form = document.getElementById("postForm");
var resto = form && form.querySelector("input[name=resto]");
var thread = a.closest(".thread");
var here = thread && resto && ("t" + resto.value) === thread.id;
if (!com || !here) return;
e.preventDefault();
var text = ">>" + a.dataset.no + "\n";
var start = com.selectionStart || 0, end = com.selectionEnd || 0;
com.value = com.value.slice(0, start) + text + com.value.slice(end);
com.selectionStart = com.selectionEnd = start + text.length;
com.focus();
return;
}
// a thumbnail: the image itself, and back
if (a.classList.contains("fileThumb") && !e.ctrlKey && !e.metaKey && !e.shiftKey && e.button === 0) {
var img = a.querySelector("img");
if (!img) return;
e.preventDefault();
if (img.classList.contains("expanded")) {
img.src = img.dataset.thumb;
img.width = +img.dataset.w;
img.height = +img.dataset.h;
img.classList.remove("expanded");
} else {
img.dataset.thumb = img.getAttribute("src");
img.dataset.w = img.width;
img.dataset.h = img.height;
img.removeAttribute("width");
img.removeAttribute("height");
img.classList.add("expanded");
img.src = a.href;
}
}
});
// hovering >>123: the post, if it is on this page
var preview = null;
function hide() {
if (preview) { preview.remove(); preview = null; }
document.querySelectorAll(".post.highlight").forEach(function (p) { p.classList.remove("highlight"); });
}
document.addEventListener("mouseover", function (e) {
var a = e.target.closest ? e.target.closest("a.quotelink") : null;
if (!a || !a.dataset.no) return;
var post = document.getElementById("p" + a.dataset.no);
if (!post) return;
var r = post.getBoundingClientRect();
if (r.top >= 0 && r.bottom <= window.innerHeight) { // in sight: show where it is
post.classList.add("highlight");
return;
}
preview = document.createElement("div");
preview.id = "quotePreview";
var copy = post.cloneNode(true);
copy.removeAttribute("id");
copy.classList.add("reply");
preview.appendChild(copy);
document.body.appendChild(preview);
var ar = a.getBoundingClientRect();
preview.style.left = Math.max(4, Math.min(ar.right + 8, window.innerWidth - preview.offsetWidth - 8)) + window.scrollX + "px";
preview.style.top = Math.max(4, ar.top - preview.offsetHeight / 2) + window.scrollY + "px";
});
document.addEventListener("mouseout", function (e) {
var a = e.target.closest ? e.target.closest("a.quotelink") : null;
if (a) hide();
});
// the style: chosen as it is picked
document.querySelectorAll(".styleSwitch select").forEach(function (sel) {
sel.addEventListener("change", function () { sel.form.submit(); });
});
})();
+15
View File
@@ -0,0 +1,15 @@
/* futaba */
body { background: #ffe; color: #800000; font-family: serif; }
a, .backlink a, a.quotelink { color: #0000ee; }
a:hover, a.quotelink:hover { color: #d00; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #d9bfb7; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #800000; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #f0e0d6; }
.post.reply { border-color: #d9bfb7; }
.post.reply:target, .post.reply.highlight { background: #f0c0b0; }
table.postForm td:first-child, table.manage th { background: #ea8; border-color: #800; color: #000; }
.subject { color: #cc1105; }
.name, .postertrip { color: #117743; }
.quote { color: #789922; }
.sideArrows { color: #d9bfb7; }
.boardTitle { font-family: serif; letter-spacing: 0; }
+15
View File
@@ -0,0 +1,15 @@
/* photon */
body { background: #eee; color: #333; font-family: verdana, sans-serif; }
a, .backlink a, a.quotelink { color: #f60; }
a:hover, a.quotelink:hover { color: #c30; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #ccc; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #024; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #ddd; }
.post.reply { border-color: #ccc; }
.post.reply:target, .post.reply.highlight { background: #ccc; }
table.postForm td:first-child, table.manage th { background: #bbb; border-color: #ccc; color: #000; }
.subject { color: #024; }
.name, .postertrip { color: #004a99; }
.quote { color: #789922; }
.sideArrows { color: #ccc; }
.boardTitle { letter-spacing: 0; font-family: verdana, sans-serif; }
+19
View File
@@ -0,0 +1,19 @@
/* tomorrow */
body { background: #1d1f21; color: #c5c8c6; }
a, .backlink a, a.quotelink { color: #81a2be; }
a:hover, a.quotelink:hover { color: #5f89ac; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #282a2e; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #c5c8c6; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #282a2e; }
.post.reply { border-color: #282a2e; }
.post.reply:target, .post.reply.highlight { background: #1d1d21; }
table.postForm td:first-child, table.manage th { background: #282a2e; border-color: #111; color: #c5c8c6; }
.subject { color: #b294bb; }
.name, .postertrip { color: #c5c8c6; }
.quote { color: #b5bd68; }
.sideArrows { color: #282a2e; }
table.postForm td:first-child, table.manage th { color: #c5c8c6; }
.post.reply:target, .post.reply.highlight { border-color: #111; }
s:hover, s:focus { color: #fff; }
input, textarea, select, button { background: #282a2e; color: #c5c8c6; border: 1px solid #111; }
.pagelist, .box h2 { color: #c5c8c6; }
+15
View File
@@ -0,0 +1,15 @@
/* yotsuba-b */
body { background: #eef2ff; color: #000; }
a, .backlink a, a.quotelink { color: #34345c; }
a:hover, a.quotelink:hover { color: #d00; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #b7c5d9; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #af0a0f; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #d6daf0; }
.post.reply { border-color: #b7c5d9; }
.post.reply:target, .post.reply.highlight { background: #d6bad0; }
table.postForm td:first-child, table.manage th { background: #9988ee; border-color: #000; color: #000; }
.subject { color: #0f0c5d; }
.name, .postertrip { color: #117743; }
.quote { color: #789922; }
.sideArrows { color: #b7c5d9; }
body { background: linear-gradient(#d1d5ee, #eef2ff 200px) no-repeat, #eef2ff; }
+15
View File
@@ -0,0 +1,15 @@
/* yotsuba */
body { background: #ffe; color: #800000; }
a, .backlink a, a.quotelink { color: #0000ee; }
a:hover, a.quotelink:hover { color: #f00; }
hr, table.manage td, table.manage th, .box, .pagelist, pre.code, .badge, .fileDeleted, .catThread .noFile, #quotePreview .post { border-color: #d9bfb7; }
.boardTitle, .frontTitle h1, .postingMode, .closedNotice { color: #af0a0f; }
.post.reply, #quotePreview .post, .pagelist, .box h2, .catThread:hover { background: #f0e0d6; }
.post.reply { border-color: #d9bfb7; }
.post.reply:target, .post.reply.highlight { background: #f0c0b0; }
table.postForm td:first-child, table.manage th { background: #ea8; border-color: #800; color: #000; }
.subject { color: #cc1105; }
.name, .postertrip { color: #117743; }
.quote { color: #789922; }
.sideArrows { color: #d9bfb7; }
body { background: linear-gradient(#fed6af, #ffe 200px) no-repeat, #ffe; }
+11
View File
@@ -0,0 +1,11 @@
{{define "banned.html"}}{{template "top" .}}
<hr>
{{with .Body}}<div class="box banned">
<h2>You are banned! ;_;</h2>
<p>You have been banned from {{if .Ban.Board}}/{{.Ban.Board}}/{{else}}all boards{{end}} for this reason:</p>
<p class="reason"><b>{{if .Ban.Reason}}{{.Ban.Reason}}{{else}}No reason was given.{{end}}</b></p>
<p>Your ban was filed on <b>{{date .Ban.Created}}</b> and {{if .Ban.Expires.IsZero}}<b>will not expire</b>{{else}}expires on <b>{{date .Ban.Expires}}</b>{{end}}.</p>
<p>The address you were banned at is <b>{{.IP}}</b>.</p>
{{with .Ban.Post}}<div class="bannedPost"><p>What you posted:</p><blockquote>{{.}}</blockquote></div>{{end}}
</div>{{end}}
{{template "bottom" .}}{{end}}
+21
View File
@@ -0,0 +1,21 @@
{{define "bans.html"}}{{template "top" .}}
<div class="boardBanner"><div class="boardTitle">Manage</div><div class="boardSubtitle">[<a href="/chan/manage">Reports</a>] [<strong>Bans</strong>]</div></div>
<hr>
{{with .Body}}<div class="box wide"><h2>Bans</h2>
{{if .Bans}}<table class="manage"><thead><tr><th>Address</th><th>Board</th><th>Reason</th><th>By</th><th>Filed</th><th>Expires</th><th></th></tr></thead><tbody>
{{range .Bans}}<tr><td>{{.IP}}</td><td>{{if .Board}}/{{.Board}}/{{else}}all{{end}}</td><td>{{.Reason}}</td><td>{{.By}}</td><td>{{date .Created}}</td><td>{{if .Expires.IsZero}}never{{else}}{{date .Expires}}{{end}}</td>
<td>{{if .CanLift}}<form method="post" action="/chan/manage/bans" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><button name="lift" value="{{.ID}}">Lift</button></form>{{end}}</td></tr>{{end}}
</tbody></table>{{else}}<p>No one is banned.</p>{{end}}
<h3>Ban an address</h3>
<form method="post" action="/chan/manage/bans">
<input type="hidden" name="tok" value="{{$.Token}}">
<table class="postForm"><tbody>
<tr><td>Address</td><td><input name="ip" type="text" required placeholder="192.0.2.7, or 192.0.2. for a range"></td></tr>
<tr><td>Board</td><td><select name="board">{{if .Admin}}<option value="">every board</option>{{end}}{{range .Mine}}<option value="{{.}}">/{{.}}/</option>{{end}}</select></td></tr>
<tr><td>Reason</td><td><input name="reason" type="text" maxlength="200" size="40"></td></tr>
<tr><td>Days</td><td><input name="days" type="number" min="0" max="3650" value="3"> (0: for ever)</td></tr>
<tr><td></td><td><button type="submit">Ban</button></td></tr>
</tbody></table>
</form>
</div>{{end}}
{{template "bottom" .}}{{end}}
+60
View File
@@ -0,0 +1,60 @@
{{define "board.html"}}{{template "top" .}}
{{template "banner" .}}
<hr class="abovePostForm">
{{$b := .Board}}{{with .Body}}
{{if .Thread}}<div class="postingMode">Posting mode: Reply</div>
<div class="navLinks">[<a href="/chan/{{$b.Dir}}/">Return</a>] [<a href="/chan/{{$b.Dir}}/catalog">Catalog</a>] [<a href="#bottom">Bottom</a>]</div>{{end}}
{{template "form" $}}
<hr>
{{if not .Thread}}<div class="navLinks">[<a href="/chan/{{$b.Dir}}/catalog">Catalog</a>]</div><hr>{{end}}
<div class="board">
{{range .Threads}}<div class="thread" id="t{{.OP.No}}">
{{template "post" .OP}}
{{if gt .OmittedPosts 0}}<span class="summary">{{.OmittedPosts}} {{if eq .OmittedPosts 1}}reply{{else}}replies{{end}}{{if gt .OmittedImages 0}} and {{.OmittedImages}} {{if eq .OmittedImages 1}}image{{else}}images{{end}}{{end}} omitted. <a href="/chan/{{$b.Dir}}/thread/{{.OP.No}}" class="replylink">Click here</a> to view.</span>{{end}}
{{range .Replies}}{{template "post" .}}{{end}}
</div>
<hr>
{{else}}<p class="empty">There are no threads here yet: start one.</p><hr>{{end}}
</div>
{{with .Thread}}<div class="threadStats">{{.OP.Replies}} {{if eq .OP.Replies 1}}reply{{else}}replies{{end}} / {{.OP.Images}} {{if eq .OP.Images 1}}image{{else}}images{{end}}{{if .BumpLimit}} &middot; <span class="warning">Bump limit reached.</span>{{end}}{{if .ImageLimit}} &middot; <span class="warning">Image limit reached.</span>{{end}}</div>
<div class="navLinks">[<a href="/chan/{{$b.Dir}}/">Return</a>] [<a href="/chan/{{$b.Dir}}/catalog">Catalog</a>] [<a href="#top">Top</a>]</div>{{end}}
<form id="delform" class="deleteForm" method="post" action="/chan/{{$b.Dir}}/delete">
<input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="back" value="{{$.Path}}">
Delete Post: <label>[<input type="checkbox" name="onlyimgdel" value="on"> File Only]</label>
Password <input type="password" name="pwd" value="{{$.Pass}}" maxlength="64" autocomplete="off">
<button type="submit">Delete</button>
</form>
{{if not .Thread}}<div class="pagelist">
{{if gt .Page 1}}<a class="pageButton" href="/chan/{{$b.Dir}}/{{if gt .Page 2}}{{add .Page -1}}{{end}}">Previous</a>{{else}}<span class="pageButton">Previous</span>{{end}}
<span class="pages">{{range seq .Pages}}[{{if eq . $.Body.Page}}<strong>{{.}}</strong>{{else}}<a href="/chan/{{$b.Dir}}/{{if gt . 1}}{{.}}{{end}}">{{.}}</a>{{end}}] {{end}}</span>
{{if lt .Page .Pages}}<a class="pageButton" href="/chan/{{$b.Dir}}/{{add .Page 1}}">Next</a>{{else}}<span class="pageButton">Next</span>{{end}}
<span class="pages">[<a href="/chan/{{$b.Dir}}/catalog">Catalog</a>]</span>
</div>{{end}}
{{end}}
<div id="bottom"></div>
{{template "bottom" .}}{{end}}
{{define "form"}}{{$b := .Board}}{{with .Body.Form}}
{{if .CanPost}}<form id="postForm" class="postForm" method="post" action="/chan/{{$b.Dir}}/post" enctype="multipart/form-data">
<input type="hidden" name="tok" value="{{$.Token}}">
{{with .Reply}}<input type="hidden" name="resto" value="{{.No}}">{{end}}
<table class="postForm"><tbody>
{{if not $b.ForcedAnon}}<tr><td>Name</td><td><input name="name" type="text" maxlength="115" placeholder="{{$b.DefaultName}}" value="{{.Name}}" autocomplete="off"></td></tr>{{end}}
<tr><td>Options</td><td><input name="email" type="text" maxlength="75" placeholder="sage, nonoko"></td></tr>
<tr><td>Subject</td><td><input name="sub" type="text" maxlength="100"> <button type="submit">{{if .Reply}}Post{{else}}New Thread{{end}}</button></td></tr>
<tr><td>Comment</td><td><textarea name="com" id="com" cols="48" rows="4">{{.Quote}}</textarea></td></tr>
<tr><td>File</td><td><input type="file" name="upfile" accept="image/jpeg,image/png,image/gif,image/webp"{{if .Image}} required{{end}}> <label class="spoilerBox"><input type="checkbox" name="spoiler" value="on"> Spoiler?</label></td></tr>
<tr><td>Password</td><td><input type="password" name="pwd" maxlength="64" value="{{$.Pass}}" autocomplete="off"> <span class="passNotice">(for deleting the post)</span></td></tr>
{{with .Capcode}}<tr><td>Staff</td><td><label><input type="checkbox" name="capcode" value="on"> Post as ## {{if eq . "admin"}}Admin{{else}}Mod{{end}}</label></td></tr>{{end}}
<tr class="rules"><td colspan="2"><ul class="rules">
<li>Supported file types are JPG, PNG, GIF and WebP{{if .Image}}; a thread starts with one{{end}}.</li>
<li>Maximum file size allowed is {{size .MaxFile}}. Images greater than {{if .Reply}}125x125{{else}}250x250{{end}} are thumbnailed.</li>
<li>Name#password signs a post with a tripcode; Name##password with a secure one. "sage" does not bump the thread.</li>
<li>&gt;greentext, &gt;&gt;123 quotes a post, &gt;&gt;&gt;/{{$b.Dir}}/ links a board; [spoiler]hides text[/spoiler]; [code]code[/code].</li>
</ul></td></tr>
</tbody></table>
</form>
{{else if .Closed}}<div class="closedNotice">Thread closed.<br>You may not reply at this time.</div>
{{else if .NeedLogin}}<div class="closedNotice">Only this BBS's users post here: <a href="/chan/login?back={{$.Path}}">sign in</a> first.</div>
{{else}}<div class="closedNotice">This board is locked: only staff post here.</div>{{end}}
{{end}}{{end}}
@@ -0,0 +1,18 @@
{{define "catalog.html"}}{{template "top" .}}
{{template "banner" .}}
<hr>
{{$b := .Board}}{{with .Body}}
<div class="navLinks">[<a href="/chan/{{$b.Dir}}/">Return</a>] [<a href="/chan/{{$b.Dir}}/#postForm">Start a New Thread</a>]
<span class="sortBy">Sort by: {{if .New}}<a href="/chan/{{$b.Dir}}/catalog">Bump order</a> &middot; <strong>Creation date</strong>{{else}}<strong>Bump order</strong> &middot; <a href="/chan/{{$b.Dir}}/catalog?order=new">Creation date</a>{{end}}</span></div>
<hr>
<div class="catalog">
{{range .Threads}}<div class="catThread" id="thread-{{.OP.No}}">
<a href="/chan/{{$b.Dir}}/thread/{{.OP.No}}">{{if .OP.ThumbURL}}{{if .OP.Spoiler}}<img src="/chan/static/spoiler.png" alt="Spoiler Image" width="100" height="100" class="thumb">{{else}}<img src="{{.OP.ThumbURL}}" alt="" width="{{.OP.TnW}}" height="{{.OP.TnH}}" class="thumb" loading="lazy">{{end}}{{else}}<span class="noFile">{{if .OP.FileDeleted}}File deleted{{else}}No image{{end}}</span>{{end}}</a>
<div class="meta" title="(R)eplies / (I)mages">R: <b>{{.OP.Replies}}</b> / I: <b>{{.OP.Images}}</b>{{if .OP.Sticky}} &middot; <span class="badge sticky">Sticky</span>{{end}}{{if .OP.Closed}} &middot; <span class="badge closed">Closed</span>{{end}}</div>
<div class="teaser">{{with .OP.Subject}}<b>{{.}}</b>: {{end}}{{.Teaser}}</div>
</div>
{{else}}<p class="empty">There are no threads here yet.</p>{{end}}
</div>
<hr>
{{end}}
{{template "bottom" .}}{{end}}
+10
View File
@@ -0,0 +1,10 @@
{{define "error.html"}}{{template "top" .}}
{{template "banner" .}}
<hr>
{{with .Body}}<div class="errorBox">
<h2 class="{{if .Done}}done{{else}}error{{end}}">{{if .Done}}{{.Message}}{{else}}Error: {{.Message}}{{end}}</h2>
{{with .Link}}<p><a href="{{.}}">See it there.</a></p>{{end}}
<p>[<a href="{{if .Back}}{{.Back}}{{else}}/chan/{{end}}">Return</a>]</p>
</div>{{end}}
<hr>
{{template "bottom" .}}{{end}}
+15
View File
@@ -0,0 +1,15 @@
{{define "front.html"}}{{template "top" .}}
<div class="frontTitle"><h1>{{.BBS}}</h1><p>Image boards: post a picture, talk about it. No account needed.</p></div>
{{with .Body}}
<div class="box"><h2>Boards</h2>
{{if .Boards}}<ul class="boards">{{range .Boards}}<li><a href="/chan/{{.Dir}}/" class="boardlink">/{{.Dir}}/ - {{.Title}}</a>{{if not .Worksafe}} <span class="nws" title="Not safe for work">(NSFW)</span>{{end}}{{with .Description}}<div class="desc">{{.}}</div>{{end}}</li>{{end}}</ul>
{{else}}<p>There are no boards yet. The sysop makes them: <code>bbs chan board add b Random</code></p>{{end}}
</div>
{{with .Recent}}<div class="box"><h2>Recent Images</h2>
<div class="recent">{{range .}}<a href="{{.URL}}" title="/{{.Dir}}/ - {{.Title}}"><img src="{{.Thumb}}" alt="" width="{{.TnW}}" height="{{.TnH}}" loading="lazy"></a>{{end}}</div>
</div>{{end}}
<div class="box"><h2>Stats</h2>
<p>Total posts: <b>{{.Posts}}</b> &middot; Active content: <b>{{size .Bytes}}</b></p>
</div>
{{end}}
{{template "bottom" .}}{{end}}
+62
View File
@@ -0,0 +1,62 @@
{{define "top"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<link rel="stylesheet" href="/chan/static/chan.css">
<link rel="stylesheet" href="/chan/static/{{.Style}}.css" id="stylesheet">
<script src="/chan/static/chan.js" defer></script>
</head>
<body class="{{.Style}}{{with .Board}} board-{{.Dir}}{{end}}">
<div class="boardNav">
<span class="boardList">[{{range $i, $b := .Boards}}{{if $i}} / {{end}}<a href="/chan/{{$b.Dir}}/" title="{{$b.Title}}">{{$b.Dir}}</a>{{end}}]</span>
<span class="navRight">
[<a href="/chan/">Home</a>]
{{if .User}}[{{.User.Name}}{{if .AnyStaff}} &middot; <a href="/chan/manage">Manage</a>{{end}} &middot; <form class="inline" method="post" action="/chan/logout"><input type="hidden" name="tok" value="{{.Token}}"><button class="linkish">Sign out</button></form>]
{{else}}[<a href="/chan/login?back={{.Path}}">Sign in</a>]{{end}}
<form class="inline styleSwitch" method="post" action="/chan/style"><input type="hidden" name="back" value="{{.Path}}">
<label>Style: <select name="style">{{range .Styles}}<option value="{{.Name}}"{{if eq .Name $.Style}} selected{{end}}>{{.Title}}</option>{{end}}</select></label>
<button class="go">Go</button></form>
</span>
</div>
{{with .Notice}}<div class="notice">{{.}}</div>{{end}}
{{end}}
{{define "bottom"}}
<div class="footer">
<div class="boardList">[{{range $i, $b := .Boards}}{{if $i}} / {{end}}<a href="/chan/{{$b.Dir}}/" title="{{$b.Title}}">{{$b.Dir}}</a>{{end}}]</div>
<div class="credit">{{.BBS}} &middot; image boards after kusaba&nbsp;x and 4chan &middot; all posts are the responsibility of their posters</div>
</div>
</body>
</html>
{{end}}
{{define "banner"}}{{with .Board}}<div class="boardBanner">
<div class="boardTitle">/{{.Dir}}/ - {{.Title}}</div>
{{with .Description}}<div class="boardSubtitle">{{.}}</div>{{end}}
</div>{{end}}{{end}}
{{define "file"}}<div class="file" id="f{{.No}}">
{{if .FileDeleted}}<span class="fileDeleted">File deleted.</span>
{{else}}<div class="fileText">File: <a href="{{.SrcURL}}" target="_blank" title="{{.FileName}}{{.Ext}}">{{short (print .FileName .Ext)}}</a> ({{if .Spoiler}}Spoiler Image, {{end}}{{size .FileSize}}, {{.W}}x{{.H}})</div>
<a class="fileThumb{{if .Spoiler}} imgspoiler{{end}}" href="{{.SrcURL}}" target="_blank">{{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}}">
{{if not .OP}}<div class="sideArrows">&gt;&gt;</div>{{end}}
<div id="p{{.No}}" class="post {{if .OP}}op{{else}}reply{{end}}">
{{if and .OP .Ext}}{{template "file" .}}{{end}}
<div class="postInfo" id="pi{{.No}}">
<input type="checkbox" name="{{.No}}" value="delete" form="delform" aria-label="Choose post {{.No}}">
{{with .Subject}}<span class="subject">{{.}}</span>{{end}}
<span class="nameBlock{{with .Capcode}} capcode-{{.}}{{end}}">{{if .Email}}<a href="mailto:{{.Email}}" class="useremail">{{end}}<span class="name">{{.Name}}</span>{{with .Trip}} <span class="postertrip">{{.}}</span>{{end}}{{if .Email}}</a>{{end}}{{with .Capcode}} <strong class="capcode">## {{if eq . "admin"}}Admin{{else}}Mod{{end}}</strong>{{end}}</span>
<span class="dateTime" title="{{iso .Created}}">{{date .Created}}</span>
<span class="postNum"><a href="/chan/{{.Dir}}/thread/{{.Thread}}#p{{.No}}" title="Link to this post">No.</a><a href="/chan/{{.Dir}}/thread/{{.Thread}}?quote={{.No}}#postForm" class="quotePost" data-no="{{.No}}" title="Reply to this post">{{.No}}</a>{{if .Sticky}} <span class="badge sticky" title="Sticky">Sticky</span>{{end}}{{if .Closed}} <span class="badge closed" title="Closed">Closed</span>{{end}}{{if and .OP .Index}} &nbsp; <span>[<a href="/chan/{{.Dir}}/thread/{{.No}}" class="replylink">Reply</a>]</span>{{end}}</span>
<a class="reportLink" href="/chan/{{.Dir}}/report?no={{.No}}" title="Report this post" rel="nofollow">&#9656;</a>{{if .Staff}} <a class="modLink" href="/chan/manage/post?b={{.Dir}}&amp;no={{.No}}" title="Moderate">[M]</a>{{end}}
{{with .Backlinks}}<div class="backlink">{{range .}}<span><a href="#p{{.}}" class="quotelink" data-no="{{.}}">&gt;&gt;{{.}}</a></span> {{end}}</div>{{end}}
</div>
{{if and (not .OP) .Ext}}{{template "file" .}}{{end}}
<blockquote class="postMessage" id="m{{.No}}">{{.Comment}}{{if .Cut}}<span class="abbr"><br>Comment too long. <a href="/chan/{{.Dir}}/thread/{{.Thread}}#p{{.No}}">Click here</a> to view the full text.</span>{{end}}{{if .Banned}}<br><br><strong class="banMessage">(USER WAS BANNED FOR THIS POST)</strong>{{end}}</blockquote>
</div>
</div>{{end}}
+14
View File
@@ -0,0 +1,14 @@
{{define "login.html"}}{{template "top" .}}
<hr>
{{with .Body}}<div class="box narrow"><h2>Sign in</h2>
<p>With your account on this BBS: staff sign in to moderate.</p>
{{with .Error}}<p class="error">{{.}}</p>{{end}}
<form method="post" action="/chan/login">
<input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="back" value="{{.Back}}">
<table class="postForm"><tbody>
<tr><td>Name</td><td><input name="name" type="text" autocomplete="username" required></td></tr>
<tr><td>Password</td><td><input name="password" type="password" autocomplete="current-password" required></td></tr>
<tr><td></td><td><button type="submit">Sign in</button></td></tr>
</tbody></table>
</form></div>{{end}}
{{template "bottom" .}}{{end}}
@@ -0,0 +1,9 @@
{{define "manage.html"}}{{template "top" .}}
<div class="boardBanner"><div class="boardTitle">Manage</div><div class="boardSubtitle">[<strong>Reports</strong>] [<a href="/chan/manage/bans">Bans</a>]</div></div>
<hr>
{{with .Body}}<div class="box wide"><h2>Reports</h2>
{{if .Reports}}<table class="manage"><thead><tr><th>Post</th><th>Reason</th><th>Reports</th><th>When</th><th>Comment</th></tr></thead><tbody>
{{range .Reports}}<tr><td><a href="/chan/manage/post?b={{.Dir}}&amp;no={{.No}}">/{{.Dir}}/{{.No}}</a></td><td>{{.Reason}}</td><td>{{.Count}}</td><td>{{date .Created}}</td><td class="excerpt">{{short .Post.Comment}}</td></tr>{{end}}
</tbody></table>{{else}}<p>Nothing is reported.</p>{{end}}
</div>{{end}}
{{template "bottom" .}}{{end}}
@@ -0,0 +1,29 @@
{{define "modpost.html"}}{{template "top" .}}
<div class="boardBanner"><div class="boardTitle">Manage /{{.Board.Dir}}/{{.Body.Post.No}}</div><div class="boardSubtitle">[<a href="/chan/manage">Reports</a>] [<a href="/chan/manage/bans">Bans</a>] [<a href="/chan/{{.Board.Dir}}/thread/{{.Body.Post.Thread}}#p{{.Body.Post.No}}">In its thread</a>]</div></div>
<hr>
{{$b := .Board}}{{with .Body}}
<div class="thread">{{template "post" .Post}}</div>
<div class="box wide">
<p>Posted from <b>{{.Post.IP}}</b>{{if .Post.UserID}} by a signed-in user{{end}}. Its posts: {{len .ByIP}}{{if ge (len .ByIP) 50}} or more{{end}}.</p>
<div class="actions">
<form method="post" action="/chan/manage/post" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.Post.No}}"><button name="action" value="delete">Delete {{if .Post.OP}}thread{{else}}post{{end}}</button></form>
{{if .Post.HasFile}}<form method="post" action="/chan/manage/post" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.Post.No}}"><button name="action" value="deletefile">Delete file</button></form>{{end}}
{{with .Thread}}<form method="post" action="/chan/manage/post" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.No}}">{{if .Sticky}}<button name="action" value="unsticky">Unsticky</button>{{else}}<button name="action" value="sticky">Sticky</button>{{end}} {{if .Closed}}<button name="action" value="open">Open</button>{{else}}<button name="action" value="close">Close</button>{{end}}</form>{{end}}
<form method="post" action="/chan/manage/post" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.Post.No}}"><button name="action" value="dismiss">Dismiss reports</button></form>
<form method="post" action="/chan/manage/post" class="inline"><input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.Post.No}}"><button name="action" value="purge">Delete all its posts on /{{$b.Dir}}/</button></form>
</div>
<h3>Ban</h3>
<form method="post" action="/chan/manage/post">
<input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="b" value="{{$b.Dir}}"><input type="hidden" name="no" value="{{.Post.No}}"><input type="hidden" name="action" value="ban">
<table class="postForm"><tbody>
<tr><td>Reason</td><td><input name="reason" type="text" maxlength="200" size="40"></td></tr>
<tr><td>Days</td><td><input name="days" type="number" min="0" max="3650" value="3"> (0: for ever)</td></tr>
<tr><td>Who</td><td><label><input type="checkbox" name="range" value="on"> its range ({{.Range}}*)</label>{{if eq $.Staff "admin"}} <label><input type="checkbox" name="everywhere" value="on"> on every board</label>{{end}}</td></tr>
<tr><td>And</td><td><label><input type="checkbox" name="public" value="on"> say so under the post</label> <label><input type="checkbox" name="delete" value="on"> delete the post</label></td></tr>
<tr><td></td><td><button type="submit">Ban</button></td></tr>
</tbody></table>
</form>
{{with .ByIP}}<h3>Its latest posts</h3><table class="manage"><tbody>{{range .}}<tr><td>{{date .Created}}</td><td>No.{{.No}}</td><td class="excerpt">{{short .Comment}}</td></tr>{{end}}</tbody></table>{{end}}
</div>
{{end}}
{{template "bottom" .}}{{end}}
+10
View File
@@ -0,0 +1,10 @@
{{define "report.html"}}{{template "top" .}}
{{template "banner" .}}
<hr>
{{with .Body}}<div class="box narrow"><h2>Report post No.{{.Post.No}}</h2>
<form method="post" action="/chan/{{$.Board.Dir}}/report">
<input type="hidden" name="tok" value="{{$.Token}}"><input type="hidden" name="no" value="{{.Post.No}}">
{{range $i, $r := .Reasons}}<label class="reason"><input type="radio" name="reason" value="{{$r}}"{{if eq $i 0}} checked{{end}}> {{$r}}</label>{{end}}
<p><button type="submit">Report</button></p>
</form></div>{{end}}
{{template "bottom" .}}{{end}}
+64
View File
@@ -0,0 +1,64 @@
package imageboard
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/japanese"
)
// tripcode is a password's tripcode, as 2channel made them and every
// image board since: the password in Shift JIS, HTML-escaped, its salt
// its second and third characters, crypt(3)'s last ten.
func tripcode(pw string) string {
b, err := encoding.ReplaceUnsupported(japanese.ShiftJIS.NewEncoder()).Bytes([]byte(pw))
if err != nil {
b = []byte(pw)
}
b = []byte(strings.NewReplacer("&", "&amp;", `"`, "&quot;", "<", "&lt;", ">", "&gt;").Replace(string(b)))
salt := []byte(string(b) + "H..")[1:3]
for i, c := range salt {
switch {
case c < '.' || c > 'z':
salt[i] = '.'
case strings.IndexByte(":;<=>?@[\\]^_`", c) >= 0:
salt[i] = "ABCDEFGabcdef"[strings.IndexByte(":;<=>?@[\\]^_`", c)]
}
}
c := desCrypt(b, string(salt))
return c[len(c)-10:]
}
// secureTrip is a secure tripcode: the password and the board's secret,
// so that it cannot be found by trying passwords elsewhere.
func secureTrip(pw string, secret []byte) string {
m := hmac.New(sha256.New, secret)
m.Write([]byte(pw))
return base64.StdEncoding.EncodeToString(m.Sum(nil))[:10]
}
// splitName splits what was typed as a name into the name and its
// tripcode: "Name#password" (!tripcode), "Name##password" (!!secure),
// "Name#password##secret" (both).
func splitName(typed string, secret []byte) (name, trip string) {
name, rest, ok := strings.Cut(typed, "#")
if !ok {
return strings.TrimSpace(typed), ""
}
pw, sec := rest, ""
if strings.HasPrefix(rest, "#") {
pw, sec = "", rest[1:]
} else if i := strings.Index(rest, "##"); i >= 0 {
pw, sec = rest[:i], rest[i+2:]
}
if pw != "" {
trip = "!" + tripcode(pw)
}
if sec != "" {
trip += "!!" + secureTrip(sec, secret)
}
return strings.TrimSpace(name), trip
}
+83
View File
@@ -0,0 +1,83 @@
package imageboard
import "testing"
// crypt(3) as glibc (libxcrypt) has it, by perl's crypt.
var cryptVectors = []struct{ key, salt, want string }{
{"\x74\x65\x61", "H.", "H.br/3AFayuA6"},
{"\x74\x65\x61", "ea", "eauWokonZwxw2"},
{"\x74\x65\x61", "./", "./YzBHeSrdtok"},
{"\x74\x65\x61", "zz", "zzSuWEzr.werg"},
{"\x74\x65\x61", "A0", "A0d7wrn7NvNIE"},
{"\x66\x61\x67\x67\x6f\x74", "H.", "H.fGD9xAZQOKg"},
{"\x66\x61\x67\x67\x6f\x74", "ea", "eahFxG76h7zl."},
{"\x66\x61\x67\x67\x6f\x74", "./", ".//NypE/U/qWA"},
{"\x66\x61\x67\x67\x6f\x74", "zz", "zz/gpilhVyi/2"},
{"\x66\x61\x67\x67\x6f\x74", "A0", "A0zab8cs93TZs"},
{"", "H.", "H.2jPpg5.obl6"},
{"", "ea", "eaIv9eteVyQUM"},
{"", "./", "./Una9Fi.seRo"},
{"", "zz", "zz6dpSdr.LHZw"},
{"", "A0", "A0BPVpWCkcv5o"},
{"\x61", "H.", "H.6ZnBI2EKkq."},
{"\x61", "ea", "eaTFN5ysU0JYI"},
{"\x61", "./", "./xT2u5QYaHcU"},
{"\x61", "zz", "zzJZ5PtvFqi9o"},
{"\x61", "A0", "A0gq9shZXLDtQ"},
{"\x70\x61\x73\x73\x77\x6f\x72\x64", "H.", "H.uSfq3SPdV.c"},
{"\x70\x61\x73\x73\x77\x6f\x72\x64", "ea", "eaL0dOhJ7ObMw"},
{"\x70\x61\x73\x73\x77\x6f\x72\x64", "./", "./xZjzHv5vzVE"},
{"\x70\x61\x73\x73\x77\x6f\x72\x64", "zz", "zzXUHfURnGg8I"},
{"\x70\x61\x73\x73\x77\x6f\x72\x64", "A0", "A0qxUqZSv1XUU"},
{"\x31\x32\x33\x34\x35\x36\x37\x38", "H.", "H.pRvhij78pUE"},
{"\x31\x32\x33\x34\x35\x36\x37\x38", "ea", "eaQvwmUPGFy6k"},
{"\x31\x32\x33\x34\x35\x36\x37\x38", "./", "./qw5JW./79Vg"},
{"\x31\x32\x33\x34\x35\x36\x37\x38", "zz", "zzRtj6pNdfpLE"},
{"\x31\x32\x33\x34\x35\x36\x37\x38", "A0", "A0B5JRmm6jDDE"},
{"\x6c\x6f\x6e\x67\x65\x72\x74\x68\x61\x6e\x38\x63\x68\x61\x72\x73", "H.", "H.yY7BHPVkmxI"},
{"\x6c\x6f\x6e\x67\x65\x72\x74\x68\x61\x6e\x38\x63\x68\x61\x72\x73", "ea", "eaq9SQqclHErg"},
{"\x6c\x6f\x6e\x67\x65\x72\x74\x68\x61\x6e\x38\x63\x68\x61\x72\x73", "./", "./haKoGjqSo/Y"},
{"\x6c\x6f\x6e\x67\x65\x72\x74\x68\x61\x6e\x38\x63\x68\x61\x72\x73", "zz", "zz6XwEAsbAWcE"},
{"\x6c\x6f\x6e\x67\x65\x72\x74\x68\x61\x6e\x38\x63\x68\x61\x72\x73", "A0", "A0bfkiZ6ERrOA"},
{"\x82\xa0\x78", "H.", "H.Z7RiE95NgPU"},
{"\x82\xa0\x78", "ea", "eazOqpcN5sPEg"},
{"\x82\xa0\x78", "./", "./XaC86oTFO8U"},
{"\x82\xa0\x78", "zz", "zzgck742pixEQ"},
{"\x82\xa0\x78", "A0", "A0Mc8wN7bP4f."},
{"\x61\x26\x61\x6d\x70\x3b\x62", "H.", "H.O5sU2MVxp2E"},
{"\x61\x26\x61\x6d\x70\x3b\x62", "ea", "eaCqRypc1nvlQ"},
{"\x61\x26\x61\x6d\x70\x3b\x62", "./", "./N5UdDJOu1vE"},
{"\x61\x26\x61\x6d\x70\x3b\x62", "zz", "zzHB7PLIiZFIM"},
{"\x61\x26\x61\x6d\x70\x3b\x62", "A0", "A0LaAfTVberTc"},
}
func TestDESCrypt(t *testing.T) {
for _, v := range cryptVectors {
if got := desCrypt([]byte(v.key), v.salt); got != v.want {
t.Errorf("crypt(%q, %q) = %q, want %q", v.key, v.salt, got, v.want)
}
}
}
func TestTripcode(t *testing.T) {
for typed, want := range map[string][2]string{
"Anon#tea": {"Anon", "!WokonZwxw2"},
"#faggot": {"", "!Ep8pui8Vw2"},
"Bob": {"Bob", ""},
" Bob # ": {"Bob", "!" + tripcode(" ")},
"Al##secret": {"Al", "!!" + secureTrip("secret", []byte("k"))},
"Al#tea##s": {"Al", "!WokonZwxw2!!" + secureTrip("s", []byte("k"))},
} {
name, trip := splitName(typed, []byte("k"))
if name != want[0] || trip != want[1] {
t.Errorf("%q: %q %q, want %q", typed, name, trip, want)
}
}
// escaped as HTML, and in Shift JIS, before it is hashed
if got, want := tripcode("a<b"), desCrypt([]byte("a&lt;b"), ".l")[3:]; got != want {
t.Errorf("escaped: %q, want %q", got, want)
}
if got, want := tripcode("あ"), desCrypt([]byte{0x82, 0xa0}, ".H")[3:]; got != want {
t.Errorf("Shift JIS: %q, want %q", got, want)
}
}
+43
View File
@@ -0,0 +1,43 @@
package server
import (
"fmt"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/config"
"github.com/Neo-Desktop/bbs-sec/internal/imageboard"
)
// chanSection reads [chan]: how the image boards are run.
func (c *Config) chanSection(s *config.Section) error {
ch := imageboard.Defaults()
ch.Dir = s.String("dir", ch.Dir)
var err error
if ch.MaxFile, err = parseSize(s, "max_file", ch.MaxFile); err != nil {
return err
}
if ch.MaxFile < 1<<10 || ch.MaxFile > 1<<30 {
return fmt.Errorf("max_file: from 1K to 1G")
}
if ch.ThreadWait, err = s.Seconds("thread_wait", int(ch.ThreadWait.Seconds()), 0, 86400); err != nil {
return err
}
if ch.ReplyWait, err = s.Seconds("reply_wait", int(ch.ReplyWait.Seconds()), 0, 86400); err != nil {
return err
}
if ch.MaxComment, err = s.Int("max_comment", ch.MaxComment, 100, 20000); err != nil {
return err
}
if ch.Strip, err = s.Bool("strip_metadata", ch.Strip); err != nil {
return err
}
if ch.Style = s.String("style", ""); ch.Style != "" && !imageboard.KnownStyle(ch.Style) {
var names []string
for _, st := range imageboard.Styles {
names = append(names, st.Name)
}
return fmt.Errorf("style: %q is not one of %s", ch.Style, strings.Join(names, ", "))
}
c.Chan = ch
return nil
}
+7 -2
View File
@@ -22,6 +22,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/ftp"
"github.com/Neo-Desktop/bbs-sec/internal/gopher"
"github.com/Neo-Desktop/bbs-sec/internal/guard"
"github.com/Neo-Desktop/bbs-sec/internal/imageboard"
"github.com/Neo-Desktop/bbs-sec/internal/ircd"
"github.com/Neo-Desktop/bbs-sec/internal/logo"
"github.com/Neo-Desktop/bbs-sec/internal/mrc"
@@ -61,7 +62,8 @@ type Config struct {
Menus map[string]*bbs.Menu
Text map[string]string // [strings]
HTTP *api.Settings // nil: no HTTP API
Gopher *gopher.Settings // nil: no gopher server
Chan imageboard.Settings
Gopher *gopher.Settings // nil: no gopher server
Database string
Log string // syslog, stderr, none, or a file
Listeners []*Listener
@@ -122,6 +124,9 @@ func Load(path string) (*Config, error) {
if err := c.doorSections(cf); err != nil {
return nil, err
}
if err := c.chanSection(cf.Get("chan", "")); err != nil {
return nil, fmt.Errorf("[chan] %w", err)
}
if err := c.httpSection(cf.Get("http", "")); err != nil {
return nil, fmt.Errorf("[http] %w", err)
}
@@ -170,7 +175,7 @@ func Load(path string) (*Config, error) {
}
for _, s := range cf.Sections {
switch s.Kind {
case "general", "security", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "mrc", "menu", "strings", "http", "level":
case "general", "security", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "mrc", "menu", "strings", "http", "level", "chan":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
}
+13
View File
@@ -31,6 +31,15 @@ func (c *Config) httpSection(s *config.Section) error {
if h.TLS && (h.CertFile == "" || h.KeyFile == "") {
return errors.New("cert_file and key_file are needed for TLS (or tls = no, behind a proxy that has it)")
}
if h.TrustedProxies, err = api.ParseProxies(s.String("trusted_proxies", "")); err != nil {
return fmt.Errorf("trusted_proxies: %v", err)
}
if h.SecureCookies, err = s.Bool("secure_cookies", h.TLS); err != nil {
return err
}
if !h.TLS && len(h.TrustedProxies) > 0 && !h.SecureCookies {
c.Warnings = append(c.Warnings, "[http] behind a proxy without secure_cookies = yes: logins' cookies may cross in the clear if the proxy also serves http://")
}
if !h.TLS {
if ip := net.ParseIP(host); host == "" || ip == nil || !ip.IsLoopback() {
c.Warnings = append(c.Warnings, "[http] tls = no on an address others reach: tokens and passwords go in the clear")
@@ -81,6 +90,10 @@ func (c *Config) httpSection(s *config.Section) error {
}
return fmt.Errorf("forum_theme: %q is not one of %s", h.Theme, strings.Join(names, ", "))
}
if h.Chan, err = s.Bool("chan", true); err != nil {
return err
}
h.ChanSettings = c.Chan
c.HTTP = h
return nil
}
+576
View File
@@ -0,0 +1,576 @@
package store
import (
"database/sql"
"errors"
"strings"
"time"
)
// Board is an image board: its directory (/b/), and how it is run.
type Board struct {
ID int64
Dir string // "b", as in /b/
Title string // "Random"
Description string
MaxFile int64 // bytes, the largest image (0: the image board's)
Pages int // of threads, before the oldest are pruned
PerPage int // threads a page
BumpLimit int // replies that bump a thread
ImageLimit int // images a thread may have
ForcedAnon bool // names and tripcodes are ignored
DefaultName string
Worksafe bool // its default style is the blue one
Locked bool // no one but staff posts
LoginToPost bool // only the BBS's users post
TextOnly bool // threads need no image
Mods string
Sort int
LastNo int64
Created time.Time
}
// BoardPost is a post on an image board: a thread's first (Thread 0) or a
// reply to one (Thread its first's number).
type BoardPost struct {
ID int64
BoardID int64
No int64
Thread int64 // 0: it starts a thread
Name string
Trip string // "!abcdefghij", "!!abcdefghij"
Capcode string // "mod", "admin"
Email string
Subject string
Comment string
Password string // a hash, to delete it by
IP string
UserID int64 // who posted, if logged in (0: anonymous)
Created time.Time
Bumped time.Time
Sticky bool
Closed bool
// its file, if it has one
FileName string // as uploaded, without its extension
Ext string // ".jpg"
Tim int64 // what it is stored as
FileSize int64
W, H int
TnW, TnH int
MD5 string // base64, as 4chan has it
Spoiler bool
FileDeleted bool
Banned bool // its poster was banned for it, as it says
// for a thread's first post, when listed
Replies, Images int
}
// HasFile says whether the post has a file still.
func (p *BoardPost) HasFile() bool { return p.Ext != "" && !p.FileDeleted }
// Ban keeps an address from posting.
type Ban struct {
ID int64
IP string // an address, or a prefix ending in . or : (a range)
Board string // "": every board
Reason string
By string
Post string // what was posted, as the banned see it
Created time.Time
Expires time.Time // zero: never
}
// Report is a post someone thinks staff should see.
type Report struct {
ID int64
BoardID int64
Dir string
No int64
Reason string
IP string
Created time.Time
}
const boardCols = `id, dir, title, description, max_file, pages, per_page, bump_limit, image_limit, forced_anon,
default_name, worksafe, locked, login_to_post, text_only, mods, sort, last_no, created`
func scanBoard(row interface{ Scan(...any) error }) (*Board, error) {
var b Board
var created int64
err := row.Scan(&b.ID, &b.Dir, &b.Title, &b.Description, &b.MaxFile, &b.Pages, &b.PerPage, &b.BumpLimit,
&b.ImageLimit, &b.ForcedAnon, &b.DefaultName, &b.Worksafe, &b.Locked, &b.LoginToPost, &b.TextOnly,
&b.Mods, &b.Sort, &b.LastNo, &created)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
b.Created = unix(created)
return &b, err
}
// CreateBoard adds an image board, as b has it (ID, LastNo, Created
// aside).
func (s *Store) CreateBoard(b *Board) (*Board, error) {
id, err := s.db.insertID(`INSERT INTO chan_boards (dir, title, description, max_file, pages, per_page, bump_limit,
image_limit, forced_anon, default_name, worksafe, locked, login_to_post, text_only, mods, sort, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, b.Dir, b.Title, b.Description, b.MaxFile, b.Pages,
b.PerPage, b.BumpLimit, b.ImageLimit, b.ForcedAnon, b.DefaultName, b.Worksafe, b.Locked, b.LoginToPost,
b.TextOnly, b.Mods, b.Sort, now())
if err != nil {
if isUnique(err) {
return nil, ErrExists
}
return nil, err
}
return s.BoardByID(id)
}
// UpdateBoard keeps a board's settings (not its directory or numbers).
func (s *Store) UpdateBoard(b *Board) error {
_, err := s.db.Exec(`UPDATE chan_boards SET title = ?, description = ?, max_file = ?, pages = ?, per_page = ?,
bump_limit = ?, image_limit = ?, forced_anon = ?, default_name = ?, worksafe = ?, locked = ?, login_to_post = ?,
text_only = ?, mods = ?, sort = ? WHERE id = ?`, b.Title, b.Description, b.MaxFile, b.Pages, b.PerPage,
b.BumpLimit, b.ImageLimit, b.ForcedAnon, b.DefaultName, b.Worksafe, b.Locked, b.LoginToPost, b.TextOnly,
b.Mods, b.Sort, b.ID)
return err
}
// DeleteBoard removes a board and its posts (its files are the caller's
// to remove).
func (s *Store) DeleteBoard(id int64) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, q := range []string{`DELETE FROM chan_posts WHERE board_id = ?`, `DELETE FROM chan_reports WHERE board_id = ?`,
`DELETE FROM chan_boards WHERE id = ?`} {
if _, err := tx.Exec(q, id); err != nil {
return err
}
}
return tx.Commit()
}
// BoardByID finds a board.
func (s *Store) BoardByID(id int64) (*Board, error) {
return scanBoard(s.db.QueryRow(`SELECT `+boardCols+` FROM chan_boards WHERE id = ?`, id))
}
// Board finds a board by its directory.
func (s *Store) Board(dir string) (*Board, error) {
return scanBoard(s.db.QueryRow(`SELECT `+boardCols+` FROM chan_boards WHERE dir = ?`, dir))
}
// Boards lists the boards, in their order.
func (s *Store) Boards() ([]*Board, error) {
rows, err := s.db.Query(`SELECT ` + boardCols + ` FROM chan_boards ORDER BY sort, dir`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Board
for rows.Next() {
b, err := scanBoard(rows)
if err != nil {
return nil, err
}
out = append(out, b)
}
return out, rows.Err()
}
const postCols = `id, board_id, num, thread, name, trip, capcode, email, subject, body, password, ip, user_id, created,
bumped, sticky, closed, file_name, ext, tim, file_size, w, h, tn_w, tn_h, md5, spoiler, file_deleted, banned`
func scanPost(row interface{ Scan(...any) error }, more ...any) (*BoardPost, error) {
var p BoardPost
var created, bumped int64
dest := []any{&p.ID, &p.BoardID, &p.No, &p.Thread, &p.Name, &p.Trip, &p.Capcode, &p.Email, &p.Subject, &p.Comment,
&p.Password, &p.IP, &p.UserID, &created, &bumped, &p.Sticky, &p.Closed, &p.FileName, &p.Ext, &p.Tim,
&p.FileSize, &p.W, &p.H, &p.TnW, &p.TnH, &p.MD5, &p.Spoiler, &p.FileDeleted, &p.Banned}
err := row.Scan(append(dest, more...)...)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
p.Created, p.Bumped = unix(created), unix(bumped)
return &p, err
}
func (s *Store) posts(q string, args ...any) ([]*BoardPost, error) {
rows, err := s.db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BoardPost
for rows.Next() {
p, err := scanPost(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// ErrThreadGone is a reply to a thread that is not there.
var ErrThreadGone = errors.New("the thread is gone")
// AddPost numbers a post and adds it to its board (to its thread, which
// it bumps unless bump is false); its No and Created are set.
func (s *Store) AddPost(p *BoardPost, bump bool) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if p.Thread != 0 {
var n int
if err := tx.QueryRow(`SELECT COUNT(*) FROM chan_posts WHERE board_id = ? AND num = ? AND thread = 0`,
p.BoardID, p.Thread).Scan(&n); err != nil {
return err
}
if n == 0 {
return ErrThreadGone
}
}
if _, err := tx.Exec(`UPDATE chan_boards SET last_no = last_no + 1 WHERE id = ?`, p.BoardID); err != nil {
return err
}
if err := tx.QueryRow(`SELECT last_no FROM chan_boards WHERE id = ?`, p.BoardID).Scan(&p.No); err != nil {
return err
}
t := now()
p.Created, p.Bumped = unix(t), unix(t)
if _, err := tx.insertID(`INSERT INTO chan_posts (board_id, num, thread, name, trip, capcode, email, subject, body,
password, ip, user_id, created, bumped, sticky, closed, file_name, ext, tim, file_size, w, h, tn_w, tn_h, md5,
spoiler) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.BoardID, p.No, p.Thread, p.Name, p.Trip, p.Capcode, p.Email, p.Subject, p.Comment, p.Password, p.IP,
p.UserID, t, t, p.Sticky, p.Closed, p.FileName, p.Ext, p.Tim, p.FileSize, p.W, p.H, p.TnW, p.TnH, p.MD5,
p.Spoiler); err != nil {
return err
}
if p.Thread != 0 && bump {
if _, err := tx.Exec(`UPDATE chan_posts SET bumped = ? WHERE board_id = ? AND num = ?`, t, p.BoardID,
p.Thread); err != nil {
return err
}
}
return tx.Commit()
}
// ChanPost finds a post by its board and number.
func (s *Store) ChanPost(board, no int64) (*BoardPost, error) {
return scanPost(s.db.QueryRow(`SELECT `+postCols+` FROM chan_posts WHERE board_id = ? AND num = ?`, board, no))
}
// threadCounts are a thread's replies and the images among them.
const threadCounts = `,
(SELECT COUNT(*) FROM chan_posts r WHERE r.board_id = chan_posts.board_id AND r.thread = chan_posts.num),
(SELECT COUNT(*) FROM chan_posts r WHERE r.board_id = chan_posts.board_id AND r.thread = chan_posts.num AND r.ext <> '')`
func (s *Store) threads(q string, args ...any) ([]*BoardPost, error) {
rows, err := s.db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BoardPost
for rows.Next() {
var replies, images int
p, err := scanPost(rows, &replies, &images)
if err != nil {
return nil, err
}
p.Replies, p.Images = replies, images
out = append(out, p)
}
return out, rows.Err()
}
// ChanThreads lists a board's threads, stickies and the last bumped first,
// with their counts: limit of them from offset.
func (s *Store) ChanThreads(board int64, offset, limit int) ([]*BoardPost, error) {
return s.threads(`SELECT `+postCols+threadCounts+` FROM chan_posts WHERE board_id = ? AND thread = 0
ORDER BY sticky DESC, bumped DESC, num DESC LIMIT ? OFFSET ?`, board, limit, offset)
}
// ChanThread is a thread's first post, with its counts.
func (s *Store) ChanThread(board, no int64) (*BoardPost, error) {
ps, err := s.threads(`SELECT `+postCols+threadCounts+` FROM chan_posts WHERE board_id = ? AND num = ? AND thread = 0`,
board, no)
if err != nil {
return nil, err
}
if len(ps) == 0 {
return nil, ErrNotFound
}
return ps[0], nil
}
// ChanThreadCount is how many threads a board has.
func (s *Store) ChanThreadCount(board int64) (int, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM chan_posts WHERE board_id = ? AND thread = 0`, board).Scan(&n)
return n, err
}
// ChanReplies are a thread's replies, oldest first: all of them (last 0),
// or the last ones.
func (s *Store) ChanReplies(board, thread int64, last int) ([]*BoardPost, error) {
if last <= 0 {
return s.posts(`SELECT `+postCols+` FROM chan_posts WHERE board_id = ? AND thread = ? ORDER BY num`, board, thread)
}
ps, err := s.posts(`SELECT `+postCols+` FROM chan_posts WHERE board_id = ? AND thread = ? ORDER BY num DESC LIMIT ?`,
board, thread, last)
for i, j := 0, len(ps)-1; i < j; i, j = i+1, j-1 {
ps[i], ps[j] = ps[j], ps[i]
}
return ps, err
}
// ChanPostThreads are, of a board's post numbers, the thread each is in (its
// own for a first post): for linking quotes. Numbers not there are not
// in it.
func (s *Store) ChanPostThreads(board int64, nos []int64) (map[int64]int64, error) {
out := map[int64]int64{}
for len(nos) > 0 {
n := min(len(nos), 200)
args := []any{board}
for _, no := range nos[:n] {
args = append(args, no)
}
rows, err := s.db.Query(`SELECT num, thread FROM chan_posts WHERE board_id = ? AND num IN (?`+
strings.Repeat(", ?", n-1)+`)`, args...)
if err != nil {
return nil, err
}
for rows.Next() {
var no, thread int64
if err := rows.Scan(&no, &thread); err != nil {
rows.Close()
return nil, err
}
if thread == 0 {
thread = no
}
out[no] = thread
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
nos = nos[n:]
}
return out, nil
}
// PostByMD5 finds a post on a board whose file has an MD5 (a duplicate).
func (s *Store) PostByMD5(board int64, md5 string) (*BoardPost, error) {
return scanPost(s.db.QueryRow(`SELECT `+postCols+` FROM chan_posts WHERE board_id = ? AND md5 = ? AND file_deleted = ?
ORDER BY num LIMIT 1`, board, md5, false))
}
// LastPostBy is when an address last posted (zero: never), and last made
// a thread.
func (s *Store) LastPostBy(ip string) (post, thread time.Time, err error) {
var p, t sql.NullInt64
err = s.db.QueryRow(`SELECT MAX(created), MAX(CASE WHEN thread = 0 THEN created END) FROM chan_posts WHERE ip = ?`,
ip).Scan(&p, &t)
if p.Valid {
post = unix(p.Int64)
}
if t.Valid {
thread = unix(t.Int64)
}
return
}
// RecentImages are the latest posts with images, across the boards.
func (s *Store) RecentImages(limit int) ([]*BoardPost, error) {
return s.posts(`SELECT `+postCols+` FROM chan_posts WHERE ext <> '' AND file_deleted = ? AND spoiler = ?
ORDER BY created DESC, id DESC LIMIT ?`, false, false, limit)
}
// PostsByIP are an address's posts, the newest first.
func (s *Store) PostsByIP(ip string, limit int) ([]*BoardPost, error) {
return s.posts(`SELECT `+postCols+` FROM chan_posts WHERE ip = ? ORDER BY created DESC, id DESC LIMIT ?`, ip, limit)
}
// ChanStats are the boards' totals: posts, and the bytes of their files.
func (s *Store) ChanStats() (posts int, bytes int64, err error) {
err = s.db.QueryRow(`SELECT COUNT(*), COALESCE(SUM(CASE WHEN file_deleted = ? THEN file_size ELSE 0 END), 0)
FROM chan_posts`, false).Scan(&posts, &bytes)
return
}
// DeleteChanPost removes a post; a thread's first takes its replies with it.
// What was removed is returned, for their files.
func (s *Store) DeleteChanPost(board, no int64) ([]*BoardPost, error) {
p, err := s.ChanPost(board, no)
if err != nil {
return nil, err
}
gone := []*BoardPost{p}
if p.Thread == 0 {
rs, err := s.ChanReplies(board, no, 0)
if err != nil {
return nil, err
}
gone = append(gone, rs...)
}
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
q, args := `DELETE FROM chan_posts WHERE board_id = ? AND num = ?`, []any{board, no}
if p.Thread == 0 {
q, args = q+` OR board_id = ? AND thread = ?`, append(args, board, no)
}
if _, err := tx.Exec(q, args...); err != nil {
return nil, err
}
if _, err := tx.Exec(`DELETE FROM chan_reports WHERE board_id = ? AND num = ?`, board, no); err != nil {
return nil, err
}
return gone, tx.Commit()
}
// DeleteChanFile marks a post's file deleted.
func (s *Store) DeleteChanFile(board, no int64) error {
_, err := s.db.Exec(`UPDATE chan_posts SET file_deleted = ? WHERE board_id = ? AND num = ?`, true, board, no)
return err
}
// MarkChanBanned has a post say its poster was banned for it.
func (s *Store) MarkChanBanned(board, no int64) error {
_, err := s.db.Exec(`UPDATE chan_posts SET banned = ? WHERE board_id = ? AND num = ?`, true, board, no)
return err
}
// SetChanThread sets a thread's sticky and closed.
func (s *Store) SetChanThread(board, no int64, sticky, closed bool) error {
_, err := s.db.Exec(`UPDATE chan_posts SET sticky = ?, closed = ? WHERE board_id = ? AND num = ? AND thread = 0`,
sticky, closed, board, no)
return err
}
// PruneChanThreads removes a board's threads past the first keep (stickies
// kept): what was removed is returned, for their files.
func (s *Store) PruneChanThreads(board int64, keep int) ([]*BoardPost, error) {
all, err := s.posts(`SELECT `+postCols+` FROM chan_posts WHERE board_id = ? AND thread = 0 AND sticky = ?
ORDER BY bumped DESC, num DESC`, board, false)
if err != nil || len(all) <= keep {
return nil, err
}
old := all[keep:]
var gone []*BoardPost
for _, t := range old {
g, err := s.DeleteChanPost(board, t.No)
if err != nil && !errors.Is(err, ErrNotFound) {
return gone, err
}
gone = append(gone, g...)
}
return gone, nil
}
// AddBan bans an address (or a range).
func (s *Store) AddBan(b *Ban) (int64, error) {
var exp int64
if !b.Expires.IsZero() {
exp = b.Expires.Unix()
}
return s.db.insertID(`INSERT INTO chan_bans (ip, board, reason, by_name, post, created, expires)
VALUES (?, ?, ?, ?, ?, ?, ?)`, b.IP, b.Board, b.Reason, b.By, b.Post, now(), exp)
}
// DeleteBan lifts a ban.
func (s *Store) DeleteBan(id int64) error {
return s.exec1(`DELETE FROM chan_bans WHERE id = ?`, id)
}
func (s *Store) bans(q string, args ...any) ([]*Ban, error) {
rows, err := s.db.Query(`SELECT id, ip, board, reason, by_name, post, created, expires FROM chan_bans `+q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Ban
for rows.Next() {
var b Ban
var created, exp int64
if err := rows.Scan(&b.ID, &b.IP, &b.Board, &b.Reason, &b.By, &b.Post, &created, &exp); err != nil {
return nil, err
}
b.Created = unix(created)
if exp != 0 {
b.Expires = unix(exp)
}
out = append(out, &b)
}
return out, rows.Err()
}
// Bans lists the bans in force, the newest first.
func (s *Store) Bans() ([]*Ban, error) {
return s.bans(`WHERE expires = 0 OR expires > ? ORDER BY id DESC`, now())
}
// BanFor is the ban in force on an address on a board (nil: none): one
// of the address, or of a range (a prefix ending in . or :) it is in.
func (s *Store) BanFor(ip, board string) (*Ban, error) {
bs, err := s.bans(`WHERE (expires = 0 OR expires > ?) AND (board = '' OR board = ?) ORDER BY id DESC`, now(), board)
if err != nil {
return nil, err
}
for _, b := range bs {
if b.IP == ip || (strings.HasSuffix(b.IP, ".") || strings.HasSuffix(b.IP, ":")) && strings.HasPrefix(ip, b.IP) {
return b, nil
}
}
return nil, nil
}
// AddReport reports a post (once an address).
func (s *Store) AddReport(r *Report) error {
var n int
if err := s.db.QueryRow(`SELECT COUNT(*) FROM chan_reports WHERE board_id = ? AND num = ? AND ip = ?`,
r.BoardID, r.No, r.IP).Scan(&n); err != nil {
return err
}
if n > 0 {
return ErrExists
}
_, err := s.db.insertID(`INSERT INTO chan_reports (board_id, num, reason, ip, created) VALUES (?, ?, ?, ?, ?)`,
r.BoardID, r.No, r.Reason, r.IP, now())
return err
}
// Reports lists the reports, the newest first.
func (s *Store) Reports() ([]*Report, error) {
rows, err := s.db.Query(`SELECT r.id, r.board_id, b.dir, r.num, r.reason, r.ip, r.created FROM chan_reports r
JOIN chan_boards b ON b.id = r.board_id ORDER BY r.id DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Report
for rows.Next() {
var r Report
var created int64
if err := rows.Scan(&r.ID, &r.BoardID, &r.Dir, &r.No, &r.Reason, &r.IP, &created); err != nil {
return nil, err
}
r.Created = unix(created)
out = append(out, &r)
}
return out, rows.Err()
}
// DismissReports clears a post's reports.
func (s *Store) DismissReports(board, no int64) error {
_, err := s.db.Exec(`DELETE FROM chan_reports WHERE board_id = ? AND num = ?`, board, no)
return err
}
+2 -1
View File
@@ -9,7 +9,8 @@ import (
// copyOrder is the tables in an order their references allow.
var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files",
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs"}
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs",
"chan_boards", "chan_posts", "chan_bans", "chan_reports"}
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
+75
View File
@@ -224,6 +224,76 @@ CREATE TABLE IF NOT EXISTS ssh_keys (
comment {str} NOT NULL DEFAULT '',
created {int} NOT NULL,
last_used {int} NOT NULL DEFAULT 0
)`, `
CREATE TABLE IF NOT EXISTS chan_boards (
id {id},
dir {name} NOT NULL UNIQUE,
title {str} NOT NULL,
description {str} NOT NULL DEFAULT '',
max_file {int} NOT NULL DEFAULT 0,
pages {int} NOT NULL DEFAULT 10,
per_page {int} NOT NULL DEFAULT 10,
bump_limit {int} NOT NULL DEFAULT 300,
image_limit {int} NOT NULL DEFAULT 150,
forced_anon {bool} NOT NULL DEFAULT FALSE,
default_name {str} NOT NULL DEFAULT 'Anonymous',
worksafe {bool} NOT NULL DEFAULT TRUE,
locked {bool} NOT NULL DEFAULT FALSE,
login_to_post {bool} NOT NULL DEFAULT FALSE,
text_only {bool} NOT NULL DEFAULT FALSE,
mods {str} NOT NULL DEFAULT '',
sort {int} NOT NULL DEFAULT 0,
last_no {int} NOT NULL DEFAULT 0,
created {int} NOT NULL
)`, `
CREATE TABLE IF NOT EXISTS chan_posts (
id {id},
board_id {int} NOT NULL REFERENCES chan_boards(id) ON DELETE CASCADE,
num {int} NOT NULL,
thread {int} NOT NULL DEFAULT 0,
name {str} NOT NULL DEFAULT '',
trip {str} NOT NULL DEFAULT '',
capcode {str} NOT NULL DEFAULT '',
email {str} NOT NULL DEFAULT '',
subject {str} NOT NULL DEFAULT '',
body {text} NOT NULL,
password {str} NOT NULL DEFAULT '',
ip {key} NOT NULL,
user_id {int} NOT NULL DEFAULT 0,
created {int} NOT NULL,
bumped {int} NOT NULL,
sticky {bool} NOT NULL DEFAULT FALSE,
closed {bool} NOT NULL DEFAULT FALSE,
file_name {str} NOT NULL DEFAULT '',
ext {str} NOT NULL DEFAULT '',
tim {int} NOT NULL DEFAULT 0,
file_size {int} NOT NULL DEFAULT 0,
w {int} NOT NULL DEFAULT 0,
h {int} NOT NULL DEFAULT 0,
tn_w {int} NOT NULL DEFAULT 0,
tn_h {int} NOT NULL DEFAULT 0,
md5 {key} NOT NULL DEFAULT '',
spoiler {bool} NOT NULL DEFAULT FALSE,
file_deleted {bool} NOT NULL DEFAULT FALSE,
banned {bool} NOT NULL DEFAULT FALSE
)`, `
CREATE TABLE IF NOT EXISTS chan_bans (
id {id},
ip {key} NOT NULL,
board {str} NOT NULL DEFAULT '',
reason {str} NOT NULL DEFAULT '',
by_name {str} NOT NULL DEFAULT '',
post {text} NOT NULL,
created {int} NOT NULL,
expires {int} NOT NULL DEFAULT 0
)`, `
CREATE TABLE IF NOT EXISTS chan_reports (
id {id},
board_id {int} NOT NULL REFERENCES chan_boards(id) ON DELETE CASCADE,
num {int} NOT NULL,
reason {str} NOT NULL DEFAULT '',
ip {key} NOT NULL,
created {int} NOT NULL
)`,
}
@@ -249,6 +319,11 @@ var indexes = []struct {
{"qwk_msgs_message", "qwk_msgs", "message_id", false},
{"messages_thread", "messages", "thread", false},
{"file_areas_fileecho", "file_areas", "fileecho", true},
{"chan_posts_num", "chan_posts", "board_id, num", true},
{"chan_posts_thread", "chan_posts", "board_id, thread, bumped", false},
{"chan_posts_md5", "chan_posts", "board_id, md5", false},
{"chan_posts_ip", "chan_posts", "ip, created", false},
{"chan_reports_post", "chan_reports", "board_id, num", false},
}
// added are the columns added since the first schema: an older database