all repos — honk @ 4036e649d270834b3fec1ff7ecd4d63fad00a5d8

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