all repos — honk @ f5d94aab46f43ac911e506d0dcf1bea8bd711cff

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