all repos — honk @ 781652add08870420a3c470bd2e8f85250f2d4c9

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 threadsort(honks []*Honk) []*Honk {
1109	sort.Slice(honks, func(i, j int) bool {
1110		return honks[i].Date.Before(honks[j].Date)
1111	})
1112	honkx := make(map[string]*Honk)
1113	kids := make(map[string][]*Honk)
1114	for _, h := range honks {
1115		honkx[h.XID] = h
1116		rid := h.RID
1117		kids[rid] = append(kids[rid], h)
1118	}
1119	done := make(map[*Honk]bool)
1120	var thread []*Honk
1121	var nextlevel func(p *Honk)
1122	level := 0
1123	nextlevel = func(p *Honk) {
1124		levelup := level < 4
1125		if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1126			levelup = false
1127		}
1128		if level > 0 && len(kids[p.RID]) == 1 {
1129			if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1130				levelup = false
1131			}
1132		}
1133		if levelup {
1134			level++
1135		}
1136		p.Style += fmt.Sprintf(" level%d", level)
1137		childs := kids[p.XID]
1138		if false {
1139			sort.SliceStable(childs, func(i, j int) bool {
1140				return sameperson(childs[i], p) && !sameperson(childs[j], p)
1141			})
1142		}
1143		if true {
1144			sort.SliceStable(childs, func(i, j int) bool {
1145				return !sameperson(childs[i], p) && sameperson(childs[j], p)
1146			})
1147		}
1148		for _, h := range childs {
1149			if !done[h] {
1150				done[h] = true
1151				thread = append(thread, h)
1152				nextlevel(h)
1153			}
1154		}
1155		if levelup {
1156			level--
1157		}
1158	}
1159	for _, h := range honks {
1160		if !done[h] && h.RID == "" {
1161			done[h] = true
1162			thread = append(thread, h)
1163			nextlevel(h)
1164		}
1165	}
1166	for _, h := range honks {
1167		if !done[h] {
1168			done[h] = true
1169			thread = append(thread, h)
1170			nextlevel(h)
1171		}
1172	}
1173	return thread
1174}
1175
1176func oguser(user *WhatAbout) template.HTML {
1177	short := user.About
1178	if len(short) > 160 {
1179		short = short[0:160] + "..."
1180	}
1181	title := user.Display
1182	imgurl := avatarURL(user)
1183	return templates.Sprintf(
1184		`<meta property="og:title" content="%s" />
1185<meta property="og:type" content="website" />
1186<meta property="og:url" content="%s" />
1187<meta property="og:image" content="%s" />
1188<meta property="og:description" content="%s" />`,
1189		title, user.URL, imgurl, short)
1190}
1191
1192func honkology(honk *Honk) template.HTML {
1193	user, ok := somenumberedusers.Get(honk.UserID)
1194	if !ok {
1195		return ""
1196	}
1197	title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1198	imgurl := avatarURL(user)
1199	for _, d := range honk.Donks {
1200		if d.Local && strings.HasPrefix(d.Media, "image") {
1201			imgurl = d.URL
1202			break
1203		}
1204	}
1205	short := honk.Noise
1206	if len(short) > 160 {
1207		short = short[0:160] + "..."
1208	}
1209	return templates.Sprintf(
1210		`<meta property="og:title" content="%s" />
1211<meta property="og:type" content="article" />
1212<meta property="article:author" content="%s" />
1213<meta property="og:url" content="%s" />
1214<meta property="og:image" content="%s" />
1215<meta property="og:description" content="%s" />`,
1216		title, user.URL, honk.XID, imgurl, short)
1217}
1218
1219func showonehonk(w http.ResponseWriter, r *http.Request) {
1220	name := mux.Vars(r)["name"]
1221	user, err := butwhatabout(name)
1222	if err != nil {
1223		http.NotFound(w, r)
1224		return
1225	}
1226	if stealthmode(user.ID, r) {
1227		http.NotFound(w, r)
1228		return
1229	}
1230	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1231
1232	if friendorfoe(r.Header.Get("Accept")) {
1233		j, ok := gimmejonk(xid)
1234		if ok {
1235			trackback(xid, r)
1236			w.Header().Set("Content-Type", theonetruename)
1237			w.Write(j)
1238		} else {
1239			http.NotFound(w, r)
1240		}
1241		return
1242	}
1243	honk := getxonk(user.ID, xid)
1244	if honk == nil {
1245		http.NotFound(w, r)
1246		return
1247	}
1248	u := login.GetUserInfo(r)
1249	if u != nil && u.UserID != user.ID {
1250		u = nil
1251	}
1252	if !honk.Public {
1253		if u == nil {
1254			http.NotFound(w, r)
1255			return
1256
1257		}
1258		honks := []*Honk{honk}
1259		donksforhonks(honks)
1260		templinfo := getInfo(r)
1261		templinfo["ServerMessage"] = "one honk maybe more"
1262		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1263		honkpage(w, u, honks, templinfo)
1264		return
1265	}
1266
1267	templinfo := getInfo(r)
1268	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1269	//reversehonks(rawhonks)
1270	rawhonks = threadsort(rawhonks)
1271	var honks []*Honk
1272	for i, h := range rawhonks {
1273		if h.XID == xid {
1274			templinfo["Honkology"] = honkology(h)
1275			if i > 0 {
1276				h.Style += " glow"
1277			}
1278		}
1279		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1280			honks = append(honks, h)
1281		}
1282	}
1283
1284	templinfo["ServerMessage"] = "one honk maybe more"
1285	if u != nil {
1286		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1287	}
1288	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1289	honkpage(w, u, honks, templinfo)
1290}
1291
1292func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1293	var userid int64 = -1
1294	if u != nil {
1295		userid = u.UserID
1296		templinfo["User"], _ = butwhatabout(u.Username)
1297	}
1298	reverbolate(userid, honks)
1299	templinfo["Honks"] = honks
1300	templinfo["MapLink"] = getmaplink(u)
1301	if templinfo["TopHID"] == nil {
1302		if len(honks) > 0 {
1303			templinfo["TopHID"] = honks[0].ID
1304		} else {
1305			templinfo["TopHID"] = 0
1306		}
1307	}
1308	if u == nil && !develMode {
1309		w.Header().Set("Cache-Control", "max-age=60")
1310	}
1311	err := readviews.Execute(w, "honkpage.html", templinfo)
1312	if err != nil {
1313		elog.Print(err)
1314	}
1315}
1316
1317func saveuser(w http.ResponseWriter, r *http.Request) {
1318	whatabout := r.FormValue("whatabout")
1319	whatabout = strings.Replace(whatabout, "\r", "", -1)
1320	u := login.GetUserInfo(r)
1321	user, _ := butwhatabout(u.Username)
1322	db := opendatabase()
1323
1324	options := user.Options
1325	if r.FormValue("skinny") == "skinny" {
1326		options.SkinnyCSS = true
1327	} else {
1328		options.SkinnyCSS = false
1329	}
1330	if r.FormValue("omitimages") == "omitimages" {
1331		options.OmitImages = true
1332	} else {
1333		options.OmitImages = false
1334	}
1335	if r.FormValue("mentionall") == "mentionall" {
1336		options.MentionAll = true
1337	} else {
1338		options.MentionAll = false
1339	}
1340	if r.FormValue("inlineqts") == "inlineqts" {
1341		options.InlineQuotes = true
1342	} else {
1343		options.InlineQuotes = false
1344	}
1345	if r.FormValue("maps") == "apple" {
1346		options.MapLink = "apple"
1347	} else {
1348		options.MapLink = ""
1349	}
1350	options.Reaction = r.FormValue("reaction")
1351
1352	sendupdate := false
1353	ava := re_avatar.FindString(whatabout)
1354	if ava != "" {
1355		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1356		ava = ava[7:]
1357		if ava[0] == ' ' {
1358			ava = ava[1:]
1359		}
1360		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1361	}
1362	if ava != options.Avatar {
1363		options.Avatar = ava
1364		sendupdate = true
1365	}
1366	ban := re_banner.FindString(whatabout)
1367	if ban != "" {
1368		whatabout = re_banner.ReplaceAllString(whatabout, "")
1369		ban = ban[7:]
1370		if ban[0] == ' ' {
1371			ban = ban[1:]
1372		}
1373		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1374	}
1375	if ban != options.Banner {
1376		options.Banner = ban
1377		sendupdate = true
1378	}
1379	whatabout = strings.TrimSpace(whatabout)
1380	if whatabout != user.About {
1381		sendupdate = true
1382	}
1383	j, err := jsonify(options)
1384	if err == nil {
1385		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1386	}
1387	if err != nil {
1388		elog.Printf("error bouting what: %s", err)
1389	}
1390	somenamedusers.Clear(u.Username)
1391	somenumberedusers.Clear(u.UserID)
1392	oldjonkers.Clear(u.Username)
1393
1394	if sendupdate {
1395		updateMe(u.Username)
1396	}
1397
1398	http.Redirect(w, r, "/account", http.StatusSeeOther)
1399}
1400
1401func bonkit(xid string, user *WhatAbout) {
1402	dlog.Printf("bonking %s", xid)
1403
1404	xonk := getxonk(user.ID, xid)
1405	if xonk == nil {
1406		return
1407	}
1408	if !xonk.Public {
1409		return
1410	}
1411	if xonk.IsBonked() {
1412		return
1413	}
1414	donksforhonks([]*Honk{xonk})
1415
1416	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1417	if err != nil {
1418		elog.Printf("error acking bonk: %s", err)
1419	}
1420
1421	oonker := xonk.Oonker
1422	if oonker == "" {
1423		oonker = xonk.Honker
1424	}
1425	dt := time.Now().UTC()
1426	bonk := &Honk{
1427		UserID:   user.ID,
1428		Username: user.Name,
1429		What:     "bonk",
1430		Honker:   user.URL,
1431		Oonker:   oonker,
1432		XID:      xonk.XID,
1433		RID:      xonk.RID,
1434		Noise:    xonk.Noise,
1435		Precis:   xonk.Precis,
1436		URL:      xonk.URL,
1437		Date:     dt,
1438		Donks:    xonk.Donks,
1439		Whofore:  2,
1440		Convoy:   xonk.Convoy,
1441		Audience: []string{thewholeworld, oonker},
1442		Public:   true,
1443		Format:   xonk.Format,
1444		Place:    xonk.Place,
1445		Onts:     xonk.Onts,
1446		Time:     xonk.Time,
1447	}
1448
1449	err = savehonk(bonk)
1450	if err != nil {
1451		elog.Printf("uh oh")
1452		return
1453	}
1454
1455	go honkworldwide(user, bonk)
1456}
1457
1458func submitbonk(w http.ResponseWriter, r *http.Request) {
1459	xid := r.FormValue("xid")
1460	userinfo := login.GetUserInfo(r)
1461	user, _ := butwhatabout(userinfo.Username)
1462
1463	bonkit(xid, user)
1464
1465	if r.FormValue("js") != "1" {
1466		templinfo := getInfo(r)
1467		templinfo["ServerMessage"] = "Bonked!"
1468		err := readviews.Execute(w, "msg.html", templinfo)
1469		if err != nil {
1470			elog.Print(err)
1471		}
1472	}
1473}
1474
1475func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1476	zonk := &Honk{
1477		What:     what,
1478		XID:      xonk.XID,
1479		Date:     time.Now().UTC(),
1480		Audience: oneofakind(xonk.Audience),
1481		Noise:    aux,
1482	}
1483	zonk.Public = loudandproud(zonk.Audience)
1484
1485	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1486	go honkworldwide(user, zonk)
1487}
1488
1489func zonkit(w http.ResponseWriter, r *http.Request) {
1490	wherefore := r.FormValue("wherefore")
1491	what := r.FormValue("what")
1492	userinfo := login.GetUserInfo(r)
1493	user, _ := butwhatabout(userinfo.Username)
1494
1495	if wherefore == "save" {
1496		xonk := getxonk(userinfo.UserID, what)
1497		if xonk != nil {
1498			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1499			if err != nil {
1500				elog.Printf("error saving: %s", err)
1501			}
1502		}
1503		return
1504	}
1505
1506	if wherefore == "unsave" {
1507		xonk := getxonk(userinfo.UserID, what)
1508		if xonk != nil {
1509			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1510			if err != nil {
1511				elog.Printf("error unsaving: %s", err)
1512			}
1513		}
1514		return
1515	}
1516
1517	if wherefore == "react" {
1518		reaction := user.Options.Reaction
1519		if r2 := r.FormValue("reaction"); r2 != "" {
1520			reaction = r2
1521		}
1522		if reaction == "none" {
1523			return
1524		}
1525		xonk := getxonk(userinfo.UserID, what)
1526		if xonk != nil {
1527			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1528			if err != nil {
1529				elog.Printf("error saving: %s", err)
1530			}
1531			sendzonkofsorts(xonk, user, "react", reaction)
1532		}
1533		return
1534	}
1535
1536	// my hammer is too big, oh well
1537	defer oldjonks.Flush()
1538
1539	if wherefore == "ack" {
1540		xonk := getxonk(userinfo.UserID, what)
1541		if xonk != nil && !xonk.IsAcked() {
1542			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1543			if err != nil {
1544				elog.Printf("error acking: %s", err)
1545			}
1546			sendzonkofsorts(xonk, user, "ack", "")
1547		}
1548		return
1549	}
1550
1551	if wherefore == "deack" {
1552		xonk := getxonk(userinfo.UserID, what)
1553		if xonk != nil && xonk.IsAcked() {
1554			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1555			if err != nil {
1556				elog.Printf("error deacking: %s", err)
1557			}
1558			sendzonkofsorts(xonk, user, "deack", "")
1559		}
1560		return
1561	}
1562
1563	if wherefore == "bonk" {
1564		user, _ := butwhatabout(userinfo.Username)
1565		bonkit(what, user)
1566		return
1567	}
1568
1569	if wherefore == "unbonk" {
1570		xonk := getbonk(userinfo.UserID, what)
1571		if xonk != nil {
1572			deletehonk(xonk.ID)
1573			xonk = getxonk(userinfo.UserID, what)
1574			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1575			if err != nil {
1576				elog.Printf("error unbonking: %s", err)
1577			}
1578			sendzonkofsorts(xonk, user, "unbonk", "")
1579		}
1580		return
1581	}
1582
1583	if wherefore == "untag" {
1584		xonk := getxonk(userinfo.UserID, what)
1585		if xonk != nil {
1586			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1587			if err != nil {
1588				elog.Printf("error untagging: %s", err)
1589			}
1590		}
1591		var badparents map[string]bool
1592		untagged.GetAndLock(userinfo.UserID, &badparents)
1593		badparents[what] = true
1594		untagged.Unlock()
1595		return
1596	}
1597
1598	ilog.Printf("zonking %s %s", wherefore, what)
1599	if wherefore == "zonk" {
1600		xonk := getxonk(userinfo.UserID, what)
1601		if xonk != nil {
1602			deletehonk(xonk.ID)
1603			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1604				sendzonkofsorts(xonk, user, "zonk", "")
1605			}
1606		}
1607	}
1608	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1609	if err != nil {
1610		elog.Printf("error saving zonker: %s", err)
1611		return
1612	}
1613}
1614
1615func edithonkpage(w http.ResponseWriter, r *http.Request) {
1616	u := login.GetUserInfo(r)
1617	user, _ := butwhatabout(u.Username)
1618	xid := r.FormValue("xid")
1619	honk := getxonk(u.UserID, xid)
1620	if !canedithonk(user, honk) {
1621		http.Error(w, "no editing that please", http.StatusInternalServerError)
1622		return
1623	}
1624
1625	noise := honk.Noise
1626
1627	honks := []*Honk{honk}
1628	donksforhonks(honks)
1629	reverbolate(u.UserID, honks)
1630	templinfo := getInfo(r)
1631	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1632	templinfo["Honks"] = honks
1633	templinfo["MapLink"] = getmaplink(u)
1634	templinfo["Noise"] = noise
1635	templinfo["SavedPlace"] = honk.Place
1636	if tm := honk.Time; tm != nil {
1637		templinfo["ShowTime"] = " "
1638		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1639		if tm.Duration != 0 {
1640			templinfo["Duration"] = tm.Duration
1641		}
1642	}
1643	templinfo["ServerMessage"] = "honk edit"
1644	templinfo["IsPreview"] = true
1645	templinfo["UpdateXID"] = honk.XID
1646	if len(honk.Donks) > 0 {
1647		var savedfiles []string
1648		for _, d := range honk.Donks {
1649			savedfiles = append(savedfiles, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1650		}
1651		templinfo["SavedFile"] = strings.Join(savedfiles, ",")
1652	}
1653	err := readviews.Execute(w, "honkpage.html", templinfo)
1654	if err != nil {
1655		elog.Print(err)
1656	}
1657}
1658
1659func newhonkpage(w http.ResponseWriter, r *http.Request) {
1660	u := login.GetUserInfo(r)
1661	rid := r.FormValue("rid")
1662	noise := ""
1663
1664	xonk := getxonk(u.UserID, rid)
1665	if xonk != nil {
1666		_, replto := handles(xonk.Honker)
1667		if replto != "" {
1668			noise = "@" + replto + " "
1669		}
1670	}
1671
1672	templinfo := getInfo(r)
1673	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1674	templinfo["InReplyTo"] = rid
1675	templinfo["Noise"] = noise
1676	templinfo["ServerMessage"] = "compose honk"
1677	templinfo["IsPreview"] = true
1678	err := readviews.Execute(w, "honkpage.html", templinfo)
1679	if err != nil {
1680		elog.Print(err)
1681	}
1682}
1683
1684func canedithonk(user *WhatAbout, honk *Honk) bool {
1685	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1686		return false
1687	}
1688	return true
1689}
1690
1691func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1692	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1693		return nil, nil
1694	}
1695	var donks []*Donk
1696	for i, hdr := range r.MultipartForm.File["donk"] {
1697		if i > 16 {
1698			break
1699		}
1700		donk, err := formtodonk(w, r, hdr)
1701		if err != nil {
1702			return nil, err
1703		}
1704		donks = append(donks, donk)
1705	}
1706	return donks, nil
1707}
1708
1709func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1710	file, err := filehdr.Open()
1711	if err != nil {
1712		if err == http.ErrMissingFile {
1713			return nil, nil
1714		}
1715		elog.Printf("error reading donk: %s", err)
1716		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1717		return nil, err
1718	}
1719	var buf bytes.Buffer
1720	io.Copy(&buf, file)
1721	file.Close()
1722	data := buf.Bytes()
1723	var media, name string
1724	img, err := bigshrink(data)
1725	if err == nil {
1726		data = img.Data
1727		format := img.Format
1728		media = "image/" + format
1729		if format == "jpeg" {
1730			format = "jpg"
1731		}
1732		if format == "svg+xml" {
1733			format = "svg"
1734		}
1735		name = xfiltrate() + "." + format
1736	} else {
1737		ct := http.DetectContentType(data)
1738		switch ct {
1739		case "application/pdf":
1740			maxsize := 10000000
1741			if len(data) > maxsize {
1742				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1743				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1744				return nil, err
1745			}
1746			media = ct
1747			name = filehdr.Filename
1748			if name == "" {
1749				name = xfiltrate() + ".pdf"
1750			}
1751		default:
1752			maxsize := 100000
1753			if len(data) > maxsize {
1754				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1755				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1756				return nil, err
1757			}
1758			for i := 0; i < len(data); i++ {
1759				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1760					ilog.Printf("bad image: %s not text: %d", err, data[i])
1761					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1762					return nil, err
1763				}
1764			}
1765			media = "text/plain"
1766			name = filehdr.Filename
1767			if name == "" {
1768				name = xfiltrate() + ".txt"
1769			}
1770		}
1771	}
1772	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1773	if desc == "" {
1774		desc = name
1775	}
1776	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1777	if err != nil {
1778		elog.Printf("unable to save image: %s", err)
1779		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1780		return nil, err
1781	}
1782	d := &Donk{
1783		FileID: fileid,
1784		XID:    xid,
1785		Desc:   desc,
1786		Local:  true,
1787	}
1788	return d, nil
1789}
1790
1791func websubmithonk(w http.ResponseWriter, r *http.Request) {
1792	h := submithonk(w, r)
1793	if h == nil {
1794		return
1795	}
1796	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1797}
1798
1799// what a hot mess this function is
1800func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1801	rid := r.FormValue("rid")
1802	noise := r.FormValue("noise")
1803	format := r.FormValue("format")
1804	if format == "" {
1805		format = "markdown"
1806	}
1807	if !(format == "markdown" || format == "html") {
1808		http.Error(w, "unknown format", 500)
1809		return nil
1810	}
1811
1812	userinfo := login.GetUserInfo(r)
1813	user, _ := butwhatabout(userinfo.Username)
1814
1815	dt := time.Now().UTC()
1816	updatexid := r.FormValue("updatexid")
1817	var honk *Honk
1818	if updatexid != "" {
1819		honk = getxonk(userinfo.UserID, updatexid)
1820		if !canedithonk(user, honk) {
1821			http.Error(w, "no editing that please", http.StatusInternalServerError)
1822			return nil
1823		}
1824		honk.Date = dt
1825		honk.What = "update"
1826		honk.Format = format
1827	} else {
1828		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1829		what := "honk"
1830		honk = &Honk{
1831			UserID:   userinfo.UserID,
1832			Username: userinfo.Username,
1833			What:     what,
1834			Honker:   user.URL,
1835			XID:      xid,
1836			Date:     dt,
1837			Format:   format,
1838		}
1839	}
1840
1841	var convoy string
1842	noise = strings.Replace(noise, "\r", "", -1)
1843	if updatexid == "" && rid == "" {
1844		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1845			convoy = m[7:]
1846			convoy = strings.TrimSpace(convoy)
1847			if !re_convalidate.MatchString(convoy) {
1848				convoy = ""
1849			}
1850			return ""
1851		})
1852	}
1853	noise = quickrename(noise, userinfo.UserID)
1854	honk.Noise = noise
1855	precipitate(honk)
1856	noise = honk.Noise
1857	recategorize(honk)
1858	translate(honk)
1859
1860	if rid != "" {
1861		xonk := getxonk(userinfo.UserID, rid)
1862		if xonk == nil {
1863			http.Error(w, "replyto disappeared", http.StatusNotFound)
1864			return nil
1865		}
1866		if xonk.Public {
1867			honk.Audience = append(honk.Audience, xonk.Audience...)
1868		}
1869		convoy = xonk.Convoy
1870		for i, a := range honk.Audience {
1871			if a == thewholeworld {
1872				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1873				break
1874			}
1875		}
1876		honk.RID = rid
1877		if xonk.Precis != "" && honk.Precis == "" {
1878			honk.Precis = xonk.Precis
1879			if !re_dangerous.MatchString(honk.Precis) {
1880				honk.Precis = "re: " + honk.Precis
1881			}
1882		}
1883	} else if updatexid == "" {
1884		honk.Audience = []string{thewholeworld}
1885	}
1886	if honk.Noise != "" && honk.Noise[0] == '@' {
1887		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1888	} else {
1889		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1890	}
1891
1892	if convoy == "" {
1893		convoy = "data:,electrichonkytonk-" + xfiltrate()
1894	}
1895	butnottooloud(honk.Audience)
1896	honk.Audience = oneofakind(honk.Audience)
1897	if len(honk.Audience) == 0 {
1898		ilog.Printf("honk to nowhere")
1899		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1900		return nil
1901	}
1902	honk.Public = loudandproud(honk.Audience)
1903	honk.Convoy = convoy
1904
1905	donkxid := strings.Join(r.Form["donkxid"], ",")
1906	if donkxid == "" {
1907		donks, err := submitdonk(w, r)
1908		if err != nil && err != http.ErrMissingFile {
1909			return nil
1910		}
1911		if len(donks) > 0 {
1912			honk.Donks = append(honk.Donks, donks...)
1913			var xids []string
1914			for _, d := range honk.Donks {
1915				xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1916			}
1917			donkxid = strings.Join(xids, ",")
1918		}
1919	} else {
1920		xids := strings.Split(donkxid, ",")
1921		for i, xid := range xids {
1922			if i > 16 {
1923				break
1924			}
1925			p := strings.Split(xid, ":")
1926			xid = p[0]
1927			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1928			var donk *Donk
1929			if len(p) > 1 {
1930				fileid, _ := strconv.ParseInt(p[1], 10, 0)
1931				donk = finddonkid(fileid, url)
1932			} else {
1933				donk = finddonk(url)
1934			}
1935			if donk != nil {
1936				honk.Donks = append(honk.Donks, donk)
1937			} else {
1938				ilog.Printf("can't find file: %s", xid)
1939			}
1940		}
1941	}
1942	memetize(honk)
1943	imaginate(honk)
1944
1945	placename := strings.TrimSpace(r.FormValue("placename"))
1946	placelat := strings.TrimSpace(r.FormValue("placelat"))
1947	placelong := strings.TrimSpace(r.FormValue("placelong"))
1948	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1949	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1950		p := new(Place)
1951		p.Name = placename
1952		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1953		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1954		p.Url = placeurl
1955		honk.Place = p
1956	}
1957	timestart := strings.TrimSpace(r.FormValue("timestart"))
1958	if timestart != "" {
1959		t := new(Time)
1960		now := time.Now().Local()
1961		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1962			start, err := time.ParseInLocation(layout, timestart, now.Location())
1963			if err == nil {
1964				if start.Year() == 0 {
1965					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1966				}
1967				t.StartTime = start
1968				break
1969			}
1970		}
1971		timeend := r.FormValue("timeend")
1972		dur := parseDuration(timeend)
1973		if dur != 0 {
1974			t.Duration = Duration(dur)
1975		}
1976		if !t.StartTime.IsZero() {
1977			honk.What = "event"
1978			honk.Time = t
1979		}
1980	}
1981
1982	if honk.Public {
1983		honk.Whofore = 2
1984	} else {
1985		honk.Whofore = 3
1986	}
1987
1988	// back to markdown
1989	honk.Noise = noise
1990
1991	if r.FormValue("preview") == "preview" {
1992		honks := []*Honk{honk}
1993		reverbolate(userinfo.UserID, honks)
1994		templinfo := getInfo(r)
1995		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1996		templinfo["Honks"] = honks
1997		templinfo["MapLink"] = getmaplink(userinfo)
1998		templinfo["InReplyTo"] = r.FormValue("rid")
1999		templinfo["Noise"] = r.FormValue("noise")
2000		templinfo["SavedFile"] = donkxid
2001		if tm := honk.Time; tm != nil {
2002			templinfo["ShowTime"] = " "
2003			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
2004			if tm.Duration != 0 {
2005				templinfo["Duration"] = tm.Duration
2006			}
2007		}
2008		templinfo["IsPreview"] = true
2009		templinfo["UpdateXID"] = updatexid
2010		templinfo["ServerMessage"] = "honk preview"
2011		err := readviews.Execute(w, "honkpage.html", templinfo)
2012		if err != nil {
2013			elog.Print(err)
2014		}
2015		return nil
2016	}
2017
2018	if updatexid != "" {
2019		updatehonk(honk)
2020		oldjonks.Clear(honk.XID)
2021	} else {
2022		err := savehonk(honk)
2023		if err != nil {
2024			elog.Printf("uh oh")
2025			return nil
2026		}
2027	}
2028
2029	// reload for consistency
2030	honk.Donks = nil
2031	donksforhonks([]*Honk{honk})
2032
2033	go honkworldwide(user, honk)
2034
2035	return honk
2036}
2037
2038func showhonkers(w http.ResponseWriter, r *http.Request) {
2039	userinfo := login.GetUserInfo(r)
2040	templinfo := getInfo(r)
2041	templinfo["Honkers"] = gethonkers(userinfo.UserID)
2042	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2043	err := readviews.Execute(w, "honkers.html", templinfo)
2044	if err != nil {
2045		elog.Print(err)
2046	}
2047}
2048
2049func showchatter(w http.ResponseWriter, r *http.Request) {
2050	u := login.GetUserInfo(r)
2051	chatnewnone(u.UserID)
2052	chatter := loadchatter(u.UserID)
2053	for _, chat := range chatter {
2054		for _, ch := range chat.Chonks {
2055			filterchonk(ch)
2056		}
2057	}
2058
2059	templinfo := getInfo(r)
2060	templinfo["Chatter"] = chatter
2061	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2062	err := readviews.Execute(w, "chatter.html", templinfo)
2063	if err != nil {
2064		elog.Print(err)
2065	}
2066}
2067
2068func submitchonk(w http.ResponseWriter, r *http.Request) {
2069	u := login.GetUserInfo(r)
2070	user, _ := butwhatabout(u.Username)
2071	noise := r.FormValue("noise")
2072	target := r.FormValue("target")
2073	format := "markdown"
2074	dt := time.Now().UTC()
2075	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2076
2077	if !strings.HasPrefix(target, "https://") {
2078		target = fullname(target, u.UserID)
2079	}
2080	if target == "" {
2081		http.Error(w, "who is that?", http.StatusInternalServerError)
2082		return
2083	}
2084	ch := Chonk{
2085		UserID: u.UserID,
2086		XID:    xid,
2087		Who:    user.URL,
2088		Target: target,
2089		Date:   dt,
2090		Noise:  noise,
2091		Format: format,
2092	}
2093	donks, err := submitdonk(w, r)
2094	if err != nil && err != http.ErrMissingFile {
2095		return
2096	}
2097	if len(donks) > 0 {
2098		ch.Donks = append(ch.Donks, donks...)
2099	}
2100
2101	translatechonk(&ch)
2102	savechonk(&ch)
2103	// reload for consistency
2104	ch.Donks = nil
2105	donksforchonks([]*Chonk{&ch})
2106	go sendchonk(user, &ch)
2107
2108	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2109}
2110
2111var combocache = gencache.New(gencache.Options[int64, []string]{Fill: func(userid int64) ([]string, bool) {
2112	honkers := gethonkers(userid)
2113	var combos []string
2114	for _, h := range honkers {
2115		combos = append(combos, h.Combos...)
2116	}
2117	for i, c := range combos {
2118		if c == "-" {
2119			combos[i] = ""
2120		}
2121	}
2122	combos = oneofakind(combos)
2123	sort.Strings(combos)
2124	return combos, true
2125}, Invalidator: &honkerinvalidator})
2126
2127func showcombos(w http.ResponseWriter, r *http.Request) {
2128	templinfo := getInfo(r)
2129	err := readviews.Execute(w, "combos.html", templinfo)
2130	if err != nil {
2131		elog.Print(err)
2132	}
2133}
2134
2135func websubmithonker(w http.ResponseWriter, r *http.Request) {
2136	h := submithonker(w, r)
2137	if h == nil {
2138		return
2139	}
2140	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2141}
2142
2143func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2144	u := login.GetUserInfo(r)
2145	user, _ := butwhatabout(u.Username)
2146	name := strings.TrimSpace(r.FormValue("name"))
2147	url := strings.TrimSpace(r.FormValue("url"))
2148	peep := r.FormValue("peep")
2149	combos := strings.TrimSpace(r.FormValue("combos"))
2150	combos = " " + combos + " "
2151	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2152
2153	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2154	if name != "" && !re_namecheck.MatchString(name) {
2155		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2156		return nil
2157	}
2158
2159	var meta HonkerMeta
2160	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2161	mj, _ := jsonify(&meta)
2162
2163	defer honkerinvalidator.Clear(u.UserID)
2164
2165	// mostly dummy, fill in later...
2166	h := &Honker{
2167		ID: honkerid,
2168	}
2169
2170	if honkerid > 0 {
2171		if r.FormValue("delete") == "delete" {
2172			unfollowyou(user, honkerid, false)
2173			stmtDeleteHonker.Exec(honkerid)
2174			return h
2175		}
2176		if r.FormValue("unsub") == "unsub" {
2177			unfollowyou(user, honkerid, false)
2178		}
2179		if r.FormValue("sub") == "sub" {
2180			followyou(user, honkerid, false)
2181		}
2182		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2183		if err != nil {
2184			elog.Printf("update honker err: %s", err)
2185			return nil
2186		}
2187		return h
2188	}
2189
2190	if url == "" {
2191		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2192		return nil
2193	}
2194
2195	flavor := "presub"
2196	if peep == "peep" {
2197		flavor = "peep"
2198	}
2199
2200	var err error
2201	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2202	if err != nil {
2203		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2204		return nil
2205	}
2206	if flavor == "presub" {
2207		followyou(user, honkerid, false)
2208	}
2209	h.ID = honkerid
2210	return h
2211}
2212
2213func hfcspage(w http.ResponseWriter, r *http.Request) {
2214	userinfo := login.GetUserInfo(r)
2215
2216	filters := getfilters(userinfo.UserID, filtAny)
2217
2218	templinfo := getInfo(r)
2219	templinfo["Filters"] = filters
2220	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2221	err := readviews.Execute(w, "hfcs.html", templinfo)
2222	if err != nil {
2223		elog.Print(err)
2224	}
2225}
2226
2227func accountpage(w http.ResponseWriter, r *http.Request) {
2228	u := login.GetUserInfo(r)
2229	user, _ := butwhatabout(u.Username)
2230	templinfo := getInfo(r)
2231	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2232	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2233	templinfo["User"] = user
2234	about := user.About
2235	if ava := user.Options.Avatar; ava != "" {
2236		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2237	}
2238	if ban := user.Options.Banner; ban != "" {
2239		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2240	}
2241	templinfo["WhatAbout"] = about
2242	err := readviews.Execute(w, "account.html", templinfo)
2243	if err != nil {
2244		elog.Print(err)
2245	}
2246}
2247
2248func dochpass(w http.ResponseWriter, r *http.Request) {
2249	err := login.ChangePassword(w, r)
2250	if err != nil {
2251		elog.Printf("error changing password: %s", err)
2252	}
2253	http.Redirect(w, r, "/account", http.StatusSeeOther)
2254}
2255
2256var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2257	if strings.HasPrefix(orig, "acct:") {
2258		orig = orig[5:]
2259	}
2260	name := orig
2261	idx := strings.LastIndexByte(name, '/')
2262	if idx != -1 {
2263		name = name[idx+1:]
2264		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2265			ilog.Printf("foreign request rejected")
2266			name = ""
2267		}
2268	} else {
2269		idx = strings.IndexByte(name, '@')
2270		if idx != -1 {
2271			name = name[:idx]
2272			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2273				ilog.Printf("foreign request rejected")
2274				name = ""
2275			}
2276		}
2277	}
2278	user, err := butwhatabout(name)
2279	if err != nil {
2280		return nil, false
2281	}
2282
2283	j := junk.New()
2284	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2285	j["aliases"] = []string{user.URL}
2286	l := junk.New()
2287	l["rel"] = "self"
2288	l["type"] = `application/activity+json`
2289	l["href"] = user.URL
2290	j["links"] = []junk.Junk{l}
2291	return j.ToBytes(), true
2292}})
2293
2294func fingerlicker(w http.ResponseWriter, r *http.Request) {
2295	orig := r.FormValue("resource")
2296
2297	dlog.Printf("finger lick: %s", orig)
2298
2299	j, ok := oldfingers.Get(orig)
2300	if ok {
2301		w.Header().Set("Content-Type", "application/jrd+json")
2302		w.Write(j)
2303	} else {
2304		http.NotFound(w, r)
2305	}
2306}
2307
2308func somedays() string {
2309	secs := 432000 + notrand.Int63n(432000)
2310	return fmt.Sprintf("%d", secs)
2311}
2312
2313func lookatme(ava string) string {
2314	if strings.Contains(ava, serverName+"/"+userSep) {
2315		idx := strings.LastIndexByte(ava, '/')
2316		if idx < len(ava) {
2317			name := ava[idx+1:]
2318			user, _ := butwhatabout(name)
2319			if user != nil && user.URL == ava {
2320				return user.Options.Avatar
2321			}
2322		}
2323	}
2324	return ""
2325}
2326
2327func avatate(w http.ResponseWriter, r *http.Request) {
2328	if develMode {
2329		loadAvatarColors()
2330	}
2331	n := r.FormValue("a")
2332	if redir := lookatme(n); redir != "" {
2333		http.Redirect(w, r, redir, http.StatusSeeOther)
2334		return
2335	}
2336	a := genAvatar(n)
2337	if !develMode {
2338		w.Header().Set("Cache-Control", "max-age="+somedays())
2339	}
2340	w.Write(a)
2341}
2342
2343func serveviewasset(w http.ResponseWriter, r *http.Request) {
2344	serveasset(w, r, viewDir)
2345}
2346func servedataasset(w http.ResponseWriter, r *http.Request) {
2347	if r.URL.Path == "/favicon.ico" {
2348		r.URL.Path = "/icon.png"
2349	}
2350	serveasset(w, r, dataDir)
2351}
2352
2353func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2354	if !develMode {
2355		w.Header().Set("Cache-Control", "max-age=7776000")
2356	}
2357	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2358}
2359func servehelp(w http.ResponseWriter, r *http.Request) {
2360	name := mux.Vars(r)["name"]
2361	if !develMode {
2362		w.Header().Set("Cache-Control", "max-age=3600")
2363	}
2364	http.ServeFile(w, r, viewDir+"/docs/"+name)
2365}
2366func servehtml(w http.ResponseWriter, r *http.Request) {
2367	u := login.GetUserInfo(r)
2368	templinfo := getInfo(r)
2369	templinfo["AboutMsg"] = aboutMsg
2370	templinfo["LoginMsg"] = loginMsg
2371	templinfo["HonkVersion"] = softwareVersion
2372	if r.URL.Path == "/about" {
2373		templinfo["Sensors"] = getSensors()
2374	}
2375	if u == nil && !develMode {
2376		w.Header().Set("Cache-Control", "max-age=60")
2377	}
2378	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2379	if err != nil {
2380		elog.Print(err)
2381	}
2382}
2383func serveemu(w http.ResponseWriter, r *http.Request) {
2384	emu := mux.Vars(r)["emu"]
2385
2386	w.Header().Set("Cache-Control", "max-age="+somedays())
2387	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2388}
2389func servememe(w http.ResponseWriter, r *http.Request) {
2390	meme := mux.Vars(r)["meme"]
2391
2392	w.Header().Set("Cache-Control", "max-age="+somedays())
2393	_, err := os.Stat(dataDir + "/memes/" + meme)
2394	if err == nil {
2395		http.ServeFile(w, r, dataDir+"/memes/"+meme)
2396	} else {
2397		mux.Vars(r)["xid"] = meme
2398		servefile(w, r)
2399	}
2400}
2401
2402func servefile(w http.ResponseWriter, r *http.Request) {
2403	xid := mux.Vars(r)["xid"]
2404	var media string
2405	var data []byte
2406	row := stmtGetFileData.QueryRow(xid)
2407	err := row.Scan(&media, &data)
2408	if err != nil {
2409		elog.Printf("error loading file: %s", err)
2410		http.NotFound(w, r)
2411		return
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}
2439
2440func webhydra(w http.ResponseWriter, r *http.Request) {
2441	u := login.GetUserInfo(r)
2442	userid := u.UserID
2443	templinfo := getInfo(r)
2444	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2445	page := r.FormValue("page")
2446
2447	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2448
2449	var hydra Hydration
2450
2451	var honks []*Honk
2452	switch page {
2453	case "atme":
2454		honks = gethonksforme(userid, wanted)
2455		honks = osmosis(honks, userid, false)
2456		menewnone(userid)
2457		hydra.Srvmsg = "at me!"
2458	case "longago":
2459		honks = gethonksfromlongago(userid, wanted)
2460		honks = osmosis(honks, userid, false)
2461		hydra.Srvmsg = "from long ago"
2462	case "home":
2463		honks = gethonksforuser(userid, wanted)
2464		honks = osmosis(honks, userid, true)
2465		hydra.Srvmsg = serverMsg
2466	case "first":
2467		honks = gethonksforuserfirstclass(userid, wanted)
2468		honks = osmosis(honks, userid, true)
2469		hydra.Srvmsg = "first class only"
2470	case "saved":
2471		honks = getsavedhonks(userid, wanted)
2472		templinfo["PageName"] = "saved"
2473		hydra.Srvmsg = "saved honks"
2474	case "combo":
2475		c := r.FormValue("c")
2476		honks = gethonksbycombo(userid, c, wanted)
2477		honks = osmosis(honks, userid, false)
2478		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2479	case "convoy":
2480		c := r.FormValue("c")
2481		honks = gethonksbyconvoy(userid, c, wanted)
2482		honks = osmosis(honks, userid, false)
2483		honks = threadsort(honks)
2484		reversehonks(honks)
2485		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2486	case "honker":
2487		xid := r.FormValue("xid")
2488		honks = gethonksbyxonker(userid, xid, wanted)
2489		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2490			<input type="hidden" name="CSRF" value="%s">
2491			<input type="hidden" name="url" value="%s">
2492			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2493			</form>`, login.GetCSRF("submithonker", r), xid)
2494		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2495		hydra.Srvmsg = msg
2496	case "user":
2497		uname := r.FormValue("uname")
2498		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2499		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2500	default:
2501		http.NotFound(w, r)
2502	}
2503
2504	if len(honks) > 0 {
2505		hydra.Tophid = honks[0].ID
2506	} else {
2507		hydra.Tophid = wanted
2508	}
2509	reverbolate(userid, honks)
2510
2511	user, _ := butwhatabout(u.Username)
2512
2513	var buf strings.Builder
2514	templinfo["Honks"] = honks
2515	templinfo["MapLink"] = getmaplink(u)
2516	templinfo["User"], _ = butwhatabout(u.Username)
2517	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2518	if err != nil {
2519		elog.Printf("frag error: %s", err)
2520		return
2521	}
2522	hydra.Honks = buf.String()
2523	hydra.MeCount = user.Options.MeCount
2524	hydra.ChatCount = user.Options.ChatCount
2525	w.Header().Set("Content-Type", "application/json")
2526	j, _ := jsonify(&hydra)
2527	io.WriteString(w, j)
2528}
2529
2530var honkline = make(chan bool)
2531
2532func honkhonkline() {
2533	for {
2534		select {
2535		case honkline <- true:
2536		default:
2537			return
2538		}
2539	}
2540}
2541
2542func apihandler(w http.ResponseWriter, r *http.Request) {
2543	u := login.GetUserInfo(r)
2544	userid := u.UserID
2545	action := r.FormValue("action")
2546	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2547	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2548	switch action {
2549	case "honk":
2550		h := submithonk(w, r)
2551		if h == nil {
2552			return
2553		}
2554		fmt.Fprintf(w, "%s", h.XID)
2555	case "donk":
2556		donks, err := submitdonk(w, r)
2557		if err != nil {
2558			http.Error(w, err.Error(), http.StatusBadRequest)
2559			return
2560		}
2561		if len(donks) == 0 {
2562			http.Error(w, "missing donk", http.StatusBadRequest)
2563			return
2564		}
2565		d := donks[0]
2566		donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2567		w.Write([]byte(donkxid))
2568	case "zonkit":
2569		zonkit(w, r)
2570	case "gethonks":
2571		var honks []*Honk
2572		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2573		page := r.FormValue("page")
2574		var waitchan <-chan time.Time
2575	requery:
2576		switch page {
2577		case "atme":
2578			honks = gethonksforme(userid, wanted)
2579			honks = osmosis(honks, userid, false)
2580			menewnone(userid)
2581		case "longago":
2582			honks = gethonksfromlongago(userid, wanted)
2583			honks = osmosis(honks, userid, false)
2584		case "home":
2585			honks = gethonksforuser(userid, wanted)
2586			honks = osmosis(honks, userid, true)
2587		case "myhonks":
2588			honks = gethonksbyuser(u.Username, true, wanted)
2589			honks = osmosis(honks, userid, true)
2590		default:
2591			http.Error(w, "unknown page", http.StatusNotFound)
2592			return
2593		}
2594		if len(honks) == 0 && wait > 0 {
2595			if waitchan == nil {
2596				waitchan = time.After(time.Duration(wait) * time.Second)
2597			}
2598			select {
2599			case <-honkline:
2600				goto requery
2601			case <-waitchan:
2602			}
2603		}
2604		reverbolate(userid, honks)
2605		j := junk.New()
2606		j["honks"] = honks
2607		j.Write(w)
2608	case "sendactivity":
2609		user, _ := butwhatabout(u.Username)
2610		public := r.FormValue("public") == "1"
2611		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2612		msg := []byte(r.FormValue("msg"))
2613		for rcpt := range rcpts {
2614			go deliverate(userid, rcpt, msg)
2615		}
2616	case "gethonkers":
2617		j := junk.New()
2618		j["honkers"] = gethonkers(u.UserID)
2619		j.Write(w)
2620	case "savehonker":
2621		h := submithonker(w, r)
2622		if h == nil {
2623			return
2624		}
2625		fmt.Fprintf(w, "%d", h.ID)
2626	default:
2627		http.Error(w, "unknown action", http.StatusNotFound)
2628		return
2629	}
2630}
2631
2632func fiveoh(w http.ResponseWriter, r *http.Request) {
2633	if !develMode {
2634		return
2635	}
2636	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2637	if err != nil {
2638		elog.Printf("error opening violations! %s", err)
2639		return
2640	}
2641	defer fd.Close()
2642	io.Copy(fd, r.Body)
2643	fd.WriteString("\n")
2644}
2645
2646var endoftheworld = make(chan bool)
2647var readyalready = make(chan bool)
2648var workinprogress = 0
2649var requestWG sync.WaitGroup
2650var listenSocket net.Listener
2651
2652func enditall() {
2653	sig := make(chan os.Signal, 1)
2654	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2655	<-sig
2656	ilog.Printf("stopping...")
2657	listenSocket.Close()
2658	for i := 0; i < workinprogress; i++ {
2659		endoftheworld <- true
2660	}
2661	ilog.Printf("waiting...")
2662	go func() {
2663		time.Sleep(10 * time.Second)
2664		elog.Printf("timed out waiting for requests to finish")
2665		os.Exit(0)
2666	}()
2667	for i := 0; i < workinprogress; i++ {
2668		<-readyalready
2669	}
2670	requestWG.Wait()
2671	ilog.Printf("apocalypse")
2672	os.Exit(0)
2673}
2674
2675func bgmonitor() {
2676	for {
2677		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2678		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2679		if err != nil {
2680			elog.Printf("error deleting old xonkers: %s", err)
2681		}
2682		zaggies.Flush()
2683		time.Sleep(50 * time.Minute)
2684	}
2685}
2686
2687func addcspheaders(next http.Handler) http.Handler {
2688	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2689		requestWG.Add(1)
2690		defer requestWG.Done()
2691		policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2692		if develMode {
2693			policy += "; report-uri /csp-violation"
2694		}
2695		w.Header().Set("Content-Security-Policy", policy)
2696		next.ServeHTTP(w, r)
2697	})
2698}
2699
2700func emuinit() {
2701	var emunames []string
2702	dir, err := os.Open(dataDir + "/emus")
2703	if err == nil {
2704		emunames, _ = dir.Readdirnames(0)
2705		dir.Close()
2706	}
2707	for _, e := range emunames {
2708		if len(e) <= 4 {
2709			continue
2710		}
2711		ext := e[len(e)-4:]
2712		emu := Emu{
2713			ID:   fmt.Sprintf("/emu/%s", e),
2714			Name: e[:len(e)-4],
2715			Type: "image/" + ext[1:],
2716		}
2717		allemus = append(allemus, emu)
2718	}
2719	sort.Slice(allemus, func(i, j int) bool {
2720		return allemus[i].Name < allemus[j].Name
2721	})
2722}
2723
2724var savedassetparams = make(map[string]string)
2725
2726func getassetparam(file string) string {
2727	if p, ok := savedassetparams[file]; ok {
2728		return p
2729	}
2730	data, err := os.ReadFile(file)
2731	if err != nil {
2732		return ""
2733	}
2734	hasher := sha512.New()
2735	hasher.Write(data)
2736
2737	return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2738}
2739
2740func startWatcher() {
2741	watcher, err := gonix.NewWatcher()
2742	if err != nil {
2743		return
2744	}
2745	go func() {
2746		s := dataDir + "/views/local.css"
2747		for {
2748			err := watcher.WatchFile(s)
2749			if err != nil {
2750				break
2751			}
2752			err = watcher.WaitForChange()
2753			if err != nil {
2754				dlog.Printf("can't wait: %s", err)
2755				break
2756			}
2757			dlog.Printf("local.css changed")
2758			delete(savedassetparams, s)
2759			savedassetparams[s] = getassetparam(s)
2760		}
2761	}()
2762}
2763
2764var usefcgi bool
2765
2766func serve() {
2767	db := opendatabase()
2768	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2769
2770	listener, err := openListener()
2771	if err != nil {
2772		elog.Fatal(err)
2773	}
2774	runBackendServer()
2775	go enditall()
2776	go redeliverator()
2777	go tracker()
2778	go bgmonitor()
2779	go qotd()
2780	loadLingo()
2781	emuinit()
2782
2783	var toload []string
2784	dents, _ := os.ReadDir(viewDir + "/views")
2785	for _, dent := range dents {
2786		name := dent.Name()
2787		if strings.HasSuffix(name, ".html") {
2788			toload = append(toload, viewDir+"/views/"+name)
2789		}
2790	}
2791
2792	readviews = templates.Load(develMode, toload...)
2793	if !develMode {
2794		assets := []string{
2795			viewDir + "/views/style.css",
2796			dataDir + "/views/local.css",
2797			viewDir + "/views/honkpage.js",
2798			viewDir + "/views/misc.js",
2799			dataDir + "/views/local.js",
2800		}
2801		for _, s := range assets {
2802			savedassetparams[s] = getassetparam(s)
2803		}
2804		loadAvatarColors()
2805	}
2806	startWatcher()
2807
2808	securitizeweb()
2809
2810	mux := mux.NewRouter()
2811	mux.Use(addcspheaders)
2812	mux.Use(login.Checker)
2813
2814	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2815
2816	posters := mux.Methods("POST").Subrouter()
2817	getters := mux.Methods("GET").Subrouter()
2818
2819	getters.HandleFunc("/", homepage)
2820	getters.HandleFunc("/home", homepage)
2821	getters.HandleFunc("/front", homepage)
2822	getters.HandleFunc("/events", homepage)
2823	getters.HandleFunc("/robots.txt", nomoroboto)
2824	getters.HandleFunc("/rss", showrss)
2825	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2826	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2827	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2828	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2829	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2830	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2831	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2832	getters.HandleFunc("/a", avatate)
2833	getters.HandleFunc("/o", thelistingoftheontologies)
2834	getters.HandleFunc("/o/{name:.+}", showontology)
2835	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2836	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2837	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2838	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2839
2840	getters.HandleFunc("/flag/{code:.+}", showflag)
2841
2842	getters.HandleFunc("/server", serveractor)
2843	posters.HandleFunc("/server/inbox", serverinbox)
2844	posters.HandleFunc("/inbox", serverinbox)
2845
2846	posters.HandleFunc("/csp-violation", fiveoh)
2847
2848	getters.HandleFunc("/style.css", serveviewasset)
2849	getters.HandleFunc("/honkpage.js", serveviewasset)
2850	getters.HandleFunc("/misc.js", serveviewasset)
2851	getters.HandleFunc("/local.css", servedataasset)
2852	getters.HandleFunc("/local.js", servedataasset)
2853	getters.HandleFunc("/icon.png", servedataasset)
2854	getters.HandleFunc("/favicon.ico", servedataasset)
2855
2856	getters.HandleFunc("/about", servehtml)
2857	getters.HandleFunc("/login", servehtml)
2858	posters.HandleFunc("/dologin", login.LoginFunc)
2859	getters.HandleFunc("/logout", login.LogoutFunc)
2860	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2861
2862	loggedin := mux.NewRoute().Subrouter()
2863	loggedin.Use(login.Required)
2864	loggedin.HandleFunc("/first", homepage)
2865	loggedin.HandleFunc("/chatter", showchatter)
2866	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2867	loggedin.HandleFunc("/saved", homepage)
2868	loggedin.HandleFunc("/account", accountpage)
2869	loggedin.HandleFunc("/funzone", showfunzone)
2870	loggedin.HandleFunc("/chpass", dochpass)
2871	loggedin.HandleFunc("/atme", homepage)
2872	loggedin.HandleFunc("/longago", homepage)
2873	loggedin.HandleFunc("/hfcs", hfcspage)
2874	loggedin.HandleFunc("/xzone", xzone)
2875	loggedin.HandleFunc("/newhonk", newhonkpage)
2876	loggedin.HandleFunc("/edit", edithonkpage)
2877	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2878	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2879	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2880	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2881	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2882	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2883	loggedin.HandleFunc("/honkers", showhonkers)
2884	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2885	loggedin.HandleFunc("/h", showhonker)
2886	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2887	loggedin.HandleFunc("/c", showcombos)
2888	loggedin.HandleFunc("/t", showconvoy)
2889	loggedin.HandleFunc("/q", showsearch)
2890	loggedin.HandleFunc("/hydra", webhydra)
2891	loggedin.HandleFunc("/emus", showemus)
2892	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2893
2894	if usefcgi {
2895		err = fcgi.Serve(listener, mux)
2896	} else {
2897		err = http.Serve(listener, mux)
2898	}
2899	if err != nil && !errors.Is(err, net.ErrClosed) {
2900		elog.Printf("serve error: %s", err)
2901	}
2902	time.Sleep(15 * time.Second)
2903	elog.Printf("fell off the bottom")
2904}