all repos — honk @ 8ebc8f128f3cfada6cca4fc705ee73f24e5bd5e1

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