Esempio n. 1
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;
}
Esempio n. 2
0
/* test HMAC
 */
int verify_hmac(const void *data, size_t datalen,
	hashid hid, unsigned char *hmac, char *key, int keylen)
{
	MHASH td;
	unsigned char *our_hmac = NULL;
	int rc = -1;

	td = mhash_hmac_init(hid, key, keylen,
		mhash_get_hash_pblock(hid));
	if (!td)
		return -1;

	our_hmac = malloc(mhash_get_block_size(hid));
	if (!our_hmac)
		return -1;

	(void)mhash(td, data, datalen);
	if (mhash_hmac_deinit(td, our_hmac))
		goto out_free;

	rc = memcmp(our_hmac, hmac, mhash_get_block_size(hid));

out_free:
	if (our_hmac)
		free(our_hmac);
	return rc;
}
Esempio n. 3
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);
}
Esempio n. 4
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;
}
Esempio n. 5
0
int checkhash(unsigned char *data, size_t datalen, char *checkhash) {
    char keyword[100];

    memcpy(together + pos, data, datalen);
    pos += datalen;

    mhash_keygen((keygenid)0, (hashid)10, 10, keyword, 100, (void *)"aaaa", 3,  key, keylen);

    MHASH hash = mhash_hmac_init((hashid)10, keyword, 100, mhash_get_hash_pblock((hashid)10));

    mhash(hash, data, datalen);
    void *mac = mhash_hmac_end(hash);

    char hash_printed[1000] = "0x";
    for (int j = 0; j < mhash_get_block_size((hashid)10); j++) {
        unsigned char *m = (unsigned char *)mac;
        char r[3];
        snprintf(r, 3, "%.2x", m[j]);
        strcat(hash_printed, r);
    }

    printf("%s\n", hash_printed);

    return strcmp(hash_printed, checkhash) == 0;
}
Esempio n. 6
0
static unsigned
digest_result_size(PX_MD * h)
{
	MHASH		mh = (MHASH) h->p.ptr;
	hashid		id = mhash_get_mhash_algo(mh);

	return mhash_get_block_size(id);
}
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;
}
Esempio n. 8
0
static int get_digest(void)
{
  if(THIS->res == NULL && THIS->hash != NULL) {
    THIS->res = mhash_end(THIS->hash);
    THIS->hash = NULL;
  }
  if(THIS->res == NULL) {
    Pike_error("No hash result available!\n");
  }
  return mhash_get_block_size(THIS->type);
}
Esempio n. 9
0
int init_hash(void)
{
	digest_len = mhash_get_block_size(HASH_FUNC);
	if (!digest_len)
		return 1;

	if (digest_len == 0 || digest_len > DIGEST_LEN_MAX)
		abort();

	return 0;
}
Esempio n. 10
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;
}
Esempio n. 11
0
static void
initialize_hashid_map (void)
{
  if (hashid_map == 0)
    {
      size_t i = 0;
      size_t j = 0;
      hashid_count = (mhash_count ());
      hashid_map = (OS_malloc ((sizeof (hashid)) * hashid_count));
      while (i <= hashid_count)
	{
	  if ((mhash_get_block_size (i)) != 0)
	    (hashid_map[j++]) = ((hashid) i);
	  i += 1;
	}
    }
}
Esempio n. 12
0
WIN32DLL_DEFINE
void *mhash_hmac_end_m(MHASH td, void *(*hash_malloc) (mutils_word32))
{
    void *digest;

    digest =
        hash_malloc(mhash_get_block_size
                    (td->algorithm_given));

    if (digest == NULL)
    {
        return(NULL);
    }

    mhash_hmac_deinit(td, digest);

    return(digest);
}
Esempio n. 13
0
WIN32DLL_DEFINE
void *mhash_end_m(MHASH td, void *(*hash_malloc) (mutils_word32))
{
    void *digest;
    mutils_word32 size;

    size = mhash_get_block_size( td->algorithm_given);

    digest = mutils_malloc(size);

    if (digest==NULL)
    {
        return NULL;
    }

    mhash_deinit( td, digest);

    return(digest);
}
Esempio n. 14
0
static const char *
vmod_hmac_sha256(const struct vrt_ctx *ctx,
	const char *key,size_t lkey, const char *msg,size_t lmsg,bool raw)
{
	hashid hash = MHASH_SHA256;
	size_t blocksize = mhash_get_block_size(hash);

	char *p;
	char *ptmp;
	p    = WS_Alloc(ctx->ws, blocksize * 2 + 1);
	ptmp = p;

	
	unsigned char *mac;
	unsigned u;
	u = WS_Reserve(ctx->ws, 0);
	assert(u > blocksize);
	mac = (unsigned char*)ctx->ws->f;
	
	int i;
	MHASH td;

	assert(msg);
	assert(key);

	assert(mhash_get_hash_pblock(hash) > 0);

	td = mhash_hmac_init(hash, (void *) key, lkey,
		mhash_get_hash_pblock(hash));
	mhash(td, msg, lmsg);
	mhash_hmac_deinit(td,mac);
	if(raw){
		WS_Release(ctx->ws, blocksize);
		return (char *)mac;
	}
	WS_Release(ctx->ws, 0);
	
	for (i = 0; i<blocksize;i++) {
		sprintf(ptmp,"%.2x",mac[i]);
		ptmp+=2;
	}
	return p;
}
Esempio n. 15
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);
}
Esempio n. 16
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();
}
Esempio n. 17
0
char * map_calculate_hash(struct map * map)
{
  char * rv;

  rv = NULL;
  assert(map != NULL);

  unsigned char * hash;
  int             hash_size;

  hash      = NULL;
  hash_size = 0;
  
#if HAVE_LIBMHASH
  hash_size = mhash_get_block_size(MHASH_MD5);
  hash = malloc(hash_size);
  assert(hash != NULL);
  if(hash != NULL)
    {
      MHASH td;

      td = mhash_init(MHASH_MD5);
      if(td != MHASH_FAILED)
        { /* Hash together all the relevant data. */
          mhash(td, map->cave_name,        strlen(map->cave_name)     );
          mhash(td, &map->level,           sizeof map->level          );
          mhash(td, &map->is_intermission, sizeof map->is_intermission);
          mhash(td, &map->width,           sizeof map->width          );
          mhash(td, &map->height,          sizeof map->height         );
          mhash(td, &map->start_x,         sizeof map->start_x        );
          mhash(td, &map->start_y,         sizeof map->start_y        );
          mhash(td, &map->exit_x,          sizeof map->exit_x         );
          mhash(td, &map->exit_y,          sizeof map->exit_y         );
          mhash(td, &map->diamonds,        sizeof map->diamonds       );
          mhash(td, &map->diamonds_needed, sizeof map->diamonds_needed);
          mhash(td, &map->diamond_score,   sizeof map->diamond_score  );
          mhash(td, &map->time_score,      sizeof map->time_score     );
          mhash(td, map->data,             map->width * map->height   );
          mhash(td, &map->time,            sizeof map->time           );
          mhash(td, &map->ameba_time,      sizeof map->ameba_time     );
          mhash(td, &map->game_speed,      sizeof map->game_speed     );
          
          mhash_deinit(td, hash);
        }
      else
        {
          free(hash);
          hash = NULL;
        }
    }

#elif HAVE_LIBCRYPTO
  MD5_CTX context;

  hash_size = MD5_DIGEST_LENGTH;
  hash = malloc(hash_size);
  assert(hash != NULL);
  if(hash != NULL)
    {
      if(MD5_Init(&context))
        {
          int success;
          
          success             = MD5_Update(&context, map->cave_name,        strlen(map->cave_name)     );
          if(success) success = MD5_Update(&context, &map->level,           sizeof map->level          );
          if(success) success = MD5_Update(&context, &map->is_intermission, sizeof map->is_intermission);
          if(success) success = MD5_Update(&context, &map->width,           sizeof map->width          );
          if(success) success = MD5_Update(&context, &map->height,          sizeof map->height         );
          if(success) success = MD5_Update(&context, &map->start_x,         sizeof map->start_x        );
          if(success) success = MD5_Update(&context, &map->start_y,         sizeof map->start_y        );
          if(success) success = MD5_Update(&context, &map->exit_x,          sizeof map->exit_x         );
          if(success) success = MD5_Update(&context, &map->exit_y,          sizeof map->exit_y         );
          if(success) success = MD5_Update(&context, &map->diamonds,        sizeof map->diamonds       );
          if(success) success = MD5_Update(&context, &map->diamonds_needed, sizeof map->diamonds_needed);
          if(success) success = MD5_Update(&context, &map->diamond_score,   sizeof map->diamond_score  );
          if(success) success = MD5_Update(&context, &map->time_score,      sizeof map->time_score     );
          if(success) success = MD5_Update(&context, map->data,             map->width * map->height   );
          if(success) success = MD5_Update(&context, &map->time,            sizeof map->time           );
          if(success) success = MD5_Update(&context, &map->ameba_time,      sizeof map->ameba_time     );
          if(success) success = MD5_Update(&context, &map->game_speed,      sizeof map->game_speed     );
          
          if(success) success = MD5_Final(hash, &context);

          if(!success)
            {
              free(hash);
              hash = NULL;
            }
        }
      else
        {
          free(hash);
          hash = NULL;
        }
    }
#endif

  if(hash != NULL)
    {
      rv = malloc(hash_size * 2 + 1);
      assert(rv != NULL);
      if(rv != NULL)
        for(int i = 0; i < hash_size; i++)
          sprintf(rv + i * 2, "%.2x", hash[i]);
      free(hash);
    }
  
  return rv;
}
Esempio n. 18
0
WIN32DLL_DEFINE
MHASH mhash_hmac_init(__const hashid type,
                      void *key, mutils_word32 keysize,
                      mutils_word32 block)
{
    MHASH ret = MHASH_FAILED;
    MHASH tmptd;
    mutils_word8 *ipad;
    mutils_word8 _ipad[MAX_BLOCK_SIZE];
    mutils_word32 i;
    mutils_boolean ipad_alloc = MUTILS_FALSE;
    mutils_boolean res;

    if (block == 0)
    {
        block = 64;	/* the default for ripemd,md5,sha-1 */
    }

    ret = mhash_init_int(type);

    if (ret != MHASH_FAILED)
    {
        /* Initial hmac calculations */
        ret->hmac_block = block;

        if ( ret->hmac_block > MAX_BLOCK_SIZE)
        {
            ipad = mutils_malloc(ret->hmac_block);
            if (ipad == NULL)
            {
                return MHASH_FAILED;
            }
            ipad_alloc = MUTILS_TRUE;
        }
        else
        {
            ipad = _ipad;
        }

        if (keysize > ret->hmac_block)
        {
            tmptd = mhash_init(type);
            mhash(tmptd, key, keysize);
            ret->hmac_key_size = mhash_get_block_size(type);
            ret->hmac_key = mhash_end(tmptd);
        }
        else
        {
            ret->hmac_key = mutils_malloc(ret->hmac_block);
            mutils_bzero(ret->hmac_key, ret->hmac_block);
            mutils_memcpy(ret->hmac_key, key, keysize);
            ret->hmac_key_size = ret->hmac_block;
        }

        /* IPAD */

        for (i = 0; i < ret->hmac_key_size; i++)
        {
            ipad[i] = (0x36) ^ ret->hmac_key[i];
        }

        for (; i < ret->hmac_block; i++)
        {
            ipad[i] = (0x36);
        }

        res = mhash(ret, ipad, ret->hmac_block);

        if (ipad_alloc == MUTILS_TRUE)
        {
            mutils_free(ipad);
        }
    }

    return(ret);
}
int main(int argc, char* argv[])
{
	FILE *fp;
	struct sockaddr_in sin;
	char buf[MAX_LINE];
	int len;
	int port;
	int s, new_s,i;
	int opt = 1;
	MHASH td;
        unsigned char buffer;
        unsigned char *hash;
        unsigned char send_hash[256];
	char hashrcv[40];
	char packet[100];
        int length = 0;
	time_t rawtime;
	FILE *fp2;
	unsigned char symlink[100];
	char fname[40];
	int length_s[2];
	char file_c[10000000];
	struct tm * timeinfo;
	struct timeval tb, ta;
	int leng = 0;
	double rtt, fsize, throughput;
	unsigned char *computedHash;
	
	/* ENSURE PROPER ARGUMENT STRUCTURE */
	if (argc == 2)
	{
		port = atoi(argv[1]);
	}
	else
	{
		perror("Needs port number as argument\n");
		exit(1);
	}

	/* FILLING SOCKADDR_IN STRUCT */
	bzero((char*)&sin, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(port);

	/* SOCKET CREATION */
	if((s=socket(PF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("simplex-talk:socket");
		exit(1);
	}

	/* ENABLE OPTION TO REUSE SOCKET */
	if((setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)& opt, sizeof(int))) < 0)
	{
		perror("simplex-talk:setsocket\n");
		exit(1);
	}

	/* BIND SOCKET */
	if ((bind(s,(struct sockaddr *)&sin, sizeof(sin))) < 0)
	{
		perror("simplex-talk:bind\n");
		exit(1);
	}

	/* LISTEN TO SOCKET */
	if ((listen(s, MAX_PENDING))<0)
	{
		perror ("simplex-talk:listen");
		exit(1);
	}
	
	while(1)
	{
		if ((new_s = accept(s,(struct sockaddr *)&sin, &len)) < 0)
		{
			perror("simplex-talk:accept");
			exit(1);
		}
		printf("Waiting for operation from client...\n");
		while(1)
		{
			bzero((char*)&buf, sizeof(buf));
			/* ACCEPT AND MAKE NEW SOCKET */
			if ((len=recv(new_s, buf, sizeof(buf),0)) == -1)
			{
				perror("Server Receiving Error!\n");
				exit(1);	
			}
			if (len == 0)
			{
				break;
			}
			if (strcmp(buf, "REQ") == 0) {
				bzero((char*)&buf, sizeof(buf));
				if ((len=recv(new_s, buf, sizeof(buf), 0)) == -1) {
					perror("Server Receiving Error!\n");
					exit(1);
				} 
				buf[strlen(buf) - 1] = '\0';

				// concat with path to test files
				bzero((char*)&symlink, sizeof(symlink));
				strcpy(symlink,"Prog3TestFiles/");
				strcat(symlink,buf);
				strcpy(buf, symlink);

				/* OPEN FILE FROM FILE NAME SENT TO SERVER */
				fp = fopen(buf, "r");
				if (fp == NULL)
				{
					int fne[1];
					fne[0] = -1;
					send(new_s,fne,4,0);
				}
				else
				{
					/* COMPUTE AND SEND FILE SIZE */
					int ex[1];	
					struct stat st;
					stat(buf, &st);
					int sz = st.st_size;
					ex[0] = sz;
					char *file_c = malloc( ex[0] + 4096 );
					send(new_s,ex,sizeof(ex),0);

					/* CALCULATE AND SEND MD5 HASH */
					fp2 = fopen(buf, "r");
        				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]);
        				}
					send(new_s, send_hash, strlen(send_hash)+1, 0);
		
					/* READ CONTENTS OF FILE */		
					rewind(fp);	
					fread(file_c, 1, ex[0], fp);			

					/* SEND FILE TO CLIENT */
		  			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(new_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;
							}	
        				}
				} 
			}// end REQ if
			// delete command
			else if (strcmp(buf, "DEL") == 0) {
				int fexists;
				if ((len=recv(new_s, buf, sizeof(buf), 0)) == -1) {
					perror("Server Receiving Error!\n");
					exit(1);
				} 
				buf[strlen(buf) - 1] = '\0';
				strcpy(fname, buf);
				fp = fopen(buf, "r");
				// check if file exists
				if (fp == NULL) 
					 fexists = 0;
				else
					 fexists = 1;
				// send whether the file exists or not
				send(new_s, &fexists, 4, 0);
	
				// receive confirmation of delete
				bzero((char *)&buf, sizeof(buf));
				recv(new_s, buf, sizeof(buf), 0);
				
				if (!strcmp(buf, "Yes")) {
					remove(fname);
				} 

			} else if (!strcmp(buf, "UPL")) {
				int ack;
				bzero((char*)&buf, sizeof(buf));
				if ((len=recv(new_s, buf, sizeof(buf), 0)) == -1) {
					perror("Server Receiving Error!\n");
					exit(1);
				} 
				fp = fopen(buf, "r");
				if (fp != NULL) {
					ack = 0;
					continue;
				} else {
					ack = 1;
				}
						
				// send ack
				send(new_s, &ack, 4, 0);
			
				// receive size of file
				recv(new_s, length_s, sizeof(length_s), 0);
	
				// receive hash
				recv(new_s, hashrcv, 33, 0);	
					
				fp = fopen(buf, "w");			// open requested file to write
			
      				if (fp == NULL)
      				{
					printf("fp is null\n");
      					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(new_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");
				if (fp2 == NULL) {
					printf("fp2 is null\n");
					exit(1);	
				}
		
				// 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
				char results[300]; 
				sprintf(results,"%d bytes transferred in %lf seconds.\nThroughput: %lf Megabytes/sec.\nFile MD5sum: %s", length_s[0], rtt, throughput, hashrcv);
				send(new_s, results, 300, 0);
			} else if (strcmp(buf, "LIS") == 0)
			{
				DIR *dirp; 
				struct dirent *dp;
				char contents[30];
				dirp = opendir(".");
				while((dp = readdir(dirp)) != NULL) 
				{
                               		sprintf(contents, dp->d_name);
			        	send(new_s, contents,30, 0);
           			}
				strcpy(contents, "end");
				send(new_s, contents, sizeof(contents), 0);
				closedir(dirp);
			}else if (strcmp(buf, "XIT") == 0) {
				break;
			}
			else {
				printf("not a valid command!\n");
			}
						
		}
		close(new_s);
	}
}
int main(void) {

	int i, buf_len;
	MHASH td1, td2, td3;
	const unsigned char *buf = "This is a test buffer to test saving and restoring, see?";
	unsigned char *hash1, *hash2;
	hashid alg;
	char mem[1024];
	int mem_size = sizeof(mem);

	buf_len = strlen(buf);

	/* NOTE: For laziness sake, I just loop through the enum, skipping invalid integers.
	   If the enum should change, this loop will have to change! */
	for (alg = 0; alg <= mhash_count(); ++alg) {
		
		/* if algorithm does not exist */
		if (mhash_get_hash_name_static( alg)==NULL)
			continue;

		printf("Testing save/restore for algorithm %s: ", mhash_get_hash_name(alg));

		td1 = mhash_init(alg);

		if (td1 == MHASH_FAILED) {
			fprintf(stderr, "Failed to init td1.\n");
			exit(1);
		}

		for (i = 0; i < buf_len; ++i)
			mhash(td1, buf+i, 1);

		hash1 = mhash_end(td1);

/*		printf("Hash 1: ");
		for (i = 0; i < mhash_get_block_size(alg); ++i)
			printf("%.2x", hash1[i]);
		printf("\n");
*/
		td2 = mhash_init(alg);

		if (td2 == MHASH_FAILED) {
			fprintf(stderr, "Failed to init td2.\n");
			exit(1);
		}

		for (i = 0; i < buf_len/2; ++i)
			mhash(td2, buf+i, 1);

		if (mhash_save_state_mem(td2, mem, &mem_size)!=0) {
			fprintf(stderr, "Error saving state. Size: %d\n", mem_size);
			exit(1);
		}

		td3 = mhash_restore_state_mem( mem);

		if (td3 == MHASH_FAILED) {
			fprintf(stderr, "Error restoring state.\n");
			exit(1);
		}

		for (i = buf_len/2; i < buf_len; ++i)
			mhash(td3, buf+i, 1);

		hash2 = mhash_end(td3);

/*		printf("Hash 2: ");
		for (i = 0; i < mhash_get_block_size(alg); ++i)
			printf("%.2x", hash2[i]);
		printf("\n");
*/
		if (memcmp(hash1, hash2, mhash_get_block_size(alg)) == 0) {
			printf("Ok\n");
		} else {
			printf("Failed\n");
			exit(1);
		}
	}
	exit(0);
}
Esempio n. 21
0
int main (int argc, char **argv)
{
  // establish necessary variables here
  int sockfd, n;		// socket and received buffer length

  if (argc != 4)
    {
      printf ("Incorrect Arguments!\n");
      printf ("usage: client <host> <port> <filename>\n");
      exit (1);
    }

  if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      printf ("Error creating socket\n");
      exit (1);
    }

  // to convert host name (returns original IP or hostname converted to IP)
  char *host = hostname_to_ip (argv[1]);

  // set up all the network stuff
  struct sockaddr_in servaddr, cliaddr;
  bzero (&servaddr, sizeof (servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = inet_addr (host);
  servaddr.sin_port = htons (atoi (argv[2]));

  if (connect (sockfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) ==
      -1)
    {
      printf ("Error creating a connection with the server\n");
      exit (1);
    }

  /* send the message to the server */
  short int length = htons (strlen (argv[3]));
  n = write (sockfd, &length, sizeof (length));
  n = write (sockfd, argv[3], strlen (argv[3]));

  int file_size;
  n = read (sockfd, &file_size, sizeof (file_size));
  if (n < 0)
    error ("ERROR reading from socket");
  file_size = ntohl (file_size);
  //printf("Response read from the server: %d\n", file_size);

  if (file_size == 0)
    {
      printf ("File does not exist on the server\n");
      exit (1);
    }

  unsigned char server_hash[16];
  n = read (sockfd, &server_hash, sizeof (server_hash));
  if (n < 0)
    error ("ERROR reading from socket");

  int i;
	/*
  printf ("Server Hash: ");
  for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
      printf ("%.2x", server_hash[i]);
    }
  printf ("\n");
	 */

  FILE *file;
  file = fopen (argv[3], "w+");
  if (file == NULL)
    {
      printf ("Could not open file\n");
      exit (1);
    }

  char output[BUF_LEN];
  bzero (output, BUF_LEN);
  int downloaded = 0;
  int buffer_size;
  struct timeval start;
  struct timeval finish;
  gettimeofday(&start,NULL);
  while (downloaded < file_size)
    {
	  if ((file_size-downloaded)>=BUF_LEN)
	  {
		  buffer_size=BUF_LEN;
	  }else{
		  buffer_size=(file_size-downloaded);
	  }
      n = read (sockfd, output, buffer_size);
      fwrite (output, sizeof (char), buffer_size, file);
      bzero (output, buffer_size);
      downloaded += buffer_size;
    }
  gettimeofday(&finish,NULL);
	long microsecs_elapsed = ((finish.tv_sec - start.tv_sec)*1000000L
						  +finish.tv_usec) - start.tv_usec;
	float time_elapsed = (float)microsecs_elapsed/1000000;

  rewind (file);

	MHASH td;
	unsigned char buffer;
	unsigned char client_hash[16];
	
	td = mhash_init (MHASH_MD5);
	
	while (fread (&buffer, 1, 1, file) == 1)
    {
		mhash (td, &buffer, 1);
    }
	mhash_deinit (td, client_hash);

	/*
  printf ("Client Hash: ");
  for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
      printf ("%.2x", client_hash[i]);
    }
  printf ("\n");
	 */
	 
  fclose (file);

  if (compare_hash (server_hash, client_hash) == 0)
    {
      printf ("File transfer was unsuccessful\n");
      remove (argv[3]);
      exit (1);
    }
	
  printf("%d bytes transferred in %.6f seconds: %.6f MB/sec\n",file_size,time_elapsed,
		 (float)(file_size/1048576)/time_elapsed);
	printf("File MD5sum: ");
	for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
		printf ("%.2x", client_hash[i]);
    }
	printf ("\n");

  close (sockfd);
  return 0;
}
Esempio n. 22
0
int main(void)
{
	mutils_word32 i;
	mutils_word32 buf_len;
	MHASH td1, td2, td3;
	const mutils_word8 *buf = (mutils_word8 *) "This is a test buffer to test saving and restoring, see?";
	mutils_word8 *hash1;
	mutils_word8 *hash2;
	hashid alg;
	mutils_word8 mem[1024];
	mutils_word32 mem_size = sizeof(mem);

	buf_len = mutils_strlen(buf);

	/*
	 * NOTE: For laziness sake, I just loop through the enum,
	 * skipping invalid integers.
	 *
	 * If the enum should change, this loop will have to change!
	 */

	for (alg = 0; alg <= mhash_count(); ++alg)
	{
		/* if algorithm does not exist */
	  if (mhash_get_hash_name_static(alg) == (mutils_word8 *) NULL)
			continue;

		printf("Testing save/restore for algorithm %s: ", mhash_get_hash_name(alg));

		td1 = mhash_init(alg);

		if (td1 == MHASH_FAILED)
		{
			fprintf(stderr, "Failed to init td1.\n");
			exit(MUTILS_INVALID_FUNCTION);
		}

		for (i = 0; i < buf_len; ++i)
		{
			mhash(td1, buf+i, 1);
		}

		hash1 = mhash_end(td1);

		td2 = mhash_init(alg);

		if (td2 == MHASH_FAILED)
		{
			fprintf(stderr, "Failed to init td2.\n");
			exit(MUTILS_INVALID_FUNCTION);
		}

		for (i = 0; i < buf_len/2; ++i)
		{
			mhash(td2, buf+i, 1);
		}

		if (mhash_save_state_mem(td2, mem, &mem_size)!=0)
		{
			fprintf(stderr, "Error saving state. Size: %d\n", mem_size);
			exit(MUTILS_INVALID_RESULT);
		}

		td3 = mhash_restore_state_mem( mem);

		if (td3 == MHASH_FAILED)
		{
			fprintf(stderr, "Error restoring state.\n");
			exit(MUTILS_INVALID_RESULT);
		}

		for (i = buf_len/2; i < buf_len; ++i)
		{
			mhash(td3, buf+i, 1);
		}

		hash2 = mhash_end(td3);

		if (mutils_memcmp(hash1, hash2, mhash_get_block_size(alg)) == 0)
		{
			printf("Ok\n");
		}
		else
		{
			printf("Failed\n");
			exit(MUTILS_INVALID_RESULT);
		}
	}
	exit(MUTILS_OK);
}
Esempio n. 23
0
int main()
{

	mutils_word8 *tmp;
	mutils_word8 *password;
	mutils_word32 passlen;
	mutils_word8 *data;
	mutils_word32 datalen;
	MHASH td;
	mutils_word8 *mac;
	mutils_word32 j;
	int result;

	passlen=sizeof(KEY1) - 1;
	password = mutils_malloc(passlen + 1);
	mutils_memcpy(password, (mutils_word8 *) KEY1, passlen);

	datalen = mutils_strlen((mutils_word8 *) DATA1);
	data = mutils_malloc(datalen+1);
	mutils_strcpy(data, (mutils_word8 *) DATA1);

	td = mhash_hmac_init(MHASH_MD5, password, passlen,
			    mhash_get_hash_pblock(MHASH_MD5));

	mhash(td, data, datalen);
	mac = mhash_hmac_end(td);

	tmp = mutils_asciify(mac, mhash_get_block_size(MHASH_MD5));
	
	result = mutils_strcmp((mutils_word8 *) DIGEST1, tmp);

	mutils_free(password);
	mutils_free(data);

	if (result != 0) {
		fprintf(stderr, "HMAC-Test: Failed\n");
		fprintf(stderr, "Digest size: %d\n", mhash_get_block_size(MHASH_MD5));
		fprintf(stderr, "Expecting: 0x%s\n", DIGEST1);
		fprintf(stderr, "Got: 0x%s\n", tmp);
		return(MUTILS_INVALID_RESULT);
	}

	mutils_free(tmp);

	/* Test No 2 */	
	
	mutils_memset(tmp, 0, sizeof(tmp));
	
	passlen=sizeof(KEY2) - 1;
	password = (mutils_word8 *) mutils_malloc(passlen+1);
	mutils_memcpy(password, KEY2, passlen);
	
	datalen = mutils_strlen((mutils_word8 *) DATA2);
	data = (mutils_word8 *) mutils_malloc(datalen+1);
	mutils_strcpy(data, (mutils_word8 *) DATA2);

	td = mhash_hmac_init(MHASH_MD5, password, passlen,
			    mhash_get_hash_pblock(MHASH_MD5));

	mhash(td, data, datalen);
	mac = mhash_hmac_end(td);

	tmp = mutils_asciify(mac, mhash_get_block_size(MHASH_MD5));
	
	result = mutils_strcmp((mutils_word8 *) DIGEST2, tmp);

	mutils_free(password);
	mutils_free(data);

	if (result != 0)
	{
		fprintf(stderr, "HMAC-Test: Failed\n");
		fprintf(stderr, "Expecting: 0x%s\nGot: 0x%s\n", DIGEST2, tmp);
		return(MUTILS_INVALID_RESULT);
	}

	fprintf(stderr, "MD5 HMAC-Test: Ok\n");

	mutils_free(tmp);

	return(MUTILS_OK);
}
Esempio n. 24
0
WIN32DLL_DEFINE
mutils_error mhash_hmac_deinit(MHASH td, void *result)
{
    mutils_word8 *opad;
    mutils_word8 _opad[MAX_BLOCK_SIZE];
    MHASH tmptd;
    mutils_word32 i;
    mutils_word32 opad_alloc = 0;

    if (td->hmac_block > MAX_BLOCK_SIZE)
    {
        opad = mutils_malloc(td->hmac_block);
        if (opad == NULL)
        {
            return(-MUTILS_SYSTEM_RESOURCE_ERROR);
        }
        opad_alloc = 1;
    }
    else
    {
        opad = _opad;
    }


    for (i = 0; i < td->hmac_key_size; i++)
    {
        opad[i] = (0x5C) ^ td->hmac_key[i];
    }

    for (; i < td->hmac_block; i++)
    {
        opad[i] = (0x5C);
    }

    tmptd = mhash_init(td->algorithm_given);
    mhash(tmptd, opad, td->hmac_block);

    if (td->final_func != NULL)
    {
        td->final_func(td->state);
    }

    if (td->deinit_func != NULL)
    {
        td->deinit_func(td->state, result);
    }

    if (result != NULL)
    {
        mhash(tmptd, result,
              mhash_get_block_size(td->algorithm_given));
    }

    mutils_free(td->state);

    if (opad_alloc!=0)
    {
        mutils_free(opad);
    }

    mutils_bzero(td->hmac_key, td->hmac_key_size);
    mutils_free(td->hmac_key);
    mutils_free(td);

    mhash_deinit(tmptd, result);

    return(MUTILS_OK);
}
Esempio n. 25
0
int frag_test(hashid hashid)
{
  unsigned char digest1[MAX_DIGEST_SIZE]; /* enough space to hold digests */
  unsigned char digest2[MAX_DIGEST_SIZE];
  unsigned char buf1[MAX_INPUT_SIZE + 1];
  unsigned char buf2[MAX_INPUT_SIZE];
  MHASH td1, td2;
  size_t input_size, digest_size;
  int i, offs, left;
  unsigned char val = 0;

  input_size = mhash_get_hash_pblock(hashid);
  assert(input_size <= MAX_INPUT_SIZE);

  digest_size = mhash_get_block_size(hashid);
  assert(digest_size <= MAX_DIGEST_SIZE);

  td1 = mhash_init(hashid);               /* get two mhash instances */
  td2 = mhash_init(hashid);

  for(i = offs = 0; i < 2 * input_size; i++, val++) /* first part */
    {
      memset(buf1, val, input_size + 1);  /* the first instance gets framgments */
      mhash(td1, buf1, input_size + 1);   /* of size (input_size+1)             */

      left = input_size - offs;           /* the second instance gets fragments */
      memset(buf2 + offs, val, left);     /* of size input_size                 */
      mhash(td2, buf2, input_size);

      offs = (input_size + 1) - left;
      memset(buf2, val, offs);
      if (offs == input_size)
	{
	  mhash(td2, buf2, input_size);
	  offs = 0;
	}
    }
  mhash(td2, buf2, offs);

  for(i = offs = 0; i < 2 * input_size; i++, val++) /* second part */
    {
      memset(buf1, val, input_size - 1);  /* the first instance gets framgments */
      mhash(td1, buf1, input_size - 1);   /* of size (input_size-1)             */
      
      if (offs == 0)                      /* the second instance gets fragments */
	{                                 /* of size input_size                 */
	  offs = input_size - 1;
	  memset(buf2, val, offs);
	}
      else
	{
	  left = input_size - offs;
	  memset(buf2 + offs, val, left);

	  mhash(td2, buf2, input_size);
	  offs = (input_size - 1) - left;
	  memset(buf2, val, offs);
	}
    }
  mhash(td2, buf2, offs);

  mhash_deinit(td1, digest1);   /* return 1 if the calculated hash values match */
  mhash_deinit(td2, digest2);
  return ! strncmp(digest1, digest2, digest_size);
}
Esempio n. 26
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);
}
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);
}
Esempio n. 28
0
File: db_sql.c Progetto: po1vo/aide
char* db_get_sql(db_line* line,db_config* dbconf){
  
  int i;
  char* s=(char*) malloc(sizeof(char)*10240); /* FIXME .. */

  if (s==NULL) {
    error(0,"\nCannot allocate memory..\n");
    abort();
  }
  
  s[0]=0;

  /* Insertion was hardcoded into aide-table, now we will use the
     provided name from the configfile */
  
  s = strcat(s,"INSERT INTO ");
  s = strcat(s, ((psql_data*)dbconf->db_out)->table);
  s = strcat(s," values(");
  
  for(i=0;i<dbconf->db_out_size;i++){
    switch (dbconf->db_out_order[i]) {
    case db_filename : {
      char* tmp;
      if ( i!=0 ) {
	s = strcat(s,",");
      }
      strcat(s,"'");
      tmp=encode_string(line->filename);
      s = strcat(s,tmp);
      free(tmp);
      strcat(s,"'");
      break;
    }
    case db_linkname : {
      if ( i!=0 ) {
	s = strcat(s,",");
      }
      strcat(s,"'");
      if (line->linkname != NULL) {
	char* tmp;
	tmp=encode_string(line->linkname);
	s = strcat(s,tmp);
	free(tmp);
      }
      strcat(s,"'");
      break;
    }  
    case db_attr : {
      sql_writeint(line->attr,s,i);
      break;
    }
    case db_bcount : {
      sql_writeint(line->bcount,s,i);
      break;
    }
    
    case db_mtime : {
      sql_write_time_base64(line->mtime,s,i);
      break;
    }
    case db_atime : {
      sql_write_time_base64(line->atime,s,i);
      break;
    }
    case db_ctime : {
      sql_write_time_base64(line->ctime,s,i);
      break;
    }
    case db_inode : {
      sql_writeint(line->inode,s,i);
      break;
    }
    case db_lnkcount : {
      sql_writeint(line->nlink,s,i);
      break;
    }
    case db_uid : {
      sql_writeint(line->uid,s,i);
      break;
    }
    case db_gid : {
      sql_writeint(line->gid,s,i);
      break;
    }
    case db_size : {
      sql_writeint(line->size,s,i);
      break;
    }
    case db_md5 : {
      sql_write_byte_base64(line->md5,
			   gcry_md_get_algo_dlen(GCRY_MD_MD5),s,i);
      break;
    }
    case db_sha1 : {
      sql_write_byte_base64(line->sha1,
			   gcry_md_get_algo_dlen(GCRY_MD_SHA1),s,i);
      break;
    }
    case db_rmd160 : {
      sql_write_byte_base64(line->rmd160,
			   gcry_md_get_algo_dlen(GCRY_MD_RMD160),
			   s,i);
      break;
    }
    case db_tiger : {
      sql_write_byte_base64(line->tiger,
			   gcry_md_get_algo_dlen(GCRY_MD_TIGER),
			   s,i);
      break;
    }
    case db_perm : {
      sql_writeint(line->perm,s,i);
      break;
    }
#ifdef WITH_MHASH
    case db_crc32 : {
      sql_write_byte_base64(line->crc32,
			   mhash_get_block_size(MHASH_CRC32),
			   s,i);
      break;
    }
    case db_crc32b : {
      sql_write_byte_base64(line->crc32b,
			   mhash_get_block_size(MHASH_CRC32B),
			   s,i);
      break;
    }
    case db_haval : {
      sql_write_byte_base64(line->haval,
			   mhash_get_block_size(MHASH_HAVAL256),
			   s,i);
      break;
    }
    case db_gost : {
      sql_write_byte_base64(line->gost ,
			   mhash_get_block_size(MHASH_GOST),
			   s,i);
      break;
    }
#endif
    case db_acl : {
      error(0,"TODO db_acl write to db_sql.c");
      /* TODO */
      break;
    }
    case db_xattrs : {
      error(0,"TODO db_xattrs write to db_sql.c");
      /* TODO */
      break;
    }
    case db_checkmask : {
      sql_writeoct(line->attr,s,i);
      break;
    }
    default : {
      error(0,"Not implemented in sql_writeline_file %i\n",
	    dbconf->db_out_order[i]);
      return NULL;
    }
    
    }
    
  }

  strcat(s,");");

  return s;
}