all repos — honk @ 1a4b39971cf83bd2acb09ceac14fd975da9f1d7d

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("omitimages") == "omitimages" {
1115		options.OmitImages = true
1116	} else {
1117		options.OmitImages = false
1118	}
1119	if r.FormValue("mentionall") == "mentionall" {
1120		options.MentionAll = true
1121	} else {
1122		options.MentionAll = false
1123	}
1124	if r.FormValue("maps") == "apple" {
1125		options.MapLink = "apple"
1126	} else {
1127		options.MapLink = ""
1128	}
1129	options.Reaction = r.FormValue("reaction")
1130
1131	sendupdate := false
1132	ava := re_avatar.FindString(whatabout)
1133	if ava != "" {
1134		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1135		ava = ava[7:]
1136		if ava[0] == ' ' {
1137			ava = ava[1:]
1138		}
1139		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1140	}
1141	if ava != options.Avatar {
1142		options.Avatar = ava
1143		sendupdate = true
1144	}
1145	ban := re_banner.FindString(whatabout)
1146	if ban != "" {
1147		whatabout = re_banner.ReplaceAllString(whatabout, "")
1148		ban = ban[7:]
1149		if ban[0] == ' ' {
1150			ban = ban[1:]
1151		}
1152		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1153	}
1154	if ban != options.Banner {
1155		options.Banner = ban
1156		sendupdate = true
1157	}
1158	whatabout = strings.TrimSpace(whatabout)
1159	if whatabout != user.About {
1160		sendupdate = true
1161	}
1162	j, err := jsonify(options)
1163	if err == nil {
1164		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1165	}
1166	if err != nil {
1167		elog.Printf("error bouting what: %s", err)
1168	}
1169	somenamedusers.Clear(u.Username)
1170	somenumberedusers.Clear(u.UserID)
1171	oldjonkers.Clear(u.Username)
1172
1173	if sendupdate {
1174		updateMe(u.Username)
1175	}
1176
1177	http.Redirect(w, r, "/account", http.StatusSeeOther)
1178}
1179
1180func bonkit(xid string, user *WhatAbout) {
1181	dlog.Printf("bonking %s", xid)
1182
1183	xonk := getxonk(user.ID, xid)
1184	if xonk == nil {
1185		return
1186	}
1187	if !xonk.Public {
1188		return
1189	}
1190	if xonk.IsBonked() {
1191		return
1192	}
1193	donksforhonks([]*Honk{xonk})
1194
1195	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1196	if err != nil {
1197		elog.Printf("error acking bonk: %s", err)
1198	}
1199
1200	oonker := xonk.Oonker
1201	if oonker == "" {
1202		oonker = xonk.Honker
1203	}
1204	dt := time.Now().UTC()
1205	bonk := &Honk{
1206		UserID:   user.ID,
1207		Username: user.Name,
1208		What:     "bonk",
1209		Honker:   user.URL,
1210		Oonker:   oonker,
1211		XID:      xonk.XID,
1212		RID:      xonk.RID,
1213		Noise:    xonk.Noise,
1214		Precis:   xonk.Precis,
1215		URL:      xonk.URL,
1216		Date:     dt,
1217		Donks:    xonk.Donks,
1218		Whofore:  2,
1219		Convoy:   xonk.Convoy,
1220		Audience: []string{thewholeworld, oonker},
1221		Public:   true,
1222		Format:   xonk.Format,
1223		Place:    xonk.Place,
1224		Onts:     xonk.Onts,
1225		Time:     xonk.Time,
1226	}
1227
1228	err = savehonk(bonk)
1229	if err != nil {
1230		elog.Printf("uh oh")
1231		return
1232	}
1233
1234	go honkworldwide(user, bonk)
1235}
1236
1237func submitbonk(w http.ResponseWriter, r *http.Request) {
1238	xid := r.FormValue("xid")
1239	userinfo := login.GetUserInfo(r)
1240	user, _ := butwhatabout(userinfo.Username)
1241
1242	bonkit(xid, user)
1243
1244	if r.FormValue("js") != "1" {
1245		templinfo := getInfo(r)
1246		templinfo["ServerMessage"] = "Bonked!"
1247		err := readviews.Execute(w, "msg.html", templinfo)
1248		if err != nil {
1249			elog.Print(err)
1250		}
1251	}
1252}
1253
1254func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1255	zonk := &Honk{
1256		What:     what,
1257		XID:      xonk.XID,
1258		Date:     time.Now().UTC(),
1259		Audience: oneofakind(xonk.Audience),
1260		Noise:    aux,
1261	}
1262	zonk.Public = loudandproud(zonk.Audience)
1263
1264	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1265	go honkworldwide(user, zonk)
1266}
1267
1268func zonkit(w http.ResponseWriter, r *http.Request) {
1269	wherefore := r.FormValue("wherefore")
1270	what := r.FormValue("what")
1271	userinfo := login.GetUserInfo(r)
1272	user, _ := butwhatabout(userinfo.Username)
1273
1274	if wherefore == "save" {
1275		xonk := getxonk(userinfo.UserID, what)
1276		if xonk != nil {
1277			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1278			if err != nil {
1279				elog.Printf("error saving: %s", err)
1280			}
1281		}
1282		return
1283	}
1284
1285	if wherefore == "unsave" {
1286		xonk := getxonk(userinfo.UserID, what)
1287		if xonk != nil {
1288			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1289			if err != nil {
1290				elog.Printf("error unsaving: %s", err)
1291			}
1292		}
1293		return
1294	}
1295
1296	if wherefore == "react" {
1297		reaction := user.Options.Reaction
1298		if r2 := r.FormValue("reaction"); r2 != "" {
1299			reaction = r2
1300		}
1301		if reaction == "none" {
1302			return
1303		}
1304		xonk := getxonk(userinfo.UserID, what)
1305		if xonk != nil {
1306			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1307			if err != nil {
1308				elog.Printf("error saving: %s", err)
1309			}
1310			sendzonkofsorts(xonk, user, "react", reaction)
1311		}
1312		return
1313	}
1314
1315	if wherefore == "wonk" {
1316		xonk := getxonk(userinfo.UserID, what)
1317		if xonk != nil {
1318			_, err := stmtUpdateFlags.Exec(flagIsWonked, xonk.ID)
1319			if err == nil {
1320				guesses := r.FormValue("guesses")
1321				_, err = stmtSaveMeta.Exec(xonk.ID, "guesses", guesses)
1322			}
1323			if err != nil {
1324				elog.Printf("error saving: %s", err)
1325			}
1326		}
1327		return
1328	}
1329
1330	// my hammer is too big, oh well
1331	defer oldjonks.Flush()
1332
1333	if wherefore == "ack" {
1334		xonk := getxonk(userinfo.UserID, what)
1335		if xonk != nil && !xonk.IsAcked() {
1336			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1337			if err != nil {
1338				elog.Printf("error acking: %s", err)
1339			}
1340			sendzonkofsorts(xonk, user, "ack", "")
1341		}
1342		return
1343	}
1344
1345	if wherefore == "deack" {
1346		xonk := getxonk(userinfo.UserID, what)
1347		if xonk != nil && xonk.IsAcked() {
1348			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1349			if err != nil {
1350				elog.Printf("error deacking: %s", err)
1351			}
1352			sendzonkofsorts(xonk, user, "deack", "")
1353		}
1354		return
1355	}
1356
1357	if wherefore == "bonk" {
1358		user, _ := butwhatabout(userinfo.Username)
1359		bonkit(what, user)
1360		return
1361	}
1362
1363	if wherefore == "unbonk" {
1364		xonk := getbonk(userinfo.UserID, what)
1365		if xonk != nil {
1366			deletehonk(xonk.ID)
1367			xonk = getxonk(userinfo.UserID, what)
1368			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1369			if err != nil {
1370				elog.Printf("error unbonking: %s", err)
1371			}
1372			sendzonkofsorts(xonk, user, "unbonk", "")
1373		}
1374		return
1375	}
1376
1377	if wherefore == "untag" {
1378		xonk := getxonk(userinfo.UserID, what)
1379		if xonk != nil {
1380			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1381			if err != nil {
1382				elog.Printf("error untagging: %s", err)
1383			}
1384		}
1385		var badparents map[string]bool
1386		untagged.GetAndLock(userinfo.UserID, &badparents)
1387		badparents[what] = true
1388		untagged.Unlock()
1389		return
1390	}
1391
1392	ilog.Printf("zonking %s %s", wherefore, what)
1393	if wherefore == "zonk" {
1394		xonk := getxonk(userinfo.UserID, what)
1395		if xonk != nil {
1396			deletehonk(xonk.ID)
1397			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1398				sendzonkofsorts(xonk, user, "zonk", "")
1399			}
1400		}
1401	}
1402	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1403	if err != nil {
1404		elog.Printf("error saving zonker: %s", err)
1405		return
1406	}
1407}
1408
1409func edithonkpage(w http.ResponseWriter, r *http.Request) {
1410	u := login.GetUserInfo(r)
1411	user, _ := butwhatabout(u.Username)
1412	xid := r.FormValue("xid")
1413	honk := getxonk(u.UserID, xid)
1414	if !canedithonk(user, honk) {
1415		http.Error(w, "no editing that please", http.StatusInternalServerError)
1416		return
1417	}
1418
1419	noise := honk.Noise
1420
1421	honks := []*Honk{honk}
1422	donksforhonks(honks)
1423	reverbolate(u.UserID, honks)
1424	templinfo := getInfo(r)
1425	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1426	templinfo["Honks"] = honks
1427	templinfo["MapLink"] = getmaplink(u)
1428	templinfo["Noise"] = noise
1429	templinfo["SavedPlace"] = honk.Place
1430	if tm := honk.Time; tm != nil {
1431		templinfo["ShowTime"] = ";"
1432		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1433		if tm.Duration != 0 {
1434			templinfo["Duration"] = tm.Duration
1435		}
1436	}
1437	templinfo["ServerMessage"] = "honk edit 2"
1438	templinfo["IsPreview"] = true
1439	templinfo["UpdateXID"] = honk.XID
1440	if len(honk.Donks) > 0 {
1441		templinfo["SavedFile"] = honk.Donks[0].XID
1442	}
1443	err := readviews.Execute(w, "honkpage.html", templinfo)
1444	if err != nil {
1445		elog.Print(err)
1446	}
1447}
1448
1449func newhonkpage(w http.ResponseWriter, r *http.Request) {
1450	u := login.GetUserInfo(r)
1451	rid := r.FormValue("rid")
1452	noise := ""
1453
1454	xonk := getxonk(u.UserID, rid)
1455	if xonk != nil {
1456		_, replto := handles(xonk.Honker)
1457		if replto != "" {
1458			noise = "@" + replto + " "
1459		}
1460	}
1461
1462	templinfo := getInfo(r)
1463	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1464	templinfo["InReplyTo"] = rid
1465	templinfo["Noise"] = noise
1466	templinfo["ServerMessage"] = "compose honk"
1467	templinfo["IsPreview"] = true
1468	err := readviews.Execute(w, "honkpage.html", templinfo)
1469	if err != nil {
1470		elog.Print(err)
1471	}
1472}
1473
1474func canedithonk(user *WhatAbout, honk *Honk) bool {
1475	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1476		return false
1477	}
1478	return true
1479}
1480
1481func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1482	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1483		return nil, nil
1484	}
1485	file, filehdr, err := r.FormFile("donk")
1486	if err != nil {
1487		if err == http.ErrMissingFile {
1488			return nil, nil
1489		}
1490		elog.Printf("error reading donk: %s", err)
1491		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1492		return nil, err
1493	}
1494	var buf bytes.Buffer
1495	io.Copy(&buf, file)
1496	file.Close()
1497	data := buf.Bytes()
1498	var media, name string
1499	img, err := shrinkit(data)
1500	if err == nil {
1501		data = img.Data
1502		format := img.Format
1503		media = "image/" + format
1504		if format == "jpeg" {
1505			format = "jpg"
1506		}
1507		name = xfiltrate() + "." + format
1508	} else {
1509		ct := http.DetectContentType(data)
1510		switch ct {
1511		case "application/pdf":
1512			maxsize := 10000000
1513			if len(data) > maxsize {
1514				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1515				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1516				return nil, err
1517			}
1518			media = ct
1519			name = filehdr.Filename
1520			if name == "" {
1521				name = xfiltrate() + ".pdf"
1522			}
1523		default:
1524			maxsize := 100000
1525			if len(data) > maxsize {
1526				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1527				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1528				return nil, err
1529			}
1530			for i := 0; i < len(data); i++ {
1531				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1532					ilog.Printf("bad image: %s not text: %d", err, data[i])
1533					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1534					return nil, err
1535				}
1536			}
1537			media = "text/plain"
1538			name = filehdr.Filename
1539			if name == "" {
1540				name = xfiltrate() + ".txt"
1541			}
1542		}
1543	}
1544	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1545	if desc == "" {
1546		desc = name
1547	}
1548	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1549	if err != nil {
1550		elog.Printf("unable to save image: %s", err)
1551		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1552		return nil, err
1553	}
1554	d := &Donk{
1555		FileID: fileid,
1556		XID:    xid,
1557		Desc:   desc,
1558		Local:  true,
1559	}
1560	return d, nil
1561}
1562
1563func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1564	h := submithonk(w, r)
1565	if h == nil {
1566		return
1567	}
1568	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1569}
1570
1571// what a hot mess this function is
1572func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1573	rid := r.FormValue("rid")
1574	noise := r.FormValue("noise")
1575	format := r.FormValue("format")
1576	if format == "" {
1577		format = "markdown"
1578	}
1579	if !(format == "markdown" || format == "html") {
1580		http.Error(w, "unknown format", 500)
1581		return nil
1582	}
1583
1584	userinfo := login.GetUserInfo(r)
1585	user, _ := butwhatabout(userinfo.Username)
1586
1587	dt := time.Now().UTC()
1588	updatexid := r.FormValue("updatexid")
1589	var honk *Honk
1590	if updatexid != "" {
1591		honk = getxonk(userinfo.UserID, updatexid)
1592		if !canedithonk(user, honk) {
1593			http.Error(w, "no editing that please", http.StatusInternalServerError)
1594			return nil
1595		}
1596		honk.Date = dt
1597		honk.What = "update"
1598		honk.Format = format
1599	} else {
1600		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1601		what := "honk"
1602		if rid != "" {
1603			what = "tonk"
1604		}
1605		wonkles := r.FormValue("wonkles")
1606		if wonkles != "" {
1607			what = "wonk"
1608		}
1609		honk = &Honk{
1610			UserID:   userinfo.UserID,
1611			Username: userinfo.Username,
1612			What:     what,
1613			Honker:   user.URL,
1614			XID:      xid,
1615			Date:     dt,
1616			Format:   format,
1617			Wonkles:  wonkles,
1618		}
1619	}
1620
1621	noise = strings.Replace(noise, "\r", "", -1)
1622	noise = quickrename(noise, userinfo.UserID)
1623	noise = hooterize(noise)
1624	honk.Noise = noise
1625	translate(honk)
1626
1627	var convoy string
1628	if rid != "" {
1629		xonk := getxonk(userinfo.UserID, rid)
1630		if xonk == nil {
1631			http.Error(w, "replyto disappeared", http.StatusNotFound)
1632			return nil
1633		}
1634		if xonk.Public {
1635			honk.Audience = append(honk.Audience, xonk.Audience...)
1636		}
1637		convoy = xonk.Convoy
1638		for i, a := range honk.Audience {
1639			if a == thewholeworld {
1640				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1641				break
1642			}
1643		}
1644		honk.RID = rid
1645		if xonk.Precis != "" && honk.Precis == "" {
1646			honk.Precis = xonk.Precis
1647			if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1648				honk.Precis = "re: " + honk.Precis
1649			}
1650		}
1651	} else {
1652		honk.Audience = []string{thewholeworld}
1653	}
1654	if honk.Noise != "" && honk.Noise[0] == '@' {
1655		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1656	} else {
1657		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1658	}
1659
1660	if convoy == "" {
1661		convoy = "data:,electrichonkytonk-" + xfiltrate()
1662	}
1663	butnottooloud(honk.Audience)
1664	honk.Audience = oneofakind(honk.Audience)
1665	if len(honk.Audience) == 0 {
1666		ilog.Printf("honk to nowhere")
1667		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1668		return nil
1669	}
1670	honk.Public = loudandproud(honk.Audience)
1671	honk.Convoy = convoy
1672
1673	donkxid := r.FormValue("donkxid")
1674	if donkxid == "" {
1675		d, err := submitdonk(w, r)
1676		if err != nil && err != http.ErrMissingFile {
1677			return nil
1678		}
1679		if d != nil {
1680			honk.Donks = append(honk.Donks, d)
1681			donkxid = d.XID
1682		}
1683	} else {
1684		xid := donkxid
1685		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1686		donk := finddonk(url)
1687		if donk != nil {
1688			honk.Donks = append(honk.Donks, donk)
1689		} else {
1690			ilog.Printf("can't find file: %s", xid)
1691		}
1692	}
1693	memetize(honk)
1694	imaginate(honk)
1695
1696	placename := strings.TrimSpace(r.FormValue("placename"))
1697	placelat := strings.TrimSpace(r.FormValue("placelat"))
1698	placelong := strings.TrimSpace(r.FormValue("placelong"))
1699	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1700	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1701		p := new(Place)
1702		p.Name = placename
1703		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1704		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1705		p.Url = placeurl
1706		honk.Place = p
1707	}
1708	timestart := strings.TrimSpace(r.FormValue("timestart"))
1709	if timestart != "" {
1710		t := new(Time)
1711		now := time.Now().Local()
1712		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1713			start, err := time.ParseInLocation(layout, timestart, now.Location())
1714			if err == nil {
1715				if start.Year() == 0 {
1716					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1717				}
1718				t.StartTime = start
1719				break
1720			}
1721		}
1722		timeend := r.FormValue("timeend")
1723		dur := parseDuration(timeend)
1724		if dur != 0 {
1725			t.Duration = Duration(dur)
1726		}
1727		if !t.StartTime.IsZero() {
1728			honk.What = "event"
1729			honk.Time = t
1730		}
1731	}
1732
1733	if honk.Public {
1734		honk.Whofore = 2
1735	} else {
1736		honk.Whofore = 3
1737	}
1738
1739	// back to markdown
1740	honk.Noise = noise
1741
1742	if r.FormValue("preview") == "preview" {
1743		honks := []*Honk{honk}
1744		reverbolate(userinfo.UserID, honks)
1745		templinfo := getInfo(r)
1746		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1747		templinfo["Honks"] = honks
1748		templinfo["MapLink"] = getmaplink(userinfo)
1749		templinfo["InReplyTo"] = r.FormValue("rid")
1750		templinfo["Noise"] = r.FormValue("noise")
1751		templinfo["SavedFile"] = donkxid
1752		if tm := honk.Time; tm != nil {
1753			templinfo["ShowTime"] = ";"
1754			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1755			if tm.Duration != 0 {
1756				templinfo["Duration"] = tm.Duration
1757			}
1758		}
1759		templinfo["IsPreview"] = true
1760		templinfo["UpdateXID"] = updatexid
1761		templinfo["ServerMessage"] = "honk preview"
1762		err := readviews.Execute(w, "honkpage.html", templinfo)
1763		if err != nil {
1764			elog.Print(err)
1765		}
1766		return nil
1767	}
1768
1769	if updatexid != "" {
1770		updatehonk(honk)
1771		oldjonks.Clear(honk.XID)
1772	} else {
1773		err := savehonk(honk)
1774		if err != nil {
1775			elog.Printf("uh oh")
1776			return nil
1777		}
1778	}
1779
1780	// reload for consistency
1781	honk.Donks = nil
1782	donksforhonks([]*Honk{honk})
1783
1784	go honkworldwide(user, honk)
1785
1786	return honk
1787}
1788
1789func showhonkers(w http.ResponseWriter, r *http.Request) {
1790	userinfo := login.GetUserInfo(r)
1791	templinfo := getInfo(r)
1792	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1793	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1794	err := readviews.Execute(w, "honkers.html", templinfo)
1795	if err != nil {
1796		elog.Print(err)
1797	}
1798}
1799
1800func showchatter(w http.ResponseWriter, r *http.Request) {
1801	u := login.GetUserInfo(r)
1802	chatnewnone(u.UserID)
1803	chatter := loadchatter(u.UserID)
1804	for _, chat := range chatter {
1805		for _, ch := range chat.Chonks {
1806			filterchonk(ch)
1807		}
1808	}
1809
1810	templinfo := getInfo(r)
1811	templinfo["Chatter"] = chatter
1812	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1813	err := readviews.Execute(w, "chatter.html", templinfo)
1814	if err != nil {
1815		elog.Print(err)
1816	}
1817}
1818
1819func submitchonk(w http.ResponseWriter, r *http.Request) {
1820	u := login.GetUserInfo(r)
1821	user, _ := butwhatabout(u.Username)
1822	noise := r.FormValue("noise")
1823	target := r.FormValue("target")
1824	format := "markdown"
1825	dt := time.Now().UTC()
1826	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1827
1828	if !strings.HasPrefix(target, "https://") {
1829		target = fullname(target, u.UserID)
1830	}
1831	if target == "" {
1832		http.Error(w, "who is that?", http.StatusInternalServerError)
1833		return
1834	}
1835	ch := Chonk{
1836		UserID: u.UserID,
1837		XID:    xid,
1838		Who:    user.URL,
1839		Target: target,
1840		Date:   dt,
1841		Noise:  noise,
1842		Format: format,
1843	}
1844	d, err := submitdonk(w, r)
1845	if err != nil && err != http.ErrMissingFile {
1846		return
1847	}
1848	if d != nil {
1849		ch.Donks = append(ch.Donks, d)
1850	}
1851
1852	translatechonk(&ch)
1853	savechonk(&ch)
1854	// reload for consistency
1855	ch.Donks = nil
1856	donksforchonks([]*Chonk{&ch})
1857	go sendchonk(user, &ch)
1858
1859	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1860}
1861
1862var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1863	honkers := gethonkers(userid)
1864	var combos []string
1865	for _, h := range honkers {
1866		combos = append(combos, h.Combos...)
1867	}
1868	for i, c := range combos {
1869		if c == "-" {
1870			combos[i] = ""
1871		}
1872	}
1873	combos = oneofakind(combos)
1874	sort.Strings(combos)
1875	return combos, true
1876}, Invalidator: &honkerinvalidator})
1877
1878func showcombos(w http.ResponseWriter, r *http.Request) {
1879	userinfo := login.GetUserInfo(r)
1880	var combos []string
1881	combocache.Get(userinfo.UserID, &combos)
1882	templinfo := getInfo(r)
1883	err := readviews.Execute(w, "combos.html", templinfo)
1884	if err != nil {
1885		elog.Print(err)
1886	}
1887}
1888
1889func submithonker(w http.ResponseWriter, r *http.Request) {
1890	u := login.GetUserInfo(r)
1891	user, _ := butwhatabout(u.Username)
1892	name := strings.TrimSpace(r.FormValue("name"))
1893	url := strings.TrimSpace(r.FormValue("url"))
1894	peep := r.FormValue("peep")
1895	combos := strings.TrimSpace(r.FormValue("combos"))
1896	combos = " " + combos + " "
1897	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1898
1899	re_namecheck := regexp.MustCompile("[\\pL[:digit:]_.-]+")
1900	if name != "" && !re_namecheck.MatchString(name) {
1901		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
1902		return
1903	}
1904
1905	var meta HonkerMeta
1906	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1907	mj, _ := jsonify(&meta)
1908
1909	defer honkerinvalidator.Clear(u.UserID)
1910
1911	if honkerid > 0 {
1912		if r.FormValue("delete") == "delete" {
1913			unfollowyou(user, honkerid)
1914			stmtDeleteHonker.Exec(honkerid)
1915			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1916			return
1917		}
1918		if r.FormValue("unsub") == "unsub" {
1919			unfollowyou(user, honkerid)
1920		}
1921		if r.FormValue("sub") == "sub" {
1922			followyou(user, honkerid)
1923		}
1924		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1925		if err != nil {
1926			elog.Printf("update honker err: %s", err)
1927			return
1928		}
1929		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1930		return
1931	}
1932
1933	if url == "" {
1934		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1935		return
1936	}
1937
1938	flavor := "presub"
1939	if peep == "peep" {
1940		flavor = "peep"
1941	}
1942
1943	err := savehonker(user, url, name, flavor, combos, mj)
1944	if err != nil {
1945		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
1946		return
1947	}
1948
1949	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1950}
1951
1952func hfcspage(w http.ResponseWriter, r *http.Request) {
1953	userinfo := login.GetUserInfo(r)
1954
1955	filters := getfilters(userinfo.UserID, filtAny)
1956
1957	templinfo := getInfo(r)
1958	templinfo["Filters"] = filters
1959	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1960	err := readviews.Execute(w, "hfcs.html", templinfo)
1961	if err != nil {
1962		elog.Print(err)
1963	}
1964}
1965
1966func savehfcs(w http.ResponseWriter, r *http.Request) {
1967	userinfo := login.GetUserInfo(r)
1968	itsok := r.FormValue("itsok")
1969	if itsok == "iforgiveyou" {
1970		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1971		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1972		if err != nil {
1973			elog.Printf("error deleting filter: %s", err)
1974		}
1975		filtInvalidator.Clear(userinfo.UserID)
1976		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1977		return
1978	}
1979
1980	filt := new(Filter)
1981	filt.Name = strings.TrimSpace(r.FormValue("name"))
1982	filt.Date = time.Now().UTC()
1983	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1984	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1985	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1986	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1987	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1988	filt.Reject = r.FormValue("doreject") == "yes"
1989	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1990	filt.Hide = r.FormValue("dohide") == "yes"
1991	filt.Collapse = r.FormValue("docollapse") == "yes"
1992	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1993	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1994	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1995		filt.Expiration = time.Now().UTC().Add(dur)
1996	}
1997	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
1998
1999	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2000		ilog.Printf("blank filter")
2001		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2002		return
2003	}
2004
2005	j, err := jsonify(filt)
2006	if err == nil {
2007		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2008	}
2009	if err != nil {
2010		elog.Printf("error saving filter: %s", err)
2011	}
2012
2013	filtInvalidator.Clear(userinfo.UserID)
2014	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2015}
2016
2017func accountpage(w http.ResponseWriter, r *http.Request) {
2018	u := login.GetUserInfo(r)
2019	user, _ := butwhatabout(u.Username)
2020	templinfo := getInfo(r)
2021	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2022	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2023	templinfo["User"] = user
2024	about := user.About
2025	if ava := user.Options.Avatar; ava != "" {
2026		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2027	}
2028	if ban := user.Options.Banner; ban != "" {
2029		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2030	}
2031	templinfo["WhatAbout"] = about
2032	err := readviews.Execute(w, "account.html", templinfo)
2033	if err != nil {
2034		elog.Print(err)
2035	}
2036}
2037
2038func dochpass(w http.ResponseWriter, r *http.Request) {
2039	err := login.ChangePassword(w, r)
2040	if err != nil {
2041		elog.Printf("error changing password: %s", err)
2042	}
2043	http.Redirect(w, r, "/account", http.StatusSeeOther)
2044}
2045
2046func fingerlicker(w http.ResponseWriter, r *http.Request) {
2047	orig := r.FormValue("resource")
2048
2049	dlog.Printf("finger lick: %s", orig)
2050
2051	if strings.HasPrefix(orig, "acct:") {
2052		orig = orig[5:]
2053	}
2054
2055	name := orig
2056	idx := strings.LastIndexByte(name, '/')
2057	if idx != -1 {
2058		name = name[idx+1:]
2059		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2060			ilog.Printf("foreign request rejected")
2061			name = ""
2062		}
2063	} else {
2064		idx = strings.IndexByte(name, '@')
2065		if idx != -1 {
2066			name = name[:idx]
2067			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2068				ilog.Printf("foreign request rejected")
2069				name = ""
2070			}
2071		}
2072	}
2073	user, err := butwhatabout(name)
2074	if err != nil {
2075		http.NotFound(w, r)
2076		return
2077	}
2078	if stealthmode(user.ID, r) {
2079		http.NotFound(w, r)
2080		return
2081	}
2082
2083	j := junk.New()
2084	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2085	j["aliases"] = []string{user.URL}
2086	l := junk.New()
2087	l["rel"] = "self"
2088	l["type"] = `application/activity+json`
2089	l["href"] = user.URL
2090	j["links"] = []junk.Junk{l}
2091
2092	w.Header().Set("Content-Type", "application/jrd+json")
2093	j.Write(w)
2094}
2095
2096func somedays() string {
2097	secs := 432000 + notrand.Int63n(432000)
2098	return fmt.Sprintf("%d", secs)
2099}
2100
2101func avatate(w http.ResponseWriter, r *http.Request) {
2102	if develMode {
2103		loadAvatarColors()
2104	}
2105	n := r.FormValue("a")
2106	a := genAvatar(n)
2107	if !develMode {
2108		w.Header().Set("Cache-Control", "max-age="+somedays())
2109	}
2110	w.Write(a)
2111}
2112
2113func serveviewasset(w http.ResponseWriter, r *http.Request) {
2114	serveasset(w, r, viewDir)
2115}
2116func servedataasset(w http.ResponseWriter, r *http.Request) {
2117	if r.URL.Path == "/favicon.ico" {
2118		r.URL.Path = "/icon.png"
2119	}
2120	serveasset(w, r, dataDir)
2121}
2122
2123func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2124	if !develMode {
2125		w.Header().Set("Cache-Control", "max-age=7776000")
2126	}
2127	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2128}
2129func servehelp(w http.ResponseWriter, r *http.Request) {
2130	name := mux.Vars(r)["name"]
2131	if !develMode {
2132		w.Header().Set("Cache-Control", "max-age=3600")
2133	}
2134	http.ServeFile(w, r, viewDir+"/docs/"+name)
2135}
2136func servehtml(w http.ResponseWriter, r *http.Request) {
2137	u := login.GetUserInfo(r)
2138	templinfo := getInfo(r)
2139	templinfo["AboutMsg"] = aboutMsg
2140	templinfo["LoginMsg"] = loginMsg
2141	templinfo["HonkVersion"] = softwareVersion
2142	if r.URL.Path == "/about" {
2143		templinfo["Sensors"] = getSensors()
2144	}
2145	if u == nil && !develMode {
2146		w.Header().Set("Cache-Control", "max-age=60")
2147	}
2148	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2149	if err != nil {
2150		elog.Print(err)
2151	}
2152}
2153func serveemu(w http.ResponseWriter, r *http.Request) {
2154	emu := mux.Vars(r)["emu"]
2155
2156	w.Header().Set("Cache-Control", "max-age="+somedays())
2157	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2158}
2159func servememe(w http.ResponseWriter, r *http.Request) {
2160	meme := mux.Vars(r)["meme"]
2161
2162	w.Header().Set("Cache-Control", "max-age="+somedays())
2163	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2164}
2165
2166func servefile(w http.ResponseWriter, r *http.Request) {
2167	xid := mux.Vars(r)["xid"]
2168	var media string
2169	var data []byte
2170	row := stmtGetFileData.QueryRow(xid)
2171	err := row.Scan(&media, &data)
2172	if err != nil {
2173		elog.Printf("error loading file: %s", err)
2174		http.NotFound(w, r)
2175		return
2176	}
2177	w.Header().Set("Content-Type", media)
2178	w.Header().Set("X-Content-Type-Options", "nosniff")
2179	w.Header().Set("Cache-Control", "max-age="+somedays())
2180	w.Write(data)
2181}
2182
2183func nomoroboto(w http.ResponseWriter, r *http.Request) {
2184	io.WriteString(w, "User-agent: *\n")
2185	io.WriteString(w, "Disallow: /a\n")
2186	io.WriteString(w, "Disallow: /d/\n")
2187	io.WriteString(w, "Disallow: /meme/\n")
2188	io.WriteString(w, "Disallow: /o\n")
2189	io.WriteString(w, "Disallow: /o/\n")
2190	io.WriteString(w, "Disallow: /help/\n")
2191	for _, u := range allusers() {
2192		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2193	}
2194}
2195
2196type Hydration struct {
2197	Tophid    int64
2198	Srvmsg    template.HTML
2199	Honks     string
2200	MeCount   int64
2201	ChatCount int64
2202}
2203
2204func webhydra(w http.ResponseWriter, r *http.Request) {
2205	u := login.GetUserInfo(r)
2206	userid := u.UserID
2207	templinfo := getInfo(r)
2208	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2209	page := r.FormValue("page")
2210
2211	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2212
2213	var hydra Hydration
2214
2215	var honks []*Honk
2216	switch page {
2217	case "atme":
2218		honks = gethonksforme(userid, wanted)
2219		honks = osmosis(honks, userid, false)
2220		menewnone(userid)
2221		hydra.Srvmsg = "at me!"
2222	case "longago":
2223		honks = gethonksfromlongago(userid, wanted)
2224		honks = osmosis(honks, userid, false)
2225		hydra.Srvmsg = "from long ago"
2226	case "home":
2227		honks = gethonksforuser(userid, wanted)
2228		honks = osmosis(honks, userid, true)
2229		hydra.Srvmsg = serverMsg
2230	case "first":
2231		honks = gethonksforuserfirstclass(userid, wanted)
2232		honks = osmosis(honks, userid, true)
2233		hydra.Srvmsg = "first class only"
2234	case "saved":
2235		honks = getsavedhonks(userid, wanted)
2236		templinfo["PageName"] = "saved"
2237		hydra.Srvmsg = "saved honks"
2238	case "combo":
2239		c := r.FormValue("c")
2240		honks = gethonksbycombo(userid, c, wanted)
2241		honks = osmosis(honks, userid, false)
2242		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2243	case "convoy":
2244		c := r.FormValue("c")
2245		honks = gethonksbyconvoy(userid, c, wanted)
2246		honks = osmosis(honks, userid, false)
2247		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2248	case "honker":
2249		xid := r.FormValue("xid")
2250		honks = gethonksbyxonker(userid, xid, wanted)
2251		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2252			<input type="hidden" name="CSRF" value="%s">
2253			<input type="hidden" name="url" value="%s">
2254			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2255			</form>`, login.GetCSRF("submithonker", r), xid)
2256		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2257		hydra.Srvmsg = msg
2258	case "user":
2259		uname := r.FormValue("uname")
2260		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2261		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2262	default:
2263		http.NotFound(w, r)
2264	}
2265
2266	if len(honks) > 0 {
2267		hydra.Tophid = honks[0].ID
2268	} else {
2269		hydra.Tophid = wanted
2270	}
2271	reverbolate(userid, honks)
2272
2273	user, _ := butwhatabout(u.Username)
2274
2275	var buf strings.Builder
2276	templinfo["Honks"] = honks
2277	templinfo["MapLink"] = getmaplink(u)
2278	templinfo["User"], _ = butwhatabout(u.Username)
2279	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2280	if err != nil {
2281		elog.Printf("frag error: %s", err)
2282		return
2283	}
2284	hydra.Honks = buf.String()
2285	hydra.MeCount = user.Options.MeCount
2286	hydra.ChatCount = user.Options.ChatCount
2287	w.Header().Set("Content-Type", "application/json")
2288	j, _ := jsonify(&hydra)
2289	io.WriteString(w, j)
2290}
2291
2292var honkline = make(chan bool)
2293
2294func honkhonkline() {
2295	for {
2296		select {
2297		case honkline <- true:
2298		default:
2299			return
2300		}
2301	}
2302}
2303
2304func apihandler(w http.ResponseWriter, r *http.Request) {
2305	u := login.GetUserInfo(r)
2306	userid := u.UserID
2307	action := r.FormValue("action")
2308	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2309	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2310	switch action {
2311	case "honk":
2312		h := submithonk(w, r)
2313		if h == nil {
2314			return
2315		}
2316		w.Write([]byte(h.XID))
2317	case "donk":
2318		d, err := submitdonk(w, r)
2319		if err != nil {
2320			http.Error(w, err.Error(), http.StatusBadRequest)
2321			return
2322		}
2323		if d == nil {
2324			http.Error(w, "missing donk", http.StatusBadRequest)
2325			return
2326		}
2327		w.Write([]byte(d.XID))
2328	case "zonkit":
2329		zonkit(w, r)
2330	case "gethonks":
2331		var honks []*Honk
2332		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2333		page := r.FormValue("page")
2334		var waitchan <-chan time.Time
2335	requery:
2336		switch page {
2337		case "atme":
2338			honks = gethonksforme(userid, wanted)
2339			honks = osmosis(honks, userid, false)
2340			menewnone(userid)
2341		case "longago":
2342			honks = gethonksfromlongago(userid, wanted)
2343			honks = osmosis(honks, userid, false)
2344		case "home":
2345			honks = gethonksforuser(userid, wanted)
2346			honks = osmosis(honks, userid, true)
2347		case "myhonks":
2348			honks = gethonksbyuser(u.Username, true, 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, SameSiteStrict: !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}