all repos — honk @ 31c306a1332b6f1f4b259ce8651aa32677102176

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	dlog.Println("convoy: %s", c)
 789	templinfo["ServerMessage"] = "honks in convoy: " + c
 790	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 791	honkpage(w, u, honks, templinfo)
 792}
 793func showsearch(w http.ResponseWriter, r *http.Request) {
 794	q := r.FormValue("q")
 795	if strings.HasPrefix(q, "https://") {
 796		ximport(w, r)
 797		return
 798	}
 799	u := login.GetUserInfo(r)
 800	honks := gethonksbysearch(u.UserID, q, 0)
 801	templinfo := getInfo(r)
 802	templinfo["PageName"] = "search"
 803	templinfo["PageArg"] = q
 804	templinfo["ServerMessage"] = "honks for search: " + q
 805	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 806	honkpage(w, u, honks, templinfo)
 807}
 808func showontology(w http.ResponseWriter, r *http.Request) {
 809	name := mux.Vars(r)["name"]
 810	u := login.GetUserInfo(r)
 811	var userid int64 = -1
 812	if u != nil {
 813		userid = u.UserID
 814	}
 815	honks := gethonksbyontology(userid, "#"+name, 0)
 816	if friendorfoe(r.Header.Get("Accept")) {
 817		if len(honks) > 40 {
 818			honks = honks[0:40]
 819		}
 820
 821		var xids []string
 822		for _, h := range honks {
 823			xids = append(xids, h.XID)
 824		}
 825
 826		user := getserveruser()
 827
 828		j := junk.New()
 829		j["@context"] = itiswhatitis
 830		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 831		j["name"] = "#" + name
 832		j["attributedTo"] = user.URL
 833		j["type"] = "OrderedCollection"
 834		j["totalItems"] = len(xids)
 835		j["orderedItems"] = xids
 836
 837		j.Write(w)
 838		return
 839	}
 840
 841	templinfo := getInfo(r)
 842	templinfo["ServerMessage"] = "honks by ontology: " + name
 843	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 844	honkpage(w, u, honks, templinfo)
 845}
 846
 847type Ont struct {
 848	Name  string
 849	Count int64
 850}
 851
 852func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 853	u := login.GetUserInfo(r)
 854	var userid int64 = -1
 855	if u != nil {
 856		userid = u.UserID
 857	}
 858	rows, err := stmtAllOnts.Query(userid)
 859	if err != nil {
 860		elog.Printf("selection error: %s", err)
 861		return
 862	}
 863	defer rows.Close()
 864	var onts []Ont
 865	for rows.Next() {
 866		var o Ont
 867		err := rows.Scan(&o.Name, &o.Count)
 868		if err != nil {
 869			elog.Printf("error scanning ont: %s", err)
 870			continue
 871		}
 872		if utf8.RuneCountInString(o.Name) > 24 {
 873			continue
 874		}
 875		o.Name = o.Name[1:]
 876		onts = append(onts, o)
 877	}
 878	sort.Slice(onts, func(i, j int) bool {
 879		return onts[i].Name < onts[j].Name
 880	})
 881	if u == nil && !develMode {
 882		w.Header().Set("Cache-Control", "max-age=300")
 883	}
 884	templinfo := getInfo(r)
 885	templinfo["Onts"] = onts
 886	templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
 887	err = readviews.Execute(w, "onts.html", templinfo)
 888	if err != nil {
 889		elog.Print(err)
 890	}
 891}
 892
 893type Track struct {
 894	xid string
 895	who string
 896}
 897
 898func getbacktracks(xid string) []string {
 899	c := make(chan bool)
 900	dumptracks <- c
 901	<-c
 902	row := stmtGetTracks.QueryRow(xid)
 903	var rawtracks string
 904	err := row.Scan(&rawtracks)
 905	if err != nil {
 906		if err != sql.ErrNoRows {
 907			elog.Printf("error scanning tracks: %s", err)
 908		}
 909		return nil
 910	}
 911	var rcpts []string
 912	for _, f := range strings.Split(rawtracks, " ") {
 913		idx := strings.LastIndexByte(f, '#')
 914		if idx != -1 {
 915			f = f[:idx]
 916		}
 917		if !strings.HasPrefix(f, "https://") {
 918			f = fmt.Sprintf("%%https://%s/inbox", f)
 919		}
 920		rcpts = append(rcpts, f)
 921	}
 922	return rcpts
 923}
 924
 925func savetracks(tracks map[string][]string) {
 926	db := opendatabase()
 927	tx, err := db.Begin()
 928	if err != nil {
 929		elog.Printf("savetracks begin error: %s", err)
 930		return
 931	}
 932	defer func() {
 933		err := tx.Commit()
 934		if err != nil {
 935			elog.Printf("savetracks commit error: %s", err)
 936		}
 937
 938	}()
 939	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 940	if err != nil {
 941		elog.Printf("savetracks error: %s", err)
 942		return
 943	}
 944	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 945	if err != nil {
 946		elog.Printf("savetracks error: %s", err)
 947		return
 948	}
 949	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 950	if err != nil {
 951		elog.Printf("savetracks error: %s", err)
 952		return
 953	}
 954	count := 0
 955	for xid, f := range tracks {
 956		count += len(f)
 957		var prev string
 958		row := stmtGetTracks.QueryRow(xid)
 959		err := row.Scan(&prev)
 960		if err == sql.ErrNoRows {
 961			f = oneofakind(f)
 962			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 963		} else if err == nil {
 964			all := append(strings.Split(prev, " "), f...)
 965			all = oneofakind(all)
 966			stmtUpdateTracks.Exec(strings.Join(all, " "))
 967		} else {
 968			elog.Printf("savetracks error: %s", err)
 969		}
 970	}
 971	dlog.Printf("saved %d new fetches", count)
 972}
 973
 974var trackchan = make(chan Track)
 975var dumptracks = make(chan chan bool)
 976
 977func tracker() {
 978	timeout := 4 * time.Minute
 979	sleeper := time.NewTimer(timeout)
 980	tracks := make(map[string][]string)
 981	workinprogress++
 982	for {
 983		select {
 984		case track := <-trackchan:
 985			tracks[track.xid] = append(tracks[track.xid], track.who)
 986		case <-sleeper.C:
 987			if len(tracks) > 0 {
 988				go savetracks(tracks)
 989				tracks = make(map[string][]string)
 990			}
 991			sleeper.Reset(timeout)
 992		case c := <-dumptracks:
 993			if len(tracks) > 0 {
 994				savetracks(tracks)
 995			}
 996			c <- true
 997		case <-endoftheworld:
 998			if len(tracks) > 0 {
 999				savetracks(tracks)
1000			}
1001			readyalready <- true
1002			return
1003		}
1004	}
1005}
1006
1007var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1008
1009func trackback(xid string, r *http.Request) {
1010	agent := r.UserAgent()
1011	who := originate(agent)
1012	sig := r.Header.Get("Signature")
1013	if sig != "" {
1014		m := re_keyholder.FindStringSubmatch(sig)
1015		if len(m) == 2 {
1016			who = m[1]
1017		}
1018	}
1019	if who != "" {
1020		trackchan <- Track{xid: xid, who: who}
1021	}
1022}
1023
1024func threadsort(honks []*Honk) []*Honk {
1025	sort.Slice(honks, func(i, j int) bool {
1026		return honks[i].Date.Before(honks[j].Date)
1027	})
1028	honkx := make(map[string]*Honk)
1029	kids := make(map[string][]*Honk)
1030	for _, h := range honks {
1031		honkx[h.XID] = h
1032		rid := h.RID
1033		kids[rid] = append(kids[rid], h)
1034	}
1035	done := make(map[*Honk]bool)
1036	var thread []*Honk
1037	var nextlevel func(p *Honk)
1038	level := 0
1039	nextlevel = func(p *Honk) {
1040		levelup := level < 4
1041		if pp := honkx[p.RID]; p.RID == "" || (pp != nil && p.Honker == pp.Honker) {
1042			levelup = false
1043		}
1044		if level > 0 && len(kids[p.RID]) == 1 {
1045			if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1046				levelup = false
1047			}
1048		}
1049		if levelup {
1050			level++
1051		}
1052		p.Style += fmt.Sprintf(" level%d", level)
1053		childs := kids[p.XID]
1054		sort.SliceStable(childs, func(i, j int) bool {
1055			return childs[i].Honker == p.Honker && childs[j].Honker != p.Honker
1056		})
1057		for _, h := range childs {
1058			if !done[h] {
1059				done[h] = true
1060				thread = append(thread, h)
1061				nextlevel(h)
1062			}
1063		}
1064		if levelup {
1065			level--
1066		}
1067	}
1068	for _, h := range honks {
1069		if !done[h] && h.RID == "" {
1070			done[h] = true
1071			thread = append(thread, h)
1072			nextlevel(h)
1073		}
1074	}
1075	for _, h := range honks {
1076		if !done[h] {
1077			done[h] = true
1078			thread = append(thread, h)
1079			nextlevel(h)
1080		}
1081	}
1082	return thread
1083}
1084
1085func honkology(honk *Honk) template.HTML {
1086	var user *WhatAbout
1087	ok := somenumberedusers.Get(honk.UserID, &user)
1088	if !ok {
1089		return ""
1090	}
1091	title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1092	imgurl := avatarURL(user)
1093	for _, d := range honk.Donks {
1094		if d.Local && strings.HasPrefix(d.Media, "image") {
1095			imgurl = d.URL
1096			break
1097		}
1098	}
1099	short := honk.Noise
1100	if len(short) > 160 {
1101		short = short[0:160] + "..."
1102	}
1103	return templates.Sprintf(
1104		`<meta property="og:title" content="%s" />
1105<meta property="og:type" content="article" />
1106<meta property="article:author" content="%s" />
1107<meta property="og:url" content="%s" />
1108<meta property="og:image" content="%s" />
1109<meta property="og:description" content="%s" />`,
1110		title, user.URL, honk.XID, imgurl, short)
1111}
1112
1113func showonehonk(w http.ResponseWriter, r *http.Request) {
1114	name := mux.Vars(r)["name"]
1115	user, err := butwhatabout(name)
1116	if err != nil {
1117		http.NotFound(w, r)
1118		return
1119	}
1120	if stealthmode(user.ID, r) {
1121		http.NotFound(w, r)
1122		return
1123	}
1124	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1125
1126	if friendorfoe(r.Header.Get("Accept")) {
1127		j, ok := gimmejonk(xid)
1128		if ok {
1129			trackback(xid, r)
1130			w.Header().Set("Content-Type", theonetruename)
1131			w.Write(j)
1132		} else {
1133			http.NotFound(w, r)
1134		}
1135		return
1136	}
1137	honk := getxonk(user.ID, xid)
1138	if honk == nil {
1139		http.NotFound(w, r)
1140		return
1141	}
1142	u := login.GetUserInfo(r)
1143	if u != nil && u.UserID != user.ID {
1144		u = nil
1145	}
1146	if !honk.Public {
1147		if u == nil {
1148			http.NotFound(w, r)
1149			return
1150
1151		}
1152		honks := []*Honk{honk}
1153		donksforhonks(honks)
1154		templinfo := getInfo(r)
1155		templinfo["ServerMessage"] = "one honk maybe more"
1156		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1157		honkpage(w, u, honks, templinfo)
1158		return
1159	}
1160
1161	templinfo := getInfo(r)
1162	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1163	//reversehonks(rawhonks)
1164	rawhonks = threadsort(rawhonks)
1165	var honks []*Honk
1166	for _, h := range rawhonks {
1167		if h.XID == xid {
1168			templinfo["Honkology"] = honkology(h)
1169			if len(honks) != 0 {
1170				h.Style += " glow"
1171			}
1172		}
1173		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1174			honks = append(honks, h)
1175		}
1176	}
1177
1178	templinfo["ServerMessage"] = "one honk maybe more"
1179	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1180	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1181	honkpage(w, u, honks, templinfo)
1182}
1183
1184func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1185	var emunames []string
1186	dir, err := os.Open(dataDir + "/emus")
1187	if err == nil {
1188		emunames, _ = dir.Readdirnames(0)
1189		dir.Close()
1190	}
1191	for i, e := range emunames {
1192		if len(e) > 4 {
1193			emunames[i] = e[:len(e)-4]
1194		}
1195	}
1196	templinfo["Emus"] = emunames
1197	var userid int64 = -1
1198	if u != nil {
1199		userid = u.UserID
1200		templinfo["User"], _ = butwhatabout(u.Username)
1201	}
1202	reverbolate(userid, honks)
1203	templinfo["Honks"] = honks
1204	templinfo["MapLink"] = getmaplink(u)
1205	if templinfo["TopHID"] == nil {
1206		if len(honks) > 0 {
1207			templinfo["TopHID"] = honks[0].ID
1208		} else {
1209			templinfo["TopHID"] = 0
1210		}
1211	}
1212	if u == nil && !develMode {
1213		w.Header().Set("Cache-Control", "max-age=60")
1214	}
1215	err = readviews.Execute(w, "honkpage.html", templinfo)
1216	if err != nil {
1217		elog.Print(err)
1218	}
1219}
1220
1221func saveuser(w http.ResponseWriter, r *http.Request) {
1222	whatabout := r.FormValue("whatabout")
1223	whatabout = strings.Replace(whatabout, "\r", "", -1)
1224	u := login.GetUserInfo(r)
1225	user, _ := butwhatabout(u.Username)
1226	db := opendatabase()
1227
1228	options := user.Options
1229	if r.FormValue("skinny") == "skinny" {
1230		options.SkinnyCSS = true
1231	} else {
1232		options.SkinnyCSS = false
1233	}
1234	if r.FormValue("omitimages") == "omitimages" {
1235		options.OmitImages = true
1236	} else {
1237		options.OmitImages = false
1238	}
1239	if r.FormValue("mentionall") == "mentionall" {
1240		options.MentionAll = true
1241	} else {
1242		options.MentionAll = false
1243	}
1244	if r.FormValue("inlineqts") == "inlineqts" {
1245		options.InlineQuotes = true
1246	} else {
1247		options.InlineQuotes = false
1248	}
1249	if r.FormValue("maps") == "apple" {
1250		options.MapLink = "apple"
1251	} else {
1252		options.MapLink = ""
1253	}
1254
1255	sendupdate := false
1256	if r.FormValue("displayname") != "" {
1257		options.CustomDisplay = r.FormValue("displayname")
1258		_, err := db.Exec("update users set displayname = ? where username = ?", options.CustomDisplay, u.Username)
1259		if err != nil {
1260			elog.Printf("error setting displayname: %s", err)
1261		}
1262		sendupdate = true
1263	} else {
1264		options.CustomDisplay = ""
1265	}
1266
1267	options.Reaction = r.FormValue("reaction")
1268
1269	ava := re_avatar.FindString(whatabout)
1270	if ava != "" {
1271		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1272		ava = ava[7:]
1273		if ava[0] == ' ' {
1274			ava = ava[1:]
1275		}
1276		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1277	}
1278	if ava != options.Avatar {
1279		options.Avatar = ava
1280		sendupdate = true
1281	}
1282	ban := re_banner.FindString(whatabout)
1283	if ban != "" {
1284		whatabout = re_banner.ReplaceAllString(whatabout, "")
1285		ban = ban[7:]
1286		if ban[0] == ' ' {
1287			ban = ban[1:]
1288		}
1289		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1290	}
1291	if ban != options.Banner {
1292		options.Banner = ban
1293		sendupdate = true
1294	}
1295	whatabout = strings.TrimSpace(whatabout)
1296	if whatabout != user.About {
1297		sendupdate = true
1298	}
1299	j, err := jsonify(options)
1300	if err == nil {
1301		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1302	}
1303	if err != nil {
1304		elog.Printf("error bouting what: %s", err)
1305	}
1306	somenamedusers.Clear(u.Username)
1307	somenumberedusers.Clear(u.UserID)
1308	oldjonkers.Clear(u.Username)
1309
1310	if sendupdate {
1311		updateMe(u.Username)
1312	}
1313
1314	http.Redirect(w, r, "/account", http.StatusSeeOther)
1315}
1316
1317func bonkit(xid string, user *WhatAbout) {
1318	dlog.Printf("bonking %s", xid)
1319
1320	xonk := getxonk(user.ID, xid)
1321	if xonk == nil {
1322		return
1323	}
1324	if !xonk.Public {
1325		return
1326	}
1327	if xonk.IsBonked() {
1328		return
1329	}
1330	donksforhonks([]*Honk{xonk})
1331
1332	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1333	if err != nil {
1334		elog.Printf("error acking bonk: %s", err)
1335	}
1336
1337	oonker := xonk.Oonker
1338	if oonker == "" {
1339		oonker = xonk.Honker
1340	}
1341	dt := time.Now().UTC()
1342	bonk := &Honk{
1343		UserID:   user.ID,
1344		Username: user.Name,
1345		What:     "bonk",
1346		Honker:   user.URL,
1347		Oonker:   oonker,
1348		XID:      xonk.XID,
1349		RID:      xonk.RID,
1350		Noise:    xonk.Noise,
1351		Precis:   xonk.Precis,
1352		URL:      xonk.URL,
1353		Date:     dt,
1354		Donks:    xonk.Donks,
1355		Whofore:  2,
1356		Convoy:   xonk.Convoy,
1357		Audience: []string{thewholeworld, oonker},
1358		Public:   true,
1359		Format:   xonk.Format,
1360		Place:    xonk.Place,
1361		Onts:     xonk.Onts,
1362		Time:     xonk.Time,
1363	}
1364
1365	err = savehonk(bonk)
1366	if err != nil {
1367		elog.Printf("uh oh")
1368		return
1369	}
1370
1371	go honkworldwide(user, bonk)
1372}
1373
1374func submitbonk(w http.ResponseWriter, r *http.Request) {
1375	xid := r.FormValue("xid")
1376	userinfo := login.GetUserInfo(r)
1377	user, _ := butwhatabout(userinfo.Username)
1378
1379	bonkit(xid, user)
1380
1381	if r.FormValue("js") != "1" {
1382		templinfo := getInfo(r)
1383		templinfo["ServerMessage"] = "Bonked!"
1384		err := readviews.Execute(w, "msg.html", templinfo)
1385		if err != nil {
1386			elog.Print(err)
1387		}
1388	}
1389}
1390
1391func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1392	zonk := &Honk{
1393		What:     what,
1394		XID:      xonk.XID,
1395		Date:     time.Now().UTC(),
1396		Audience: oneofakind(xonk.Audience),
1397		Noise:    aux,
1398	}
1399	zonk.Public = loudandproud(zonk.Audience)
1400
1401	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1402	go honkworldwide(user, zonk)
1403}
1404
1405func zonkit(w http.ResponseWriter, r *http.Request) {
1406	wherefore := r.FormValue("wherefore")
1407	what := r.FormValue("what")
1408	userinfo := login.GetUserInfo(r)
1409	user, _ := butwhatabout(userinfo.Username)
1410
1411	if wherefore == "save" {
1412		xonk := getxonk(userinfo.UserID, what)
1413		if xonk != nil {
1414			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1415			if err != nil {
1416				elog.Printf("error saving: %s", err)
1417			}
1418		}
1419		return
1420	}
1421
1422	if wherefore == "unsave" {
1423		xonk := getxonk(userinfo.UserID, what)
1424		if xonk != nil {
1425			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1426			if err != nil {
1427				elog.Printf("error unsaving: %s", err)
1428			}
1429		}
1430		return
1431	}
1432
1433	if wherefore == "react" {
1434		reaction := user.Options.Reaction
1435		if r2 := r.FormValue("reaction"); r2 != "" {
1436			reaction = r2
1437		}
1438		if reaction == "none" {
1439			return
1440		}
1441		xonk := getxonk(userinfo.UserID, what)
1442		if xonk != nil {
1443			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1444			if err != nil {
1445				elog.Printf("error saving: %s", err)
1446			}
1447			sendzonkofsorts(xonk, user, "react", reaction)
1448		}
1449		return
1450	}
1451
1452	// my hammer is too big, oh well
1453	defer oldjonks.Flush()
1454
1455	if wherefore == "ack" {
1456		xonk := getxonk(userinfo.UserID, what)
1457		if xonk != nil && !xonk.IsAcked() {
1458			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1459			if err != nil {
1460				elog.Printf("error acking: %s", err)
1461			}
1462			sendzonkofsorts(xonk, user, "ack", "")
1463		}
1464		return
1465	}
1466
1467	if wherefore == "deack" {
1468		xonk := getxonk(userinfo.UserID, what)
1469		if xonk != nil && xonk.IsAcked() {
1470			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1471			if err != nil {
1472				elog.Printf("error deacking: %s", err)
1473			}
1474			sendzonkofsorts(xonk, user, "deack", "")
1475		}
1476		return
1477	}
1478
1479	if wherefore == "bonk" {
1480		user, _ := butwhatabout(userinfo.Username)
1481		bonkit(what, user)
1482		return
1483	}
1484
1485	if wherefore == "unbonk" {
1486		xonk := getbonk(userinfo.UserID, what)
1487		if xonk != nil {
1488			deletehonk(xonk.ID)
1489			xonk = getxonk(userinfo.UserID, what)
1490			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1491			if err != nil {
1492				elog.Printf("error unbonking: %s", err)
1493			}
1494			sendzonkofsorts(xonk, user, "unbonk", "")
1495		}
1496		return
1497	}
1498
1499	if wherefore == "untag" {
1500		xonk := getxonk(userinfo.UserID, what)
1501		if xonk != nil {
1502			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1503			if err != nil {
1504				elog.Printf("error untagging: %s", err)
1505			}
1506		}
1507		var badparents map[string]bool
1508		untagged.GetAndLock(userinfo.UserID, &badparents)
1509		badparents[what] = true
1510		untagged.Unlock()
1511		return
1512	}
1513
1514	ilog.Printf("zonking %s %s", wherefore, what)
1515	if wherefore == "zonk" {
1516		xonk := getxonk(userinfo.UserID, what)
1517		if xonk != nil {
1518			deletehonk(xonk.ID)
1519			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1520				sendzonkofsorts(xonk, user, "zonk", "")
1521			}
1522		}
1523	}
1524	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1525	if err != nil {
1526		elog.Printf("error saving zonker: %s", err)
1527		return
1528	}
1529}
1530
1531func edithonkpage(w http.ResponseWriter, r *http.Request) {
1532	u := login.GetUserInfo(r)
1533	user, _ := butwhatabout(u.Username)
1534	xid := r.FormValue("xid")
1535	honk := getxonk(u.UserID, xid)
1536	if !canedithonk(user, honk) {
1537		http.Error(w, "no editing that please", http.StatusInternalServerError)
1538		return
1539	}
1540
1541	noise := honk.Noise
1542
1543	honks := []*Honk{honk}
1544	donksforhonks(honks)
1545	reverbolate(u.UserID, honks)
1546	templinfo := getInfo(r)
1547	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1548	templinfo["Honks"] = honks
1549	templinfo["MapLink"] = getmaplink(u)
1550	templinfo["Noise"] = noise
1551	templinfo["SavedPlace"] = honk.Place
1552	if tm := honk.Time; tm != nil {
1553		templinfo["ShowTime"] = " "
1554		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1555		if tm.Duration != 0 {
1556			templinfo["Duration"] = tm.Duration
1557		}
1558	}
1559	templinfo["ServerMessage"] = "honk edit 2"
1560	templinfo["IsPreview"] = true
1561	templinfo["UpdateXID"] = honk.XID
1562	if len(honk.Donks) > 0 {
1563		templinfo["SavedFile"] = honk.Donks[0].XID
1564	}
1565	err := readviews.Execute(w, "honkpage.html", templinfo)
1566	if err != nil {
1567		elog.Print(err)
1568	}
1569}
1570
1571func newhonkpage(w http.ResponseWriter, r *http.Request) {
1572	u := login.GetUserInfo(r)
1573	rid := r.FormValue("rid")
1574	noise := ""
1575
1576	xonk := getxonk(u.UserID, rid)
1577	if xonk != nil {
1578		_, replto := handles(xonk.Honker)
1579		if replto != "" {
1580			noise = "@" + replto + " "
1581		}
1582	}
1583
1584	templinfo := getInfo(r)
1585	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1586	templinfo["InReplyTo"] = rid
1587	templinfo["Noise"] = noise
1588	templinfo["ServerMessage"] = "compose honk"
1589	templinfo["IsPreview"] = true
1590	err := readviews.Execute(w, "honkpage.html", templinfo)
1591	if err != nil {
1592		elog.Print(err)
1593	}
1594}
1595
1596func canedithonk(user *WhatAbout, honk *Honk) bool {
1597	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1598		return false
1599	}
1600	return true
1601}
1602
1603func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1604	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1605		return nil, nil
1606	}
1607	file, filehdr, err := r.FormFile("donk")
1608	if err != nil {
1609		if err == http.ErrMissingFile {
1610			return nil, nil
1611		}
1612		elog.Printf("error reading donk: %s", err)
1613		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1614		return nil, err
1615	}
1616	var buf bytes.Buffer
1617	io.Copy(&buf, file)
1618	file.Close()
1619	data := buf.Bytes()
1620	var media, name string
1621	img, err := shrinkit(data)
1622	if err == nil {
1623		data = img.Data
1624		format := img.Format
1625		media = "image/" + format
1626		if format == "jpeg" {
1627			format = "jpg"
1628		}
1629		if format == "svg+xml" {
1630			format = "svg"
1631		}
1632		name = xfiltrate() + "." + format
1633	} else {
1634		ct := http.DetectContentType(data)
1635		switch ct {
1636		case "application/pdf":
1637			maxsize := 10000000
1638			if len(data) > maxsize {
1639				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1640				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1641				return nil, err
1642			}
1643			media = ct
1644			name = filehdr.Filename
1645			if name == "" {
1646				name = xfiltrate() + ".pdf"
1647			}
1648		default:
1649			maxsize := 100000
1650			if len(data) > maxsize {
1651				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1652				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1653				return nil, err
1654			}
1655			for i := 0; i < len(data); i++ {
1656				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1657					ilog.Printf("bad image: %s not text: %d", err, data[i])
1658					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1659					return nil, err
1660				}
1661			}
1662			media = "text/plain"
1663			name = filehdr.Filename
1664			if name == "" {
1665				name = xfiltrate() + ".txt"
1666			}
1667		}
1668	}
1669	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1670	if desc == "" {
1671		desc = name
1672	}
1673	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1674	if err != nil {
1675		elog.Printf("unable to save image: %s", err)
1676		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1677		return nil, err
1678	}
1679	d := &Donk{
1680		FileID: fileid,
1681		XID:    xid,
1682		Desc:   desc,
1683		Local:  true,
1684	}
1685	return d, nil
1686}
1687
1688func websubmithonk(w http.ResponseWriter, r *http.Request) {
1689	h := submithonk(w, r)
1690	if h == nil {
1691		return
1692	}
1693	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1694}
1695
1696// what a hot mess this function is
1697func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1698	rid := r.FormValue("rid")
1699	noise := r.FormValue("noise")
1700	format := r.FormValue("format")
1701	if format == "" {
1702		format = "markdown"
1703	}
1704	if !(format == "markdown" || format == "html") {
1705		http.Error(w, "unknown format", 500)
1706		return nil
1707	}
1708
1709	userinfo := login.GetUserInfo(r)
1710	user, _ := butwhatabout(userinfo.Username)
1711
1712	dt := time.Now().UTC()
1713	updatexid := r.FormValue("updatexid")
1714	var honk *Honk
1715	if updatexid != "" {
1716		honk = getxonk(userinfo.UserID, updatexid)
1717		if !canedithonk(user, honk) {
1718			http.Error(w, "no editing that please", http.StatusInternalServerError)
1719			return nil
1720		}
1721		honk.Date = dt
1722		honk.What = "update"
1723		honk.Format = format
1724	} else {
1725		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1726		what := "honk"
1727		if rid != "" {
1728			what = "tonk"
1729		}
1730		honk = &Honk{
1731			UserID:   userinfo.UserID,
1732			Username: userinfo.Username,
1733			What:     what,
1734			Honker:   user.URL,
1735			XID:      xid,
1736			Date:     dt,
1737			Format:   format,
1738		}
1739	}
1740
1741	var convoy string
1742	noise = strings.Replace(noise, "\r", "", -1)
1743	if updatexid == "" && rid == "" {
1744		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1745			convoy = m[7:]
1746			convoy = strings.TrimSpace(convoy)
1747			if !re_convalidate.MatchString(convoy) {
1748				convoy = ""
1749			}
1750			return ""
1751		})
1752	}
1753	noise = quickrename(noise, userinfo.UserID)
1754	noise = hooterize(noise)
1755	honk.Noise = noise
1756	precipitate(honk)
1757	noise = honk.Noise
1758	translate(honk)
1759
1760	if rid != "" {
1761		xonk := getxonk(userinfo.UserID, rid)
1762		if xonk == nil {
1763			http.Error(w, "replyto disappeared", http.StatusNotFound)
1764			return nil
1765		}
1766		if xonk.Public {
1767			honk.Audience = append(honk.Audience, xonk.Audience...)
1768		}
1769		convoy = xonk.Convoy
1770		for i, a := range honk.Audience {
1771			if a == thewholeworld {
1772				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1773				break
1774			}
1775		}
1776		honk.RID = rid
1777		if xonk.Precis != "" && honk.Precis == "" {
1778			honk.Precis = xonk.Precis
1779			if !re_dangerous.MatchString(honk.Precis) {
1780				honk.Precis = "re: " + honk.Precis
1781			}
1782		}
1783	} else {
1784		honk.Audience = []string{thewholeworld}
1785	}
1786	if honk.Noise != "" && honk.Noise[0] == '@' {
1787		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1788	} else {
1789		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1790	}
1791
1792	if convoy == "" {
1793		convoy = fmt.Sprintf("data:,%s-", masqName) + xfiltrate()
1794	}
1795	butnottooloud(honk.Audience)
1796	honk.Audience = oneofakind(honk.Audience)
1797	if len(honk.Audience) == 0 {
1798		ilog.Printf("honk to nowhere")
1799		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1800		return nil
1801	}
1802	honk.Public = loudandproud(honk.Audience)
1803	honk.Convoy = convoy
1804
1805	donkxid := r.FormValue("donkxid")
1806	if donkxid == "" {
1807		d, err := submitdonk(w, r)
1808		if err != nil && err != http.ErrMissingFile {
1809			return nil
1810		}
1811		if d != nil {
1812			honk.Donks = append(honk.Donks, d)
1813			donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1814		}
1815	} else {
1816		p := strings.Split(donkxid, ":")
1817		xid := p[0]
1818		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1819		var donk *Donk
1820		if len(p) > 1 {
1821			fileid, _ := strconv.ParseInt(p[1], 10, 0)
1822			donk = finddonkid(fileid, url)
1823		} else {
1824			donk = finddonk(url)
1825		}
1826		if donk != nil {
1827			honk.Donks = append(honk.Donks, donk)
1828		} else {
1829			ilog.Printf("can't find file: %s", xid)
1830		}
1831	}
1832	memetize(honk)
1833	imaginate(honk)
1834
1835	placename := strings.TrimSpace(r.FormValue("placename"))
1836	placelat := strings.TrimSpace(r.FormValue("placelat"))
1837	placelong := strings.TrimSpace(r.FormValue("placelong"))
1838	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1839	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1840		p := new(Place)
1841		p.Name = placename
1842		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1843		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1844		p.Url = placeurl
1845		honk.Place = p
1846	}
1847	timestart := strings.TrimSpace(r.FormValue("timestart"))
1848	if timestart != "" {
1849		t := new(Time)
1850		now := time.Now().Local()
1851		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1852			start, err := time.ParseInLocation(layout, timestart, now.Location())
1853			if err == nil {
1854				if start.Year() == 0 {
1855					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1856				}
1857				t.StartTime = start
1858				break
1859			}
1860		}
1861		timeend := r.FormValue("timeend")
1862		dur := parseDuration(timeend)
1863		if dur != 0 {
1864			t.Duration = Duration(dur)
1865		}
1866		if !t.StartTime.IsZero() {
1867			honk.What = "event"
1868			honk.Time = t
1869		}
1870	}
1871
1872	if honk.Public {
1873		honk.Whofore = 2
1874	} else {
1875		honk.Whofore = 3
1876	}
1877
1878	// back to markdown
1879	honk.Noise = noise
1880
1881	if r.FormValue("preview") == "preview" {
1882		honks := []*Honk{honk}
1883		reverbolate(userinfo.UserID, honks)
1884		templinfo := getInfo(r)
1885		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1886		templinfo["Honks"] = honks
1887		templinfo["MapLink"] = getmaplink(userinfo)
1888		templinfo["InReplyTo"] = r.FormValue("rid")
1889		templinfo["Noise"] = r.FormValue("noise")
1890		templinfo["SavedFile"] = donkxid
1891		if tm := honk.Time; tm != nil {
1892			templinfo["ShowTime"] = " "
1893			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1894			if tm.Duration != 0 {
1895				templinfo["Duration"] = tm.Duration
1896			}
1897		}
1898		templinfo["IsPreview"] = true
1899		templinfo["UpdateXID"] = updatexid
1900		templinfo["ServerMessage"] = "honk preview"
1901		err := readviews.Execute(w, "honkpage.html", templinfo)
1902		if err != nil {
1903			elog.Print(err)
1904		}
1905		return nil
1906	}
1907
1908	if updatexid != "" {
1909		updatehonk(honk)
1910		oldjonks.Clear(honk.XID)
1911	} else {
1912		err := savehonk(honk)
1913		if err != nil {
1914			elog.Printf("uh oh")
1915			return nil
1916		}
1917	}
1918
1919	// reload for consistency
1920	honk.Donks = nil
1921	donksforhonks([]*Honk{honk})
1922
1923	go honkworldwide(user, honk)
1924
1925	return honk
1926}
1927
1928func showhonkers(w http.ResponseWriter, r *http.Request) {
1929	userinfo := login.GetUserInfo(r)
1930	templinfo := getInfo(r)
1931	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1932	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1933	err := readviews.Execute(w, "honkers.html", templinfo)
1934	if err != nil {
1935		elog.Print(err)
1936	}
1937}
1938
1939func showchatter(w http.ResponseWriter, r *http.Request) {
1940	u := login.GetUserInfo(r)
1941	chatnewnone(u.UserID)
1942	chatter := loadchatter(u.UserID)
1943	for _, chat := range chatter {
1944		for _, ch := range chat.Chonks {
1945			filterchonk(ch)
1946		}
1947	}
1948
1949	templinfo := getInfo(r)
1950	templinfo["Chatter"] = chatter
1951	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1952	err := readviews.Execute(w, "chatter.html", templinfo)
1953	if err != nil {
1954		elog.Print(err)
1955	}
1956}
1957
1958func submitchonk(w http.ResponseWriter, r *http.Request) {
1959	u := login.GetUserInfo(r)
1960	user, _ := butwhatabout(u.Username)
1961	noise := r.FormValue("noise")
1962	target := r.FormValue("target")
1963	format := "markdown"
1964	dt := time.Now().UTC()
1965	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1966
1967	if !strings.HasPrefix(target, "https://") {
1968		target = fullname(target, u.UserID)
1969	}
1970	if target == "" {
1971		http.Error(w, "who is that?", http.StatusInternalServerError)
1972		return
1973	}
1974	ch := Chonk{
1975		UserID: u.UserID,
1976		XID:    xid,
1977		Who:    user.URL,
1978		Target: target,
1979		Date:   dt,
1980		Noise:  noise,
1981		Format: format,
1982	}
1983	d, err := submitdonk(w, r)
1984	if err != nil && err != http.ErrMissingFile {
1985		return
1986	}
1987	if d != nil {
1988		ch.Donks = append(ch.Donks, d)
1989	}
1990
1991	translatechonk(&ch)
1992	savechonk(&ch)
1993	// reload for consistency
1994	ch.Donks = nil
1995	donksforchonks([]*Chonk{&ch})
1996	go sendchonk(user, &ch)
1997
1998	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1999}
2000
2001var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2002	honkers := gethonkers(userid)
2003	var combos []string
2004	for _, h := range honkers {
2005		combos = append(combos, h.Combos...)
2006	}
2007	for i, c := range combos {
2008		if c == "-" {
2009			combos[i] = ""
2010		}
2011	}
2012	combos = oneofakind(combos)
2013	sort.Strings(combos)
2014	return combos, true
2015}, Invalidator: &honkerinvalidator})
2016
2017func showcombos(w http.ResponseWriter, r *http.Request) {
2018	userinfo := login.GetUserInfo(r)
2019	var combos []string
2020	combocache.Get(userinfo.UserID, &combos)
2021	templinfo := getInfo(r)
2022	err := readviews.Execute(w, "combos.html", templinfo)
2023	if err != nil {
2024		elog.Print(err)
2025	}
2026}
2027
2028func websubmithonker(w http.ResponseWriter, r *http.Request) {
2029	h := submithonker(w, r)
2030	if h == nil {
2031		return
2032	}
2033	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2034}
2035
2036func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2037	u := login.GetUserInfo(r)
2038	user, _ := butwhatabout(u.Username)
2039	name := strings.TrimSpace(r.FormValue("name"))
2040	url := strings.TrimSpace(r.FormValue("url"))
2041	peep := r.FormValue("peep")
2042	combos := strings.TrimSpace(r.FormValue("combos"))
2043	combos = " " + combos + " "
2044	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2045
2046	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2047	if name != "" && !re_namecheck.MatchString(name) {
2048		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2049		return nil
2050	}
2051
2052	var meta HonkerMeta
2053	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2054	mj, _ := jsonify(&meta)
2055
2056	defer honkerinvalidator.Clear(u.UserID)
2057
2058	// mostly dummy, fill in later...
2059	h := &Honker{
2060		ID: honkerid,
2061	}
2062
2063	if honkerid > 0 {
2064		if r.FormValue("delete") == "delete" {
2065			unfollowyou(user, honkerid, false)
2066			stmtDeleteHonker.Exec(honkerid)
2067			return h
2068		}
2069		if r.FormValue("unsub") == "unsub" {
2070			unfollowyou(user, honkerid, false)
2071		}
2072		if r.FormValue("sub") == "sub" {
2073			followyou(user, honkerid, false)
2074		}
2075		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2076		if err != nil {
2077			elog.Printf("update honker err: %s", err)
2078			return nil
2079		}
2080		return h
2081	}
2082
2083	if url == "" {
2084		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2085		return nil
2086	}
2087
2088	flavor := "presub"
2089	if peep == "peep" {
2090		flavor = "peep"
2091	}
2092
2093	var err error
2094	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2095	if err != nil {
2096		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2097		return nil
2098	}
2099	if flavor == "presub" {
2100		followyou(user, honkerid, false)
2101	}
2102	h.ID = honkerid
2103	return h
2104}
2105
2106func hfcspage(w http.ResponseWriter, r *http.Request) {
2107	userinfo := login.GetUserInfo(r)
2108
2109	filters := getfilters(userinfo.UserID, filtAny)
2110
2111	templinfo := getInfo(r)
2112	templinfo["Filters"] = filters
2113	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2114	err := readviews.Execute(w, "hfcs.html", templinfo)
2115	if err != nil {
2116		elog.Print(err)
2117	}
2118}
2119
2120func savehfcs(w http.ResponseWriter, r *http.Request) {
2121	userinfo := login.GetUserInfo(r)
2122	itsok := r.FormValue("itsok")
2123	if itsok == "iforgiveyou" {
2124		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2125		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2126		if err != nil {
2127			elog.Printf("error deleting filter: %s", err)
2128		}
2129		filtInvalidator.Clear(userinfo.UserID)
2130		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2131		return
2132	}
2133
2134	filt := new(Filter)
2135	filt.Name = strings.TrimSpace(r.FormValue("name"))
2136	filt.Date = time.Now().UTC()
2137	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2138	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2139	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2140	filt.IsReply = r.FormValue("isreply") == "yes"
2141	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2142	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2143	filt.Reject = r.FormValue("doreject") == "yes"
2144	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2145	filt.Hide = r.FormValue("dohide") == "yes"
2146	filt.Collapse = r.FormValue("docollapse") == "yes"
2147	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2148	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2149	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2150		filt.Expiration = time.Now().UTC().Add(dur)
2151	}
2152	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2153
2154	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2155		ilog.Printf("blank filter")
2156		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2157		return
2158	}
2159
2160	j, err := jsonify(filt)
2161	if err == nil {
2162		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2163	}
2164	if err != nil {
2165		elog.Printf("error saving filter: %s", err)
2166	}
2167
2168	filtInvalidator.Clear(userinfo.UserID)
2169	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2170}
2171
2172func accountpage(w http.ResponseWriter, r *http.Request) {
2173	u := login.GetUserInfo(r)
2174	user, _ := butwhatabout(u.Username)
2175	templinfo := getInfo(r)
2176	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2177	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2178	templinfo["User"] = user
2179	about := user.About
2180	if ava := user.Options.Avatar; ava != "" {
2181		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2182	}
2183	if ban := user.Options.Banner; ban != "" {
2184		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2185	}
2186	templinfo["WhatAbout"] = about
2187	err := readviews.Execute(w, "account.html", templinfo)
2188	if err != nil {
2189		elog.Print(err)
2190	}
2191}
2192
2193func dochpass(w http.ResponseWriter, r *http.Request) {
2194	err := login.ChangePassword(w, r)
2195	if err != nil {
2196		elog.Printf("error changing password: %s", err)
2197	}
2198	http.Redirect(w, r, "/account", http.StatusSeeOther)
2199}
2200
2201var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2202	if strings.HasPrefix(orig, "acct:") {
2203		orig = orig[5:]
2204	}
2205	name := orig
2206	idx := strings.LastIndexByte(name, '/')
2207	if idx != -1 {
2208		name = name[idx+1:]
2209		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2210			ilog.Printf("foreign request rejected")
2211			name = ""
2212		}
2213	} else {
2214		idx = strings.IndexByte(name, '@')
2215		if idx != -1 {
2216			name = name[:idx]
2217			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2218				ilog.Printf("foreign request rejected")
2219				name = ""
2220			}
2221		}
2222	}
2223	user, err := butwhatabout(name)
2224	if err != nil {
2225		return nil, false
2226	}
2227
2228	j := junk.New()
2229	pretty := fmt.Sprintf("https://%s/@%s", serverName, name)
2230	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2231	j["aliases"] = []string{pretty, user.URL}
2232	l := junk.New()
2233	l["rel"] = "self"
2234	l["type"] = `application/activity+json`
2235	l["href"] = user.URL
2236	j["links"] = []junk.Junk{l}
2237	return j.ToBytes(), true
2238	l2 := junk.New()
2239	l2["rel"] = "http://webfinger.net/rel/profile-page"
2240	l2["type"] = "text/html"
2241	l2["href"] = pretty
2242	j["links"] = []junk.Junk{l, l2}
2243}})
2244
2245func fingerlicker(w http.ResponseWriter, r *http.Request) {
2246	orig := r.FormValue("resource")
2247
2248	dlog.Printf("finger lick: %s", orig)
2249
2250	var j []byte
2251	ok := oldfingers.Get(orig, &j)
2252	if ok {
2253		w.Header().Set("Content-Type", "application/jrd+json")
2254		w.Write(j)
2255	} else {
2256		http.NotFound(w, r)
2257	}
2258}
2259
2260func somedays() string {
2261	secs := 432000 + notrand.Int63n(432000)
2262	return fmt.Sprintf("%d", secs)
2263}
2264
2265func lookatme(ava string) string {
2266	if strings.Contains(ava, serverName+"/"+userSep) {
2267		idx := strings.LastIndexByte(ava, '/')
2268		if idx < len(ava) {
2269			name := ava[idx+1:]
2270			user, _ := butwhatabout(name)
2271			if user != nil && user.URL == ava {
2272				return user.Options.Avatar
2273			}
2274		}
2275	}
2276	return ""
2277}
2278
2279func avatate(w http.ResponseWriter, r *http.Request) {
2280	if develMode {
2281		loadAvatarColors()
2282	}
2283	var a []byte
2284	n := r.FormValue("a")
2285	if redir := lookatme(n); redir != "" {
2286		http.Redirect(w, r, redir, http.StatusSeeOther)
2287		return
2288	}
2289	a := genAvatar(n)
2290	if !develMode {
2291		w.Header().Set("Cache-Control", "max-age="+somedays())
2292	}
2293
2294	w.Write(a)
2295}
2296
2297func serveviewasset(w http.ResponseWriter, r *http.Request) {
2298	serveasset(w, r, viewDir)
2299}
2300func servedataasset(w http.ResponseWriter, r *http.Request) {
2301	if r.URL.Path == "/favicon.ico" {
2302		r.URL.Path = "/icon.png"
2303	}
2304	serveasset(w, r, dataDir)
2305}
2306
2307func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2308	if !develMode {
2309		w.Header().Set("Cache-Control", "max-age=7776000")
2310	}
2311	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2312}
2313func servehelp(w http.ResponseWriter, r *http.Request) {
2314	name := mux.Vars(r)["name"]
2315	if !develMode {
2316		w.Header().Set("Cache-Control", "max-age=3600")
2317	}
2318	http.ServeFile(w, r, viewDir+"/docs/"+name)
2319}
2320func servehtml(w http.ResponseWriter, r *http.Request) {
2321	u := login.GetUserInfo(r)
2322	templinfo := getInfo(r)
2323	templinfo["AboutMsg"] = aboutMsg
2324	templinfo["LoginMsg"] = loginMsg
2325	templinfo["HonkVersion"] = softwareVersion
2326	if r.URL.Path == "/about" {
2327		templinfo["Sensors"] = getSensors()
2328	}
2329	if u == nil && !develMode {
2330		w.Header().Set("Cache-Control", "max-age=60")
2331	}
2332	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2333	if err != nil {
2334		elog.Print(err)
2335	}
2336}
2337func serveemu(w http.ResponseWriter, r *http.Request) {
2338	emu := mux.Vars(r)["emu"]
2339
2340	w.Header().Set("Cache-Control", "max-age="+somedays())
2341	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2342}
2343func servememe(w http.ResponseWriter, r *http.Request) {
2344	meme := mux.Vars(r)["meme"]
2345
2346	w.Header().Set("Cache-Control", "max-age="+somedays())
2347	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2348}
2349
2350func servefile(w http.ResponseWriter, r *http.Request) {
2351	xid := mux.Vars(r)["xid"]
2352	var media string
2353	var data []byte
2354	row := stmtGetFileData.QueryRow(xid)
2355	err := row.Scan(&media, &data)
2356	if err != nil {
2357		elog.Printf("error loading file: %s", err)
2358		http.NotFound(w, r)
2359		return
2360	}
2361	w.Header().Set("Content-Type", media)
2362	w.Header().Set("X-Content-Type-Options", "nosniff")
2363	w.Header().Set("Cache-Control", "max-age="+somedays())
2364	w.Write(data)
2365}
2366
2367func nomoroboto(w http.ResponseWriter, r *http.Request) {
2368	io.WriteString(w, "User-agent: *\n")
2369	io.WriteString(w, "Disallow: /a\n")
2370	io.WriteString(w, "Disallow: /d/\n")
2371	io.WriteString(w, "Disallow: /meme/\n")
2372	io.WriteString(w, "Disallow: /o\n")
2373	io.WriteString(w, "Disallow: /o/\n")
2374	io.WriteString(w, "Disallow: /help/\n")
2375	for _, u := range allusers() {
2376		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2377	}
2378}
2379
2380type Hydration struct {
2381	Tophid    int64
2382	Srvmsg    template.HTML
2383	Honks     string
2384	MeCount   int64
2385	ChatCount int64
2386}
2387
2388func webhydra(w http.ResponseWriter, r *http.Request) {
2389	u := login.GetUserInfo(r)
2390	userid := u.UserID
2391	templinfo := getInfo(r)
2392	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2393	page := r.FormValue("page")
2394
2395	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2396
2397	var hydra Hydration
2398
2399	var honks []*Honk
2400	switch page {
2401	case "atme":
2402		honks = gethonksforme(userid, wanted)
2403		honks = osmosis(honks, userid, false)
2404		menewnone(userid)
2405		hydra.Srvmsg = "at me!"
2406	case "longago":
2407		honks = gethonksfromlongago(userid, wanted)
2408		honks = osmosis(honks, userid, false)
2409		hydra.Srvmsg = "from long ago"
2410	case "home":
2411		honks = gethonksforuser(userid, wanted)
2412		honks = osmosis(honks, userid, true)
2413		hydra.Srvmsg = serverMsg
2414	case "first":
2415		honks = gethonksforuserfirstclass(userid, wanted)
2416		honks = osmosis(honks, userid, true)
2417		hydra.Srvmsg = "first class only"
2418	case "saved":
2419		honks = getsavedhonks(userid, wanted)
2420		templinfo["PageName"] = "saved"
2421		hydra.Srvmsg = "saved honks"
2422	case "combo":
2423		c := r.FormValue("c")
2424		honks = gethonksbycombo(userid, c, wanted)
2425		honks = osmosis(honks, userid, false)
2426		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2427	case "convoy":
2428		c := r.FormValue("c")
2429		honks = gethonksbyconvoy(userid, c, wanted)
2430		honks = osmosis(honks, userid, false)
2431		honks = threadsort(honks)
2432		reversehonks(honks)
2433		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2434	case "honker":
2435		xid := r.FormValue("xid")
2436		honks = gethonksbyxonker(userid, xid, wanted)
2437		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2438			<input type="hidden" name="CSRF" value="%s">
2439			<input type="hidden" name="url" value="%s">
2440			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2441			</form>`, login.GetCSRF("submithonker", r), xid)
2442		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2443		hydra.Srvmsg = msg
2444	case "user":
2445		uname := r.FormValue("uname")
2446		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2447		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2448	default:
2449		http.NotFound(w, r)
2450	}
2451
2452	if len(honks) > 0 {
2453		hydra.Tophid = honks[0].ID
2454	} else {
2455		hydra.Tophid = wanted
2456	}
2457	reverbolate(userid, honks)
2458
2459	user, _ := butwhatabout(u.Username)
2460
2461	var buf strings.Builder
2462	templinfo["Honks"] = honks
2463	templinfo["MapLink"] = getmaplink(u)
2464	templinfo["User"], _ = butwhatabout(u.Username)
2465	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2466	if err != nil {
2467		elog.Printf("frag error: %s", err)
2468		return
2469	}
2470	hydra.Honks = buf.String()
2471	hydra.MeCount = user.Options.MeCount
2472	hydra.ChatCount = user.Options.ChatCount
2473	w.Header().Set("Content-Type", "application/json")
2474	j, _ := jsonify(&hydra)
2475	io.WriteString(w, j)
2476}
2477
2478var honkline = make(chan bool)
2479
2480func honkhonkline() {
2481	for {
2482		select {
2483		case honkline <- true:
2484		default:
2485			return
2486		}
2487	}
2488}
2489
2490func apihandler(w http.ResponseWriter, r *http.Request) {
2491	u := login.GetUserInfo(r)
2492	userid := u.UserID
2493	action := r.FormValue("action")
2494	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2495	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2496	switch action {
2497	case "honk":
2498		h := submithonk(w, r)
2499		if h == nil {
2500			return
2501		}
2502
2503		fmt.Fprintf(w, "%s", h.XID)
2504	case "donk":
2505		d, err := submitdonk(w, r)
2506		if err != nil {
2507			http.Error(w, err.Error(), http.StatusBadRequest)
2508			return
2509		}
2510		if d == nil {
2511			http.Error(w, "missing donk", http.StatusBadRequest)
2512			return
2513		}
2514		w.Write([]byte(d.XID))
2515	case "zonkit":
2516		zonkit(w, r)
2517	case "gethonks":
2518		var honks []*Honk
2519		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2520		page := r.FormValue("page")
2521		var waitchan <-chan time.Time
2522	requery:
2523		switch page {
2524		case "atme":
2525			honks = gethonksforme(userid, wanted)
2526			honks = osmosis(honks, userid, false)
2527			menewnone(userid)
2528		case "longago":
2529			honks = gethonksfromlongago(userid, wanted)
2530			honks = osmosis(honks, userid, false)
2531		case "home":
2532			honks = gethonksforuser(userid, wanted)
2533			honks = osmosis(honks, userid, true)
2534		case "myhonks":
2535			honks = gethonksbyuser(u.Username, true, wanted)
2536			honks = osmosis(honks, userid, true)
2537		default:
2538			http.Error(w, "unknown page", http.StatusNotFound)
2539			return
2540		}
2541		if len(honks) == 0 && wait > 0 {
2542			if waitchan == nil {
2543				waitchan = time.After(time.Duration(wait) * time.Second)
2544			}
2545			select {
2546			case <-honkline:
2547				goto requery
2548			case <-waitchan:
2549			}
2550		}
2551		reverbolate(userid, honks)
2552		j := junk.New()
2553		j["honks"] = honks
2554		j.Write(w)
2555	case "sendactivity":
2556		user, _ := butwhatabout(u.Username)
2557		public := r.FormValue("public") == "1"
2558		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2559		msg := []byte(r.FormValue("msg"))
2560		for rcpt := range rcpts {
2561			go deliverate(userid, rcpt, msg)
2562		}
2563	case "gethonkers":
2564		j := junk.New()
2565		j["honkers"] = gethonkers(u.UserID)
2566		j.Write(w)
2567	case "savehonker":
2568		h := submithonker(w, r)
2569		if h == nil {
2570			return
2571		}
2572		fmt.Fprintf(w, "%d", h.ID)
2573	default:
2574		http.Error(w, "unknown action", http.StatusNotFound)
2575		return
2576	}
2577}
2578
2579func fiveoh(w http.ResponseWriter, r *http.Request) {
2580	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2581	if err != nil {
2582		elog.Printf("error opening violations! %s", err)
2583		return
2584	}
2585	defer fd.Close()
2586	io.Copy(fd, r.Body)
2587}
2588
2589var endoftheworld = make(chan bool)
2590var readyalready = make(chan bool)
2591var workinprogress = 0
2592
2593func enditall() {
2594	sig := make(chan os.Signal)
2595	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2596	<-sig
2597	ilog.Printf("stopping...")
2598	for i := 0; i < workinprogress; i++ {
2599		endoftheworld <- true
2600	}
2601	ilog.Printf("waiting...")
2602	for i := 0; i < workinprogress; i++ {
2603		<-readyalready
2604	}
2605	ilog.Printf("apocalypse")
2606	os.Exit(0)
2607}
2608
2609var preservehooks []func()
2610
2611func bgmonitor() {
2612	for {
2613		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2614		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2615		if err != nil {
2616			elog.Printf("error deleting old xonkers: %s", err)
2617		}
2618		zaggies.Flush()
2619		time.Sleep(50 * time.Minute)
2620	}
2621}
2622
2623func addcspheaders(next http.Handler) http.Handler {
2624	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2625		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")
2626		next.ServeHTTP(w, r)
2627	})
2628}
2629
2630func emuinit() {
2631	var emunames []string
2632	dir, err := os.Open(dataDir + "/emus")
2633	if err == nil {
2634		emunames, _ = dir.Readdirnames(0)
2635		dir.Close()
2636	}
2637	for _, e := range emunames {
2638		if len(e) <= 4 {
2639			continue
2640		}
2641		ext := e[len(e)-4:]
2642		emu := Emu{
2643			ID:   fmt.Sprintf("/emu/%s", e),
2644			Name: e[:len(e)-4],
2645			Type: "image/" + ext[1:],
2646		}
2647		allemus = append(allemus, emu)
2648	}
2649	sort.Slice(allemus, func(i, j int) bool {
2650		return allemus[i].Name < allemus[j].Name
2651	})
2652}
2653
2654func redirectPretty(w http.ResponseWriter, r *http.Request) {
2655	last := path.Base(r.URL.Path)
2656	name := mux.Vars(r)["name"]
2657	aturl := "/@" + name
2658
2659	if last == name {
2660		last = ""
2661	}
2662	http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2663}
2664
2665func serve() {
2666	db := opendatabase()
2667	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2668
2669	listener, err := openListener()
2670	if err != nil {
2671		elog.Fatal(err)
2672	}
2673	runBackendServer()
2674	go enditall()
2675	go redeliverator()
2676	go tracker()
2677	go bgmonitor()
2678	loadLingo()
2679	emuinit()
2680
2681	readviews = templates.Load(develMode,
2682		viewDir+"/views/honkpage.html",
2683		viewDir+"/views/honkfrags.html",
2684		viewDir+"/views/honkers.html",
2685		viewDir+"/views/chatter.html",
2686		viewDir+"/views/hfcs.html",
2687		viewDir+"/views/combos.html",
2688		viewDir+"/views/honkform.html",
2689		viewDir+"/views/honk.html",
2690		viewDir+"/views/account.html",
2691		viewDir+"/views/about.html",
2692		viewDir+"/views/funzone.html",
2693		viewDir+"/views/login.html",
2694		viewDir+"/views/xzone.html",
2695		viewDir+"/views/msg.html",
2696		viewDir+"/views/header.html",
2697		viewDir+"/views/onts.html",
2698		viewDir+"/views/emus.html",
2699		viewDir+"/views/honkpage.js",
2700	)
2701	if !develMode {
2702		assets := []string{
2703			viewDir + "/views/style.css",
2704			dataDir + "/views/local.css",
2705			viewDir + "/views/honkpage.js",
2706			dataDir + "/views/local.js",
2707		}
2708		for _, s := range assets {
2709			savedassetparams[s] = getassetparam(s)
2710		}
2711		loadAvatarColors()
2712	}
2713
2714	for _, h := range preservehooks {
2715		h()
2716	}
2717
2718	mux := mux.NewRouter()
2719	mux.Use(addcspheaders)
2720	mux.Use(login.Checker)
2721
2722	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2723
2724	posters := mux.Methods("POST").Subrouter()
2725	getters := mux.Methods("GET").Subrouter()
2726
2727	getters.HandleFunc("/", homepage)
2728	getters.HandleFunc("/home", homepage)
2729	getters.HandleFunc("/front", homepage)
2730	getters.HandleFunc("/events", homepage)
2731	getters.HandleFunc("/robots.txt", nomoroboto)
2732	getters.HandleFunc("/rss", showrss)
2733	getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
2734	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
2735	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2736	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2737	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2738	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2739	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2740	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2741	getters.HandleFunc("/a", avatate)
2742	getters.HandleFunc("/o", thelistingoftheontologies)
2743	getters.HandleFunc("/o/{name:.+}", showontology)
2744	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2745	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2746	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2747	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2748
2749	getters.HandleFunc("/flag/{code:.+}", showflag)
2750
2751	getters.HandleFunc("/server", serveractor)
2752	posters.HandleFunc("/server/inbox", serverinbox)
2753	posters.HandleFunc("/inbox", serverinbox)
2754
2755	posters.HandleFunc("/csp-violation", fiveoh)
2756
2757	getters.HandleFunc("/style.css", serveviewasset)
2758	getters.HandleFunc("/honkpage.js", serveviewasset)
2759	getters.HandleFunc("/misc.js", serveviewasset)
2760	getters.HandleFunc("/local.css", servedataasset)
2761	getters.HandleFunc("/local.js", servedataasset)
2762	getters.HandleFunc("/icon.png", servedataasset)
2763	getters.HandleFunc("/favicon.ico", servedataasset)
2764
2765	getters.HandleFunc("/about", servehtml)
2766	getters.HandleFunc("/login", servehtml)
2767	posters.HandleFunc("/dologin", login.LoginFunc)
2768	getters.HandleFunc("/logout", login.LogoutFunc)
2769	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2770
2771	loggedin := mux.NewRoute().Subrouter()
2772	loggedin.Use(login.Required)
2773	loggedin.HandleFunc("/first", homepage)
2774	loggedin.HandleFunc("/chatter", showchatter)
2775	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2776	loggedin.HandleFunc("/saved", homepage)
2777	loggedin.HandleFunc("/account", accountpage)
2778	loggedin.HandleFunc("/funzone", showfunzone)
2779	loggedin.HandleFunc("/chpass", dochpass)
2780	loggedin.HandleFunc("/atme", homepage)
2781	loggedin.HandleFunc("/longago", homepage)
2782	loggedin.HandleFunc("/hfcs", hfcspage)
2783	loggedin.HandleFunc("/xzone", xzone)
2784	loggedin.HandleFunc("/newhonk", newhonkpage)
2785	loggedin.HandleFunc("/edit", edithonkpage)
2786	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2787	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2788	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2789	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2790	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2791	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2792	loggedin.HandleFunc("/honkers", showhonkers)
2793	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2794	loggedin.HandleFunc("/h", showhonker)
2795	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2796	loggedin.HandleFunc("/c", showcombos)
2797	loggedin.HandleFunc("/t", showconvoy)
2798	loggedin.HandleFunc("/q", showsearch)
2799	loggedin.HandleFunc("/hydra", webhydra)
2800	loggedin.HandleFunc("/emus", showemus)
2801	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2802
2803	err = http.Serve(listener, mux)
2804	if err != nil {
2805		elog.Fatal(err)
2806	}
2807}