Image boards: poster IDs and country flags

A board with ids gives each poster an ID in each thread, as 4chan's: a
keyed hash of their address, the board and the thread, the same all
through a thread, another in the next. Each has its colour; hovering
counts its posts, clicking marks them.

A board with flags shows each poster's country's flag (an emoji, its
name on hovering), from [chan] geoip: a country database read by the
new internal/geoip, which reads MaxMind DB files (GeoLite2, DB-IP
Lite, IPinfo's...; tested on files made by MaxMind's own writer in
each record size, and broken ones) and CSVs of ranges (DB-IP's,
IP2Location LITE's), plain or gzipped, read again when the file
changes. Country names from ISO 3166.

Both are kept with each post, shown on the terminals by the name, and
given in the JSON as 4chan's id, country and country_name.

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 04:20:29 +00:00
1 parent a47cbc946f
commit 6ea47bb179
23 files changed
+1192 -42

No files matched your search

+4
View File
@@ -263,6 +263,10 @@ address = 127.0.0.1:2513
; the post form's Options line (sage: no bump; nonoko); a board may say
; otherwise: bbs chan board set DIR options yes|no|default
;options = yes
; a country database for the boards with flags (bbs chan board set DIR
; flags yes): a MaxMind DB (.mmdb: GeoLite2 Country, DB-IP Lite...) or a
; CSV of ranges; read again when it changes
;geoip = /var/lib/bbs/GeoLite2-Country.mmdb
; 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
+11 -3
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
@@ -46,7 +47,7 @@ func chanBoardCmd(cfg *server.Config, args []string) {
var opts []string
for name, on := range map[string]bool{"nsfw": !b.Worksafe, "forced anon": b.ForcedAnon, "locked": b.Locked,
"users post": b.LoginToPost && !b.LoginToRead, "users only": b.LoginToRead, "text only": b.TextOnly,
"oekaki": b.Oekaki, "captcha " + b.Captcha: b.Captcha != "", "options " + b.Options: b.Options != ""} {
"oekaki": b.Oekaki, "ids": b.PosterIDs, "flags": b.Flags, "captcha " + b.Captcha: b.Captcha != "", "options " + b.Options: b.Options != ""} {
if on {
opts = append(opts, name)
}
@@ -68,7 +69,7 @@ func chanBoardCmd(cfg *server.Config, args []string) {
}
b.Worksafe = !flags["nsfw"]
b.ForcedAnon, b.Locked, b.LoginToPost, b.TextOnly = flags["forced-anon"], flags["locked"], flags["login"], flags["text-only"]
b.Oekaki = flags["oekaki"]
b.Oekaki, b.PosterIDs, b.Flags = flags["oekaki"], flags["ids"], flags["flags"]
if _, err := st.CreateBoard(b); errors.Is(err, store.ErrExists) {
fatal(fmt.Errorf("there is a /%s/ already", b.Dir))
} else if err != nil {
@@ -86,6 +87,9 @@ func chanBoardCmd(cfg *server.Config, args []string) {
if err := setBoard(b, words[2], words[3]); err != nil {
fatal(err)
}
if b.Flags && cfg.Chan.GeoIP == "" {
fmt.Fprintln(os.Stderr, "bbs: no flags are shown until [chan] geoip names a country database")
}
if err := st.UpdateBoard(b); err != nil {
fatal(err)
}
@@ -192,9 +196,13 @@ func setBoard(b *store.Board, key, val string) error {
b.TextOnly, err = yes()
case "oekaki":
b.Oekaki, err = yes()
case "ids":
b.PosterIDs, err = yes()
case "flags":
b.Flags, 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, oekaki, captcha, options)", key)
"bump_limit, image_limit, max_file, sort, nsfw, forced_anon, locked, login, text_only, oekaki, ids, flags, captcha, options)", key)
}
return err
}
+1
View File
@@ -128,6 +128,7 @@ func usage() {
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] [-oekaki]
[-ids] [-flags]
bbs [-config FILE] chan board set DIR KEY VALUE (pages, per_page, mods, nsfw, login, captcha, options...)
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)
+34 -3
View File
@@ -37,6 +37,7 @@ address = :8443
;captcha_level = normal ; easy, normal or hard to read
;captcha_lifetime = 600 ; seconds one lasts
;options = yes ; the post form's Options line (sage, nonoko)
;geoip = /var/lib/bbs/GeoLite2-Country.mmdb ; for the boards with flags
```
| setting | default | |
@@ -136,6 +137,32 @@ can post under, as anyone can type a name. On a `forced_anon` board posts
are marked, never signed. On the terminals every poster is signed in: no
captcha, `[member]` by the name, and *Sign it as NAME?* before the post.
## Poster IDs and flags
A board with `ids yes` gives each poster an ID in each thread, as 4chan's
do: eight characters from a keyed hash of their address, the board and
the thread, so a poster has the same ID all through a thread and another
in the next, and nothing of their address can be had from it. Each ID has
a colour of its own; hovering it says how many posts in the thread are
by it, and clicking it marks them all. On the terminals it is by the
name: `Anonymous (ID: aQvqbFdJ)`.
A board with `flags yes` shows the flag of each poster's country by their
name (an emoji, its name on hovering; `[NZ]` on the terminals), from a
country database the sysop has, `[chan] geoip`:
- a MaxMind DB file (`.mmdb`): MaxMind's GeoLite2 or GeoIP2 Country or
City, DB-IP's *IP to Country Lite*, IPinfo's and others in its format;
- or a CSV of ranges, plain or gzipped: DB-IP's (`start,end,CC`) or
IP2Location LITE DB1's (`"from","to","CC","Country"`, by numbers).
The BBS reads them itself (nothing is fetched); replace the file and it
is read again within a minute. Posts from no address (a modem's caller)
or one the database does not know have no flag. Behind a reverse proxy
name it in `trusted_proxies`, or every poster is the proxy and has its ID
and its flag. Both are kept with each post when it is made: turning them
off leaves those already made as they were.
## Threads
A reply bumps its thread to the top of the board until the thread has
@@ -203,6 +230,8 @@ bbs chan ban del ID
| `forced_anon` | no | no names or tripcodes |
| `text_only` | no | threads need no image |
| `oekaki` | no | posters can draw their pictures in the page ([below](#oekaki)) |
| `ids` | no | each poster has an ID in a thread ([below](#poster-ids-and-flags)) |
| `flags` | no | posts show their country's flag (with `[chan] geoip`) |
| `locked` | no | only staff post |
| `login` | `no` | `post`: only the BBS's users post (signed in at `/chan/login`); `all`: only they see the board at all (its pages, images and JSON; others are sent to sign in, and the front page marks it *(members)*) |
| `captcha` | `default` | `yes` or `no` for this board, else `[chan]`'s |
@@ -280,8 +309,10 @@ The boards can be read as JSON, in the shapes of 4chan's read-only API
| `/chan/b/1.json` | a page of the index |
| `/chan/b/thread/123.json` | a thread |
Beyond 4chan's fields, `boards.json` says `"oekaki": 1` of an oekaki
board, and a drawing that replays has `"replay": 1` and `"draw_ms"`.
Posts have 4chan's `id`, `country` and `country_name` where the board
has them, and `boards.json` its `user_ids` and `country_flags`. Beyond
4chan's fields, `boards.json` says `"oekaki": 1` of an oekaki board, and
a drawing that replays has `"replay": 1` and `"draw_ms"`.
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/`).
@@ -291,7 +322,7 @@ 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 and captchas.
pruned threads.
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
+6
View File
@@ -286,6 +286,12 @@ func (s *Session) chanMessage(b *store.Board, op, p *store.BoardPost, posts []*s
case p.UserID != 0:
name += " [member]" // posted by a signed-in user
}
if p.PosterID != "" {
name += " (ID: " + p.PosterID + ")"
}
if p.Country != "" {
name += " [" + p.Country + "]"
}
if p.Capcode != "" {
name += " ## " + map[string]string{"admin": "Admin", "mod": "Mod"}[p.Capcode]
}
+447
View File
@@ -0,0 +1,447 @@
// Package geoip finds the country of an address, from a database the
// sysop has: a MaxMind DB file (.mmdb: MaxMind's GeoLite2 and GeoIP2
// Country and City, DB-IP's IP to Country Lite, IPinfo's and others in its
// format), or a CSV of ranges (DB-IP's "start,end,CC", IP2Location LITE's
// "from","to","CC","Country", by addresses or by their numbers), plain
// or gzipped. It reads them itself: nothing is fetched, nothing else is
// needed.
package geoip
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"math/big"
"net"
"os"
"sort"
"strings"
)
// Reader is a country database.
type Reader struct {
mmdb *mmdb
ranges []span // a CSV's, by start
}
// span is a CSV's range of addresses (as 16 bytes) and its country.
type span struct {
start, end [16]byte
code, name string
}
// maxFile is the largest database read (a City database is some 70 MB).
const maxFile = 512 << 20
// Open reads a database file.
func Open(path string) (*Reader, error) {
fi, err := os.Stat(path)
if err != nil {
return nil, err
}
if fi.Size() > maxFile {
return nil, fmt.Errorf("%s: bigger than %d MB", path, maxFile>>20)
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if bytes.HasPrefix(data, []byte{0x1f, 0x8b}) {
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
if data, err = io.ReadAll(io.LimitReader(zr, maxFile+1)); err != nil {
return nil, err
}
if len(data) > maxFile {
return nil, fmt.Errorf("%s: bigger than %d MB unpacked", path, maxFile>>20)
}
}
if bytes.Contains(data[max(0, len(data)-128<<10):], metaMarker) {
m, err := openMMDB(data)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return &Reader{mmdb: m}, nil
}
ranges, err := readCSV(data)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return &Reader{ranges: ranges}, nil
}
// Country is an address's country: its ISO 3166 code (upper case) and
// name in English; ok false if the database does not say.
func (r *Reader) Country(ip net.IP) (code, name string, ok bool) {
if r == nil || ip == nil {
return "", "", false
}
if r.mmdb != nil {
v, err := r.mmdb.lookup(ip)
if err != nil || v == nil {
return "", "", false
}
code, name = countryOf(v)
} else {
code, name = r.lookupCSV(ip)
}
code = strings.ToUpper(code)
if len(code) != 2 || code[0] < 'A' || code[0] > 'Z' || code[1] < 'A' || code[1] > 'Z' {
return "", "", false
}
if name == "" {
name = Names[code]
}
if name == "" {
name = code
}
return code, name, true
}
// countryOf is a record's country (or, without one, its registered
// country's): GeoIP2's and its likes' shape.
func countryOf(v any) (string, string) {
rec, _ := v.(map[string]any)
for _, key := range []string{"country", "registered_country"} {
c, _ := rec[key].(map[string]any)
code, _ := c["iso_code"].(string)
if code == "" {
continue
}
names, _ := c["names"].(map[string]any)
name, _ := names["en"].(string)
return code, name
}
// flat ones: {"country_code": "NZ", "country_name": "..."} (IPinfo's)
for _, key := range []string{"country_code", "country", "iso_code"} {
if code, _ := rec[key].(string); code != "" {
name, _ := rec["country_name"].(string)
return code, name
}
}
return "", ""
}
// Flag is a country's flag as an emoji: its code's two regional
// indicator symbols ("" for no code).
func Flag(code string) string {
if len(code) != 2 {
return ""
}
code = strings.ToUpper(code)
return string([]rune{0x1F1E6 + rune(code[0]-'A'), 0x1F1E6 + rune(code[1]-'A')})
}
// ---- MaxMind DB ----
var metaMarker = []byte("\xab\xcd\xefMaxMind.com")
type mmdb struct {
tree []byte
data []byte
nodeCount uint
recordSize uint
ipVersion uint
ipv4Start uint // the node the IPv4 addresses begin at, in an IPv6 tree
}
func openMMDB(b []byte) (*mmdb, error) {
at := bytes.LastIndex(b, metaMarker)
if at < 0 {
return nil, errors.New("not a MaxMind DB")
}
d := decoder{buf: b[at+len(metaMarker):]}
mv, _, err := d.decode(0, 0)
if err != nil {
return nil, fmt.Errorf("its metadata: %w", err)
}
meta, ok := mv.(map[string]any)
if !ok {
return nil, errors.New("its metadata is not a map")
}
num := func(k string) uint {
v, _ := meta[k].(uint64)
return uint(v)
}
m := &mmdb{nodeCount: num("node_count"), recordSize: num("record_size"), ipVersion: num("ip_version")}
if m.recordSize != 24 && m.recordSize != 28 && m.recordSize != 32 {
return nil, fmt.Errorf("a record size of %d", m.recordSize)
}
if m.ipVersion != 4 && m.ipVersion != 6 {
return nil, fmt.Errorf("IP version %d", m.ipVersion)
}
treeSize := m.nodeCount * m.recordSize / 4
if treeSize+16 > uint(at) || m.nodeCount == 0 {
return nil, errors.New("its search tree is bigger than it is")
}
m.tree = b[:treeSize]
m.data = b[treeSize+16 : at]
if m.ipVersion == 6 {
// IPv4 is ::a.b.c.d: 96 zero bits in
node := uint(0)
for i := 0; i < 96 && node < m.nodeCount; i++ {
node = m.record(node, 0)
}
m.ipv4Start = node
}
return m, nil
}
// record is a node's left (0) or right (1) record.
func (m *mmdb) record(node, bit uint) uint {
switch m.recordSize {
case 24:
o := node*6 + bit*3
b := m.tree[o : o+3]
return uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2])
case 28:
o := node * 7
b := m.tree[o : o+7]
if bit == 0 {
return uint(b[3]&0xf0)<<20 | uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2])
}
return uint(b[3]&0x0f)<<24 | uint(b[4])<<16 | uint(b[5])<<8 | uint(b[6])
default:
o := node*8 + bit*4
return uint(binary.BigEndian.Uint32(m.tree[o : o+4]))
}
}
func (m *mmdb) lookup(ip net.IP) (any, error) {
var bits []byte
node := uint(0)
if v4 := ip.To4(); v4 != nil {
bits = v4
if m.ipVersion == 6 {
node = m.ipv4Start
}
} else if m.ipVersion == 4 {
return nil, nil // an IPv4 database: no IPv6 in it
} else {
bits = ip.To16()
}
for i := 0; i < len(bits)*8 && node < m.nodeCount; i++ {
node = m.record(node, uint(bits[i/8]>>(7-i%8)&1))
}
switch {
case node == m.nodeCount:
return nil, nil // not there
case node < m.nodeCount:
return nil, errors.New("the search tree ends in a node")
}
off := node - m.nodeCount - 16
if off >= uint(len(m.data)) {
return nil, errors.New("a record past the data")
}
d := decoder{buf: m.data}
v, _, err := d.decode(off, 0)
return v, err
}
// decoder reads the MaxMind DB data section's values.
type decoder struct{ buf []byte }
var errData = errors.New("the data is broken")
const maxDepth = 32
// decode reads the value at off: it, and where the next begins.
func (d decoder) decode(off uint, depth int) (any, uint, error) {
if depth > maxDepth || off >= uint(len(d.buf)) {
return nil, 0, errData
}
ctrl := d.buf[off]
off++
typ := uint(ctrl >> 5)
if typ == 1 { // a pointer
ss, vvv := uint(ctrl>>3&3), uint(ctrl&7)
n := ss + 1
if off+n > uint(len(d.buf)) {
return nil, 0, errData
}
var p uint
switch ss {
case 0:
p = vvv<<8 | uint(d.buf[off])
case 1:
p = (vvv<<16 | uint(d.buf[off])<<8 | uint(d.buf[off+1])) + 2048
case 2:
p = (vvv<<24 | uint(d.buf[off])<<16 | uint(d.buf[off+1])<<8 | uint(d.buf[off+2])) + 526336
default:
p = uint(binary.BigEndian.Uint32(d.buf[off : off+4]))
}
v, _, err := d.decode(p, depth+1)
return v, off + n, err
}
if typ == 0 { // extended
if off >= uint(len(d.buf)) {
return nil, 0, errData
}
typ = 7 + uint(d.buf[off])
off++
}
size := uint(ctrl & 0x1f)
if size >= 29 {
n := size - 28
if off+n > uint(len(d.buf)) {
return nil, 0, errData
}
switch size {
case 29:
size = 29 + uint(d.buf[off])
case 30:
size = 285 + (uint(d.buf[off])<<8 | uint(d.buf[off+1]))
default:
size = 65821 + (uint(d.buf[off])<<16 | uint(d.buf[off+1])<<8 | uint(d.buf[off+2]))
}
off += n
}
bytesOf := func() ([]byte, error) {
if off+size > uint(len(d.buf)) {
return nil, errData
}
return d.buf[off : off+size], nil
}
switch typ {
case 2, 4: // a string, bytes
b, err := bytesOf()
if err != nil {
return nil, 0, err
}
if typ == 2 {
return string(b), off + size, nil
}
return append([]byte(nil), b...), off + size, nil
case 3, 15: // a double, a float
b, err := bytesOf()
if err != nil || (typ == 3 && size != 8) || (typ == 15 && size != 4) {
return nil, 0, errData
}
if typ == 3 {
return math.Float64frombits(binary.BigEndian.Uint64(b)), off + size, nil
}
return float64(math.Float32frombits(binary.BigEndian.Uint32(b))), off + size, nil
case 5, 6, 8, 9, 10: // unsigned (and signed 32) integers
b, err := bytesOf()
if err != nil || size > 16 {
return nil, 0, errData
}
var v uint64
for _, c := range b {
v = v<<8 | uint64(c)
}
return v, off + size, nil
case 7: // a map
m := make(map[string]any, min(size, 64))
for i := uint(0); i < size; i++ {
k, next, err := d.decode(off, depth+1)
if err != nil {
return nil, 0, err
}
ks, ok := k.(string)
if !ok {
return nil, 0, errData
}
v, next2, err := d.decode(next, depth+1)
if err != nil {
return nil, 0, err
}
m[ks] = v
off = next2
}
return m, off, nil
case 11: // an array
a := make([]any, 0, min(size, 64))
for i := uint(0); i < size; i++ {
v, next, err := d.decode(off, depth+1)
if err != nil {
return nil, 0, err
}
a = append(a, v)
off = next
}
return a, off, nil
case 14: // a boolean, in its size
return size != 0, off, nil
}
return nil, 0, fmt.Errorf("a value of type %d", typ)
}
// ---- CSV ----
// readCSV reads ranges: "start,end,CC[,name...]", by addresses or by
// their numbers, quoted or not; lines that are not are passed over.
func readCSV(b []byte) ([]span, error) {
var out []span
sc := bufio.NewScanner(bytes.NewReader(b))
sc.Buffer(make([]byte, 0, 4096), 1<<20)
for sc.Scan() {
f := strings.Split(sc.Text(), ",")
if len(f) < 3 {
continue
}
for i := range f {
f[i] = strings.Trim(strings.TrimSpace(f[i]), `"`)
}
start, ok1 := address(f[0])
end, ok2 := address(f[1])
if !ok1 || !ok2 || len(f[2]) != 2 || f[2] == "-" {
continue
}
sp := span{start: start, end: end, code: strings.ToUpper(f[2])}
if len(f) >= 4 && f[3] != "" && f[3] != "-" {
sp.name = strings.Join(f[3:], ",")
}
out = append(out, sp)
}
if err := sc.Err(); err != nil {
return nil, err
}
if len(out) == 0 {
return nil, errors.New("not a MaxMind DB, nor a CSV of ranges (start,end,country)")
}
sort.Slice(out, func(i, j int) bool { return bytes.Compare(out[i].start[:], out[j].start[:]) < 0 })
return out, nil
}
// address is an address, or an address's number (IPv4 under 2^32, else
// IPv6), as 16 bytes.
func address(s string) ([16]byte, bool) {
var a [16]byte
if ip := net.ParseIP(s); ip != nil {
copy(a[:], ip.To16())
return a, true
}
n, ok := new(big.Int).SetString(s, 10)
if !ok || n.Sign() < 0 || n.BitLen() > 128 {
return a, false
}
if n.BitLen() <= 32 && !strings.HasPrefix(s, "00") {
ip := net.IPv4(byte(n.Uint64()>>24), byte(n.Uint64()>>16), byte(n.Uint64()>>8), byte(n.Uint64()))
copy(a[:], ip.To16())
return a, true
}
n.FillBytes(a[:])
return a, true
}
func (r *Reader) lookupCSV(ip net.IP) (string, string) {
var a [16]byte
copy(a[:], ip.To16())
i := sort.Search(len(r.ranges), func(i int) bool { return bytes.Compare(r.ranges[i].start[:], a[:]) > 0 })
if i == 0 {
return "", ""
}
sp := r.ranges[i-1]
if bytes.Compare(a[:], sp.end[:]) > 0 {
return "", ""
}
return sp.code, sp.name
}
+125
View File
@@ -0,0 +1,125 @@
package geoip
import (
"bytes"
"compress/gzip"
"net"
"os"
"path/filepath"
"testing"
)
// The test databases were made by MaxMind's own writer (mmdbwriter), in
// each record size.
var cases = []struct{ ip, code, name string }{
{"203.0.113.7", "NZ", "New Zealand"},
{"198.51.100.200", "DE", "Germany"},
{"192.0.2.5", "JP", "Japan"},
{"192.0.2.200", "", ""}, // the /25 ends before it
{"2001:db8::1", "FR", "France"},
{"2001:db9::1", "", ""},
{"81.2.69.160", "GB", "United Kingdom"},
{"::ffff:81.2.69.160", "GB", "United Kingdom"},
{"100.64.1.1", "US", "United States"}, // a registered country alone
{"8.8.8.8", "", ""},
}
func TestMMDB(t *testing.T) {
for _, rs := range []string{"24", "28", "32"} {
r, err := Open(filepath.Join("testdata", "test-"+rs+".mmdb"))
if err != nil {
t.Fatalf("%s: %v", rs, err)
}
for _, c := range cases {
code, name, ok := r.Country(net.ParseIP(c.ip))
if code != c.code || name != c.name || ok != (c.code != "") {
t.Errorf("%s bits, %s: %q %q %v", rs, c.ip, code, name, ok)
}
}
}
}
func TestBroken(t *testing.T) {
good, _ := os.ReadFile(filepath.Join("testdata", "test-24.mmdb"))
dir := t.TempDir()
// every cut, and every byte of the data turned: no panic
for i := 0; i < len(good); i += 7 {
for _, b := range [][]byte{good[:i], flip(good, i)} {
p := filepath.Join(dir, "x.mmdb")
os.WriteFile(p, b, 0600)
if r, err := Open(p); err == nil {
for _, c := range cases {
r.Country(net.ParseIP(c.ip))
}
}
}
}
}
func flip(b []byte, i int) []byte {
c := append([]byte{}, b...)
c[i] ^= 0xff
return c
}
func TestCSV(t *testing.T) {
dir := t.TempDir()
dbip := "1.0.0.0,1.0.0.255,AU\n203.0.113.0,203.0.113.255,NZ\n2001:db8::,2001:db8:ffff:ffff:ffff:ffff:ffff:ffff,FR\n"
ip2l := "\"16777216\",\"16777471\",\"AU\",\"Australia\"\n\"3405803776\",\"3405804031\",\"NZ\",\"New Zealand (Aotearoa)\"\n" +
"\"0\",\"16777215\",\"-\",\"-\"\n"
var gz bytes.Buffer
zw := gzip.NewWriter(&gz)
zw.Write([]byte(dbip))
zw.Close()
for name, data := range map[string][]byte{"dbip.csv": []byte(dbip), "ip2l.csv": []byte(ip2l), "dbip.csv.gz": gz.Bytes()} {
p := filepath.Join(dir, name)
os.WriteFile(p, data, 0600)
r, err := Open(p)
if err != nil {
t.Fatalf("%s: %v", name, err)
}
code, cname, ok := r.Country(net.ParseIP("203.0.113.9"))
want := "New Zealand"
if name == "ip2l.csv" {
want = "New Zealand (Aotearoa)"
}
if code != "NZ" || cname != want || !ok {
t.Errorf("%s: %q %q %v", name, code, cname, ok)
}
if code, _, _ := r.Country(net.ParseIP("1.0.0.1")); code != "AU" {
t.Errorf("%s: 1.0.0.1 %q", name, code)
}
if _, _, ok := r.Country(net.ParseIP("9.9.9.9")); ok {
t.Errorf("%s: 9.9.9.9 found", name)
}
if _, _, ok := r.Country(net.ParseIP("0.1.2.3")); ok {
t.Errorf("%s: a range of no country found", name)
}
}
if code, _, _ := mustOpen(t, dir, "dbip.csv").Country(net.ParseIP("2001:db8::5")); code != "FR" {
t.Errorf("IPv6: %q", code)
}
p := filepath.Join(dir, "junk.txt")
os.WriteFile(p, []byte("hello\nworld\n"), 0600)
if _, err := Open(p); err == nil {
t.Error("junk opened")
}
}
func mustOpen(t *testing.T, dir, name string) *Reader {
r, err := Open(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
return r
}
func TestFlag(t *testing.T) {
if Flag("nz") != "\U0001F1F3\U0001F1FF" || Flag("") != "" {
t.Errorf("%q", Flag("nz"))
}
var r *Reader
if _, _, ok := r.Country(net.ParseIP("1.2.3.4")); ok {
t.Error("a nil reader found a country")
}
}
+258
View File
@@ -0,0 +1,258 @@
package geoip
// Names are the countries' names in English, by their ISO 3166-1 codes
// (from the iso-codes project's list; common names where it has them):
// for databases that give codes alone.
var Names = map[string]string{
"AD": "Andorra",
"AE": "United Arab Emirates",
"AF": "Afghanistan",
"AG": "Antigua and Barbuda",
"AI": "Anguilla",
"AL": "Albania",
"AM": "Armenia",
"AO": "Angola",
"AQ": "Antarctica",
"AR": "Argentina",
"AS": "American Samoa",
"AT": "Austria",
"AU": "Australia",
"AW": "Aruba",
"AX": "Åland Islands",
"AZ": "Azerbaijan",
"BA": "Bosnia and Herzegovina",
"BB": "Barbados",
"BD": "Bangladesh",
"BE": "Belgium",
"BF": "Burkina Faso",
"BG": "Bulgaria",
"BH": "Bahrain",
"BI": "Burundi",
"BJ": "Benin",
"BL": "Saint Barthélemy",
"BM": "Bermuda",
"BN": "Brunei Darussalam",
"BO": "Bolivia",
"BQ": "Bonaire, Sint Eustatius and Saba",
"BR": "Brazil",
"BS": "Bahamas",
"BT": "Bhutan",
"BV": "Bouvet Island",
"BW": "Botswana",
"BY": "Belarus",
"BZ": "Belize",
"CA": "Canada",
"CC": "Cocos (Keeling) Islands",
"CD": "Congo, The Democratic Republic of the",
"CF": "Central African Republic",
"CG": "Congo",
"CH": "Switzerland",
"CI": "Côte d'Ivoire",
"CK": "Cook Islands",
"CL": "Chile",
"CM": "Cameroon",
"CN": "China",
"CO": "Colombia",
"CR": "Costa Rica",
"CU": "Cuba",
"CV": "Cabo Verde",
"CW": "Curaçao",
"CX": "Christmas Island",
"CY": "Cyprus",
"CZ": "Czechia",
"DE": "Germany",
"DJ": "Djibouti",
"DK": "Denmark",
"DM": "Dominica",
"DO": "Dominican Republic",
"DZ": "Algeria",
"EC": "Ecuador",
"EE": "Estonia",
"EG": "Egypt",
"EH": "Western Sahara",
"ER": "Eritrea",
"ES": "Spain",
"ET": "Ethiopia",
"FI": "Finland",
"FJ": "Fiji",
"FK": "Falkland Islands (Malvinas)",
"FM": "Micronesia, Federated States of",
"FO": "Faroe Islands",
"FR": "France",
"GA": "Gabon",
"GB": "United Kingdom",
"GD": "Grenada",
"GE": "Georgia",
"GF": "French Guiana",
"GG": "Guernsey",
"GH": "Ghana",
"GI": "Gibraltar",
"GL": "Greenland",
"GM": "Gambia",
"GN": "Guinea",
"GP": "Guadeloupe",
"GQ": "Equatorial Guinea",
"GR": "Greece",
"GS": "South Georgia and the South Sandwich Islands",
"GT": "Guatemala",
"GU": "Guam",
"GW": "Guinea-Bissau",
"GY": "Guyana",
"HK": "Hong Kong",
"HM": "Heard Island and McDonald Islands",
"HN": "Honduras",
"HR": "Croatia",
"HT": "Haiti",
"HU": "Hungary",
"ID": "Indonesia",
"IE": "Ireland",
"IL": "Israel",
"IM": "Isle of Man",
"IN": "India",
"IO": "British Indian Ocean Territory",
"IQ": "Iraq",
"IR": "Iran",
"IS": "Iceland",
"IT": "Italy",
"JE": "Jersey",
"JM": "Jamaica",
"JO": "Jordan",
"JP": "Japan",
"KE": "Kenya",
"KG": "Kyrgyzstan",
"KH": "Cambodia",
"KI": "Kiribati",
"KM": "Comoros",
"KN": "Saint Kitts and Nevis",
"KP": "North Korea",
"KR": "South Korea",
"KW": "Kuwait",
"KY": "Cayman Islands",
"KZ": "Kazakhstan",
"LA": "Laos",
"LB": "Lebanon",
"LC": "Saint Lucia",
"LI": "Liechtenstein",
"LK": "Sri Lanka",
"LR": "Liberia",
"LS": "Lesotho",
"LT": "Lithuania",
"LU": "Luxembourg",
"LV": "Latvia",
"LY": "Libya",
"MA": "Morocco",
"MC": "Monaco",
"MD": "Moldova",
"ME": "Montenegro",
"MF": "Saint Martin (French part)",
"MG": "Madagascar",
"MH": "Marshall Islands",
"MK": "North Macedonia",
"ML": "Mali",
"MM": "Myanmar",
"MN": "Mongolia",
"MO": "Macao",
"MP": "Northern Mariana Islands",
"MQ": "Martinique",
"MR": "Mauritania",
"MS": "Montserrat",
"MT": "Malta",
"MU": "Mauritius",
"MV": "Maldives",
"MW": "Malawi",
"MX": "Mexico",
"MY": "Malaysia",
"MZ": "Mozambique",
"NA": "Namibia",
"NC": "New Caledonia",
"NE": "Niger",
"NF": "Norfolk Island",
"NG": "Nigeria",
"NI": "Nicaragua",
"NL": "Netherlands",
"NO": "Norway",
"NP": "Nepal",
"NR": "Nauru",
"NU": "Niue",
"NZ": "New Zealand",
"OM": "Oman",
"PA": "Panama",
"PE": "Peru",
"PF": "French Polynesia",
"PG": "Papua New Guinea",
"PH": "Philippines",
"PK": "Pakistan",
"PL": "Poland",
"PM": "Saint Pierre and Miquelon",
"PN": "Pitcairn",
"PR": "Puerto Rico",
"PS": "Palestine, State of",
"PT": "Portugal",
"PW": "Palau",
"PY": "Paraguay",
"QA": "Qatar",
"RE": "Réunion",
"RO": "Romania",
"RS": "Serbia",
"RU": "Russian Federation",
"RW": "Rwanda",
"SA": "Saudi Arabia",
"SB": "Solomon Islands",
"SC": "Seychelles",
"SD": "Sudan",
"SE": "Sweden",
"SG": "Singapore",
"SH": "Saint Helena, Ascension and Tristan da Cunha",
"SI": "Slovenia",
"SJ": "Svalbard and Jan Mayen",
"SK": "Slovakia",
"SL": "Sierra Leone",
"SM": "San Marino",
"SN": "Senegal",
"SO": "Somalia",
"SR": "Suriname",
"SS": "South Sudan",
"ST": "Sao Tome and Principe",
"SV": "El Salvador",
"SX": "Sint Maarten (Dutch part)",
"SY": "Syria",
"SZ": "Eswatini",
"TC": "Turks and Caicos Islands",
"TD": "Chad",
"TF": "French Southern Territories",
"TG": "Togo",
"TH": "Thailand",
"TJ": "Tajikistan",
"TK": "Tokelau",
"TL": "Timor-Leste",
"TM": "Turkmenistan",
"TN": "Tunisia",
"TO": "Tonga",
"TR": "Türkiye",
"TT": "Trinidad and Tobago",
"TV": "Tuvalu",
"TW": "Taiwan",
"TZ": "Tanzania",
"UA": "Ukraine",
"UG": "Uganda",
"UM": "United States Minor Outlying Islands",
"US": "United States",
"UY": "Uruguay",
"UZ": "Uzbekistan",
"VA": "Holy See (Vatican City State)",
"VC": "Saint Vincent and the Grenadines",
"VE": "Venezuela",
"VG": "Virgin Islands, British",
"VI": "Virgin Islands, U.S.",
"VN": "Vietnam",
"VU": "Vanuatu",
"WF": "Wallis and Futuna",
"WS": "Samoa",
"YE": "Yemen",
"YT": "Mayotte",
"ZA": "South Africa",
"ZM": "Zambia",
"ZW": "Zimbabwe",
"EU": "European Union",
"XK": "Kosovo",
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.
+9 -2
View File
@@ -42,6 +42,9 @@ type apiPost struct {
DrawMS int64 `json:"draw_ms,omitempty"` // how long it took to draw
Member int `json:"member,omitempty"` // posted by a signed-in user of the BBS
Account string `json:"account,omitempty"` // their account's name, if they signed with it
ID string `json:"id,omitempty"`
Country string `json:"country,omitempty"`
CountryName string `json:"country_name,omitempty"`
Spoiler int `json:"spoiler,omitempty"`
Replies *int `json:"replies,omitempty"`
Images *int `json:"images,omitempty"`
@@ -80,7 +83,8 @@ 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),
Member: flag(p.UserID != 0), Account: p.Account}
Member: flag(p.UserID != 0), Account: p.Account, ID: p.PosterID, Country: p.Country,
CountryName: p.CountryName}
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
@@ -144,6 +148,8 @@ func (s *Server) boardsJSON(q *req) {
ForcedAnon int `json:"forced_anon,omitempty"`
TextOnly int `json:"text_only,omitempty"`
Oekaki int `json:"oekaki,omitempty"`
UserIDs int `json:"user_ids,omitempty"`
CountryFlags int `json:"country_flags,omitempty"`
Login string `json:"login,omitempty"` // "post": only users post; "all": only users see it
Captcha int `json:"captcha,omitempty"` // those not signed in answer a captcha
Spoilers int `json:"spoilers"`
@@ -158,7 +164,8 @@ func (s *Server) boardsJSON(q *req) {
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), Oekaki: flag(b.Oekaki), Login: loginOf(b), Captcha: flag(s.captchaOn(b)), Spoilers: 1, CodeTags: 1})
TextOnly: flag(b.TextOnly), Oekaki: flag(b.Oekaki), UserIDs: flag(b.PosterIDs),
CountryFlags: flag(b.Flags && s.S.GeoIP != ""), Login: loginOf(b), Captcha: flag(s.captchaOn(b)), Spoilers: 1, CodeTags: 1})
}
q.json(out)
}
+80
View File
@@ -0,0 +1,80 @@
package imageboard
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"hash/fnv"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/geoip"
)
// Poster IDs and country flags, on the boards that have them.
// posterID is a poster's ID in a thread: eight characters of a keyed hash
// of their address, the board and the thread, as 4chan's: the same all
// through a thread, another in the next, and nothing of the address to be
// had from it.
func (s *Server) posterID(addr, dir string, thread int64) string {
m := hmac.New(sha256.New, s.key)
m.Write([]byte("id\x00" + addr + "\x00" + dir + "\x00" + strconv.FormatInt(thread, 10)))
return base64.StdEncoding.EncodeToString(m.Sum(nil)[:6])
}
// idColors are how many colours IDs are shown in (idc-0 ... in chan.css).
const idColors = 24
// idClass is an ID's colour's class: the same ID, the same colour.
func idClass(id string) string {
h := fnv.New32a()
h.Write([]byte(id))
return "idc-" + strconv.Itoa(int(h.Sum32()%idColors))
}
// geo is the country database, read again when its file changes (looked
// at once a minute at most).
type geo struct {
mu sync.Mutex
reader atomic.Pointer[geoip.Reader]
stamp time.Time // the file's, when read
checked time.Time
}
// country is an address's country (code, name), if the boards have a
// database and it says.
func (s *Server) country(addr string) (string, string) {
ip := net.ParseIP(addr)
if s.S.GeoIP == "" || ip == nil {
return "", ""
}
g := &s.geo
g.mu.Lock()
if time.Since(g.checked) > time.Minute {
g.checked = time.Now()
if fi, err := os.Stat(s.S.GeoIP); err == nil && !fi.ModTime().Equal(g.stamp) {
r, err := geoip.Open(s.S.GeoIP)
if err != nil {
s.B.Log.Printf("chan: the country database: %v", err)
} else {
g.reader.Store(r)
g.stamp = fi.ModTime()
}
}
}
g.mu.Unlock()
code, name, ok := g.reader.Load().Country(ip)
if !ok {
return "", ""
}
return code, name
}
// flagOf is a code's flag, for the templates.
func flagOf(code string) string { return geoip.Flag(strings.ToUpper(code)) }
+80
View File
@@ -0,0 +1,80 @@
package imageboard
import (
"strings"
"testing"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// TestIDsAndFlags: a poster's ID, the same through a thread and another
// in the next; their country's flag from the database.
func TestIDsAndFlags(t *testing.T) {
s := setup(t)
s.srv.S.GeoIP = "../geoip/testdata/test-24.mmdb"
s.bd.PosterIDs, s.bd.Flags, s.bd.TextOnly = true, true, true
s.b.Store.UpdateBoard(s.bd)
post := func(ip string, thread int64, com string) *store.BoardPost {
t.Helper()
p, err := s.srv.Submit(&Submission{Board: s.bd, Thread: thread, IP: ip, Comment: com})
if err != nil {
t.Fatal(err)
}
got, _ := s.b.Store.ChanPost(s.bd.ID, p.No)
return got
}
op := post("203.0.113.7", 0, "first")
same := post("203.0.113.7", 1, "me again")
other := post("198.51.100.9", 1, "someone else")
unknown := post("8.8.8.8", 1, "from nowhere known")
member := post("bbs:alice", 1, "a terminal's")
next := post("203.0.113.7", 0, "a new thread")
if op.PosterID == "" || op.PosterID != s.srv.posterID("203.0.113.7", "b", 1) || same.PosterID != op.PosterID ||
other.PosterID == op.PosterID || next.PosterID == op.PosterID || len(op.PosterID) != 8 || member.PosterID == "" {
t.Errorf("IDs: %q %q %q %q %q", op.PosterID, same.PosterID, other.PosterID, next.PosterID, member.PosterID)
}
if op.Country != "NZ" || op.CountryName != "New Zealand" || other.Country != "DE" || unknown.Country != "" ||
member.Country != "" {
t.Errorf("countries: %q %q %q %q", op.Country, other.Country, unknown.Country, member.Country)
}
br := s.browser()
_, _, body := br.get("/chan/b/thread/1")
for _, want := range []string{`data-id="` + op.PosterID + `"`,
`(ID: <span class="hand ` + idClass(op.PosterID) + `" data-id="` + op.PosterID + `" title="2 posts by this ID; click to highlight them">`,
`<span class="flag" title="New Zealand">` + "\U0001F1F3\U0001F1FF" + `</span>`,
`<span class="flag" title="Germany">`} {
if !strings.Contains(body, want) {
t.Errorf("no %s", want)
}
}
var thread struct {
Posts []apiPost `json:"posts"`
}
getJSON(t, s.ts.URL+"/chan/b/thread/1.json", &thread)
if thread.Posts[0].ID != op.PosterID || thread.Posts[0].Country != "NZ" || thread.Posts[0].CountryName != "New Zealand" ||
thread.Posts[3].Country != "" {
t.Errorf("json: %+v", thread.Posts[0])
}
var boards struct {
Boards []map[string]any `json:"boards"`
}
getJSON(t, s.ts.URL+"/chan/boards.json", &boards)
if boards.Boards[0]["user_ids"] != float64(1) || boards.Boards[0]["country_flags"] != float64(1) {
t.Errorf("boards.json: %v", boards.Boards[0])
}
// off again: no more of either
s.bd.PosterIDs, s.bd.Flags = false, false
s.b.Store.UpdateBoard(s.bd)
if p := post("203.0.113.7", 1, "plain"); p.PosterID != "" || p.Country != "" {
t.Errorf("off: %+v", p)
}
// without a database: IDs, no flags
s.srv.S.GeoIP = ""
s.bd.PosterIDs, s.bd.Flags = true, true
s.b.Store.UpdateBoard(s.bd)
if p := post("198.51.100.9", 1, "x"); p.PosterID == "" || p.Country != "" {
t.Errorf("no database: %+v", p)
}
}
+3 -1
View File
@@ -61,7 +61,8 @@ type Settings struct {
CaptchaLength int
CaptchaTTL time.Duration
CaptchaLevel string
Options bool // the post form has an Options line (sage, nonoko; a board may say otherwise)
Options bool // the post form has an Options line (sage, nonoko; a board may say otherwise)
GeoIP string // the country database (geoip.Open's: .mmdb, or a CSV of ranges), for flags
}
// Defaults are the settings unless bbs.conf says otherwise.
@@ -111,6 +112,7 @@ type Server struct {
once sync.Once
initErr error
captchas captchas
geo geo
}
const (
+18
View File
@@ -18,6 +18,8 @@ var funcs = template.FuncMap{
"add": func(a, b int) int { return a + b },
"short": shortName,
"dur": drawTime,
"flag": flagOf,
"idc": idClass,
"seq": func(n int) []int {
out := make([]int, n)
for i := range out {
@@ -77,6 +79,7 @@ type postView struct {
Staff bool // the viewer may moderate it
Index bool // shown on a board's index (a thread's first gets [Reply])
Draw bool // its board is an oekaki board: its drawing can be drawn over
IDCount int // the posts by its poster's ID in the thread (on a thread's page)
}
// threadView is a thread as a board's index or its own page shows it.
@@ -271,12 +274,27 @@ func (q *req) threadViews(b *store.Board, ops []*store.BoardPost, here int64) ([
tv.OmittedImages = op.Images - images
if here != 0 {
backlinks(tv)
idCounts(tv)
}
out = append(out, tv)
}
return out, nil
}
// idCounts are, for each post, how many in the thread are by its ID.
func idCounts(tv *threadView) {
posts := append([]*postView{tv.OP}, tv.Replies...)
n := map[string]int{}
for _, p := range posts {
if p.PosterID != "" {
n[p.PosterID]++
}
}
for _, p := range posts {
p.IDCount = n[p.PosterID]
}
}
// backlinks are, under each post's number, the posts in the thread that
// quote it.
func backlinks(tv *threadView) {
+13
View File
@@ -163,6 +163,12 @@ func (s *Server) Submit(sub *Submission) (*store.BoardPost, error) {
if sub.Password != "" {
p.Password = s.mac("pw", sub.Password)
}
if b.Flags {
p.Country, p.CountryName = s.country(sub.IP)
}
if b.PosterIDs && sub.Thread != 0 {
p.PosterID = s.posterID(sub.IP, b.Dir, sub.Thread)
}
p.Comment = cleanComment(sub.Comment)
if n := utf8.RuneCountInString(p.Comment); n > s.S.MaxComment {
return nil, refuse(http.StatusBadRequest, "Your comment is too long: %d characters, at most %d.", n, s.S.MaxComment)
@@ -229,6 +235,13 @@ func (s *Server) Submit(sub *Submission) (*store.BoardPost, error) {
s.B.Log.Printf("chan: /%s/: posting: %v", b.Dir, err)
return nil, refuse(http.StatusInternalServerError, "The post could not be made: try again later.")
}
if b.PosterIDs && sub.Thread == 0 {
// a thread's first post: its ID is of the thread it begins
p.PosterID = s.posterID(sub.IP, b.Dir, p.No)
if err := s.B.Store.SetChanPosterID(b.ID, p.No, p.PosterID); err != nil {
s.B.Log.Printf("chan: /%s/%d: its ID: %v", b.Dir, p.No, err)
}
}
if sub.Thread == 0 {
gone, err := s.B.Store.PruneChanThreads(b.ID, b.Pages*b.PerPage)
if err != nil {
+28
View File
@@ -138,3 +138,31 @@ table.postForm input[name=captcha] { width: 150px; text-transform: uppercase; }
.memberMark { font-size: 9pt; font-weight: bold; color: #2a8a2a; cursor: help; }
.memberMark.signed { color: #2060c0; }
.name.account { text-decoration: underline dotted; }
/* poster IDs: a colour each, by its hash (idClass) */
.posteruid .hand { padding: 0 5px; border-radius: 6px; font-size: 0.8em; cursor: pointer; }
.flag { font-size: 1.1em; cursor: help; }
.post.op.highlight { outline: 2px dashed #888; outline-offset: 2px; }
.idc-0 { background: hsl(0, 65%, 45%); color: #fff; }
.idc-1 { background: hsl(15, 65%, 45%); color: #fff; }
.idc-2 { background: hsl(30, 65%, 45%); color: #fff; }
.idc-3 { background: hsl(45, 65%, 40%); color: #fff; }
.idc-4 { background: hsl(60, 65%, 40%); color: #fff; }
.idc-5 { background: hsl(75, 65%, 40%); color: #fff; }
.idc-6 { background: hsl(90, 65%, 40%); color: #fff; }
.idc-7 { background: hsl(105, 65%, 40%); color: #fff; }
.idc-8 { background: hsl(120, 65%, 40%); color: #fff; }
.idc-9 { background: hsl(135, 65%, 40%); color: #fff; }
.idc-10 { background: hsl(150, 65%, 40%); color: #fff; }
.idc-11 { background: hsl(165, 65%, 40%); color: #fff; }
.idc-12 { background: hsl(180, 65%, 40%); color: #fff; }
.idc-13 { background: hsl(195, 65%, 40%); color: #fff; }
.idc-14 { background: hsl(210, 65%, 45%); color: #fff; }
.idc-15 { background: hsl(225, 65%, 45%); color: #fff; }
.idc-16 { background: hsl(240, 65%, 45%); color: #fff; }
.idc-17 { background: hsl(255, 65%, 45%); color: #fff; }
.idc-18 { background: hsl(270, 65%, 45%); color: #fff; }
.idc-19 { background: hsl(285, 65%, 45%); color: #fff; }
.idc-20 { background: hsl(300, 65%, 45%); color: #fff; }
.idc-21 { background: hsl(315, 65%, 45%); color: #fff; }
.idc-22 { background: hsl(330, 65%, 45%); color: #fff; }
.idc-23 { background: hsl(345, 65%, 45%); color: #fff; }
+12
View File
@@ -79,6 +79,18 @@
if (a) hide();
});
// a poster's ID: their posts in the thread highlighted, or not again
document.addEventListener("click", function (e) {
var h = e.target.closest ? e.target.closest(".posteruid .hand") : null;
if (!h) return;
var posts = document.querySelectorAll('.post[data-id="' + CSS.escape(h.dataset.id) + '"]');
var on = !(posts.length && posts[0].classList.contains("idHighlight"));
document.querySelectorAll(".post.idHighlight").forEach(function (p) {
p.classList.remove("idHighlight", "highlight");
});
if (on) posts.forEach(function (p) { p.classList.add("idHighlight", "highlight"); });
});
// a captcha that cannot be read: another
document.querySelectorAll(".captchaNew").forEach(function (b) {
b.addEventListener("click", function () {
+2 -2
View File
@@ -46,12 +46,12 @@
{{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}}">
<div id="p{{.No}}" class="post {{if .OP}}op{{else}}reply{{end}}"{{with .PosterID}} data-id="{{.}}"{{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{{if .Account}} account{{end}}">{{.Name}}</span>{{with .Trip}} <span class="postertrip">{{.}}</span>{{end}}{{if .Email}}</a>{{end}}{{if .Account}} <span class="memberMark signed" title="Signed: {{.Account}}, a user of this BBS">&#10003;</span>{{else if .UserID}} <span class="memberMark" title="Posted by a signed-in user of this BBS">&#10003;</span>{{end}}{{with .Capcode}} <strong class="capcode">## {{if eq . "admin"}}Admin{{else}}Mod{{end}}</strong>{{end}}</span>
<span class="nameBlock{{with .Capcode}} capcode-{{.}}{{end}}">{{if .Email}}<a href="mailto:{{.Email}}" class="useremail">{{end}}<span class="name{{if .Account}} account{{end}}">{{.Name}}</span>{{with .Trip}} <span class="postertrip">{{.}}</span>{{end}}{{if .Email}}</a>{{end}}{{if .Account}} <span class="memberMark signed" title="Signed: {{.Account}}, a user of this BBS">&#10003;</span>{{else if .UserID}} <span class="memberMark" title="Posted by a signed-in user of this BBS">&#10003;</span>{{end}}{{with .Capcode}} <strong class="capcode">## {{if eq . "admin"}}Admin{{else}}Mod{{end}}</strong>{{end}}{{with .PosterID}} <span class="posteruid">(ID: <span class="hand {{idc .}}" data-id="{{.}}" title="{{if $.IDCount}}{{$.IDCount}} {{if eq $.IDCount 1}}post{{else}}posts{{end}} by this ID; {{end}}click to highlight them">{{.}}</span>)</span>{{end}}{{with .Country}} <span class="flag" title="{{$.CountryName}}">{{flag .}}</span>{{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}}
+6
View File
@@ -2,6 +2,7 @@ package server
import (
"fmt"
"os"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/config"
@@ -47,6 +48,11 @@ func (c *Config) chanSection(s *config.Section) error {
if ch.Options, err = s.Bool("options", ch.Options); err != nil {
return err
}
if ch.GeoIP = s.String("geoip", ""); ch.GeoIP != "" {
if _, err := os.Stat(ch.GeoIP); err != nil {
c.Warnings = append(c.Warnings, fmt.Sprintf("[chan] geoip: %v: no flags until it is there", err))
}
}
if ch.Style = s.String("style", ""); ch.Style != "" && !imageboard.KnownStyle(ch.Style) {
var names []string
for _, st := range imageboard.Styles {
+43 -29
View File
@@ -28,6 +28,8 @@ type Board struct {
LoginToRead bool // only the BBS's users see it at all (and so post)
Captcha string // those not signed in answer a captcha: "yes", "no", "" as [chan] says
Options string // the post form's Options line: "yes", "no", "" as [chan] says
PosterIDs bool // each poster has an ID in a thread
Flags bool // posts show their country's flag
Mods string
Sort int
LastNo int64
@@ -37,24 +39,27 @@ type Board struct {
// 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): marked as a member's
Account string // the poster's account name, if they signed with it
Created time.Time
Bumped time.Time
Sticky bool
Closed bool
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): marked as a member's
Account string // the poster's account name, if they signed with it
PosterID string // the poster's ID in the thread ("": the board has none)
Country string // the poster's country's ISO code ("": not known, or no flags)
CountryName string
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"
@@ -100,14 +105,14 @@ type Report struct {
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, oekaki,
login_to_read, captcha, options`
login_to_read, captcha, options, poster_ids, flags`
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, &b.Oekaki, &b.LoginToRead, &b.Captcha, &b.Options)
&b.Mods, &b.Sort, &b.LastNo, &created, &b.Oekaki, &b.LoginToRead, &b.Captcha, &b.Options, &b.PosterIDs, &b.Flags)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -120,10 +125,10 @@ func scanBoard(row interface{ Scan(...any) error }) (*Board, error) {
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, oekaki,
login_to_read, captcha, options)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, b.Dir, b.Title, b.Description, b.MaxFile, b.Pages,
login_to_read, captcha, options, poster_ids, flags)
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(), b.Oekaki, b.LoginToRead, b.Captcha, b.Options)
b.TextOnly, b.Mods, b.Sort, now(), b.Oekaki, b.LoginToRead, b.Captcha, b.Options, b.PosterIDs, b.Flags)
if err != nil {
if isUnique(err) {
return nil, ErrExists
@@ -137,9 +142,10 @@ func (s *Store) CreateBoard(b *Board) (*Board, error) {
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 = ?, oekaki = ?, login_to_read = ?, captcha = ?, options = ? WHERE id = ?`, b.Title, b.Description, b.MaxFile, b.Pages, b.PerPage,
text_only = ?, mods = ?, sort = ?, oekaki = ?, login_to_read = ?, captcha = ?, options = ?,
poster_ids = ?, flags = ? 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.Oekaki, b.LoginToRead, b.Captcha, b.Options, b.ID)
b.Mods, b.Sort, b.Oekaki, b.LoginToRead, b.Captcha, b.Options, b.PosterIDs, b.Flags, b.ID)
return err
}
@@ -189,14 +195,14 @@ func (s *Store) Boards() ([]*Board, error) {
}
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, replay, draw_ms, account`
bumped, sticky, closed, file_name, ext, tim, file_size, w, h, tn_w, tn_h, md5, spoiler, file_deleted, banned, replay, draw_ms, account, poster_id, country, country_name`
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, &p.Replay, &p.DrawMS, &p.Account}
&p.FileSize, &p.W, &p.H, &p.TnW, &p.TnH, &p.MD5, &p.Spoiler, &p.FileDeleted, &p.Banned, &p.Replay, &p.DrawMS, &p.Account, &p.PosterID, &p.Country, &p.CountryName}
err := row.Scan(append(dest, more...)...)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -253,10 +259,11 @@ func (s *Store) AddPost(p *BoardPost, bump bool) error {
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, replay, draw_ms, account) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
spoiler, replay, draw_ms, account, poster_id, country, country_name)
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, p.Replay, p.DrawMS, p.Account); err != nil {
p.Spoiler, p.Replay, p.DrawMS, p.Account, p.PosterID, p.Country, p.CountryName); err != nil {
return err
}
if p.Thread != 0 && bump {
@@ -452,6 +459,13 @@ func (s *Store) DeleteChanFile(board, no int64) error {
return err
}
// SetChanPosterID gives a post its poster's ID (a thread's first post's
// is known only once it has its number).
func (s *Store) SetChanPosterID(board, no int64, id string) error {
_, err := s.db.Exec(`UPDATE chan_posts SET poster_id = ? WHERE board_id = ? AND num = ?`, id, 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)
+12 -2
View File
@@ -248,7 +248,9 @@ CREATE TABLE IF NOT EXISTS chan_boards (
oekaki {bool} NOT NULL DEFAULT FALSE,
login_to_read {bool} NOT NULL DEFAULT FALSE,
captcha {str} NOT NULL DEFAULT '',
options {str} NOT NULL DEFAULT ''
options {str} NOT NULL DEFAULT '',
poster_ids {bool} NOT NULL DEFAULT FALSE,
flags {bool} NOT NULL DEFAULT FALSE
)`, `
CREATE TABLE IF NOT EXISTS chan_posts (
id {id},
@@ -282,7 +284,10 @@ CREATE TABLE IF NOT EXISTS chan_posts (
banned {bool} NOT NULL DEFAULT FALSE,
replay {bool} NOT NULL DEFAULT FALSE,
draw_ms {int} NOT NULL DEFAULT 0,
account {str} NOT NULL DEFAULT ''
account {str} NOT NULL DEFAULT '',
poster_id {key} NOT NULL DEFAULT '',
country {str} NOT NULL DEFAULT '',
country_name {str} NOT NULL DEFAULT ''
)`, `
CREATE TABLE IF NOT EXISTS chan_bans (
id {id},
@@ -375,6 +380,11 @@ var added = []struct{ table, column, decl string }{
{"chan_boards", "login_to_read", "{bool} NOT NULL DEFAULT FALSE"},
{"chan_boards", "captcha", "{str} NOT NULL DEFAULT ''"},
{"chan_boards", "options", "{str} NOT NULL DEFAULT ''"},
{"chan_boards", "poster_ids", "{bool} NOT NULL DEFAULT FALSE"},
{"chan_boards", "flags", "{bool} NOT NULL DEFAULT FALSE"},
{"chan_posts", "poster_id", "{key} NOT NULL DEFAULT ''"},
{"chan_posts", "country", "{str} NOT NULL DEFAULT ''"},
{"chan_posts", "country_name", "{str} NOT NULL DEFAULT ''"},
}
// migrate makes the schema, or brings an older database up to it.