Exemple #1
0
PKI_MEM *PKI_MEM_get_url_encoded(PKI_MEM *mem, int skipNewLines)
{
	PKI_MEM *encoded = NULL;

	char enc_buf[1024];

	int i = 0;
	int enc_idx = 0;

	if (!mem || !mem->data || (mem->size == 0))
	{
		PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
		return NULL;
	}

	if ((encoded = PKI_MEM_new_null()) == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		return NULL;
	}

	for( i = 0; i < mem->size; i++ )
	{
		char *str = "=$&+,/:;=?@ <>#\%{}|\\^~[]\r\n`";
		unsigned char tmp_d2 = 0;

		if (skipNewLines && (mem->data[i] == '\r' || mem->data[i] == '\n')) continue;

		tmp_d2 = mem->data[i];
		if ((strchr( str, tmp_d2 ) != NULL ) ||
			(tmp_d2 <= 31) || ( tmp_d2 >= 127 ) || (isgraph(tmp_d2) == 0))
		{
			enc_idx += sprintf(&enc_buf[enc_idx], "%%%2.2x", tmp_d2 );
			// PKI_MEM_add ( encoded, enc_buf, 3 );
		}
		else
		{
			// PKI_MEM_add ( encoded, (char *) &(mem->data[i]), 1);
			enc_buf[enc_idx++] = mem->data[i];
		}

		// Let's check if it is time to move the buffer contents into the
		// PKI_MEM. If so, let's transfer the content and reset the buffer
		// index
		if (enc_idx >= sizeof(enc_buf) - 4)
		{
			PKI_MEM_add(encoded, enc_buf, enc_idx);
			enc_idx = 0;
		}
	}

	// If there is something left in the buffer that needs to be added
	// we add it
	if (enc_idx > 0) PKI_MEM_add(encoded, enc_buf, enc_idx);

	// Let's now return the encoded PKI_MEM
	return encoded;
}
Exemple #2
0
PKI_MEM *PKI_MEM_new_bio(PKI_IO *io, PKI_MEM **mem)
{
	unsigned char buf[1024];

	PKI_MEM *my_mem = NULL;

	if (!io) return NULL;

	if (mem != NULL)
	{
		if (*mem)
		{
			my_mem = *mem;
		}
		else
		{
			*mem = PKI_MEM_new_null();
			my_mem = *mem;
		}
	}
	else
	{
		my_mem = PKI_MEM_new_null();
	}
	
	if (!my_mem) return NULL;

	{
		int i = -1;
		for (i = BIO_read(io, buf, sizeof(buf)); i > 0; i = BIO_read(io, buf, sizeof(buf)))
		{
			if (i > 0) PKI_MEM_add(my_mem, (char *)buf, (size_t) i);
		}
	}

	return my_mem;
}
Exemple #3
0
PKI_MEM *PKI_MEM_new ( size_t size ) {
	PKI_MEM *ret = NULL;

	ret = PKI_MEM_new_null();
	if( !ret ) return (NULL);

	ret->data = PKI_Malloc ( size );
	if( !ret->data ) {
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		PKI_MEM_free ( ret );
		return (NULL);
	}
	ret->size = size;

	return(ret);
}
Exemple #4
0
PKI_MEM *PKI_MEM_new_membio ( PKI_IO *io ) {

	BUF_MEM *buf_mem = NULL;
	PKI_MEM *pki_mem = NULL;

	if( !io ) {
		PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
		return ( NULL );
	}

	/* Copy the data from the BIO to the PKI_MEM structure */
	BIO_get_mem_ptr( io, &buf_mem);

	if( buf_mem ) {
		if((pki_mem = PKI_MEM_new_null()) == NULL ) {
			return ( NULL );
		}
		PKI_MEM_add( pki_mem, buf_mem->data, (size_t) buf_mem->length );
	}

	return( pki_mem );
}
Exemple #5
0
PKI_MEM * PKI_X509_KEYPAIR_get_pubkey(PKI_X509_KEYPAIR *kp)
{
	PKI_X509_KEYPAIR_VALUE *kVal = NULL;
	PKI_MEM *ret = NULL;

	if(!kp || !kp->value)
	{
		PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
		return NULL;
	};

	kVal = kp->value;

	if((ret = PKI_MEM_new_null())==NULL)
	{
		PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
		return NULL;
	};

	ret->size = (size_t) i2d_PUBKEY(kVal, &(ret->data));

	return ret;
}
Exemple #6
0
PKI_MEM *PKI_MEM_get_b64_decoded(PKI_MEM *mem, int withNewLines)
{
	PKI_MEM *decoded = NULL;

	PKI_IO *b64 = NULL;
	PKI_IO *bio = NULL;

	int i = 0;
	int n = 0;

	char buf[1024];
	unsigned char *tmp_ptr;

	if (!(b64 = BIO_new(BIO_f_base64()))) return NULL;
	if (withNewLines <= 0) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

	if ((bio = BIO_new_mem_buf(mem->data, (int) mem->size)) == NULL)
	{
		BIO_free_all(b64);
		return NULL;
	}
	BIO_push(b64, bio);

	if ((decoded = PKI_MEM_new_null()) == NULL)
	{
		BIO_free_all(b64);
		return NULL;
	}

	while ((n = BIO_read(b64, buf, sizeof(buf))) > 0)
	{
		PKI_MEM_add(decoded, buf, n);
	}
	BIO_free_all(b64);

	return decoded;
}
Exemple #7
0
PKI_HTTP *PKI_HTTP_get_message (const PKI_SOCKET * sock,
		                        int                timeout,
								size_t             max_size) {

  PKI_HTTP * ret = NULL;

  char * eoh = NULL;
  char * body = NULL;

  ssize_t read = 0; // Keeps track of the single reading
  ssize_t free = 0; // Keeps track of the remaining buffer space
  ssize_t idx = 0; // Keeps track of how much data we poured into MEM
  ssize_t size = 0; // Keeps track of the read data from socket

  // Let's initialize some useful variables (code readability)
  long long content_length = -1;

  // Buffer where to keep the data
  PKI_MEM *m = NULL;

  // Allocates the HTTP message container
  if ((ret = PKI_HTTP_new()) == NULL)
  {
      PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL );
      goto err;
  }
  ret->method = PKI_HTTP_METHOD_UNKNOWN;

  if (max_size > 0)
  {
	  // Allocates a new MEM object
	  m = PKI_MEM_new(max_size + 1);
  }
  else
  {
	  // Allocates the default buffer for HTTP messages
	  m = PKI_MEM_new(HTTP_BUF_SIZE + 1);
  }

	if (m == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		return NULL;
	}

	// Sets the free space in the buffer
	free = (ssize_t) m->size - 1;

  // Let's retrieve the data from the socket. Note that this for
  // always read at most 'free' bytes which carries the amount of
  // free space in the buffer -> safe
  for (read = PKI_SOCKET_read(sock, (char *)(&(m->data[idx])), (size_t) free, timeout);
       read > 0;
       read = PKI_SOCKET_read(sock, (char *)(&(m->data[idx])), (size_t) free, timeout))
  {
      // If read is negative, there was an error on the socket
      // let's just report it as an error and move on
      if (read < 0)
      {
    	  if (!eoh)
    	  {
    		  PKI_log_err("Error while reading from socket");
    		  goto err;
    	  }
    	  else
    	  {
    		  // Nothing to read anymore - let's break
    		  PKI_log_err("Nothing to read anymore (read = %d)", read);
    		  break;
    	  }
      }
      else if (read == 0 && eoh)
      {
    	  // No data was read, let's assume the stream is complete and
    	  // break from the for loop
    	  break;
      }

      // Let's be sure there is a NULL-bound limit to the read data
      size += read;
      free -= read;
      m->data[size] = '\x0';

      // If we don't have a header yet, let's look for it
      if (!eoh && ((eoh = __find_end_of_header(m, idx)) != NULL))
      {
    	  // We want the header to finish with just one '\r\n' - since the
    	  // pointer we receive is at the end of the '\r\n\r\n' sequence,
    	  // we need to shrink by 2 bytes
    	  size_t header_size = (size_t) (eoh - (char *) m->data - 2);
    	  ret->head = PKI_MEM_new_data(header_size + 1, m->data);
    	  ret->head->data[header_size] = '\x0';

    	  // If we can not parse the header - we have to return error
    	  if (PKI_ERR == __parse_http_header(ret)) goto err;

    	  // Let's get the pointer to the start of the body
    	  body = eoh + 1;

    	  // Checks for the content-length is in the header - if we have not found it, yet
    	  if (ret->method != PKI_HTTP_METHOD_GET && content_length < 0)
    	  {
    		  char *cnt_len_s = NULL;
    		  if ((cnt_len_s = PKI_HTTP_get_header(ret, "Content-Length" )) != NULL)
    		  {
    			  content_length = atoll(cnt_len_s);
    			  PKI_Free(cnt_len_s);
    			  // PKI_log_debug ( "HTTP Content-Length: %d bytes", content_length);
    		  }
    	  }
      } // End of if (!eoh) ...

      // Updates the start pointer for the next read operation
      idx += read;

      // Let's check if we need to expand the buffer
      if (max_size <= 0)
      {
    	  // We expand the mem if the buffer has less than 2K free
    	  if (free < 2048)
    	  {
    			ssize_t ofs = 0;

    		  if(body)
    		  {
    		    ofs = (ssize_t)(body - (char *)m->data);
          
    		    if(ofs < 0)
    		    {
    		      PKI_log_debug ( "Invalid offset for HTTP body: Start: %p - Body: %p", m->data, body);
    		      PKI_ERROR(PKI_ERR_URI_READ, NULL);
    		      goto err;
    		    }
    		  }

    		  // Grow the memory for the HTTP message
    		  if(content_length > 0 && body && m->size < (size_t)(content_length + ofs))
    		  {
           size_t len = ((size_t)(content_length + ofs) - m->size);

    		    if (PKI_MEM_grow(m, len + 1) == PKI_ERR)
    		    {
    		      PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
    		      goto err;
    		    }
    		    free += (ssize_t)len;
    		  }
    		  else
    		  {
    		    if (PKI_MEM_grow(m, HTTP_BUF_SIZE) == PKI_ERR)
    		    {
    		      PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
    		      goto err;
    		    }
    		    free += HTTP_BUF_SIZE;
    		  }

    		  // Let's update the pointer to the body
    		  if(body) body = (char *)m->data + ofs;
    	  }
      }

      // Let's check if we need to perform the next read or not
      if (eoh && ret->method == PKI_HTTP_METHOD_GET)
      {
    	  // We do not need to wait for any other read as GETs do not have
    	  // a full body
    	  break;
      }
      else if ((content_length >= 0) && (&m->data[size] - (unsigned char *)body >= content_length))
      {
    	  // Here we have received the full body (since the size of the body corresponds or exceeds the
    	  // contents of the Content-Length: header line), therefore we can safely get out of the cycle
    	  break;
      }

  } /* End of for..loop */

  // Here we should have both the eoh and the body - if not, there was
  // an error and we return the malformed request message
  if (!eoh)
  {
	  // PKI_log_err ( "Read data (so far): %d bytes - Last read: %d bytes", idx, read);
	  PKI_ERROR(PKI_ERR_URI_READ, NULL);
	  goto err;
  }

  // Sets some HTTP specific data
  ret->location = PKI_HTTP_get_header ( ret, "Location" );
  ret->type     = PKI_HTTP_get_header ( ret, "Content-Type" );

  if (ret->method != PKI_HTTP_METHOD_GET && content_length > 0 && body)
  {
	  ssize_t body_start = (ssize_t)(body - (char *)m->data);
	  ssize_t body_size = idx - body_start;

	  if (body_start < 0 || body_size < 0)
	  {
		  PKI_log_err ( "Invalid offset for HTTP body - body_start: %d bytes - body_size: %d bytes", body_start, body_size);
		  PKI_ERROR(PKI_ERR_URI_READ, NULL);
		  goto err;
	  }
 
	  //Check if Content-Length > 0 but body_size is 0
	  if (body_size == 0) goto err; 

	  // Let's allocate the body for the HTTP message (if any)
	  ret->body = PKI_MEM_new_data((size_t)body_size+1, (unsigned char *)body);
	  if(ret->body == NULL)
	  {
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		goto err;
	  }
	  ret->body->size = (size_t) body_size;
  }
  else
  {
	  ret->body = PKI_MEM_new_null();
  }

  // Let's free the buffer memory
  if (m) PKI_MEM_free(m);

  // Now we can return the HTTP message
  return ret;

