all repos — honk @ 6371617e08954ae58f83fbf3000c699db39f9811

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	"fmt"
  21	"html"
  22	"html/template"
  23	"io"
  24	"io/ioutil"
  25	"log"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"sort"
  31	"strconv"
  32	"strings"
  33	"time"
  34
  35	"github.com/gorilla/mux"
  36	"humungus.tedunangst.com/r/webs/css"
  37	"humungus.tedunangst.com/r/webs/htfilter"
  38	"humungus.tedunangst.com/r/webs/httpsig"
  39	"humungus.tedunangst.com/r/webs/image"
  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
  51func getuserstyle(u *login.UserInfo) template.CSS {
  52	if u == nil {
  53		return ""
  54	}
  55	user, _ := butwhatabout(u.Username)
  56	if user.SkinnyCSS {
  57		return "main { max-width: 700px; }"
  58	}
  59	return ""
  60}
  61
  62func getInfo(r *http.Request) map[string]interface{} {
  63	u := login.GetUserInfo(r)
  64	templinfo := make(map[string]interface{})
  65	templinfo["StyleParam"] = getassetparam("views/style.css")
  66	templinfo["LocalStyleParam"] = getassetparam("views/local.css")
  67	templinfo["JSParam"] = getassetparam("views/honkpage.js")
  68	templinfo["UserStyle"] = getuserstyle(u)
  69	templinfo["ServerName"] = serverName
  70	templinfo["IconName"] = iconName
  71	templinfo["UserInfo"] = u
  72	templinfo["UserSep"] = userSep
  73	if u != nil {
  74		var combos []string
  75		combocache.Get(u.UserID, &combos)
  76		templinfo["Combos"] = combos
  77	}
  78	return templinfo
  79}
  80
  81func homepage(w http.ResponseWriter, r *http.Request) {
  82	templinfo := getInfo(r)
  83	u := login.GetUserInfo(r)
  84	var honks []*Honk
  85	var userid int64 = -1
  86	if r.URL.Path == "/front" || u == nil {
  87		honks = getpublichonks()
  88	} else {
  89		userid = u.UserID
  90		if r.URL.Path == "/atme" {
  91			templinfo["PageName"] = "atme"
  92			honks = gethonksforme(userid)
  93		} else {
  94			templinfo["PageName"] = "home"
  95			honks = gethonksforuser(userid)
  96			honks = osmosis(honks, userid)
  97		}
  98		if len(honks) > 0 {
  99			templinfo["TopXID"] = honks[0].XID
 100		}
 101		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 102	}
 103
 104	templinfo["ShowRSS"] = true
 105	templinfo["ServerMessage"] = serverMsg
 106	honkpage(w, u, honks, templinfo)
 107}
 108
 109func showfunzone(w http.ResponseWriter, r *http.Request) {
 110	var emunames, memenames []string
 111	dir, err := os.Open("emus")
 112	if err == nil {
 113		emunames, _ = dir.Readdirnames(0)
 114		dir.Close()
 115	}
 116	for i, e := range emunames {
 117		if len(e) > 4 {
 118			emunames[i] = e[:len(e)-4]
 119		}
 120	}
 121	dir, err = os.Open("memes")
 122	if err == nil {
 123		memenames, _ = dir.Readdirnames(0)
 124		dir.Close()
 125	}
 126	templinfo := getInfo(r)
 127	templinfo["Emus"] = emunames
 128	templinfo["Memes"] = memenames
 129	err = readviews.Execute(w, "funzone.html", templinfo)
 130	if err != nil {
 131		log.Print(err)
 132	}
 133}
 134
 135func showrss(w http.ResponseWriter, r *http.Request) {
 136	name := mux.Vars(r)["name"]
 137
 138	var honks []*Honk
 139	if name != "" {
 140		honks = gethonksbyuser(name, false)
 141	} else {
 142		honks = getpublichonks()
 143	}
 144	if len(honks) > 20 {
 145		honks = honks[0:20]
 146	}
 147	reverbolate(-1, honks)
 148
 149	home := fmt.Sprintf("https://%s/", serverName)
 150	base := home
 151	if name != "" {
 152		home += "u/" + name
 153		name += " "
 154	}
 155	feed := rss.Feed{
 156		Title:       name + "honk",
 157		Link:        home,
 158		Description: name + "honk rss",
 159		Image: &rss.Image{
 160			URL:   base + "icon.png",
 161			Title: name + "honk rss",
 162			Link:  home,
 163		},
 164	}
 165	var modtime time.Time
 166	for _, honk := range honks {
 167		if !firstclass(honk) {
 168			continue
 169		}
 170		desc := string(honk.HTML)
 171		for _, d := range honk.Donks {
 172			desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 173				d.URL, html.EscapeString(d.Name))
 174		}
 175
 176		feed.Items = append(feed.Items, &rss.Item{
 177			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 178			Description: rss.CData{desc},
 179			Link:        honk.URL,
 180			PubDate:     honk.Date.Format(time.RFC1123),
 181			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 182		})
 183		if honk.Date.After(modtime) {
 184			modtime = honk.Date
 185		}
 186	}
 187	w.Header().Set("Cache-Control", "max-age=300")
 188	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 189
 190	err := feed.Write(w)
 191	if err != nil {
 192		log.Printf("error writing rss: %s", err)
 193	}
 194}
 195
 196func crappola(j junk.Junk) bool {
 197	t, _ := j.GetString("type")
 198	a, _ := j.GetString("actor")
 199	o, _ := j.GetString("object")
 200	if t == "Delete" && a == o {
 201		log.Printf("crappola from %s", a)
 202		return true
 203	}
 204	return false
 205}
 206
 207func ping(user *WhatAbout, who string) {
 208	box, err := getboxes(who)
 209	if err != nil {
 210		log.Printf("no inbox for ping: %s", err)
 211		return
 212	}
 213	j := junk.New()
 214	j["@context"] = itiswhatitis
 215	j["type"] = "Ping"
 216	j["id"] = user.URL + "/ping/" + xfiltrate()
 217	j["actor"] = user.URL
 218	j["to"] = who
 219	keyname, key := ziggy(user.Name)
 220	err = PostJunk(keyname, key, box.In, j)
 221	if err != nil {
 222		log.Printf("can't send ping: %s", err)
 223		return
 224	}
 225	log.Printf("sent ping to %s: %s", who, j["id"])
 226}
 227
 228func pong(user *WhatAbout, who string, obj string) {
 229	box, err := getboxes(who)
 230	if err != nil {
 231		log.Printf("no inbox for pong %s : %s", who, err)
 232		return
 233	}
 234	j := junk.New()
 235	j["@context"] = itiswhatitis
 236	j["type"] = "Pong"
 237	j["id"] = user.URL + "/pong/" + xfiltrate()
 238	j["actor"] = user.URL
 239	j["to"] = who
 240	j["object"] = obj
 241	keyname, key := ziggy(user.Name)
 242	err = PostJunk(keyname, key, box.In, j)
 243	if err != nil {
 244		log.Printf("can't send pong: %s", err)
 245		return
 246	}
 247}
 248
 249func inbox(w http.ResponseWriter, r *http.Request) {
 250	name := mux.Vars(r)["name"]
 251	user, err := butwhatabout(name)
 252	if err != nil {
 253		http.NotFound(w, r)
 254		return
 255	}
 256	if stealthmode(user.ID, r) {
 257		http.NotFound(w, r)
 258		return
 259	}
 260	var buf bytes.Buffer
 261	io.Copy(&buf, r.Body)
 262	payload := buf.Bytes()
 263	j, err := junk.Read(bytes.NewReader(payload))
 264	if err != nil {
 265		log.Printf("bad payload: %s", err)
 266		io.WriteString(os.Stdout, "bad payload\n")
 267		os.Stdout.Write(payload)
 268		io.WriteString(os.Stdout, "\n")
 269		return
 270	}
 271	if crappola(j) {
 272		return
 273	}
 274	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 275	if err != nil {
 276		log.Printf("inbox message failed signature: %s", err)
 277		if keyname != "" {
 278			keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
 279			if err != nil {
 280				log.Printf("still failed: %s", err)
 281			}
 282		}
 283		if err != nil {
 284			return
 285		}
 286	}
 287	what, _ := j.GetString("type")
 288	if what == "Like" {
 289		return
 290	}
 291	who, _ := j.GetString("actor")
 292	origin := keymatch(keyname, who)
 293	if origin == "" {
 294		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 295		return
 296	}
 297	objid, _ := j.GetString("id")
 298	if thoudostbitethythumb(user.ID, []string{who}, objid) {
 299		log.Printf("ignoring thumb sucker %s", who)
 300		return
 301	}
 302	switch what {
 303	case "Ping":
 304		obj, _ := j.GetString("id")
 305		log.Printf("ping from %s: %s", who, obj)
 306		pong(user, who, obj)
 307	case "Pong":
 308		obj, _ := j.GetString("object")
 309		log.Printf("pong from %s: %s", who, obj)
 310	case "Follow":
 311		obj, _ := j.GetString("object")
 312		if obj == user.URL {
 313			log.Printf("updating honker follow: %s", who)
 314			stmtSaveDub.Exec(user.ID, who, who, "dub")
 315			go rubadubdub(user, j)
 316		} else {
 317			log.Printf("can't follow %s", obj)
 318		}
 319	case "Accept":
 320		log.Printf("updating honker accept: %s", who)
 321		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
 322		if err != nil {
 323			log.Printf("error updating honker: %s", err)
 324			return
 325		}
 326	case "Update":
 327		obj, ok := j.GetMap("object")
 328		if ok {
 329			what, _ := obj.GetString("type")
 330			switch what {
 331			case "Person":
 332				return
 333			case "Question":
 334				return
 335			case "Note":
 336				go consumeactivity(user, j, origin)
 337				return
 338			}
 339		}
 340		log.Printf("unknown Update activity")
 341		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 342		j.Write(fd)
 343		io.WriteString(fd, "\n")
 344		fd.Close()
 345
 346	case "Undo":
 347		obj, ok := j.GetMap("object")
 348		if !ok {
 349			log.Printf("unknown undo no object")
 350		} else {
 351			what, _ := obj.GetString("type")
 352			switch what {
 353			case "Follow":
 354				log.Printf("updating honker undo: %s", who)
 355				_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
 356				if err != nil {
 357					log.Printf("error updating honker: %s", err)
 358					return
 359				}
 360			case "Announce":
 361				xid, _ := obj.GetString("object")
 362				log.Printf("undo announce: %s", xid)
 363			case "Like":
 364			default:
 365				log.Printf("unknown undo: %s", what)
 366			}
 367		}
 368	default:
 369		go consumeactivity(user, j, origin)
 370	}
 371}
 372
 373func ximport(w http.ResponseWriter, r *http.Request) {
 374	xid := r.FormValue("xid")
 375	p, _ := investigate(xid)
 376	if p != nil {
 377		xid = p.XID
 378	}
 379	j, err := GetJunk(xid)
 380	if err != nil {
 381		http.Error(w, "error getting external object", http.StatusInternalServerError)
 382		log.Printf("error getting external object: %s", err)
 383		return
 384	}
 385	log.Printf("importing %s", xid)
 386	u := login.GetUserInfo(r)
 387	user, _ := butwhatabout(u.Username)
 388
 389	what, _ := j.GetString("type")
 390	if isactor(what) {
 391		outbox, _ := j.GetString("outbox")
 392		gimmexonks(user, outbox)
 393		http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 394		return
 395	}
 396	xonk := xonkxonk(user, j, originate(xid))
 397	convoy := ""
 398	if xonk != nil {
 399		convoy = xonk.Convoy
 400		savexonk(xonk)
 401	}
 402	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 403}
 404
 405func xzone(w http.ResponseWriter, r *http.Request) {
 406	u := login.GetUserInfo(r)
 407	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 408	if err != nil {
 409		log.Printf("query err: %s", err)
 410		return
 411	}
 412	defer rows.Close()
 413	var honkers []Honker
 414	for rows.Next() {
 415		var xid string
 416		rows.Scan(&xid)
 417		honkers = append(honkers, Honker{XID: xid})
 418	}
 419	rows.Close()
 420	for i, _ := range honkers {
 421		_, honkers[i].Handle = handles(honkers[i].XID)
 422	}
 423	templinfo := getInfo(r)
 424	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 425	templinfo["Honkers"] = honkers
 426	err = readviews.Execute(w, "xzone.html", templinfo)
 427	if err != nil {
 428		log.Print(err)
 429	}
 430}
 431
 432func outbox(w http.ResponseWriter, r *http.Request) {
 433	name := mux.Vars(r)["name"]
 434	user, err := butwhatabout(name)
 435	if err != nil {
 436		http.NotFound(w, r)
 437		return
 438	}
 439	if stealthmode(user.ID, r) {
 440		http.NotFound(w, r)
 441		return
 442	}
 443
 444	honks := gethonksbyuser(name, false)
 445	if len(honks) > 20 {
 446		honks = honks[0:20]
 447	}
 448
 449	var jonks []junk.Junk
 450	for _, h := range honks {
 451		j, _ := jonkjonk(user, h)
 452		jonks = append(jonks, j)
 453	}
 454
 455	j := junk.New()
 456	j["@context"] = itiswhatitis
 457	j["id"] = user.URL + "/outbox"
 458	j["type"] = "OrderedCollection"
 459	j["totalItems"] = len(jonks)
 460	j["orderedItems"] = jonks
 461
 462	w.Header().Set("Content-Type", theonetruename)
 463	j.Write(w)
 464}
 465
 466func emptiness(w http.ResponseWriter, r *http.Request) {
 467	name := mux.Vars(r)["name"]
 468	user, err := butwhatabout(name)
 469	if err != nil {
 470		http.NotFound(w, r)
 471		return
 472	}
 473	if stealthmode(user.ID, r) {
 474		http.NotFound(w, r)
 475		return
 476	}
 477	colname := "/followers"
 478	if strings.HasSuffix(r.URL.Path, "/following") {
 479		colname = "/following"
 480	}
 481	j := junk.New()
 482	j["@context"] = itiswhatitis
 483	j["id"] = user.URL + colname
 484	j["type"] = "OrderedCollection"
 485	j["totalItems"] = 0
 486	j["orderedItems"] = []junk.Junk{}
 487
 488	w.Header().Set("Content-Type", theonetruename)
 489	j.Write(w)
 490}
 491
 492func showuser(w http.ResponseWriter, r *http.Request) {
 493	name := mux.Vars(r)["name"]
 494	user, err := butwhatabout(name)
 495	if err != nil {
 496		log.Printf("user not found %s: %s", name, err)
 497		http.NotFound(w, r)
 498		return
 499	}
 500	if stealthmode(user.ID, r) {
 501		http.NotFound(w, r)
 502		return
 503	}
 504	if friendorfoe(r.Header.Get("Accept")) {
 505		j := asjonker(user)
 506		w.Header().Set("Content-Type", theonetruename)
 507		j.Write(w)
 508		return
 509	}
 510	u := login.GetUserInfo(r)
 511	honks := gethonksbyuser(name, u != nil && u.Username == name)
 512	templinfo := getInfo(r)
 513	filt := htfilter.New()
 514	templinfo["Name"] = user.Name
 515	whatabout := user.About
 516	whatabout = obfusbreak(user.About)
 517	templinfo["WhatAbout"], _ = filt.String(whatabout)
 518	templinfo["ServerMessage"] = ""
 519	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 520	honkpage(w, u, honks, templinfo)
 521}
 522
 523func showhonker(w http.ResponseWriter, r *http.Request) {
 524	u := login.GetUserInfo(r)
 525	name := mux.Vars(r)["name"]
 526	var honks []*Honk
 527	if name == "" {
 528		name = r.FormValue("xid")
 529		honks = gethonksbyxonker(u.UserID, name)
 530	} else {
 531		honks = gethonksbyhonker(u.UserID, name)
 532	}
 533	name = html.EscapeString(name)
 534	msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 535	templinfo := getInfo(r)
 536	templinfo["PageName"] = "honker"
 537	templinfo["ServerMessage"] = template.HTML(msg)
 538	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 539	honkpage(w, u, honks, templinfo)
 540}
 541
 542func showcombo(w http.ResponseWriter, r *http.Request) {
 543	name := mux.Vars(r)["name"]
 544	u := login.GetUserInfo(r)
 545	honks := gethonksbycombo(u.UserID, name)
 546	honks = osmosis(honks, u.UserID)
 547	templinfo := getInfo(r)
 548	templinfo["PageName"] = "combo"
 549	templinfo["PageArg"] = "name"
 550	templinfo["ServerMessage"] = "honks by combo: " + name
 551	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 552	if len(honks) > 0 {
 553		templinfo["TopXID"] = honks[0].XID
 554	}
 555	honkpage(w, u, honks, templinfo)
 556}
 557func showconvoy(w http.ResponseWriter, r *http.Request) {
 558	c := r.FormValue("c")
 559	u := login.GetUserInfo(r)
 560	honks := gethonksbyconvoy(u.UserID, c)
 561	templinfo := getInfo(r)
 562	templinfo["ServerMessage"] = "honks in convoy: " + c
 563	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 564	honkpage(w, u, honks, templinfo)
 565}
 566func showsearch(w http.ResponseWriter, r *http.Request) {
 567	q := r.FormValue("q")
 568	u := login.GetUserInfo(r)
 569	honks := gethonksbysearch(u.UserID, q)
 570	templinfo := getInfo(r)
 571	templinfo["ServerMessage"] = "honks for search: " + q
 572	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 573	honkpage(w, u, honks, templinfo)
 574}
 575func showontology(w http.ResponseWriter, r *http.Request) {
 576	name := mux.Vars(r)["name"]
 577	u := login.GetUserInfo(r)
 578	var userid int64 = -1
 579	if u != nil {
 580		userid = u.UserID
 581	}
 582	honks := gethonksbyontology(userid, "#"+name)
 583	templinfo := getInfo(r)
 584	templinfo["ServerMessage"] = "honks by ontology: " + name
 585	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 586	honkpage(w, u, honks, templinfo)
 587}
 588
 589func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 590	u := login.GetUserInfo(r)
 591	var userid int64 = -1
 592	if u != nil {
 593		userid = u.UserID
 594	}
 595	rows, err := stmtSelectOnts.Query(userid)
 596	if err != nil {
 597		log.Printf("selection error: %s", err)
 598		return
 599	}
 600	defer rows.Close()
 601	var onts [][]string
 602	for rows.Next() {
 603		var o string
 604		err := rows.Scan(&o)
 605		if err != nil {
 606			log.Printf("error scanning ont: %s", err)
 607			continue
 608		}
 609		onts = append(onts, []string{o, o[1:]})
 610	}
 611	if u == nil {
 612		w.Header().Set("Cache-Control", "max-age=300")
 613	}
 614	templinfo := getInfo(r)
 615	templinfo["Onts"] = onts
 616	err = readviews.Execute(w, "onts.html", templinfo)
 617	if err != nil {
 618		log.Print(err)
 619	}
 620}
 621
 622func showhonk(w http.ResponseWriter, r *http.Request) {
 623	name := mux.Vars(r)["name"]
 624	user, err := butwhatabout(name)
 625	if err != nil {
 626		http.NotFound(w, r)
 627		return
 628	}
 629	if stealthmode(user.ID, r) {
 630		http.NotFound(w, r)
 631		return
 632	}
 633
 634	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 635	honk := getxonk(user.ID, xid)
 636	if honk == nil {
 637		http.NotFound(w, r)
 638		return
 639	}
 640	u := login.GetUserInfo(r)
 641	if u != nil && u.UserID != user.ID {
 642		u = nil
 643	}
 644	if !honk.Public {
 645		if u == nil {
 646			http.NotFound(w, r)
 647			return
 648
 649		}
 650		templinfo := getInfo(r)
 651		templinfo["ServerMessage"] = "one honk maybe more"
 652		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 653		honkpage(w, u, []*Honk{honk}, templinfo)
 654		return
 655	}
 656	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 657	if friendorfoe(r.Header.Get("Accept")) {
 658		for _, h := range rawhonks {
 659			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 660				honk.Replies = append(honk.Replies, h)
 661			}
 662		}
 663		donksforhonks([]*Honk{honk})
 664		_, j := jonkjonk(user, honk)
 665		j["@context"] = itiswhatitis
 666		w.Header().Set("Content-Type", theonetruename)
 667		j.Write(w)
 668		return
 669	}
 670	var honks []*Honk
 671	for _, h := range rawhonks {
 672		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 673			honks = append(honks, h)
 674		}
 675	}
 676
 677	templinfo := getInfo(r)
 678	templinfo["ServerMessage"] = "one honk maybe more"
 679	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 680	honkpage(w, u, honks, templinfo)
 681}
 682
 683func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 684	var userid int64 = -1
 685	if u != nil {
 686		userid = u.UserID
 687	}
 688	if u == nil {
 689		w.Header().Set("Cache-Control", "max-age=60")
 690	}
 691	reverbolate(userid, honks)
 692	templinfo["Honks"] = honks
 693	err := readviews.Execute(w, "honkpage.html", templinfo)
 694	if err != nil {
 695		log.Print(err)
 696	}
 697}
 698
 699func saveuser(w http.ResponseWriter, r *http.Request) {
 700	whatabout := r.FormValue("whatabout")
 701	u := login.GetUserInfo(r)
 702	db := opendatabase()
 703	options := ""
 704	if r.FormValue("skinny") == "skinny" {
 705		options += " skinny "
 706	}
 707	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 708	if err != nil {
 709		log.Printf("error bouting what: %s", err)
 710	}
 711
 712	http.Redirect(w, r, "/account", http.StatusSeeOther)
 713}
 714
 715func submitbonk(w http.ResponseWriter, r *http.Request) {
 716	xid := r.FormValue("xid")
 717	userinfo := login.GetUserInfo(r)
 718	user, _ := butwhatabout(userinfo.Username)
 719
 720	log.Printf("bonking %s", xid)
 721
 722	xonk := getxonk(userinfo.UserID, xid)
 723	if xonk == nil {
 724		return
 725	}
 726	if !xonk.Public {
 727		return
 728	}
 729	donksforhonks([]*Honk{xonk})
 730
 731	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 732	if err != nil {
 733		log.Printf("error acking bonk: %s", err)
 734	}
 735
 736	oonker := xonk.Oonker
 737	if oonker == "" {
 738		oonker = xonk.Honker
 739	}
 740	dt := time.Now().UTC()
 741	bonk := Honk{
 742		UserID:   userinfo.UserID,
 743		Username: userinfo.Username,
 744		What:     "bonk",
 745		Honker:   user.URL,
 746		Oonker:   oonker,
 747		XID:      xonk.XID,
 748		RID:      xonk.RID,
 749		Noise:    xonk.Noise,
 750		Precis:   xonk.Precis,
 751		URL:      xonk.URL,
 752		Date:     dt,
 753		Donks:    xonk.Donks,
 754		Whofore:  2,
 755		Convoy:   xonk.Convoy,
 756		Audience: []string{thewholeworld, oonker},
 757		Public:   true,
 758	}
 759
 760	bonk.Format = "html"
 761
 762	err = savehonk(&bonk)
 763	if err != nil {
 764		log.Printf("uh oh")
 765		return
 766	}
 767
 768	go honkworldwide(user, &bonk)
 769}
 770
 771func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 772	zonk := Honk{
 773		What:     what,
 774		XID:      xonk.XID,
 775		Date:     time.Now().UTC(),
 776		Audience: oneofakind(xonk.Audience),
 777	}
 778	zonk.Public = !keepitquiet(zonk.Audience)
 779
 780	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 781	go honkworldwide(user, &zonk)
 782}
 783
 784func zonkit(w http.ResponseWriter, r *http.Request) {
 785	wherefore := r.FormValue("wherefore")
 786	what := r.FormValue("what")
 787	userinfo := login.GetUserInfo(r)
 788	user, _ := butwhatabout(userinfo.Username)
 789
 790	if wherefore == "ack" {
 791		xonk := getxonk(userinfo.UserID, what)
 792		if xonk != nil {
 793			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 794			if err != nil {
 795				log.Printf("error acking: %s", err)
 796			}
 797			sendzonkofsorts(xonk, user, "ack")
 798		}
 799		return
 800	}
 801
 802	if wherefore == "deack" {
 803		xonk := getxonk(userinfo.UserID, what)
 804		if xonk != nil {
 805			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 806			if err != nil {
 807				log.Printf("error deacking: %s", err)
 808			}
 809			sendzonkofsorts(xonk, user, "deack")
 810		}
 811		return
 812	}
 813
 814	if wherefore == "unbonk" {
 815		xonk := getbonk(userinfo.UserID, what)
 816		if xonk != nil {
 817			deletehonk(xonk.ID)
 818			xonk = getxonk(userinfo.UserID, what)
 819			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 820			if err != nil {
 821				log.Printf("error unbonking: %s", err)
 822			}
 823			sendzonkofsorts(xonk, user, "unbonk")
 824		}
 825		return
 826	}
 827
 828	log.Printf("zonking %s %s", wherefore, what)
 829	if wherefore == "zonk" {
 830		xonk := getxonk(userinfo.UserID, what)
 831		if xonk != nil {
 832			deletehonk(xonk.ID)
 833			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 834				sendzonkofsorts(xonk, user, "zonk")
 835			}
 836		}
 837	}
 838	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 839	if err != nil {
 840		log.Printf("error saving zonker: %s", err)
 841		return
 842	}
 843}
 844
 845func edithonkpage(w http.ResponseWriter, r *http.Request) {
 846	u := login.GetUserInfo(r)
 847	user, _ := butwhatabout(u.Username)
 848	xid := r.FormValue("xid")
 849	honk := getxonk(u.UserID, xid)
 850	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 851		log.Printf("no edit")
 852		return
 853	}
 854
 855	noise := honk.Noise
 856	if honk.Precis != "" {
 857		noise = honk.Precis + "\n\n" + noise
 858	}
 859
 860	honks := []*Honk{honk}
 861	donksforhonks(honks)
 862	reverbolate(u.UserID, honks)
 863	templinfo := getInfo(r)
 864	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 865	templinfo["Honks"] = honks
 866	templinfo["Noise"] = noise
 867	templinfo["ServerMessage"] = "honk edit"
 868	templinfo["UpdateXID"] = honk.XID
 869	if len(honk.Donks) > 0 {
 870		templinfo["SavedFile"] = honk.Donks[0].XID
 871	}
 872	err := readviews.Execute(w, "honkpage.html", templinfo)
 873	if err != nil {
 874		log.Print(err)
 875	}
 876}
 877
 878// what a hot mess this function is
 879func submithonk(w http.ResponseWriter, r *http.Request) {
 880	rid := r.FormValue("rid")
 881	noise := r.FormValue("noise")
 882
 883	userinfo := login.GetUserInfo(r)
 884	user, _ := butwhatabout(userinfo.Username)
 885
 886	dt := time.Now().UTC()
 887	updatexid := r.FormValue("updatexid")
 888	var honk *Honk
 889	if updatexid != "" {
 890		honk = getxonk(userinfo.UserID, updatexid)
 891		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 892			log.Printf("not saving edit")
 893			return
 894		}
 895		honk.Date = dt
 896		honk.What = "update"
 897		honk.Format = "markdown"
 898	} else {
 899		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 900		what := "honk"
 901		if rid != "" {
 902			what = "tonk"
 903		}
 904		honk = &Honk{
 905			UserID:   userinfo.UserID,
 906			Username: userinfo.Username,
 907			What:     what,
 908			Honker:   user.URL,
 909			XID:      xid,
 910			Date:     dt,
 911			Format:   "markdown",
 912		}
 913	}
 914
 915	noise = hooterize(noise)
 916	honk.Noise = noise
 917	translate(honk)
 918
 919	var convoy string
 920	if rid != "" {
 921		xonk := getxonk(userinfo.UserID, rid)
 922		if xonk != nil {
 923			if xonk.Public {
 924				honk.Audience = append(honk.Audience, xonk.Audience...)
 925			}
 926			convoy = xonk.Convoy
 927		} else {
 928			xonkaud, c := whosthere(rid)
 929			honk.Audience = append(honk.Audience, xonkaud...)
 930			convoy = c
 931		}
 932		for i, a := range honk.Audience {
 933			if a == thewholeworld {
 934				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 935				break
 936			}
 937		}
 938		honk.RID = rid
 939	} else {
 940		honk.Audience = []string{thewholeworld}
 941	}
 942	if honk.Noise != "" && honk.Noise[0] == '@' {
 943		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
 944	} else {
 945		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
 946	}
 947
 948	if convoy == "" {
 949		convoy = "data:,electrichonkytonk-" + xfiltrate()
 950	}
 951	butnottooloud(honk.Audience)
 952	honk.Audience = oneofakind(honk.Audience)
 953	if len(honk.Audience) == 0 {
 954		log.Printf("honk to nowhere")
 955		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 956		return
 957	}
 958	honk.Public = !keepitquiet(honk.Audience)
 959	honk.Convoy = convoy
 960
 961	donkxid := r.FormValue("donkxid")
 962	if donkxid == "" {
 963		file, filehdr, err := r.FormFile("donk")
 964		if err == nil {
 965			var buf bytes.Buffer
 966			io.Copy(&buf, file)
 967			file.Close()
 968			data := buf.Bytes()
 969			xid := xfiltrate()
 970			var media, name string
 971			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 972			if err == nil {
 973				data = img.Data
 974				format := img.Format
 975				media = "image/" + format
 976				if format == "jpeg" {
 977					format = "jpg"
 978				}
 979				name = xid + "." + format
 980				xid = name
 981			} else {
 982				maxsize := 100000
 983				if len(data) > maxsize {
 984					log.Printf("bad image: %s too much text: %d", err, len(data))
 985					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 986					return
 987				}
 988				for i := 0; i < len(data); i++ {
 989					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
 990						log.Printf("bad image: %s not text: %d", err, data[i])
 991						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 992						return
 993					}
 994				}
 995				media = "text/plain"
 996				name = filehdr.Filename
 997				if name == "" {
 998					name = xid + ".txt"
 999				}
1000				xid += ".txt"
1001			}
1002			desc := r.FormValue("donkdesc")
1003			if desc == "" {
1004				desc = name
1005			}
1006			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1007			res, err := stmtSaveFile.Exec(xid, name, desc, url, media, 1, data)
1008			if err != nil {
1009				log.Printf("unable to save image: %s", err)
1010				return
1011			}
1012			var d Donk
1013			d.FileID, _ = res.LastInsertId()
1014			honk.Donks = append(honk.Donks, &d)
1015			donkxid = d.XID
1016		}
1017	} else {
1018		xid := donkxid
1019		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1020		var donk Donk
1021		row := stmtFindFile.QueryRow(url)
1022		err := row.Scan(&donk.FileID)
1023		if err == nil {
1024			honk.Donks = append(honk.Donks, &donk)
1025		} else {
1026			log.Printf("can't find file: %s", xid)
1027		}
1028	}
1029	herd := herdofemus(honk.Noise)
1030	for _, e := range herd {
1031		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1032		if donk != nil {
1033			donk.Name = e.Name
1034			honk.Donks = append(honk.Donks, donk)
1035		}
1036	}
1037	memetize(honk)
1038
1039	if honk.Public {
1040		honk.Whofore = 2
1041	} else {
1042		honk.Whofore = 3
1043	}
1044
1045	// back to markdown
1046	honk.Noise = noise
1047
1048	if r.FormValue("preview") == "preview" {
1049		honks := []*Honk{honk}
1050		reverbolate(userinfo.UserID, honks)
1051		templinfo := getInfo(r)
1052		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1053		templinfo["Honks"] = honks
1054		templinfo["InReplyTo"] = r.FormValue("rid")
1055		templinfo["Noise"] = r.FormValue("noise")
1056		templinfo["SavedFile"] = donkxid
1057		templinfo["ServerMessage"] = "honk preview"
1058		err := readviews.Execute(w, "honkpage.html", templinfo)
1059		if err != nil {
1060			log.Print(err)
1061		}
1062		return
1063	}
1064
1065	if updatexid != "" {
1066		updatehonk(honk)
1067	} else {
1068		err := savehonk(honk)
1069		if err != nil {
1070			log.Printf("uh oh")
1071			return
1072		}
1073	}
1074
1075	// reload for consistency
1076	honk.Donks = nil
1077	donksforhonks([]*Honk{honk})
1078
1079	go honkworldwide(user, honk)
1080
1081	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1082}
1083
1084func showhonkers(w http.ResponseWriter, r *http.Request) {
1085	userinfo := login.GetUserInfo(r)
1086	templinfo := getInfo(r)
1087	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1088	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1089	err := readviews.Execute(w, "honkers.html", templinfo)
1090	if err != nil {
1091		log.Print(err)
1092	}
1093}
1094
1095var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
1096	userid := key.(int64)
1097	honkers := gethonkers(userid)
1098	var combos []string
1099	for _, h := range honkers {
1100		combos = append(combos, h.Combos...)
1101	}
1102	for i, c := range combos {
1103		if c == "-" {
1104			combos[i] = ""
1105		}
1106	}
1107	combos = oneofakind(combos)
1108	sort.Strings(combos)
1109	return combos, true
1110})
1111
1112func showcombos(w http.ResponseWriter, r *http.Request) {
1113	userinfo := login.GetUserInfo(r)
1114	var combos []string
1115	combocache.Get(userinfo.UserID, &combos)
1116	templinfo := getInfo(r)
1117	err := readviews.Execute(w, "combos.html", templinfo)
1118	if err != nil {
1119		log.Print(err)
1120	}
1121}
1122
1123func submithonker(w http.ResponseWriter, r *http.Request) {
1124	u := login.GetUserInfo(r)
1125	name := r.FormValue("name")
1126	url := r.FormValue("url")
1127	peep := r.FormValue("peep")
1128	combos := r.FormValue("combos")
1129	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1130
1131	defer combocache.Clear(u.UserID)
1132
1133	if honkerid > 0 {
1134		goodbye := r.FormValue("goodbye")
1135		if goodbye == "F" {
1136			db := opendatabase()
1137			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1138				honkerid, u.UserID)
1139			var xid string
1140			err := row.Scan(&xid)
1141			if err != nil {
1142				log.Printf("can't get honker xid: %s", err)
1143				return
1144			}
1145			log.Printf("unsubscribing from %s", xid)
1146			user, _ := butwhatabout(u.Username)
1147			go itakeitallback(user, xid)
1148			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1149			if err != nil {
1150				log.Printf("error updating honker: %s", err)
1151				return
1152			}
1153
1154			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1155			return
1156		}
1157		combos = " " + strings.TrimSpace(combos) + " "
1158		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1159		if err != nil {
1160			log.Printf("update honker err: %s", err)
1161			return
1162		}
1163		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1164		return
1165	}
1166
1167	flavor := "presub"
1168	if peep == "peep" {
1169		flavor = "peep"
1170	}
1171	p, err := investigate(url)
1172	if err != nil {
1173		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1174		log.Printf("failed to investigate honker")
1175		return
1176	}
1177	url = p.XID
1178	if name == "" {
1179		name = p.Handle
1180	}
1181	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1182	if err != nil {
1183		log.Print(err)
1184		return
1185	}
1186	if flavor == "presub" {
1187		user, _ := butwhatabout(u.Username)
1188		go subsub(user, url)
1189	}
1190	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1191}
1192
1193func zonkzone(w http.ResponseWriter, r *http.Request) {
1194	userinfo := login.GetUserInfo(r)
1195	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1196	if err != nil {
1197		log.Printf("err: %s", err)
1198		return
1199	}
1200	defer rows.Close()
1201	var zonkers []Zonker
1202	for rows.Next() {
1203		var z Zonker
1204		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1205		zonkers = append(zonkers, z)
1206	}
1207	sort.Slice(zonkers, func(i, j int) bool {
1208		w1 := zonkers[i].Wherefore
1209		w2 := zonkers[j].Wherefore
1210		if w1 == w2 {
1211			return zonkers[i].Name < zonkers[j].Name
1212		}
1213		if w1 == "zonvoy" {
1214			w1 = "zzzzzzz"
1215		}
1216		if w2 == "zonvoy" {
1217			w2 = "zzzzzzz"
1218		}
1219		return w1 < w2
1220	})
1221
1222	templinfo := getInfo(r)
1223	templinfo["Zonkers"] = zonkers
1224	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1225	err = readviews.Execute(w, "zonkers.html", templinfo)
1226	if err != nil {
1227		log.Print(err)
1228	}
1229}
1230
1231func zonkzonk(w http.ResponseWriter, r *http.Request) {
1232	userinfo := login.GetUserInfo(r)
1233	itsok := r.FormValue("itsok")
1234	if itsok == "iforgiveyou" {
1235		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1236		db := opendatabase()
1237		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1238			userinfo.UserID, zonkerid)
1239		bitethethumbs()
1240		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1241		return
1242	}
1243	wherefore := r.FormValue("wherefore")
1244	name := r.FormValue("name")
1245	if name == "" {
1246		return
1247	}
1248	switch wherefore {
1249	case "zonker":
1250	case "zomain":
1251	case "zonvoy":
1252	case "zord":
1253	case "zilence":
1254	default:
1255		return
1256	}
1257	db := opendatabase()
1258	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1259		userinfo.UserID, name, wherefore)
1260	if wherefore == "zonker" || wherefore == "zomain" || wherefore == "zord" || wherefore == "zilence" {
1261		bitethethumbs()
1262	}
1263
1264	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1265}
1266
1267func accountpage(w http.ResponseWriter, r *http.Request) {
1268	u := login.GetUserInfo(r)
1269	user, _ := butwhatabout(u.Username)
1270	templinfo := getInfo(r)
1271	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1272	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1273	templinfo["User"] = user
1274	err := readviews.Execute(w, "account.html", templinfo)
1275	if err != nil {
1276		log.Print(err)
1277	}
1278}
1279
1280func dochpass(w http.ResponseWriter, r *http.Request) {
1281	err := login.ChangePassword(w, r)
1282	if err != nil {
1283		log.Printf("error changing password: %s", err)
1284	}
1285	http.Redirect(w, r, "/account", http.StatusSeeOther)
1286}
1287
1288func fingerlicker(w http.ResponseWriter, r *http.Request) {
1289	orig := r.FormValue("resource")
1290
1291	log.Printf("finger lick: %s", orig)
1292
1293	if strings.HasPrefix(orig, "acct:") {
1294		orig = orig[5:]
1295	}
1296
1297	name := orig
1298	idx := strings.LastIndexByte(name, '/')
1299	if idx != -1 {
1300		name = name[idx+1:]
1301		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1302			log.Printf("foreign request rejected")
1303			name = ""
1304		}
1305	} else {
1306		idx = strings.IndexByte(name, '@')
1307		if idx != -1 {
1308			name = name[:idx]
1309			if name+"@"+serverName != orig {
1310				log.Printf("foreign request rejected")
1311				name = ""
1312			}
1313		}
1314	}
1315	user, err := butwhatabout(name)
1316	if err != nil {
1317		http.NotFound(w, r)
1318		return
1319	}
1320	if stealthmode(user.ID, r) {
1321		http.NotFound(w, r)
1322		return
1323	}
1324
1325	j := junk.New()
1326	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1327	j["aliases"] = []string{user.URL}
1328	var links []junk.Junk
1329	l := junk.New()
1330	l["rel"] = "self"
1331	l["type"] = `application/activity+json`
1332	l["href"] = user.URL
1333	links = append(links, l)
1334	j["links"] = links
1335
1336	w.Header().Set("Cache-Control", "max-age=3600")
1337	w.Header().Set("Content-Type", "application/jrd+json")
1338	j.Write(w)
1339}
1340
1341func somedays() string {
1342	secs := 432000 + notrand.Int63n(432000)
1343	return fmt.Sprintf("%d", secs)
1344}
1345
1346func avatate(w http.ResponseWriter, r *http.Request) {
1347	n := r.FormValue("a")
1348	a := avatar(n)
1349	w.Header().Set("Cache-Control", "max-age="+somedays())
1350	w.Write(a)
1351}
1352
1353func servecss(w http.ResponseWriter, r *http.Request) {
1354	data, _ := ioutil.ReadFile("views" + r.URL.Path)
1355	s := css.Process(string(data))
1356	w.Header().Set("Cache-Control", "max-age=7776000")
1357	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1358	w.Write([]byte(s))
1359}
1360func serveasset(w http.ResponseWriter, r *http.Request) {
1361	w.Header().Set("Cache-Control", "max-age=7776000")
1362	http.ServeFile(w, r, "views"+r.URL.Path)
1363}
1364func servehtml(w http.ResponseWriter, r *http.Request) {
1365	templinfo := getInfo(r)
1366	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1367	if err != nil {
1368		log.Print(err)
1369	}
1370}
1371func serveemu(w http.ResponseWriter, r *http.Request) {
1372	xid := mux.Vars(r)["xid"]
1373	w.Header().Set("Cache-Control", "max-age="+somedays())
1374	http.ServeFile(w, r, "emus/"+xid)
1375}
1376func servememe(w http.ResponseWriter, r *http.Request) {
1377	xid := mux.Vars(r)["xid"]
1378	w.Header().Set("Cache-Control", "max-age="+somedays())
1379	http.ServeFile(w, r, "memes/"+xid)
1380}
1381
1382func servefile(w http.ResponseWriter, r *http.Request) {
1383	xid := mux.Vars(r)["xid"]
1384	row := stmtFileData.QueryRow(xid)
1385	var media string
1386	var data []byte
1387	err := row.Scan(&media, &data)
1388	if err != nil {
1389		log.Printf("error loading file: %s", err)
1390		http.NotFound(w, r)
1391		return
1392	}
1393	w.Header().Set("Content-Type", media)
1394	w.Header().Set("X-Content-Type-Options", "nosniff")
1395	w.Header().Set("Cache-Control", "max-age="+somedays())
1396	w.Write(data)
1397}
1398
1399func nomoroboto(w http.ResponseWriter, r *http.Request) {
1400	io.WriteString(w, "User-agent: *\n")
1401	io.WriteString(w, "Disallow: /a\n")
1402	io.WriteString(w, "Disallow: /d\n")
1403	io.WriteString(w, "Disallow: /meme\n")
1404	for _, u := range allusers() {
1405		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1406	}
1407}
1408
1409func webhydra(w http.ResponseWriter, r *http.Request) {
1410	u := login.GetUserInfo(r)
1411	userid := u.UserID
1412	templinfo := getInfo(r)
1413	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1414	page := r.FormValue("page")
1415	var honks []*Honk
1416	switch page {
1417	case "atme":
1418		honks = gethonksforme(userid)
1419	case "home":
1420		honks = gethonksforuser(userid)
1421		honks = osmosis(honks, userid)
1422	case "combo":
1423		c := r.FormValue("c")
1424		honks = gethonksbycombo(userid, c)
1425	case "convoy":
1426		c := r.FormValue("c")
1427		honks = gethonksbyconvoy(userid, c)
1428	default:
1429		http.NotFound(w, r)
1430	}
1431	if len(honks) > 0 {
1432		templinfo["TopXID"] = honks[0].XID
1433	}
1434	if topxid := r.FormValue("topxid"); topxid != "" {
1435		for i, h := range honks {
1436			if h.XID == topxid {
1437				honks = honks[0:i]
1438				break
1439			}
1440		}
1441		log.Printf("topxid %d frags", len(honks))
1442	}
1443	reverbolate(userid, honks)
1444	templinfo["Honks"] = honks
1445	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1446	err := readviews.Execute(w, "honkfrags.html", templinfo)
1447	if err != nil {
1448		log.Printf("frag error: %s", err)
1449	}
1450}
1451
1452func serve() {
1453	db := opendatabase()
1454	login.Init(db)
1455
1456	listener, err := openListener()
1457	if err != nil {
1458		log.Fatal(err)
1459	}
1460	go redeliverator()
1461
1462	debug := false
1463	getconfig("debug", &debug)
1464	readviews = templates.Load(debug,
1465		"views/honkpage.html",
1466		"views/honkfrags.html",
1467		"views/honkers.html",
1468		"views/zonkers.html",
1469		"views/combos.html",
1470		"views/honkform.html",
1471		"views/honk.html",
1472		"views/account.html",
1473		"views/about.html",
1474		"views/funzone.html",
1475		"views/login.html",
1476		"views/xzone.html",
1477		"views/header.html",
1478		"views/onts.html",
1479		"views/honkpage.js",
1480	)
1481	if !debug {
1482		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1483		for _, s := range assets {
1484			savedassetparams[s] = getassetparam(s)
1485		}
1486	}
1487
1488	bitethethumbs()
1489
1490	mux := mux.NewRouter()
1491	mux.Use(login.Checker)
1492
1493	posters := mux.Methods("POST").Subrouter()
1494	getters := mux.Methods("GET").Subrouter()
1495
1496	getters.HandleFunc("/", homepage)
1497	getters.HandleFunc("/home", homepage)
1498	getters.HandleFunc("/front", homepage)
1499	getters.HandleFunc("/robots.txt", nomoroboto)
1500	getters.HandleFunc("/rss", showrss)
1501	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1502	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1503	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1504	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1505	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1506	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1507	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1508	getters.HandleFunc("/a", avatate)
1509	getters.HandleFunc("/o", thelistingoftheontologies)
1510	getters.HandleFunc("/o/{name:.+}", showontology)
1511	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1512	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1513	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1514	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1515
1516	getters.HandleFunc("/style.css", servecss)
1517	getters.HandleFunc("/local.css", servecss)
1518	getters.HandleFunc("/honkpage.js", serveasset)
1519	getters.HandleFunc("/about", servehtml)
1520	getters.HandleFunc("/login", servehtml)
1521	posters.HandleFunc("/dologin", login.LoginFunc)
1522	getters.HandleFunc("/logout", login.LogoutFunc)
1523
1524	loggedin := mux.NewRoute().Subrouter()
1525	loggedin.Use(login.Required)
1526	loggedin.HandleFunc("/account", accountpage)
1527	loggedin.HandleFunc("/funzone", showfunzone)
1528	loggedin.HandleFunc("/chpass", dochpass)
1529	loggedin.HandleFunc("/atme", homepage)
1530	loggedin.HandleFunc("/zonkzone", zonkzone)
1531	loggedin.HandleFunc("/xzone", xzone)
1532	loggedin.HandleFunc("/edit", edithonkpage)
1533	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1534	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1535	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1536	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1537	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1538	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1539	loggedin.HandleFunc("/honkers", showhonkers)
1540	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1541	loggedin.HandleFunc("/h", showhonker)
1542	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1543	loggedin.HandleFunc("/c", showcombos)
1544	loggedin.HandleFunc("/t", showconvoy)
1545	loggedin.HandleFunc("/q", showsearch)
1546	loggedin.HandleFunc("/hydra", webhydra)
1547	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1548
1549	err = http.Serve(listener, mux)
1550	if err != nil {
1551		log.Fatal(err)
1552	}
1553}