Esempio n. 1
0
func (s *XLSuite) TestBadLengths(c *C) {

	datum, err := xi.New(nil) // generates random NodeID

	rng := xr.MakeSimpleRNG()
	ndx := uint32(rng.Intn(256 * 256 * 256))
	okData := make([]byte, 256+rng.Intn(3))

	// verify nil datum causes error
	nilChunk, err := NewChunk(nil, ndx, okData)
	c.Assert(err, Equals, NilDatum)
	c.Assert(nilChunk, Equals, (*Chunk)(nil))

	// verify nil data causes error
	nilChunk, err = NewChunk(datum, ndx, nil)
	c.Assert(err, Equals, NilData)
	c.Assert(nilChunk, Equals, (*Chunk)(nil))

	// verify length of zero causes error
	zeroLenData := make([]byte, 0)
	lenZeroChunk, err := NewChunk(datum, ndx, zeroLenData)
	c.Assert(err, Equals, ZeroLengthChunk)
	c.Assert(lenZeroChunk, Equals, (*Chunk)(nil))

	// verify length > MAX_CHUNK_BYTES causes error
	bigData := make([]byte, MAX_CHUNK_BYTES+1+rng.Intn(3))
	tooBig, err := NewChunk(datum, ndx, bigData)
	c.Assert(err, Equals, ChunkTooLong)
	c.Assert(tooBig, Equals, (*Chunk)(nil))
}
Esempio n. 2
0
func (s *XLSuite) makeANodeID(c *C, rng *xr.PRNG) (nodeID *xi.NodeID) {
	id := s.makeAnID(c, rng)
	nodeID, err := xi.New(id)
	c.Assert(err, IsNil)
	c.Assert(nodeID, Not(IsNil))
	return
}
Esempio n. 3
0
func NewAdminClient(
	serverName string, serverID *xi.NodeID, serverEnd xt.EndPointI,
	serverCK, serverSK *rsa.PublicKey,
	clusterName string, clusterAttrs uint64,
	size, epCount uint32, e []xt.EndPointI) (
	ac *AdminClient, err error) {

	nodeID, err := xi.New(nil)
	// DEBUG
	fmt.Printf("NewAdminClient: admin ID %x\n", nodeID.Value())
	// END
	if err == nil {
		node, err := xn.NewNew("admin", nodeID, "") // name, id, lfs
		if err == nil {
			cn, err := NewMemberMaker(node,
				xcl.ATTR_ADMIN|xcl.ATTR_SOLO|xcl.ATTR_EPHEMERAL,
				serverName, serverID, serverEnd, serverCK, serverSK,
				clusterName, clusterAttrs, nil, size, epCount, e)

			if err == nil {
				// Start() fills in clusterID
				ac = &AdminClient{
					MemberMaker: *cn,
				}
				// we do NOT invoke node.OpenAcc() on adminClients
				// DEBUG
				fmt.Println("   NewAdminClient: OK exit")
				// END
			}
		}
	}
	return
}
Esempio n. 4
0
func NewUserMember(
	name, lfs string, ckPriv, skPriv *rsa.PrivateKey,
	serverName string, serverID *xi.NodeID, serverEnd xt.EndPointI,
	serverCK, serverSK *rsa.PublicKey,
	clusterName string, clusterAttrs uint64, clusterID *xi.NodeID,
	size, epCount uint32, e []xt.EndPointI) (ac *UserMember, err error) {

	var attrs uint64

	nodeID, err := xi.New(nil)
	if err == nil {
		if lfs == "" {
			attrs |= xcl.ATTR_EPHEMERAL
		}
		node, err := xn.New(name, nodeID, lfs, ckPriv, skPriv, nil, nil, nil)
		if err == nil {
			mn, err := NewMemberMaker(node,
				attrs,
				serverName, serverID, serverEnd,
				serverCK, serverSK, //  *rsa.PublicKey,
				clusterName, clusterAttrs, clusterID, size,
				epCount, e)

			if err == nil {
				// Start() fills in clusterID
				ac = &UserMember{
					MemberMaker: *mn,
				}
			}
		}
	}
	return

}
Esempio n. 5
0
// Given a node, construct a Peer with the same properties.
func NewPeerFromNode(node *Node) (p *Peer, err error) {
	if node == nil {
		err = NilNode
	} else {
		id := node.GetNodeID().Value()
		nodeID, err := xi.New(id)
		if err == nil {
			var o []xo.OverlayI
			for i := 0; i < node.SizeOverlays(); i++ {
				o = append(o, node.GetOverlay(i))
			}
			var ctors []xt.ConnectorI
			for i := 0; i < node.SizeAcceptors(); i++ {
				var ctor *xt.TcpConnector
				ep := node.GetAcceptor(i).GetEndPoint()
				ctor, err = xt.NewTcpConnector(ep)
				if err != nil {
					break
				}
				ctors = append(ctors, ctor)
			}
			if err == nil {
				p, err = NewPeer(node.GetName(), nodeID,
					node.GetCommsPublicKey(), node.GetSigPublicKey(),
					o, ctors)
			}
		}
	}
	return
}
Esempio n. 6
0
// This function generates a good-quality random NodeID (a 20-byte
// value) that is not already known to the registry and then adds
// the new NodeID to the registry's Bloom filter.
func (reg *Registry) InsertUniqueNodeID() (nodeID *xi.NodeID, err error) {

	nodeID, err = xi.New(nil)
	found, err := reg.ContainsID(nodeID)
	for err == nil && found {
		nodeID, err = xi.New(nil)
		found, err = reg.ContainsID(nodeID)
	}
	if err == nil {
		err = reg.idFilter.Insert(nodeID.Value())
	}
	// DEBUG
	reg.Logger.Printf("InsertUniqueNodeID returning %x, %v\n",
		nodeID.Value(), err)
	// END
	return
}
Esempio n. 7
0
func NewMemberInfoFromToken(token *XLRegMsg_Token) (
	m *xcl.MemberInfo, err error) {

	var (
		ck, sk *rsa.PublicKey
		ctor   xt.ConnectorI
		ctors  []xt.ConnectorI
		farEnd xt.EndPointI
		nodeID *xi.NodeID
		peer   *xn.Peer
	)
	if token == nil {
		err = NilToken
	} else {
		nodeID, err = xi.New(token.GetID())
		if err == nil {
			ck, err = xc.RSAPubKeyFromWire(token.GetCommsKey())
			if err == nil {
				sk, err = xc.RSAPubKeyFromWire(token.GetSigKey())
				if err == nil {
					attrs := token.GetAttrs()
					myEnds := token.GetMyEnds()
					for i := 0; i < len(myEnds); i++ {
						myEnd := myEnds[i]
						farEnd, err = xt.NewTcpEndPoint(myEnd)
						if err != nil {
							break
						}
						ctor, err = xt.NewTcpConnector(farEnd)
						if err != nil {
							break
						}
						ctors = append(ctors, ctor)
					}
					if err == nil {
						peer, err = xn.NewPeer(token.GetName(), nodeID,
							ck, sk, nil, ctors)
						if err == nil {
							m = &xcl.MemberInfo{
								Attrs: attrs,
								Peer:  peer,
							}
						}
					}
				}
				//if err == nil {
				//	m, err = NewMemberInfo(token.GetName(), nodeID,
				//		ck, sk, token.GetAttrs(), token.GetMyEnds())
				//}
			}
		}
	}
	return
}
Esempio n. 8
0
func (s *XLSuite) TestChunks(c *C) {
	rng := xr.MakeSimpleRNG()

	ndx := uint32(rng.Int31())
	datum, err := xi.New(nil)
	c.Assert(err, IsNil)
	dataLen := 1 + rng.Intn(256*256) // 1 .. 2^16
	data := make([]byte, dataLen)
	rng.NextBytes(data)
	ch, err := NewChunk(datum, ndx, data)
	c.Assert(err, IsNil)
	c.Assert(ch, NotNil)

	// field checks: magic, type, reserved
	c.Assert(ch.Magic(), Equals, byte(0))
	c.Assert(ch.Type(), Equals, byte(0))
	expectedReserved := make([]byte, 6)
	c.Assert(bytes.Equal(expectedReserved, ch.Reserved()), Equals, true)

	// field checks: length, index, datum (= hash of overall message)
	c.Assert(int(ch.GetDataLen()), Equals, dataLen)
	c.Assert(ch.GetIndex(), Equals, ndx)
	actualDatum := ch.GetDatum()
	c.Assert(actualDatum, NotNil)
	// DEBUG
	//fmt.Printf("actualDatum: %x\n", actualDatum)
	//fmt.Printf("datum:       %x\n", datum.Value())
	// END
	c.Assert(bytes.Equal(actualDatum, datum.Value()), Equals, true)

	// field checks: data, chunk hash
	// DEBUG
	//fmt.Printf("data:       %x\n", data)
	//fmt.Printf("from chunk: %x\n", ch.GetData())
	// END
	c.Assert(bytes.Equal(ch.GetData(), data), Equals, true)
	//d := sha3.NewKeccak256()
	d := sha1.New()
	d.Write(ch.packet[0 : len(ch.packet)-HASH_BYTES])
	hash := d.Sum(nil)
	// DEBUG
	//fmt.Printf("TestChunks:\n    hash in chunk %x\n    calculated    %x\n",
	//	ch.GetChunkHash(), hash)
	// END
	c.Assert(bytes.Equal(ch.GetChunkHash(), hash), Equals, true)
}
Esempio n. 9
0
func NewClientInfoFromToken(token *XLRegMsg_Token) (
	m *ClientInfo, err error) {

	var nodeID *xi.NodeID
	if token == nil {
		err = NilToken
	} else {
		nodeID, err = xi.New(token.GetID())
		if err == nil {
			ck, err := xc.RSAPubKeyFromWire(token.GetCommsKey())
			if err == nil {
				sk, err := xc.RSAPubKeyFromWire(token.GetSigKey())
				if err == nil {
					m, err = NewClientInfo(token.GetName(), nodeID,
						ck, sk, token.GetAttrs(), token.GetMyEnds())
				}
			}
		}
	}
	return
}
Esempio n. 10
0
func (mm *MemberMaker) CreateAndReply() (err error) {

	var response *XLRegMsg

	// Send CREATE MSG ==========================================

	op := XLRegMsg_Create
	request := &XLRegMsg{
		Op:             &op,
		ClusterName:    &mm.ClusterName,
		ClusterAttrs:   &mm.ClusterAttrs,
		ClusterMaxSize: &mm.ClusterMaxSize,
		EndPointCount:  &mm.EPCount,
	}
	// SHOULD CHECK FOR TIMEOUT
	err = mm.writeMsg(request)
	if err == nil {
		// Process CREATE REPLY -------------------------------------
		// SHOULD CHECK FOR TIMEOUT AND VERIFY THAT IT'S A CREATE REPLY
		response, err = mm.readMsg()
		if err == io.EOF {
			err = nil
		}
		if err == nil {
			op = response.GetOp()
			_ = op
			if err == nil {
				id := response.GetClusterID()
				mm.ClusterID, err = xi.New(id)
				if err == nil {
					mm.ClusterAttrs = response.GetClusterAttrs()
					mm.ClusterMaxSize = response.GetClusterMaxSize()
				}
			}
		}
	}
	return
}
Esempio n. 11
0
func NewBootstrapper(
	// properties of the prospective cluster member
	name, lfs string, ckPriv, skPriv *rsa.PrivateKey, attrs uint64,
	// reg server properties
	serverName string, serverID *xi.NodeID, serverEnd xt.EndPointI,
	serverCK, serverSK *rsa.PublicKey,
	// cluster attributes
	clusterName string, clusterAttrs uint64, clusterID *xi.NodeID,
	size, epCount uint32, e []xt.EndPointI) (bs *Bootstrapper, err error) {

	// DEBUG
	fmt.Printf("NewBootstrapper: name '%s', lfs '%s'\n", name, lfs)
	// END

	if lfs == "" {
		attrs |= xcl.ATTR_EPHEMERAL
	}
	nodeID, err := xi.New(nil) // ie, make me a NodeID
	if err == nil {
		node, err := xn.NewNew(name, nodeID, lfs)
		if err == nil {
			mn, err := NewMemberMaker(node, attrs,
				serverName, serverID, serverEnd, serverCK, serverSK,
				clusterName, clusterAttrs, clusterID, size, epCount, e)

			if err == nil {
				bs = &Bootstrapper{
					DoneCh:      make(chan error),
					MemberMaker: *mn,
				}
			}
		}
	}
	return

}
Esempio n. 12
0
func doCreateMsg(h *InHandler) {
	var err error
	defer func() {
		h.errOut = err
	}()
	// Examine incoming message -------------------------------------
	var (
		clusterID *xi.NodeID
		index     int
	)

	createMsg := h.msgIn
	clusterName := createMsg.GetClusterName()
	clusterAttrs := createMsg.GetClusterAttrs()
	clusterMaxSize := createMsg.GetClusterMaxSize()
	endPointCount := createMsg.GetEndPointCount()

	// Take appropriate action --------------------------------------

	// Determine whether the cluster exists.  If it does, we will just
	// use its existing properties.

	h.reg.mu.RLock()
	cluster, exists := h.reg.ClustersByName[clusterName]
	h.reg.mu.RUnlock()

	if exists {
		h.reg.Logger.Printf("doCreateMsg: cluster %s already exists\n", clusterName)
		clusterMaxSize = cluster.maxSize
		clusterAttrs = cluster.Attrs
		endPointCount = cluster.epCount
		if cluster.ID == nil {
			h.reg.Logger.Println("  no ID for cluster %s\n", clusterName)
			clusterID, _ = xi.New(nil)
		} else {
			clusterID, _ = xi.New(cluster.ID)
		}
		// XXX index not assigned
	} else {
		h.reg.Logger.Printf("doCreateMsg: new cluster %s\n", clusterName)
		attrs := uint64(0)
		if clusterMaxSize < MIN_CLUSTER_SIZE {
			clusterMaxSize = MIN_CLUSTER_SIZE
		} else if clusterMaxSize > MAX_CLUSTER_SIZE {
			clusterMaxSize = MAX_CLUSTER_SIZE
		}
		// Assign a quasi-random cluster ID, adding it to the registry
		clusterID, err = h.reg.InsertUniqueNodeID()
		if err == nil {
			cluster, err = NewRegCluster(clusterName, clusterID, attrs,
				clusterMaxSize, endPointCount)
			h.reg.Logger.Printf("cluster %s assigning ID %x\n",
				clusterName, clusterID.Value())
		}
		if err == nil {
			h.cluster = cluster
			index, err = h.reg.AddCluster(cluster)
			// XXX index not used
		}
	}
	_ = index // INDEX IS NOT BEING USED

	if err == nil {
		// Prepare reply to client --------------------------------------
		op := XLRegMsg_CreateReply
		id := clusterID.Value()
		h.msgOut = &XLRegMsg{
			Op:             &op,
			ClusterID:      id,
			ClusterMaxSize: &clusterMaxSize,
			ClusterAttrs:   &clusterAttrs,
			EndPointCount:  &endPointCount,
		}
		// Set exit state -----------------------------------------------
		h.exitState = CREATE_REQUEST_RCVD
	}
}
Esempio n. 13
0
func (rc *RegCluster) GetNodeID() (id *xi.NodeID) {
	id, _ = xi.New(rc.ID)
	return
}
Esempio n. 14
0
func (s *XLSuite) TestSoloMember(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_SOLO_CLIENT")
	}

	rng := xr.MakeSimpleRNG()

	// 1.  create a new ephemeral server ----------------------------
	es, err := NewEphServer()
	c.Assert(err, IsNil)
	c.Assert(es, NotNil)

	server := es.Server

	c.Assert(&server.RegNode.ckPriv.PublicKey,
		DeepEquals, server.GetCommsPublicKey())
	serverName := server.GetName()
	serverID := server.GetNodeID()
	serverEnd := server.GetEndPoint(0)
	serverCK := server.GetCommsPublicKey()
	serverSK := server.GetSigPublicKey()
	c.Assert(serverEnd, NotNil)

	// start the mock server ------------------------------
	err = es.Start()
	c.Assert(err, IsNil)

	// 2. create the solo client ------------------------------------
	name := rng.NextFileName(8)
	lfs := path.Join("tmp", name)
	found, err := xf.PathExists(lfs)
	c.Assert(err, IsNil)
	for found {
		name = rng.NextFileName(8)
		lfs = path.Join("tmp", name)
		found, err = xf.PathExists(lfs)
		c.Assert(err, IsNil)
	}

	ep, err := xt.NewTcpEndPoint("127.0.0.1:0")
	c.Assert(err, IsNil)
	e := []xt.EndPointI{ep}

	nodeID, err := xi.New(nil)
	c.Assert(err, IsNil)

	node, err := xn.NewNew(name, nodeID, lfs)
	c.Assert(err, IsNil)

	sc, err := NewSoloMember(node, serverName, serverID, serverEnd,
		serverCK, serverSK, e)
	c.Assert(err, IsNil)
	c.Assert(sc, NotNil)

	// 3. run the client
	sc.Start()
	err = <-sc.DoneCh

	// 4.  verify that the client LFS exists and is correct ---------
	found, err = xf.PathExists(lfs)
	c.Assert(err, IsNil)
	c.Assert(found, Equals, true)

	// 5.  shut down the client -------------------------------------
	sc.CloseAcc() // should close any acceptors

	// 6.  stop the server, closing its acceptor --------------------
	es.Stop()

}
Esempio n. 15
0
func doClientMsg(h *InHandler) {
	var err error
	defer func() {
		h.errOut = err
	}()

	// DEBUG
	regName := h.reg.GetName()
	h.reg.Logger.Printf("doClientMsg: regName is %s\n", regName)
	// END

	// Examine incoming message -------------------------------------
	var (
		name   string
		attrs  uint64
		nodeID *xi.NodeID
		ck, sk *rsa.PublicKey
		myEnds []string
		hash   []byte
		cm     *ClientInfo
	)

	// XXX We should accept EITHER clientName + token OR clientID
	// This implementation only accepts a token.

	clientMsg := h.msgIn
	clientSpecs := clientMsg.GetMemberSpecs()
	name = clientSpecs.GetName()
	attrs = clientSpecs.GetAttrs()
	ckBytes := clientSpecs.GetCommsKey()
	skBytes := clientSpecs.GetSigKey()
	digSig := clientSpecs.GetDigSig()

	ck, err = xc.RSAPubKeyFromWire(ckBytes)
	if err == nil {
		sk, err = xc.RSAPubKeyFromWire(skBytes)
		if err == nil {
			myEnds = clientSpecs.GetMyEnds() // a string array
		}
	}
	if err == nil {
		// calculate hash over fields in canonical order XXX EXCLUDING ID
		aBytes := make([]byte, 8)
		binary.LittleEndian.PutUint64(aBytes, attrs)
		d := sha1.New()
		d.Write([]byte(name))
		d.Write(aBytes)
		d.Write(ckBytes)
		d.Write(skBytes)
		for i := 0; i < len(myEnds); i++ {
			d.Write([]byte(myEnds[i]))
		}
		hash = d.Sum(nil)
		// verify the digital signature
		err = rsa.VerifyPKCS1v15(sk, crypto.SHA1, hash, digSig)
	}
	if err == nil {
		id := clientSpecs.GetID()
		// DEBUG
		if id == nil {
			h.reg.Logger.Println("  doClientMsg: id from Specs is NIL")
		} else {
			h.reg.Logger.Printf("  doClientMsg: id from Specs is %x\n", id)
		}
		// END
		if id == nil {
			nodeID, err = h.reg.InsertUniqueNodeID()
			// DEBUG
			h.reg.Logger.Printf("  doClientMsg: inserting %x returned %v\n", id, err)
			// END
			if err == nil {
				id := nodeID.Value()
				// this is echoed to the console
				h.reg.Logger.Printf("doClientMsg: assigning new MemberID %xi, user %s",
					id, name)
			}
		} else {
			// must be known to the registry
			nodeID, err = xi.New(id)
			if err == nil {
				var found bool
				found, err = h.reg.ContainsID(nodeID)
				if err == nil && !found {
					err = h.reg.InsertID(nodeID)
				}
			}
		}
	}
	// Take appropriate action --------------------------------------
	if err == nil || err == IDAlreadyInUse {
		// The appropriate action is to hang a token for this client off
		// the InHandler.
		cm, err = NewClientInfo(name, nodeID, ck, sk, attrs, myEnds)
		if err == nil {
			h.thisClient = cm
		}
	}
	if err == nil {
		// Prepare reply to client --------------------------------------
		// In this implementation We simply accept the client's proposed
		// attrs and ID.
		op := XLRegMsg_MemberOK
		h.msgOut = &XLRegMsg{
			Op:          &op,
			MemberID:    nodeID.Value(),
			MemberAttrs: &attrs, // in production, review and limit
		}

		// Set exit state -----------------------------------------------
		h.exitState = CLIENT_DETAILS_RCVD
	}
}
Esempio n. 16
0
func (s *XLSuite) TestPortlandRegCred(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PORTLAND_REG_CRED")
	}
	rng := xr.MakeSimpleRNG()
	_ = rng

	// read our local copy of the reg cred
	rcData, err := ioutil.ReadFile("portlandRegCred.dat")
	c.Assert(err, IsNil)
	rc, err := ParseRegCred(string(rcData))
	c.Assert(err, IsNil)
	c.Assert(rc, NotNil)

	// DEBUG
	fmt.Println("portlandRegCred_test PORTLAND - A PUZZLE")
	// END

	// set up the client --------------------------------------------
	name := rng.NextFileName(8)
	lfs := path.Join("tmp", name)
	found, err := xf.PathExists(lfs)
	c.Assert(err, IsNil)
	for found {
		name = rng.NextFileName(8)
		lfs = path.Join("tmp", name)
		found, err = xf.PathExists(lfs)
		c.Assert(err, IsNil)
	}

	ep, err := xt.NewTcpEndPoint("127.0.0.1:0")
	c.Assert(err, IsNil)
	e := []xt.EndPointI{ep}
	c.Assert(e, NotNil)

	nodeID, err := xi.New(nil)
	c.Assert(err, IsNil)

	node, err := xn.NewNew(name, nodeID, lfs)
	c.Assert(err, IsNil)

	// DEBUG
	fmt.Printf("Portland client is at %v; lfs is %s\n",
		e, lfs)
	// END

	// set up its relationship to the server ------------------------
	serverName := rc.Name
	serverID := rc.ID
	serverEnd := rc.EndPoints
	c.Assert(serverEnd, NotNil)
	c.Assert(len(serverEnd) > 0, Equals, true)
	c.Assert(serverEnd[0], NotNil)
	// XXX TOO RIGID
	c.Assert(serverEnd[0].String(), Equals, "TcpEndPoint: 54.186.197.123:56789")
	// END
	serverCK := rc.CommsPubKey
	serverSK := rc.SigPubKey

	sc, err := NewSoloMember(node, serverName, serverID, serverEnd[0],
		serverCK, serverSK, e)
	c.Assert(err, IsNil)
	c.Assert(sc, NotNil)

	// DEBUG
	fmt.Println("SoloMember CREATED")

	// END

	// 3. run the client
	sc.Start()
	err = <-sc.DoneCh

	// 4.  verify that the client LFS exists and is correct ---------
	found, err = xf.PathExists(lfs)
	c.Assert(err, IsNil)
	c.Assert(found, Equals, true)

	// 5.  shut down the client -------------------------------------
	sc.CloseAcc() // should close any acceptors

}
Esempio n. 17
0
func ParseRegCred(s string) (rc *RegCred, err error) {

	var (
		line    string
		parts   []string
		name    string
		nodeID  *xi.NodeID
		ck, sk  *rsa.PublicKey
		e       []xt.EndPointI
		version xu.DecimalVersion
	)
	ss := strings.Split(s, "\n")
	line, err = xc.NextNBLine(&ss)
	if (err == nil) && (line != "regCred {") {
		err = IllFormedRegCred
	}
	if err == nil {
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			parts = strings.Split(line, ": ")
			if len(parts) == 2 && parts[0] == "Name" {
				name = strings.TrimLeft(parts[1], " \t")
			} else {
				err = IllFormedRegCred
			}
		}
	}
	if err == nil {
		var id []byte
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			parts = strings.Split(line, ": ")
			if len(parts) == 2 && parts[0] == "ID" {
				id, err = hex.DecodeString(parts[1])
			} else {
				err = IllFormedRegCred
			}
		}
		if err == nil {
			nodeID, err = xi.New(id)
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			parts = strings.Split(line, ": ")
			if len(parts) == 2 && parts[0] == "CommsPubKey" {
				ck, err = xc.RSAPubKeyFromDisk([]byte(parts[1]))
			} else {
				err = IllFormedRegCred
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			parts = strings.Split(line, ": ")
			if len(parts) == 2 && parts[0] == "SigPubKey" {
				sk, err = xc.RSAPubKeyFromDisk([]byte(parts[1]))
			} else {
				err = IllFormedRegCred
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			// collect EndPoints section; this should be turned into a
			// utility function
			if line == "EndPoints {" {
				for err == nil {
					line = strings.TrimSpace(ss[0]) // peek
					if line == "}" {
						break
					}
					line, err = xc.NextNBLine(&ss)
					if err == nil {
						line = strings.TrimSpace(line)
						parts := strings.Split(line, ": ")
						if len(parts) != 2 || parts[0] != "TcpEndPoint" {
							err = IllFormedRegCred
						} else {
							var ep xt.EndPointI
							ep, err = xt.NewTcpEndPoint(parts[1])
							if err == nil {
								e = append(e, ep)
							}
						}
					}
				}
				if err == nil {
					line, err = xc.NextNBLine(&ss)
					if (err == nil) && (line != "}") {
						err = MissingClosingBrace
					}
				}
			} else {
				err = MissingEndPointsSection
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&ss)
		if err == nil {
			parts = strings.Split(line, ": ")
			if len(parts) == 2 && parts[0] == "Version" {
				version, err = xu.ParseDecimalVersion(parts[1])
			} else {
				err = IllFormedRegCred
			}
		}
	}
	if err == nil {
		rc = &RegCred{
			Name:        name,
			ID:          nodeID,
			CommsPubKey: ck,
			SigPubKey:   sk,
			EndPoints:   e,
			Version:     version,
		}
	}
	return
}
Esempio n. 18
0
func ParseRegClusterFromStrings(ss []string) (
	rc *RegCluster, rest []string, err error) {

	var (
		attrs            uint64
		name             string
		id               *xi.NodeID
		epCount, maxSize uint32
	)
	rest = ss

	var line string
	line, err = xc.NextNBLine(&rest) // the line is trimmed
	if err == nil {
		if line != "regCluster {" {
			fmt.Println("MISSING regCluster {")
			err = IllFormedCluster
		} else {
			line, err = xc.NextNBLine(&rest)
			if err == nil {
				if strings.HasPrefix(line, "Attrs: ") {
					var i int64
					i, err = strconv.ParseInt(line[7:], 0, 64)
					if err == nil {
						attrs = uint64(i)
					}
				} else {
					fmt.Printf("BAD ATTRS in line '%s'", line)
					err = IllFormedCluster
				}
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if strings.HasPrefix(line, "Name: ") {
				name = line[6:]
			} else {
				fmt.Printf("BAD NAME in line '%s'", line)
				err = IllFormedCluster
			}
		}
	}
	if err == nil {
		// collect ID
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if strings.HasPrefix(line, "ID: ") {
				var val []byte
				val, err = hex.DecodeString(line[4:])
				if err == nil {
					id, err = xi.New(val)
				}
			} else {
				fmt.Println("BAD ID")
				err = IllFormedCluster
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if strings.HasPrefix(line, "epCount: ") {
				var count int
				count, err = strconv.Atoi(line[9:])
				if err == nil {
					epCount = uint32(count)
				}
			} else {
				fmt.Println("BAD END POINT COUNT")
				err = IllFormedCluster
			}
		}
	}
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if strings.HasPrefix(line, "maxSize: ") {
				var size int
				size, err = strconv.Atoi(line[9:])
				if err == nil {
					maxSize = uint32(size)
				}
			} else {
				fmt.Println("BAD MAX_SIZE")
				err = IllFormedCluster
			}
		}
	}
	if err == nil {
		rc, err = NewRegCluster(name, id, attrs, maxSize, epCount)
	}
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if line == "Members {" {
				for {
					line = strings.TrimSpace(rest[0]) // peek
					if line == "}" {
						break
					}
					var member *ClientInfo
					member, rest, err = ParseClientInfoFromStrings(rest)
					if err != nil {
						break
					}
					err = rc.AddMember(member)
					if err != nil {
						break
					}
				}
			} else {
				err = MissingMembersList
			}
		}
	}

	// expect closing brace for Members list
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if line != "}" {
				err = MissingClosingBrace
			}
		}
	}
	// expect closing brace  for cluster
	if err == nil {
		line, err = xc.NextNBLine(&rest)
		if err == nil {
			if line != "}" {
				err = MissingClosingBrace
			}
		}
	}

	return
}
Esempio n. 19
-1
func setup(opt *reg.RegOptions) (rs *reg.RegServer, err error) {
	// If LFS/.xlattice/reg.config exists, we load that.  Otherwise we
	// create a node.  In either case we force the node to listen on
	// the designated port

	var (
		e                []xt.EndPointI
		node             *xn.Node
		pathToConfigFile string
		rn               *reg.RegNode
		ckPriv, skPriv   *rsa.PrivateKey
	)
	logger := opt.Logger
	verbose := opt.Verbose

	greetings := fmt.Sprintf("xlReg v%s %s start run\n",
		reg.VERSION, reg.VERSION_DATE)
	if verbose {
		fmt.Print(greetings)
	}
	logger.Print(greetings)

	pathToConfigFile = path.Join(path.Join(opt.Lfs, ".xlattice"), "reg.config")
	found, err := xf.PathExists(pathToConfigFile)
	if err == nil {
		if found {
			logger.Printf("Loading existing reg config from %s\n",
				pathToConfigFile)
			// The registry node already exists.  Parse it and we are done.
			var data []byte
			data, err = ioutil.ReadFile(pathToConfigFile)
			if err == nil {
				rn, _, err = reg.ParseRegNode(string(data))
			}
		} else {
			logger.Println("No config file found, creating new registry.")
			// We need to create a registry node from scratch.
			nodeID, _ := xi.New(nil)
			ep, err := xt.NewTcpEndPoint(opt.Address + ":" + opt.Port)
			if err == nil {
				e = []xt.EndPointI{ep}
				ckPriv, err = rsa.GenerateKey(rand.Reader, 2048)
				if err == nil {
					skPriv, err = rsa.GenerateKey(rand.Reader, 2048)
				}
				if err == nil {
					node, err = xn.New("xlReg", nodeID, opt.Lfs, ckPriv, skPriv,
						nil, e, nil)
					if err == nil {
						node.OpenAcc() // XXX needs a complementary close
						if err == nil {
							// DEBUG
							fmt.Printf("XLattice node successfully created\n")
							fmt.Printf("  listening on %s\n", ep.String())
							// END
							rn, err = reg.NewRegNode(node, ckPriv, skPriv)
							if err == nil {
								// DEBUG
								fmt.Printf("regNode successfully created\n")
								// END
								err = xf.MkdirsToFile(pathToConfigFile, 0700)
								if err == nil {
									err = ioutil.WriteFile(pathToConfigFile,
										[]byte(rn.String()), 0400)
									// DEBUG
								} else {
									fmt.Printf("error writing config file: %v\n",
										err.Error())
								}
								// END --------------

								// DEBUG
							} else {
								fmt.Printf("error creating regNode: %v\n",
									err.Error())
								// END
							}
						}
					}
				}
			}
		}
	}
	if err == nil {
		var r *reg.Registry
		r, err = reg.NewRegistry(nil, // nil = clusters so far
			rn, opt) // regNode, options
		if err == nil {
			logger.Printf("Registry name: %s\n", rn.GetName())
			logger.Printf("         ID:   %s\n", rn.GetNodeID().String())
		}
		if err == nil {
			var verbosity int
			if opt.Verbose {
				verbosity++
			}
			rs, err = reg.NewRegServer(r, opt.Testing, verbosity)
		}
	}
	if err != nil {
		logger.Printf("ERROR: %s\n", err.Error())
	}
	return
}
Esempio n. 20
-1
func NewEphServer() (ms *EphServer, err error) {

	// Create an XLattice node with quasi-random parameters including
	// low-quality keys and an endPoint in 127.0.0.1, localhost.
	var (
		ckPriv, skPriv *rsa.PrivateKey
		rn             *RegNode
		ep             *xt.TcpEndPoint
		node           *xn.Node
		reg            *Registry
		server         *RegServer
	)

	rng := xr.MakeSimpleRNG()
	name := rng.NextFileName(16)
	idBuf := make([]byte, xu.SHA1_BIN_LEN)
	rng.NextBytes(idBuf)
	lfs := "tmp/" + hex.EncodeToString(idBuf)
	id, err := xi.New(nil)
	if err == nil {
		// XXX cheap keys, too weak for any serious use
		ckPriv, err = rsa.GenerateKey(rand.Reader, 1024)
		if err == nil {
			skPriv, err = rsa.GenerateKey(rand.Reader, 1024)
		}
	}
	if err == nil {
		ep, err = xt.NewTcpEndPoint("127.0.0.1:0")
		eps := []xt.EndPointI{ep}
		if err == nil {
			node, err = xn.New(name, id, lfs, ckPriv, skPriv, nil, eps, nil)
			if err == nil {
				err = node.OpenAcc() // so acceptors are now live
				if err == nil {
					rn, err = NewRegNode(node, ckPriv, skPriv)
					if err == nil {
						// DEBUG
						if rn == nil {
							fmt.Println("regNode is NIL!\n")
						} else {
							fmt.Printf("eph server listening on %s\n",
								rn.GetAcceptor(0).String())
						}
						// END
						// a registry with no clusters and no logger
						opt := &RegOptions{
							EndPoint:       ep, // not used
							Ephemeral:      true,
							GlobalEndPoint: node.GetEndPoint(0),
							Lfs:            lfs, // redundant (is in node's BaseNode)
							Logger:         nil,
							K:              DEFAULT_K,
							M:              DEFAULT_M,
						}
						reg, err = NewRegistry(nil, rn, opt)
						if err == nil {
							server, err = NewRegServer(reg, true, 1)
							if err == nil {
								ms = &EphServer{
									acc:    rn.GetAcceptor(0),
									Server: server,
								}
							}
						}
					}
				}
			}
		}
	}
	return
}