all repos — honk @ 960e9141ae5a1e57bb83e21e071b761650af965f

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
1773var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1774	honkers := gethonkers(userid)
1775	var combos []string
1776	for _, h := range honkers {
1777		combos = append(combos, h.Combos...)
1778	}
1779	for i, c := range combos {
1780		if c == "-" {
1781			combos[i] = ""
1782		}
1783	}
1784	combos = oneofakind(combos)
1785	sort.Strings(combos)
1786	return combos, true
1787}, Invalidator: &honkerinvalidator})
1788
1789func showcombos(w http.ResponseWriter, r *http.Request) {
1790	userinfo := login.GetUserInfo(r)
1791	var combos []string
1792	combocache.Get(userinfo.UserID, &combos)
1793	templinfo := getInfo(r)
1794	err := readviews.Execute(w, "combos.html", templinfo)
1795	if err != nil {
1796		log.Print(err)
1797	}
1798}
1799
1800func submithonker(w http.ResponseWriter, r *http.Request) {
1801	u := login.GetUserInfo(r)
1802	name := strings.TrimSpace(r.FormValue("name"))
1803	url := strings.TrimSpace(r.FormValue("url"))
1804	peep := r.FormValue("peep")
1805	combos := strings.TrimSpace(r.FormValue("combos"))
1806	combos = " " + combos + " "
1807	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1808
1809	var meta HonkerMeta
1810	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1811	mj, _ := jsonify(&meta)
1812
1813	defer honkerinvalidator.Clear(u.UserID)
1814
1815	if honkerid > 0 {
1816		goodbye := r.FormValue("goodbye")
1817		if goodbye == "F" {
1818			db := opendatabase()
1819			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1820				honkerid, u.UserID)
1821			err := row.Scan(&url)
1822			if err != nil {
1823				log.Printf("can't get honker xid: %s", err)
1824				return
1825			}
1826			log.Printf("unsubscribing from %s", url)
1827			user, _ := butwhatabout(u.Username)
1828			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1829			if err != nil {
1830				log.Printf("error updating honker: %s", err)
1831				return
1832			}
1833			go itakeitallback(user, url)
1834
1835			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1836			return
1837		}
1838		if goodbye == "X" {
1839			var owner string
1840			db := opendatabase()
1841			row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1842				honkerid, u.UserID)
1843			err := row.Scan(&url, &owner)
1844			if err != nil {
1845				log.Printf("can't get honker xid: %s", err)
1846				return
1847			}
1848			log.Printf("resubscribing to %s", url)
1849			user, _ := butwhatabout(u.Username)
1850			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1851			if err == nil {
1852				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1853			}
1854			if err != nil {
1855				log.Printf("error updating honker: %s", err)
1856				return
1857			}
1858			go subsub(user, url, owner)
1859
1860			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1861			return
1862		}
1863		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1864		if err != nil {
1865			log.Printf("update honker err: %s", err)
1866			return
1867		}
1868		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1869		return
1870	}
1871
1872	if url == "" {
1873		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1874		return
1875	}
1876
1877	flavor := "presub"
1878	if peep == "peep" {
1879		flavor = "peep"
1880	}
1881
1882	if url[0] == '#' {
1883		flavor = "peep"
1884		if name == "" {
1885			name = url
1886		}
1887		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url, mj)
1888		if err != nil {
1889			log.Print(err)
1890			return
1891		}
1892		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1893		return
1894	}
1895
1896	info, err := investigate(url)
1897	if err != nil {
1898		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1899		log.Printf("failed to investigate honker: %s", err)
1900		return
1901	}
1902	url = info.XID
1903
1904	var x string
1905	db := opendatabase()
1906	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1907	err = row.Scan(&x)
1908	if err != sql.ErrNoRows {
1909		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1910		if err != nil {
1911			log.Printf("honker scan err: %s", err)
1912		}
1913		return
1914	}
1915
1916	if name == "" {
1917		name = info.Name
1918	}
1919	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner, mj)
1920	if err != nil {
1921		log.Print(err)
1922		return
1923	}
1924	if flavor == "presub" {
1925		user, _ := butwhatabout(u.Username)
1926		go subsub(user, url, info.Owner)
1927	}
1928	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1929}
1930
1931func hfcspage(w http.ResponseWriter, r *http.Request) {
1932	userinfo := login.GetUserInfo(r)
1933
1934	filters := getfilters(userinfo.UserID, filtAny)
1935
1936	templinfo := getInfo(r)
1937	templinfo["Filters"] = filters
1938	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1939	err := readviews.Execute(w, "hfcs.html", templinfo)
1940	if err != nil {
1941		log.Print(err)
1942	}
1943}
1944
1945func savehfcs(w http.ResponseWriter, r *http.Request) {
1946	userinfo := login.GetUserInfo(r)
1947	itsok := r.FormValue("itsok")
1948	if itsok == "iforgiveyou" {
1949		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1950		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1951		if err != nil {
1952			log.Printf("error deleting filter: %s", err)
1953		}
1954		filtInvalidator.Clear(userinfo.UserID)
1955		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1956		return
1957	}
1958
1959	filt := new(Filter)
1960	filt.Name = strings.TrimSpace(r.FormValue("name"))
1961	filt.Date = time.Now().UTC()
1962	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1963	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1964	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1965	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1966	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1967	filt.Reject = r.FormValue("doreject") == "yes"
1968	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1969	filt.Hide = r.FormValue("dohide") == "yes"
1970	filt.Collapse = r.FormValue("docollapse") == "yes"
1971	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1972	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1973	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1974		filt.Expiration = time.Now().UTC().Add(dur)
1975	}
1976	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
1977
1978	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1979		log.Printf("blank filter")
1980		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1981		return
1982	}
1983
1984	j, err := jsonify(filt)
1985	if err == nil {
1986		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1987	}
1988	if err != nil {
1989		log.Printf("error saving filter: %s", err)
1990	}
1991
1992	filtInvalidator.Clear(userinfo.UserID)
1993	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1994}
1995
1996func accountpage(w http.ResponseWriter, r *http.Request) {
1997	u := login.GetUserInfo(r)
1998	user, _ := butwhatabout(u.Username)
1999	templinfo := getInfo(r)
2000	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2001	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2002	templinfo["User"] = user
2003	about := user.About
2004	if ava := user.Options.Avatar; ava != "" {
2005		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2006	}
2007	templinfo["WhatAbout"] = about
2008	err := readviews.Execute(w, "account.html", templinfo)
2009	if err != nil {
2010		log.Print(err)
2011	}
2012}
2013
2014func dochpass(w http.ResponseWriter, r *http.Request) {
2015	err := login.ChangePassword(w, r)
2016	if err != nil {
2017		log.Printf("error changing password: %s", err)
2018	}
2019	http.Redirect(w, r, "/account", http.StatusSeeOther)
2020}
2021
2022func fingerlicker(w http.ResponseWriter, r *http.Request) {
2023	orig := r.FormValue("resource")
2024
2025	log.Printf("finger lick: %s", orig)
2026
2027	if strings.HasPrefix(orig, "acct:") {
2028		orig = orig[5:]
2029	}
2030
2031	name := orig
2032	idx := strings.LastIndexByte(name, '/')
2033	if idx != -1 {
2034		name = name[idx+1:]
2035		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2036			log.Printf("foreign request rejected")
2037			name = ""
2038		}
2039	} else {
2040		idx = strings.IndexByte(name, '@')
2041		if idx != -1 {
2042			name = name[:idx]
2043			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2044				log.Printf("foreign request rejected")
2045				name = ""
2046			}
2047		}
2048	}
2049	user, err := butwhatabout(name)
2050	if err != nil {
2051		http.NotFound(w, r)
2052		return
2053	}
2054	if stealthmode(user.ID, r) {
2055		http.NotFound(w, r)
2056		return
2057	}
2058
2059	j := junk.New()
2060	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2061	j["aliases"] = []string{user.URL}
2062	l := junk.New()
2063	l["rel"] = "self"
2064	l["type"] = `application/activity+json`
2065	l["href"] = user.URL
2066	j["links"] = []junk.Junk{l}
2067
2068	w.Header().Set("Content-Type", "application/jrd+json")
2069	j.Write(w)
2070}
2071
2072func somedays() string {
2073	secs := 432000 + notrand.Int63n(432000)
2074	return fmt.Sprintf("%d", secs)
2075}
2076
2077func avatate(w http.ResponseWriter, r *http.Request) {
2078	if debugMode {
2079		loadAvatarColors()
2080	}
2081	n := r.FormValue("a")
2082	a := genAvatar(n)
2083	w.Header().Set("Cache-Control", "max-age="+somedays())
2084	w.Write(a)
2085}
2086
2087func serveasset(w http.ResponseWriter, r *http.Request) {
2088	if !debugMode {
2089		w.Header().Set("Cache-Control", "max-age=7776000")
2090	}
2091	dir := viewDir
2092	if r.URL.Path == "/local.css" {
2093		dir = dataDir
2094	}
2095	http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2096}
2097func servehelp(w http.ResponseWriter, r *http.Request) {
2098	name := mux.Vars(r)["name"]
2099	if !debugMode {
2100		w.Header().Set("Cache-Control", "max-age=3600")
2101	}
2102	http.ServeFile(w, r, viewDir+"/docs/"+name)
2103}
2104func servehtml(w http.ResponseWriter, r *http.Request) {
2105	u := login.GetUserInfo(r)
2106	templinfo := getInfo(r)
2107	templinfo["AboutMsg"] = aboutMsg
2108	templinfo["LoginMsg"] = loginMsg
2109	templinfo["HonkVersion"] = softwareVersion
2110	if r.URL.Path == "/about" {
2111		templinfo["Sensors"] = getSensors()
2112	}
2113	if u == nil && !debugMode {
2114		w.Header().Set("Cache-Control", "max-age=60")
2115	}
2116	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2117	if err != nil {
2118		log.Print(err)
2119	}
2120}
2121func serveemu(w http.ResponseWriter, r *http.Request) {
2122	emu := mux.Vars(r)["emu"]
2123
2124	w.Header().Set("Cache-Control", "max-age="+somedays())
2125	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2126}
2127func servememe(w http.ResponseWriter, r *http.Request) {
2128	meme := mux.Vars(r)["meme"]
2129
2130	w.Header().Set("Cache-Control", "max-age="+somedays())
2131	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2132}
2133
2134func servefile(w http.ResponseWriter, r *http.Request) {
2135	xid := mux.Vars(r)["xid"]
2136	var media string
2137	var data []byte
2138	row := stmtGetFileData.QueryRow(xid)
2139	err := row.Scan(&media, &data)
2140	if err != nil {
2141		log.Printf("error loading file: %s", err)
2142		http.NotFound(w, r)
2143		return
2144	}
2145	w.Header().Set("Content-Type", media)
2146	w.Header().Set("X-Content-Type-Options", "nosniff")
2147	w.Header().Set("Cache-Control", "max-age="+somedays())
2148	w.Write(data)
2149}
2150
2151func nomoroboto(w http.ResponseWriter, r *http.Request) {
2152	io.WriteString(w, "User-agent: *\n")
2153	io.WriteString(w, "Disallow: /a\n")
2154	io.WriteString(w, "Disallow: /d/\n")
2155	io.WriteString(w, "Disallow: /meme/\n")
2156	io.WriteString(w, "Disallow: /o\n")
2157	io.WriteString(w, "Disallow: /o/\n")
2158	for _, u := range allusers() {
2159		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2160	}
2161}
2162
2163func webhydra(w http.ResponseWriter, r *http.Request) {
2164	u := login.GetUserInfo(r)
2165	userid := u.UserID
2166	templinfo := getInfo(r)
2167	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2168	page := r.FormValue("page")
2169
2170	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2171
2172	var honks []*Honk
2173	switch page {
2174	case "atme":
2175		honks = gethonksforme(userid, wanted)
2176		honks = osmosis(honks, userid, false)
2177		templinfo["ServerMessage"] = "at me!"
2178	case "home":
2179		honks = gethonksforuser(userid, wanted)
2180		honks = osmosis(honks, userid, true)
2181		templinfo["ServerMessage"] = serverMsg
2182	case "first":
2183		honks = gethonksforuserfirstclass(userid, wanted)
2184		honks = osmosis(honks, userid, true)
2185		templinfo["ServerMessage"] = "first class only"
2186	case "saved":
2187		honks = getsavedhonks(userid, wanted)
2188		templinfo["PageName"] = "saved"
2189		templinfo["ServerMessage"] = "saved honks"
2190	case "combo":
2191		c := r.FormValue("c")
2192		honks = gethonksbycombo(userid, c, wanted)
2193		honks = osmosis(honks, userid, false)
2194		templinfo["ServerMessage"] = "honks by combo: " + c
2195	case "convoy":
2196		c := r.FormValue("c")
2197		honks = gethonksbyconvoy(userid, c, wanted)
2198		honks = osmosis(honks, userid, false)
2199		templinfo["ServerMessage"] = "honks in convoy: " + c
2200	case "honker":
2201		xid := r.FormValue("xid")
2202		honks = gethonksbyxonker(userid, xid, wanted)
2203		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2204		templinfo["ServerMessage"] = msg
2205	default:
2206		http.NotFound(w, r)
2207	}
2208	if len(honks) > 0 {
2209		templinfo["TopHID"] = honks[0].ID
2210	} else {
2211		templinfo["TopHID"] = wanted
2212	}
2213	reverbolate(userid, honks)
2214	templinfo["Honks"] = honks
2215	templinfo["MapLink"] = getmaplink(u)
2216	templinfo["User"], _ = butwhatabout(u.Username)
2217	w.Header().Set("Content-Type", "text/html; charset=utf-8")
2218	err := readviews.Execute(w, "honkfrags.html", templinfo)
2219	if err != nil {
2220		log.Printf("frag error: %s", err)
2221	}
2222}
2223
2224var honkline = make(chan bool)
2225
2226func honkhonkline() {
2227	for {
2228		select {
2229		case honkline <- true:
2230		default:
2231			return
2232		}
2233	}
2234}
2235
2236func apihandler(w http.ResponseWriter, r *http.Request) {
2237	u := login.GetUserInfo(r)
2238	userid := u.UserID
2239	user, _ := butwhatabout(u.Username)
2240	action := r.FormValue("action")
2241	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2242	log.Printf("api request '%s' on behalf of %s", action, u.Username)
2243	switch action {
2244	case "honk":
2245		h := submithonk(w, r)
2246		if h == nil {
2247			return
2248		}
2249		w.Write([]byte(h.XID))
2250	case "donk":
2251		d, err := submitdonk(w, r)
2252		if err != nil {
2253			if err == http.ErrMissingFile {
2254				http.Error(w, "missing donk", http.StatusBadRequest)
2255			}
2256			return
2257		}
2258		w.Write([]byte(d.XID))
2259	case "zonkit":
2260		zonkit(w, r)
2261	case "gethonks":
2262		var honks []*Honk
2263		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2264		page := r.FormValue("page")
2265		var waitchan <-chan time.Time
2266	requery:
2267		switch page {
2268		case "atme":
2269			honks = gethonksforme(userid, wanted)
2270			honks = osmosis(honks, userid, false)
2271		case "home":
2272			honks = gethonksforuser(userid, wanted)
2273			honks = osmosis(honks, userid, true)
2274		default:
2275			http.Error(w, "unknown page", http.StatusNotFound)
2276			return
2277		}
2278		if len(honks) == 0 && wait > 0 {
2279			if waitchan == nil {
2280				waitchan = time.After(time.Duration(wait) * time.Second)
2281			}
2282			select {
2283			case <-honkline:
2284				goto requery
2285			case <-waitchan:
2286			}
2287		}
2288		reverbolate(userid, honks)
2289		j := junk.New()
2290		j["honks"] = honks
2291		j.Write(w)
2292	case "sendactivity":
2293		public := r.FormValue("public") == "1"
2294		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2295		msg := []byte(r.FormValue("msg"))
2296		for rcpt := range rcpts {
2297			go deliverate(0, userid, rcpt, msg)
2298		}
2299	default:
2300		http.Error(w, "unknown action", http.StatusNotFound)
2301		return
2302	}
2303}
2304
2305var endoftheworld = make(chan bool)
2306var readyalready = make(chan bool)
2307var workinprogress = 0
2308
2309func enditall() {
2310	sig := make(chan os.Signal)
2311	signal.Notify(sig, os.Interrupt)
2312	signal.Notify(sig, syscall.SIGTERM)
2313	<-sig
2314	log.Printf("stopping...")
2315	for i := 0; i < workinprogress; i++ {
2316		endoftheworld <- true
2317	}
2318	log.Printf("waiting...")
2319	for i := 0; i < workinprogress; i++ {
2320		<-readyalready
2321	}
2322	log.Printf("apocalypse")
2323	os.Exit(0)
2324}
2325
2326var preservehooks []func()
2327
2328func wait100ms() chan struct{} {
2329	c := make(chan struct{})
2330	go func() {
2331		time.Sleep(100 * time.Millisecond)
2332		close(c)
2333	}()
2334	return c
2335}
2336
2337func bgmonitor() {
2338	for {
2339		time.Sleep(5 * time.Minute)
2340		log.Printf("good morning!")
2341		log.Printf("outstanding deliveries: %d", garage.Outstanding())
2342	}
2343}
2344
2345func serve() {
2346	db := opendatabase()
2347	login.Init(db)
2348
2349	listener, err := openListener()
2350	if err != nil {
2351		log.Fatal(err)
2352	}
2353	go runBackendServer()
2354	go enditall()
2355	go redeliverator()
2356	go tracker()
2357	go bgmonitor()
2358	w100 := wait100ms()
2359
2360	getconfig("debug", &debugMode)
2361	readviews = templates.Load(debugMode,
2362		viewDir+"/views/honkpage.html",
2363		viewDir+"/views/honkfrags.html",
2364		viewDir+"/views/honkers.html",
2365		viewDir+"/views/hfcs.html",
2366		viewDir+"/views/combos.html",
2367		viewDir+"/views/honkform.html",
2368		viewDir+"/views/honk.html",
2369		viewDir+"/views/account.html",
2370		viewDir+"/views/about.html",
2371		viewDir+"/views/funzone.html",
2372		viewDir+"/views/login.html",
2373		viewDir+"/views/xzone.html",
2374		viewDir+"/views/msg.html",
2375		viewDir+"/views/header.html",
2376		viewDir+"/views/onts.html",
2377		viewDir+"/views/honkpage.js",
2378	)
2379	if !debugMode {
2380		assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2381		for _, s := range assets {
2382			savedassetparams[s] = getassetparam(s)
2383		}
2384		loadAvatarColors()
2385	}
2386	<-w100
2387
2388	for _, h := range preservehooks {
2389		h()
2390	}
2391
2392	mux := mux.NewRouter()
2393	mux.Use(login.Checker)
2394
2395	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2396
2397	posters := mux.Methods("POST").Subrouter()
2398	getters := mux.Methods("GET").Subrouter()
2399
2400	getters.HandleFunc("/", homepage)
2401	getters.HandleFunc("/home", homepage)
2402	getters.HandleFunc("/front", homepage)
2403	getters.HandleFunc("/events", homepage)
2404	getters.HandleFunc("/robots.txt", nomoroboto)
2405	getters.HandleFunc("/rss", showrss)
2406	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2407	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2408	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2409	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2410	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2411	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2412	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2413	getters.HandleFunc("/a", avatate)
2414	getters.HandleFunc("/o", thelistingoftheontologies)
2415	getters.HandleFunc("/o/{name:.+}", showontology)
2416	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2417	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2418	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2419	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2420
2421	getters.HandleFunc("/flag/{code:.+}", bloat_showflag)
2422
2423	getters.HandleFunc("/server", serveractor)
2424	posters.HandleFunc("/server/inbox", serverinbox)
2425	posters.HandleFunc("/inbox", serverinbox)
2426
2427	getters.HandleFunc("/style.css", serveasset)
2428	getters.HandleFunc("/local.css", serveasset)
2429	getters.HandleFunc("/honkpage.js", serveasset)
2430	getters.HandleFunc("/about", servehtml)
2431	getters.HandleFunc("/login", servehtml)
2432	posters.HandleFunc("/dologin", login.LoginFunc)
2433	getters.HandleFunc("/logout", login.LogoutFunc)
2434	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2435
2436	loggedin := mux.NewRoute().Subrouter()
2437	loggedin.Use(login.Required)
2438	loggedin.HandleFunc("/first", homepage)
2439	loggedin.HandleFunc("/saved", homepage)
2440	loggedin.HandleFunc("/account", accountpage)
2441	loggedin.HandleFunc("/funzone", showfunzone)
2442	loggedin.HandleFunc("/chpass", dochpass)
2443	loggedin.HandleFunc("/atme", homepage)
2444	loggedin.HandleFunc("/hfcs", hfcspage)
2445	loggedin.HandleFunc("/xzone", xzone)
2446	loggedin.HandleFunc("/newhonk", newhonkpage)
2447	loggedin.HandleFunc("/edit", edithonkpage)
2448	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2449	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2450	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2451	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2452	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2453	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2454	loggedin.HandleFunc("/honkers", showhonkers)
2455	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2456	loggedin.HandleFunc("/h", showhonker)
2457	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2458	loggedin.HandleFunc("/c", showcombos)
2459	loggedin.HandleFunc("/t", showconvoy)
2460	loggedin.HandleFunc("/q", showsearch)
2461	loggedin.HandleFunc("/hydra", webhydra)
2462	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2463
2464	err = http.Serve(listener, mux)
2465	if err != nil {
2466		log.Fatal(err)
2467	}
2468}