all repos — honk @ 6a82b88ca1106994824642a7731299954297ccaf

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