all repos — honk @ 343341549c0b31d8e03019a59d51a53ab8c532bf

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