TITANIUM_FUNCTION(Utils, base64decode)
	{
		if (arguments.size() >= 1) {
			const auto _0 = arguments.at(0);

			// Titanium.Blob / Titanium.Filesystem.File
			if (_0.IsObject()) {
				const auto js_obj = static_cast<JSObject>(_0);

				// Titanium.Blob
				const auto blob_obj = js_obj.GetPrivate<Blob>();
				if (blob_obj != nullptr) {
					return static_cast<JSValue>(base64decode(blob_obj)->get_object());
				}

				// Titanium.Filesystem.File
				const auto file_obj = js_obj.GetPrivate<Filesystem::File>();
				if (file_obj != nullptr) {
					return static_cast<JSValue>(base64decode(file_obj)->get_object());
				}

			// String
			} else if (_0.IsString()) {
				auto obj = static_cast<std::string>(_0);
				return static_cast<JSValue>(base64decode(obj)->get_object());
			}
		}
		return get_context().CreateUndefined();
	}
예제 #2
0
파일: bitmap.c 프로젝트: CynicRus/CMML
bool bitmap_from_32bit_string(bitmap *bmp, const char *str)
{
    if (!bmp || bmp->pixels)
        return false;

    char *buffer;
    uint32_t buff_len;

    if ((str[0] == 'm') && base64decode((const uint8_t *)&str[1], strlen(&str[1]), &buffer, &buff_len))
    {
        uint32_t size = ((bmp->width * 32 + 31) / 32) * 4 * bmp->height;
        bmp->pixels = malloc(size);

        if (bmp->pixels)
        {
            if (uncompress((Bytef *)bmp->pixels, (uLongf *)&size, (Bytef *)buffer, buff_len) == Z_OK)
            {
                free(buffer);
                return true;
            }

            free(bmp->pixels);
        }

        free(buffer);
    }

    bmp->width = 0;
    bmp->height = 0;
    bmp->pixels = NULL;
    return false;
}
예제 #3
0
파일: base64.cpp 프로젝트: aivarsk/fuxedo
static std::string b64decode(const std::string &s) {
  std::string result;
  result.resize(s.size() * 2 + 3);
  auto n = base64decode(s.data(), s.size(), &result[0], result.size());
  result.resize(n);
  return result;
}
예제 #4
0
void test_base64(void)
{
	/* The string "Hello, world" should encode as "SGVsbG8sIHdvcmxk" */
  const unsigned char	*input = (const unsigned char *)"Hello, world";
	unsigned char	 output[100];
	unsigned char	 decode[100];
	unsigned int	 i;

	for (i = 0; i < 100; i++) {
		output[i] = '\0';
	}

	printf("Base64 encode.......................... "); fflush(stdout);
	i = base64encode(input, strlen((char *)input), output, 100);
	if ((i != 16) || (strncmp((char *)output, "SGVsbG8sIHdvcmxk", i) != 0)) {
		printf("fail\n");
		return;
	}
	printf("pass\n");

	printf("Base64 decode.......................... "); fflush(stdout);
	i = base64decode(output, i, decode, 100);
	if ((i != 12) || (strncmp((char *)decode, "Hello, world", i) != 0)) {
		printf("fail\n");
		return;
	}
	printf("pass\n");
}
예제 #5
0
// RSA decrypting of a block of data in ctext into ptext
// This code assumes the RSA public key is embedded in PEM format in 
// the executable via simlib as 'simatra'
int decode(int clen, unsigned char *ctext, int *plen, unsigned char *ptext){
  RSA *rsa_pub;
  BIO *mem;
  char *keydata;
  int keylen;
  int tmp_clen;
  unsigned char tmp_ctext[KEYLEN];

  // Check for valid sizes and existence of buffers
  if(clen < 0 || clen > B64LEN || NULL == ctext || NULL == ptext){
    return 1;
  }

  // Read in the RSA public key
  if(get_contents_from_archive("", "simatra", &keylen, &keydata)){
    return 2;
  }
  mem = BIO_new_mem_buf(keydata, keylen);
  rsa_pub = PEM_read_bio_RSA_PUBKEY(mem, NULL, NULL, NULL);
  BIO_free(mem);
  if(NULL == rsa_pub){
    return 3;
  }

  // Convert the base64 encoded license to the raw encrypted cipher text form
  base64decode(clen, ctext, &tmp_clen, tmp_ctext);

  // Decrypt the cipher text into plain text
  *plen = RSA_public_decrypt(tmp_clen, tmp_ctext, ptext, rsa_pub, RSA_PKCS1_PADDING);
  if(*plen < 1)
    return 4;

  return 0;
}
/* detection functions */
int rule13308eval(void *p) {
    const u_int8_t *cursor_normal = 0;
    const u_int8_t *beg_of_buffer, *end_of_buffer;

    SFSnortPacket *sp = (SFSnortPacket *) p;
    
    // Base64 stuff
    u_int8_t base64buf[256], decodedbuf[256];
    u_int32_t inputchars, base64bytes, decodedbytes;

    int i;

    if(sp == NULL)
        return RULE_NOMATCH;

    // flow:established, to_server;
    if (checkFlow(p, rule13308options[0]->option_u.flowFlags) <= 0)
        return RULE_NOMATCH;

    // Doing this content match is pretty useless because it's duplicated in our PCRE.
    // But we want to keep the structure for the pattern matcher.
//    // content:"Authorization|3A|", depth 0, nocase, fast_pattern;
//    if (contentMatch(p, rule13308options[1]->option_u.content, &cursor_normal) <= 0)
//        return RULE_NOMATCH;

    // pcre:"^Authorization\x3A\s*Basic[ \t]+", dotall, multiline, nocase;
    if (pcreMatch(p, rule13308options[2]->option_u.pcre, &cursor_normal) <= 0)
        return RULE_NOMATCH;

    if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &beg_of_buffer, &end_of_buffer) != CURSOR_IN_BOUNDS)
        return RULE_NOMATCH;

    // At this point, cursor should point to the start of the auth data
    inputchars = (end_of_buffer > cursor_normal + sizeof(base64buf)) ? sizeof(base64buf) : end_of_buffer - cursor_normal;

    DEBUG_SO(printf("%d input chars: %*s\n", inputchars, inputchars, cursor_normal));

    if(unfold_header(cursor_normal, inputchars, base64buf, sizeof(base64buf), &base64bytes) != 0)
        return RULE_NOMATCH;

    DEBUG_SO(printf("Successfully unfolded header (%s)(%d)\n", base64buf, base64bytes));

    if(base64decode(base64buf, base64bytes, decodedbuf, sizeof(decodedbuf), &decodedbytes) < 0)
        return RULE_NOMATCH;

    DEBUG_SO(printf("Successfully base64 decoded (%s)(%d)\n", decodedbuf, decodedbytes));
  
    for(i=0; i<decodedbytes; i++) {
        DEBUG_SO(printf("checking byte: %c\n", decodedbuf[i]));
        if(decodedbuf[i] == '%') {
            return RULE_MATCH;
        } else if(decodedbuf[i] == ':') {
            // Separator between username:password
            return RULE_NOMATCH;
        }
    }        
        
    return RULE_NOMATCH;
}
예제 #7
0
int b64Decode(const char *b64Data, int32_t b64length, uint8_t *binData, size_t binLength)
{
    if (b64length == 0)
        return 0;

    size_t codelength = binLength;
    base64decode (b64Data, b64length, binData, &codelength);
    return codelength;
}
// Receive a NET msg from the OVMS server
void net_msg_in(char* msg)
  {
  int k;

  if (net_msg_serverok == 0)
    {
    if (memcmppgm2ram(msg, (char const rom far*)"MP-S 0 ", 7) == 0)
      {
      net_msg_server_welcome(msg+7);
      }
    return; // otherwise ignore it
    }

  // Ok, we've got an encrypted message waiting for work.
  // The following is a nasty hack because base64decode doesn't like incoming
  // messages of length divisible by 4, and is really expecting a CRLF
  // terminated string, so we give it one...
  strcatpgm2ram(msg,(char const rom far*)"\r\n");
  k = base64decode(msg,net_scratchpad);
  RC4_crypt(&rx_crypto1, &rx_crypto2, net_scratchpad, k);
  if (memcmppgm2ram(net_scratchpad, (char const rom far*)"MP-0 ", 5) == 0)
    {
    msg = net_scratchpad+5;
    switch (*msg)
      {
      case 'A': // PING
        strcpypgm2ram(net_scratchpad,(char const rom far*)"MP-0 a");
        if (net_msg_sendpending==0)
          {
          net_msg_start();
          net_msg_encode_puts();
          net_msg_send();
          }
        break;
      case 'Z': // PEER connection
        if (msg[1] != '0')
          {
          net_apps_connected = 1;
          if (net_msg_sendpending==0)
            {
            net_msg_start();
            net_msg_stat();
            net_msg_gps();
            net_msg_tpms();
            net_msg_firmware();
            net_msg_environment();
            net_msg_send();
            }
          }
        else
          {
          net_apps_connected = 0;
          }
        break;
      }
    }
  }
