all repos — honk @ af18a4b1d3f52d22c4ed97213f2b21c98a90f913

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