all repos — honk @ 7b9615399efa8c1f3176748abdf8b8e7c8778738

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