예제 #9
0
파일: base64.c 프로젝트: bruceg/ucspi-proxy
int main(int argc, char* argv[])
{
  int i;
  int r;
  str d = {0,0,0};
  for (i = 1; i < argc; i++) {
    int r = base64decode(argv[i], strlen(argv[i]), &d);
    printf("argv[%d] = %d: '%s'\n", i, r, d.s);
  }
  return 0;
}
예제 #10
0
int WebServerBaseClass::parseAuth(char *auth_header, char *out, int out_len)//returns 0 on unknown auth, 1 on basic
{
  char *authstr=auth_header;
  *out=0;
  if (!auth_header || !*auth_header) return 0;
  while (*authstr == ' ') authstr++;
  if (strnicmp(authstr,"basic ",6)) return 0;
  authstr+=6;
  while (*authstr == ' ') authstr++;
  base64decode(authstr,out,out_len);
  return 1;
}
예제 #11
0
static void handle_auth_login_response(str* line, ssize_t offset)
{
  saw_auth_login = 0;
  if (!base64decode(line->s + offset, line->len + offset, &tmpstr))
    username.len = 0;
  else {
    make_username(tmpstr.s, tmpstr.len, "AUTH LOGIN ");
    line->len = offset;
    base64encode(username.s, username.len, line);
    str_catb(line, CRLF, 2);
  }
}
예제 #12
0
파일: bitmap.c 프로젝트: CynicRus/CMML
bool bitmap_from_24bit_string(bitmap *bmp, const char *str)
{
    if (!bmp || bmp->pixels)
        return false;

    int I, J;
    char *buffer;
    uint32_t buff_len;

    if ((str[0] == 'm') && base64decode((const uint8_t *)&str[1], strlen(&str[1]), &buffer, &buff_len))
    {
        uint32_t size = ((bmp->width * 24 + 31) / 32) * 4 * bmp->height;
        rgb24 *pixels = malloc(size);

        if (pixels)
        {
            if (uncompress((Bytef *)pixels, (uLongf *)&size, (Bytef *)buffer, buff_len) == Z_OK)
            {
                bmp->pixels = malloc(((bmp->width * 32 + 31) / 32) * 4 * bmp->height);
                if (bmp->pixels)
                {
                    for (I = 0; I < bmp->height; ++I)
                    {
                        for (J = 0; J < bmp->width; ++J)
                        {
                            bmp->pixels[I * bmp->width + J].r = pixels[I * bmp->width + J].b;
                            bmp->pixels[I * bmp->width + J].g = pixels[I * bmp->width + J].g;
                            bmp->pixels[I * bmp->width + J].b = pixels[I * bmp->width + J].r;
                            bmp->pixels[I * bmp->width + J].a = 0xFF;
                        }
                    }

                    free(pixels);
                    free(buffer);
                    return true;
                }
            }
            free(pixels);
        }
        free(buffer);
    }

    bmp->width = 0;
    bmp->height = 0;
    bmp->pixels = NULL;
    return false;
}
예제 #13
0
// read and verify whether the csr's signature is valid. Returns 1 if it is, otherwise 0.
unsigned char read_csr(unsigned int *id, char *cname, char time[TIME_BUFFER_SIZE], unsigned char auth_key[SMQV_PKEY_SIZE], unsigned char token_key[MSS_PKEY_SIZE], unsigned char csr_signature[MSS_SIGNATURE_SIZE], char csr[CSR_MAX_SIZE]) {
	unsigned int index = 0;
	int csr_size = CSR_MAX_SIZE;
	unsigned char buffer[CSR_MAX_SIZE];
	memset(buffer, 0, CSR_MAX_SIZE);
	char t_now[TIME_BUFFER_SIZE];
	now(&t_now);
	base64decode(csr, strlen(csr), buffer, &csr_size);

	csr_split_info(buffer, id, cname, time, auth_key, token_key, csr_signature);

        unsigned char digest[2 * MSS_SEC_LVL];
	index = csr_append_info(buffer, *id, cname, time, auth_key, token_key);
        sponge_hash(buffer, index, digest, 2 * MSS_SEC_LVL);

	// verify [(id || cname || time || auth_key || token_key), csr_signature, token_key]
	return mss_verify(csr_signature, token_key, digest) && compare_dates(time, t_now) != -1;
}
예제 #14
0
static void handle_auth_plain_response(str* line, ssize_t offset)
{
  int start;
  int end;

  saw_auth_plain = 0;
  if (base64decode(line->s + offset, line->len - offset, &tmpstr)) {
    /* tmpstr should now contain "AUTHORIZATION\0AUTHENTICATION\0PASSWORD" */
    if ((start = str_findfirst(&tmpstr, NUL)) >= 0
	&& (end = str_findnext(&tmpstr, NUL, ++start)) > start) {
      make_username(tmpstr.s + start, end - start, "AUTH PLAIN ");
      str_splice(&tmpstr, start, end - start, &username);
      line->len = offset;
      base64encode(tmpstr.s, tmpstr.len, line);
      str_catb(line, CRLF, 2);
    }
  }
}
예제 #15
0
파일: test18.c 프로젝트: ernelli/matasano
int main(int argc, char *argv[]) {
  unsigned char data[1024], testblock[1024], plaintext[1024], nonce[16];
  int len;

  char *ciphertext = "L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ==";

  len = base64decode(ciphertext, strlen(ciphertext), data);

  memset(nonce, 0, 16);

  aes_ctr_decrypt(data, len, "YELLOW SUBMARINE", 16, nonce, 0, 0);

  data[len] = '\0';

  //hexdump(data, len);
  printf("%s\n", data);

  return 0;
}
예제 #16
0
// return 1 if certificate is valid, 0 otherwise
unsigned char read_certificate(unsigned int *id, char *cname, char time[TIME_BUFFER_SIZE], char valid[TIME_BUFFER_SIZE], unsigned char auth_key[SMQV_PKEY_SIZE], unsigned char token_key[MSS_PKEY_SIZE], unsigned char cert_signature[ECDSA_SIGNATURE_SIZE], const unsigned char ca_pkey[ECDSA_PKEY_SIZE], const unsigned char certificate[CERTIFICATE_MAX_SIZE]) {
	unsigned int index = 0;
	int certificate_size = CERTIFICATE_MAX_SIZE;
	unsigned char buffer[CERTIFICATE_MAX_SIZE];
	char t_now[TIME_BUFFER_SIZE];

	now(&t_now);
	memset(buffer, 0, CERTIFICATE_MAX_SIZE);
	base64decode(certificate, strlen(certificate), buffer, &certificate_size);

	cert_split_info(buffer, id, cname, time, valid, auth_key, token_key, cert_signature);

	unsigned char cert_digest[2 * MSS_SEC_LVL];
	index = cert_append_info(buffer, *id, cname, time, valid, auth_key, token_key);
        sponge_hash(buffer, index, cert_digest, 2 * MSS_SEC_LVL);

	// verify [(id || cname || time || valid || auth_key || token_key), csr_signature, token_key]
	return compare_dates(t_now, time) <= 0 && compare_dates(t_now, valid) >= 0 && ecdsa_verify(ca_pkey, cert_digest, cert_signature);
}
예제 #17
0
int dlg_th_decode_callid(struct sip_msg *msg)
{
	struct lump *del;
	str new_callid;
	int i,max_size;

	if (msg->callid == NULL) {
		LM_ERR("Message with no callid\n");
		return -1;
	}

	max_size = calc_max_base64_decode_len(msg->callid->body.len - topo_hiding_prefix.len);
	new_callid.s = pkg_malloc(max_size);
	if (new_callid.s==NULL) {
		LM_ERR("No more pkg\n");
		return -1;
	}
		
	new_callid.len = base64decode((unsigned char *)(new_callid.s),
			(unsigned char *)(msg->callid->body.s + topo_hiding_prefix.len),
			msg->callid->body.len - topo_hiding_prefix.len);
	for (i=0;i<new_callid.len;i++)
		new_callid.s[i] ^= topo_hiding_seed.s[i%topo_hiding_seed.len]; 

	del=del_lump(msg, msg->callid->body.s-msg->buf, msg->callid->body.len, HDR_CALLID_T);
	if (del==NULL) {               
		LM_ERR("Failed to delete old callid\n");
		pkg_free(new_callid.s);
		return -1;
	}

	if (insert_new_lump_after(del,new_callid.s,new_callid.len,HDR_CALLID_T)==NULL) {
		LM_ERR("Failed to insert new callid\n");
		pkg_free(new_callid.s);
		return -1;
	}

	return 0;

	return 0;
}
예제 #18
0
파일: test1.c 프로젝트: ernelli/matasano
int main(int argc, char *argv[]) {
  char inbuf[256];
  char b64buf[256];
  char hexbuf[256];

  int len;

  unsigned char binbuf[256];

  fgets(inbuf, sizeof(inbuf), stdin);
  len = hexdecode(inbuf, binbuf);
  len = base64encode(binbuf, len, b64buf);
  b64buf[len] = '\0';
  printf("%s\n", b64buf);
  len = base64decode(b64buf, len, binbuf);
  hexencode(binbuf, len,  hexbuf);
  hexbuf[2*len] = '\0';
  printf("%s\n", hexbuf);

  return 0;
}
예제 #19
0
파일: main.c 프로젝트: daolong/cencrypt
static void flow_test() {
  DEBUG("\n\n== flow_test ==\n");  
  size_t resp_size = 0;
  size_t out_len = 0;
  char buffer[1024];
  DO_CLEAR(buffer, 0, 1024);
  sprintf(buffer, "{\"name\"=\"%s\", \"number\"=\"%s\", \"class\"=\"%s\", \"memo\"=\"%s\"}", 
    TEST_NAME, TEST_NUMBER, TEST_CLASS, TEST_MEMO);
  DEBUG("param = %s\n", buffer);  
  int len = strlen(buffer);
  char *cipher = encrypt_publickey_fromcode(buffer);   
  if (cipher != NULL) {
    DEBUG("The cipher text = %s \n", cipher);
    dump((const unsigned char *)cipher);
    char *encoded = base64encode_rsa(cipher,&out_len);
    if (encoded != NULL) {
      DEBUG("%s : encoded = %s \n", __func__, encoded);
      char *decode = base64decode((const unsigned char *)encoded, &out_len);
      if (decode != NULL) {
        DEBUG("local : content encrypted = %s \n", decode);
        dump((const unsigned char *)decode);
        char *plaintext = decrypt_privatekey_fromcode(decode);
        if (plaintext != NULL) {
            DEBUG("local : content decrypted = %s \n", plaintext);
            DO_FREE(plaintext);
        }
        DO_FREE(decode);
      }
    }
    
    char *plaintext_local = decrypt_privatekey_fromcode(cipher);
    if (plaintext_local != NULL) {
        DEBUG("content decrypted local = %s \n", plaintext_local);
        DO_FREE(plaintext_local);
    }
    
    free(cipher);
    cipher = NULL;
  }   
}
예제 #20
0
파일: base64.c 프로젝트: att/ast
// TODO: What shall we do with the test in 'src/lib/libast/tests/misc/base64.c' ?
tmain() {
    UNUSED(argc);
    UNUSED(argv);

    char encoded_result[1024];
    char decoded_result[1024];
    ssize_t result_size;

    for (int i = 0; tests[i].string; ++i) {
        // TODO: What does the third parameter of this function do ? It's not used by ksh.
        result_size = base64encode(tests[i].string, strlen(tests[i].string), NULL, encoded_result,
                                   sizeof(encoded_result));

        if (result_size != strlen(encoded_result)) {
            terror("base64encode() :: Invalid return value :: Expected: %d, Actual: %d",
                   strlen(encoded_result), result_size);
        }

        if (strcmp(tests[i].base64_string, encoded_result)) {
            terror("base64encode() :: Invalid result :: Expected: %s, Actual: %s",
                   tests[i].base64_string, encoded_result);
        }

        result_size = base64decode(encoded_result, strlen(encoded_result), NULL, decoded_result,
                                   sizeof(decoded_result));

        if (result_size != strlen(decoded_result)) {
            terror("base64encode() :: Invalid return value :: Expected: %d, Actual: %d",
                   strlen(decoded_result), result_size);
        }

        if (strcmp(decoded_result, tests[i].string)) {
            terror("base64decode() :: Invalid result :: Expected: %s, Actual: %s", tests[i].string,
                   decoded_result);
        }
    }

    texit(0);
}
예제 #21
0
파일: mtypes.c 프로젝트: smokku/libgmbus
/* Data */
MObject *
mbus_data_new( const guint8 * str, guint len, gboolean decode )
{
  M_OBJECT_ALLOC( MData, MDATA );

  if ( str ) {
    if ( decode ) {
      GByteArray * tmp = g_byte_array_sized_new( len );

      me->array = g_byte_array_new();
      g_byte_array_append( tmp, str, len );
      base64decode( tmp, me->array );

      g_byte_array_free( tmp, TRUE );
    } else {
      me->array = g_byte_array_sized_new( len );
      g_byte_array_append( me->array, str, len );
    }
  } else
    me->array = g_byte_array_new();

  return obj;
}
/* detection functions */
int rule17697eval(void *p) {
    const uint8_t *cursor_normal = 0;
    const uint8_t *beg_of_buffer, *end_of_buffer;

    uint8_t decodedbuf[MAX_BASE64_BUFFER_SIZE], *decodedbuf_ptr;
    uint32_t inputchars, decodedbytes;
    SFSnortPacket *sp = (SFSnortPacket *) p;

    uint32_t tmpval = 0;

    if(sp == NULL)
        return RULE_NOMATCH;

    if(sp->payload == NULL)
        return RULE_NOMATCH;
    
    // flow:established, to_server;
    if (checkFlow(p, rule17697options[0]->option_u.flowFlags) > 0 ) {
        // content:"-----BEGIN PGP MESSAGE-----", depth 0, nocase, fast_pattern;
        if (contentMatch(p, rule17697options[1]->option_u.content, &cursor_normal) > 0) {
            DEBUG_SO(printf("Matched the PGP header\n"));

            // content:"Version|3A|", offset 2, depth 8, nocase, relative;
            if (contentMatch(p, rule17697options[2]->option_u.content, &cursor_normal) > 0) {
                DEBUG_SO(printf("Matched the version\n"));

                // content:"|0D 0A 0D 0A|", depth 0, relative;
                if (contentMatch(p, rule17697options[3]->option_u.content, &cursor_normal) > 0) {
                    DEBUG_SO(printf("Matched the newline\n"));

                    if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &beg_of_buffer, &end_of_buffer) != CURSOR_IN_BOUNDS)
                        return RULE_NOMATCH;
               
                    // We should now be at the beginning of the PGP data
                    // Four base64 input chars become three output chars
                    inputchars = (end_of_buffer > cursor_normal + (sizeof(decodedbuf) * 4 / 3)) ? (sizeof(decodedbuf) * 4 / 3) : end_of_buffer - cursor_normal;
                    DEBUG_SO(printf("Decoding %d bytes\n", inputchars));

                    // Only need 6 output bytes, plus 1 byte for the NULL added by base64decode()
                    if(base64decode(cursor_normal, inputchars, decodedbuf, 7, &decodedbytes) < 0) {
                        DEBUG_SO(printf("Failed to decode any data to work with\n"));
                        return RULE_NOMATCH;
                    }
                    
                    DEBUG_SO(printf("Decoded %d bytes\n", decodedbytes));

                    // Make sure we have enough data to work with
                    if(decodedbytes >= 6) {
                        decodedbuf_ptr = decodedbuf;

                        // New format with content tag of 16 or 61 (both in the first byte)
                        DEBUG_SO(printf("Packet format: %01x\n", decodedbuf[0]));

                        // The top two bits are set, the lower six we want to be either 16 or 61.
                        // 0xC0 + 16 = 0xD0,  0xC0 + 61 = 0xFD
                        if((decodedbuf[0] == (uint8_t)0xD0) || (decodedbuf[0] == (uint8_t)0xFD)) {

                            if(decodedbuf[1] == 0xFF) {
                               decodedbuf_ptr = decodedbuf + 2;

                               tmpval =  *decodedbuf_ptr++;
                               tmpval |= *decodedbuf_ptr++ << 8;
                               tmpval |= *decodedbuf_ptr++ << 16;
                               tmpval |= *decodedbuf_ptr++ << 24;

                               DEBUG_SO(printf("Packet Size: 0x%08x\n", tmpval));

                               if((tmpval >= 0xF9FFFFFF) && (tmpval <= 0xFEFFFFFF)) {
                                  return RULE_MATCH;
                               }
                            }
                        }       
                    }
                }
            }
        }
    }
    return RULE_NOMATCH;
}
예제 #23
0
파일: xplist.c 프로젝트: EchoLiao/libplist
static void xml_to_node(xmlNodePtr xml_node, plist_t * plist_node)
{
    xmlNodePtr node = NULL;
    plist_data_t data = NULL;
    plist_t subnode = NULL;

    //for string
    long len = 0;
    int type = 0;

    if (!xml_node)
        return;

    for (node = xml_node->children; node; node = node->next)
    {

        while (node && !xmlStrcmp(node->name, XPLIST_TEXT))
            node = node->next;
        if (!node)
            break;

        if (!xmlStrcmp(node->name, BAD_CAST("comment"))) {
            continue;
        }

        data = plist_new_plist_data();
        subnode = plist_new_node(data);
        if (*plist_node)
            node_attach(*plist_node, subnode);
        else
            *plist_node = subnode;

        if (!xmlStrcmp(node->name, XPLIST_TRUE))
        {
            data->boolval = TRUE;
            data->type = PLIST_BOOLEAN;
            data->length = 1;
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_FALSE))
        {
            data->boolval = FALSE;
            data->type = PLIST_BOOLEAN;
            data->length = 1;
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_INT))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            int is_negative = 0;
            char *str = (char*)strval;
            if ((str[0] == '-') || (str[0] == '+')) {
                if (str[0] == '-') {
                    is_negative = 1;
                }
                str++;
            }
            char* endp = NULL;
            data->intval = strtoull((char*)str, &endp, 0);
            if ((endp != NULL) && (strlen(endp) > 0)) {
                fprintf(stderr, "%s: integer parse error: string contains invalid characters: '%s'\n", __func__, endp);
            }
            if (is_negative || (data->intval <= INT64_MAX)) {
                int64_t v = data->intval;
                if (is_negative) {
                    v = -v;
                }
                data->intval = (uint64_t)v;
                data->length = 8;
            } else {
                data->length = 16;
            }
            data->type = PLIST_UINT;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_REAL))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            data->realval = atof((char *) strval);
            data->type = PLIST_REAL;
            data->length = 8;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DATE))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            time_t timev = 0;
            if (strlen((const char*)strval) >= 11) {
                struct tm btime;
                struct tm* tm_utc;
                parse_date((const char*)strval, &btime);
                timev = mktime(&btime);
                tm_utc = gmtime(&timev);
                timev -= (mktime(tm_utc) - timev);
            }
            data->timeval.tv_sec = (long)(timev - MAC_EPOCH);
            data->timeval.tv_usec = 0;
            data->type = PLIST_DATE;
            data->length = sizeof(struct timeval);
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_STRING))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            len = strlen((char *) strval);
            type = xmlDetectCharEncoding(strval, len);

            if (XML_CHAR_ENCODING_UTF8 == type || XML_CHAR_ENCODING_ASCII == type || XML_CHAR_ENCODING_NONE == type)
            {
                data->strval = strdup((char *) strval);
                data->type = PLIST_STRING;
                data->length = strlen(data->strval);
            }
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_KEY))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            len = strlen((char *) strval);
            type = xmlDetectCharEncoding(strval, len);

            if (XML_CHAR_ENCODING_UTF8 == type || XML_CHAR_ENCODING_ASCII == type || XML_CHAR_ENCODING_NONE == type)
            {
                data->strval = strdup((char *) strval);
                data->type = PLIST_KEY;
                data->length = strlen(data->strval);
            }
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DATA))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            size_t size = 0;
            unsigned char *dec = base64decode((char*)strval, &size);
            data->buff = (uint8_t *) malloc(size * sizeof(uint8_t));
            memcpy(data->buff, dec, size * sizeof(uint8_t));
            free(dec);
            data->length = size;
            data->type = PLIST_DATA;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_ARRAY))
        {
            data->type = PLIST_ARRAY;
            xml_to_node(node, &subnode);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DICT))
        {
            data->type = PLIST_DICT;
            xml_to_node(node, &subnode);
            if (plist_get_node_type(subnode) == PLIST_DICT) {
                if (plist_dict_get_size(subnode) == 1) {
                    plist_t uid = plist_dict_get_item(subnode, "CF$UID");
                    if (uid) {
                        uint64_t val = 0;
                        plist_get_uint_val(uid, &val);
                        plist_dict_remove_item(subnode, "CF$UID");
                        plist_data_t nodedata = plist_get_data((node_t*)subnode);
                        free(nodedata->buff);
                        nodedata->type = PLIST_UID;
                        nodedata->length = sizeof(uint64_t);
                        nodedata->intval = val;
                    } 
                }
            }
            continue;
        }
    }
}
// Receive a NET msg from the OVMS server
void net_msg_in(char* msg)
  {
  int k;
  char s;

  if (net_msg_serverok == 0)
    {
    if (memcmppgm2ram(msg, (char const rom far*)"MP-S 0 ", 7) == 0)
      {
      net_msg_server_welcome(msg+7);
      net_granular_tick = 3590; // Nasty hack to force a status transmission in 10 seconds
      }
    return; // otherwise ignore it
    }

  // Ok, we've got an encrypted message waiting for work.
  // The following is a nasty hack because base64decode doesn't like incoming
  // messages of length divisible by 4, and is really expecting a CRLF
  // terminated string, so we give it one...
  CHECKPOINT(0x40)
  if (((strlen(msg)*4)/3) >= (NET_BUF_MAX-3))
    {
    // Quick exit to reset link if incoming message is too big
    net_state_enter(NET_STATE_DONETINIT);
    return;
    }
  strcatpgm2ram(msg,(char const rom far*)"\r\n");
  k = base64decode(msg,net_scratchpad);
  CHECKPOINT(0x41)
  RC4_crypt(&rx_crypto1, &rx_crypto2, net_scratchpad, k);
  if (memcmppgm2ram(net_scratchpad, (char const rom far*)"MP-0 ", 5) != 0)
    {
    net_state_enter(NET_STATE_DONETINIT);
    return;
    }
  msg = net_scratchpad+5;

  if ((*msg == 'E')&&(msg[1]=='M'))
    {
    // A paranoid-mode message from the server (or, more specifically, app)
    // The following is a nasty hack because base64decode doesn't like incoming
    // messages of length divisible by 4, and is really expecting a CRLF
    // terminated string, so we give it one...
    msg += 2; // Now pointing to the code just before encrypted paranoid message
    strcatpgm2ram(msg,(char const rom far*)"\r\n");
    k = base64decode(msg+1,net_msg_scratchpad+1);
    RC4_setup(&pm_crypto1, &pm_crypto2, pdigest, MD5_SIZE);
    for (k=0;k<1024;k++)
      {
      net_scratchpad[0] = 0;
      RC4_crypt(&pm_crypto1, &pm_crypto2, net_scratchpad, 1);
      }
    RC4_crypt(&pm_crypto1, &pm_crypto2, net_msg_scratchpad+1, k);
    net_msg_scratchpad[0] = *msg; // The code
    // The message is now out of paranoid mode...
    msg = net_msg_scratchpad;
    }

  CHECKPOINT(0x42)
  switch (*msg)
    {
    case 'A': // PING
      strcpypgm2ram(net_scratchpad,(char const rom far*)"MP-0 a");
      if (net_msg_sendpending==0)
        {
        net_msg_start();
        net_msg_encode_puts();
        net_msg_send();
        }
      break;
    case 'Z': // PEER connection
      if (msg[1] != '0')
        {
        net_apps_connected = 1;
        if (net_msg_sendpending==0)
          {
          net_msg_start();
          net_msgp_stat(0);
          net_msgp_gps(0);
          net_msgp_tpms(0);
          net_msgp_firmware(0);
          net_msgp_environment(0);
          net_msg_send();
          }
        }
      else
        {
        net_apps_connected = 0;
        }
      break;
    case 'h': // Historical data acknowledgement
#ifdef OVMS_LOGGINGMODULE
      logging_ack(atoi(msg+1));
#endif // #ifdef OVMS_LOGGINGMODULE
      break;
    case 'C': // COMMAND
      net_msg_cmd_in(msg+1);
      if (net_msg_sendpending==0) net_msg_cmd_do();
      break;
    }
  }
