all repos — honk @ 796aa4e8d07547dc7f9ab17e45ae77b5bf1e43b6

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