all repos — honk @ 2718526d6166cdb7faea728c3540fb5021a7498c

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