static int rule13921eval(void *p) {
   SFSnortPacket *sp = (SFSnortPacket *)p;

   const u_int8_t *cursor, *beg_of_payload, *end_of_payload;

   int16_t lm_x;  

   int n;  /* cruft */

   /* Data for holding our base64 data */
   u_int8_t decoded_data[16];
   u_int32_t num_bytes_extracted;


   /* General sanity checking */
  if(sp == NULL)
      return RULE_NOMATCH;

   if(sp->payload == NULL)
      return RULE_NOMATCH;

   if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &beg_of_payload, &end_of_payload) <= 0)
      return RULE_NOMATCH;

   if((end_of_payload - beg_of_payload) < 32)
      return RULE_NOMATCH;

   /* call flow match */
   if (checkFlow(sp, rule13921options[0]->option_u.flowFlags) <= 0 )
      return RULE_NOMATCH;

   /* call first content match */
   if (contentMatch(sp, rule13921options[1]->option_u.content, &cursor) <= 0) {
      return RULE_NOMATCH;
   }

   /* call second content match */
   if (contentMatch(sp, rule13921options[2]->option_u.content, &cursor) <= 0) {
      return RULE_NOMATCH;
   }

   /* Decode the part containing "/P.\x03/" to ensure the proper header and message type */
   n = base64decode(&(beg_of_payload[8]), 4, decoded_data, sizeof(decoded_data), &num_bytes_extracted);

   if((n < 0) || (num_bytes_extracted < 3))
      return RULE_NOMATCH;

   /* verify contents */
   if((decoded_data[0] != 'P') || (decoded_data[2] != 0x03))
      return RULE_NOMATCH;

   /* Now decode the part containing LM_X */
   n = base64decode(&(beg_of_payload[24]), 8, decoded_data, sizeof(decoded_data), &num_bytes_extracted);

   if((n < 0) || (num_bytes_extracted < 6))
      return RULE_NOMATCH;

   /* Extract LM_X, a signed 16-bit entity in little-endian format */
   lm_x = decoded_data[2];
   lm_x += decoded_data[3] << 8; 

   if((lm_x < 0) || (lm_x > 56))
      return RULE_MATCH;

   return RULE_NOMATCH;
}
예제 #26
0
static struct rdata* deserialize_dns_rdata(char *buff,int buf_len,int do_decoding)
{
	unsigned char *p;
	int max_len=0,actual_len=0,entry_len=0;
	struct rdata *head,*it,**last;
	struct naptr_rdata *naptr_rd;
	struct srv_rdata *srv_rd;
	struct txt_rdata *txt_rd;
	struct ebl_rdata *ebl_rd;

