all repos — honk @ 66c6ced8bf552408c833216614873a616b2720dc

my fork of honk

web.go (view raw)

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