all repos — honk @ 254d2ab513a185cb1457835fbd0d01e6befdb97b

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["ServerMessage"] = "honk edit"
1637	templinfo["IsPreview"] = true
1638	templinfo["UpdateXID"] = honk.XID
1639	if len(honk.Donks) > 0 {
1640		var savedfiles []string
1641		for _, d := range honk.Donks {
1642			savedfiles = append(savedfiles, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1643		}
1644		templinfo["SavedFile"] = strings.Join(savedfiles, ",")
1645	}
1646	err := readviews.Execute(w, "honkpage.html", templinfo)
1647	if err != nil {
1648		elog.Print(err)
1649	}
1650}
1651
1652func newhonkpage(w http.ResponseWriter, r *http.Request) {
1653	u := login.GetUserInfo(r)
1654	rid := r.FormValue("rid")
1655	noise := ""
1656
1657	xonk := getxonk(u.UserID, rid)
1658	if xonk != nil {
1659		_, replto := handles(xonk.Honker)
1660		if replto != "" {
1661			noise = "@" + replto + " "
1662		}
1663	}
1664
1665	templinfo := getInfo(r)
1666	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1667	templinfo["InReplyTo"] = rid
1668	templinfo["Noise"] = noise
1669	templinfo["ServerMessage"] = "compose honk"
1670	templinfo["IsPreview"] = true
1671	err := readviews.Execute(w, "honkpage.html", templinfo)
1672	if err != nil {
1673		elog.Print(err)
1674	}
1675}
1676
1677func canedithonk(user *WhatAbout, honk *Honk) bool {
1678	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1679		return false
1680	}
1681	return true
1682}
1683
1684func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1685	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1686		return nil, nil
1687	}
1688	var donks []*Donk
1689	for i, hdr := range r.MultipartForm.File["donk"] {
1690		if i > 16 {
1691			break
1692		}
1693		donk, err := formtodonk(w, r, hdr)
1694		if err != nil {
1695			return nil, err
1696		}
1697		donks = append(donks, donk)
1698	}
1699	return donks, nil
1700}
1701
1702func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1703	file, err := filehdr.Open()
1704	if err != nil {
1705		if err == http.ErrMissingFile {
1706			return nil, nil
1707		}
1708		elog.Printf("error reading donk: %s", err)
1709		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1710		return nil, err
1711	}
1712	var buf bytes.Buffer
1713	io.Copy(&buf, file)
1714	file.Close()
1715	data := buf.Bytes()
1716	var media, name string
1717	img, err := bigshrink(data)
1718	if err == nil {
1719		data = img.Data
1720		format := img.Format
1721		media = "image/" + format
1722		if format == "jpeg" {
1723			format = "jpg"
1724		}
1725		if format == "svg+xml" {
1726			format = "svg"
1727		}
1728		name = xfiltrate() + "." + format
1729	} else {
1730		ct := http.DetectContentType(data)
1731		switch ct {
1732		case "application/pdf":
1733			maxsize := 10000000
1734			if len(data) > maxsize {
1735				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1736				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1737				return nil, err
1738			}
1739			media = ct
1740			name = filehdr.Filename
1741			if name == "" {
1742				name = xfiltrate() + ".pdf"
1743			}
1744		default:
1745			maxsize := 100000
1746			if len(data) > maxsize {
1747				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1748				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1749				return nil, err
1750			}
1751			for i := 0; i < len(data); i++ {
1752				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1753					ilog.Printf("bad image: %s not text: %d", err, data[i])
1754					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1755					return nil, err
1756				}
1757			}
1758			media = "text/plain"
1759			name = filehdr.Filename
1760			if name == "" {
1761				name = xfiltrate() + ".txt"
1762			}
1763		}
1764	}
1765	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1766	if desc == "" {
1767		desc = name
1768	}
1769	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1770	if err != nil {
1771		elog.Printf("unable to save image: %s", err)
1772		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1773		return nil, err
1774	}
1775	d := &Donk{
1776		FileID: fileid,
1777		XID:    xid,
1778		Desc:   desc,
1779		Local:  true,
1780	}
1781	return d, nil
1782}
1783
1784func websubmithonk(w http.ResponseWriter, r *http.Request) {
1785	h := submithonk(w, r)
1786	if h == nil {
1787		return
1788	}
1789	redir := h.XID[len(serverURL("")):]
1790	http.Redirect(w, r, redir, http.StatusSeeOther)
1791}
1792
1793// what a hot mess this function is
1794func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1795	rid := r.FormValue("rid")
1796	noise := r.FormValue("noise")
1797	format := r.FormValue("format")
1798	if format == "" {
1799		format = "markdown"
1800	}
1801	if !(format == "markdown" || format == "html") {
1802		http.Error(w, "unknown format", 500)
1803		return nil
1804	}
1805
1806	userinfo := login.GetUserInfo(r)
1807	user, _ := butwhatabout(userinfo.Username)
1808
1809	dt := time.Now().UTC()
1810	updatexid := r.FormValue("updatexid")
1811	var honk *Honk
1812	if updatexid != "" {
1813		honk = getxonk(userinfo.UserID, updatexid)
1814		if !canedithonk(user, honk) {
1815			http.Error(w, "no editing that please", http.StatusInternalServerError)
1816			return nil
1817		}
1818		honk.Date = dt
1819		honk.What = "update"
1820		honk.Format = format
1821	} else {
1822		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1823		what := "honk"
1824		honk = &Honk{
1825			UserID:   userinfo.UserID,
1826			Username: userinfo.Username,
1827			What:     what,
1828			Honker:   user.URL,
1829			XID:      xid,
1830			Date:     dt,
1831			Format:   format,
1832		}
1833	}
1834
1835	var convoy string
1836	noise = strings.Replace(noise, "\r", "", -1)
1837	if updatexid == "" && rid == "" {
1838		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1839			convoy = m[7:]
1840			convoy = strings.TrimSpace(convoy)
1841			if !re_convalidate.MatchString(convoy) {
1842				convoy = ""
1843			}
1844			return ""
1845		})
1846	}
1847	noise = quickrename(noise, userinfo.UserID)
1848	honk.Noise = noise
1849	precipitate(honk)
1850	noise = honk.Noise
1851	recategorize(honk)
1852	translate(honk)
1853
1854	if rid != "" {
1855		xonk := getxonk(userinfo.UserID, rid)
1856		if xonk == nil {
1857			http.Error(w, "replyto disappeared", http.StatusNotFound)
1858			return nil
1859		}
1860		if xonk.Public {
1861			honk.Audience = append(honk.Audience, xonk.Audience...)
1862		}
1863		convoy = xonk.Convoy
1864		for i, a := range honk.Audience {
1865			if a == thewholeworld {
1866				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1867				break
1868			}
1869		}
1870		honk.RID = rid
1871		if xonk.Precis != "" && honk.Precis == "" {
1872			honk.Precis = xonk.Precis
1873			if !re_dangerous.MatchString(honk.Precis) {
1874				honk.Precis = "re: " + honk.Precis
1875			}
1876		}
1877	} else if updatexid == "" {
1878		honk.Audience = []string{thewholeworld}
1879	}
1880	if noise != "" && noise[0] == '@' {
1881		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1882	} else {
1883		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1884	}
1885
1886	if convoy == "" {
1887		convoy = "data:,electrichonkytonk-" + xfiltrate()
1888	}
1889	butnottooloud(honk.Audience)
1890	honk.Audience = oneofakind(honk.Audience)
1891	if len(honk.Audience) == 0 {
1892		ilog.Printf("honk to nowhere")
1893		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1894		return nil
1895	}
1896	honk.Public = loudandproud(honk.Audience)
1897	honk.Convoy = convoy
1898
1899	donkxid := strings.Join(r.Form["donkxid"], ",")
1900	if donkxid == "" {
1901		donks, err := submitdonk(w, r)
1902		if err != nil && err != http.ErrMissingFile {
1903			return nil
1904		}
1905		if len(donks) > 0 {
1906			honk.Donks = append(honk.Donks, donks...)
1907			var xids []string
1908			for _, d := range honk.Donks {
1909				xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1910			}
1911			donkxid = strings.Join(xids, ",")
1912		}
1913	} else {
1914		xids := strings.Split(donkxid, ",")
1915		for i, xid := range xids {
1916			if i > 16 {
1917				break
1918			}
1919			p := strings.Split(xid, ":")
1920			xid = p[0]
1921			url := serverURL("/d/%s", xid)
1922			var donk *Donk
1923			if len(p) > 1 {
1924				fileid, _ := strconv.ParseInt(p[1], 10, 0)
1925				donk = finddonkid(fileid, url)
1926			} else {
1927				donk = finddonk(url)
1928			}
1929			if donk != nil {
1930				honk.Donks = append(honk.Donks, donk)
1931			} else {
1932				ilog.Printf("can't find file: %s", xid)
1933			}
1934		}
1935	}
1936	memetize(honk)
1937	imaginate(honk)
1938
1939	placename := strings.TrimSpace(r.FormValue("placename"))
1940	placelat := strings.TrimSpace(r.FormValue("placelat"))
1941	placelong := strings.TrimSpace(r.FormValue("placelong"))
1942	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1943	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1944		p := new(Place)
1945		p.Name = placename
1946		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1947		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1948		p.Url = placeurl
1949		honk.Place = p
1950	}
1951	timestart := strings.TrimSpace(r.FormValue("timestart"))
1952	if timestart != "" {
1953		t := new(Time)
1954		now := time.Now().Local()
1955		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1956			start, err := time.ParseInLocation(layout, timestart, now.Location())
1957			if err == nil {
1958				if start.Year() == 0 {
1959					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1960				}
1961				t.StartTime = start
1962				break
1963			}
1964		}
1965		timeend := r.FormValue("timeend")
1966		dur := parseDuration(timeend)
1967		if dur != 0 {
1968			t.Duration = Duration(dur)
1969		}
1970		if !t.StartTime.IsZero() {
1971			honk.What = "event"
1972			honk.Time = t
1973		}
1974	}
1975
1976	if honk.Public {
1977		honk.Whofore = 2
1978	} else {
1979		honk.Whofore = 3
1980	}
1981
1982	// back to markdown
1983	honk.Noise = noise
1984
1985	if r.FormValue("preview") == "preview" {
1986		honks := []*Honk{honk}
1987		reverbolate(userinfo.UserID, honks)
1988		templinfo := getInfo(r)
1989		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1990		templinfo["Honks"] = honks
1991		templinfo["MapLink"] = getmaplink(userinfo)
1992		templinfo["InReplyTo"] = r.FormValue("rid")
1993		templinfo["Noise"] = r.FormValue("noise")
1994		templinfo["SavedFile"] = donkxid
1995		if tm := honk.Time; tm != nil {
1996			templinfo["ShowTime"] = " "
1997			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1998			if tm.Duration != 0 {
1999				templinfo["Duration"] = tm.Duration
2000			}
2001		}
2002		templinfo["IsPreview"] = true
2003		templinfo["UpdateXID"] = updatexid
2004		templinfo["ServerMessage"] = "honk preview"
2005		err := readviews.Execute(w, "honkpage.html", templinfo)
2006		if err != nil {
2007			elog.Print(err)
2008		}
2009		return nil
2010	}
2011
2012	if updatexid != "" {
2013		updatehonk(honk)
2014		oldjonks.Clear(honk.XID)
2015	} else {
2016		err := savehonk(honk)
2017		if err != nil {
2018			elog.Printf("uh oh")
2019			return nil
2020		}
2021	}
2022
2023	// reload for consistency
2024	honk.Donks = nil
2025	donksforhonks([]*Honk{honk})
2026
2027	go honkworldwide(user, honk)
2028
2029	return honk
2030}
2031
2032func showhonkers(w http.ResponseWriter, r *http.Request) {
2033	userinfo := login.GetUserInfo(r)
2034	templinfo := getInfo(r)
2035	templinfo["Honkers"] = gethonkers(userinfo.UserID)
2036	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2037	err := readviews.Execute(w, "honkers.html", templinfo)
2038	if err != nil {
2039		elog.Print(err)
2040	}
2041}
2042
2043func showchatter(w http.ResponseWriter, r *http.Request) {
2044	u := login.GetUserInfo(r)
2045	chatnewnone(u.UserID)
2046	chatter := loadchatter(u.UserID)
2047	for _, chat := range chatter {
2048		for _, ch := range chat.Chonks {
2049			filterchonk(ch)
2050		}
2051	}
2052
2053	templinfo := getInfo(r)
2054	templinfo["Chatter"] = chatter
2055	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2056	err := readviews.Execute(w, "chatter.html", templinfo)
2057	if err != nil {
2058		elog.Print(err)
2059	}
2060}
2061
2062func submitchonk(w http.ResponseWriter, r *http.Request) {
2063	u := login.GetUserInfo(r)
2064	user, _ := butwhatabout(u.Username)
2065	noise := r.FormValue("noise")
2066	target := r.FormValue("target")
2067	format := "markdown"
2068	dt := time.Now().UTC()
2069	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2070
2071	if !strings.HasPrefix(target, "https://") {
2072		target = fullname(target, u.UserID)
2073	}
2074	if target == "" {
2075		http.Error(w, "who is that?", http.StatusInternalServerError)
2076		return
2077	}
2078	ch := Chonk{
2079		UserID: u.UserID,
2080		XID:    xid,
2081		Who:    user.URL,
2082		Target: target,
2083		Date:   dt,
2084		Noise:  noise,
2085		Format: format,
2086	}
2087	donks, err := submitdonk(w, r)
2088	if err != nil && err != http.ErrMissingFile {
2089		return
2090	}
2091	if len(donks) > 0 {
2092		ch.Donks = append(ch.Donks, donks...)
2093	}
2094
2095	translatechonk(&ch)
2096	savechonk(&ch)
2097	// reload for consistency
2098	ch.Donks = nil
2099	donksforchonks([]*Chonk{&ch})
2100	go sendchonk(user, &ch)
2101
2102	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2103}
2104
2105var combocache = gencache.New(gencache.Options[int64, []string]{Fill: func(userid int64) ([]string, bool) {
2106	honkers := gethonkers(userid)
2107	var combos []string
2108	for _, h := range honkers {
2109		combos = append(combos, h.Combos...)
2110	}
2111	for i, c := range combos {
2112		if c == "-" {
2113			combos[i] = ""
2114		}
2115	}
2116	combos = oneofakind(combos)
2117	sort.Strings(combos)
2118	return combos, true
2119}, Invalidator: &honkerinvalidator})
2120
2121func showcombos(w http.ResponseWriter, r *http.Request) {
2122	templinfo := getInfo(r)
2123	err := readviews.Execute(w, "combos.html", templinfo)
2124	if err != nil {
2125		elog.Print(err)
2126	}
2127}
2128
2129func websubmithonker(w http.ResponseWriter, r *http.Request) {
2130	h := submithonker(w, r)
2131	if h == nil {
2132		return
2133	}
2134	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2135}
2136
2137func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2138	u := login.GetUserInfo(r)
2139	user, _ := butwhatabout(u.Username)
2140	name := strings.TrimSpace(r.FormValue("name"))
2141	url := strings.TrimSpace(r.FormValue("url"))
2142	peep := r.FormValue("peep")
2143	combos := strings.TrimSpace(r.FormValue("combos"))
2144	combos = " " + combos + " "
2145	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2146
2147	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2148	if name != "" && !re_namecheck.MatchString(name) {
2149		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2150		return nil
2151	}
2152
2153	var meta HonkerMeta
2154	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2155	mj, _ := jsonify(&meta)
2156
2157	defer honkerinvalidator.Clear(u.UserID)
2158
2159	// mostly dummy, fill in later...
2160	h := &Honker{
2161		ID: honkerid,
2162	}
2163
2164	if honkerid > 0 {
2165		if r.FormValue("delete") == "delete" {
2166			unfollowyou(user, honkerid, false)
2167			stmtDeleteHonker.Exec(honkerid)
2168			return h
2169		}
2170		if r.FormValue("unsub") == "unsub" {
2171			unfollowyou(user, honkerid, false)
2172		}
2173		if r.FormValue("sub") == "sub" {
2174			followyou(user, honkerid, false)
2175		}
2176		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2177		if err != nil {
2178			elog.Printf("update honker err: %s", err)
2179			return nil
2180		}
2181		return h
2182	}
2183
2184	if url == "" {
2185		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2186		return nil
2187	}
2188
2189	flavor := "presub"
2190	if peep == "peep" {
2191		flavor = "peep"
2192	}
2193
2194	var err error
2195	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2196	if err != nil {
2197		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2198		return nil
2199	}
2200	if flavor == "presub" {
2201		followyou(user, honkerid, false)
2202	}
2203	h.ID = honkerid
2204	return h
2205}
2206
2207func hfcspage(w http.ResponseWriter, r *http.Request) {
2208	userinfo := login.GetUserInfo(r)
2209
2210	filters := getfilters(userinfo.UserID, filtAny)
2211
2212	templinfo := getInfo(r)
2213	templinfo["Filters"] = filters
2214	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2215	err := readviews.Execute(w, "hfcs.html", templinfo)
2216	if err != nil {
2217		elog.Print(err)
2218	}
2219}
2220
2221func accountpage(w http.ResponseWriter, r *http.Request) {
2222	u := login.GetUserInfo(r)
2223	user, _ := butwhatabout(u.Username)
2224	templinfo := getInfo(r)
2225	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2226	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2227	templinfo["User"] = user
2228	about := user.About
2229	if ava := user.Options.Avatar; ava != "" {
2230		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2231	}
2232	if ban := user.Options.Banner; ban != "" {
2233		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2234	}
2235	templinfo["WhatAbout"] = about
2236	err := readviews.Execute(w, "account.html", templinfo)
2237	if err != nil {
2238		elog.Print(err)
2239	}
2240}
2241
2242func dochpass(w http.ResponseWriter, r *http.Request) {
2243	err := login.ChangePassword(w, r)
2244	if err != nil {
2245		elog.Printf("error changing password: %s", err)
2246	}
2247	http.Redirect(w, r, "/account", http.StatusSeeOther)
2248}
2249
2250var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2251	if strings.HasPrefix(orig, "acct:") {
2252		orig = orig[5:]
2253	}
2254	name := orig
2255	idx := strings.LastIndexByte(name, '/')
2256	if idx != -1 {
2257		name = name[idx+1:]
2258		if serverURL("/%s/%s", userSep, name) != orig {
2259			ilog.Printf("foreign request rejected")
2260			name = ""
2261		}
2262	} else {
2263		idx = strings.IndexByte(name, '@')
2264		if idx != -1 {
2265			name = name[:idx]
2266			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2267				ilog.Printf("foreign request rejected")
2268				name = ""
2269			}
2270		}
2271	}
2272	user, err := butwhatabout(name)
2273	if err != nil {
2274		return nil, false
2275	}
2276
2277	j := junk.New()
2278	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2279	j["aliases"] = []string{user.URL}
2280	l := junk.New()
2281	l["rel"] = "self"
2282	l["type"] = `application/activity+json`
2283	l["href"] = user.URL
2284	j["links"] = []junk.Junk{l}
2285	return j.ToBytes(), true
2286}})
2287
2288func fingerlicker(w http.ResponseWriter, r *http.Request) {
2289	orig := r.FormValue("resource")
2290
2291	dlog.Printf("finger lick: %s", orig)
2292
2293	j, ok := oldfingers.Get(orig)
2294	if ok {
2295		w.Header().Set("Content-Type", "application/jrd+json")
2296		w.Write(j)
2297	} else {
2298		http.NotFound(w, r)
2299	}
2300}
2301
2302func somedays() string {
2303	secs := 432000 + notrand.Int63n(432000)
2304	return fmt.Sprintf("%d", secs)
2305}
2306
2307func lookatme(ava string) string {
2308	if strings.Contains(ava, serverName+"/"+userSep) {
2309		idx := strings.LastIndexByte(ava, '/')
2310		if idx < len(ava) {
2311			name := ava[idx+1:]
2312			user, _ := butwhatabout(name)
2313			if user != nil && user.URL == ava {
2314				return user.Options.Avatar
2315			}
2316		}
2317	}
2318	return ""
2319}
2320
2321func avatate(w http.ResponseWriter, r *http.Request) {
2322	if develMode {
2323		loadAvatarColors()
2324	}
2325	n := r.FormValue("a")
2326	if redir := lookatme(n); redir != "" {
2327		http.Redirect(w, r, redir, http.StatusSeeOther)
2328		return
2329	}
2330	a := genAvatar(n)
2331	if !develMode {
2332		w.Header().Set("Cache-Control", "max-age="+somedays())
2333	}
2334	w.Write(a)
2335}
2336
2337func serveviewasset(w http.ResponseWriter, r *http.Request) {
2338	serveasset(w, r, viewDir)
2339}
2340func servedataasset(w http.ResponseWriter, r *http.Request) {
2341	if r.URL.Path == "/favicon.ico" {
2342		r.URL.Path = "/icon.png"
2343	}
2344	serveasset(w, r, dataDir)
2345}
2346
2347func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2348	if !develMode {
2349		w.Header().Set("Cache-Control", "max-age=7776000")
2350	}
2351	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2352}
2353func servehelp(w http.ResponseWriter, r *http.Request) {
2354	name := mux.Vars(r)["name"]
2355	if !develMode {
2356		w.Header().Set("Cache-Control", "max-age=3600")
2357	}
2358	http.ServeFile(w, r, viewDir+"/docs/"+name)
2359}
2360func servehtml(w http.ResponseWriter, r *http.Request) {
2361	u := login.GetUserInfo(r)
2362	templinfo := getInfo(r)
2363	templinfo["AboutMsg"] = aboutMsg
2364	templinfo["LoginMsg"] = loginMsg
2365	templinfo["HonkVersion"] = softwareVersion
2366	if r.URL.Path == "/about" {
2367		templinfo["Sensors"] = getSensors()
2368	}
2369	if u == nil && !develMode {
2370		w.Header().Set("Cache-Control", "max-age=60")
2371	}
2372	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2373	if err != nil {
2374		elog.Print(err)
2375	}
2376}
2377func serveemu(w http.ResponseWriter, r *http.Request) {
2378	emu := mux.Vars(r)["emu"]
2379
2380	w.Header().Set("Cache-Control", "max-age="+somedays())
2381	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2382}
2383func servememe(w http.ResponseWriter, r *http.Request) {
2384	meme := mux.Vars(r)["meme"]
2385
2386	w.Header().Set("Cache-Control", "max-age="+somedays())
2387	_, err := os.Stat(dataDir + "/memes/" + meme)
2388	if err == nil {
2389		http.ServeFile(w, r, dataDir+"/memes/"+meme)
2390	} else {
2391		mux.Vars(r)["xid"] = meme
2392		servefile(w, r)
2393	}
2394}
2395
2396func servefile(w http.ResponseWriter, r *http.Request) {
2397	if friendorfoe(r.Header.Get("Accept")) {
2398		dlog.Printf("incompatible accept for donk")
2399		http.Error(w, "there are no activities here", http.StatusNotAcceptable)
2400		return
2401	}
2402	xid := mux.Vars(r)["xid"]
2403	preview := r.FormValue("preview") == "1"
2404	var media string
2405	var data []byte
2406	row := stmtGetFileData.QueryRow(xid)
2407	err := row.Scan(&media, &data)
2408	if err != nil {
2409		elog.Printf("error loading file: %s", err)
2410		http.NotFound(w, r)
2411		return
2412	}
2413	if preview && strings.HasPrefix(media, "image") {
2414		img, err := lilshrink(data)
2415		if err == nil {
2416			data = img.Data
2417		}
2418	}
2419	w.Header().Set("Content-Type", media)
2420	w.Header().Set("X-Content-Type-Options", "nosniff")
2421	w.Header().Set("Cache-Control", "max-age="+somedays())
2422	w.Write(data)
2423}
2424
2425func nomoroboto(w http.ResponseWriter, r *http.Request) {
2426	io.WriteString(w, "User-agent: *\n")
2427	io.WriteString(w, "Disallow: /a\n")
2428	io.WriteString(w, "Disallow: /d/\n")
2429	io.WriteString(w, "Disallow: /meme/\n")
2430	io.WriteString(w, "Disallow: /o\n")
2431	io.WriteString(w, "Disallow: /o/\n")
2432	io.WriteString(w, "Disallow: /help/\n")
2433	for _, u := range allusers() {
2434		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2435	}
2436}
2437
2438type Hydration struct {
2439	Tophid    int64
2440	Srvmsg    template.HTML
2441	Honks     string
2442	MeCount   int64
2443	ChatCount int64
2444	Poses     []int
2445}
2446
2447func webhydra(w http.ResponseWriter, r *http.Request) {
2448	u := login.GetUserInfo(r)
2449	userid := u.UserID
2450	templinfo := getInfo(r)
2451	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2452	page := r.FormValue("page")
2453
2454	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2455
2456	var hydra Hydration
2457
2458	var honks []*Honk
2459	switch page {
2460	case "atme":
2461		honks = gethonksforme(userid, wanted)
2462		honks = osmosis(honks, userid, false)
2463		menewnone(userid)
2464		hydra.Srvmsg = "at me!"
2465	case "longago":
2466		honks = gethonksfromlongago(userid, wanted)
2467		honks = osmosis(honks, userid, false)
2468		hydra.Srvmsg = "from long ago"
2469	case "home":
2470		honks = gethonksforuser(userid, wanted)
2471		honks = osmosis(honks, userid, true)
2472		hydra.Srvmsg = serverMsg
2473	case "first":
2474		honks = gethonksforuserfirstclass(userid, wanted)
2475		honks = osmosis(honks, userid, true)
2476		hydra.Srvmsg = "first class only"
2477	case "saved":
2478		honks = getsavedhonks(userid, wanted)
2479		templinfo["PageName"] = "saved"
2480		hydra.Srvmsg = "saved honks"
2481	case "combo":
2482		c := r.FormValue("c")
2483		honks = gethonksbycombo(userid, c, wanted)
2484		honks = osmosis(honks, userid, false)
2485		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2486	case "convoy":
2487		c := r.FormValue("c")
2488		honks = gethonksbyconvoy(userid, c, 0)
2489		honks = osmosis(honks, userid, false)
2490		honks = threadsort(honks)
2491		honks, hydra.Poses = threadposes(honks, wanted)
2492		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2493	case "honker":
2494		xid := r.FormValue("xid")
2495		honks = gethonksbyxonker(userid, xid, wanted)
2496		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2497			<input type="hidden" name="CSRF" value="%s">
2498			<input type="hidden" name="url" value="%s">
2499			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2500			</form>`, login.GetCSRF("submithonker", r), xid)
2501		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2502		hydra.Srvmsg = msg
2503	case "user":
2504		uname := r.FormValue("uname")
2505		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2506		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2507	default:
2508		http.NotFound(w, r)
2509	}
2510
2511	if len(honks) > 0 {
2512		if page == "convoy" {
2513			hydra.Tophid = honks[len(honks)-1].ID
2514		} else {
2515			hydra.Tophid = honks[0].ID
2516		}
2517	} else {
2518		hydra.Tophid = wanted
2519	}
2520	reverbolate(userid, honks)
2521
2522	user, _ := butwhatabout(u.Username)
2523
2524	var buf strings.Builder
2525	templinfo["Honks"] = honks
2526	templinfo["MapLink"] = getmaplink(u)
2527	templinfo["User"], _ = butwhatabout(u.Username)
2528	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2529	if err != nil {
2530		elog.Printf("frag error: %s", err)
2531		return
2532	}
2533	hydra.Honks = buf.String()
2534	hydra.MeCount = user.Options.MeCount
2535	hydra.ChatCount = user.Options.ChatCount
2536	w.Header().Set("Content-Type", "application/json")
2537	j, _ := jsonify(&hydra)
2538	io.WriteString(w, j)
2539}
2540
2541var honkline = make(chan bool)
2542
2543func honkhonkline() {
2544	for {
2545		select {
2546		case honkline <- true:
2547		default:
2548			return
2549		}
2550	}
2551}
2552
2553func apihandler(w http.ResponseWriter, r *http.Request) {
2554	u := login.GetUserInfo(r)
2555	userid := u.UserID
2556	action := r.FormValue("action")
2557	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2558	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2559	switch action {
2560	case "honk":
2561		h := submithonk(w, r)
2562		if h == nil {
2563			return
2564		}
2565		fmt.Fprintf(w, "%s", h.XID)
2566	case "donk":
2567		donks, err := submitdonk(w, r)
2568		if err != nil {
2569			http.Error(w, err.Error(), http.StatusBadRequest)
2570			return
2571		}
2572		if len(donks) == 0 {
2573			http.Error(w, "missing donk", http.StatusBadRequest)
2574			return
2575		}
2576		d := donks[0]
2577		donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2578		w.Write([]byte(donkxid))
2579	case "zonkit":
2580		zonkit(w, r)
2581	case "gethonks":
2582		var honks []*Honk
2583		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2584		page := r.FormValue("page")
2585		var waitchan <-chan time.Time
2586	requery:
2587		switch page {
2588		case "atme":
2589			honks = gethonksforme(userid, wanted)
2590			honks = osmosis(honks, userid, false)
2591			menewnone(userid)
2592		case "longago":
2593			honks = gethonksfromlongago(userid, wanted)
2594			honks = osmosis(honks, userid, false)
2595		case "home":
2596			honks = gethonksforuser(userid, wanted)
2597			honks = osmosis(honks, userid, true)
2598		case "myhonks":
2599			honks = gethonksbyuser(u.Username, true, wanted)
2600			honks = osmosis(honks, userid, true)
2601		case "saved":
2602			honks = getsavedhonks(userid, wanted)
2603		case "combo":
2604			c := r.FormValue("c")
2605			honks = gethonksbycombo(userid, c, wanted)
2606			honks = osmosis(honks, userid, false)
2607		case "convoy":
2608			c := r.FormValue("c")
2609			honks = gethonksbyconvoy(userid, c, 0)
2610			honks = osmosis(honks, userid, false)
2611			honks = threadsort(honks)
2612			honks, _ = threadposes(honks, wanted)
2613		case "honker":
2614			xid := r.FormValue("xid")
2615			honks = gethonksbyxonker(userid, xid, wanted)
2616		case "search":
2617			q := r.FormValue("q")
2618			honks = gethonksbysearch(u.UserID, q, wanted)
2619		default:
2620			http.Error(w, "unknown page", http.StatusNotFound)
2621			return
2622		}
2623		if len(honks) == 0 && wait > 0 {
2624			if waitchan == nil {
2625				waitchan = time.After(time.Duration(wait) * time.Second)
2626			}
2627			select {
2628			case <-honkline:
2629				goto requery
2630			case <-waitchan:
2631			}
2632		}
2633		reverbolate(userid, honks)
2634		user, _ := butwhatabout(u.Username)
2635		j := junk.New()
2636		j["honks"] = honks
2637		j["mecount"] = user.Options.MeCount
2638		j["chatcount"] = user.Options.ChatCount
2639		j.Write(w)
2640	case "sendactivity":
2641		public := r.FormValue("public") == "1"
2642		user, _ := butwhatabout(u.Username)
2643		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2644		msg := []byte(r.FormValue("msg"))
2645		for rcpt := range rcpts {
2646			go deliverate(userid, rcpt, msg)
2647		}
2648	case "gethonkers":
2649		j := junk.New()
2650		j["honkers"] = gethonkers(u.UserID)
2651		j.Write(w)
2652	case "savehonker":
2653		h := submithonker(w, r)
2654		if h == nil {
2655			return
2656		}
2657		fmt.Fprintf(w, "%d", h.ID)
2658	default:
2659		http.Error(w, "unknown action", http.StatusNotFound)
2660		return
2661	}
2662}
2663
2664func fiveoh(w http.ResponseWriter, r *http.Request) {
2665	if !develMode {
2666		return
2667	}
2668	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2669	if err != nil {
2670		elog.Printf("error opening violations! %s", err)
2671		return
2672	}
2673	defer fd.Close()
2674	io.Copy(fd, r.Body)
2675	fd.WriteString("\n")
2676}
2677
2678var endoftheworld = make(chan bool)
2679var readyalready = make(chan bool)
2680var workinprogress = 0
2681var requestWG sync.WaitGroup
2682var listenSocket net.Listener
2683
2684func enditall() {
2685	sig := make(chan os.Signal, 1)
2686	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2687	<-sig
2688	ilog.Printf("stopping...")
2689	listenSocket.Close()
2690	for i := 0; i < workinprogress; i++ {
2691		endoftheworld <- true
2692	}
2693	if *cpuprofile != "" {
2694		pprof.StopCPUProfile()
2695	}
2696	if *memprofile != "" {
2697		pprof.WriteHeapProfile(memprofilefd)
2698		memprofilefd.Close()
2699	}
2700	ilog.Printf("waiting...")
2701	go func() {
2702		time.Sleep(10 * time.Second)
2703		elog.Printf("timed out waiting for requests to finish")
2704		os.Exit(0)
2705	}()
2706	for i := 0; i < workinprogress; i++ {
2707		<-readyalready
2708	}
2709	requestWG.Wait()
2710	ilog.Printf("apocalypse")
2711	closedatabases()
2712	os.Exit(0)
2713}
2714
2715func bgmonitor() {
2716	for {
2717		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2718		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2719		if err != nil {
2720			elog.Printf("error deleting old xonkers: %s", err)
2721		}
2722		zaggies.Flush()
2723		time.Sleep(50 * time.Minute)
2724	}
2725}
2726
2727func addcspheaders(next http.Handler) http.Handler {
2728	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2729		requestWG.Add(1)
2730		defer requestWG.Done()
2731		policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2732		if develMode {
2733			policy += "; report-uri /csp-violation"
2734		}
2735		w.Header().Set("Content-Security-Policy", policy)
2736		next.ServeHTTP(w, r)
2737	})
2738}
2739
2740func emuinit() {
2741	var emunames []string
2742	dir, err := os.Open(dataDir + "/emus")
2743	if err == nil {
2744		emunames, _ = dir.Readdirnames(0)
2745		dir.Close()
2746	}
2747	for _, e := range emunames {
2748		if len(e) <= 4 {
2749			continue
2750		}
2751		ext := e[len(e)-4:]
2752		emu := Emu{
2753			ID:   fmt.Sprintf("/emu/%s", e),
2754			Name: e[:len(e)-4],
2755			Type: "image/" + ext[1:],
2756		}
2757		allemus = append(allemus, emu)
2758	}
2759	sort.Slice(allemus, func(i, j int) bool {
2760		return allemus[i].Name < allemus[j].Name
2761	})
2762}
2763
2764var savedassetparams = make(map[string]string)
2765
2766func getassetparam(file string) string {
2767	if p, ok := savedassetparams[file]; ok {
2768		return p
2769	}
2770	data, err := os.ReadFile(file)
2771	if err != nil {
2772		return ""
2773	}
2774	hasher := sha512.New()
2775	hasher.Write(data)
2776
2777	return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2778}
2779
2780func startWatcher() {
2781	watcher, err := gonix.NewWatcher()
2782	if err != nil {
2783		return
2784	}
2785	go func() {
2786		s := dataDir + "/views/local.css"
2787		for {
2788			err := watcher.WatchFile(s)
2789			if err != nil {
2790				break
2791			}
2792			err = watcher.WaitForChange()
2793			if err != nil {
2794				dlog.Printf("can't wait: %s", err)
2795				break
2796			}
2797			dlog.Printf("local.css changed")
2798			delete(savedassetparams, s)
2799			savedassetparams[s] = getassetparam(s)
2800		}
2801	}()
2802}
2803
2804var usefcgi bool
2805
2806func serve() {
2807	db := opendatabase()
2808	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2809
2810	listener, err := openListener()
2811	if err != nil {
2812		elog.Fatal(err)
2813	}
2814	runBackendServer()
2815	go enditall()
2816	go redeliverator()
2817	go tracker()
2818	go bgmonitor()
2819	go qotd()
2820	loadLingo()
2821	emuinit()
2822
2823	var toload []string
2824	dents, _ := os.ReadDir(viewDir + "/views")
2825	for _, dent := range dents {
2826		name := dent.Name()
2827		if strings.HasSuffix(name, ".html") {
2828			toload = append(toload, viewDir+"/views/"+name)
2829		}
2830	}
2831
2832	readviews = templates.Load(develMode, toload...)
2833	if !develMode {
2834		assets := []string{
2835			viewDir + "/views/style.css",
2836			dataDir + "/views/local.css",
2837			viewDir + "/views/honkpage.js",
2838			viewDir + "/views/misc.js",
2839			dataDir + "/views/local.js",
2840		}
2841		for _, s := range assets {
2842			savedassetparams[s] = getassetparam(s)
2843		}
2844		loadAvatarColors()
2845	}
2846	startWatcher()
2847
2848	securitizeweb()
2849
2850	mux := mux.NewRouter()
2851	mux.Use(addcspheaders)
2852	mux.Use(login.Checker)
2853
2854	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2855
2856	posters := mux.Methods("POST").Subrouter()
2857	getters := mux.Methods("GET").Subrouter()
2858
2859	getters.HandleFunc("/", homepage)
2860	getters.HandleFunc("/home", homepage)
2861	getters.HandleFunc("/front", homepage)
2862	getters.HandleFunc("/events", homepage)
2863	getters.HandleFunc("/robots.txt", nomoroboto)
2864	getters.HandleFunc("/rss", showrss)
2865	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2866	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2867	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2868	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2869	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2870	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2871	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2872	getters.HandleFunc("/a", avatate)
2873	getters.HandleFunc("/o", thelistingoftheontologies)
2874	getters.HandleFunc("/o/{name:.+}", showontology)
2875	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2876	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2877	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2878	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2879
2880	getters.HandleFunc("/flag/{code:.+}", showflag)
2881
2882	getters.HandleFunc("/server", serveractor)
2883	posters.HandleFunc("/server/inbox", serverinbox)
2884	posters.HandleFunc("/inbox", serverinbox)
2885
2886	posters.HandleFunc("/csp-violation", fiveoh)
2887
2888	getters.HandleFunc("/style.css", serveviewasset)
2889	getters.HandleFunc("/honkpage.js", serveviewasset)
2890	getters.HandleFunc("/misc.js", serveviewasset)
2891	getters.HandleFunc("/local.css", servedataasset)
2892	getters.HandleFunc("/local.js", servedataasset)
2893	getters.HandleFunc("/icon.png", servedataasset)
2894	getters.HandleFunc("/favicon.ico", servedataasset)
2895
2896	getters.HandleFunc("/about", servehtml)
2897	getters.HandleFunc("/login", servehtml)
2898	posters.HandleFunc("/dologin", login.LoginFunc)
2899	getters.HandleFunc("/logout", login.LogoutFunc)
2900	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2901
2902	loggedin := mux.NewRoute().Subrouter()
2903	loggedin.Use(login.Required)
2904	loggedin.HandleFunc("/first", homepage)
2905	loggedin.HandleFunc("/chatter", showchatter)
2906	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2907	loggedin.HandleFunc("/saved", homepage)
2908	loggedin.HandleFunc("/account", accountpage)
2909	loggedin.HandleFunc("/funzone", showfunzone)
2910	loggedin.HandleFunc("/chpass", dochpass)
2911	loggedin.HandleFunc("/atme", homepage)
2912	loggedin.HandleFunc("/longago", homepage)
2913	loggedin.HandleFunc("/hfcs", hfcspage)
2914	loggedin.HandleFunc("/xzone", xzone)
2915	loggedin.HandleFunc("/newhonk", newhonkpage)
2916	loggedin.HandleFunc("/edit", edithonkpage)
2917	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2918	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2919	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2920	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2921	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2922	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2923	loggedin.HandleFunc("/honkers", showhonkers)
2924	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2925	loggedin.HandleFunc("/h", showhonker)
2926	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2927	loggedin.HandleFunc("/c", showcombos)
2928	loggedin.HandleFunc("/t", showconvoy)
2929	loggedin.HandleFunc("/q", showsearch)
2930	loggedin.HandleFunc("/hydra", webhydra)
2931	loggedin.HandleFunc("/emus", showemus)
2932	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2933
2934	if usefcgi {
2935		err = fcgi.Serve(listener, mux)
2936	} else {
2937		err = http.Serve(listener, mux)
2938	}
2939	if err != nil && !errors.Is(err, net.ErrClosed) {
2940		elog.Printf("serve error: %s", err)
2941	}
2942	time.Sleep(15 * time.Second)
2943	elog.Printf("fell off the bottom")
2944}