github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/cmd/geph-binder/main.go (about)

     1  package main
     2  
     3  import (
     4  	"database/sql"
     5  	"log"
     6  	"net"
     7  	"net/http"
     8  	"strings"
     9  	"time"
    10  
    11  	statsd "github.com/etsy/statsd/examples/go"
    12  	"github.com/gorilla/mux"
    13  	_ "github.com/lib/pq"
    14  )
    15  
    16  func rotateTickets() {
    17  	for {
    18  		endOfDay := time.Now().Truncate(time.Hour * 24).Add(time.Hour * 24)
    19  		log.Println("rotateTickets() sleeping until", endOfDay)
    20  		time.Sleep(time.Until(endOfDay))
    21  		log.Println("rotateTickets() actually rotating!")
    22  		go func() {
    23  			tx, err := pgDB.Begin()
    24  			if err != nil {
    25  				log.Println(err)
    26  				return
    27  			}
    28  			defer tx.Rollback()
    29  			tx.Exec("delete from secrets where key = $1 or key = $2",
    30  				"ticket-id-free", "ticket-id-paid")
    31  			tx.Commit()
    32  		}()
    33  	}
    34  }
    35  
    36  var statClient *statsd.StatsdClient
    37  
    38  func countUserAgent(req *http.Request) {
    39  	statClient.Increment("binderUA." + strings.ReplaceAll(req.Header.Get("user-agent"), ".", "-"))
    40  }
    41  
    42  func main() {
    43  	z, e := net.ResolveUDPAddr("udp", "c2.geph.io:8125")
    44  	if e != nil {
    45  		panic(e)
    46  	}
    47  	statClient = statsd.New(z.IP.String(), z.Port)
    48  	var err error
    49  	pgDB, err = sql.Open("postgres",
    50  		"postgres://postgres:postgres@localhost/postgres?sslmode=disable")
    51  	if err != nil {
    52  		log.Fatal("cannot connect to database:", err)
    53  	}
    54  	pgDB.SetMaxOpenConns(50)
    55  	sk, err := getMasterIdentity()
    56  	if err != nil {
    57  		log.Fatal("cannot obtain master identity:", err)
    58  	}
    59  	go rotateTickets()
    60  	log.Printf("Geph2 binder started")
    61  	log.Printf("MPK      = %x", sk.Public())
    62  
    63  	r := mux.NewRouter()
    64  	r.HandleFunc("/get-ticket", handleGetTicket)
    65  	r.HandleFunc("/get-tier", handleGetTier)
    66  	r.HandleFunc("/get-ticket-key", handleGetTicketKey)
    67  	r.HandleFunc("/redeem-ticket", handleRedeemTicket)
    68  	r.HandleFunc("/add-bridge", handleAddBridge)
    69  	r.HandleFunc("/get-bridges", handleGetBridges)
    70  	r.HandleFunc("/client-info", handleClientInfo)
    71  	r.HandleFunc("/captcha", handleCaptcha)
    72  	r.HandleFunc("/register", handleRegister)
    73  	r.HandleFunc("/warpfronts", handleGetWarpfronts)
    74  	//r.HandleFunc("/cryptrr", handleCryptrr)
    75  	if err := http.ListenAndServe(":9080", r); err != nil {
    76  		panic(err)
    77  	}
    78  }