/**
* @brief Sign a message with provided RSA key.
*
* Hash msg (SHA1) and encrypt the resulting digest. The buffer supplied to hold
* the signature must be at least RSA_size(keypair) bytes long.
*
* @param msg Data to sign.
* @param msg_len Size of data to sign.
* @param sigbuf Buffer to hold created signature.
* @param sigbuflen Space available for signature.
*
* @return Size of signature on success, 0 on error.
*/
uint32_t sign(RSA *keypair, char *msg, size_t msg_len, char *sigbuf, int sigbuflen) {
	
	if (sigbuflen < RSA_size(keypair)) {
		ERROR("ERROR: Could not sign message because sigbuf is too small");
		return 0;
	}

	/* first hash msg */
	unsigned char *digest = myhash(msg, msg_len);
	if (digest == NULL) {
		ERROR("ERROR: Unable to hash message");
		return 0;
	}

	/* now sign the hash */
    uint32_t siglen;
    if (RSA_sign(NID_sha1, digest, SHA_DIGEST_LENGTH, (unsigned char*)sigbuf, &siglen, keypair) != 1) {

    	char *err = (char *)malloc(130); //FIXME?
        ERR_load_crypto_strings();
        ERR_error_string(ERR_get_error(), err);
        ERRORF("Error signing message: %s", err);
        
        free(err);
        return 0;
    }

	free(digest);
	return siglen;
}
/*******************************************************************************************************************
* Function     : WFREQ_myhash_id_1
* Description  : 1. Verify that a new memory is allocated when a new element is added to the hash table with a 
* 		new index.
* 		2. Verify that if already there is element at an index in hashtable then only counter is incremented.
* Input        : Nothing
* Output       : Nothing
* Exception    : 
********************************************************************************************************************/
void WFREQ_add_inc_word_in_hashtbl_ID_1(void)
{
	HASHNODE  *head[BUCKETSIZE] = {{NULL}};
	char word[] = "abcd";
	int ret = FAILURE;
	unsigned int hash_val = 0;
	HASHNODE *temp_hash = NULL;
	
	/*case 1: when no element in hash table*/
	hash_val = myhash(word);
	ret = add_inc_word_in_hashtbl(word,head);
	
	temp_hash = head[hash_val];	
	CU_ASSERT(SUCCESS == ret);
	CU_ASSERT(1 == temp_hash->count);

	/*case 2 one element already added in hash table*/
	ret = add_inc_word_in_hashtbl(word,head);
	temp_hash = head[hash_val];	
	CU_ASSERT(SUCCESS == ret);
        CU_ASSERT(2 == temp_hash->count);

/*free the memory after use*/
	free_hashtable(head);

}
Esempio n. 3
0
void get_map_1(vector<string> &mqueue, uint32_t num_nodes) {
        //map<uint32_t, NodeList> update_map;
        //uint32_t num_nodes = svrclient.memberList.size();
        for(vector<string>::iterator it = mqueue.begin(); it != mqueue.end(); ++it) {
                Package package;
                package.ParseFromString(*it); //cout << "key = " << package.virtualpath() << endl;
                uint32_t serverid = myhash(package.virtualpath().c_str(), num_nodes);
                string str(*it); str.append("#");
                if(update_map_zht.find(serverid) == update_map_zht.end()) {
                        str.append("$");
                        NodeList new_list;
                        new_list.push_back(str);
                        update_map_zht.insert(make_pair(serverid, new_list));
                }
                else {
                        NodeList &exist_list = update_map_zht[serverid];
                        string last_str(exist_list.back());
                        if((last_str.size() + str.size()) > STRING_THRESHOLD) {
                                str.append("$");
                                exist_list.push_back(str);
                        }
                        else {
                                exist_list.pop_back();
                                str.append(last_str);
                                exist_list.push_back(str);
                        }
                }
        }
        //return update_map;
}
Esempio n. 4
0
map<uint32_t, NodeList> Worker::get_map(vector<string> &mqueue) {
	map<uint32_t, NodeList> update_map;
	/*Package package;
	 package.set_operation(operation);
	 if(operation == 25) {
	 package.set_currnode(toid);
	 }*/
	uint32_t num_nodes = svrclient.memberList.size();
	for (vector<string>::iterator it = mqueue.begin(); it != mqueue.end();
			++it) {
		uint32_t serverid = myhash((*it).c_str(), num_nodes);
		string str(*it);
		str.append("\'");
		if (update_map.find(serverid) == update_map.end()) {
			str.append("\"");
			NodeList new_list;
			new_list.push_back(str);
			update_map.insert(make_pair(serverid, new_list));
		} else {
			NodeList &exist_list = update_map[serverid];
			string last_str(exist_list.back());
			if ((last_str.size() + str.size()) > STRING_THRESHOLD) {
				str.append("\"");
				exist_list.push_back(str);
			} else {
				exist_list.pop_back();
				str.append(last_str);
				exist_list.push_back(str);
			}
		}
	}
	return update_map;
}
Esempio n. 5
0
int Worker::zht_remove(string key) {

	/*Package package;
	 package.set_virtualpath(key);
	 package.set_operation(2);
	 string str = package.SerializeAsString();

	 int index;
	 svrclient.str2Host(str, index);*/

	int index = myhash(key.c_str(), svrclient.memberList.size());

	if (index != selfIndex) {
		Package package;
		package.set_virtualpath(key);
		package.set_operation(2);
		string str = package.SerializeAsString();
		pthread_mutex_lock(&msg_lock);
		int ret = svrclient.remove(str);
		pthread_mutex_unlock(&msg_lock);
		return ret;
	} else {
		int ret = pmap->remove(key);
		if (ret != 0) {
			cerr << "DB Error: fail to remove :ret= " << ret << endl;
			return -2;
		} else
			return 0; //succeed.
	}

}
Esempio n. 6
0
void mapHM::set(string key, int value){
    int hash_value = myhash(&*key.begin(), key.length(), size_of_table);
    if (!(is_in(key))){
        Pairs p;
        p.setPairs(key, value);
    arrayOfPairs[hash_value].add(p);
    }
}
Esempio n. 7
0
//transfer a key to a host index where it should go
struct HostEntity ZHTClient::str2Host(string str) {
	Package pkg;
	pkg.ParseFromString(str);
	int index = myhash(pkg.virtualpath().c_str(), this->memberList.size());
	struct HostEntity host = this->memberList.at(index);

