2017-01-18 17:02:44 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
|
|
|
|
|
|
|
"git.xeserv.us/xena/route/routerpc"
|
2017-01-20 00:28:38 +00:00
|
|
|
"git.xeserv.us/xena/route/utils"
|
2017-01-18 17:02:44 +00:00
|
|
|
r "github.com/GoRethink/gorethink"
|
|
|
|
)
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// DB is the high level wrapper to the datastore.
|
2017-01-18 17:02:44 +00:00
|
|
|
type DB struct {
|
|
|
|
s *r.Session
|
|
|
|
}
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// New takes a rethinkdb host and databasea and sets up a connection.
|
2017-01-18 17:02:44 +00:00
|
|
|
func New(host, database string) (*DB, error) {
|
|
|
|
session, err := r.Connect(r.ConnectOpts{
|
|
|
|
Address: host,
|
|
|
|
Database: database,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
db := &DB{
|
|
|
|
s: session,
|
|
|
|
}
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var tables = []string{
|
|
|
|
"certs",
|
|
|
|
"routes",
|
|
|
|
}
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// Route is a single route object serialized to rethinkdb.
|
2017-01-18 17:02:44 +00:00
|
|
|
type Route struct {
|
|
|
|
ID string `gorethink:"id,omitempty"`
|
|
|
|
Hostname string `gorethink:"hostname"`
|
|
|
|
OnionHostname string `gorethink:"onionhostname"`
|
|
|
|
Token string `gorethink:"token"`
|
|
|
|
OnionKey []byte `gorethink:"onionKey"` // PEM-encoded
|
|
|
|
}
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// SaveRoute adds the route to the database.
|
2017-01-18 17:02:44 +00:00
|
|
|
func (db *DB) SaveRoute(resp *routerpc.AddHostResponse) error {
|
2017-01-20 00:28:38 +00:00
|
|
|
bytes := utils.RSAPrivateKeyToPem(resp.PrivKey.(*rsa.PrivateKey))
|
2017-01-18 17:02:44 +00:00
|
|
|
|
|
|
|
rt := &Route{
|
|
|
|
Hostname: resp.Hostname,
|
|
|
|
OnionHostname: resp.OnionHostname,
|
|
|
|
Token: resp.Token,
|
|
|
|
OnionKey: bytes,
|
|
|
|
}
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// TODO: check if OnionHostname or Hostname actually exists in
|
|
|
|
// the database. RethinkDB doesn't support unique secondary indexes.
|
|
|
|
|
2017-01-18 17:02:44 +00:00
|
|
|
_, err := r.Table("routes").Insert(rt).RunWrite(db.s)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-01-20 00:28:38 +00:00
|
|
|
// GetAllRoutes fetches all of the route entries from the database
|
|
|
|
// and returns them. This is intended for the startup process or
|
|
|
|
// admin tooling.
|
2017-01-18 17:02:44 +00:00
|
|
|
func (db *DB) GetAllRoutes() ([]Route, error) {
|
|
|
|
rows, err := r.Table("routes").Run(db.s)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var routes []Route
|
|
|
|
err = rows.All(&routes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return routes, nil
|
|
|
|
}
|