	head=it=NULL;
	last=&head;	

	if (do_decoding) {
		max_len = calc_max_base64_decode_len(buf_len);
	} else {
		max_len = buf_len;
	}

	if (dec_rdata_buf == NULL || max_len > dec_rdata_buf_len) {
		/* realloc buff if not enough space */
		dec_rdata_buf = pkg_realloc(dec_rdata_buf,max_len);	
		if (dec_rdata_buf == NULL) {
			LM_ERR("No more pkg\n");
			return NULL;				
		}
		dec_rdata_buf_len = max_len;
	}

	if (do_decoding) {
		/* decode base64 buf */
		actual_len = base64decode(dec_rdata_buf,(unsigned char *)buff,buf_len);	
		p = dec_rdata_buf;
	} else {
		memcpy(dec_rdata_buf,buff,buf_len);
		actual_len = buf_len;
		p = dec_rdata_buf;
	}

	while ( p < dec_rdata_buf+actual_len) {
		it = pkg_malloc(sizeof(struct rdata));		
		if (it == 0) {
			LM_ERR("no more pkg mem\n");
			goto it_alloc_error;
		}

		/* copy type, class & ttl */
		memcpy(it,p,rdata_struct_len);
		p+=rdata_struct_len;			
		it->next=0;
		it->rdata=0;

		switch (it->type) {
			case T_A:
				it->rdata = pkg_malloc(sizeof(struct a_rdata)); 
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				memcpy(p,it->rdata,sizeof(struct a_rdata));
				p+=sizeof(struct a_rdata);	
				*last=it;
				last=&(it->next);
				break;	
			case T_AAAA:
				it->rdata = pkg_malloc(sizeof(struct aaaa_rdata)); 
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				memcpy(p,it->rdata,sizeof(struct aaaa_rdata));
				p+=sizeof(struct aaaa_rdata);	
				*last=it;
				last=&(it->next);
				break;	
			case T_CNAME:
				it->rdata = pkg_malloc(sizeof(struct cname_rdata));	
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}	
				memcpy(&entry_len,p,sizeof(int));
				p+=sizeof(int);	
				memcpy(((struct cname_rdata*)it->rdata)->name,
					p,entry_len+1);
				p+=entry_len+1;		
				*last=it;
				last=&(it->next);
				break;
			case T_NAPTR:
				it->rdata = pkg_malloc(sizeof(struct naptr_rdata));
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				naptr_rd = (struct naptr_rdata*)it->rdata;
				memcpy(naptr_rd,p,2*sizeof(unsigned short) + 
					sizeof(unsigned int));
				p+=2*sizeof(unsigned short) + sizeof(unsigned int);
				memcpy(naptr_rd->flags,p,naptr_rd->flags_len+1);
				p+=naptr_rd->flags_len+1;
				memcpy(&naptr_rd->services_len,p,sizeof(unsigned int));
				p+=sizeof(unsigned int);
				memcpy(naptr_rd->services,p,naptr_rd->services_len+1);
				p+=naptr_rd->services_len+1;
				memcpy(&naptr_rd->regexp_len,p,sizeof(unsigned int));
				p+=sizeof(unsigned int);
				memcpy(naptr_rd->regexp,p,naptr_rd->regexp_len+1);
				p+=naptr_rd->regexp_len+1;
				memcpy(&naptr_rd->repl_len,p,sizeof(unsigned int));
				p+=sizeof(unsigned int);
				memcpy(naptr_rd->repl,p,naptr_rd->repl_len+1);
				p+=naptr_rd->repl_len+1;
				*last=it;
				last=&(it->next);
				break;
			case T_SRV:
				it->rdata = pkg_malloc(sizeof(struct srv_rdata));
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				srv_rd = (struct srv_rdata*)it->rdata;
				memcpy(srv_rd,p,4*sizeof(unsigned short) + 
					sizeof(unsigned int));
				p+=4*sizeof(unsigned short) + sizeof(unsigned int);
				memcpy(srv_rd->name,p,srv_rd->name_len+1);
				p+=srv_rd->name_len+1;
				*last=it;
				last=&(it->next);
				break;
			case T_TXT:
				it->rdata = pkg_malloc(sizeof(struct txt_rdata));
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				txt_rd = (struct txt_rdata*)it->rdata;
				memcpy(&entry_len,p,sizeof(int));
				p+=sizeof(int);	
				memcpy(txt_rd->txt,p,entry_len+1);
				p+=entry_len+1;		
				*last=it;
				last=&(it->next);
				break;
			case T_EBL:
				it->rdata = pkg_malloc(sizeof(struct ebl_rdata));
				if (it->rdata == 0) {
					LM_ERR("no more pkg\n");
					goto rdata_alloc_error;
				}
				ebl_rd = (struct ebl_rdata*)it->rdata;
				memcpy(ebl_rd,p,sizeof(unsigned char) + 
					sizeof(unsigned int));	
				p+=sizeof(unsigned char)+sizeof(unsigned int);	
				memcpy(ebl_rd->separator,p,ebl_rd->separator_len+1);
				p+=ebl_rd->separator_len+1;
				memcpy(&ebl_rd->apex_len,p,sizeof(unsigned int));
				p+=sizeof(unsigned int);
				memcpy(ebl_rd->apex,p,ebl_rd->apex_len+1);
				p+=ebl_rd->apex_len+1;
				*last=it;
				last=&(it->next);
				break;
		}
	}

	return head;

