Exemplo n.º 1
0
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
    char payload[1024],buf[1024],url[1024],digest[512],pairstr[512],pricestr[64],*extra,*typestr;
    cJSON *json; uint64_t txid = 0;
    if ( (extra= *retstrp) != 0 )
        *retstrp = 0;
    if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
    {
        printf("cant find baserel (%s/%s)\n",base,rel);
        return(0);
    }
    if ( extra != 0 && strcmp(extra,"market") == 0 )
        typestr = (dir > 0) ? "buy_market" : "sell_market", sprintf(pricestr,"&price=%.2f",price); // docs say market orders put volume in price
    else typestr = (dir > 0) ? "buy" : "sell";
    sprintf(pricestr,"&price=%.2f",price);
    sprintf(buf,"amount=%.4f&api_key=%s%ssymbol=%s&type=%s&secret_key=%s",volume,exchange->apikey,pricestr,pairstr,typestr,exchange->apisecret);
    calc_md5(digest,buf,(int32_t)strlen(buf));
    touppercase(digest);
    sprintf(payload,"amount=%.4f&api_key=%s%s&symbol=%s&type=%s&sign=%s",volume,exchange->apikey,pricestr,pairstr,typestr,digest);
    sprintf(url,"%s/%s",EXCHANGE_AUTHURL,"trade.do");
    if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,url,payload)) != 0 )
    {
        txid = j64bits(json,"order_id");
        free_json(json);
    }
    return(txid);
}
Exemplo n.º 2
0
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
    char url[1024],req[1024],md5secret[128],tmp[1024],dest[1025],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*sig,*data = 0;
    cJSON *json; uint64_t nonce;
    hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
    json = 0;
    nonce = exchange_nonce(exchange) * 1000 + ((uint64_t)milliseconds() % 1000);
    sprintf(tmp,"%llu%s%s",(long long)nonce,exchange->userid,exchange->apikey);
    calc_md5(md5secret,exchange->apisecret,(int32_t)strlen(exchange->apisecret));
    if ( (sig= hmac_sha256_str(dest,md5secret,(int32_t)strlen(md5secret),tmp)) != 0 )
    {
        sprintf(req,"{\"key\":\"%s\",%s\"nonce\":%llu,\"signature\":\"%s\"}",exchange->apikey,payload,(long long)nonce,sig);
        sprintf(hdr1,"Content-Type:application/json");
        sprintf(hdr2,"charset=utf-8");
        sprintf(hdr3,"Content-Length:%ld",(long)strlen(req));
        sprintf(url,"https://api.quadrigacx.com/v2/%s",path);
        if ( dotrade == 0 )
            data = exchange_would_submit(req,hdr1,hdr2,hdr3,hdr4);
        else if ( (data= curl_post(cHandlep,url,0,req,hdr1,hdr2,hdr3,hdr4)) != 0 )
            json = cJSON_Parse(data);
    }
    if ( retstrp != 0 )
        *retstrp = data;
    else if ( data != 0 )
        free(data);
    return(json);
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
	FILE *fp;
	PE_FILE pe;
	unsigned char *data;
	size_t pesize = 0;

	if (argc < 2)
	{
		usage();
		exit(1);
	}

	parse_options(argc, argv);

	if ((fp = fopen(argv[argc-1], "rb")) == NULL)
		EXIT_ERROR("file not found or unreadable");

	pe_init(&pe, fp);
	fseek(pe.handle, 0, SEEK_END);
	pesize = ftell(pe.handle);
	rewind(pe.handle);
	data = (unsigned char *) xmalloc(pesize + 1);
	fread(data, pesize, 1, pe.handle);

	if (config.md5 || config.all)
	{
		char md5_sum[(MD5_DIGEST_LENGTH*2) + 1];

		calc_md5(data, pesize, md5_sum);
		output("md5", md5_sum);
	}

	if (config.sha1 || config.all)
	{
		char sha1_sum[((SHA_DIGEST_LENGTH*2)+1)];

		calc_sha1(data, pesize, sha1_sum);
		output("sha-1", sha1_sum);
	}


	if (config.sha256 || config.all)
	{
		char sha256_sum[((SHA256_DIGEST_LENGTH*2)+1)];

		calc_sha256(data, pesize, sha256_sum);
		output("sha-256", sha256_sum);
	}

	pe_deinit(&pe);
	free(data);
	return 0;
}
Exemplo n.º 4
0
cJSON *huobi_issue_auth(struct exchange_info *exchange,char *method,char *buf)
{
    char payload[1024],digest[33],tmp[1024]; uint64_t nonce;
    nonce = exchange_nonce(exchange);
    sprintf(tmp,"access_key=%s&created=%llu&method=%s%s",exchange->apikey,(long long)nonce,method,buf);
    sprintf(payload,"%s&secret_key=%s",tmp,exchange->apisecret);
    //printf("tmp.(%s) payload.(%s)\n",tmp,payload);
    calc_md5(digest,payload,(int32_t)strlen(payload));
    sprintf(payload,"%s&sign=%s",tmp,digest);
    //printf("-> (%s)\n",payload);
    return(SIGNPOST(0,exchange,payload));
}
Exemplo n.º 5
0
cJSON *okcoin_issue_auth(void **cHandlep,struct exchange_info *exchange,char *method,char *buf)
{
    char payload[1024],tmp[1024],digest[512],url[512];
    sprintf(tmp,"api_key=%s%s",exchange->apikey,buf);
    
    sprintf(payload,"%s&secret_key=%s",tmp,exchange->apisecret);
    //printf("tmp.(%s) payload.(%s)\n",tmp,payload);
    calc_md5(digest,payload,(int32_t)strlen(payload));
    touppercase(digest);
    sprintf(payload,"%s&sign=%s",tmp,digest);
    sprintf(url,"%s/%s",EXCHANGE_AUTHURL,method);
    return(SIGNPOST(cHandlep,1,0,exchange,url,payload));
}
Exemplo n.º 6
0
/*
 * md5ファイルの中と対象ファイルのmd5を突き合わせる
 */
