all repos — honk @ 1cdcf0570ab2ce9ec07863dd7670d1e7e42173e4

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