all repos — honk @ 0c27f3dfb4b17c77f8395cbf55cb75f4e58b7f96

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