Пример #1
0
int
px_find_digest(const char *name, PX_MD ** res)
{
	PX_MD	   *h;
	MHASH		mh;
	int			i;

	i = find_hashid(name);
	if (i < 0)
		return -1;

	mh = mhash_init(i);
	h = px_alloc(sizeof(*h));
	h->p.ptr = (void *) mh;

	h->result_size = digest_result_size;
	h->block_size = digest_block_size;
	h->reset = digest_reset;
	h->update = digest_update;
	h->finish = digest_finish;
	h->free = digest_free;

	*res = h;
	return 0;
}
Пример #2
0
/*
**! file: Mhash/mhash.c
**!  File implementing the Mhash.Hash() class.
**! cvs_version: $Id$
**! class: Mhash.Hash
**!  An instance of a normal Mhash object. This object can be used to
**!  calculate various hashes supported by the Mhash library.
**! see_also: Mhash.HMAC
**! method: void create(int|void type)
**!  Called when instantiating a new object. It takes an optional first
**!  argument with the type of hash to use.
**! arg: int|void type
**!  The hash type to use. Can also be set with set_type();
**! name: create - Create a new hash instance.
*/
void f_hash_create(INT32 args)
{
  if(THIS->type != -1 || THIS->hash || THIS->res) {
    Pike_error("Recursive call to create. Use Mhash.Hash()->reset() or \n"
	  "Mhash.Hash()->set_type() to change the hash type or reset\n"
	  "the object.\n");
  }
  switch(args) {
  default:
    Pike_error("Invalid number of arguments to Mhash.Hash(), expected 0 or 1.\n");
    break;
  case 1:
    if(Pike_sp[-args].type != T_INT) {
      Pike_error("Invalid argument 1. Expected integer.\n");
    }
    THIS->type = Pike_sp[-args].u.integer;
    THIS->hash = mhash_init(THIS->type);
    if(THIS->hash == MHASH_FAILED) {
      THIS->hash = NULL;
      Pike_error("Failed to initialize hash.\n");
    }
    break;
  case 0:
    break;
  }
  
  pop_n_elems(args);
}
Пример #3
0
Файл: hash.c Проект: dodoma/reef
void test_iterate()
{
    MHASH *table;
    char s[KEY_LEN + 1], *ps[100];
    MERR *err;

    for (int i = 0; i < 100; i++) {
        //mstr_rand_string(s, KEY_LEN);
        snprintf(s, sizeof(s), "str %d", i);
        ps[i] = strdup(s);      /* TODO memory leak */
    }

    err = mhash_init(&table, mhash_str_hash, mhash_str_comp, mhash_str_free);
    MTEST_ASSERT(err == MERR_OK);

    for (int i = 0; i < 100; i++) {
        err = mhash_insert(table, ps[i], strdup(ps[i]));
        MTEST_ASSERT(err == MERR_OK);
    }

    int x = 0;
    char *key, *val;
    MHASH_ITERATE(table, key, val) {
        //printf("key %s %s\n", key, ps[x]);
        MTEST_ASSERT_STR_EQ(key, val);
        x++;
    }
Пример #4
0
/* create md5 hash from input string
 * returns NULL on failure
 * user must free returned string
 */
char *
Stats::Md5Hash(const char *thread)
{
    MHASH td;
    char *tmpcstr;
    int i;
    unsigned char *hash;
    char *rethash;

    td = mhash_init(MHASH_MD5);
    if (td == MHASH_FAILED)
        return NULL;

    if (thread==NULL)
        return NULL;

    mhash(td, thread, strlen(thread));
    //mhash_deinit(td, hash);
    hash = (unsigned char*) mhash_end(td);

    rethash = (char*) calloc(mhash_get_block_size(MHASH_MD5)*2+1, sizeof(char));
    for (i = 0; i < mhash_get_block_size(MHASH_MD5); i++) {
        sprintf(&rethash[i*2], "%.2x", hash[i]);
    }

    return rethash;
}
Пример #5
0
int main()
{
    MHASH *table;
    MERR *err;
    char str[101], *pstr[NODE_NUM];

    mtc_init("load.log", MTC_DEBUG);

    for (int i = 0; i < NODE_NUM; i++) {
        //mstr_rand_string(str, 100);
        //mstr_rand_string_fixlen(str, 100);
        snprintf(str, sizeof(str), "%d", i);

        pstr[i] = strdup(str);
    }

    err = mhash_init(&table, mhash_str_hash, mhash_str_comp, mhash_str_free);
    TRACE_NOK(err);

    mtimer_start();
    for (int i = 0; i < NODE_NUM; i++) {
        mhash_insert(table, pstr[i], NULL);
    }
    mtimer_stop("hash insert");

    mtimer_start();
    for (int i = 0; i < NODE_NUM; i++) {
        mhash_lookup(table, pstr[i]);
    }
    mtimer_stop("hash lookup");

    mhash_destroy(&table);

    return 0;
}
Пример #6
0
void hash_given_data( void* data, size_t data_size) {
MHASH td;
byte _res[20];
int i;

	td = mhash_init( MHASH_SHA1);
	if (td==MHASH_FAILED) {
		err_quit(_("mhash_init() failed."));
	}

	/* also hash the pool
	 */
	mhash( td, rnd_pool, 20);
	
	mhash(td, data, data_size);

	mhash_deinit( td, _res);

	/* addition may do as well as xor
	 */
	for(i=0;i<20;i++) rnd_pool[i] ^= _res[i];


	/* Step 1 was completed. The pool was updated.
	 */
	 
}
Пример #7
0
int
rasqal_digest_buffer(rasqal_digest_type type, const unsigned char *output,
                     const unsigned char * const input, size_t len)
{
  hashid hash_type;
  unsigned int output_len;
  MHASH m;
  
  if(type > RASQAL_DIGEST_LAST)
    return -1;
  
  hash_type = rasqal_digest_to_hashid[type];
  if(hash_type == (hashid)-1)
    return -1;
  
  output_len = mhash_get_block_size(hash_type);
  if(!input)
    return output_len;
  
  m = mhash_init(hash_type);
  if(m == MHASH_FAILED)
    return -1;

  mhash(m, (const void *)input, len);
  
  mhash_deinit(m, (void*)output);

  return output_len;
}
Пример #8
0
/*
**! method: Mhash.hash feed(string data)
**!    alt: Mhash.hash update(string data)
**!  Update the current hash context with data.
**!  update() is here for compatibility reasons with Crypto.md5.
**! arg: string data
**!  The data to update the context with.
**! returns:
**!  The current hash object.
**! name: feed - Update the current hash context.
*/
void f_hash_feed(INT32 args) 
{
  if(THIS->hash == NULL) {
    if(THIS->type != -1) {
      free_hash();
      THIS->hash = mhash_init(THIS->type);
      if(THIS->hash == MHASH_FAILED) {
	THIS->hash = NULL;
	Pike_error("Failed to initialize hash.\n");
      }
    } else
      Pike_error("Hash is uninitialized. Use Mhash.Hash()->set_type() to select hash type.\n");
  }
  if(args == 1) {
    if(Pike_sp[-args].type != T_STRING) {
      Pike_error("Invalid argument 1. Expected string.\n");
    }
    mhash(THIS->hash, Pike_sp[-args].u.string->str,
	  Pike_sp[-args].u.string->len << Pike_sp[-args].u.string->size_shift);
  } else {
    Pike_error("Invalid number of arguments to Mhash.Hash->feed(), expected 1.\n");
  }
  pop_n_elems(args);
  push_object(this_object());
}
Пример #9
0
struct running_checksum *start_running_checksum(void)
{
	struct running_checksum *c = calloc(1, sizeof(struct running_checksum));

	if (c)
		c->td = mhash_init(HASH_FUNC);

	return c;
}
Пример #10
0
void checksum_block(char *buf, int len, unsigned char *digest)
{
	td = mhash_init(HASH_FUNC);
	if (td == MHASH_FAILED)
		abort();

	mhash(td, buf, len);
	mhash_deinit(td, digest);
}
Пример #11
0
static void
digest_reset(PX_MD * h)
{
	MHASH		mh = (MHASH) h->p.ptr;
	hashid		id = mhash_get_mhash_algo(mh);
	uint8	   *res = mhash_end(mh);

	mhash_free(res);
	mh = mhash_init(id);
	h->p.ptr = mh;
}
Пример #12
0
/*
**! method: void reset()
**!  Clean up the current hash context and start from the beginning. Use
**!  this if you want to hash another string.
**! name: reset - Reset hash context
*/
void f_hash_reset(INT32 args)
{
  free_hash();
  if(THIS->type != -1) {
    THIS->hash = mhash_init(THIS->type);
    if(THIS->hash == MHASH_FAILED) {
      THIS->hash = NULL;
      Pike_error("Failed to initialize hash.\n");
    }
  }
  pop_n_elems(args);
}
Пример #13
0
/*
 * ******************************************* 
 *  Function: get_crc 
 *
 *  Description: gets the crc of a packet   
 *   
 *  Parameters : 
 *     buffer - link layer buffer 
 *     len    - length of buffer 
 *  
 * ******************************************* 
 */
uint32_t get_crc(void *buffer , int len)
{
     
	MHASH td;
	uint32_t crc;
	td = mhash_init(MHASH_CRC32);
        mhash(td,buffer,len); 
        mhash_deinit(td,&crc);
	return crc; 
 

}
Пример #14
0
static void
digest_finish(PX_MD * h, uint8 *dst)
{
	MHASH		mh = (MHASH) h->p.ptr;
	unsigned	hlen = digest_result_size(h);
	hashid		id = mhash_get_mhash_algo(mh);
	uint8	   *buf = mhash_end(mh);

	memcpy(dst, buf, hlen);
	mhash_free(buf);

	mh = mhash_init(id);
	h->p.ptr = mh;
}
Пример #15
0
char * compute_hash(FILE* file)
{
	MHASH td;
	unsigned char buffer;
	unsigned char hash[16];
	
	td = mhash_init (MHASH_MD5);
	
	while (fread (&buffer, 1, 1, file) == 1)
    {
		mhash (td, &buffer, 1);
    }
	mhash_deinit (td, hash);
	return hash;
}
Пример #16
0
int sha1passwdok(const char *pw) {
	unsigned char out[mhash_get_block_size(MHASH_SHA1)];
	char outstr[mhash_get_block_size(MHASH_SHA1)*2+1];
	int i;
	MHASH td;
	td=mhash_init(MHASH_SHA1);
	mhash(td, pw, strlen(pw));
	mhash_deinit(td, out);
	for (i=0; i<mhash_get_block_size(MHASH_SHA1); i++) {
		outstr[2*i]=hex[out[i] >> 4];
		outstr[2*i+1]=hex[out[i] & 0xf];
	}
	outstr[2*i]=0;
	return (memcmp(outstr,passwd,mhash_get_block_size(MHASH_SHA1))==0);
}
Пример #17
0
bool gtkhash_hash_lib_mhash_is_supported(const enum hash_func_e id)
{
	struct hash_lib_mhash_s data;

	if (!gtkhash_hash_lib_mhash_set_type(id, &data.type))
		return false;

	if (G_UNLIKELY((data.thread = mhash_init(data.type)) == MHASH_FAILED)) {
		g_warning("mhash_init failed (%d)", id);
		return false;
	}

	mhash_deinit(data.thread, NULL);

	return true;
}
Пример #18
0
int ddfs_calculate_hash(char * dst, char * src, int len) {
	//memcpy(dst, src, DDFS_HASH_LEN);
	//return 0;

    /*
	md5_state_t state;
	md5_init(&state);
	md5_append(&state, src , len);
	md5_finish(&state, dst);
    */

    MHASH td = mhash_init(MHASH_TIGER);
    mhash(td, src, len);
    mhash_deinit(td, dst);
	return 0;

}
Пример #19
0
static int MD4BlockChecksum( void *buffer, int length )
{
	MHASH	mh;
	int		digest[ 4 ], checksum;
	
	
	/* make md4 hash */
	mh = mhash_init( MHASH_MD4 );
	if( !mh )
		Error( "Unable to initialize MD4 hash context" );
	mhash( mh, buffer, length );
	mhash_deinit( mh, digest );
	
	/* xor the bits and return */
	checksum = digest[ 0 ] ^ digest[ 1 ] ^ digest[ 2 ] ^ digest[ 3 ];
	return checksum;
}
Пример #20
0
static const char *
vmod_hash_sha256(const struct vrt_ctx *ctx, const char *msg)
{
	MHASH td;
	hashid hash = MHASH_SHA256;
	unsigned char h[mhash_get_block_size(hash)];
	int i;
	char *p;
	char *ptmp;
	td = mhash_init(hash);
	mhash(td, msg, strlen(msg));
	mhash_deinit(td, h);
	p = WS_Alloc(ctx->ws,mhash_get_block_size(hash)*2 + 1);
	ptmp = p;
	for (i = 0; i<mhash_get_block_size(hash);i++) {
		sprintf(ptmp,"%.2x",h[i]);
		ptmp+=2;
	}
	return p;
}
Пример #21
0
/*
**! method: void set_type(int type)
**!  Set or change the type of the has in the current context.
**!  This function will also reset any hashing in progress.
**! name: set_type - Change the hash type
*/
void f_hash_set_type(INT32 args)
{
  if(args == 1) {
    if(Pike_sp[-args].type != T_INT) {
      Pike_error("Invalid argument 1. Expected integer.\n");
    } 
    THIS->type = Pike_sp[-args].u.integer;
  } else {
    Pike_error("Invalid number of arguments to Mhash.Hash()->set_type, expected 1.\n");
  }
  free_hash();
  if(THIS->type != -1) {
    THIS->hash = mhash_init(THIS->type);
    if(THIS->hash == MHASH_FAILED) {
      THIS->hash = NULL;
      Pike_error("Failed to initialize hash.\n");
    }
  }
  pop_n_elems(args);
}
Пример #22
0
std::string
MD5::md5_file(const std::string& filename)
{
  unsigned char hash[16]; /* enough size for MD5 */
  MHASH td = mhash_init(MHASH_MD5);
  if (td == MHASH_FAILED) 
  {
    throw std::runtime_error("Failed to init MHash");
  }
  else
  {  
    const unsigned int buf_size = 32768;
    char buf[buf_size];
    std::ifstream in(filename.c_str(), std::ios::in | std::ios::binary); 
    if (!in)
    {
      throw std::runtime_error("MD5::md5_file(): Couldn't open file " + filename);
    }
    else
    {
    
      while(!in.eof())
      {
        in.read(buf, buf_size);
        mhash(td, buf, in.gcount());
      }

      in.close();
    
      mhash_deinit(td, hash);

      // Convert to string representation
      std::ostringstream out;
      for (int i = 0; i < 16; i++)
        out << std::setfill('0') << std::setw(2) << std::hex << int(hash[i]);

      return out.str();  
    }
  }
}
Пример #23
0
Файл: hash.c Проект: dodoma/reef
void test_basic()
{
    MHASH *table;
    char s[KEY_LEN + 1], *ps[NODE_NUM], *data;
    MERR *err;

    for (int i = 0; i < NODE_NUM; i++) {
        //mstr_rand_string(s, KEY_LEN);
        snprintf(s, sizeof(s), "str %d", i);
        ps[i] = strdup(s);
    }

    err = mhash_init(&table, mhash_str_hash, mhash_str_comp, NULL);
    MTEST_ASSERT(err == MERR_OK);

    for (int i = 0; i < NODE_NUM; i++) {
        err = mhash_insert(table, ps[i], ps[i]);
        MTEST_ASSERT(err == MERR_OK);
    }

    MTEST_ASSERT(mhash_length(table) == NODE_NUM);

    for (int i = 0; i < NODE_NUM; i++) {
        MTEST_ASSERT(mhash_has_key(table, ps[i]));
    }

    for (int i = 0; i < NODE_NUM; i++) {
        data = mhash_lookup(table, ps[i]);
        MTEST_ASSERT(data == ps[i]);
    }

    for (int i = 0; i < NODE_NUM; i++) {
        MTEST_ASSERT(mhash_remove(table, ps[i]));
    }

    MTEST_ASSERT(mhash_length(table) == 0);

    mhash_destroy(&table);
}
Пример #24
0
int main(void)         {
  MHASH td;
  unsigned char buffer;
  unsigned char *hash;  

  td = mhash_init(MHASH_MD5);  

  if (td == MHASH_FAILED) exit(1);  

  while (fread(&buffer, 1, 1, stdin) == 1) {
    mhash(td, &buffer, 1);
  }
  hash = (unsigned char *) mhash_end(td);
 
  printf("Hash:");
  for (unsigned int i = 0; i < mhash_get_block_size(MHASH_MD5); ++i) {
    printf("%.2x", hash[i]);
  }
  printf("\n");
  
  exit(0);
}
Пример #25
0
std::string
MD5::md5_string(const std::string& str)
{
  unsigned char hash[16]; /* enough size for MD5 */
  MHASH td = mhash_init(MHASH_MD5);
  if (td == MHASH_FAILED)
  {
    throw std::runtime_error("MD5::md5_string(): Failed to init MHash");
  }
  else
  {  
    mhash(td, str.c_str(), str.length());
  
    mhash_deinit(td, hash);

    // Convert to string representation
    std::ostringstream out;
    for (int i = 0; i < 16; i++) 
      out << std::setfill('0') << std::setw(2) << std::hex << int(hash[i]);

    return out.str();
  }
}
Пример #26
0
uw_Basis_string uw_Hash_sha512(uw_context ctx, uw_Basis_string str) {
  uw_Basis_string hash;
  MHASH td;
  int i;
  unsigned char *buf;

  td = mhash_init(MHASH_SHA512);

  if (td == MHASH_FAILED) 
    uw_error(ctx, FATAL, "uw_Hash_sha512: mhash_init(MHASH_SHA512) failed.");
  
  buf = uw_malloc(ctx, mhash_get_block_size(MHASH_SHA512));
  hash = uw_malloc(ctx, (mhash_get_block_size(MHASH_SHA512) * 2) + 1);

  mhash(td, str, uw_Basis_strlen(ctx, str));
  buf = mhash_end(td);

  for(i = 0; i < mhash_get_block_size(MHASH_SHA512); i++) {
    sprintf((hash + 2*i), "%02x", buf[i]);
  }
  hash[2 * i] = '\0';

  return hash;
}
Пример #27
0
std::string hashMD5 (const char* in) {

  MHASH td;
  unsigned char* p;
  unsigned char *hash;

  td = mhash_init(MHASH_MD5);  

  if (td == MHASH_FAILED) exit(1);  

  for (p = (unsigned char*) in; *p != 0; ++p)
    mhash(td, p, 1);

  hash = (unsigned char *) mhash_end(td);

  std::ostringstream sout;
  sout.unsetf(std::ios::dec); sout.setf(std::ios::hex);
  sout.fill('0');
  for (unsigned int i = 0; i < mhash_get_block_size(MHASH_MD5); i++) {
    sout.width(2); sout << (unsigned int) hash[i];
  }
  
  return sout.str();
}
int main(int argc, char * argv[])
{
	FILE *fp;
	FILE *fp2;
	struct hostent *hp;
	struct sockaddr_in sin;
	char *host; 
	char hashrcv[MAX_LINE];
	char command[10];
	char file_c[10000000];
	char buf[MAX_LINE];
	int length_s[1];
	int length;
	int s;
	int port;
	int len;
	int r_val;
	double rtt;
	double throughput;
	double fsize;
	struct tm * timeinfo;
	struct timeval tb, ta;
	clock_t start_t, end_t, total_t;
	int fd;
	unsigned char buffer;
	unsigned char *computedHash;
	unsigned char *hash;
	unsigned char send_hash[4096];
	int leng = 0;
	int i;
	MHASH td;
	
	// Check if the arguments are appropriate
	if (argc==3)
	{
		host = argv[1];
		port = atoi(argv[2]);
	}
	else
	{
		fprintf(stderr, "usage: simplex-talk host\n");
		exit(1);
	}

	// convert to IP
	hp = gethostbyname(host);
	if (!hp)
	{
		fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
		exit(1);
	}
	
	// Fill in Socket
	bzero((char *)&sin, sizeof(sin));
	sin.sin_family = AF_INET;
	bcopy(hp->h_addr, (char*)&sin.sin_addr, hp->h_length);
	sin.sin_port = htons(port);
	
	// Exit if socket can't be created
	if ((s=socket(PF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("simplex-talk: socket");
		exit(1);
	}
	
	// Exit if Connection refused
	if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
	{
		perror("simplex-talk: connect");
		close(s);
		exit(1);
	}
	
	while (1) 
	{
		bzero((char*)&buf, sizeof(buf));
		bzero((char*)&command, sizeof(command));
		printf("Please enter command--REQ, UPL, LIS, DEL, XIT: ");
		fgets(command, 50, stdin);
		command[strlen(command) - 1] = '\0';
		if (strcmp(command, "REQ") == 0) {
			if (send(s,command,strlen(command) + 1,0)==-1)
			{
				perror("client send error!");
				exit (1);
			} 
			printf("Enter name of file to download from server: ");
			fgets(buf, 50, stdin);
			
			// send name of file to server
			if (send(s, buf, strlen(buf) + 1, 0) == -1) 
			{
				perror("client send error!");
				exit(1);
			}
			buf[strlen(buf) - 1] = '\0';
	
			// Receive the size
			recv(s,length_s,sizeof(length_s), 0);
	
			// if -1, file doesn't exist and exit
			if (length_s[0] == -1)
			{
				perror("File does not exist\n");
				continue;
			}
	
			// File exists=>Receive file hash from server
			else
			{
				recv(s, hashrcv, 33, 0);			
				fp = fopen(buf, "w");			// open requested file to write
      				if (fp == NULL)
      				{
      					exit(1);
      				}
		
				// prepare to receive blocks from the file
				// set remain_data = size of the file
		   		int remain_data = length_s[0];
				int datarcv = 5000;
		
				// if file size is less than default receiving block size
				// set equal to size
				if (remain_data < datarcv) {
					datarcv = remain_data;
				}

				// get time of day before file is received
				gettimeofday(&tb, NULL);
	
				// receive file from server
				bzero((char*)&file_c, sizeof(file_c));
      				while (recv(s, file_c, datarcv, 0) > 0 && (remain_data > 0))
      				{
                			fwrite(file_c, sizeof(char), datarcv, fp);
					bzero((char*)&file_c, sizeof(file_c));
                			remain_data -= datarcv;
					if (remain_data < datarcv) {
						datarcv = remain_data;
					}
					if (remain_data <= 0) break;
      				}
				gettimeofday(&ta, NULL); // time of day after

				int fileSize;
				rewind(fp);
				fclose(fp);
		
				// open file received	
				fp2 = fopen(buf, "r");
		
				// Compute hash
				bzero((char*)&buffer, sizeof(buffer));
				bzero((char*)&computedHash, sizeof(computedHash));
				bzero((char*)&send_hash, sizeof(send_hash));
      				td = mhash_init(MHASH_MD5);
      				if (td == MHASH_FAILED) exit(1);
     	 			while (fread(&buffer, 1, 1, fp2) == 1) {
      					mhash(td, &buffer, 1);
      				}

      				computedHash = mhash_end(td);
				leng = 0;
      				// Fill in computed hash into send_hash
      				for (i = 0; i < mhash_get_block_size(MHASH_MD5); i++) {
            				leng += sprintf(send_hash+leng,"%.2x", computedHash[i]);
      				}
					
				// If the hashes do not match exit
				if ( strcmp(send_hash, hashrcv) != 0) {
					perror("The hash Received does not match the computed hash!\n");
					exit(1);
				}

				// Compute Round trip time
				rtt = ((ta.tv_sec - tb.tv_sec)*1000000L +ta.tv_usec) -tb.tv_usec; 
				rtt /= 1000000;
			}
	
			fsize = (double) length_s[0]/1000000;		// Size in Mb
			throughput = fsize/rtt;						// Throughput 
			printf("%d bytes transferred in %lf seconds.\nThroughput: %lf Megabytes/sec.\nFile MD5sum: %s\n", length_s[0], rtt, throughput, hashrcv);
		} else if (strcmp(command, "DEL") == 0) {
			int fexists;
			if (send(s,command,strlen(command) + 1,0)==-1)
			{
				perror("client send error!");
				exit (1);
			}
			printf("Enter name of file to delete: ");
			fgets(buf, 40, stdin);
		
			// send name of file to server
			if (send(s, buf, strlen(buf) + 1, 0) == -1) {
				perror("client send error!");
				exit(1);
			}
			buf[strlen(buf) - 1] = '\0';
			//printf("buf to delete is %s\n", buf);
			recv(s, &fexists, 4, 0);
			if (fexists) {
				while (1) {
					printf("'Yes' to delete, 'No' to ignore. ");
					bzero((char*)&buf, sizeof(buf));
					fgets(buf, sizeof(buf), stdin);
					buf[strlen(buf) - 1] = '\0';
					if (!strcmp(buf, "Yes")) {
						send(s, buf, strlen(buf) + 1, 0);
						break;
					} else if (!strcmp(buf, "No")) {
						send(s, buf, strlen(buf) + 1, 0);
						break;
					} else {
						continue;
					}
				}
			} else {
				printf("The file does not exist on the server\n");
				continue;
			}
		} else if (!strcmp(command, "UPL")) {
		// ********* UPlOAD ****************
			int ack;
			if (send(s,command,strlen(command) + 1,0)==-1)
			{
				perror("client send error!");
				exit (1);
			}
			while (1) {
				printf("Enter name of file to upload to server: ");
				fgets(buf, 40, stdin);
				buf[strlen(buf) - 1] = '\0';
			
				fp = fopen(buf, "r");
				if (fp != NULL) {
					break;
				}
			}

	
			// send name of file to server
			if (send(s, buf, strlen(buf) + 1, 0) == -1) {
				perror("client send error!");
				exit(1);
			}
			// receive acknowledgement
			recv(s, &ack, 4, 0);
	
			// break if acknowledge is 0
			if (!ack) {
				printf("Server acknowledges 0 because it already has the file\n");
				continue;
			}
		
			// COMPUTE AND SEND FILE SIZE 
			int ex[1];
			//fseek(fp, 0L, SEEK_END);
			//ex[0] = ftell(fp);	
			struct stat st;
			stat(buf, &st);
			int sz = st.st_size;
			ex[0] = sz;
			char *file_c = malloc( ex[0] + 4096 );
			send(s,ex,sizeof(ex),0);
				
			// CALCULATE AND SEND MD5 HASH 
			fp2 = fopen(buf, "r");
			if (fp2 == NULL ) {
				printf("fp2 is NULL: \n", buf);
			}
        		td = mhash_init(MHASH_MD5);
        		if (td == MHASH_FAILED) exit(1);
        		while (fread(&buffer, 1, 1, fp2) == 1) {
                		mhash(td, &buffer, 1);
        		}
        		hash = mhash_end(td);
			bzero((char*)&send_hash, sizeof(send_hash));
			length = 0;
        		for (i = 0; i < mhash_get_block_size(MHASH_MD5); i++) {
               			length += sprintf(send_hash+length,"%.2x", hash[i]);
        		}
			//printf("SENDING HASH: %s\n", send_hash);
			send(s, send_hash, strlen(send_hash)+1, 0);
		
			// READ CONTENTS OF FILE //		
			rewind(fp);	
			fread(file_c, 1, ex[0], fp);		
			//printf("size is %d\n", ex[0]);	

			// SEND FILE TO SERVER /
	 		int offset = 0;
		  	int sent_bytes = 5000;
        		int remain_data = ex[0];
			if (remain_data < sent_bytes) {		// send as one packet
				sent_bytes = remain_data;
			}
        		while (((send(s, file_c + offset,sent_bytes,0)) > 0) && (remain_data > 0))
        		{
                		remain_data -= sent_bytes;
                		offset += sent_bytes;	// keeping track of sent and remaining data
					if (remain_data < sent_bytes) {
						sent_bytes = remain_data;
					}	
        		}
			char results[200];
			recv(s, results, 200, 0);
			printf("%s\n", results);		
		} else if (strcmp(command, "LIS") == 0)
		{
			char files[30];
                        if (send(s,command,strlen(command) + 1,0)==-1)
                        {
                                perror("client send error!");
                                exit (1);
                        }
			while (recv(s, files, sizeof(files), 0) > 0)
			{
				if (strcmp(files, "end") != 0)
				{
					printf("%s\n",files);
		//			bzero((char*)files, sizeof(files));
				}
				else
					break;
			}	
		} else if (strcmp(command, "XIT") == 0) {
			break;
		} else {
			printf("Not a valid command!\n");
			continue;
		}
	} // end while
	printf("Session closed\n");
	close (s);
}
Пример #29
0
Файл: md.c Проект: IFGHou/AIDE
int init_md(struct md_container* md) {
  
  int i;
  /*    First we check the parameter..   */
#ifdef _PARAMETER_CHECK_
  if (md==NULL) {
    return RETFAIL;  
  }
#endif
  error(255,"init_md called\n");
  /*
    We don't have calculator for this yet :)
  */
  md->calc_attr=0;
#ifdef WITH_MHASH
  error(255,"Mhash library initialization\n");
  for(i=0;i<=HASH_MHASH_COUNT;i++) {
    if (((hash_mhash2attr(i)&HASH_USE_MHASH)&md->todo_attr)!=0) {
      DB_ATTR_TYPE h=hash_mhash2attr(i);
      error(255,"inserting %llu\n",h);
      md->mhash_mdh[i]=mhash_init(i);
      if (md->mhash_mdh[i]!=MHASH_FAILED) {
				md->calc_attr|=h;
      } else {
	/*
	  Oops.. 
	  We just don't calculate this.
	 */

				md->todo_attr&=~h;
      }

    } else {
      md->mhash_mdh[i]=MHASH_FAILED;      
    }
  }
#endif 
#ifdef WITH_GCRYPT
  error(255,"Gcrypt library initialization\n");
  	if(!gcry_check_version(GCRYPT_VERSION)) {
		error(0,"libgcrypt version mismatch\n");
		exit(VERSION_MISMATCH_ERROR);
	}
	gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
	if(gcry_md_open(&md->mdh,0,0)!=GPG_ERR_NO_ERROR){
		error(0,"gcrypt_md_open failed\n");
		exit(IO_ERROR);
	}
  for(i=0;i<=HASH_GCRYPT_COUNT;i++) {
    if (((hash_gcrypt2attr(i)&HASH_USE_GCRYPT)&md->todo_attr)!=0) {
      DB_ATTR_TYPE h=hash_gcrypt2attr(i);
      error(255,"inserting %llu\n",h);
			if(gcry_md_enable(md->mdh,i)==GPG_ERR_NO_ERROR){
				md->calc_attr|=h;
			} else {
				error(0,"gcry_md_enable %i failed",i);
				md->todo_attr&=~h;
			}
		}
	}
#endif
  return RETOK;
}
Пример #30
0
ERRORCODE_T Checksum_Calculate(
    const char *pPathname,CHECKSUMTYPE_E Type,const char **ppChecksum)
{
    ERRORCODE_T ErrorCode;
    ERRORCODE_T TempErrorCode;
    unsigned int MHASHType;
    struct stat FileStats;
    MHASH HashData;
    FILE *pFile;
    unsigned int Count;
    unsigned int ReadSize;
    char pReadBuffer[CHECKSUM_READBUFFER_SIZE];
    unsigned char *pHash;


    DEBUGLOG_Printf4("Checksum_Calculate(%p(%s),%u,%p)",
                     pPathname,pPathname,Type,ppChecksum);
    DEBUGLOG_Login();

    /* Parameter checking. */
    if ( (pPathname==NULL) || (ppChecksum==NULL) )
        ErrorCode=ERRORCODE_NULLPARAMETER;
    else if (CHECKSUMTYPE_ISVALID(Type)==0)
        ErrorCode=ERRORCODE_INVALIDPARAMETER;
    else
    {
#if       !defined(USE_MHASH)
        ErrorCode=ERRORCODE_UNSUPPORTED;
#else     /* !defined(USE_MHASH) */
        /* Convert from CHECKSUM_ value to MHASH value. */
        ErrorCode=ERRORCODE_SUCCESS;
        switch(Type)
        {
        case CHECKSUMTYPE_CRC32:
            MHASHType=MHASH_CRC32;
            break;
        case CHECKSUMTYPE_MD5:
            MHASHType=MHASH_MD5;
            break;
        default:
            ErrorCode=ERRORCODE_INVALIDPARAMETER;
            break;
        }

        if (ErrorCode>0)
        {
            /* Get the file size. */
            if (stat(pPathname,&FileStats)==-1)
                ErrorCode=ERRORCODE_SYSTEMFAILURE;
            else
            {
                /* Initialize the hash. */
                HashData=mhash_init(MHASHType);
                if (HashData==MHASH_FAILED)
                    ErrorCode=ERRORCODE_LIBRARYFAILURE;
                else
                {
                    /* Open the file. */
                    pFile=fopen(pPathname,"rb");
                    if (pFile==NULL)
                        ErrorCode=ERRORCODE_SYSTEMFAILURE;
                    else
                    {
                        /* Read the file in chunks, computing the hash on each chunk. */
                        ErrorCode=ERRORCODE_SUCCESS;
                        Count=FileStats.st_size;
                        while( (feof(pFile)==0) && (ferror(pFile)==0) && (Count!=0) )
                        {
                            if (Count>=CHECKSUM_READBUFFER_SIZE)
                                ReadSize=CHECKSUM_READBUFFER_SIZE;
                            else
                                ReadSize=Count;
                            Count-=ReadSize;

                            if (fread(pReadBuffer,ReadSize,1,pFile)!=1)
                            {
                                ErrorCode=ERRORCODE_SYSTEMFAILURE;
                                break;
                            }

                            if (mhash(HashData,pReadBuffer,ReadSize)!=MUTILS_FALSE)
                            {
                                ErrorCode=ERRORCODE_LIBRARYFAILURE;
                                break;
                            }
                        }

                        TempErrorCode=ERRORCODE_SUCCESS;
                        if (fclose(pFile)!=0)
                            TempErrorCode=ERRORCODE_SYSTEMFAILURE;
                        if ( (TempErrorCode<0) && (ErrorCode>0) )
                            ErrorCode=TempErrorCode;
                    }

                    /* Get the hash value. */
                    pHash=mhash_end(HashData);
                    if ( (pHash==NULL) && (ErrorCode>0) )
                        ErrorCode=ERRORCODE_LIBRARYFAILURE;

                    if (ErrorCode>0)
                    {
                        /* Convert the hash value to a string to be returned. */
                        *ppChecksum=malloc(2*mhash_get_block_size(MHASHType)+1);
                        if (*ppChecksum==NULL)
                            ErrorCode=ERRORCODE_SYSTEMFAILURE;
                        else
                            for(Count=0; Count<mhash_get_block_size(MHASHType); Count++)
                                sprintf((char*)&((*ppChecksum)[2*Count]),"%.2x",pHash[Count]);
                    }
                }
            }
        }
#endif    /* !defined(USE_MHASH) */
    }

    DEBUGLOG_Logout();
    return(ErrorCode);
}