err:

	// First we free the return message
	if (ret) PKI_HTTP_free(ret);

	// We then free the buffer memory object
	if (m) PKI_MEM_free(m);

	return NULL;
}
Exemple #8
0
PKI_MEM *PKI_X509_PKCS7_get_raw_data( PKI_X509_PKCS7 *p7 ) {

	unsigned char *data = NULL;
	ssize_t len = -1;
	int type = -1;

	PKI_X509_PKCS7_VALUE *p7val = NULL;
	PKI_MEM *ret = NULL;

	if( !p7 || !p7->value ) return ( NULL );

	p7val = p7->value;
	type = PKI_X509_PKCS7_get_type ( p7 );

	switch (type)
	{
		case PKI_X509_PKCS7_TYPE_DATA:
			data = p7val->d.data->data;
			len  = p7val->d.data->length;
			break;

		case PKI_X509_PKCS7_TYPE_SIGNED:
			if (p7val->d.sign && p7val->d.sign->contents &&
				p7val->d.sign->contents->d.data)
			{
				data = p7val->d.sign->contents->d.data->data;
				len  = p7val->d.sign->contents->d.data->length;
			}
			break;

		case PKI_X509_PKCS7_TYPE_ENCRYPTED:
			if (p7val->d.enveloped && p7val->d.enveloped->enc_data &&
				p7val->d.enveloped->enc_data->enc_data)
			{
				data = p7val->d.enveloped->enc_data->enc_data->data;
				len  = p7val->d.enveloped->enc_data->enc_data->length;
			}
			break;

		case PKI_X509_PKCS7_TYPE_SIGNEDANDENCRYPTED:
			if (p7val->d.signed_and_enveloped &&
				p7val->d.signed_and_enveloped->enc_data &&
				p7val->d.signed_and_enveloped->enc_data->enc_data )
			{
				data = p7val->d.signed_and_enveloped->enc_data->enc_data->data;
				len = p7val->d.signed_and_enveloped->enc_data->enc_data->length;
			}
			break;

		default:
			PKI_log_debug ("Unknown PKCS7 type");
			return NULL;
	}

	if ((ret = PKI_MEM_new_null()) == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		return NULL;
	}

	if (PKI_MEM_add(ret, (char *) data, (size_t) len) == PKI_ERR)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, "Memory Failure (ret=%p, data=%p, len=%d)",
				ret, data, len );
		PKI_MEM_free ( ret );
		return NULL;
	}

	/*
        if((p7bio = PKCS7_dataInit(p7->value ,NULL)) != NULL ) {
		(void)BIO_flush(p7bio);
                ret = PKI_MEM_new_bio( p7bio, NULL );
		BIO_free_all ( p7bio );
        } else {
		PKI_log_debug("PKCS7::get_raw_data()::Can not get data [%s]",
			ERR_error_string(ERR_get_error(), NULL ));
	}
	*/

	return ( ret );
	
}
Exemple #9
0
void * PKI_X509_OCSP_RESP_get_data ( PKI_X509_OCSP_RESP *r, PKI_X509_DATA type )
{
	void * ret = NULL;
	PKI_OCSP_RESP *val = NULL;
	OCSP_BASICRESP *tmp_x = NULL;
	PKI_MEM *mem = NULL;
	int idx = -1;

	if( !r || !r->value ) return NULL;

	val = r->value;

	/* Let's check that the response data is there!! */
	if( !val->bs ) return NULL;

	tmp_x = val->bs;

	switch ( type )
	{
		case PKI_X509_DATA_NONCE:
			idx = OCSP_BASICRESP_get_ext_by_NID(tmp_x, NID_id_pkix_OCSP_Nonce, -1);
			if (idx >= 0)
			{
				X509_EXTENSION *ext = OCSP_BASICRESP_get_ext(tmp_x, idx);
				if (ext) ret = PKI_STRING_new(ext->value->type,
						(char *) ext->value->data, (ssize_t) ext->value->length);
			}
			break;

		case PKI_X509_DATA_NOTBEFORE:
			ret = tmp_x->tbsResponseData->producedAt;
			break;

		case PKI_X509_DATA_NOTAFTER:
			break;

		case PKI_X509_DATA_SIGNATURE:
			if ( tmp_x && tmp_x->signature ) {
				ret = tmp_x->signature;
			}
			break;

		case PKI_X509_DATA_ALGORITHM:
		case PKI_X509_DATA_SIGNATURE_ALG1:
			if ( tmp_x && tmp_x->signatureAlgorithm ) {
				ret = tmp_x->signatureAlgorithm;
			}
			break;

		case PKI_X509_DATA_SIGNATURE_ALG2:
			break;

		case PKI_X509_DATA_TBS_MEM_ASN1:
			if((mem = PKI_MEM_new_null()) == NULL )
			{
				PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL );
				break;
			}
			mem->size = (size_t) ASN1_item_i2d ( (void *) tmp_x->tbsResponseData, 
				&(mem->data), &OCSP_RESPDATA_it );
			ret = mem;
			break;

		default:
			return NULL;
	}

	return ret;
}
Exemple #10
0
PKI_MEM_STACK *URL_get_data_pkcs11_url ( URL *url, ssize_t size ) {

#ifdef HAVE_P11
	// PKCS11_CTX   *ctx   = NULL;
	PKCS11_SLOT  *slots = NULL;
	PKCS11_TOKEN *tk    = NULL;

	char *libfile = NULL;
	int num = 0;
	int i = 0;

	char * search_label = NULL;
	char * search_id = NULL;
	char * search_slot = NULL;
	char * search_slotid = NULL;

	PKI_MEM *tmp_mem = NULL;
	PKI_MEM_STACK *sk = NULL;

	if( !url ) return (NULL);

	/*
	if((libfile = pkcs11_parse_url_libpath ( url )) == NULL ) {
		return( NULL );
	}
	*/

	/*
	slot = pkcs11_parse_url_slot ( url );
	id = pkcs11_parse_url_id ( url );
	*/

	if( ctx == NULL ) {
		if((ctx = PKCS11_CTX_new ()) == NULL ) {
			return(NULL);
		}

		PKI_log_debug("Loading %s Library", url->addr );
		if(( i = PKCS11_CTX_load(ctx, url->addr)) != 0 ) {
			PKI_log_err("Can not load library %s [err::%d]", url->addr, i);
			// ERR_print_errors_fp( stderr );
		}
	}

	if( PKCS11_enumerate_slots( ctx, &slots, &num ) == -1 ) {
		PKI_log_err ("Can not enumerate slots");
		goto err;
        };

	if(( sk = PKI_STACK_MEM_new()) == NULL ) {
		goto err;
	}

	search_slot   = pkcs11_parse_url_getval( url, "slot" );
	search_slotid = pkcs11_parse_url_getval( url, "slotid" );
	search_label  = pkcs11_parse_url_getval( url, "label" );
	search_id     = pkcs11_parse_url_getval( url, "id" );
	
	if( search_slot )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::SLOT =>  %s\n", search_slot);
	if( search_slotid )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::SLOTID =>  %s\n", search_slotid);
	if( search_label )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::LABEL => %s\n", search_label);
	if( search_id )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::ID =>    %s\n", search_id);

	for(i = 0; i < num; i++ ) {

		BIO *mem = NULL;
		BUF_MEM *mem_buf = NULL;

		PKCS11_CERT *certs = NULL;
		PKCS11_SLOT *p = NULL;
		PKCS11_CERT *x = NULL;

		PKCS11_KEY  *keyList = NULL;
		PKCS11_KEY  *key     = NULL;
		EVP_PKEY    *evp_pkey = NULL;

		int n = 0;
		int t = 0;
		int n_objs = 0;
		int p_ret = 0;
		
                p = &slots[i];

                if((!p) || ((tk = p->token) == NULL) ) {
			continue;
		}

		if( (search_slot) && ( strncmp_nocase( search_slot, 
				tk->label, strlen(search_slot) == 0) )) {
			continue;
		}

		if( (search_slotid) && ( atoi(search_slotid) != i )) {
			PKI_log_debug("PKCS11::SLOTID is %s (%d), curr is %d\n",
					search_slotid, atoi(search_slotid), i);
			continue;
		}

		if( strncmp_nocase( url->attrs, "cert", 4 ) == 0) {
			PKI_log_debug("PKCS11::CERT DATATYPE SELECTED!\n");
			if((mem = BIO_new(BIO_s_mem())) == NULL ) {
				goto err;
			}

			/* Get the list of certificates in the slot */
			p_ret = PKCS11_enumerate_certs( tk, &certs, &n_objs);

			for( n = 0; n < n_objs; n++ ) {

				/* Pointer to the current certificate */
				x = &certs[n];

				PKI_log_debug("PKCS11::CERT label=%s\n",
					x->label);
				PKI_log_debug("PKCS11::CERT id=");
				for( t = 0; t < x->id_len; t ++ ) {
					printf("%c", x->id[t] );
				} printf("\n");

				if( (search_label) &&
					(strncmp_nocase( search_label, x->label,
						strlen( search_label)) != 0 )){
					PKI_log_debug("PKCS11::LABEL does not"
						"match, SKIPPING!!!!\n");
					continue;
				}
 
				if( search_id ) {
					int stop = 0;

					for( t = 0; t < x->id_len; t ++ ) {
						if( search_id[t] != x->id[t] ) {
							stop = 1;
							break;
						}
					}

					if( stop == 1 ) { 
					printf("DEBUG::PKCS11::ID does not"
						"match, SKIPPING!!!!\n");
						continue;
					}
				}
 
				/* Write the cert in PEM format to memory */
				p_ret = PEM_write_bio_X509( mem, x->x509 );

				/* Get the pointer to the memory buffer */
				BIO_get_mem_ptr( mem, &mem_buf );

				/* Push a PKI_MEM buffer on the stack */
				tmp_mem = PKI_MEM_new_null();
				PKI_MEM_add ( tmp_mem, mem_buf->data, 
							mem_buf->length);
				PKI_STACK_push( sk, tmp_mem );
			}

			/* Free the temp memory buffer */
			if( mem ) BIO_free( mem );

		} else if (strncmp_nocase( url->attrs, "key", 3) == 0 ) {
			char *pin = NULL;

			PKI_log_debug("PKCS11::KEY DATATYPE SELECTED!\n");

			pin = pkcs11_parse_url_getval( url, "pin" );

			if ( (tk->loginRequired == 1) && (pin != NULL ) ) {
				p_ret = PKCS11_login ( p, 0, pin );
				PKI_log_debug("PKCS11::LOGIN Result %d\n",
					p_ret );
        		}

			if((mem = BIO_new(BIO_s_mem())) == NULL ) {
				goto err;
			}

		        p_ret = PKCS11_enumerate_keys ( tk, &keyList, &n_objs );

			for( n = 0; n < n_objs; n++ ) {
				key = &keyList[n];

				printf("DEBUG::PKCS11::KEY label=%s\n",
					key->label);
				printf("DEBUG::PKCS11::KEY id=");
				for( t = 0; t < key->id_len; t ++ ) {
					printf("%c", key->id[t] );
				} printf("\n");

				if( (search_label) &&
					(strncmp_nocase( search_label, x->label,
						strlen( search_label)) != 0 )){
					printf("DEBUG::PKCS11::LABEL does not"
						"match, SKIPPING!!!!\n");
					continue;
				}
 
				if( search_id ) {
					int stop = 0;

					for( t = 0; t < x->id_len; t ++ ) {
						if( search_id[t] != x->id[t] ) {
							stop = 1;
							break;
						}
					}

					if( stop == 1 ) { 
					printf("DEBUG::PKCS11::ID does not"
						"match, SKIPPING!!!!\n");
						continue;
					}
				}
 
				/* Get Private Key in OpenSSL format */
				evp_pkey = PKCS11_get_private_key( key );

				/* Write the cert in PEM format to memory */
				p_ret = PEM_write_bio_PUBKEY( mem, evp_pkey );

				/* Get the pointer to the memory buffer */
				BIO_get_mem_ptr( mem, &mem_buf );

				/* Push a PKI_MEM buffer on the stack */
				tmp_mem = PKI_MEM_new_null();
				PKI_MEM_add ( tmp_mem, mem_buf->data, 
							mem_buf->length);
				PKI_STACK_push( sk, tmp_mem );
			}

			if( mem ) BIO_free ( mem );

		} else {
			printf("DEBUG::PKCS11::OTHER DATATYPE SELECTED!\n");
		}
	}

err:
	if( slots ) PKCS11_release_all_slots( ctx, slots, num );

	/*
	if( ctx ) { 
		PKCS11_CTX_unload(ctx);
		PKCS11_CTX_free(ctx);
	}
	*/

	if( libfile ) PKI_Free (libfile);

	if( search_slot ) PKI_Free ( search_slot );
	if( search_slotid ) PKI_Free ( search_slotid );
	if( search_label ) PKI_Free ( search_label );
	if( search_id ) PKI_Free ( search_id );

	return ( sk );

#else
	return ( NULL );
#endif
}
Exemple #11
0
void * PKI_X509_CERT_get_data ( PKI_X509_CERT *x, PKI_X509_DATA type ) {

	void *ret = NULL;
	PKI_X509_CERT_VALUE *tmp_x = NULL;
	PKI_MEM *mem = NULL;
	int *tmp_int = NULL;

	if( !x || !x->value ) return (NULL);

	tmp_x = x->value;

	switch (type)
	{
		case PKI_X509_DATA_VERSION:
			ret = (tmp_x)->cert_info->version;
			break;

		case PKI_X509_DATA_SERIAL:
			ret = X509_get_serialNumber ( (X509 *) x->value );
			break;

		case PKI_X509_DATA_SUBJECT:
			ret = X509_get_subject_name( (X509 *) x->value );
			break;

		case PKI_X509_DATA_ISSUER:
			ret = X509_get_issuer_name( (X509 *) x->value );
			break;

		case PKI_X509_DATA_NOTBEFORE:
			ret = X509_get_notBefore( (X509 *) x->value );
			break;

		case PKI_X509_DATA_NOTAFTER:
			ret = X509_get_notAfter( (X509 *) x->value );
			break;

		case PKI_X509_DATA_KEYPAIR_VALUE:
		case PKI_X509_DATA_PUBKEY:
			ret = X509_get_pubkey( (X509 *) x->value);
			break;

		case PKI_X509_DATA_PUBKEY_BITSTRING:
			ret = X509_get0_pubkey_bitstr( (X509 *) x->value);
			break;

		case PKI_X509_DATA_SIGNATURE:
			ret = (void *) (tmp_x)->signature;
			break;

		case PKI_X509_DATA_ALGORITHM:
		case PKI_X509_DATA_SIGNATURE_ALG1:
			if (tmp_x->cert_info && tmp_x->cert_info->signature)
				ret = tmp_x->cert_info->signature;
			break;

		case PKI_X509_DATA_SIGNATURE_ALG2:
			if (tmp_x->sig_alg) ret = tmp_x->sig_alg;
			break;

		case PKI_X509_DATA_KEYSIZE:
			tmp_int = PKI_Malloc ( sizeof( int ));
			*tmp_int = EVP_PKEY_size(
			X509_get_pubkey ( (X509 *) x->value ));
			ret = tmp_int;
			break;

		case PKI_X509_DATA_TBS_MEM_ASN1:
			if((mem = PKI_MEM_new_null()) == NULL ) break;
			mem->size = (size_t) ASN1_item_i2d ( (void *) tmp_x->cert_info, 
				&(mem->data), &X509_CINF_it );
			ret = mem;
			break;

		case PKI_X509_DATA_CERT_TYPE:
			tmp_int = PKI_Malloc ( sizeof ( int ));
			*tmp_int = PKI_X509_CERT_get_type( x );
			break;

		case PKI_X509_DATA_EXTENSIONS:
		default:
			/* Not Recognized/Supported DATATYPE */
			return (NULL);
	}

	return (ret);
}
Exemple #12
0
int OCSPD_build_ca_list ( OCSPD_CONFIG *handler,
			PKI_CONFIG_STACK *ca_conf_sk) {

	int i = 0;
	PKI_STACK *ca_list = NULL;

	PKI_log_debug("Building CA List");

	if ( !ca_conf_sk ) {
		PKI_log( PKI_LOG_ERR, "No stack of ca configs!");
		return ( PKI_ERR );
	}

	if((ca_list = PKI_STACK_new((void (*))CA_LIST_ENTRY_free)) == NULL ) {
		PKI_log_err ( "Memory Error");
	return ( PKI_ERR );
	}

	for (i = 0; i < PKI_STACK_CONFIG_elements( ca_conf_sk ); i++)
	{
		char *tmp_s = NULL;
		URL *tmp_url = NULL;
		PKI_X509_CERT *tmp_cert = NULL;

		CA_LIST_ENTRY *ca = NULL;
		PKI_CONFIG *cnf = NULL;

		/* Get the current Configureation file */
		cnf = PKI_STACK_CONFIG_get_num( ca_conf_sk, i );
		if (!cnf) continue;

		/* Get the CA cert from the cfg file itself */
		if((tmp_s = PKI_CONFIG_get_value( cnf, "/caConfig/caCertValue" )) == NULL )
		{
			/* Get the CA parsed url */
			if((tmp_url = URL_new( PKI_CONFIG_get_value( cnf, "/caConfig/caCertUrl" ))) == NULL )
			{
				/* Error, can not parse url data */
				PKI_log( PKI_LOG_ERR, "Can not parse CA cert url (%s)", 
					PKI_CONFIG_get_value(cnf, "/caConfig/caCertUrl"));

				continue;
			}

			if((tmp_cert = PKI_X509_CERT_get_url(tmp_url, NULL, NULL ))== NULL)
			{
				PKI_log_err("Can not get CA cert from (%s)", tmp_url);
				URL_free (tmp_url);

				continue;
			}
		}
		else
		{
			PKI_X509_CERT_STACK *cc_sk = NULL;
			PKI_MEM *mm = NULL;

			if((mm = PKI_MEM_new_null()) == NULL )
			{
				PKI_Free(tmp_s);
				continue;
			}

			PKI_MEM_add ( mm, tmp_s, strlen(tmp_s));

			if((cc_sk=PKI_X509_CERT_STACK_get_mem(mm, NULL)) == NULL )
			{
				PKI_log_err ( "Can not parse cert from /caConfig/caCertValue");
				PKI_Free(tmp_s);

				continue;
			}

			if ((tmp_cert = PKI_STACK_X509_CERT_pop( cc_sk )) == NULL )
			{
				PKI_log_err ( "No elements on stack from /caConfig/caCertValue");

				PKI_STACK_X509_CERT_free_all(cc_sk);
				PKI_Free(tmp_s);

				continue;
			}

			PKI_STACK_X509_CERT_free ( cc_sk );
			PKI_Free(tmp_s);
		}

		/* OCSPD create the CA entry */
		if ((ca = CA_LIST_ENTRY_new()) == NULL )
		{
			PKI_log_err ( "CA List structure init error");

			/* remember to do THIS!!!! */
			if( tmp_url ) URL_free ( tmp_url );
			if( tmp_cert ) PKI_X509_CERT_free ( tmp_cert );

			continue;
		}

		ca->ca_cert = tmp_cert;
		tmp_cert = NULL;

		ca->ca_url = tmp_url;
		tmp_url = NULL;

		ca->ca_id = PKI_CONFIG_get_value( cnf, "/caConfig/name" );
		ca->cid = CA_ENTRY_CERTID_new ( ca->ca_cert, handler->digest );

		/* Get the CRL URL and the CRL itself */
		if((tmp_s = PKI_CONFIG_get_value(cnf, "/caConfig/crlUrl")) == NULL)
		{
			PKI_STACK *cdp_sk = NULL;

			/* Now let's get it from PRQP */

			/* Now from the Certificate */
			
			if((cdp_sk = PKI_X509_CERT_get_cdp (ca->ca_cert)) ==NULL)
			{
				// No source for the CRL Distribution Point
				PKI_log_err ( "ERROR::Can not find the CDP for %s, skipping CA", ca->ca_id );

				CA_LIST_ENTRY_free ( ca );
				continue;
			}

			while ((tmp_s = PKI_STACK_pop ( cdp_sk )) != NULL)
			{
				if ((ca->crl_url = URL_new ( tmp_s )) == NULL )
				{
					PKI_log_err( "URL %s not in the right format!");
					CA_LIST_ENTRY_free ( ca );
					continue;
				}
				else if( tmp_s ) PKI_Free ( tmp_s );

				break;
			}
		}
		else
		{
			PKI_log_debug("Got CRL Url -> %s", tmp_s );

			if((ca->crl_url = URL_new ( tmp_s )) == NULL )
			{
				PKI_log_err ("Error Parsing CRL URL [%s] for CA [%s]", ca->ca_id, tmp_s);

				CA_LIST_ENTRY_free ( ca );
				PKI_Free(tmp_s);

				continue;
			}

			PKI_Free(tmp_s);
		}

		if(OCSPD_load_crl ( ca, handler ) == PKI_ERR )
		{
			PKI_log_err ( "Can not get CRL for %s", ca->ca_id);
			CA_LIST_ENTRY_free ( ca );

			continue;
		}

		/* If the Server has a Token to be used with this CA, let's
                   load it */
		if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/serverToken" )) == NULL)
		{
			/* No token in config, let's see if a specific cert
			   is configured */
			ca->token = NULL;

			if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/serverCertUrl" )) == NULL )
			{
				/* No cert is configured, we will use the defaults */
				ca->server_cert = NULL;
			}
			else
			{
				/* The Server's cert URL is found, let's load the certificate */
				if ((tmp_cert = PKI_X509_CERT_get ( tmp_s, NULL, NULL )) == NULL )
				{
					PKI_log_err("Can not get server's cert from %s!", tmp_s );

					CA_LIST_ENTRY_free ( ca );
					PKI_Free(tmp_s);

					continue;
				}
				else
				{
					ca->server_cert = tmp_cert;
				}

				PKI_Free(tmp_s);
			}
		}
		else
		{
			/* A Token for this CA is found - we do not load
 			   it to avoid problems with Thread Initialization */
			ca->server_cert = NULL;
			ca->token_name = tmp_s;
			ca->token = PKI_TOKEN_new_null();

			if ((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/pkiConfigDir" )) != NULL) {
				ca->token_config_dir = strdup( tmp_s );
				PKI_Free(tmp_s);
			}
			else
			{
				ca->token_config_dir = strdup(handler->token_config_dir);
			}
		}

		if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/caCompromised" )) == NULL) {
			ca->compromised = 0;
		}
		else
		{
			ca->compromised = atoi(tmp_s);
			PKI_Free(tmp_s);
		}

		/* Responder Id Type */
		if ((tmp_s = PKI_CONFIG_get_value(cnf, "/caConfig/responderIdType")) != NULL)
		{
			if (strncmp_nocase(tmp_s, "keyid", 5) == 0) 
			{
				ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_KEYID;
			}
			else if (strncmp_nocase(tmp_s, "name", 4) == 0)
			{
				ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_NAME;
			}
			else
			{
				PKI_log_err("Can not parse responderIdType: %s (allowed 'keyid' or 'name')", tmp_s);
				exit(1);
			}

			PKI_Free(tmp_s);
		}
		else
		{
			// Default Value
			ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_NAME;
		}

		// Now let's add the CA_LIST_ENTRY to the list of configured CAs
		PKI_STACK_push ( ca_list, ca );

	}

	handler->ca_list = ca_list;

	return ( PKI_OK );
}
Exemple #13
0
/*! \brief Returns a MEM STACK with the requested DNS records */
PKI_MEM_STACK *URL_get_data_dns_url(URL *url, ssize_t size) {

	PKI_MEM_STACK *ret = NULL;

#ifdef HAVE_LIBRESOLV

	int type = T_A;
	PKI_MEM *obj = NULL;

	if( (!url) || (!url->addr)) {
		return NULL;
	}

	unsigned char response[NS_PACKETSZ];

	ns_msg dnsMessage;
	ns_rr dnsRecord;

	int dnsRecordSection = ns_s_an;
	int dns_msgCount = 0;
	int len = 0;

	// Check the Type of record
	if ((type = URL_get_dns_type(url->attrs)) == -1) return NULL;

	PKI_log_debug("DNS URI: Searching for %s (%s/%d)",
		url->addr, url->attrs, type);

	if ((len = res_search(url->addr, C_IN, type, response, sizeof(response))) < 0)
	{
		// An Error Occurred
		PKI_log_err("DNS URI: search failed\n");
		return NULL;
	}

	if (ns_initparse(response, len, &dnsMessage) < 0)
	{
		// This should not happen if the record is correct
		PKI_log_err("DNS URI: can not init DNS parsing of the dnsMessage\n");
		return NULL;
	}

	len = ns_msg_count(dnsMessage, dnsRecordSection);
	PKI_log_debug("DNS_URI: msg count ==> %d\n", len);

	if (len <= 0) return NULL;

	if((ret = PKI_STACK_MEM_new()) == NULL ) {
		PKI_log_debug ("DNS URI: Memory Failure");
		return NULL;
	}

	for (dns_msgCount = 0; dns_msgCount < len; dns_msgCount++)
	{
		PKI_log_debug("DNS URI: Retrieving DNS record #%d",dns_msgCount);

		if (ns_parserr(&dnsMessage, dnsRecordSection, dns_msgCount, &dnsRecord))
		{
			// ERROR: ns_parserr failed, let's continue to the next record
			PKI_log_err("DNS URI: Can not parse record %d of %d", dns_msgCount, len);
			continue;
		}

		PKI_log_debug("DNS URI: type = %d (req: %d)\n", ns_rr_type(dnsRecord), type);

		if (type == pki_ns_t_address)
		{
			switch (ns_rr_type(dnsRecord))
			{
				case T_A:
				case T_AAAA:
				case T_CNAME:
					break;
				default:
					continue;
			}
		}
		else if (type != ns_rr_type(dnsRecord))
		{
			PKI_log_debug("DNS URI: recived type %d is different from requested (%d)", 
				type, ns_rr_type(dnsRecord));
			// continue;
		}

		// int i = 0;
		int rv = 0;
		// int len = 0;
		int offset = 0;

		char dnsRecordName[MAXDNAME];

		memset(dnsRecordName, '\x0', MAXDNAME);
		// Parse the different types of DNS records
		if ((ns_rr_type(dnsRecord) == T_A) || (ns_rr_type(dnsRecord) == T_AAAA))
		{
			// These require Translation using IPv4/IPv6 functions
			int family = AF_INET;

			if (ns_rr_type(dnsRecord) == T_A) family = AF_INET;
			else family = AF_INET6;

			if(inet_ntop(family, ns_rr_rdata(dnsRecord), dnsRecordName, 
				sizeof(dnsRecordName)) == NULL)
			{
				// Can not convert
				continue;
			}
		}
		else if ((ns_rr_type(dnsRecord) == T_CNAME) || (ns_rr_type(dnsRecord) == T_MX) ||
			(ns_rr_type(dnsRecord) == T_NS))
		{
			if (ns_rr_type(dnsRecord) == T_MX) offset = NS_INT16SZ;

			rv = ns_name_uncompress(ns_msg_base(dnsMessage), ns_msg_end(dnsMessage),
				ns_rr_rdata(dnsRecord) + offset, dnsRecordName, MAXDNAME);

			// ERROR, can not uncompress the names
			if (rv < 0) continue;
		}
		else if (ns_rr_type(dnsRecord) == T_SRV)
		{
			// This requires special handling, the format is [SHORT][SHORT][SHORT][DATA]
			// unsigned short *pri = (unsigned short *) ns_rr_rdata(dnsRecord);
			// unsigned short *weight = (unsigned short *) &(ns_rr_rdata(dnsRecord)[2]);
			// unsigned short *port = (unsigned short *) &(ns_rr_rdata(dnsRecord)[4]);

			// Shall we return the additional data too ?
			// printf("PRI : %d\n", *pri);
			// printf("WEIGHT : %d\n", ntohs(*weight));
			// printf("PORT : %d\n", ntohs(*port));

			offset = 6;
			rv = ns_name_uncompress(ns_msg_base(dnsMessage), ns_msg_end(dnsMessage),
				ns_rr_rdata(dnsRecord) + offset, dnsRecordName, MAXDNAME);

			if (rv < 0) continue;
		}
		else if (ns_rr_type(dnsRecord) == T_TXT)
		{
			// Special handling required. Format is [BYTE][DATA]
			unsigned char *p = (unsigned char *)ns_rr_rdata(dnsRecord);

			snprintf(dnsRecordName, (size_t) *p+1, "%s", &ns_rr_rdata(dnsRecord)[1]);
		}
		else
		{
			PKI_log_debug("DNS URI: record type not supported [%d]", ns_rr_type(dnsRecord));
			continue;
		}

		if((obj = PKI_MEM_new_null()) == NULL ) {
			// Memory Allocation Error, we abort
			break;
		}

		if (strlen(dnsRecordName) > 0) {
			// If it is a printable value, we add the parsed version of the
			// record
			if(PKI_MEM_add(obj, (char *) dnsRecordName, strlen(dnsRecordName)) == PKI_ERR) {
				/* ERROR in memory growth */;
				PKI_log_err("DNS URI: Memory Allocation Error");
				break;
			}
		} else {
			// The value is not parsed/parsable, we return the raw data
			// the application should know what to do with the data!
			if(PKI_MEM_add(obj, (char *) ns_rr_rdata(dnsRecord), 
					ns_rr_rdlen(dnsRecord)) == PKI_ERR) {
				/* ERROR in memory growth */;
				PKI_log_err("DNS URI: Memory Allocation Error");
				break;
			}
		}

/*
		printf("MSG Data [%d]:\n", ns_rr_rdlen(dnsRecord));
		for (i=0; i < ns_rr_rdlen(dnsRecord); i++)
		{
			unsigned char *kk;

			kk = (unsigned char *) &ns_rr_rdata(dnsRecord)[i];
			printf("%x:", *kk);
		};
		printf("\n");

		fprintf(stderr, "DEBUG: RV => %d (err: %d, %s)\n", rv, h_errno, hstrerror(h_errno));
		fprintf(stderr, "DEBUG: name => %s (%s)\n", ns_rr_name(dnsRecord), url->addr);
		fprintf(stderr, "DEBUG: value => %s\n", dnsRecordName);
		fprintf(stderr, "DEBUG: type => %d\n", ns_rr_type(dnsRecord));
		fprintf(stderr, "DEBUG: class => %d\n", ns_rr_class(dnsRecord));
*/

		PKI_STACK_MEM_push(ret, obj);

		// PKI_log_debug("DNS URI: Added object #%d to stack", PKI_STACK_MEM_elements(ret));
	}

#endif

	return ret;
};
Exemple #14
0
PKI_MEM_STACK *URL_get_data_mysql_url ( const URL *url, ssize_t size ) {

#ifdef HAVE_MYSQL
	MYSQL_ROW row;
	MYSQL * sql = NULL;
	MYSQL_FIELD *fields = NULL;
	MYSQL_RES *res = NULL;

	unsigned long *lengths = NULL;
	long long n_rows = 0;
	int n_fields = 0;

	PKI_MEM *tmp_mem = NULL;
	PKI_MEM_STACK *sk = NULL;

	char * query = NULL;

	if( !url ) return (NULL);

	if((sql = db_connect ( url )) == NULL )
	{
		return NULL;
	}

	if ((query = parse_url_query(url)) == NULL)
	{
		PKI_log_err("Can not parse URL query");
		goto end;
	}
	else mysql_query(sql, query);

	/* Get the Data */
	if((res = mysql_store_result( sql )) == NULL)
	{
		PKI_log_err("Can not retrieve SQL data");
		goto end;
	}

	if( ((n_rows = (long long) mysql_num_rows( res )) < 1 ) || 
			((sk = PKI_STACK_MEM_new()) == NULL))
	{
		PKI_log_err("No returned rows found");
		goto end;
	}

	while((row = mysql_fetch_row(res)) != NULL )
	{
		/* Count the number of fields retrieved */
		n_fields = (int) mysql_num_fields( res );
		lengths = mysql_fetch_lengths( res );
		fields = mysql_fetch_fields( res );
		if (!fields)
		{
			PKI_ERROR(PKI_ERR_GENERAL, "can not fetch query fields");
			break;
		}

		if (n_fields > 0)
		{
			tmp_mem = PKI_MEM_new_null();
			if (size == 0 || (( size > 0 ) && ( lengths[0] < size)))
			{
				PKI_MEM_add(tmp_mem,row[0],lengths[0]);

				/* For now, let's only deal with one 
				   field at the time */
				PKI_STACK_push( sk, tmp_mem );
			}
		}
	}

end:

	if (query) PKI_Free (query);
	db_close ( sql );

	return ( sk );

#else
	return ( NULL );
#endif
}
Exemple #15
0
char *parse_url_put_query ( const URL * url, const PKI_MEM *data ) {

	char * ret = NULL;
	char * table = NULL;
	char * tmp_s = NULL;
	char * tmp_s2 = NULL;

	int where = 0;
	int add_and = 0;

	char col[1024];
	char val[1024];
	char tmp[1024];

	// char buf[BUFF_MAX_SIZE];

	PKI_MEM *buf = NULL;

	if( !url || !url->path ) return( NULL );

	tmp_s = url->path;

	while((tmp_s2 = strchr(tmp_s, '/')) != NULL ) {
		tmp_s2++;
		tmp_s = tmp_s2;
	}

	if((table = parse_url_table ( url )) == NULL) {
		return (NULL);
	}

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

	sprintf( tmp, "INSERT INTO %s (%s) VALUES ('", table, url->attrs );
	PKI_MEM_add( buf, tmp, strlen( tmp ));
	PKI_MEM_add( buf, (char *) data->data, data->size );
	PKI_MEM_add( buf, "') ", 3);

	/*
	base=strlen(buf);
	for( i=0; i < data->size; i++ ) {
		sprintf(buf + base + i, "%c", data->data[i]);
	}
	sprintf(buf+base+i,"') ");
	*/

	where = 0;
	while( (sscanf(tmp_s, "(%[^)=]=\"%[^)\"]\")", col, val) > 1) ||
			(sscanf(tmp_s, "(%[^)=]=%[^)])", col, val) > 1)) {
		if( where == 0 ) {
			/* It is actually an update, let's update! */
			snprintf( tmp, sizeof( tmp ),
				"UPDATE %s SET %s='", table, url->attrs);
			if( buf ) PKI_MEM_free ( buf );

			buf = PKI_MEM_new_null();
			PKI_MEM_add( buf, tmp, strlen( tmp ));
			PKI_MEM_add( buf, (char *) data->data, data->size );
			PKI_MEM_add( buf, "' WHERE ", 8);

			/*
			base=strlen(buf);
			for( i=0; i < data->size; i++ ) {
				sprintf(buf + base + i, "%c", data->data[i]);
			}
			sprintf(buf+base+i,"' WHERE ");
			*/

			/* Let's add the WHERE clause */
			where = 1;
		}
		/* The tmp_s should point to the next token */
		tmp_s += strlen(col) + strlen(val) + 3;

		/* Control if we need to add the AND in the SQL statement */
		if( add_and == 1 ) {
			PKI_MEM_add( buf, " AND ", 5);
		}

		PKI_MEM_add( buf, col, strlen( col ));
		PKI_MEM_add( buf, "='", 2);
		PKI_MEM_add( buf, val, strlen( val ));
		PKI_MEM_add( buf, "' ", 2 );

		/*
		strncat( buf, col, BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, "='", BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, val, BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, "'", BUFF_MAX_SIZE - strlen(buf) );
		*/

		/* This triggers the adding of AND on the next iteration */
		add_and = 1;
	}

	PKI_Free (table);

	if( (ret = PKI_Malloc(buf->size) + 1) == NULL ) {
		if( buf ) PKI_MEM_free ( buf );
		return( NULL );
	}
	memcpy( ret, buf->data, buf->size );

	PKI_MEM_free ( buf );

	return( ret );
}
Exemple #16
0
char *parse_url_query ( const URL * url ) {

	char * ret = NULL;
	char * table = NULL;
	char * tmp_s = NULL;
	char * tmp_s2 = NULL;
	int where = 0;
	int add_and = 0;

	char col[1024];
	char val[1024];
	char tmp[1024];

	PKI_MEM *buf = NULL;

	if( !url || !url->path ) return( NULL );

	tmp_s = url->path;

	while((tmp_s2 = strchr(tmp_s, '/')) != NULL ) {
		tmp_s2++;
		tmp_s = tmp_s2;
	}

	if((table = parse_url_table ( url )) == NULL) {
		return (NULL);
	}

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

	snprintf( tmp, sizeof( tmp ), "SELECT %s from %s ", url->attrs, table );
	PKI_Free (table);

	PKI_MEM_add( buf, tmp, strlen( tmp ));

	where = 0;
	while( sscanf(tmp_s, "(%[^)=]=%[^)])", col, val) > 1 ) {
		if( where == 0 ) {
			/* Let's add the WHERE clause */
			PKI_MEM_add(buf, "WHERE ", 6);
			where = 1;
		}
		/* The tmp_s should point to the next token */
		tmp_s += strlen(col) + strlen(val) + 3;

		/* Control if we need to add the AND in the SQL statement */
		if( add_and == 1 ) {
			PKI_MEM_add( buf, " AND ", 5);
		}

		PKI_MEM_add( buf, col, strlen( col ));
		PKI_MEM_add( buf, "='", 2);
		PKI_MEM_add( buf, val, strlen( val ));
		PKI_MEM_add( buf, "' ", 2);

/*
	fprintf(stderr, "DEBUG:::PKI_MEM_BUF => ");
	for ( i=0; i< buf->size; i++ ) {
		fprintf( stderr, "%c", buf->data[i]);
	} fprintf( stderr, "\n");
*/

		/*
		strncat( buf, col, BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, "='", BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, val, BUFF_MAX_SIZE - strlen(buf) );
		strncat( buf, "'", BUFF_MAX_SIZE - strlen(buf) );
		*/

		/* This triggers the adding of AND on the next iteration */
		add_and = 1;
	}

	if( (ret = PKI_Malloc (buf->size+1)) == NULL ) {
		PKI_MEM_free ( buf );
		return( NULL );
	}

	memcpy( ret, buf->data, buf->size );
	// fprintf( stderr, "DEBUG:::QUERY => %s\n\n", ret );

	/*
	strncpy( ret, buf, strlen( buf ));
	*/

	PKI_MEM_free ( buf );
	return( ret );
}