all repos — honk @ c1a6c34f08818a19ad773afacf2b9edce618b96e

my fork of honk

web.go (view raw)

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