all repos — honk @ ca5c01f5674ed4f0d715148140623e518752118c

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