all repos — honk @ 0f87c9ba9f9b9301059e9fada4675bf9c0339ee7

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