all repos — honk @ ca598399f31e6d1b408791d588048d4bac294c69

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