all repos — honk @ dfad4879c8226e3a8cd776b1ee9caf5d83f9af84

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