all repos — honk @ 8bbde5f9fd7dba1567b32b7ca738c4d67a626b08

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