	return host;
}
Esempio n. 8
0
int mapHM::get(string key){
    int hash_value = myhash(&*key.begin(), key.length(), size_of_table);
    for (int i = 0; i < arrayOfPairs[hash_value].getSize(); i++){
        if (arrayOfPairs[hash_value].getArray()[i].getKey() == key){
                return arrayOfPairs[hash_value].getArray()[i].getValue();
            }
    }
    return -5;
}
Esempio n. 9
0
bool mapHM::is_in(string key){
    int hash_value = myhash(&*key.begin(), key.length(), size_of_table);
    for (int i = 0; i < arrayOfPairs[hash_value].getSize(); i++){
        if (arrayOfPairs[hash_value].getArray()[i].getKey() == key){
            return true;
        }
    }   
  return false; 
}
/** test adding a random element */
static void
testremove(struct lruhash* table, testdata_t* ref[])
{
	int num = random() % HASHTESTMAX;
	testkey_t* key = newkey(num);
	lruhash_remove(table, myhash(num), key);
	ref[num] = NULL;
	delkey(key);
}
/** allocate new key, fill in hash */
static testkey_t* newkey(int id) {
	testkey_t* k = (testkey_t*)calloc(1, sizeof(testkey_t));
	if(!k) fatal_exit("out of memory");
	k->id = id;
	k->entry.hash = myhash(id);
	k->entry.key = k;
	lock_rw_init(&k->entry.lock);
	return k;
}
Esempio n. 12
0
void mapHM::rmove(string key){
    int hash_value = myhash(&*key.begin(), key.length(), size_of_table);
    for (int i = 0; i < arrayOfPairs[hash_value].getSize(); i++){
        if (arrayOfPairs[hash_value].getArray()[i].getKey() == key){
            arrayOfPairs[hash_value].getArray()[i].setPairs(deleted, 0);
        }
    }
    
    
}
/** test adding a random element */
static void
testadd(struct lruhash* table, testdata_t* ref[])
{
	int numtoadd = random() % HASHTESTMAX;
	testdata_t* data = newdata(numtoadd);
	testkey_t* key = newkey(numtoadd);
	key->entry.data = data;
	lruhash_insert(table, myhash(numtoadd), &key->entry, data, NULL);
	ref[numtoadd] = data;
}
/** test adding a random element (unlimited range) */
static void
testremove_unlim(struct lruhash* table, testdata_t** ref)
{
	int num = random() % (HASHTESTMAX*10);
	testkey_t* key = newkey(num);
	lruhash_remove(table, myhash(num), key);
	if(ref)
		ref[num] = NULL;
	delkey(key);
}
Esempio n. 15
0
/* lookup in a symbol table */
TreeNode *LookupSymbol(char *name, SymbolTable *symtab){
	int idx = myhash(name);
	Symbol *p = symtab->NameList[idx];
	while (p){
		if (!strcmp(p->name, name)){
			return p->content;
		}
		p = p->next;
	}
	return NULL;
}
/** test adding a random element (unlimited range) */
static void
testadd_unlim(struct lruhash* table, testdata_t** ref)
{
	int numtoadd = random() % (HASHTESTMAX * 10);
	testdata_t* data = newdata(numtoadd);
	testkey_t* key = newkey(numtoadd);
	key->entry.data = data;
	lruhash_insert(table, myhash(numtoadd), &key->entry, data, NULL);
	if(ref)
		ref[numtoadd] = data;
}
bool insert(const HashedObj & x)
{
  auto & whichList = theLists[myhash(x)];
  if(find(begin(whichList),end(whichList),x) != end(whichList))
    return false;
  whichList.push_back(x);
  
  if(++currentSize > theLists.size())
    rehash;
    
  return true;
}
bool remove(const HashedObj & x)
{
  auto & whichList = theLists[myhash(x)];
  auto itr = find(begin(whichList),end(whichList),x);
  
  if(itr == end(whichList))
    return false;
    
  whichList.erase(itr);
  --currentSize;
  return true;
}
	bool remove(const int x)
	{
		list<int>¡¡& curList = theLists[myhash(x)];
		list<int>::iterator itr = find(curList.begin(), curList.end(), x);

		if(itr == curList.end())
			return false;
		
		curList.erase(itr);
		currentSize--;
		return true;
	}
