all repos — honk @ a730f32767264505de21afb8d92e0275246ae4db

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