all repos — honk @ d8c806f17382698deb007894a2fd31f87f7e298b

my fork of honk

web.go (view raw)

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