all repos — honk @ 91b52462a0e5d52e39efa5d987aee8f28a33ad60

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