all repos — honk @ becdc3c600fdbd563ff886b9c2fff2991ddabacf

my fork of honk

web.go (view raw)

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