all repos — honk @ c2d5d3d89852bc20761b110fdaf91c7b424c5307

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