Пример #1
0
char* encode(const char* input)
{
	/* set up a destination buffer large enough to hold the encoded data */
	char* output = (char*)malloc(SIZE);
	/* keep track of our encoded position */
	char* c = output;
	/* store the number of bytes encoded by a single call */
	int cnt = 0;
	/* we need an encoder state */
	base64_encodestate s;
	
	/*---------- START ENCODING ----------*/
	/* initialise the encoder state */
	base64_init_encodestate(&s);
	/* gather data from the input and send it to the output */
	cnt = base64_encode_block(input, strlen(input), c, &s);
	c += cnt;
	/* since we have encoded the entire input string, we know that 
	   there is no more input data; finalise the encoding */
	cnt = base64_encode_blockend(c, &s);
	c += cnt;
	/*---------- STOP ENCODING  ----------*/
	
	/* we want to print the encoded data, so null-terminate it: */
	*c = 0;
	
	return output;
}
Пример #2
0
void
test_base64 (void)
{
  base64_encodestate encode;
  base64_decodestate decode;
  char b64dig[64];
  char buf[64];
  int size1, size2;
  int ret;

  TEST(("test base64 encoding"));
  base64_init_encodestate(&encode);
  size1 = base64_encode_block("foo", 3, b64dig, &encode);
  size2 = base64_encode_blockend(&b64dig[size1], &encode);
  b64dig[size1 + size2 - 1] = '\0';

  printf("b64 encode: %s, expected: Zm9v\n", b64dig);
  ret = strcmp(b64dig, "Zm9v");
  assert(ret == 0);

  TEST(("test base64 decoding"));
  base64_init_decodestate(&decode);
  base64_decode_block ("YmxhaG9uZ2E=", 12, buf, &decode);

  printf("b64 decode: %s, expexted: blahonga\n", buf);
  ret = strcmp(buf, "blahonga");
  assert(ret == 0);
}
Пример #3
0
//============================================================================
//		NDataEncoder::B64_Encode : Encode to Base64.
//----------------------------------------------------------------------------
NString NDataEncoder::B64_Encode(const NData &theValue)
{	NData					theBuffer;
	NString					theString;
	base64_encodestate		theState;
	char					*dataPtr;
	NIndex					dataSize;



	// Get the state we need
	base64_init_encodestate(&theState);

	if (theValue.IsEmpty() || !theBuffer.SetSize(theValue.GetSize() * 2))
		return(theString);



	// Encode the value
	dataPtr   = (char *) theBuffer.GetData();
	dataSize  = base64_encode_block((const char *) theValue.GetData(), theValue.GetSize(), dataPtr, &theState);
	theString = NString(dataPtr, dataSize);

	dataSize = base64_encode_blockend(dataPtr, &theState);
	if (dataSize != 0)
		theString += NString(dataPtr, dataSize);



	// Remove the trailing newline
	NN_ASSERT(theString.GetRight(1) == "\n");
	theString.TrimRight(1);

	return(theString);
}
Пример #4
0
int base64_encode_chars(const char* plaintext_in, int length_in, char* code_out)
{
    base64_encodestate _state;
    base64_init_encodestate(&_state);
    int len = base64_encode_block(plaintext_in, length_in, code_out, &_state);
    return len + base64_encode_blockend((code_out + len), &_state);
}
Пример #5
0
int
base64_encode(const char *in_bin, int in_len,
	      char *out_base64, int out_len)
{
	struct base64_encodestate state;
	base64_encodestate_init(&state);
	int res = base64_encode_block(in_bin, in_len, out_base64,
				      out_len, &state);
	return res + base64_encode_blockend(out_base64 + res, out_len - res,
					    &state);
}
Пример #6
0
char*
Ybase64_encode(const char *buf, int buflen)
{
  base64_encodestate bstate;
  const char *ibuf;
  int ilen, olen;
  char *result;
  char obuf[20];
  Ybuffer *ybuf;

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

  if (buflen < 0) {
    buflen = strlen(buf);
  }

  /* Output should be (buflen / 3) * 4 + 4 + 1 */
  ybuf = Ybuffer_init(16);
  if (ybuf == NULL) {
    return NULL;
  }

  base64_init_encodestate(&bstate);

  ibuf = buf;
  while (buflen > 0) {
    if (buflen < 12) {
      ilen = buflen;
    } else {
      ilen = 12;
    }

    olen = base64_encode_block(ibuf, ilen, obuf, &bstate);
    Ybuffer_append(ybuf, obuf, olen);

    ibuf += ilen;
    buflen -= ilen;
  }

  olen = base64_encode_blockend(obuf, &bstate);
  Ybuffer_append(ybuf, obuf, olen);

  /* Get sure output buffer is a valid null terminated string */
  Ybuffer_append(ybuf, "\0", 1);

  /* Extract string and release Ybuffer container */
  result = Ybuffer_detach(ybuf, NULL);

  return result;
}
Пример #7
0
size_t
b64_encode( const char* in, size_t insize, char* out )
{
  const char* start = out;
  size_t len = 0;
  base64_encodestate state;
  base64_init_encodestate( &state );
  len = base64_encode_block( in, insize, out, &state );
  out += len;
  len = base64_encode_blockend( out, &state );
  out += len;
  return out - start;
}
Пример #8
0
static int
prepare_response (const unsigned char *buf, int len, const char *bd,
		  char **response, size_t * response_len)
{
  base64_encodestate b64ctx;
  char b64resp[2048];
  char bdstr[2048];
  int cnt;

  if (len > 2048)
    return U2FH_MEMORY_ERROR;
  if (strlen (bd) > 2048)
    return U2FH_MEMORY_ERROR;

  base64_init_encodestate (&b64ctx);
  cnt = base64_encode_block (buf, len, b64resp, &b64ctx);
  base64_encode_blockend (b64resp + cnt, &b64ctx);

  base64_init_encodestate (&b64ctx);
  cnt = base64_encode_block (bd, strlen (bd), bdstr, &b64ctx);
  base64_encode_blockend (bdstr + cnt, &b64ctx);

  return prepare_response2 (b64resp, bdstr, response, response_len);
}
Пример #9
0
static u2fs_rc encode_b64u(const char *data, size_t data_len, char *output)
{
  base64_encodestate b64;
  int cnt;

  if ((data_len * 4) >= (_B64_BUFSIZE * 3) || output == NULL)	//base64 is 75% efficient (4 characters encode 3 bytes)
    return U2FS_MEMORY_ERROR;

  base64_init_encodestate(&b64);
  cnt = base64_encode_block(data, data_len, output, &b64);
  cnt += base64_encode_blockend(output + cnt, &b64);

  output[cnt] = '\0';

  return U2FS_OK;
}
Пример #10
0
int
sc_vtk_write_binary (FILE * vtkfile, char *numeric_data, size_t byte_length)
{
  size_t              chunks, chunksize, remaining, writenow;
  size_t              code_length, base_length;
  uint32_t            int_header;
  char               *base_data;
  base64_encodestate  encode_state;

  /* VTK format used 32bit header info */
  SC_ASSERT (byte_length <= (size_t) UINT32_MAX);

  chunksize = (size_t) 1 << 15; /* 32768 */
  int_header = (uint32_t) byte_length;

  code_length = 2 * chunksize;
  base_data = SC_ALLOC (char, code_length);

  base64_init_encodestate (&encode_state);
  base_length =
    base64_encode_block ((char *) &int_header, sizeof (int_header), base_data,
                         &encode_state);
  base_data[base_length] = '\0';
  (void) fwrite (base_data, 1, base_length, vtkfile);

  chunks = 0;
  remaining = byte_length;
  while (remaining > 0) {
    writenow = SC_MIN (remaining, chunksize);
    base_length = base64_encode_block (numeric_data + chunks * chunksize,
                                       writenow, base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
    remaining -= writenow;
    ++chunks;
  }

  base_length = base64_encode_blockend (base_data, &encode_state);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  SC_FREE (base_data);
  if (ferror (vtkfile)) {
    return -1;
  }
  return 0;
}
Пример #11
0
char*
_plb64encode(char* idat, unsigned int ilen, unsigned int* olen) {
	unsigned int osiz;
	unsigned int csiz;
	unsigned int tsiz;
	char* odat;
	base64_encodestate b64state;

	if (idat == NULL || ilen == 0) { return NULL; }
	osiz = (((ilen + 2) / 3) + 1 ) * 4; 
	odat = _plzalloc(osiz);
	if (odat == NULL) { return NULL; }
	base64_init_encodestate(&b64state);
	csiz = base64_encode_block(idat, ilen, odat, &b64state);
	tsiz = base64_encode_blockend(&odat[csiz], &b64state);
	if (olen != NULL) { *olen = csiz + tsiz; }
	return odat;
}
Пример #12
0
static int
ws_compute_handshake(struct http_client *c, char *out, size_t *out_sz) {

	unsigned char *buffer, sha1_output[20];
	char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
	SHA1Context ctx;
	base64_encodestate b64_ctx;
	int pos, i;

	// websocket handshake
	const char *key = client_get_header(c, "Sec-WebSocket-Key");
	size_t key_sz = key?strlen(key):0, buffer_sz = key_sz + sizeof(magic) - 1;
	buffer = calloc(buffer_sz, 1);

	// concatenate key and guid in buffer
	memcpy(buffer, key, key_sz);
	memcpy(buffer+key_sz, magic, sizeof(magic)-1);

	// compute sha-1
	SHA1Reset(&ctx);
	SHA1Input(&ctx, buffer, buffer_sz);
	SHA1Result(&ctx);
	for(i = 0; i < 5; ++i) {	// put in correct byte order before memcpy.
		ctx.Message_Digest[i] = ntohl(ctx.Message_Digest[i]);
	}
	memcpy(sha1_output, (unsigned char*)ctx.Message_Digest, 20);

	// encode `sha1_output' in base 64, into `out'.
	base64_init_encodestate(&b64_ctx);
	pos = base64_encode_block((const char*)sha1_output, 20, out, &b64_ctx);
	base64_encode_blockend(out + pos, &b64_ctx);

	// compute length, without \n
	*out_sz = strlen(out);
	if(out[*out_sz-1] == '\n')
		(*out_sz)--;

	free(buffer);

	return 0;
}
Пример #13
0
 string toBase64(const void *input, int inputSize)
 {
     if (inputSize == 0)
     {
         return string();
     }
     
     char *buffer = new char[inputSize * 4 / 3 + 4];
     
     base64_encodestate state;
     base64_init_encodestate(&state);
     
     int resultSize = base64_encode_block(reinterpret_cast<const char*>(input), inputSize, &buffer[0], &state);
     resultSize += base64_encode_blockend(&buffer[resultSize], &state);
     buffer[resultSize] = 0; // NULL TERMINATE THE STRING
     
     string result(buffer);
     delete[] buffer;
     
     return result;
 }
Пример #14
0
	int Crypto::encodeBase64(const void* input,
		int inputLength,
		char* output,
		int outputBufferLength)
	{
		int bufferSize = 2 * inputLength;
		char* buffer = (char*)malloc(bufferSize);
		memset(buffer, 0, bufferSize);

		base64_encodestate state;
		base64_init_encodestate(&state);
		int r1 = base64_encode_block(static_cast<const char*>(input), inputLength, buffer, &state);
		int r2 = base64_encode_blockend(buffer + r1, &state);

		int dataUsed = r1 + r2;
		memset(output, 0, outputBufferLength);
		int cp = dataUsed < outputBufferLength ? dataUsed : outputBufferLength - 1;
		memcpy(output, buffer, cp);
		free(buffer);
		return cp;
	}
Пример #15
0
char *encode_base64_from_file(char *filename)
{
	base64_encodestate enstate;
	statstruct statb;	
	FILE *fp=NULL;
	size_t size=0,size1=0;
	char *temp=NULL;
	char *temp1=NULL;
	char *base64_result=NULL;

#if !defined(LINUX_SUSE6_1)
	if(stat(filename,&statb)!=(-1))
#else
	if(_xstat(_STAT_VER,filename,&statb)!=(-1))
#endif
	{
		if(statb.st_size>0)
		{
			fp=fopen(filename,"rb");
			if(fp!=NULL)
			{
				size=statb.st_size;
				temp=(char *)Rmalloc(size+1);
				memset(temp,0,size+1);
				printf("size [%d]\n",size);
				size=fread(temp,sizeof(char),size,fp);
				printf("size [%d]\n",size);
				if(ferror(fp))
				{
					prterr("Error:  Failed to read characters to the end of file [%s].",filename);
				}else if(size==0) {
					prterr("Error:  File [%s] is an empty or an error occurred.",filename);
				}else{
					/*
					size1=base64_encoded_size(temp,size);
					*/
					size1=(size*2);

					temp1=(char *)Rmalloc(size1+1);
					memset(temp1,0,size1+1);

					base64_result=(char *)Rmalloc(size1+1);
					memset(base64_result,0,size1+1);
					
					base64_init_encodestate(&enstate);
					base64_encode_block(temp,size,temp1,&enstate);
					sprintf(base64_result,"%s%s",base64_result,temp1);

					memset(temp1,0,size1+1);
					base64_encode_blockend(temp1,&enstate);
					sprintf(base64_result,"%s%s",base64_result,temp1);

					if(temp!=NULL) Rfree(temp);
					if(temp1!=NULL) Rfree(temp1);
					fclose(fp);
					return(base64_result);
				}
				if(temp!=NULL) Rfree(temp);
				fclose(fp);
			}else{
				prterr("Error:  Could not open file [%s] for encoding to base64.\n",filename);
			}
		}else{
			prterr("Error:  Zero sized file [%s] could not be used for encoding to base64.\n",filename);
		}
	}else{
		prterr("Error:  Could not stat file [%s], not attempting to open file.\n",filename);
	}
	return(NULL);
}
Пример #16
0
static axa_json_res_t
add_whit(axa_emsg_t *emsg, yajl_gen g, struct axa_strbuf *yajl_sb, nmsg_input_t nmsg_input, axa_p_whit_t *whit, size_t whit_len)
{
	axa_json_res_t json_res;

	json_res = add_channel(emsg, g, whit->hdr.ch);
	if (json_res != AXA_JSON_RES_SUCCESS)
		return (json_res);

	switch (whit->hdr.type) {
	case AXA_P_WHIT_NMSG: {
		struct axa_strbuf *sb;
		nmsg_message_t msg;
		axa_w2n_res_t wres;
		nmsg_res nres;
		const char *vname, *mname;
		char *nmsg_json = NULL;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_nmsg_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu", whit_len, sizeof(axa_p_whit_nmsg_t));
			return (AXA_JSON_RES_FAILURE);
		}

		wres = axa_whit2nmsg(emsg, nmsg_input, &msg, whit, whit_len);
		if (wres != AXA_W2N_RES_SUCCESS) {
			return (AXA_JSON_RES_FAILURE);
		}

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}

		if(AXA_P2H_IDX(whit->nmsg.hdr.field_idx) < AXA_NMSG_IDX_RSVD) {
			const char *field_name;
			nres = nmsg_message_get_field_name(msg, whit->nmsg.hdr.field_idx, &field_name);
			if (nres == nmsg_res_success) {
				add_yajl_string(g, "field");
				add_yajl_string(g, field_name);
			} else {
				add_yajl_string(g, "field_idx");
				add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.field_idx));
			}
		}

		if (AXA_P2H_IDX(whit->nmsg.hdr.val_idx) < AXA_NMSG_IDX_RSVD) {
			add_yajl_string(g, "val_idx");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.val_idx));
		}

		vname = nmsg_msgmod_vid_to_vname(AXA_P2H_IDX(whit->nmsg.hdr.vid));
		if (vname != NULL) {
			add_yajl_string(g, "vname");
			add_yajl_string(g, vname);
		} else {
			add_yajl_string(g, "vid");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.vid));
		}

		mname = nmsg_msgmod_msgtype_to_mname(
				AXA_P2H16(whit->nmsg.hdr.vid),
				AXA_P2H16(whit->nmsg.hdr.type));
		if (mname != NULL) {
			add_yajl_string(g, "mname");
			add_yajl_string(g, mname);
		} else {
			add_yajl_string(g, "msgtype");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.type));
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->nmsg.hdr.ts.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		axa_strbuf_reset(sb);
		axa_strbuf_append(sb, "%s.%09u", when,
				AXA_P2H32(whit->nmsg.hdr.ts.tv_nsec));
		add_yajl_string(g, sb->data);

		nres = nmsg_message_to_json(msg, &nmsg_json);
		if (nres == nmsg_res_success) {
			add_yajl_string(g, "nmsg");
			add_yajl_integer(g, 0);

			yajl_gen_clear(g);
			axa_strbuf_clip(yajl_sb, axa_strbuf_len(yajl_sb)-1);
			axa_strbuf_append(yajl_sb, "%s", nmsg_json);
			free(nmsg_json);
		}

		axa_strbuf_destroy(&sb);
		nmsg_message_destroy(&msg);

		return (AXA_JSON_RES_SUCCESS);
	}
	case AXA_P_WHIT_IP: {
		struct axa_strbuf *sb;
		struct nmsg_ipdg dg;
		nmsg_res res;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_ip_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu",
					whit_len, sizeof(axa_p_whit_ip_t));
			return (AXA_JSON_RES_FAILURE);
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->ip.hdr.tv.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}
		axa_strbuf_append(sb, "%s.%06u", when,
				AXA_P2H32(whit->ip.hdr.tv.tv_usec));
		add_yajl_string(g, sb->data);
		axa_strbuf_destroy(&sb);

		res = nmsg_ipdg_parse_pcap_raw(&dg, DLT_RAW, whit->ip.b, whit_len - offsetof(axa_p_whit_ip_t, b));
		if (res != nmsg_res_success || dg.len_network == 0) {
			add_yajl_string(g, "parse_error");
			add_yajl_bool(g, true);

			return (AXA_JSON_RES_SUCCESS);
		}

		add_yajl_string(g, "af");
		switch(dg.proto_network) {
		case AF_INET: {
			struct ip *ip_hdr;
			char addr_str[INET_ADDRSTRLEN];

			add_yajl_string(g, "IPv4");

			if (dg.network != NULL && dg.len_network >= sizeof(ip_hdr)) {
				ip_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_src, addr_str, sizeof(addr_str)));
				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip_hdr->ip_ttl);
			}
			break;
		}
		case AF_INET6: {
			struct ip6_hdr *ip6_hdr;
			char addr_str[INET6_ADDRSTRLEN];
			
			add_yajl_string(g, "IPv6");

			if (dg.network != NULL && dg.len_network >= sizeof(ip6_hdr)) {
				ip6_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_src, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip6_hdr->ip6_hlim);

			}
			break;
		}
		default:
			add_yajl_integer(g, dg.proto_network);
			return (AXA_JSON_RES_SUCCESS);
		} /* switch */

		add_yajl_string(g, "proto");
		switch(dg.proto_transport) {
		case IPPROTO_ICMP:
			add_yajl_string(g, "ICMP");
			break;
		case IPPROTO_ICMPV6:
			add_yajl_string(g, "ICMPv6");
			break;
		case IPPROTO_TCP:
			add_yajl_string(g, "TCP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct tcphdr)) {
				struct tcphdr *tcp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_dport));

				add_yajl_string(g, "flags");
				add_yajl_array(g);
				if ((tcp_hdr->th_flags & TH_FIN) != 0)
					add_yajl_string(g, "FIN");
				if ((tcp_hdr->th_flags & TH_SYN) != 0)
					add_yajl_string(g, "SYN");
				if ((tcp_hdr->th_flags & TH_ACK) != 0)
					add_yajl_string(g, "ACK");
				if ((tcp_hdr->th_flags & TH_RST) != 0)
					add_yajl_string(g, "RST");
				close_yajl_array(g);
			}
			break;
		case IPPROTO_UDP:
			add_yajl_string(g, "UDP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct udphdr)) {
				struct udphdr *udp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_dport));

			}
			break;
		default:
			add_yajl_integer(g, dg.proto_transport);
			break;
		} /* switch */

		if (dg.payload != NULL) {
			base64_encodestate b64;
			char *b64_str;
			size_t b64_str_len;

			base64_init_encodestate(&b64);
			b64_str = alloca(2 * dg.len_payload + 1);
			AXA_ASSERT(b64_str != NULL);

			b64_str_len = base64_encode_block((void*)dg.payload,
					dg.len_payload, b64_str, &b64);
			b64_str_len += base64_encode_blockend(b64_str + b64_str_len, &b64);

			add_yajl_string(g, "payload");
			add_yajl_string_len(g, b64_str, b64_str_len);
		}

		return (AXA_JSON_RES_SUCCESS);
	}
	default:
		axa_pemsg(emsg, "unknown whit hdr type: %d", whit->hdr.type);
		return (AXA_JSON_RES_FAILURE);
	}
}
Пример #17
0
int log_send(struct bb_state *bb_data, struct file_state *file_state,
	     const char *filename, const char *msg, int len, off_t offset)
{
	static char hn[512] = "\0";
	char buf[LOG_PACKET_LENGTH];
	char off[64];
	int i, l, m, n, chunk, ret;
	int prio = 13 * 8 + 5; /* log_audit.log_notice, 109 */
	/* timestamp stuff */
	struct tm tm;
	time_t now;

	/* base64 encoder stuff*/
	base64_encodestate s;
	int b64len;
	char *b64 = (char *)malloc(len*4/3+8);
	char *c = b64;
	if (!b64) {
		syslog(LOG_ERR, "%s: malloc failed!", __func__);
		return -1;
	}

	now = time(NULL);
	gmtime_r(&now, &tm);

	base64_init_encodestate(&s);
	n = base64_encode_block(msg, len, c, &s);
	c += n;
	b64len = n;
	n = base64_encode_blockend(c, &s);
	c += n;
	*c = '\0';
	b64len += n;
	// fprintf(stderr, "b64: '%s'\n", b64);

	ret = gethostname(hn, 512);
	if (ret < 0)
		strcpy(hn, inet_ntoa(bb_data->log_addr.sin_addr));
	n = sprintf(buf, "<%d>", prio);
	n += strftime(buf + n, LOG_PACKET_LENGTH - n, "%b %e %T ", &tm);
	strncat(buf + n, hn, LOG_PACKET_LENGTH - n);
	n += strlen(hn);
	m = snprintf(buf + n, LOG_PACKET_LENGTH - n, " %s:%08x ", filename, 0);
	if (m >= LOG_PACKET_LENGTH - n) {
		syslog(LOG_ERR, "filename too long, not sending log message");
		syslog(LOG_ERR, "%s", filename);
		free(b64);
		return -1;
	}
	n += m;

	/* "size@offset " */
	l = sprintf(off, "%x@%" PRIx64 " ", len, offset);

	chunk = LOG_PACKET_LENGTH - 1 - n;
	if (chunk < MIN_BUF_SPACE) {
		/* we assume that MIN_BUF_SPACE is much bigger than l (strlen "size@offset")
		 * here, so no extra check for l is made */
		syslog(LOG_ERR, "not enough space in packet (%d), not sending log message", chunk);
		syslog(LOG_ERR, "%s", filename);
		free(b64);
		return -1;
	}

	for (i = 0; i < b64len; /*i+= chunk*/) {
		sprintf(buf + n -9 , "%08x ", ++file_state->seq);
		/* first packet of this log message: add "size@offset " prefix */
		if (l)
			strcpy(buf + n, off);
		/* strncpy stops at end of b64 string, so it does not matter that chunk may point beyound b64 array */
		strncpy(buf + n + l, b64 + i, chunk - l);
#if 0
		/* debugging, send length of base64 string instead of string */
		char tmp[128];
		int x = strlen(buf+n);
		sprintf(tmp, "strlen %d, n: %d, tot: %d", x, n, x+n);
		strcpy(buf + n, tmp);
#else
		m = b64len - i + n + l;
		if (m > LOG_PACKET_LENGTH)
			m = LOG_PACKET_LENGTH;
		ret = sendto(bb_data->log_fd, buf, m, 0, (struct sockaddr *)&(bb_data->log_addr), sizeof(struct sockaddr_in));
		if (ret < 0) {
			syslog(LOG_ERR, "Error, send() failed: %m");
			//return 1;
		}
#endif
		i += chunk - l;
		l = 0; /* reset after first packet is sent */
		fprintf(stderr, "sendto: %s\n", buf);
	}
	free(b64);

	return 0;
}
Пример #18
0
int
ykclient_request (ykclient_t *ykc,
		  const char *yubikey)
{
  const char *url_template = ykc->url_template;
  char *user_agent = NULL;
  char *status;
  int out;

  if (!url_template)
    url_template = "http://api.yubico.com/wsapi/verify?id=%d&otp=%s";

  free (ykc->curl_chunk);
  ykc->curl_chunk_size = 0;
  ykc->curl_chunk = NULL;

  {
    size_t len = strlen (url_template) + strlen (yubikey) + 20;
    size_t wrote;

    free (ykc->url);
    ykc->url = malloc (len);
    if (!ykc->url)
      return YKCLIENT_OUT_OF_MEMORY;
    wrote = snprintf (ykc->url, len, url_template,
		      ykc->client_id, yubikey);
    if (wrote < 0 || wrote > len)
      return YKCLIENT_FORMAT_ERROR;
  }

  if (ykc->key && ykc->keylen)
    {
      uint8_t digest[USHAMaxHashSize];
      char b64dig[3*4*SHA1HashSize+1];
      base64_encodestate b64;
      char *text;
      int res, res2;

      /* Find parameters to sign. */
      text = strchr (ykc->url, '?');
      if (!text)
	return YKCLIENT_PARSE_ERROR;
      text++;

      /* HMAC data. */
      res = hmac (SHA1, (unsigned char*) text, strlen (text),
		  (unsigned char*) ykc->key, ykc->keylen, digest);
      if (res != shaSuccess)
	return YKCLIENT_HMAC_ERROR;

      /* Base64 signature. */
      base64_init_encodestate(&b64);
      res = base64_encode_block((char*)digest, SHA1HashSize, b64dig, &b64);
      res2 = base64_encode_blockend(&b64dig[res], &b64);
      b64dig[res+res2-1] = '\0';

      /* Escape + into %2B. */
      {
	char *p;

	while ((p = strchr (b64dig, '+')))
	  {
	    memmove (p+3, p+1, strlen (p));
	    memcpy (p, "%2B", 3);
	  }
      }

      /* Create new URL. */
      {
	char *url;
	size_t len;
	int wrote;

#define ADD_HASH "&h="
	len = strlen (ykc->url) + strlen (ADD_HASH) + strlen (b64dig) + 1;
	url = malloc (len);
	if (!url)
	  return YKCLIENT_OUT_OF_MEMORY;

	wrote = snprintf (url, len, "%s" ADD_HASH "%s", ykc->url, b64dig);
	if (wrote + 1 != len)
	  return YKCLIENT_FORMAT_ERROR;
	free (ykc->url);
	ykc->url = url;
      }
    }

  if (ykc->nonce)
    {
      /* Create new URL. */
      char *url;
      size_t len;
      int wrote;

#define ADD_NONCE "&nonce="
      len = strlen (ykc->url) + strlen (ADD_NONCE) + strlen (ykc->nonce) + 1;
      url = malloc (len);
      if (!url)
        return YKCLIENT_OUT_OF_MEMORY;

      wrote = snprintf (url, len, "%s" ADD_NONCE "%s", ykc->url, ykc->nonce);
      if (wrote + 1 != len)
        return YKCLIENT_FORMAT_ERROR;
      free (ykc->url);
      ykc->url = url;
    }

  if(ykc->ca_path)
    {
      curl_easy_setopt (ykc->curl, CURLOPT_CAPATH, ykc->ca_path);
    }

  curl_easy_setopt (ykc->curl, CURLOPT_URL, ykc->url);
  curl_easy_setopt (ykc->curl, CURLOPT_WRITEFUNCTION, curl_callback);
  curl_easy_setopt (ykc->curl, CURLOPT_WRITEDATA, (void *) ykc);

  {
    size_t len = strlen (PACKAGE) + 1 + strlen (PACKAGE_VERSION) + 1;
    user_agent = malloc (len);
    if (!user_agent)
      return YKCLIENT_OUT_OF_MEMORY;
    if (snprintf (user_agent, len, "%s/%s", PACKAGE, PACKAGE_VERSION) > 0)
      curl_easy_setopt(ykc->curl, CURLOPT_USERAGENT, user_agent);
  }

  curl_easy_perform (ykc->curl);

  if (ykc->curl_chunk_size == 0 || ykc->curl_chunk == NULL)
    {
      out = YKCLIENT_PARSE_ERROR;
      goto done;
    }

  status = strstr (ykc->curl_chunk, "status=");
  if (!status)
    {
      out = YKCLIENT_PARSE_ERROR;
      goto done;
    }

  while (status[strlen (status) - 1] == '\r'
	 || status[strlen (status) - 1] == '\n')
    status[strlen (status) - 1] = '\0';

  if (strcmp (status, "status=OK") == 0)
    {
      out = YKCLIENT_OK;
      goto done;
    }
  else if (strcmp (status, "status=BAD_OTP") == 0)
    {
      out = YKCLIENT_BAD_OTP;
      goto done;
    }
  else if (strcmp (status, "status=REPLAYED_OTP") == 0)
    {
      out = YKCLIENT_REPLAYED_OTP;
      goto done;
    }
  else if (strcmp (status, "status=REPLAYED_REQUEST") == 0)
    {
      out = YKCLIENT_REPLAYED_REQUEST;
      goto done;
    }
  else if (strcmp (status, "status=BAD_SIGNATURE") == 0)
    {
      out = YKCLIENT_BAD_SIGNATURE;
      goto done;
    }
  else if (strcmp (status, "status=MISSING_PARAMETER") == 0)
    {
      out = YKCLIENT_MISSING_PARAMETER;
      goto done;
    }
  else if (strcmp (status, "status=NO_SUCH_CLIENT") == 0)
    {
      out = YKCLIENT_NO_SUCH_CLIENT;
      goto done;
    }
  else if (strcmp (status, "status=OPERATION_NOT_ALLOWED") == 0)
    {
      out = YKCLIENT_OPERATION_NOT_ALLOWED;
      goto done;
    }
  else if (strcmp (status, "status=BACKEND_ERROR") == 0)
    {
      out = YKCLIENT_BACKEND_ERROR;
      goto done;
    }
  else if (strcmp (status, "status=NOT_ENOUGH_ANSWERS") == 0)
    {
      out = YKCLIENT_NOT_ENOUGH_ANSWERS;
      goto done;
    }

  out = YKCLIENT_PARSE_ERROR;

 done:
  if (user_agent)
    free (user_agent);

  return out;
}
Пример #19
0
int
main (int argc, char **argv)
{
    int                  c;
    char *m4afile =      NULL;
    M4A_TAG_CFG          cfg;

    cfg.mode           = M4A_MODE_INVALID;
    cfg.md5sum         = M4A_FALSE;
    cfg.sha1sum        = M4A_FALSE;
    cfg.art            = M4A_FALSE;
    cfg.pixpath[0]     = '\0';

    while (1)
    {
        static struct option long_options[] =
        {
            {"literal",        no_argument,       0, 'l'},
            {"verbose",        no_argument,       0, 'v'},
            {"with-md5sum",    no_argument,       0, 'm'},
            {"with-sha1sum",   no_argument,       0, 's'},
            {"extract-art",    no_argument,       0, 'e'},
            {"extract-art-to", required_argument, 0, 'p'},
            {"output",         required_argument, 0, 'o'},
            {"help",           no_argument,       0, 'h'},
            {"test",           no_argument,       0, 't'},
            {0, 0, 0, 0}
        };
        /* getopt_long stores the option index. */
        int option_index = 0;

        c = getopt_long (argc, argv, "p:o:lvhtmse",
               long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch (c)
        {
            case 0:
                /* Is mode set ? */
                if (long_options[option_index].flag != 0)
                    break;
                printf ("option %s", long_options[option_index].name);
                if (optarg)
                    printf (" with arg %s", optarg);
                printf ("\n");
                break;

            case 'l':
                cfg.mode = M4A_MODE_LITERAL;
                break;

            case 'v':
                cfg.mode = M4A_MODE_VERBOSE;
                break;

            case 't':
                cfg.mode = M4A_MODE_TESTING;
                break;

            case 'm':
                cfg.md5sum  = M4A_TRUE;
                break;

            case 's':
                cfg.sha1sum = M4A_TRUE;
                break;

            case 'e':
                cfg.art = M4A_TRUE;
                break;

            case 'p':
                cfg.art = M4A_TRUE;
                strcpy(cfg.pixpath, optarg);
                break;

            case 'o':
                printf ("option -o with value `%s'\n", optarg);
                printf ("Not Yet Supported.....\n");
                return 20;

            case 'h':
                printf ("\n%s", USAGE);
                return 0;

            case '?':
                /* getopt_long already printed an error message. */
                return 20;

            default:
                fprintf (stderr, "Invalid Option\n%s\n", USAGE);
                return 30;
        }
    }

    /* Grab File names*/
    if (optind < argc)
    {
        /*  For Later Use only one for now
        while (optind < argc)
        {
            printf ("%s ", argv[optind++]);
        }
        */
        m4afile = argv[optind];
    }
    else
    {
        fprintf(stderr, "No Files specified\n%s", USAGE);
        return 1;
    }

    TestFileExistence(m4afile, true);
    xmlInitEndianDetection();
    
    ExtractPaddingPrefs(NULL);
    
    tree_display_only=true;
    APar_ScanAtoms(m4afile);
    
    if (cfg.mode == M4A_MODE_LITERAL)
    {
        unsigned char *md5sum   =  NULL;
        unsigned char *sha1sum  =  NULL;
        int cnt                 =  0;
        M4A_ART  *art           =  NULL;
        M4A_ART                    bfr[M4A_MAX_ART];
        char     *bfname        =  NULL;
        char                       path[512];


        openSomeFile(m4afile, true);
        get_chksum(&cfg, m4afile, &md5sum, &sha1sum);

        if (cfg.art == M4A_TRUE)
        {
            int   cvr;
            int   idx;
            int   ret;

            cvr = m4a_get_atomidx((const char *) "covr", 1, 0);
            idx = parsedAtoms[cvr].NextAtomNumber;
            while (parsedAtoms[idx].AtomicLevel > parsedAtoms[cvr].AtomicLevel)
            {
                ret = m4a_extract_art(idx, &bfr[cnt]);
                if (ret != 0) break;
                cnt++;
                idx = parsedAtoms[idx].NextAtomNumber;
            }

            if (cnt != 0) 
            {
                char tmp[512];

                strcpy(tmp, m4afile);
                if (cfg.pixpath[0] != '\0')
                {
                    char *bname;
                    strcpy(path, cfg.pixpath);
                    strcat(path, "/");
                    bname = basename(tmp);
                    strcat(path, bname);

                    // printf ("Fname: %s\n", path);
                    bfname = path;
                }
                art = bfr;
            }
            
        }

        redirect_io(&cfg);
        if (metadata_style >= THIRD_GEN_PARTNER) 
        {
            APar_PrintUserDataAssests();
        } 
        else if (metadata_style == ITUNES_STYLE) 
        {
            APar_PrintDataAtoms(m4afile, NULL, 0, PRINT_DATA);
        }
        reset_io(&cfg);
        m4a_display_json_tags(
            cfg.str, stdout, md5sum, sha1sum, art, cnt, bfname);
        openSomeFile(m4afile, false);
    }
    else if (cfg.mode == M4A_MODE_VERBOSE)
    {
        redirect_io(&cfg);
        APar_PrintAtomicTree();
        reset_io(&cfg);
        m4a_display_json_tree(cfg.str, stdout);
    }
    else if (cfg.mode == M4A_MODE_TESTING)
    {
        int mda;
        unsigned char  bfr[2][64];
        int cvr;

        mda = APar_DetermineMediaData_AtomPosition();
        printf ("Location of mdat: %d\n", mda);

        //APar_SimpleAtomPrintout();
        m4a_stream_chksum(m4afile, bfr[0], bfr[1]);

        cvr = m4a_get_atomidx((const char *) "covr", 1, 0);
        printf("\n");
        
    }
    else
    {
        unsigned char *md5sum = NULL, *sha1sum = NULL;

        if (get_chksum(&cfg, m4afile, &md5sum, &sha1sum) == 0)
        {
            if ((md5sum != NULL) || (sha1sum != NULL))
            {
                char pfx[2];

                pfx[0] = '\0';
                printf("{\n    \"stream\": {"); 
                if (md5sum != NULL)
                {
                    printf(" \"md5sum\": \"%s\"", md5sum);
                    pfx[0] = ','; pfx[1] = '\0';
                }

                if (sha1sum != NULL)
                {
                    printf("%s \"sha1sum\": \"%s\"", pfx, sha1sum);
                }
                printf(" }\n}\n"); 
            }
        }
        else if (cfg.art == M4A_TRUE)
        {
            M4A_ART   art[M4A_MAX_ART];
            int       cvr;
            int       idx;
            int       ret;
            int       cnt = 0;
            char      path[512];
            FILE      *fp;
            FILE      *out = stdout;

            if (cfg.pixpath[0] != '\0')
            {
                char tmp[256];
                char *bname = NULL;

                strcpy(tmp, m4afile);
                strcpy(path, cfg.pixpath);
                strcat(path, "/");
                bname = basename(tmp);
                strcat(path, bname);
            }

            fputs ("{\n    \"@img\": [ ", out);
            openSomeFile(m4afile, true);
            cvr = m4a_get_atomidx((const char *) "covr", 1, 0);
            idx = parsedAtoms[cvr].NextAtomNumber;
            while (parsedAtoms[idx].AtomicLevel > parsedAtoms[cvr].AtomicLevel)
            {
                int err = M4A_FALSE;
                const char *extn  = NULL;

                ret = m4a_extract_art(idx, &art[cnt]);
                if (ret != 0) break;

                if ( art[cnt].type == M4A_PNG) 
                {
                    extn = "png";
                }
                else if ( art[cnt].type == M4A_JPG) 
                {
                    extn = "jpg";
                }

                if (cfg.pixpath[0] != '\0')
                {
                    char       fname[512];

                    sprintf(fname, "%s.%d.%s", path, cnt+1, extn);
                    if ((fp = fopen(fname, "wb")) != NULL)
                    {
                        if (fwrite(art[cnt].data, 1, art[cnt].size, fp) !=
                            art[cnt].size)
                        {
                            perror("img write:");
                            err = M4A_TRUE;
                        }
                        fclose(fp);
                    }
                    else
                    {
                        perror("img create:");
                        err = M4A_TRUE; 
                    }

                    if (cnt != 0) fputs(", ", out);
                    if (err == M4A_TRUE)
                        fputs("null", out);
                    else
                        fprintf(out, "\"%s\"", fname);

                }
                else
                {
                    base64_encodestate  inst;
                    char                bfr[M4A_B64_BFR_SZ*2];
                    int                 clen;
                    int                 blks;
                    int                 j;

                    base64_init_encodestate(&inst);

                    blks = art[cnt].size/1024;
                    if (cnt != 0) fputs(", ", out);
                    fprintf (out, "{\"type\": \"%s\", \"data\": \"", extn);
                    for (j = 0; j < blks; j++)
                    {
                        clen = base64_encode_block(
                            (const char*) &art[cnt].data[j * M4A_B64_BFR_SZ],
                            M4A_B64_BFR_SZ,
                            bfr,
                            &inst);
                        //fwrite((void *)bfr, clen, 1, out);
                        m4a_print_without_newlines(out, bfr, clen);
                    }

                    clen = base64_encode_block(
                        (const char*) &art[cnt].data[j * M4A_B64_BFR_SZ],
                        art[cnt].size % M4A_B64_BFR_SZ,
                        bfr,
                        &inst);
                    m4a_print_without_newlines(out, bfr, clen);

                    clen = base64_encode_blockend(bfr, &inst);

                    m4a_print_without_newlines(out, bfr, clen);
                    if (cnt != 0) fputs(", ", out);
                    fputs ("\"}", out);
                }
                cnt++;
                idx = parsedAtoms[idx].NextAtomNumber;
            }
            openSomeFile(m4afile, false);
            fputs (" ]\n}\n", out);
        }
    }
    exit (0);
}
Пример #20
0
void
_wdns_rdata_to_ubuf(ubuf *u, const uint8_t *rdata, uint16_t rdlen,
		    uint16_t rrtype, uint16_t rrclass)
{

#define bytes_required(n) do { \
	if (src_bytes < ((signed) (n))) \
		goto err; \
} while(0)

#define bytes_consumed(n) do { \
	src += n; \
	src_bytes -= n; \
} while(0)

	char domain_name[WDNS_PRESLEN_NAME];
	const record_descr *descr;
	const uint8_t *src;
	size_t len;
	ssize_t src_bytes;
	uint8_t oclen;
	wdns_res res;
	
	if (rrtype < record_descr_len)
		descr = &record_descr_array[rrtype];

	if (rrtype >= record_descr_len || descr->types[0] == rdf_unknown) {
		/* generic encoding */

		ubuf_add_cstr(u, "\\# ");
		ubuf_add_fmt(u, "%u ", rdlen);

		for (unsigned i = 0; i < rdlen; i++)
			ubuf_add_fmt(u, "%02x ", rdata[i]);

		return;

	} else if (!(descr->record_class == class_un ||
		     descr->record_class == rrclass))
	{
		return;
	}

	src = rdata;
	src_bytes = (ssize_t) rdlen;

	for (const uint8_t *t = &descr->types[0]; *t != rdf_end; t++) {
		if (src_bytes == 0)
			break;

		switch (*t) {
		case rdf_name:
		case rdf_uname:
			res = wdns_len_uname(src, src + src_bytes, &len);
			if (res != wdns_res_success) {
				src_bytes = 0;
				goto err_res;
			}
			wdns_domain_to_str(src, len, domain_name);
			ubuf_add_cstr(u, domain_name);
			ubuf_add_cstr(u, " ");
			bytes_consumed(len);
			break;

		case rdf_bytes:
			len = src_bytes;
			while (len > 0) {
				ubuf_add_fmt(u, "%02X", *src);
				src++;
				len--;
			}
			src_bytes = 0;
			break;

		case rdf_bytes_b64: {
			base64_encodestate b64;
			char *buf;
			base64_init_encodestate(&b64);
			buf = alloca(2 * src_bytes + 1);
			len = base64_encode_block((const char *) src, src_bytes, buf, &b64);
			ubuf_append(u, (uint8_t *) buf, len);
			len = base64_encode_blockend(buf, &b64);
			ubuf_append(u, (uint8_t *) buf, len);
			src_bytes = 0;
			break;
		}

		case rdf_ipv6prefix:
			bytes_required(1);
			len = oclen = *src++;
			bytes_required(1 + oclen);
			while (len > 0) {
				ubuf_add_fmt(u, "%02x", *src);
				src++;
				len--;
			}
			ubuf_add_cstr(u, " ");
			src_bytes -= oclen + 1;
			break;

		case rdf_salt:
			bytes_required(1);
			len = oclen = *src++;
			bytes_required(1 + oclen);
			if (oclen == 0)
				ubuf_add_cstr(u, "-");
			while (len > 0) {
				ubuf_add_fmt(u, "%02x", *src);
				src++;
				len--;
			}
			ubuf_add_cstr(u, " ");
			src_bytes -= oclen + 1;
			break;

		case rdf_hash: {
			char *buf;
			bytes_required(1);
			oclen = *src++;
			bytes_required(1 + oclen);
			buf = alloca(2 * oclen + 1);
			len = base32_encode(buf, 2 * oclen + 1, src, oclen);
			ubuf_append(u, (uint8_t *) buf, len);
			ubuf_add_cstr(u, " ");
			src += oclen;
			src_bytes -= oclen + 1;
			break;
		}

		case rdf_int8: {
			uint8_t val;
			bytes_required(1);
			memcpy(&val, src, sizeof(val));
			ubuf_add_fmt(u, "%u ", val);
			bytes_consumed(1);
			break;
		}

		case rdf_int16: {
			uint16_t val;
			bytes_required(2);
			memcpy(&val, src, sizeof(val));
			val = ntohs(val);
			ubuf_add_fmt(u, "%hu ", val);
			bytes_consumed(2);
			break;
		}

		case rdf_int32: {
			uint32_t val;
			bytes_required(4);
			memcpy(&val, src, sizeof(val));
			val = ntohl(val);
			ubuf_add_fmt(u, "%u ", val);
			bytes_consumed(4);
			break;
		}

		case rdf_ipv4: {
			char pres[WDNS_PRESLEN_TYPE_A];
			bytes_required(4);
			inet_ntop(AF_INET, src, pres, sizeof(pres));
			ubuf_add_cstr(u, pres);
			ubuf_add_cstr(u, " ");
			bytes_consumed(4);
			break;
		}

		case rdf_ipv6: {
			char pres[WDNS_PRESLEN_TYPE_AAAA];
			bytes_required(16);
			inet_ntop(AF_INET6, src, pres, sizeof(pres));
			ubuf_add_cstr(u, pres);
			ubuf_add_cstr(u, " ");
			bytes_consumed(16);
			break;
		}

		case rdf_string: {
			bytes_required(1);
			oclen = *src;
			bytes_required(1 + oclen);
			len = rdata_to_str_string(src, u);
			bytes_consumed(len);
			break;
		}

		case rdf_repstring:
			while (src_bytes > 0) {
				bytes_required(1);
				oclen = *src;
				bytes_required(1 + oclen);
				len = rdata_to_str_string(src, u);
				bytes_consumed(len);
			}
			break;

		case rdf_rrtype: {
			const char *s_rrtype;
			uint16_t my_rrtype;

			bytes_required(2);
			memcpy(&my_rrtype, src, 2);
			my_rrtype = ntohs(my_rrtype);
			bytes_consumed(2);

			s_rrtype = wdns_rrtype_to_str(my_rrtype);
			if (s_rrtype != NULL) {
				ubuf_add_cstr(u, s_rrtype);
				ubuf_add_cstr(u, " ");
			} else {
				ubuf_add_fmt(u, "TYPE%hu ", my_rrtype);
			}

			break;
		}

		case rdf_type_bitmap: {
			const char *s_rrtype;
			uint16_t my_rrtype, lo;
			uint8_t a, b, window_block, bitmap_len;

			bytes_required(2);
			while (src_bytes >= 2) {
				window_block = *src;
				bitmap_len = *(src + 1);
				bytes_consumed(2);
				bytes_required(bitmap_len);
				lo = 0;
				for (int i = 0; i < bitmap_len; i++) {
					a = src[i];
					for (int j = 1; j <= 8; j++) {
						b = a & (1 << (8 - j));
						if (b != 0) {
							my_rrtype = (window_block << 16) | lo;
							s_rrtype = wdns_rrtype_to_str(my_rrtype);
							if (s_rrtype != NULL) {
								ubuf_add_cstr(u, s_rrtype);
								ubuf_add_cstr(u, " ");
							} else {
								ubuf_add_fmt(u, "TYPE%hu ", my_rrtype);
							}
						}
						lo += 1;
					}
				}
				bytes_consumed(bitmap_len);
			}
			break;
		} /* end case */

		}
	}

	/* truncate trailing " " */
	if (ubuf_size(u) > 0 && ubuf_value(u, ubuf_size(u) - 1) == ' ')
		ubuf_clip(u, ubuf_size(u) - 1);
	
	return;

