all repos — honk @ 9cb8e19e6b2c560f5f7f0811b772c0d8f4c2f5d3

my fork of honk

web.go (view raw)

   1//
   2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
   3//
   4// Permission to use, copy, modify, and distribute this software for any
   5// purpose with or without fee is hereby granted, provided that the above
   6// copyright notice and this permission notice appear in all copies.
   7//
   8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15
  16package main
  17
  18import (
  19	"bytes"
  20	"crypto/sha512"
  21	"database/sql"
  22	"errors"
  23	"fmt"
  24	"html/template"
  25	"io"
  26	notrand "math/rand"
  27	"mime/multipart"
  28	"net"
  29	"net/http"
  30	"net/http/fcgi"
  31	"net/url"
  32	"os"
  33	"os/signal"
  34	"regexp"
  35	"runtime/pprof"
  36	"sort"
  37	"strconv"
  38	"strings"
  39	"sync"
  40	"syscall"
  41	"time"
  42	"unicode/utf8"
  43
  44	"github.com/gorilla/mux"
  45	"humungus.tedunangst.com/r/gonix"
  46	"humungus.tedunangst.com/r/webs/gencache"
  47	"humungus.tedunangst.com/r/webs/httpsig"
  48	"humungus.tedunangst.com/r/webs/junk"
  49	"humungus.tedunangst.com/r/webs/login"
  50	"humungus.tedunangst.com/r/webs/rss"
  51	"humungus.tedunangst.com/r/webs/templates"
  52)
  53
  54var readviews *templates.Template
  55
  56var userSep = "u"
  57var honkSep = "h"
  58
  59var develMode = false
  60
  61var allemus []Emu
  62
  63func getuserstyle(u *login.UserInfo) template.HTMLAttr {
  64	if u == nil {
  65		return ""
  66	}
  67	user, _ := butwhatabout(u.Username)
  68	class := template.HTMLAttr("")
  69	if user.Options.SkinnyCSS {
  70		class += `class="skinny"`
  71	}
  72	return class
  73}
  74
  75func getmaplink(u *login.UserInfo) string {
  76	if u == nil {
  77		return "osm"
  78	}
  79	user, _ := butwhatabout(u.Username)
  80	ml := user.Options.MapLink
  81	if ml == "" {
  82		ml = "osm"
  83	}
  84	return ml
  85}
  86
  87func getInfo(r *http.Request) map[string]interface{} {
  88	templinfo := make(map[string]interface{})
  89	templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
  90	templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
  91	templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
  92	templinfo["MiscJSParam"] = getassetparam(viewDir + "/views/misc.js")
  93	templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
  94	templinfo["ServerName"] = serverName
  95	templinfo["IconName"] = iconName
  96	templinfo["UserSep"] = userSep
  97	if r == nil {
  98		return templinfo
  99	}
 100	if u := login.GetUserInfo(r); u != nil {
 101		templinfo["UserInfo"], _ = butwhatabout(u.Username)
 102		templinfo["UserStyle"] = getuserstyle(u)
 103		combos, _ := combocache.Get(UserID(u.UserID))
 104		templinfo["Combos"] = combos
 105	}
 106	return templinfo
 107}
 108
 109var oldnews = gencache.New(gencache.Options[string, []byte]{
 110	Fill: func(url string) ([]byte, bool) {
 111		templinfo := getInfo(nil)
 112		var honks []*Honk
 113		var userid UserID = -1
 114
 115		templinfo["ServerMessage"] = serverMsg
 116		switch url {
 117		case "/events":
 118			honks = geteventhonks(userid)
 119			templinfo["ServerMessage"] = "some recent and upcoming events"
 120		default:
 121			templinfo["ShowRSS"] = true
 122			honks = getpublichonks()
 123		}
 124		reverbolate(userid, honks)
 125		templinfo["Honks"] = honks
 126		templinfo["MapLink"] = getmaplink(nil)
 127		var buf bytes.Buffer
 128		err := readviews.Execute(&buf, "honkpage.html", templinfo)
 129		if err != nil {
 130			elog.Print(err)
 131		}
 132		return buf.Bytes(), true
 133
 134	},
 135	Duration: 1 * time.Minute,
 136})
 137
 138func lonelypage(w http.ResponseWriter, r *http.Request) {
 139	page, _ := oldnews.Get(r.URL.Path)
 140	if !develMode {
 141		w.Header().Set("Cache-Control", "max-age=60")
 142	}
 143	w.Write(page)
 144}
 145
 146func homepage(w http.ResponseWriter, r *http.Request) {
 147	u := login.GetUserInfo(r)
 148	if u == nil {
 149		lonelypage(w, r)
 150		return
 151	}
 152	templinfo := getInfo(r)
 153	var honks []*Honk
 154	var userid UserID = -1
 155
 156	templinfo["ServerMessage"] = serverMsg
 157	if u == nil || r.URL.Path == "/front" {
 158		switch r.URL.Path {
 159		case "/events":
 160			honks = geteventhonks(userid)
 161			templinfo["ServerMessage"] = "some recent and upcoming events"
 162		default:
 163			templinfo["ShowRSS"] = true
 164			honks = getpublichonks()
 165		}
 166	} else {
 167		userid = UserID(u.UserID)
 168		switch r.URL.Path {
 169		case "/atme":
 170			templinfo["ServerMessage"] = "at me!"
 171			templinfo["PageName"] = "atme"
 172			honks = gethonksforme(userid, 0)
 173			honks = osmosis(honks, userid, false)
 174			menewnone(userid)
 175			templinfo["UserInfo"], _ = butwhatabout(u.Username)
 176		case "/longago":
 177			templinfo["ServerMessage"] = "long ago and far away!"
 178			templinfo["PageName"] = "longago"
 179			honks = gethonksfromlongago(userid, 0)
 180			honks = osmosis(honks, userid, false)
 181		case "/events":
 182			templinfo["ServerMessage"] = "some recent and upcoming events"
 183			templinfo["PageName"] = "events"
 184			honks = geteventhonks(userid)
 185			honks = osmosis(honks, userid, true)
 186		case "/first":
 187			templinfo["PageName"] = "first"
 188			honks = gethonksforuserfirstclass(userid, 0)
 189			honks = osmosis(honks, userid, true)
 190		case "/saved":
 191			templinfo["ServerMessage"] = "saved honks"
 192			templinfo["PageName"] = "saved"
 193			honks = getsavedhonks(userid, 0)
 194		default:
 195			templinfo["PageName"] = "home"
 196			honks = gethonksforuser(userid, 0)
 197			honks = osmosis(honks, userid, true)
 198		}
 199		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 200	}
 201
 202	honkpage(w, u, honks, templinfo)
 203}
 204
 205func showemus(w http.ResponseWriter, r *http.Request) {
 206	templinfo := getInfo(r)
 207	templinfo["Emus"] = allemus
 208	err := readviews.Execute(w, "emus.html", templinfo)
 209	if err != nil {
 210		elog.Print(err)
 211	}
 212}
 213
 214func showfunzone(w http.ResponseWriter, r *http.Request) {
 215	var emunames, memenames []string
 216	emuext := make(map[string]string)
 217	dir, err := os.Open(dataDir + "/emus")
 218	if err == nil {
 219		emunames, _ = dir.Readdirnames(0)
 220		dir.Close()
 221	}
 222	for i, e := range emunames {
 223		if len(e) > 4 {
 224			emunames[i] = e[:len(e)-4]
 225			emuext[emunames[i]] = e[len(e)-4:]
 226		}
 227	}
 228	dir, err = os.Open(dataDir + "/memes")
 229	if err == nil {
 230		memenames, _ = dir.Readdirnames(0)
 231		dir.Close()
 232	}
 233	sort.Strings(emunames)
 234	sort.Strings(memenames)
 235	templinfo := getInfo(r)
 236	templinfo["Emus"] = emunames
 237	templinfo["Emuext"] = emuext
 238	templinfo["Memes"] = memenames
 239	err = readviews.Execute(w, "funzone.html", templinfo)
 240	if err != nil {
 241		elog.Print(err)
 242	}
 243}
 244
 245func showrss(w http.ResponseWriter, r *http.Request) {
 246	name := mux.Vars(r)["name"]
 247
 248	var honks []*Honk
 249	if name != "" {
 250		honks = gethonksbyuser(name, false, 0)
 251	} else {
 252		honks = getpublichonks()
 253	}
 254	reverbolate(-1, honks)
 255
 256	home := serverURL("/")
 257	base := home
 258	if name != "" {
 259		home += "u/" + name
 260		name += " "
 261	}
 262	feed := rss.Feed{
 263		Title:       name + "honk",
 264		Link:        home,
 265		Description: name + "honk rss",
 266		Image: &rss.Image{
 267			URL:   base + "icon.png",
 268			Title: name + "honk rss",
 269			Link:  home,
 270		},
 271	}
 272	var modtime time.Time
 273	for _, honk := range honks {
 274		if !firstclass(honk) {
 275			continue
 276		}
 277		desc := string(honk.HTML)
 278		if t := honk.Time; t != nil {
 279			desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM MST Mon Jan 02"))
 280			if t.Duration != 0 {
 281				desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
 282			}
 283		}
 284		if p := honk.Place; p != nil {
 285			desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 286				p.Url, p.Name, p.Latitude, p.Longitude))
 287		}
 288		for _, d := range honk.Donks {
 289			desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 290				d.URL, d.Desc))
 291			if strings.HasPrefix(d.Media, "image") {
 292				desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
 293			}
 294		}
 295
 296		feed.Items = append(feed.Items, &rss.Item{
 297			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 298			Description: rss.CData{Data: desc},
 299			Link:        honk.URL,
 300			PubDate:     honk.Date.Format(time.RFC1123),
 301			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 302		})
 303		if honk.Date.After(modtime) {
 304			modtime = honk.Date
 305		}
 306	}
 307	if !develMode {
 308		w.Header().Set("Cache-Control", "max-age=300")
 309		w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 310	}
 311
 312	err := feed.Write(w)
 313	if err != nil {
 314		elog.Printf("error writing rss: %s", err)
 315	}
 316}
 317
 318func crappola(j junk.Junk) bool {
 319	t := firstofmany(j, "type")
 320	if t == "Delete" {
 321		a, _ := j.GetString("actor")
 322		o, _ := j.GetString("object")
 323		if a == o {
 324			dlog.Printf("crappola from %s", a)
 325			return true
 326		}
 327	}
 328	if t == "Announce" {
 329		if obj, ok := j.GetMap("object"); ok {
 330			j = obj
 331			t = firstofmany(j, "type")
 332		}
 333	}
 334	if t == "Undo" {
 335		if obj, ok := j.GetMap("object"); ok {
 336			j = obj
 337			t = firstofmany(j, "type")
 338		}
 339	}
 340	if t == "Like" || t == "Dislike" || t == "Listen" {
 341		return true
 342	}
 343	if t == "EmojiReact" {
 344		o, _ := j.GetString("object")
 345		if originate(o) != serverName {
 346			return true
 347		}
 348	}
 349	return false
 350}
 351
 352func ping(user *WhatAbout, who string) {
 353	if targ := fullname(who, user.ID); targ != "" {
 354		who = targ
 355	}
 356	if !strings.HasPrefix(who, "https://") {
 357		who = gofish(who)
 358	}
 359	if who == "" {
 360		ilog.Printf("nobody to ping!")
 361		return
 362	}
 363	box, ok := boxofboxes.Get(who)
 364	if !ok {
 365		ilog.Printf("no inbox to ping %s", who)
 366		return
 367	}
 368	ilog.Printf("sending ping to %s", box.In)
 369	j := junk.New()
 370	j["@context"] = itiswhatitis
 371	j["type"] = "Ping"
 372	j["id"] = user.URL + "/ping/" + xfiltrate()
 373	j["actor"] = user.URL
 374	j["to"] = who
 375	ki := ziggy(user.ID)
 376	if ki == nil {
 377		return
 378	}
 379	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 380	if err != nil {
 381		elog.Printf("can't send ping: %s", err)
 382		return
 383	}
 384	ilog.Printf("sent ping to %s: %s", who, j["id"])
 385}
 386
 387func pong(user *WhatAbout, who string, obj string) {
 388	box, ok := boxofboxes.Get(who)
 389	if !ok {
 390		ilog.Printf("no inbox to pong %s", who)
 391		return
 392	}
 393	j := junk.New()
 394	j["@context"] = itiswhatitis
 395	j["type"] = "Pong"
 396	j["id"] = user.URL + "/pong/" + xfiltrate()
 397	j["actor"] = user.URL
 398	j["to"] = who
 399	j["object"] = obj
 400	ki := ziggy(user.ID)
 401	if ki == nil {
 402		return
 403	}
 404	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 405	if err != nil {
 406		elog.Printf("can't send pong: %s", err)
 407		return
 408	}
 409}
 410
 411func inbox(w http.ResponseWriter, r *http.Request) {
 412	name := mux.Vars(r)["name"]
 413	user, err := butwhatabout(name)
 414	if err != nil {
 415		http.NotFound(w, r)
 416		return
 417	}
 418	if stealthmode(user.ID, r) {
 419		http.NotFound(w, r)
 420		return
 421	}
 422	var buf bytes.Buffer
 423	limiter := io.LimitReader(r.Body, 1*1024*1024)
 424	io.Copy(&buf, limiter)
 425	payload := buf.Bytes()
 426	j, err := junk.FromBytes(payload)
 427	if err != nil {
 428		ilog.Printf("bad payload: %s", err)
 429		ilog.Writer().Write(payload)
 430		ilog.Writer().Write([]byte{'\n'})
 431		return
 432	}
 433
 434	if crappola(j) {
 435		return
 436	}
 437	what := firstofmany(j, "type")
 438	who, _ := j.GetString("actor")
 439	if rejectactor(user.ID, who) {
 440		return
 441	}
 442
 443	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 444	if err != nil && keyname != "" {
 445		savingthrow(keyname)
 446		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 447	}
 448	if err != nil {
 449		ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
 450		if keyname != "" {
 451			ilog.Printf("bad signature from %s", keyname)
 452		}
 453		http.Error(w, "what did you call me?", http.StatusUnauthorized)
 454		return
 455	}
 456	origin := keymatch(keyname, who)
 457	if origin == "" {
 458		ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 459		if what == "Create" {
 460			var xid string
 461			obj, ok := j.GetMap("object")
 462			if ok {
 463				xid, _ = obj.GetString("id")
 464			} else {
 465				xid, _ = j.GetString("object")
 466			}
 467			if xid != "" {
 468				dlog.Printf("getting forwarded create from %s: %s", keyname, xid)
 469				go grabhonk(user, xid)
 470			}
 471		}
 472		return
 473	}
 474
 475	switch what {
 476	case "Ping":
 477		id, _ := j.GetString("id")
 478		ilog.Printf("ping from %s: %s", who, id)
 479		pong(user, who, id)
 480	case "Pong":
 481		obj, _ := j.GetString("object")
 482		ilog.Printf("pong from %s: %s", who, obj)
 483	case "Follow":
 484		obj, _ := j.GetString("object")
 485		if obj != user.URL {
 486			ilog.Printf("can't follow %s", obj)
 487			return
 488		}
 489		followme(user, who, who, j)
 490	case "Accept":
 491		followyou2(user, j)
 492	case "Reject":
 493		nofollowyou2(user, j)
 494	case "Update":
 495		obj, ok := j.GetMap("object")
 496		if ok {
 497			what := firstofmany(obj, "type")
 498			switch what {
 499			case "Service":
 500				fallthrough
 501			case "Person":
 502				return
 503			case "Question":
 504				return
 505			}
 506		}
 507		go xonksaver(user, j, origin)
 508	case "Undo":
 509		obj, ok := j.GetMap("object")
 510		if !ok {
 511			folxid, ok := j.GetString("object")
 512			if ok && originate(folxid) == origin {
 513				unfollowme(user, "", "", j)
 514			}
 515			return
 516		}
 517		what := firstofmany(obj, "type")
 518		switch what {
 519		case "Follow":
 520			unfollowme(user, who, who, j)
 521		case "Announce":
 522			xid, _ := obj.GetString("object")
 523			dlog.Printf("undo announce: %s", xid)
 524		case "Like":
 525		default:
 526			ilog.Printf("unknown undo: %s", what)
 527		}
 528	case "EmojiReact":
 529		obj, ok := j.GetString("object")
 530		if ok {
 531			content, _ := j.GetString("content")
 532			addreaction(user, obj, who, content)
 533		}
 534	default:
 535		go saveandcheck(user, j, origin)
 536	}
 537}
 538
 539func saveandcheck(user *WhatAbout, j junk.Junk, origin string) {
 540	xonk := xonksaver(user, j, origin)
 541	if xonk == nil {
 542		return
 543	}
 544	if sname := shortname(user.ID, xonk.Honker); sname == "" {
 545		dlog.Printf("received unexpected activity from %s", xonk.Honker)
 546		if xonk.Whofore == 0 {
 547			dlog.Printf("it's not even for me!")
 548		}
 549	}
 550}
 551
 552func serverinbox(w http.ResponseWriter, r *http.Request) {
 553	user := getserveruser()
 554	if stealthmode(user.ID, r) {
 555		http.NotFound(w, r)
 556		return
 557	}
 558	var buf bytes.Buffer
 559	io.Copy(&buf, r.Body)
 560	payload := buf.Bytes()
 561	j, err := junk.FromBytes(payload)
 562	if err != nil {
 563		ilog.Printf("bad payload: %s", err)
 564		ilog.Writer().Write(payload)
 565		ilog.Writer().Write([]byte{'\n'})
 566		return
 567	}
 568	if crappola(j) {
 569		return
 570	}
 571	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 572	if err != nil && keyname != "" {
 573		savingthrow(keyname)
 574		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 575	}
 576	if err != nil {
 577		ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
 578		if keyname != "" {
 579			ilog.Printf("bad signature from %s", keyname)
 580		}
 581		http.Error(w, "what did you call me?", http.StatusUnauthorized)
 582		return
 583	}
 584	who, _ := j.GetString("actor")
 585	origin := keymatch(keyname, who)
 586	if origin == "" {
 587		ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 588		return
 589	}
 590	if rejectactor(user.ID, who) {
 591		return
 592	}
 593	re_ont := regexp.MustCompile(serverURL("/o") + "/([\\pL[:digit:]]+)")
 594	what := firstofmany(j, "type")
 595	dlog.Printf("server got a %s", what)
 596	switch what {
 597	case "Follow":
 598		obj, _ := j.GetString("object")
 599		if obj == user.URL {
 600			ilog.Printf("can't follow the server!")
 601			return
 602		}
 603		m := re_ont.FindStringSubmatch(obj)
 604		if len(m) != 2 {
 605			ilog.Printf("not sure how to handle this")
 606			return
 607		}
 608		ont := "#" + m[1]
 609
 610		followme(user, who, ont, j)
 611	case "Undo":
 612		obj, ok := j.GetMap("object")
 613		if !ok {
 614			ilog.Printf("unknown undo no object")
 615			return
 616		}
 617		what := firstofmany(obj, "type")
 618		if what != "Follow" {
 619			ilog.Printf("unknown undo: %s", what)
 620			return
 621		}
 622		targ, _ := obj.GetString("object")
 623		m := re_ont.FindStringSubmatch(targ)
 624		if len(m) != 2 {
 625			ilog.Printf("not sure how to handle this")
 626			return
 627		}
 628		ont := "#" + m[1]
 629		unfollowme(user, who, ont, j)
 630	default:
 631		ilog.Printf("unhandled server activity: %s", what)
 632		dumpactivity(j)
 633	}
 634}
 635
 636func serveractor(w http.ResponseWriter, r *http.Request) {
 637	user := getserveruser()
 638	if stealthmode(user.ID, r) {
 639		http.NotFound(w, r)
 640		return
 641	}
 642	j := junkuser(user)
 643	j.Write(w)
 644}
 645
 646func ximport(w http.ResponseWriter, r *http.Request) {
 647	u := login.GetUserInfo(r)
 648	xid := strings.TrimSpace(r.FormValue("q"))
 649	xonk := getxonk(UserID(u.UserID), xid)
 650	if xonk == nil {
 651		p, _ := investigate(xid)
 652		if p != nil {
 653			xid = p.XID
 654		}
 655		j, err := GetJunk(UserID(u.UserID), xid)
 656		if err != nil {
 657			http.Error(w, "error getting external object", http.StatusInternalServerError)
 658			ilog.Printf("error getting external object: %s", err)
 659			return
 660		}
 661		allinjest(originate(xid), j)
 662		dlog.Printf("importing %s", xid)
 663		user, _ := butwhatabout(u.Username)
 664
 665		info, _ := somethingabout(j)
 666		if info == nil {
 667			xonk = xonksaver(user, j, originate(xid))
 668		} else if info.What == SomeActor {
 669			outbox, _ := j.GetString("outbox")
 670			gimmexonks(user, outbox)
 671			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 672			return
 673		} else if info.What == SomeCollection {
 674			gimmexonks(user, xid)
 675			http.Redirect(w, r, "/xzone", http.StatusSeeOther)
 676			return
 677		}
 678	}
 679	convoy := ""
 680	if xonk != nil {
 681		convoy = xonk.Convoy
 682	}
 683	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 684}
 685
 686func xzone(w http.ResponseWriter, r *http.Request) {
 687	u := login.GetUserInfo(r)
 688	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 689	if err != nil {
 690		elog.Printf("query err: %s", err)
 691		return
 692	}
 693	defer rows.Close()
 694	var honkers []Honker
 695	for rows.Next() {
 696		var xid string
 697		rows.Scan(&xid)
 698		honkers = append(honkers, Honker{XID: xid})
 699	}
 700	rows.Close()
 701	for i := range honkers {
 702		_, honkers[i].Handle = handles(honkers[i].XID)
 703	}
 704	templinfo := getInfo(r)
 705	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 706	templinfo["Honkers"] = honkers
 707	err = readviews.Execute(w, "xzone.html", templinfo)
 708	if err != nil {
 709		elog.Print(err)
 710	}
 711}
 712
 713var oldoutbox = gencache.New(gencache.Options[string, []byte]{Fill: func(name string) ([]byte, bool) {
 714	user, err := butwhatabout(name)
 715	if err != nil {
 716		return nil, false
 717	}
 718	honks := gethonksbyuser(name, false, 0)
 719	if len(honks) > 20 {
 720		honks = honks[0:20]
 721	}
 722
 723	var jonks []junk.Junk
 724	for _, h := range honks {
 725		j, _ := jonkjonk(user, h)
 726		jonks = append(jonks, j)
 727	}
 728
 729	j := junk.New()
 730	j["@context"] = itiswhatitis
 731	j["id"] = user.URL + "/outbox"
 732	j["attributedTo"] = user.URL
 733	j["type"] = "OrderedCollection"
 734	j["totalItems"] = len(jonks)
 735	j["orderedItems"] = jonks
 736
 737	return j.ToBytes(), true
 738}, Duration: 1 * time.Minute})
 739
 740func outbox(w http.ResponseWriter, r *http.Request) {
 741	name := mux.Vars(r)["name"]
 742	user, err := butwhatabout(name)
 743	if err != nil {
 744		http.NotFound(w, r)
 745		return
 746	}
 747	if stealthmode(user.ID, r) {
 748		http.NotFound(w, r)
 749		return
 750	}
 751	j, ok := oldoutbox.Get(name)
 752	if ok {
 753		w.Header().Set("Content-Type", theonetruename)
 754		w.Write(j)
 755	} else {
 756		http.NotFound(w, r)
 757	}
 758}
 759
 760var oldempties = gencache.New(gencache.Options[string, []byte]{Fill: func(url string) ([]byte, bool) {
 761	colname := "/followers"
 762	if strings.HasSuffix(url, "/following") {
 763		colname = "/following"
 764	}
 765	user := serverURL("%s", url[:len(url)-10])
 766	j := junk.New()
 767	j["@context"] = itiswhatitis
 768	j["id"] = user + colname
 769	j["attributedTo"] = user
 770	j["type"] = "OrderedCollection"
 771	j["totalItems"] = 0
 772	j["orderedItems"] = []junk.Junk{}
 773
 774	return j.ToBytes(), true
 775}})
 776
 777func emptiness(w http.ResponseWriter, r *http.Request) {
 778	name := mux.Vars(r)["name"]
 779	user, err := butwhatabout(name)
 780	if err != nil {
 781		http.NotFound(w, r)
 782		return
 783	}
 784	if stealthmode(user.ID, r) {
 785		http.NotFound(w, r)
 786		return
 787	}
 788	j, ok := oldempties.Get(r.URL.Path)
 789	if ok {
 790		w.Header().Set("Content-Type", theonetruename)
 791		w.Write(j)
 792	} else {
 793		http.NotFound(w, r)
 794	}
 795}
 796
 797func showuser(w http.ResponseWriter, r *http.Request) {
 798	name := mux.Vars(r)["name"]
 799	user, err := butwhatabout(name)
 800	if err != nil {
 801		ilog.Printf("user not found %s: %s", name, err)
 802		http.NotFound(w, r)
 803		return
 804	}
 805	if stealthmode(user.ID, r) {
 806		http.NotFound(w, r)
 807		return
 808	}
 809	wantjson := false
 810	if strings.HasSuffix(r.URL.Path, ".json") {
 811		wantjson = true
 812	}
 813	if friendorfoe(r.Header.Get("Accept")) || wantjson {
 814		j, ok := asjonker(name)
 815		if ok {
 816			w.Header().Set("Content-Type", theonetruename)
 817			w.Write(j)
 818		} else {
 819			http.NotFound(w, r)
 820		}
 821		return
 822	}
 823	u := login.GetUserInfo(r)
 824	if u != nil && u.Username != name {
 825		u = nil
 826	}
 827	honks := gethonksbyuser(name, u != nil, 0)
 828	templinfo := getInfo(r)
 829	templinfo["PageName"] = "user"
 830	templinfo["PageArg"] = name
 831	templinfo["Name"] = user.Name
 832	templinfo["Honkology"] = oguser(user)
 833	templinfo["WhatAbout"] = user.HTAbout
 834	templinfo["ServerMessage"] = ""
 835	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", user.URL)
 836	if u != nil {
 837		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 838	}
 839	honkpage(w, u, honks, templinfo)
 840}
 841
 842func showhonker(w http.ResponseWriter, r *http.Request) {
 843	u := login.GetUserInfo(r)
 844	name := mux.Vars(r)["name"]
 845	var honks []*Honk
 846	if name == "" {
 847		name = r.FormValue("xid")
 848		honks = gethonksbyxonker(UserID(u.UserID), name, 0)
 849	} else {
 850		honks = gethonksbyhonker(UserID(u.UserID), name, 0)
 851	}
 852	miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
 853<input type="hidden" name="CSRF" value="%s">
 854<input type="hidden" name="url" value="%s">
 855<button tabindex=1 name="add honker" value="add honker">add honker</button>
 856</form>`, login.GetCSRF("submithonker", r), name)
 857	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
 858	templinfo := getInfo(r)
 859	templinfo["PageName"] = "honker"
 860	templinfo["PageArg"] = name
 861	templinfo["ServerMessage"] = msg
 862	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 863	honkpage(w, u, honks, templinfo)
 864}
 865
 866func showcombo(w http.ResponseWriter, r *http.Request) {
 867	name := mux.Vars(r)["name"]
 868	u := login.GetUserInfo(r)
 869	honks := gethonksbycombo(UserID(u.UserID), name, 0)
 870	honks = osmosis(honks, UserID(u.UserID), true)
 871	templinfo := getInfo(r)
 872	templinfo["PageName"] = "combo"
 873	templinfo["PageArg"] = name
 874	templinfo["ServerMessage"] = "honks by combo: " + name
 875	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 876	honkpage(w, u, honks, templinfo)
 877}
 878func showconvoy(w http.ResponseWriter, r *http.Request) {
 879	c := r.FormValue("c")
 880	u := login.GetUserInfo(r)
 881	honks := gethonksbyconvoy(UserID(u.UserID), c, 0)
 882	templinfo := getInfo(r)
 883	if len(honks) > 0 {
 884		templinfo["TopHID"] = honks[0].ID
 885	}
 886	honks = osmosis(honks, UserID(u.UserID), false)
 887	//reversehonks(honks)
 888	honks = threadsort(honks)
 889	templinfo["PageName"] = "convoy"
 890	templinfo["PageArg"] = c
 891	templinfo["ServerMessage"] = "honks in convoy: " + c
 892	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 893	honkpage(w, u, honks, templinfo)
 894}
 895func showsearch(w http.ResponseWriter, r *http.Request) {
 896	q := r.FormValue("q")
 897	if strings.HasPrefix(q, "https://") {
 898		ximport(w, r)
 899		return
 900	}
 901	u := login.GetUserInfo(r)
 902	honks := gethonksbysearch(UserID(u.UserID), q, 0)
 903	templinfo := getInfo(r)
 904	templinfo["PageName"] = "search"
 905	templinfo["PageArg"] = q
 906	templinfo["ServerMessage"] = "honks for search: " + q
 907	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 908	honkpage(w, u, honks, templinfo)
 909}
 910func showontology(w http.ResponseWriter, r *http.Request) {
 911	name := mux.Vars(r)["name"]
 912	u := login.GetUserInfo(r)
 913	var userid UserID = -1
 914	if u != nil {
 915		userid = UserID(u.UserID)
 916	}
 917	honks := gethonksbyontology(userid, "#"+name, 0)
 918	if friendorfoe(r.Header.Get("Accept")) {
 919		if len(honks) > 40 {
 920			honks = honks[0:40]
 921		}
 922
 923		var xids []string
 924		for _, h := range honks {
 925			xids = append(xids, h.XID)
 926		}
 927
 928		user := getserveruser()
 929
 930		j := junk.New()
 931		j["@context"] = itiswhatitis
 932		j["id"] = serverURL("/o/%s", name)
 933		j["name"] = "#" + name
 934		j["attributedTo"] = user.URL
 935		j["type"] = "OrderedCollection"
 936		j["totalItems"] = len(xids)
 937		j["orderedItems"] = xids
 938
 939		j.Write(w)
 940		return
 941	}
 942
 943	templinfo := getInfo(r)
 944	templinfo["ServerMessage"] = "honks by ontology: " + name
 945	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 946	honkpage(w, u, honks, templinfo)
 947}
 948
 949type Ont struct {
 950	Name  string
 951	Count int64
 952}
 953
 954func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 955	u := login.GetUserInfo(r)
 956	var userid UserID = -1
 957	if u != nil {
 958		userid = UserID(u.UserID)
 959	}
 960	rows, err := stmtAllOnts.Query(userid)
 961	if err != nil {
 962		elog.Printf("selection error: %s", err)
 963		return
 964	}
 965	defer rows.Close()
 966	var onts, pops []Ont
 967	for rows.Next() {
 968		var o Ont
 969		err := rows.Scan(&o.Name, &o.Count)
 970		if err != nil {
 971			elog.Printf("error scanning ont: %s", err)
 972			continue
 973		}
 974		if utf8.RuneCountInString(o.Name) > 24 {
 975			continue
 976		}
 977		o.Name = o.Name[1:]
 978		onts = append(onts, o)
 979		if o.Count > 1 {
 980			pops = append(pops, o)
 981		}
 982	}
 983	sort.Slice(onts, func(i, j int) bool {
 984		return onts[i].Name < onts[j].Name
 985	})
 986	sort.Slice(pops, func(i, j int) bool {
 987		return pops[i].Count > pops[j].Count
 988	})
 989	if len(pops) > 40 {
 990		pops = pops[:40]
 991	}
 992	var letters []string
 993	var lastrune rune = -1
 994	for _, o := range onts {
 995		if r := firstRune(o.Name); r != lastrune {
 996			letters = append(letters, string(r))
 997			lastrune = r
 998		}
 999	}
1000	if u == nil && !develMode {
1001		w.Header().Set("Cache-Control", "max-age=300")
1002	}
1003	templinfo := getInfo(r)
1004	templinfo["Pops"] = pops
1005	templinfo["Onts"] = onts
1006	templinfo["Letters"] = letters
1007	templinfo["FirstRune"] = firstRune
1008	err = readviews.Execute(w, "onts.html", templinfo)
1009	if err != nil {
1010		elog.Print(err)
1011	}
1012}
1013
1014type Track struct {
1015	xid string
1016	who string
1017}
1018
1019func getbacktracks(xid string) []string {
1020	c := make(chan bool)
1021	dumptracks <- c
1022	<-c
1023	row := stmtGetTracks.QueryRow(xid)
1024	var rawtracks string
1025	err := row.Scan(&rawtracks)
1026	if err != nil {
1027		if err != sql.ErrNoRows {
1028			elog.Printf("error scanning tracks: %s", err)
1029		}
1030		return nil
1031	}
1032	var rcpts []string
1033	for _, f := range strings.Split(rawtracks, " ") {
1034		idx := strings.LastIndexByte(f, '#')
1035		if idx != -1 {
1036			f = f[:idx]
1037		}
1038		if !strings.HasPrefix(f, "https://") {
1039			f = fmt.Sprintf("%%https://%s/inbox", f)
1040		}
1041		rcpts = append(rcpts, f)
1042	}
1043	return rcpts
1044}
1045
1046func savetracks(tracks map[string][]string) {
1047	db := opendatabase()
1048	tx, err := db.Begin()
1049	if err != nil {
1050		elog.Printf("savetracks begin error: %s", err)
1051		return
1052	}
1053	defer func() {
1054		err := tx.Commit()
1055		if err != nil {
1056			elog.Printf("savetracks commit error: %s", err)
1057		}
1058
1059	}()
1060	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
1061	if err != nil {
1062		elog.Printf("savetracks error: %s", err)
1063		return
1064	}
1065	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
1066	if err != nil {
1067		elog.Printf("savetracks error: %s", err)
1068		return
1069	}
1070	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
1071	if err != nil {
1072		elog.Printf("savetracks error: %s", err)
1073		return
1074	}
1075	count := 0
1076	for xid, f := range tracks {
1077		count += len(f)
1078		var prev string
1079		row := stmtGetTracks.QueryRow(xid)
1080		err := row.Scan(&prev)
1081		if err == sql.ErrNoRows {
1082			f = oneofakind(f)
1083			stmtNewTracks.Exec(xid, strings.Join(f, " "))
1084		} else if err == nil {
1085			all := append(strings.Split(prev, " "), f...)
1086			all = oneofakind(all)
1087			stmtUpdateTracks.Exec(strings.Join(all, " "))
1088		} else {
1089			elog.Printf("savetracks error: %s", err)
1090		}
1091	}
1092	dlog.Printf("saved %d new fetches", count)
1093}
1094
1095var trackchan = make(chan Track)
1096var dumptracks = make(chan chan bool)
1097
1098func tracker() {
1099	timeout := 4 * time.Minute
1100	sleeper := time.NewTimer(timeout)
1101	tracks := make(map[string][]string)
1102	workinprogress++
1103	for {
1104		select {
1105		case track := <-trackchan:
1106			tracks[track.xid] = append(tracks[track.xid], track.who)
1107		case <-sleeper.C:
1108			if len(tracks) > 0 {
1109				go savetracks(tracks)
1110				tracks = make(map[string][]string)
1111			}
1112			sleeper.Reset(timeout)
1113		case c := <-dumptracks:
1114			if len(tracks) > 0 {
1115				savetracks(tracks)
1116			}
1117			c <- true
1118		case <-endoftheworld:
1119			if len(tracks) > 0 {
1120				savetracks(tracks)
1121			}
1122			readyalready <- true
1123			return
1124		}
1125	}
1126}
1127
1128var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1129
1130func requestActor(r *http.Request) string {
1131	if sig := r.Header.Get("Signature"); sig != "" {
1132		if m := re_keyholder.FindStringSubmatch(sig); len(m) == 2 {
1133			return m[1]
1134		}
1135	}
1136	return ""
1137}
1138
1139func trackback(xid string, r *http.Request) {
1140	who := requestActor(r)
1141	if who != "" {
1142		trackchan <- Track{xid: xid, who: who}
1143	}
1144}
1145
1146func sameperson(h1, h2 *Honk) bool {
1147	n1, n2 := h1.Honker, h2.Honker
1148	if h1.Oonker != "" {
1149		n1 = h1.Oonker
1150	}
1151	if h2.Oonker != "" {
1152		n2 = h2.Oonker
1153	}
1154	return n1 == n2
1155}
1156
1157func threadposes(honks []*Honk, wanted int64) ([]*Honk, []int) {
1158	var poses []int
1159	var newhonks []*Honk
1160	for i, honk := range honks {
1161		if honk.ID > wanted {
1162			newhonks = append(newhonks, honk)
1163			poses = append(poses, i)
1164		}
1165	}
1166	return newhonks, poses
1167}
1168
1169func threadsort(honks []*Honk) []*Honk {
1170	sort.Slice(honks, func(i, j int) bool {
1171		return honks[i].Date.Before(honks[j].Date)
1172	})
1173	honkx := make(map[string]*Honk)
1174	kids := make(map[string][]*Honk)
1175	for _, h := range honks {
1176		honkx[h.XID] = h
1177		rid := h.RID
1178		kids[rid] = append(kids[rid], h)
1179	}
1180	done := make(map[*Honk]bool)
1181	var thread []*Honk
1182	var nextlevel func(p *Honk)
1183	level := 0
1184	nextlevel = func(p *Honk) {
1185		levelup := level < 4
1186		if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1187			levelup = false
1188		}
1189		if level > 0 && len(kids[p.RID]) == 1 {
1190			if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1191				levelup = false
1192			}
1193		}
1194		if levelup {
1195			level++
1196		}
1197		p.Style += fmt.Sprintf(" level%d", level)
1198		childs := kids[p.XID]
1199		if false {
1200			sort.SliceStable(childs, func(i, j int) bool {
1201				return sameperson(childs[i], p) && !sameperson(childs[j], p)
1202			})
1203		}
1204		if true {
1205			sort.SliceStable(childs, func(i, j int) bool {
1206				return !sameperson(childs[i], p) && sameperson(childs[j], p)
1207			})
1208		}
1209		for _, h := range childs {
1210			if !done[h] {
1211				done[h] = true
1212				thread = append(thread, h)
1213				nextlevel(h)
1214			}
1215		}
1216		if levelup {
1217			level--
1218		}
1219	}
1220	for _, h := range honks {
1221		if !done[h] && h.RID == "" {
1222			done[h] = true
1223			thread = append(thread, h)
1224			nextlevel(h)
1225		}
1226	}
1227	for _, h := range honks {
1228		if !done[h] {
1229			done[h] = true
1230			thread = append(thread, h)
1231			nextlevel(h)
1232		}
1233	}
1234	return thread
1235}
1236
1237func oguser(user *WhatAbout) template.HTML {
1238	short := user.About
1239	if len(short) > 160 {
1240		short = short[0:160] + "..."
1241	}
1242	title := user.Display
1243	imgurl := avatarURL(user)
1244	return templates.Sprintf(
1245		`<meta property="og:title" content="%s" />
1246<meta property="og:type" content="website" />
1247<meta property="og:url" content="%s" />
1248<meta property="og:image" content="%s" />
1249<meta property="og:description" content="%s" />`,
1250		title, user.URL, imgurl, short)
1251}
1252
1253func honkology(honk *Honk) template.HTML {
1254	user, ok := somenumberedusers.Get(honk.UserID)
1255	if !ok {
1256		return ""
1257	}
1258	title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1259	imgurl := avatarURL(user)
1260	for _, d := range honk.Donks {
1261		if d.Local && strings.HasPrefix(d.Media, "image") {
1262			imgurl = d.URL
1263			break
1264		}
1265	}
1266	short := honk.Noise
1267	if len(short) > 160 {
1268		short = short[0:160] + "..."
1269	}
1270	return templates.Sprintf(
1271		`<meta property="og:title" content="%s" />
1272<meta property="og:type" content="article" />
1273<meta property="article:author" content="%s" />
1274<meta property="og:url" content="%s" />
1275<meta property="og:image" content="%s" />
1276<meta property="og:description" content="%s" />`,
1277		title, user.URL, honk.XID, imgurl, short)
1278}
1279
1280func showonehonk(w http.ResponseWriter, r *http.Request) {
1281	name := mux.Vars(r)["name"]
1282	user, err := butwhatabout(name)
1283	if err != nil {
1284		http.NotFound(w, r)
1285		return
1286	}
1287	if stealthmode(user.ID, r) {
1288		http.NotFound(w, r)
1289		return
1290	}
1291	wantjson := false
1292	path := r.URL.Path
1293	if strings.HasSuffix(path, ".json") {
1294		path = path[:len(path)-5]
1295		wantjson = true
1296	}
1297	xid := serverURL("%s", path)
1298
1299	if friendorfoe(r.Header.Get("Accept")) || wantjson {
1300		j, ok := gimmejonk(xid)
1301		if ok {
1302			trackback(xid, r)
1303			w.Header().Set("Content-Type", theonetruename)
1304			w.Write(j)
1305		} else {
1306			http.NotFound(w, r)
1307		}
1308		return
1309	}
1310	honk := getxonk(user.ID, xid)
1311	if honk == nil {
1312		http.NotFound(w, r)
1313		return
1314	}
1315	u := login.GetUserInfo(r)
1316	if u != nil && UserID(u.UserID) != user.ID {
1317		u = nil
1318	}
1319	if !honk.Public {
1320		if u == nil {
1321			http.NotFound(w, r)
1322			return
1323
1324		}
1325		honks := []*Honk{honk}
1326		donksforhonks(honks)
1327		templinfo := getInfo(r)
1328		templinfo["ServerMessage"] = "one honk maybe more"
1329		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1330		honkpage(w, u, honks, templinfo)
1331		return
1332	}
1333
1334	templinfo := getInfo(r)
1335	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1336	//reversehonks(rawhonks)
1337	rawhonks = threadsort(rawhonks)
1338	var honks []*Honk
1339	for i, h := range rawhonks {
1340		if h.XID == xid {
1341			templinfo["Honkology"] = honkology(h)
1342			if i > 0 {
1343				h.Style += " glow"
1344			}
1345		}
1346		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1347			honks = append(honks, h)
1348		}
1349	}
1350
1351	templinfo["ServerMessage"] = "one honk maybe more"
1352	if u != nil {
1353		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1354	}
1355	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1356	honkpage(w, u, honks, templinfo)
1357}
1358
1359func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1360	var userid UserID = -1
1361	if u != nil {
1362		userid = UserID(u.UserID)
1363		templinfo["User"], _ = butwhatabout(u.Username)
1364	}
1365	reverbolate(userid, honks)
1366	templinfo["Honks"] = honks
1367	templinfo["MapLink"] = getmaplink(u)
1368	if templinfo["TopHID"] == nil {
1369		if len(honks) > 0 {
1370			templinfo["TopHID"] = honks[0].ID
1371		} else {
1372			templinfo["TopHID"] = 0
1373		}
1374	}
1375	if u == nil && !develMode {
1376		w.Header().Set("Cache-Control", "max-age=60")
1377	}
1378	err := readviews.Execute(w, "honkpage.html", templinfo)
1379	if err != nil {
1380		elog.Print(err)
1381	}
1382}
1383
1384func saveuser(w http.ResponseWriter, r *http.Request) {
1385	whatabout := r.FormValue("whatabout")
1386	whatabout = strings.Replace(whatabout, "\r", "", -1)
1387	u := login.GetUserInfo(r)
1388	user, _ := butwhatabout(u.Username)
1389	db := opendatabase()
1390
1391	options := user.Options
1392	options.SkinnyCSS = r.FormValue("skinny") == "skinny"
1393	options.OmitImages = r.FormValue("omitimages") == "omitimages"
1394	options.MentionAll = r.FormValue("mentionall") == "mentionall"
1395	options.InlineQuotes = r.FormValue("inlineqts") == "inlineqts"
1396	options.MapLink = r.FormValue("maps")
1397	options.Reaction = r.FormValue("reaction")
1398
1399	sendupdate := false
1400	ava := re_avatar.FindString(whatabout)
1401	if ava != "" {
1402		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1403		ava = ava[7:]
1404		if ava[0] == ' ' {
1405			ava = ava[1:]
1406		}
1407		ava = serverURL("/meme/%s", ava)
1408	}
1409	if ava != options.Avatar {
1410		options.Avatar = ava
1411		sendupdate = true
1412	}
1413	ban := re_banner.FindString(whatabout)
1414	if ban != "" {
1415		whatabout = re_banner.ReplaceAllString(whatabout, "")
1416		ban = ban[7:]
1417		if ban[0] == ' ' {
1418			ban = ban[1:]
1419		}
1420		ban = serverURL("/meme/%s", ban)
1421	}
1422	if ban != options.Banner {
1423		options.Banner = ban
1424		sendupdate = true
1425	}
1426	whatabout = strings.TrimSpace(whatabout)
1427	if whatabout != user.About {
1428		sendupdate = true
1429	}
1430	j, err := jsonify(options)
1431	if err == nil {
1432		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1433	}
1434	if err != nil {
1435		elog.Printf("error bouting what: %s", err)
1436	}
1437	somenamedusers.Clear(u.Username)
1438	somenumberedusers.Clear(user.ID)
1439	oldjonkers.Clear(u.Username)
1440
1441	if sendupdate {
1442		updateMe(u.Username)
1443	}
1444
1445	http.Redirect(w, r, "/account", http.StatusSeeOther)
1446}
1447
1448func bonkit(xid string, user *WhatAbout) {
1449	dlog.Printf("bonking %s", xid)
1450
1451	xonk := getxonk(user.ID, xid)
1452	if xonk == nil {
1453		return
1454	}
1455	if !xonk.Public {
1456		return
1457	}
1458	if xonk.IsBonked() {
1459		return
1460	}
1461	donksforhonks([]*Honk{xonk})
1462
1463	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1464	if err != nil {
1465		elog.Printf("error acking bonk: %s", err)
1466	}
1467
1468	oonker := xonk.Oonker
1469	if oonker == "" {
1470		oonker = xonk.Honker
1471	}
1472	dt := time.Now().UTC()
1473	bonk := &Honk{
1474		UserID:   user.ID,
1475		Username: user.Name,
1476		What:     "bonk",
1477		Honker:   user.URL,
1478		Oonker:   oonker,
1479		XID:      xonk.XID,
1480		RID:      xonk.RID,
1481		Noise:    xonk.Noise,
1482		Precis:   xonk.Precis,
1483		URL:      xonk.URL,
1484		Date:     dt,
1485		Donks:    xonk.Donks,
1486		Whofore:  2,
1487		Convoy:   xonk.Convoy,
1488		Audience: []string{thewholeworld, oonker},
1489		Public:   true,
1490		Format:   xonk.Format,
1491		Place:    xonk.Place,
1492		Onts:     xonk.Onts,
1493		Time:     xonk.Time,
1494	}
1495
1496	err = savehonk(bonk)
1497	if err != nil {
1498		elog.Printf("uh oh")
1499		return
1500	}
1501
1502	go honkworldwide(user, bonk)
1503}
1504
1505func submitbonk(w http.ResponseWriter, r *http.Request) {
1506	xid := r.FormValue("xid")
1507	userinfo := login.GetUserInfo(r)
1508	user, _ := butwhatabout(userinfo.Username)
1509
1510	bonkit(xid, user)
1511
1512	if r.FormValue("js") != "1" {
1513		templinfo := getInfo(r)
1514		templinfo["ServerMessage"] = "Bonked!"
1515		err := readviews.Execute(w, "msg.html", templinfo)
1516		if err != nil {
1517			elog.Print(err)
1518		}
1519	}
1520}
1521
1522func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1523	zonk := &Honk{
1524		What:     what,
1525		XID:      xonk.XID,
1526		Date:     time.Now().UTC(),
1527		Audience: oneofakind(xonk.Audience),
1528		Noise:    aux,
1529	}
1530	zonk.Public = loudandproud(zonk.Audience)
1531
1532	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1533	go honkworldwide(user, zonk)
1534}
1535
1536func zonkit(w http.ResponseWriter, r *http.Request) {
1537	wherefore := r.FormValue("wherefore")
1538	what := r.FormValue("what")
1539	u := login.GetUserInfo(r)
1540	user, _ := butwhatabout(u.Username)
1541
1542	if wherefore == "save" {
1543		xonk := getxonk(user.ID, what)
1544		if xonk != nil {
1545			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1546			if err != nil {
1547				elog.Printf("error saving: %s", err)
1548			}
1549		}
1550		return
1551	}
1552
1553	if wherefore == "unsave" {
1554		xonk := getxonk(user.ID, what)
1555		if xonk != nil {
1556			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1557			if err != nil {
1558				elog.Printf("error unsaving: %s", err)
1559			}
1560		}
1561		return
1562	}
1563
1564	if wherefore == "react" {
1565		reaction := user.Options.Reaction
1566		if r2 := r.FormValue("reaction"); r2 != "" {
1567			reaction = r2
1568		}
1569		if reaction == "none" {
1570			return
1571		}
1572		xonk := getxonk(user.ID, what)
1573		if xonk != nil {
1574			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1575			if err != nil {
1576				elog.Printf("error saving: %s", err)
1577			}
1578			sendzonkofsorts(xonk, user, "react", reaction)
1579		}
1580		return
1581	}
1582
1583	// my hammer is too big, oh well
1584	defer oldjonks.Flush()
1585
1586	if wherefore == "ack" {
1587		xonk := getxonk(user.ID, what)
1588		if xonk != nil && !xonk.IsAcked() {
1589			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1590			if err != nil {
1591				elog.Printf("error acking: %s", err)
1592			}
1593			sendzonkofsorts(xonk, user, "ack", "")
1594		}
1595		return
1596	}
1597
1598	if wherefore == "deack" {
1599		xonk := getxonk(user.ID, what)
1600		if xonk != nil && xonk.IsAcked() {
1601			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1602			if err != nil {
1603				elog.Printf("error deacking: %s", err)
1604			}
1605			sendzonkofsorts(xonk, user, "deack", "")
1606		}
1607		return
1608	}
1609
1610	if wherefore == "bonk" {
1611		bonkit(what, user)
1612		return
1613	}
1614
1615	if wherefore == "unbonk" {
1616		xonk := getbonk(user.ID, what)
1617		if xonk != nil {
1618			deletehonk(xonk.ID)
1619			xonk = getxonk(user.ID, what)
1620			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1621			if err != nil {
1622				elog.Printf("error unbonking: %s", err)
1623			}
1624			sendzonkofsorts(xonk, user, "unbonk", "")
1625		}
1626		return
1627	}
1628
1629	if wherefore == "untag" {
1630		xonk := getxonk(user.ID, what)
1631		if xonk != nil {
1632			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1633			if err != nil {
1634				elog.Printf("error untagging: %s", err)
1635			}
1636		}
1637		var badparents map[string]bool
1638		untagged.GetAndLock(user.ID, &badparents)
1639		badparents[what] = true
1640		untagged.Unlock()
1641		return
1642	}
1643
1644	ilog.Printf("zonking %s %s", wherefore, what)
1645	if wherefore == "zonk" {
1646		xonk := getxonk(user.ID, what)
1647		if xonk != nil {
1648			deletehonk(xonk.ID)
1649			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1650				sendzonkofsorts(xonk, user, "zonk", "")
1651			}
1652		}
1653	}
1654	_, err := stmtSaveZonker.Exec(user.ID, what, wherefore)
1655	if err != nil {
1656		elog.Printf("error saving zonker: %s", err)
1657		return
1658	}
1659}
1660
1661func edithonkpage(w http.ResponseWriter, r *http.Request) {
1662	u := login.GetUserInfo(r)
1663	user, _ := butwhatabout(u.Username)
1664	xid := r.FormValue("xid")
1665	honk := getxonk(user.ID, xid)
1666	if !canedithonk(user, honk) {
1667		http.Error(w, "no editing that please", http.StatusInternalServerError)
1668		return
1669	}
1670	noise := honk.Noise
1671	var savedfiles []string
1672
1673	honks := []*Honk{honk}
1674	donksforhonks(honks)
1675	for _, d := range honk.Donks {
1676		savedfiles = append(savedfiles, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1677	}
1678	reverbolate(user.ID, honks)
1679
1680	templinfo := getInfo(r)
1681	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1682	templinfo["Honks"] = honks
1683	templinfo["MapLink"] = getmaplink(u)
1684	templinfo["Noise"] = noise
1685	templinfo["SavedPlace"] = honk.Place
1686	if tm := honk.Time; tm != nil {
1687		templinfo["ShowTime"] = " "
1688		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1689		if tm.Duration != 0 {
1690			templinfo["Duration"] = tm.Duration
1691		}
1692	}
1693	templinfo["Onties"] = honk.Onties
1694	templinfo["SeeAlso"] = honk.SeeAlso
1695	templinfo["Link"] = honk.Link
1696	templinfo["LegalName"] = honk.LegalName
1697	templinfo["ServerMessage"] = "honk edit"
1698	templinfo["IsPreview"] = true
1699	templinfo["UpdateXID"] = honk.XID
1700	if len(savedfiles) > 0 {
1701		templinfo["SavedFile"] = strings.Join(savedfiles, ",")
1702	}
1703	err := readviews.Execute(w, "honkpage.html", templinfo)
1704	if err != nil {
1705		elog.Print(err)
1706	}
1707}
1708
1709func newhonkpage(w http.ResponseWriter, r *http.Request) {
1710	u := login.GetUserInfo(r)
1711	rid := r.FormValue("rid")
1712	noise := ""
1713
1714	xonk := getxonk(UserID(u.UserID), rid)
1715	if xonk != nil {
1716		_, replto := handles(xonk.Honker)
1717		if replto != "" {
1718			noise = "@" + replto + " "
1719		}
1720	}
1721
1722	templinfo := getInfo(r)
1723	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1724	templinfo["InReplyTo"] = rid
1725	templinfo["Noise"] = noise
1726	templinfo["ServerMessage"] = "compose honk"
1727	templinfo["IsPreview"] = true
1728	err := readviews.Execute(w, "honkpage.html", templinfo)
1729	if err != nil {
1730		elog.Print(err)
1731	}
1732}
1733
1734func canedithonk(user *WhatAbout, honk *Honk) bool {
1735	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1736		return false
1737	}
1738	return true
1739}
1740
1741func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1742	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1743		return nil, nil
1744	}
1745	var donks []*Donk
1746	for i, hdr := range r.MultipartForm.File["donk"] {
1747		if i > 16 {
1748			break
1749		}
1750		donk, err := formtodonk(w, r, hdr)
1751		if err != nil {
1752			return nil, err
1753		}
1754		donks = append(donks, donk)
1755	}
1756	return donks, nil
1757}
1758
1759func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1760	file, err := filehdr.Open()
1761	if err != nil {
1762		if err == http.ErrMissingFile {
1763			return nil, nil
1764		}
1765		elog.Printf("error reading donk: %s", err)
1766		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1767		return nil, err
1768	}
1769	var buf bytes.Buffer
1770	io.Copy(&buf, file)
1771	file.Close()
1772	data := buf.Bytes()
1773	var media, name string
1774	img, err := bigshrink(data)
1775	if err == nil {
1776		data = img.Data
1777		format := img.Format
1778		media = "image/" + format
1779		if format == "jpeg" {
1780			format = "jpg"
1781		}
1782		if format == "svg+xml" {
1783			format = "svg"
1784		}
1785		name = xfiltrate() + "." + format
1786	} else {
1787		ct := http.DetectContentType(data)
1788		switch ct {
1789		case "application/pdf":
1790			maxsize := 10000000
1791			if len(data) > maxsize {
1792				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1793				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1794				return nil, err
1795			}
1796			media = ct
1797			name = filehdr.Filename
1798			if name == "" {
1799				name = xfiltrate() + ".pdf"
1800			}
1801		default:
1802			maxsize := 100000
1803			if len(data) > maxsize {
1804				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1805				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1806				return nil, err
1807			}
1808			for i := 0; i < len(data); i++ {
1809				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1810					ilog.Printf("bad image: %s not text: %d", err, data[i])
1811					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1812					return nil, err
1813				}
1814			}
1815			media = "text/plain"
1816			name = filehdr.Filename
1817			if name == "" {
1818				name = xfiltrate() + ".txt"
1819			}
1820		}
1821	}
1822	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1823	if desc == "" {
1824		desc = name
1825	}
1826	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1827	if err != nil {
1828		elog.Printf("unable to save image: %s", err)
1829		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1830		return nil, err
1831	}
1832	d := &Donk{
1833		FileID: fileid,
1834		XID:    xid,
1835		Desc:   desc,
1836		Local:  true,
1837	}
1838	return d, nil
1839}
1840
1841func websubmithonk(w http.ResponseWriter, r *http.Request) {
1842	h := submithonk(w, r)
1843	if h == nil {
1844		return
1845	}
1846	redir := h.XID[len(serverURL("")):]
1847	http.Redirect(w, r, redir, http.StatusSeeOther)
1848}
1849
1850// what a hot mess this function is
1851func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1852	rid := r.FormValue("rid")
1853	noise := r.FormValue("noise")
1854	format := r.FormValue("format")
1855	if format == "" {
1856		format = "markdown"
1857	}
1858	if !(format == "markdown" || format == "html") {
1859		http.Error(w, "unknown format", 500)
1860		return nil
1861	}
1862
1863	u := login.GetUserInfo(r)
1864	user, _ := butwhatabout(u.Username)
1865
1866	dt := time.Now().UTC()
1867	updatexid := r.FormValue("updatexid")
1868	var honk *Honk
1869	if updatexid != "" {
1870		honk = getxonk(user.ID, updatexid)
1871		if !canedithonk(user, honk) {
1872			http.Error(w, "no editing that please", http.StatusInternalServerError)
1873			return nil
1874		}
1875		honk.Date = dt
1876		honk.What = "update"
1877		honk.Format = format
1878	} else {
1879		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1880		what := "honk"
1881		honk = &Honk{
1882			UserID:   user.ID,
1883			Username: user.Name,
1884			What:     what,
1885			Honker:   user.URL,
1886			XID:      xid,
1887			Date:     dt,
1888			Format:   format,
1889		}
1890	}
1891	honk.SeeAlso = strings.TrimSpace(r.FormValue("seealso"))
1892	honk.Onties = strings.TrimSpace(r.FormValue("onties"))
1893	honk.Link = strings.TrimSpace(r.FormValue("link"))
1894	honk.LegalName = strings.TrimSpace(r.FormValue("legalname"))
1895
1896	var convoy string
1897	noise = strings.Replace(noise, "\r", "", -1)
1898	if updatexid == "" && rid == "" {
1899		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1900			convoy = m[7:]
1901			convoy = strings.TrimSpace(convoy)
1902			if !re_convalidate.MatchString(convoy) {
1903				convoy = ""
1904			}
1905			return ""
1906		})
1907	}
1908	noise = quickrename(noise, user.ID)
1909	honk.Noise = noise
1910	precipitate(honk)
1911	noise = honk.Noise
1912	translate(honk)
1913
1914	if rid != "" {
1915		xonk := getxonk(user.ID, rid)
1916		if xonk == nil {
1917			http.Error(w, "replyto disappeared", http.StatusNotFound)
1918			return nil
1919		}
1920		if xonk.Public {
1921			honk.Audience = append(honk.Audience, xonk.Audience...)
1922		}
1923		convoy = xonk.Convoy
1924		for i, a := range honk.Audience {
1925			if a == thewholeworld {
1926				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1927				break
1928			}
1929		}
1930		honk.RID = rid
1931		if xonk.Precis != "" && honk.Precis == "" {
1932			honk.Precis = xonk.Precis
1933			if !re_dangerous.MatchString(honk.Precis) {
1934				honk.Precis = "re: " + honk.Precis
1935			}
1936		}
1937	} else if updatexid == "" {
1938		honk.Audience = []string{thewholeworld}
1939	}
1940	if noise != "" && noise[0] == '@' {
1941		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1942	} else {
1943		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1944	}
1945	honk.Convoy = convoy
1946
1947	if honk.Convoy == "" {
1948		honk.Convoy = "data:,electrichonkytonk-" + xfiltrate()
1949	}
1950	butnottooloud(honk.Audience)
1951	honk.Audience = oneofakind(honk.Audience)
1952	if len(honk.Audience) == 0 {
1953		ilog.Printf("honk to nowhere")
1954		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1955		return nil
1956	}
1957	honk.Public = loudandproud(honk.Audience)
1958
1959	donkxid := strings.Join(r.Form["donkxid"], ",")
1960	if donkxid == "" {
1961		donks, err := submitdonk(w, r)
1962		if err != nil && err != http.ErrMissingFile {
1963			return nil
1964		}
1965		if len(donks) > 0 {
1966			honk.Donks = append(honk.Donks, donks...)
1967			var xids []string
1968			for _, d := range honk.Donks {
1969				xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1970			}
1971			donkxid = strings.Join(xids, ",")
1972		}
1973	} else {
1974		xids := strings.Split(donkxid, ",")
1975		for i, xid := range xids {
1976			if i > 16 {
1977				break
1978			}
1979			p := strings.Split(xid, ":")
1980			xid = p[0]
1981			url := serverURL("/d/%s", xid)
1982			var donk *Donk
1983			if len(p) > 1 {
1984				fileid, _ := strconv.ParseInt(p[1], 10, 0)
1985				donk = finddonkid(fileid, url)
1986			} else {
1987				donk = finddonk(url)
1988			}
1989			if donk != nil {
1990				honk.Donks = append(honk.Donks, donk)
1991			} else {
1992				ilog.Printf("can't find file: %s", xid)
1993			}
1994		}
1995	}
1996	memetize(honk)
1997	imaginate(honk)
1998
1999	placename := strings.TrimSpace(r.FormValue("placename"))
2000	placelat := strings.TrimSpace(r.FormValue("placelat"))
2001	placelong := strings.TrimSpace(r.FormValue("placelong"))
2002	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
2003	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
2004		p := new(Place)
2005		p.Name = placename
2006		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
2007		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
2008		p.Url = placeurl
2009		honk.Place = p
2010	}
2011	timestart := strings.TrimSpace(r.FormValue("timestart"))
2012	if timestart != "" {
2013		t := new(Time)
2014		now := time.Now().Local()
2015		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
2016			start, err := time.ParseInLocation(layout, timestart, now.Location())
2017			if err == nil {
2018				if start.Year() == 0 {
2019					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
2020				}
2021				t.StartTime = start
2022				break
2023			}
2024		}
2025		timeend := r.FormValue("timeend")
2026		dur := parseDuration(timeend)
2027		if dur != 0 {
2028			t.Duration = Duration(dur)
2029		}
2030		if !t.StartTime.IsZero() {
2031			honk.What = "event"
2032			honk.Time = t
2033		}
2034	}
2035
2036	if honk.Public {
2037		honk.Whofore = 2
2038	} else {
2039		honk.Whofore = 3
2040	}
2041
2042	// back to markdown
2043	honk.Noise = noise
2044
2045	if r.FormValue("preview") == "preview" {
2046		honks := []*Honk{honk}
2047		reverbolate(user.ID, honks)
2048		templinfo := getInfo(r)
2049		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2050		templinfo["Honks"] = honks
2051		templinfo["MapLink"] = getmaplink(u)
2052		templinfo["InReplyTo"] = r.FormValue("rid")
2053		templinfo["Noise"] = r.FormValue("noise")
2054		templinfo["Onties"] = honk.Onties
2055		templinfo["SeeAlso"] = honk.SeeAlso
2056		templinfo["Link"] = honk.Link
2057		templinfo["LegalName"] = honk.LegalName
2058		templinfo["SavedFile"] = donkxid
2059		if tm := honk.Time; tm != nil {
2060			templinfo["ShowTime"] = " "
2061			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
2062			if tm.Duration != 0 {
2063				templinfo["Duration"] = tm.Duration
2064			}
2065		}
2066		templinfo["IsPreview"] = true
2067		templinfo["UpdateXID"] = updatexid
2068		templinfo["ServerMessage"] = "honk preview"
2069		err := readviews.Execute(w, "honkpage.html", templinfo)
2070		if err != nil {
2071			elog.Print(err)
2072		}
2073		return nil
2074	}
2075
2076	if updatexid != "" {
2077		updatehonk(honk)
2078		oldjonks.Clear(honk.XID)
2079	} else {
2080		err := savehonk(honk)
2081		if err != nil {
2082			elog.Printf("uh oh")
2083			return nil
2084		}
2085	}
2086
2087	// reload for consistency
2088	honk.Donks = nil
2089	donksforhonks([]*Honk{honk})
2090
2091	go honkworldwide(user, honk)
2092
2093	return honk
2094}
2095
2096func firstRune(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
2097
2098func showhonkers(w http.ResponseWriter, r *http.Request) {
2099	userid := UserID(login.GetUserInfo(r).UserID)
2100	honkers := gethonkers(userid)
2101	var letters []string
2102	var lastrune rune = -1
2103	for _, h := range honkers {
2104		if r := firstRune(h.Name); r != lastrune {
2105			letters = append(letters, string(r))
2106			lastrune = r
2107		}
2108	}
2109	templinfo := getInfo(r)
2110	templinfo["FirstRune"] = firstRune
2111	templinfo["Letters"] = letters
2112	templinfo["Honkers"] = honkers
2113	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2114	err := readviews.Execute(w, "honkers.html", templinfo)
2115	if err != nil {
2116		elog.Print(err)
2117	}
2118}
2119
2120func showchatter(w http.ResponseWriter, r *http.Request) {
2121	u := login.GetUserInfo(r)
2122	chatnewnone(UserID(u.UserID))
2123	chatter := loadchatter(UserID(u.UserID))
2124	for _, chat := range chatter {
2125		for _, ch := range chat.Chonks {
2126			filterchonk(ch)
2127		}
2128	}
2129
2130	templinfo := getInfo(r)
2131	templinfo["Chatter"] = chatter
2132	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2133	err := readviews.Execute(w, "chatter.html", templinfo)
2134	if err != nil {
2135		elog.Print(err)
2136	}
2137}
2138
2139func submitchonk(w http.ResponseWriter, r *http.Request) {
2140	u := login.GetUserInfo(r)
2141	user, _ := butwhatabout(u.Username)
2142	noise := r.FormValue("noise")
2143	target := r.FormValue("target")
2144	format := "markdown"
2145	dt := time.Now().UTC()
2146	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2147
2148	if !strings.HasPrefix(target, "https://") {
2149		target = fullname(target, user.ID)
2150	}
2151	if target == "" {
2152		http.Error(w, "who is that?", http.StatusInternalServerError)
2153		return
2154	}
2155	ch := Chonk{
2156		UserID: user.ID,
2157		XID:    xid,
2158		Who:    user.URL,
2159		Target: target,
2160		Date:   dt,
2161		Noise:  noise,
2162		Format: format,
2163	}
2164	donks, err := submitdonk(w, r)
2165	if err != nil && err != http.ErrMissingFile {
2166		return
2167	}
2168	if len(donks) > 0 {
2169		ch.Donks = append(ch.Donks, donks...)
2170	}
2171
2172	translatechonk(&ch)
2173	savechonk(&ch)
2174	// reload for consistency
2175	ch.Donks = nil
2176	donksforchonks([]*Chonk{&ch})
2177	go sendchonk(user, &ch)
2178
2179	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2180}
2181
2182var combocache = gencache.New(gencache.Options[UserID, []string]{Fill: func(userid UserID) ([]string, bool) {
2183	honkers := gethonkers(userid)
2184	var combos []string
2185	for _, h := range honkers {
2186		combos = append(combos, h.Combos...)
2187	}
2188	for i, c := range combos {
2189		if c == "-" {
2190			combos[i] = ""
2191		}
2192	}
2193	combos = oneofakind(combos)
2194	sort.Strings(combos)
2195	return combos, true
2196}, Invalidator: &honkerinvalidator})
2197
2198func showcombos(w http.ResponseWriter, r *http.Request) {
2199	templinfo := getInfo(r)
2200	err := readviews.Execute(w, "combos.html", templinfo)
2201	if err != nil {
2202		elog.Print(err)
2203	}
2204}
2205
2206func websubmithonker(w http.ResponseWriter, r *http.Request) {
2207	h := submithonker(w, r)
2208	if h == nil {
2209		return
2210	}
2211	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2212}
2213
2214func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2215	u := login.GetUserInfo(r)
2216	user, _ := butwhatabout(u.Username)
2217	name := strings.TrimSpace(r.FormValue("name"))
2218	url := strings.TrimSpace(r.FormValue("url"))
2219	peep := r.FormValue("peep")
2220	combos := strings.TrimSpace(r.FormValue("combos"))
2221	combos = " " + combos + " "
2222	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2223
2224	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2225	if name != "" && !re_namecheck.MatchString(name) {
2226		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2227		return nil
2228	}
2229
2230	var meta HonkerMeta
2231	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2232	mj, _ := jsonify(&meta)
2233
2234	defer honkerinvalidator.Clear(user.ID)
2235
2236	// mostly dummy, fill in later...
2237	h := &Honker{
2238		ID: honkerid,
2239	}
2240
2241	if honkerid > 0 {
2242		if r.FormValue("delete") == "delete" {
2243			unfollowyou(user, honkerid, false)
2244			stmtDeleteHonker.Exec(honkerid)
2245			return h
2246		}
2247		if r.FormValue("unsub") == "unsub" {
2248			unfollowyou(user, honkerid, false)
2249		}
2250		if r.FormValue("sub") == "sub" {
2251			followyou(user, honkerid, false)
2252		}
2253		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, user.ID)
2254		if err != nil {
2255			elog.Printf("update honker err: %s", err)
2256			return nil
2257		}
2258		return h
2259	}
2260
2261	if url == "" {
2262		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2263		return nil
2264	}
2265
2266	flavor := "presub"
2267	if peep == "peep" {
2268		flavor = "peep"
2269	}
2270
2271	var err error
2272	honkerid, flavor, err = savehonker(user, url, name, flavor, combos, mj)
2273	if err != nil {
2274		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2275		return nil
2276	}
2277	if flavor == "presub" {
2278		followyou(user, honkerid, false)
2279	}
2280	h.ID = honkerid
2281	return h
2282}
2283
2284func hfcspage(w http.ResponseWriter, r *http.Request) {
2285	u := login.GetUserInfo(r)
2286
2287	filters := getfilters(UserID(u.UserID), filtAny)
2288
2289	templinfo := getInfo(r)
2290	templinfo["Filters"] = filters
2291	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2292	err := readviews.Execute(w, "hfcs.html", templinfo)
2293	if err != nil {
2294		elog.Print(err)
2295	}
2296}
2297
2298func accountpage(w http.ResponseWriter, r *http.Request) {
2299	u := login.GetUserInfo(r)
2300	user, _ := butwhatabout(u.Username)
2301	templinfo := getInfo(r)
2302	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2303	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2304	templinfo["User"] = user
2305	about := user.About
2306	if ava := user.Options.Avatar; ava != "" {
2307		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2308	}
2309	if ban := user.Options.Banner; ban != "" {
2310		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2311	}
2312	templinfo["WhatAbout"] = about
2313	err := readviews.Execute(w, "account.html", templinfo)
2314	if err != nil {
2315		elog.Print(err)
2316	}
2317}
2318
2319func dochpass(w http.ResponseWriter, r *http.Request) {
2320	err := login.ChangePassword(w, r)
2321	if err != nil {
2322		elog.Printf("error changing password: %s", err)
2323	}
2324	http.Redirect(w, r, "/account", http.StatusSeeOther)
2325}
2326
2327var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2328	if strings.HasPrefix(orig, "acct:") {
2329		orig = orig[5:]
2330	}
2331	name := orig
2332	idx := strings.LastIndexByte(name, '/')
2333	if idx != -1 {
2334		name = name[idx+1:]
2335		if serverURL("/%s/%s", userSep, name) != orig {
2336			ilog.Printf("foreign request rejected")
2337			name = ""
2338		}
2339	} else {
2340		idx = strings.IndexByte(name, '@')
2341		if idx != -1 {
2342			name = name[:idx]
2343			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2344				ilog.Printf("foreign request rejected")
2345				name = ""
2346			}
2347		}
2348	}
2349	user, err := butwhatabout(name)
2350	if err != nil {
2351		return nil, false
2352	}
2353
2354	j := junk.New()
2355	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2356	j["aliases"] = []string{user.URL}
2357	l := junk.New()
2358	l["rel"] = "self"
2359	l["type"] = `application/activity+json`
2360	l["href"] = user.URL
2361	j["links"] = []junk.Junk{l}
2362	return j.ToBytes(), true
2363}})
2364
2365func fingerlicker(w http.ResponseWriter, r *http.Request) {
2366	orig := r.FormValue("resource")
2367
2368	dlog.Printf("finger lick: %s", orig)
2369
2370	j, ok := oldfingers.Get(orig)
2371	if ok {
2372		w.Header().Set("Content-Type", "application/jrd+json")
2373		w.Write(j)
2374	} else {
2375		http.NotFound(w, r)
2376	}
2377}
2378
2379func somedays() string {
2380	secs := 432000 + notrand.Int63n(432000)
2381	return fmt.Sprintf("%d", secs)
2382}
2383
2384func lookatme(ava string) string {
2385	if strings.Contains(ava, serverName+"/"+userSep) {
2386		idx := strings.LastIndexByte(ava, '/')
2387		if idx < len(ava) {
2388			name := ava[idx+1:]
2389			user, _ := butwhatabout(name)
2390			if user != nil && user.URL == ava {
2391				return user.Options.Avatar
2392			}
2393		}
2394	}
2395	return ""
2396}
2397
2398func avatate(w http.ResponseWriter, r *http.Request) {
2399	if develMode {
2400		loadAvatarColors()
2401	}
2402	n := r.FormValue("a")
2403	if redir := lookatme(n); redir != "" {
2404		http.Redirect(w, r, redir, http.StatusSeeOther)
2405		return
2406	}
2407	a := genAvatar(n)
2408	if !develMode {
2409		w.Header().Set("Cache-Control", "max-age="+somedays())
2410	}
2411	w.Write(a)
2412}
2413
2414func serveviewasset(w http.ResponseWriter, r *http.Request) {
2415	serveasset(w, r, viewDir)
2416}
2417func servedataasset(w http.ResponseWriter, r *http.Request) {
2418	if r.URL.Path == "/favicon.ico" {
2419		r.URL.Path = "/icon.png"
2420	}
2421	serveasset(w, r, dataDir)
2422}
2423
2424func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2425	if !develMode {
2426		w.Header().Set("Cache-Control", "max-age=7776000")
2427	}
2428	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2429}
2430func servehelp(w http.ResponseWriter, r *http.Request) {
2431	name := mux.Vars(r)["name"]
2432	if !develMode {
2433		w.Header().Set("Cache-Control", "max-age=3600")
2434	}
2435	http.ServeFile(w, r, viewDir+"/docs/"+name)
2436}
2437func servehtml(w http.ResponseWriter, r *http.Request) {
2438	u := login.GetUserInfo(r)
2439	templinfo := getInfo(r)
2440	templinfo["AboutMsg"] = aboutMsg
2441	templinfo["LoginMsg"] = loginMsg
2442	templinfo["HonkVersion"] = softwareVersion
2443	if r.URL.Path == "/about" {
2444		templinfo["Sensors"] = getSensors()
2445	}
2446	if u == nil && !develMode {
2447		w.Header().Set("Cache-Control", "max-age=60")
2448	}
2449	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2450	if err != nil {
2451		elog.Print(err)
2452	}
2453}
2454func serveemu(w http.ResponseWriter, r *http.Request) {
2455	emu := mux.Vars(r)["emu"]
2456
2457	w.Header().Set("Cache-Control", "max-age="+somedays())
2458	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2459}
2460func servememe(w http.ResponseWriter, r *http.Request) {
2461	meme := mux.Vars(r)["meme"]
2462
2463	w.Header().Set("Cache-Control", "max-age="+somedays())
2464	_, err := os.Stat(dataDir + "/memes/" + meme)
2465	if err == nil {
2466		http.ServeFile(w, r, dataDir+"/memes/"+meme)
2467	} else {
2468		mux.Vars(r)["xid"] = meme
2469		servefile(w, r)
2470	}
2471}
2472
2473func servefile(w http.ResponseWriter, r *http.Request) {
2474	if friendorfoe(r.Header.Get("Accept")) {
2475		dlog.Printf("incompatible accept for donk")
2476		http.Error(w, "there are no activities here", http.StatusNotAcceptable)
2477		return
2478	}
2479	xid := mux.Vars(r)["xid"]
2480	preview := r.FormValue("preview") == "1"
2481	var media string
2482	var data []byte
2483	row := stmtGetFileData.QueryRow(xid)
2484	err := row.Scan(&media, &data)
2485	if err != nil {
2486		elog.Printf("error loading file: %s", err)
2487		http.NotFound(w, r)
2488		return
2489	}
2490	if preview && strings.HasPrefix(media, "image") {
2491		img, err := lilshrink(data)
2492		if err == nil {
2493			data = img.Data
2494		}
2495	}
2496	w.Header().Set("Content-Type", media)
2497	w.Header().Set("X-Content-Type-Options", "nosniff")
2498	w.Header().Set("Cache-Control", "max-age="+somedays())
2499	w.Write(data)
2500}
2501
2502func nomoroboto(w http.ResponseWriter, r *http.Request) {
2503	io.WriteString(w, "User-agent: *\n")
2504	io.WriteString(w, "Disallow: /a\n")
2505	io.WriteString(w, "Disallow: /d/\n")
2506	io.WriteString(w, "Disallow: /meme/\n")
2507	io.WriteString(w, "Disallow: /o\n")
2508	io.WriteString(w, "Disallow: /o/\n")
2509	io.WriteString(w, "Disallow: /help/\n")
2510	for _, u := range allusers() {
2511		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2512	}
2513}
2514
2515type Hydration struct {
2516	Tophid    int64
2517	Srvmsg    template.HTML
2518	Honks     string
2519	MeCount   int64
2520	ChatCount int64
2521	Poses     []int
2522}
2523
2524func webhydra(w http.ResponseWriter, r *http.Request) {
2525	u := login.GetUserInfo(r)
2526	userid := UserID(u.UserID)
2527	templinfo := getInfo(r)
2528	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2529	page := r.FormValue("page")
2530
2531	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2532
2533	var hydra Hydration
2534
2535	var honks []*Honk
2536	switch page {
2537	case "atme":
2538		honks = gethonksforme(userid, wanted)
2539		honks = osmosis(honks, userid, false)
2540		menewnone(userid)
2541		hydra.Srvmsg = "at me!"
2542	case "longago":
2543		honks = gethonksfromlongago(userid, wanted)
2544		honks = osmosis(honks, userid, false)
2545		hydra.Srvmsg = "from long ago"
2546	case "home":
2547		honks = gethonksforuser(userid, wanted)
2548		honks = osmosis(honks, userid, true)
2549		hydra.Srvmsg = serverMsg
2550	case "first":
2551		honks = gethonksforuserfirstclass(userid, wanted)
2552		honks = osmosis(honks, userid, true)
2553		hydra.Srvmsg = "first class only"
2554	case "saved":
2555		honks = getsavedhonks(userid, wanted)
2556		templinfo["PageName"] = "saved"
2557		hydra.Srvmsg = "saved honks"
2558	case "combo":
2559		c := r.FormValue("c")
2560		honks = gethonksbycombo(userid, c, wanted)
2561		honks = osmosis(honks, userid, false)
2562		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2563	case "convoy":
2564		c := r.FormValue("c")
2565		honks = gethonksbyconvoy(userid, c, 0)
2566		honks = osmosis(honks, userid, false)
2567		honks = threadsort(honks)
2568		honks, hydra.Poses = threadposes(honks, wanted)
2569		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2570	case "honker":
2571		xid := r.FormValue("xid")
2572		honks = gethonksbyxonker(userid, xid, wanted)
2573		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2574			<input type="hidden" name="CSRF" value="%s">
2575			<input type="hidden" name="url" value="%s">
2576			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2577			</form>`, login.GetCSRF("submithonker", r), xid)
2578		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2579		hydra.Srvmsg = msg
2580	case "user":
2581		uname := r.FormValue("uname")
2582		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2583		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2584	default:
2585		http.NotFound(w, r)
2586	}
2587
2588	if len(honks) > 0 {
2589		if page == "convoy" {
2590			hydra.Tophid = honks[len(honks)-1].ID
2591		} else {
2592			hydra.Tophid = honks[0].ID
2593		}
2594	} else {
2595		hydra.Tophid = wanted
2596	}
2597	reverbolate(userid, honks)
2598
2599	user, _ := butwhatabout(u.Username)
2600
2601	var buf strings.Builder
2602	templinfo["Honks"] = honks
2603	templinfo["MapLink"] = getmaplink(u)
2604	templinfo["User"], _ = butwhatabout(u.Username)
2605	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2606	if err != nil {
2607		elog.Printf("frag error: %s", err)
2608		return
2609	}
2610	hydra.Honks = buf.String()
2611	hydra.MeCount = user.Options.MeCount
2612	hydra.ChatCount = user.Options.ChatCount
2613	w.Header().Set("Content-Type", "application/json")
2614	j, _ := jsonify(&hydra)
2615	io.WriteString(w, j)
2616}
2617
2618var honkline = make(chan bool)
2619
2620func honkhonkline() {
2621	for {
2622		select {
2623		case honkline <- true:
2624		default:
2625			return
2626		}
2627	}
2628}
2629
2630func apihandler(w http.ResponseWriter, r *http.Request) {
2631	u := login.GetUserInfo(r)
2632	userid := UserID(u.UserID)
2633	action := r.FormValue("action")
2634	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2635	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2636	switch action {
2637	case "honk":
2638		h := submithonk(w, r)
2639		if h == nil {
2640			return
2641		}
2642		fmt.Fprintf(w, "%s", h.XID)
2643	case "donk":
2644		donks, err := submitdonk(w, r)
2645		if err != nil {
2646			http.Error(w, err.Error(), http.StatusBadRequest)
2647			return
2648		}
2649		if len(donks) == 0 {
2650			http.Error(w, "missing donk", http.StatusBadRequest)
2651			return
2652		}
2653		d := donks[0]
2654		donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2655		w.Write([]byte(donkxid))
2656	case "zonkit":
2657		zonkit(w, r)
2658	case "gethonks":
2659		var honks []*Honk
2660		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2661		page := r.FormValue("page")
2662		var waitchan <-chan time.Time
2663	requery:
2664		switch page {
2665		case "atme":
2666			honks = gethonksforme(userid, wanted)
2667			honks = osmosis(honks, userid, false)
2668			menewnone(userid)
2669		case "longago":
2670			honks = gethonksfromlongago(userid, wanted)
2671			honks = osmosis(honks, userid, false)
2672		case "home":
2673			honks = gethonksforuser(userid, wanted)
2674			honks = osmosis(honks, userid, true)
2675		case "myhonks":
2676			honks = gethonksbyuser(u.Username, true, wanted)
2677			honks = osmosis(honks, userid, true)
2678		case "saved":
2679			honks = getsavedhonks(userid, wanted)
2680		case "combo":
2681			c := r.FormValue("c")
2682			honks = gethonksbycombo(userid, c, wanted)
2683			honks = osmosis(honks, userid, false)
2684		case "convoy":
2685			c := r.FormValue("c")
2686			honks = gethonksbyconvoy(userid, c, 0)
2687			honks = osmosis(honks, userid, false)
2688			honks = threadsort(honks)
2689			honks, _ = threadposes(honks, wanted)
2690		case "honker":
2691			xid := r.FormValue("xid")
2692			honks = gethonksbyxonker(userid, xid, wanted)
2693		case "search":
2694			q := r.FormValue("q")
2695			honks = gethonksbysearch(userid, q, wanted)
2696		default:
2697			http.Error(w, "unknown page", http.StatusNotFound)
2698			return
2699		}
2700		if len(honks) == 0 && wait > 0 {
2701			if waitchan == nil {
2702				waitchan = time.After(time.Duration(wait) * time.Second)
2703			}
2704			select {
2705			case <-honkline:
2706				goto requery
2707			case <-waitchan:
2708			}
2709		}
2710		reverbolate(userid, honks)
2711		user, _ := butwhatabout(u.Username)
2712		j := junk.New()
2713		j["honks"] = honks
2714		j["mecount"] = user.Options.MeCount
2715		j["chatcount"] = user.Options.ChatCount
2716		j.Write(w)
2717	case "sendactivity":
2718		public := r.FormValue("public") == "1"
2719		user, _ := butwhatabout(u.Username)
2720		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2721		msg := []byte(r.FormValue("msg"))
2722		for rcpt := range rcpts {
2723			go deliverate(userid, rcpt, msg)
2724		}
2725	case "gethonkers":
2726		j := junk.New()
2727		j["honkers"] = gethonkers(userid)
2728		j.Write(w)
2729	case "savehonker":
2730		h := submithonker(w, r)
2731		if h == nil {
2732			return
2733		}
2734		fmt.Fprintf(w, "%d", h.ID)
2735	default:
2736		http.Error(w, "unknown action", http.StatusNotFound)
2737		return
2738	}
2739}
2740
2741func fiveoh(w http.ResponseWriter, r *http.Request) {
2742	if !develMode {
2743		return
2744	}
2745	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2746	if err != nil {
2747		elog.Printf("error opening violations! %s", err)
2748		return
2749	}
2750	defer fd.Close()
2751	io.Copy(fd, r.Body)
2752	fd.WriteString("\n")
2753}
2754
2755var endoftheworld = make(chan bool)
2756var readyalready = make(chan bool)
2757var workinprogress = 0
2758var requestWG sync.WaitGroup
2759var listenSocket net.Listener
2760
2761func enditall() {
2762	sig := make(chan os.Signal, 1)
2763	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2764	<-sig
2765	ilog.Printf("stopping...")
2766	listenSocket.Close()
2767	for i := 0; i < workinprogress; i++ {
2768		endoftheworld <- true
2769	}
2770	if *cpuprofile != "" {
2771		pprof.StopCPUProfile()
2772	}
2773	if *memprofile != "" {
2774		pprof.WriteHeapProfile(memprofilefd)
2775		memprofilefd.Close()
2776	}
2777	ilog.Printf("waiting...")
2778	go func() {
2779		time.Sleep(10 * time.Second)
2780		elog.Printf("timed out waiting for requests to finish")
2781		os.Exit(0)
2782	}()
2783	for i := 0; i < workinprogress; i++ {
2784		<-readyalready
2785	}
2786	requestWG.Wait()
2787	ilog.Printf("apocalypse")
2788	closedatabases()
2789	os.Exit(0)
2790}
2791
2792func bgmonitor() {
2793	for {
2794		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2795		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2796		if err != nil {
2797			elog.Printf("error deleting old xonkers: %s", err)
2798		}
2799		zaggies.Flush()
2800		time.Sleep(50 * time.Minute)
2801	}
2802}
2803
2804func addcspheaders(next http.Handler) http.Handler {
2805	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2806		requestWG.Add(1)
2807		defer requestWG.Done()
2808		policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2809		if develMode {
2810			policy += "; report-uri /csp-violation"
2811		}
2812		w.Header().Set("Content-Security-Policy", policy)
2813		next.ServeHTTP(w, r)
2814	})
2815}
2816
2817func emuinit() {
2818	var emunames []string
2819	dir, err := os.Open(dataDir + "/emus")
2820	if err == nil {
2821		emunames, _ = dir.Readdirnames(0)
2822		dir.Close()
2823	}
2824	for _, e := range emunames {
2825		if len(e) <= 4 {
2826			continue
2827		}
2828		ext := e[len(e)-4:]
2829		emu := Emu{
2830			ID:   fmt.Sprintf("/emu/%s", e),
2831			Name: e[:len(e)-4],
2832			Type: "image/" + ext[1:],
2833		}
2834		allemus = append(allemus, emu)
2835	}
2836	sort.Slice(allemus, func(i, j int) bool {
2837		return allemus[i].Name < allemus[j].Name
2838	})
2839}
2840
2841var savedassetparams = make(map[string]string)
2842
2843func getassetparam(file string) string {
2844	if p, ok := savedassetparams[file]; ok {
2845		return p
2846	}
2847	data, err := os.ReadFile(file)
2848	if err != nil {
2849		return ""
2850	}
2851	hasher := sha512.New()
2852	hasher.Write(data)
2853
2854	return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2855}
2856
2857func startWatcher() {
2858	watcher, err := gonix.NewWatcher()
2859	if err != nil {
2860		return
2861	}
2862	go func() {
2863		s := dataDir + "/views/local.css"
2864		for {
2865			err := watcher.WatchFile(s)
2866			if err != nil {
2867				break
2868			}
2869			err = watcher.WaitForChange()
2870			if err != nil {
2871				dlog.Printf("can't wait: %s", err)
2872				break
2873			}
2874			dlog.Printf("local.css changed")
2875			delete(savedassetparams, s)
2876			savedassetparams[s] = getassetparam(s)
2877		}
2878	}()
2879}
2880
2881var usefcgi bool
2882
2883func serve() {
2884	db := opendatabase()
2885	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2886
2887	listener, err := openListener()
2888	if err != nil {
2889		elog.Fatal(err)
2890	}
2891	runBackendServer()
2892	go enditall()
2893	go redeliverator()
2894	go tracker()
2895	go syndicator()
2896	go bgmonitor()
2897	go qotd()
2898	loadLingo()
2899	emuinit()
2900
2901	var toload []string
2902	dents, _ := os.ReadDir(viewDir + "/views")
2903	for _, dent := range dents {
2904		name := dent.Name()
2905		if strings.HasSuffix(name, ".html") {
2906			toload = append(toload, viewDir+"/views/"+name)
2907		}
2908	}
2909
2910	readviews = templates.Load(develMode, toload...)
2911	if !develMode {
2912		assets := []string{
2913			viewDir + "/views/style.css",
2914			dataDir + "/views/local.css",
2915			viewDir + "/views/honkpage.js",
2916			viewDir + "/views/misc.js",
2917			dataDir + "/views/local.js",
2918		}
2919		for _, s := range assets {
2920			savedassetparams[s] = getassetparam(s)
2921		}
2922		loadAvatarColors()
2923	}
2924	startWatcher()
2925
2926	securitizeweb()
2927
2928	mux := mux.NewRouter()
2929	mux.Use(addcspheaders)
2930	mux.Use(login.Checker)
2931
2932	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2933
2934	posters := mux.Methods("POST").Subrouter()
2935	getters := mux.Methods("GET").Subrouter()
2936
2937	getters.HandleFunc("/", homepage)
2938	getters.HandleFunc("/home", homepage)
2939	getters.HandleFunc("/front", homepage)
2940	getters.HandleFunc("/events", homepage)
2941	getters.HandleFunc("/robots.txt", nomoroboto)
2942	getters.HandleFunc("/rss", showrss)
2943	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2944	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}.json", showuser)
2945	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2946	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}.json", showonehonk)
2947	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2948	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2949	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2950	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2951	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2952	getters.HandleFunc("/a", avatate)
2953	getters.HandleFunc("/o", thelistingoftheontologies)
2954	getters.HandleFunc("/o/{name:.+}", showontology)
2955	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2956	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2957	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2958	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2959
2960	getters.HandleFunc("/flag/{code:.+}", showflag)
2961
2962	getters.HandleFunc("/server", serveractor)
2963	posters.HandleFunc("/server/inbox", serverinbox)
2964	posters.HandleFunc("/inbox", serverinbox)
2965
2966	posters.HandleFunc("/csp-violation", fiveoh)
2967
2968	getters.HandleFunc("/style.css", serveviewasset)
2969	getters.HandleFunc("/honkpage.js", serveviewasset)
2970	getters.HandleFunc("/misc.js", serveviewasset)
2971	getters.HandleFunc("/local.css", servedataasset)
2972	getters.HandleFunc("/local.js", servedataasset)
2973	getters.HandleFunc("/icon.png", servedataasset)
2974	getters.HandleFunc("/favicon.ico", servedataasset)
2975
2976	getters.HandleFunc("/about", servehtml)
2977	getters.HandleFunc("/login", servehtml)
2978	posters.HandleFunc("/dologin", login.LoginFunc)
2979	getters.HandleFunc("/logout", login.LogoutFunc)
2980	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2981
2982	loggedin := mux.NewRoute().Subrouter()
2983	loggedin.Use(login.Required)
2984	loggedin.HandleFunc("/first", homepage)
2985	loggedin.HandleFunc("/chatter", showchatter)
2986	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2987	loggedin.HandleFunc("/saved", homepage)
2988	loggedin.HandleFunc("/account", accountpage)
2989	loggedin.HandleFunc("/funzone", showfunzone)
2990	loggedin.HandleFunc("/chpass", dochpass)
2991	loggedin.HandleFunc("/atme", homepage)
2992	loggedin.HandleFunc("/longago", homepage)
2993	loggedin.HandleFunc("/hfcs", hfcspage)
2994	loggedin.HandleFunc("/xzone", xzone)
2995	loggedin.HandleFunc("/newhonk", newhonkpage)
2996	loggedin.HandleFunc("/edit", edithonkpage)
2997	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2998	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2999	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
3000	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
3001	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
3002	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
3003	loggedin.HandleFunc("/honkers", showhonkers)
3004	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
3005	loggedin.HandleFunc("/h", showhonker)
3006	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
3007	loggedin.HandleFunc("/c", showcombos)
3008	loggedin.HandleFunc("/t", showconvoy)
3009	loggedin.HandleFunc("/q", showsearch)
3010	loggedin.HandleFunc("/hydra", webhydra)
3011	loggedin.HandleFunc("/emus", showemus)
3012	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
3013
3014	if usefcgi {
3015		err = fcgi.Serve(listener, mux)
3016	} else {
3017		err = http.Serve(listener, mux)
3018	}
3019	if err != nil && !errors.Is(err, net.ErrClosed) {
3020		elog.Printf("serve error: %s", err)
3021	}
3022	time.Sleep(15 * time.Second)
3023	elog.Printf("fell off the bottom")
3024}