int check_md5(const kjm::_tstring& fname, const kjm::cmdLine& cmd) {
	int file_cnt = 0;
	int ng_cnt = 0;
	bool result = false;
	kjm::cfile file;
	if (file.open(fname, _T("r"))) {
		kjm::_tstring lineBuf;

		while (file.getline(lineBuf) == 0) {
			kjm::_tstrings cols = kjm::util::split(lineBuf, ' ');

			//_tprintf(_T("%s\n"), lineBuf.c_str());
			//_tprintf(_T("%d\n"), cols.size());
			
			if (cols.size() == 2) {
				// cols[0] が md5
				// cols[1] が ファイル名のハズ

				//_tprintf(_T("%s\n"), cols[1].c_str());
				kjm::_tstring fname = (cols[1].at(0) == '*' ? cols[1].substr(1) : cols[1]);
				kjm::_tstring md5 = calc_md5(fname, (cmd.hasOption(_T("status")) ? false : true));
				//_tprintf(_T("%s\n"), md5.c_str());

				++file_cnt;
				if (cols[0] == md5) {
					if (cmd.hasOption(_T("status")) == false && cmd.hasOption(_T("quiet")) == false) {
						_tprintf(_T("%s: 完了\n"), fname.c_str());
					}
				} else {
					++ng_cnt;
					if (cmd.hasOption(_T("status")) == false) {
						_tprintf(_T("%s: %s\n"), fname.c_str(), (md5.empty() ? _T("オープンまたは読み込みに失敗しました") : _T("失敗")));
					} else {
						// status 指定の時は、一つ異常が見つかれば、即終了
						break;
					}
				}
			}
		}
		file.close();

		if (cmd.hasOption(_T("status")) == false && ng_cnt > 0) {
			_tprintf(_T("md5sum: WARNING: %d of %d computed %s did NOT match\n"),
				ng_cnt, file_cnt, (file_cnt > 1 ? _T("checksums") : _T("checksum")) );
		}
	}

	return ng_cnt;
}
Exemplo n.º 7
0
// main 処理
void get_md5(const kjm::_tstring& fname, const kjm::cmdLine& cmd) {
	
	// output オプションが指定されているときは、進捗報告を行う。
	bool verbose = cmd.hasOption(_T("output"));

	kjm::_tstring md5 = calc_md5(fname, verbose);

	_tprintf(_T("%s %c%s\n"), md5.c_str(), (g_binaryMode ? '*' : ' '), fname.c_str());

	// oputput オプションが指定されているときは、指定ファイルにも追記する
	if (cmd.hasOption(_T("output"))) {
		FILE* fp = _tfopen(cmd.getOptArgument(_T("output")).c_str(), _T("a+"));
		if (fp) {
			_ftprintf(fp, _T("%s %c%s\n"), md5.c_str(), (g_binaryMode ? '*' : ' '), fname.c_str());
			fclose(fp);
		}
	}
}
Exemplo n.º 8
0
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
    char cmdbuf[2048],url[1024],buf[1024],hdr1[512],hdr2[512],hdr3[512],hdr4[512],digest[33],*data;
    cJSON *json;
    uint64_t nonce;
    hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
    json = 0;
    nonce = exchange_nonce(exchange);
    sprintf(buf,"%s_%s_%s_%llu",exchange->apikey,exchange->userid,exchange->apisecret,(long long)nonce);
    //printf("MD5.(%s)\n",buf);
    calc_md5(digest,buf,(int32_t)strlen(buf));
    sprintf(cmdbuf,"key=%s&time=%llu&md5=%s%s",exchange->apikey,(long long)nonce,digest,payload);
    sprintf(url,"%s/%s",EXCHANGE_AUTHURL,path);
    if ( dotrade == 0 )
        data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
    else if ( (data= curl_post(cHandlep,url,0,cmdbuf,hdr1,hdr2,hdr3,hdr4)) != 0 )
        json = cJSON_Parse(data);
    if ( retstrp != 0 )
        *retstrp = data;
    else if ( data != 0 )
        free(data);
    return(json);
}
Exemplo n.º 9
0
static int process_file(void){

  struct stat statb;
  int ccb_offset = g.opt_ccbsize;
  int status = 0;
  product prod;
  ssize_t nread;
  ssize_t filedata_size;
  unsigned char *p;
  int n;
  
  status = pq_open(g.opt_pqfname, PQ_DEFAULT, &g.pq);
  if(status != 0){
    if(status == PQ_CORRUPT)
      errx(1, "The product queue %s is inconsistent.", g.opt_pqfname);
    else 
      err(1, "pq_open");
  }

  prod.info.origin = g.opt_origin;
  prod.info.feedtype = g.opt_feedtype;
  set_timestamp(&prod.info.arrival);
  prod.info.seqno = g.seq;
  prod.info.ident = g.opt_prodid;
  if(prod.info.ident == NULL)
    prod.info.ident = g.input_fname;

  /*
   * This should not happen because it has been checked in option processing.
   */
  if(prod.info.ident == NULL)
    errx(1, "No prodid specified.");

  if(g.input_fname == NULL){
    g.fd = STDIN_FILENO;
    filedata_size = g.opt_filesize;
  }else {
    g.fd = open(g.input_fname, O_RDONLY, 0);
    if(g.fd == -1)
      err(1, "open");
	
    if(g.opt_filesize == 0){
      if(fstat(g.fd, &statb) == -1)
	err(1, "fstat");
      
      filedata_size = statb.st_size;
    }else
      filedata_size = g.opt_filesize;
  }

  if(g.opt_noccb == 0){
    if(filedata_size <= g.opt_ccbsize)
      input_file_errx(1, "No data in inputfile");
    else
      filedata_size -= g.opt_ccbsize;
  }else
    ccb_offset = 0;

  prod.info.sz = filedata_size;
  if(g.opt_gempak == 1){
    prod.info.sz += GMPK_HEADER_SIZE + GMPK_TRAILER_SIZE;
  }

  if(prod.info.sz <= STATIC_POOL_SIZE)
    prod.data = (void*)static_pool;
  else
    prod.data = malloc(prod.info.sz);

  if(prod.data == NULL)
    err(1, "malloc");

  if(ccb_offset != 0){
    if(lseek(g.fd, ccb_offset, SEEK_SET) == -1)
      input_file_err(1, "lseek error in inputfile");
  }

  p = (unsigned char*)prod.data;

  if(g.opt_gempak == 1){
    n = sprintf(gmpk_header_str, gmpk_header_fmt, (int)(g.seq % 1000));
    if(n != GMPK_HEADER_SIZE)
      errx(1, "gmpk_header_fmt format error.");

    memcpy(p, gmpk_header_str, GMPK_HEADER_SIZE);
    p += GMPK_HEADER_SIZE;
  }

  /*
   * Use readn when nbsp2ldm is opened as a pipe in tcl.
   */
  nread = readn(g.fd, p, filedata_size);
  if(nread != filedata_size)
    input_file_err(1, "read() error");

  if((g.opt_seq_str != NULL) && (g.opt_md5seq == 1))
    status = calc_md5((unsigned char*)g.opt_seq_str, strlen(g.opt_seq_str),
		      prod.info.signature);
  else
    status = calc_md5(p, filedata_size, prod.info.signature);

  if (status != 0)
    errx(1, "calc_md5");

  if(g.opt_gempak == 1){
    p += filedata_size;
    memcpy(p, gmpk_trailer_str, GMPK_TRAILER_SIZE);
  }

  status = pq_insert(g.pq, &prod);    
  if(status == PQUEUE_DUP){
    status = 0;
    warnx("Product already in queue: %s.", prod.info.ident);
  }else if(status != 0)
    errx(1, "pq_insert: %d", status);

  return(status);
}
Exemplo n.º 10
0
static int process_file(void) {
  /*
   * Process a file given in the command line or its data from stdin
   */
  struct stat statb;
  int ccb_offset = g.opt_ccbsize;
  int status = 0;
  product prod;
  ssize_t nread;
  ssize_t filedata_size;
  unsigned char *p;
  int n;

#ifdef TEST
  test_print();
  return(0);
#endif
  
  prod.info.origin = g.opt_origin;
  prod.info.feedtype = g.opt_feedtype;
  set_timestamp(&prod.info.arrival);
  prod.info.seqno = g.seq;
  prod.info.ident = g.opt_prodid;
  if(prod.info.ident == NULL)
    prod.info.ident = g.input_fname;

  /*
   * This should not happen because it has been checked in option processing.
   */
  if(prod.info.ident == NULL)
    log_errx(1, "No prodid specified.");

  if(g.input_fname == NULL){
    g.fd = STDIN_FILENO;
    filedata_size = g.opt_filesize;
  } else {
    g.fd = open(g.input_fname, O_RDONLY, 0);
    if(g.fd == -1)
      input_file_err(1, "Error from open()");
	
    if(g.opt_filesize == 0){
      if(fstat(g.fd, &statb) == -1)
	input_file_err(1, "Error from fstat()");
      
      filedata_size = statb.st_size;
    }else
      filedata_size = g.opt_filesize;
  }

  if(g.opt_noccb == 0){
    if(filedata_size <= g.opt_ccbsize)
      input_file_errx(1, "No data in inputfile");
    else
      filedata_size -= g.opt_ccbsize;
  }else
    ccb_offset = 0;

  prod.info.sz = filedata_size;
  if(g.opt_gempak == 1){
    prod.info.sz += GMPK_HEADER_SIZE + GMPK_TRAILER_SIZE;
  }

  if(prod.info.sz <= STATIC_POOL_SIZE)
    prod.data = (void*)static_pool;
  else if(prod.info.sz <= g.dynamic_pool_size)
    prod.data = g.dynamic_pool;
  else {
    prod.data = malloc(prod.info.sz);
    if(prod.data == NULL)
      log_err(1, "Error frrom malloc()");

    if(g.dynamic_pool != NULL)
      free(g.dynamic_pool);
    
    g.dynamic_pool = prod.data;
    g.dynamic_pool_size = prod.info.sz;
  }

  if(ccb_offset != 0){
    if(lseek(g.fd, ccb_offset, SEEK_SET) == -1)
      input_file_err(1, "Error from lseek()");
  }

  p = (unsigned char*)prod.data;

  if(g.opt_gempak == 1){
    n = sprintf(gmpk_header_str, gmpk_header_fmt, (int)(g.seq % 1000));
    if(n != GMPK_HEADER_SIZE)
      errx(1, "gmpk_header_fmt format error.");

    memcpy(p, gmpk_header_str, GMPK_HEADER_SIZE);
    p += GMPK_HEADER_SIZE;
  }

  /*
   * Use readn when nbsp2ldm is opened as a pipe in tcl.
   */
  nread = readn(g.fd, p, filedata_size);
  if(nread != filedata_size)
    input_file_err(1, "Error from read()");

  if((g.opt_md5seq == 1) && (g.opt_seq_str != NULL))
    status = calc_md5((unsigned char*)g.opt_seq_str,
		      strlen(g.opt_seq_str),
		      prod.info.signature);
  else
    status = calc_md5(p, filedata_size, prod.info.signature);

  if (status != 0)
    log_errx(1, "Error from calc_md5()");

  if(g.opt_gempak == 1){
    p += filedata_size;
    memcpy(p, gmpk_trailer_str, GMPK_TRAILER_SIZE);
  }

  status = pq_insert(g.pq, &prod);    
  if(status == PQUEUE_DUP){
    status = 0;
    log_warnx("Product already in queue: %s.", prod.info.ident);
  }else if(status != 0)
    log_errx(1, "Error from pq_insert: %d", status);
  else if(g.opt_verbose == 1)
    log_info("Inserted %s", prod.info.ident);

  if((g.fd != -1) && (g.fd != STDIN_FILENO)){
    close(g.fd);
    g.fd = -1;
  }

  resetdefaults();    /* reset the option parameters for the next file */
  
  return(status != 0 ? 1 : 0);
}
Exemplo n.º 11
0
void C_MessageQueue::run(int isrecv, int maxbytesend)
{
  // recieve message
  if (isrecv)
  {
    if (m_newmsg_pos==-1)
    {
      if (m_con->recv_bytes_available() >= 40)
      {
        unsigned char t[8];
        m_con->recv_bytes(&m_newmsg.message_md5,16);
        m_con->recv_bytes(t,8);
        m_newmsg.message_type=t[0]|(t[1]<<8)|(t[2]<<16)|(t[3]<<24);
        m_newmsg.message_prio=t[4];
        m_newmsg.message_length=t[5]|(t[6]<<8);
        m_newmsg.message_ttl=t[7];
        m_con->recv_bytes(&m_newmsg.message_guid,16);

        if (!m_newmsg.message_type ||
            m_newmsg.message_ttl > G_MAX_TTL ||
            m_newmsg.message_length < 0 || 
            m_newmsg.message_length > MESSAGE_MAX_PAYLOAD_ROUTE ||            
              (MESSAGE_TYPE_BCAST(m_newmsg.message_type) &&
               m_newmsg.message_length > MESSAGE_MAX_PAYLOAD_BCAST)
            )
        {       
          debug_printf("queue::run() got bad message type=%d, prio=%d, ttl=%d, len=%d\n", m_newmsg.message_type,m_newmsg.message_prio,m_newmsg.message_ttl,m_newmsg.message_length);        
          m_newmsg.message_length=0;
          m_con->close(1);
          return;
        }
        m_newmsg.data=new C_SHBuf(m_newmsg.message_length);
        if (!m_newmsg.data->Get())
        {
          delete m_newmsg.data;
          m_newmsg.message_length=0;
          m_con->close(1);
          return;
        }
        m_newmsg.data->Lock();
        m_newmsg_pos=0;
      }
    }

    int padlen=PAD8(m_newmsg.message_length);
    if (m_newmsg_pos >= 0 && m_newmsg_pos < padlen)
    {
      int len=padlen-m_newmsg_pos;
      int len2=m_con->recv_bytes_available();
      if (len > len2) len=len2;
      if (len > 0)
      {
        m_con->recv_bytes((char*)m_newmsg.data->Get()+m_newmsg_pos,len);
        m_newmsg_pos+=len;
      }
      if (m_newmsg_pos >= padlen) // finish crc calculation
      {
        unsigned char buf[16];
        calc_md5(&m_newmsg,buf);
        if (memcmp(buf,m_newmsg.message_md5,16))
        {
          debug_printf("queue::run() got bad message (MD5 differs) type=%d, prio=%d, ttl=%d, len=%d\n", m_newmsg.message_type,m_newmsg.message_prio,m_newmsg.message_ttl,m_newmsg.message_length);        
          m_newmsg.message_length=0;
          m_newmsg_pos=-1;
          m_con->close(1);
          return;
        }
      }
    }
  }
  else
  {
    int do_saturate=(g_throttle_flag&32) && (m_con->get_saturatemode()&1);
    int satsize=min(m_con->getMaxSendSize()/64,216);
    if (satsize < 4) satsize=4;
    if (!m_msg_used && do_saturate && m_con->send_bytes_in_queue() < 40+satsize*2 && (maxbytesend < 0 || m_con->send_bytes_in_queue()+40+satsize < maxbytesend)) saturate(satsize);

    while (m_msg_used>0 && (maxbytesend<0 || m_con->send_bytes_in_queue() < maxbytesend))
    {
      if (m_msg_bsent<0)
      {
        if (m_con->send_bytes_available() >= 40)
        {
          unsigned char t[8];
          m_con->send_bytes(&m_msg->message_md5,16);
          t[0]=m_msg->message_type&0xff;
          t[1]=(m_msg->message_type>>8)&0xff;
          t[2]=(m_msg->message_type>>16)&0xff;
          t[3]=(m_msg->message_type>>24)&0xff;
          t[4]=m_msg->message_prio;
          t[5]=m_msg->message_length&0xff;
          t[6]=(m_msg->message_length>>8)&0xff;
          t[7]=m_msg->message_ttl;
          m_con->send_bytes(t,8);
          m_con->send_bytes(&m_msg->message_guid,16);
          m_msg_bsent=0;
          if (MESSAGE_TYPE_BCAST(m_msg->message_type) &&
              m_msg->message_length > MESSAGE_MAX_PAYLOAD_BCAST)
          {
            debug_printf("queue::run() send bcast payload length of %d too large\n",m_msg->message_length);
          }
          else if (m_msg->message_length > MESSAGE_MAX_PAYLOAD_ROUTE)
          {
            debug_printf("queue::run() send route/local payload length of %d too large\n",m_msg->message_length);
          }
        }
        else break;
      }
      if (m_msg_bsent>=0)
      {
        int len=PAD8(m_msg->message_length)-m_msg_bsent;
        int len2=m_con->send_bytes_available();
        if (len > len2) len=len2;

        if (len >= 8)
        {
          m_con->send_bytes((char*)m_msg->data->Get()+m_msg_bsent,len);
          m_msg_bsent += len;
        }
        if (m_msg_bsent >= m_msg->message_length)
        {
          m_msg_bsent=-1;
          removefirst();
          if (!m_msg_used && do_saturate && m_con->send_bytes_available() >= 40+satsize && m_con->send_bytes_in_queue() < 40+satsize*2 && (maxbytesend < 0 || m_con->send_bytes_in_queue()+40+satsize < maxbytesend)) saturate(satsize);
        }

        if (len2 < 8) break;
      }
    }
Exemplo n.º 12
0
Arquivo: zync.c Projeto: rvergis/zync
int generate_zync_state(FILE *in_file,
                        struct zync_state *zs,
                        zync_block_size_t block_size)
{
    if (block_size <= 0)
    {
        fprintf(stderr, "block_size <= 0");
        return -1;
    }
    if (fseek(in_file, 0, SEEK_SET) != 0)
    {
        return -1;
    }
    zync_file_size_t in_filelen = 0;
    zync_block_index_t block_id = 0;
    
    unsigned char *zync_checksum = safe_malloc(sizeof(unsigned char) * 16); //zync_checksum+1
    if (zync_checksum == NULL)
    {
        return -1;
    }
    
    CC_MD5_CTX *zync_ctx = init_md5(); //zync_ctx+1
    
    while (block_id < MAX_BLOCKS)
    {
        unsigned char *in_file_buf = safe_malloc(sizeof(unsigned char) * block_size); //in_file_buf+1
        if (in_file_buf == NULL)
        {
            free(zync_checksum); //zync_checksum-1
            free(zync_ctx); //zync_ctx-1
            return -1;
        }
        size_t in_file_read = safe_fread(in_file_buf, block_size, in_file);
        if (in_file_read == -1)
        {
            free(zync_checksum); //zync_checksum-1
            free(zync_ctx); //zync_ctx-1
            free(in_file_buf); //in_file_buf-1
            return -1;
        }
        
        zync_rsum_t adler = (zync_rsum_t) calc_adler32(in_file_buf, block_size);
        
        unsigned char *md5_buf = safe_malloc(sizeof(unsigned char) * 16); //md5_buf+1
        if (md5_buf == NULL)
        {
            free(zync_checksum); //zync_checksum-1
            free(zync_ctx); //zync_ctx-1
            free(in_file_buf); //in_file_buf-1
            return -1;
        }
        
        calc_md5((void *) in_file_buf, block_size, md5_buf);
        add_zync_block(zs, block_id++, 0, 0, adler, md5_buf);
        
        free(md5_buf); //md5_buf-1
        
        update_md5(zync_ctx, (void *) in_file_buf, block_size);
        
        in_filelen += in_file_read;
        
        free(in_file_buf); //in_file_buf-1
        
        if (feof(in_file))
        {
            break;
        }
    }
    
    finalize_md5(zync_ctx, zync_checksum); //zync_ctx-1
    
    for (int i = 0; i < 16; i++)
    {
        zs->checksum[i] = zync_checksum[i];
    }
    
    free(zync_checksum); //zync_checksum-1
    
    zs->filelen = in_filelen;
    zs->block_size = block_size;
    zs->block_fill_count = 0;
    
    return 0;
}
Exemplo n.º 13
0
Arquivo: zync.c Projeto: rvergis/zync
int zync_original_file(FILE *original_file, FILE *download_file, zync_file_size_t original_filelen)
{
    if (fseek(download_file, 0, SEEK_SET) != 0)
    {
        return -1;
    }
    struct zync_state *zs = read_zync_file(download_file); //zs+1
    if (zs == NULL)
    {
        return -1;
    }
    
    zync_block_size_t block_size = zs->block_size;
    
    unsigned char *adler32_buf = safe_malloc(sizeof(unsigned char) * block_size); //adler32_buf+1
    if (adler32_buf == NULL)
    {
        return -1;
    }
    if (fseek(download_file, 0, SEEK_SET) != 0)
    {
        free(zs); //zs-1
        free(adler32_buf); //adler32_buf-1
        return -1;
    }
    if (safe_fread(adler32_buf, block_size, original_file) == -1)
    {
        free(zs); //zs-1
        free(adler32_buf); //adler32_buf-1
        return -1;
    }
    zync_rsum_t rolling_adler32 = calc_adler32(adler32_buf, block_size);
    free(adler32_buf); //adler32_buf-1
    
    unsigned char *prev_buf = safe_malloc(sizeof(unsigned char) * block_size); //prev_buf+1
    if (prev_buf == NULL)
    {
        free(zs); //zs-1
        return -1;
    }
    
    unsigned char *next_buf = safe_malloc(sizeof(unsigned char) * block_size); //next_buf+1
    if (next_buf == NULL)
    {
        free(zs); //zs-1
        free(prev_buf); //prev_buf-1
        return -1;
    }
    
    unsigned char prev_ch = 0;
    unsigned char next_ch = 0;
    
    off_t prev_offset = 0;
    off_t next_offset = block_size;
    zync_file_size_t index = 0;
    if (read_rolling_bufs(original_file, prev_buf, next_buf, block_size, prev_offset, next_offset) != 0)
    {
        free(zs); //zs-1
        free(prev_buf); //prev_buf-1
        free(next_buf); //next_buf-1
        return -1;
    }
    
    while (true)
    {
        struct zync_block *unfilled_zb = find_unfilled_zync_block_by_rsum(zs, rolling_adler32);
        if (unfilled_zb != NULL)
        {
            unsigned char *data_buf = safe_malloc(sizeof(unsigned char) * block_size); //data_buf+1
            if (data_buf == NULL)
            {
                free(zs); //zs-1
                free(prev_buf); //prev_buf-1
                free(next_buf); //next_buf-1
                return -1;
            }
            unsigned char *checksum_buf = safe_malloc(sizeof(unsigned char) * 16); //checksum_buf+1
            if (checksum_buf == NULL)
            {
                free(zs); //zs-1
                free(prev_buf); //prev_buf-1
                free(next_buf); //next_buf-1
                free(data_buf); //data_buf-1
                return -1;
            }
            if (fseek(original_file, prev_offset, SEEK_SET) != 0)
            {
                free(zs); //zs-1
                free(prev_buf); //prev_buf-1
                free(next_buf); //next_buf-1
                free(data_buf); //data_buf-1
                free(checksum_buf); //checksum_buf-1
                return -1;
            }
            if (safe_fread(data_buf, block_size, original_file) == -1)
            {
                free(zs); //zs-1
                free(prev_buf); //prev_buf-1
                free(next_buf); //next_buf-1
                free(data_buf); //data_buf-1
                free(checksum_buf); //checksum_buf-1
                return -1;
            }
            calc_md5(data_buf, block_size, checksum_buf);
            if (unfilled_zb != NULL)
            {
                if (unfilled_zb->rsum == rolling_adler32)
                {
                    if (memcmp(unfilled_zb->checksum, checksum_buf, 16) == 0)
                    {
                        unfilled_zb->block_fill_flag = 1;
                        zs->block_fill_count++;
                        
                        if (fseek(download_file, 0, SEEK_SET) != 0)
                        {
                            free(zs); //zs-1
                            free(prev_buf); //prev_buf-1
                            free(next_buf); //next_buf-1
                            free(data_buf); //data_buf-1
                            free(checksum_buf); //checksum_buf-1
                            return -1;
                        }
                        if (update_download_file(download_file, data_buf, zs, unfilled_zb->block_index) == -1)
                        {
                            free(zs); //zs-1
                            free(prev_buf); //prev_buf-1
                            free(next_buf); //next_buf-1
                            free(data_buf); //data_buf-1
                            free(checksum_buf); //checksum_buf-1
                            return -1;
                        }
                    }
                }
            }
            free(data_buf); //data_buf-1
            free(checksum_buf); //checksum_buf-1
        }
        prev_ch = prev_buf[index];
        next_ch = next_buf[index];
        rolling_adler32 = calc_rolling_adler32(rolling_adler32, block_size, prev_ch, next_ch);
        index = (index + 1) % block_size;
        if (index == 0)
        {
            prev_offset += block_size;
            next_offset += block_size;
            
            if (prev_offset >= original_filelen)
            {
                break;
            }
            
            if (read_rolling_bufs(original_file, prev_buf, next_buf, block_size, prev_offset, next_offset) != 0)
            {
                free(zs); //zs-1
                free(prev_buf); //prev_buf-1
                free(next_buf); //next_buf-1
                return -1;
            }
        }
    }
    
    free(zs); //zs-1
    free(prev_buf); //prev_buf-1
    free(next_buf); //next_buf-1
    return 0;
}