From 6ea47bb1792014e7017873303d441b68dacf6c34 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 04:20:29 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr --- bbs.conf.sample | 4 + cmd/bbs/chan.go | 14 +- cmd/bbs/main.go | 1 + docs/wiki/Image-Boards.md | 37 +- internal/app/chan.go | 6 + internal/geoip/geoip.go | 447 ++++++++++++++++++++++ internal/geoip/geoip_test.go | 125 ++++++ internal/geoip/names.go | 258 +++++++++++++ internal/geoip/testdata/test-24.mmdb | Bin 0 -> 1985 bytes internal/geoip/testdata/test-28.mmdb | Bin 0 -> 2235 bytes internal/geoip/testdata/test-32.mmdb | Bin 0 -> 2485 bytes internal/imageboard/api.go | 11 +- internal/imageboard/ids.go | 80 ++++ internal/imageboard/ids_test.go | 80 ++++ internal/imageboard/imageboard.go | 4 +- internal/imageboard/pages.go | 18 + internal/imageboard/post.go | 13 + internal/imageboard/static/chan.css | 28 ++ internal/imageboard/static/chan.js | 12 + internal/imageboard/templates/layout.html | 4 +- internal/server/chanconfig.go | 6 + internal/store/chan.go | 72 ++-- internal/store/schema.go | 14 +- 23 files changed, 1192 insertions(+), 42 deletions(-) create mode 100644 internal/geoip/geoip.go create mode 100644 internal/geoip/geoip_test.go create mode 100644 internal/geoip/names.go create mode 100644 internal/geoip/testdata/test-24.mmdb create mode 100644 internal/geoip/testdata/test-28.mmdb create mode 100644 internal/geoip/testdata/test-32.mmdb create mode 100644 internal/imageboard/ids.go create mode 100644 internal/imageboard/ids_test.go diff --git a/bbs.conf.sample b/bbs.conf.sample index 9dc0f72..25a99dd 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -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 diff --git a/cmd/bbs/chan.go b/cmd/bbs/chan.go index 208886c..b2a7b53 100644 --- a/cmd/bbs/chan.go +++ b/cmd/bbs/chan.go @@ -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 } diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 0eb68f9..718af6b 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -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) diff --git a/docs/wiki/Image-Boards.md b/docs/wiki/Image-Boards.md index 385e828..19cd114 100644 --- a/docs/wiki/Image-Boards.md +++ b/docs/wiki/Image-Boards.md @@ -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 diff --git a/internal/app/chan.go b/internal/app/chan.go index b7216c3..76b0103 100644 --- a/internal/app/chan.go +++ b/internal/app/chan.go @@ -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] } diff --git a/internal/geoip/geoip.go b/internal/geoip/geoip.go new file mode 100644 index 0000000..f7aa0da --- /dev/null +++ b/internal/geoip/geoip.go @@ -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 +} diff --git a/internal/geoip/geoip_test.go b/internal/geoip/geoip_test.go new file mode 100644 index 0000000..342a47b --- /dev/null +++ b/internal/geoip/geoip_test.go @@ -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") + } +} diff --git a/internal/geoip/names.go b/internal/geoip/names.go new file mode 100644 index 0000000..e00d348 --- /dev/null +++ b/internal/geoip/names.go @@ -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", +} diff --git a/internal/geoip/testdata/test-24.mmdb b/internal/geoip/testdata/test-24.mmdb new file mode 100644 index 0000000000000000000000000000000000000000..6181529f0238ba7383de55922f5765e169041981 GIT binary patch literal 1985 zcmZ9~cX$(J9Ki8kVnx9{(7I2p6N|XTMGdrR6B41Nj-sB|+)KFH+{L>q5FDW3-g_%` zD=O~2z&#N69;9{Q!aexQH{bNM*eB2D`Q~@;^S+nsiNr)!h{SOfkvBzZ=v8qDu7<1Q zP#lJ9;F`D=u8r&9y0{*$j~n2II2<>^jjtr)BRYJDfCiJZ>-3_Me0fyh}R*NU9Y_!vHp`ktR4p2Vj_o+h5b zg{TjGn|KzV!{_k@d=X#5m+=*R6<@=}_&P4ZH&DN*ZxPia-l5;c_warE06)Z!@MHW0 zKNb0#_)O$;Vkwrf5Bo)a6#0Vw62HQ)@f%!*-{N=pJ^q0DR`ui3pXDMyMg24Ji^#9h zybUW0)~qUr$Xi>iUck%_*yBxq4@#p^+T4WLzUlQc2|(EVsm>ElDQ zV0C%EIZgS2%<~%an?ecHX#vO>L_Y@%{_#x&0V~^0>J@_d+$A{ zTXFBL;2wy357N4D;U4_ubNA`1iRO>I@B91x?ztyV5|NmQtQ3jEDw?-MYDlZXFjx&% zhc#e0tO;wu+OQ6+3+uu9umNlc8^H+J7&d{CuqkW?o5LvB0=9(FV8B+eHEaX5uq|u{ z+rtj9BkTlYU}va#cd!x7K{)8I%r3XX;>bb_flHTsE4 zmq<>h*(6IuF)|(UpnuFVL&PR^!!ghU1#lp|!4)Zzj;$0u5uX%5Z>2X=WY$oM>3>0q zG-s$N$B7(IIss0s^yZ4pBb@{%!+ba;A~twD;Ra6=Ii21aaHi%Sk+U?{ikwaH95@%w zgY)46xDYOai{TQu6fT3y;R?7Cu7Yq&SBqQ|rC7KZT?vcViCj-w0DTblZeZj_k((&q zTV=T_Sf!DK=QVx6-?h`|cNcfZ~Jj5IhWzz@zXOJPuDl zxa%ib>?wF!;6-=|UWQlTRd@|vhb8a^EQL3rQ{-(Ps~;I2 z`@8TSybmA1hwu@644=TK@R{Zxmi}Di3yRC24E->m`AOtU(pT^`d;{OYa`+Cuhacca z=!Ec)SBU&vNx!g{Uqyba6o04q2mC4W7rnnD;&Dyuauqc>cqr literal 0 HcmV?d00001 diff --git a/internal/geoip/testdata/test-32.mmdb b/internal/geoip/testdata/test-32.mmdb new file mode 100644 index 0000000000000000000000000000000000000000..fdbce0513b6fe0575f507e1747e0ca5edffb68b3 GIT binary patch literal 2485 zcmZA0cYG6d7{~D>R#e<5ijzYt4lLppXAQJz6B41Nj-p<#xgX(ba~JQfKyZNI1l(It zsatVxaDsav?mbBB!i9VAm(L}i+LOLs&+Gkte$SJ;>*bY5Bod88B5S2$xSsfyR2BXD zH~=@m4RIqJh#TW3xG8Rio8uO^B@V)^aBCcl+u*i11h>QOaR=NHcfy@-N=>IXMMa*BIShU?Q=}~V4m<@rF^@I|pL3)N^rwc-UCAE3k6oepRLRr&`)Kf+ zE7H&CKaZRy`E>d-@XXMBrsP@lXW?v|gJ)Na_Pxj8xzCk4kNNp{fq0+PT&e4&=1B#+ z^YKEw2rtG<@KU@CFUKqJO1uiM#%u6eybgnVFOXVT>7&8(1!qCsAax^o5q4uRzlnUa zcnkSf4Cc3yZx`&IeZ>pz!&i)d>LQCSMfD`9arERxDwyQHt}t8-!r^R z{~o@NAK-`h5q^xH;HUVR_z(GW@eA@QEMX7!ia$wxN&gjojo;w6xEjC1@9_ux5!*2M zUe-wc9O{1||0@0#I{%&g2mUGkMgF^DEJojkLjPYWk#)Lk-!1kgbIP%eywWXm`KZwi zmgneM$5in|ye>HQdg7*<&|+J@GPRUt=S(MGBV%P}{(o3%a#haqeB~-ru28;sk2WOU z(yUdNwAwV=&A#C)ucSqLwSn4TnJ33<)jisXhNMw2Y`L;lTUU;um9cf@m1IJ>dBZN2 zml8CgwM=VyEt65xv{q$w8n#(pO@$6Z>-A0L^~QSFu(PVXSzpPESFA}J)6v^NYarLRn^(@Ekj;%Yj?EdMZRC|}zY3i!rWT#ZcI#xz!rcJ{) z+6_el`R_XHTr literal 0 HcmV?d00001 diff --git a/internal/imageboard/api.go b/internal/imageboard/api.go index 79537d7..8ddc335 100644 --- a/internal/imageboard/api.go +++ b/internal/imageboard/api.go @@ -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) } diff --git a/internal/imageboard/ids.go b/internal/imageboard/ids.go new file mode 100644 index 0000000..243ab87 --- /dev/null +++ b/internal/imageboard/ids.go @@ -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)) } diff --git a/internal/imageboard/ids_test.go b/internal/imageboard/ids_test.go new file mode 100644 index 0000000..c64e617 --- /dev/null +++ b/internal/imageboard/ids_test.go @@ -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: `, + `` + "\U0001F1F3\U0001F1FF" + ``, + ``} { + 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) + } +} diff --git a/internal/imageboard/imageboard.go b/internal/imageboard/imageboard.go index 47cc797..0d882dc 100644 --- a/internal/imageboard/imageboard.go +++ b/internal/imageboard/imageboard.go @@ -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 ( diff --git a/internal/imageboard/pages.go b/internal/imageboard/pages.go index 9f39ece..537d983 100644 --- a/internal/imageboard/pages.go +++ b/internal/imageboard/pages.go @@ -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) { diff --git a/internal/imageboard/post.go b/internal/imageboard/post.go index 42dedff..d0d9e1d 100644 --- a/internal/imageboard/post.go +++ b/internal/imageboard/post.go @@ -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 { diff --git a/internal/imageboard/static/chan.css b/internal/imageboard/static/chan.css index 486cd82..a5e0df1 100644 --- a/internal/imageboard/static/chan.css +++ b/internal/imageboard/static/chan.css @@ -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; } diff --git a/internal/imageboard/static/chan.js b/internal/imageboard/static/chan.js index ee73a69..1a11050 100644 --- a/internal/imageboard/static/chan.js +++ b/internal/imageboard/static/chan.js @@ -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 () { diff --git a/internal/imageboard/templates/layout.html b/internal/imageboard/templates/layout.html index 72b2e41..77761d5 100644 --- a/internal/imageboard/templates/layout.html +++ b/internal/imageboard/templates/layout.html @@ -46,12 +46,12 @@ {{define "post"}}
{{if not .OP}}
>>
{{end}} -
+
{{if and .OP .Ext}}{{template "file" .}}{{end}}