all repos — honk @ 9943d358f37564e962837374e0a70f28667ca1b5

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