all repos — honk @ 70f4ec402d58561098e475b788c7f3c7e648cc30

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