all repos — honk @ e7b725fabdc66d45df72fe053e0dbcef55aa2c27

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