err:
	ubuf_add_fmt(u, " ### PARSE ERROR ###");
	return;

err_res:
	ubuf_add_fmt(u, " ### PARSE ERROR #%u ###", res);
	return;
}
Пример #21
0
struct acl *
conf_parse_acl(json_t *j) {

	json_t *jcidr, *jbasic, *jlist;
	unsigned short mask_bits = 0;

	struct acl *a = calloc(1, sizeof(struct acl));

	/* parse CIDR */
	if((jcidr = json_object_get(j, "ip")) && json_typeof(jcidr) == JSON_STRING) {
		const char *s;
		char *p, *ip;

		s = json_string_value(jcidr);
		p = strchr(s, '/');
		if(!p) {
			ip = strdup(s);
		} else {
			ip = calloc((size_t)(p - s + 1), 1);
			memcpy(ip, s, (size_t)(p - s));
			mask_bits = (unsigned short)atoi(p+1);
		}
		a->cidr.enabled = 1;
		a->cidr.mask = (mask_bits == 0 ? 0xffffffff : (0xffffffff << (32 - mask_bits)));
		a->cidr.subnet = ntohl(inet_addr(ip)) & a->cidr.mask;
		free(ip);
	}

	/* parse basic_auth */
	if((jbasic = json_object_get(j, "http_basic_auth")) && json_typeof(jbasic) == JSON_STRING) {

		/* base64 encode */
		base64_encodestate b64;
		int pos;
		char *p;
		const char *plain = json_string_value(jbasic);
		size_t len, plain_len = strlen(plain) + 0;
		len = (plain_len + 8) * 8 / 6;
		a->http_basic_auth = calloc(len, 1);
		
		base64_init_encodestate(&b64);
		pos = base64_encode_block(plain, (int)plain_len, a->http_basic_auth, &b64); /* FIXME: check return value */
		base64_encode_blockend(a->http_basic_auth + pos, &b64);

		/* end string with \0 rather than \n */
		if((p = strchr(a->http_basic_auth + pos, '\n'))) {
			*p = 0;
		}
	}

	/* parse enabled commands */
	if((jlist = json_object_get(j, "enabled")) && json_typeof(jlist) == JSON_ARRAY) {
		acl_read_commands(jlist, &a->enabled);
	}

	/* parse disabled commands */
	if((jlist = json_object_get(j, "disabled")) && json_typeof(jlist) == JSON_ARRAY) {
		acl_read_commands(jlist, &a->disabled);
	}

	return a;
}
Пример #22
0
int
sc_vtk_write_compressed (FILE * vtkfile, char *numeric_data,
                         size_t byte_length)
{
  int                 retval, fseek1, fseek2;
  size_t              iz;
  size_t              blocksize, lastsize;
  size_t              theblock, numregularblocks, numfullblocks;
  size_t              header_entries;
  size_t              code_length, base_length;
  long                header_pos, final_pos;
  char               *comp_data, *base_data;
  uint32_t           *compression_header;
  uLongf              comp_length;
  base64_encodestate  encode_state;

  /* compute block sizes */
  blocksize = (size_t) (1 << 15);       /* 32768 */
  lastsize = byte_length % blocksize;
  numregularblocks = byte_length / blocksize;
  numfullblocks = numregularblocks + (lastsize > 0 ? 1 : 0);

  /* allocate compression and base64 arrays */
  code_length = 2 * blocksize;
  comp_data = SC_ALLOC (char, code_length);
  base_data = SC_ALLOC (char, code_length);

  /* figure out the size of the header and write a dummy */
  header_entries = 3 + numfullblocks;
  compression_header = SC_ALLOC (uint32_t, header_entries);
  compression_header[0] = (uint32_t) numfullblocks;
  compression_header[1] = (uint32_t) blocksize;
  compression_header[2] = (uint32_t)
    (lastsize > 0 || byte_length == 0 ? lastsize : blocksize);
  for (iz = 3; iz < header_entries; ++iz) {
    compression_header[iz] = 0;
  }
  base64_init_encodestate (&encode_state);
  base_length = base64_encode_block ((char *) compression_header,
                                     sizeof (*compression_header) *
                                     header_entries, base_data,
                                     &encode_state);
  base_length +=
    base64_encode_blockend (base_data + base_length, &encode_state);
  base_data[base_length] = '\0';
  SC_ASSERT (base_length < code_length);
  header_pos = ftell (vtkfile);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  /* write the regular data blocks */
  base64_init_encodestate (&encode_state);
  for (theblock = 0; theblock < numregularblocks; ++theblock) {
    comp_length = code_length;
    retval = compress2 ((Bytef *) comp_data, &comp_length,
                        (const Bytef *) (numeric_data + theblock * blocksize),
                        (uLong) blocksize, Z_BEST_COMPRESSION);
    SC_ASSERT (retval == Z_OK);
    compression_header[3 + theblock] = comp_length;
    base_length = base64_encode_block (comp_data, comp_length,
                                       base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
  }

  /* write odd-sized last block if necessary */
  if (lastsize > 0) {
    comp_length = code_length;
    retval = compress2 ((Bytef *) comp_data, &comp_length,
                        (const Bytef *) (numeric_data + theblock * blocksize),
                        (uLong) lastsize, Z_BEST_COMPRESSION);
    SC_ASSERT (retval == Z_OK);
    compression_header[3 + theblock] = comp_length;
    base_length = base64_encode_block (comp_data, comp_length,
                                       base_data, &encode_state);
    base_data[base_length] = '\0';
    SC_ASSERT (base_length < code_length);
    (void) fwrite (base_data, 1, base_length, vtkfile);
  }

  /* write base64 end block */
  base_length = base64_encode_blockend (base_data, &encode_state);
  (void) fwrite (base_data, 1, base_length, vtkfile);

  /* seek back, write header block, seek forward */
  final_pos = ftell (vtkfile);
  base64_init_encodestate (&encode_state);
  base_length = base64_encode_block ((char *) compression_header,
                                     sizeof (*compression_header) *
                                     header_entries, base_data,
                                     &encode_state);
  base_length +=
    base64_encode_blockend (base_data + base_length, &encode_state);
  base_data[base_length] = '\0';
  SC_ASSERT (base_length < code_length);
  fseek1 = fseek (vtkfile, header_pos, SEEK_SET);
  (void) fwrite (base_data, 1, base_length, vtkfile);
  fseek2 = fseek (vtkfile, final_pos, SEEK_SET);

  /* clean up and return */
  SC_FREE (compression_header);
  SC_FREE (comp_data);
  SC_FREE (base_data);
  if (fseek1 != 0 || fseek2 != 0 || ferror (vtkfile)) {
    return -1;
  }
  return 0;
}
int Base64encoder::encode_end(char* plaintext_out)
{
    return base64_encode_blockend(plaintext_out, &_state);
}