rdata_alloc_error:
	if (it) 
		pkg_free(it);
it_alloc_error:
	if (head)
		free_rdata_list(head);
	return NULL;
}
예제 #27
0
static struct hostent* deserialize_he_rdata(char *buff,int buf_len,int do_decoding)
{
	char **ap,**hap;
	unsigned char *p;
	int max_len=0;
	int i,alias_no=0,addr_no=0,len=0;
	
	/* max estimation of needed buffer */
	if (do_decoding) {
		max_len=calc_max_base64_decode_len(buf_len);
	} else {
		max_len = buf_len;
	}

	if (dec_he_buf == NULL || max_len > dec_he_buf_len) {
		/* realloc buff if not enough space */
		dec_he_buf = pkg_realloc(dec_he_buf,max_len);	
		if (dec_he_buf == NULL) {
			LM_ERR("No more pkg\n");
			return NULL;				
		}
		dec_he_buf_len = max_len;
	}

	/* set pointer in dec_global_he */
	ap = host_aliases;
	*ap = NULL;
	dec_global_he.h_aliases = host_aliases;
	hap = h_addr_ptrs;
	*hap = NULL;
	dec_global_he.h_addr_list = h_addr_ptrs;
	
	if (do_decoding) {
		/* decode base64 buf */
		base64decode(dec_he_buf,(unsigned char *)buff,buf_len);
		p = dec_he_buf;
	} else {
		memcpy(dec_he_buf,buff,buf_len);
		p = dec_he_buf;
	}

