all repos — honk @ ad914bc3e057a0d2ac68c5c831e3e8939fd3cbce

my fork of honk

web.go (view raw)

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