all repos — honk @ 0ea1cd89cb14dffd049d5f55b0d6ef378760ccc7

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