all repos — honk @ 40aeb02291615dc20350a84224c43813ce254c12

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