all repos — honk @ b81e0b79ea9edc40a3c42b53e2daa91084ff54b1

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