all repos — honk @ b0d27e034626426df022ff5ee20e78984b21157f

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	notrand "math/rand"
  25	"net/http"
  26	"net/url"
  27	"os"
  28	"os/signal"
  29	"regexp"
  30	"sort"
  31	"strconv"
  32	"strings"
  33	"syscall"
  34	"time"
  35	"unicode/utf8"
  36
  37	"github.com/gorilla/mux"
  38	"github.com/sassoftware/relic/lib/dlog"
  39	"humungus.tedunangst.com/r/webs/cache"
  40	"humungus.tedunangst.com/r/webs/httpsig"
  41	"humungus.tedunangst.com/r/webs/junk"
  42	"humungus.tedunangst.com/r/webs/login"
  43	"humungus.tedunangst.com/r/webs/rss"
  44	"humungus.tedunangst.com/r/webs/templates"
  45)
  46
  47var readviews *templates.Template
  48
  49var userSep = "u"
  50var honkSep = "h"
  51
  52var develMode = false
  53
  54var allemus []Emu
  55
  56func getuserstyle(u *login.UserInfo) template.HTMLAttr {
  57	if u == nil {
  58		return ""
  59	}
  60	user, _ := butwhatabout(u.Username)
  61	class := template.HTMLAttr("")
  62	if user.Options.SkinnyCSS {
  63		class += `class="skinny"`
  64	}
  65	return class
  66}
  67
  68func getmaplink(u *login.UserInfo) string {
  69	if u == nil {
  70		return "osm"
  71	}
  72	user, _ := butwhatabout(u.Username)
  73	ml := user.Options.MapLink
  74	if ml == "" {
  75		ml = "osm"
  76	}
  77	return ml
  78}
  79
  80func getInfo(r *http.Request) map[string]interface{} {
  81	templinfo := make(map[string]interface{})
  82	templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
  83	templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
  84	templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
  85	templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
  86	templinfo["MiscJSParam"] = getassetparam(dataDir + "/views/misc.js")
  87	templinfo["ServerName"] = serverName
  88	templinfo["IconName"] = iconName
  89	templinfo["UserSep"] = userSep
  90	if u := login.GetUserInfo(r); u != nil {
  91		templinfo["UserInfo"], _ = butwhatabout(u.Username)
  92		templinfo["UserStyle"] = getuserstyle(u)
  93		var combos []string
  94		combocache.Get(u.UserID, &combos)
  95		templinfo["Combos"] = combos
  96	}
  97	return templinfo
  98}
  99
 100func homepage(w http.ResponseWriter, r *http.Request) {
 101	templinfo := getInfo(r)
 102	u := login.GetUserInfo(r)
 103	var honks []*Honk
 104	var userid int64 = -1
 105
 106	templinfo["ServerMessage"] = serverMsg
 107	if u == nil || r.URL.Path == "/front" {
 108		switch r.URL.Path {
 109		case "/events":
 110			honks = geteventhonks(userid)
 111			templinfo["ServerMessage"] = "some recent and upcoming events"
 112		default:
 113			templinfo["ShowRSS"] = true
 114			honks = getpublichonks()
 115		}
 116	} else {
 117		userid = u.UserID
 118		switch r.URL.Path {
 119		case "/atme":
 120			templinfo["ServerMessage"] = "at me!"
 121			templinfo["PageName"] = "atme"
 122			honks = gethonksforme(userid, 0)
 123			honks = osmosis(honks, userid, false)
 124			menewnone(userid)
 125			templinfo["UserInfo"], _ = butwhatabout(u.Username)
 126		case "/longago":
 127			templinfo["ServerMessage"] = "long ago and far away!"
 128			templinfo["PageName"] = "longago"
 129			honks = gethonksfromlongago(userid, 0)
 130			honks = osmosis(honks, userid, false)
 131		case "/events":
 132			templinfo["ServerMessage"] = "some recent and upcoming events"
 133			templinfo["PageName"] = "events"
 134			honks = geteventhonks(userid)
 135			honks = osmosis(honks, userid, true)
 136		case "/first":
 137			templinfo["PageName"] = "first"
 138			honks = gethonksforuserfirstclass(userid, 0)
 139			honks = osmosis(honks, userid, true)
 140		case "/saved":
 141			templinfo["ServerMessage"] = "saved honks"
 142			templinfo["PageName"] = "saved"
 143			honks = getsavedhonks(userid, 0)
 144		default:
 145			templinfo["PageName"] = "home"
 146			honks = gethonksforuser(userid, 0)
 147			honks = osmosis(honks, userid, true)
 148		}
 149		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 150	}
 151
 152	honkpage(w, u, honks, templinfo)
 153}
 154
 155func showemus(w http.ResponseWriter, r *http.Request) {
 156	templinfo := getInfo(r)
 157	templinfo["Emus"] = allemus
 158	err := readviews.Execute(w, "emus.html", templinfo)
 159	if err != nil {
 160		elog.Print(err)
 161	}
 162}
 163
 164func showfunzone(w http.ResponseWriter, r *http.Request) {
 165	var emunames, memenames []string
 166	emuext := make(map[string]string)
 167	dir, err := os.Open(dataDir + "/emus")
 168	if err == nil {
 169		emunames, _ = dir.Readdirnames(0)
 170		dir.Close()
 171	}
 172	for i, e := range emunames {
 173		if len(e) > 4 {
 174			emunames[i] = e[:len(e)-4]
 175			emuext[emunames[i]] = e[len(e)-4:]
 176		}
 177	}
 178	dir, err = os.Open(dataDir + "/memes")
 179	if err == nil {
 180		memenames, _ = dir.Readdirnames(0)
 181		dir.Close()
 182	}
 183	sort.Strings(emunames)
 184	sort.Strings(memenames)
 185	templinfo := getInfo(r)
 186	templinfo["Emus"] = emunames
 187	templinfo["Emuext"] = emuext
 188	templinfo["Memes"] = memenames
 189	err = readviews.Execute(w, "funzone.html", templinfo)
 190	if err != nil {
 191		elog.Print(err)
 192	}
 193}
 194
 195func showrss(w http.ResponseWriter, r *http.Request) {
 196	name := mux.Vars(r)["name"]
 197
 198	var honks []*Honk
 199	if name != "" {
 200		honks = gethonksbyuser(name, false, 0)
 201	} else {
 202		honks = getpublichonks()
 203	}
 204	reverbolate(-1, honks)
 205
 206	home := fmt.Sprintf("https://%s/", serverName)
 207	base := home
 208	if name != "" {
 209		home += "u/" + name
 210		name += " "
 211	}
 212	feed := rss.Feed{
 213		Title:       name + "honk",
 214		Link:        home,
 215		Description: name + "honk rss",
 216		Image: &rss.Image{
 217			URL:   base + "icon.png",
 218			Title: name + "honk rss",
 219			Link:  home,
 220		},
 221	}
 222	var modtime time.Time
 223	for _, honk := range honks {
 224		if !firstclass(honk) {
 225			continue
 226		}
 227		desc := string(honk.HTML)
 228		if t := honk.Time; t != nil {
 229			desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
 230			if t.Duration != 0 {
 231				desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
 232			}
 233		}
 234		if p := honk.Place; p != nil {
 235			desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 236				p.Url, p.Name, p.Latitude, p.Longitude))
 237		}
 238		for _, d := range honk.Donks {
 239			desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 240				d.URL, d.Desc))
 241			if strings.HasPrefix(d.Media, "image") {
 242				desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
 243			}
 244		}
 245
 246		feed.Items = append(feed.Items, &rss.Item{
 247			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 248			Description: rss.CData{Data: desc},
 249			Link:        honk.URL,
 250			PubDate:     honk.Date.Format(time.RFC1123),
 251			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 252		})
 253		if honk.Date.After(modtime) {
 254			modtime = honk.Date
 255		}
 256	}
 257	if !develMode {
 258		w.Header().Set("Cache-Control", "max-age=300")
 259		w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 260	}
 261
 262	err := feed.Write(w)
 263	if err != nil {
 264		elog.Printf("error writing rss: %s", err)
 265	}
 266}
 267
 268func crappola(j junk.Junk) bool {
 269	t, _ := j.GetString("type")
 270	a, _ := j.GetString("actor")
 271	o, _ := j.GetString("object")
 272	if t == "Delete" && a == o {
 273		dlog.Printf("crappola from %s", a)
 274		return true
 275	}
 276	return false
 277}
 278
 279func ping(user *WhatAbout, who string) {
 280	if targ := fullname(who, user.ID); targ != "" {
 281		who = targ
 282	}
 283	if !strings.HasPrefix(who, "https:") {
 284		who = gofish(who)
 285	}
 286	if who == "" {
 287		ilog.Printf("nobody to ping!")
 288		return
 289	}
 290	var box *Box
 291	ok := boxofboxes.Get(who, &box)
 292	if !ok {
 293		ilog.Printf("no inbox to ping %s", who)
 294		return
 295	}
 296	ilog.Printf("sending ping to %s", box.In)
 297	j := junk.New()
 298	j["@context"] = itiswhatitis
 299	j["type"] = "Ping"
 300	j["id"] = user.URL + "/ping/" + xfiltrate()
 301	j["actor"] = user.URL
 302	j["to"] = who
 303	ki := ziggy(user.ID)
 304	if ki == nil {
 305		return
 306	}
 307	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 308	if err != nil {
 309		elog.Printf("can't send ping: %s", err)
 310		return
 311	}
 312	ilog.Printf("sent ping to %s: %s", who, j["id"])
 313}
 314
 315func pong(user *WhatAbout, who string, obj string) {
 316	var box *Box
 317	ok := boxofboxes.Get(who, &box)
 318	if !ok {
 319		ilog.Printf("no inbox to pong %s", who)
 320		return
 321	}
 322	j := junk.New()
 323	j["@context"] = itiswhatitis
 324	j["type"] = "Pong"
 325	j["id"] = user.URL + "/pong/" + xfiltrate()
 326	j["actor"] = user.URL
 327	j["to"] = who
 328	j["object"] = obj
 329	ki := ziggy(user.ID)
 330	if ki == nil {
 331		return
 332	}
 333	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 334	if err != nil {
 335		elog.Printf("can't send pong: %s", err)
 336		return
 337	}
 338}
 339
 340func inbox(w http.ResponseWriter, r *http.Request) {
 341	name := mux.Vars(r)["name"]
 342	user, err := butwhatabout(name)
 343	if err != nil {
 344		http.NotFound(w, r)
 345		return
 346	}
 347	if stealthmode(user.ID, r) {
 348		http.NotFound(w, r)
 349		return
 350	}
 351	var buf bytes.Buffer
 352	limiter := io.LimitReader(r.Body, 1*1024*1024)
 353	io.Copy(&buf, limiter)
 354	payload := buf.Bytes()
 355	j, err := junk.FromBytes(payload)
 356	if err != nil {
 357		ilog.Printf("bad payload: %s", err)
 358		ilog.Writer().Write(payload)
 359		ilog.Writer().Write([]byte{'\n'})
 360		return
 361	}
 362
 363	if crappola(j) {
 364		return
 365	}
 366	what, _ := j.GetString("type")
 367	obj, _ := j.GetString("object")
 368	if what == "Like" || (what == "EmojiReact" && originate(obj) != serverName) {
 369		return
 370	}
 371	who, _ := j.GetString("actor")
 372	if rejectactor(user.ID, who) {
 373		return
 374	}
 375
 376	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 377	if err != nil && keyname != "" {
 378		savingthrow(keyname)
 379		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 380	}
 381	if err != nil {
 382		ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
 383		if keyname != "" {
 384			ilog.Printf("bad signature from %s", keyname)
 385		}
 386		http.Error(w, "what did you call me?", http.StatusTeapot)
 387		return
 388	}
 389	origin := keymatch(keyname, who)
 390	if origin == "" {
 391		ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 392		return
 393	}
 394
 395	switch what {
 396	case "Ping":
 397		id, _ := j.GetString("id")
 398		ilog.Printf("ping from %s: %s", who, id)
 399		pong(user, who, id)
 400	case "Pong":
 401		ilog.Printf("pong from %s: %s", who, obj)
 402	case "Follow":
 403		if obj != user.URL {
 404			ilog.Printf("can't follow %s", obj)
 405			return
 406		}
 407		followme(user, who, who, j)
 408	case "Accept":
 409		followyou2(user, j)
 410	case "Reject":
 411		nofollowyou2(user, j)
 412	case "Update":
 413		obj, ok := j.GetMap("object")
 414		if ok {
 415			what, _ := obj.GetString("type")
 416			switch what {
 417			case "Service":
 418				fallthrough
 419			case "Person":
 420				return
 421			case "Question":
 422				return
 423			}
 424		}
 425		go xonksaver(user, j, origin)
 426	case "Undo":
 427		obj, ok := j.GetMap("object")
 428		if !ok {
 429			folxid, ok := j.GetString("object")
 430			if ok && originate(folxid) == origin {
 431				unfollowme(user, "", "", j)
 432			}
 433			return
 434		}
 435		what, _ := obj.GetString("type")
 436		switch what {
 437		case "Follow":
 438			unfollowme(user, who, who, j)
 439		case "Announce":
 440			xid, _ := obj.GetString("object")
 441			dlog.Printf("undo announce: %s", xid)
 442		case "Like":
 443		default:
 444			ilog.Printf("unknown undo: %s", what)
 445		}
 446	case "EmojiReact":
 447		obj, ok := j.GetString("object")
 448		if ok {
 449			content, _ := j.GetString("content")
 450			addreaction(user, obj, who, content)
 451		}
 452	default:
 453		go xonksaver(user, j, origin)
 454	}
 455}
 456
 457func serverinbox(w http.ResponseWriter, r *http.Request) {
 458	user := getserveruser()
 459	if stealthmode(user.ID, r) {
 460		http.NotFound(w, r)
 461		return
 462	}
 463	var buf bytes.Buffer
 464	io.Copy(&buf, r.Body)
 465	payload := buf.Bytes()
 466	j, err := junk.FromBytes(payload)
 467	if err != nil {
 468		ilog.Printf("bad payload: %s", err)
 469		ilog.Writer().Write(payload)
 470		ilog.Writer().Write([]byte{'\n'})
 471		return
 472	}
 473	if crappola(j) {
 474		return
 475	}
 476	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 477	if err != nil && keyname != "" {
 478		savingthrow(keyname)
 479		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 480	}
 481	if err != nil {
 482		ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
 483		if keyname != "" {
 484			ilog.Printf("bad signature from %s", keyname)
 485		}
 486		http.Error(w, "what did you call me?", http.StatusTeapot)
 487		return
 488	}
 489	who, _ := j.GetString("actor")
 490	origin := keymatch(keyname, who)
 491	if origin == "" {
 492		ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 493		return
 494	}
 495	if rejectactor(user.ID, who) {
 496		return
 497	}
 498	re_ont := regexp.MustCompile("https://" + serverName + "/o/([\\pL[:digit:]]+)")
 499	what, _ := j.GetString("type")
 500	dlog.Printf("server got a %s", what)
 501	switch what {
 502	case "Follow":
 503		obj, _ := j.GetString("object")
 504		if obj == user.URL {
 505			ilog.Printf("can't follow the server!")
 506			return
 507		}
 508		m := re_ont.FindStringSubmatch(obj)
 509		if len(m) != 2 {
 510			ilog.Printf("not sure how to handle this")
 511			return
 512		}
 513		ont := "#" + m[1]
 514
 515		followme(user, who, ont, j)
 516	case "Undo":
 517		obj, ok := j.GetMap("object")
 518		if !ok {
 519			ilog.Printf("unknown undo no object")
 520			return
 521		}
 522		what, _ := obj.GetString("type")
 523		if what != "Follow" {
 524			ilog.Printf("unknown undo: %s", what)
 525			return
 526		}
 527		targ, _ := obj.GetString("object")
 528		m := re_ont.FindStringSubmatch(targ)
 529		if len(m) != 2 {
 530			ilog.Printf("not sure how to handle this")
 531			return
 532		}
 533		ont := "#" + m[1]
 534		unfollowme(user, who, ont, j)
 535	default:
 536		ilog.Printf("unhandled server activity: %s", what)
 537		dumpactivity(j)
 538	}
 539}
 540
 541func serveractor(w http.ResponseWriter, r *http.Request) {
 542	user := getserveruser()
 543	if stealthmode(user.ID, r) {
 544		http.NotFound(w, r)
 545		return
 546	}
 547	j := junkuser(user)
 548	j.Write(w)
 549}
 550
 551func ximport(w http.ResponseWriter, r *http.Request) {
 552	u := login.GetUserInfo(r)
 553	xid := strings.TrimSpace(r.FormValue("q"))
 554	xonk := getxonk(u.UserID, xid)
 555	if xonk == nil {
 556		p, _ := investigate(xid)
 557		if p != nil {
 558			xid = p.XID
 559		}
 560		j, err := GetJunk(u.UserID, xid)
 561		if err != nil {
 562			http.Error(w, "error getting external object", http.StatusInternalServerError)
 563			ilog.Printf("error getting external object: %s", err)
 564			return
 565		}
 566		allinjest(originate(xid), j)
 567		dlog.Printf("importing %s", xid)
 568		user, _ := butwhatabout(u.Username)
 569
 570		info, _ := somethingabout(j)
 571		if info == nil {
 572			xonk = xonksaver(user, j, originate(xid))
 573		} else if info.What == SomeActor {
 574			outbox, _ := j.GetString("outbox")
 575			gimmexonks(user, outbox)
 576			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 577			return
 578		} else if info.What == SomeCollection {
 579			gimmexonks(user, xid)
 580			http.Redirect(w, r, "/xzone", http.StatusSeeOther)
 581			return
 582		}
 583	}
 584	convoy := ""
 585	if xonk != nil {
 586		convoy = xonk.Convoy
 587	}
 588	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 589}
 590
 591func xzone(w http.ResponseWriter, r *http.Request) {
 592	u := login.GetUserInfo(r)
 593	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 594	if err != nil {
 595		elog.Printf("query err: %s", err)
 596		return
 597	}
 598	defer rows.Close()
 599	var honkers []Honker
 600	for rows.Next() {
 601		var xid string
 602		rows.Scan(&xid)
 603		honkers = append(honkers, Honker{XID: xid})
 604	}
 605	rows.Close()
 606	for i, _ := range honkers {
 607		_, honkers[i].Handle = handles(honkers[i].XID)
 608	}
 609	templinfo := getInfo(r)
 610	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 611	templinfo["Honkers"] = honkers
 612	err = readviews.Execute(w, "xzone.html", templinfo)
 613	if err != nil {
 614		elog.Print(err)
 615	}
 616}
 617
 618var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
 619	user, err := butwhatabout(name)
 620	if err != nil {
 621		return nil, false
 622	}
 623	honks := gethonksbyuser(name, false, 0)
 624	if len(honks) > 20 {
 625		honks = honks[0:20]
 626	}
 627
 628	var jonks []junk.Junk
 629	for _, h := range honks {
 630		j, _ := jonkjonk(user, h)
 631		jonks = append(jonks, j)
 632	}
 633
 634	j := junk.New()
 635	j["@context"] = itiswhatitis
 636	j["id"] = user.URL + "/outbox"
 637	j["attributedTo"] = user.URL
 638	j["type"] = "OrderedCollection"
 639	j["totalItems"] = len(jonks)
 640	j["orderedItems"] = jonks
 641
 642	return j.ToBytes(), true
 643}, Duration: 1 * time.Minute})
 644
 645func outbox(w http.ResponseWriter, r *http.Request) {
 646	name := mux.Vars(r)["name"]
 647	user, err := butwhatabout(name)
 648	if err != nil {
 649		http.NotFound(w, r)
 650		return
 651	}
 652	if stealthmode(user.ID, r) {
 653		http.NotFound(w, r)
 654		return
 655	}
 656	var j []byte
 657	ok := oldoutbox.Get(name, &j)
 658	if ok {
 659		w.Header().Set("Content-Type", theonetruename)
 660		w.Write(j)
 661	} else {
 662		http.NotFound(w, r)
 663	}
 664}
 665
 666var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
 667	colname := "/followers"
 668	if strings.HasSuffix(url, "/following") {
 669		colname = "/following"
 670	}
 671	user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
 672	j := junk.New()
 673	j["@context"] = itiswhatitis
 674	j["id"] = user + colname
 675	j["attributedTo"] = user
 676	j["type"] = "OrderedCollection"
 677	j["totalItems"] = 0
 678	j["orderedItems"] = []junk.Junk{}
 679
 680	return j.ToBytes(), true
 681}})
 682
 683func emptiness(w http.ResponseWriter, r *http.Request) {
 684	name := mux.Vars(r)["name"]
 685	user, err := butwhatabout(name)
 686	if err != nil {
 687		http.NotFound(w, r)
 688		return
 689	}
 690	if stealthmode(user.ID, r) {
 691		http.NotFound(w, r)
 692		return
 693	}
 694	var j []byte
 695	ok := oldempties.Get(r.URL.Path, &j)
 696	if ok {
 697		w.Header().Set("Content-Type", theonetruename)
 698		w.Write(j)
 699	} else {
 700		http.NotFound(w, r)
 701	}
 702}
 703
 704func showuser(w http.ResponseWriter, r *http.Request) {
 705	name := mux.Vars(r)["name"]
 706	user, err := butwhatabout(name)
 707	if err != nil {
 708		ilog.Printf("user not found %s: %s", name, err)
 709		http.NotFound(w, r)
 710		return
 711	}
 712	if stealthmode(user.ID, r) {
 713		http.NotFound(w, r)
 714		return
 715	}
 716	if friendorfoe(r.Header.Get("Accept")) {
 717		j, ok := asjonker(name)
 718		if ok {
 719			w.Header().Set("Content-Type", theonetruename)
 720			w.Write(j)
 721		} else {
 722			http.NotFound(w, r)
 723		}
 724		return
 725	}
 726	u := login.GetUserInfo(r)
 727	honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
 728	templinfo := getInfo(r)
 729	templinfo["PageName"] = "user"
 730	templinfo["PageArg"] = name
 731	templinfo["Name"] = user.Name
 732	templinfo["WhatAbout"] = user.HTAbout
 733	templinfo["ServerMessage"] = ""
 734	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 735	honkpage(w, u, honks, templinfo)
 736}
 737
 738func showhonker(w http.ResponseWriter, r *http.Request) {
 739	u := login.GetUserInfo(r)
 740	name := mux.Vars(r)["name"]
 741	var honks []*Honk
 742	if name == "" {
 743		name = r.FormValue("xid")
 744		honks = gethonksbyxonker(u.UserID, name, 0)
 745	} else {
 746		honks = gethonksbyhonker(u.UserID, name, 0)
 747	}
 748	miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
 749<input type="hidden" name="CSRF" value="%s">
 750<input type="hidden" name="url" value="%s">
 751<button tabindex=1 name="add honker" value="add honker">add honker</button>
 752</form>`, login.GetCSRF("submithonker", r), name)
 753	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
 754	templinfo := getInfo(r)
 755	templinfo["PageName"] = "honker"
 756	templinfo["PageArg"] = name
 757	templinfo["ServerMessage"] = msg
 758	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 759	honkpage(w, u, honks, templinfo)
 760}
 761
 762func showcombo(w http.ResponseWriter, r *http.Request) {
 763	name := mux.Vars(r)["name"]
 764	u := login.GetUserInfo(r)
 765	honks := gethonksbycombo(u.UserID, name, 0)
 766	honks = osmosis(honks, u.UserID, true)
 767	templinfo := getInfo(r)
 768	templinfo["PageName"] = "combo"
 769	templinfo["PageArg"] = name
 770	templinfo["ServerMessage"] = "honks by combo: " + name
 771	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 772	honkpage(w, u, honks, templinfo)
 773}
 774func showconvoy(w http.ResponseWriter, r *http.Request) {
 775	c := r.FormValue("c")
 776	u := login.GetUserInfo(r)
 777	honks := gethonksbyconvoy(u.UserID, c, 0)
 778	templinfo := getInfo(r)
 779	if len(honks) > 0 {
 780		templinfo["TopHID"] = honks[0].ID
 781	}
 782	honks = osmosis(honks, u.UserID, false)
 783	//reversehonks(honks)
 784	honks = threadsort(honks)
 785	templinfo["PageName"] = "convoy"
 786	templinfo["PageArg"] = c
 787	templinfo["ServerMessage"] = "honks in convoy: " + c
 788	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 789	honkpage(w, u, honks, templinfo)
 790}
 791func showsearch(w http.ResponseWriter, r *http.Request) {
 792	q := r.FormValue("q")
 793	if strings.HasPrefix(q, "https://") {
 794		ximport(w, r)
 795		return
 796	}
 797	u := login.GetUserInfo(r)
 798	honks := gethonksbysearch(u.UserID, q, 0)
 799	templinfo := getInfo(r)
 800	templinfo["PageName"] = "search"
 801	templinfo["PageArg"] = q
 802	templinfo["ServerMessage"] = "honks for search: " + q
 803	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 804	honkpage(w, u, honks, templinfo)
 805}
 806func showontology(w http.ResponseWriter, r *http.Request) {
 807	name := mux.Vars(r)["name"]
 808	u := login.GetUserInfo(r)
 809	var userid int64 = -1
 810	if u != nil {
 811		userid = u.UserID
 812	}
 813	honks := gethonksbyontology(userid, "#"+name, 0)
 814	if friendorfoe(r.Header.Get("Accept")) {
 815		if len(honks) > 40 {
 816			honks = honks[0:40]
 817		}
 818
 819		var xids []string
 820		for _, h := range honks {
 821			xids = append(xids, h.XID)
 822		}
 823
 824		user := getserveruser()
 825
 826		j := junk.New()
 827		j["@context"] = itiswhatitis
 828		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 829		j["name"] = "#" + name
 830		j["attributedTo"] = user.URL
 831		j["type"] = "OrderedCollection"
 832		j["totalItems"] = len(xids)
 833		j["orderedItems"] = xids
 834
 835		j.Write(w)
 836		return
 837	}
 838
 839	templinfo := getInfo(r)
 840	templinfo["ServerMessage"] = "honks by ontology: " + name
 841	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 842	honkpage(w, u, honks, templinfo)
 843}
 844
 845type Ont struct {
 846	Name  string
 847	Count int64
 848}
 849
 850func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 851	u := login.GetUserInfo(r)
 852	var userid int64 = -1
 853	if u != nil {
 854		userid = u.UserID
 855	}
 856	rows, err := stmtAllOnts.Query(userid)
 857	if err != nil {
 858		elog.Printf("selection error: %s", err)
 859		return
 860	}
 861	defer rows.Close()
 862	var onts []Ont
 863	for rows.Next() {
 864		var o Ont
 865		err := rows.Scan(&o.Name, &o.Count)
 866		if err != nil {
 867			elog.Printf("error scanning ont: %s", err)
 868			continue
 869		}
 870		if utf8.RuneCountInString(o.Name) > 24 {
 871			continue
 872		}
 873		o.Name = o.Name[1:]
 874		onts = append(onts, o)
 875	}
 876	sort.Slice(onts, func(i, j int) bool {
 877		return onts[i].Name < onts[j].Name
 878	})
 879	if u == nil && !develMode {
 880		w.Header().Set("Cache-Control", "max-age=300")
 881	}
 882	templinfo := getInfo(r)
 883	templinfo["Onts"] = onts
 884	templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
 885	err = readviews.Execute(w, "onts.html", templinfo)
 886	if err != nil {
 887		elog.Print(err)
 888	}
 889}
 890
 891type Track struct {
 892	xid string
 893	who string
 894}
 895
 896func getbacktracks(xid string) []string {
 897	c := make(chan bool)
 898	dumptracks <- c
 899	<-c
 900	row := stmtGetTracks.QueryRow(xid)
 901	var rawtracks string
 902	err := row.Scan(&rawtracks)
 903	if err != nil {
 904		if err != sql.ErrNoRows {
 905			elog.Printf("error scanning tracks: %s", err)
 906		}
 907		return nil
 908	}
 909	var rcpts []string
 910	for _, f := range strings.Split(rawtracks, " ") {
 911		idx := strings.LastIndexByte(f, '#')
 912		if idx != -1 {
 913			f = f[:idx]
 914		}
 915		if !strings.HasPrefix(f, "https://") {
 916			f = fmt.Sprintf("%%https://%s/inbox", f)
 917		}
 918		rcpts = append(rcpts, f)
 919	}
 920	return rcpts
 921}
 922
 923func savetracks(tracks map[string][]string) {
 924	db := opendatabase()
 925	tx, err := db.Begin()
 926	if err != nil {
 927		elog.Printf("savetracks begin error: %s", err)
 928		return
 929	}
 930	defer func() {
 931		err := tx.Commit()
 932		if err != nil {
 933			elog.Printf("savetracks commit error: %s", err)
 934		}
 935
 936	}()
 937	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 938	if err != nil {
 939		elog.Printf("savetracks error: %s", err)
 940		return
 941	}
 942	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 943	if err != nil {
 944		elog.Printf("savetracks error: %s", err)
 945		return
 946	}
 947	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 948	if err != nil {
 949		elog.Printf("savetracks error: %s", err)
 950		return
 951	}
 952	count := 0
 953	for xid, f := range tracks {
 954		count += len(f)
 955		var prev string
 956		row := stmtGetTracks.QueryRow(xid)
 957		err := row.Scan(&prev)
 958		if err == sql.ErrNoRows {
 959			f = oneofakind(f)
 960			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 961		} else if err == nil {
 962			all := append(strings.Split(prev, " "), f...)
 963			all = oneofakind(all)
 964			stmtUpdateTracks.Exec(strings.Join(all, " "))
 965		} else {
 966			elog.Printf("savetracks error: %s", err)
 967		}
 968	}
 969	dlog.Printf("saved %d new fetches", count)
 970}
 971
 972var trackchan = make(chan Track)
 973var dumptracks = make(chan chan bool)
 974
 975func tracker() {
 976	timeout := 4 * time.Minute
 977	sleeper := time.NewTimer(timeout)
 978	tracks := make(map[string][]string)
 979	workinprogress++
 980	for {
 981		select {
 982		case track := <-trackchan:
 983			tracks[track.xid] = append(tracks[track.xid], track.who)
 984		case <-sleeper.C:
 985			if len(tracks) > 0 {
 986				go savetracks(tracks)
 987				tracks = make(map[string][]string)
 988			}
 989			sleeper.Reset(timeout)
 990		case c := <-dumptracks:
 991			if len(tracks) > 0 {
 992				savetracks(tracks)
 993			}
 994			c <- true
 995		case <-endoftheworld:
 996			if len(tracks) > 0 {
 997				savetracks(tracks)
 998			}
 999			readyalready <- true
1000			return
1001		}
1002	}
1003}
1004
1005var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1006
1007func trackback(xid string, r *http.Request) {
1008	agent := r.UserAgent()
1009	who := originate(agent)
1010	sig := r.Header.Get("Signature")
1011	if sig != "" {
1012		m := re_keyholder.FindStringSubmatch(sig)
1013		if len(m) == 2 {
1014			who = m[1]
1015		}
1016	}
1017	if who != "" {
1018		trackchan <- Track{xid: xid, who: who}
1019	}
1020}
1021
1022func threadsort(honks []*Honk) []*Honk {
1023	sort.Slice(honks, func(i, j int) bool {
1024		return honks[i].Date.Before(honks[j].Date)
1025	})
1026	honkx := make(map[string]*Honk)
1027	kids := make(map[string][]*Honk)
1028	for _, h := range honks {
1029		honkx[h.XID] = h
1030		rid := h.RID
1031		kids[rid] = append(kids[rid], h)
1032	}
1033	done := make(map[*Honk]bool)
1034	var thread []*Honk
1035	var nextlevel func(p *Honk)
1036	level := 0
1037	nextlevel = func(p *Honk) {
1038		levelup := level < 4
1039		if pp := honkx[p.RID]; p.RID == "" || (pp != nil && p.Honker == pp.Honker) {
1040			levelup = false
1041		}
1042		if level > 0 && len(kids[p.RID]) == 1 {
1043			if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1044				levelup = false
1045			}
1046		}
1047		if levelup {
1048			level++
1049		}
1050		p.Style += fmt.Sprintf(" level%d", level)
1051		childs := kids[p.XID]
1052		sort.SliceStable(childs, func(i, j int) bool {
1053			return childs[i].Honker == p.Honker && childs[j].Honker != p.Honker
1054		})
1055		for _, h := range childs {
1056			if !done[h] {
1057				done[h] = true
1058				thread = append(thread, h)
1059				nextlevel(h)
1060			}
1061		}
1062		if levelup {
1063			level--
1064		}
1065	}
1066	for _, h := range honks {
1067		if !done[h] && h.RID == "" {
1068			done[h] = true
1069			thread = append(thread, h)
1070			nextlevel(h)
1071		}
1072	}
1073	for _, h := range honks {
1074		if !done[h] {
1075			done[h] = true
1076			thread = append(thread, h)
1077			nextlevel(h)
1078		}
1079	}
1080	return thread
1081}
1082
1083func honkology(honk *Honk) template.HTML {
1084	var user *WhatAbout
1085	ok := somenumberedusers.Get(honk.UserID, &user)
1086	if !ok {
1087		return ""
1088	}
1089	title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1090	imgurl := avatarURL(user)
1091	for _, d := range honk.Donks {
1092		if d.Local && strings.HasPrefix(d.Media, "image") {
1093			imgurl = d.URL
1094			break
1095		}
1096	}
1097	short := honk.Noise
1098	if len(short) > 160 {
1099		short = short[0:160] + "..."
1100	}
1101	return templates.Sprintf(
1102		`<meta property="og:title" content="%s" />
1103<meta property="og:type" content="article" />
1104<meta property="article:author" content="%s" />
1105<meta property="og:url" content="%s" />
1106<meta property="og:image" content="%s" />
1107<meta property="og:description" content="%s" />`,
1108		title, user.URL, honk.XID, imgurl, short)
1109}
1110
1111func showonehonk(w http.ResponseWriter, r *http.Request) {
1112	name := mux.Vars(r)["name"]
1113	user, err := butwhatabout(name)
1114	if err != nil {
1115		http.NotFound(w, r)
1116		return
1117	}
1118	if stealthmode(user.ID, r) {
1119		http.NotFound(w, r)
1120		return
1121	}
1122	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1123
1124	if friendorfoe(r.Header.Get("Accept")) {
1125		j, ok := gimmejonk(xid)
1126		if ok {
1127			trackback(xid, r)
1128			w.Header().Set("Content-Type", theonetruename)
1129			w.Write(j)
1130		} else {
1131			http.NotFound(w, r)
1132		}
1133		return
1134	}
1135	honk := getxonk(user.ID, xid)
1136	if honk == nil {
1137		http.NotFound(w, r)
1138		return
1139	}
1140	u := login.GetUserInfo(r)
1141	if u != nil && u.UserID != user.ID {
1142		u = nil
1143	}
1144	if !honk.Public {
1145		if u == nil {
1146			http.NotFound(w, r)
1147			return
1148
1149		}
1150		honks := []*Honk{honk}
1151		donksforhonks(honks)
1152		templinfo := getInfo(r)
1153		templinfo["ServerMessage"] = "one honk maybe more"
1154		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1155		honkpage(w, u, honks, templinfo)
1156		return
1157	}
1158
1159	templinfo := getInfo(r)
1160	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1161	//reversehonks(rawhonks)
1162	rawhonks = threadsort(rawhonks)
1163	var honks []*Honk
1164	for _, h := range rawhonks {
1165		if h.XID == xid {
1166			templinfo["Honkology"] = honkology(h)
1167			if len(honks) != 0 {
1168				h.Style += " glow"
1169			}
1170		}
1171		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1172			honks = append(honks, h)
1173		}
1174	}
1175
1176	templinfo["ServerMessage"] = "one honk maybe more"
1177	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1178	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1179	honkpage(w, u, honks, templinfo)
1180}
1181
1182func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1183	var userid int64 = -1
1184	if u != nil {
1185		userid = u.UserID
1186		templinfo["User"], _ = butwhatabout(u.Username)
1187	}
1188	reverbolate(userid, honks)
1189	templinfo["Honks"] = honks
1190	templinfo["MapLink"] = getmaplink(u)
1191	if templinfo["TopHID"] == nil {
1192		if len(honks) > 0 {
1193			templinfo["TopHID"] = honks[0].ID
1194		} else {
1195			templinfo["TopHID"] = 0
1196		}
1197	}
1198	if u == nil && !develMode {
1199		w.Header().Set("Cache-Control", "max-age=60")
1200	}
1201	err := readviews.Execute(w, "honkpage.html", templinfo)
1202	if err != nil {
1203		elog.Print(err)
1204	}
1205}
1206
1207func saveuser(w http.ResponseWriter, r *http.Request) {
1208	whatabout := r.FormValue("whatabout")
1209	whatabout = strings.Replace(whatabout, "\r", "", -1)
1210	u := login.GetUserInfo(r)
1211	user, _ := butwhatabout(u.Username)
1212	db := opendatabase()
1213
1214	options := user.Options
1215	if r.FormValue("skinny") == "skinny" {
1216		options.SkinnyCSS = true
1217	} else {
1218		options.SkinnyCSS = false
1219	}
1220	if r.FormValue("omitimages") == "omitimages" {
1221		options.OmitImages = true
1222	} else {
1223		options.OmitImages = false
1224	}
1225	if r.FormValue("mentionall") == "mentionall" {
1226		options.MentionAll = true
1227	} else {
1228		options.MentionAll = false
1229	}
1230	if r.FormValue("inlineqts") == "inlineqts" {
1231		options.InlineQuotes = true
1232	} else {
1233		options.InlineQuotes = false
1234	}
1235	if r.FormValue("maps") == "apple" {
1236		options.MapLink = "apple"
1237	} else {
1238		options.MapLink = ""
1239	}
1240
1241
1242	sendupdate := false
1243	if r.FormValue("displayname") != "" {
1244		options.CustomDisplay = r.FormValue("displayname")
1245		sendupdate = true
1246	} else {
1247		options.CustomDisplay = ""
1248	}
1249
1250	options.Reaction = r.FormValue("reaction")
1251
1252	ava := re_avatar.FindString(whatabout)
1253	if ava != "" {
1254		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1255		ava = ava[7:]
1256		if ava[0] == ' ' {
1257			ava = ava[1:]
1258		}
1259		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1260	}
1261	if ava != options.Avatar {
1262		options.Avatar = ava
1263		sendupdate = true
1264	}
1265	ban := re_banner.FindString(whatabout)
1266	if ban != "" {
1267		whatabout = re_banner.ReplaceAllString(whatabout, "")
1268		ban = ban[7:]
1269		if ban[0] == ' ' {
1270			ban = ban[1:]
1271		}
1272		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1273	}
1274	if ban != options.Banner {
1275		options.Banner = ban
1276		sendupdate = true
1277	}
1278	whatabout = strings.TrimSpace(whatabout)
1279	if whatabout != user.About {
1280		sendupdate = true
1281	}
1282	j, err := jsonify(options)
1283	if err == nil {
1284		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1285	}
1286	if err != nil {
1287		elog.Printf("error bouting what: %s", err)
1288	}
1289	somenamedusers.Clear(u.Username)
1290	somenumberedusers.Clear(u.UserID)
1291	oldjonkers.Clear(u.Username)
1292
1293	if sendupdate {
1294		updateMe(u.Username)
1295	}
1296
1297	http.Redirect(w, r, "/account", http.StatusSeeOther)
1298}
1299
1300func bonkit(xid string, user *WhatAbout) {
1301	dlog.Printf("bonking %s", xid)
1302
1303	xonk := getxonk(user.ID, xid)
1304	if xonk == nil {
1305		return
1306	}
1307	if !xonk.Public {
1308		return
1309	}
1310	if xonk.IsBonked() {
1311		return
1312	}
1313	donksforhonks([]*Honk{xonk})
1314
1315	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1316	if err != nil {
1317		elog.Printf("error acking bonk: %s", err)
1318	}
1319
1320	oonker := xonk.Oonker
1321	if oonker == "" {
1322		oonker = xonk.Honker
1323	}
1324	dt := time.Now().UTC()
1325	bonk := &Honk{
1326		UserID:   user.ID,
1327		Username: user.Name,
1328		What:     "bonk",
1329		Honker:   user.URL,
1330		Oonker:   oonker,
1331		XID:      xonk.XID,
1332		RID:      xonk.RID,
1333		Noise:    xonk.Noise,
1334		Precis:   xonk.Precis,
1335		URL:      xonk.URL,
1336		Date:     dt,
1337		Donks:    xonk.Donks,
1338		Whofore:  2,
1339		Convoy:   xonk.Convoy,
1340		Audience: []string{thewholeworld, oonker},
1341		Public:   true,
1342		Format:   xonk.Format,
1343		Place:    xonk.Place,
1344		Onts:     xonk.Onts,
1345		Time:     xonk.Time,
1346	}
1347
1348	err = savehonk(bonk)
1349	if err != nil {
1350		elog.Printf("uh oh")
1351		return
1352	}
1353
1354	go honkworldwide(user, bonk)
1355}
1356
1357func submitbonk(w http.ResponseWriter, r *http.Request) {
1358	xid := r.FormValue("xid")
1359	userinfo := login.GetUserInfo(r)
1360	user, _ := butwhatabout(userinfo.Username)
1361
1362	bonkit(xid, user)
1363
1364	if r.FormValue("js") != "1" {
1365		templinfo := getInfo(r)
1366		templinfo["ServerMessage"] = "Bonked!"
1367		err := readviews.Execute(w, "msg.html", templinfo)
1368		if err != nil {
1369			elog.Print(err)
1370		}
1371	}
1372}
1373
1374func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1375	zonk := &Honk{
1376		What:     what,
1377		XID:      xonk.XID,
1378		Date:     time.Now().UTC(),
1379		Audience: oneofakind(xonk.Audience),
1380		Noise:    aux,
1381	}
1382	zonk.Public = loudandproud(zonk.Audience)
1383
1384	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1385	go honkworldwide(user, zonk)
1386}
1387
1388func zonkit(w http.ResponseWriter, r *http.Request) {
1389	wherefore := r.FormValue("wherefore")
1390	what := r.FormValue("what")
1391	userinfo := login.GetUserInfo(r)
1392	user, _ := butwhatabout(userinfo.Username)
1393
1394	if wherefore == "save" {
1395		xonk := getxonk(userinfo.UserID, what)
1396		if xonk != nil {
1397			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1398			if err != nil {
1399				elog.Printf("error saving: %s", err)
1400			}
1401		}
1402		return
1403	}
1404
1405	if wherefore == "unsave" {
1406		xonk := getxonk(userinfo.UserID, what)
1407		if xonk != nil {
1408			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1409			if err != nil {
1410				elog.Printf("error unsaving: %s", err)
1411			}
1412		}
1413		return
1414	}
1415
1416	if wherefore == "react" {
1417		reaction := user.Options.Reaction
1418		if r2 := r.FormValue("reaction"); r2 != "" {
1419			reaction = r2
1420		}
1421		if reaction == "none" {
1422			return
1423		}
1424		xonk := getxonk(userinfo.UserID, what)
1425		if xonk != nil {
1426			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1427			if err != nil {
1428				elog.Printf("error saving: %s", err)
1429			}
1430			sendzonkofsorts(xonk, user, "react", reaction)
1431		}
1432		return
1433	}
1434
1435	// my hammer is too big, oh well
1436	defer oldjonks.Flush()
1437
1438	if wherefore == "ack" {
1439		xonk := getxonk(userinfo.UserID, what)
1440		if xonk != nil && !xonk.IsAcked() {
1441			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1442			if err != nil {
1443				elog.Printf("error acking: %s", err)
1444			}
1445			sendzonkofsorts(xonk, user, "ack", "")
1446		}
1447		return
1448	}
1449
1450	if wherefore == "deack" {
1451		xonk := getxonk(userinfo.UserID, what)
1452		if xonk != nil && xonk.IsAcked() {
1453			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1454			if err != nil {
1455				elog.Printf("error deacking: %s", err)
1456			}
1457			sendzonkofsorts(xonk, user, "deack", "")
1458		}
1459		return
1460	}
1461
1462	if wherefore == "bonk" {
1463		user, _ := butwhatabout(userinfo.Username)
1464		bonkit(what, user)
1465		return
1466	}
1467
1468	if wherefore == "unbonk" {
1469		xonk := getbonk(userinfo.UserID, what)
1470		if xonk != nil {
1471			deletehonk(xonk.ID)
1472			xonk = getxonk(userinfo.UserID, what)
1473			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1474			if err != nil {
1475				elog.Printf("error unbonking: %s", err)
1476			}
1477			sendzonkofsorts(xonk, user, "unbonk", "")
1478		}
1479		return
1480	}
1481
1482	if wherefore == "untag" {
1483		xonk := getxonk(userinfo.UserID, what)
1484		if xonk != nil {
1485			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1486			if err != nil {
1487				elog.Printf("error untagging: %s", err)
1488			}
1489		}
1490		var badparents map[string]bool
1491		untagged.GetAndLock(userinfo.UserID, &badparents)
1492		badparents[what] = true
1493		untagged.Unlock()
1494		return
1495	}
1496
1497	ilog.Printf("zonking %s %s", wherefore, what)
1498	if wherefore == "zonk" {
1499		xonk := getxonk(userinfo.UserID, what)
1500		if xonk != nil {
1501			deletehonk(xonk.ID)
1502			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1503				sendzonkofsorts(xonk, user, "zonk", "")
1504			}
1505		}
1506	}
1507	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1508	if err != nil {
1509		elog.Printf("error saving zonker: %s", err)
1510		return
1511	}
1512}
1513
1514func edithonkpage(w http.ResponseWriter, r *http.Request) {
1515	u := login.GetUserInfo(r)
1516	user, _ := butwhatabout(u.Username)
1517	xid := r.FormValue("xid")
1518	honk := getxonk(u.UserID, xid)
1519	if !canedithonk(user, honk) {
1520		http.Error(w, "no editing that please", http.StatusInternalServerError)
1521		return
1522	}
1523
1524	noise := honk.Noise
1525
1526	honks := []*Honk{honk}
1527	donksforhonks(honks)
1528	reverbolate(u.UserID, honks)
1529	templinfo := getInfo(r)
1530	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1531	templinfo["Honks"] = honks
1532	templinfo["MapLink"] = getmaplink(u)
1533	templinfo["Noise"] = noise
1534	templinfo["SavedPlace"] = honk.Place
1535	if tm := honk.Time; tm != nil {
1536		templinfo["ShowTime"] = " "
1537		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1538		if tm.Duration != 0 {
1539			templinfo["Duration"] = tm.Duration
1540		}
1541	}
1542	templinfo["ServerMessage"] = "honk edit 2"
1543	templinfo["IsPreview"] = true
1544	templinfo["UpdateXID"] = honk.XID
1545	if len(honk.Donks) > 0 {
1546		templinfo["SavedFile"] = honk.Donks[0].XID
1547	}
1548	err := readviews.Execute(w, "honkpage.html", templinfo)
1549	if err != nil {
1550		elog.Print(err)
1551	}
1552}
1553
1554func newhonkpage(w http.ResponseWriter, r *http.Request) {
1555	u := login.GetUserInfo(r)
1556	rid := r.FormValue("rid")
1557	noise := ""
1558
1559	xonk := getxonk(u.UserID, rid)
1560	if xonk != nil {
1561		_, replto := handles(xonk.Honker)
1562		if replto != "" {
1563			noise = "@" + replto + " "
1564		}
1565	}
1566
1567	templinfo := getInfo(r)
1568	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1569	templinfo["InReplyTo"] = rid
1570	templinfo["Noise"] = noise
1571	templinfo["ServerMessage"] = "compose honk"
1572	templinfo["IsPreview"] = true
1573	err := readviews.Execute(w, "honkpage.html", templinfo)
1574	if err != nil {
1575		elog.Print(err)
1576	}
1577}
1578
1579func canedithonk(user *WhatAbout, honk *Honk) bool {
1580	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1581		return false
1582	}
1583	return true
1584}
1585
1586func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1587	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1588		return nil, nil
1589	}
1590	file, filehdr, err := r.FormFile("donk")
1591	if err != nil {
1592		if err == http.ErrMissingFile {
1593			return nil, nil
1594		}
1595		elog.Printf("error reading donk: %s", err)
1596		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1597		return nil, err
1598	}
1599	var buf bytes.Buffer
1600	io.Copy(&buf, file)
1601	file.Close()
1602	data := buf.Bytes()
1603	var media, name string
1604	img, err := shrinkit(data)
1605	if err == nil {
1606		data = img.Data
1607		format := img.Format
1608		media = "image/" + format
1609		if format == "jpeg" {
1610			format = "jpg"
1611		}
1612		if format == "svg+xml" {
1613			format = "svg"
1614		}
1615		name = xfiltrate() + "." + format
1616	} else {
1617		ct := http.DetectContentType(data)
1618		switch ct {
1619		case "application/pdf":
1620			maxsize := 10000000
1621			if len(data) > maxsize {
1622				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1623				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1624				return nil, err
1625			}
1626			media = ct
1627			name = filehdr.Filename
1628			if name == "" {
1629				name = xfiltrate() + ".pdf"
1630			}
1631		default:
1632			maxsize := 100000
1633			if len(data) > maxsize {
1634				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1635				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1636				return nil, err
1637			}
1638			for i := 0; i < len(data); i++ {
1639				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1640					ilog.Printf("bad image: %s not text: %d", err, data[i])
1641					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1642					return nil, err
1643				}
1644			}
1645			media = "text/plain"
1646			name = filehdr.Filename
1647			if name == "" {
1648				name = xfiltrate() + ".txt"
1649			}
1650		}
1651	}
1652	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1653	if desc == "" {
1654		desc = name
1655	}
1656	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1657	if err != nil {
1658		elog.Printf("unable to save image: %s", err)
1659		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1660		return nil, err
1661	}
1662	d := &Donk{
1663		FileID: fileid,
1664		XID:    xid,
1665		Desc:   desc,
1666		Local:  true,
1667	}
1668	return d, nil
1669}
1670
1671func websubmithonk(w http.ResponseWriter, r *http.Request) {
1672	h := submithonk(w, r)
1673	if h == nil {
1674		return
1675	}
1676	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1677}
1678
1679// what a hot mess this function is
1680func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1681	rid := r.FormValue("rid")
1682	noise := r.FormValue("noise")
1683	format := r.FormValue("format")
1684	if format == "" {
1685		format = "markdown"
1686	}
1687	if !(format == "markdown" || format == "html") {
1688		http.Error(w, "unknown format", 500)
1689		return nil
1690	}
1691
1692	userinfo := login.GetUserInfo(r)
1693	user, _ := butwhatabout(userinfo.Username)
1694
1695	dt := time.Now().UTC()
1696	updatexid := r.FormValue("updatexid")
1697	var honk *Honk
1698	if updatexid != "" {
1699		honk = getxonk(userinfo.UserID, updatexid)
1700		if !canedithonk(user, honk) {
1701			http.Error(w, "no editing that please", http.StatusInternalServerError)
1702			return nil
1703		}
1704		honk.Date = dt
1705		honk.What = "update"
1706		honk.Format = format
1707	} else {
1708		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1709		what := "honk"
1710		if rid != "" {
1711			what = "tonk"
1712		}
1713		honk = &Honk{
1714			UserID:   userinfo.UserID,
1715			Username: userinfo.Username,
1716			What:     what,
1717			Honker:   user.URL,
1718			XID:      xid,
1719			Date:     dt,
1720			Format:   format,
1721		}
1722	}
1723
1724	var convoy string
1725	noise = strings.Replace(noise, "\r", "", -1)
1726	if updatexid == "" && rid == "" {
1727		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1728			convoy = m[7:]
1729			convoy = strings.TrimSpace(convoy)
1730			if !re_convalidate.MatchString(convoy) {
1731				convoy = ""
1732			}
1733			return ""
1734		})
1735	}
1736	noise = quickrename(noise, userinfo.UserID)
1737	noise = hooterize(noise)
1738	honk.Noise = noise
1739	precipitate(honk)
1740	noise = honk.Noise
1741	translate(honk)
1742
1743	if rid != "" {
1744		xonk := getxonk(userinfo.UserID, rid)
1745		if xonk == nil {
1746			http.Error(w, "replyto disappeared", http.StatusNotFound)
1747			return nil
1748		}
1749		if xonk.Public {
1750			honk.Audience = append(honk.Audience, xonk.Audience...)
1751		}
1752		convoy = xonk.Convoy
1753		for i, a := range honk.Audience {
1754			if a == thewholeworld {
1755				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1756				break
1757			}
1758		}
1759		honk.RID = rid
1760		if xonk.Precis != "" && honk.Precis == "" {
1761			honk.Precis = xonk.Precis
1762			if !re_dangerous.MatchString(honk.Precis) {
1763				honk.Precis = "re: " + honk.Precis
1764			}
1765		}
1766	} else {
1767		honk.Audience = []string{thewholeworld}
1768	}
1769	if honk.Noise != "" && honk.Noise[0] == '@' {
1770		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1771	} else {
1772		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1773	}
1774
1775	if convoy == "" {
1776		convoy = fmt.Sprintf("data:,%s-", masqName) + xfiltrate()
1777	}
1778	butnottooloud(honk.Audience)
1779	honk.Audience = oneofakind(honk.Audience)
1780	if len(honk.Audience) == 0 {
1781		ilog.Printf("honk to nowhere")
1782		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1783		return nil
1784	}
1785	honk.Public = loudandproud(honk.Audience)
1786	honk.Convoy = convoy
1787
1788	donkxid := r.FormValue("donkxid")
1789	if donkxid == "" {
1790		d, err := submitdonk(w, r)
1791		if err != nil && err != http.ErrMissingFile {
1792			return nil
1793		}
1794		if d != nil {
1795			honk.Donks = append(honk.Donks, d)
1796			donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1797		}
1798	} else {
1799		p := strings.Split(donkxid, ":")
1800		xid := p[0]
1801		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1802		var donk *Donk
1803		if len(p) > 1 {
1804			fileid, _ := strconv.ParseInt(p[1], 10, 0)
1805			donk = finddonkid(fileid, url)
1806		} else {
1807			donk = finddonk(url)
1808		}
1809		if donk != nil {
1810			honk.Donks = append(honk.Donks, donk)
1811		} else {
1812			ilog.Printf("can't find file: %s", xid)
1813		}
1814	}
1815	memetize(honk)
1816	imaginate(honk)
1817
1818	placename := strings.TrimSpace(r.FormValue("placename"))
1819	placelat := strings.TrimSpace(r.FormValue("placelat"))
1820	placelong := strings.TrimSpace(r.FormValue("placelong"))
1821	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1822	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1823		p := new(Place)
1824		p.Name = placename
1825		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1826		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1827		p.Url = placeurl
1828		honk.Place = p
1829	}
1830	timestart := strings.TrimSpace(r.FormValue("timestart"))
1831	if timestart != "" {
1832		t := new(Time)
1833		now := time.Now().Local()
1834		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1835			start, err := time.ParseInLocation(layout, timestart, now.Location())
1836			if err == nil {
1837				if start.Year() == 0 {
1838					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1839				}
1840				t.StartTime = start
1841				break
1842			}
1843		}
1844		timeend := r.FormValue("timeend")
1845		dur := parseDuration(timeend)
1846		if dur != 0 {
1847			t.Duration = Duration(dur)
1848		}
1849		if !t.StartTime.IsZero() {
1850			honk.What = "event"
1851			honk.Time = t
1852		}
1853	}
1854
1855	if honk.Public {
1856		honk.Whofore = 2
1857	} else {
1858		honk.Whofore = 3
1859	}
1860
1861	// back to markdown
1862	honk.Noise = noise
1863
1864	if r.FormValue("preview") == "preview" {
1865		honks := []*Honk{honk}
1866		reverbolate(userinfo.UserID, honks)
1867		templinfo := getInfo(r)
1868		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1869		templinfo["Honks"] = honks
1870		templinfo["MapLink"] = getmaplink(userinfo)
1871		templinfo["InReplyTo"] = r.FormValue("rid")
1872		templinfo["Noise"] = r.FormValue("noise")
1873		templinfo["SavedFile"] = donkxid
1874		if tm := honk.Time; tm != nil {
1875			templinfo["ShowTime"] = " "
1876			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1877			if tm.Duration != 0 {
1878				templinfo["Duration"] = tm.Duration
1879			}
1880		}
1881		templinfo["IsPreview"] = true
1882		templinfo["UpdateXID"] = updatexid
1883		templinfo["ServerMessage"] = "honk preview"
1884		err := readviews.Execute(w, "honkpage.html", templinfo)
1885		if err != nil {
1886			elog.Print(err)
1887		}
1888		return nil
1889	}
1890
1891	if updatexid != "" {
1892		updatehonk(honk)
1893		oldjonks.Clear(honk.XID)
1894	} else {
1895		err := savehonk(honk)
1896		if err != nil {
1897			elog.Printf("uh oh")
1898			return nil
1899		}
1900	}
1901
1902	// reload for consistency
1903	honk.Donks = nil
1904	donksforhonks([]*Honk{honk})
1905
1906	go honkworldwide(user, honk)
1907
1908	return honk
1909}
1910
1911func showhonkers(w http.ResponseWriter, r *http.Request) {
1912	userinfo := login.GetUserInfo(r)
1913	templinfo := getInfo(r)
1914	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1915	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1916	err := readviews.Execute(w, "honkers.html", templinfo)
1917	if err != nil {
1918		elog.Print(err)
1919	}
1920}
1921
1922func showchatter(w http.ResponseWriter, r *http.Request) {
1923	u := login.GetUserInfo(r)
1924	chatnewnone(u.UserID)
1925	chatter := loadchatter(u.UserID)
1926	for _, chat := range chatter {
1927		for _, ch := range chat.Chonks {
1928			filterchonk(ch)
1929		}
1930	}
1931
1932	templinfo := getInfo(r)
1933	templinfo["Chatter"] = chatter
1934	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1935	err := readviews.Execute(w, "chatter.html", templinfo)
1936	if err != nil {
1937		elog.Print(err)
1938	}
1939}
1940
1941func submitchonk(w http.ResponseWriter, r *http.Request) {
1942	u := login.GetUserInfo(r)
1943	user, _ := butwhatabout(u.Username)
1944	noise := r.FormValue("noise")
1945	target := r.FormValue("target")
1946	format := "markdown"
1947	dt := time.Now().UTC()
1948	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1949
1950	if !strings.HasPrefix(target, "https://") {
1951		target = fullname(target, u.UserID)
1952	}
1953	if target == "" {
1954		http.Error(w, "who is that?", http.StatusInternalServerError)
1955		return
1956	}
1957	ch := Chonk{
1958		UserID: u.UserID,
1959		XID:    xid,
1960		Who:    user.URL,
1961		Target: target,
1962		Date:   dt,
1963		Noise:  noise,
1964		Format: format,
1965	}
1966	d, err := submitdonk(w, r)
1967	if err != nil && err != http.ErrMissingFile {
1968		return
1969	}
1970	if d != nil {
1971		ch.Donks = append(ch.Donks, d)
1972	}
1973
1974	translatechonk(&ch)
1975	savechonk(&ch)
1976	// reload for consistency
1977	ch.Donks = nil
1978	donksforchonks([]*Chonk{&ch})
1979	go sendchonk(user, &ch)
1980
1981	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1982}
1983
1984var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1985	honkers := gethonkers(userid)
1986	var combos []string
1987	for _, h := range honkers {
1988		combos = append(combos, h.Combos...)
1989	}
1990	for i, c := range combos {
1991		if c == "-" {
1992			combos[i] = ""
1993		}
1994	}
1995	combos = oneofakind(combos)
1996	sort.Strings(combos)
1997	return combos, true
1998}, Invalidator: &honkerinvalidator})
1999
2000func showcombos(w http.ResponseWriter, r *http.Request) {
2001	userinfo := login.GetUserInfo(r)
2002	var combos []string
2003	combocache.Get(userinfo.UserID, &combos)
2004	templinfo := getInfo(r)
2005	err := readviews.Execute(w, "combos.html", templinfo)
2006	if err != nil {
2007		elog.Print(err)
2008	}
2009}
2010
2011func websubmithonker(w http.ResponseWriter, r *http.Request) {
2012	h := submithonker(w, r)
2013	if h == nil {
2014		return
2015	}
2016	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2017}
2018
2019func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2020	u := login.GetUserInfo(r)
2021	user, _ := butwhatabout(u.Username)
2022	name := strings.TrimSpace(r.FormValue("name"))
2023	url := strings.TrimSpace(r.FormValue("url"))
2024	peep := r.FormValue("peep")
2025	combos := strings.TrimSpace(r.FormValue("combos"))
2026	combos = " " + combos + " "
2027	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2028
2029	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2030	if name != "" && !re_namecheck.MatchString(name) {
2031		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2032		return nil
2033	}
2034
2035	var meta HonkerMeta
2036	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2037	mj, _ := jsonify(&meta)
2038
2039	defer honkerinvalidator.Clear(u.UserID)
2040
2041	// mostly dummy, fill in later...
2042	h := &Honker{
2043		ID: honkerid,
2044	}
2045
2046	if honkerid > 0 {
2047		if r.FormValue("delete") == "delete" {
2048			unfollowyou(user, honkerid, false)
2049			stmtDeleteHonker.Exec(honkerid)
2050			return h
2051		}
2052		if r.FormValue("unsub") == "unsub" {
2053			unfollowyou(user, honkerid, false)
2054		}
2055		if r.FormValue("sub") == "sub" {
2056			followyou(user, honkerid, false)
2057		}
2058		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2059		if err != nil {
2060			elog.Printf("update honker err: %s", err)
2061			return nil
2062		}
2063		return h
2064	}
2065
2066	if url == "" {
2067		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2068		return nil
2069	}
2070
2071	flavor := "presub"
2072	if peep == "peep" {
2073		flavor = "peep"
2074	}
2075
2076	var err error
2077	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2078	if err != nil {
2079		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2080		return nil
2081	}
2082	if flavor == "presub" {
2083		followyou(user, honkerid, false)
2084	}
2085	h.ID = honkerid
2086	return h
2087}
2088
2089func hfcspage(w http.ResponseWriter, r *http.Request) {
2090	userinfo := login.GetUserInfo(r)
2091
2092	filters := getfilters(userinfo.UserID, filtAny)
2093
2094	templinfo := getInfo(r)
2095	templinfo["Filters"] = filters
2096	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2097	err := readviews.Execute(w, "hfcs.html", templinfo)
2098	if err != nil {
2099		elog.Print(err)
2100	}
2101}
2102
2103func savehfcs(w http.ResponseWriter, r *http.Request) {
2104	userinfo := login.GetUserInfo(r)
2105	itsok := r.FormValue("itsok")
2106	if itsok == "iforgiveyou" {
2107		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2108		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2109		if err != nil {
2110			elog.Printf("error deleting filter: %s", err)
2111		}
2112		filtInvalidator.Clear(userinfo.UserID)
2113		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2114		return
2115	}
2116
2117	filt := new(Filter)
2118	filt.Name = strings.TrimSpace(r.FormValue("name"))
2119	filt.Date = time.Now().UTC()
2120	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2121	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2122	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2123	filt.IsReply = r.FormValue("isreply") == "yes"
2124	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2125	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2126	filt.Reject = r.FormValue("doreject") == "yes"
2127	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2128	filt.Hide = r.FormValue("dohide") == "yes"
2129	filt.Collapse = r.FormValue("docollapse") == "yes"
2130	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2131	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2132	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2133		filt.Expiration = time.Now().UTC().Add(dur)
2134	}
2135	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2136
2137	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2138		ilog.Printf("blank filter")
2139		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2140		return
2141	}
2142
2143	j, err := jsonify(filt)
2144	if err == nil {
2145		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2146	}
2147	if err != nil {
2148		elog.Printf("error saving filter: %s", err)
2149	}
2150
2151	filtInvalidator.Clear(userinfo.UserID)
2152	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2153}
2154
2155func accountpage(w http.ResponseWriter, r *http.Request) {
2156	u := login.GetUserInfo(r)
2157	user, _ := butwhatabout(u.Username)
2158	templinfo := getInfo(r)
2159	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2160	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2161	templinfo["User"] = user
2162	about := user.About
2163	if ava := user.Options.Avatar; ava != "" {
2164		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2165	}
2166	if ban := user.Options.Banner; ban != "" {
2167		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2168	}
2169	templinfo["WhatAbout"] = about
2170	err := readviews.Execute(w, "account.html", templinfo)
2171	if err != nil {
2172		elog.Print(err)
2173	}
2174}
2175
2176func dochpass(w http.ResponseWriter, r *http.Request) {
2177	err := login.ChangePassword(w, r)
2178	if err != nil {
2179		elog.Printf("error changing password: %s", err)
2180	}
2181	http.Redirect(w, r, "/account", http.StatusSeeOther)
2182}
2183
2184var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2185	if strings.HasPrefix(orig, "acct:") {
2186		orig = orig[5:]
2187	}
2188	name := orig
2189	idx := strings.LastIndexByte(name, '/')
2190	if idx != -1 {
2191		name = name[idx+1:]
2192		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2193			ilog.Printf("foreign request rejected")
2194			name = ""
2195		}
2196	} else {
2197		idx = strings.IndexByte(name, '@')
2198		if idx != -1 {
2199			name = name[:idx]
2200			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2201				ilog.Printf("foreign request rejected")
2202				name = ""
2203			}
2204		}
2205	}
2206	user, err := butwhatabout(name)
2207	if err != nil {
2208		return nil, false
2209	}
2210
2211	j := junk.New()
2212	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2213	j["aliases"] = []string{user.URL}
2214	l := junk.New()
2215	l["rel"] = "self"
2216	l["type"] = `application/activity+json`
2217	l["href"] = user.URL
2218	j["links"] = []junk.Junk{l}
2219	return j.ToBytes(), true
2220}})
2221
2222func fingerlicker(w http.ResponseWriter, r *http.Request) {
2223	orig := r.FormValue("resource")
2224
2225	dlog.Printf("finger lick: %s", orig)
2226
2227	var j []byte
2228	ok := oldfingers.Get(orig, &j)
2229	if ok {
2230		w.Header().Set("Content-Type", "application/jrd+json")
2231		w.Write(j)
2232	} else {
2233		http.NotFound(w, r)
2234	}
2235}
2236
2237func somedays() string {
2238	secs := 432000 + notrand.Int63n(432000)
2239	return fmt.Sprintf("%d", secs)
2240}
2241
2242func lookatme(ava string) string {
2243	if strings.Contains(ava, serverName+"/"+userSep) {
2244		idx := strings.LastIndexByte(ava, '/')
2245		if idx < len(ava) {
2246			name := ava[idx+1:]
2247			user, _ := butwhatabout(name)
2248			if user != nil && user.URL == ava {
2249				return user.Options.Avatar
2250			}
2251		}
2252	}
2253	return ""
2254}
2255
2256func avatate(w http.ResponseWriter, r *http.Request) {
2257	if develMode {
2258		loadAvatarColors()
2259	}
2260	var a []byte
2261	n := r.FormValue("a")
2262	if redir := lookatme(n); redir != "" {
2263		http.Redirect(w, r, redir, http.StatusSeeOther)
2264		return
2265	}
2266	a := genAvatar(n)
2267	if !develMode {
2268		w.Header().Set("Cache-Control", "max-age="+somedays())
2269	}
2270
2271	w.Write(a)
2272}
2273
2274func serveviewasset(w http.ResponseWriter, r *http.Request) {
2275	serveasset(w, r, viewDir)
2276}
2277func servedataasset(w http.ResponseWriter, r *http.Request) {
2278	if r.URL.Path == "/favicon.ico" {
2279		r.URL.Path = "/icon.png"
2280	}
2281	serveasset(w, r, dataDir)
2282}
2283
2284func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2285	if !develMode {
2286		w.Header().Set("Cache-Control", "max-age=7776000")
2287	}
2288	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2289}
2290func servehelp(w http.ResponseWriter, r *http.Request) {
2291	name := mux.Vars(r)["name"]
2292	if !develMode {
2293		w.Header().Set("Cache-Control", "max-age=3600")
2294	}
2295	http.ServeFile(w, r, viewDir+"/docs/"+name)
2296}
2297func servehtml(w http.ResponseWriter, r *http.Request) {
2298	u := login.GetUserInfo(r)
2299	templinfo := getInfo(r)
2300	templinfo["AboutMsg"] = aboutMsg
2301	templinfo["LoginMsg"] = loginMsg
2302	templinfo["HonkVersion"] = softwareVersion
2303	if r.URL.Path == "/about" {
2304		templinfo["Sensors"] = getSensors()
2305	}
2306	if u == nil && !develMode {
2307		w.Header().Set("Cache-Control", "max-age=60")
2308	}
2309	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2310	if err != nil {
2311		elog.Print(err)
2312	}
2313}
2314func serveemu(w http.ResponseWriter, r *http.Request) {
2315	emu := mux.Vars(r)["emu"]
2316
2317	w.Header().Set("Cache-Control", "max-age="+somedays())
2318	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2319}
2320func servememe(w http.ResponseWriter, r *http.Request) {
2321	meme := mux.Vars(r)["meme"]
2322
2323	w.Header().Set("Cache-Control", "max-age="+somedays())
2324	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2325}
2326
2327func servefile(w http.ResponseWriter, r *http.Request) {
2328	xid := mux.Vars(r)["xid"]
2329	var media string
2330	var data []byte
2331	row := stmtGetFileData.QueryRow(xid)
2332	err := row.Scan(&media, &data)
2333	if err != nil {
2334		elog.Printf("error loading file: %s", err)
2335		http.NotFound(w, r)
2336		return
2337	}
2338	w.Header().Set("Content-Type", media)
2339	w.Header().Set("X-Content-Type-Options", "nosniff")
2340	w.Header().Set("Cache-Control", "max-age="+somedays())
2341	w.Write(data)
2342}
2343
2344func nomoroboto(w http.ResponseWriter, r *http.Request) {
2345	io.WriteString(w, "User-agent: *\n")
2346	io.WriteString(w, "Disallow: /a\n")
2347	io.WriteString(w, "Disallow: /d/\n")
2348	io.WriteString(w, "Disallow: /meme/\n")
2349	io.WriteString(w, "Disallow: /o\n")
2350	io.WriteString(w, "Disallow: /o/\n")
2351	io.WriteString(w, "Disallow: /help/\n")
2352	for _, u := range allusers() {
2353		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2354	}
2355}
2356
2357type Hydration struct {
2358	Tophid    int64
2359	Srvmsg    template.HTML
2360	Honks     string
2361	MeCount   int64
2362	ChatCount int64
2363}
2364
2365func webhydra(w http.ResponseWriter, r *http.Request) {
2366	u := login.GetUserInfo(r)
2367	userid := u.UserID
2368	templinfo := getInfo(r)
2369	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2370	page := r.FormValue("page")
2371
2372	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2373
2374	var hydra Hydration
2375
2376	var honks []*Honk
2377	switch page {
2378	case "atme":
2379		honks = gethonksforme(userid, wanted)
2380		honks = osmosis(honks, userid, false)
2381		menewnone(userid)
2382		hydra.Srvmsg = "at me!"
2383	case "longago":
2384		honks = gethonksfromlongago(userid, wanted)
2385		honks = osmosis(honks, userid, false)
2386		hydra.Srvmsg = "from long ago"
2387	case "home":
2388		honks = gethonksforuser(userid, wanted)
2389		honks = osmosis(honks, userid, true)
2390		hydra.Srvmsg = serverMsg
2391	case "first":
2392		honks = gethonksforuserfirstclass(userid, wanted)
2393		honks = osmosis(honks, userid, true)
2394		hydra.Srvmsg = "first class only"
2395	case "saved":
2396		honks = getsavedhonks(userid, wanted)
2397		templinfo["PageName"] = "saved"
2398		hydra.Srvmsg = "saved honks"
2399	case "combo":
2400		c := r.FormValue("c")
2401		honks = gethonksbycombo(userid, c, wanted)
2402		honks = osmosis(honks, userid, false)
2403		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2404	case "convoy":
2405		c := r.FormValue("c")
2406		honks = gethonksbyconvoy(userid, c, wanted)
2407		honks = osmosis(honks, userid, false)
2408		honks = threadsort(honks)
2409		reversehonks(honks)
2410		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2411	case "honker":
2412		xid := r.FormValue("xid")
2413		honks = gethonksbyxonker(userid, xid, wanted)
2414		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2415			<input type="hidden" name="CSRF" value="%s">
2416			<input type="hidden" name="url" value="%s">
2417			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2418			</form>`, login.GetCSRF("submithonker", r), xid)
2419		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2420		hydra.Srvmsg = msg
2421	case "user":
2422		uname := r.FormValue("uname")
2423		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2424		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2425	default:
2426		http.NotFound(w, r)
2427	}
2428
2429	if len(honks) > 0 {
2430		hydra.Tophid = honks[0].ID
2431	} else {
2432		hydra.Tophid = wanted
2433	}
2434	reverbolate(userid, honks)
2435
2436	user, _ := butwhatabout(u.Username)
2437
2438	var buf strings.Builder
2439	templinfo["Honks"] = honks
2440	templinfo["MapLink"] = getmaplink(u)
2441	templinfo["User"], _ = butwhatabout(u.Username)
2442	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2443	if err != nil {
2444		elog.Printf("frag error: %s", err)
2445		return
2446	}
2447	hydra.Honks = buf.String()
2448	hydra.MeCount = user.Options.MeCount
2449	hydra.ChatCount = user.Options.ChatCount
2450	w.Header().Set("Content-Type", "application/json")
2451	j, _ := jsonify(&hydra)
2452	io.WriteString(w, j)
2453}
2454
2455var honkline = make(chan bool)
2456
2457func honkhonkline() {
2458	for {
2459		select {
2460		case honkline <- true:
2461		default:
2462			return
2463		}
2464	}
2465}
2466
2467func apihandler(w http.ResponseWriter, r *http.Request) {
2468	u := login.GetUserInfo(r)
2469	userid := u.UserID
2470	action := r.FormValue("action")
2471	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2472	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2473	switch action {
2474	case "honk":
2475		h := submithonk(w, r)
2476		if h == nil {
2477			return
2478		}
2479
2480		fmt.Fprintf(w, "%s", h.XID)
2481	case "donk":
2482		d, err := submitdonk(w, r)
2483		if err != nil {
2484			http.Error(w, err.Error(), http.StatusBadRequest)
2485			return
2486		}
2487		if d == nil {
2488			http.Error(w, "missing donk", http.StatusBadRequest)
2489			return
2490		}
2491		w.Write([]byte(d.XID))
2492	case "zonkit":
2493		zonkit(w, r)
2494	case "gethonks":
2495		var honks []*Honk
2496		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2497		page := r.FormValue("page")
2498		var waitchan <-chan time.Time
2499	requery:
2500		switch page {
2501		case "atme":
2502			honks = gethonksforme(userid, wanted)
2503			honks = osmosis(honks, userid, false)
2504			menewnone(userid)
2505		case "longago":
2506			honks = gethonksfromlongago(userid, wanted)
2507			honks = osmosis(honks, userid, false)
2508		case "home":
2509			honks = gethonksforuser(userid, wanted)
2510			honks = osmosis(honks, userid, true)
2511		case "myhonks":
2512			honks = gethonksbyuser(u.Username, true, wanted)
2513			honks = osmosis(honks, userid, true)
2514		default:
2515			http.Error(w, "unknown page", http.StatusNotFound)
2516			return
2517		}
2518		if len(honks) == 0 && wait > 0 {
2519			if waitchan == nil {
2520				waitchan = time.After(time.Duration(wait) * time.Second)
2521			}
2522			select {
2523			case <-honkline:
2524				goto requery
2525			case <-waitchan:
2526			}
2527		}
2528		reverbolate(userid, honks)
2529		j := junk.New()
2530		j["honks"] = honks
2531		j.Write(w)
2532	case "sendactivity":
2533		user, _ := butwhatabout(u.Username)
2534		public := r.FormValue("public") == "1"
2535		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2536		msg := []byte(r.FormValue("msg"))
2537		for rcpt := range rcpts {
2538			go deliverate(userid, rcpt, msg)
2539		}
2540	case "gethonkers":
2541		j := junk.New()
2542		j["honkers"] = gethonkers(u.UserID)
2543		j.Write(w)
2544	case "savehonker":
2545		h := submithonker(w, r)
2546		if h == nil {
2547			return
2548		}
2549		fmt.Fprintf(w, "%d", h.ID)
2550	default:
2551		http.Error(w, "unknown action", http.StatusNotFound)
2552		return
2553	}
2554}
2555
2556func fiveoh(w http.ResponseWriter, r *http.Request) {
2557	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2558	if err != nil {
2559		elog.Printf("error opening violations! %s", err)
2560		return
2561	}
2562	defer fd.Close()
2563	io.Copy(fd, r.Body)
2564}
2565
2566var endoftheworld = make(chan bool)
2567var readyalready = make(chan bool)
2568var workinprogress = 0
2569
2570func enditall() {
2571	sig := make(chan os.Signal)
2572	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2573	<-sig
2574	ilog.Printf("stopping...")
2575	for i := 0; i < workinprogress; i++ {
2576		endoftheworld <- true
2577	}
2578	ilog.Printf("waiting...")
2579	for i := 0; i < workinprogress; i++ {
2580		<-readyalready
2581	}
2582	ilog.Printf("apocalypse")
2583	os.Exit(0)
2584}
2585
2586var preservehooks []func()
2587
2588func bgmonitor() {
2589	for {
2590		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2591		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2592		if err != nil {
2593			elog.Printf("error deleting old xonkers: %s", err)
2594		}
2595		zaggies.Flush()
2596		time.Sleep(50 * time.Minute)
2597	}
2598}
2599
2600func addcspheaders(next http.Handler) http.Handler {
2601	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2602		w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'; report-uri /csp-violation")
2603		next.ServeHTTP(w, r)
2604	})
2605}
2606
2607func emuinit() {
2608	var emunames []string
2609	dir, err := os.Open(dataDir + "/emus")
2610	if err == nil {
2611		emunames, _ = dir.Readdirnames(0)
2612		dir.Close()
2613	}
2614	for _, e := range emunames {
2615		if len(e) <= 4 {
2616			continue
2617		}
2618		ext := e[len(e)-4:]
2619		emu := Emu{
2620			ID:   fmt.Sprintf("/emu/%s", e),
2621			Name: e[:len(e)-4],
2622			Type: "image/" + ext[1:],
2623		}
2624		allemus = append(allemus, emu)
2625	}
2626	sort.Slice(allemus, func(i, j int) bool {
2627		return allemus[i].Name < allemus[j].Name
2628	})
2629}
2630
2631func serve() {
2632	db := opendatabase()
2633	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2634
2635	listener, err := openListener()
2636	if err != nil {
2637		elog.Fatal(err)
2638	}
2639	runBackendServer()
2640	go enditall()
2641	go redeliverator()
2642	go tracker()
2643	go bgmonitor()
2644	loadLingo()
2645	emuinit()
2646
2647	readviews = templates.Load(develMode,
2648		viewDir+"/views/honkpage.html",
2649		viewDir+"/views/honkfrags.html",
2650		viewDir+"/views/honkers.html",
2651		viewDir+"/views/chatter.html",
2652		viewDir+"/views/hfcs.html",
2653		viewDir+"/views/combos.html",
2654		viewDir+"/views/honkform.html",
2655		viewDir+"/views/honk.html",
2656		viewDir+"/views/account.html",
2657		viewDir+"/views/about.html",
2658		viewDir+"/views/funzone.html",
2659		viewDir+"/views/login.html",
2660		viewDir+"/views/xzone.html",
2661		viewDir+"/views/msg.html",
2662		viewDir+"/views/header.html",
2663		viewDir+"/views/onts.html",
2664		viewDir+"/views/emus.html",
2665		viewDir+"/views/honkpage.js",
2666	)
2667	if !develMode {
2668		assets := []string{
2669			viewDir + "/views/style.css",
2670			dataDir + "/views/local.css",
2671			viewDir + "/views/honkpage.js",
2672			dataDir + "/views/local.js",
2673		}
2674		for _, s := range assets {
2675			savedassetparams[s] = getassetparam(s)
2676		}
2677		loadAvatarColors()
2678	}
2679
2680	for _, h := range preservehooks {
2681		h()
2682	}
2683
2684	mux := mux.NewRouter()
2685	mux.Use(addcspheaders)
2686	mux.Use(login.Checker)
2687
2688	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2689
2690	posters := mux.Methods("POST").Subrouter()
2691	getters := mux.Methods("GET").Subrouter()
2692
2693	getters.HandleFunc("/", homepage)
2694	getters.HandleFunc("/home", homepage)
2695	getters.HandleFunc("/front", homepage)
2696	getters.HandleFunc("/events", homepage)
2697	getters.HandleFunc("/robots.txt", nomoroboto)
2698	getters.HandleFunc("/rss", showrss)
2699	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2700	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2701	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2702	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2703	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2704	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2705	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2706	getters.HandleFunc("/a", avatate)
2707	getters.HandleFunc("/o", thelistingoftheontologies)
2708	getters.HandleFunc("/o/{name:.+}", showontology)
2709	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2710	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2711	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2712	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2713
2714	getters.HandleFunc("/flag/{code:.+}", showflag)
2715
2716	getters.HandleFunc("/server", serveractor)
2717	posters.HandleFunc("/server/inbox", serverinbox)
2718	posters.HandleFunc("/inbox", serverinbox)
2719
2720	posters.HandleFunc("/csp-violation", fiveoh)
2721
2722	getters.HandleFunc("/style.css", serveviewasset)
2723	getters.HandleFunc("/honkpage.js", serveviewasset)
2724	getters.HandleFunc("/misc.js", serveviewasset)
2725	getters.HandleFunc("/local.css", servedataasset)
2726	getters.HandleFunc("/local.js", servedataasset)
2727	getters.HandleFunc("/icon.png", servedataasset)
2728	getters.HandleFunc("/favicon.ico", servedataasset)
2729
2730	getters.HandleFunc("/about", servehtml)
2731	getters.HandleFunc("/login", servehtml)
2732	posters.HandleFunc("/dologin", login.LoginFunc)
2733	getters.HandleFunc("/logout", login.LogoutFunc)
2734	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2735
2736	loggedin := mux.NewRoute().Subrouter()
2737	loggedin.Use(login.Required)
2738	loggedin.HandleFunc("/first", homepage)
2739	loggedin.HandleFunc("/chatter", showchatter)
2740	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2741	loggedin.HandleFunc("/saved", homepage)
2742	loggedin.HandleFunc("/account", accountpage)
2743	loggedin.HandleFunc("/funzone", showfunzone)
2744	loggedin.HandleFunc("/chpass", dochpass)
2745	loggedin.HandleFunc("/atme", homepage)
2746	loggedin.HandleFunc("/longago", homepage)
2747	loggedin.HandleFunc("/hfcs", hfcspage)
2748	loggedin.HandleFunc("/xzone", xzone)
2749	loggedin.HandleFunc("/newhonk", newhonkpage)
2750	loggedin.HandleFunc("/edit", edithonkpage)
2751	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2752	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2753	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2754	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2755	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2756	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2757	loggedin.HandleFunc("/honkers", showhonkers)
2758	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2759	loggedin.HandleFunc("/h", showhonker)
2760	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2761	loggedin.HandleFunc("/c", showcombos)
2762	loggedin.HandleFunc("/t", showconvoy)
2763	loggedin.HandleFunc("/q", showsearch)
2764	loggedin.HandleFunc("/hydra", webhydra)
2765	loggedin.HandleFunc("/emus", showemus)
2766	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2767
2768	err = http.Serve(listener, mux)
2769	if err != nil {
2770		elog.Fatal(err)
2771	}
2772}