all repos — honk @ 08df567edc039a043d062d47e9a9893d7762cdb7

my fork of honk

web.go (view raw)

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