all repos — honk @ v1.1.1

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