all repos — honk @ aa9b124486a6d616faa530544bccf2d5f6439705

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