all repos — honk @ 41deae42c872cab5b3758e610a0564a5137e8644

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