all repos — honk @ v0.9.91

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, obj)
 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			case "Note":
 423				go xonksaver(user, j, origin)
 424				return
 425			}
 426		}
 427		ilog.Printf("unknown Update activity")
 428		dumpactivity(j)
 429	case "Undo":
 430		obj, ok := j.GetMap("object")
 431		if !ok {
 432			folxid, ok := j.GetString("object")
 433			if ok && originate(folxid) == origin {
 434				unfollowme(user, "", "", j)
 435			}
 436			return
 437		}
 438		what, _ := obj.GetString("type")
 439		switch what {
 440		case "Follow":
 441			unfollowme(user, who, who, j)
 442		case "Announce":
 443			xid, _ := obj.GetString("object")
 444			dlog.Printf("undo announce: %s", xid)
 445		case "Like":
 446		default:
 447			ilog.Printf("unknown undo: %s", what)
 448		}
 449	case "EmojiReact":
 450		obj, ok := j.GetString("object")
 451		if ok {
 452			content, _ := j.GetString("content")
 453			addreaction(user, obj, who, content)
 454		}
 455	default:
 456		go xonksaver(user, j, origin)
 457	}
 458}
 459
 460func serverinbox(w http.ResponseWriter, r *http.Request) {
 461	user := getserveruser()
 462	if stealthmode(user.ID, r) {
 463		http.NotFound(w, r)
 464		return
 465	}
 466	var buf bytes.Buffer
 467	io.Copy(&buf, r.Body)
 468	payload := buf.Bytes()
 469	j, err := junk.FromBytes(payload)
 470	if err != nil {
 471		ilog.Printf("bad payload: %s", err)
 472		ilog.Writer().Write(payload)
 473		ilog.Writer().Write([]byte{'\n'})
 474		return
 475	}
 476	if crappola(j) {
 477		return
 478	}
 479	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 480	if err != nil && keyname != "" {
 481		savingthrow(keyname)
 482		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 483	}
 484	if err != nil {
 485		ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
 486		if keyname != "" {
 487			ilog.Printf("bad signature from %s", keyname)
 488		}
 489		http.Error(w, "what did you call me?", http.StatusTeapot)
 490		return
 491	}
 492	who, _ := j.GetString("actor")
 493	origin := keymatch(keyname, who)
 494	if origin == "" {
 495		ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 496		return
 497	}
 498	if rejectactor(user.ID, who) {
 499		return
 500	}
 501	re_ont := regexp.MustCompile("https://" + serverName + "/o/([\\pL[:digit:]]+)")
 502	what, _ := j.GetString("type")
 503	dlog.Printf("server got a %s", what)
 504	switch what {
 505	case "Follow":
 506		obj, _ := j.GetString("object")
 507		if obj == user.URL {
 508			ilog.Printf("can't follow the server!")
 509			return
 510		}
 511		m := re_ont.FindStringSubmatch(obj)
 512		if len(m) != 2 {
 513			ilog.Printf("not sure how to handle this")
 514			return
 515		}
 516		ont := "#" + m[1]
 517
 518		followme(user, who, ont, j)
 519	case "Undo":
 520		obj, ok := j.GetMap("object")
 521		if !ok {
 522			ilog.Printf("unknown undo no object")
 523			return
 524		}
 525		what, _ := obj.GetString("type")
 526		if what != "Follow" {
 527			ilog.Printf("unknown undo: %s", what)
 528			return
 529		}
 530		targ, _ := obj.GetString("object")
 531		m := re_ont.FindStringSubmatch(targ)
 532		if len(m) != 2 {
 533			ilog.Printf("not sure how to handle this")
 534			return
 535		}
 536		ont := "#" + m[1]
 537		unfollowme(user, who, ont, j)
 538	default:
 539		ilog.Printf("unhandled server activity: %s", what)
 540		dumpactivity(j)
 541	}
 542}
 543
 544func serveractor(w http.ResponseWriter, r *http.Request) {
 545	user := getserveruser()
 546	if stealthmode(user.ID, r) {
 547		http.NotFound(w, r)
 548		return
 549	}
 550	j := junkuser(user)
 551	j.Write(w)
 552}
 553
 554func ximport(w http.ResponseWriter, r *http.Request) {
 555	u := login.GetUserInfo(r)
 556	xid := strings.TrimSpace(r.FormValue("xid"))
 557	xonk := getxonk(u.UserID, xid)
 558	if xonk == nil {
 559		p, _ := investigate(xid)
 560		if p != nil {
 561			xid = p.XID
 562		}
 563		j, err := GetJunk(u.UserID, xid)
 564		if err != nil {
 565			http.Error(w, "error getting external object", http.StatusInternalServerError)
 566			ilog.Printf("error getting external object: %s", err)
 567			return
 568		}
 569		allinjest(originate(xid), j)
 570		dlog.Printf("importing %s", xid)
 571		user, _ := butwhatabout(u.Username)
 572
 573		info, _ := somethingabout(j)
 574		if info == nil {
 575			xonk = xonksaver(user, j, originate(xid))
 576		} else if info.What == SomeActor {
 577			outbox, _ := j.GetString("outbox")
 578			gimmexonks(user, outbox)
 579			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 580			return
 581		} else if info.What == SomeCollection {
 582			gimmexonks(user, xid)
 583			http.Redirect(w, r, "/xzone", http.StatusSeeOther)
 584			return
 585		}
 586	}
 587	convoy := ""
 588	if xonk != nil {
 589		convoy = xonk.Convoy
 590	}
 591	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 592}
 593
 594func xzone(w http.ResponseWriter, r *http.Request) {
 595	u := login.GetUserInfo(r)
 596	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 597	if err != nil {
 598		elog.Printf("query err: %s", err)
 599		return
 600	}
 601	defer rows.Close()
 602	var honkers []Honker
 603	for rows.Next() {
 604		var xid string
 605		rows.Scan(&xid)
 606		honkers = append(honkers, Honker{XID: xid})
 607	}
 608	rows.Close()
 609	for i, _ := range honkers {
 610		_, honkers[i].Handle = handles(honkers[i].XID)
 611	}
 612	templinfo := getInfo(r)
 613	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 614	templinfo["Honkers"] = honkers
 615	err = readviews.Execute(w, "xzone.html", templinfo)
 616	if err != nil {
 617		elog.Print(err)
 618	}
 619}
 620
 621var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
 622	user, err := butwhatabout(name)
 623	if err != nil {
 624		return nil, false
 625	}
 626	honks := gethonksbyuser(name, false, 0)
 627	if len(honks) > 20 {
 628		honks = honks[0:20]
 629	}
 630
 631	var jonks []junk.Junk
 632	for _, h := range honks {
 633		j, _ := jonkjonk(user, h)
 634		jonks = append(jonks, j)
 635	}
 636
 637	j := junk.New()
 638	j["@context"] = itiswhatitis
 639	j["id"] = user.URL + "/outbox"
 640	j["attributedTo"] = user.URL
 641	j["type"] = "OrderedCollection"
 642	j["totalItems"] = len(jonks)
 643	j["orderedItems"] = jonks
 644
 645	return j.ToBytes(), true
 646}, Duration: 1 * time.Minute})
 647
 648func outbox(w http.ResponseWriter, r *http.Request) {
 649	name := mux.Vars(r)["name"]
 650	user, err := butwhatabout(name)
 651	if err != nil {
 652		http.NotFound(w, r)
 653		return
 654	}
 655	if stealthmode(user.ID, r) {
 656		http.NotFound(w, r)
 657		return
 658	}
 659	var j []byte
 660	ok := oldoutbox.Get(name, &j)
 661	if ok {
 662		w.Header().Set("Content-Type", theonetruename)
 663		w.Write(j)
 664	} else {
 665		http.NotFound(w, r)
 666	}
 667}
 668
 669var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
 670	colname := "/followers"
 671	if strings.HasSuffix(url, "/following") {
 672		colname = "/following"
 673	}
 674	user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
 675	j := junk.New()
 676	j["@context"] = itiswhatitis
 677	j["id"] = user + colname
 678	j["attributedTo"] = user
 679	j["type"] = "OrderedCollection"
 680	j["totalItems"] = 0
 681	j["orderedItems"] = []junk.Junk{}
 682
 683	return j.ToBytes(), true
 684}})
 685
 686func emptiness(w http.ResponseWriter, r *http.Request) {
 687	name := mux.Vars(r)["name"]
 688	user, err := butwhatabout(name)
 689	if err != nil {
 690		http.NotFound(w, r)
 691		return
 692	}
 693	if stealthmode(user.ID, r) {
 694		http.NotFound(w, r)
 695		return
 696	}
 697	var j []byte
 698	ok := oldempties.Get(r.URL.Path, &j)
 699	if ok {
 700		w.Header().Set("Content-Type", theonetruename)
 701		w.Write(j)
 702	} else {
 703		http.NotFound(w, r)
 704	}
 705}
 706
 707func showuser(w http.ResponseWriter, r *http.Request) {
 708	name := mux.Vars(r)["name"]
 709	user, err := butwhatabout(name)
 710	if err != nil {
 711		ilog.Printf("user not found %s: %s", name, err)
 712		http.NotFound(w, r)
 713		return
 714	}
 715	if stealthmode(user.ID, r) {
 716		http.NotFound(w, r)
 717		return
 718	}
 719	if friendorfoe(r.Header.Get("Accept")) {
 720		j, ok := asjonker(name)
 721		if ok {
 722			w.Header().Set("Content-Type", theonetruename)
 723			w.Write(j)
 724		} else {
 725			http.NotFound(w, r)
 726		}
 727		return
 728	}
 729	u := login.GetUserInfo(r)
 730	honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
 731	templinfo := getInfo(r)
 732	templinfo["PageName"] = "user"
 733	templinfo["PageArg"] = name
 734	templinfo["Name"] = user.Name
 735	templinfo["WhatAbout"] = user.HTAbout
 736	templinfo["ServerMessage"] = ""
 737	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 738	honkpage(w, u, honks, templinfo)
 739}
 740
 741func showhonker(w http.ResponseWriter, r *http.Request) {
 742	u := login.GetUserInfo(r)
 743	name := mux.Vars(r)["name"]
 744	var honks []*Honk
 745	if name == "" {
 746		name = r.FormValue("xid")
 747		honks = gethonksbyxonker(u.UserID, name, 0)
 748	} else {
 749		honks = gethonksbyhonker(u.UserID, name, 0)
 750	}
 751	miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
 752<input type="hidden" name="CSRF" value="%s">
 753<input type="hidden" name="url" value="%s">
 754<button tabindex=1 name="add honker" value="add honker">add honker</button>
 755</form>`, login.GetCSRF("submithonker", r), name)
 756	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
 757	templinfo := getInfo(r)
 758	templinfo["PageName"] = "honker"
 759	templinfo["PageArg"] = name
 760	templinfo["ServerMessage"] = msg
 761	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 762	honkpage(w, u, honks, templinfo)
 763}
 764
 765func showcombo(w http.ResponseWriter, r *http.Request) {
 766	name := mux.Vars(r)["name"]
 767	u := login.GetUserInfo(r)
 768	honks := gethonksbycombo(u.UserID, name, 0)
 769	honks = osmosis(honks, u.UserID, true)
 770	templinfo := getInfo(r)
 771	templinfo["PageName"] = "combo"
 772	templinfo["PageArg"] = name
 773	templinfo["ServerMessage"] = "honks by combo: " + name
 774	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 775	honkpage(w, u, honks, templinfo)
 776}
 777func showconvoy(w http.ResponseWriter, r *http.Request) {
 778	c := r.FormValue("c")
 779	u := login.GetUserInfo(r)
 780	honks := gethonksbyconvoy(u.UserID, c, 0)
 781	templinfo := getInfo(r)
 782	if len(honks) > 0 {
 783		templinfo["TopHID"] = honks[0].ID
 784	}
 785	honks = osmosis(honks, u.UserID, false)
 786	reversehonks(honks)
 787	templinfo["PageName"] = "convoy"
 788	templinfo["PageArg"] = c
 789	templinfo["ServerMessage"] = "honks in convoy: " + c
 790	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 791	honkpage(w, u, honks, templinfo)
 792}
 793func showsearch(w http.ResponseWriter, r *http.Request) {
 794	q := r.FormValue("q")
 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	noise = strings.Replace(noise, "\r", "", -1)
1616	noise = quickrename(noise, userinfo.UserID)
1617	noise = hooterize(noise)
1618	honk.Noise = noise
1619	precipitate(honk)
1620	noise = honk.Noise
1621	translate(honk)
1622
1623	var convoy string
1624	if rid != "" {
1625		xonk := getxonk(userinfo.UserID, rid)
1626		if xonk == nil {
1627			http.Error(w, "replyto disappeared", http.StatusNotFound)
1628			return nil
1629		}
1630		if xonk.Public {
1631			honk.Audience = append(honk.Audience, xonk.Audience...)
1632		}
1633		convoy = xonk.Convoy
1634		for i, a := range honk.Audience {
1635			if a == thewholeworld {
1636				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1637				break
1638			}
1639		}
1640		honk.RID = rid
1641		if xonk.Precis != "" && honk.Precis == "" {
1642			honk.Precis = xonk.Precis
1643			if !re_dangerous.MatchString(honk.Precis) {
1644				honk.Precis = "re: " + honk.Precis
1645			}
1646		}
1647	} else {
1648		honk.Audience = []string{thewholeworld}
1649	}
1650	if honk.Noise != "" && honk.Noise[0] == '@' {
1651		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1652	} else {
1653		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1654	}
1655
1656	if convoy == "" {
1657		convoy = "data:,electrichonkytonk-" + xfiltrate()
1658	}
1659	butnottooloud(honk.Audience)
1660	honk.Audience = oneofakind(honk.Audience)
1661	if len(honk.Audience) == 0 {
1662		ilog.Printf("honk to nowhere")
1663		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1664		return nil
1665	}
1666	honk.Public = loudandproud(honk.Audience)
1667	honk.Convoy = convoy
1668
1669	donkxid := r.FormValue("donkxid")
1670	if donkxid == "" {
1671		d, err := submitdonk(w, r)
1672		if err != nil && err != http.ErrMissingFile {
1673			return nil
1674		}
1675		if d != nil {
1676			honk.Donks = append(honk.Donks, d)
1677			donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1678		}
1679	} else {
1680		p := strings.Split(donkxid, ":")
1681		xid := p[0]
1682		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1683		var donk *Donk
1684		if len(p) > 1 {
1685			fileid, _ := strconv.ParseInt(p[1], 10, 0)
1686			donk = finddonkid(fileid, url)
1687		} else {
1688			donk = finddonk(url)
1689		}
1690		if donk != nil {
1691			honk.Donks = append(honk.Donks, donk)
1692		} else {
1693			ilog.Printf("can't find file: %s", xid)
1694		}
1695	}
1696	memetize(honk)
1697	imaginate(honk)
1698
1699	placename := strings.TrimSpace(r.FormValue("placename"))
1700	placelat := strings.TrimSpace(r.FormValue("placelat"))
1701	placelong := strings.TrimSpace(r.FormValue("placelong"))
1702	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1703	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1704		p := new(Place)
1705		p.Name = placename
1706		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1707		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1708		p.Url = placeurl
1709		honk.Place = p
1710	}
1711	timestart := strings.TrimSpace(r.FormValue("timestart"))
1712	if timestart != "" {
1713		t := new(Time)
1714		now := time.Now().Local()
1715		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1716			start, err := time.ParseInLocation(layout, timestart, now.Location())
1717			if err == nil {
1718				if start.Year() == 0 {
1719					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1720				}
1721				t.StartTime = start
1722				break
1723			}
1724		}
1725		timeend := r.FormValue("timeend")
1726		dur := parseDuration(timeend)
1727		if dur != 0 {
1728			t.Duration = Duration(dur)
1729		}
1730		if !t.StartTime.IsZero() {
1731			honk.What = "event"
1732			honk.Time = t
1733		}
1734	}
1735
1736	if honk.Public {
1737		honk.Whofore = 2
1738	} else {
1739		honk.Whofore = 3
1740	}
1741
1742	// back to markdown
1743	honk.Noise = noise
1744
1745	if r.FormValue("preview") == "preview" {
1746		honks := []*Honk{honk}
1747		reverbolate(userinfo.UserID, honks)
1748		templinfo := getInfo(r)
1749		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1750		templinfo["Honks"] = honks
1751		templinfo["MapLink"] = getmaplink(userinfo)
1752		templinfo["InReplyTo"] = r.FormValue("rid")
1753		templinfo["Noise"] = r.FormValue("noise")
1754		templinfo["SavedFile"] = donkxid
1755		if tm := honk.Time; tm != nil {
1756			templinfo["ShowTime"] = " "
1757			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1758			if tm.Duration != 0 {
1759				templinfo["Duration"] = tm.Duration
1760			}
1761		}
1762		templinfo["IsPreview"] = true
1763		templinfo["UpdateXID"] = updatexid
1764		templinfo["ServerMessage"] = "honk preview"
1765		err := readviews.Execute(w, "honkpage.html", templinfo)
1766		if err != nil {
1767			elog.Print(err)
1768		}
1769		return nil
1770	}
1771
1772	if updatexid != "" {
1773		updatehonk(honk)
1774		oldjonks.Clear(honk.XID)
1775	} else {
1776		err := savehonk(honk)
1777		if err != nil {
1778			elog.Printf("uh oh")
1779			return nil
1780		}
1781	}
1782
1783	// reload for consistency
1784	honk.Donks = nil
1785	donksforhonks([]*Honk{honk})
1786
1787	go honkworldwide(user, honk)
1788
1789	return honk
1790}
1791
1792func showhonkers(w http.ResponseWriter, r *http.Request) {
1793	userinfo := login.GetUserInfo(r)
1794	templinfo := getInfo(r)
1795	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1796	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1797	err := readviews.Execute(w, "honkers.html", templinfo)
1798	if err != nil {
1799		elog.Print(err)
1800	}
1801}
1802
1803func showchatter(w http.ResponseWriter, r *http.Request) {
1804	u := login.GetUserInfo(r)
1805	chatnewnone(u.UserID)
1806	chatter := loadchatter(u.UserID)
1807	for _, chat := range chatter {
1808		for _, ch := range chat.Chonks {
1809			filterchonk(ch)
1810		}
1811	}
1812
1813	templinfo := getInfo(r)
1814	templinfo["Chatter"] = chatter
1815	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1816	err := readviews.Execute(w, "chatter.html", templinfo)
1817	if err != nil {
1818		elog.Print(err)
1819	}
1820}
1821
1822func submitchonk(w http.ResponseWriter, r *http.Request) {
1823	u := login.GetUserInfo(r)
1824	user, _ := butwhatabout(u.Username)
1825	noise := r.FormValue("noise")
1826	target := r.FormValue("target")
1827	format := "markdown"
1828	dt := time.Now().UTC()
1829	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1830
1831	if !strings.HasPrefix(target, "https://") {
1832		target = fullname(target, u.UserID)
1833	}
1834	if target == "" {
1835		http.Error(w, "who is that?", http.StatusInternalServerError)
1836		return
1837	}
1838	ch := Chonk{
1839		UserID: u.UserID,
1840		XID:    xid,
1841		Who:    user.URL,
1842		Target: target,
1843		Date:   dt,
1844		Noise:  noise,
1845		Format: format,
1846	}
1847	d, err := submitdonk(w, r)
1848	if err != nil && err != http.ErrMissingFile {
1849		return
1850	}
1851	if d != nil {
1852		ch.Donks = append(ch.Donks, d)
1853	}
1854
1855	translatechonk(&ch)
1856	savechonk(&ch)
1857	// reload for consistency
1858	ch.Donks = nil
1859	donksforchonks([]*Chonk{&ch})
1860	go sendchonk(user, &ch)
1861
1862	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1863}
1864
1865var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1866	honkers := gethonkers(userid)
1867	var combos []string
1868	for _, h := range honkers {
1869		combos = append(combos, h.Combos...)
1870	}
1871	for i, c := range combos {
1872		if c == "-" {
1873			combos[i] = ""
1874		}
1875	}
1876	combos = oneofakind(combos)
1877	sort.Strings(combos)
1878	return combos, true
1879}, Invalidator: &honkerinvalidator})
1880
1881func showcombos(w http.ResponseWriter, r *http.Request) {
1882	userinfo := login.GetUserInfo(r)
1883	var combos []string
1884	combocache.Get(userinfo.UserID, &combos)
1885	templinfo := getInfo(r)
1886	err := readviews.Execute(w, "combos.html", templinfo)
1887	if err != nil {
1888		elog.Print(err)
1889	}
1890}
1891
1892func websubmithonker(w http.ResponseWriter, r *http.Request) {
1893	h := submithonker(w, r)
1894	if h == nil {
1895		return
1896	}
1897	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1898}
1899
1900func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
1901	u := login.GetUserInfo(r)
1902	user, _ := butwhatabout(u.Username)
1903	name := strings.TrimSpace(r.FormValue("name"))
1904	url := strings.TrimSpace(r.FormValue("url"))
1905	peep := r.FormValue("peep")
1906	combos := strings.TrimSpace(r.FormValue("combos"))
1907	combos = " " + combos + " "
1908	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1909
1910	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
1911	if name != "" && !re_namecheck.MatchString(name) {
1912		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
1913		return nil
1914	}
1915
1916	var meta HonkerMeta
1917	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1918	mj, _ := jsonify(&meta)
1919
1920	defer honkerinvalidator.Clear(u.UserID)
1921
1922	// mostly dummy, fill in later...
1923	h := &Honker{
1924		ID: honkerid,
1925	}
1926
1927	if honkerid > 0 {
1928		if r.FormValue("delete") == "delete" {
1929			unfollowyou(user, honkerid, false)
1930			stmtDeleteHonker.Exec(honkerid)
1931			return h
1932		}
1933		if r.FormValue("unsub") == "unsub" {
1934			unfollowyou(user, honkerid, false)
1935		}
1936		if r.FormValue("sub") == "sub" {
1937			followyou(user, honkerid, false)
1938		}
1939		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1940		if err != nil {
1941			elog.Printf("update honker err: %s", err)
1942			return nil
1943		}
1944		return h
1945	}
1946
1947	if url == "" {
1948		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1949		return nil
1950	}
1951
1952	flavor := "presub"
1953	if peep == "peep" {
1954		flavor = "peep"
1955	}
1956
1957	var err error
1958	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
1959	if err != nil {
1960		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
1961		return nil
1962	}
1963	if flavor == "presub" {
1964		followyou(user, honkerid, false)
1965	}
1966	h.ID = honkerid
1967	return h
1968}
1969
1970func hfcspage(w http.ResponseWriter, r *http.Request) {
1971	userinfo := login.GetUserInfo(r)
1972
1973	filters := getfilters(userinfo.UserID, filtAny)
1974
1975	templinfo := getInfo(r)
1976	templinfo["Filters"] = filters
1977	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1978	err := readviews.Execute(w, "hfcs.html", templinfo)
1979	if err != nil {
1980		elog.Print(err)
1981	}
1982}
1983
1984func savehfcs(w http.ResponseWriter, r *http.Request) {
1985	userinfo := login.GetUserInfo(r)
1986	itsok := r.FormValue("itsok")
1987	if itsok == "iforgiveyou" {
1988		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1989		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1990		if err != nil {
1991			elog.Printf("error deleting filter: %s", err)
1992		}
1993		filtInvalidator.Clear(userinfo.UserID)
1994		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1995		return
1996	}
1997
1998	filt := new(Filter)
1999	filt.Name = strings.TrimSpace(r.FormValue("name"))
2000	filt.Date = time.Now().UTC()
2001	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2002	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2003	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2004	filt.IsReply = r.FormValue("isreply") == "yes"
2005	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2006	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2007	filt.Reject = r.FormValue("doreject") == "yes"
2008	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2009	filt.Hide = r.FormValue("dohide") == "yes"
2010	filt.Collapse = r.FormValue("docollapse") == "yes"
2011	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2012	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2013	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2014		filt.Expiration = time.Now().UTC().Add(dur)
2015	}
2016	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2017
2018	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2019		ilog.Printf("blank filter")
2020		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2021		return
2022	}
2023
2024	j, err := jsonify(filt)
2025	if err == nil {
2026		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2027	}
2028	if err != nil {
2029		elog.Printf("error saving filter: %s", err)
2030	}
2031
2032	filtInvalidator.Clear(userinfo.UserID)
2033	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2034}
2035
2036func accountpage(w http.ResponseWriter, r *http.Request) {
2037	u := login.GetUserInfo(r)
2038	user, _ := butwhatabout(u.Username)
2039	templinfo := getInfo(r)
2040	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2041	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2042	templinfo["User"] = user
2043	about := user.About
2044	if ava := user.Options.Avatar; ava != "" {
2045		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2046	}
2047	if ban := user.Options.Banner; ban != "" {
2048		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2049	}
2050	templinfo["WhatAbout"] = about
2051	err := readviews.Execute(w, "account.html", templinfo)
2052	if err != nil {
2053		elog.Print(err)
2054	}
2055}
2056
2057func dochpass(w http.ResponseWriter, r *http.Request) {
2058	err := login.ChangePassword(w, r)
2059	if err != nil {
2060		elog.Printf("error changing password: %s", err)
2061	}
2062	http.Redirect(w, r, "/account", http.StatusSeeOther)
2063}
2064
2065func fingerlicker(w http.ResponseWriter, r *http.Request) {
2066	orig := r.FormValue("resource")
2067
2068	dlog.Printf("finger lick: %s", orig)
2069
2070	if strings.HasPrefix(orig, "acct:") {
2071		orig = orig[5:]
2072	}
2073
2074	name := orig
2075	idx := strings.LastIndexByte(name, '/')
2076	if idx != -1 {
2077		name = name[idx+1:]
2078		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2079			ilog.Printf("foreign request rejected")
2080			name = ""
2081		}
2082	} else {
2083		idx = strings.IndexByte(name, '@')
2084		if idx != -1 {
2085			name = name[:idx]
2086			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2087				ilog.Printf("foreign request rejected")
2088				name = ""
2089			}
2090		}
2091	}
2092	user, err := butwhatabout(name)
2093	if err != nil {
2094		http.NotFound(w, r)
2095		return
2096	}
2097	if stealthmode(user.ID, r) {
2098		http.NotFound(w, r)
2099		return
2100	}
2101
2102	j := junk.New()
2103	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2104	j["aliases"] = []string{user.URL}
2105	l := junk.New()
2106	l["rel"] = "self"
2107	l["type"] = `application/activity+json`
2108	l["href"] = user.URL
2109	j["links"] = []junk.Junk{l}
2110
2111	w.Header().Set("Content-Type", "application/jrd+json")
2112	j.Write(w)
2113}
2114
2115func somedays() string {
2116	secs := 432000 + notrand.Int63n(432000)
2117	return fmt.Sprintf("%d", secs)
2118}
2119
2120func lookatme(ava string) string {
2121	if strings.Contains(ava, serverName+"/"+userSep) {
2122		idx := strings.LastIndexByte(ava, '/')
2123		if idx < len(ava) {
2124			name := ava[idx+1:]
2125			user, _ := butwhatabout(name)
2126			if user != nil && user.URL == ava {
2127				return user.Options.Avatar
2128			}
2129		}
2130	}
2131	return ""
2132}
2133
2134func avatate(w http.ResponseWriter, r *http.Request) {
2135	if develMode {
2136		loadAvatarColors()
2137	}
2138	n := r.FormValue("a")
2139	if redir := lookatme(n); redir != "" {
2140		http.Redirect(w, r, redir, http.StatusSeeOther)
2141		return
2142	}
2143	a := genAvatar(n)
2144	if !develMode {
2145		w.Header().Set("Cache-Control", "max-age="+somedays())
2146	}
2147	w.Write(a)
2148}
2149
2150func serveviewasset(w http.ResponseWriter, r *http.Request) {
2151	serveasset(w, r, viewDir)
2152}
2153func servedataasset(w http.ResponseWriter, r *http.Request) {
2154	if r.URL.Path == "/favicon.ico" {
2155		r.URL.Path = "/icon.png"
2156	}
2157	serveasset(w, r, dataDir)
2158}
2159
2160func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2161	if !develMode {
2162		w.Header().Set("Cache-Control", "max-age=7776000")
2163	}
2164	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2165}
2166func servehelp(w http.ResponseWriter, r *http.Request) {
2167	name := mux.Vars(r)["name"]
2168	if !develMode {
2169		w.Header().Set("Cache-Control", "max-age=3600")
2170	}
2171	http.ServeFile(w, r, viewDir+"/docs/"+name)
2172}
2173func servehtml(w http.ResponseWriter, r *http.Request) {
2174	u := login.GetUserInfo(r)
2175	templinfo := getInfo(r)
2176	templinfo["AboutMsg"] = aboutMsg
2177	templinfo["LoginMsg"] = loginMsg
2178	templinfo["HonkVersion"] = softwareVersion
2179	if r.URL.Path == "/about" {
2180		templinfo["Sensors"] = getSensors()
2181	}
2182	if u == nil && !develMode {
2183		w.Header().Set("Cache-Control", "max-age=60")
2184	}
2185	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2186	if err != nil {
2187		elog.Print(err)
2188	}
2189}
2190func serveemu(w http.ResponseWriter, r *http.Request) {
2191	emu := mux.Vars(r)["emu"]
2192
2193	w.Header().Set("Cache-Control", "max-age="+somedays())
2194	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2195}
2196func servememe(w http.ResponseWriter, r *http.Request) {
2197	meme := mux.Vars(r)["meme"]
2198
2199	w.Header().Set("Cache-Control", "max-age="+somedays())
2200	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2201}
2202
2203func servefile(w http.ResponseWriter, r *http.Request) {
2204	xid := mux.Vars(r)["xid"]
2205	var media string
2206	var data []byte
2207	row := stmtGetFileData.QueryRow(xid)
2208	err := row.Scan(&media, &data)
2209	if err != nil {
2210		elog.Printf("error loading file: %s", err)
2211		http.NotFound(w, r)
2212		return
2213	}
2214	w.Header().Set("Content-Type", media)
2215	w.Header().Set("X-Content-Type-Options", "nosniff")
2216	w.Header().Set("Cache-Control", "max-age="+somedays())
2217	w.Write(data)
2218}
2219
2220func nomoroboto(w http.ResponseWriter, r *http.Request) {
2221	io.WriteString(w, "User-agent: *\n")
2222	io.WriteString(w, "Disallow: /a\n")
2223	io.WriteString(w, "Disallow: /d/\n")
2224	io.WriteString(w, "Disallow: /meme/\n")
2225	io.WriteString(w, "Disallow: /o\n")
2226	io.WriteString(w, "Disallow: /o/\n")
2227	io.WriteString(w, "Disallow: /help/\n")
2228	for _, u := range allusers() {
2229		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2230	}
2231}
2232
2233type Hydration struct {
2234	Tophid    int64
2235	Srvmsg    template.HTML
2236	Honks     string
2237	MeCount   int64
2238	ChatCount int64
2239}
2240
2241func webhydra(w http.ResponseWriter, r *http.Request) {
2242	u := login.GetUserInfo(r)
2243	userid := u.UserID
2244	templinfo := getInfo(r)
2245	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2246	page := r.FormValue("page")
2247
2248	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2249
2250	var hydra Hydration
2251
2252	var honks []*Honk
2253	switch page {
2254	case "atme":
2255		honks = gethonksforme(userid, wanted)
2256		honks = osmosis(honks, userid, false)
2257		menewnone(userid)
2258		hydra.Srvmsg = "at me!"
2259	case "longago":
2260		honks = gethonksfromlongago(userid, wanted)
2261		honks = osmosis(honks, userid, false)
2262		hydra.Srvmsg = "from long ago"
2263	case "home":
2264		honks = gethonksforuser(userid, wanted)
2265		honks = osmosis(honks, userid, true)
2266		hydra.Srvmsg = serverMsg
2267	case "first":
2268		honks = gethonksforuserfirstclass(userid, wanted)
2269		honks = osmosis(honks, userid, true)
2270		hydra.Srvmsg = "first class only"
2271	case "saved":
2272		honks = getsavedhonks(userid, wanted)
2273		templinfo["PageName"] = "saved"
2274		hydra.Srvmsg = "saved honks"
2275	case "combo":
2276		c := r.FormValue("c")
2277		honks = gethonksbycombo(userid, c, wanted)
2278		honks = osmosis(honks, userid, false)
2279		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2280	case "convoy":
2281		c := r.FormValue("c")
2282		honks = gethonksbyconvoy(userid, c, wanted)
2283		honks = osmosis(honks, userid, false)
2284		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2285	case "honker":
2286		xid := r.FormValue("xid")
2287		honks = gethonksbyxonker(userid, xid, wanted)
2288		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2289			<input type="hidden" name="CSRF" value="%s">
2290			<input type="hidden" name="url" value="%s">
2291			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2292			</form>`, login.GetCSRF("submithonker", r), xid)
2293		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2294		hydra.Srvmsg = msg
2295	case "user":
2296		uname := r.FormValue("uname")
2297		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2298		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2299	default:
2300		http.NotFound(w, r)
2301	}
2302
2303	if len(honks) > 0 {
2304		hydra.Tophid = honks[0].ID
2305	} else {
2306		hydra.Tophid = wanted
2307	}
2308	reverbolate(userid, honks)
2309
2310	user, _ := butwhatabout(u.Username)
2311
2312	var buf strings.Builder
2313	templinfo["Honks"] = honks
2314	templinfo["MapLink"] = getmaplink(u)
2315	templinfo["User"], _ = butwhatabout(u.Username)
2316	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2317	if err != nil {
2318		elog.Printf("frag error: %s", err)
2319		return
2320	}
2321	hydra.Honks = buf.String()
2322	hydra.MeCount = user.Options.MeCount
2323	hydra.ChatCount = user.Options.ChatCount
2324	w.Header().Set("Content-Type", "application/json")
2325	j, _ := jsonify(&hydra)
2326	io.WriteString(w, j)
2327}
2328
2329var honkline = make(chan bool)
2330
2331func honkhonkline() {
2332	for {
2333		select {
2334		case honkline <- true:
2335		default:
2336			return
2337		}
2338	}
2339}
2340
2341func apihandler(w http.ResponseWriter, r *http.Request) {
2342	u := login.GetUserInfo(r)
2343	userid := u.UserID
2344	action := r.FormValue("action")
2345	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2346	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2347	switch action {
2348	case "honk":
2349		h := submithonk(w, r)
2350		if h == nil {
2351			return
2352		}
2353		fmt.Fprintf(w, "%s", h.XID)
2354	case "donk":
2355		d, err := submitdonk(w, r)
2356		if err != nil {
2357			http.Error(w, err.Error(), http.StatusBadRequest)
2358			return
2359		}
2360		if d == nil {
2361			http.Error(w, "missing donk", http.StatusBadRequest)
2362			return
2363		}
2364		w.Write([]byte(d.XID))
2365	case "zonkit":
2366		zonkit(w, r)
2367	case "gethonks":
2368		var honks []*Honk
2369		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2370		page := r.FormValue("page")
2371		var waitchan <-chan time.Time
2372	requery:
2373		switch page {
2374		case "atme":
2375			honks = gethonksforme(userid, wanted)
2376			honks = osmosis(honks, userid, false)
2377			menewnone(userid)
2378		case "longago":
2379			honks = gethonksfromlongago(userid, wanted)
2380			honks = osmosis(honks, userid, false)
2381		case "home":
2382			honks = gethonksforuser(userid, wanted)
2383			honks = osmosis(honks, userid, true)
2384		case "myhonks":
2385			honks = gethonksbyuser(u.Username, true, wanted)
2386			honks = osmosis(honks, userid, true)
2387		default:
2388			http.Error(w, "unknown page", http.StatusNotFound)
2389			return
2390		}
2391		if len(honks) == 0 && wait > 0 {
2392			if waitchan == nil {
2393				waitchan = time.After(time.Duration(wait) * time.Second)
2394			}
2395			select {
2396			case <-honkline:
2397				goto requery
2398			case <-waitchan:
2399			}
2400		}
2401		reverbolate(userid, honks)
2402		j := junk.New()
2403		j["honks"] = honks
2404		j.Write(w)
2405	case "sendactivity":
2406		user, _ := butwhatabout(u.Username)
2407		public := r.FormValue("public") == "1"
2408		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2409		msg := []byte(r.FormValue("msg"))
2410		for rcpt := range rcpts {
2411			go deliverate(0, userid, rcpt, msg, true)
2412		}
2413	case "gethonkers":
2414		j := junk.New()
2415		j["honkers"] = gethonkers(u.UserID)
2416		j.Write(w)
2417	case "savehonker":
2418		h := submithonker(w, r)
2419		if h == nil {
2420			return
2421		}
2422		fmt.Fprintf(w, "%d", h.ID)
2423	default:
2424		http.Error(w, "unknown action", http.StatusNotFound)
2425		return
2426	}
2427}
2428
2429var endoftheworld = make(chan bool)
2430var readyalready = make(chan bool)
2431var workinprogress = 0
2432
2433func enditall() {
2434	sig := make(chan os.Signal)
2435	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2436	<-sig
2437	ilog.Printf("stopping...")
2438	for i := 0; i < workinprogress; i++ {
2439		endoftheworld <- true
2440	}
2441	ilog.Printf("waiting...")
2442	for i := 0; i < workinprogress; i++ {
2443		<-readyalready
2444	}
2445	ilog.Printf("apocalypse")
2446	os.Exit(0)
2447}
2448
2449var preservehooks []func()
2450
2451func bgmonitor() {
2452	for {
2453		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2454		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2455		if err != nil {
2456			elog.Printf("error deleting old xonkers: %s", err)
2457		}
2458		zaggies.Flush()
2459		time.Sleep(50 * time.Minute)
2460	}
2461}
2462
2463func addcspheaders(next http.Handler) http.Handler {
2464	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2465		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")
2466		next.ServeHTTP(w, r)
2467	})
2468}
2469
2470func emuinit() {
2471	var emunames []string
2472	dir, err := os.Open(dataDir + "/emus")
2473	if err == nil {
2474		emunames, _ = dir.Readdirnames(0)
2475		dir.Close()
2476	}
2477	for _, e := range emunames {
2478		if len(e) <= 4 {
2479			continue
2480		}
2481		ext := e[len(e)-4:]
2482		emu := Emu{
2483			ID:   fmt.Sprintf("/emu/%s", e),
2484			Name: e[:len(e)-4],
2485			Type: "image/" + ext[1:],
2486		}
2487		allemus = append(allemus, emu)
2488	}
2489	sort.Slice(allemus, func(i, j int) bool {
2490		return allemus[i].Name < allemus[j].Name
2491	})
2492}
2493
2494func serve() {
2495	db := opendatabase()
2496	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2497
2498	listener, err := openListener()
2499	if err != nil {
2500		elog.Fatal(err)
2501	}
2502	runBackendServer()
2503	go enditall()
2504	go redeliverator()
2505	go tracker()
2506	go bgmonitor()
2507	loadLingo()
2508	emuinit()
2509
2510	readviews = templates.Load(develMode,
2511		viewDir+"/views/honkpage.html",
2512		viewDir+"/views/honkfrags.html",
2513		viewDir+"/views/honkers.html",
2514		viewDir+"/views/chatter.html",
2515		viewDir+"/views/hfcs.html",
2516		viewDir+"/views/combos.html",
2517		viewDir+"/views/honkform.html",
2518		viewDir+"/views/honk.html",
2519		viewDir+"/views/account.html",
2520		viewDir+"/views/about.html",
2521		viewDir+"/views/funzone.html",
2522		viewDir+"/views/login.html",
2523		viewDir+"/views/xzone.html",
2524		viewDir+"/views/msg.html",
2525		viewDir+"/views/header.html",
2526		viewDir+"/views/onts.html",
2527		viewDir+"/views/emus.html",
2528		viewDir+"/views/honkpage.js",
2529	)
2530	if !develMode {
2531		assets := []string{
2532			viewDir + "/views/style.css",
2533			dataDir + "/views/local.css",
2534			viewDir + "/views/honkpage.js",
2535			dataDir + "/views/local.js",
2536		}
2537		for _, s := range assets {
2538			savedassetparams[s] = getassetparam(s)
2539		}
2540		loadAvatarColors()
2541	}
2542
2543	for _, h := range preservehooks {
2544		h()
2545	}
2546
2547	mux := mux.NewRouter()
2548	mux.Use(addcspheaders)
2549	mux.Use(login.Checker)
2550
2551	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2552
2553	posters := mux.Methods("POST").Subrouter()
2554	getters := mux.Methods("GET").Subrouter()
2555
2556	getters.HandleFunc("/", homepage)
2557	getters.HandleFunc("/home", homepage)
2558	getters.HandleFunc("/front", homepage)
2559	getters.HandleFunc("/events", homepage)
2560	getters.HandleFunc("/robots.txt", nomoroboto)
2561	getters.HandleFunc("/rss", showrss)
2562	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2563	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2564	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2565	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2566	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2567	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2568	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2569	getters.HandleFunc("/a", avatate)
2570	getters.HandleFunc("/o", thelistingoftheontologies)
2571	getters.HandleFunc("/o/{name:.+}", showontology)
2572	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2573	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2574	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2575	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2576
2577	getters.HandleFunc("/flag/{code:.+}", showflag)
2578
2579	getters.HandleFunc("/server", serveractor)
2580	posters.HandleFunc("/server/inbox", serverinbox)
2581	posters.HandleFunc("/inbox", serverinbox)
2582
2583	getters.HandleFunc("/style.css", serveviewasset)
2584	getters.HandleFunc("/honkpage.js", serveviewasset)
2585	getters.HandleFunc("/misc.js", serveviewasset)
2586	getters.HandleFunc("/local.css", servedataasset)
2587	getters.HandleFunc("/local.js", servedataasset)
2588	getters.HandleFunc("/icon.png", servedataasset)
2589	getters.HandleFunc("/favicon.ico", servedataasset)
2590
2591	getters.HandleFunc("/about", servehtml)
2592	getters.HandleFunc("/login", servehtml)
2593	posters.HandleFunc("/dologin", login.LoginFunc)
2594	getters.HandleFunc("/logout", login.LogoutFunc)
2595	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2596
2597	loggedin := mux.NewRoute().Subrouter()
2598	loggedin.Use(login.Required)
2599	loggedin.HandleFunc("/first", homepage)
2600	loggedin.HandleFunc("/chatter", showchatter)
2601	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2602	loggedin.HandleFunc("/saved", homepage)
2603	loggedin.HandleFunc("/account", accountpage)
2604	loggedin.HandleFunc("/funzone", showfunzone)
2605	loggedin.HandleFunc("/chpass", dochpass)
2606	loggedin.HandleFunc("/atme", homepage)
2607	loggedin.HandleFunc("/longago", homepage)
2608	loggedin.HandleFunc("/hfcs", hfcspage)
2609	loggedin.HandleFunc("/xzone", xzone)
2610	loggedin.HandleFunc("/newhonk", newhonkpage)
2611	loggedin.HandleFunc("/edit", edithonkpage)
2612	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2613	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2614	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2615	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2616	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2617	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2618	loggedin.HandleFunc("/honkers", showhonkers)
2619	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2620	loggedin.HandleFunc("/h", showhonker)
2621	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2622	loggedin.HandleFunc("/c", showcombos)
2623	loggedin.HandleFunc("/t", showconvoy)
2624	loggedin.HandleFunc("/q", showsearch)
2625	loggedin.HandleFunc("/hydra", webhydra)
2626	loggedin.HandleFunc("/emus", showemus)
2627	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2628
2629	err = http.Serve(listener, mux)
2630	if err != nil {
2631		elog.Fatal(err)
2632	}
2633}