all repos — honk @ d61c72d0643cb9eb62a047b367bda78d8854ac30

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