Esempio n. 20
0
	bool remove(const T & x)
	{
		std::list<T> & whichList = theLists[myhash(x)];
		std::list<T>::iterator itr = find(whichList.begin(), whichList.end(), x);

		if (itr == whichList.end())
			return false;

		whichList.erase(itr);
		--currentSize;
		return true;
	}
Esempio n. 21
0
  bool HashTable::contains(const string & x) const
 {
    int pos = myhash(x);
    if(theLists.size() < pos)
       return false;
    else
    {
       vector<string> list = theLists[pos];
       pos = binarySearch(list, 0, list.size()-1, x);	
       return pos != -1;			
    }
 }
Esempio n. 22
0
	bool insert(const T & x)//插入一个元素
	{
		std::list<T> & whichList = theLists[myhash(x)]; //通过hash函数计算下标
		if (find(whichList.begin(), whichList.end(), x) != whichList.end())//判断是否已经包含了当前元素
			return false;
		whichList.push_back(x);

		if (++currentSize > theLists.size() / 2)//如果元素个数超过散列表的一半,再散列
			rehash();

		return true;
	}
/*****************************************************************************************************************
* Function     : WFREQ_myhash_id_1
* Description  : 1. Verify that a hash value is returned by the function "myhash" according to the algo when
* 		 a string is passed to the function.
* 		 2. Verify that invalid value is returned when a NULL pointer is passes to the function "myhash".
* Input        : Nothing
* Output       : Nothing
* Exception    : 
******************************************************************************************************************/
void WFREQ_myhash_ID_1(void)
{
	char word[] = "abcd";
	char *c = NULL;
	unsigned int ret = 0;

	ret = myhash(word);
	CU_ASSERT(17074 == ret);

	/*CASE 2: If NULL pointer is passed to the function*/
	
//	ret = myhash(c); /*this call will crash becasue call handling is not done in the code for NULL pointer*/
}
Esempio n. 24
0
 bool insert( const HashedObj & x )
 {
     list<HashedObj> & whichList = theLists[ myhash( x ) ];
     if( find( whichList.begin( ), whichList.end( ), x ) != whichList.end( ) )
         return false;
     whichList.push_back( x );
 
         // Rehash; see Section 5.5
     if( ++currentSize > theLists.size( ) )
         rehash( );
 
     return true;
 }
