all repos — honk @ 466fa4b6ec5157da77e04afcce29e06097509dc6

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