all repos — honk @ 864217dd3c8150e3a34ec2adff241afe12b698b4

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