go/svc/{invoice,speedtest} -> bgpwtf/

Continued from https://gerrit.hackerspace.pl/c/hscloud/+/71 .

Change-Id: I5aef587c7e9a4cec301e3c95530c33914851ad44
diff --git a/bgpwtf/invoice/BUILD.bazel b/bgpwtf/invoice/BUILD.bazel
new file mode 100644
index 0000000..b2e2ee8
--- /dev/null
+++ b/bgpwtf/invoice/BUILD.bazel
@@ -0,0 +1,32 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+
+go_library(
+    name = "go_default_library",
+    srcs = [
+        "calc.go",
+        "main.go",
+        "model.go",
+        "render.go",
+        "statusz.go",
+    ],
+    importpath = "code.hackerspace.pl/hscloud/bgpwtf/invoice",
+    visibility = ["//visibility:private"],
+    deps = [
+        "//go/mirko:go_default_library",
+        "//go/statusz:go_default_library",
+        "//bgpwtf/invoice/templates:go_default_library",
+        "//proto/invoice:go_default_library",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_golang_protobuf//proto:go_default_library",
+        "@com_github_mattn_go_sqlite3//:go_default_library",
+        "@com_github_sebastiaanklippert_go_wkhtmltopdf//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+    ],
+)
+
+go_binary(
+    name = "invoice",
+    embed = [":go_default_library"],
+    visibility = ["//visibility:public"],
+)
diff --git a/bgpwtf/invoice/calc.go b/bgpwtf/invoice/calc.go
new file mode 100644
index 0000000..5df763f
--- /dev/null
+++ b/bgpwtf/invoice/calc.go
@@ -0,0 +1,29 @@
+package main
+
+import (
+	"time"
+
+	pb "code.hackerspace.pl/hscloud/proto/invoice"
+)
+
+func calculateInvoiceData(p *pb.Invoice) {
+	p.Unit = p.Data.Unit
+	if p.Unit == "" {
+		p.Unit = "€"
+	}
+
+	p.TotalNet = 0
+	p.Total = 0
+	for _, i := range p.Data.Item {
+		rowTotalNet := uint64(i.UnitPrice * i.Count)
+		rowTotal := uint64(float64(rowTotalNet) * (float64(1) + float64(i.Vat)/100000))
+
+		p.TotalNet += rowTotalNet
+		p.Total += rowTotal
+		i.TotalNet = rowTotalNet
+		i.Total = rowTotal
+	}
+
+	due := int64(time.Hour*24) * p.Data.DaysDue
+	p.DueDate = time.Unix(0, p.Date).Add(time.Duration(due)).UnixNano()
+}
diff --git a/bgpwtf/invoice/main.go b/bgpwtf/invoice/main.go
new file mode 100644
index 0000000..4a80441
--- /dev/null
+++ b/bgpwtf/invoice/main.go
@@ -0,0 +1,198 @@
+package main
+
+import (
+	"context"
+	"flag"
+
+	"github.com/golang/glog"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	"code.hackerspace.pl/hscloud/go/mirko"
+	pb "code.hackerspace.pl/hscloud/proto/invoice"
+)
+
+var (
+	flagDatabasePath string
+	flagInit         bool
+	flagDisablePKI   bool
+)
+
+type service struct {
+	m *model
+}
+
+func (s *service) CreateInvoice(ctx context.Context, req *pb.CreateInvoiceRequest) (*pb.CreateInvoiceResponse, error) {
+	if req.InvoiceData == nil {
+		return nil, status.Error(codes.InvalidArgument, "invoice data must be given")
+	}
+	if len(req.InvoiceData.Item) < 1 {
+		return nil, status.Error(codes.InvalidArgument, "invoice data must contain at least one item")
+	}
+	for i, item := range req.InvoiceData.Item {
+		if item.Title == "" {
+			return nil, status.Errorf(codes.InvalidArgument, "invoice data item %d must have title set", i)
+		}
+		if item.Count == 0 || item.Count > 1000000 {
+			return nil, status.Errorf(codes.InvalidArgument, "invoice data item %d must have correct count", i)
+		}
+		if item.UnitPrice == 0 {
+			return nil, status.Errorf(codes.InvalidArgument, "invoice data item %d must have correct unit price", i)
+		}
+		if item.Vat > 100000 {
+			return nil, status.Errorf(codes.InvalidArgument, "invoice data item %d must have correct vat set", i)
+		}
+	}
+	if len(req.InvoiceData.CustomerBilling) < 1 {
+		return nil, status.Error(codes.InvalidArgument, "invoice data must contain at least one line of the customer's billing address")
+	}
+	if len(req.InvoiceData.InvoicerBilling) < 1 {
+		return nil, status.Error(codes.InvalidArgument, "invoice data must contain at least one line of the invoicer's billing address")
+	}
+	for i, c := range req.InvoiceData.InvoicerContact {
+		if c.Medium == "" {
+			return nil, status.Errorf(codes.InvalidArgument, "contact point %d must have medium set", i)
+		}
+		if c.Contact == "" {
+			return nil, status.Errorf(codes.InvalidArgument, "contact point %d must have contact set", i)
+		}
+	}
+	if req.InvoiceData.InvoicerVatId == "" {
+		return nil, status.Error(codes.InvalidArgument, "invoice data must contain invoicer's vat id")
+	}
+
+	uid, err := s.m.createInvoice(ctx, req.InvoiceData)
+	if err != nil {
+		if _, ok := status.FromError(err); ok {
+			return nil, err
+		}
+		glog.Errorf("createInvoice(_, _): %v", err)
+		return nil, status.Error(codes.Unavailable, "could not create invoice")
+	}
+	return &pb.CreateInvoiceResponse{
+		Uid: uid,
+	}, nil
+}
+
+func (s *service) GetInvoice(ctx context.Context, req *pb.GetInvoiceRequest) (*pb.GetInvoiceResponse, error) {
+	invoice, err := s.m.getInvoice(ctx, req.Uid)
+	if err != nil {
+		if _, ok := status.FromError(err); ok {
+			return nil, err
+		}
+		glog.Errorf("getInvoice(_, %q): %v", req.Uid, err)
+		return nil, status.Error(codes.Unavailable, "internal server error")
+	}
+	res := &pb.GetInvoiceResponse{
+		Invoice: invoice,
+	}
+	return res, nil
+}
+
+func newService(m *model) *service {
+	return &service{
+		m: m,
+	}
+}
+
+func (s *service) invoicePDF(ctx context.Context, uid, language string) ([]byte, error) {
+	sealed, err := s.m.getSealedUid(ctx, uid)
+	if err != nil {
+		return nil, err
+	}
+
+	var rendered []byte
+	if sealed != "" {
+		// Invoice is sealed, return stored PDF.
+		rendered, err = s.m.getRendered(ctx, uid)
+		if err != nil {
+			return nil, err
+		}
+	} else {
+		// Invoice is proforma, render.
+		invoice, err := s.m.getInvoice(ctx, uid)
+		if err != nil {
+			return nil, err
+		}
+
+		rendered, err = renderInvoicePDF(invoice, language)
+		if err != nil {
+			return nil, err
+		}
+	}
+	return rendered, nil
+}
+
+func (s *service) RenderInvoice(req *pb.RenderInvoiceRequest, srv pb.Invoicer_RenderInvoiceServer) error {
+	rendered, err := s.invoicePDF(srv.Context(), req.Uid, req.Language)
+	if err != nil {
+		if _, ok := status.FromError(err); ok {
+			return err
+		}
+		glog.Errorf("invoicePDF(_, %q): %v", req.Uid, err)
+		return status.Error(codes.Unavailable, "internal server error")
+	}
+
+	chunkSize := 16 * 1024
+	chunk := &pb.RenderInvoiceResponse{}
+	for i := 0; i < len(rendered); i += chunkSize {
+		if i+chunkSize > len(rendered) {
+			chunk.Data = rendered[i:len(rendered)]
+		} else {
+			chunk.Data = rendered[i : i+chunkSize]
+		}
+		if err := srv.Send(chunk); err != nil {
+			glog.Errorf("srv.Send: %v", err)
+			return status.Error(codes.Unavailable, "stream broken")
+		}
+	}
+	return nil
+}
+
+func (s *service) SealInvoice(ctx context.Context, req *pb.SealInvoiceRequest) (*pb.SealInvoiceResponse, error) {
+	useProformaTime := false
+	if req.DateSource == pb.SealInvoiceRequest_DATE_SOURCE_PROFORMA {
+		useProformaTime = true
+	}
+	if err := s.m.sealInvoice(ctx, req.Uid, req.Language, useProformaTime); err != nil {
+		if _, ok := status.FromError(err); ok {
+			return nil, err
+		}
+		glog.Errorf("sealInvoice(_, %q): %v", req.Uid, err)
+		return nil, status.Error(codes.Unavailable, "internal server error")
+	}
+	return &pb.SealInvoiceResponse{}, nil
+}
+
+func init() {
+	flag.Set("logtostderr", "true")
+}
+
+func main() {
+	flag.StringVar(&flagDatabasePath, "db_path", "./foo.db", "path to sqlite database")
+	flag.BoolVar(&flagInit, "init_db", false, "init database and exit")
+	flag.Parse()
+
+	m, err := newModel(flagDatabasePath)
+	if err != nil {
+		glog.Exitf("newModel: %v", err)
+	}
+	if flagInit {
+		glog.Exit(m.init())
+	}
+
+	mi := mirko.New()
+	if err := mi.Listen(); err != nil {
+		glog.Exitf("Listen failed: %v", err)
+	}
+
+	s := newService(m)
+	s.setupStatusz(mi)
+	pb.RegisterInvoicerServer(mi.GRPC(), s)
+
+	if err := mi.Serve(); err != nil {
+		glog.Exitf("Serve failed: %v", err)
+	}
+
+	<-mi.Done()
+}
diff --git a/bgpwtf/invoice/model.go b/bgpwtf/invoice/model.go
new file mode 100644
index 0000000..d628e1a
--- /dev/null
+++ b/bgpwtf/invoice/model.go
@@ -0,0 +1,295 @@
+package main
+
+import (
+	"context"
+	"database/sql"
+	"fmt"
+	"strconv"
+	"time"
+
+	"github.com/golang/glog"
+	"github.com/golang/protobuf/proto"
+	_ "github.com/mattn/go-sqlite3"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	pb "code.hackerspace.pl/hscloud/proto/invoice"
+)
+
+type model struct {
+	db *sql.DB
+}
+
+func newModel(dsn string) (*model, error) {
+	db, err := sql.Open("sqlite3", dsn)
+	if err != nil {
+		return nil, err
+	}
+	return &model{
+		db: db,
+	}, nil
+}
+
+func (m *model) init() error {
+	_, err := m.db.Exec(`
+		create table invoice (
+			id integer primary key not null,
+			created_time integer not null,
+			proto blob not null
+		);
+		create table invoice_seal (
+			id integer primary key not null,
+			invoice_id integer not null,
+			final_uid text not null unique,
+			sealed_time integer not null,
+			foreign key (invoice_id) references invoice(id)
+		);
+		create table invoice_blob (
+			id integer primary key not null,
+			invoice_id integer not null,
+			pdf blob not null,
+			foreign key (invoice_id) references invoice(id)
+		);
+	`)
+	return err
+}
+
+func (m *model) sealInvoice(ctx context.Context, uid, language string, useProformaTime bool) error {
+	id, err := strconv.Atoi(uid)
+	if err != nil {
+		return status.Error(codes.InvalidArgument, "invalid uid")
+	}
+
+	invoice, err := m.getInvoice(ctx, uid)
+	if err != nil {
+		return err
+	}
+
+	tx, err := m.db.BeginTx(ctx, nil)
+	if err != nil {
+		return err
+	}
+
+	q := `
+		insert into invoice_seal (
+			invoice_id, final_uid, sealed_time
+		) values (
+			?,
+			( select printf("%04d", ifnull( (select final_uid as v from invoice_seal order by final_uid desc limit 1), 19000) + 1 )),
+			?
+		)
+
+	`
+	sealTime := time.Now()
+	if useProformaTime {
+		sealTime = time.Unix(0, invoice.Date)
+	}
+	res, err := tx.Exec(q, id, sealTime.UnixNano())
+	if err != nil {
+		return err
+	}
+
+	lastInvoiceSealId, err := res.LastInsertId()
+	if err != nil {
+		return err
+	}
+
+	q = `
+		select final_uid from invoice_seal where id = ?
+	`
+
+	var finalUid string
+	if err := tx.QueryRow(q, lastInvoiceSealId).Scan(&finalUid); err != nil {
+		return err
+	}
+
+	invoice.State = pb.Invoice_STATE_SEALED
+	// TODO(q3k): this should be configurable.
+	invoice.FinalUid = fmt.Sprintf("FV/%s", finalUid)
+	invoice.Date = sealTime.UnixNano()
+	calculateInvoiceData(invoice)
+
+	pdfBlob, err := renderInvoicePDF(invoice, language)
+	if err != nil {
+		return err
+	}
+
+	q = `
+		insert into invoice_blob (
+			invoice_id, pdf
+		) values (
+			?, ?
+		)
+	`
+
+	if _, err := tx.Exec(q, id, pdfBlob); err != nil {
+		return err
+	}
+
+	if err := tx.Commit(); err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func (m *model) createInvoice(ctx context.Context, id *pb.InvoiceData) (string, error) {
+	data, err := proto.Marshal(id)
+	if err != nil {
+		return "", err
+	}
+
+	sql := `
+		insert into invoice (
+			proto, created_time
+		) values (
+			?, ?
+		)
+	`
+
+	t := time.Now()
+	if id.Date != 0 {
+		t = time.Unix(0, id.Date)
+	}
+
+	res, err := m.db.Exec(sql, data, t.UnixNano())
+	if err != nil {
+		return "", err
+	}
+	uid, err := res.LastInsertId()
+	if err != nil {
+		return "", err
+	}
+
+	glog.Infof("%+v", uid)
+	return fmt.Sprintf("%d", uid), nil
+}
+
+func (m *model) getRendered(ctx context.Context, uid string) ([]byte, error) {
+	id, err := strconv.Atoi(uid)
+	if err != nil {
+		return nil, status.Error(codes.InvalidArgument, "invalid uid")
+	}
+
+	q := `
+		select invoice_blob.pdf from invoice_blob where invoice_blob.invoice_id = ?
+	`
+	res := m.db.QueryRow(q, id)
+
+	data := []byte{}
+	if err := res.Scan(&data); err != nil {
+		if err == sql.ErrNoRows {
+			return nil, status.Error(codes.InvalidArgument, "no such invoice")
+		}
+		return nil, err
+	}
+	return data, nil
+}
+
+func (m *model) getSealedUid(ctx context.Context, uid string) (string, error) {
+	id, err := strconv.Atoi(uid)
+	if err != nil {
+		return "", status.Error(codes.InvalidArgument, "invalid uid")
+	}
+
+	q := `
+		select invoice_seal.final_uid from invoice_seal where invoice_seal.invoice_id = ?
+	`
+	res := m.db.QueryRow(q, id)
+	finalUid := ""
+	if err := res.Scan(&finalUid); err != nil {
+		if err == sql.ErrNoRows {
+			return "", nil
+		}
+		return "", err
+	}
+	return finalUid, nil
+}
+
+type sqlInvoiceSealRow struct {
+	proto       []byte
+	createdTime int64
+	sealedTime  sql.NullInt64
+	finalUid    sql.NullString
+	uid         int64
+}
+
+func (s *sqlInvoiceSealRow) Proto() (*pb.Invoice, error) {
+	data := &pb.InvoiceData{}
+	if err := proto.Unmarshal(s.proto, data); err != nil {
+		return nil, err
+	}
+
+	p := &pb.Invoice{
+		Uid:  fmt.Sprintf("%d", s.uid),
+		Data: data,
+	}
+	if s.finalUid.Valid {
+		p.State = pb.Invoice_STATE_SEALED
+		p.FinalUid = fmt.Sprintf("FV/%s", s.finalUid.String)
+		p.Date = s.sealedTime.Int64
+	} else {
+		p.State = pb.Invoice_STATE_PROFORMA
+		p.FinalUid = fmt.Sprintf("PROFORMA/%d", s.uid)
+		p.Date = s.createdTime
+	}
+	calculateInvoiceData(p)
+	return p, nil
+}
+
+func (m *model) getInvoice(ctx context.Context, uid string) (*pb.Invoice, error) {
+	id, err := strconv.Atoi(uid)
+	if err != nil {
+		return nil, status.Error(codes.InvalidArgument, "invalid uid")
+	}
+
+	q := `
+		select
+				invoice.id, invoice.proto, invoice.created_time, invoice_seal.sealed_time, invoice_seal.final_uid
+		from invoice
+		left join invoice_seal
+		on invoice_seal.invoice_id = invoice.id
+		where invoice.id = ?
+	`
+	res := m.db.QueryRow(q, id)
+	row := sqlInvoiceSealRow{}
+	if err := res.Scan(&row.uid, &row.proto, &row.createdTime, &row.sealedTime, &row.finalUid); err != nil {
+		if err == sql.ErrNoRows {
+			return nil, status.Error(codes.NotFound, "no such invoice")
+		}
+		return nil, err
+	}
+
+	return row.Proto()
+}
+
+func (m *model) getInvoices(ctx context.Context) ([]*pb.Invoice, error) {
+	q := `
+		select
+				invoice.id, invoice.proto, invoice.created_time, invoice_seal.sealed_time, invoice_seal.final_uid
+		from invoice
+		left join invoice_seal
+		on invoice_seal.invoice_id = invoice.id
+	`
+	rows, err := m.db.QueryContext(ctx, q)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+
+	res := []*pb.Invoice{}
+
+	for rows.Next() {
+		row := sqlInvoiceSealRow{}
+		if err := rows.Scan(&row.uid, &row.proto, &row.createdTime, &row.sealedTime, &row.finalUid); err != nil {
+			return nil, err
+		}
+		p, err := row.Proto()
+		if err != nil {
+			return nil, err
+		}
+		res = append(res, p)
+	}
+
+	return res, nil
+}
diff --git a/bgpwtf/invoice/proto/BUILD.bazel b/bgpwtf/invoice/proto/BUILD.bazel
new file mode 100644
index 0000000..511bf26
--- /dev/null
+++ b/bgpwtf/invoice/proto/BUILD.bazel
@@ -0,0 +1,8 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["generate.go"],
+    importpath = "code.hackerspace.pl/hscloud/bgpwtf/invoice/proto",
+    visibility = ["//visibility:public"],
+)
diff --git a/bgpwtf/invoice/proto/generate.go b/bgpwtf/invoice/proto/generate.go
new file mode 100644
index 0000000..b0f6618
--- /dev/null
+++ b/bgpwtf/invoice/proto/generate.go
@@ -0,0 +1,3 @@
+package proto
+
+//go:generate protoc -I.. ../inboice.proto --go_out=plugins=grpc:.
diff --git a/bgpwtf/invoice/render.go b/bgpwtf/invoice/render.go
new file mode 100644
index 0000000..2353014
--- /dev/null
+++ b/bgpwtf/invoice/render.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+	"bytes"
+	"fmt"
+	"html/template"
+	"time"
+
+	wkhtml "github.com/sebastiaanklippert/go-wkhtmltopdf"
+
+	"code.hackerspace.pl/hscloud/bgpwtf/invoice/templates"
+	pb "code.hackerspace.pl/hscloud/proto/invoice"
+)
+
+var (
+	invTmpl map[string]*template.Template
+
+	languages       = []string{"en", "pl"}
+	defaultLanguage = "en"
+)
+
+func init() {
+	invTmpl = make(map[string]*template.Template)
+	for _, language := range languages {
+		filename := fmt.Sprintf("invoice_%s.html", language)
+		a, err := templates.Asset(filename)
+		if err != nil {
+			panic(err)
+		}
+		invTmpl[language] = template.Must(template.New(filename).Parse(string(a)))
+	}
+}
+
+func renderInvoicePDF(i *pb.Invoice, language string) ([]byte, error) {
+	type item struct {
+		Title     string
+		UnitPrice string
+		Qty       string
+		VATRate   string
+		TotalNet  string
+		Total     string
+	}
+
+	data := struct {
+		InvoiceNumber         string
+		InvoicerBilling       []string
+		InvoicerVAT           string
+		InvoicerCompanyNumber string
+		InvoiceeBilling       []string
+		InvoiceeVAT           string
+		Date                  time.Time
+		DueDate               time.Time
+		IBAN                  string
+		SWIFT                 string
+		Proforma              bool
+		ReverseVAT            bool
+		USCustomer            bool
+		Items                 []item
+		TotalNet              string
+		VATTotal              string
+		Total                 string
+		DeliveryCharge        string
+	}{
+		InvoiceNumber:         i.FinalUid,
+		Date:                  time.Unix(0, i.Date),
+		DueDate:               time.Unix(0, i.DueDate),
+		IBAN:                  i.Data.Iban,
+		SWIFT:                 i.Data.Swift,
+		InvoicerVAT:           i.Data.InvoicerVatId,
+		InvoicerCompanyNumber: i.Data.InvoicerCompanyNumber,
+		InvoiceeVAT:           i.Data.CustomerVatId,
+		Proforma:              i.State == pb.Invoice_STATE_PROFORMA,
+		ReverseVAT:            i.Data.ReverseVat,
+		USCustomer:            i.Data.UsCustomer,
+
+		InvoicerBilling: make([]string, len(i.Data.InvoicerBilling)),
+		InvoiceeBilling: make([]string, len(i.Data.CustomerBilling)),
+	}
+
+	for d, s := range i.Data.InvoicerBilling {
+		data.InvoicerBilling[d] = s
+	}
+	for d, s := range i.Data.CustomerBilling {
+		data.InvoiceeBilling[d] = s
+	}
+
+	unit := i.Unit
+
+	for _, it := range i.Data.Item {
+		data.Items = append(data.Items, item{
+			Title:     it.Title,
+			Qty:       fmt.Sprintf("%d", it.Count),
+			UnitPrice: fmt.Sprintf(unit+"%.2f", float64(it.UnitPrice)/100),
+			VATRate:   fmt.Sprintf("%.2f%%", float64(it.Vat)/1000),
+			TotalNet:  fmt.Sprintf(unit+"%.2f", float64(it.TotalNet)/100),
+			Total:     fmt.Sprintf(unit+"%.2f", float64(it.Total)/100),
+		})
+	}
+
+	data.TotalNet = fmt.Sprintf(unit+"%.2f", float64(i.TotalNet)/100)
+	data.VATTotal = fmt.Sprintf(unit+"%.2f", float64(i.Total-i.TotalNet)/100)
+	data.Total = fmt.Sprintf(unit+"%.2f", float64(i.Total)/100)
+	data.DeliveryCharge = fmt.Sprintf(unit+"%.2f", float64(0))
+
+	if _, ok := invTmpl[language]; !ok {
+		language = defaultLanguage
+	}
+
+	var b bytes.Buffer
+	err := invTmpl[language].Execute(&b, &data)
+	if err != nil {
+		return []byte{}, err
+	}
+
+	pdfg, err := wkhtml.NewPDFGenerator()
+	if err != nil {
+		return []byte{}, err
+	}
+	pdfg.Dpi.Set(600)
+	pdfg.NoCollate.Set(false)
+	pdfg.PageSize.Set(wkhtml.PageSizeA4)
+
+	pdfg.AddPage(wkhtml.NewPageReader(&b))
+
+	if err := pdfg.Create(); err != nil {
+		return []byte{}, err
+	}
+	return pdfg.Bytes(), nil
+}
diff --git a/bgpwtf/invoice/statusz.go b/bgpwtf/invoice/statusz.go
new file mode 100644
index 0000000..0a64ce4
--- /dev/null
+++ b/bgpwtf/invoice/statusz.go
@@ -0,0 +1,105 @@
+package main
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"sort"
+	"time"
+
+	"code.hackerspace.pl/hscloud/go/mirko"
+	"code.hackerspace.pl/hscloud/go/statusz"
+	pb "code.hackerspace.pl/hscloud/proto/invoice"
+	"github.com/golang/glog"
+)
+
+const invoicesFragment = `
+    <style type="text/css">
+		.table td,th {
+			background-color: #eee;
+			padding: 0.2em 0.4em 0.2em 0.4em;
+		}
+		.table th {
+			background-color: #c0c0c0;
+		}
+		.table {
+			background-color: #fff;
+			border-spacing: 0.2em;
+			margin-left: auto;
+			margin-right: auto;
+		}
+	</style>
+    <div>
+		{{ .Msg }}
+        <table class="table">
+            <tr>
+                <th>Number</th>
+				<th>Created/Issued</th>
+				<th>Customer</th>
+				<th>Amount (net)</th>
+				<th>Actions</th>
+            </tr>
+            {{ range .Invoices }}
+				{{ if eq .State 2 }}
+				<tr>
+				{{ else }}
+				<tr style="opacity: 0.5">
+				{{ end }}
+				    <td>{{ .FinalUid }}</td>
+					<td>{{ .DatePretty.Format "2006/01/02 15:04:05" }}</td>
+					<td>{{ index .Data.CustomerBilling 0 }}</td>
+					<td>{{ .TotalNetPretty }}</td>
+				    <td>
+						{{ if eq .State 2 }}
+						<a href="/debug/view?id={{ .Uid }}">View</a>
+						{{ else }}
+						<a href="/debug/view?id={{ .Uid }}&language=en">Preview (en)</a> |
+						<a href="/debug/view?id={{ .Uid }}&language=pl">Preview (pl)</a>
+						{{ end }}
+					</td>
+				</tr>
+			{{ end }}
+        </table>
+    </div>
+`
+
+type templateInvoice struct {
+	*pb.Invoice
+	TotalNetPretty string
+	DatePretty     time.Time
+}
+
+func (s *service) setupStatusz(m *mirko.Mirko) {
+	statusz.AddStatusPart("Invoices", invoicesFragment, func(ctx context.Context) interface{} {
+		var res struct {
+			Invoices []templateInvoice
+			Msg      string
+		}
+		invoices, err := s.m.getInvoices(ctx)
+		res.Invoices = make([]templateInvoice, len(invoices))
+		for i, inv := range invoices {
+			res.Invoices[i] = templateInvoice{
+				Invoice:        inv,
+				TotalNetPretty: fmt.Sprintf("%.2f %s", float64(inv.TotalNet)/100, inv.Unit),
+				DatePretty:     time.Unix(0, inv.Date),
+			}
+		}
+
+		if err != nil {
+			glog.Errorf("Could not get invoices for statusz: %v", err)
+			res.Msg = fmt.Sprintf("Could not get invoices: %v", err)
+		}
+
+		sort.Slice(res.Invoices, func(i, j int) bool { return res.Invoices[i].Date > res.Invoices[j].Date })
+		return res
+	})
+
+	m.HTTPMux().HandleFunc("/debug/view", func(w http.ResponseWriter, r *http.Request) {
+		rendered, err := s.invoicePDF(r.Context(), r.URL.Query().Get("id"), r.URL.Query().Get("language"))
+		if err != nil {
+			fmt.Fprintf(w, "error: %v", err)
+		}
+		w.Header().Set("Content-type", "application/pdf")
+		w.Write(rendered)
+	})
+}
diff --git a/bgpwtf/invoice/templates/BUILD.bazel b/bgpwtf/invoice/templates/BUILD.bazel
new file mode 100644
index 0000000..4756da4
--- /dev/null
+++ b/bgpwtf/invoice/templates/BUILD.bazel
@@ -0,0 +1,18 @@
+load("@io_bazel_rules_go//extras:bindata.bzl", "bindata")
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+bindata(
+    name = "templates_bindata",
+    srcs = glob(["*"]),
+    extra_args = ["."],
+    package = "templates",
+)
+
+go_library(
+    name = "go_default_library",
+    srcs = [
+        ":templates_bindata",  # keep
+    ],
+    importpath = "code.hackerspace.pl/hscloud/bgpwtf/invoice/templates",  # keep
+    visibility = ["//bgpwtf/invoice:__subpackages__"],
+)
diff --git a/bgpwtf/invoice/templates/invoice_en.html b/bgpwtf/invoice/templates/invoice_en.html
new file mode 100644
index 0000000..d661732
--- /dev/null
+++ b/bgpwtf/invoice/templates/invoice_en.html
@@ -0,0 +1,199 @@
+<!doctype html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8">
+        <title>Invoice 0001</title>
+        <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">
+        <style type="text/css">
+body {
+    background-color: #fff;
+    font-family: 'Roboto', sans-serif;
+    font-size: 1em;
+
+    padding: 2em;
+}
+ul {
+    list-style: none;
+    padding: 0;
+}
+ul li {
+    margin-bottom: 0.2em;
+}
+
+@page {
+  size: A4;
+  margin: 0;
+}
+div.rhs {
+    float: right;
+    width: 50%;
+    text-align: right;
+}
+div.lhs {
+    float: left;
+    text-align: left;
+    width: 50%;
+    min-height: 35em;
+}
+div.metadata {
+    margin-top: 2em;
+}
+div.invoicee {
+    margin-top: 9em;
+}
+h1 {
+    font-size: 1.5em;
+    margin: 0;
+    text-transform: uppercase;
+}
+h2 {
+    font-size: 1.2em;
+    margin: 0;
+}
+table.items {
+    text-align: right;
+    border-spacing: 0px;
+    border-collapse: collapse;
+    border: 0;
+    width: 100%;
+}
+table.items td,th {
+    border: 1px solid black;
+}
+table.items tr:first-child {
+    background-color: #eee;
+    color: #111;
+    padding: 0.8em;
+    text-align: left;
+}
+table.items td {
+    background-color: #fff;
+}
+table.items td,th {
+    padding: 0.5em 1em 0.5em 1em;
+}
+td.lhead {
+    border: 0 !important;
+    text-align: right;
+    text-transform: uppercase;
+    background: rgba(0, 0, 0, 0) !important;
+}
+div.bgtext {
+    z-index: -10;
+    position: absolute;
+    top: 140mm;
+    left: 0;
+    width: 100%;
+}
+div.bgtext div {
+    text-align: center;
+    font-size: 10em;
+    color: #ddd;
+    -webkit-transform: rotate(-45deg);
+    text-transform: uppercase;
+}
+        </style>
+    </head>
+    <body>
+        {{ if .Proforma }}
+        <div class="bgtext"><div>Proforma</div></div>
+        {{ end }}
+        <div class="rhs">
+            <div class="invoicer">
+                <ul>
+                    {{ range $i, $e := .InvoicerBilling }}
+                    {{ if eq $i 0 }}
+                    <li><b>{{ $e }}</b></li>
+                    {{ else }}
+                    <li>{{ $e }}</li>
+                    {{ end }}
+                    {{ end }}
+                    {{ if .InvoicerCompanyNumber }}
+                    <li>{{ .InvoicerCompanyNumber }}</li>
+                    {{ end }}
+                    <li><b>Tax Number:</b> {{ .InvoicerVAT }}</li>
+                </ul>
+            </div>
+            <div class="metadata">
+                <ul>
+                    <li><b>Invoice number:</b> {{ .InvoiceNumber }}</li>
+                    <li><b>Date:</b> {{ .Date.Format "2006/01/02" }}</li>
+                    <li><b>Due date:</b> {{ .DueDate.Format "2006/01/02" }}</li>
+                    <li><b>IBAN:</b> {{ .IBAN }}</li>
+                    <li><b>SWIFT/BIC:</b> {{ .SWIFT }}</li>
+                </ul>
+            </div>
+        </div>
+        <div class="lhs">
+            <div class="invoicee">
+                {{ if .Proforma }}
+                <h1>Proforma Invoice</h1>
+                {{ else }}
+                <h1>VAT Invoice</h1>
+                {{ end }}
+                <ul>
+                    {{ range $i, $e := .InvoiceeBilling }}
+                    {{ if eq $i 0 }}
+                    <li><b>{{ $e }}</b></li>
+                    {{ else }}
+                    <li>{{ $e }}</li>
+                    {{ end }}
+                    {{ end }}
+                    {{ if .USCustomer }}
+                    <li>EIN: {{ .InvoiceeVAT }}</li>
+                    <li><b>(VAT zero rate)</b></li>
+                    {{ else }}
+                    <li><b>NIP:</b> {{ .InvoiceeVAT }}</li>
+                    {{ end }}
+
+                    {{ if .ReverseVAT }}
+                    <li><b>(reverse charge / obciążenie odwrotne)</b></li>
+                    {{ end }}
+                </ul>
+            </div>
+        </div>
+        <div style="clear: both; height: 1em;"></div>
+        <table class="items">
+            <tr>
+                <th style="width: 60%;">Name of goods / service</th>
+                <th>Unit price<br />(net)</th>
+                <th>Qty</th>
+                {{ if not .ReverseVAT }}
+                <th>VAT rate</th>
+                {{ end }}
+                <th>Goods value<br />(net)</th>
+                {{ if not .ReverseVAT }}
+                <th>Goods value<br />(gross)</th>
+                {{ end }}
+            </tr>
+            {{ range .Items }}
+            <tr>
+                <td style="text-align: left;">{{ .Title }}</td>
+                <td>{{ .UnitPrice }}</td>
+                <td>{{ .Qty }}</td>
+                {{ if not $.ReverseVAT }}
+                <td>{{ .VATRate }}</td>
+                {{ end }}
+                <td>{{ .TotalNet }}</td>
+                {{ if not $.ReverseVAT }}
+                <td>{{ .Total }}</td>
+                {{ end }}
+            </tr>
+            {{ end }}
+            {{ if not .ReverseVAT }}
+            <tr>
+                <td colspan="5" class="lhead">Subtotal without VAT</td>
+                <td>{{ .TotalNet }}</td>
+            </tr>
+            <tr>
+                <td colspan="5" class="lhead">VAT Total {{ if .USCustomer }}(VAT zero rate){{ end }}</td>
+                <td>{{ .VATTotal }}</td>
+            </tr>
+            {{ end }}
+            <tr>
+                <td colspan="{{ if .ReverseVAT }}3{{ else }}5{{ end }}" class="lhead"><b>Total</b></td>
+                <td><b>{{ .Total }}</b></td>
+            </tr>
+        </table>
+    </body>
+</html>
diff --git a/bgpwtf/invoice/templates/invoice_pl.html b/bgpwtf/invoice/templates/invoice_pl.html
new file mode 100644
index 0000000..df49da8
--- /dev/null
+++ b/bgpwtf/invoice/templates/invoice_pl.html
@@ -0,0 +1,190 @@
+<!doctype html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8">
+        <title>Invoice 0001</title>
+        <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">
+        <style type="text/css">
+body {
+    background-color: #fff;
+    font-family: 'Roboto', sans-serif;
+    font-size: 1em;
+
+    padding: 2em;
+}
+ul {
+    list-style: none;
+    padding: 0;
+}
+ul li {
+    margin-bottom: 0.2em;
+}
+
+@page {
+  size: A4;
+  margin: 0;
+}
+div.rhs {
+    float: right;
+    width: 50%;
+    text-align: right;
+}
+div.lhs {
+    float: left;
+    text-align: left;
+    width: 50%;
+    min-height: 35em;
+}
+div.metadata {
+    margin-top: 2em;
+}
+div.invoicee {
+    margin-top: 9em;
+}
+h1 {
+    font-size: 1.5em;
+    margin: 0;
+    text-transform: uppercase;
+}
+h2 {
+    font-size: 1.2em;
+    margin: 0;
+}
+table.items {
+    text-align: right;
+    border-spacing: 0px;
+    border-collapse: collapse;
+    border: 0;
+    width: 100%;
+}
+table.items td,th {
+    border: 1px solid black;
+}
+table.items tr:first-child {
+    background-color: #eee;
+    color: #111;
+    padding: 0.8em;
+    text-align: left;
+}
+table.items td {
+    background-color: #fff;
+}
+table.items td,th {
+    padding: 0.5em 1em 0.5em 1em;
+}
+td.lhead {
+    border: 0 !important;
+    text-align: right;
+    text-transform: uppercase;
+    background: rgba(0, 0, 0, 0) !important;
+}
+div.bgtext {
+    z-index: -10;
+    position: absolute;
+    top: 140mm;
+    left: 0;
+    width: 100%;
+}
+div.bgtext div {
+    text-align: center;
+    font-size: 10em;
+    color: #ddd;
+    -webkit-transform: rotate(-45deg);
+    text-transform: uppercase;
+}
+        </style>
+    </head>
+    <body>
+        {{ if .Proforma }}
+        <div class="bgtext"><div>Proforma</div></div>
+        {{ end }}
+        <div class="rhs">
+            <div class="invoicer">
+                <ul>
+                    {{ range $i, $e := .InvoicerBilling }}
+                    {{ if eq $i 0 }}
+                    <li><b>{{ $e }}</b></li>
+                    {{ else }}
+                    <li>{{ $e }}</li>
+                    {{ end }}
+                    {{ end }}
+                    {{ if .InvoicerCompanyNumber }}
+                    <li>{{ .InvoicerCompanyNumber }}</li>
+                    {{ end }}
+                    <li><b>NIP:</b> {{ .InvoicerVAT }}</li>
+                </ul>
+            </div>
+            <div class="metadata">
+                <ul>
+                    <li><b>Numer faktury:</b> {{ .InvoiceNumber }}</li>
+                    <li><b>Data wystawienia:</b> {{ .Date.Format "2006/01/02" }}</li>
+                    <li><b>Termin płatności:</b> {{ .DueDate.Format "2006/01/02" }}</li>
+                    <li><b>IBAN:</b> {{ .IBAN }}</li>
+                    <li><b>SWIFT/BIC:</b> {{ .SWIFT }}</li>
+                </ul>
+            </div>
+        </div>
+        <div class="lhs">
+            <div class="invoicee">
+                {{ if .Proforma }}
+                <h1>Faktura Proforma</h1>
+                {{ else }}
+                <h1>Faktura VAT</h1>
+                {{ end }}
+                <h2>nr. {{ .InvoiceNumber }}</h2>
+                <ul>
+                    {{ range $i, $e := .InvoiceeBilling }}
+                    {{ if eq $i 0 }}
+                    <li><b>{{ $e }}</b></li>
+                    {{ else }}
+                    <li>{{ $e }}</li>
+                    {{ end }}
+                    {{ end }}
+                    {{ if .USCustomer }}
+                    <li>EIN: {{ .InvoiceeVAT }}</li>
+                    <li><b>(VAT zero rate)</b></li>
+                    {{ else }}
+                    <li><b>NIP:</b> {{ .InvoiceeVAT }}</li>
+                    {{ end }}
+
+                    {{ if .ReverseVAT }}
+                    <li><b>(nie podlega VAT)</b></li>
+                    {{ end }}
+                </ul>
+            </div>
+        </div>
+        <div style="clear: both; height: 1em;"></div>
+        <table class="items">
+            <tr>
+                <th style="width: 60%;">Nazwa towaru lub usługi</th>
+                <th>Cena<br />netto</th>
+                <th>Ilość</th>
+                <th>VAT (%)</th>
+                <th>Wartość<br />netto</th>
+                <th>Wartość<br />brutto</th>
+            </tr>
+            {{ range .Items }}
+            <tr>
+                <td style="text-align: left;">{{ .Title }}</td>
+                <td>{{ .UnitPrice }}</td>
+                <td>{{ .Qty }}</td>
+                <td>{{ .VATRate }}</td>
+                <td>{{ .TotalNet }}</td>
+                <td>{{ .Total }}</td>
+            </tr>
+            {{ end }}
+            <tr>
+                <td colspan="5" class="lhead">RAZEM netto</td>
+                <td>{{ .TotalNet }}</td>
+            </tr>
+            <tr>
+                <td colspan="5" class="lhead">VAT{{ if .ReverseVAT }} (nie podlega){{ end }} {{ if .USCustomer }}(nie podlega){{ end }}</td>
+                <td>{{ .VATTotal }}</td>
+            </tr>
+            <tr>
+                <td colspan="5" class="lhead"><b>RAZEM brutto</b></td>
+                <td><b>{{ .Total }}</b></td>
+            </tr>
+        </table>
+    </body>
+</html>
diff --git a/bgpwtf/speedtest/.gitignore b/bgpwtf/speedtest/.gitignore
new file mode 100644
index 0000000..3391695
--- /dev/null
+++ b/bgpwtf/speedtest/.gitignore
@@ -0,0 +1,2 @@
+srv
+*swp
diff --git a/bgpwtf/speedtest/BUILD.bazel b/bgpwtf/speedtest/BUILD.bazel
new file mode 100644
index 0000000..cc431d0
--- /dev/null
+++ b/bgpwtf/speedtest/BUILD.bazel
@@ -0,0 +1,42 @@
+load("@io_bazel_rules_docker//container:container.bzl", "container_image")
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//extras:embed_data.bzl", "go_embed_data")
+
+go_embed_data(
+    name = "static",
+    srcs = ["index.html", "speedtest.js", "speedtest_worker.js"],
+    package = "static",
+)
+
+# keep
+go_library(
+    name = "static_go",
+    srcs = [":static"],
+    importpath = "code.hackerspace.pl/hscloud/bgpwtf/speedtest/static",
+    visibility = ["//visibility:public"],
+)
+
+container_image(
+    name="latest",
+    base="@prodimage-bionic//image",
+    files = ["//bgpwtf/speedtest/backend:backend"],
+    directory = "/hscloud",
+    entrypoint = ["/hscloud/backend"],
+)
+
+genrule(
+    name = "push_latest",
+    srcs = [":latest"],
+    outs = ["version.sh"],
+    executable = True,
+    cmd = """
+        local=bazel/bgpwtf/speedtest:latest
+        tag=$$(date +%s)
+        remote=registry.k0.hswaw.net/bgpwtf/speedtest:$$tag
+
+        docker tag $$local $$remote
+        docker push $$remote
+        echo -ne "#!/bin/sh\necho Pushed $$remote\n" > $(OUTS)
+    """,
+)
+
diff --git a/bgpwtf/speedtest/LICENSE b/bgpwtf/speedtest/LICENSE
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/bgpwtf/speedtest/LICENSE
@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/bgpwtf/speedtest/README.md b/bgpwtf/speedtest/README.md
new file mode 100644
index 0000000..6364a1c
--- /dev/null
+++ b/bgpwtf/speedtest/README.md
@@ -0,0 +1,49 @@
+# HTML5 Speedtest
+
+No Flash, No Java, No Websocket, No Bullshit.
+
+This is a very lightweight Speedtest implemented in Javascript, using XMLHttpRequest and Web Workers.
+
+Forked from [adolfintel/speedtest](https://github.com/adolfintel/speedtest) to remove unnecessary features and implement Go backend for use at [bgp.wtf](http://bgp.wtf).
+
+## Compatibility
+All modern browsers are supported: IE11, latest Edge, latest Chrome, latest Firefox, latest Safari.  
+Works with mobile versions too.
+
+## Features
+* Download
+* Upload
+* Ping
+* Jitter
+
+## Server requirements
+* A machine that can run Go code.
+
+## Installation
+
+    go build -o srv github.com/q3k/speedtest/backend
+    ./srv
+
+## Donate
+
+Support the original developer:
+[![Donate with Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/fdossena/donate)  
+[Donate with PayPal](https://www.paypal.me/sineisochronic)  
+
+## License
+Copyright (C) 2016-2019 Federico Dossena
+
+Copyright (C) 2019 Serge Bazanski
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this program.  If not, see <https://www.gnu.org/licenses/lgpl>.
diff --git a/bgpwtf/speedtest/backend/BUILD.bazel b/bgpwtf/speedtest/backend/BUILD.bazel
new file mode 100644
index 0000000..54ea2f6
--- /dev/null
+++ b/bgpwtf/speedtest/backend/BUILD.bazel
@@ -0,0 +1,24 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
+
+go_library(
+    name = "go_default_library",
+    srcs = ["main.go"],
+    importpath = "code.hackerspace.pl/hscloud/bgpwtf/speedtest/backend",
+    visibility = ["//visibility:private"],
+    deps = [
+        "@com_github_golang_glog//:go_default_library",
+        "//bgpwtf/speedtest:static_go", # keep
+    ],
+)
+
+go_binary(
+    name = "backend",
+    embed = [":go_default_library"],
+    visibility = ["//visibility:public"],
+)
+
+go_test(
+    name = "go_default_test",
+    srcs = ["main_test.go"],
+    embed = [":go_default_library"],
+)
diff --git a/bgpwtf/speedtest/backend/main.go b/bgpwtf/speedtest/backend/main.go
new file mode 100644
index 0000000..7d4aece
--- /dev/null
+++ b/bgpwtf/speedtest/backend/main.go
@@ -0,0 +1,148 @@
+package main
+
+// Copyright 2019 Serge Bazanski
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import (
+	"crypto/rand"
+	"encoding/json"
+	"flag"
+	"io"
+	"io/ioutil"
+	"net"
+	"net/http"
+	"strconv"
+	"strings"
+
+	"github.com/golang/glog"
+
+	"code.hackerspace.pl/hscloud/bgpwtf/speedtest/static"
+)
+
+var (
+	flagBind            string
+	flagUseForwardedFor bool
+)
+
+func cors(w http.ResponseWriter) {
+	w.Header().Add("Access-Control-Allow-Origin", "*")
+	w.Header().Add("Access-Control-Allow-Methods", "GET, POST")
+}
+
+func noCache(w http.ResponseWriter) {
+	w.Header().Add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, s-maxage=0")
+	w.Header().Add("Cache-Control", " post-check=0, pre-check=0")
+	w.Header().Add("Pragma", "no-cache")
+}
+
+func remoteIP(r *http.Request) net.IP {
+	remote := strings.TrimSpace(r.RemoteAddr)
+	if flagUseForwardedFor {
+		remote = strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
+	}
+
+	if remote == "" {
+		return nil
+	}
+
+	if strings.HasPrefix(remote, "[") {
+		// Looks like a [::1] v6 address
+		inner := strings.Split(strings.Split(remote, "[")[1], "]")[0]
+		return net.ParseIP(inner)
+	}
+
+	if strings.Count(remote, ":") == 1 {
+		// Looks like a :4321 port suffix
+		inner := strings.Split(remote, ":")[0]
+		return net.ParseIP(inner)
+	}
+
+	return net.ParseIP(remote)
+}
+
+func init() {
+	flag.Set("logtostderr", "true")
+}
+
+func main() {
+	flag.StringVar(&flagBind, "bind", "0.0.0.0:8080", "Address at which to serve HTTP requests")
+	flag.BoolVar(&flagUseForwardedFor, "use_forwarded_for", false, "Honor X-Forwarded-For headers to detect user IP")
+	flag.Parse()
+	http.HandleFunc("/empty", func(w http.ResponseWriter, r *http.Request) {
+		cors(w)
+		noCache(w)
+		w.Header().Add("Connection", "keep-alive")
+		w.WriteHeader(http.StatusOK)
+		io.Copy(ioutil.Discard, r.Body)
+	})
+	http.HandleFunc("/garbage", func(w http.ResponseWriter, r *http.Request) {
+		cors(w)
+		w.Header().Add("Content-Description", "File Tranfer")
+		w.Header().Add("Content-Type", "application/octet-stream")
+		w.Header().Add("Content-Disposition", "attachment; filename=random.dat")
+		w.Header().Add("Content-Transfer-Encoding", "binary")
+		noCache(w)
+		w.WriteHeader(http.StatusOK)
+
+		chunks := 4
+		if val, err := strconv.Atoi(r.Header.Get("ckSize")); err == nil {
+			if val > 0 && val <= 1024 {
+				chunks = val
+			}
+		}
+
+		chunk := make([]byte, 1024*1024)
+		rand.Read(chunk)
+
+		for i := 0; i < chunks; i += 1 {
+			w.Write(chunk)
+		}
+	})
+	http.HandleFunc("/ip", func(w http.ResponseWriter, r *http.Request) {
+		cors(w)
+		noCache(w)
+
+		res := struct {
+			ProcessedString string `json:processedString`
+			RawISPInfo      string `json:rawIspInfo`
+		}{
+			ProcessedString: "",
+			RawISPInfo:      "",
+		}
+
+		ip := remoteIP(r)
+		if ip != nil {
+			res.ProcessedString = ip.String()
+		}
+
+		w.Header().Set("Content-Type", "application/json")
+
+		json.NewEncoder(w).Encode(res)
+	})
+	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+		w.Write(static.Data["bgpwtf/speedtest/index.html"])
+	})
+	http.HandleFunc("/speedtest.js", func(w http.ResponseWriter, r *http.Request) {
+		w.Write(static.Data["bgpwtf/speedtest/speedtest.js"])
+	})
+	http.HandleFunc("/speedtest_worker.js", func(w http.ResponseWriter, r *http.Request) {
+		w.Write(static.Data["bgpwtf/speedtest/speedtest_worker.js"])
+	})
+
+	glog.Infof("Starting up at %v", flagBind)
+	err := http.ListenAndServe(flagBind, nil)
+	if err != nil {
+		glog.Exit(err)
+	}
+}
diff --git a/bgpwtf/speedtest/backend/main_test.go b/bgpwtf/speedtest/backend/main_test.go
new file mode 100644
index 0000000..51bdfb4
--- /dev/null
+++ b/bgpwtf/speedtest/backend/main_test.go
@@ -0,0 +1,50 @@
+package main
+
+// Copyright 2019 Serge Bazanski
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import (
+	"net/http"
+	"testing"
+)
+
+func TestRemoteIP(t *testing.T) {
+	cases := []struct {
+		in  string
+		out string
+	}{
+		{"1.2.3.4", "1.2.3.4"},
+		{" 1.2.3.4	", "1.2.3.4"},
+		{"1.2.3.4.5", ""},
+		{"1.2.3.4:8080", "1.2.3.4"},
+		{"fe80::2", "fe80::2"},
+		{"[fe80::2]:3213", "fe80::2"},
+		{"fe80::2:43214", ""},
+	}
+
+	for i, c := range cases {
+		r := http.Request{
+			RemoteAddr: c.in,
+		}
+		res := remoteIP(&r)
+		got := ""
+		if res != nil {
+			got = res.String()
+		}
+
+		if c.out != got {
+			t.Errorf("Test case %d: got %q, want %q", i, got, c.out)
+		}
+	}
+}
diff --git a/bgpwtf/speedtest/index.html b/bgpwtf/speedtest/index.html
new file mode 100644
index 0000000..b634e54
--- /dev/null
+++ b/bgpwtf/speedtest/index.html
@@ -0,0 +1,168 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <title>bgp.wtf</title>
+        <style type="text/css">
+            body {
+                margin: 80px auto;
+                line-height: 1.6;
+                font-size: 18px;
+                max-width: 650px;
+                color: #444;
+                background-color: #aaa;
+                padding: 0 10px;
+                font-family: helvetica, arial, sans-serif;
+            }
+            a {
+                color: #444;
+                font-weight: 600;
+                text-decoration: none;
+            }
+            a:hover {
+                text-decoration: underline;
+            }
+
+            span.snippet {
+                font-family: system, courier new, serif;
+            }
+
+            div.container {
+                background-color: #f8f8f8;
+                padding: 10px 20px 10px 20px;
+                box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
+                margin-bottom: 40px;
+            }
+
+            div.container h1, h2, h3 {
+                margin: 0;
+                color: #333;
+            }
+
+            div.splitContainer {
+                display: flex;
+                flex-direction: row;
+                flex-wrap: wrap;
+            }
+
+            div.split {
+                flex-grow: 1;
+                background-color: #f8f8f8;
+                box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
+                position: relative;
+                padding: 10px 20px 10px 20px;
+                z-index: 1;
+            }
+
+            div.background {
+                position: absolute;
+                top: 0;
+                left: 0;
+                right: 0;
+                bottom: 100%;
+                z-index: -1;
+                background-color: #e8f8e8;
+                -webkit-transition: bottom 0.5s ease-in, top 0.5s ease-in;
+            }
+
+            a.button {
+                border-radius: 2px;
+                cursor: pointer;
+                font-size: 11px;
+                font-weight: bold;
+                text-align: center;
+                white-space: nowrap;
+                height: 27px;
+                line-height: 27px;
+                min-width: 54px;
+                outline: 0;
+                padding: 0 8px;
+                text-shadow: 0 1px rgba(0,0,0,0.1);
+                background-image: -webkit-linear-gradient(top,#f5f5f5,#f1f1f1);
+                background-image: -moz-linear-gradient(top,#f5f5f5,#f1f1f1);
+                background-image: linear-gradient(top,#f5f5f5,#f1f1f1);
+                color: #666;
+                border: 1px solid rgba(0,0,0,0.1);
+                display: inline-block;
+                text-decoration: none;
+            }
+            a.button:hover {
+                border: 1px solid #c6c6c6;
+                color: #333;
+                background-image: -webkit-linear-gradient(top, #f8f8f8, #f1f1f1);
+                background-image: -moz-linear-gradient(top, #f8f8f8, #f1f1f1);
+                background-image: linear-gradient(top, #f8f8f8, #f1f1f1);
+            }
+            a.red {
+                background-image: -webkit-linear-gradient(top,#dd4b39,#d14836);
+                background-image: -moz-linear-gradient(top,#dd4b39,#d14836);
+                background-image: linear-gradient(top,#dd4b39,#d14836);
+                color: #fff;
+                border: 1px solid transparent;
+                text-transform: uppercase;
+            }
+            a.red:hover {
+                border: 1px solid #b0281a;
+                box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
+                background-image: -webkit-linear-gradient(top, #dd4b39, #c53727);
+                background-image: -moz-linear-gradient(top, #dd4b39, #c53727);
+                background-image: linear-gradient(top, #dd4b39, #c53727);
+                color: #fff;
+            }
+        </style>
+    </head>
+    <body>
+        <div class="splitContainer">
+            <div class="split" style="width: 10rem; margin: 0.5rem;">
+                <div class="background" id="dlBackground"></div>
+                <h2>Download</h2>
+                <p id="download"><i>not started...</i></p>
+            </div>
+
+            <div class="split" style="width: 10rem; margin: 0.5rem;">
+                <div class="background" id="ulBackground" style="top: 100%; bottom: 0;"></div>
+                <h2>Upload</h2>
+                <p id="upload"><i>not started...</i></p>
+            </div>
+        </div>
+
+        <div class="container" style="margin: 0.5rem;">
+            <p>
+                <b>Server Location</b>: Warsaw, Poland (waw.bgp.wtf)<br />
+                <b>Latency</b>: <span id="ping"><i>not started...</i></span><br />
+                <a class="button red" style="margin-top: 20px;" onclick="startTest();">Start test</a>
+            </p>
+        </div>
+
+        <script type="text/javascript" src="speedtest.js"></script>
+        <script type="text/javascript">
+            const s = new Speedtest();
+            s.onupdate = function (data) { // when status is received, put the values in the appropriate fields
+                if (data.testState >= 1) {
+                    if (data.dlStatus) {
+                        document.getElementById('dlBackground').style.bottom = ((1-data.dlProgress) * 100 + "%");
+                        document.getElementById('download').textContent = data.dlStatus + ' Mbit/s';
+                    }
+                    else
+                        document.getElementById('download').innerHTML = '<i>starting...</i>';
+                }
+                if (data.testState >= 2)
+                    document.getElementById('ping').textContent = data.pingStatus + ' ms, ' + data.jitterStatus + ' ms jitter'
+                if (data.testState >= 3) {
+                    if (data.ulStatus) {
+                        document.getElementById('ulBackground').style.top = ((1-data.ulProgress) * 100 + "%");
+                        document.getElementById('upload').textContent = data.ulStatus + ' Mbit/s'
+                    } else
+                        document.getElementById('upload').innerHTML = '<i>starting...</i>';
+                }
+            }
+
+             var startTest = () => {
+                console.log("Starting test...");
+                document.getElementById('dlBackground').style.bottom = "100%";
+                document.getElementById('ulBackground').style.top = "100%";
+                s.start();
+            };
+        </script>
+    </body>
+</html>
diff --git a/bgpwtf/speedtest/kube/prod.jsonnet b/bgpwtf/speedtest/kube/prod.jsonnet
new file mode 100644
index 0000000..fc6e083
--- /dev/null
+++ b/bgpwtf/speedtest/kube/prod.jsonnet
@@ -0,0 +1,86 @@
+local kube = import '../../../../kube/kube.libsonnet';
+
+{
+    local speedtest = self,
+    local cfg = speedtest.cfg,
+    cfg:: {
+        namespace: "speedtest",
+        appName: "speedtest",
+        domain: "speedtest.hackerspace.pl",
+
+        tag: "1563032542",
+        image: "registry.k0.hswaw.net/bgpwtf/speedtest:" + cfg.tag,
+
+        resources: {
+            requests: {
+                cpu: "25m",
+                memory: "50Mi",
+            },
+            limits: {
+                cpu: "100m",
+                memory: "200Mi",
+            },
+        },
+    },
+
+    namespace: kube.Namespace(cfg.namespace),
+
+    metadata(component):: {
+        namespace: cfg.namespace,
+        labels: {
+            "app.kubernetes.io/name": cfg.appName,
+            "app.kubernetes.io/managed-by": "kubecfg",
+            "app.kubernetes.io/component": component,
+        },
+    },
+
+    deployment: kube.Deployment("backend") {
+        metadata+: speedtest.metadata("backend"),
+        spec+: {
+            replicas: 1,
+            template+: {
+                 spec+: {
+                     containers_: {
+                         nginx: kube.Container("backend") {
+                             image: cfg.image,
+                             ports_: {
+                                 http: { containerPort: 8080 },
+                             },
+                             resources: cfg.resources,
+                         },
+                     },
+                 },
+            },
+        },
+    },
+
+    svc: kube.Service("public") {
+        metadata+: speedtest.metadata("public"),
+        target_pod:: speedtest.deployment.spec.template,
+    },
+
+    ingress: kube.Ingress("public") {
+        metadata+: speedtest.metadata("public") {
+            annotations+: {
+                "kubernetes.io/tls-acme": "true",
+                "certmanager.k8s.io/cluster-issuer": "letsencrypt-prod",
+                "nginx.ingress.kubernetes.io/proxy-body-size": "0",
+            },
+        },
+        spec+: {
+            tls: [
+                { hosts: [cfg.domain], secretName: "public-tls"}
+            ],
+            rules: [
+                {
+                    host: cfg.domain,
+                    http: {
+                        paths: [
+                            { path: "/", backend: speedtest.svc.name_port },
+                        ],
+                    },
+                },
+            ],
+        },
+    },
+}
diff --git a/bgpwtf/speedtest/speedtest.js b/bgpwtf/speedtest/speedtest.js
new file mode 100644
index 0000000..2c4dcaf
--- /dev/null
+++ b/bgpwtf/speedtest/speedtest.js
@@ -0,0 +1,342 @@
+/*
+	HTML5 Speedtest - Main
+	by Federico Dossena
+	https://github.com/adolfintel/speedtest/
+	GNU LGPLv3 License
+*/
+
+/*
+   This is the main interface between your webpage and the speedtest.
+   It hides the speedtest web worker to the page, and provides many convenient functions to control the test.
+   
+   The best way to learn how to use this is to look at the basic example, but here's some documentation.
+  
+   To initialize the test, create a new Speedtest object:
+    var s=new Speedtest();
+   Now you can think of this as a finite state machine. These are the states (use getState() to see them):
+   - 0: here you can change the speedtest settings (such as test duration) with the setParameter("parameter",value) method. From here you can either start the test using start() (goes to state 3) or you can add multiple test points using addTestPoint(server) or addTestPoints(serverList) (goes to state 1). Additionally, this is the perfect moment to set up callbacks for the onupdate(data) and onend(aborted) events.
+   - 1: here you can add test points. You only need to do this if you want to use multiple test points.
+        A server is defined as an object like this:
+        {
+            name: "User friendly name",
+            server:"http://yourBackend.com/",     <---- URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
+            dlURL:"garbage.php"    <----- path to garbage.php or its replacement on the server
+            ulURL:"empty.php"    <----- path to empty.php or its replacement on the server
+            pingURL:"empty.php"    <----- path to empty.php or its replacement on the server. This is used to ping the server by this selector
+            getIpURL:"getIP.php"    <----- path to getIP.php or its replacement on the server
+        }
+        While in state 1, you can only add test points, you cannot change the test settings. When you're done, use selectServer(callback) to select the test point with the lowest ping. This is asynchronous, when it's done, it will call your callback function and move to state 2. Calling setSelectedServer(server) will manually select a server and move to state 2.
+    - 2: test point selected, ready to start the test. Use start() to begin, this will move to state 3
+    - 3: test running. Here, your onupdate event calback will be called periodically, with data coming from the worker about speed and progress. A data object will be passed to your onupdate function, with the following items:
+            - dlStatus: download speed in mbps
+            - ulStatus: upload speed in mbps
+            - pingStatus: ping in ms
+            - jitterStatus: jitter in ms
+            - dlProgress: progress of the download test as a float 0-1
+            - ulProgress: progress of the upload test as a float 0-1
+            - pingProgress: progress of the ping/jitter test as a float 0-1
+            - testState: state of the test (-1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=aborted)
+            - clientIp: IP address of the client performing the test (and optionally ISP and distance) 
+        At the end of the test, the onend function will be called, with a boolean specifying whether the test was aborted or if it ended normally.
+        The test can be aborted at any time with abort().
+        At the end of the test, it will move to state 4
+    - 4: test finished. You can run it again by calling start() if you want.
+ */
+
+function Speedtest() {
+  this._serverList = []; //when using multiple points of test, this is a list of test points
+  this._selectedServer = null; //when using multiple points of test, this is the selected server
+  this._settings = {}; //settings for the speedtest worker
+  this._state = 0; //0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
+  console.log(
+    "HTML5 Speedtest by Federico Dossena v5.0 - https://github.com/adolfintel/speedtest"
+  );
+}
+
+Speedtest.prototype = {
+  constructor: Speedtest,
+  /**
+   * Returns the state of the test: 0=adding settings, 1=adding servers, 2=server selection done, 3=test running, 4=done
+   */
+  getState: function() {
+    return this._state;
+  },
+  /**
+   * Change one of the test settings from their defaults.
+   * - parameter: string with the name of the parameter that you want to set
+   * - value: new value for the parameter
+   *
+   * Invalid values or nonexistant parameters will be ignored by the speedtest worker.
+   */
+  setParameter: function(parameter, value) {
+    if (this._state != 0)
+      throw "You cannot change the test settings after adding server or starting the test";
+    this._settings[parameter] = value;
+  },
+  /**
+   * Used internally to check if a server object contains all the required elements.
+   * Also fixes the server URL if needed.
+   */
+  _checkServerDefinition: function(server) {
+    try {
+      if (typeof server.name !== "string")
+        throw "Name string missing from server definition (name)";
+      if (typeof server.server !== "string")
+        throw "Server address string missing from server definition (server)";
+      if (server.server.charAt(server.server.length - 1) != "/")
+        server.server += "/";
+      if (server.server.indexOf("//") == 0)
+        server.server = location.protocol + server.server;
+      if (typeof server.dlURL !== "string")
+        throw "Download URL string missing from server definition (dlURL)";
+      if (typeof server.ulURL !== "string")
+        throw "Upload URL string missing from server definition (ulURL)";
+      if (typeof server.pingURL !== "string")
+        throw "Ping URL string missing from server definition (pingURL)";
+      if (typeof server.getIpURL !== "string")
+        throw "GetIP URL string missing from server definition (getIpURL)";
+    } catch (e) {
+      throw "Invalid server definition";
+    }
+  },
+  /**
+   * Add a test point (multiple points of test)
+   * server: the server to be added as an object. Must contain the following elements:
+   *  {
+   *       name: "User friendly name",
+   *       server:"http://yourBackend.com/",   URL to your server. You can specify http:// or https://. If your server supports both, just write // without the protocol
+   *       dlURL:"garbage.php"   path to garbage.php or its replacement on the server
+   *       ulURL:"empty.php"   path to empty.php or its replacement on the server
+   *       pingURL:"empty.php"   path to empty.php or its replacement on the server. This is used to ping the server by this selector
+   *       getIpURL:"getIP.php"   path to getIP.php or its replacement on the server
+   *   }
+   */
+  addTestPoint: function(server) {
+    this._checkServerDefinition(server);
+    if (this._state == 0) this._state = 1;
+    if (this._state != 1) throw "You can't add a server after server selection";
+    this._settings.mpot = true;
+    this._serverList.push(server);
+  },
+  /**
+   * Same as addTestPoint, but you can pass an array of servers
+   */
+  addTestPoints: function(list) {
+    for (var i = 0; i < list.length; i++) this.addTestPoint(list[i]);
+  },
+  /**
+   * Returns the selected server (multiple points of test)
+   */
+  getSelectedServer: function() {
+    if (this._state < 2 || this._selectedServer == null)
+      throw "No server is selected";
+    return this._selectedServer;
+  },
+  /**
+   * Manually selects one of the test points (multiple points of test)
+   */
+  setSelectedServer: function(server) {
+    this._checkServerDefinition(server);
+    if (this._state == 3)
+      throw "You can't select a server while the test is running";
+    this._selectedServer = server;
+    this._state = 2;
+  },
+  /**
+   * Automatically selects a server from the list of added test points. The server with the lowest ping will be chosen. (multiple points of test)
+   * The process is asynchronous and the passed result callback function will be called when it's done, then the test can be started.
+   */
+  selectServer: function(result) {
+    if (this._state != 1) {
+      if (this._state == 0) throw "No test points added";
+      if (this._state == 2) throw "Server already selected";
+      if (this._state >= 3)
+        throw "You can't select a server while the test is running";
+    }
+    if (this._selectServerCalled) throw "selectServer already called"; else this._selectServerCalled=true;
+    /*this function goes through a list of servers. For each server, the ping is measured, then the server with the function result is called with the best server, or null if all the servers were down.
+     */
+    var select = function(serverList, result) {
+      //pings the specified URL, then calls the function result. Result will receive a parameter which is either the time it took to ping the URL, or -1 if something went wrong.
+      var PING_TIMEOUT = 2000;
+      var USE_PING_TIMEOUT = true; //will be disabled on unsupported browsers
+      if (/MSIE.(\d+\.\d+)/i.test(navigator.userAgent)) {
+        //IE11 doesn't support XHR timeout
+        USE_PING_TIMEOUT = false;
+      }
+      var ping = function(url, result) {
+        url += (url.match(/\?/) ? "&" : "?") + "cors=true";
+        var xhr = new XMLHttpRequest();
+        var t = new Date().getTime();
+        xhr.onload = function() {
+          if (xhr.responseText.length == 0) {
+            //we expect an empty response
+            var instspd = new Date().getTime() - t; //rough timing estimate
+            try {
+              //try to get more accurate timing using performance API
+              var p = performance.getEntriesByName(url);
+              p = p[p.length - 1];
+              var d = p.responseStart - p.requestStart;
+              if (d <= 0) d = p.duration;
+              if (d > 0 && d < instspd) instspd = d;
+            } catch (e) {}
+            result(instspd);
+          } else result(-1);
+        }.bind(this);
+        xhr.onerror = function() {
+          result(-1);
+        }.bind(this);
+        xhr.open("GET", url);
+        if (USE_PING_TIMEOUT) {
+          try {
+            xhr.timeout = PING_TIMEOUT;
+            xhr.ontimeout = xhr.onerror;
+          } catch (e) {}
+        }
+        xhr.send();
+      }.bind(this);
+
+      //this function repeatedly pings a server to get a good estimate of the ping. When it's done, it calls the done function without parameters. At the end of the execution, the server will have a new parameter called pingT, which is either the best ping we got from the server or -1 if something went wrong.
+      var PINGS = 3, //up to 3 pings are performed, unless the server is down...
+        SLOW_THRESHOLD = 500; //...or one of the pings is above this threshold
+      var checkServer = function(server, done) {
+        var i = 0;
+        server.pingT = -1;
+        if (server.server.indexOf(location.protocol) == -1) done();
+        else {
+          var nextPing = function() {
+            if (i++ == PINGS) {
+              done();
+              return;
+            }
+            ping(
+              server.server + server.pingURL,
+              function(t) {
+                if (t >= 0) {
+                  if (t < server.pingT || server.pingT == -1) server.pingT = t;
+                  if (t < SLOW_THRESHOLD) nextPing();
+                  else done();
+                } else done();
+              }.bind(this)
+            );
+          }.bind(this);
+          nextPing();
+        }
+      }.bind(this);
+      //check servers in list, one by one
+      var i = 0;
+      var done = function() {
+        var bestServer = null;
+        for (var i = 0; i < serverList.length; i++) {
+          if (
+            serverList[i].pingT != -1 &&
+            (bestServer == null || serverList[i].pingT < bestServer.pingT)
+          )
+            bestServer = serverList[i];
+        }
+        result(bestServer);
+      }.bind(this);
+      var nextServer = function() {
+        if (i == serverList.length) {
+          done();
+          return;
+        }
+        checkServer(serverList[i++], nextServer);
+      }.bind(this);
+      nextServer();
+    }.bind(this);
+
+    //parallel server selection
+    var CONCURRENCY = 6;
+    var serverLists = [];
+    for (var i = 0; i < CONCURRENCY; i++) {
+      serverLists[i] = [];
+    }
+    for (var i = 0; i < this._serverList.length; i++) {
+      serverLists[i % CONCURRENCY].push(this._serverList[i]);
+    }
+    var completed = 0;
+    var bestServer = null;
+    for (var i = 0; i < CONCURRENCY; i++) {
+      select(
+        serverLists[i],
+        function(server) {
+          if (server != null) {
+            if (bestServer == null || server.pingT < bestServer.pingT)
+              bestServer = server;
+          }
+          completed++;
+          if (completed == CONCURRENCY) {
+            this._selectedServer = bestServer;
+            this._state = 2;
+            if (result) result(bestServer);
+          }
+        }.bind(this)
+      );
+    }
+  },
+  /**
+   * Starts the test.
+   * During the test, the onupdate(data) callback function will be called periodically with data from the worker.
+   * At the end of the test, the onend(aborted) function will be called with a boolean telling you if the test was aborted or if it ended normally.
+   */
+  start: function() {
+    if (this._state == 3) throw "Test already running";
+    this.worker = new Worker("speedtest_worker.js?r=" + Math.random());
+    this.worker.onmessage = function(e) {
+      if (e.data === this._prevData) return;
+      else this._prevData = e.data;
+      var data = JSON.parse(e.data);
+      try {
+        if (this.onupdate) this.onupdate(data);
+      } catch (e) {
+        console.error("Speedtest onupdate event threw exception: " + e);
+      }
+      if (data.testState >= 4) {
+        try {
+          if (this.onend) this.onend(data.testState == 5);
+        } catch (e) {
+          console.error("Speedtest onend event threw exception: " + e);
+        }
+        clearInterval(this.updater);
+        this._state = 4;
+      }
+    }.bind(this);
+    this.updater = setInterval(
+      function() {
+        this.worker.postMessage("status");
+      }.bind(this),
+      200
+    );
+    if (this._state == 1)
+        throw "When using multiple points of test, you must call selectServer before starting the test";
+    if (this._state == 2) {
+      this._settings.url_dl =
+        this._selectedServer.server + this._selectedServer.dlURL;
+      this._settings.url_ul =
+        this._selectedServer.server + this._selectedServer.ulURL;
+      this._settings.url_ping =
+        this._selectedServer.server + this._selectedServer.pingURL;
+      this._settings.url_getIp =
+        this._selectedServer.server + this._selectedServer.getIpURL;
+      if (typeof this._settings.telemetry_extra !== "undefined") {
+        this._settings.telemetry_extra = JSON.stringify({
+          server: this._selectedServer.name,
+          extra: this._settings.telemetry_extra
+        });
+      } else
+        this._settings.telemetry_extra = JSON.stringify({
+          server: this._selectedServer.name
+        });
+    }
+    this._state = 3;
+    this.worker.postMessage("start " + JSON.stringify(this._settings));
+  },
+  /**
+   * Aborts the test while it's running.
+   */
+  abort: function() {
+    if (this._state < 3) throw "You cannot abort a test that's not started yet";
+    if (this._state < 4) this.worker.postMessage("abort");
+  }
+};
diff --git a/bgpwtf/speedtest/speedtest_worker.js b/bgpwtf/speedtest/speedtest_worker.js
new file mode 100644
index 0000000..4b0958a
--- /dev/null
+++ b/bgpwtf/speedtest/speedtest_worker.js
@@ -0,0 +1,726 @@
+/*
+	HTML5 Speedtest - Worker
+	by Federico Dossena
+	https://github.com/adolfintel/speedtest/
+	GNU LGPLv3 License
+*/
+
+// data reported to main thread
+var testState = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort
+var dlStatus = ""; // download speed in megabit/s with 2 decimal digits
+var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
+var pingStatus = ""; // ping in milliseconds with 2 decimal digits
+var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
+var clientIp = ""; // client's IP address as reported by getIP.php
+var dlProgress = 0; //progress of download test 0-1
+var ulProgress = 0; //progress of upload test 0-1
+var pingProgress = 0; //progress of ping+jitter test 0-1
+var testId = null; //test ID (sent back by telemetry if used, null otherwise)
+
+var log = ""; //telemetry log
+function tlog(s) {
+	if (settings.telemetry_level >= 2) {
+		log += Date.now() + ": " + s + "\n";
+	}
+}
+function tverb(s) {
+	if (settings.telemetry_level >= 3) {
+		log += Date.now() + ": " + s + "\n";
+	}
+}
+function twarn(s) {
+	if (settings.telemetry_level >= 2) {
+		log += Date.now() + " WARN: " + s + "\n";
+	}
+	console.warn(s);
+}
+
+// test settings. can be overridden by sending specific values with the start command
+var settings = {
+	mpot: false, //set to true when in MPOT mode
+	test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
+	time_ul_max: 15, // max duration of upload test in seconds
+	time_dl_max: 15, // max duration of download test in seconds
+	time_auto: true, // if set to true, tests will take less time on faster connections
+	time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
+	time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
+	count_ping: 10, // number of pings to perform in ping test
+	url_dl: "garbage", // path to a large file or garbage.php, used for download test. must be relative to this js file
+	url_ul: "empty", // path to an empty file, used for upload test. must be relative to this js file
+	url_ping: "empty", // path to an empty file, used for ping test. must be relative to this js file
+	url_getIp: "ip", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
+	getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
+	getIp_ispInfo_distance: "km", //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
+	xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
+	xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
+	xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
+	xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
+	xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
+	xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
+	garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
+	enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
+	ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
+	overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
+	useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
+	telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
+	url_telemetry: "results/telemetry.php", // path to the script that adds telemetry data to the database
+	telemetry_extra: "" //extra data that can be passed to the telemetry through the settings
+};
+
+var xhr = null; // array of currently active xhr requests
+var interval = null; // timer used in tests
+var test_pointer = 0; //pointer to the next test to run inside settings.test_order
+
+/*
+  this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
+*/
+function url_sep(url) {
+	return url.match(/\?/) ? "&" : "?";
+}
+
+/*
+	listener for commands from main thread to this worker.
+	commands:
+	-status: returns the current status as a JSON string containing testState, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
+	-abort: aborts the current test
+	-start: starts the test. optionally, settings can be passed as JSON.
+		example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
+*/
+this.addEventListener("message", function(e) {
+	var params = e.data.split(" ");
+	if (params[0] === "status") {
+		// return status
+		postMessage(
+			JSON.stringify({
+				testState: testState,
+				dlStatus: dlStatus,
+				ulStatus: ulStatus,
+				pingStatus: pingStatus,
+				clientIp: clientIp,
+				jitterStatus: jitterStatus,
+				dlProgress: dlProgress,
+				ulProgress: ulProgress,
+				pingProgress: pingProgress,
+				testId: testId
+			})
+		);
+	}
+	if (params[0] === "start" && testState === -1) {
+		// start new test
+		testState = 0;
+		try {
+			// parse settings, if present
+			var s = {};
+			try {
+				var ss = e.data.substring(5);
+				if (ss) s = JSON.parse(ss);
+			} catch (e) {
+				twarn("Error parsing custom settings JSON. Please check your syntax");
+			}
+			//copy custom settings
+			for (var key in s) {
+				if (typeof settings[key] !== "undefined") settings[key] = s[key];
+				else twarn("Unknown setting ignored: " + key);
+			}
+			// quirks for specific browsers. apply only if not overridden. more may be added in future releases
+			if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
+				var ua = navigator.userAgent;
+				if (/Firefox.(\d+\.\d+)/i.test(ua)) {
+					if (typeof s.xhr_ulMultistream === "undefined") {
+						// ff more precise with 1 upload stream
+						settings.xhr_ulMultistream = 1;
+					}
+					if (typeof s.xhr_ulMultistream === "undefined") {
+						// ff performance API sucks
+						settings.ping_allowPerformanceApi = false;
+					}
+				}
+				if (/Edge.(\d+\.\d+)/i.test(ua)) {
+					if (typeof s.xhr_dlMultistream === "undefined") {
+						// edge more precise with 3 download streams
+						settings.xhr_dlMultistream = 3;
+					}
+				}
+				if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
+					if (typeof s.xhr_dlMultistream === "undefined") {
+						// chrome more precise with 5 streams
+						settings.xhr_dlMultistream = 5;
+					}
+				}
+			}
+			if (/Edge.(\d+\.\d+)/i.test(ua)) {
+				//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
+				settings.forceIE11Workaround = true;
+			}
+			if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
+				//PS4 browser has the same bug as IE11/Edge
+				settings.forceIE11Workaround = true;
+			}
+			if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
+				//cheap af
+				//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
+				settings.xhr_ul_blob_megabytes = 4;
+			}
+			if (/^((?!chrome|android|crios|fxios).)*safari/i.test(ua)) {
+				//Safari also needs the IE11 workaround but only for the MPOT version
+				settings.forceIE11Workaround = true;
+			}
+			//telemetry_level has to be parsed and not just copied
+			if (typeof s.telemetry_level !== "undefined") settings.telemetry_level = s.telemetry_level === "basic" ? 1 : s.telemetry_level === "full" ? 2 : s.telemetry_level === "debug" ? 3 : 0; // telemetry level
+			//transform test_order to uppercase, just in case
+			settings.test_order = settings.test_order.toUpperCase();
+		} catch (e) {
+			twarn("Possible error in custom test settings. Some settings might not have been applied. Exception: " + e);
+		}
+		// run the tests
+		tverb(JSON.stringify(settings));
+		test_pointer = 0;
+		var iRun = false,
+			dRun = false,
+			uRun = false,
+			pRun = false;
+		var runNextTest = function() {
+			if (testState == 5) return;
+			if (test_pointer >= settings.test_order.length) {
+				//test is finished
+				if (settings.telemetry_level > 0)
+					sendTelemetry(function(id) {
+						testState = 4;
+						if (id != null) testId = id;
+					});
+				else testState = 4;
+				return;
+			}
+			switch (settings.test_order.charAt(test_pointer)) {
+				case "I":
+					{
+						test_pointer++;
+						if (iRun) {
+							runNextTest();
+							return;
+						} else iRun = true;
+						getIp(runNextTest);
+					}
+					break;
+				case "D":
+					{
+						test_pointer++;
+						if (dRun) {
+							runNextTest();
+							return;
+						} else dRun = true;
+						testState = 1;
+						dlTest(runNextTest);
+					}
+					break;
+				case "U":
+					{
+						test_pointer++;
+						if (uRun) {
+							runNextTest();
+							return;
+						} else uRun = true;
+						testState = 3;
+						ulTest(runNextTest);
+					}
+					break;
+				case "P":
+					{
+						test_pointer++;
+						if (pRun) {
+							runNextTest();
+							return;
+						} else pRun = true;
+						testState = 2;
+						pingTest(runNextTest);
+					}
+					break;
+				case "_":
+					{
+						test_pointer++;
+						setTimeout(runNextTest, 1000);
+					}
+					break;
+				default:
+					test_pointer++;
+			}
+		};
+		runNextTest();
+	}
+	if (params[0] === "abort") {
+		// abort command
+		tlog("manually aborted");
+		clearRequests(); // stop all xhr activity
+		runNextTest = null;
+		if (interval) clearInterval(interval); // clear timer if present
+		if (settings.telemetry_level > 1) sendTelemetry(function() {});
+		testState = 5; //set test as aborted
+		dlStatus = "";
+		ulStatus = "";
+		pingStatus = "";
+		jitterStatus = "";
+        clientIp = "";
+		dlProgress = 0;
+		ulProgress = 0;
+		pingProgress = 0;
+	}
+});
+// stops all XHR activity, aggressively
+function clearRequests() {
+	tverb("stopping pending XHRs");
+	if (xhr) {
+		for (var i = 0; i < xhr.length; i++) {
+			try {
+				xhr[i].onprogress = null;
+				xhr[i].onload = null;
+				xhr[i].onerror = null;
+			} catch (e) {}
+			try {
+				xhr[i].upload.onprogress = null;
+				xhr[i].upload.onload = null;
+				xhr[i].upload.onerror = null;
+			} catch (e) {}
+			try {
+				xhr[i].abort();
+			} catch (e) {}
+			try {
+				delete xhr[i];
+			} catch (e) {}
+		}
+		xhr = null;
+	}
+}
+// gets client's IP using url_getIp, then calls the done function
+var ipCalled = false; // used to prevent multiple accidental calls to getIp
+var ispInfo = ""; //used for telemetry
+function getIp(done) {
+	tverb("getIp");
+	if (ipCalled) return;
+	else ipCalled = true; // getIp already called?
+	var startT = new Date().getTime();
+	xhr = new XMLHttpRequest();
+	xhr.onload = function() {
+		tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
+		try {
+			var data = JSON.parse(xhr.responseText);
+			clientIp = data.processedString;
+			ispInfo = data.rawIspInfo;
+		} catch (e) {
+			clientIp = xhr.responseText;
+			ispInfo = "";
+		}
+		done();
+	};
+	xhr.onerror = function() {
+		tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
+		done();
+	};
+	xhr.open("GET", settings.url_getIp + url_sep(settings.url_getIp) + (settings.mpot ? "cors=true&" : "") + (settings.getIp_ispInfo ? "isp=true" + (settings.getIp_ispInfo_distance ? "&distance=" + settings.getIp_ispInfo_distance + "&" : "&") : "&") + "r=" + Math.random(), true);
+	xhr.send();
+}
+// download test, calls done function when it's over
+var dlCalled = false; // used to prevent multiple accidental calls to dlTest
+function dlTest(done) {
+	tverb("dlTest");
+	if (dlCalled) return;
+	else dlCalled = true; // dlTest already called?
+	var totLoaded = 0.0, // total number of loaded bytes
+		startT = new Date().getTime(), // timestamp when test was started
+		bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
+		graceTimeDone = false, //set to true after the grace time is past
+		failed = false; // set to true if a stream fails
+	xhr = [];
+	// function to create a download stream. streams are slightly delayed so that they will not end at the same time
+	var testStream = function(i, delay) {
+		setTimeout(
+			function() {
+				if (testState !== 1) return; // delayed stream ended up starting after the end of the download test
+				tverb("dl test stream started " + i + " " + delay);
+				var prevLoaded = 0; // number of bytes loaded last time onprogress was called
+				var x = new XMLHttpRequest();
+				xhr[i] = x;
+				xhr[i].onprogress = function(event) {
+					tverb("dl stream progress event " + i + " " + event.loaded);
+					if (testState !== 1) {
+						try {
+							x.abort();
+						} catch (e) {}
+					} // just in case this XHR is still running after the download test
+					// progress event, add number of new loaded bytes to totLoaded
+					var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
+					if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
+					totLoaded += loadDiff;
+					prevLoaded = event.loaded;
+				}.bind(this);
+				xhr[i].onload = function() {
+					// the large file has been loaded entirely, start again
+					tverb("dl stream finished " + i);
+					try {
+						xhr[i].abort();
+					} catch (e) {} // reset the stream data to empty ram
+					testStream(i, 0);
+				}.bind(this);
+				xhr[i].onerror = function() {
+					// error
+					tverb("dl stream failed " + i);
+					if (settings.xhr_ignoreErrors === 0) failed = true; //abort
+					try {
+						xhr[i].abort();
+					} catch (e) {}
+					delete xhr[i];
+					if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
+				}.bind(this);
+				// send xhr
+				try {
+					if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
+					else xhr[i].responseType = "arraybuffer";
+				} catch (e) {}
+				xhr[i].open("GET", settings.url_dl + url_sep(settings.url_dl) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random() + "&ckSize=" + settings.garbagePhp_chunkSize, true); // random string to prevent caching
+				xhr[i].send();
+			}.bind(this),
+			1 + delay
+		);
+	}.bind(this);
+	// open streams
+	for (var i = 0; i < settings.xhr_dlMultistream; i++) {
+		testStream(i, settings.xhr_multistreamDelay * i);
+	}
+	// every 200ms, update dlStatus
+	interval = setInterval(
+		function() {
+			tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
+			var t = new Date().getTime() - startT;
+			if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
+			if (t < 200) return;
+			if (!graceTimeDone) {
+				if (t > 1000 * settings.time_dlGraceTime) {
+					if (totLoaded > 0) {
+						// if the connection is so slow that we didn't get a single chunk yet, do not reset
+						startT = new Date().getTime();
+						bonusT = 0;
+						totLoaded = 0.0;
+					}
+					graceTimeDone = true;
+				}
+			} else {
+				var speed = totLoaded / (t / 1000.0);
+				if (settings.time_auto) {
+					//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
+					var bonus = (6.4 * speed) / 100000;
+					bonusT += bonus > 800 ? 800 : bonus;
+				}
+				//update status
+				dlStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
+				if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
+					// test is over, stop streams and timer
+					if (failed || isNaN(dlStatus)) dlStatus = "Fail";
+					clearRequests();
+					clearInterval(interval);
+					dlProgress = 1;
+					tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
+					done();
+				}
+			}
+		}.bind(this),
+		200
+	);
+}
+// upload test, calls done function whent it's over
+var ulCalled = false; // used to prevent multiple accidental calls to ulTest
+function ulTest(done) {
+	tverb("ulTest");
+	if (ulCalled) return;
+	else ulCalled = true; // ulTest already called?
+	// garbage data for upload test
+	var r = new ArrayBuffer(1048576);
+	var maxInt = Math.pow(2, 32) - 1;
+	try {
+		r = new Uint32Array(r);
+		for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
+	} catch (e) {}
+	var req = [];
+	var reqsmall = [];
+	for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
+	req = new Blob(req);
+	r = new ArrayBuffer(262144);
+	try {
+		r = new Uint32Array(r);
+		for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
+	} catch (e) {}
+	reqsmall.push(r);
+	reqsmall = new Blob(reqsmall);
+	var testFunction = function() {
+		var totLoaded = 0.0, // total number of transmitted bytes
+			startT = new Date().getTime(), // timestamp when test was started
+			bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
+			graceTimeDone = false, //set to true after the grace time is past
+			failed = false; // set to true if a stream fails
+		xhr = [];
+		// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
+		var testStream = function(i, delay) {
+			setTimeout(
+				function() {
+					if (testState !== 3) return; // delayed stream ended up starting after the end of the upload test
+					tverb("ul test stream started " + i + " " + delay);
+					var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
+					var x = new XMLHttpRequest();
+					xhr[i] = x;
+					var ie11workaround;
+					if (settings.forceIE11Workaround) ie11workaround = true;
+					else {
+						try {
+							xhr[i].upload.onprogress;
+							ie11workaround = false;
+						} catch (e) {
+							ie11workaround = true;
+						}
+					}
+					if (ie11workaround) {
+						// IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
+						xhr[i].onload = xhr[i].onerror = function() {
+							tverb("ul stream progress event (ie11wa)");
+							totLoaded += reqsmall.size;
+							testStream(i, 0);
+						};
+						xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
+						try {
+							xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
+						} catch (e) {}
+						//No Content-Type header in MPOT branch because it triggers bugs in some browsers
+						xhr[i].send(reqsmall);
+					} else {
+						// REGULAR version, no workaround
+						xhr[i].upload.onprogress = function(event) {
+							tverb("ul stream progress event " + i + " " + event.loaded);
+							if (testState !== 3) {
+								try {
+									x.abort();
+								} catch (e) {}
+							} // just in case this XHR is still running after the upload test
+							// progress event, add number of new loaded bytes to totLoaded
+							var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
+							if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
+							totLoaded += loadDiff;
+							prevLoaded = event.loaded;
+						}.bind(this);
+						xhr[i].upload.onload = function() {
+							// this stream sent all the garbage data, start again
+							tverb("ul stream finished " + i);
+							testStream(i, 0);
+						}.bind(this);
+						xhr[i].upload.onerror = function() {
+							tverb("ul stream failed " + i);
+							if (settings.xhr_ignoreErrors === 0) failed = true; //abort
+							try {
+								xhr[i].abort();
+							} catch (e) {}
+							delete xhr[i];
+							if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
+						}.bind(this);
+						// send xhr
+						xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
+						try {
+							xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
+						} catch (e) {}
+						//No Content-Type header in MPOT branch because it triggers bugs in some browsers
+						xhr[i].send(req);
+					}
+				}.bind(this),
+				1
+			);
+		}.bind(this);
+		// open streams
+		for (var i = 0; i < settings.xhr_ulMultistream; i++) {
+			testStream(i, settings.xhr_multistreamDelay * i);
+		}
+		// every 200ms, update ulStatus
+		interval = setInterval(
+			function() {
+				tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
+				var t = new Date().getTime() - startT;
+				if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
+				if (t < 200) return;
+				if (!graceTimeDone) {
+					if (t > 1000 * settings.time_ulGraceTime) {
+						if (totLoaded > 0) {
+							// if the connection is so slow that we didn't get a single chunk yet, do not reset
+							startT = new Date().getTime();
+							bonusT = 0;
+							totLoaded = 0.0;
+						}
+						graceTimeDone = true;
+					}
+				} else {
+					var speed = totLoaded / (t / 1000.0);
+					if (settings.time_auto) {
+						//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
+						var bonus = (6.4 * speed) / 100000;
+						bonusT += bonus > 800 ? 800 : bonus;
+					}
+					//update status
+					ulStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
+					if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
+						// test is over, stop streams and timer
+						if (failed || isNaN(ulStatus)) ulStatus = "Fail";
+						clearRequests();
+						clearInterval(interval);
+						ulProgress = 1;
+						tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
+						done();
+					}
+				}
+			}.bind(this),
+			200
+		);
+	}.bind(this);
+	if (settings.mpot) {
+		tverb("Sending POST request before performing upload test");
+		xhr = [];
+		xhr[0] = new XMLHttpRequest();
+		xhr[0].onload = xhr[0].onerror = function() {
+			tverb("POST request sent, starting upload test");
+			testFunction();
+		}.bind(this);
+		xhr[0].open("POST", settings.url_ul);
+		xhr[0].send();
+	} else testFunction();
+}
+// ping+jitter test, function done is called when it's over
+var ptCalled = false; // used to prevent multiple accidental calls to pingTest
+function pingTest(done) {
+	tverb("pingTest");
+	if (ptCalled) return;
+	else ptCalled = true; // pingTest already called?
+	var startT = new Date().getTime(); //when the test was started
+	var prevT = null; // last time a pong was received
+	var ping = 0.0; // current ping value
+	var jitter = 0.0; // current jitter value
+	var i = 0; // counter of pongs received
+	var prevInstspd = 0; // last ping time, used for jitter calculation
+	xhr = [];
+	// ping function
+	var doPing = function() {
+		tverb("ping");
+		pingProgress = i / settings.count_ping;
+		prevT = new Date().getTime();
+		xhr[0] = new XMLHttpRequest();
+		xhr[0].onload = function() {
+			// pong
+			tverb("pong");
+			if (i === 0) {
+				prevT = new Date().getTime(); // first pong
+			} else {
+				var instspd = new Date().getTime() - prevT;
+				if (settings.ping_allowPerformanceApi) {
+					try {
+						//try to get accurate performance timing using performance api
+						var p = performance.getEntries();
+						p = p[p.length - 1];
+						var d = p.responseStart - p.requestStart;
+						if (d <= 0) d = p.duration;
+						if (d > 0 && d < instspd) instspd = d;
+					} catch (e) {
+						//if not possible, keep the estimate
+						tverb("Performance API not supported, using estimate");
+					}
+				}
+				//noticed that some browsers randomly have 0ms ping
+				if (instspd < 1) instspd = prevInstspd;
+				if (instspd < 1) instspd = 1;
+				var instjitter = Math.abs(instspd - prevInstspd);
+				if (i === 1) ping = instspd;
+				/* first ping, can't tell jitter yet*/ else {
+					ping = instspd < ping ? instspd : ping * 0.8 + instspd * 0.2; // update ping, weighted average. if the instant ping is lower than the current average, it is set to that value instead of averaging
+					if (i === 2) jitter = instjitter;
+					//discard the first jitter measurement because it might be much higher than it should be
+					else jitter = instjitter > jitter ? jitter * 0.3 + instjitter * 0.7 : jitter * 0.8 + instjitter * 0.2; // update jitter, weighted average. spikes in ping values are given more weight.
+				}
+				prevInstspd = instspd;
+			}
+			pingStatus = ping.toFixed(2);
+			jitterStatus = jitter.toFixed(2);
+			i++;
+			tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
+			if (i < settings.count_ping) doPing();
+			else {
+				// more pings to do?
+				pingProgress = 1;
+				tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
+				done();
+			}
+		}.bind(this);
+		xhr[0].onerror = function() {
+			// a ping failed, cancel test
+			tverb("ping failed");
+			if (settings.xhr_ignoreErrors === 0) {
+				//abort
+				pingStatus = "Fail";
+				jitterStatus = "Fail";
+				clearRequests();
+				tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
+				pingProgress = 1;
+				done();
+			}
+			if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
+			if (settings.xhr_ignoreErrors === 2) {
+				//ignore failed ping
+				i++;
+				if (i < settings.count_ping) doPing();
+				else {
+					// more pings to do?
+					pingProgress = 1;
+					tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
+					done();
+				}
+			}
+		}.bind(this);
+		// send xhr
+		xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true); // random string to prevent caching
+		xhr[0].send();
+	}.bind(this);
+	doPing(); // start first ping
+}
+// telemetry
+function sendTelemetry(done) {
+	if (settings.telemetry_level < 1) return;
+	xhr = new XMLHttpRequest();
+	xhr.onload = function() {
+		try {
+			var parts = xhr.responseText.split(" ");
+			if (parts[0] == "id") {
+				try {
+					var id = parts[1];
+					done(id);
+				} catch (e) {
+					done(null);
+				}
+			} else done(null);
+		} catch (e) {
+			done(null);
+		}
+	};
+	xhr.onerror = function() {
+		console.log("TELEMETRY ERROR " + xhr.status);
+		done(null);
+	};
+	xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + (settings.mpot ? "cors=true&" : "") + "r=" + Math.random(), true);
+	var telemetryIspInfo = {
+		processedString: clientIp,
+		rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
+	};
+	try {
+		var fd = new FormData();
+		fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
+		fd.append("dl", dlStatus);
+		fd.append("ul", ulStatus);
+		fd.append("ping", pingStatus);
+		fd.append("jitter", jitterStatus);
+		fd.append("log", settings.telemetry_level > 1 ? log : "");
+		fd.append("extra", settings.telemetry_extra);
+		xhr.send(fd);
+	} catch (ex) {
+		var postData = "extra=" + encodeURIComponent(settings.telemetry_extra) + "&ispinfo=" + encodeURIComponent(JSON.stringify(telemetryIspInfo)) + "&dl=" + encodeURIComponent(dlStatus) + "&ul=" + encodeURIComponent(ulStatus) + "&ping=" + encodeURIComponent(pingStatus) + "&jitter=" + encodeURIComponent(jitterStatus) + "&log=" + encodeURIComponent(settings.telemetry_level > 1 ? log : "");
+		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+		xhr.send(postData);
+	}
+}