all repos — honk @ v1.0.0

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