all repos — honk @ 4a788131f9034941227bb4b1ab55a042969f01bf

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