all repos — honk @ v1.3.0

my fork of honk

web.go (view raw)

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