all repos — honk @ bd0905f4e16d392b10b9d269cba6f5d5bc9c99fc

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