all repos — honk @ 06bb4cda6cd19b14bcad2cc9f29e8fb96fc477c9

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