all repos — honk @ f5a4b55535f8e31d73d6055edad923e95f414c6c

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