all repos — honk @ 018b6c68c9e2b8659008b80fed7c9b984c0f9a38

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