all repos — honk @ b67691a4192414f421ab4a24a8e674095ff8da28

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