all repos — honk @ b33d367aab703308e2c1c951295d89952157087e

my fork of honk

web.go (view raw)

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