all repos — honk @ 2b081dc63590ac40e5cce10dd5a69cfe889f3bbf

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 getbacktracks(xid string) []string {
 894	c := make(chan bool)
 895	dumptracks <- c
 896	<-c
 897	row := stmtGetTracks.QueryRow(xid)
 898	var rawtracks string
 899	err := row.Scan(&rawtracks)
 900	if err != nil {
 901		if err != sql.ErrNoRows {
 902			log.Printf("error scanning tracks: %s", err)
 903		}
 904		return nil
 905	}
 906	var rcpts []string
 907	for _, f := range strings.Split(rawtracks, " ") {
 908		idx := strings.LastIndexByte(f, '#')
 909		if idx != -1 {
 910			f = f[:idx]
 911		}
 912		if !strings.HasPrefix(f, "https://") {
 913			f = fmt.Sprintf("%https://%s/inbox", f)
 914		}
 915		rcpts = append(rcpts, f)
 916	}
 917	return rcpts
 918}
 919
 920func savetracks(tracks map[string][]string) {
 921	db := opendatabase()
 922	tx, err := db.Begin()
 923	if err != nil {
 924		log.Printf("savetracks begin error: %s", err)
 925		return
 926	}
 927	defer func() {
 928		err := tx.Commit()
 929		if err != nil {
 930			log.Printf("savetracks commit error: %s", err)
 931		}
 932
 933	}()
 934	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 935	if err != nil {
 936		log.Printf("savetracks error: %s", err)
 937		return
 938	}
 939	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 940	if err != nil {
 941		log.Printf("savetracks error: %s", err)
 942		return
 943	}
 944	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 945	if err != nil {
 946		log.Printf("savetracks error: %s", err)
 947		return
 948	}
 949	count := 0
 950	for xid, f := range tracks {
 951		count += len(f)
 952		var prev string
 953		row := stmtGetTracks.QueryRow(xid)
 954		err := row.Scan(&prev)
 955		if err == sql.ErrNoRows {
 956			f = oneofakind(f)
 957			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 958		} else if err == nil {
 959			all := append(strings.Split(prev, " "), f...)
 960			all = oneofakind(all)
 961			stmtUpdateTracks.Exec(strings.Join(all, " "))
 962		} else {
 963			log.Printf("savetracks error: %s", err)
 964		}
 965	}
 966	log.Printf("saved %d new fetches", count)
 967}
 968
 969var trackchan = make(chan Track)
 970var dumptracks = make(chan chan bool)
 971
 972func tracker() {
 973	timeout := 4 * time.Minute
 974	sleeper := time.NewTimer(timeout)
 975	tracks := make(map[string][]string)
 976	for {
 977		select {
 978		case track := <-trackchan:
 979			tracks[track.xid] = append(tracks[track.xid], track.who)
 980		case <-sleeper.C:
 981			if len(tracks) > 0 {
 982				go savetracks(tracks)
 983				tracks = make(map[string][]string)
 984			}
 985			sleeper.Reset(timeout)
 986		case c := <-dumptracks:
 987			if len(tracks) > 0 {
 988				savetracks(tracks)
 989			}
 990			c <- true
 991		case <-endoftheworld:
 992			if len(tracks) > 0 {
 993				savetracks(tracks)
 994			}
 995			readyalready <- true
 996			return
 997		}
 998	}
 999}
