all repos — honk @ 7625b655bde20d302a9c747e0bb74afbefbaf8ef

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				top := new(Honk)
1252				*top = *h
1253				honks = append([]*Honk{top}, honks...)
1254				h.Style += " glow"
1255			}
1256		}
1257		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1258			honks = append(honks, h)
1259		}
1260	}
1261
1262	templinfo["ServerMessage"] = "one honk maybe more"
1263	if u != nil {
1264		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1265	}
1266	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1267	honkpage(w, u, honks, templinfo)
1268}
1269
1270func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1271	var userid int64 = -1
1272	if u != nil {
1273		userid = u.UserID
1274		templinfo["User"], _ = butwhatabout(u.Username)
1275	}
1276	reverbolate(userid, honks)
1277	templinfo["Honks"] = honks
1278	templinfo["MapLink"] = getmaplink(u)
1279	if templinfo["TopHID"] == nil {
1280		if len(honks) > 0 {
1281			templinfo["TopHID"] = honks[0].ID
1282		} else {
1283			templinfo["TopHID"] = 0
1284		}
1285	}
1286	if u == nil && !develMode {
1287		w.Header().Set("Cache-Control", "max-age=60")
1288	}
1289	err := readviews.Execute(w, "honkpage.html", templinfo)
1290	if err != nil {
1291		elog.Print(err)
1292	}
1293}
1294
1295func saveuser(w http.ResponseWriter, r *http.Request) {
1296	whatabout := r.FormValue("whatabout")
1297	whatabout = strings.Replace(whatabout, "\r", "", -1)
1298	u := login.GetUserInfo(r)
1299	user, _ := butwhatabout(u.Username)
1300	db := opendatabase()
1301
1302	options := user.Options
1303	if r.FormValue("skinny") == "skinny" {
1304		options.SkinnyCSS = true
1305	} else {
1306		options.SkinnyCSS = false
1307	}
1308	if r.FormValue("omitimages") == "omitimages" {
1309		options.OmitImages = true
1310	} else {
1311		options.OmitImages = false
1312	}
1313	if r.FormValue("mentionall") == "mentionall" {
1314		options.MentionAll = true
1315	} else {
1316		options.MentionAll = false
1317	}
1318	if r.FormValue("inlineqts") == "inlineqts" {
1319		options.InlineQuotes = true
1320	} else {
1321		options.InlineQuotes = false
1322	}
1323	if r.FormValue("maps") == "apple" {
1324		options.MapLink = "apple"
1325	} else {
1326		options.MapLink = ""
1327	}
1328	options.Reaction = r.FormValue("reaction")
1329
1330	sendupdate := false
1331	ava := re_avatar.FindString(whatabout)
1332	if ava != "" {
1333		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1334		ava = ava[7:]
1335		if ava[0] == ' ' {
1336			ava = ava[1:]
1337		}
1338		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1339	}
1340	if ava != options.Avatar {
1341		options.Avatar = ava
1342		sendupdate = true
1343	}
1344	ban := re_banner.FindString(whatabout)
1345	if ban != "" {
1346		whatabout = re_banner.ReplaceAllString(whatabout, "")
1347		ban = ban[7:]
1348		if ban[0] == ' ' {
1349			ban = ban[1:]
1350		}
1351		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1352	}
1353	if ban != options.Banner {
1354		options.Banner = ban
1355		sendupdate = true
1356	}
1357	whatabout = strings.TrimSpace(whatabout)
1358	if whatabout != user.About {
1359		sendupdate = true
1360	}
1361	j, err := jsonify(options)
1362	if err == nil {
1363		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1364	}
1365	if err != nil {
1366		elog.Printf("error bouting what: %s", err)
1367	}
1368	somenamedusers.Clear(u.Username)
1369	somenumberedusers.Clear(u.UserID)
1370	oldjonkers.Clear(u.Username)
1371
1372	if sendupdate {
1373		updateMe(u.Username)
1374	}
1375
1376	http.Redirect(w, r, "/account", http.StatusSeeOther)
1377}
1378
1379func bonkit(xid string, user *WhatAbout) {
1380	dlog.Printf("bonking %s", xid)
1381
1382	xonk := getxonk(user.ID, xid)
1383	if xonk == nil {
1384		return
1385	}
1386	if !xonk.Public {
1387		return
1388	}
1389	if xonk.IsBonked() {
1390		return
1391	}
1392	donksforhonks([]*Honk{xonk})
1393
1394	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1395	if err != nil {
1396		elog.Printf("error acking bonk: %s", err)
1397	}
1398
1399	oonker := xonk.Oonker
1400	if oonker == "" {
1401		oonker = xonk.Honker
1402	}
1403	dt := time.Now().UTC()
1404	bonk := &Honk{
1405		UserID:   user.ID,
1406		Username: user.Name,
1407		What:     "bonk",
1408		Honker:   user.URL,
1409		Oonker:   oonker,
1410		XID:      xonk.XID,
1411		RID:      xonk.RID,
1412		Noise:    xonk.Noise,
1413		Precis:   xonk.Precis,
1414		URL:      xonk.URL,
1415		Date:     dt,
1416		Donks:    xonk.Donks,
1417		Whofore:  2,
1418		Convoy:   xonk.Convoy,
1419		Audience: []string{thewholeworld, oonker},
1420		Public:   true,
1421		Format:   xonk.Format,
1422		Place:    xonk.Place,
1423		Onts:     xonk.Onts,
1424		Time:     xonk.Time,
1425	}
1426
1427	err = savehonk(bonk)
1428	if err != nil {
1429		elog.Printf("uh oh")
1430		return
1431	}
1432
1433	go honkworldwide(user, bonk)
1434}
1435
1436func submitbonk(w http.ResponseWriter, r *http.Request) {
1437	xid := r.FormValue("xid")
1438	userinfo := login.GetUserInfo(r)
1439	user, _ := butwhatabout(userinfo.Username)
1440
1441	bonkit(xid, user)
1442
1443	if r.FormValue("js") != "1" {
1444		templinfo := getInfo(r)
1445		templinfo["ServerMessage"] = "Bonked!"
1446		err := readviews.Execute(w, "msg.html", templinfo)
1447		if err != nil {
1448			elog.Print(err)
1449		}
1450	}
1451}
1452
1453func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1454	zonk := &Honk{
1455		What:     what,
1456		XID:      xonk.XID,
1457		Date:     time.Now().UTC(),
1458		Audience: oneofakind(xonk.Audience),
1459		Noise:    aux,
1460	}
1461	zonk.Public = loudandproud(zonk.Audience)
1462
1463	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1464	go honkworldwide(user, zonk)
1465}
1466
1467func zonkit(w http.ResponseWriter, r *http.Request) {
1468	wherefore := r.FormValue("wherefore")
1469	what := r.FormValue("what")
1470	userinfo := login.GetUserInfo(r)
1471	user, _ := butwhatabout(userinfo.Username)
1472
1473	if wherefore == "save" {
1474		xonk := getxonk(userinfo.UserID, what)
1475		if xonk != nil {
1476			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1477			if err != nil {
1478				elog.Printf("error saving: %s", err)
1479			}
1480		}
1481		return
1482	}
1483
1484	if wherefore == "unsave" {
1485		xonk := getxonk(userinfo.UserID, what)
1486		if xonk != nil {
1487			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1488			if err != nil {
1489				elog.Printf("error unsaving: %s", err)
1490			}
1491		}
1492		return
1493	}
1494
1495	if wherefore == "react" {
1496		reaction := user.Options.Reaction
1497		if r2 := r.FormValue("reaction"); r2 != "" {
1498			reaction = r2
1499		}
1500		if reaction == "none" {
1501			return
1502		}
1503		xonk := getxonk(userinfo.UserID, what)
1504		if xonk != nil {
1505			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1506			if err != nil {
1507				elog.Printf("error saving: %s", err)
1508			}
1509			sendzonkofsorts(xonk, user, "react", reaction)
1510		}
1511		return
1512	}
1513
1514	// my hammer is too big, oh well
1515	defer oldjonks.Flush()
1516
1517	if wherefore == "ack" {
1518		xonk := getxonk(userinfo.UserID, what)
1519		if xonk != nil && !xonk.IsAcked() {
1520			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1521			if err != nil {
1522				elog.Printf("error acking: %s", err)
1523			}
1524			sendzonkofsorts(xonk, user, "ack", "")
1525		}
1526		return
1527	}
1528
1529	if wherefore == "deack" {
1530		xonk := getxonk(userinfo.UserID, what)
1531		if xonk != nil && xonk.IsAcked() {
1532			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1533			if err != nil {
1534				elog.Printf("error deacking: %s", err)
1535			}
1536			sendzonkofsorts(xonk, user, "deack", "")
1537		}
1538		return
1539	}
1540
1541	if wherefore == "bonk" {
1542		user, _ := butwhatabout(userinfo.Username)
1543		bonkit(what, user)
1544		return
1545	}
1546
1547	if wherefore == "unbonk" {
1548		xonk := getbonk(userinfo.UserID, what)
1549		if xonk != nil {
1550			deletehonk(xonk.ID)
1551			xonk = getxonk(userinfo.UserID, what)
1552			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1553			if err != nil {
1554				elog.Printf("error unbonking: %s", err)
1555			}
1556			sendzonkofsorts(xonk, user, "unbonk", "")
1557		}
1558		return
1559	}
1560
1561	if wherefore == "untag" {
1562		xonk := getxonk(userinfo.UserID, what)
1563		if xonk != nil {
1564			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1565			if err != nil {
1566				elog.Printf("error untagging: %s", err)
1567			}
1568		}
1569		var badparents map[string]bool
1570		untagged.GetAndLock(userinfo.UserID, &badparents)
1571		badparents[what] = true
1572		untagged.Unlock()
1573		return
1574	}
1575
1576	ilog.Printf("zonking %s %s", wherefore, what)
1577	if wherefore == "zonk" {
1578		xonk := getxonk(userinfo.UserID, what)
1579		if xonk != nil {
1580			deletehonk(xonk.ID)
1581			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1582				sendzonkofsorts(xonk, user, "zonk", "")
1583			}
1584		}
1585	}
1586	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1587	if err != nil {
1588		elog.Printf("error saving zonker: %s", err)
1589		return
1590	}
1591}
1592
1593func edithonkpage(w http.ResponseWriter, r *http.Request) {
1594	u := login.GetUserInfo(r)
1595	user, _ := butwhatabout(u.Username)
1596	xid := r.FormValue("xid")
1597	honk := getxonk(u.UserID, xid)
1598	if !canedithonk(user, honk) {
1599		http.Error(w, "no editing that please", http.StatusInternalServerError)
1600		return
1601	}
1602
1603	noise := honk.Noise
1604
1605	honks := []*Honk{honk}
1606	donksforhonks(honks)
1607	reverbolate(u.UserID, honks)
1608	templinfo := getInfo(r)
1609	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1610	templinfo["Honks"] = honks
1611	templinfo["MapLink"] = getmaplink(u)
1612	templinfo["Noise"] = noise
1613	templinfo["SavedPlace"] = honk.Place
1614	if tm := honk.Time; tm != nil {
1615		templinfo["ShowTime"] = " "
1616		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1617		if tm.Duration != 0 {
1618			templinfo["Duration"] = tm.Duration
1619		}
1620	}
1621	templinfo["ServerMessage"] = "honk edit"
1622	templinfo["IsPreview"] = true
1623	templinfo["UpdateXID"] = honk.XID
1624	if len(honk.Donks) > 0 {
1625		var savedfiles []string
1626		for _, d := range honk.Donks {
1627			savedfiles = append(savedfiles, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1628		}
1629		templinfo["SavedFile"] = strings.Join(savedfiles, ",")
1630	}
1631	err := readviews.Execute(w, "honkpage.html", templinfo)
1632	if err != nil {
1633		elog.Print(err)
1634	}
1635}
1636
1637func newhonkpage(w http.ResponseWriter, r *http.Request) {
1638	u := login.GetUserInfo(r)
1639	rid := r.FormValue("rid")
1640	noise := ""
1641
1642	xonk := getxonk(u.UserID, rid)
1643	if xonk != nil {
1644		_, replto := handles(xonk.Honker)
1645		if replto != "" {
1646			noise = "@" + replto + " "
1647		}
1648	}
1649
1650	templinfo := getInfo(r)
1651	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1652	templinfo["InReplyTo"] = rid
1653	templinfo["Noise"] = noise
1654	templinfo["ServerMessage"] = "compose honk"
1655	templinfo["IsPreview"] = true
1656	err := readviews.Execute(w, "honkpage.html", templinfo)
1657	if err != nil {
1658		elog.Print(err)
1659	}
1660}
1661
1662func canedithonk(user *WhatAbout, honk *Honk) bool {
1663	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1664		return false
1665	}
1666	return true
1667}
1668
1669func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1670	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1671		return nil, nil
1672	}
1673	var donks []*Donk
1674	for i, hdr := range r.MultipartForm.File["donk"] {
1675		if i > 16 {
1676			break
1677		}
1678		donk, err := formtodonk(w, r, hdr)
1679		if err != nil {
1680			return nil, err
1681		}
1682		donks = append(donks, donk)
1683	}
1684	return donks, nil
1685}
1686
1687func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1688	file, err := filehdr.Open()
1689	if err != nil {
1690		if err == http.ErrMissingFile {
1691			return nil, nil
1692		}
1693		elog.Printf("error reading donk: %s", err)
1694		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1695		return nil, err
1696	}
1697	var buf bytes.Buffer
1698	io.Copy(&buf, file)
1699	file.Close()
1700	data := buf.Bytes()
1701	var media, name string
1702	img, err := bigshrink(data)
1703	if err == nil {
1704		data = img.Data
1705		format := img.Format
1706		media = "image/" + format
1707		if format == "jpeg" {
1708			format = "jpg"
1709		}
1710		if format == "svg+xml" {
1711			format = "svg"
1712		}
1713		name = xfiltrate() + "." + format
1714	} else {
1715		ct := http.DetectContentType(data)
1716		switch ct {
1717		case "application/pdf":
1718			maxsize := 10000000
1719			if len(data) > maxsize {
1720				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1721				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1722				return nil, err
1723			}
1724			media = ct
1725			name = filehdr.Filename
1726			if name == "" {
1727				name = xfiltrate() + ".pdf"
1728			}
1729		default:
1730			maxsize := 100000
1731			if len(data) > maxsize {
1732				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1733				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1734				return nil, err
1735			}
1736			for i := 0; i < len(data); i++ {
1737				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1738					ilog.Printf("bad image: %s not text: %d", err, data[i])
1739					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1740					return nil, err
1741				}
1742			}
1743			media = "text/plain"
1744			name = filehdr.Filename
1745			if name == "" {
1746				name = xfiltrate() + ".txt"
1747			}
1748		}
1749	}
1750	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1751	if desc == "" {
1752		desc = name
1753	}
1754	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1755	if err != nil {
1756		elog.Printf("unable to save image: %s", err)
1757		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1758		return nil, err
1759	}
1760	d := &Donk{
1761		FileID: fileid,
1762		XID:    xid,
1763		Desc:   desc,
1764		Local:  true,
1765	}
1766	return d, nil
1767}
1768
1769func websubmithonk(w http.ResponseWriter, r *http.Request) {
1770	h := submithonk(w, r)
1771	if h == nil {
1772		return
1773	}
1774	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1775}
1776
1777// what a hot mess this function is
1778func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1779	rid := r.FormValue("rid")
1780	noise := r.FormValue("noise")
1781	format := r.FormValue("format")
1782	if format == "" {
1783		format = "markdown"
1784	}
1785	if !(format == "markdown" || format == "html") {
1786		http.Error(w, "unknown format", 500)
1787		return nil
1788	}
1789
1790	userinfo := login.GetUserInfo(r)
1791	user, _ := butwhatabout(userinfo.Username)
1792
1793	dt := time.Now().UTC()
1794	updatexid := r.FormValue("updatexid")
1795	var honk *Honk
1796	if updatexid != "" {
1797		honk = getxonk(userinfo.UserID, updatexid)
1798		if !canedithonk(user, honk) {
1799			http.Error(w, "no editing that please", http.StatusInternalServerError)
1800			return nil
1801		}
1802		honk.Date = dt
1803		honk.What = "update"
1804		honk.Format = format
1805	} else {
1806		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1807		what := "honk"
1808		honk = &Honk{
1809			UserID:   userinfo.UserID,
1810			Username: userinfo.Username,
1811			What:     what,
1812			Honker:   user.URL,
1813			XID:      xid,
1814			Date:     dt,
1815			Format:   format,
1816		}
1817	}
1818
1819	var convoy string
1820	noise = strings.Replace(noise, "\r", "", -1)
1821	if updatexid == "" && rid == "" {
1822		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1823			convoy = m[7:]
1824			convoy = strings.TrimSpace(convoy)
1825			if !re_convalidate.MatchString(convoy) {
1826				convoy = ""
1827			}
1828			return ""
1829		})
1830	}
1831	noise = quickrename(noise, userinfo.UserID)
1832	noise = hooterize(noise)
1833	honk.Noise = noise
1834	precipitate(honk)
1835	noise = honk.Noise
1836	recategorize(honk)
1837	translate(honk)
1838
1839	if rid != "" {
1840		xonk := getxonk(userinfo.UserID, rid)
1841		if xonk == nil {
1842			http.Error(w, "replyto disappeared", http.StatusNotFound)
1843			return nil
1844		}
1845		if xonk.Public {
1846			honk.Audience = append(honk.Audience, xonk.Audience...)
1847		}
1848		convoy = xonk.Convoy
1849		for i, a := range honk.Audience {
1850			if a == thewholeworld {
1851				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1852				break
1853			}
1854		}
1855		honk.RID = rid
1856		if xonk.Precis != "" && honk.Precis == "" {
1857			honk.Precis = xonk.Precis
1858			if !re_dangerous.MatchString(honk.Precis) {
1859				honk.Precis = "re: " + honk.Precis
1860			}
1861		}
1862	} else if updatexid == "" {
1863		honk.Audience = []string{thewholeworld}
1864	}
1865	if honk.Noise != "" && honk.Noise[0] == '@' {
1866		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1867	} else {
1868		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1869	}
1870
1871	if convoy == "" {
1872		convoy = "data:,electrichonkytonk-" + xfiltrate()
1873	}
1874	butnottooloud(honk.Audience)
1875	honk.Audience = oneofakind(honk.Audience)
1876	if len(honk.Audience) == 0 {
1877		ilog.Printf("honk to nowhere")
1878		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1879		return nil
1880	}
1881	honk.Public = loudandproud(honk.Audience)
1882	honk.Convoy = convoy
1883
1884	donkxid := strings.Join(r.Form["donkxid"], ",")
1885	if donkxid == "" {
1886		donks, err := submitdonk(w, r)
1887		if err != nil && err != http.ErrMissingFile {
1888			return nil
1889		}
1890		if len(donks) > 0 {
1891			honk.Donks = append(honk.Donks, donks...)
1892			var xids []string
1893			for _, d := range honk.Donks {
1894				xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1895			}
1896			donkxid = strings.Join(xids, ",")
1897		}
1898	} else {
1899		xids := strings.Split(donkxid, ",")
1900		for i, xid := range xids {
1901			if i > 16 {
1902				break
1903			}
1904			p := strings.Split(xid, ":")
1905			xid = p[0]
1906			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1907			var donk *Donk
1908			if len(p) > 1 {
1909				fileid, _ := strconv.ParseInt(p[1], 10, 0)
1910				donk = finddonkid(fileid, url)
1911			} else {
1912				donk = finddonk(url)
1913			}
1914			if donk != nil {
1915				honk.Donks = append(honk.Donks, donk)
1916			} else {
1917				ilog.Printf("can't find file: %s", xid)
1918			}
1919		}
1920	}
1921	memetize(honk)
1922	imaginate(honk)
1923
1924	placename := strings.TrimSpace(r.FormValue("placename"))
1925	placelat := strings.TrimSpace(r.FormValue("placelat"))
1926	placelong := strings.TrimSpace(r.FormValue("placelong"))
1927	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1928	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1929		p := new(Place)
1930		p.Name = placename
1931		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1932		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1933		p.Url = placeurl
1934		honk.Place = p
1935	}
1936	timestart := strings.TrimSpace(r.FormValue("timestart"))
1937	if timestart != "" {
1938		t := new(Time)
1939		now := time.Now().Local()
1940		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1941			start, err := time.ParseInLocation(layout, timestart, now.Location())
1942			if err == nil {
1943				if start.Year() == 0 {
1944					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1945				}
1946				t.StartTime = start
1947				break
1948			}
1949		}
1950		timeend := r.FormValue("timeend")
1951		dur := parseDuration(timeend)
1952		if dur != 0 {
1953			t.Duration = Duration(dur)
1954		}
1955		if !t.StartTime.IsZero() {
1956			honk.What = "event"
1957			honk.Time = t
1958		}
1959	}
1960
1961	if honk.Public {
1962		honk.Whofore = 2
1963	} else {
1964		honk.Whofore = 3
1965	}
1966
1967	// back to markdown
1968	honk.Noise = noise
1969
1970	if r.FormValue("preview") == "preview" {
1971		honks := []*Honk{honk}
1972		reverbolate(userinfo.UserID, honks)
1973		templinfo := getInfo(r)
1974		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1975		templinfo["Honks"] = honks
1976		templinfo["MapLink"] = getmaplink(userinfo)
1977		templinfo["InReplyTo"] = r.FormValue("rid")
1978		templinfo["Noise"] = r.FormValue("noise")
1979		templinfo["SavedFile"] = donkxid
1980		if tm := honk.Time; tm != nil {
1981			templinfo["ShowTime"] = " "
1982			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1983			if tm.Duration != 0 {
1984				templinfo["Duration"] = tm.Duration
1985			}
1986		}
1987		templinfo["IsPreview"] = true
1988		templinfo["UpdateXID"] = updatexid
1989		templinfo["ServerMessage"] = "honk preview"
1990		err := readviews.Execute(w, "honkpage.html", templinfo)
1991		if err != nil {
1992			elog.Print(err)
1993		}
1994		return nil
1995	}
1996
1997	if updatexid != "" {
1998		updatehonk(honk)
1999		oldjonks.Clear(honk.XID)
2000	} else {
2001		err := savehonk(honk)
2002		if err != nil {
2003			elog.Printf("uh oh")
2004			return nil
2005		}
2006	}
2007
2008	// reload for consistency
2009	honk.Donks = nil
2010	donksforhonks([]*Honk{honk})
2011
2012	go honkworldwide(user, honk)
2013
2014	return honk
2015}
2016
2017func showhonkers(w http.ResponseWriter, r *http.Request) {
2018	userinfo := login.GetUserInfo(r)
2019	templinfo := getInfo(r)
2020	templinfo["Honkers"] = gethonkers(userinfo.UserID)
2021	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2022	err := readviews.Execute(w, "honkers.html", templinfo)
2023	if err != nil {
2024		elog.Print(err)
2025	}
2026}
2027
2028func showchatter(w http.ResponseWriter, r *http.Request) {
2029	u := login.GetUserInfo(r)
2030	chatnewnone(u.UserID)
2031	chatter := loadchatter(u.UserID)
2032	for _, chat := range chatter {
2033		for _, ch := range chat.Chonks {
2034			filterchonk(ch)
2035		}
2036	}
2037
2038	templinfo := getInfo(r)
2039	templinfo["Chatter"] = chatter
2040	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2041	err := readviews.Execute(w, "chatter.html", templinfo)
2042	if err != nil {
2043		elog.Print(err)
2044	}
2045}
2046
2047func submitchonk(w http.ResponseWriter, r *http.Request) {
2048	u := login.GetUserInfo(r)
2049	user, _ := butwhatabout(u.Username)
2050	noise := r.FormValue("noise")
2051	target := r.FormValue("target")
2052	format := "markdown"
2053	dt := time.Now().UTC()
2054	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2055
2056	if !strings.HasPrefix(target, "https://") {
2057		target = fullname(target, u.UserID)
2058	}
2059	if target == "" {
2060		http.Error(w, "who is that?", http.StatusInternalServerError)
2061		return
2062	}
2063	ch := Chonk{
2064		UserID: u.UserID,
2065		XID:    xid,
2066		Who:    user.URL,
2067		Target: target,
2068		Date:   dt,
2069		Noise:  noise,
2070		Format: format,
2071	}
2072	donks, err := submitdonk(w, r)
2073	if err != nil && err != http.ErrMissingFile {
2074		return
2075	}
2076	if len(donks) > 0 {
2077		ch.Donks = append(ch.Donks, donks...)
2078	}
2079
2080	translatechonk(&ch)
2081	savechonk(&ch)
2082	// reload for consistency
2083	ch.Donks = nil
2084	donksforchonks([]*Chonk{&ch})
2085	go sendchonk(user, &ch)
2086
2087	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2088}
2089
2090var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2091	honkers := gethonkers(userid)
2092	var combos []string
2093	for _, h := range honkers {
2094		combos = append(combos, h.Combos...)
2095	}
2096	for i, c := range combos {
2097		if c == "-" {
2098			combos[i] = ""
2099		}
2100	}
2101	combos = oneofakind(combos)
2102	sort.Strings(combos)
2103	return combos, true
2104}, Invalidator: &honkerinvalidator})
2105
2106func showcombos(w http.ResponseWriter, r *http.Request) {
2107	userinfo := login.GetUserInfo(r)
2108	var combos []string
2109	combocache.Get(userinfo.UserID, &combos)
2110	templinfo := getInfo(r)
2111	err := readviews.Execute(w, "combos.html", templinfo)
2112	if err != nil {
2113		elog.Print(err)
2114	}
2115}
2116
2117func websubmithonker(w http.ResponseWriter, r *http.Request) {
2118	h := submithonker(w, r)
2119	if h == nil {
2120		return
2121	}
2122	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2123}
2124
2125func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2126	u := login.GetUserInfo(r)
2127	user, _ := butwhatabout(u.Username)
2128	name := strings.TrimSpace(r.FormValue("name"))
2129	url := strings.TrimSpace(r.FormValue("url"))
2130	peep := r.FormValue("peep")
2131	combos := strings.TrimSpace(r.FormValue("combos"))
2132	combos = " " + combos + " "
2133	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2134
2135	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2136	if name != "" && !re_namecheck.MatchString(name) {
2137		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2138		return nil
2139	}
2140
2141	var meta HonkerMeta
2142	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2143	mj, _ := jsonify(&meta)
2144
2145	defer honkerinvalidator.Clear(u.UserID)
2146
2147	// mostly dummy, fill in later...
2148	h := &Honker{
2149		ID: honkerid,
2150	}
2151
2152	if honkerid > 0 {
2153		if r.FormValue("delete") == "delete" {
2154			unfollowyou(user, honkerid, false)
2155			stmtDeleteHonker.Exec(honkerid)
2156			return h
2157		}
2158		if r.FormValue("unsub") == "unsub" {
2159			unfollowyou(user, honkerid, false)
2160		}
2161		if r.FormValue("sub") == "sub" {
2162			followyou(user, honkerid, false)
2163		}
2164		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2165		if err != nil {
2166			elog.Printf("update honker err: %s", err)
2167			return nil
2168		}
2169		return h
2170	}
2171
2172	if url == "" {
2173		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2174		return nil
2175	}
2176
2177	flavor := "presub"
2178	if peep == "peep" {
2179		flavor = "peep"
2180	}
2181
2182	var err error
2183	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2184	if err != nil {
2185		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2186		return nil
2187	}
2188	if flavor == "presub" {
2189		followyou(user, honkerid, false)
2190	}
2191	h.ID = honkerid
2192	return h
2193}
2194
2195func hfcspage(w http.ResponseWriter, r *http.Request) {
2196	userinfo := login.GetUserInfo(r)
2197
2198	filters := getfilters(userinfo.UserID, filtAny)
2199
2200	templinfo := getInfo(r)
2201	templinfo["Filters"] = filters
2202	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2203	err := readviews.Execute(w, "hfcs.html", templinfo)
2204	if err != nil {
2205		elog.Print(err)
2206	}
2207}
2208
2209func savehfcs(w http.ResponseWriter, r *http.Request) {
2210	userinfo := login.GetUserInfo(r)
2211	itsok := r.FormValue("itsok")
2212	if itsok == "iforgiveyou" {
2213		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2214		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2215		if err != nil {
2216			elog.Printf("error deleting filter: %s", err)
2217		}
2218		filtInvalidator.Clear(userinfo.UserID)
2219		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2220		return
2221	}
2222
2223	filt := new(Filter)
2224	filt.Name = strings.TrimSpace(r.FormValue("name"))
2225	filt.Date = time.Now().UTC()
2226	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2227	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2228	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2229	filt.IsReply = r.FormValue("isreply") == "yes"
2230	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2231	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2232	filt.Reject = r.FormValue("doreject") == "yes"
2233	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2234	filt.Hide = r.FormValue("dohide") == "yes"
2235	filt.Collapse = r.FormValue("docollapse") == "yes"
2236	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2237	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2238	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2239		filt.Expiration = time.Now().UTC().Add(dur)
2240	}
2241	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2242
2243	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2244		ilog.Printf("blank filter")
2245		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2246		return
2247	}
2248
2249	j, err := jsonify(filt)
2250	if err == nil {
2251		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2252	}
2253	if err != nil {
2254		elog.Printf("error saving filter: %s", err)
2255	}
2256
2257	filtInvalidator.Clear(userinfo.UserID)
2258	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2259}
2260
2261func accountpage(w http.ResponseWriter, r *http.Request) {
2262	u := login.GetUserInfo(r)
2263	user, _ := butwhatabout(u.Username)
2264	templinfo := getInfo(r)
2265	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2266	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2267	templinfo["User"] = user
2268	about := user.About
2269	if ava := user.Options.Avatar; ava != "" {
2270		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2271	}
2272	if ban := user.Options.Banner; ban != "" {
2273		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2274	}
2275	templinfo["WhatAbout"] = about
2276	err := readviews.Execute(w, "account.html", templinfo)
2277	if err != nil {
2278		elog.Print(err)
2279	}
2280}
2281
2282func dochpass(w http.ResponseWriter, r *http.Request) {
2283	err := login.ChangePassword(w, r)
2284	if err != nil {
2285		elog.Printf("error changing password: %s", err)
2286	}
2287	http.Redirect(w, r, "/account", http.StatusSeeOther)
2288}
2289
2290var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2291	if strings.HasPrefix(orig, "acct:") {
2292		orig = orig[5:]
2293	}
2294	name := orig
2295	idx := strings.LastIndexByte(name, '/')
2296	if idx != -1 {
2297		name = name[idx+1:]
2298		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2299			ilog.Printf("foreign request rejected")
2300			name = ""
2301		}
2302	} else {
2303		idx = strings.IndexByte(name, '@')
2304		if idx != -1 {
2305			name = name[:idx]
2306			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2307				ilog.Printf("foreign request rejected")
2308				name = ""
2309			}
2310		}
2311	}
2312	user, err := butwhatabout(name)
2313	if err != nil {
2314		return nil, false
2315	}
2316
2317	j := junk.New()
2318	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2319	j["aliases"] = []string{user.URL}
2320	l := junk.New()
2321	l["rel"] = "self"
2322	l["type"] = `application/activity+json`
2323	l["href"] = user.URL
2324	j["links"] = []junk.Junk{l}
2325	return j.ToBytes(), true
2326}})
2327
2328func fingerlicker(w http.ResponseWriter, r *http.Request) {
2329	orig := r.FormValue("resource")
2330
2331	dlog.Printf("finger lick: %s", orig)
2332
2333	var j []byte
2334	ok := oldfingers.Get(orig, &j)
2335	if ok {
2336		w.Header().Set("Content-Type", "application/jrd+json")
2337		w.Write(j)
2338	} else {
2339		http.NotFound(w, r)
2340	}
2341}
2342
2343func somedays() string {
2344	secs := 432000 + notrand.Int63n(432000)
2345	return fmt.Sprintf("%d", secs)
2346}
2347
2348func lookatme(ava string) string {
2349	if strings.Contains(ava, serverName+"/"+userSep) {
2350		idx := strings.LastIndexByte(ava, '/')
2351		if idx < len(ava) {
2352			name := ava[idx+1:]
2353			user, _ := butwhatabout(name)
2354			if user != nil && user.URL == ava {
2355				return user.Options.Avatar
2356			}
2357		}
2358	}
2359	return ""
2360}
2361
2362func avatate(w http.ResponseWriter, r *http.Request) {
2363	if develMode {
2364		loadAvatarColors()
2365	}
2366	n := r.FormValue("a")
2367	if redir := lookatme(n); redir != "" {
2368		http.Redirect(w, r, redir, http.StatusSeeOther)
2369		return
2370	}
2371	a := genAvatar(n)
2372	if !develMode {
2373		w.Header().Set("Cache-Control", "max-age="+somedays())
2374	}
2375	w.Write(a)
2376}
2377
2378func serveviewasset(w http.ResponseWriter, r *http.Request) {
2379	serveasset(w, r, viewDir)
2380}
2381func servedataasset(w http.ResponseWriter, r *http.Request) {
2382	if r.URL.Path == "/favicon.ico" {
2383		r.URL.Path = "/icon.png"
2384	}
2385	serveasset(w, r, dataDir)
2386}
2387
2388func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2389	if !develMode {
2390		w.Header().Set("Cache-Control", "max-age=7776000")
2391	}
2392	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2393}
2394func servehelp(w http.ResponseWriter, r *http.Request) {
2395	name := mux.Vars(r)["name"]
2396	if !develMode {
2397		w.Header().Set("Cache-Control", "max-age=3600")
2398	}
2399	http.ServeFile(w, r, viewDir+"/docs/"+name)
2400}
2401func servehtml(w http.ResponseWriter, r *http.Request) {
2402	u := login.GetUserInfo(r)
2403	templinfo := getInfo(r)
2404	templinfo["AboutMsg"] = aboutMsg
2405	templinfo["LoginMsg"] = loginMsg
2406	templinfo["HonkVersion"] = softwareVersion
2407	if r.URL.Path == "/about" {
2408		templinfo["Sensors"] = getSensors()
2409	}
2410	if u == nil && !develMode {
2411		w.Header().Set("Cache-Control", "max-age=60")
2412	}
2413	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2414	if err != nil {
2415		elog.Print(err)
2416	}
2417}
2418func serveemu(w http.ResponseWriter, r *http.Request) {
2419	emu := mux.Vars(r)["emu"]
2420
2421	w.Header().Set("Cache-Control", "max-age="+somedays())
2422	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2423}
2424func servememe(w http.ResponseWriter, r *http.Request) {
2425	meme := mux.Vars(r)["meme"]
2426
2427	w.Header().Set("Cache-Control", "max-age="+somedays())
2428	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2429}
2430
2431func servefile(w http.ResponseWriter, r *http.Request) {
2432	xid := mux.Vars(r)["xid"]
2433	var media string
2434	var data []byte
2435	row := stmtGetFileData.QueryRow(xid)
2436	err := row.Scan(&media, &data)
2437	if err != nil {
2438		elog.Printf("error loading file: %s", err)
2439		http.NotFound(w, r)
2440		return
2441	}
2442	w.Header().Set("Content-Type", media)
2443	w.Header().Set("X-Content-Type-Options", "nosniff")
2444	w.Header().Set("Cache-Control", "max-age="+somedays())
2445	w.Write(data)
2446}
2447
2448func nomoroboto(w http.ResponseWriter, r *http.Request) {
2449	io.WriteString(w, "User-agent: *\n")
2450	io.WriteString(w, "Disallow: /a\n")
2451	io.WriteString(w, "Disallow: /d/\n")
2452	io.WriteString(w, "Disallow: /meme/\n")
2453	io.WriteString(w, "Disallow: /o\n")
2454	io.WriteString(w, "Disallow: /o/\n")
2455	io.WriteString(w, "Disallow: /help/\n")
2456	for _, u := range allusers() {
2457		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2458	}
2459}
2460
2461type Hydration struct {
2462	Tophid    int64
2463	Srvmsg    template.HTML
2464	Honks     string
2465	MeCount   int64
2466	ChatCount int64
2467}
2468
2469func webhydra(w http.ResponseWriter, r *http.Request) {
2470	u := login.GetUserInfo(r)
2471	userid := u.UserID
2472	templinfo := getInfo(r)
2473	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2474	page := r.FormValue("page")
2475
2476	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2477
2478	var hydra Hydration
2479
2480	var honks []*Honk
2481	switch page {
2482	case "atme":
2483		honks = gethonksforme(userid, wanted)
2484		honks = osmosis(honks, userid, false)
2485		menewnone(userid)
2486		hydra.Srvmsg = "at me!"
2487	case "longago":
2488		honks = gethonksfromlongago(userid, wanted)
2489		honks = osmosis(honks, userid, false)
2490		hydra.Srvmsg = "from long ago"
2491	case "home":
2492		honks = gethonksforuser(userid, wanted)
2493		honks = osmosis(honks, userid, true)
2494		hydra.Srvmsg = serverMsg
2495	case "first":
2496		honks = gethonksforuserfirstclass(userid, wanted)
2497		honks = osmosis(honks, userid, true)
2498		hydra.Srvmsg = "first class only"
2499	case "saved":
2500		honks = getsavedhonks(userid, wanted)
2501		templinfo["PageName"] = "saved"
2502		hydra.Srvmsg = "saved honks"
2503	case "combo":
2504		c := r.FormValue("c")
2505		honks = gethonksbycombo(userid, c, wanted)
2506		honks = osmosis(honks, userid, false)
2507		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2508	case "convoy":
2509		c := r.FormValue("c")
2510		honks = gethonksbyconvoy(userid, c, wanted)
2511		honks = osmosis(honks, userid, false)
2512		honks = threadsort(honks)
2513		reversehonks(honks)
2514		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2515	case "honker":
2516		xid := r.FormValue("xid")
2517		honks = gethonksbyxonker(userid, xid, wanted)
2518		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2519			<input type="hidden" name="CSRF" value="%s">
2520			<input type="hidden" name="url" value="%s">
2521			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2522			</form>`, login.GetCSRF("submithonker", r), xid)
2523		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2524		hydra.Srvmsg = msg
2525	case "user":
2526		uname := r.FormValue("uname")
2527		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2528		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2529	default:
2530		http.NotFound(w, r)
2531	}
2532
2533	if len(honks) > 0 {
2534		hydra.Tophid = honks[0].ID
2535	} else {
2536		hydra.Tophid = wanted
2537	}
2538	reverbolate(userid, honks)
2539
2540	user, _ := butwhatabout(u.Username)
2541
2542	var buf strings.Builder
2543	templinfo["Honks"] = honks
2544	templinfo["MapLink"] = getmaplink(u)
2545	templinfo["User"], _ = butwhatabout(u.Username)
2546	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2547	if err != nil {
2548		elog.Printf("frag error: %s", err)
2549		return
2550	}
2551	hydra.Honks = buf.String()
2552	hydra.MeCount = user.Options.MeCount
2553	hydra.ChatCount = user.Options.ChatCount
2554	w.Header().Set("Content-Type", "application/json")
2555	j, _ := jsonify(&hydra)
2556	io.WriteString(w, j)
2557}
2558
2559var honkline = make(chan bool)
2560
2561func honkhonkline() {
2562	for {
2563		select {
2564		case honkline <- true:
2565		default:
2566			return
2567		}
2568	}
2569}
2570
2571func apihandler(w http.ResponseWriter, r *http.Request) {
2572	u := login.GetUserInfo(r)
2573	userid := u.UserID
2574	action := r.FormValue("action")
2575	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2576	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2577	switch action {
2578	case "honk":
2579		h := submithonk(w, r)
2580		if h == nil {
2581			return
2582		}
2583		fmt.Fprintf(w, "%s", h.XID)
2584	case "donk":
2585		donks, err := submitdonk(w, r)
2586		if err != nil {
2587			http.Error(w, err.Error(), http.StatusBadRequest)
2588			return
2589		}
2590		if len(donks) == 0 {
2591			http.Error(w, "missing donk", http.StatusBadRequest)
2592			return
2593		}
2594		d := donks[0]
2595		donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2596		w.Write([]byte(donkxid))
2597	case "zonkit":
2598		zonkit(w, r)
2599	case "gethonks":
2600		var honks []*Honk
2601		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2602		page := r.FormValue("page")
2603		var waitchan <-chan time.Time
2604	requery:
2605		switch page {
2606		case "atme":
2607			honks = gethonksforme(userid, wanted)
2608			honks = osmosis(honks, userid, false)
2609			menewnone(userid)
2610		case "longago":
2611			honks = gethonksfromlongago(userid, wanted)
2612			honks = osmosis(honks, userid, false)
2613		case "home":
2614			honks = gethonksforuser(userid, wanted)
2615			honks = osmosis(honks, userid, true)
2616		case "myhonks":
2617			honks = gethonksbyuser(u.Username, true, wanted)
2618			honks = osmosis(honks, userid, true)
2619		default:
2620			http.Error(w, "unknown page", http.StatusNotFound)
2621			return
2622		}
2623		if len(honks) == 0 && wait > 0 {
2624			if waitchan == nil {
2625				waitchan = time.After(time.Duration(wait) * time.Second)
2626			}
2627			select {
2628			case <-honkline:
2629				goto requery
2630			case <-waitchan:
2631			}
2632		}
2633		reverbolate(userid, honks)
2634		j := junk.New()
2635		j["honks"] = honks
2636		j.Write(w)
2637	case "sendactivity":
2638		user, _ := butwhatabout(u.Username)
2639		public := r.FormValue("public") == "1"
2640		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2641		msg := []byte(r.FormValue("msg"))
2642		for rcpt := range rcpts {
2643			go deliverate(userid, rcpt, msg)
2644		}
2645	case "gethonkers":
2646		j := junk.New()
2647		j["honkers"] = gethonkers(u.UserID)
2648		j.Write(w)
2649	case "savehonker":
2650		h := submithonker(w, r)
2651		if h == nil {
2652			return
2653		}
2654		fmt.Fprintf(w, "%d", h.ID)
2655	default:
2656		http.Error(w, "unknown action", http.StatusNotFound)
2657		return
2658	}
2659}
2660
2661func fiveoh(w http.ResponseWriter, r *http.Request) {
2662	if !develMode {
2663		return
2664	}
2665	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2666	if err != nil {
2667		elog.Printf("error opening violations! %s", err)
2668		return
2669	}
2670	defer fd.Close()
2671	io.Copy(fd, r.Body)
2672	fd.WriteString("\n")
2673}
2674
2675var endoftheworld = make(chan bool)
2676var readyalready = make(chan bool)
2677var workinprogress = 0
2678
2679func enditall() {
2680	sig := make(chan os.Signal, 1)
2681	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2682	<-sig
2683	ilog.Printf("stopping...")
2684	for i := 0; i < workinprogress; i++ {
2685		endoftheworld <- true
2686	}
2687	ilog.Printf("waiting...")
2688	for i := 0; i < workinprogress; i++ {
2689		<-readyalready
2690	}
2691	ilog.Printf("apocalypse")
2692	os.Exit(0)
2693}
2694
2695var preservehooks []func()
2696
2697func bgmonitor() {
2698	for {
2699		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2700		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2701		if err != nil {
2702			elog.Printf("error deleting old xonkers: %s", err)
2703		}
2704		zaggies.Flush()
2705		time.Sleep(50 * time.Minute)
2706	}
2707}
2708
2709func addcspheaders(next http.Handler) http.Handler {
2710	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2711		policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2712		if develMode {
2713			policy += "; report-uri /csp-violation"
2714		}
2715		w.Header().Set("Content-Security-Policy", policy)
2716		next.ServeHTTP(w, r)
2717	})
2718}
2719
2720func emuinit() {
2721	var emunames []string
2722	dir, err := os.Open(dataDir + "/emus")
2723	if err == nil {
2724		emunames, _ = dir.Readdirnames(0)
2725		dir.Close()
2726	}
2727	for _, e := range emunames {
2728		if len(e) <= 4 {
2729			continue
2730		}
2731		ext := e[len(e)-4:]
2732		emu := Emu{
2733			ID:   fmt.Sprintf("/emu/%s", e),
2734			Name: e[:len(e)-4],
2735			Type: "image/" + ext[1:],
2736		}
2737		allemus = append(allemus, emu)
2738	}
2739	sort.Slice(allemus, func(i, j int) bool {
2740		return allemus[i].Name < allemus[j].Name
2741	})
2742}
2743
2744var savedassetparams = make(map[string]string)
2745
2746func getassetparam(file string) string {
2747	if p, ok := savedassetparams[file]; ok {
2748		return p
2749	}
2750	data, err := os.ReadFile(file)
2751	if err != nil {
2752		return ""
2753	}
2754	hasher := sha512.New()
2755	hasher.Write(data)
2756
2757	return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2758}
2759
2760func serve() {
2761	db := opendatabase()
2762	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2763
2764	listener, err := openListener()
2765	if err != nil {
2766		elog.Fatal(err)
2767	}
2768	runBackendServer()
2769	go enditall()
2770	go redeliverator()
2771	go tracker()
2772	go bgmonitor()
2773	go qotd()
2774	loadLingo()
2775	emuinit()
2776
2777	readviews = templates.Load(develMode,
2778		viewDir+"/views/honkpage.html",
2779		viewDir+"/views/honkfrags.html",
2780		viewDir+"/views/honkers.html",
2781		viewDir+"/views/chatter.html",
2782		viewDir+"/views/hfcs.html",
2783		viewDir+"/views/combos.html",
2784		viewDir+"/views/honkform.html",
2785		viewDir+"/views/honk.html",
2786		viewDir+"/views/account.html",
2787		viewDir+"/views/about.html",
2788		viewDir+"/views/funzone.html",
2789		viewDir+"/views/login.html",
2790		viewDir+"/views/xzone.html",
2791		viewDir+"/views/msg.html",
2792		viewDir+"/views/header.html",
2793		viewDir+"/views/onts.html",
2794		viewDir+"/views/emus.html",
2795		viewDir+"/views/honkpage.js",
2796	)
2797	if !develMode {
2798		assets := []string{
2799			viewDir + "/views/style.css",
2800			dataDir + "/views/local.css",
2801			viewDir + "/views/honkpage.js",
2802			viewDir + "/views/misc.js",
2803			dataDir + "/views/local.js",
2804		}
2805		for _, s := range assets {
2806			savedassetparams[s] = getassetparam(s)
2807		}
2808		loadAvatarColors()
2809	}
2810
2811	for _, h := range preservehooks {
2812		h()
2813	}
2814
2815	mux := mux.NewRouter()
2816	mux.Use(addcspheaders)
2817	mux.Use(login.Checker)
2818
2819	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2820
2821	posters := mux.Methods("POST").Subrouter()
2822	getters := mux.Methods("GET").Subrouter()
2823
2824	getters.HandleFunc("/", homepage)
2825	getters.HandleFunc("/home", homepage)
2826	getters.HandleFunc("/front", homepage)
2827	getters.HandleFunc("/events", homepage)
2828	getters.HandleFunc("/robots.txt", nomoroboto)
2829	getters.HandleFunc("/rss", showrss)
2830	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2831	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2832	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2833	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2834	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2835	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2836	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2837	getters.HandleFunc("/a", avatate)
2838	getters.HandleFunc("/o", thelistingoftheontologies)
2839	getters.HandleFunc("/o/{name:.+}", showontology)
2840	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2841	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2842	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2843	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2844
2845	getters.HandleFunc("/flag/{code:.+}", showflag)
2846
2847	getters.HandleFunc("/server", serveractor)
2848	posters.HandleFunc("/server/inbox", serverinbox)
2849	posters.HandleFunc("/inbox", serverinbox)
2850
2851	posters.HandleFunc("/csp-violation", fiveoh)
2852
2853	getters.HandleFunc("/style.css", serveviewasset)
2854	getters.HandleFunc("/honkpage.js", serveviewasset)
2855	getters.HandleFunc("/misc.js", serveviewasset)
2856	getters.HandleFunc("/local.css", servedataasset)
2857	getters.HandleFunc("/local.js", servedataasset)
2858	getters.HandleFunc("/icon.png", servedataasset)
2859	getters.HandleFunc("/favicon.ico", servedataasset)
2860
2861	getters.HandleFunc("/about", servehtml)
2862	getters.HandleFunc("/login", servehtml)
2863	posters.HandleFunc("/dologin", login.LoginFunc)
2864	getters.HandleFunc("/logout", login.LogoutFunc)
2865	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2866
2867	loggedin := mux.NewRoute().Subrouter()
2868	loggedin.Use(login.Required)
2869	loggedin.HandleFunc("/first", homepage)
2870	loggedin.HandleFunc("/chatter", showchatter)
2871	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2872	loggedin.HandleFunc("/saved", homepage)
2873	loggedin.HandleFunc("/account", accountpage)
2874	loggedin.HandleFunc("/funzone", showfunzone)
2875	loggedin.HandleFunc("/chpass", dochpass)
2876	loggedin.HandleFunc("/atme", homepage)
2877	loggedin.HandleFunc("/longago", homepage)
2878	loggedin.HandleFunc("/hfcs", hfcspage)
2879	loggedin.HandleFunc("/xzone", xzone)
2880	loggedin.HandleFunc("/newhonk", newhonkpage)
2881	loggedin.HandleFunc("/edit", edithonkpage)
2882	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2883	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2884	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2885	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2886	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2887	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2888	loggedin.HandleFunc("/honkers", showhonkers)
2889	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2890	loggedin.HandleFunc("/h", showhonker)
2891	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2892	loggedin.HandleFunc("/c", showcombos)
2893	loggedin.HandleFunc("/t", showconvoy)
2894	loggedin.HandleFunc("/q", showsearch)
2895	loggedin.HandleFunc("/hydra", webhydra)
2896	loggedin.HandleFunc("/emus", showemus)
2897	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2898
2899	err = http.Serve(listener, mux)
2900	if err != nil {
2901		elog.Fatal(err)
2902	}
2903}