all repos — honk @ e43284c6fe8530e327a25ac87cdf3ea844fdbfe3

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