all repos — honk @ e6e46106cb20226329ab57e30c7152416da21525

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