Esempio n. 25
0
int HashTable<HashObj>::findPos( const HashObj & x) const{
        std::cout << "ENTERING FINDPOS FUNCTION" << std::endl;
        int offset = 1;
        int currentPos = myhash( x );
        while ( array[currentPos].info != EMPTY &&
                array[currentPos].element != x ){
                currentPos += offset;  // iTh probe
                offset += 2;           // offset
                if ( currentPos >= (int)array.size() )
                        currentPos -= array.size();
        }
        return currentPos;
}
Esempio n. 26
0
int Worker::update_nodehistory(uint32_t currnode, string alltasks) {
	int num_vector_count, per_vector_count;
	vector<vector<string> > tokenize_string = tokenize(alltasks, '\"', '\'',
			num_vector_count, per_vector_count);
	uint32_t num_nodes = svrclient.memberList.size();
	//cout << "Worker = " << selfIndex << " num_vector_count = " << num_vector_count << " per_vector_count = " << per_vector_count << endl;
	for (int i = 0; i < num_vector_count; i++) {
		for (int j = 0; j < per_vector_count; j++) {
			try {
				string &taskid = tokenize_string.at(i).at(j);
				string value = zht_lookup(taskid);
				Package recv_pkg;
				recv_pkg.ParseFromString(value);

				int index = myhash(taskid.c_str(), num_nodes);
				if (index != selfIndex) {
					cout
							<< "something wrong..doing remote update_nodehistory index = "
							<< index << " selfIndex = " << selfIndex << endl;
				}

				// update number of moves (increment)
				uint32_t old_nummoves = recv_pkg.nummoves();
				recv_pkg.set_nummoves(old_nummoves + 1);

				// update current location of task
				recv_pkg.set_currnode(currnode);

				// update task migration history
				stringstream nodehistory_ss;
				nodehistory_ss << currnode << "\'";
				string new_nodehistory(nodehistory_ss.str());
				new_nodehistory.append(recv_pkg.nodehistory()); //cout << "update_nodehistory: task " << recv_pkg.virtualpath() << " node history = " << recv_pkg.nodehistory();
				recv_pkg.set_nodehistory(new_nodehistory); //cout << " node history = " << recv_pkg.nodehistory() << endl;

				// insert updated task into ZHT
				int ret = zht_insert(recv_pkg.SerializeAsString());
				if (ret != 0) {
					cout << "update_nodehistory: zht_insert error ret = " << ret
							<< endl;
					exit(1);
				}
			} catch (exception& e) {
				cout << "update_nodehistory: (tokenize_string.at(i).at(0)) "
						<< " " << e.what() << endl;
				exit(1);
			}
		}
	}
	return 0;
}
Esempio n. 27
0
int Worker::update_numwait(string alltasks) {
	int num_vector_count, per_vector_count;
	vector<vector<string> > tokenize_string = tokenize(alltasks, '\"', '\'',
			num_vector_count, per_vector_count);
	uint32_t num_nodes = svrclient.memberList.size();
	for (int i = 0; i < num_vector_count; i++) {
		for (int j = 0; j < per_vector_count; j++) {
			try {
				string &taskid = tokenize_string.at(i).at(j);
				string value = zht_lookup(taskid);
				Package recv_pkg;
				recv_pkg.ParseFromString(value);

				int index = myhash(taskid.c_str(), num_nodes);
				if (index != selfIndex) {
					cout
							<< "something wrong..doing remote update_numwait: index = "
							<< index << " selfIndex = " << selfIndex << endl;
				}

				// update number of tasks to wait (decrement)
				uint32_t old_numwait = recv_pkg.numwait();
				recv_pkg.set_numwait(old_numwait - 1);
				notr++;
				if (LOGGING) {
					if (old_numwait - 1 == 0) {
						log_fp << "task = " << taskid << " is ready" << endl;
					}
				}

				// insert updated task into ZHT
				int ret = zht_insert(recv_pkg.SerializeAsString());
				if (ret != 0) {
					cout << "update_numwait: old_numwait = " << old_numwait
							<< endl;
					cout << "update_numwait: zht_insert error ret = " << ret
							<< " key = " << taskid << " index = " << index
							<< " selfindex = " << selfIndex << endl;
					exit(1);
				}
			} catch (exception& e) {
				cout << "update_numwait: (tokenize_string.at(i).at(0)) " << " "
						<< e.what() << endl;
				exit(1);
			}
		}
	}
	log_fp << "notr = " << notr << endl;
	return 0;
}
/**
* @brief Verify a signature with the provided RSA public key.
*
* @param keypair Public key for verifying signature.
* @param msg Message to verify.
* @param msg_len Size of message to verify.
* @param sig Signature to verify.
* @param sig_len Size of signature to verify.
*
* @return 1 on successful verification, 0 otherwise
*/
int verify(RSA *keypair, char *msg, size_t msg_len, char *sig, size_t sig_len) {

	/* first hash msg */
	unsigned char *digest = myhash(msg, msg_len);
	if (digest == NULL) {
		ERROR("ERROR: Unable to hash message");
		return 0;
	}

	/* now verify signature */
	int rc = RSA_verify(NID_sha1, digest, SHA_DIGEST_LENGTH, (unsigned char*)sig, sig_len, keypair);

	free(digest);
	return rc;
}
Esempio n. 29
0
/* Create Symbol element */
void InsertSymbol(char *name, TreeNode *node, SymbolTable *symtab){
	int idx = myhash(name);
	Symbol *q = symtab->NameList[idx];
	/* init p */
	Symbol *p = (Symbol *)malloc(sizeof(Symbol));
	strcpy(p->name, name);
	p->content = node;
	/* connect nodes */
	if (q){
		while (q->next) q = q->next;
		q->next = p;
	} else {
		symtab->NameList[idx] = p;
	}
}
	bool insert(const int x)
	{
		list<int> & curList = theLists[myhash(x)];
		list<int>::iterator itr = find(curList.begin(), curList.end(), x);
		
		if(itr == curList.end())
			return false;

		curList.insert(curList.begin(),x);
		currentSize++;
		
		if(currentSize == theLists.size())  //load factor too big..
			rehash();

		return true;
	}