all repos — honk @ 42c2b270b13a0fa3a6989f9fa71259732e0d1f9f

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