1000
1001var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1002
1003func trackback(xid string, r *http.Request) {
1004	agent := r.UserAgent()
1005	who := originate(agent)
1006	sig := r.Header.Get("Signature")
1007	if sig != "" {
1008		m := re_keyholder.FindStringSubmatch(sig)
1009		if len(m) == 2 {
1010			who = m[1]
1011		}
1012	}
1013	if who != "" {
1014		trackchan <- Track{xid: xid, who: who}
1015	}
1016}
1017
1018func showonehonk(w http.ResponseWriter, r *http.Request) {
1019	name := mux.Vars(r)["name"]
1020	user, err := butwhatabout(name)
1021	if err != nil {
1022		http.NotFound(w, r)
1023		return
1024	}
1025	if stealthmode(user.ID, r) {
1026		http.NotFound(w, r)
1027		return
1028	}
1029	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1030
1031	if friendorfoe(r.Header.Get("Accept")) {
1032		j, ok := gimmejonk(xid)
1033		if ok {
1034			trackback(xid, r)
1035			w.Header().Set("Content-Type", theonetruename)
1036			w.Write(j)
1037		} else {
1038			http.NotFound(w, r)
1039		}
1040		return
1041	}
1042	honk := getxonk(user.ID, xid)
1043	if honk == nil {
1044		http.NotFound(w, r)
1045		return
1046	}
1047	u := login.GetUserInfo(r)
1048	if u != nil && u.UserID != user.ID {
1049		u = nil
1050	}
1051	if !honk.Public {
1052		if u == nil {
1053			http.NotFound(w, r)
1054			return
1055
1056		}
1057		templinfo := getInfo(r)
1058		templinfo["ServerMessage"] = "one honk maybe more"
1059		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1060		honkpage(w, u, []*Honk{honk}, templinfo)
1061		return
1062	}
1063	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1064	reversehonks(rawhonks)
1065	var honks []*Honk
1066	for _, h := range rawhonks {
1067		if h.XID == xid && len(honks) != 0 {
1068			h.Style += " glow"
1069		}
1070		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1071			honks = append(honks, h)
1072		}
1073	}
1074
1075	templinfo := getInfo(r)
1076	templinfo["ServerMessage"] = "one honk maybe more"
1077	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1078	honkpage(w, u, honks, templinfo)
1079}
1080
1081func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1082	var userid int64 = -1
1083	if u != nil {
1084		userid = u.UserID
1085	}
1086	reverbolate(userid, honks)
1087	templinfo["Honks"] = honks
1088	templinfo["MapLink"] = getmaplink(u)
1089	if templinfo["TopHID"] == nil {
1090		if len(honks) > 0 {
1091			templinfo["TopHID"] = honks[0].ID
1092		} else {
1093			templinfo["TopHID"] = 0
1094		}
1095	}
1096	if u == nil {
1097		w.Header().Set("Cache-Control", "max-age=60")
1098	}
1099	err := readviews.Execute(w, "honkpage.html", templinfo)
1100	if err != nil {
1101		log.Print(err)
1102	}
1103}
1104
1105var re_avatar = regexp.MustCompile("avatar: ?([[:alnum:]_.-]+)")
1106
1107func saveuser(w http.ResponseWriter, r *http.Request) {
1108	whatabout := r.FormValue("whatabout")
1109	u := login.GetUserInfo(r)
1110	user, _ := butwhatabout(u.Username)
1111	db := opendatabase()
1112	options := user.Options
1113	if r.FormValue("skinny") == "skinny" {
1114		options.SkinnyCSS = true
1115	} else {
1116		options.SkinnyCSS = false
1117	}
1118	if r.FormValue("maps") == "apple" {
1119		options.MapLink = "apple"
1120	} else {
1121		options.MapLink = ""
1122	}
1123	if ava := re_avatar.FindString(whatabout); ava != "" {
1124		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1125		ava = ava[7:]
1126		if ava[0] == ' ' {
1127			ava = ava[1:]
1128		}
1129		options.Avatar = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1130	} else {
1131		options.Avatar = ""
1132	}
1133	whatabout = strings.TrimSpace(whatabout)
1134	j, err := jsonify(options)
1135	if err == nil {
1136		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1137	}
1138	if err != nil {
1139		log.Printf("error bouting what: %s", err)
1140	}
1141	somenamedusers.Clear(u.Username)
1142	somenumberedusers.Clear(u.UserID)
1143
1144	http.Redirect(w, r, "/account", http.StatusSeeOther)
1145}
1146
1147func submitbonk(w http.ResponseWriter, r *http.Request) {
1148	xid := r.FormValue("xid")
1149	userinfo := login.GetUserInfo(r)
1150	user, _ := butwhatabout(userinfo.Username)
1151
1152	log.Printf("bonking %s", xid)
1153
1154	xonk := getxonk(userinfo.UserID, xid)
1155	if xonk == nil {
1156		return
1157	}
1158	if !xonk.Public {
1159		return
1160	}
1161	if xonk.IsBonked() {
1162		return
1163	}
1164	donksforhonks([]*Honk{xonk})
1165
1166	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1167	if err != nil {
1168		log.Printf("error acking bonk: %s", err)
1169	}
1170
1171	oonker := xonk.Oonker
1172	if oonker == "" {
1173		oonker = xonk.Honker
1174	}
1175	dt := time.Now().UTC()
1176	bonk := &Honk{
1177		UserID:   userinfo.UserID,
1178		Username: userinfo.Username,
1179		What:     "bonk",
1180		Honker:   user.URL,
1181		Oonker:   oonker,
1182		XID:      xonk.XID,
1183		RID:      xonk.RID,
1184		Noise:    xonk.Noise,
1185		Precis:   xonk.Precis,
1186		URL:      xonk.URL,
1187		Date:     dt,
1188		Donks:    xonk.Donks,
1189		Whofore:  2,
1190		Convoy:   xonk.Convoy,
1191		Audience: []string{thewholeworld, oonker},
1192		Public:   true,
1193		Format:   "html",
1194		Place:    xonk.Place,
1195		Onts:     xonk.Onts,
1196		Time:     xonk.Time,
1197	}
1198
1199	err = savehonk(bonk)
1200	if err != nil {
1201		log.Printf("uh oh")
1202		return
1203	}
1204
1205	go honkworldwide(user, bonk)
1206
1207	if r.FormValue("js") != "1" {
1208		templinfo := getInfo(r)
1209		templinfo["ServerMessage"] = "Bonked!"
1210		err = readviews.Execute(w, "msg.html", templinfo)
1211		if err != nil {
1212			log.Print(err)
1213		}
1214	}
1215}
1216
1217func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1218	zonk := &Honk{
1219		What:     what,
1220		XID:      xonk.XID,
1221		Date:     time.Now().UTC(),
1222		Audience: oneofakind(xonk.Audience),
1223	}
1224	zonk.Public = loudandproud(zonk.Audience)
1225
1226	log.Printf("announcing %sed honk: %s", what, xonk.XID)
1227	go honkworldwide(user, zonk)
1228}
1229
1230func zonkit(w http.ResponseWriter, r *http.Request) {
1231	wherefore := r.FormValue("wherefore")
1232	what := r.FormValue("what")
1233	userinfo := login.GetUserInfo(r)
1234	user, _ := butwhatabout(userinfo.Username)
1235
1236	if wherefore == "save" {
1237		xonk := getxonk(userinfo.UserID, what)
1238		if xonk != nil {
1239			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1240			if err != nil {
1241				log.Printf("error saving: %s", err)
1242			}
1243		}
1244		return
1245	}
1246
1247	if wherefore == "unsave" {
1248		xonk := getxonk(userinfo.UserID, what)
1249		if xonk != nil {
1250			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1251			if err != nil {
1252				log.Printf("error unsaving: %s", err)
1253			}
1254		}
1255		return
1256	}
1257
1258	// my hammer is too big, oh well
1259	defer oldjonks.Flush()
1260
1261	if wherefore == "ack" {
1262		xonk := getxonk(userinfo.UserID, what)
1263		if xonk != nil && !xonk.IsAcked() {
1264			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1265			if err != nil {
1266				log.Printf("error acking: %s", err)
1267			}
1268			sendzonkofsorts(xonk, user, "ack")
1269		}
1270		return
1271	}
1272
1273	if wherefore == "deack" {
1274		xonk := getxonk(userinfo.UserID, what)
1275		if xonk != nil && xonk.IsAcked() {
1276			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1277			if err != nil {
1278				log.Printf("error deacking: %s", err)
1279			}
1280			sendzonkofsorts(xonk, user, "deack")
1281		}
1282		return
1283	}
1284
1285	if wherefore == "unbonk" {
1286		xonk := getbonk(userinfo.UserID, what)
1287		if xonk != nil {
1288			deletehonk(xonk.ID)
1289			xonk = getxonk(userinfo.UserID, what)
1290			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1291			if err != nil {
1292				log.Printf("error unbonking: %s", err)
1293			}
1294			sendzonkofsorts(xonk, user, "unbonk")
1295		}
1296		return
1297	}
1298
1299	if wherefore == "untag" {
1300		xonk := getxonk(userinfo.UserID, what)
1301		if xonk != nil {
1302			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1303			if err != nil {
1304				log.Printf("error untagging: %s", err)
1305			}
1306		}
1307		var badparents map[string]bool
1308		untagged.GetAndLock(userinfo.UserID, &badparents)
1309		badparents[what] = true
1310		untagged.Unlock()
1311		return
1312	}
1313
1314	log.Printf("zonking %s %s", wherefore, what)
1315	if wherefore == "zonk" {
1316		xonk := getxonk(userinfo.UserID, what)
1317		if xonk != nil {
1318			deletehonk(xonk.ID)
1319			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1320				sendzonkofsorts(xonk, user, "zonk")
1321			}
1322		}
1323	}
1324	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1325	if err != nil {
1326		log.Printf("error saving zonker: %s", err)
1327		return
1328	}
1329}
1330
1331func edithonkpage(w http.ResponseWriter, r *http.Request) {
1332	u := login.GetUserInfo(r)
1333	user, _ := butwhatabout(u.Username)
1334	xid := r.FormValue("xid")
1335	honk := getxonk(u.UserID, xid)
1336	if !canedithonk(user, honk) {
1337		http.Error(w, "no editing that please", http.StatusInternalServerError)
1338		return
1339	}
1340
1341	noise := honk.Noise
1342
1343	honks := []*Honk{honk}
1344	donksforhonks(honks)
1345	reverbolate(u.UserID, honks)
1346	templinfo := getInfo(r)
1347	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1348	templinfo["Honks"] = honks
1349	templinfo["MapLink"] = getmaplink(u)
1350	templinfo["Noise"] = noise
1351	templinfo["SavedPlace"] = honk.Place
1352	templinfo["ServerMessage"] = "honk edit"
1353	templinfo["IsPreview"] = true
1354	templinfo["UpdateXID"] = honk.XID
1355	if len(honk.Donks) > 0 {
1356		templinfo["SavedFile"] = honk.Donks[0].XID
1357	}
1358	err := readviews.Execute(w, "honkpage.html", templinfo)
1359	if err != nil {
1360		log.Print(err)
1361	}
1362}
1363
1364func newhonkpage(w http.ResponseWriter, r *http.Request) {
1365	u := login.GetUserInfo(r)
1366	rid := r.FormValue("rid")
1367	noise := ""
1368
1369	xonk := getxonk(u.UserID, rid)
1370	if xonk != nil {
1371		_, replto := handles(xonk.Honker)
1372		if replto != "" {
1373			noise = "@" + replto + " "
1374		}
1375	}
1376
1377	templinfo := getInfo(r)
1378	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1379	templinfo["InReplyTo"] = rid
1380	templinfo["Noise"] = noise
1381	templinfo["ServerMessage"] = "compose honk"
1382	templinfo["IsPreview"] = true
1383	err := readviews.Execute(w, "honkpage.html", templinfo)
1384	if err != nil {
1385		log.Print(err)
1386	}
1387}
1388
1389func canedithonk(user *WhatAbout, honk *Honk) bool {
1390	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1391		return false
1392	}
1393	return true
1394}
1395
1396func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1397	submithonk(w, r, false)
1398}
1399
1400// what a hot mess this function is
1401func submithonk(w http.ResponseWriter, r *http.Request, isAPI bool) {
1402	rid := r.FormValue("rid")
1403	noise := r.FormValue("noise")
1404
1405	userinfo := login.GetUserInfo(r)
1406	user, _ := butwhatabout(userinfo.Username)
1407
1408	dt := time.Now().UTC()
1409	updatexid := r.FormValue("updatexid")
1410	var honk *Honk
1411	if updatexid != "" {
1412		honk = getxonk(userinfo.UserID, updatexid)
1413		if !canedithonk(user, honk) {
1414			http.Error(w, "no editing that please", http.StatusInternalServerError)
1415			return
1416		}
1417		honk.Date = dt
1418		honk.What = "update"
1419		honk.Format = "markdown"
1420	} else {
1421		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1422		what := "honk"
1423		if rid != "" {
1424			what = "tonk"
1425		}
1426		honk = &Honk{
1427			UserID:   userinfo.UserID,
1428			Username: userinfo.Username,
1429			What:     what,
1430			Honker:   user.URL,
1431			XID:      xid,
1432			Date:     dt,
1433			Format:   "markdown",
1434		}
1435	}
1436
1437	noise = strings.Replace(noise, "\r", "", -1)
1438	noise = quickrename(noise, userinfo.UserID)
1439	noise = hooterize(noise)
1440	honk.Noise = noise
1441	translate(honk, false)
1442
1443	var convoy string
1444	if rid != "" {
1445		xonk := getxonk(userinfo.UserID, rid)
1446		if xonk != nil {
1447			if xonk.Public {
1448				honk.Audience = append(honk.Audience, xonk.Audience...)
1449			}
1450			convoy = xonk.Convoy
1451		} else {
1452			xonkaud, c := whosthere(rid)
1453			honk.Audience = append(honk.Audience, xonkaud...)
1454			convoy = c
1455		}
1456		for i, a := range honk.Audience {
1457			if a == thewholeworld {
1458				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1459				break
1460			}
1461		}
1462		honk.RID = rid
1463		if xonk.Precis != "" && honk.Precis == "" {
1464			honk.Precis = xonk.Precis
1465			if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1466				honk.Precis = "re: " + honk.Precis
1467			}
1468		}
1469	} else {
1470		honk.Audience = []string{thewholeworld}
1471	}
1472	if honk.Noise != "" && honk.Noise[0] == '@' {
1473		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1474	} else {
1475		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1476	}
1477
1478	if convoy == "" {
1479		convoy = "data:,electrichonkytonk-" + xfiltrate()
1480	}
1481	butnottooloud(honk.Audience)
1482	honk.Audience = oneofakind(honk.Audience)
1483	if len(honk.Audience) == 0 {
1484		log.Printf("honk to nowhere")
1485		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1486		return
1487	}
1488	honk.Public = loudandproud(honk.Audience)
1489	honk.Convoy = convoy
1490
1491	donkxid := r.FormValue("donkxid")
1492	if donkxid == "" {
1493		file, filehdr, err := r.FormFile("donk")
1494		if err == nil {
1495			var buf bytes.Buffer
1496			io.Copy(&buf, file)
1497			file.Close()
1498			data := buf.Bytes()
1499			xid := xfiltrate()
1500			var media, name string
1501			img, err := shrinkit(data)
1502			if err == nil {
1503				data = img.Data
1504				format := img.Format
1505				media = "image/" + format
1506				if format == "jpeg" {
1507					format = "jpg"
1508				}
1509				name = xid + "." + format
1510				xid = name
1511			} else {
1512				ct := http.DetectContentType(data)
1513				switch ct {
1514				case "application/pdf":
1515					maxsize := 1000000
1516					if len(data) > maxsize {
1517						log.Printf("bad image: %s too much pdf: %d", err, len(data))
1518						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1519						return
1520					}
1521					media = ct
1522					xid += ".pdf"
1523					name = filehdr.Filename
1524					if name == "" {
1525						name = xid
1526					}
1527				default:
1528					maxsize := 100000
1529					if len(data) > maxsize {
1530						log.Printf("bad image: %s too much text: %d", err, len(data))
1531						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1532						return
1533					}
1534					for i := 0; i < len(data); i++ {
1535						if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1536							log.Printf("bad image: %s not text: %d", err, data[i])
1537							http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1538							return
1539						}
1540					}
1541					media = "text/plain"
1542					xid += ".txt"
1543					name = filehdr.Filename
1544					if name == "" {
1545						name = xid
1546					}
1547				}
1548			}
1549			desc := strings.TrimSpace(r.FormValue("donkdesc"))
1550			if desc == "" {
1551				desc = name
1552			}
1553			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1554			fileid, err := savefile(xid, name, desc, url, media, true, data)
1555			if err != nil {
1556				log.Printf("unable to save image: %s", err)
1557				return
1558			}
1559			d := &Donk{
1560				FileID: fileid,
1561				XID:    xid,
1562				Desc:   desc,
1563				URL:    url,
1564				Local:  true,
1565			}
1566			honk.Donks = append(honk.Donks, d)
1567			donkxid = xid
1568		}
1569	} else {
1570		xid := donkxid
1571		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1572		donk := finddonk(url)
1573		if donk != nil {
1574			honk.Donks = append(honk.Donks, donk)
1575		} else {
1576			log.Printf("can't find file: %s", xid)
1577		}
1578	}
1579	herd := herdofemus(noise)
1580	for _, e := range herd {
1581		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1582		if donk != nil {
1583			donk.Name = e.Name
1584			honk.Donks = append(honk.Donks, donk)
1585		}
1586	}
1587	memetize(honk)
1588	imaginate(honk)
1589
1590	placename := strings.TrimSpace(r.FormValue("placename"))
1591	placelat := strings.TrimSpace(r.FormValue("placelat"))
1592	placelong := strings.TrimSpace(r.FormValue("placelong"))
1593	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1594	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1595		p := new(Place)
1596		p.Name = placename
1597		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1598		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1599		p.Url = placeurl
1600		honk.Place = p
1601	}
1602	timestart := strings.TrimSpace(r.FormValue("timestart"))
1603	if timestart != "" {
1604		t := new(Time)
1605		now := time.Now().Local()
1606		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1607			start, err := time.ParseInLocation(layout, timestart, now.Location())
1608			if err == nil {
1609				if start.Year() == 0 {
1610					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1611				}
1612				t.StartTime = start
1613				break
1614			}
1615		}
1616		timeend := r.FormValue("timeend")
1617		dur := parseDuration(timeend)
1618		if dur != 0 {
1619			t.Duration = Duration(dur)
1620		}
1621		if !t.StartTime.IsZero() {
1622			honk.What = "event"
1623			honk.Time = t
1624		}
1625	}
1626
1627	if honk.Public {
1628		honk.Whofore = 2
1629	} else {
1630		honk.Whofore = 3
1631	}
1632
1633	// back to markdown
1634	honk.Noise = noise
1635
1636	if r.FormValue("preview") == "preview" {
1637		honks := []*Honk{honk}
1638		reverbolate(userinfo.UserID, honks)
1639		templinfo := getInfo(r)
1640		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1641		templinfo["Honks"] = honks
1642		templinfo["MapLink"] = getmaplink(userinfo)
1643		templinfo["InReplyTo"] = r.FormValue("rid")
1644		templinfo["Noise"] = r.FormValue("noise")
1645		templinfo["SavedFile"] = donkxid
1646		templinfo["IsPreview"] = true
1647		templinfo["UpdateXID"] = updatexid
1648		templinfo["ServerMessage"] = "honk preview"
1649		err := readviews.Execute(w, "honkpage.html", templinfo)
1650		if err != nil {
1651			log.Print(err)
1652		}
1653		return
1654	}
1655
1656	if updatexid != "" {
1657		updatehonk(honk)
1658		oldjonks.Clear(honk.XID)
1659	} else {
1660		err := savehonk(honk)
1661		if err != nil {
1662			log.Printf("uh oh")
1663			return
1664		}
1665	}
1666
1667	// reload for consistency
1668	honk.Donks = nil
1669	donksforhonks([]*Honk{honk})
1670
1671	go honkworldwide(user, honk)
1672
1673	if isAPI {
1674		w.Write([]byte(honk.XID))
1675	} else {
1676		http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1677	}
1678}
1679
1680func showhonkers(w http.ResponseWriter, r *http.Request) {
1681	userinfo := login.GetUserInfo(r)
1682	templinfo := getInfo(r)
1683	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1684	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1685	err := readviews.Execute(w, "honkers.html", templinfo)
1686	if err != nil {
1687		log.Print(err)
1688	}
1689}
1690
1691var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1692	honkers := gethonkers(userid)
1693	var combos []string
1694	for _, h := range honkers {
1695		combos = append(combos, h.Combos...)
1696	}
1697	for i, c := range combos {
1698		if c == "-" {
1699			combos[i] = ""
1700		}
1701	}
1702	combos = oneofakind(combos)
1703	sort.Strings(combos)
1704	return combos, true
1705}, Invalidator: &honkerinvalidator})
1706
1707func showcombos(w http.ResponseWriter, r *http.Request) {
1708	userinfo := login.GetUserInfo(r)
1709	var combos []string
1710	combocache.Get(userinfo.UserID, &combos)
1711	templinfo := getInfo(r)
1712	err := readviews.Execute(w, "combos.html", templinfo)
1713	if err != nil {
1714		log.Print(err)
1715	}
1716}
1717
1718func submithonker(w http.ResponseWriter, r *http.Request) {
1719	u := login.GetUserInfo(r)
1720	name := strings.TrimSpace(r.FormValue("name"))
1721	url := strings.TrimSpace(r.FormValue("url"))
1722	peep := r.FormValue("peep")
1723	combos := strings.TrimSpace(r.FormValue("combos"))
1724	combos = " " + combos + " "
1725	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1726
1727	defer honkerinvalidator.Clear(u.UserID)
1728
1729	if honkerid > 0 {
1730		goodbye := r.FormValue("goodbye")
1731		if goodbye == "F" {
1732			db := opendatabase()
1733			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1734				honkerid, u.UserID)
1735			err := row.Scan(&url)
1736			if err != nil {
1737				log.Printf("can't get honker xid: %s", err)
1738				return
1739			}
1740			log.Printf("unsubscribing from %s", url)
1741			user, _ := butwhatabout(u.Username)
1742			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1743			if err != nil {
1744				log.Printf("error updating honker: %s", err)
1745				return
1746			}
1747			go itakeitallback(user, url)
1748
1749			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1750			return
1751		}
1752		if goodbye == "X" {
1753			var owner string
1754			db := opendatabase()
1755			row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1756				honkerid, u.UserID)
1757			err := row.Scan(&url, &owner)
1758			if err != nil {
1759				log.Printf("can't get honker xid: %s", err)
1760				return
1761			}
1762			log.Printf("resubscribing to %s", url)
1763			user, _ := butwhatabout(u.Username)
1764			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1765			if err == nil {
1766				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1767			}
1768			if err != nil {
1769				log.Printf("error updating honker: %s", err)
1770				return
1771			}
1772			go subsub(user, url, owner)
1773
1774			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1775			return
1776		}
1777		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1778		if err != nil {
1779			log.Printf("update honker err: %s", err)
1780			return
1781		}
1782		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1783		return
1784	}
1785
1786	if url == "" {
1787		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1788		return
1789	}
1790
1791	flavor := "presub"
1792	if peep == "peep" {
1793		flavor = "peep"
1794	}
1795
1796	if url[0] == '#' {
1797		flavor = "peep"
1798		if name == "" {
1799			name = url
1800		}
1801		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1802		if err != nil {
1803			log.Print(err)
1804			return
1805		}
1806		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1807		return
1808	}
1809
1810	info, err := investigate(url)
1811	if err != nil {
1812		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1813		log.Printf("failed to investigate honker: %s", err)
1814		return
1815	}
1816	url = info.XID
1817
1818	var x string
1819	db := opendatabase()
1820	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1821	err = row.Scan(&x)
1822	if err != sql.ErrNoRows {
1823		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1824		if err != nil {
1825			log.Printf("honker scan err: %s", err)
1826		}
1827		return
1828	}
1829
1830	if name == "" {
1831		name = info.Name
1832	}
1833	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1834	if err != nil {
1835		log.Print(err)
1836		return
1837	}
1838	if flavor == "presub" {
1839		user, _ := butwhatabout(u.Username)
1840		go subsub(user, url, info.Owner)
1841	}
1842	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1843}
1844
1845func hfcspage(w http.ResponseWriter, r *http.Request) {
1846	userinfo := login.GetUserInfo(r)
1847
1848	filters := getfilters(userinfo.UserID, filtAny)
1849
1850	templinfo := getInfo(r)
1851	templinfo["Filters"] = filters
1852	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1853	err := readviews.Execute(w, "hfcs.html", templinfo)
1854	if err != nil {
1855		log.Print(err)
1856	}
1857}
1858
1859func savehfcs(w http.ResponseWriter, r *http.Request) {
1860	userinfo := login.GetUserInfo(r)
1861	itsok := r.FormValue("itsok")
1862	if itsok == "iforgiveyou" {
1863		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1864		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1865		if err != nil {
1866			log.Printf("error deleting filter: %s", err)
1867		}
1868		filtcache.Clear(userinfo.UserID)
1869		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1870		return
1871	}
1872
1873	filt := new(Filter)
1874	filt.Name = strings.TrimSpace(r.FormValue("name"))
1875	filt.Date = time.Now().UTC()
1876	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1877	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1878	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1879	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1880	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1881	filt.Reject = r.FormValue("doreject") == "yes"
1882	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1883	filt.Hide = r.FormValue("dohide") == "yes"
1884	filt.Collapse = r.FormValue("docollapse") == "yes"
1885	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1886	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1887	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1888		filt.Expiration = time.Now().UTC().Add(dur)
1889	}
1890
1891	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1892		log.Printf("blank filter")
1893		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1894		return
1895	}
1896
1897	j, err := jsonify(filt)
1898	if err == nil {
1899		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1900	}
1901	if err != nil {
1902		log.Printf("error saving filter: %s", err)
1903	}
1904
1905	filtcache.Clear(userinfo.UserID)
1906	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1907}
1908
1909func accountpage(w http.ResponseWriter, r *http.Request) {
1910	u := login.GetUserInfo(r)
1911	user, _ := butwhatabout(u.Username)
1912	templinfo := getInfo(r)
1913	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1914	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1915	templinfo["User"] = user
1916	about := user.About
1917	if ava := user.Options.Avatar; ava != "" {
1918		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
1919	}
1920	templinfo["WhatAbout"] = about
1921	err := readviews.Execute(w, "account.html", templinfo)
1922	if err != nil {
1923		log.Print(err)
1924	}
1925}
1926
1927func dochpass(w http.ResponseWriter, r *http.Request) {
1928	err := login.ChangePassword(w, r)
1929	if err != nil {
1930		log.Printf("error changing password: %s", err)
1931	}
1932	http.Redirect(w, r, "/account", http.StatusSeeOther)
1933}
1934
1935func fingerlicker(w http.ResponseWriter, r *http.Request) {
1936	orig := r.FormValue("resource")
1937
1938	log.Printf("finger lick: %s", orig)
1939
1940	if strings.HasPrefix(orig, "acct:") {
1941		orig = orig[5:]
1942	}
1943
1944	name := orig
1945	idx := strings.LastIndexByte(name, '/')
1946	if idx != -1 {
1947		name = name[idx+1:]
1948		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1949			log.Printf("foreign request rejected")
1950			name = ""
1951		}
1952	} else {
1953		idx = strings.IndexByte(name, '@')
1954		if idx != -1 {
1955			name = name[:idx]
1956			if name+"@"+serverName != orig {
1957				log.Printf("foreign request rejected")
1958				name = ""
1959			}
1960		}
1961	}
1962	user, err := butwhatabout(name)
1963	if err != nil {
1964		http.NotFound(w, r)
1965		return
1966	}
1967	if stealthmode(user.ID, r) {
1968		http.NotFound(w, r)
1969		return
1970	}
1971
1972	j := junk.New()
1973	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1974	j["aliases"] = []string{user.URL}
1975	l := junk.New()
1976	l["rel"] = "self"
1977	l["type"] = `application/activity+json`
1978	l["href"] = user.URL
1979	j["links"] = []junk.Junk{l}
1980
1981	w.Header().Set("Content-Type", "application/jrd+json")
1982	j.Write(w)
1983}
1984
1985func somedays() string {
1986	secs := 432000 + notrand.Int63n(432000)
1987	return fmt.Sprintf("%d", secs)
1988}
1989
1990func avatate(w http.ResponseWriter, r *http.Request) {
1991	n := r.FormValue("a")
1992	a := avatar(n)
1993	w.Header().Set("Cache-Control", "max-age="+somedays())
1994	w.Write(a)
1995}
1996
1997func serveasset(w http.ResponseWriter, r *http.Request) {
1998	w.Header().Set("Cache-Control", "max-age=7776000")
1999	dir := viewDir
2000	if r.URL.Path == "/local.css" {
2001		dir = dataDir
2002	}
2003	http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2004}
2005func servehelp(w http.ResponseWriter, r *http.Request) {
2006	name := mux.Vars(r)["name"]
2007	w.Header().Set("Cache-Control", "max-age=3600")
2008	http.ServeFile(w, r, viewDir+"/docs/"+name)
2009}
2010func servehtml(w http.ResponseWriter, r *http.Request) {
2011	u := login.GetUserInfo(r)
2012	templinfo := getInfo(r)
2013	templinfo["AboutMsg"] = aboutMsg
2014	templinfo["LoginMsg"] = loginMsg
2015	templinfo["HonkVersion"] = softwareVersion
2016	if r.URL.Path == "/about" {
2017		templinfo["Sensors"] = getSensors()
2018	}
2019	if u == nil {
2020		w.Header().Set("Cache-Control", "max-age=60")
2021	}
2022	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2023	if err != nil {
2024		log.Print(err)
2025	}
2026}
2027func serveemu(w http.ResponseWriter, r *http.Request) {
2028	xid := mux.Vars(r)["xid"]
2029	w.Header().Set("Cache-Control", "max-age="+somedays())
2030	http.ServeFile(w, r, dataDir+"/emus/"+xid)
2031}
2032func servememe(w http.ResponseWriter, r *http.Request) {
2033	xid := mux.Vars(r)["xid"]
2034	w.Header().Set("Cache-Control", "max-age="+somedays())
2035	http.ServeFile(w, r, dataDir+"/memes/"+xid)
2036}
2037
2038func servefile(w http.ResponseWriter, r *http.Request) {
2039	xid := mux.Vars(r)["xid"]
2040	var media string
2041	var data []byte
2042	row := stmtGetFileData.QueryRow(xid)
2043	err := row.Scan(&media, &data)
2044	if err != nil {
2045		log.Printf("error loading file: %s", err)
2046		http.NotFound(w, r)
2047		return
2048	}
2049	w.Header().Set("Content-Type", media)
2050	w.Header().Set("X-Content-Type-Options", "nosniff")
2051	w.Header().Set("Cache-Control", "max-age="+somedays())
2052	w.Write(data)
2053}
2054
2055func nomoroboto(w http.ResponseWriter, r *http.Request) {
2056	io.WriteString(w, "User-agent: *\n")
2057	io.WriteString(w, "Disallow: /a\n")
2058	io.WriteString(w, "Disallow: /d\n")
2059	io.WriteString(w, "Disallow: /meme\n")
2060	io.WriteString(w, "Disallow: /o\n")
2061	for _, u := range allusers() {
2062		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2063	}
2064}
2065
2066func webhydra(w http.ResponseWriter, r *http.Request) {
2067	u := login.GetUserInfo(r)
2068	userid := u.UserID
2069	templinfo := getInfo(r)
2070	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2071	page := r.FormValue("page")
2072
2073	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2074
2075	var honks []*Honk
2076	switch page {
2077	case "atme":
2078		honks = gethonksforme(userid, wanted)
2079		honks = osmosis(honks, userid, false)
2080		templinfo["ServerMessage"] = "at me!"
2081	case "home":
2082		honks = gethonksforuser(userid, wanted)
2083		honks = osmosis(honks, userid, true)
2084		templinfo["ServerMessage"] = serverMsg
2085	case "first":
2086		honks = gethonksforuserfirstclass(userid, wanted)
2087		honks = osmosis(honks, userid, true)
2088		templinfo["ServerMessage"] = "first class only"
2089	case "saved":
2090		honks = getsavedhonks(userid, wanted)
2091		templinfo["PageName"] = "saved"
2092		templinfo["ServerMessage"] = "saved honks"
2093	case "combo":
2094		c := r.FormValue("c")
2095		honks = gethonksbycombo(userid, c, wanted)
2096		honks = osmosis(honks, userid, false)
2097		templinfo["ServerMessage"] = "honks by combo: " + c
2098	case "convoy":
2099		c := r.FormValue("c")
2100		honks = gethonksbyconvoy(userid, c, wanted)
2101		honks = osmosis(honks, userid, false)
2102		templinfo["ServerMessage"] = "honks in convoy: " + c
2103	case "honker":
2104		xid := r.FormValue("xid")
2105		honks = gethonksbyxonker(userid, xid, wanted)
2106		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2107		templinfo["ServerMessage"] = msg
2108	default:
2109		http.NotFound(w, r)
2110	}
2111	if len(honks) > 0 {
2112		templinfo["TopHID"] = honks[0].ID
2113	} else {
2114		templinfo["TopHID"] = wanted
2115	}
2116	reverbolate(userid, honks)
2117	templinfo["Honks"] = honks
2118	templinfo["MapLink"] = getmaplink(u)
2119	w.Header().Set("Content-Type", "text/html; charset=utf-8")
2120	err := readviews.Execute(w, "honkfrags.html", templinfo)
2121	if err != nil {
2122		log.Printf("frag error: %s", err)
2123	}
2124}
2125
2126var honkline = make(chan bool)
2127
2128func honkhonkline() {
2129	for {
2130		select {
2131		case honkline <- true:
2132		default:
2133			return
2134		}
2135	}
2136}
2137
2138func apihandler(w http.ResponseWriter, r *http.Request) {
2139	u := login.GetUserInfo(r)
2140	userid := u.UserID
2141	action := r.FormValue("action")
2142	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2143	log.Printf("api request '%s' on behalf of %s", action, u.Username)
2144	switch action {
2145	case "honk":
2146		submithonk(w, r, true)
2147	case "gethonks":
2148		var honks []*Honk
2149		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2150		page := r.FormValue("page")
2151		var waitchan <-chan time.Time
2152	requery:
2153		switch page {
2154		case "atme":
2155			honks = gethonksforme(userid, wanted)
2156			honks = osmosis(honks, userid, false)
2157		case "home":
2158			honks = gethonksforuser(userid, wanted)
2159			honks = osmosis(honks, userid, true)
2160		default:
2161			http.Error(w, "unknown page", http.StatusNotFound)
2162			return
2163		}
2164		if len(honks) == 0 && wait > 0 {
2165			if waitchan == nil {
2166				waitchan = time.After(time.Duration(wait) * time.Second)
2167			}
2168			select {
2169			case <-honkline:
2170				goto requery
2171			case <-waitchan:
2172			}
2173		}
2174		reverbolate(userid, honks)
2175		j := junk.New()
2176		j["honks"] = honks
2177		j.Write(w)
2178	default:
2179		http.Error(w, "unknown action", http.StatusNotFound)
2180		return
2181	}
2182}
2183
2184var endoftheworld = make(chan bool)
2185var readyalready = make(chan bool)
2186
2187func enditall() {
2188	sig := make(chan os.Signal)
2189	signal.Notify(sig, os.Interrupt)
2190	signal.Notify(sig, syscall.SIGTERM)
2191	<-sig
2192	count := 0
2193	log.Printf("stopping...")
2194sendloop:
2195	for {
2196		select {
2197		case endoftheworld <- true:
2198			count++
2199		default:
2200			break sendloop
2201		}
2202	}
2203	log.Printf("waiting...")
2204	for i := 0; i < count; i++ {
2205		<-readyalready
2206	}
2207	log.Printf("apocalypse")
2208	os.Exit(0)
2209}
2210
2211var preservehooks []func()
2212
2213func serve() {
2214	db := opendatabase()
2215	login.Init(db)
2216
2217	listener, err := openListener()
2218	if err != nil {
2219		log.Fatal(err)
2220	}
2221	startBackendServer()
2222	go enditall()
2223	go redeliverator()
2224	go tracker()
2225
2226	debug := false
2227	getconfig("debug", &debug)
2228	readviews = templates.Load(debug,
2229		viewDir+"/views/honkpage.html",
2230		viewDir+"/views/honkfrags.html",
2231		viewDir+"/views/honkers.html",
2232		viewDir+"/views/hfcs.html",
2233		viewDir+"/views/combos.html",
2234		viewDir+"/views/honkform.html",
2235		viewDir+"/views/honk.html",
2236		viewDir+"/views/account.html",
2237		viewDir+"/views/about.html",
2238		viewDir+"/views/funzone.html",
2239		viewDir+"/views/login.html",
2240		viewDir+"/views/xzone.html",
2241		viewDir+"/views/msg.html",
2242		viewDir+"/views/header.html",
2243		viewDir+"/views/onts.html",
2244		viewDir+"/views/honkpage.js",
2245	)
2246	if !debug {
2247		assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2248		for _, s := range assets {
2249			savedassetparams[s] = getassetparam(s)
2250		}
2251	}
2252
2253	for _, h := range preservehooks {
2254		h()
2255	}
2256
2257	mux := mux.NewRouter()
2258	mux.Use(login.Checker)
2259
2260	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2261
2262	posters := mux.Methods("POST").Subrouter()
2263	getters := mux.Methods("GET").Subrouter()
2264
2265	getters.HandleFunc("/", homepage)
2266	getters.HandleFunc("/home", homepage)
2267	getters.HandleFunc("/front", homepage)
2268	getters.HandleFunc("/events", homepage)
2269	getters.HandleFunc("/robots.txt", nomoroboto)
2270	getters.HandleFunc("/rss", showrss)
2271	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2272	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2273	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2274	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2275	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2276	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2277	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2278	getters.HandleFunc("/a", avatate)
2279	getters.HandleFunc("/o", thelistingoftheontologies)
2280	getters.HandleFunc("/o/{name:.+}", showontology)
2281	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2282	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
2283	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
2284	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2285
2286	getters.HandleFunc("/server", serveractor)
2287	posters.HandleFunc("/server/inbox", serverinbox)
2288
2289	getters.HandleFunc("/style.css", serveasset)
2290	getters.HandleFunc("/local.css", serveasset)
2291	getters.HandleFunc("/honkpage.js", serveasset)
2292	getters.HandleFunc("/about", servehtml)
2293	getters.HandleFunc("/login", servehtml)
2294	posters.HandleFunc("/dologin", login.LoginFunc)
2295	getters.HandleFunc("/logout", login.LogoutFunc)
2296	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2297
2298	loggedin := mux.NewRoute().Subrouter()
2299	loggedin.Use(login.Required)
2300	loggedin.HandleFunc("/first", homepage)
2301	loggedin.HandleFunc("/saved", homepage)
2302	loggedin.HandleFunc("/account", accountpage)
2303	loggedin.HandleFunc("/funzone", showfunzone)
2304	loggedin.HandleFunc("/chpass", dochpass)
2305	loggedin.HandleFunc("/atme", homepage)
2306	loggedin.HandleFunc("/hfcs", hfcspage)
2307	loggedin.HandleFunc("/xzone", xzone)
2308	loggedin.HandleFunc("/newhonk", newhonkpage)
2309	loggedin.HandleFunc("/edit", edithonkpage)
2310	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2311	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2312	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2313	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2314	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2315	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2316	loggedin.HandleFunc("/honkers", showhonkers)
2317	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2318	loggedin.HandleFunc("/h", showhonker)
2319	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2320	loggedin.HandleFunc("/c", showcombos)
2321	loggedin.HandleFunc("/t", showconvoy)
2322	loggedin.HandleFunc("/q", showsearch)
2323	loggedin.HandleFunc("/hydra", webhydra)
2324	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2325
2326	err = http.Serve(listener, mux)
2327	if err != nil {
2328		log.Fatal(err)
2329	}
2330}