	/* set address type & length */
	memcpy(&dec_global_he.h_addrtype,p,sizeof(int));
	p+=sizeof(int);
	if (dec_global_he.h_addrtype == AF_INET)
		dec_global_he.h_length=4;
	else
		dec_global_he.h_length=16;

	/* set name */
	memcpy(&len,p,sizeof(int));
	p+=sizeof(int);
	dec_global_he.h_name = (char *)p;
	p+=len;

	/* get number of aliases */
	memcpy(&alias_no,p,sizeof(int));
	p+=sizeof(int);

	for (i=0;i<alias_no;i++) {
		/* get alias length, set pointer and skip over length */
		memcpy(&len,p,sizeof(int));
		p+=sizeof(int);
		*ap++ = (char *)p;
		p+=len;		
	}

	/* get number of addresses */
	memcpy(&addr_no,p,sizeof(int));	
	p+=sizeof(int);

	for (i=0;i<addr_no;i++) {
		/* set pointer and skip over length */
		*hap++ = (char *)p;	
		p+=dec_global_he.h_length;
	}			
		
	return &dec_global_he;
}
예제 #28
0
/*
 * Function to decompress a compressed message
 */
static int mc_decompress(struct sip_msg* msg)
{
	#define HDRS_TO_SKIP 4

	int i;
	int j;
	int rc;
	int algo=-1;
	int hdrs_algo=-1;
	int b64_required=-1;

	str msg_body;
	str msg_final;

	str b64_decode={NULL, 0};
	str hdr_b64_decode={NULL,0};
	str uncomp_body={NULL,0};
	str uncomp_hdrs={NULL,0};

	char *new_buf;

	unsigned long temp;

	/* hdr_vec allows to sort the headers. This will help skipping
		these headers when building the new message */
	struct hdr_field *hf;
	struct hdr_field *hdr_vec[HDRS_TO_SKIP];
					/*hdr_vec : 	0 Content-Length
							1 Comp-Hdrs
							2 Headers-Algo
							3 Content-Encoding*/

	memset(hdr_vec, 0, HDRS_TO_SKIP * sizeof(struct hdr_field*));

	if (parse_headers(msg, HDR_EOH_F, 0) != 0) {
		LM_ERR("failed to parse SIP message\n");
		return -1;
	}

	/*If compressed with this module there are great chances that Content-Encoding is last*/
	hdr_vec[3] = msg->last_header;

	if (!is_content_encoding(hdr_vec[3])) {
		hdr_vec[3] = NULL;
		for (hf = msg->headers; hf; hf = hf->next) {
			if (is_content_encoding(hf)) {
				hdr_vec[3] = hf;
				continue;
			}
			if (hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) {
				hdr_vec[1] = hf;
				continue;
			}

			if (hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, HDRS_ENCODING,
						sizeof(HDRS_ENCODING)-1)) {
				hdr_vec[2] = hf;
			}

			if (hdr_vec[1] && hdr_vec[2] && hdr_vec[3])
					break;
		}
	} else {
		for (hf = msg->headers; hf; hf = hf->next) {
			if (!hdr_vec[1] && hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) {
				hdr_vec[1] = hf;
				continue;
			}

			if (!hdr_vec[2] && hf->type == HDR_OTHER_T &&
				!strncasecmp(hf->name.s, HDRS_ENCODING,
						sizeof(HDRS_ENCODING)-1))
				hdr_vec[2] = hf;

			if (hdr_vec[2] && hdr_vec[3] && hdr_vec[1])
					break;
		}
	}

	/* Only if content-encoding present, Content-Length will be replaced
		with the one in the compressed body or in compressed headers*/

	if (hdr_vec[3]) {
		hdr_vec[0] = msg->content_length;
		parse_algo_hdr(hdr_vec[3], &algo, &b64_required);
	}


	if (b64_required > 0 && hdr_vec[3]) {
		msg_body.s = msg->last_header->name.s + msg->last_header->len + CRLF_LEN;
		msg_body.len = strlen(msg_body.s);

		/* Cutting CRLF'S at the end of the message */
		while (WORD(msg_body.s + msg_body.len-CRLF_LEN) == PARSE_CRLF) {
			msg_body.len -= CRLF_LEN;
		}

		if (wrap_realloc(&body_in, calc_max_base64_decode_len(msg_body.len)))
			return -1;

		b64_decode.s = body_in.s;

		b64_decode.len = base64decode((unsigned char*)b64_decode.s,
						(unsigned char*)msg_body.s,
							msg_body.len);
	} else if (hdr_vec[3]) {
		if (get_body(msg, &msg_body) < 0) {
			LM_ERR("failed to get body\n");
			return -1;
		}

		b64_decode.s = msg_body.s;
		b64_decode.len = msg_body.len;
	}

	b64_required=0;
	if (hdr_vec[2]) {
		parse_algo_hdr(hdr_vec[3], &algo, &b64_required);
	}

	if (b64_required > 0 &&  hdr_vec[1]) {
		if (wrap_realloc(&hdr_in, calc_max_base64_decode_len(hdr_vec[1]->body.len)))
			return -1;

		hdr_b64_decode.s = hdr_in.s;

		hdr_b64_decode.len = base64decode(
					(unsigned char*)hdr_b64_decode.s,
					(unsigned char*)hdr_vec[1]->body.s,
							hdr_vec[1]->body.len
					);
	} else if (hdr_vec[1]) {
		hdr_b64_decode.s = hdr_vec[1]->body.s;
		hdr_b64_decode.len = hdr_vec[1]->body.len;
	}

	switch (hdrs_algo) {
		case 0: /* deflate */
			temp = (unsigned long)BUFLEN;

			rc = uncompress((unsigned char*)hdr_buf,
					&temp,
					(unsigned char*)hdr_b64_decode.s,
					(unsigned long)hdr_b64_decode.len);

			uncomp_hdrs.s = hdr_buf;
			uncomp_hdrs.len = temp;

			if (check_zlib_rc(rc)) {
				LM_ERR("header decompression failed\n");
				return -1;
			}
			break;
		case 1: /* gzip */
			rc = gzip_uncompress(
					(unsigned char*)hdr_b64_decode.s,
					(unsigned long)hdr_b64_decode.len,
					&hdr_out,
					&temp);

			if (check_zlib_rc(rc)) {
				LM_ERR("header decompression failed\n");
				return -1;
			}

			uncomp_hdrs.s = hdr_out.s;
			uncomp_hdrs.len = temp;

			break;
		case -1:
			break;
		default:
			return -1;
	}

	switch (algo) {
		case 0: /* deflate */
			temp = (unsigned long)BUFLEN;

			rc = uncompress((unsigned char*)body_buf,
					&temp,
					(unsigned char*)b64_decode.s,
					(unsigned long)b64_decode.len);

			if (check_zlib_rc(rc)) {
				LM_ERR("body decompression failed\n");
				return -1;
			}

			uncomp_body.s = body_buf;
			uncomp_body.len = temp;

			break;
		case 1: /* gzip */
			rc = gzip_uncompress(
					(unsigned char*)b64_decode.s,
					(unsigned long)b64_decode.len,
					&body_out,
					&temp);

			if (check_zlib_rc(rc)) {
				LM_ERR("body decompression failed\n");
				return -1;
			}

			uncomp_body.s = body_out.s;
			uncomp_body.len = temp;

			break;
		case -1:
			LM_DBG("no body\n");
			break;
		default:
			LM_ERR("invalid algo\n");
			return -1;
	}

	/* Sort to have the headers in order */
	for (i = 0; i < HDRS_TO_SKIP - 1; i++) {
		for (j = i + 1; j < HDRS_TO_SKIP; j++) {
			if (!hdr_vec[j])
				continue;

			if (!hdr_vec[i] && hdr_vec[j]) {
				hdr_vec[i] = hdr_vec[j];
				hdr_vec[j] = NULL;
			}

			if ((hdr_vec[i] && hdr_vec[j]) &&
				(hdr_vec[i]->name.s > hdr_vec[j]->name.s)) {
				hf = hdr_vec[i];
				hdr_vec[i] = hdr_vec[j];
				hdr_vec[j] = hf;
			}
		}
	}

	int msg_final_len = 0;
	int msg_ptr=0;

	for ( i = 0; i < HDRS_TO_SKIP; i++) {
		if (hdr_vec[i]) {
			msg_final_len += hdr_vec[i]->name.s - (msg->buf+msg_ptr);
			msg_ptr += hdr_vec[i]->name.s+hdr_vec[i]->len - (msg->buf+msg_ptr);
		}
	}

	msg_final_len += msg->last_header->name.s + msg->last_header->len -
				(msg->buf + msg_ptr);

	if (hdrs_algo >= 0)
		msg_final_len += uncomp_hdrs.len;

	if (algo >= 0)
		msg_final_len += uncomp_body.len;
	else
		msg_final_len += strlen(msg->eoh);

	if (wrap_realloc(&buf_out, msg_final_len))
		return -1;

	msg_ptr = 0;

	msg_final.len = 0;
	msg_final.s = buf_out.s;

	for ( i = 0; i < HDRS_TO_SKIP; i++) {
		if (hdr_vec[i]) {
			wrap_copy_and_update(&msg_final.s,
					msg->buf+msg_ptr,
					hdr_vec[i]->name.s-(msg->buf+msg_ptr),
					&msg_final.len);

			msg_ptr += (hdr_vec[i]->name.s+hdr_vec[i]->len) -
					(msg->buf+msg_ptr);
		}
	}

	wrap_copy_and_update(
			&msg_final.s,
			msg->buf+msg_ptr,
			(msg->last_header->name.s+msg->last_header->len)-
							(msg->buf+msg_ptr),
			&msg_final.len
		);

	if (hdrs_algo >= 0) {
		wrap_copy_and_update(&msg_final.s, uncomp_hdrs.s,
					uncomp_hdrs.len,&msg_final.len);
	}

	if (algo >= 0) {
		wrap_copy_and_update(&msg_final.s, uncomp_body.s,
					uncomp_body.len, &msg_final.len);
	} else {
		wrap_copy_and_update(&msg_final.s, msg->eoh, strlen(msg->eoh), &msg_final.len);
	}

	/* new buffer because msg_final(out_buf) will
	 * be overwritten at next iteration */
