all repos — honk @ 0ab13b622ea0644ecd1f2fcb87248d69cb850e26

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