all repos — honk @ d2fee4b857e8262b0cbb535411917f741d543227

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.StatusTeapot)
 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.StatusTeapot)
 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 savehfcs(w http.ResponseWriter, r *http.Request) {
2238	userinfo := login.GetUserInfo(r)
2239	itsok := r.FormValue("itsok")
2240	if itsok == "iforgiveyou" {
2241		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2242		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2243		if err != nil {
2244			elog.Printf("error deleting filter: %s", err)
2245		}
2246		filtInvalidator.Clear(userinfo.UserID)
2247		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2248		return
2249	}
2250
2251	filt := new(Filter)
2252	filt.Name = strings.TrimSpace(r.FormValue("name"))
2253	filt.Date = time.Now().UTC()
2254	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2255	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2256	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2257	filt.IsReply = r.FormValue("isreply") == "yes"
2258	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2259	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2260	filt.Reject = r.FormValue("doreject") == "yes"
2261	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2262	filt.Hide = r.FormValue("dohide") == "yes"
2263	filt.Collapse = r.FormValue("docollapse") == "yes"
2264	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2265	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2266	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2267		filt.Expiration = time.Now().UTC().Add(dur)
2268	}
2269	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2270
2271	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2272		ilog.Printf("blank filter")
2273		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2274		return
2275	}
2276
2277	j, err := jsonify(filt)
2278	if err == nil {
2279		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2280	}
2281	if err != nil {
2282		elog.Printf("error saving filter: %s", err)
2283	}
2284
2285	filtInvalidator.Clear(userinfo.UserID)
2286	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2287}
2288
2289func accountpage(w http.ResponseWriter, r *http.Request) {
2290	u := login.GetUserInfo(r)
2291	user, _ := butwhatabout(u.Username)
2292	templinfo := getInfo(r)
2293	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2294	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2295	templinfo["User"] = user
2296	about := user.About
2297	if ava := user.Options.Avatar; ava != "" {
2298		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2299	}
2300	if ban := user.Options.Banner; ban != "" {
2301		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2302	}
2303	templinfo["WhatAbout"] = about
2304	err := readviews.Execute(w, "account.html", templinfo)
2305	if err != nil {
2306		elog.Print(err)
2307	}
2308}
2309
2310func dochpass(w http.ResponseWriter, r *http.Request) {
2311	err := login.ChangePassword(w, r)
2312	if err != nil {
2313		elog.Printf("error changing password: %s", err)
2314	}
2315	http.Redirect(w, r, "/account", http.StatusSeeOther)
2316}
2317
2318var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2319	if strings.HasPrefix(orig, "acct:") {
2320		orig = orig[5:]
2321	}
2322	name := orig
2323	idx := strings.LastIndexByte(name, '/')
2324	if idx != -1 {
2325		name = name[idx+1:]
2326		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2327			ilog.Printf("foreign request rejected")
2328			name = ""
2329		}
2330	} else {
2331		idx = strings.IndexByte(name, '@')
2332		if idx != -1 {
2333			name = name[:idx]
2334			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2335				ilog.Printf("foreign request rejected")
2336				name = ""
2337			}
2338		}
2339	}
2340	user, err := butwhatabout(name)
2341	if err != nil {
2342		return nil, false
2343	}
2344
2345	j := junk.New()
2346	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2347	j["aliases"] = []string{user.URL}
2348	l := junk.New()
2349	l["rel"] = "self"
2350	l["type"] = `application/activity+json`
2351	l["href"] = user.URL
2352	j["links"] = []junk.Junk{l}
2353	return j.ToBytes(), true
2354}})
2355
2356func fingerlicker(w http.ResponseWriter, r *http.Request) {
2357	orig := r.FormValue("resource")
2358
2359	dlog.Printf("finger lick: %s", orig)
2360
2361	var j []byte
2362	ok := oldfingers.Get(orig, &j)
2363	if ok {
2364		w.Header().Set("Content-Type", "application/jrd+json")
2365		w.Write(j)
2366	} else {
2367		http.NotFound(w, r)
2368	}
2369}
2370
2371func somedays() string {
2372	secs := 432000 + notrand.Int63n(432000)
2373	return fmt.Sprintf("%d", secs)
2374}
2375
2376func lookatme(ava string) string {
2377	if strings.Contains(ava, serverName+"/"+userSep) {
2378		idx := strings.LastIndexByte(ava, '/')
2379		if idx < len(ava) {
2380			name := ava[idx+1:]
2381			user, _ := butwhatabout(name)
2382			if user != nil && user.URL == ava {
2383				return user.Options.Avatar
2384			}
2385		}
2386	}
2387	return ""
2388}
2389
2390func avatate(w http.ResponseWriter, r *http.Request) {
2391	if develMode {
2392		loadAvatarColors()
2393	}
2394	n := r.FormValue("a")
2395	if redir := lookatme(n); redir != "" {
2396		http.Redirect(w, r, redir, http.StatusSeeOther)
2397		return
2398	}
2399	a := genAvatar(n)
2400	if !develMode {
2401		w.Header().Set("Cache-Control", "max-age="+somedays())
2402	}
2403	w.Write(a)
2404}
2405
2406func serveviewasset(w http.ResponseWriter, r *http.Request) {
2407	serveasset(w, r, viewDir)
2408}
2409func servedataasset(w http.ResponseWriter, r *http.Request) {
2410	if r.URL.Path == "/favicon.ico" {
2411		r.URL.Path = "/icon.png"
2412	}
2413	serveasset(w, r, dataDir)
2414}
2415
2416func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2417	if !develMode {
2418		w.Header().Set("Cache-Control", "max-age=7776000")
2419	}
2420	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2421}
2422func servehelp(w http.ResponseWriter, r *http.Request) {
2423	name := mux.Vars(r)["name"]
2424	if !develMode {
2425		w.Header().Set("Cache-Control", "max-age=3600")
2426	}
2427	http.ServeFile(w, r, viewDir+"/docs/"+name)
2428}
2429func servehtml(w http.ResponseWriter, r *http.Request) {
2430	u := login.GetUserInfo(r)
2431	templinfo := getInfo(r)
2432	templinfo["AboutMsg"] = aboutMsg
2433	templinfo["LoginMsg"] = loginMsg
2434	templinfo["HonkVersion"] = softwareVersion
2435	if r.URL.Path == "/about" {
2436		templinfo["Sensors"] = getSensors()
2437	}
2438	if u == nil && !develMode {
2439		w.Header().Set("Cache-Control", "max-age=60")
2440	}
2441	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2442	if err != nil {
2443		elog.Print(err)
2444	}
2445}
2446func serveemu(w http.ResponseWriter, r *http.Request) {
2447	emu := mux.Vars(r)["emu"]
2448
2449	w.Header().Set("Cache-Control", "max-age="+somedays())
2450	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2451}
2452func servememe(w http.ResponseWriter, r *http.Request) {
2453	meme := mux.Vars(r)["meme"]
2454
2455	w.Header().Set("Cache-Control", "max-age="+somedays())
2456	_, err := os.Stat(dataDir + "/memes/" + meme)
2457	if err == nil {
2458		http.ServeFile(w, r, dataDir+"/memes/"+meme)
2459	} else {
2460		mux.Vars(r)["xid"] = meme
2461		servefile(w, r)
2462	}
2463}
2464
2465func servefile(w http.ResponseWriter, r *http.Request) {
2466	xid := mux.Vars(r)["xid"]
2467	var media string
2468	var data []byte
2469	row := stmtGetFileData.QueryRow(xid)
2470	err := row.Scan(&media, &data)
2471	if err != nil {
2472		elog.Printf("error loading file: %s", err)
2473		http.NotFound(w, r)
2474		return
2475	}
2476	w.Header().Set("Content-Type", media)
2477	w.Header().Set("X-Content-Type-Options", "nosniff")
2478	w.Header().Set("Cache-Control", "max-age="+somedays())
2479	w.Write(data)
2480}
2481
2482func nomoroboto(w http.ResponseWriter, r *http.Request) {
2483	io.WriteString(w, "User-agent: *\n")
2484	io.WriteString(w, "Disallow: /a\n")
2485	io.WriteString(w, "Disallow: /d/\n")
2486	io.WriteString(w, "Disallow: /meme/\n")
2487	io.WriteString(w, "Disallow: /o\n")
2488	io.WriteString(w, "Disallow: /o/\n")
2489	io.WriteString(w, "Disallow: /help/\n")
2490	for _, u := range allusers() {
2491		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2492	}
2493}
2494
2495type Hydration struct {
2496	Tophid    int64
2497	Srvmsg    template.HTML
2498	Honks     string
2499	MeCount   int64
2500	ChatCount int64
2501}
2502
2503func webhydra(w http.ResponseWriter, r *http.Request) {
2504	u := login.GetUserInfo(r)
2505	userid := u.UserID
2506	templinfo := getInfo(r)
2507	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2508	page := r.FormValue("page")
2509
2510	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2511
2512	var hydra Hydration
2513
2514	var honks []*Honk
2515	switch page {
2516	case "atme":
2517		honks = gethonksforme(userid, wanted)
2518		honks = osmosis(honks, userid, false)
2519		menewnone(userid)
2520		hydra.Srvmsg = "at me!"
2521	case "longago":
2522		honks = gethonksfromlongago(userid, wanted)
2523		honks = osmosis(honks, userid, false)
2524		hydra.Srvmsg = "from long ago"
2525	case "home":
2526		honks = gethonksforuser(userid, wanted)
2527		honks = osmosis(honks, userid, true)
2528		hydra.Srvmsg = serverMsg
2529	case "first":
2530		honks = gethonksforuserfirstclass(userid, wanted)
2531		honks = osmosis(honks, userid, true)
2532		hydra.Srvmsg = "first class only"
2533	case "saved":
2534		honks = getsavedhonks(userid, wanted)
2535		templinfo["PageName"] = "saved"
2536		hydra.Srvmsg = "saved honks"
2537	case "combo":
2538		c := r.FormValue("c")
2539		honks = gethonksbycombo(userid, c, wanted)
2540		honks = osmosis(honks, userid, false)
2541		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2542	case "convoy":
2543		c := r.FormValue("c")
2544		honks = gethonksbyconvoy(userid, c, wanted)
2545		honks = osmosis(honks, userid, false)
2546		honks = threadsort(honks)
2547		reversehonks(honks)
2548		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2549	case "honker":
2550		xid := r.FormValue("xid")
2551		honks = gethonksbyxonker(userid, xid, wanted)
2552		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2553			<input type="hidden" name="CSRF" value="%s">
2554			<input type="hidden" name="url" value="%s">
2555			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2556			</form>`, login.GetCSRF("submithonker", r), xid)
2557		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2558		hydra.Srvmsg = msg
2559	case "user":
2560		uname := r.FormValue("uname")
2561		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2562		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2563	default:
2564		http.NotFound(w, r)
2565	}
2566
2567	if len(honks) > 0 {
2568		hydra.Tophid = honks[0].ID
2569	} else {
2570		hydra.Tophid = wanted
2571	}
2572	reverbolate(userid, honks)
2573
2574	user, _ := butwhatabout(u.Username)
2575
2576	var buf strings.Builder
2577	templinfo["Honks"] = honks
2578	templinfo["MapLink"] = getmaplink(u)
2579	templinfo["User"], _ = butwhatabout(u.Username)
2580	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2581	if err != nil {
2582		elog.Printf("frag error: %s", err)
2583		return
2584	}
2585	hydra.Honks = buf.String()
2586	hydra.MeCount = user.Options.MeCount
2587	hydra.ChatCount = user.Options.ChatCount
2588	w.Header().Set("Content-Type", "application/json")
2589	j, _ := jsonify(&hydra)
2590	io.WriteString(w, j)
2591}
2592
2593var honkline = make(chan bool)
2594
2595func honkhonkline() {
2596	for {
2597		select {
2598		case honkline <- true:
2599		default:
2600			return
2601		}
2602	}
2603}
2604
2605func apihandler(w http.ResponseWriter, r *http.Request) {
2606	u := login.GetUserInfo(r)
2607	userid := u.UserID
2608	action := r.FormValue("action")
2609	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2610	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2611	switch action {
2612	case "honk":
2613		h := submithonk(w, r)
2614		if h == nil {
2615			return
2616		}
2617		fmt.Fprintf(w, "%s", h.XID)
2618	case "donk":
2619		donks, err := submitdonk(w, r)
2620		if err != nil {
2621			http.Error(w, err.Error(), http.StatusBadRequest)
2622			return
2623		}
2624		if len(donks) == 0 {
2625			http.Error(w, "missing donk", http.StatusBadRequest)
2626			return
2627		}
2628		d := donks[0]
2629		donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2630		w.Write([]byte(donkxid))
2631	case "zonkit":
2632		zonkit(w, r)
2633	case "gethonks":
2634		var honks []*Honk
2635		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2636		page := r.FormValue("page")
2637		var waitchan <-chan time.Time
2638	requery:
2639		switch page {
2640		case "atme":
2641			honks = gethonksforme(userid, wanted)
2642			honks = osmosis(honks, userid, false)
2643			menewnone(userid)
2644		case "longago":
2645			honks = gethonksfromlongago(userid, wanted)
2646			honks = osmosis(honks, userid, false)
2647		case "home":
2648			honks = gethonksforuser(userid, wanted)
2649			honks = osmosis(honks, userid, true)
2650		case "myhonks":
2651			honks = gethonksbyuser(u.Username, true, wanted)
2652			honks = osmosis(honks, userid, true)
2653		default:
2654			http.Error(w, "unknown page", http.StatusNotFound)
2655			return
2656		}
2657		if len(honks) == 0 && wait > 0 {
2658			if waitchan == nil {
2659				waitchan = time.After(time.Duration(wait) * time.Second)
2660			}
2661			select {
2662			case <-honkline:
2663				goto requery
2664			case <-waitchan:
2665			}
2666		}
2667		reverbolate(userid, honks)
2668		j := junk.New()
2669		j["honks"] = honks
2670		j.Write(w)
2671	case "sendactivity":
2672		user, _ := butwhatabout(u.Username)
2673		public := r.FormValue("public") == "1"
2674		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2675		msg := []byte(r.FormValue("msg"))
2676		for rcpt := range rcpts {
2677			go deliverate(userid, rcpt, msg)
2678		}
2679	case "gethonkers":
2680		j := junk.New()
2681		j["honkers"] = gethonkers(u.UserID)
2682		j.Write(w)
2683	case "savehonker":
2684		h := submithonker(w, r)
2685		if h == nil {
2686			return
2687		}
2688		fmt.Fprintf(w, "%d", h.ID)
2689	default:
2690		http.Error(w, "unknown action", http.StatusNotFound)
2691		return
2692	}
2693}
2694
2695func fiveoh(w http.ResponseWriter, r *http.Request) {
2696	if !develMode {
2697		return
2698	}
2699	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2700	if err != nil {
2701		elog.Printf("error opening violations! %s", err)
2702		return
2703	}
2704	defer fd.Close()
2705	io.Copy(fd, r.Body)
2706	fd.WriteString("\n")
2707}
2708
2709var endoftheworld = make(chan bool)
2710var readyalready = make(chan bool)
2711var workinprogress = 0
2712var requestWG sync.WaitGroup
2713var listenSocket net.Listener
2714
2715func enditall() {
2716	sig := make(chan os.Signal, 1)
2717	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2718	<-sig
2719	ilog.Printf("stopping...")
2720	listenSocket.Close()
2721	for i := 0; i < workinprogress; i++ {
2722		endoftheworld <- true
2723	}
2724	ilog.Printf("waiting...")
2725	go func() {
2726		time.Sleep(10 * time.Second)
2727		elog.Printf("timed out waiting for requests to finish")
2728		os.Exit(0)
2729	}()
2730	for i := 0; i < workinprogress; i++ {
2731		<-readyalready
2732	}
2733	requestWG.Wait()
2734	ilog.Printf("apocalypse")
2735	os.Exit(0)
2736}
2737
2738func bgmonitor() {
2739	for {
2740		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2741		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2742		if err != nil {
2743			elog.Printf("error deleting old xonkers: %s", err)
2744		}
2745		zaggies.Flush()
2746		time.Sleep(50 * time.Minute)
2747	}
2748}
2749
2750func addcspheaders(next http.Handler) http.Handler {
2751	requestWG.Add(1)
2752	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2753		defer requestWG.Done()
2754		policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2755		if develMode {
2756			policy += "; report-uri /csp-violation"
2757		}
2758		w.Header().Set("Content-Security-Policy", policy)
2759		next.ServeHTTP(w, r)
2760	})
2761}
2762
2763func emuinit() {
2764	var emunames []string
2765	dir, err := os.Open(dataDir + "/emus")
2766	if err == nil {
2767		emunames, _ = dir.Readdirnames(0)
2768		dir.Close()
2769	}
2770	for _, e := range emunames {
2771		if len(e) <= 4 {
2772			continue
2773		}
2774		ext := e[len(e)-4:]
2775		emu := Emu{
2776			ID:   fmt.Sprintf("/emu/%s", e),
2777			Name: e[:len(e)-4],
2778			Type: "image/" + ext[1:],
2779		}
2780		allemus = append(allemus, emu)
2781	}
2782	sort.Slice(allemus, func(i, j int) bool {
2783		return allemus[i].Name < allemus[j].Name
2784	})
2785}
2786
2787var savedassetparams = make(map[string]string)
2788
2789func getassetparam(file string) string {
2790	if p, ok := savedassetparams[file]; ok {
2791		return p
2792	}
2793	data, err := os.ReadFile(file)
2794	if err != nil {
2795		return ""
2796	}
2797	hasher := sha512.New()
2798	hasher.Write(data)
2799
2800	return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2801}
2802
2803func startWatcher() {
2804	watcher, err := gonix.NewWatcher()
2805	if err != nil {
2806		return
2807	}
2808	go func() {
2809		s := dataDir + "/views/local.css"
2810		for {
2811			err := watcher.WatchFile(s)
2812			if err != nil {
2813				break
2814			}
2815			err = watcher.WaitForChange()
2816			if err != nil {
2817				dlog.Printf("can't wait: %s", err)
2818				break
2819			}
2820			dlog.Printf("local.css changed")
2821			delete(savedassetparams, s)
2822			savedassetparams[s] = getassetparam(s)
2823		}
2824	}()
2825}
2826
2827var usefcgi bool
2828
2829func serve() {
2830	db := opendatabase()
2831	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2832
2833	listener, err := openListener()
2834	if err != nil {
2835		elog.Fatal(err)
2836	}
2837	runBackendServer()
2838	go enditall()
2839	go redeliverator()
2840	go tracker()
2841	go bgmonitor()
2842	go qotd()
2843	loadLingo()
2844	emuinit()
2845
2846	readviews = templates.Load(develMode,
2847		viewDir+"/views/honkpage.html",
2848		viewDir+"/views/honkfrags.html",
2849		viewDir+"/views/honkers.html",
2850		viewDir+"/views/chatter.html",
2851		viewDir+"/views/hfcs.html",
2852		viewDir+"/views/combos.html",
2853		viewDir+"/views/honkform.html",
2854		viewDir+"/views/honk.html",
2855		viewDir+"/views/account.html",
2856		viewDir+"/views/about.html",
2857		viewDir+"/views/funzone.html",
2858		viewDir+"/views/login.html",
2859		viewDir+"/views/xzone.html",
2860		viewDir+"/views/msg.html",
2861		viewDir+"/views/header.html",
2862		viewDir+"/views/onts.html",
2863		viewDir+"/views/emus.html",
2864		viewDir+"/views/honkpage.js",
2865	)
2866	if !develMode {
2867		assets := []string{
2868			viewDir + "/views/style.css",
2869			dataDir + "/views/local.css",
2870			viewDir + "/views/honkpage.js",
2871			viewDir + "/views/misc.js",
2872			dataDir + "/views/local.js",
2873		}
2874		for _, s := range assets {
2875			savedassetparams[s] = getassetparam(s)
2876		}
2877		loadAvatarColors()
2878	}
2879	startWatcher()
2880
2881	securitizeweb()
2882
2883	mux := mux.NewRouter()
2884	mux.Use(addcspheaders)
2885	mux.Use(login.Checker)
2886
2887	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2888
2889	posters := mux.Methods("POST").Subrouter()
2890	getters := mux.Methods("GET").Subrouter()
2891
2892	getters.HandleFunc("/", homepage)
2893	getters.HandleFunc("/home", homepage)
2894	getters.HandleFunc("/front", homepage)
2895	getters.HandleFunc("/events", homepage)
2896	getters.HandleFunc("/robots.txt", nomoroboto)
2897	getters.HandleFunc("/rss", showrss)
2898	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2899	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2900	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2901	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2902	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2903	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2904	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2905	getters.HandleFunc("/a", avatate)
2906	getters.HandleFunc("/o", thelistingoftheontologies)
2907	getters.HandleFunc("/o/{name:.+}", showontology)
2908	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2909	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2910	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2911	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2912
2913	getters.HandleFunc("/flag/{code:.+}", showflag)
2914
2915	getters.HandleFunc("/server", serveractor)
2916	posters.HandleFunc("/server/inbox", serverinbox)
2917	posters.HandleFunc("/inbox", serverinbox)
2918
2919	posters.HandleFunc("/csp-violation", fiveoh)
2920
2921	getters.HandleFunc("/style.css", serveviewasset)
2922	getters.HandleFunc("/honkpage.js", serveviewasset)
2923	getters.HandleFunc("/misc.js", serveviewasset)
2924	getters.HandleFunc("/local.css", servedataasset)
2925	getters.HandleFunc("/local.js", servedataasset)
2926	getters.HandleFunc("/icon.png", servedataasset)
2927	getters.HandleFunc("/favicon.ico", servedataasset)
2928
2929	getters.HandleFunc("/about", servehtml)
2930	getters.HandleFunc("/login", servehtml)
2931	posters.HandleFunc("/dologin", login.LoginFunc)
2932	getters.HandleFunc("/logout", login.LogoutFunc)
2933	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2934
2935	loggedin := mux.NewRoute().Subrouter()
2936	loggedin.Use(login.Required)
2937	loggedin.HandleFunc("/first", homepage)
2938	loggedin.HandleFunc("/chatter", showchatter)
2939	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2940	loggedin.HandleFunc("/saved", homepage)
2941	loggedin.HandleFunc("/account", accountpage)
2942	loggedin.HandleFunc("/funzone", showfunzone)
2943	loggedin.HandleFunc("/chpass", dochpass)
2944	loggedin.HandleFunc("/atme", homepage)
2945	loggedin.HandleFunc("/longago", homepage)
2946	loggedin.HandleFunc("/hfcs", hfcspage)
2947	loggedin.HandleFunc("/xzone", xzone)
2948	loggedin.HandleFunc("/newhonk", newhonkpage)
2949	loggedin.HandleFunc("/edit", edithonkpage)
2950	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2951	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2952	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2953	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2954	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2955	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2956	loggedin.HandleFunc("/honkers", showhonkers)
2957	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2958	loggedin.HandleFunc("/h", showhonker)
2959	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2960	loggedin.HandleFunc("/c", showcombos)
2961	loggedin.HandleFunc("/t", showconvoy)
2962	loggedin.HandleFunc("/q", showsearch)
2963	loggedin.HandleFunc("/hydra", webhydra)
2964	loggedin.HandleFunc("/emus", showemus)
2965	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2966
2967	if usefcgi {
2968		err = fcgi.Serve(listener, mux)
2969	} else {
2970		err = http.Serve(listener, mux)
2971	}
2972	if err != nil && !errors.Is(err, net.ErrClosed) {
2973		elog.Printf("serve error: %s", err)
2974	}
2975	time.Sleep(15 * time.Second)
2976	elog.Printf("fell off the bottom")
2977}