#ifdef DYN_BUF
	new_buf = pkg_malloc(msg_final.len+1);
	if (new_buf == NULL) {
		LM_ERR("no more pkg mem\n");
		return -1;
	}
#else
	new_buf = msg->buf;
#endif

	memcpy(new_buf, msg_final.s, msg_final.len);
	new_buf[msg_final.len] = '\0';

	struct sip_msg tmp;

	memcpy(&tmp, msg, sizeof(struct sip_msg));

	/*reset dst_uri and path_vec to avoid free*/
	if (msg->dst_uri.s != NULL) {
		msg->dst_uri.s = NULL;
		msg->dst_uri.len = 0;
	}
	if (msg->path_vec.s != NULL)
	{
		msg->path_vec.s = NULL;
		msg->path_vec.len = 0;
	}

	free_sip_msg(msg);
	memset(msg, 0, sizeof(struct sip_msg));

	/* restore msg fields */
	msg->id					= tmp.id;
	msg->rcv				= tmp.rcv;
	msg->set_global_address = tmp.set_global_address;
	msg->set_global_port    = tmp.set_global_port;
	msg->flags              = tmp.flags;
	msg->msg_flags          = tmp.msg_flags;
	msg->hash_index         = tmp.hash_index;
	msg->force_send_socket  = tmp.force_send_socket;
	msg->dst_uri            = tmp.dst_uri;
	msg->path_vec           = tmp.path_vec;
	/* set the new ones */
	msg->buf = new_buf;
	msg->len = msg_final.len;

	/* reparse the message */
	if (parse_msg(msg->buf, msg->len, msg) != 0)
		LM_ERR("parse_msg failed\n");

	return 1;
}
예제 #29
0
파일: main.c 프로젝트: lionaneesh/radare2
int main(int argc, const char **argv) {
	char *line;
	const char *arg, *grep = NULL;
	int i, ret, fmt = MODE_DFLT;
	int db0 = 1, argi = 1;
	bool interactive = false;

	/* terminate flags */
	if (argc < 2) {
		return showusage (1);
	}
	arg = argv[1];

	if (arg[0] == '-') {// && arg[1] && arg[2]==0) {
		switch (arg[1]) {
		case 0:
			/* no-op */
			break;
		case '0':
			fmt = MODE_ZERO;
			db0++;
			argi++;
			if (db0 >= argc) {
				return showusage (1);
			}
			break;
		case 'g':
			db0 += 2;
			if (db0 >= argc) {
				return showusage (1);
			}
			grep = argv[2];
			argi += 2;
			break;
		case 'J':
			options |= SDB_OPTION_JOURNAL;
			db0++;
			argi++;
			if (db0 >= argc) {
				return showusage (1);
			}
			break;
		case 'c': return (argc < 3)? showusage (1) : showcount (argv[2]);
		case 'v': return showversion ();
		case 'h': return showusage (2);
		case 'e': return base64encode ();
		case 'd': return base64decode ();
		case 'D':
			if (argc == 4) {
				return dbdiff (argv[2], argv[3]);
			}
			return showusage (0);
		case 'j':
			if (argc > 2) {
				return sdb_dump (argv[db0 + 1], MODE_JSON);
			}
			return jsonIndent();
		default:
			eprintf ("Invalid flag %s\n", arg);
			break;
		}
	}

	/* sdb - */
	if (argi == 1 && !strcmp (argv[argi], "-")) {
		/* no database */
		argv[argi] = "";
		if (argc == db0 + 1) {
			interactive = true;
			/* if no argument passed */
			argv[argi] = "-";
			argc++;
			argi++;
		}
	}
	/* sdb dbname */
	if (argc - 1 == db0) {
		if (grep) {
			return sdb_grep (argv[db0], fmt, grep);
		}
		return sdb_dump (argv[db0], fmt);
	}
#if USE_MMAN
	signal (SIGINT, terminate);
	signal (SIGHUP, synchronize);
#endif
	ret = 0;
	if (interactive || !strcmp (argv[db0 + 1], "-")) {
		if ((s = sdb_new (NULL, argv[db0], 0))) {
			sdb_config (s, options);
			int kvs = db0 + 2;
			if (kvs < argc) {
				save |= insertkeys (s, argv + argi + 2, argc - kvs, '-');
			}
			for (;(line = stdin_slurp (NULL));) {
				save |= sdb_query (s, line);
				if (fmt) {
					fflush (stdout);
					write (1, "", 1);
				}
				free (line);
			}
		}
	} else if (!strcmp (argv[db0 + 1], "=")) {
		ret = createdb (argv[db0], NULL, 0);
	} else {
		s = sdb_new (NULL, argv[db0], 0);
		if (!s) {
			return 1;
		}
		sdb_config (s, options);
		for (i = db0 + 1; i < argc; i++) {
			save |= sdb_query (s, argv[i]);
			if (fmt) {
				fflush (stdout);
				write (1, "", 1);
			}
		}
	}
	terminate (0);
	return ret;
}
void par_getbase64(unsigned char param, void* dest, size_t length)
  {
  char *p = par_get(param);
  memset(dest,0,length);
  base64decode(p, dest);
  }