all repos — honk @ 764308c6bd46e984cee267f517e3f2f224d1f198

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