all repos — honk @ eaceb0995f874d48c43fcb0fe0bdb3d54a63cd89

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["ServerMessage"] = template.HTML(msg)
 530	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 531	honkpage(w, u, honks, templinfo)
 532}
 533
 534func showcombo(w http.ResponseWriter, r *http.Request) {
 535	name := mux.Vars(r)["name"]
 536	u := login.GetUserInfo(r)
 537	honks := gethonksbycombo(u.UserID, name)
 538	honks = osmosis(honks, u.UserID)
 539	templinfo := getInfo(r)
 540	templinfo["PageName"] = "combo"
 541	templinfo["ServerMessage"] = "honks by combo: " + name
 542	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 543	honkpage(w, u, honks, templinfo)
 544}
 545func showconvoy(w http.ResponseWriter, r *http.Request) {
 546	c := r.FormValue("c")
 547	u := login.GetUserInfo(r)
 548	honks := gethonksbyconvoy(u.UserID, c)
 549	templinfo := getInfo(r)
 550	templinfo["ServerMessage"] = "honks in convoy: " + c
 551	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 552	honkpage(w, u, honks, templinfo)
 553}
 554func showsearch(w http.ResponseWriter, r *http.Request) {
 555	q := r.FormValue("q")
 556	u := login.GetUserInfo(r)
 557	honks := gethonksbysearch(u.UserID, q)
 558	templinfo := getInfo(r)
 559	templinfo["ServerMessage"] = "honks for search: " + q
 560	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 561	honkpage(w, u, honks, templinfo)
 562}
 563func showontology(w http.ResponseWriter, r *http.Request) {
 564	name := mux.Vars(r)["name"]
 565	u := login.GetUserInfo(r)
 566	var userid int64 = -1
 567	if u != nil {
 568		userid = u.UserID
 569	}
 570	honks := gethonksbyontology(userid, "#"+name)
 571	templinfo := getInfo(r)
 572	templinfo["ServerMessage"] = "honks by ontology: " + name
 573	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 574	honkpage(w, u, honks, templinfo)
 575}
 576
 577func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 578	u := login.GetUserInfo(r)
 579	var userid int64 = -1
 580	if u != nil {
 581		userid = u.UserID
 582	}
 583	rows, err := stmtSelectOnts.Query(userid)
 584	if err != nil {
 585		log.Printf("selection error: %s", err)
 586		return
 587	}
 588	var onts [][]string
 589	for rows.Next() {
 590		var o string
 591		err := rows.Scan(&o)
 592		if err != nil {
 593			log.Printf("error scanning ont: %s", err)
 594			continue
 595		}
 596		onts = append(onts, []string{o, o[1:]})
 597	}
 598	if u == nil {
 599		w.Header().Set("Cache-Control", "max-age=300")
 600	}
 601	templinfo := getInfo(r)
 602	templinfo["Onts"] = onts
 603	err = readviews.Execute(w, "onts.html", templinfo)
 604	if err != nil {
 605		log.Print(err)
 606	}
 607}
 608
 609func showhonk(w http.ResponseWriter, r *http.Request) {
 610	name := mux.Vars(r)["name"]
 611	user, err := butwhatabout(name)
 612	if err != nil {
 613		http.NotFound(w, r)
 614		return
 615	}
 616	if stealthed(r) {
 617		http.NotFound(w, r)
 618		return
 619	}
 620
 621	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 622	honk := getxonk(user.ID, xid)
 623	if honk == nil {
 624		http.NotFound(w, r)
 625		return
 626	}
 627	u := login.GetUserInfo(r)
 628	if u != nil && u.UserID != user.ID {
 629		u = nil
 630	}
 631	if !honk.Public {
 632		if u == nil {
 633			http.NotFound(w, r)
 634			return
 635
 636		}
 637		templinfo := getInfo(r)
 638		templinfo["ServerMessage"] = "one honk maybe more"
 639		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 640		honkpage(w, u, []*Honk{honk}, templinfo)
 641		return
 642	}
 643	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 644	if friendorfoe(r.Header.Get("Accept")) {
 645		for _, h := range rawhonks {
 646			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 647				honk.Replies = append(honk.Replies, h)
 648			}
 649		}
 650		donksforhonks([]*Honk{honk})
 651		_, j := jonkjonk(user, honk)
 652		j["@context"] = itiswhatitis
 653		w.Header().Set("Content-Type", theonetruename)
 654		j.Write(w)
 655		return
 656	}
 657	var honks []*Honk
 658	for _, h := range rawhonks {
 659		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 660			honks = append(honks, h)
 661		}
 662	}
 663
 664	templinfo := getInfo(r)
 665	templinfo["ServerMessage"] = "one honk maybe more"
 666	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 667	honkpage(w, u, honks, templinfo)
 668}
 669
 670func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 671	var userid int64 = -1
 672	if u != nil {
 673		userid = u.UserID
 674	}
 675	if u == nil {
 676		w.Header().Set("Cache-Control", "max-age=60")
 677	}
 678	reverbolate(userid, honks)
 679	templinfo["Honks"] = honks
 680	err := readviews.Execute(w, "honkpage.html", templinfo)
 681	if err != nil {
 682		log.Print(err)
 683	}
 684}
 685
 686func saveuser(w http.ResponseWriter, r *http.Request) {
 687	whatabout := r.FormValue("whatabout")
 688	u := login.GetUserInfo(r)
 689	db := opendatabase()
 690	options := ""
 691	if r.FormValue("skinny") == "skinny" {
 692		options += " skinny "
 693	}
 694	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 695	if err != nil {
 696		log.Printf("error bouting what: %s", err)
 697	}
 698
 699	http.Redirect(w, r, "/account", http.StatusSeeOther)
 700}
 701
 702func submitbonk(w http.ResponseWriter, r *http.Request) {
 703	xid := r.FormValue("xid")
 704	userinfo := login.GetUserInfo(r)
 705	user, _ := butwhatabout(userinfo.Username)
 706
 707	log.Printf("bonking %s", xid)
 708
 709	xonk := getxonk(userinfo.UserID, xid)
 710	if xonk == nil {
 711		return
 712	}
 713	if !xonk.Public {
 714		return
 715	}
 716	donksforhonks([]*Honk{xonk})
 717
 718	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 719	if err != nil {
 720		log.Printf("error acking bonk: %s", err)
 721	}
 722
 723	oonker := xonk.Oonker
 724	if oonker == "" {
 725		oonker = xonk.Honker
 726	}
 727	dt := time.Now().UTC()
 728	bonk := Honk{
 729		UserID:   userinfo.UserID,
 730		Username: userinfo.Username,
 731		What:     "bonk",
 732		Honker:   user.URL,
 733		Oonker:   oonker,
 734		XID:      xonk.XID,
 735		RID:      xonk.RID,
 736		Noise:    xonk.Noise,
 737		Precis:   xonk.Precis,
 738		URL:      xonk.URL,
 739		Date:     dt,
 740		Donks:    xonk.Donks,
 741		Whofore:  2,
 742		Convoy:   xonk.Convoy,
 743		Audience: []string{thewholeworld, oonker},
 744		Public:   true,
 745	}
 746
 747	bonk.Format = "html"
 748
 749	err = savehonk(&bonk)
 750	if err != nil {
 751		log.Printf("uh oh")
 752		return
 753	}
 754
 755	go honkworldwide(user, &bonk)
 756}
 757
 758func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 759	zonk := Honk{
 760		What:     what,
 761		XID:      xonk.XID,
 762		Date:     time.Now().UTC(),
 763		Audience: oneofakind(xonk.Audience),
 764	}
 765	zonk.Public = !keepitquiet(zonk.Audience)
 766
 767	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 768	go honkworldwide(user, &zonk)
 769}
 770
 771func zonkit(w http.ResponseWriter, r *http.Request) {
 772	wherefore := r.FormValue("wherefore")
 773	what := r.FormValue("what")
 774	userinfo := login.GetUserInfo(r)
 775	user, _ := butwhatabout(userinfo.Username)
 776
 777	if wherefore == "ack" {
 778		xonk := getxonk(userinfo.UserID, what)
 779		if xonk != nil {
 780			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 781			if err != nil {
 782				log.Printf("error acking: %s", err)
 783			}
 784			sendzonkofsorts(xonk, user, "ack")
 785		}
 786		return
 787	}
 788
 789	if wherefore == "deack" {
 790		xonk := getxonk(userinfo.UserID, what)
 791		if xonk != nil {
 792			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 793			if err != nil {
 794				log.Printf("error deacking: %s", err)
 795			}
 796			sendzonkofsorts(xonk, user, "deack")
 797		}
 798		return
 799	}
 800
 801	if wherefore == "unbonk" {
 802		xonk := getbonk(userinfo.UserID, what)
 803		if xonk != nil {
 804			deletehonk(xonk.ID)
 805			xonk = getxonk(userinfo.UserID, what)
 806			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 807			if err != nil {
 808				log.Printf("error unbonking: %s", err)
 809			}
 810			sendzonkofsorts(xonk, user, "unbonk")
 811		}
 812		return
 813	}
 814
 815	log.Printf("zonking %s %s", wherefore, what)
 816	if wherefore == "zonk" {
 817		xonk := getxonk(userinfo.UserID, what)
 818		if xonk != nil {
 819			deletehonk(xonk.ID)
 820			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 821				sendzonkofsorts(xonk, user, "zonk")
 822			}
 823		}
 824	}
 825	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 826	if err != nil {
 827		log.Printf("error saving zonker: %s", err)
 828		return
 829	}
 830}
 831
 832func edithonkpage(w http.ResponseWriter, r *http.Request) {
 833	u := login.GetUserInfo(r)
 834	user, _ := butwhatabout(u.Username)
 835	xid := r.FormValue("xid")
 836	honk := getxonk(u.UserID, xid)
 837	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 838		log.Printf("no edit")
 839		return
 840	}
 841
 842	honks := []*Honk{honk}
 843	reverbolate(u.UserID, honks)
 844	templinfo := getInfo(r)
 845	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 846	templinfo["Honks"] = honks
 847	templinfo["Noise"] = honk.Noise
 848	templinfo["ServerMessage"] = "honk edit"
 849	templinfo["UpdateXID"] = honk.XID
 850	err := readviews.Execute(w, "honkpage.html", templinfo)
 851	if err != nil {
 852		log.Print(err)
 853	}
 854}
 855
 856func submithonk(w http.ResponseWriter, r *http.Request) {
 857	rid := r.FormValue("rid")
 858	noise := r.FormValue("noise")
 859
 860	userinfo := login.GetUserInfo(r)
 861	user, _ := butwhatabout(userinfo.Username)
 862
 863	dt := time.Now().UTC()
 864	updatexid := r.FormValue("updatexid")
 865	var honk *Honk
 866	if updatexid != "" {
 867		honk = getxonk(userinfo.UserID, updatexid)
 868		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 869			log.Printf("not saving edit")
 870			return
 871		}
 872		honk.Date = dt
 873		honk.What = "update"
 874	} else {
 875		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 876		what := "honk"
 877		if rid != "" {
 878			what = "tonk"
 879		}
 880		honk = &Honk{
 881			UserID:   userinfo.UserID,
 882			Username: userinfo.Username,
 883			What:     what,
 884			Honker:   user.URL,
 885			XID:      xid,
 886			Date:     dt,
 887		}
 888	}
 889	if strings.HasPrefix(noise, "DZ:") {
 890		idx := strings.Index(noise, "\n")
 891		if idx == -1 {
 892			honk.Precis = noise
 893			noise = ""
 894		} else {
 895			honk.Precis = noise[:idx]
 896			noise = noise[idx+1:]
 897		}
 898	}
 899	noise = quickrename(noise, userinfo.UserID)
 900	noise = hooterize(noise)
 901	noise = strings.TrimSpace(noise)
 902	honk.Precis = strings.TrimSpace(honk.Precis)
 903
 904	var convoy string
 905	if rid != "" {
 906		xonk := getxonk(userinfo.UserID, rid)
 907		if xonk != nil {
 908			if xonk.Public {
 909				honk.Audience = append(honk.Audience, xonk.Audience...)
 910			}
 911			convoy = xonk.Convoy
 912		} else {
 913			xonkaud, c := whosthere(rid)
 914			honk.Audience = append(honk.Audience, xonkaud...)
 915			convoy = c
 916		}
 917		for i, a := range honk.Audience {
 918			if a == thewholeworld {
 919				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 920				break
 921			}
 922		}
 923		honk.RID = rid
 924	} else {
 925		honk.Audience = []string{thewholeworld}
 926	}
 927	if noise != "" && noise[0] == '@' {
 928		honk.Audience = append(grapevine(noise), honk.Audience...)
 929	} else {
 930		honk.Audience = append(honk.Audience, grapevine(noise)...)
 931	}
 932	if convoy == "" {
 933		convoy = "data:,electrichonkytonk-" + xfiltrate()
 934	}
 935	butnottooloud(honk.Audience)
 936	honk.Audience = oneofakind(honk.Audience)
 937	if len(honk.Audience) == 0 {
 938		log.Printf("honk to nowhere")
 939		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 940		return
 941	}
 942	honk.Public = !keepitquiet(honk.Audience)
 943	noise = obfusbreak(noise)
 944	honk.Noise = noise
 945	honk.Convoy = convoy
 946
 947	donkxid := r.FormValue("donkxid")
 948	if donkxid == "" {
 949		file, filehdr, err := r.FormFile("donk")
 950		if err == nil {
 951			var buf bytes.Buffer
 952			io.Copy(&buf, file)
 953			file.Close()
 954			data := buf.Bytes()
 955			xid := xfiltrate()
 956			var media, name string
 957			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 958			if err == nil {
 959				data = img.Data
 960				format := img.Format
 961				media = "image/" + format
 962				if format == "jpeg" {
 963					format = "jpg"
 964				}
 965				name = xid + "." + format
 966				xid = name
 967			} else {
 968				maxsize := 100000
 969				if len(data) > maxsize {
 970					log.Printf("bad image: %s too much text: %d", err, len(data))
 971					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 972					return
 973				}
 974				for i := 0; i < len(data); i++ {
 975					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
 976						log.Printf("bad image: %s not text: %d", err, data[i])
 977						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 978						return
 979					}
 980				}
 981				media = "text/plain"
 982				name = filehdr.Filename
 983				if name == "" {
 984					name = xid + ".txt"
 985				}
 986				xid += ".txt"
 987			}
 988			desc := r.FormValue("donkdesc")
 989			if desc == "" {
 990				desc = name
 991			}
 992			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
 993			res, err := stmtSaveFile.Exec(xid, name, desc, url, media, 1, data)
 994			if err != nil {
 995				log.Printf("unable to save image: %s", err)
 996				return
 997			}
 998			var d Donk
 999			d.FileID, _ = res.LastInsertId()
1000			honk.Donks = append(honk.Donks, &d)
1001			donkxid = d.XID
1002		}
1003	} else {
1004		xid := donkxid
1005		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1006		var donk Donk
1007		row := stmtFindFile.QueryRow(url)
1008		err := row.Scan(&donk.FileID)
1009		if err == nil {
1010			honk.Donks = append(honk.Donks, &donk)
1011		} else {
1012			log.Printf("can't find file: %s", xid)
1013		}
1014	}
1015	herd := herdofemus(honk.Noise)
1016	for _, e := range herd {
1017		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1018		if donk != nil {
1019			donk.Name = e.Name
1020			honk.Donks = append(honk.Donks, donk)
1021		}
1022	}
1023	memetize(honk)
1024
1025	if honk.Public {
1026		honk.Whofore = 2
1027	} else {
1028		honk.Whofore = 3
1029	}
1030	if r.FormValue("preview") == "preview" {
1031		honks := []*Honk{honk}
1032		reverbolate(userinfo.UserID, honks)
1033		templinfo := getInfo(r)
1034		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1035		templinfo["Honks"] = honks
1036		templinfo["InReplyTo"] = r.FormValue("rid")
1037		templinfo["Noise"] = r.FormValue("noise")
1038		templinfo["SavedFile"] = donkxid
1039		templinfo["ServerMessage"] = "honk preview"
1040		err := readviews.Execute(w, "honkpage.html", templinfo)
1041		if err != nil {
1042			log.Print(err)
1043		}
1044		return
1045	}
1046	honk.Onts = oneofakind(ontologies(honk.Noise))
1047	honk.UserID = userinfo.UserID
1048	honk.RID = rid
1049	honk.Date = dt
1050	honk.Convoy = convoy
1051	honk.Format = "html"
1052
1053	if updatexid != "" {
1054		updatehonk(honk)
1055
1056	} else {
1057
1058		err := savehonk(honk)
1059		if err != nil {
1060			log.Printf("uh oh")
1061			return
1062		}
1063	}
1064
1065	// reload for consistency
1066	honk.Donks = nil
1067	donksforhonks([]*Honk{honk})
1068
1069	go honkworldwide(user, honk)
1070
1071	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1072}
1073
1074func showhonkers(w http.ResponseWriter, r *http.Request) {
1075	userinfo := login.GetUserInfo(r)
1076	templinfo := getInfo(r)
1077	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1078	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1079	err := readviews.Execute(w, "honkers.html", templinfo)
1080	if err != nil {
1081		log.Print(err)
1082	}
1083}
1084
1085func showcombos(w http.ResponseWriter, r *http.Request) {
1086	userinfo := login.GetUserInfo(r)
1087	templinfo := getInfo(r)
1088	honkers := gethonkers(userinfo.UserID)
1089	var combos []string
1090	for _, h := range honkers {
1091		combos = append(combos, h.Combos...)
1092	}
1093	for i, c := range combos {
1094		if c == "-" {
1095			combos[i] = ""
1096		}
1097	}
1098	combos = oneofakind(combos)
1099	sort.Strings(combos)
1100	templinfo["Combos"] = combos
1101	err := readviews.Execute(w, "combos.html", templinfo)
1102	if err != nil {
1103		log.Print(err)
1104	}
1105}
1106
1107func submithonker(w http.ResponseWriter, r *http.Request) {
1108	u := login.GetUserInfo(r)
1109	name := r.FormValue("name")
1110	url := r.FormValue("url")
1111	peep := r.FormValue("peep")
1112	combos := r.FormValue("combos")
1113	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1114
1115	if honkerid > 0 {
1116		goodbye := r.FormValue("goodbye")
1117		if goodbye == "F" {
1118			db := opendatabase()
1119			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1120				honkerid, u.UserID)
1121			var xid string
1122			err := row.Scan(&xid)
1123			if err != nil {
1124				log.Printf("can't get honker xid: %s", err)
1125				return
1126			}
1127			log.Printf("unsubscribing from %s", xid)
1128			user, _ := butwhatabout(u.Username)
1129			go itakeitallback(user, xid)
1130			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1131			if err != nil {
1132				log.Printf("error updating honker: %s", err)
1133				return
1134			}
1135
1136			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1137			return
1138		}
1139		combos = " " + strings.TrimSpace(combos) + " "
1140		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1141		if err != nil {
1142			log.Printf("update honker err: %s", err)
1143			return
1144		}
1145		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1146	}
1147
1148	flavor := "presub"
1149	if peep == "peep" {
1150		flavor = "peep"
1151	}
1152	p, err := investigate(url)
1153	if err != nil {
1154		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1155		log.Printf("failed to investigate honker")
1156		return
1157	}
1158	url = p.XID
1159	if name == "" {
1160		name = p.Handle
1161	}
1162	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1163	if err != nil {
1164		log.Print(err)
1165		return
1166	}
1167	if flavor == "presub" {
1168		user, _ := butwhatabout(u.Username)
1169		go subsub(user, url)
1170	}
1171	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1172}
1173
1174func zonkzone(w http.ResponseWriter, r *http.Request) {
1175	userinfo := login.GetUserInfo(r)
1176	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1177	if err != nil {
1178		log.Printf("err: %s", err)
1179		return
1180	}
1181	defer rows.Close()
1182	var zonkers []Zonker
1183	for rows.Next() {
1184		var z Zonker
1185		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1186		zonkers = append(zonkers, z)
1187	}
1188	sort.Slice(zonkers, func(i, j int) bool {
1189		w1 := zonkers[i].Wherefore
1190		w2 := zonkers[j].Wherefore
1191		if w1 == w2 {
1192			return zonkers[i].Name < zonkers[j].Name
1193		}
1194		if w1 == "zonvoy" {
1195			w1 = "zzzzzzz"
1196		}
1197		if w2 == "zonvoy" {
1198			w2 = "zzzzzzz"
1199		}
1200		return w1 < w2
1201	})
1202
1203	templinfo := getInfo(r)
1204	templinfo["Zonkers"] = zonkers
1205	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1206	err = readviews.Execute(w, "zonkers.html", templinfo)
1207	if err != nil {
1208		log.Print(err)
1209	}
1210}
1211
1212func zonkzonk(w http.ResponseWriter, r *http.Request) {
1213	userinfo := login.GetUserInfo(r)
1214	itsok := r.FormValue("itsok")
1215	if itsok == "iforgiveyou" {
1216		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1217		db := opendatabase()
1218		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1219			userinfo.UserID, zonkerid)
1220		bitethethumbs()
1221		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1222		return
1223	}
1224	wherefore := r.FormValue("wherefore")
1225	name := r.FormValue("name")
1226	if name == "" {
1227		return
1228	}
1229	switch wherefore {
1230	case "zonker":
1231	case "zomain":
1232	case "zonvoy":
1233	case "zord":
1234	case "zilence":
1235	default:
1236		return
1237	}
1238	db := opendatabase()
1239	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1240		userinfo.UserID, name, wherefore)
1241	if wherefore == "zonker" || wherefore == "zomain" || wherefore == "zord" || wherefore == "zilence" {
1242		bitethethumbs()
1243	}
1244
1245	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1246}
1247
1248func accountpage(w http.ResponseWriter, r *http.Request) {
1249	u := login.GetUserInfo(r)
1250	user, _ := butwhatabout(u.Username)
1251	templinfo := getInfo(r)
1252	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1253	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1254	templinfo["User"] = user
1255	err := readviews.Execute(w, "account.html", templinfo)
1256	if err != nil {
1257		log.Print(err)
1258	}
1259}
1260
1261func dochpass(w http.ResponseWriter, r *http.Request) {
1262	err := login.ChangePassword(w, r)
1263	if err != nil {
1264		log.Printf("error changing password: %s", err)
1265	}
1266	http.Redirect(w, r, "/account", http.StatusSeeOther)
1267}
1268
1269func fingerlicker(w http.ResponseWriter, r *http.Request) {
1270	orig := r.FormValue("resource")
1271
1272	log.Printf("finger lick: %s", orig)
1273
1274	if strings.HasPrefix(orig, "acct:") {
1275		orig = orig[5:]
1276	}
1277
1278	name := orig
1279	idx := strings.LastIndexByte(name, '/')
1280	if idx != -1 {
1281		name = name[idx+1:]
1282		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1283			log.Printf("foreign request rejected")
1284			name = ""
1285		}
1286	} else {
1287		idx = strings.IndexByte(name, '@')
1288		if idx != -1 {
1289			name = name[:idx]
1290			if name+"@"+serverName != orig {
1291				log.Printf("foreign request rejected")
1292				name = ""
1293			}
1294		}
1295	}
1296	user, err := butwhatabout(name)
1297	if err != nil {
1298		http.NotFound(w, r)
1299		return
1300	}
1301
1302	j := junk.New()
1303	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1304	j["aliases"] = []string{user.URL}
1305	var links []junk.Junk
1306	l := junk.New()
1307	l["rel"] = "self"
1308	l["type"] = `application/activity+json`
1309	l["href"] = user.URL
1310	links = append(links, l)
1311	j["links"] = links
1312
1313	w.Header().Set("Cache-Control", "max-age=3600")
1314	w.Header().Set("Content-Type", "application/jrd+json")
1315	j.Write(w)
1316}
1317
1318func somedays() string {
1319	secs := 432000 + notrand.Int63n(432000)
1320	return fmt.Sprintf("%d", secs)
1321}
1322
1323func avatate(w http.ResponseWriter, r *http.Request) {
1324	n := r.FormValue("a")
1325	a := avatar(n)
1326	w.Header().Set("Cache-Control", "max-age="+somedays())
1327	w.Write(a)
1328}
1329
1330func servecss(w http.ResponseWriter, r *http.Request) {
1331	data, _ := ioutil.ReadFile("views" + r.URL.Path)
1332	s := css.Process(string(data))
1333	w.Header().Set("Cache-Control", "max-age=7776000")
1334	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1335	w.Write([]byte(s))
1336}
1337func servehtml(w http.ResponseWriter, r *http.Request) {
1338	templinfo := getInfo(r)
1339	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1340	if err != nil {
1341		log.Print(err)
1342	}
1343}
1344func serveemu(w http.ResponseWriter, r *http.Request) {
1345	xid := mux.Vars(r)["xid"]
1346	w.Header().Set("Cache-Control", "max-age="+somedays())
1347	http.ServeFile(w, r, "emus/"+xid)
1348}
1349func servememe(w http.ResponseWriter, r *http.Request) {
1350	xid := mux.Vars(r)["xid"]
1351	w.Header().Set("Cache-Control", "max-age="+somedays())
1352	http.ServeFile(w, r, "memes/"+xid)
1353}
1354
1355func servefile(w http.ResponseWriter, r *http.Request) {
1356	xid := mux.Vars(r)["xid"]
1357	row := stmtFileData.QueryRow(xid)
1358	var media string
1359	var data []byte
1360	err := row.Scan(&media, &data)
1361	if err != nil {
1362		log.Printf("error loading file: %s", err)
1363		http.NotFound(w, r)
1364		return
1365	}
1366	w.Header().Set("Content-Type", media)
1367	w.Header().Set("X-Content-Type-Options", "nosniff")
1368	w.Header().Set("Cache-Control", "max-age="+somedays())
1369	w.Write(data)
1370}
1371
1372func nomoroboto(w http.ResponseWriter, r *http.Request) {
1373	io.WriteString(w, "User-agent: *\n")
1374	io.WriteString(w, "Disallow: /a\n")
1375	io.WriteString(w, "Disallow: /d\n")
1376	io.WriteString(w, "Disallow: /meme\n")
1377	for _, u := range allusers() {
1378		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1379	}
1380}
1381
1382func webhydra(w http.ResponseWriter, r *http.Request) {
1383	u := login.GetUserInfo(r)
1384	userid := u.UserID
1385	templinfo := getInfo(r)
1386	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1387	page := r.FormValue("page")
1388	var honks []*Honk
1389	switch page {
1390	case "atme":
1391		honks = gethonksforme(userid)
1392	case "home":
1393		honks = gethonksforuser(userid)
1394		honks = osmosis(honks, userid)
1395	case "convoy":
1396		c := r.FormValue("c")
1397		honks = gethonksbyconvoy(userid, c)
1398	default:
1399		http.NotFound(w, r)
1400	}
1401	if len(honks) > 0 {
1402		templinfo["TopXID"] = honks[0].XID
1403	}
1404	if topxid := r.FormValue("topxid"); topxid != "" {
1405		for i, h := range honks {
1406			if h.XID == topxid {
1407				honks = honks[0:i]
1408				break
1409			}
1410		}
1411		log.Printf("topxid %d frags", len(honks))
1412	}
1413	reverbolate(userid, honks)
1414	templinfo["Honks"] = honks
1415	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1416	err := readviews.Execute(w, "honkfrags.html", templinfo)
1417	if err != nil {
1418		log.Printf("frag error: %s", err)
1419	}
1420}
1421
1422func serve() {
1423	db := opendatabase()
1424	login.Init(db)
1425
1426	listener, err := openListener()
1427	if err != nil {
1428		log.Fatal(err)
1429	}
1430	go redeliverator()
1431
1432	debug := false
1433	getconfig("debug", &debug)
1434	readviews = templates.Load(debug,
1435		"views/honkpage.html",
1436		"views/honkfrags.html",
1437		"views/honkers.html",
1438		"views/zonkers.html",
1439		"views/combos.html",
1440		"views/honkform.html",
1441		"views/honk.html",
1442		"views/account.html",
1443		"views/about.html",
1444		"views/funzone.html",
1445		"views/login.html",
1446		"views/xzone.html",
1447		"views/header.html",
1448		"views/onts.html",
1449		"views/honkpage.js",
1450	)
1451	if !debug {
1452		s := "views/style.css"
1453		savedstyleparams[s] = getstyleparam(s)
1454		s = "views/local.css"
1455		savedstyleparams[s] = getstyleparam(s)
1456	}
1457
1458	bitethethumbs()
1459
1460	mux := mux.NewRouter()
1461	mux.Use(login.Checker)
1462
1463	posters := mux.Methods("POST").Subrouter()
1464	getters := mux.Methods("GET").Subrouter()
1465
1466	getters.HandleFunc("/", homepage)
1467	getters.HandleFunc("/home", homepage)
1468	getters.HandleFunc("/front", homepage)
1469	getters.HandleFunc("/robots.txt", nomoroboto)
1470	getters.HandleFunc("/rss", showrss)
1471	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1472	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1473	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1474	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1475	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1476	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1477	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1478	getters.HandleFunc("/a", avatate)
1479	getters.HandleFunc("/o", thelistingoftheontologies)
1480	getters.HandleFunc("/o/{name:[a-z0-9-]+}", showontology)
1481	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1482	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1483	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1484	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1485
1486	getters.HandleFunc("/style.css", servecss)
1487	getters.HandleFunc("/local.css", servecss)
1488	getters.HandleFunc("/about", servehtml)
1489	getters.HandleFunc("/login", servehtml)
1490	posters.HandleFunc("/dologin", login.LoginFunc)
1491	getters.HandleFunc("/logout", login.LogoutFunc)
1492
1493	loggedin := mux.NewRoute().Subrouter()
1494	loggedin.Use(login.Required)
1495	loggedin.HandleFunc("/account", accountpage)
1496	loggedin.HandleFunc("/funzone", showfunzone)
1497	loggedin.HandleFunc("/chpass", dochpass)
1498	loggedin.HandleFunc("/atme", homepage)
1499	loggedin.HandleFunc("/zonkzone", zonkzone)
1500	loggedin.HandleFunc("/xzone", xzone)
1501	loggedin.HandleFunc("/edit", edithonkpage)
1502	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1503	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1504	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1505	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1506	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1507	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1508	loggedin.HandleFunc("/honkers", showhonkers)
1509	loggedin.HandleFunc("/h/{name:[[:alnum:]]+}", showhonker)
1510	loggedin.HandleFunc("/h", showhonker)
1511	loggedin.HandleFunc("/c/{name:[[:alnum:]]+}", showcombo)
1512	loggedin.HandleFunc("/c", showcombos)
1513	loggedin.HandleFunc("/t", showconvoy)
1514	loggedin.HandleFunc("/q", showsearch)
1515	loggedin.HandleFunc("/hydra", webhydra)
1516	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1517
1518	err = http.Serve(listener, mux)
1519	if err != nil {
1520		log.Fatal(err)
1521	}
1522}