all repos — honk @ 57f1c9fc1fd1d432c07d71d7f72138e87f6c5841

my fork of honk

web.go (view raw)

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