repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
azadeh-afzar/CCN-IRIBU | src/ccnl-fwd/include/ccnl-localrpc.h | <reponame>azadeh-afzar/CCN-IRIBU<filename>src/ccnl-fwd/include/ccnl-localrpc.h<gh_stars>10-100
/**
* @addtogroup CCNL-fwd
* @{
* @file ccnl-localrpc.h
* @brief CCN-lite - local RPC processing logic
*
* @author <NAME> <<EMAIL>>
*
* @copyright (C) 2014-2018, <NAME>, University of Basel
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_LOCALRPC_H
#define CCNL_LOCALRPC_H
#ifndef CCNL_LINUXKERNEL
#include "ccnl-relay.h"
#include "ccnl-face.h"
#else
#include "../../ccnl-core/include/ccnl-relay.h"
#include "../../ccnl-core/include/ccnl-face.h"
#endif
/**
* @brief Processing of Local RPC messages
*
* @param[in] relay pointer to current ccnl relay
* @param[in] from face on which the message was received
* @param[in] buf data which were received
* @param[in] buflen length of the received data
*
* @return < 0 if no bytes consumed or error
*/
int8_t
ccnl_localrpc_exec(struct ccnl_relay_s *relay, struct ccnl_face_s *from,
uint8_t **buf, size_t *buflen);
#endif
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-test/include/ccnl-unit.h | <filename>src/ccnl-test/include/ccnl-unit.h
#ifndef CCNL_UNIT_H
#define CCNL_UNIT_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
int C_ASSERT_EQUAL_INT(int a, int b){
return a == b ? 1 : 0;
}
int C_ASSERT_EQUAL_STRING(char *a, char *b){
return !strcmp(a,b);
}
int C_ASSERT_EQUAL_STRING_N(char *a, char *b, int len){
return !strncmp(a,b,len);
}
// COL: 0 = defalut, 1 = green, -1 = red
#define TESTMSG(LVL, COL, ...) do{ \
if(COL == 0){\
fprintf(stderr, "\033[0m");\
}\
else if(COL == 1){\
fprintf(stderr, "\033[0;32m");\
}\
else if(COL == -1){\
fprintf(stderr, "\033[0;31m");\
}\
fprintf(stderr, "Test[%d]: ", LVL);\
fprintf(stderr, __VA_ARGS__);\
fprintf(stderr, "\033[0m");\
} while (0);
int RUN_TEST(int testnum, char *description,
int (*prepare)(void **testdata, void **comp),
int(*run)(void *testdata, void *comp),
int(*cleanup)(void *testdata, void *comp),
void *testdata, void *comp){
TESTMSG(testnum, 0, "%s \n", description);
int ret = 0;
ret = prepare(&testdata, &comp);
if(!ret){
TESTMSG(testnum, -1, "Error while preparing test\n");
return 0;
}
ret = run(testdata, comp);
if(!ret){
TESTMSG(testnum, -1, "Error while running test\n");
return 0;
}
ret = cleanup(testdata, comp);
if(!ret){
TESTMSG(testnum, -1, "Error while cleaning up test\n");
return 0;
}
TESTMSG(testnum, 1, "SUCCESSFUL\n");
return 1;
}
#endif // CCNL_UNIT_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-array.c | /*
* @f ccnl-buf.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
void null_func(void);
#ifndef CCNL_LINUXKERNEL
#include "ccnl-array.h"
#include <stddef.h>
#include "ccnl-malloc.h"
struct ccnl_array_s*
ccnl_array_new(int capacity)
{
size_t size = sizeof(struct ccnl_array_s);
struct ccnl_array_s* array = (struct ccnl_array_s *)ccnl_malloc(size);
array->count = 0;
array->capacity = capacity ? capacity : CCNL_ARRAY_DEFAULT_CAPACITY;
array->items = (void **)ccnl_calloc(array->capacity, sizeof(void *));
return array;
}
void
ccnl_array_free(struct ccnl_array_s *array)
{
if (array)
{
ccnl_free(array->items);
ccnl_free(array);
}
}
void
ccnl_array_push(struct ccnl_array_s *array, void *item)
{
ccnl_array_insert(array, item, array->count);
}
void*
ccnl_array_pop(struct ccnl_array_s *array)
{
#ifdef CCNL_ARRAY_CHECK_BOUNDS
if (array->count < 1)
{
// TODO: warning
return NULL;
}
#endif
array->count--;
return array->items[array->count];
}
void
ccnl_array_insert(struct ccnl_array_s *array, void *item, int index)
{
int i;
#ifdef CCNL_ARRAY_CHECK_BOUNDS
if (index > array->count)
{
// TODO: warning
return;
}
#endif
if (index >= array->capacity)
{
array->capacity = array->capacity * 3 / 2;
array->items = (void **)ccnl_realloc(array->items, array->capacity * sizeof(void *));
}
for (i = array->count - 1; i >= index; i--)
{
array->items[i+1] = array->items[i];
}
array->items[index] = item;
array->count++;
}
void
ccnl_array_remove(struct ccnl_array_s *array, void *item)
{
int offset = 0;
int i = 0;
while (i + offset < array->count)
{
if (array->items[i + offset] == item)
{
offset++;
}
else
{
array->items[i] = array->items[i + offset];
i++;
}
}
array->count -= offset;
}
void
ccnl_array_remove_index(struct ccnl_array_s *array, int index)
{
int i;
#ifdef CCNL_ARRAY_CHECK_BOUNDS
if (index >= array->count)
{
// TODO: warning
return;
}
#endif
for (i = index; i < array->count - 1; i++)
{
array->items[i] = array->items[i+1];
}
array->count--;
}
int
ccnl_array_find(struct ccnl_array_s *array, void *item)
{
int i;
for (i = 0; i < array->count; i++)
{
if (array->items[i] == item)
{
return i;
}
}
return CCNL_ARRAY_NOT_FOUND;
}
int
ccnl_array_contains(struct ccnl_array_s *array, void *item)
{
return ccnl_array_find(array, item) != CCNL_ARRAY_NOT_FOUND;
}
#endif
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-callbacks.h | /*
* @f ccnl-callbacks.h
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2018 <NAME>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2018-05-21 created (based on ccnl-producer.h)
*/
#ifndef CCNL_CALLBACKS_H
#define CCNL_CALLBACKS_H
#include "ccnl-core.h"
/**
* @brief Function pointer callback type for on-data events
*/
typedef int (*ccnl_cb_on_data)(struct ccnl_relay_s *relay,
struct ccnl_face_s *face,
struct ccnl_pkt_s *pkt);
/**
* @brief Set an inbound on-data event callback function
*
* Setting an on-data callback function allows to intercept inbound Data
* packets. The event is triggered before a Content Store lookup is performed.
*
* @param[in] func The callback function for inbound on-data events
*/
void ccnl_set_cb_rx_on_data(ccnl_cb_on_data func);
/**
* @brief Set an outbound on-data event callback function
*
* Setting an on-data callback function allows to intercept outbound Data
* packets. The event is triggered after a Content Store lookup is performed.
*
* @param[in] func The callback function for outbound on-data events
*/
void ccnl_set_cb_tx_on_data(ccnl_cb_on_data func);
/**
* @brief Callback for inbound on-data events
*
* @param[in] relay The active ccn-lite relay
* @param[in] from The face the packet was received over
* @param[in] pkt The actual received packet
*
* @note if the callback function returns any other value than 0,
* then the data packet is discarded.
*
* @return return value of the callback function
* @return 0, if no function has been set
*/
int ccnl_callback_rx_on_data(struct ccnl_relay_s *relay,
struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt);
/**
* @brief Callback for outbound on-data events
*
* @param[in] relay The active ccn-lite relay
* @param[in] from The face the packet is sent over
* @param[in] pkt The actual packet to send
*
* @note if the callback function returns any other value than 0,
* then the data packet is not sent and discarded.
*
* @return return value of the callback function
* @return 0, if no function has been set
*/
int ccnl_callback_tx_on_data(struct ccnl_relay_s *relay,
struct ccnl_face_s *to,
struct ccnl_pkt_s *pkt);
#endif /* CCNL_CALLBACKS_H */
|
azadeh-afzar/CCN-IRIBU | test/ccnl-core/test_sockunion.c | /**
* @file test-sockunion.c
* @brief Tests for sockunion related functions
*
* Copyright (C) 2018 Safety IO
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "ccnl-sockunion.h"
void test_ll2ascii_invalid()
{
char *result = ll2ascii(NULL, 1);
assert_true(result == NULL);
const char *address = "deadbeef";
/** size (second parameter) should be larger than the array which stores the result (in order to fail) */
result = ll2ascii(NULL, CCNL_LLADDR_STR_MAX_LEN + 1);
assert_true(result == NULL);
}
void test_ll2ascii_valid()
{
const char *address = "ffffffffffff";
char *result = ll2ascii((unsigned char*)address, 6);
assert_true(result != NULL);
/**
* The test will actually fail at the above "assert_true" statement if 'result'
* is null - however, the static code analyzer of LLVM does not recognize this
* behavior, hence, the actual check if 'result' is not NULL
*/
if (result) {
/**
* This caused some confusion, but "f" is a numerical 102 in ASCII and
* (102 >> 4) => 6 and (also 102 & 0xF) => 6, so the result is '66'. Writing
* something alike "fff...fff" in order to retrieve "ff:ff ... ff" does
* not work.
*/
assert_true(memcmp("66:66:66:66:66:66", result, 17) == 0);
}
}
void test_half_byte_to_char()
{
uint8_t half_byte = 0x9;
char result = _half_byte_to_char(half_byte);
assert_true(result == '9');
half_byte = 0xB;
result = _half_byte_to_char(half_byte);
assert_true(result == 'b');
}
void test_ccnl_is_local_addr_invalid()
{
int result = ccnl_is_local_addr(NULL);
assert_int_equal(result, 0);
}
void test_ccnl_is_local_addr_valid()
{
sockunion socket;
socket.sa.sa_family = AF_UNIX;
int result = ccnl_is_local_addr(&socket);
assert_int_equal(result, -1);
/** test for socket type ipv4 */
socket.sa.sa_family = AF_INET;
socket.ip4.sin_addr.s_addr = htonl(0x7f000001);
result = ccnl_is_local_addr(&socket);
assert_int_equal(result, 1);
/** test for socket type ipv6 with given ipv4 loopback */
socket.sa.sa_family = AF_INET6;
unsigned char ipv4_loopback[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1 };
memcpy((socket.ip6.sin6_addr.s6_addr), ipv4_loopback, 16);
result = ccnl_is_local_addr(&socket);
assert_int_equal(result, 1);
unsigned char ipv6_loopback[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
memcpy(socket.ip6.sin6_addr.s6_addr, ipv6_loopback, 16);
/** test for socket type ipv6 with ipv6 loopback */
result = ccnl_is_local_addr(&socket);
assert_int_equal(result, 1);
}
void test_ccnl_addr2ascii_invalid()
{
char *result = ccnl_addr2ascii(NULL);
assert_string_equal(result, "(local)");
}
int main(void)
{
const UnitTest tests[] = {
unit_test(test_half_byte_to_char),
unit_test(test_ll2ascii_invalid),
unit_test(test_ll2ascii_valid),
unit_test(test_ccnl_is_local_addr_invalid),
unit_test(test_ccnl_is_local_addr_valid),
unit_test(test_ccnl_addr2ascii_invalid),
};
return run_tests(tests);
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-buf.c | <reponame>azadeh-afzar/CCN-IRIBU
/*
* @f ccnl-buf.c
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_LINUXKERNEL
#include <stdio.h>
#include "ccnl-os-time.h"
#include "ccnl-buf.h"
#include "ccnl-logging.h"
#include "ccnl-relay.h"
#include "ccnl-forward.h"
#include "ccnl-prefix.h"
#include "ccnl-malloc.h"
#else
#include "../include/ccnl-os-time.h"
#include "../include/ccnl-buf.h"
#include "../include/ccnl-logging.h"
#include "../include/ccnl-relay.h"
#include "../include/ccnl-forward.h"
#include "../include/ccnl-prefix.h"
#include "../include/ccnl-malloc.h"
#endif
struct ccnl_buf_s*
ccnl_buf_new(void *data, size_t len)
{
struct ccnl_buf_s *b = (struct ccnl_buf_s*) ccnl_malloc(sizeof(*b) + len);
if (!b) {
return NULL;
}
b->next = NULL;
b->datalen = len;
if (data) {
memcpy(b->data, data, len);
}
return b;
}
void
ccnl_core_cleanup(struct ccnl_relay_s *ccnl)
{
int k;
DEBUGMSG_CORE(TRACE, "ccnl_core_cleanup %p\n", (void *) ccnl);
while (ccnl->pit)
ccnl_interest_remove(ccnl, ccnl->pit);
while (ccnl->faces)
ccnl_face_remove(ccnl, ccnl->faces); // removes allmost all FWD entries
while (ccnl->fib) {
struct ccnl_forward_s *fwd = ccnl->fib->next;
ccnl_prefix_free(ccnl->fib->prefix);
ccnl_free(ccnl->fib);
ccnl->fib = fwd;
}
while (ccnl->contents)
ccnl_content_remove(ccnl, ccnl->contents);
while (ccnl->nonces) {
struct ccnl_buf_s *tmp = ccnl->nonces->next;
ccnl_free(ccnl->nonces);
ccnl->nonces = tmp;
}
for (k = 0; k < ccnl->ifcount; k++)
ccnl_interface_cleanup(ccnl->ifs + k);
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-android/native/src/ccn-lite-android.c | <gh_stars>10-100
/*
* @f ccn-lite-android.c
* @b native code (library) for Android devices
*
* Copyright (C) 2015, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2015-04-29 created
*/
#include "ccn-lite-android.h"
#include "ccnl-defs.h"
#include "ccnl-core.h"
#include "ccnl-echo.h"
#include "ccnl-defs.h"
#include "ccnl-os-time.h"
#include "ccnl-logging.h"
#include "ccnl-http-status.h"
#include <unistd.h>
#define _GNU_SOURCE
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
int pipe2(int fds[2], int flags){
return syscall(__NR_pipe2, fds, flags);
}
void append_to_log(char *line);
#ifdef USE_HMAC256
const char secret_key[] = "some secret secret secret secret";
unsigned char keyval[64];
unsigned char keyid[32];
#endif
#define ccnl_app_RX(x,y) do{}while(0)
#define cache_strategy_remove(...) 0
#define cache_strategy_cache(...) 0
#include "ccnl-localrpc.h"
#include "ccnl-sched.h"
#include "ccnl-frag.h"
// ----------------------------------------------------------------------
struct ccnl_relay_s theRelay;
// ----------------------------------------------------------------------
#ifdef USE_LINKLAYER
int
ccnl_open_ethdev(char *devname, struct sockaddr_ll *sll, int ethtype)
{
struct ifreq ifr;
int s;
DEBUGMSG(TRACE, "ccnl_open_ethdev %s 0x%04x\n", devname, ethtype);
s = socket(AF_PACKET, SOCK_RAW, htons(ethtype));
if (s < 0) {
perror("eth socket");
return -1;
}
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, (char*) devname, IFNAMSIZ);
if(ioctl(s, SIOCGIFHWADDR, (void *) &ifr) < 0 ) {
perror("ethsock ioctl get hw addr");
return -1;
}
sll->sll_family = AF_PACKET;
memcpy(sll->sll_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
if(ioctl(s, SIOCGIFINDEX, (void *) &ifr) < 0 ) {
perror("ethsock ioctl get index");
return -1;
}
sll->sll_ifindex = ifr.ifr_ifindex;
sll->sll_protocol = htons(ethtype);
if (bind(s, (struct sockaddr*) sll, sizeof(*sll)) < 0) {
perror("ethsock bind");
return -1;
}
return s;
}
#endif // USE_LINKLAYER
int
ccnl_open_udpdev(int port, struct sockaddr_in *si)
{
int s;
unsigned int len;
s = socket(PF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("udp socket");
return -1;
}
si->sin_addr.s_addr = INADDR_ANY;
si->sin_port = htons(port);
si->sin_family = PF_INET;
if(bind(s, (struct sockaddr *)si, sizeof(*si)) < 0) {
perror("udp sock bind");
return -1;
}
len = sizeof(*si);
getsockname(s, (struct sockaddr*) si, &len);
return s;
}
void
ccnl_ll_TX(struct ccnl_relay_s *ccnl, struct ccnl_if_s *ifc,
sockunion *dest, struct ccnl_buf_s *buf)
{
int rc;
switch(dest->sa.sa_family) {
#ifdef USE_IPV4
case AF_INET:
rc = sendto(ifc->sock,
buf->data, buf->datalen, 0,
(struct sockaddr*) &dest->ip4, sizeof(struct sockaddr_in));
DEBUGMSG(DEBUG, "udp sendto %s/%d returned %d\n",
inet_ntoa(dest->ip4.sin_addr), ntohs(dest->ip4.sin_port), rc);
break;
#endif
#ifdef USE_LINKLAYER
case AF_PACKET:
rc = jni_bleSend(buf->data, buf->datalen);
DEBUGMSG(DEBUG, "eth_sendto %s returned %d\n",
ll2ascii(dest->linklayer.sll_addr, dest->linklayer.sll_halen), rc);
break;
#endif
#ifdef USE_UNIXSOCKET
case AF_UNIX:
rc = sendto(ifc->sock,
buf->data, buf->datalen, 0,
(struct sockaddr*) &dest->ux, sizeof(struct sockaddr_un));
DEBUGMSG(DEBUG, "unix sendto %s returned %d\n",
dest->ux.sun_path, rc);
break;
#endif
default:
DEBUGMSG(WARNING, "unknown transport\n");
break;
}
rc = 0; // just to silence a compiler warning (if USE_DEBUG is not set)
}
int
ccnl_close_socket(int s)
{
struct sockaddr_un su;
socklen_t len = sizeof(su);
#ifdef USE_UNIXSOCKET
if (!getsockname(s, (struct sockaddr*) &su, &len) &&
su.sun_family == AF_UNIX) {
unlink(su.sun_path);
}
#endif
close(s);
return 0;
}
// ----------------------------------------------------------------------
static int inter_ccn_interval = 0; // in usec
static int inter_pkt_interval = 0; // in usec
#ifdef USE_SCHEDULER
struct ccnl_sched_s*
ccnl_relay_defaultFaceScheduler(struct ccnl_relay_s *ccnl,
void(*cb)(void*,void*))
{
return ccnl_sched_pktrate_new(cb, ccnl, inter_ccn_interval);
}
struct ccnl_sched_s*
ccnl_relay_defaultInterfaceScheduler(struct ccnl_relay_s *ccnl,
void(*cb)(void*,void*))
{
return ccnl_sched_pktrate_new(cb, ccnl, inter_pkt_interval);
}
/*
#else
# define ccnl_relay_defaultFaceScheduler NULL
# define ccnl_relay_defaultInterfaceScheduler NULL
*/
#endif // USE_SCHEDULER
void ccnl_ageing(void *relay, void *aux)
{
ccnl_do_ageing(relay, aux);
ccnl_set_timer(1000000, ccnl_ageing, relay, 0);
}
// ----------------------------------------------------------------------
char *echopath = "/local/echo";
void
add_udpPort(struct ccnl_relay_s *relay, int port)
{
struct ccnl_if_s *i;
i = &relay->ifs[relay->ifcount];
i->sock = ccnl_open_udpdev(port, &i->addr.ip4);
if (i->sock < 0) {
DEBUGMSG(WARNING, "sorry, could not open udp device (port %d)\n",
port);
return;
}
// i->frag = CCNL_DGRAM_FRAG_NONE;
#ifdef USE_SUITE_CCNB
i->mtu = CCN_DEFAULT_MTU;
#endif
#ifdef USE_SUITE_NDNTLV
i->mtu = NDN_DEFAULT_MTU;
#endif
i->fwdalli = 1;
if (relay->defaultInterfaceScheduler)
i->sched = relay->defaultInterfaceScheduler(relay,
ccnl_interface_CTS);
relay->ifcount++;
DEBUGMSG(INFO, "UDP interface (%s) configured\n",
ccnl_addr2ascii(&i->addr));
}
// ----------------------------------------------------------------------
void
ccnl_relay_config(struct ccnl_relay_s *relay, int httpport, char *uxpath,
int max_cache_entries, char *crypto_face_path)
{
struct ccnl_if_s *i;
DEBUGMSG(INFO, "configuring relay\n");
relay->max_cache_entries = max_cache_entries;
relay->max_pit_entries = CCNL_DEFAULT_MAX_PIT_ENTRIES;
#ifdef USE_SCHEDULER
relay->defaultFaceScheduler = ccnl_relay_defaultFaceScheduler;
relay->defaultInterfaceScheduler = ccnl_relay_defaultInterfaceScheduler;
#endif
// use interface 0 for BT low energy
relay->ifs[0].mtu = 20;
if (relay->defaultInterfaceScheduler)
relay->ifs[0].sched = relay->defaultInterfaceScheduler(relay,
ccnl_interface_CTS);
relay->ifcount++;
#ifdef USE_SUITE_NDNTLV
add_udpPort(relay, NDN_UDP_PORT);
#endif
#ifdef USE_SUITE_CCNTLV
add_udpPort(relay, CCN_UDP_PORT);
#endif
#ifdef USE_HTTP_STATUS
if (httpport > 0) {
relay->http = ccnl_http_new(relay, httpport);
}
#endif // USE_HTTP_STATUS
ccnl_set_timer(1000000, ccnl_ageing, relay, 0);
}
// ----------------------------------------------------------------------
void
ccnl_populate_cache(struct ccnl_relay_s *ccnl, char *path)
{
DIR *dir;
struct dirent *de;
dir = opendir(path);
if (!dir) {
DEBUGMSG(ERROR, "could not open directory %s\n", path);
return;
}
DEBUGMSG(INFO, "populating cache from directory %s\n", path);
while ((de = readdir(dir))) {
char fname[1000];
struct stat s;
struct ccnl_buf_s *buf = 0; // , *nonce=0, *ppkd=0, *pkt = 0;
struct ccnl_content_s *c = 0;
unsigned char *data;
int fd, datalen, typ, len, suite, skip;
struct ccnl_pkt_s *pk;
if (de->d_name[0] == '.')
continue;
strncpy(fname, path, sizeof(fname));
strcat(fname, "/");
strncat(fname, de->d_name, sizeof(fname) - strlen(fname) - 1);
if (stat(fname, &s)) {
perror("stat");
continue;
}
if (S_ISDIR(s.st_mode))
continue;
DEBUGMSG(INFO, "loading file %s, %d bytes\n", de->d_name,
(int) s.st_size);
fd = open(fname, O_RDONLY);
if (!fd) {
perror("open");
continue;
}
buf = (struct ccnl_buf_s *) ccnl_malloc(sizeof(*buf) + s.st_size);
if (buf)
datalen = read(fd, buf->data, s.st_size);
else
datalen = -1;
close(fd);
if (!buf || datalen != s.st_size || datalen < 2) {
DEBUGMSG(WARNING, "size mismatch for file %s, %d/%d bytes\n",
de->d_name, datalen, (int) s.st_size);
continue;
}
buf->datalen = datalen;
suite = ccnl_pkt2suite(buf->data, datalen, &skip);
pk = NULL;
switch (suite) {
#ifdef USE_SUITE_CCNB
case CCNL_SUITE_CCNB: {
unsigned char *start;
data = start = buf->data + skip;
datalen -= skip;
if (data[0] != 0x04 || data[1] != 0x82)
goto notacontent;
data += 2;
datalen -= 2;
pk = ccnl_ccnb_bytes2pkt(start, &data, &datalen);
break;
}
#endif
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV: {
int hdrlen;
unsigned char *start;
data = start = buf->data + skip;
datalen -= skip;
hdrlen = ccnl_ccntlv_getHdrLen(data, datalen);
data += hdrlen;
datalen -= hdrlen;
pk = ccnl_ccntlv_bytes2pkt(start, &data, &datalen);
break;
}
#endif
#ifdef USE_SUITE_NDNTLV
case CCNL_SUITE_NDNTLV: {
unsigned char *olddata;
data = olddata = buf->data + skip;
datalen -= skip;
if (ccnl_ndntlv_dehead(&data, &datalen, &typ, &len) ||
typ != NDN_TLV_Data)
goto notacontent;
pk = ccnl_ndntlv_bytes2pkt(typ, olddata, &data, &datalen);
break;
}
#endif
default:
DEBUGMSG(WARNING, "unknown packet format (%s)\n", de->d_name);
goto Done;
}
if (!pk) {
DEBUGMSG(DEBUG, " parsing error in %s\n", de->d_name);
goto Done;
}
c = ccnl_content_new(&pk);
if (!c) {
DEBUGMSG(WARNING, "could not create content (%s)\n", de->d_name);
goto Done;
}
ccnl_content_add2cache(ccnl, c);
c->flags |= CCNL_CONTENT_FLAGS_STATIC;
Done:
ccnl_pkt_free(pk);
ccnl_free(buf);
continue;
notacontent:
DEBUGMSG(WARNING, "not a content object (%s)\n", de->d_name);
ccnl_free(buf);
}
closedir(dir);
}
// ----------------------------------------------------------------------
ALooper *theLooper;
pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t timer_thread;
volatile int timer_usec = -1;
int pipeT2R[2]; // timer thread to relay
int
ccnl_android_timer_io(int fd, int events, void *data)
{
unsigned char c;
int len;
if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))
return 0;
len = read(pipeT2R[0], &c, 1);
DEBUGMSG(TRACE, "timer_io %d\n", len);
timer_usec = ccnl_run_events();
pthread_mutex_unlock(&timer_mutex);
return 1; // continue receiving callbacks
}
int
ccnl_android_udp_io(int fd, int events, void *data)
{
struct ccnl_relay_s *relay = (struct ccnl_relay_s*) data;
unsigned char buf[CCNL_MAX_PACKET_SIZE];
int i, len;
DEBUGMSG(TRACE, "-- udp_io\n");
if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
return 0;
}
DEBUGMSG(TRACE, "android_udp_io %d 0x%04x, %d\n",
fd, events, relay->ifcount);
for (i = 0; i < relay->ifcount; i++) {
if (relay->ifs[i].sock != fd)
continue;
if (events | ALOOPER_EVENT_INPUT) {
sockunion src_addr;
socklen_t addrlen = sizeof(sockunion);
if ((len = recvfrom(relay->ifs[i].sock, buf, sizeof(buf),
MSG_DONTWAIT,
(struct sockaddr*) &src_addr, &addrlen)) > 0) {
DEBUGMSG(TRACE, "android_udp_io - input event %d\n", len);
if (src_addr.sa.sa_family == AF_INET) {
ccnl_core_RX(relay, i, buf, len,
&src_addr.sa, sizeof(src_addr.ip4));
}
}
}
}
return 1; // continue receiving callbacks
}
int
ccnl_android_http_io(int fd, int events, void *data)
{
struct ccnl_relay_s *relay = (struct ccnl_relay_s*) data;
struct ccnl_http_s *http = relay->http;
DEBUGMSG(TRACE, "-- http_io\n");
if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
close(http->client);
http->client = 0;
// we should check if there are pending clients ...
return 0;
}
if (events | ALOOPER_EVENT_INPUT) {
int len = sizeof(http->in) - http->inlen - 1;
len = recv(http->client, http->in + http->inlen, len, 0);
if (len == 0) {
ALooper_removeFd(theLooper, http->client);
DEBUGMSG(WARNING, "web client went away\n");
close(http->client);
http->client = 0;
// we should check if there are pending clients ...
return 0;
} else if (len > 0) {
http->in[len] = 0;
ccnl_http_status(relay, http);
}
}
if (http->outlen > 0 && (events | ALOOPER_EVENT_OUTPUT)) {
int len = send(http->client, http->out + http->outoffs,
http->outlen, 0);
if (len > 0) {
http->outlen -= len;
http->outoffs += len;
if (http->outlen <= 0) {
ALooper_removeFd(theLooper, http->client);
close(http->client);
http->client = 0;
// we should check if there are pending clients ...
DEBUGMSG(TRACE, " http closed\n");
return 0;
} else {
DEBUGMSG(TRACE, " http more to send %d\n", http->outlen);
}
}
}
return 1; // continue receiving callbacks
}
int
ccnl_android_http_accept(int fd, int events, void *data)
{
struct ccnl_relay_s *relay = (struct ccnl_relay_s*) data;
struct ccnl_http_s *http = relay->http;
struct sockaddr_in peer;
socklen_t len = sizeof(peer);
DEBUGMSG(TRACE, "-- http_accept\n");
if (http->client) // only one client at the time
return 1;
if (!(events | ALOOPER_EVENT_INPUT))
return 1;
http->client = accept(http->server,
(struct sockaddr*) &peer, &len);
if (http->client < 0)
http->client = 0;
else {
DEBUGMSG(DEBUG, "accepted web server client fd=%d\n", http->client);
http->inlen = http->outlen = http->inoffs = http->outoffs = 0;
ALooper_addFd(theLooper, http->client,
ALOOPER_POLL_CALLBACK,
ALOOPER_EVENT_INPUT, // | ALOOPER_EVENT_OUTPUT,
ccnl_android_http_io,
&theRelay);
}
return 1; // continue receiving callbacks
}
void*
timer()
{
char c = 't';
usleep(1000000);
pthread_mutex_lock(&timer_mutex);
while (1) {
timer_usec = -1;
if (theLooper) {
write(pipeT2R[1], &c, 1);
pthread_mutex_lock(&timer_mutex);
}
usleep(timer_usec < 0 ? 500000 : timer_usec);
}
return NULL;
}
// ----------------------------------------------------------------------
char*
ccnl_android_init()
{
static char done;
static char hello[200];
time_t now = time(NULL);
int i, dummy = 0;
struct ccnl_prefix_s *echoprefix;
if (done)
return hello;
done = 1;
time(&theRelay.startup_time);
debug_level = INFO;
ccnl_core_init();
DEBUGMSG(INFO, "This is 'ccn-lite-android', starting at %s",
ctime(&theRelay.startup_time) + 4);
DEBUGMSG(INFO, " ccnl-core: %s\n", CCNL_VERSION);
DEBUGMSG(INFO, " compile time: %s %s\n", __DATE__, __TIME__);
// DEBUGMSG(INFO, " compile options: %s\n", compile_string);
ccnl_relay_config(&theRelay, 8080, NULL, 0, NULL);
theLooper = ALooper_forThread();
// launch timer thread
pipe2(pipeT2R, O_DIRECT);
pthread_create(&timer_thread, NULL, timer, NULL);
// timer handler
ALooper_addFd(theLooper, pipeT2R[0], ALOOPER_POLL_CALLBACK,
ALOOPER_EVENT_INPUT, ccnl_android_timer_io, &theRelay);
// UDP and HTTP ports
for (i = 0; i < theRelay.ifcount; i++) {
if (theRelay.ifs[i].addr.sa.sa_family == AF_INET)
ALooper_addFd(theLooper, theRelay.ifs[i].sock,
ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT,
ccnl_android_udp_io, &theRelay);
}
ALooper_addFd(theLooper, theRelay.http->server, ALOOPER_POLL_CALLBACK,
ALOOPER_EVENT_INPUT, ccnl_android_http_accept, &theRelay);
ccnl_populate_cache(&theRelay, "/mnt/sdcard/ccn-lite");
#ifdef USE_ECHO
#ifdef USE_SUITE_CCNTLV
strncpy(hello, echopath, sizeof(hello));
echoprefix = ccnl_URItoPrefix(hello, CCNL_SUITE_CCNTLV, &dummy);
ccnl_echo_add(&theRelay, echoprefix);
#endif
#ifdef USE_SUITE_NDNTLV
strncpy(hello, echopath, sizeof(hello));
echoprefix = ccnl_URItoPrefix(hello, CCNL_SUITE_NDNTLV, NULL);
ccnl_echo_add(&theRelay, echoprefix);
#endif
#endif // USE_ECHO
#ifdef USE_HMAC256
ccnl_hmac256_keyval((unsigned char*)secret_key,
strlen(secret_key), keyval);
ccnl_hmac256_keyid((unsigned char*)secret_key,
strlen(secret_key), keyid);
#endif
snprintf(hello, sizeof(hello), "ccn-lite-android, %s",
ctime(&theRelay.startup_time) + 4);
return hello;
}
char*
ccnl_android_getTransport()
{
static char addr[100];
struct ifreq *ifr;
struct ifconf ifc;
int s, i;
int numif;
// find number of interfaces.
memset(&ifc, 0, sizeof(ifc));
ifc.ifc_ifcu.ifcu_req = NULL;
ifc.ifc_len = 0;
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
return NULL;
if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
return NULL;
if ((ifr = (struct ifreq*) ccnl_malloc(ifc.ifc_len)) == NULL)
return NULL;
ifc.ifc_ifcu.ifcu_req = ifr;
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
ccnl_free(ifr);
return NULL;
}
numif = ifc.ifc_len / sizeof(struct ifreq);
for (i = 0; i < numif; i++) {
struct ifreq *r = &ifr[i];
struct sockaddr_in *sin = (struct sockaddr_in *)&r->ifr_addr;
if (strcmp(r->ifr_name, "lo")) {
snprintf(addr, sizeof(addr), "(%s) UDP ", ifr[i].ifr_name);
for (i = 0; i < theRelay.ifcount; i++) {
if (theRelay.ifs[i].addr.sa.sa_family != AF_INET)
continue;
sin->sin_port = theRelay.ifs[i].addr.ip4.sin_port;
snprintf(addr + strlen(addr), sizeof(addr) - strlen(addr), "%s ",
ccnl_addr2ascii((sockunion*)sin));
}
ccnl_free(ifr);
return addr;
}
}
ccnl_free(ifr);
return NULL;
}
// eof
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-crypto.h | <reponame>azadeh-afzar/CCN-IRIBU
//
// Created by <NAME> on 28.06.17.
//
#ifndef CCNL_CRYPTO_H
#define CCNL_CRYPTO_H
#endif //CCNL_CRYPTO_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/include/ccnl-ext-hmac.h | /**
* @addtogroup CCNL-utils
* @{
*
* @file ccnl-ext-hmac.h
* @brief HMAC-256 signing support based on RFC 2104
*
* Copyright (C) 2015-18 <<EMAIL>>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_EXT_MAC_H_
#define CCNL_EXT_MAC_H_
#include "lib-sha256.h"
#include "ccnl-pkt-ccnb.h"
#include "ccnl-pkt-ccntlv.h"
#include "ccnl-pkt-localrpc.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-switch.h"
/**
* @brief Generates an HMAC key
*
* @note The \p keyval must be of at least 64 bytes (block length).
*
* The function either copies \p klen bytes of \p key or generates a new
* key.
*
* @param[in] key The value of the key (to be copied or generated)
* @param[in] klen The length of the key
* @param[in] keyval The (final) key (to be copied or generated)
*/
void
ccnl_hmac256_keyval(uint8_t *key, size_t klen,
uint8_t *keyval);
/**
* @brief TODO
*
* @note The \p keyid must be of at least 32 bytes (digest length).
*
* @param[in] key The actual key
* @param[in] klen The length of the key
* @param[in] keyid TODO
*/
void
ccnl_hmac256_keyid(uint8_t *key, size_t klen,
uint8_t *keyid);
/**
* @brief Adds padding bytes to a key
*
* @param[in] ctx Context 'object' of the underlying SHA256 implementation
* @param[in] keyval The key to pad
* @param[in] kvlen The length of the key
* @param[in] pad The padding byte
*/
void
ccnl_hmac256_keysetup(SHA256_CTX_t *ctx, uint8_t *keyval, size_t kvlen,
uint8_t pad);
/**
* @brief Generates an HMAC signature
*
* @param[in] keyval The key
* @param[in] kvlen The lengthof the key
* @param[in] data The data to sign
* @param[in] dlen The length of the sign
* @param[in] md The message digest
* @param[out] mlen The length of the message digest
*/
void
ccnl_hmac256_sign(uint8_t *keyval, size_t kvlen,
uint8_t *data, size_t dlen,
uint8_t *md, size_t *mlen);
#ifdef NEEDS_PACKET_CRAFTING
#ifdef USE_SUITE_CCNTLV
/**
* @brief Signs CCNx content and prepends signature with the header
*
* @note The content is before the \p offset in \p buf. The function adjusts the
* \p offset.
*
* @param[in] name The prefix of the content to sign
* @param[in] payload The actual content
* @param[in] paylen The length of \p payload
* @param[in] lastchunknum Position of the last chunk in the \p buf
* @param[in] contentpos Position of the content in the \p buf
* @param[in] keyval The key to use for signing the content (>= 64 bytes)
* @param[in] keydigest The digest (>= 32 bytes)
* @param[out] offset TODO
* @param[out] buf A byte representation of the actual packet
*
* @return Upon success, the function returns the number of used bytes
*/
int8_t
ccnl_ccntlv_prependSignedContentWithHdr(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *lastchunknum,
size_t *contentpos,
uint8_t *keyval, // 64B
uint8_t *keydigest, // 32B
size_t *offset, uint8_t *buf, size_t *retlen);
#endif // USE_SUITE_CCNTLV
#ifdef USE_SUITE_NDNTLV
/**
* @brief Signs an NDO and prepends signature
*
* @param[in] name The prefix of the content to sign
* @param[in] payload The actual content
* @param[in] paylen The length of \p payload
* @param[in] final_block_id Denotes position of optional MetaInfo fields
* @param[in] contentpos Position of the content in the \p buf
* @param[in] keyval The key to use for signing the content (>= 64 bytes)
* @param[in] keydigest The digest (>= 32 bytes)
* @param[out] offset TODO
* @param[out] buf A byte representation of the actual packet
*
* @return 0 upon success, nonzero upon failure
*/
int8_t
ccnl_ndntlv_prependSignedContent(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *final_block_id, size_t *contentpos,
uint8_t *keyval, // 64B
uint8_t *keydigest, // 32B
size_t *offset, uint8_t *buf, size_t *reslen);
#endif // USE_SUITE_NDNTLV
#endif // NEEDS_PACKET_CRAFTING
#endif
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-face.h | /*
* @f ccnl-face.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_FACE_H
#define CCNL_FACE_H
#include "ccnl-sockunion.h"
#ifdef CCNL_RIOT
#include "evtimer_msg.h"
#endif
struct ccnl_face_s {
struct ccnl_face_s *next, *prev;
int faceid;
int ifndx;
sockunion peer;
int flags;
uint32_t last_used; // updated when we receive a packet
struct ccnl_buf_s *outq, *outqend; // queue of packets to send
struct ccnl_frag_s *frag; // which special datagram armoring
struct ccnl_sched_s *sched;
#ifdef CCNL_RIOT
evtimer_msg_event_t evtmsg_timeout;
#endif
};
void
ccnl_face_free(struct ccnl_face_s *face);
#endif // CCNL_FACE_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-array.h | <reponame>azadeh-afzar/CCN-IRIBU
/*
* @f ccnl-buf.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_LINUXKERNEL
#define CCNL_ARRAY_DEFAULT_CAPACITY 4
#define CCNL_ARRAY_CHECK_BOUNDS
#define CCNL_ARRAY_NOT_FOUND -1
struct ccnl_array_s
{
int count;
int capacity;
void **items;
};
struct ccnl_array_s*
ccnl_array_new(int capacity);
void
ccnl_array_free(struct ccnl_array_s *array);
// Insert an item at the end of the array, possibly realocating the array.
void
ccnl_array_push(struct ccnl_array_s *array, void *item);
// Return and remove the last item.
void*
ccnl_array_pop(struct ccnl_array_s *array);
// Insert item at index by pushing down all subsequent items by one,
// possibly reallocating the array.
void
ccnl_array_insert(struct ccnl_array_s *array, void *item, int index);
// Remove all occurrences of item by moving up the subsequent items.
void
ccnl_array_remove(struct ccnl_array_s *array, void *item);
// Remove the item at index by moving up all subsequent items by one.
void
ccnl_array_remove_index(struct ccnl_array_s *array, int index);
// Returns the index of the first occurrence of item, or CCNL_ARRAY_NOT_FOUND.
int
ccnl_array_find(struct ccnl_array_s *array, void *item);
// Returns 1 if the item can be found in the array.
int
ccnl_array_contains(struct ccnl_array_s *array, void *item);
#endif
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-relay.h | <reponame>azadeh-afzar/CCN-IRIBU
/**
* @ingroup CCNL-core
* @{
* @file ccnl-relay.h
* @brief CCN lite (CCNL) data structure ccnl-relay. contains all important datastructures for CCN-lite forwarding
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*
* @copyright (C) 2011-17, University of Basel
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_RELAY_H
#define CCNL_RELAY_H
#include "ccnl-defs.h"
#include "ccnl-face.h"
#include "ccnl-if.h"
#include "ccnl-pkt.h"
#include "ccnl-sched.h"
struct ccnl_relay_s {
void (*ccnl_ll_TX_ptr)(struct ccnl_relay_s*, struct ccnl_if_s*,
sockunion*, struct ccnl_buf_s*);
#ifndef CCNL_ARDUINO
time_t startup_time;
#endif
int id;
struct ccnl_face_s *faces; /**< The existing forwarding faces */
struct ccnl_forward_s *fib; /**< The Forwarding Information Base (FIB) */
struct ccnl_interest_s *pit; /**< The Pending Interest Table (PIT) */
struct ccnl_content_s *contents; /**< contentsend; */
struct ccnl_buf_s *nonces; /**< The nonces that are currently in use */
int contentcnt; /**< number of cached items */
int max_cache_entries; /**< max number of cached items -1: unlimited */
int pitcnt; /**< Number of entries in the PIT */
int max_pit_entries; /**< max number of pit entries; -1: unlimited */
struct ccnl_if_s ifs[CCNL_MAX_INTERFACES];
int ifcount; /**< number of active interfaces */
char halt_flag; /**< Flag to interrupt the IO_Loop and to exit the relay */
struct ccnl_sched_s* (*defaultFaceScheduler)(struct ccnl_relay_s*,
void(*cts_done)(void*,void*)); /**< FuncPoint to the scheduler for faces*/
struct ccnl_sched_s* (*defaultInterfaceScheduler)(struct ccnl_relay_s*,
void(*cts_done)(void*,void*)); /**< FuncPoint to the scheduler for interfaces*/
#ifdef USE_HTTP_STATUS
struct ccnl_http_s *http; /**< http server for status information*/
#endif
void *aux;
/*
struct ccnl_face_s *crypto_face;
struct ccnl_pendcrypt_s *pendcrypt;
char *crypto_path;
*/
};
/**
* @brief Function pointer type for caching strategy function
*/
typedef int (*ccnl_cache_strategy_func)(struct ccnl_relay_s *relay,
struct ccnl_content_s *c);
/**
* @brief Broadcast an interest message to all available interfaces
*
* @param[in] ccnl The CCN-lite relay used to send the interest
* @param[in] interest The interest which should be sent
*/
void ccnl_interest_broadcast(struct ccnl_relay_s *ccnl,
struct ccnl_interest_s *interest);
void ccnl_face_CTS(struct ccnl_relay_s *ccnl, struct ccnl_face_s *f);
struct ccnl_face_s*
ccnl_get_face_or_create(struct ccnl_relay_s *ccnl, int ifndx,
struct sockaddr *sa, size_t addrlen);
struct ccnl_face_s*
ccnl_face_remove(struct ccnl_relay_s *ccnl, struct ccnl_face_s *f);
void
ccnl_interface_enqueue(void (tx_done)(void*, int, int), struct ccnl_face_s *f,
struct ccnl_relay_s *ccnl, struct ccnl_if_s *ifc,
struct ccnl_buf_s *buf, sockunion *dest);
struct ccnl_buf_s*
ccnl_face_dequeue(struct ccnl_relay_s *ccnl, struct ccnl_face_s *f);
void
ccnl_face_CTS_done(void *ptr, int cnt, int len);
/**
* @brief Send a packet to the face @p to
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] to face to send to
* @param[in] pkt packet to be sent
*
* @return 0 on success
* @return < 0 on failure
*/
int
ccnl_send_pkt(struct ccnl_relay_s *ccnl, struct ccnl_face_s *to,
struct ccnl_pkt_s *pkt);
/**
* @brief Send a buffer to the face @p to
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] to face to send to
* @param[in] buf buffer to be sent
*
* @return 0 on success
* @return < 0 on failure
*/
int
ccnl_face_enqueue(struct ccnl_relay_s *ccnl, struct ccnl_face_s *to,
struct ccnl_buf_s *buf);
struct ccnl_interest_s*
ccnl_interest_remove(struct ccnl_relay_s *ccnl, struct ccnl_interest_s *i);
/**
* @brief Forwards interest message according to FIB rules
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] i interest message to be forwarded
*/
void
ccnl_interest_propagate(struct ccnl_relay_s *ccnl, struct ccnl_interest_s *i);
struct ccnl_content_s*
ccnl_content_remove(struct ccnl_relay_s *ccnl, struct ccnl_content_s *c);
/**
* @brief add content @p c to the content store
*
* @note adding content with this function bypasses pending interests
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] c content to be added to the content store
*
* @return reference to the content @p c
* @return NULL, if @p c cannot be added
*/
struct ccnl_content_s*
ccnl_content_add2cache(struct ccnl_relay_s *ccnl, struct ccnl_content_s *c);
/**
* @brief deliver new content @p c to all clients with (loosely) matching interest
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] c content to be sent
*
* @return number of faces to which the content was sent to
*/
int
ccnl_content_serve_pending(struct ccnl_relay_s *ccnl, struct ccnl_content_s *c);
void
ccnl_do_ageing(void *ptr, void *dummy);
int
ccnl_nonce_find_or_append(struct ccnl_relay_s *ccnl, struct ccnl_buf_s *nonce);
int
ccnl_nonce_isDup(struct ccnl_relay_s *relay, struct ccnl_pkt_s *pkt);
void
ccnl_core_cleanup(struct ccnl_relay_s *ccnl);
#ifdef NEEDS_PREFIX_MATCHING
/**
* @brief Add entry to the FIB
*
* @par[in] relay Local relay struct
* @par[in] pfx Prefix of the FIB entry
* @par[in] face Face for the FIB entry
*
* @return 0 on success
* @return -1 on error
*/
int
ccnl_fib_add_entry(struct ccnl_relay_s *relay, struct ccnl_prefix_s *pfx,
struct ccnl_face_s *face);
/**
* @brief Remove entry from the FIB
*
* @par[in] relay Local relay struct
* @par[in] pfx Prefix of the FIB entry, may be NULL
* @par[in] face Face for the FIB entry, may be NULL
*
* @return 0 on success
* @return -1 on error
*/
int
ccnl_fib_rem_entry(struct ccnl_relay_s *relay, struct ccnl_prefix_s *pfx,
struct ccnl_face_s *face);
#endif //NEEDS_PREFIX_MATCHING
/**
* @brief Prints the current FIB
*
* @par[in] relay Local relay struct
*/
void
ccnl_fib_show(struct ccnl_relay_s *relay);
/**
* @brief Prints the content of the content store
*
* @par[in] ccnl Local relay struct
*/
void
ccnl_cs_dump(struct ccnl_relay_s *ccnl);
void
ccnl_interface_CTS(void *aux1, void *aux2);
#define DBL_LINKED_LIST_ADD(l,e) \
do { if ((l)) (l)->prev = (e); \
(e)->next = (l); \
(l) = (e); \
} while(0)
#define DBL_LINKED_LIST_REMOVE(l,e) \
do { if ((l) == (e)) (l) = (e)->next; \
if ((e)->prev) (e)->prev->next = (e)->next; \
if ((e)->next) (e)->next->prev = (e)->prev; \
} while(0)
#ifdef CCNL_APP_RX
int ccnl_app_RX(struct ccnl_relay_s *ccnl, struct ccnl_content_s *c);
#endif
/**
* @brief Add content @p c to the Content Store and serve pending Interests
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] c content to add to the content store
*
* @return 0, if @p c was added to the content store
* @return -1, otherwise
*/
int
ccnl_cs_add(struct ccnl_relay_s *ccnl, struct ccnl_content_s *c);
/**
* @brief Remove content with @p prefix from the Content Store
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] prefix prefix of the content to remove from the Content Store
*
* @return 0, if content with @p prefix was removed
* @return -1, if @p ccnl or @p prefix are NULL
* @return -2, if no memory could be allocated
* @return -3, if no content with @p prefix was found to be removed
*/
int
ccnl_cs_remove(struct ccnl_relay_s *ccnl, char *prefix);
/**
* @brief Lookup content from the Content Store with prefix @p prefix
*
* @param[in] ccnl pointer to current ccnl relay
* @param[in] prefix prefix of the content to lookup from the Content Store
*
* @return pointer to the content, if found
* @return NULL, if @p ccnl or @p prefix are NULL
* @return NULL, on memory allocation failure
* @return NULL, if not found
*/
struct ccnl_content_s *
ccnl_cs_lookup(struct ccnl_relay_s *ccnl, char *prefix);
/**
* @brief Set a function to control the cache replacement strategy
*
* The given function will be called if the cache is full and a new content
* chunk arrives. It shall remove (at least) one entry from the cache.
*
* If the return value of @p func is 0, the default caching strategy will be
* applied by the CCN-lite stack. If the return value is 1, it is assumed that
* (at least) one entry has been removed from the cache.
*
* @param[in] func The function to be called for an incoming content chunk if
* the cache is full.
*/
void ccnl_set_cache_strategy_remove(ccnl_cache_strategy_func func);
/**
* @brief Set a function to control the caching decision strategy
*
* The given function will be called when a new content chunk arrives.
* It decides whether or not to cache the new content.
*
* If the return value of @p func is 1, the content chunk will be cached;
* otherwise, it will be discarded. If no caching decision strategy is
* implemented, all content chunks will be cached.
*
* @param[in] func The function to be called for an incoming content
* chunk.
*/
void ccnl_set_cache_strategy_cache(ccnl_cache_strategy_func func);
/**
* @brief May be defined for a particular caching strategy
*/
int cache_strategy_remove(struct ccnl_relay_s *relay, struct ccnl_content_s *c);
/**
* @brief May be defined for a particular caching decision strategy
*/
int cache_strategy_cache(struct ccnl_relay_s *relay, struct ccnl_content_s *c);
#endif //CCNL_RELAY_H
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-interest.h | /*
* @f ccnl-interest.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17 University of Basel
* Copyright (C) 2018 <NAME>
* Copyright (C) 2018 Safety IO
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_INTEREST_H
#define CCNL_INTEREST_H
#include "ccnl-pkt.h"
#include "ccnl-face.h"
#ifdef CCNL_RIOT
#include "evtimer_msg.h"
#endif
/**
* @brief A pending interest linked list element
*/
struct ccnl_pendint_s {
struct ccnl_pendint_s *next; /**< pointer to the next list element */
struct ccnl_face_s *face; /**< pointer to incoming face */
uint32_t last_used; /** */
};
/**
* @brief A interest linked list element
*/
struct ccnl_interest_s {
struct ccnl_interest_s *next; /**< pointer to the next list element */
struct ccnl_interest_s *prev; /**< pointer to the previous list element */
struct ccnl_pkt_s *pkt; /**< the packet the interests originates from (?) */
struct ccnl_face_s *from; /**< the face the interest was received from */
struct ccnl_pendint_s *pending; /**< linked list of faces wanting that content */
uint32_t lifetime; /**< interest lifetime */
uint32_t last_used; /**< last time the entry was used */
int retries; /**< current number of executed retransmits. */
#ifdef CCNL_RIOT
evtimer_msg_event_t evtmsg_retrans; /**< retransmission timer */
evtimer_msg_event_t evtmsg_timeout; /**< timeout timer for (?) */
#endif
};
/**
* Creates a new interest of type \ref ccnl_interest_s
*
* @param[in] ccnl
* @param[in] from
* @param[in] pkt
*
* @return Upon success a new interest of type \ref ccnl_interest_s, otherwise NULL
*/
struct ccnl_interest_s*
ccnl_interest_new(struct ccnl_relay_s *ccnl, struct ccnl_face_s *from,
struct ccnl_pkt_s **pkt);
/**
* Checks if two interests are the same
*
* @param[in] i
* @param[in] pkt
*
* @return 0
* @return 1
* @return -1 if \ref i was NULL
* @return -2 if \ref pkt was NULL
*/
int
ccnl_interest_isSame(struct ccnl_interest_s *i, struct ccnl_pkt_s *pkt);
/**
* Adds a pending interest
*
* @param[in] i
* @param[in] face
*
* @return 0
* @return 1
* @return -1 if \ref i was NULL
* @return -2 if \ref face was NULL
*/
int
ccnl_interest_append_pending(struct ccnl_interest_s *i, struct ccnl_face_s *from);
/**
* Removes a pending interest
*
* @param[in] i
* @param[in] face
*
* @return 0
* @return 1
* @return -1 if \ref i was NULL
* @return -2 if \ref face was NULL
*/
int
ccnl_interest_remove_pending(struct ccnl_interest_s *i, struct ccnl_face_s *face);
#endif //CCNL_INTEREST_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-dump.h | <reponame>azadeh-afzar/CCN-IRIBU
/**
* @file ccnl-dump.h
* @brief CCN lite extension
*
* Copyright (C) 2012-18, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_DUMP_H
#define CCNL_DUMP_H
/**
* @brief A macro which prints @p n whitespace characters
*/
#define INDENT(n) for (i = 0; i < (n); i++) CONSOLE(" ")
/**
* @brief Lists different packet types and data structures for @ref ccnl_dump
*/
enum {
CCNL_BUF = 1, /**< data type is a buffer */
CCNL_PREFIX, /**< data type is a prefix */
CCNL_RELAY, /**< data type is a relay */
CCNL_FACE, /**< data type is a face */
CCNL_FRAG, /**< data type is a fragment */
CCNL_FWD, /**< data type is a fib entry */
CCNL_INTEREST, /**< data type is an interest */
CCNL_PENDINT, /**< data type is pending interest */
CCNL_PACKET, /**< data type is packet */
CCNL_CONTENT, /**< data type is content */
CCNL_DO_NOT_USE = UINT8_MAX /**< for internal use only, sets the width of the enum to sizeof(uint8_t) */
};
char *frag_protocol(int e);
void ccnl_dump(int lev, int typ, void *p);
int get_buf_dump(int lev, void *p, long *outbuf, int *len, long *next);
int get_prefix_dump(int lev, void *p, int *len, char **val);
int get_num_faces(void *p);
int get_faces_dump(int lev, void *p, int *faceid, long *next, long *prev, int *ifndx, int *flags, char **peer, int *type, char **frag);
int get_num_fwds(void *p);
int get_fwd_dump(int lev, void *p, long *outfwd, long *next, long *face, int *faceid, int *suite, int *prefixlen, char **prefix);
int get_num_interface(void *p);
int get_interface_dump(int lev, void *p, int *ifndx, char **addr, long *dev, int *devtype, int *reflect);
int get_num_interests(void *p);
int get_interest_dump(int lev, void *p, long *interest, long *next, long *prev, int *last, int *min, int *max, int *retries, long *publisher, int *prefixlen, char **prefix);
/**
* @brief Writes PIT entries to @p out (an array of arrays).
*
* @param[in] lev The number of spaces to indent the log output (defunct)
* @param[in] p A pointer to the global @ref struct ccnl_relay_s
* @param[out] out A array of arrays where the PIT is written to
*
* @return The number of entries written for the PIT
*/
int get_pendint_dump(int lev, void *p, char **out);
int get_num_contents(void *p);
int get_content_dump(int lev, void *p, long *content, long *next, long *prev, int *last_use, int *served_cnt, int *prefixlen, char **prefix);
#endif // CCNL_DUMP_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-callbacks.c | <filename>src/ccnl-core/src/ccnl-callbacks.c
/*
* @f ccnl-callbacks.c
* @b Callback functions
*
* Copyright (C) 2018 <NAME>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2018-05-21 created (based on ccnl-producer.c)
*/
#include "ccnl-callbacks.h"
/**
* callback function for inbound on-data events
*/
static ccnl_cb_on_data _cb_rx_on_data = NULL;
/**
* callback function for outbound on-data events
*/
static ccnl_cb_on_data _cb_tx_on_data = NULL;
void
ccnl_set_cb_rx_on_data(ccnl_cb_on_data func)
{
_cb_rx_on_data = func;
}
void
ccnl_set_cb_tx_on_data(ccnl_cb_on_data func)
{
_cb_tx_on_data = func;
}
int
ccnl_callback_rx_on_data(struct ccnl_relay_s *relay,
struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt)
{
if (_cb_rx_on_data) {
return _cb_rx_on_data(relay, from, pkt);
}
return 0;
}
int
ccnl_callback_tx_on_data(struct ccnl_relay_s *relay,
struct ccnl_face_s *to,
struct ccnl_pkt_s *pkt)
{
if (_cb_tx_on_data) {
return _cb_tx_on_data(relay, to, pkt);
}
return 0;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-riot/include/ccnl-riot-logging.h | /*
* @file ccnl-riot-logging.h
*
* @copyright Copyright (C) 2011-18, University of Basel
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_RIOT_LOGGING
#define CCNL_RIOT_LOGGING
/**
* Define the log level of the CCN-Lite stack
*/
#ifndef LOG_LEVEL
#define LOG_LEVEL LOG_DEBUG
#endif
#include "log.h"
/**
* Closing an interface or socket from CCN-Lite
*/
#define ccnl_close_socket(s) close(s)
/**
* @name Log levels used by CCN-Lite debugging
*
* @{
*/
#define FATAL LOG_ERROR
#define ERROR LOG_ERROR
#define WARNING LOG_WARNING
#define INFO LOG_INFO
#define DEBUG LOG_DEBUG
#define TRACE LOG_DEBUG
#define VERBOSE LOG_ALL
/**
* @}
*/
/**
* @name CCN-Lite's debugging macros
*
* @{
*/
#define DEBUGMSG(LVL, ...) do { \
if ((LVL)>debug_level) break; \
LOG(LVL, __VA_ARGS__); \
} while (0)
#define DEBUGMSG_CORE(...) DEBUGMSG(__VA_ARGS__)
#define DEBUGMSG_CFWD(...) DEBUGMSG(__VA_ARGS__)
#define DEBUGMSG_CUTL(...) DEBUGMSG(__VA_ARGS__)
#define DEBUGMSG_PIOT(...) DEBUGMSG(__VA_ARGS__)
#define DEBUGSTMT(LVL, ...) do { \
if ((LVL)>debug_level) break; \
__VA_ARGS__; \
} while (0)
#define TRACEIN(...) do {} while(0)
#define TRACEOUT(...) do {} while(0)
/**
* @}
*/
#endif
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-sockunion.h | /*
* @f ccnl-sockunion.h
* @b CCN lite (CCNL), core header file (internal data structures)
*
* Copyright (C) 2011-17, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_SOCKET_UNION_H
#define CCNL_SOCKET_UNION_H
//#define _DEFAULT_SOURCE
#include "ccnl-defs.h"
#ifndef CCNL_LINUXKERNEL
#include <netinet/in.h>
#include <net/ethernet.h>
#ifndef CCNL_RIOT
#include <sys/un.h>
#else
#include "net/packet.h"
#include <net/packet.h>
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
# include <sys/types.h>
# include <sys/socket.h>
# ifdef USE_LINKLAYER
#pragma message "ethernet support in FreeBSD and MacOS is work in progress \
and not fully implemented!"
# endif
#elif defined(__linux__)
# include <endian.h>
#ifndef CCNL_RIOT
# include <linux/if_ether.h> // ETH_ALEN
# include <linux/if_packet.h> // sockaddr_ll
#endif //CCNL_RIOT
#endif
#endif //!CCNL_LINUXKERNEL
#ifdef USE_WPAN
/* TODO: remove when af_ieee802154.h is in linux mainline */
#define IEEE802154_ADDR_LEN 8
typedef enum {
IEEE802154_ADDR_NONE = 0x0,
IEEE802154_ADDR_SHORT = 0x2,
IEEE802154_ADDR_LONG = 0x3,
} wpan_addr_type_t;
struct ieee802154_addr_sa {
int addr_type;
uint16_t pan_id;
union {
uint8_t hwaddr[IEEE802154_ADDR_LEN];
uint16_t short_addr;
} addr;
};
struct sockaddr_ieee802154 {
sa_family_t family;
struct ieee802154_addr_sa addr;
};
#endif
typedef union {
struct sockaddr sa;
#ifdef USE_IPV4
struct sockaddr_in ip4;
#endif
#ifdef USE_IPV6
struct sockaddr_in6 ip6;
#endif
#ifdef USE_LINKLAYER
#if (!defined(__FreeBSD__) && !defined(__APPLE__)) || \
(defined(CCNL_RIOT) && defined(__FreeBSD__)) || \
(defined(CCNL_RIOT) && defined(__APPLE__))
struct sockaddr_ll linklayer;
#endif
#endif
#ifdef USE_WPAN
struct sockaddr_ieee802154 wpan;
#endif
#ifdef USE_UNIXSOCKET
struct sockaddr_un ux;
#endif
} sockunion;
int
ccnl_is_local_addr(sockunion *su);
/**
* @brief Returns a string representation of a given socket
*
* This function checks if the given socket type is supported by CCN-lite and
* returns its string representation. In no circumstance should one pass this
* function without a check to the return type to a function expecting a
* string, e.g. "printf("from: %s\n", ccnl_addr2ascii(some_type));"!
*
* @param[in] su The socket type to represent as string
*
* @return NULL if \ref su was NULL
* @return NULL if the given socket type is not supported
* @return A string representation of \ref su
*/
char* ccnl_addr2ascii(sockunion *su);
int
ccnl_addr_cmp(sockunion *s1, sockunion *s2);
char*
ll2ascii(unsigned char *addr, size_t len);
char
_half_byte_to_char(uint8_t half_byte);
//char
//*inet_ntoa(struct in_addr in);
#endif
|
azadeh-afzar/CCN-IRIBU | src/ccnl-unix/include/ccnl-unix.h | <reponame>azadeh-afzar/CCN-IRIBU<filename>src/ccnl-unix/include/ccnl-unix.h
/*
* @f ccnl-unix.h
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_UNIX_H
#define CCNL_UNIX_H
#include <dirent.h>
#include <fnmatch.h>
#include <regex.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <inttypes.h>
#include <netinet/in.h>
#include "ccnl-sockunion.h"
#include "ccnl-relay.h"
#include "ccnl-if.h"
#include "ccnl-buf.h"
#ifdef USE_LINKLAYER
#if !(defined(__FreeBSD__) || defined(__APPLE__))
int
ccnl_open_ethdev(char *devname, struct sockaddr_ll *sll, uint16_t ethtype);
#endif
#endif
#ifdef USE_WPAN
int
ccnl_open_wpandev(char *devname, struct sockaddr_ieee802154 *swpan);
#endif
#ifdef USE_UNIXSOCKET
int
ccnl_open_unixpath(char *path, struct sockaddr_un *ux);
#endif
#ifdef USE_IPV4
int
ccnl_open_udpdev(uint16_t port, struct sockaddr_in *si);
#endif
#ifdef USE_IPV6
int
ccnl_open_udp6dev(uint16_t port, struct sockaddr_in6 *sin);
#endif
#ifdef USE_LINKLAYER
ssize_t
ccnl_eth_sendto(int sock, uint8_t *dst, uint8_t *src,
uint8_t *data, size_t datalen);
#endif
#ifdef USE_WPAN
int
ccnl_wpan_sendto(int sock, unsigned char *data, int datalen,
struct sockaddr_ieee802154 *dst);
#endif
#ifdef USE_SCHEDULER
struct ccnl_sched_s*
ccnl_relay_defaultFaceScheduler(struct ccnl_relay_s *ccnl,
void(*cb)(void*,void*));
struct ccnl_sched_s*
ccnl_relay_defaultInterfaceScheduler(struct ccnl_relay_s *ccnl,
void(*cb)(void*,void*));
#endif // USE_SCHEDULER
void
ccnl_ageing(void *relay, void *aux);
#if defined(USE_IPV4) || defined(USE_IPV6)
void
ccnl_relay_udp(struct ccnl_relay_s *relay, int32_t port, int af, int suite);
#endif
void
ccnl_ll_TX(struct ccnl_relay_s *ccnl, struct ccnl_if_s *ifc,
sockunion *dest, struct ccnl_buf_s *buf);
void
ccnl_relay_config(struct ccnl_relay_s *relay, char *ethdev, char *wpandev,
int32_t udpport1, int32_t udpport2,
int32_t udp6port1, int32_t udp6port2, int32_t httpport,
char *uxpath, int suite, int max_cache_entries,
char *crypto_face_path);
int
ccnl_io_loop(struct ccnl_relay_s *ccnl);
void
ccnl_populate_cache(struct ccnl_relay_s *ccnl, char *path);
#endif // CCNL_UNIX_H
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-crypto.c | <filename>src/ccnl-core/src/ccnl-crypto.c<gh_stars>10-100
/*
* @f ccnl-ext-crypto.c
* @b CCN lite extension, crypto logic (sign, verify, encrypt, decrypt)
*
* Copyright (C) 2013, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2012-10-03 created
*/
#include <stdlib.h>
#include <string.h>
#include <ccnl-sockunion.h>
#include <ccnl-logging.h>
#include <ccnl-os-time.h>
#include <ccnl-relay.h>
#include <ccnl-malloc.h>
#include <ccnl-pkt-ccnb.h>
#include "ccnl-crypto.h"
#ifdef USE_SIGNATURES
char buf[64000];
int plen;
int received;
static int
ccnl_crypto_strtoint(char *str){
#ifdef CCNL_LINUXKERNEL
return strtol(str,NULL,0);
#else
return strtol(str,NULL,0);
#endif
}
int
ccnl_mgmt_handle(struct ccnl_relay_s *ccnl, struct ccnl_buf_s *orig,
struct ccnl_prefix_s *prefix, struct ccnl_face_s *from,
char *cmd, int verified);
static int
ccnl_crypto_get_tag_content(unsigned char **buf, int *len, int numletters, char *content, int contentlen){
int num = 0;
int end = numletters < contentlen ? numletters : contentlen;
memset(content,0,contentlen);
for(num = 0; num < end; ++num)
{
content[num] = **buf;
++(*buf); --(*len);
}
++(*buf); --(*len);
++num;
return num;
}
#define extractStr2(VAR,DTAG) \
if (typ == CCN_TT_DTAG && num == DTAG) { \
char *s; unsigned char *valptr; int vallen; \
if (ccnl_ccnb_consume(typ, num, buf, buflen, &valptr, &vallen) < 0)\
goto Bail; \
s = ccnl_malloc(vallen+1); if (!s) goto Bail; \
memcpy(s, valptr, vallen); s[vallen] = '\0'; \
ccnl_free(VAR); \
VAR = (unsigned char*) s; \
continue; \
} do {} while(0)
static int
ccnl_crypto_create_ccnl_crypto_face(struct ccnl_relay_s *relay, char *ux_path)
{
sockunion su;
DEBUGMSG(DEBUG, " adding UNIX face unixsrc=%s\n", ux_path);
su.sa.sa_family = AF_UNIX;
strncpy(su.ux.sun_path, (char*) ux_path, sizeof(su.ux.sun_path));
relay->crypto_face = ccnl_get_face_or_create(relay, -1, &su.sa, sizeof(struct sockaddr_un));
if(!relay->crypto_face) return 0;
relay->crypto_face->flags = CCNL_FACE_FLAGS_STATIC;
return 1;
}
static int
ccnl_crypto_create_ccnl_sign_verify_msg(char *typ, int txid, char *content, int content_len,
char *sig, int sig_len, char *msg, char *callback)
{
int len = 0, len2 = 0, len3 = 0;
char *component_buf, *contentobj_buf;
char h[100];
component_buf = ccnl_malloc(sizeof(char)*(content_len)+2000);
contentobj_buf = ccnl_malloc(sizeof(char)*(content_len)+1000);
len = ccnl_ccnb_mkHeader(msg, CCN_DTAG_INTEREST, CCN_TT_DTAG); // interest
len += ccnl_ccnb_mkHeader(msg+len, CCN_DTAG_NAME, CCN_TT_DTAG); // name
len += ccnl_ccnb_mkStrBlob(msg+len, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "ccnx");
len += ccnl_ccnb_mkStrBlob(msg+len, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "crypto");
// prepare FACEINSTANCE
len3 += ccnl_ccnb_mkStrBlob(component_buf+len3, CCNL_DTAG_CALLBACK, CCN_TT_DTAG, callback);
len3 += ccnl_ccnb_mkStrBlob(component_buf+len3, CCN_DTAG_TYPE, CCN_TT_DTAG, typ);
memset(h, 0, sizeof(h));
snprintf(h, sizeof(h), "%d", txid);
len3 += ccnl_ccnb_mkStrBlob(component_buf+len3, CCN_DTAG_SEQNO, CCN_TT_DTAG, h);
if(!strcmp(typ, "verify"))
len3 += ccnl_ccnb_mkBlob(component_buf+len3, CCN_DTAG_SIGNATURE, CCN_TT_DTAG, // content
(char*) sig, sig_len);
len3 += ccnl_ccnb_mkBlob(component_buf+len3, CCN_DTAG_CONTENTDIGEST, CCN_TT_DTAG, // content
(char*) content, content_len);
// prepare CONTENTOBJ with CONTENT
len2 = ccnl_ccnb_mkHeader(contentobj_buf, CCN_DTAG_CONTENTOBJ, CCN_TT_DTAG); // contentobj
len2 += ccnl_ccnb_mkBlob(contentobj_buf+len2, CCN_DTAG_CONTENT, CCN_TT_DTAG, // content
(char*) component_buf, len3);
contentobj_buf[len2++] = 0; // end-of-contentobj
// add CONTENTOBJ as the final name component
len += ccnl_ccnb_mkBlob(msg+len, CCN_DTAG_COMPONENT, CCN_TT_DTAG, // comp
(char*) contentobj_buf, len2);
msg[len++] = 0; // end-of-name
msg[len++] = 0; // end-o
ccnl_free(component_buf);
ccnl_free(contentobj_buf);
return len;
}
static int
ccnl_crypto_extract_type_callback(unsigned char **buf, int *buflen, char *type,
int max_type_length, char* callback, int max_callback_length)
{
int typ, num;
char comp1[10];
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_CONTENTOBJ) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_NAME) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_COMPONENT) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, comp1, sizeof(comp1));
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_COMPONENT) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, comp1, sizeof(comp1));
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_CONTENT) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCNL_DTAG_CALLBACK) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, callback, max_callback_length);
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_TYPE) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, type, max_type_length);
return 1;
Bail:
return 0;
}
static int
ccnl_crypto_extract_msg(unsigned char **buf, int *buflen, unsigned char **msg){
int len = 0;
int num, typ;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_CONTENTDIGEST) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
*msg = *buf;
len = num;
return len;
Bail:
DEBUGMSG(DEBUG, "Failed to extract msg\n");
return 0;
}
static int
ccnl_crypto_extract_sign_reply(unsigned char **buf, int *buflen, char *sig, int *sig_len, int *seqnum)
{
int ret = 0;
int num, typ;
char seqnumber_s[100];
int seqnubmer;
int siglen = 0;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_SEQNO) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, seqnumber_s, sizeof(seqnumber_s));
seqnubmer = ccnl_crypto_strtoint(seqnumber_s);
*seqnum = seqnubmer;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_SIGNATURE) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
siglen = num;
ccnl_crypto_get_tag_content(buf, buflen, siglen, sig, CCNL_MAX_PACKET_SIZE);
//ccnl_crypto_get_signature(buf, buflen, sig, siglen);
*sig_len = siglen;
ret = 1;
Bail:
return ret;
}
static int
ccnl_crypto_extract_verify_reply(unsigned char **buf, int *buflen, int *seqnum)
{
int verified = 0;
int num, typ;
char seqnumber_s[100], verified_s[100];
int seqnubmer, h;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCN_DTAG_SEQNO) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, seqnumber_s, sizeof(seqnumber_s));
seqnubmer = ccnl_crypto_strtoint(seqnumber_s);
*seqnum = seqnubmer;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_DTAG || num != CCNL_DTAG_VERIFIED) goto Bail;
if(ccnl_ccnb_dehead(buf, buflen, &num, &typ)) goto Bail;
if (typ != CCN_TT_BLOB) goto Bail;
ccnl_crypto_get_tag_content(buf, buflen, num, verified_s, sizeof(verified_s));
h = ccnl_crypto_strtoint(verified_s);
if(h == 1) {
verified = 1;
DEBUGMSG(DEBUG,"VERIFIED\n");
}
Bail:
return verified;
}
static int
ccnl_crypto_add_signature(unsigned char *out, char *sig, int siglen)
{
int len;
len = ccnl_ccnb_mkHeader(out, CCN_DTAG_SIGNATURE, CCN_TT_DTAG);
len += ccnl_ccnb_mkStrBlob(out + len, CCN_DTAG_NAME, CCN_TT_DTAG, "SHA256");
len += ccnl_ccnb_mkStrBlob(out + len, CCN_DTAG_WITNESS, CCN_TT_DTAG, "");
//add signaturebits bits...
len += ccnl_ccnb_mkHeader(out + len, CCN_DTAG_SIGNATUREBITS, CCN_TT_DTAG);
len += ccnl_ccnb_addBlob(out + len, sig, siglen);
out[len++] = 0; // end signaturebits
out[len++] = 0; // end signature
return len;
}
/**
*
* @param ccnl
* @param content
* @param content_len
* @param sig
* @param sig_len
* @param callback function which should be called when crypto system returns
* for a new callback function you have to extend ccnl_crypto()!!!!
* @return
*/
int
ccnl_crypto_sign(struct ccnl_relay_s *ccnl, char *content, int content_len,
char *callback, int seqnum)
{
//char *buf = 0;
char *msg = 0; int len;
struct ccnl_buf_s *retbuf;
int ret = 0; //, plen = 0;
plen = 0;
memset(buf,0,sizeof(buf));
//create ccn_msg
if(!ccnl->crypto_face) return 0;
msg = (char *) ccnl_malloc(sizeof(char)*(content_len)+3000);
len = ccnl_crypto_create_ccnl_sign_verify_msg("sign", seqnum, content, content_len,
NULL, 0, msg, callback);
if(len > CCNL_MAX_PACKET_SIZE){
DEBUGMSG(DEBUG,"Ignored, packet size too large");
return 0;
}
//send ccn_msg to crytoserver
retbuf = ccnl_buf_new((char *)msg, len);
ccnl_face_enqueue(ccnl, ccnl->crypto_face, retbuf);
if(msg) ccnl_free(msg);
return ret;
}
/**
*
* @param ccnl
* @param content
* @param content_len
* @param sig
* @param sig_len
* @param callback function which should be called when crypto system returns
* for a new callback function you have to extend ccnl_crypto()!!!!
* @return
*/
int
ccnl_crypto_verify(struct ccnl_relay_s *ccnl, char *content, int content_len,
char *sig, int sig_len, char* callback, int sequnum)
{
char *msg = 0;
int len = 0, ret = 0;
struct ccnl_buf_s *retbuf;
//int plen;
//unsigned char *buf;
plen = 0;
memset(buf,0,sizeof(buf));
if(!ccnl->crypto_face) return ret;
msg = (char *)ccnl_malloc(sizeof(char)*(content_len+sig_len)+3000);
len = ccnl_crypto_create_ccnl_sign_verify_msg("verify", sequnum, content,
content_len, sig, sig_len, msg, callback);
if(len > CCNL_MAX_PACKET_SIZE){
DEBUGMSG(DEBUG,"Ignored, packet size too large");
return 0;
}
//send ccn_msg to crytoserver
retbuf = ccnl_buf_new((char *)msg, len);
ccnl_face_enqueue(ccnl, ccnl->crypto_face, retbuf);
if(msg) ccnl_free(msg);
return ret;
}
int
ccnl_mgmt_crypto(struct ccnl_relay_s *ccnl, char *type, unsigned char *buf, int buflen)
{
struct ccnl_face_s *from;
DEBUGMSG(DEBUG,"ccnl_crypto type: %s\n", type);
if(!strcmp(type, "verify")){
int seqnum = 0;
int verified = ccnl_crypto_extract_verify_reply(&buf, &buflen, &seqnum);
unsigned char *msg, *msg2;
char cmd[500];
int len = ccnl_crypto_extract_msg(&buf, &buflen, &msg), len2 = 0;
struct ccnl_face_s *from;
//DEBUGMSG(DEBUG,"VERIFIED: %d, MSG_LEN: %d\n", verified, len);
int scope=3, aok=3, minsfx=0, maxsfx=CCNL_MAX_NAME_COMP, contlen;
struct ccnl_buf_s *buf1 = 0, *nonce=0, *ppkd=0;
struct ccnl_prefix_s *p = 0;
struct ccnl_buf_s *msg2_buf;
unsigned char *content = 0;
msg2 = (char *) ccnl_malloc(sizeof(char) * len + 200);
len2 = ccnl_ccnb_mkHeader(msg2,CCN_DTAG_NAME, CCN_TT_DTAG);
memcpy(msg2+len2, msg, len);
len2 +=len;
msg2[len2++] = 0;
from = ccnl->faces;
while(from){
if(from->faceid == seqnum)
break;
from = from->next;
}
buf1 = ccnl_ccnb_extract(&msg2, &len2, &scope, &aok, &minsfx,
&maxsfx, &p, &nonce, &ppkd, &content, &contlen);
if (p->complen[2] < sizeof(cmd)) {
memcpy(cmd, p->comp[2], p->complen[2]);
cmd[p->complen[2]] = '\0';
} else
strcpy(cmd, "cmd-is-too-long-to-display");
msg2_buf = ccnl_buf_new((char *)msg2, len2);
ccnl_mgmt_handle(ccnl, msg2_buf, p, from, cmd, verified);
ccnl_free(msg2_buf);
}else if(!strcmp(type, "sign")){
char *sig = (char *) ccnl_malloc(sizeof(char)* CCNL_MAX_PACKET_SIZE);
unsigned char *out;
unsigned char *msg;
int siglen = 0, seqnum = 0, len, len1;
struct ccnl_buf_s *retbuf;
ccnl_crypto_extract_sign_reply(&buf, &buflen, sig, &siglen, &seqnum);
len = ccnl_crypto_extract_msg(&buf, &buflen, &msg);
out = (char *) ccnl_malloc(sizeof(unsigned char)*len + sizeof(unsigned char)*siglen + 4096);
len1 = ccnl_ccnb_mkHeader(out, CCN_DTAG_CONTENTOBJ, CCN_TT_DTAG); // content
if(siglen > 0) len1 += ccnl_crypto_add_signature(out+len1, sig, siglen);
memcpy(out+len1, msg, len);
len1 +=len;
out[len1++] = 0; // end-of-interest
from = ccnl->faces;
while(from){
if(from->faceid == seqnum)
break;
from = from->next;
}
retbuf = ccnl_buf_new((char *)out, len1);
if(seqnum >= 0){
ccnl_face_enqueue(ccnl, from, retbuf);
}else{
struct ccnl_prefix_s *prefix_a = 0;
struct ccnl_content_s *c = 0;
struct ccnl_buf_s *nonce=0, *ppkd=0, *pkt = 0;
unsigned char *content = 0;
char *ht = (char *) ccnl_malloc(sizeof(char)*20);
int contlen;
pkt = ccnl_ccnb_extract(&out, &len1, 0, 0, 0, 0,
&prefix_a, &nonce, &ppkd, &content, &contlen);
if (!pkt) {
DEBUGMSG(WARNING, " parsing error\n"); goto Done;
}
if (prefix_a) {
//DEBUGMSG(DEBUG, "%s", prefix_a->comp);
//ccnl_free(prefix_a);
}
//prefix_a = (struct ccnl_prefix_s *)ccnl_malloc(sizeof(struct ccnl_prefix_s));
prefix_a->compcnt = 2;
prefix_a->comp = (unsigned char **) ccnl_malloc(sizeof(unsigned char*)*2);
prefix_a->comp[0] = "mgmt";
snprintf(ht, 20, "seqnum-%d", -seqnum);
prefix_a->comp[1] = ht;
prefix_a->complen = (int *) ccnl_malloc(sizeof(int)*2);
prefix_a->complen[0] = strlen("mgmt");
prefix_a->complen[1] = strlen(ht);
c = ccnl_content_new(ccnl, CCNL_SUITE_CCNB, &pkt, &prefix_a, &ppkd,
content, contlen);
if (!c) goto Done;
ccnl_content_serve_pending(ccnl, c);
ccnl_content_add2cache(ccnl, c);
}
Done:
ccnl_free(out);
}
return 0;
}
int
ccnl_crypto(struct ccnl_relay_s *ccnl, struct ccnl_buf_s *orig,
struct ccnl_prefix_s *prefix, struct ccnl_face_s *from)
{
unsigned char *buf = orig->data;
int buflen = orig->datalen;
char type[100];
char callback[100];
if(!ccnl_crypto_extract_type_callback(&buf, &buflen, type, sizeof(type), callback,
sizeof(callback))) goto Bail;
DEBUGMSG(DEBUG,"Callback: %s Type: %s\n", callback, type);
if(!strcmp(callback, "ccnl_mgmt_crypto"))
ccnl_mgmt_crypto(ccnl, type, buf, buflen);
/**
* Add here further callback functions
* else if(!strcmp(callback, "")){
*
*}
*/
Bail:
return -1;
}
#endif /*USE_SIGNATURES*/
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/src/ccnl-crypto.c | <reponame>azadeh-afzar/CCN-IRIBU
/*
* @f util/ccnl-crypto.c
* @b crypto functions for the CCN-lite utilities
*
* Copyright (C) 2013, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2013-07-22 created
*/
// ----------------------------------------------------------------------
#include "ccnl-crypto.h"
#ifdef USE_SIGNATURES
// ----------------------------------------------------------------------
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/objects.h>
#include <openssl/err.h>
// ----------------------------------------------------------------------
#endif
/*
int
mkHeader(unsigned char *buf, unsigned int num, unsigned int tt)
{
unsigned char tmp[100];
int len = 0, i;
*tmp = 0x80 | ((num & 0x0f) << 3) | tt;
len = 1;
num = num >> 4;
while (num > 0) {
tmp[len++] = num & 0x7f;
num = num >> 7;
}
for (i = len-1; i >= 0; i--)
*buf++ = tmp[i];
return len;
}
int
addBlob(unsigned char *out, char *cp, int cnt)
{
int len;
len = mkHeader(out, cnt, CCN_TT_BLOB);
memcpy(out+len, cp, cnt);
len += cnt;
return len;
}
int
mkBlob(unsigned char *out, unsigned int num, unsigned int tt,
char *cp, int cnt)
{
int len;
len = mkHeader(out, num, tt);
len += addBlob(out+len, cp, cnt);
out[len++] = 0;
return len;
}
int
mkStrBlob(unsigned char *out, unsigned int num, unsigned int tt,
char *str)
{
return mkBlob(out, num, tt, str, strlen(str));
}
*/
#ifdef USE_SIGNATURES
int sha(void* input, unsigned long length, unsigned char* md)
{
SHA256_CTX context;
if(!SHA256_Init(&context))
return 0;
if(!SHA256_Update(&context, (unsigned char*)input, length))
return 0;
if(!SHA256_Final(md, &context))
return 0;
return 1;
}
int
sign(char* private_key_path, unsigned char *msg, int msg_len,
unsigned char *sig, unsigned int *sig_len)
{
//Load private key
FILE *fp = fopen(private_key_path, "r");
if(!fp) {
DEBUGMSG(ERROR, "Could not find private key\n");
return 0;
}
RSA *rsa = (RSA *) PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL);
fclose(fp);
if(!rsa) return 0;
unsigned char md[SHA256_DIGEST_LENGTH];
sha(msg, msg_len, md);
//Compute signatur
int err = RSA_sign(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int*)sig_len, rsa);
if(!err){
printf("Error: %ul\n", (unsigned int)ERR_get_error());
}
RSA_free(rsa);
return err;
}
int
verify(char* public_key_path, unsigned char *msg, int msg_len,
unsigned char *sig, unsigned int sig_len)
{
//Load public key
FILE *fp = fopen(public_key_path, "r");
if(!fp) {
printf("Could not find public key\n");
return 0;
}
RSA *rsa = (RSA *) PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
if(!rsa) return 0;
fclose(fp);
//Compute Hash
unsigned char md[SHA256_DIGEST_LENGTH];
sha(msg, msg_len, md);
//Verify signature
int verified = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int)sig_len, rsa);
if(!verified){
printf("Error: %ul\n", (unsigned int)ERR_get_error());
}
RSA_free(rsa);
return verified;
}
int
add_signature(unsigned char *out, char *private_key_path,
unsigned char *file, unsigned int fsize)
{
int len;
unsigned char sig[2048];
unsigned int sig_len;
len = ccnl_ccnb_mkHeader(out, CCN_DTAG_SIGNATURE, CCN_TT_DTAG);
len += ccnl_ccnb_mkStrBlob(out + len, CCN_DTAG_NAME, CCN_TT_DTAG, "SHA256");
len += ccnl_ccnb_mkStrBlob(out + len, CCN_DTAG_WITNESS, CCN_TT_DTAG, "");
if(!sign(private_key_path, (unsigned char*)file, fsize, (unsigned char*)sig, &sig_len)) return 0;
//printf("SIGLEN: %d\n",sig_len);
sig[sig_len]=0;
//add signaturebits bits...
len += ccnl_ccnb_mkHeader(out + len, CCN_DTAG_SIGNATUREBITS, CCN_TT_DTAG);
len += ccnl_ccnb_addBlob(out + len, (char*)sig, sig_len);
out[len++] = 0; // end signaturebits
out[len++] = 0; // end signature
/*char *publickey = "/home/blacksheeep/.ssh/publickey.pem";
int verified = verify(publickey, file, fsize, sig, sig_len);
printf("Verified: %d\n", verified);*/
return len;
}
#endif /*USE_SIGNATURES*/
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-producer.c | /*
* @f ccnl-producer.c
* @b Producer functions
*
* Copyright (C) 2011-14, <NAME>, University of Basel
* Copyright (C) 2015, 2016, 2018, <NAME>, INRIA
* Copyright (C) 2018, <NAME>, MSA Safety
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2018-01-24 created (based on ccn-lite-riot.c)
*/
#include "ccnl-producer.h"
/**
* local producer function defined by the application
*/
static ccnl_producer_func _prod_func = NULL;
void
ccnl_set_local_producer(ccnl_producer_func func)
{
_prod_func = func;
}
int
local_producer(struct ccnl_relay_s *relay, struct ccnl_face_s *from,
struct ccnl_pkt_s *pkt)
{
if (_prod_func) {
return _prod_func(relay, from, pkt);
}
return 0;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/src/ccnl-prefix.c | /*
* @f ccnl-prefix.c
* @b CCN lite, core CCNx protocol logic
*
* Copyright (C) 2011-18 University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2017-06-16 created
*/
#ifndef CCNL_LINUXKERNEL
#include "ccnl-prefix.h"
#include "ccnl-pkt-ndntlv.h"
#include "ccnl-pkt-ccntlv.h"
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#if !defined(CCNL_RIOT) && !defined(CCNL_ANDROID)
#include <openssl/sha.h>
#endif // !defined(CCNL_RIOT) && !defined(CCNL_ANDROID)
#else //CCNL_LINUXKERNEL
#include "../include/ccnl-prefix.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ndntlv.h"
#include "../../ccnl-pkt/include/ccnl-pkt-ccntlv.h"
#endif //CCNL_LINUXKERNEL
struct ccnl_prefix_s*
ccnl_prefix_new(char suite, uint32_t cnt)
{
struct ccnl_prefix_s *p;
p = (struct ccnl_prefix_s *) ccnl_calloc(1, sizeof(struct ccnl_prefix_s));
if (!p){
return NULL;
}
p->comp = (uint8_t **) ccnl_malloc(cnt * sizeof(uint8_t*));
p->complen = (size_t *) ccnl_malloc(cnt * sizeof(size_t));
if (!p->comp || !p->complen) {
ccnl_prefix_free(p);
return NULL;
}
p->compcnt = cnt;
p->suite = suite;
p->chunknum = NULL;
return p;
}
void
ccnl_prefix_free(struct ccnl_prefix_s *p)
{
ccnl_free(p->bytes);
ccnl_free(p->comp);
ccnl_free(p->complen);
ccnl_free(p->chunknum);
ccnl_free(p);
}
struct ccnl_prefix_s*
ccnl_prefix_dup(struct ccnl_prefix_s *prefix)
{
uint32_t i = 0;
size_t len;
struct ccnl_prefix_s *p;
p = ccnl_prefix_new(prefix->suite, prefix->compcnt);
if (!p){
return NULL;
}
p->compcnt = prefix->compcnt;
p->chunknum = prefix->chunknum;
for (i = 0, len = 0; i < prefix->compcnt; i++) {
len += prefix->complen[i];
}
p->bytes = (unsigned char*) ccnl_malloc(len);
if (!p->bytes) {
ccnl_prefix_free(p);
return NULL;
}
for (i = 0, len = 0; i < prefix->compcnt; i++) {
p->complen[i] = prefix->complen[i];
p->comp[i] = p->bytes + len;
memcpy(p->bytes + len, prefix->comp[i], p->complen[i]);
len += p->complen[i];
}
if (prefix->chunknum) {
p->chunknum = (uint32_t *) ccnl_malloc(sizeof(uint32_t));
*p->chunknum = *prefix->chunknum;
}
return p;
}
int8_t
ccnl_prefix_appendCmp(struct ccnl_prefix_s *prefix, uint8_t *cmp,
size_t cmplen)
{
uint32_t lastcmp = prefix->compcnt, i;
size_t *oldcomplen = prefix->complen;
uint8_t **oldcomp = prefix->comp;
uint8_t *oldbytes = prefix->bytes;
size_t prefixlen = 0;
if (prefix->compcnt >= CCNL_MAX_NAME_COMP) {
return -1;
}
for (i = 0; i < lastcmp; i++) {
prefixlen += prefix->complen[i];
}
prefix->compcnt++;
prefix->comp = (uint8_t **) ccnl_malloc(prefix->compcnt * sizeof(unsigned char*));
if (!prefix->comp) {
prefix->comp = oldcomp;
return -1;
}
prefix->complen = (size_t*) ccnl_malloc(prefix->compcnt * sizeof(size_t));
if (!prefix->complen) {
ccnl_free(prefix->comp);
prefix->comp = oldcomp;
prefix->complen = oldcomplen;
return -1;
}
prefix->bytes = (uint8_t *) ccnl_malloc(prefixlen + cmplen);
if (!prefix->bytes) {
ccnl_free(prefix->comp);
ccnl_free(prefix->complen);
prefix->comp = oldcomp;
prefix->complen = oldcomplen;
prefix->bytes = oldbytes;
return -1;
}
memcpy(prefix->bytes, oldbytes, prefixlen);
memcpy(prefix->bytes + prefixlen, cmp, cmplen);
prefixlen = 0;
for (i = 0; i < lastcmp; i++) {
prefix->comp[i] = &prefix->bytes[prefixlen];
prefix->complen[i] = oldcomplen[i];
prefixlen += oldcomplen[i];
}
prefix->comp[lastcmp] = &prefix->bytes[prefixlen];
prefix->complen[lastcmp] = cmplen;
ccnl_free(oldcomp);
ccnl_free(oldcomplen);
ccnl_free(oldbytes);
return 0;
}
// TODO: This function should probably be moved to another file to indicate that it should only be used by application level programs
// and not in the ccnl core. Chunknumbers for NDNTLV are only a convention and there no specification on the packet encoding level.
int
ccnl_prefix_addChunkNum(struct ccnl_prefix_s *prefix, uint32_t chunknum)
{
if (chunknum >= 0xff) {
DEBUGMSG_CUTL(WARNING, "addChunkNum is only implemented for "
"chunknum smaller than 0xff (%lu)\n", (long unsigned) chunknum);
return -1;
}
switch(prefix->suite) {
#ifdef USE_SUITE_NDNTLV
case CCNL_SUITE_NDNTLV: {
uint8_t cmp[2];
uint32_t *oldchunknum = prefix->chunknum;
cmp[0] = NDN_Marker_SegmentNumber;
// TODO: this only works for chunknums smaller than 255
cmp[1] = (uint8_t) chunknum;
if (ccnl_prefix_appendCmp(prefix, cmp, 2) < 0) {
return -1;
}
prefix->chunknum = (uint32_t *) ccnl_malloc(sizeof(uint32_t));
if (!prefix->chunknum) {
prefix->chunknum = oldchunknum;
return -1;
}
*prefix->chunknum = chunknum;
if (oldchunknum) {
ccnl_free(oldchunknum);
}
}
break;
#endif
#ifdef USE_SUITE_CCNTLV
case CCNL_SUITE_CCNTLV: {
uint8_t cmp[5];
uint32_t *oldchunknum = prefix->chunknum;
cmp[0] = 0;
// TODO: this only works for chunknums smaller than 255
cmp[1] = CCNX_TLV_N_Chunk;
cmp[2] = 0;
cmp[3] = 1;
cmp[4] = (uint8_t) chunknum;
if(ccnl_prefix_appendCmp(prefix, cmp, 5) < 0) {
return -1;
}
prefix->chunknum = (uint32_t *) ccnl_malloc(sizeof(uint32_t));
if (!prefix->chunknum) {
prefix->chunknum = oldchunknum;
return -1;
}
*prefix->chunknum = chunknum;
if (oldchunknum) {
ccnl_free(oldchunknum);
}
}
break;
#endif
default:
DEBUGMSG_CUTL(WARNING,
"add chunk number not implemented for suite %d\n",
prefix->suite);
return -1;
}
return 0;
}
// TODO: move to a util file?
uint8_t
hex2int(char c)
{
if (c >= '0' && c <= '9') {
return (uint8_t) (c - '0');
}
c = (char) tolower(c);
if (c >= 'a' && c <= 'f') {
return (uint8_t) (c - 'a' + 0x0a);
}
return 0;
}
size_t
unescape_component(char *comp)
{
char *in = comp, *out = comp;
size_t len;
for (len = 0; *in; len++) {
if (in[0] != '%' || !in[1] || !in[2]) {
*out++ = *in++;
continue;
}
*out++ = (char) (hex2int(in[1]) * 16 + hex2int(in[2]));
in += 3;
}
return len;
}
uint32_t
ccnl_URItoComponents(char **compVector, size_t *compLens, char *uri)
{
uint32_t i;
size_t len;
if (*uri == '/') {
uri++;
}
for (i = 0; *uri && i < (CCNL_MAX_NAME_COMP - 1); i++) {
compVector[i] = uri;
while (*uri && *uri != '/') {
uri++;
}
if (*uri) {
*uri = '\0';
uri++;
}
len = unescape_component(compVector[i]);
if (compLens) {
compLens[i] = len;
}
compVector[i][len] = '\0';
}
compVector[i] = NULL;
return i;
}
struct ccnl_prefix_s *
ccnl_URItoPrefix(char* uri, int suite, uint32_t *chunknum)
{
struct ccnl_prefix_s *p;
char *compvect[CCNL_MAX_NAME_COMP];
size_t complens[CCNL_MAX_NAME_COMP], len, tlen;
uint32_t cnt, i;
DEBUGMSG_CUTL(TRACE, "ccnl_URItoPrefix(suite=%s, uri=%s)\n",
ccnl_suite2str(suite), uri);
if (strlen(uri)) {
cnt = ccnl_URItoComponents(compvect, complens, uri);
} else {
cnt = 0U;
}
p = ccnl_prefix_new(suite, cnt);
if (!p) {
return NULL;
}
for (i = 0, len = 0; i < cnt; i++) {
len += complens[i];
}
#ifdef USE_SUITE_CCNTLV
if (suite == CCNL_SUITE_CCNTLV) {
len += cnt * 4; // add TL size
}
#endif
p->bytes = (unsigned char*) ccnl_malloc(len);
if (!p->bytes) {
ccnl_prefix_free(p);
return NULL;
}
for (i = 0, len = 0; i < cnt; i++) {
char *cp = compvect[i];
tlen = complens[i];
p->comp[i] = p->bytes + len;
tlen = ccnl_pkt_mkComponent(suite, p->comp[i], cp, tlen);
p->complen[i] = tlen;
len += tlen;
}
p->compcnt = cnt;
if (chunknum) {
p->chunknum = (uint32_t*) ccnl_malloc(sizeof(uint32_t));
if (!p->chunknum) {
ccnl_prefix_free(p);
return NULL;
}
*p->chunknum = *chunknum;
}
return p;
}
#ifdef NEEDS_PREFIX_MATCHING
const char*
ccnl_matchMode2str(int mode)
{
switch (mode) {
case CMP_EXACT:
return CONSTSTR("CMP_EXACT");
case CMP_MATCH:
return CONSTSTR("CMP_MATCH");
case CMP_LONGEST:
return CONSTSTR("CMP_LONGEST");
}
return CONSTSTR("?");
}
int32_t
ccnl_prefix_cmp(struct ccnl_prefix_s *pfx, unsigned char *md,
struct ccnl_prefix_s *nam, int mode)
/* returns -1 if no match at all (all modes) or exact match failed
returns 0 if full match (mode = CMP_EXACT) or no components match (mode = CMP_MATCH)
returns n>0 for matched components (mode = CMP_MATCH, CMP_LONGEST) */
{
int32_t rc = -1;
size_t clen;
uint32_t plen = pfx->compcnt + (md ? 1 : 0), i;
unsigned char *comp;
char s[CCNL_MAX_PREFIX_SIZE];
DEBUGMSG(VERBOSE, "prefix_cmp(mode=%s) ", ccnl_matchMode2str(mode));
DEBUGMSG(VERBOSE, "prefix=<%s>(%p) of? ",
ccnl_prefix_to_str(pfx, s, CCNL_MAX_PREFIX_SIZE), (void *) pfx);
DEBUGMSG(VERBOSE, "name=<%s>(%p) digest=%p\n",
ccnl_prefix_to_str(nam, s, CCNL_MAX_PREFIX_SIZE), (void *) nam, (void *) md);
if (mode == CMP_EXACT) {
if (plen != nam->compcnt) {
DEBUGMSG(VERBOSE, "comp count mismatch\n");
goto done;
}
if (pfx->chunknum || nam->chunknum) {
if (!pfx->chunknum || !nam->chunknum) {
DEBUGMSG(VERBOSE, "chunk mismatch\n");
goto done;
}
if (*pfx->chunknum != *nam->chunknum) {
DEBUGMSG(VERBOSE, "chunk number mismatch\n");
goto done;
}
}
}
for (i = 0; i < plen && i < nam->compcnt; ++i) {
comp = i < pfx->compcnt ? pfx->comp[i] : md;
clen = i < pfx->compcnt ? pfx->complen[i] : 32; // SHA256_DIGEST_LEN
if (clen != nam->complen[i] || memcmp(comp, nam->comp[i], nam->complen[i])) {
rc = mode == CMP_EXACT ? -1 : (int32_t) i;
DEBUGMSG(VERBOSE, "component mismatch: %lu\n", (long unsigned) i);
goto done;
}
}
// FIXME: we must also inspect chunknum here!
rc = (mode == CMP_EXACT) ? 0 : (int32_t) i;
done:
DEBUGMSG(TRACE, " cmp result: pfxlen=%lu cmplen=%lu namlen=%lu matchlen=%ld\n",
(long unsigned) pfx->compcnt, (long unsigned) plen, (long unsigned) nam->compcnt, (long) rc);
return rc;
}
int8_t
ccnl_i_prefixof_c(struct ccnl_prefix_s *prefix,
uint64_t minsuffix, uint64_t maxsuffix, struct ccnl_content_s *c)
{
struct ccnl_prefix_s *p = c->pkt->pfx;
char s[CCNL_MAX_PREFIX_SIZE];
DEBUGMSG(VERBOSE, "ccnl_i_prefixof_c prefix=<%s> ",
ccnl_prefix_to_str(prefix, s, CCNL_MAX_PREFIX_SIZE));
DEBUGMSG(VERBOSE, "content=<%s> min=%llu max=%llu\n",
ccnl_prefix_to_str(p, s, CCNL_MAX_PREFIX_SIZE), (unsigned long long) minsuffix, (unsigned long long)maxsuffix);
//
// CONFORM: we do prefix match, honour min. and maxsuffix,
// NON-CONFORM: "Note that to match a ContentObject must satisfy
// all of the specifications given in the Interest Message."
// >> CCNL does not honour the exclusion filtering
if ( (prefix->compcnt + minsuffix) > (p->compcnt + 1) ||
(prefix->compcnt + maxsuffix) < (p->compcnt + 1)) {
DEBUGMSG(TRACE, " mismatch in # of components\n");
return -2;
}
unsigned char *md = NULL;
if ((prefix->compcnt - p->compcnt) == 1) {
md = compute_ccnx_digest(c->pkt->buf);
/* computing the ccnx digest failed */
if (!md) {
DEBUGMSG(TRACE, "computing the digest failed\n");
return -3;
}
}
int32_t cmp = ccnl_prefix_cmp(p, md, prefix, CMP_EXACT);
return cmp;
}
#endif // NEEDS_PREFIX_MATCHING
#ifndef CCNL_LINUXKERNEL
char*
ccnl_prefix_to_path_detailed(struct ccnl_prefix_s *pr, int ccntlv_skip,
int escape_components, int call_slash)
{
(void) ccntlv_skip;
(void) call_slash;
/*static char *prefix_buf1;
static char *prefix_buf2;
static char *buf;*/
if (!pr) {
return NULL;
}
/*if (!buf) {
struct ccnl_buf_s *b;
b = ccnl_buf_new(NULL, PREFIX_BUFSIZE);
//ccnl_core_addToCleanup(b);
prefix_buf1 = (char*) b->data;
b = ccnl_buf_new(NULL, PREFIX_BUFSIZE);
//ccnl_core_addToCleanup(b);
prefix_buf2 = (char*) b->data;
buf = prefix_buf1;
} else if (buf == prefix_buf2)
buf = prefix_buf1;
else
buf = prefix_buf2;
*/
char *buf = (char*) ccnl_malloc(CCNL_MAX_PREFIX_SIZE+1);
if (!buf) {
DEBUGMSG_CUTL(ERROR, "ccnl_prefix_to_path_detailed: malloc failed, exiting\n");
return NULL;
}
memset(buf, 0, CCNL_MAX_PREFIX_SIZE+1);
return ccnl_prefix_to_str_detailed(pr, ccntlv_skip, escape_components, call_slash, buf, CCNL_MAX_PREFIX_SIZE);
}
char*
ccnl_prefix_to_str_detailed(struct ccnl_prefix_s *pr, int ccntlv_skip, int escape_components, int call_slash,
char *buf, size_t buflen) {
size_t len = 0, i, j;
int result;
(void)i;
(void)j;
(void)len;
(void) call_slash;
(void) ccntlv_skip;
uint8_t skip = 0;
#if defined(USE_SUITE_CCNTLV)
// In the future it is possibly helpful to see the type information
// in the logging output. However, this does not work with NFN because
// it uses this function to create the names in NFN expressions
// resulting in CCNTLV type information names within expressions.
if (ccntlv_skip && (0
#ifdef USE_SUITE_CCNTLV
|| pr->suite == CCNL_SUITE_CCNTLV
#endif
)) {
skip = 4;
}
#endif
for (i = 0; i < (size_t) pr->compcnt; i++) {
result = snprintf(buf + len, buflen - len, "/");
DEBUGMSG(TRACE, "result: %d, buf: %s, avail size: %zd, buflen: %zd\n", result, buf+len, buflen - len, buflen);
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
for (j = skip; j < pr->complen[i]; j++) {
char c = pr->comp[i][j];
char *fmt;
fmt = (c < 0x20 || c == 0x7f
|| (escape_components && c == '/' )) ?
#ifdef CCNL_ARDUINO
(char*)PSTR("%%%02x") : (char*)PSTR("%c");
result = snprintf_P(buf + len, buflen - len, fmt, c);
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
#else
(char *) "%%%02x" : (char *) "%c";
result = snprintf(buf + len, buflen - len, fmt, c);
DEBUGMSG(TRACE, "result: %d, buf: %s, avail size: %zd, buflen: %zd\n", result, buf+len, buflen - len, buflen);
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
#endif
if(len > CCNL_MAX_PREFIX_SIZE) {
DEBUGMSG(ERROR, "BUFSIZE SMALLER THAN OUTPUT LEN");
break;
}
}
}
return buf;
}
#else // CCNL_LINUXKERNEL
/**
* Transforms a prefix into a string, since returning static buffer cannot be called twice into the same statement
* @param[in] pr the prefix to be transformed
* @return a static buffer containing the prefix transformed into a string.
*/
char*
ccnl_prefix_to_path(struct ccnl_prefix_s *pr)
{
static char prefix_buf[4096];
int len= 0, i;
int result;
if (!pr)
return NULL;
return ccnl_prefix_to_str(pr, prefix_buf,4096);
/*
for (i = 0; i < pr->compcnt; i++) {
if(!strncmp("call", (char*)pr->comp[i], 4) && strncmp((char*)pr->comp[pr->compcnt-1], "NFN", 3)){
result = snprintf(prefix_buf + len, CCNL_MAX_PREFIX_SIZE - len, "%.*s", pr->complen[i], pr->comp[i]);
}
else{
result = snprintf(prefix_buf + len, CCNL_MAX_PREFIX_SIZE - len, "/%.*s", pr->complen[i], pr->comp[i]);
}
if (!(result > -1 && result < (CCNL_MAX_PREFIX_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
}
prefix_buf[len] = '\0';
return prefix_buf;*/
}
char*
ccnl_prefix_to_str(struct ccnl_prefix_s *pr, char *buf, size_t buflen) {
size_t len = 0, i, j;
int result;
int skip = 0;
(void)i;
(void)j;
(void)len;
#if defined(USE_SUITE_CCNTLV)
// In the future it is possibly helpful to see the type information
// in the logging output. However, this does not work with NFN because
// it uses this function to create the names in NFN expressions
// resulting in CCNTLV type information names within expressions.
if (1 && (0
#ifdef USE_SUITE_CCNTLV
|| pr->suite == CCNL_SUITE_CCNTLV
#endif
))
skip = 4;
#endif
for (i = 0; i < (size_t)pr->compcnt; i++) {
result = snprintf(buf + len, buflen - len, "/");
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
for (j = skip; j < (size_t)pr->complen[i]; j++) {
char c = pr->comp[i][j];
char *fmt;
fmt = (c < 0x20 || c == 0x7f
|| (0 && c == '/' )) ?
#ifdef CCNL_ARDUINO
(char*)PSTR("%%%02x") : (char*)PSTR("%c");
result = snprintf_P(buf + len, buflen - len, fmt, c);
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
#else
(char *) "%%%02x" : (char *) "%c";
result = snprintf(buf + len, buflen - len, fmt, c);
if (!(result > -1 && (size_t)result < (buflen - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
return NULL;
}
len += result;
#endif
if(len > CCNL_MAX_PREFIX_SIZE) {
DEBUGMSG(ERROR, "BUFSIZE SMALLER THAN OUTPUT LEN");
break;
}
}
}
return buf;
}
#endif // CCNL_LINUXKERNEL
char*
ccnl_prefix_debug_info(struct ccnl_prefix_s *p) {
size_t len = 0;
uint32_t i = 0;
int result;
char *buf = (char*) ccnl_malloc(CCNL_MAX_PACKET_SIZE);
if (buf == NULL) {
DEBUGMSG_CUTL(ERROR, "ccnl_prefix_debug_info: malloc failed, exiting\n");
return NULL;
}
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "<");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "suite:%i, ", p->suite);
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "compcnt:%lu ", (long unsigned) p->compcnt);
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "complen:(");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
for (i = 0; i < p->compcnt; i++) {
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "%zd", p->complen[i]);
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
if (i < p->compcnt - 1) {
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, ",");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
}
}
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "), ");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "comp:(");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
for (i = 0; i < p->compcnt; i++) {
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, "%.*s", (int) p->complen[i], p->comp[i]);
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
if (i < p->compcnt - 1) {
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, ",");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
}
}
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, ")");
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
len += result;
result = snprintf(buf + len, CCNL_MAX_PACKET_SIZE - len, ">%c", '\0');
if (!(result > -1 && (unsigned) result < (CCNL_MAX_PACKET_SIZE - len))) {
DEBUGMSG(ERROR, "Could not print prefix, since out of allocated memory");
ccnl_free(buf);
return NULL;
}
return buf;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/src/ccn-lite-cryptoserver.c | /*
* @f util/ccn-lite-cryptoserver.c
* @b cryptoserver for functions for the CCN-lite
*
* Copyright (C) 2013, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2013-07-22 created <<EMAIL>>
*/
#include "ccnl-common.h"
#include "ccnl-crypto.h"
// ----------------------------------------------------------------------
char *ux_path, *private_key, *ctrl_public_key;
/*int ux_sendto(int sock, char *topath, unsigned char *data, int len)
{
struct sockaddr_un name;
int rc;
// Construct name of socket to send to.
name.sun_family = AF_UNIX;
strcpy(name.sun_path, topath);
// Send message.
rc = sendto(sock, data, len, 0, (struct sockaddr*) &name,
sizeof(struct sockaddr_un));
if (rc < 0) {
fprintf(stderr, "\tnamed pipe \'%s\'\n", topath);
perror("\tsending datagram message");
}
return rc;
}*/
int
ccnl_crypto_ux_open(char *frompath)
{
int sock;
size_t bufsize;
struct sockaddr_un name;
/* Create socket for sending */
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
perror("\topening datagram socket");
exit(1);
}
unlink(frompath);
name.sun_family = AF_UNIX;
strncpy(name.sun_path, frompath, sizeof(name.sun_path));
if (bind(sock, (struct sockaddr *) &name,
sizeof(struct sockaddr_un))) {
perror("\tbinding name to datagram socket");
exit(1);
}
// printf("socket -->%s\n", NAME);
bufsize = 4 * CCNL_MAX_PACKET_SIZE;
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
return sock;
}
size_t
ccnl_crypto_get_tag_content(uint8_t **buf, size_t *len, char *content, size_t contentlen){
size_t num = 0;
memset(content, 0, contentlen);
while ((**buf) != 0 && num < contentlen)
{
content[num] = **buf;
++(*buf); --(*len);
++num;
}
++(*buf); --(*len);
return num;
}
int
handle_verify(uint8_t **buf, size_t *buflen, int sock, char *callback){
uint64_t num;
uint8_t typ;
int8_t verified = 0;
size_t contentlen = 0, siglen = 0;
uint8_t *txid_s = 0, *sig = 0, *content = 0;
size_t len = 0, len3 = 0, msglen = 0, complen = 0;
uint8_t *component_buf = 0, *msg = 0;
char h[1024];
while (!ccnl_ccnb_dehead(buf, buflen, &num, &typ)) {
if (num==0 && typ==0) {
break; // end
}
extractStr2(txid_s, CCN_DTAG_SEQNO);
if (!siglen){
siglen = *buflen;
}
extractStr2(sig, CCN_DTAG_SIGNATURE);
siglen = siglen - (*buflen + 5);
contentlen = *buflen;
extractStr2(content, CCN_DTAG_CONTENTDIGEST);
if (ccnl_ccnb_consume(typ, num, buf, buflen, 0, 0)) {
goto Bail;
}
}
contentlen = contentlen - (*buflen + 4);
printf(" \tHandeling TXID: %s; Type: Verify; Siglen: %zu; Contentlen: %zu;\n", txid_s, siglen, contentlen);
#ifdef USE_SIGNATURES
verified = verify(ctrl_public_key, content, contentlen, sig, siglen);
printf("\tResult: Verified: %d\n", verified);
#endif
//return message object
msglen = sizeof(char)*contentlen + 1000;
msg = ccnl_malloc(msglen);
if (!msg) {
goto Bail;
}
complen = sizeof(char)*contentlen + 666;
component_buf = ccnl_malloc(complen);
if (!component_buf) {
goto Bail;
}
if (ccnl_ccnb_mkHeader(msg, msg + msglen, CCN_DTAG_CONTENTOBJ, CCN_TT_DTAG, &len)) { // ContentObj
goto Bail;
}
if (ccnl_ccnb_mkHeader(msg+len, msg + msglen, CCN_DTAG_NAME, CCN_TT_DTAG, &len)) { // name
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(msg+len, msg + msglen, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "ccnx", &len)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(msg+len, msg + msglen, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "crypto", &len)) {
goto Bail;
}
if (len + 1 >= 1000) {
goto Bail;
}
msg[len++] = 0; // end-of-name
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCNL_DTAG_CALLBACK, CCN_TT_DTAG, callback, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCN_DTAG_TYPE, CCN_TT_DTAG, "verify", &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCN_DTAG_SEQNO, CCN_TT_DTAG, (char*) txid_s, &len3)) {
goto Bail;
}
memset(h,0,sizeof(h));
snprintf(h, sizeof(h), "%d", verified);
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCNL_DTAG_VERIFIED, CCN_TT_DTAG, h, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkBlob(component_buf + len3, component_buf + complen, CCN_DTAG_CONTENTDIGEST, CCN_TT_DTAG, (char*) content, contentlen, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkBlob(msg+len, msg + msglen, CCN_DTAG_CONTENT, CCN_TT_DTAG, // content
(char*) component_buf, len3, &len)) {
goto Bail;
}
if (len + 1 >= msglen) {
goto Bail;
}
msg[len++] = 0; // end-of contentobj
memset(h,0,sizeof(h));
snprintf(h, sizeof(h), "%s-2", ux_path);
if (h[sizeof(h) - 1] != 0) {
goto Bail;
}
if (len > CCNL_MAX_PACKET_SIZE) {
return 0;
}
ux_sendto(sock, h, msg, len);
printf("\t complete, answered to: %s len: %zu\n", ux_path, len);
Bail:
if (component_buf) {
ccnl_free(component_buf);
}
if (msg) {
ccnl_free(msg);
}
return verified;
}
int
handle_sign(uint8_t **buf, size_t *buflen, int sock, char *callback){
uint64_t num;
uint8_t typ;
int ret = 0;
size_t contentlen = 0;
size_t siglen = 0, msglen = 0, complen = 0;
uint8_t *txid_s = 0, *sig = 0, *content = 0;
size_t len = 0, len3 = 0;
uint8_t *component_buf = 0, *msg = 0;
char h[1024];
while (ccnl_ccnb_dehead(buf, buflen, &num, &typ) == 0) {
if (num==0 && typ==0) {
break; // end
}
extractStr2(txid_s, CCN_DTAG_SEQNO);
contentlen = *buflen;
extractStr2(content, CCN_DTAG_CONTENTDIGEST);
if (ccnl_ccnb_consume(typ, num, buf, buflen, 0, 0) < 0) goto Bail;
}
contentlen = contentlen - (*buflen + 4);
printf(" \tHandeling TXID: %s; Type: Sign; Contentlen: %zu;\n", txid_s, contentlen);
sig = ccnl_malloc(sizeof(char)*4096);
if (!sig) {
goto Bail;
}
#ifdef USE_SIGNATURES
sign(private_key, content, contentlen, sig, &siglen);
#endif
if (siglen <= 0) {
ccnl_free(sig);
sig = (unsigned char*) "Error";
siglen = 6;
}
//return message object
msglen = sizeof(char)*siglen + sizeof(char)*contentlen + 1000;
msg = ccnl_malloc(msglen);
if (!msg) {
goto Bail;
}
complen = sizeof(char)*siglen + sizeof(char)*contentlen + 666;
component_buf = ccnl_malloc(complen);
if (!component_buf) {
goto Bail;
}
if (ccnl_ccnb_mkHeader(msg, msg+msglen, CCN_DTAG_CONTENTOBJ, CCN_TT_DTAG, &len)) { // ContentObj
goto Bail;
}
if (ccnl_ccnb_mkHeader(msg+len, msg+msglen, CCN_DTAG_NAME, CCN_TT_DTAG, &len)) { // name
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(msg+len, msg+msglen, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "ccnx", &len)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(msg+len, msg+msglen, CCN_DTAG_COMPONENT, CCN_TT_DTAG, "crypto", &len)) {
goto Bail;
}
if (len + 1 >= msglen) {
goto Bail;
}
msg[len++] = 0; // end-of-name
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCNL_DTAG_CALLBACK, CCN_TT_DTAG, callback, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCN_DTAG_TYPE, CCN_TT_DTAG, "sign", &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkStrBlob(component_buf+len3, component_buf + complen, CCN_DTAG_SEQNO, CCN_TT_DTAG, (char*) txid_s, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkBlob(component_buf+len3, component_buf + complen, CCN_DTAG_SIGNATURE, CCN_TT_DTAG, // signature
(char*) sig, siglen, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkBlob(component_buf + len3, component_buf + complen, CCN_DTAG_CONTENTDIGEST,
CCN_TT_DTAG, (char*) content, contentlen, &len3)) {
goto Bail;
}
if (ccnl_ccnb_mkBlob(msg+len, msg + msglen, CCN_DTAG_CONTENT, CCN_TT_DTAG, // content
(char*) component_buf, len3, &len)) {
goto Bail;
}
if (len + 1 >= msglen) {
goto Bail;
}
msg[len++] = 0; // end-o
memset(h,0,sizeof(h));
snprintf(h, sizeof(h), "%s-2", ux_path);
if (h[sizeof(h)-1] != 0) {
goto Bail;
}
if (len > CCNL_MAX_PACKET_SIZE) {
return 0;
}
ux_sendto(sock, h, msg, len);
printf("\t complete, answered to: %s len: %zu\n", ux_path, len);
Bail:
if (component_buf) {
ccnl_free(component_buf);
}
if (msg) {
ccnl_free(msg);
}
if (sig) {
ccnl_free(sig);
}
ret = 1;
return ret;
}
int parse_crypto_packet(uint8_t *buf, size_t buflen, int sock) {
uint64_t num;
uint8_t typ;
char component[100];
char type[100];
// char content[CCNL_MAX_PACKET_SIZE];
char callback[1024];
printf("Crypto Request... parsing \n");
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_INTEREST) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_NAME) {
goto Bail;
}
//check if component ist ccnx
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_COMPONENT) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
memset(component, 0, sizeof(component));
ccnl_crypto_get_tag_content(&buf, &buflen, component, sizeof(component));
if (strcmp(component, "ccnx")) {
goto Bail;
}
//check if component is crypto
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_COMPONENT) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
memset(component, 0, sizeof(component));
ccnl_crypto_get_tag_content(&buf, &buflen, component, sizeof(component));
if(strcmp(component, "crypto")) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_COMPONENT) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
//open content object
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_CONTENTOBJ) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_CONTENT) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCNL_DTAG_CALLBACK) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
memset(callback, 0, sizeof(callback));
ccnl_crypto_get_tag_content(&buf, &buflen, callback, sizeof(callback));
printf("\tCallback function is: %s\n", callback);
//get msg-type, what to do
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_DTAG || num != CCN_DTAG_TYPE) {
goto Bail;
}
if(ccnl_ccnb_dehead(&buf, &buflen, &num, &typ)) {
goto Bail;
}
if (typ != CCN_TT_BLOB) {
goto Bail;
}
memset(type, 0, sizeof(type));
ccnl_crypto_get_tag_content(&buf, &buflen, type, sizeof(type));
if(!strcmp(type, "verify")) {
handle_verify(&buf, &buflen, sock, callback);
}
if (!strcmp(type, "sign")) {
handle_sign(&buf, &buflen, sock, callback);
}
return 1;
Bail:
printf("\tError occured\n");
return 0;
}
int crypto_main_loop(int sock)
{
//receive packet async and call parse/answer...
size_t len;
ssize_t len_s;
// pid_t pid;
uint8_t buf[CCNL_MAX_PACKET_SIZE];
struct sockaddr_un src_addr;
socklen_t addrlen = sizeof(struct sockaddr_un);
len_s = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*) &src_addr,
&addrlen);
if (len_s < 0) {
return 0;
}
len = (size_t) len_s;
//pid = fork();
//if(pid == 0){
parse_crypto_packet(buf, len, sock);
// _exit(0);
//}
return 1;
}
int main(int argc, char **argv)
{
if(argc < 3) {
goto Bail;
}
ux_path = argv[1];
ctrl_public_key = argv[2];
if(argc >= 3) {
private_key = argv[3];
}
int sock = ccnl_crypto_ux_open(ux_path);
while (crypto_main_loop(sock));
return 0;
Bail:
printf("Usage: %s crypto_ux_socket_path"
" public_key [private_key]\n", argv[0]);
return -1;
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/include/ccnl-crypto.h | /**
* @addtogroup CCNL-utils
* @{
*
* @file ccnl-crypto.h
* @brief Crypto functions for CCN-lite utilities
*
* Copyright (C) 2013-2018, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef CCNL_CRYPTO_H
#define CCNL_CRYPTO_H
#ifdef USE_SIGNATURES
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/objects.h>
#include <openssl/err.h>
#endif
int sha(void* input, unsigned long length, unsigned char* md);
int sign(char* private_key_path, unsigned char *msg, int msg_len,
unsigned char *sig, unsigned int *sig_len);
int
verify(char* public_key_path, unsigned char *msg, int msg_len,
unsigned char *sig, unsigned int sig_len);
int
add_signature(unsigned char *out, char *private_key_path,
unsigned char *file, unsigned int fsize);
#endif
/** @} */
|
azadeh-afzar/CCN-IRIBU | src/ccnl-utils/src/ccnl-ext-hmac.c | #include "ccnl-ext-hmac.h"
#ifdef USE_HMAC256
// RFC2104 keyval generation
void
ccnl_hmac256_keyval(uint8_t *key, size_t klen,
uint8_t *keyval) // MUST have 64 bytes (BLOCK_LENGTH)
{
DEBUGMSG(TRACE, "ccnl_hmac256_keyval %zu bytes\n", klen);
if (klen <= SHA256_BLOCK_LENGTH) {
memcpy(keyval, key, klen);
} else {
SHA256_CTX_t ctx;
ccnl_SHA256_Init(&ctx);
ccnl_SHA256_Update(&ctx, key, klen);
ccnl_SHA256_Final(keyval, &ctx);
klen = SHA256_DIGEST_LENGTH;
}
memset(keyval + klen, 0, SHA256_BLOCK_LENGTH - klen);
}
void
ccnl_hmac256_keyid(uint8_t *key, size_t klen,
uint8_t *keyid) // MUST have 32 bytes (DIGEST_LENGTH)
{
SHA256_CTX_t ctx;
DEBUGMSG(TRACE, "ccnl_hmac256_keyid %zu bytes\n", klen);
ccnl_SHA256_Init(&ctx);
ccnl_SHA256_Update(&ctx, key, klen);
if (klen > SHA256_BLOCK_LENGTH) {
uint8_t md[32];
ccnl_SHA256_Final(md, &ctx);
ccnl_SHA256_Init(&ctx);
ccnl_SHA256_Update(&ctx, md, sizeof(md));
}
ccnl_SHA256_Final(keyid, &ctx);
}
// internal
void
ccnl_hmac256_keysetup(SHA256_CTX_t *ctx, uint8_t *keyval, size_t kvlen,
uint8_t pad)
{
uint8_t buf[64];
size_t i;
if (kvlen > sizeof(buf)) {
kvlen = sizeof(buf);
}
for (i = 0; i < kvlen; i++, keyval++) {
buf[i] = *keyval ^ pad;
}
while (i < sizeof(buf)) {
buf[i++] = (uint8_t) (0 ^ pad); //TODO: WTF?
}
ccnl_SHA256_Init(ctx);
ccnl_SHA256_Update(ctx, buf, sizeof(buf));
}
// RFC2104 signature generation
void
ccnl_hmac256_sign(uint8_t *keyval, size_t kvlen,
uint8_t *data, size_t dlen,
uint8_t *md, size_t *mlen)
{
uint8_t tmp[SHA256_DIGEST_LENGTH];
SHA256_CTX_t ctx;
DEBUGMSG(TRACE, "ccnl_hmac_sign %zu bytes\n", dlen);
ccnl_hmac256_keysetup(&ctx, keyval, kvlen, 0x36); // inner hash
ccnl_SHA256_Update(&ctx, data, dlen);
ccnl_SHA256_Final(tmp, &ctx);
ccnl_hmac256_keysetup(&ctx, keyval, kvlen, 0x5c); // outer hash
ccnl_SHA256_Update(&ctx, tmp, sizeof(tmp));
ccnl_SHA256_Final(tmp, &ctx);
if (*mlen > SHA256_DIGEST_LENGTH) {
*mlen = SHA256_DIGEST_LENGTH;
}
memcpy(md, tmp, *mlen);
}
#ifdef NEEDS_PACKET_CRAFTING
#ifdef USE_SUITE_CCNTLV
// write Content packet *before* buf[offs], adjust offs and return bytes used
int8_t
ccnl_ccntlv_prependSignedContentWithHdr(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *lastchunknum,
size_t *contentpos,
uint8_t *keyval, // 64B
uint8_t *keydigest, // 32B
size_t *offset, uint8_t *buf, size_t *retlen)
{
size_t mdlength = 32, mdoffset, endofsign, oldoffset, len;
uint8_t hoplimit = 255; // setting to max (conten obj has no hoplimit)
(void)keydigest;
if (*offset < (8 + paylen + 4+32 + 3*4+32)) {
return -1;
}
oldoffset = *offset;
*offset -= mdlength; // reserve space for the digest
mdoffset = *offset;
if (ccnl_ccntlv_prependTL(CCNX_TLV_TL_ValidationPayload, mdlength, offset, buf)) {
return -1;
}
endofsign = *offset;
#ifdef XXX // we skip this
*offset -= 32;
memcpy(buf + *offset, keydigest, 32);
if (ccnl_ccntlv_prependTL(CCNX_VALIDALGO_KEYID, 32, offset, buf)) {
return -1;
}
if (ccnl_ccntlv_prependTL(CCNX_VALIDALGO_HMAC_SHA256, 4+32, offset, buf)) {
return -1;
}
if (ccnl_ccntlv_prependTL(CCNX_TLV_TL_ValidationAlgo, 4+4+32, offset, buf)) {
return -1;
}
#endif
if (ccnl_ccntlv_prependTL(CCNX_VALIDALGO_HMAC_SHA256, 0, offset, buf)) {
return -1;
}
if (ccnl_ccntlv_prependTL(CCNX_TLV_TL_ValidationAlgo, 4, offset, buf)) {
return -1;
}
len = oldoffset - *offset;
if (ccnl_ccntlv_prependContent(name, payload, paylen, lastchunknum,
contentpos, offset, buf, &len)) {
return -1;
}
if (len > (UINT16_MAX - 8)) {
DEBUGMSG(ERROR, "payload to sign is too large\n");
return -1;
}
ccnl_hmac256_sign(keyval, 64, buf + *offset, endofsign - *offset,
buf + mdoffset, &mdlength);
if (ccnl_ccntlv_prependFixedHdr(CCNX_TLV_V1, CCNX_PT_Data,
len, hoplimit, offset, buf)) {
return -1;
}
*retlen = oldoffset - *offset;
return 0;
}
#endif // USE_SUITE_CCNTLV
#ifdef USE_SUITE_NDNTLV
int8_t
ccnl_ndntlv_prependSignedContent(struct ccnl_prefix_s *name,
uint8_t *payload, size_t paylen,
uint32_t *final_block_id, size_t *contentpos,
uint8_t *keyval, // 64B
uint8_t *keydigest, // 32B
size_t *offset, uint8_t *buf, size_t *reslen) {
size_t mdlength = 32;
size_t oldoffset = *offset, oldoffset2, mdoffset, endofsign;
uint8_t signatureType[1] = {NDN_SigTypeVal_SignatureHmacWithSha256};
(void) keydigest;
if (contentpos) {
*contentpos = *offset - paylen;
}
// fill in backwards
*offset -= mdlength; // sha256 msg digest bits, filled out later
mdoffset = *offset;
// mandatory
if (ccnl_ndntlv_prependTL(NDN_TLV_SignatureValue, (uint64_t) mdlength, offset, buf)) {
return -1;
}
// to find length from start of content to end of SignatureInfo
endofsign = *offset;
#ifdef XXX // we skip this
// keyid
*offset -= 32;
memcpy(buf + *offset, keydigest, 32);
if (ccnl_ndntlv_prependTL(NDN_TLV_KeyLocatorDigest, 32, offset, buf)) {
return -1;
}
if (ccnl_ndntlv_prependTL(NDN_TLV_KeyLocator, 32+2, offset, buf)) {
return -1;
}
#endif
// use NDN_SigTypeVal_SignatureHmacWithSha256
if (ccnl_ndntlv_prependBlob(NDN_TLV_SignatureType, signatureType, 1,
offset, buf)) {
return 1;
}
// Groups KeyLocator and Signature Type with stored len
if (ccnl_ndntlv_prependTL(NDN_TLV_SignatureInfo, endofsign - *offset, offset, buf)) {
return -1;
}
// mandatory payload/content
if (ccnl_ndntlv_prependBlob(NDN_TLV_Content, payload, paylen,
offset, buf)) {
return -1;
}
// to find length of optional MetaInfo fields
oldoffset2 = *offset;
if (final_block_id) {
if (ccnl_ndntlv_prependIncludedNonNegInt(NDN_TLV_NameComponent,
*final_block_id,
NDN_Marker_SegmentNumber,
offset, buf)) {
return -1;
}
// optional
if (ccnl_ndntlv_prependTL(NDN_TLV_FinalBlockId, oldoffset2 - *offset, offset, buf)) {
return -1;
}
}
// mandatory (empty for now)
if (ccnl_ndntlv_prependTL(NDN_TLV_MetaInfo, oldoffset2 - *offset, offset, buf)) {
return -1;
}
// mandatory
if (ccnl_ndntlv_prependName(name, offset, buf)) {
return -1;
}
// mandatory
if (ccnl_ndntlv_prependTL(NDN_TLV_Data, oldoffset - *offset,
offset, buf)) {
return -1;
}
if (contentpos) {
*contentpos -= *offset;
}
ccnl_hmac256_sign(keyval, 64, buf + *offset, (endofsign - *offset),
buf + mdoffset, &mdlength);
*reslen = oldoffset - *offset;
return 0;
}
#endif // USE_SUITE_NDNTLV
#endif // NEEDS_PACKET_CRAFTING
#endif // USE_HMAC256
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-defs.h | /*
* @f ccnl-defs.h
* @b header file with constants for CCN lite (CCNL)
*
* Copyright (C) 2011-14, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2011-03-30 created
*/
#ifndef CCNL_DEFS_H
#define CCNL_DEFS_H
#define CCNL_VERSION "2015-07-07"
#define ETHTYPE_XEROX_PUP 0x0a00
#define ETHTYPE_PARC_CCNX 0x0801
#define CCNL_ETH_TYPE ETHTYPE_PARC_CCNX
//#define CCNL_ETH_TYPE 0x88b5
#define CCNL_DEFAULT_UNIXSOCKNAME "/tmp/.ccnl.sock"
/* assuming that all broadcast addresses consist of a sequence of equal octets */
#define CCNL_BROADCAST_OCTET 0xFF
#if defined(CCNL_ARDUINO) || defined(CCNL_RIOT)
# define CCNL_MAX_INTERFACES 1
# define CCNL_MAX_IF_QLEN 14
#ifndef CCNL_MAX_PACKET_SIZE
# define CCNL_MAX_PACKET_SIZE 120
#endif
#ifndef CCNL_MAX_PREFIX_SIZE
# define CCNL_MAX_PREFIX_SIZE 50
#endif
# define CCNL_MAX_ADDRESS_LEN 8
# define CCNL_MAX_NAME_COMP 8
#ifndef CCNL_DEFAULT_MAX_PIT_ENTRIES
# define CCNL_DEFAULT_MAX_PIT_ENTRIES 20
#endif
#elif defined(CCNL_ANDROID) // max of BTLE and 2xUDP
# define CCNL_MAX_INTERFACES 3
# define CCNL_MAX_IF_QLEN 10
# define CCNL_MAX_PACKET_SIZE 4096
# define CCNL_MAX_ADDRESS_LEN 6
# define CCNL_MAX_NAME_COMP 16
# define CCNL_DEFAULT_MAX_PIT_ENTRIES 100
# define CCNL_MAX_PREFIX_SIZE 2048
#else
# define CCNL_MAX_INTERFACES 10
# define CCNL_MAX_IF_QLEN 64
# define CCNL_MAX_PACKET_SIZE 8096
# define CCNL_MAX_ADDRESS_LEN 6
# define CCNL_MAX_NAME_COMP 64
# define CCNL_MAX_PREFIX_SIZE 2048
# define CCNL_DEFAULT_MAX_PIT_ENTRIES (-1)
#endif
#ifndef CCNL_CONTENT_TIMEOUT
# define CCNL_CONTENT_TIMEOUT 300 // sec
#endif
#ifndef CCNL_INTEREST_TIMEOUT
# define CCNL_INTEREST_TIMEOUT 10 // sec
#endif
#ifndef CCNL_MAX_INTEREST_RETRANSMIT
# define CCNL_MAX_INTEREST_RETRANSMIT 7
#endif
#ifndef CCNL_FACE_TIMEOUT
// # define CCNL_FACE_TIMEOUT 60 // sec
# define CCNL_FACE_TIMEOUT 30 // sec
#endif
#define CCNL_DEFAULT_MAX_CACHE_ENTRIES 0 // means: no content caching
#ifdef CCNL_RIOT
#define CCNL_MAX_NONCES -1 // -1 --> detect dups by PIT
#else //!CCNL_RIOT
#define CCNL_MAX_NONCES 256 // for detected dups
#endif //CCNL_RIOT
enum {
#ifdef USE_SUITE_CCNB
CCNL_SUITE_CCNB = 1,
#endif
#ifdef USE_SUITE_CCNTLV
CCNL_SUITE_CCNTLV = 2,
#endif
#ifdef USE_SUITE_LOCALRPC
CCNL_SUITE_LOCALRPC = 5,
#endif
#ifdef USE_SUITE_NDNTLV
CCNL_SUITE_NDNTLV = 6,
#endif
CCNL_SUITE_LAST = 7
};
#define CCNL_SUITE_DEFAULT (CCNL_SUITE_LAST - 1)
// ----------------------------------------------------------------------
// our own packet format extension for switching encodings:
// 0x80 followed by:
// (add new encodings at the end)
/**
* @brief Provides an (internal) mapping to the supported packet types
*
* Note: Previous versions of CCN-lite supported Cisco's IOT packet format
* which has since be removed. In previous versions, this enum had a
* member CCNL_ENC_IOT2014 (with an implictly assigned value of 3).
*/
typedef enum ccnl_enc_e {
CCNL_ENC_CCNB, /**< encoding for CCN */
CCNL_ENC_NDN2013, /**< NDN encoding (version 2013) */
CCNL_ENC_CCNX2014, /**< CCNx encoding (version 2014) */
CCNL_ENC_LOCALRPC /**< encoding type for local rpc mechanism */
} ccnl_enc;
// ----------------------------------------------------------------------
// our own CCN-lite extensions for the ccnb encoding:
// management protocol: (ccnl-ext-mgmt.c)
#define CCNL_DTAG_MACSRC 99001 // newface: which L2 interface
#define CCNL_DTAG_IP4SRC 99002 // newface: which L3 interface
#define CCNL_DTAG_IP6SRC 99003 // newface: which L3 interface
#define CCNL_DTAG_UNIXSRC 99004 // newface: which UNIX path
#define CCNL_DTAG_FRAG 99005 // fragmentation protocol, see core.h
#define CCNL_DTAG_FACEFLAGS 99006 //
#define CCNL_DTAG_DEVINSTANCE 99007 // adding/removing a device/interface
#define CCNL_DTAG_DEVNAME 99008 // name of interface (eth0, wlan0)
#define CCNL_DTAG_DEVFLAGS 99009 //
#define CCNL_DTAG_MTU 99010 //
#define CCNL_DTAG_WPANADR 99011 // newface: WPAN
#define CCNL_DTAG_WPANPANID 99012 // newface: WPAN
#define CCNL_DTAG_DEBUGREQUEST 99100 //
#define CCNL_DTAG_DEBUGACTION 99101 // dump, halt, dump+halt
//FOR THE DEBUG_REPLY MSG
#define CCNL_DTAG_DEBUGREPLY 99201 // dump reply
#define CCNL_DTAG_INTERFACE 99202 // interface list
#define CCNL_DTAG_NEXT 99203 // next pointer e.g. for faceinstance
#define CCNL_DTAG_PREV 99204 // prev pointer e.g. for faceinstance
#define CCNL_DTAG_IFNDX 99205
#define CCNL_DTAG_IP 99206
#define CCNL_DTAG_ETH 99207
#define CCNL_DTAG_UNIX 99208
#define CCNL_DTAG_PEER 99209
#define CCNL_DTAG_FWD 99210
#define CCNL_DTAG_FACE 99211
#define CCNL_DTAG_ADDRESS 99212
#define CCNL_DTAG_SOCK 99213
#define CCNL_DTAG_REFLECT 99214
#define CCNL_DTAG_PREFIX 99215
#define CCNL_DTAG_INTERESTPTR 99216
#define CCNL_DTAG_LAST 99217
#define CCNL_DTAG_MIN 99218
#define CCNL_DTAG_MAX 99219
#define CCNL_DTAG_RETRIES 99220
#define CCNL_DTAG_PUBLISHER 99221
#define CCNL_DTAG_CONTENTPTR 99222
#define CCNL_DTAG_LASTUSE 99223
#define CCNL_DTAG_SERVEDCTN 99224
#define CCNL_DTAG_VERIFIED 99225
#define CCNL_DTAG_CALLBACK 99226
#define CCNL_DTAG_SUITE 99300
#define CCNL_DTAG_COMPLENGTH 99301
#define CCNL_DTAG_CHUNKNUM 99302
#define CCNL_DTAG_CHUNKFLAG 99303
// ----------------------------------------------------------------------
// fragmentation protocol: (ccnl-ext-frag.c, FRAG_SEQUENCED2012)
#define CCNL_DTAG_FRAGMENT2012 144144 // http://redmine.ccnx.org/issues/100803
#define CCNL_DTAG_FRAG2012_TYPE (CCNL_DTAG_FRAGMENT2012+1)
#define CCNL_DTAG_FRAG2012_FLAGS (CCNL_DTAG_FRAGMENT2012+2)
#define CCNL_DTAG_FRAG2012_SEQNR (CCNL_DTAG_FRAGMENT2012+3) // our seq number
#define CCNL_DTAG_FRAG2012_OLOSS (CCNL_DTAG_FRAGMENT2012+5) // our loss count
#define CCNL_DTAG_FRAG2012_YSEQN (CCNL_DTAG_FRAGMENT2012+6) // your (highest) seq no
// fragmentation protocol: (ccnl-ext-frag.c, FRAG_CCNx2013)
#define CCNL_DTAG_FRAGMENT2013 CCN_DTAG_FragP // requested 2013-07-24, assigned 2013-08-12
#define CCNL_DTAG_FRAG2013_TYPE CCN_DTAG_FragA
#define CCNL_DTAG_FRAG2013_SEQNR CCN_DTAG_FragB // our seq number
#define CCNL_DTAG_FRAG2013_FLAGS CCN_DTAG_FragC
#define CCNL_DTAG_FRAG2013_OLOSS CCNL_DTAG_FRAG2012_OLOSS // our loss count
#define CCNL_DTAG_FRAG2013_YSEQN CCNL_DTAG_FRAG2012_YSEQN // your (highest) seq no
#define CCNL_DTAG_FRAG_FLAG_MASK 0x03
#define CCNL_DTAG_FRAG_FLAG_FIRST 0x01
#define CCNL_DTAG_FRAG_FLAG_MID 0x00
#define CCNL_DTAG_FRAG_FLAG_LAST 0x02
#define CCNL_DTAG_FRAG_FLAG_SINGLE 0x03
// echo "FHBH" | base64 -d | hexdump -v -e '/1 "@x%02x"'| tr @ '\\'; echo
#define CCNL_FRAG_TYPE_CCNx2013_VAL "\x14\x70\x47"
// ----------------------------------------------------------------------
// face mgmt protocol:
#define CCNL_DTAG_FRAG_FLAG_STATUSREQ 0x04
// ----------------------------------------------------------------------
// begin-end fragmentation protocol:
#define CCNL_BEFRAG_FLAG_MASK 0x03
#define CCNL_BEFRAG_FLAG_FIRST 0x01
#define CCNL_BEFRAG_FLAG_MID 0x00
#define CCNL_BEFRAG_FLAG_LAST 0x02
#define CCNL_BEFRAG_FLAG_SINGLE 0x03
//#define USE_SIGNATURES
#define EXACT_MATCH 1
#define PREFIX_MATCH 0
#define CMP_EXACT 0 // used to compare interests among themselves
#define CMP_MATCH 1 // used to match interest and content
#define CMP_LONGEST 2 // used to lookup the FIB
#define CCNL_FACE_FLAGS_STATIC 1
#define CCNL_FACE_FLAGS_REFLECT 2
#define CCNL_FACE_FLAGS_SERVED 4
#define CCNL_FACE_FLAGS_FWDALLI 8 // forward all interests, also known ones
#define CCNL_FRAG_NONE 0
#define CCNL_FRAG_SEQUENCED2012 1
#define CCNL_FRAG_CCNx2013 2
#define CCNL_FRAG_SEQUENCED2015 3
#define CCNL_FRAG_BEGINEND2015 4
#if defined(CCNL_RIOT) || defined(USE_WPAN)
#define CCNL_LLADDR_STR_MAX_LEN (3 * 8)
#else
/* unless a platform supports a link layer with longer addresses than Ethernet,
* 6 is enough */
#define CCNL_LLADDR_STR_MAX_LEN (3 * 6)
#endif
// ----------------------------------------------------------------------
#ifdef USE_CCNxDIGEST
# define compute_ccnx_digest(buf) SHA256(buf->data, buf->datalen, NULL)
#else
# define compute_ccnx_digest(b) NULL
#endif
#endif //CCNL_DEFS_H
//define true / false
#define true 1
#define false 0
// eof
|
azadeh-afzar/CCN-IRIBU | test/ccnl-core/test_interest.c | /**
* @file test-interest.c
* @brief CCN lite - Tests for interest functions
*
* Copyright (C) 2018 Safety IO
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "ccnl-interest.h"
void test_ccnl_interest_append_pending_invalid_parameters()
{
int result = ccnl_interest_append_pending(NULL, NULL);
assert_int_equal(result, -1);
struct ccnl_interest_s interest;
result = ccnl_interest_append_pending(&interest, NULL);
assert_int_equal(result, -2);
}
void test_ccnl_interest_is_same_invalid_parameters()
{
int result = ccnl_interest_isSame(NULL, NULL);
assert_int_equal(result, -1);
struct ccnl_interest_s interest;
result = ccnl_interest_isSame(&interest, NULL);
assert_int_equal(result, -2);
}
void test_ccnl_interest_remove_pending_invalid_parameters()
{
int result = ccnl_interest_remove_pending(NULL, NULL);
assert_int_equal(result, -1);
struct ccnl_interest_s interest;
result = ccnl_interest_remove_pending(&interest, NULL);
assert_int_equal(result, -2);
}
void test1()
{
int result = 0;
assert_int_equal(result, 0);
}
int main(void)
{
const UnitTest tests[] = {
unit_test(test1),
unit_test(test_ccnl_interest_is_same_invalid_parameters),
unit_test(test_ccnl_interest_remove_pending_invalid_parameters),
unit_test(test_ccnl_interest_append_pending_invalid_parameters),
};
return run_tests(tests);
}
|
azadeh-afzar/CCN-IRIBU | src/ccnl-core/include/ccnl-core.h | /*
* @f ccnl-core.h
* @b Core Lib Header file
*
* Copyright (C) 2015, <NAME>, University of Basel
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* File history:
* 2015-04-25 created
*/
#ifndef CCNL_CORE_H
#define CCNL_CORE_H
#include "ccnl-array.h"
#include "ccnl-content.h"
#include "ccnl-defs.h"
#include "ccnl-face.h"
#include "ccnl-frag.h"
#include "ccnl-interest.h"
#include "ccnl-malloc.h"
#include "ccnl-os-time.h"
#include "ccnl-pkt.h"
#include "ccnl-relay.h"
#include "ccnl-sockunion.h"
#include "ccnl-buf.h"
#include "ccnl-crypto.h"
#include "ccnl-dump.h"
#include "ccnl-forward.h"
#include "ccnl-if.h"
#include "ccnl-logging.h"
#include "ccnl-mgmt.h"
#include "ccnl-pkt-util.h"
#include "ccnl-prefix.h"
#include "ccnl-sched.h"
#endif // CCNL_CORE_H
|
QUST-Coder/Yui | LoginDialog.h | <reponame>QUST-Coder/Yui
#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H
//(*Headers(LoginDialog)
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/dialog.h>
//*)
class LoginDialog: public wxDialog
{
public:
LoginDialog(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~LoginDialog();
//(*Declarations(LoginDialog)
wxTextCtrl* Password;
wxButton* ButtonExit;
wxStaticText* StaticText2;
wxStaticText* RaceStatu;
wxStaticText* StaticText1;
wxStaticText* StaticText3;
wxTextCtrl* UserName;
wxButton* LoginButton;
wxStaticText* StaticText5;
wxButton* Reset;
wxStaticText* StaticText4;
//*)
protected:
//(*Identifiers(LoginDialog)
static const long ID_BUTTON_Login;
static const long ID_TEXTCTRL_Username;
static const long ID_TEXTCTRL_Password;
static const long ID_STATICTEXT1;
static const long ID_STATICTEXT2;
static const long ID_BUTTON_Exit;
static const long ID_STATICTEXT3;
static const long ID_STATICTEXT4;
static const long ID_STATICTEXT5;
static const long ID_STATICTEXT_RaceStatu;
static const long ID_BUTTON_Reset;
//*)
private:
//(*Handlers(LoginDialog)
void OnTextCtrl1Text(wxCommandEvent& event);
void OnLoginButtonClick(wxCommandEvent& event);
void OnButtonExitClick(wxCommandEvent& event);
void OnResetClick(wxCommandEvent& event);
//*)
DECLARE_EVENT_TABLE()
};
#endif
|
QUST-Coder/Yui | LoginConfig.h | #ifndef LOGINCONFIG_H
#define LOGINCONFIG_H
#include "src/YuiUtil.h"
//(*Headers(LoginConfig)
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/dialog.h>
//*)
class LoginConfig: public wxDialog
{
public:
LoginConfig(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~LoginConfig();
//(*Declarations(LoginConfig)
wxButton* ServerAddressConfirm;
wxStaticText* WarningText;
wxTextCtrl* ServerAddress;
//*)
protected:
//(*Identifiers(LoginConfig)
static const long ID_TEXTCTRL_ServerAddress;
static const long ID_BUTTON_Confirm;
static const long ID_STATICTEXT_Warning;
//*)
private:
//(*Handlers(LoginConfig)
void OnTextCtrl1Text(wxCommandEvent& event);
void OnButton1Click(wxCommandEvent& event);
void OnServerAddressConfirmClick(wxCommandEvent& event);
void OnInit(wxInitDialogEvent& event);
//*)
DECLARE_EVENT_TABLE()
};
#endif
|
QUST-Coder/Yui | UserFrame.h | #ifndef USERFRAME_H
#define USERFRAME_H
//(*Headers(UserFrame)
#include <wx/stattext.h>
#include <wx/frame.h>
//*)
class UserFrame: public wxFrame
{
public:
UserFrame(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~UserFrame();
//(*Declarations(UserFrame)
wxStaticText* StaticText2;
wxStaticText* StaticText1;
//*)
protected:
//(*Identifiers(UserFrame)
static const long ID_STATICTEXT1;
static const long ID_STATICTEXT2;
//*)
private:
//(*Handlers(UserFrame)
//*)
DECLARE_EVENT_TABLE()
};
#endif
|
QUST-Coder/Yui | src/YuiUtil.h | <reponame>QUST-Coder/Yui
#ifndef YUIUTIL_H_INCLUDED
#define YUIUTIL_H_INCLUDED
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <wx/app.h>
#include <wx/string.h>
#include <cstring>
#include <string>
class YuiUtil
{
public:
bool is_ipaddress(wxString address);
};
#endif // YUIUTIL_H_INCLUDED
|
QUST-Coder/Yui | src/YuiMain.h | /***************************************************************
* Name: YuiMain.h
* Purpose:
* Author: Richard (<EMAIL>)
* Created: 2017-03-28
* Copyright: Richard ()
* License:
**************************************************************/
#ifndef YUIMAIN_H_INCLUDED
#define YUIMAIN_H_INCLUDED
//(*Headers(YuiMain)
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/statline.h>
#include <wx/button.h>
#include <wx/dialog.h>
//*)
#endif // YUIMAIN_H_INCLUDED
|
QUST-Coder/Yui | src/YuiApp.h | /***************************************************************
* Name: YuiApp.h
* Purpose:
* Author: Richard (<EMAIL>)
* Created: 2017-03-28
* Copyright: Richard ()
* License:
**************************************************************/
#ifndef YUIAPP_H_INCLUDED
#define YUIAPP_H_INCLUDED
#define WINDOWS
#include <wx/app.h>
class YuiApp : public wxApp
{
public:
virtual bool OnInit();
};
#endif // YUIAPP_H_INCLUDED
|
publickanai/PLMScrollMenu | Example/Pods/Target Support Files/PLMScrollMenu/PLMScrollMenu-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double PLMScrollMenuVersionNumber;
FOUNDATION_EXPORT const unsigned char PLMScrollMenuVersionString[];
|
publickanai/PLMScrollMenu | Example/Pods/Target Support Files/Pods-PLMScrollMenu_Tests/Pods-PLMScrollMenu_Tests-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_PLMScrollMenu_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_PLMScrollMenu_TestsVersionString[];
|
publickanai/PLMScrollMenu | Example/Pods/Target Support Files/Pods-PLMScrollMenu_Example/Pods-PLMScrollMenu_Example-umbrella.h | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_PLMScrollMenu_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_PLMScrollMenu_ExampleVersionString[];
|
tomatolog/RadixSpline | include/rs/ctz_clz.h | <reponame>tomatolog/RadixSpline<gh_stars>0
#ifdef _MSC_VER
#include <intrin.h>
static inline int __builtin_ctz(unsigned x) {
unsigned long ret;
_BitScanForward(&ret, x);
return (int)ret;
}
static inline int __builtin_ctzll(unsigned long long x) {
unsigned long ret;
_BitScanForward64(&ret, x);
return (int)ret;
}
static inline int __builtin_ctzl(unsigned long x) {
return sizeof(x) == 8 ? __builtin_ctzll(x) : __builtin_ctz((uint32_t)x);
}
static inline int __builtin_clz(unsigned x) {
//unsigned long ret;
//_BitScanReverse(&ret, x);
//return (int)(31 ^ ret);
return (int)__lzcnt(x);
}
static inline int __builtin_clzll(unsigned long long x) {
//unsigned long ret;
//_BitScanReverse64(&ret, x);
//return (int)(63 ^ ret);
return (int)__lzcnt64(x);
}
static inline int __builtin_clzl(unsigned long x) {
return sizeof(x) == 8 ? __builtin_clzll(x) : __builtin_clz((uint32_t)x);
}
#ifdef __cplusplus
static inline int __builtin_ctzl(unsigned long long x) {
return __builtin_ctzll(x);
}
static inline int __builtin_clzl(unsigned long long x) {
return __builtin_clzll(x);
}
#endif
#endif
|
brinoausrino/ofxPointilize | example/src/ofApp.h | <reponame>brinoausrino/ofxPointilize
#pragma once
#include "ofMain.h"
#include "ofxPointilize.h"
#include "ofxGui.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void onRenderTypeChanged(int& t);
void onDynamicSizeChanged(int& t);
void onScaleModeChanged(int& t);
void onBorderSizeChanged(float& t);
void onRadiusChanged(float& t);
ofxPointilize pointilize;
ofxPanel panel;
ofParameter<int> renderType;
ofParameter<int> dynamicSize;
ofParameter<float> borderSize;
ofParameter<float> radius;
ofVideoGrabber vidGrabber;
};
|
brinoausrino/ofxPointilize | src/ofxPointilize.h | #pragma once
#include "ofMain.h"
#define STRINGIFY(...) STRINGIFY_AUX(__VA_ARGS__)
#define STRINGIFY_AUX(...) #__VA_ARGS__
class ofxPointilize
{
public:
enum ScaleMode {
/// \brief complete image is shown
FIT,
/// \brief image fills whole texture, image is cut off
FILL,
/// \brief image fills whole texture, image is streched
STRECHED
};
enum RenderType {
QUADRATIC,
CIRCLES
};
enum DynamicSizeMode {
ALL_EQUAL,
DARK_BIG,
BRIGHT_BIG,
CLOSE_BIG,
FAR_BIG
};
void setup(int w = 512, int h = 512, bool useDepth = false);
void update();
void draw(int x, int y);
void loadTexture(ofTexture texture);
void loadDepthTexture(ofTexture texture);
ofTexture& getTexture();
ofxPointilize::RenderType getRenderType();
void setRenderType(RenderType renderType);
void setRenderType(int renderType);
float getBorderSize();
void setBorderSize(float size);
ofxPointilize::DynamicSizeMode getDynamicSizeMode();
void setDynamicSizeMode(DynamicSizeMode mode);
void setDynamicSizeMode(int mode);
ofxPointilize::ScaleMode getScaleMode();
void setScaleMode(ScaleMode mode);
void setScaleMode(int mode);
float getRadius();
void setRadius(float radius);
private:
string getVertexShader();
string getFragmentShader();
static ofVec2f resize(ofVec2f src, ofVec2f dst, ScaleMode mode = FILL);
static ofVec2f centerObjects(ofVec2f src, ofVec2f dst);
ofShader shader;
bool useDepth;
int width, height;
ofTexture colorInTexture, depthInTexture;
RenderType renderType;
float borderSize;
DynamicSizeMode dynamicSize;
ScaleMode scaleMode;
float radius;
bool useFboColor, useFboDepth;
ofFbo fboColor, fboDepth;
ofTexture textureColor, textureDepth;
ofFbo outputFbo;
};
|
pelahi/Develop-with-OpenMP | Solutions/c/src/pi-omp-v3.c | /*************************************
* Calculating Pi with using method: *
* integral 4.0/(1+x^2) dx = p *
* Serial Version *
************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// Reference value to estimate error
double PI_ref=3.1415926535897932;
static long num_steps=1000000000;
static int MIN_NUM_STEPS=500000000;
double step;
double local_int(int start, int end, double delta)
{
double sum = 0, x;
for (int i=start; i<end; i++){
x=(i+0.5) * delta;
sum = sum + 4.0/(1.0+(x*x));
}
return sum;
}
// recursively split integration domain till small enough for one task
// this is NOT the optimal soluiton but is informative
double my_integrate(int start, int end, double delta) {
int nsteps = (end - start);
int nthreads = floor(nsteps/(double)MIN_NUM_STEPS);
int midpoint = nsteps / 2+start;
double sum=0.0;
if (nthreads > 1) {
#pragma omp parallel \
default(none) shared(start,end,nthreads,sum,midpoint,delta) \
num_threads(2) if (nthreads > 1)
#pragma single
{
double sumleft, sumright;
#pragma omp task shared(sumleft)
{
sumleft = my_integrate(start, midpoint, delta);
}
#pragma omp task shared(sumright)
{
sumright = my_integrate(midpoint, end, delta);
}
#pragma omp taskwait
sum = sumleft + sumright;
}
}
else
{
sum = local_int(start, end, delta);
}
return sum;
}
int main (int argc, char* argv[]){
double start,stop,diff_time;
double sum=0.0, pi;
start= omp_get_wtime();
step = 1.0 / (double) num_steps;
sum = my_integrate(0, num_steps, step);
pi = step * sum ;
stop= omp_get_wtime();
diff_time = (double) (stop-start);
printf ("Estimated value of pi = %2.15lf\n",pi);
printf ("Error = %2.15lf\n",fabs(PI_ref - pi));
printf ("Compute time= %2.5lf seconds\n",diff_time);
}
|
pelahi/Develop-with-OpenMP | Solutions/c/src/hello-omp.c | <reponame>pelahi/Develop-with-OpenMP
#include <omp.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void main (){
#pragma omp parallel
{
int thread_id =omp_get_thread_num();
char* hostname = (char*) malloc(256*sizeof(char));
gethostname(hostname,256*sizeof(char));
printf("Hello world from thread %d on node %s\n",thread_id,hostname);
}
}
|
pelahi/Develop-with-OpenMP | Workbench/Exercise1/c/pi-serial.c | /********************************************************
* Calculating Pi with using midpoint rectangle method: *
* integral 4.0/(1+x^2) dx = pi *
* or *
* summation (for i=0 to n) 4.0/(1+x_i^2) *
* where x_i = (i + 1/2) * delta x *
* Serial Version *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Including OpenMP header to call the timing function from API
* to estimate compute_time*/
#include <omp.h>
// Reference value to estimate error
double PI_ref=3.1415926535897932;
static long num_rects=1000000000;
double step;
int main (int argc, char* argv[]){
double start,stop;
double diff_time;
long i;
double x,pi,sum=0.0;
printf ("Requested number of steps = %ld\n",num_rects);
start= omp_get_wtime();
// Calculate delta x. Hint: reciprocal of num_rects
step = 1/(double) num_rects;
for (i=0; i<num_rects; i++){
/*
* Write an algorithm which first evaluates the
* evaluate midpoint of ith rectangle (x_i)
* updates the sum by evaluating f(x) at x
*/
}
//Update value of pi
stop= omp_get_wtime();
diff_time = stop-start;
printf ("Estimated value of pi = %2.15lf\n",pi);
printf ("Error = %2.15lf\n",fabs(PI_ref - pi));
printf ("Compute time= %2.5lf seconds\n",diff_time);
}
|
pelahi/Develop-with-OpenMP | Solutions/c/src/pi-omp-v2.c | /*************************************
* Calculating Pi with using method: *
* integral 4.0/(1+x^2) dx = p *
* Serial Version *
************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// Reference value to estimate error
double PI_ref=3.1415926535897932;
static long num_steps=1000000000;
double step;
int main (int argc, char* argv[]){
double start,stop,diff_time;
long i;
double x,pi,sum=0.0;
start= omp_get_wtime();
step = 1.0 / (double) num_steps;
#pragma omp parallel for private(x) reduction(+:sum)
//Work will be partitioned uniformly with the last thread getting the extra (in case the remainder(num_steps,nthreads) != 0
for (i=0; i<num_steps; i++){
x=(i+0.5) * step;
sum = sum + 4.0/(1.0+(x*x));
}
//Master finally evaluates pi
pi = step * sum ;
stop= omp_get_wtime();
diff_time = (double) (stop-start);
printf ("Estimated value of pi = %2.15lf\n",pi);
printf ("Error = %2.15lf\n",fabs(PI_ref - pi));
printf ("Compute time= %2.5lf seconds\n",diff_time);
}
|
pelahi/Develop-with-OpenMP | Solutions/c/src/pi-serial.c | /********************************************************
* Calculating Pi with using midpoint rectangle method: *
* integral 4.0/(1+x^2) dx = pi *
* or *
* summation (for i=0 to n) 4.0/(1+x_i^2) *
* where x_i = (i + 1/2) * delta x *
* Serial Version *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
// Reference value to estimate error
double PI_ref=3.1415926535897932;
static long num_rects=1000000000;
double step;
int main (int argc, char* argv[]){
double start,stop;
double diff_time;
long i;
double x,pi,sum=0.0;
start= omp_get_wtime();
step = 1.0 / (double) num_rects;
for (i=0; i<num_rects; i++){
x=(i+0.5) * step;
sum = sum + 4.0/(1.0+(x*x));
}
pi = step * sum ;
stop=omp_get_wtime();
diff_time = stop-start;
printf ("Estimated value of pi = %2.16lf\n",pi);
printf ("Error = %2.16lf\n",fabs(PI_ref - pi));
printf ("Compute time= %2.5lf seconds\n",diff_time);
}
|
pelahi/Develop-with-OpenMP | Gauss_demo/Gauss_serial/include/gaussian.h | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct{
int neq;
int num_row,num_col;
char* filename;
}input;
void* check_malloc(size_t, char*);
void Read_command_line_arguments(int*,char**, input*);
float** allocate_mat(int,int);
void set_to_default_system(float**);
void read_in_system(int, float**,char*);
void write_out(int , float** );
float* solve(int , float** );
float summation(int,float*, float**);
float* backward_substitution(int,float**);
|
pelahi/Develop-with-OpenMP | Workbench/Preliminary/c/hello-omp.c | #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
/*
Exercise:
Intent : Write a helloworld program with OpenMP.
Goals:
1. Include OpenMP header
2. Within the scope of #pragma omp parallel
a. Each thread queries it thread ID.
b. Each thread then prints its thread ID.
*/
void main (){
int thread_id = 0;
//Initialize parallel region here
{
printf("Hello World from %d \n", thread_id);
}
}
|
pelahi/Develop-with-OpenMP | Solutions/c/src/pi-omp-v1.c | <gh_stars>0
/********************************************************
* Calculating Pi with using midpoint rectangle method: *
* integral 4.0/(1+x^2) dx = pi *
* or *
* summation (for i=0 to n) 4.0/(1+x_i^2) *
* where x_i = (i + 1/2) * delta x *
* OpenMP Version 1 *
********************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double PI_ref=3.1415926535897932;
static long num_rects=1000000000;
double step;
int main (int argc, char* argv[]){
double start,stop,diff_time;
long i;
start= omp_get_wtime();
double x,
sum=0.0,pi=0.0;
step = 1.0 / (double) num_rects;
int nthreads=0;
#pragma omp parallel private(x) firstprivate(sum) shared(pi,nthreads)
{
//All threads retrieve their thread id
int tid= omp_get_thread_num();
//Any one of the threads retrieve the total number of threads in the shared variable nthreads
#pragma omp single
{
nthreads = omp_get_num_threads();
}
//Partition the work into block cyclic manner store local sum in a private variable
for (i=tid; i<num_rects; i+=nthreads){
x=(i+0.5) * step;
sum = sum+4.0/(1.0+(x*x));
}
#pragma omp critical (summation)
{
//Each thread does the following one at a time.
pi += (step * sum);
}
}
stop= omp_get_wtime();
diff_time = (double) (stop-start);
printf ("Estimated value of pi = %2.16lf\n",pi);
printf ("Error = %2.16lf\n",fabs(PI_ref - pi));
printf ("Compute time= %2.5lf seconds\n",diff_time);
}
|
onutech/npio | npio_test_c.c | <reponame>onutech/npio<filename>npio_test_c.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <unistd.h>
#include "npio.h"
/* 100-long 64-bit signed array */
void test1()
{
int err;
size_t i;
int64_t *data, total;
npio_Array array;
npio_init_array(&array);
err = npio_load("test1.npy", &array);
if (err)
{
fprintf(stderr, "npio_load: %s\n", strerror(err));
exit(1);
}
printf("data type: ");
if (array.floating_point)
printf("%d-bit float\n", array.bit_width);
else if (array.is_signed)
printf("%d-bit signed integer\n", array.bit_width);
else
printf("%d-bit unsigned integer\n", array.bit_width);
printf("shape: ");
for (i = 0; i < array.dim; ++i)
printf("%ld ", array.shape[i]);
printf("\n");
assert(array.bit_width == 64 && !array.floating_point && array.is_signed);
data = (int64_t*) array.data;
total = 0;
for (i = 0; i < array.size; ++i)
total += data[i];
assert(total == 4950);
npio_free_array(&array);
printf("test1 passed\n");
}
/* 10000-long 32-bit floats in 100x10x10 array */
void test2()
{
int err;
size_t i;
float *data, total;
npio_Array array;
npio_init_array(&array);
err = npio_load("test2.npy", &array);
if (err)
{
fprintf(stderr, "npio_load: %s\n", strerror(err));
exit(1);
}
printf("data type: ");
if (array.floating_point)
printf("%d-bit float\n", array.bit_width);
else if (array.is_signed)
printf("%d-bit signed integer\n", array.bit_width);
else
printf("%d-bit unsigned integer\n", array.bit_width);
printf("shape: ");
for (i = 0; i < array.dim; ++i)
printf("%ld ", array.shape[i]);
printf("\n");
assert(array.bit_width == 32 && array.floating_point);
data = (float*) array.data;
total = 0;
for (i = 0; i < array.size; ++i)
total += data[i];
assert(fabs(total / 5005.37f - 1.0f) < 1e-6f);
npio_free_array(&array);
printf("test2 passed\n");
}
void test3()
{
int i, err;
float *data, total;
npio_Array array;
npio_init_array(&array);
err = npio_load_header("test2.npy", &array);
if (err)
{
fprintf(stderr, "npio_load_header: %s\n", strerror(err));
exit(1);
}
err = npio_load_data(&array);
if (err)
{
fprintf(stderr, "npio_load_data: %s\n", strerror(err));
exit(1);
}
data = (float*) array.data;
total = 0;
for (i = 0; i < array.size; ++i)
total += data[i];
assert(fabs(total / 5005.37f - 1.0f) < 1e-6f);
npio_free_array(&array);
printf("test3 passed\n");
}
void test4()
{
int i, err;
int64_t *data;
float total;
FILE *f;
void *p;
size_t sz;
npio_Array array;
npio_init_array(&array);
f = fopen("test1.npy", "r");
if (!f)
{
fprintf(stderr, "could not open test1.npy\n");
exit(1);
}
fseek(f, 0, SEEK_END);
sz = ftell(f);
fseek(f, 0, SEEK_SET);
p = malloc(sz);
if (fread(p, 1, sz, f) != sz)
{
perror("fread");
exit(1);
}
err = npio_load_mem(p, sz, &array);
if (err)
{
fprintf(stderr, "npio_load_mem: %s\n", strerror(err));
exit(1);
}
fclose(f);
data = (int64_t*) array.data;
total = 0;
for (i = 0; i < array.size; ++i)
total += data[i];
assert(total == 4950);
npio_free_array(&array);
free(p);
printf("test4 passed\n");
}
/* pipe in a file to ourselves to check read-based load */
void test5()
{
int fd, err;
npio_Array array;
size_t sz, i;
FILE* f;
int64_t *data, total;
f = popen("cat test1.npy", "r");
if (f == 0)
{
perror("popen");
exit(1);
}
fd = fileno(f);
npio_init_array(&array);
if ((err = npio_load_fd(fd, &array)))
{
fprintf(stderr, "npio_load_fd: %s\n", strerror(err));
exit(1);
}
data = (int64_t*) array.data;
total = 0;
for (i = 0; i < array.size; ++i)
total += data[i];
assert(total == 4950);
fclose(f);
npio_free_array(&array);
printf("test5 passed\n");
}
int main()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}
|
onutech/npio | npio.h | #ifndef NPIO_H_
#define NPIO_H_
/******************************************************************************
Simple header-only routines for reading and writing numpy files. This header
can be used with both C and C++ code. There are no external library
dependencies. Just place the header in your include path to use.
Based on the documentation at
https://docs.scipy.org/doc/numpy-dev/neps/npy-format.html
License: MIT (see LICENSE.txt)
Limitations:
Can only be used for homogenous arrays. Structured arrays and Object arrays are
not supported. Structured arrays may be supported at some point in the future.
This code does not conform strictly to the specified format. It is known to
work with files actually generated by numpy, but there are lots of variations
in the header that are not supported by the minimalist parser in this file.
It is safe to use this with numpy files that may contain pickle objects or
executable code - such files will simply result in an error.
This code assumes that a C char is a single octet. If you are on a system
that does not satisfy this assumption, you should buy a different system.
Authors:
Vishal (<EMAIL>)
******************************************************************************/
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
/* Version of this header. */
#define NPIO_MAJOR_VERSION 0
#define NPIO_MINOR_VERSION 1
/* Some defaults */
#define NPIO_DEFAULT_MAX_DIM 32
/* Summary of revisions:
0.1 Initial version
*/
/* This struct represents the contents of a numpy file. */
typedef struct
{
char major_version; /* The npy major version number. */
char minor_version; /* The npy minor version number. */
size_t header_len; /* The length of the header in the file. */
char *dtype; /* The unparsed string representation of dtype */
size_t dim; /* The number of elements in shape. */
size_t *shape; /* The size on each axis. */
size_t size; /* The total number of elements.[1] */
int fortran_order; /* Whether or not data is in fortan-ordering. */
int little_endian; /* Whether or not elements are little-endian. */
int floating_point; /* Whether data is integral or floating point.*/
int is_signed; /* Whether data is signed or unsigned */
int bit_width; /* The number of bits to this datatype*/
void *data; /* Pointer to contents*/
/* The following fields are private. */
int _fd; /* File descriptor from which we are loading */
void* _buf; /* Memory buffer from where we are loading */
size_t _buf_size; /* Size of memory buffer from where we are loading */
char* _hdr_buf; /* A buffer for the header, if we are loading from fd */
size_t _shape_capacity; /* The space allocated for shape */
int _mmapped; /* Whether we mmapped the data into buf */
int _malloced; /* Whether we allocated the buffer */
int _opened; /* Whether we opened the file descriptor */
} npio_Array;
/*
[1]: the size field is only set when you load a numpy file. If you
want to save a numpy file, the size field is ignored by the library
and the size is computed from the shape. Both the npio_array_size() and
npio_array_memsize() functions do a full computation of the number of
elements from the shape, so if you are populating the struct yourself,
you may want to explicitly set the array->size field to cache it.
*/
/*
Some internal notes:
- The _buf field is set if either loading from memory or from a mapped file.
- The data field is allocated by us if _buf is null.
*/
/* Compute the total number of elements from the shape. */
static inline size_t npio_array_size(const npio_Array* array)
{
size_t n = 1, i;
for (i = 0; i < array->dim; ++i)
n *= array->shape[i];
return n;
}
/* Return the memory size in bytes that would be needed by the array data
Note: this does a full computation of the size from the shape. */
static inline size_t npio_array_memsize(const npio_Array* array)
{
return npio_array_size(array) * array->bit_width / 8;
}
/* Minimalist parser for python dict in the header. Lots of files that are
valid as per the spec may not be deemed valid by this code. Caveat Emptor. */
/* skip until we see a non-whitespace character. */
static inline const char* npio_ph_skip_spaces_(const char* p, const char* end)
{
while (p < end && isspace(*p))
++p;
return p;
}
/* append a value to array->shape, reallocating if needed. */
static inline int npio_ph_shape_append_(npio_Array* array, size_t val)
{
size_t *tmp;
if (array->dim == array->_shape_capacity)
{
array->_shape_capacity *= 2;
tmp = (size_t*) realloc(array->shape, sizeof(size_t) * array->_shape_capacity);
if (tmp == 0)
return ENOMEM;
array->shape = tmp;
}
array->shape[array->dim++] = val;
return 0;
}
/* Parse a python tuple of integers. Anything else should fail. */
static inline int npio_ph_parse_shape_(npio_Array* array, const char *start
, const char *end, const char **where)
{
const char *p = start, *nbeg, *nend;
size_t val;
int err;
if (p == end)
return EINVAL;
if (*p++ != '(')
return EINVAL;
array->_shape_capacity = 8;
array->shape = (size_t*) malloc(sizeof(size_t) * array->_shape_capacity);
if (array->shape == 0)
return ENOMEM;
while (1)
{
p = npio_ph_skip_spaces_(p, end);
nbeg = p;
while (p < end && *p >= '0' && *p <= '9')
++p;
nend = p;
if (p == end)
return EINVAL;
if (nbeg < nend) /* trailing comma is allowed in python, so must check */
{
val = 0;
while (nbeg < nend)
val = (*nbeg++ - '0') + val * 10;
if ((err = npio_ph_shape_append_(array, val)))
return err;
}
p = npio_ph_skip_spaces_(p, end);
if (p == end)
return EINVAL;
if (*p == ',')
++p;
else if (*p == ')')
{
++p;
break;
}
else
return EINVAL;
}
*where = p;
array->size = npio_array_size(array);
return 0;
}
/*
Parse a dtype for homogeneous arrays.
The Numpy specification says that the dtype can be any Python object that would
serve as a valid argument to numpy.dtype(). Right now we restrict the dtype to
match strings of the form 'EDN' where E can be '<' or '>' for the endianness, D
can be 'i', 'f' or 'u' for the c-type and N can be 1, 2, 4, or 8. All others we
reject. If we really want support for structured data (tables), then we need a
better parser and a single-header minimalist solution may not be appropriate.
Arguments:
dtype is the null-terminated string value of the dtype in the header.
Return:
A parsed type if we understand the dtype, otherwise npio_unknown.
*/
static inline int npio_ph_parse_dtype_(npio_Array* array)
{
const char* dtype = array->dtype;
if (strlen(dtype) != 3)
return ENOTSUP;
switch (dtype[0])
{
case '<': array->little_endian = 1; break;
case '>': array->little_endian = 0; break;
default : return ENOTSUP;
}
switch (dtype[1])
{
case 'i':
array->is_signed = 1;
array->floating_point = 0;
break;
case 'u':
array->is_signed = 0;
array->floating_point = 0;
break;
case 'f':
array->is_signed = 1;
array->floating_point = 1;
break;
default:
return ENOTSUP;
}
switch (dtype[2])
{
case '1': array->bit_width = 8; break;
case '2': array->bit_width = 16; break;
case '4': array->bit_width = 32; break;
case '8': array->bit_width = 64; break;
default: return ENOTSUP;
}
return 0;
}
static inline int npio_ph_is_quote_(char p)
{
return (p == '\'' || p == '"');
}
/* parse a python dictionary containing the specific keys and value we expect */
static inline int npio_ph_parse_dict_(npio_Array* array, const char* start, const char* end)
{
int err;
char open_quote;
const char *p = start;
const char *dtbeg, *dtend;
size_t dtsz;
enum {k_descr, k_shape, k_fortran_order} key;
if (p >= end)
return EINVAL;
if (*p++ != '{')
return EINVAL;
/* Go through all key-value pairs. */
while (1)
{
p = npio_ph_skip_spaces_(p, end);
if (p >= end)
return EINVAL;
/* are we done? */
if (*p == '}')
{
++p;
break;
}
/* Expect the open quote of a key */
if (!npio_ph_is_quote_(open_quote = *p++))
return EINVAL;
/* Check for one of the three possible keys */
if (p + 5 < end && memcmp(p, "descr", 5) == 0)
{
key = k_descr;
p += 5;
}
else if (p + 5 < end && memcmp(p, "shape", 5) == 0)
{
key = k_shape;
p += 5;
}
else if (p + 13 < end && memcmp(p, "fortran_order", 13) == 0)
{
key = k_fortran_order;
p += 13;
}
else
return EINVAL;
/* Expect the close quote of the key */
if (p >= end || *p++ != open_quote)
return EINVAL;
/* Get to the colon */
p = npio_ph_skip_spaces_(p, end);
if (p >= end || *p++ != ':')
return EINVAL;
/* skip any more spaces */
p = npio_ph_skip_spaces_(p, end);
if (p == end)
return EINVAL;
switch (key)
{
case k_descr:
if (!npio_ph_is_quote_(open_quote = *p++))
return EINVAL;
dtbeg = p;
while (p < end && *p != open_quote)
++p;
dtend = p;
if (p == end)
return EINVAL;
++p;
dtsz = dtend - dtbeg;
array->dtype = (char*) malloc(dtsz + 1);
memcpy(array->dtype, dtbeg, dtsz);
array->dtype[dtsz] = 0;
break;
case k_fortran_order:
if (p + 4 < end && memcmp(p, "True", 4) == 0)
{
array->fortran_order = 1;
p += 4;
}
else if (p + 5 < end && memcmp(p, "False", 5) == 0)
{
array->fortran_order = 0;
p += 5;
}
else
return EINVAL;
break;
case k_shape:
if ((err = npio_ph_parse_shape_(array, p, end, &p)))
return err;
break;
}
/* skip any spaces after end of key : value */
p = npio_ph_skip_spaces_(p, end);
if (p == end)
return EINVAL;
/* grab that separating comma */
if (*p == ',')
++p;
/* next iteration takes care of any nonsense that might happen here! */
}
/* Parse the (very restricted) numpy dtype and return */
return npio_ph_parse_dtype_(array);
}
/* Initialize the struct so that we can cleanup correctly. Also provide
defaults for npy_save
*/
static inline void npio_init_array(npio_Array* array)
{
array->major_version = 1;
array->minor_version = 0;
array->header_len = 0;
array->dtype = 0;
array->dim = 0;
array->shape = 0;
array->size = 0;
array->fortran_order = 0;
array->little_endian = (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
array->floating_point = 1;
array->is_signed = 1;
array->bit_width = 32;
array->data = 0;
array->_fd = 0;
array->_buf = 0;
array->_buf_size = 0;
array->_hdr_buf = 0;
array->_shape_capacity = 0;
array->_mmapped = 0;
array->_malloced = 0;
}
/*
Release all resources associated with an Array that was initialized with
npio_init_array and then populated via one of the npio_load_* functions.
You should not call this if you manually populated the Array structure for
writing out data that you allocated yourself.
Note: this function does not free any memory associated with the struct itself.
Arguments:
array: a previously loaded array.
*/
static inline void npio_free_array(npio_Array* array)
{
if (array->dtype)
{
free(array->dtype);
array->dtype = 0;
}
if (array->shape)
{
free(array->shape);
array->shape = 0;
}
if (array->data && !array->_buf)
{
free(array->data);
array->data = 0;
}
if (array->_mmapped)
{
munmap(array->_buf, array->_buf_size);
array->_buf = 0;
}
if (array->_fd >= 0)
{
close(array->_fd);
array->_fd = -1;
}
if (array->_hdr_buf)
{
free(array->_hdr_buf);
array->_hdr_buf = 0;
}
}
/*
Check the magic number, the format version and gets the HEADER_LEN field.
The prelude should have atleast 10 characters for version 1 and 12 characters
for version 2.
*/
static inline int npio_load_header_prelude_(char* p, npio_Array* array, char** end)
{
/* assert magic string. Basic size check was done above. */
if (memcmp(p, "\x93NUMPY", 6) != 0)
return EINVAL;
p += 6;
/* get the version numbers */
array->major_version = *p++;
array->minor_version = *p++;
/* get the header length. Version 1 uses 2 bytes, version 2 uses 4 bytes. */
switch (array->major_version)
{
case 1:
array->header_len = p[0] + (p[1] << 8);
p += 2;
break;
case 2:
array->header_len = p[0]
+ (p[1] << 8)
+ (p[2] << 16)
+ (p[3] << 24);
p += 4;
break;
default:
return ENOTSUP;
}
*end = p;
return 0;
}
/* Load the header from a pointer to (partial) file data in memory. */
static inline int npio_load_header_mem4(void* p_, size_t sz
, npio_Array* array, size_t max_dim)
{
int err;
char* p = (char*) p_;
char *end = p + sz;
/* sanity check, to avoid some checks a bit later. */
if (sz < 16)
return EINVAL;
/* Store this buffer address for load_data */
if (!array->_mmapped)
{
array->_buf = p;
array->_buf_size = sz;
}
if ((err = npio_load_header_prelude_(p, array, &p)))
return err;
/* Ensure that the header_len doesn't make us go out of bounds */
if (p + array->header_len < end)
end = p + array->header_len;
/* Parse the header and return */
return npio_ph_parse_dict_(array, p, end);
}
/* Same as above, with default max_dim */
static inline int npio_load_header_mem(void *p, size_t sz, npio_Array* array)
{
return npio_load_header_mem4(p, sz, array, NPIO_DEFAULT_MAX_DIM);
}
/* Loads the header using read calls instead of mmap. */
static inline int npio_load_header_fd_read_(int fd, npio_Array* array, size_t max_dim)
{
/* Read just enough to know how much more we need to read */
char prelude[12];
char *end;
int nr, err;
size_t prelude_size;
nr = read(fd, prelude, sizeof(prelude));
if (nr < (int) sizeof(prelude))
return errno;
if ((err = npio_load_header_prelude_(prelude, array, &end)))
return err;
/* Keep track of how many bytes of prelude were present */
prelude_size = end - prelude;
/* We suppose here that each dimension in shape should not take more than 20
characters to estimate a limit on the header_len. Admitted, this is sloppy. */
if (array->header_len > 1024 + max_dim * 20)
return ERANGE;
/* We stick the prelude back together with the rest of the header */
if ((array->_hdr_buf = (char*) malloc(prelude_size + array->header_len)) == 0)
return ENOMEM;
memcpy(array->_hdr_buf, prelude, sizeof(prelude));
/* Now read in the rest of the header, accounting for excess bytes possibly
read in with the prelude. */
nr = read(fd, array->_hdr_buf + sizeof(prelude)
, array->header_len - (sizeof(prelude) - prelude_size));
/* Parse the header */
return npio_ph_parse_dict_(array, array->_hdr_buf + prelude_size, end);
}
/*
Load the header of a numpy file. If successful, you may call npio_load_data
subsequently to actually obtain the array elements. Finally you must call
npio_free_array to release all associated resources, even if there was an
error while loading.
Arguments:
fd: file descriptor of a file in numpy format.
array: pointer to an Array struct that will be populated (partially) on
return. The data is not loaded. You must have called npio_init_array
on array prior to calling this function.
max_hdr_size: as a security measure, return an error if the header size
is larger than this limit.
Return:
0 on success.
EINVAL the file is not a valid numpy file, or we failed to parse.
ENOTSUP unsupported npy version
ERANGE header exceeded max_hdr_size
Other errno codes if file could not be accessed etc.
*/
static inline int npio_load_header_fd3(int fd, npio_Array* array, size_t max_dim)
{
ssize_t file_size;
char *p;
/* Store the file descriptor for load_data */
if (!array->_opened)
array->_fd = fd;
/* Get the file size in preparation to mmap */
file_size = lseek(fd, 0, SEEK_END);
/* If we could not lseek, fallback on read. */
if (file_size < 0)
return npio_load_header_fd_read_(fd, array, max_dim);
/* map-in the file */
p = (char*) mmap(0, file_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED)
{
if (lseek(fd, 0, SEEK_SET))
return errno;
return npio_load_header_fd_read_(fd, array, max_dim);
}
array->_mmapped = 1;
array->_buf = p;
array->_buf_size = file_size;
return npio_load_header_mem4(p, file_size, array, max_dim);
}
/* Same as above, with default max_dim */
static inline int npio_load_header_fd(int fd, npio_Array* array)
{
return npio_load_header_fd3(fd, array, NPIO_DEFAULT_MAX_DIM);
}
/* Load the header of a numpy array from a file. The data is not explicitly
loaded (although it may be mapped into memory if the specified path is
mappable). */
static inline int npio_load_header3(const char* filename, npio_Array* array
, size_t max_dim)
{
int fd, err;
fd = open(filename, O_RDONLY);
if (fd < 0)
return errno;
array->_fd = fd;
array->_opened = 1;
err = npio_load_header_fd3(fd, array, max_dim);
/* we don't need to hang on the fd if we managed to map */
if (array->_mmapped)
{
close(fd);
array->_fd = -1;
array->_opened = 0;
}
return err;
}
/* Same as above, with a default max_dim */
static inline int npio_load_header(const char* filename, npio_Array* array)
{
return npio_load_header3(filename, array, NPIO_DEFAULT_MAX_DIM);
}
/* Swap two bytes, used for endian conversion below. */
static inline void npio_swap_bytes_(char* p1, char* p2)
{
char tmp;
tmp = *p2;
*p2 = *p1;
*p1 = tmp;
}
/*
Reverse the bytes of each element in the array to go from little to big or big
to little endian. This is a simple non-optimized implementation for the sake of
portability and ease-of-compilation of this code. Performance will be quite
poor.
Note: assumption: 1 byte == 1 octet.
Arguments:
n: the number of elements in the array
bit_width: number of bits per element, with 8 bits == 1 byte
data: pointer to data.
*/
static inline int npio_swap_bytes(size_t n, size_t bit_width, void* data)
{
size_t i;
char *p = (char*) data;
if (bit_width == 8)
return 0;
switch (bit_width)
{
case 16:
for (i = 0; i < n; ++i)
{
npio_swap_bytes_(p, p + 1);
p += 2;
}
return 0;
case 32:
for (i = 0; i < n; ++i)
{
npio_swap_bytes_(p, p + 3);
npio_swap_bytes_(p + 1, p + 2);
p += 4;
}
return 0;
case 64:
for (i = 0; i < n; ++i)
{
npio_swap_bytes_(p, p + 7);
npio_swap_bytes_(p + 1, p + 6);
npio_swap_bytes_(p + 2, p + 5);
npio_swap_bytes_(p + 3, p + 4);
p += 8;
}
return 0;
default:
return ENOTSUP;
}
}
/*
Load the array data, having previously read a header via npio_load_header.
If swap_bytes is true, the loaded data is converted to host endian.
*/
static inline int npio_load_data2(npio_Array* array, int swap_bytes)
{
/* These macros work on both GCC and CLANG without an additional include.
Right now we do not support any other endianness than big and little.
Numpy also only supports these two ('<' and '>'). */
static const int little_endian = (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
size_t data_offset;
size_t sz;
ssize_t nr;
/* Check that the header_len matches the alignment requirements
of the format */
data_offset = array->header_len + 6 + (array->major_version == 1 ? 4 : 6);
if (data_offset % 16)
return EINVAL;
if (array->_buf)
{
/* Check that the indicated data is within the mapped bounds. */
/* We are also checking here that there is no trailing data. */
if (data_offset + npio_array_memsize(array) != array->_buf_size)
return EINVAL;
/* Set the data pointer to the start of data */
array->data = (char*) array->_buf + data_offset;
}
else
{
/* we must allocate memory and read in the data */
sz = array->size * array->bit_width / 8;
if ((ssize_t) sz < 0)
return ERANGE;
array->data = malloc(sz);
if (!array->data)
return ENOMEM;
nr = read(array->_fd, array->data, sz);
if (nr < 0)
return errno;
if (nr != (ssize_t) sz)
return EINVAL;
}
/* Swap bytes if necessary */
if (swap_bytes && little_endian != array->little_endian)
{
array->little_endian = little_endian;
return npio_swap_bytes(array->size, array->bit_width, array->data);
}
return 0;
}
/* Same as above, but always swaps the byte order to match host. */
static inline int npio_load_data(npio_Array* array)
{
return npio_load_data2(array, 1);
}
/*
Load a numpy file.
Arguments:
fd: file descriptor of a file in numpy format.
array: pointer to an Array struct that will be populated on success.
Return:
0 on success, error code otherwise.
*/
static inline int npio_load_fd3(int fd, npio_Array* array, size_t max_dim)
{
int err;
/* First load the header. */
if ((err = npio_load_header_fd3(fd, array, max_dim)))
return err;
return npio_load_data(array);
}
/* Same as above but with defaulted max_dim */
static inline int npio_load_fd(int fd, npio_Array* array)
{
return npio_load_fd3(fd, array, NPIO_DEFAULT_MAX_DIM);
}
/*
Load a numpy file.
Arguments:
filename: name of the file to be loaded.
array: an Array struct that will be populated on return. You should not
have called npio_init_array on the array. On success, you can access
the header information and data in array. When done with it, you must
call npio_free_array() on the array to cleanup.
Return:
0 on success, error code otherwise.
*/
static inline int npio_load3(const char* filename, npio_Array* array
, size_t max_dim)
{
int fd, err;
fd = open(filename, O_RDONLY);
if (fd < 0)
return errno;
err = npio_load_fd3(fd, array, max_dim);
close(fd);
return err;
}
/* Same as above, but with a reasonable default for the max_hdr_size
safety parameter. */
static inline int npio_load(const char* filename, npio_Array* array)
{
/* This covers all version-1 files and should not be in any danger
of bringing down the calling code. */
return npio_load3(filename, array, 65536);
}
/* Load an numpy array from a memory buffer. The contents point to the
buffer and are not copied. */
static inline int npio_load_mem4(void *p, size_t sz, npio_Array* array
, size_t max_dim)
{
int err;
if ((err = npio_load_header_mem4(p, sz, array, max_dim)))
return err;
return npio_load_data(array);
}
/* Same as above, with a default for max_dim. */
static inline int npio_load_mem(void *p, size_t sz, npio_Array* array)
{
return npio_load_mem4(p, sz, array, NPIO_DEFAULT_MAX_DIM);
}
/* Prepare a numpy header in the designated memory buffer. On success, zero is
returned and out is set to 1 beyond the last written byte of the header. */
static inline int npio_save_header_mem(void* p, size_t sz, const npio_Array* array
, void **out)
{
size_t i, hdr_len;
char* hdr_buf = (char*) p;
char* hdr_end = hdr_buf + sz;
char* hdr = hdr_buf;
/* This is the absolute minimum space for the header the way we write it. */
if (sz < 64)
return ERANGE;
memcpy(hdr, "\x93NUMPY\x1\x0", 8);
hdr = hdr_buf + 8 + 2; /* leave 2 bytes for header_len, to be filled later*/
hdr += sprintf(hdr, "{\"descr\": \"%c%c%d\", "
, array->little_endian ? '<' : '>'
, array->floating_point ? 'f' : array->is_signed ? 'i' : 'u'
, array->bit_width / 8);
/* There is no way hdr can overflow at this point! */
hdr += sprintf(hdr, "\"fortran_order\": %s, "
, array->fortran_order ? "True" : "False");
/* Again, no need to check for overflow here. */
hdr += sprintf(hdr, "\"shape\": (");
for (i = 0; i < array->dim; ++i)
{
hdr += snprintf(hdr, hdr_end - hdr, "%ld, ", array->shape[i]);
if (hdr >= hdr_end - 3)
return ERANGE;
}
hdr += sprintf(hdr, ")} "); /* hence the -3 above. */
/* insert pad spaces */
while (hdr < hdr_end && ((hdr - hdr_end) % 16))
*hdr++ = ' ';
/* check that we still have space */
if ((hdr - hdr_end) % 16)
return ERANGE;
/* terminate with a \n. The npy specification is vague on this. One
interpretation is that the \n can occur first and then be followed by
spaces, but that causes "IndentationError: unexpected indent" from the
python loader. */
hdr[-1] = '\n';
/* Fill in the header_len field */
hdr_len = hdr - hdr_buf - 10;
hdr_buf[8] = hdr_len & 0xff;
hdr_buf[9] = hdr_len >> 8;
*out = hdr;
return 0;
}
/*
Save a numpy file.
Arguments:
fd: file descriptor of file to be saved to.
array: array to be saved.
Return:
0 on success.
ERANGE: the array has too many dimensions.
Other IO error from the OS.
*/
static inline int npio_save_fd(int fd, const npio_Array* array)
{
/*
We save in version 1 for now, so no need for dynamic allocation.
hdr_buf should be no smaller than 128 and should be divisible by 16.
*/
char hdr_buf[65536];
void *end;
char* hdr;
int err;
ssize_t nw;
size_t sz;
if ((err = npio_save_header_mem(hdr_buf, sizeof(hdr_buf), array, &end)))
return err;
hdr = (char*) end;
nw = write(fd, hdr_buf, hdr - hdr_buf);
if (nw < hdr - hdr_buf)
return errno;
/* Ok, now write out the data */
sz = npio_array_memsize(array);
if ((ssize_t) sz < 0)
return ERANGE; /* We can break it up into multiple writes,
but this is pretty damn large and will surely
exceed filesystem limits! */
nw = write(fd, array->data, sz);
if (nw != (ssize_t) sz)
return errno;
/* all done */
return 0;
}
/*
Save a numpy file.
Arguments:
filename: name of the file to be saved to.
array: the array to be saved.
Return:
0 on success, error code otherwise.
*/
static inline int npio_save(const char* filename, const npio_Array* array)
{
int fd, err;
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
return errno;
err = npio_save_fd(fd, array);
close(fd);
return err;
}
#ifdef __cplusplus
// Convenience wrappers for C++
// Enable additional convenience functions for C++11
#define NPIO_CXX11 __cplusplus >= 201103L
// You must define this macro if you want the C++ API to use exceptions instead
// of return values.
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
#include <typeinfo>
#include <system_error>
#endif
#if NPIO_CXX11
#include <initializer_list>
#endif
namespace npio
{
// Not relying on C++11 type_traits for compatibilty with legacy code-bases.
//For integral types.
template <class T>
struct Traits
{
static const bool is_signed = T(-1) < T(0);
static const bool floating_point = false;
static const size_t bit_width = sizeof(T) * 8;
static const char spec = is_signed ? 'i' : 'u';
};
template <>
struct Traits<float>
{
static const bool is_signed = true;
static const bool floating_point = true;
static const size_t bit_width = 32;
static const char spec = 'f';
};
template <>
struct Traits<double>
{
static const bool is_signed = true;
static const bool floating_point = true;
static const size_t bit_width = 64;
static const char spec = 'f';
};
// Save the array specicied by nDim, shape and data to a file descriptor
// opened for writing.
template <class T>
int save(int fd, size_t nDim, const size_t *shape, const T* data)
{
npio_Array array;
npio_init_array(&array);
array.dim = nDim;
array.shape = (size_t*) shape;
array.floating_point = Traits<T>::floating_point;
array.is_signed = Traits<T>::is_signed;
array.bit_width = Traits<T>::bit_width;
array.data = (char*) data;
return npio_save_fd(fd, &array);
}
#if NPIO_CXX11
// Same as above, but with initializer_list for convenience
template <class T>
int save(int fd, std::initializer_list<size_t> shape, const T* data)
{
return save(fd, shape.size(), shape.begin(), data);
}
#endif
// Save the array specified by nDim, shape and data to the specified file.
template <class T>
int save(const char* fn, size_t nDim, const size_t *shape, const T* data)
{
int fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
return errno;
int ret = save(fd, nDim, shape, data);
close(fd);
return ret;
}
#if NPIO_CXX11
// Same as above, but with initializer_list
template <class T>
int save(const char* fn, std::initializer_list<size_t> shape, const T* data)
{
return save(fn, shape.size(), shape.begin(), data);
}
#endif
// Simple untyped class wrapper for npio_load*
class Array
{
private:
npio_Array array;
#ifndef NPIO_CXX_ENABLE_EXCEPTIONS
int err;
#endif
public:
Array(const char* filename, size_t max_dim = NPIO_DEFAULT_MAX_DIM)
{
npio_init_array(&array);
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
if (int err = npio_load3(filename, &array, max_dim))
throw std::system_error(err, std::system_category());
#else
err = npio_load3(filename, &array, max_dim);
#endif
}
Array(int fd, size_t max_dim = NPIO_DEFAULT_MAX_DIM)
{
npio_init_array(&array);
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
if (int err = npio_load_fd3(fd, &array, max_dim))
throw std::system_error(err, std::system_category());
#else
err = npio_load_fd3(fd, &array, max_dim);
#endif
}
Array(void *p, size_t sz, size_t max_dim = NPIO_DEFAULT_MAX_DIM)
{
npio_init_array(&array);
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
if (int err = npio_load_mem4(p, sz, &array, max_dim))
throw std::system_error(err, std::system_category());
#else
err = npio_load_mem4(p, sz, &array, max_dim);
#endif
}
// Read-only accessors
#ifndef NPIO_CXX_ENABLE_EXCEPTIONS
// Get any error that occurred during construction. You must check this
// if you are not using exceptions.
int error() const { return err; }
#endif
// Get the total number of elements
size_t size() const { return array.size; }
// Get the dimensionality of the array
size_t dim() const { return array.dim; }
// Whether the array is in fortran order
bool fortran_order() const { return array.fortran_order; }
// Whether the array is in little endian order
bool little_endian() const { return array.little_endian; }
// Whether the data type is a float type.
bool floating_point() const { return array.floating_point; }
// Whether the data is signed.
bool is_signed() const { return array.is_signed; }
// Number of bits per element.
size_t bit_width() const { return array.bit_width; }
// The size along each dimension.
const size_t* shape() const { return array.shape; }
// The raw data pointer.
const void* data() const { return array.data; }
// The major and minor version of the loaded file's format.
char major_version() const { return array.major_version; }
char minor_version() const { return array.minor_version; }
// Some convenience functions
// Get the size along ith dimension. Implicitly all dimensions are 1
// beyond the dimensionality of the array.
size_t shape(size_t i)
{
if (i < array.dim)
return array.shape[i];
else
return 1;
}
// Returns whether the underlying data is of the specified type T.
template <class T>
bool isType() const
{
return Traits<T>::floating_point == array.floating_point
&& Traits<T>::is_signed == array.is_signed
&& Traits<T>::bit_width == array.bit_width;
}
// Get a typed pointer to the data. If the type does not match the
// underlying data, throws a bad_cast if exceptions are enabled.
template <class T>
T* get() const
{
if (!isType<T>())
{
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
throw std::bad_cast();
#else
return 0;
#endif
}
return (T*) array.data;
}
#if NPIO_CXX11
template <class T>
class ValueRange
{
T* _begin;
T* _end;
ValueRange(T* begin, T* end)
: _begin(begin)
, _end(end)
{}
friend class Array;
public:
~ValueRange() = default;
T* begin() const { return _begin; }
T* end() const { return _end; }
};
// For C++11 range-based for loops
template <class T>
ValueRange<T> values() const
{
if (isType<T>())
return ValueRange<T>((T*) array.data, (T*) array.data + array.size);
else
{
#ifdef NPIO_CXX_ENABLE_EXCEPTIONS
throw std::bad_cast();
#else
return ValueRange<T>(0, 0);
#endif
}
}
#endif
// Save the array back to file
int save(const char* filename)
{
return npio_save(filename, &array);
}
// Save the array back to fd
int save(int fd)
{
return npio_save_fd(fd, &array);
}
~Array()
{
npio_free_array(&array);
}
};
} // namespace npio
#endif
#endif
|
onutech/npio | example1.c | /* Simple example to print the shape of an array in npy format. */
#include <stdio.h>
#include "npio.h"
int main()
{
int i;
npio_Array array;
npio_init_array(&array);
npio_load("test1.npy", &array);
printf("shape: ");
for (i = 0; i < array.dim; ++i)
printf("%ld ", array.shape[i]);
printf("\n");
npio_free_array(&array);
return 0;
}
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/fftmr.h | /*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* fftmr.h
*
* Fast Fourier Transform with Mixed Radix Algorithm
*
* This class is designed for calculating discrete Fourier transform and
* inverse discrete Fourier transform of 1D signals by using Mixed-Radix
* Algorithms. The length of signals should equal to powers of 2.
*
* The algorithm is modified from "kube-gustavson-fft.c". Which is a pretty
* fast FFT algorithm. Not super-optimized lightning-fast, but very good
* considering its age and relative simplicity.
*
* <NAME>, 2010-04, Xi'an Jiaotong University.
*****************************************************************************/
#ifndef FFTMR_H
#define FFTMR_H
#include "vector.h"
namespace splab
{
/**
* complex node converted from "C" version for this algorithm
*/
template<typename Type>
struct Complex
{
Type re;
Type im;
};
/**
* two routines frequently used in FFT algorithm
*/
bool isPower2( int );
int fastLog2( int );
/**
* Radix based FFT class
*/
template<typename Type>
class FFTMR
{
public:
FFTMR();
~FFTMR();
void fft( Vector< complex<Type> > &xn );
void ifft( Vector< complex<Type> > &Xk );
void fft( const Vector<Type> &xn, Vector< complex<Type> > &Xk );
void ifft( const Vector< complex<Type> > &Xk, Vector<Type> &xn );
private:
void bitReverse( Vector<int> &bitrev );
void radix2( int nthpo, Complex<Type> *c0, Complex<Type> *c1 );
void radix4( int nthpo, Complex<Type> *c0, Complex<Type> *c1,
Complex<Type> *c2, Complex<Type> *c3 );
void radix8( int nxtlt, int nthpo, int length,
Complex<Type> *cc0, Complex<Type> *cc1,
Complex<Type> *cc2, Complex<Type> *cc3,
Complex<Type> *cc4, Complex<Type> *cc5,
Complex<Type> *cc6, Complex<Type> *cc7 );
void dft( int direction, int n, Complex<Type> *b );
};
// class FFTMR
#include "fftmr-impl.h"
}
// namespace splab
#endif
// FFTMR_H
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/usingdeclare.h | /*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* usingdeclare.h
*
* Usually used name declaration.
*
* <NAME>, 2010-08, Xi'an Jiaotong University.
*****************************************************************************/
#ifndef USINGDECLARE_H
#define USINGDECLARE_H
namespace splab
{
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::complex;
using std::ostream;
using std::istream;
//using std::min;
//using std::max;
using std::swap;
using std::ceil;
using std::abs;
using std::cos;
using std::sin;
using std::tan;
using std::acos;
using std::asin;
using std::atan;
using std::exp;
using std::log;
using std::log10;
using std::sqrt;
using std::pow;
}
// namespace splab
#endif
// USINGDECLARE_H
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/fftmr-impl.h | /*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* fftmr-impl.h
*
* Implementation for FFTMR class.
*
* <NAME>, 2010-04, Xi'an Jiaotong University.
*****************************************************************************/
/**
* To determine the input integer is or isn't the power of positive
* integer of 2. If it is, return true, or return false.
*/
bool isPower2( int n )
{
int bits = 0;
while( n )
{
bits += n & 1;
n >>= 1;
}
return ( bits == 1 );
}
/**
* Get binary log of integer argument -- exact if n is a power of 2.
*/
int fastLog2( int n )
{
int log = -1;
while( n )
{
log++;
n >>= 1;
}
return log;
}
/**
* constructors and destructor
*/
template<typename Type>
FFTMR<Type>::FFTMR()
{
}
template<typename Type>
FFTMR<Type>::~FFTMR()
{
}
/**
* Generate the bit reversed array.
*/
template<typename Type>
void FFTMR<Type>::bitReverse( Vector<int> &bitrev )
{
int i, j;
bitrev[0] = 0;
for( j=1; j<bitrev.size(); j<<=1 )
for( i=0; i<j; ++i )
{
bitrev[i] <<= 1;
bitrev[i+j] = bitrev[i]+1;
}
}
/**
* Radix-2 iteration subroutine.
*/
template<typename Type>
void FFTMR<Type>::radix2( int nthpo, Complex<Type> *c0, Complex<Type> *c1 )
{
int k, kk;
Type *cr0, *ci0, *cr1, *ci1, r1, fi1;
cr0 = &(c0[0].re);
ci0 = &(c0[0].im);
cr1 = &(c1[0].re);
ci1 = &(c1[0].im);
for( k=0; k<nthpo; k+=2 )
{
kk = k*2;
r1 = cr0[kk] + cr1[kk];
cr1[kk] = cr0[kk] - cr1[kk];
cr0[kk] = r1;
fi1 = ci0[kk] + ci1[kk];
ci1[kk] = ci0[kk] - ci1[kk];
ci0[kk] = fi1;
}
}
/**
* Radix-4 iteration subroutine.
*/
template<typename Type>
void FFTMR<Type>::radix4( int nthpo, Complex<Type> *c0, Complex<Type> *c1,
Complex<Type> *c2, Complex<Type> *c3 )
{
int k, kk;
Type *cr0, *ci0, *cr1, *ci1, *cr2, *ci2, *cr3, *ci3;
Type r1, r2, r3, r4, i1, i2, i3, i4;
cr0 = &(c0[0].re);
cr1 = &(c1[0].re);
cr2 = &(c2[0].re);
cr3 = &(c3[0].re);
ci0 = &(c0[0].im);
ci1 = &(c1[0].im);
ci2 = &(c2[0].im);
ci3 = &(c3[0].im);
for( k=1; k<=nthpo; k+=4 )
{
kk = (k-1)*2;
r1 = cr0[kk] + cr2[kk];
r2 = cr0[kk] - cr2[kk];
r3 = cr1[kk] + cr3[kk];
r4 = cr1[kk] - cr3[kk];
i1 = ci0[kk] + ci2[kk];
i2 = ci0[kk] - ci2[kk];
i3 = ci1[kk] + ci3[kk];
i4 = ci1[kk] - ci3[kk];
cr0[kk] = r1 + r3;
ci0[kk] = i1 + i3;
cr1[kk] = r1 - r3;
ci1[kk] = i1 - i3;
cr2[kk] = r2 - i4;
ci2[kk] = i2 + r4;
cr3[kk] = r2 + i4;
ci3[kk] = i2 - r4;
}
}
/**
* Radix-8 iteration subroutine.
*/
template<typename Type>
void FFTMR<Type>::radix8( int nxtlt, int nthpo, int length,
Complex<Type> *cc0, Complex<Type> *cc1,
Complex<Type> *cc2, Complex<Type> *cc3,
Complex<Type> *cc4, Complex<Type> *cc5,
Complex<Type> *cc6, Complex<Type> *cc7 )
{
int j, k, kk;
Type scale, arg, tr, ti;
Type c1, c2, c3, c4, c5, c6, c7,
s1, s2, s3, s4, s5, s6, s7;
Type ar0, ar1, ar2, ar3, ar4, ar5, ar6, ar7,
ai0, ai1, ai2, ai3, ai4, ai5, ai6, ai7;
Type br0, br1, br2, br3, br4, br5, br6, br7,
bi0, bi1, bi2, bi3, bi4, bi5, bi6, bi7;
Type *cr0, *cr1, *cr2, *cr3, *cr4, *cr5, *cr6, *cr7;
Type *ci0, *ci1, *ci2, *ci3, *ci4, *ci5, *ci6, *ci7;
cr0 = &(cc0[0].re);
cr1 = &(cc1[0].re);
cr2 = &(cc2[0].re);
cr3 = &(cc3[0].re);
cr4 = &(cc4[0].re);
cr5 = &(cc5[0].re);
cr6 = &(cc6[0].re);
cr7 = &(cc7[0].re);
ci0 = &(cc0[0].im);
ci1 = &(cc1[0].im);
ci2 = &(cc2[0].im);
ci3 = &(cc3[0].im);
ci4 = &(cc4[0].im);
ci5 = &(cc5[0].im);
ci6 = &(cc6[0].im);
ci7 = &(cc7[0].im);
scale = Type(TWOPI/length);
for( j=1; j<=nxtlt; j++ )
{
arg = (j-1)*scale;
c1 = cos(arg);
s1 = sin(arg);
c2 = c1*c1 - s1*s1;
s2 = c1*s1 + c1*s1;
c3 = c1*c2 - s1*s2;
s3 = c2*s1 + s2*c1;
c4 = c2*c2 - s2*s2;
s4 = c2*s2 + c2*s2;
c5 = c2*c3 - s2*s3;
s5 = c3*s2 + s3*c2;
c6 = c3*c3 - s3*s3;
s6 = c3*s3 + c3*s3;
c7 = c3*c4 - s3*s4;
s7 = c4*s3 + s4*c3;
for( k=j; k<=nthpo; k+=length )
{
kk = (k-1)*2; /* index by twos; re & im alternate */
ar0 = cr0[kk] + cr4[kk];
ar1 = cr1[kk] + cr5[kk];
ar2 = cr2[kk] + cr6[kk];
ar3 = cr3[kk] + cr7[kk];
ar4 = cr0[kk] - cr4[kk];
ar5 = cr1[kk] - cr5[kk];
ar6 = cr2[kk] - cr6[kk];
ar7 = cr3[kk] - cr7[kk];
ai0 = ci0[kk] + ci4[kk];
ai1 = ci1[kk] + ci5[kk];
ai2 = ci2[kk] + ci6[kk];
ai3 = ci3[kk] + ci7[kk];
ai4 = ci0[kk] - ci4[kk];
ai5 = ci1[kk] - ci5[kk];
ai6 = ci2[kk] - ci6[kk];
ai7 = ci3[kk] - ci7[kk];
br0 = ar0 + ar2;
br1 = ar1 + ar3;
br2 = ar0 - ar2;
br3 = ar1 - ar3;
br4 = ar4 - ai6;
br5 = ar5 - ai7;
br6 = ar4 + ai6;
br7 = ar5 + ai7;
bi0 = ai0 + ai2;
bi1 = ai1 + ai3;
bi2 = ai0 - ai2;
bi3 = ai1 - ai3;
bi4 = ai4 + ar6;
bi5 = ai5 + ar7;
bi6 = ai4 - ar6;
bi7 = ai5 - ar7;
cr0[kk] = br0 + br1;
ci0[kk] = bi0 + bi1;
if( j > 1 )
{
cr1[kk] = c4*(br0-br1) - s4*(bi0-bi1);
cr2[kk] = c2*(br2-bi3) - s2*(bi2+br3);
cr3[kk] = c6*(br2+bi3) - s6*(bi2-br3);
ci1[kk] = c4*(bi0-bi1) + s4*(br0-br1);
ci2[kk] = c2*(bi2+br3) + s2*(br2-bi3);
ci3[kk] = c6*(bi2-br3) + s6*(br2+bi3);
tr = Type(IRT2)*(br5-bi5);
ti = Type(IRT2)*(br5+bi5);
cr4[kk] = c1*(br4+tr) - s1*(bi4+ti);
ci4[kk] = c1*(bi4+ti) + s1*(br4+tr);
cr5[kk] = c5*(br4-tr) - s5*(bi4-ti);
ci5[kk] = c5*(bi4-ti) + s5*(br4-tr);
tr = -Type(IRT2)*(br7+bi7);
ti = Type(IRT2)*(br7-bi7);
cr6[kk] = c3*(br6+tr) - s3*(bi6+ti);
ci6[kk] = c3*(bi6+ti) + s3*(br6+tr);
cr7[kk] = c7*(br6-tr) - s7*(bi6-ti);
ci7[kk] = c7*(bi6-ti) + s7*(br6-tr);
}
else
{
cr1[kk] = br0 - br1;
cr2[kk] = br2 - bi3;
cr3[kk] = br2 + bi3;
ci1[kk] = bi0 - bi1;
ci2[kk] = bi2 + br3;
ci3[kk] = bi2 - br3;
tr = Type(IRT2)*(br5-bi5);
ti = Type(IRT2)*(br5+bi5);
cr4[kk] = br4 + tr;
ci4[kk] = bi4 + ti;
cr5[kk] = br4 - tr;
ci5[kk] = bi4 - ti;
tr = -Type(IRT2)*(br7+bi7);
ti = Type(IRT2)*(br7-bi7);
cr6[kk] = br6 + tr;
ci6[kk] = bi6 + ti;
cr7[kk] = br6 - tr;
ci7[kk] = bi6 - ti;
}
}
}
}
/**
* This routine replaces the input Complex<Type> vector by its
* finite discrete Fourier transform if direction == FORWARD.
* It replaces the input Complex<Type> vector by its finite discrete
* inverse Fourier transform if direction == INVERSE.
*/
template<typename Type>
void FFTMR<Type>::dft( int direction, int n, Complex<Type> *b )
{
int i, j;
int n2pow, n8pow, nthpo, ipass, nxtlt, length;
Complex<Type> tmp;
n2pow = fastLog2(n);
nthpo = n;
// Conjugate the input
if( direction == FORWARD )
for( i=0; i<n; i++ )
b[i].im = -b[i].im;
n8pow = n2pow/3;
if( n8pow )
{
// radix 8 iterations
for( ipass=1; ipass<=n8pow; ipass++ )
{
nxtlt = 0x1 << ( n2pow - 3*ipass );
length = 8*nxtlt;
radix8( nxtlt, nthpo, length,
b, b+nxtlt, b+2*nxtlt, b+3*nxtlt,
b+4*nxtlt, b+5*nxtlt, b+6*nxtlt, b+7*nxtlt );
}
}
// A final radix 2 or radix 4 iteration is needed.
if( n2pow%3 == 1 )
radix2( nthpo, b, b+1 );
if( n2pow%3 == 2 )
radix4( nthpo, b, b+1, b+2, b+3 );
// scale outputs
if( direction == FORWARD )
for( i=0; i<n; i++ )
b[i].im *= -1;
if( direction == INVERSE )
{
for( i=0; i<nthpo; i++ )
{
b[i].re /= n;
b[i].im /= n;
}
}
// bit reverse
Vector<int> bitrev(n);
bitReverse( bitrev );
for( i=0; i<n; ++i )
{
j = bitrev[i];
if( i < j )
{
tmp = b[i];
b[i] = b[j];
b[j] = tmp;
}
}
}
/**
* Forward Transform
*/
template<typename Type>
void FFTMR<Type>::fft( Vector<complex<Type> > &xn )
{
int nFFT = xn.size();
if( isPower2(nFFT) )
dft( FORWARD, nFFT, reinterpret_cast<Complex<Type>*>(xn.begin()) );
else
cerr << "The length of signal must abe power of 2!" ;
}
template<typename Type>
void FFTMR<Type>::fft( const Vector<Type> &xn, Vector< complex<Type> > &Xk )
{
int nFFT = xn.size();
if( isPower2(nFFT) )
{
if( Xk.size() != nFFT )
Xk.resize(nFFT);
for( int i=0; i<nFFT; ++i )
Xk[i] = xn[i];
dft( FORWARD, nFFT, reinterpret_cast<Complex<Type>*>(Xk.begin()) );
}
else
cerr << "The length of signal must abe power of 2!" ;
}
/**
* Inverse Transform
*/
template<typename Type>
void FFTMR<Type>::ifft( Vector<complex<Type> > &Xk )
{
int nFFT = Xk.size();
if( isPower2(nFFT) )
dft( INVERSE, nFFT, reinterpret_cast<Complex<Type>*>(Xk.begin()) );
else
cerr << "The length of signal must abe power of 2!" ;
}
template<typename Type>
void FFTMR<Type>::ifft( const Vector< complex<Type> > &Xk, Vector<Type> &xn )
{
int nFFT = Xk.size();
Vector< complex<Type> > tmp(Xk);
if( isPower2(nFFT) )
{
dft( INVERSE, nFFT, reinterpret_cast<Complex<Type>*>(tmp.begin()) );
if( xn.size() != nFFT )
xn.resize(nFFT);
for( int i=0; i<nFFT; ++i )
xn[i] = tmp[i].real();
}
else
cerr << "The length of signal must abe power of 2!" ;
}
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/constants.h | <reponame>luischuang/MeasureMotorSpeed<filename>MeasureMotorSpeed/constants.h
/*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* constants.h
*
* Some constants often used in numeric computing.
*
* <NAME>, 2010-01, Xi'an Jiaotong University.
*****************************************************************************/
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace splab
{
const double EPS = 2.220446049250313e-016;
const double PI = 3.141592653589793;
const double TWOPI = 6.283185307179586;
const double HALFPI = 1.570796326794897;
const double D2R = 0.017453292519943;
const double EXP = 2.718281828459046;
const double RT2 = 1.414213562373095;
const double IRT2 = 0.707106781186547;
const int FORWARD = 1;
const int INVERSE = 0;
const int MAXTERM = 20;
const int INITSIZE = 20;
const int EXTFACTOR = 2;
}
// namespace splab
#endif
// CONSTANTS_H
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/window.h | /*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* window.h
*
* This file includes seven usually used windows in signal processing:
* Rectangle Bartlett Hanning Hamming
* Blackman Kaiser Gauss
* All of them are same to those in "Matlab".
*
* <NAME>, 2010-01, Xi'an Jiaotong University.
*****************************************************************************/
#pragma once
#ifndef WINDOW_H
#define WINDOW_H
#include "vector.h"
namespace splab
{
template<typename Type> Vector<Type> window( const string&, int, Type );
template<typename Type> Vector<Type> window( const string&, int,
Type, Type );
template<typename Type> Vector<Type> rectangle( int, Type );
template<typename Type> Vector<Type> bartlett( int, Type );
template<typename Type> Vector<Type> hanning( int, Type, int, double);
template<typename Type> Vector<Type> hamming( int, Type, int, double);
template<typename Type> Vector<Type> blackman( int, Type );
template<typename Type> Vector<Type> kaiser( int, Type, Type );
template<typename Type> Vector<Type> gauss( int, Type, Type );
template<typename Type> Type I0( Type alpha );
#include "window-impl.h"
}
// namespace splab
#endif
// WINDOW_H
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/DataType.h | <gh_stars>0
#pragma once
template<typename Type>
class TwoTuples
{
public:
Type first;
Type second;
};
template<typename Type>
class ThreeTuples
{
public:
Type first;
Type second;
Type third;
};
template<typename Type>
class FourTuples
{
public:
Type first;
Type second;
Type third;
Type fourth;
};
template<typename Type>
class FiveTuples
{
public:
Type first;
Type second;
Type third;
Type fourth;
Type fifth;
}; |
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/fft-impl.h | <reponame>luischuang/MeasureMotorSpeed
/*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* fft-impl.h
*
* Implementation for FFT and IFFT interface.
*
* <NAME>, 2010-09, Xi'an Jiaotong University.
*****************************************************************************/
/**
* Forward FFT algorithm.
*/
template<typename Type>
inline Vector< complex<Type> > fft( const Vector<Type> &xn )
{
return fftr2c( xn );
}
//template<typename Type>
//inline Vector< complex<Type> > fft( const Vector< complex<Type> > &xn )
//{
// return fftc2c( xn );
//}
/**
* Inverse FFT algorithm.
*/
template<typename Type>
inline Vector< complex<Type> > ifft( const Vector< complex<Type> > &Xk )
{
return ifftc2c( Xk );
}
/**
* Real to complex DFT of 1D signal.
*/
template<typename Type>
inline Vector< complex<Type> > fftr2c( const Vector<Type> &xn )
{
Vector< complex<Type> > Xk( xn.size() );
if( isPower2(xn.size()) )
{
FFTMR<Type> dft;
dft.fft( xn, Xk );
}
else
{
FFTPF<Type> dft;
dft.fft( xn, Xk );
}
return Xk;
}
/**
* Complex to complex DFT of 1D signal.
*/
template<typename Type>
inline Vector< complex<Type> > fftc2c( const Vector< complex<Type> > &xn )
{
Vector< complex<Type> > Xk( xn.size() );
if( isPower2(xn.size()) )
{
for( int i=0; i<xn.size(); ++i )
Xk[i] = xn[i];
FFTMR<Type> dft;
dft.fft( Xk );
}
else
{
FFTPF<Type> dft;
dft.fft( xn, Xk );
}
return Xk;
}
/**
* Complex to real IDFT of 1D signal.
*/
template<typename Type>
inline Vector<Type> ifftc2r( const Vector< complex<Type> > &Xk )
{
Vector<Type> xn( Xk.size() );
if( isPower2(xn.size()) )
{
Vector< complex<Type> > tmp( Xk );
FFTMR<Type> dft;
dft.ifft( tmp, xn );
}
else
{
FFTPF<Type> dft;
dft.ifft( Xk, xn );
}
return xn;
}
/**
* Complex to complex IDFT of 1D signal.
*/
template<typename Type>
inline Vector< complex<Type> > ifftc2c( const Vector< complex<Type> > &Xk )
{
Vector< complex<Type> > xn( Xk.size() );
if( isPower2(xn.size()) )
{
for( int i=0; i<xn.size(); ++i )
xn[i] = Xk[i];
FFTMR<Type> dft;
dft.ifft( xn );
}
else
{
FFTPF<Type> dft;
dft.ifft( Xk, xn );
}
return xn;
}
|
luischuang/MeasureMotorSpeed | MeasureMotorSpeed/fftpf.h | <gh_stars>0
/*
* Copyright (c) 2008-2011 <NAME> (<NAME>), <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 2 or any later version.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. A copy of the GNU General Public License is available at:
* http://www.fsf.org/licensing/licenses
*/
/*****************************************************************************
* fftpf.h
*
* Fast Fourier Transform with prime factor algorithm
*
* This class is designed for calculating discrete Fourier transform and
* inverse discrete Fourier transform of 1D signals by using prime factor
* algorithms. The signals can be arbitrary length. The largest prime factor
* of n must be less than or equal to the constant PRIMEFACTOR defined below.
*
* The general idea is to factor the length of the DFT "n" into factors that are
* efficiently handled by the routines. A number of short DFT's are implemented
* with a minimum of arithmetical operations and using(almost) straight line
* code resultingin very fast execution when the factors of n belong to this
* set. Especially radix-10 is optimized. Prime factors, that are not in the
* set of short DFT's are handled with direct evaluation of the DFP expression.
*
* The algorithm is modified from "xFFT.h" of "Pratical Fourier Transform
* and C++ Implementation" written by <NAME>.
*
* <NAME>, 2010-09, Xi'an Jiaotong University.
*****************************************************************************/
#ifndef FFTPF_H
#define FFTPF_H
#include "vector.h"
#define PRIMEFACTOR 37
#define PRIMEFACTORHALF (PRIMEFACTOR+1)/2
#define PRIMECOUNT 20
namespace splab
{
template<class Type>
class FFTPF
{
public:
FFTPF();
~FFTPF();
void fft( const Vector<Type> &xn, Vector< complex<Type> > &Xk );
void ifft( const Vector< complex<Type> > &Xk, Vector<Type> &xn );
void fft( const Vector< complex<Type> > &xn,
Vector< complex<Type> > &Xk );
void ifft( const Vector< complex<Type> > &Xk,
Vector< complex<Type> > &xn );
private:
bool bAlloc;
int mNOldSize, mNFactor, nNewFactorSize, nHalfFactorSize,
groupOffset, dataOffset, blockOffset, adr, groupNo,
dataNo, blockNo, twNo;
int mSofarRadix[PRIMECOUNT], mActualRadix[PRIMECOUNT],
mRemainRadix[PRIMECOUNT];
Type tPI, t2PI, tIRT2, tIRT3, omega, twRe, twIim;
Type *pftwRe, *pftgRe, *pfzRe, *pfvRe, *pfwRe, *pftwIm, *pftgIm,
*pfzIm, *pfvIm, *pfwIm;
Type twiddleRe[PRIMEFACTOR], trigRe[PRIMEFACTOR], zRe[PRIMEFACTOR],
twiddleIm[PRIMEFACTOR], trigIm[PRIMEFACTOR], zIm[PRIMEFACTOR],
vRe[PRIMEFACTORHALF], wRe[PRIMEFACTORHALF],
vIm[PRIMEFACTORHALF], wIm[PRIMEFACTORHALF];
Type c3_1,
c5_1, c5_2, c5_3, c5_4, c5_5,
c7_1, c7_2, c7_3, c7_4, c7_5, c7_6,
c9_2, c9_3, c9_4, c9_5, c9_6, c9_7, c9_8, c9_9,
c11_1, c11_2, c11_3, c11_4, c11_5, c11_6, c11_7, c11_8,
c11_9, c11_10, c13_1, c13_2, c13_3, c13_4, c13_5, c13_6,
c13_7, c13_8, c13_9, c13_10, c13_11, c13_12, c16_2, c16_3,
c16_4, c16_5;
Type ttmp,
t1_re, t1_im, t2_re, t2_im, t3_re, t3_im, t4_re, t4_im,
t5_re, t5_im, t6_re, t6_im, t7_re, t7_im, t8_re, t8_im,
t9_re, t9_im, t10_re, t10_im, t11_re, t11_im, t12_re, t12_im,
t13_re, t13_im, t14_re, t14_im, t15_re, t15_im, t16_re, t16_im,
t17_re, t17_im, t18_re, t18_im, t19_re, t19_im, t20_re, t20_im,
t21_re, t21_im, t22_re, t22_im,
m1_re, m1_im, m2_re, m2_im, m3_re, m3_im, m4_re, m4_im,
m5_re, m5_im, m6_re, m6_im, m7_re, m7_im, m8_re, m8_im,
m9_re, m9_im, m10_re, m10_im, m11_re, m11_im, m12_re, m12_im;
void releaseMem();
void allocateMem();
void factorize( int n, int &nFact, int *fact);
void primeSetup( int nPoints );
void permute( const Vector<Type> &xn, Vector< complex<Type> > &yn );
void permute( const Vector< complex<Type> > &xn, Vector< complex<Type> > &yn,
bool bTrans=true );
void initTrig( int radix );
void radix2( Type *aRe, Type *aIm );
void radix3( Type *aRe, Type *aIm );
void radix4( Type *aRe, Type *aIm );
void radix5( Type *aRe, Type *aIm );
void radix7( Type *aRe, Type *aIm );
void radix8( Type *aRe, Type *aIm );
void radix9( Type *aRe, Type *aIm );
void radix10( Type *aRe, Type *aIm );
void radix11( Type *aRe, Type *aIm );
void radix13( Type *aRe, Type *aIm );
void radix16( Type *aRe, Type *aIm );
void radixOther( int radix );
void twiddleFFT( int sofarRadix, int radix, int remainRadix,
Vector< complex<Type> > &yn );
};
// class FFTPF
#include "fftpf-impl.h"
}
// namespace splab
#endif
//FFTPF_H
|
jsbourdon/lwgl | LWGL/include/Resources/Texture.h | <filename>LWGL/include/Resources/Texture.h<gh_stars>1-10
#pragma once
#include "Core/RefCountedObject.h"
#include "Descriptors/TextureDescriptor.h"
namespace lwgl
{
using namespace descriptors;
namespace resources
{
class Texture : public RefCountedObject<Texture>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
protected:
Texture() = default;
virtual ~Texture();
protected:
ID3D11Texture2D* m_pTexture { nullptr };
ID3D11ShaderResourceView* m_pSRV { nullptr };
union
{
ID3D11RenderTargetView* m_pRTV { nullptr };
ID3D11DepthStencilView* m_pDSV;
};
TextureType m_Type { TextureType::Texture2D };
uint32_t m_Width { 0 };
uint32_t m_Height { 0 };
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/Macros.h | <gh_stars>1-10
#pragma once
#include <type_traits>
#ifndef ARRAYSIZE
#define ARRAYSIZE(A) std::extent<decltype(A)>::value
#endif
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } }
#endif
#define SAFE_ADDREF(p) { if (p) { p->AddRef(); } }
#ifdef _DEBUG
#define CHECK_HRESULT_RETURN_VALUE_INTERNAL(hr, x, v) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
char tmp[1024]; \
sprintf_s(tmp, ARRAYSIZE(tmp), "Statement %s failed with HRESULT %lX", #x, hr); \
int selection = MessageBoxA(NULL, tmp, "COM Call Failed", MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL); \
if (selection == IDCANCEL) DebugBreak(); \
return v; \
} \
}
#else
#define CHECK_HRESULT_RETURN_VALUE_INTERNAL(hr, x, v) \
{ \
HRESULT hr = (x); \
if (FAILED(hr)) \
{ \
return v; \
} \
}
#endif
#define CHECK_HRESULT(x) CHECK_HRESULT_RETURN_VALUE_INTERNAL(hr_##__FILE__##__LINE__, x, hr_##__FILE__##__LINE__)
#define CHECK_HRESULT_RETURN_VALUE(x, v) CHECK_HRESULT_RETURN_VALUE_INTERNAL(hr_##__FILE__##__LINE__, x, v)
#define RAW_STRING_START() R"(
#define str)";
|
jsbourdon/lwgl | LWGL/include/Core/IRenderer.h | #pragma once
namespace lwgl
{
namespace core
{
class GfxDevice;
class GfxDeviceContext;
class RenderCore;
class IRenderer
{
public:
virtual bool Init(RenderCore *pRenderCore, GfxDevice* pDevice, GfxDeviceContext* pContext) = 0;
virtual void Destroy(RenderCore *pRenderCore) = 0;
virtual void OnUpdate(RenderCore *pRenderCore, GfxDeviceContext* pContext, double fTimeSec, float fElapsedTimeSec, void* pUserContext) = 0;
virtual void OnFrameRender(RenderCore *pRenderCore, GfxDevice* pDevice, GfxDeviceContext* pContext, double fTimeSec, float fElapsedTimeSec, void* pUserContext) = 0;
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/Constants.h | <filename>LWGL/include/Core/Constants.h
#pragma once
#include "3rd/DXUT/Core/DXUT.h"
namespace lwgl
{
namespace core
{
constexpr float PI = DirectX::XM_PI;
constexpr float TWO_PI = DirectX::XM_2PI;
constexpr float ONE_ON_PI = DirectX::XM_1DIVPI;
constexpr float ONE_ON_TWO_PI = DirectX::XM_1DIV2PI;
constexpr float PI_ON_TWO = DirectX::XM_PIDIV2;
constexpr float PI_ON_FOUR = DirectX::XM_PIDIV4;
constexpr size_t MAX_RENDERTARGET_COUNT = 8;
constexpr size_t MAX_SHADERRESOURCE_COUNT = 32;
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/SamplerStateDescriptor.h | #pragma once
namespace lwgl
{
namespace descriptors
{
struct SamplerStateDescriptor
{
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/Mesh.h | #pragma once
#include "3rd/DXUT/Optional/SDKmesh.h"
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace core
{
class GfxDevice;
class GfxDeviceContext;
}
using namespace core;
namespace resources
{
class Mesh final : public RefCountedObject<Mesh>
{
private:
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
Mesh() = default;
~Mesh();
CDXUTSDKMesh m_DXUTMesh {};
uint32_t m_AlbedoSlot { uint32_t(-1) };
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/RenderCore.h | #pragma once
#include <vector>
#include "Core/TypeDefs.h"
#include "Core/Globals.h"
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace utilities
{
class Camera;
}
namespace input
{
class IInputReceiver;
}
namespace debugging
{
class DebuggingFeatures;
}
using namespace utilities;
using namespace input;
using namespace debugging;
namespace core
{
class IRenderer;
class GfxDevice;
class GfxDeviceContext;
class RenderCore : public RefCountedObject<RenderCore>
{
friend base;
public:
static RenderCore* CreateCore();
template<typename T>
void Init(wchar_t const *windowTitle, uint32_t windowWidth, uint32_t windowHeight);
void RegisterInputReceiver(IInputReceiver *pReceiver);
Camera* CreateCamera(Vector4 worldPosition, Vector4 lookAtWorldPosition, float fov, float aspectRatio, float nearPlane, float farPlane);
void StartRenderLoop();
const std::vector<Camera*>& GetRegisteredCameras() const { return m_Cameras; }
DebuggingFeatures* GetDebuggingFeatures() { return m_pDebuggingFeatures; }
void GetBackBufferPixelSize(uint32_t &width, uint32_t &height);
private:
RenderCore();
~RenderCore();
static LRESULT CALLBACK MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext);
static HRESULT CALLBACK OnD3D11CreateDevice(ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext);
static void CALLBACK OnD3D11ReleasingSwapChain(void* pUserContext);
static void CALLBACK OnD3D11DestroyDevice(void* pUserContext);
static void CALLBACK OnFrameMove(double fTime, float fElapsedTime, void* pUserContext);
static void CALLBACK OnD3D11FrameRender(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext,
double fTime, float fElapsedTime, void* pUserContext);
static bool CALLBACK IsD3D11DeviceAcceptable(const CD3D11EnumAdapterInfo* AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo* DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext);
static HRESULT CALLBACK OnD3D11ResizedSwapChain(ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext);
void InternalInit(wchar_t const *windowTitle, uint32_t windowWidth, uint32_t windowHeight);
void CreateDepthStencil(uint32_t windowWidth, uint32_t windowHeight);
void CreateFullScreenTriangleResources();
void OnKeyPressed(uint32_t keyCode, bool keyDown, bool firstDown = false);
IRenderer* m_pRenderer;
GfxDevice* m_pDevice;
GfxDeviceContext* m_pDeviceContext;
IInputReceiver* m_pReceiver;
DebuggingFeatures* m_pDebuggingFeatures;
std::vector<Camera*> m_Cameras;
uint32_t m_BackBufferWidth;
uint32_t m_BackBufferHeight;
};
template<typename T>
void RenderCore::Init(wchar_t const *windowTitle, uint32_t windowWidth, uint32_t windowHeight)
{
void* alignedMem = AlignedAlloc(sizeof(T), alignof(T));
m_pRenderer = new(alignedMem) T();
InternalInit(windowTitle, windowWidth, windowHeight);
}
}
}
|
jsbourdon/lwgl | LWGL/include/Descriptors/PixelFormats.h | #pragma once
namespace lwgl
{
namespace descriptors
{
enum class PixelFormat
{
Unknown,
R32G32B32A32_FLOAT,
R32G32B32A32_UINT,
R32G32B32A32_SINT,
R32G32B32_FLOAT,
R32G32B32_UINT,
R32G32B32_SINT,
R16G16B16A16_FLOAT,
R16G16B16A16_UNORM,
R16G16B16A16_UINT,
R16G16B16A16_SNORM,
R16G16B16A16_SINT,
R32G32_FLOAT,
R32G32_UINT,
R32G32_SINT,
R10G10B10A2_UNORM,
R10G10B10A2_UINT,
R11G11B10_FLOAT,
R8G8B8A8_UNORM,
R8G8B8A8_UNORM_SRGB,
R8G8B8A8_UINT,
R8G8B8A8_SNORM,
R8G8B8A8_SINT,
R16G16_FLOAT,
R16G16_UNORM,
R16G16_UINT,
R16G16_SNORM,
R16G16_SINT,
D32_FLOAT,
R32_FLOAT,
R32_UINT,
R32_SINT,
D24_UNORM_S8_UINT,
R24_UNORM_X8_TYPELESS,
R8G8_UNORM,
R8G8_UINT,
R8G8_SNORM,
R8G8_SINT,
R16_FLOAT,
D16_UNORM,
R16_UNORM,
R16_UINT,
R16_SNORM,
R16_SINT,
R8_UNORM,
R8_UINT,
R8_SNORM,
R8_SINT,
A8_UNORM,
R1_UNORM,
BC1_UNORM,
BC1_UNORM_SRGB,
BC2_UNORM,
BC2_UNORM_SRGB,
BC3_UNORM,
BC3_UNORM_SRGB,
BC4_UNORM,
BC4_SNORM,
BC5_UNORM,
BC5_SNORM,
B5G6R5_UNORM,
B5G5R5A1_UNORM,
B8G8R8A8_UNORM,
B8G8R8A8_UNORM_SRGB,
EnumCount
};
}
}
|
jsbourdon/lwgl | LWGL/include/Descriptors/InputLayoutDescriptor.h | <filename>LWGL/include/Descriptors/InputLayoutDescriptor.h
#pragma once
#include <vector>
namespace lwgl
{
namespace resources
{
class Shader;
}
namespace descriptors
{
enum class InputLayoutSemantic
{
Position,
Normal,
Tangent,
UV,
Float2,
Float3,
Float4,
EnumCount
};
struct InputLayoutElement
{
InputLayoutSemantic Semantic;
uint32_t Slot;
};
struct InputLayoutDescriptor
{
std::vector<InputLayoutElement> Elements;
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/InputLayout.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class InputLayout final : public RefCountedObject<InputLayout>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
InputLayout() = default;
~InputLayout();
private:
ID3D11InputLayout* m_pLayout { nullptr };
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/RefCountedObject.h | <gh_stars>1-10
#pragma once
namespace lwgl
{
namespace resources
{
template<typename T>
class RefCountedObject
{
public:
virtual ~RefCountedObject();
uint32_t AddRef();
uint32_t Release();
protected:
typedef RefCountedObject<T> base;
RefCountedObject();
private:
uint32_t m_RefCount;
};
}
}
#include "RefCountedObject.inl" |
jsbourdon/lwgl | LWGL/include/Debugging/DebuggingFeatures.h | <filename>LWGL/include/Debugging/DebuggingFeatures.h<gh_stars>1-10
#pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace core
{
class RenderCore;
class GfxDevice;
class GfxDeviceContext;
}
namespace descriptors
{
struct SurfaceDescriptor;
}
namespace utilities
{
class Camera;
}
using namespace core;
using namespace descriptors;
using namespace utilities;
namespace debugging
{
class DebugResourceManager;
class DebuggingFeatures : RefCountedObject<DebuggingFeatures>
{
friend base;
friend class RenderCore;
public:
void DrawText(const wchar_t *pText, const RECT &pos, const Vector4 &color);
void ShowFPS(bool show);
void ShowMainCameraPosition(bool show);
private:
DebuggingFeatures();
~DebuggingFeatures();
bool Init(GfxDevice *pDevice, GfxDeviceContext *pContext);
bool OnSwapChainResized(GfxDevice *pDevice, const NativeSurfaceDescriptor *pSurfaceDesc);
void OnSwapChainReleased();
void OnUpdate(RenderCore *pCore, double fTime, float fElapsedTime);
void OnFrameRender(RenderCore *pCore, double fTime, float fElapsedTime);
void UpdateFPS(float fElapsedTimeSec);
void RenderFPS();
void RenderCameraPosition(const Camera *pCamera);
private:
static constexpr float s_FPSUpdateRateSec = 0.5f;
#ifdef _DEBUG
DebugResourceManager* m_pRscManager;
GfxDevice* m_pDevice;
GfxDeviceContext* m_pContext;
float m_AverageFPS;
float m_AccumulatedFPSElapsedTimeSec;
uint32_t m_AccumulatedFPSFrames;
bool m_ShowFPS;
bool m_ShowCameraPos;
#endif
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/RasterizerState.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class RasterizerState final : public RefCountedObject<RasterizerState>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
RasterizerState();
~RasterizerState();
private:
ID3D11RasterizerState* m_pD3DRasterizerState;
};
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/ShaderDescriptor.h | <reponame>jsbourdon/lwgl<filename>LWGL/include/Descriptors/ShaderDescriptor.h
#pragma once
namespace lwgl
{
namespace descriptors
{
enum class ShaderType
{
Unknonwn = -1,
VertexShader,
FragmentShader,
EnumCount
};
struct ShaderDescriptor
{
const wchar_t* FilePath { nullptr };
const wchar_t* BytecodeFilePath { nullptr };
const char* Code { nullptr };
const char* EntryPoint { nullptr };
const char* DebugName { nullptr };
ShaderType Type { ShaderType::Unknonwn };
};
}
} |
jsbourdon/lwgl | LWGL/include/Utilities/FixedCamera.h | #pragma once
#include "Core/RefCountedObject.h"
#include "3rd/DXUT/Optional/DXUTCamera.h"
namespace lwgl
{
using namespace core;
namespace utilities
{
class FixedCamera
{
public:
FixedCamera() = default;
~FixedCamera() = default;
void Init(const Vector4 &worldPosition, const Vector4 &lookAtWorldPosition, float fov, float aspectRatio, float nearPlane, float farPlane);
Matrix4x4 GetViewMatrix() const { return m_ViewMatrix; }
Matrix4x4 GetProjMatrix() const { return m_ProjectionMatrix; }
Vector3 GetWorldPosition() const { return m_WorldPosition; }
Vector2 GetViewSpaceZParams() const { return m_ViewSpaceZParams; }
void GetClipPlanes(float &nearClip, float &farClip) const { nearClip = m_NearPlane; farClip = m_FarPlane; }
private:
Matrix4x4 m_ViewMatrix {};
Matrix4x4 m_ProjectionMatrix {};
Vector3 m_WorldPosition {};
Vector2 m_ViewSpaceZParams {};
float m_NearPlane { 0 };
float m_FarPlane { 0 };
};
}
}
|
jsbourdon/lwgl | LWGL/include/Resources/DepthStencilState.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class DepthStencilState final : public RefCountedObject<DepthStencilState>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
DepthStencilState();
~DepthStencilState();
private:
ID3D11DepthStencilState *m_pDepthStencilState;
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/TypeDefs.h | <reponame>jsbourdon/lwgl<gh_stars>1-10
#pragma once
#include "3rd/DXUT/Core/DXUT.h"
namespace lwgl
{
namespace core
{
typedef DirectX::XMMATRIX Matrix4x4;
typedef DirectX::XMFLOAT3X3 Matrix3x3;
typedef DirectX::XMVECTORF32 Vector4;
typedef DirectX::XMFLOAT3 Vector3;
typedef DirectX::XMFLOAT2 Vector2;
typedef ID3D11Device GfxNativeDevice;
typedef ID3D11DeviceContext GfxNativeDeviceContext;
typedef DXGI_FORMAT NativePixelFormat;
typedef DXGI_SURFACE_DESC NativeSurfaceDescriptor;
}
} |
jsbourdon/lwgl | LWGL/include/Pipeline/GfxPipeline.h | #pragma once
#include "Core/RefCountedObject.h"
#include "Descriptors/PipelineDescriptor.h"
namespace lwgl
{
namespace resources
{
class InputLayout;
class Shader;
class BlendState;
class DepthStencilState;
class RasterizerState;
}
using namespace descriptors;
namespace pipeline
{
class GfxPipeline : public RefCountedObject<GfxPipeline>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
public:
void SetStencilRef(uint32_t stencilRef);
private:
GfxPipeline();
~GfxPipeline();
InputLayout* m_pInputLayout;
Shader* m_pVertexShader;
Shader* m_pFragmentShader;
BlendState* m_pBlendState;
DepthStencilState* m_pDepthStencilState;
RasterizerState* m_pRasterizerState;
uint32_t m_StencilRef;
};
}
} |
jsbourdon/lwgl | LWGL/include/Inputs/IInputReceiver.h | #pragma once
namespace lwgl
{
namespace input
{
class IInputReceiver
{
public:
virtual void OnKeyDown(uint32_t keyCode, bool firstDown) = 0;
virtual void OnKeyUp(uint32_t keyCode) = 0;
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/RenderTarget.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class Texture;
class RenderTarget final : public RefCountedObject<RenderTarget>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
RenderTarget();
~RenderTarget();
private:
Texture* m_pRenderTexture;
ID3D11RenderTargetView* m_pRenderTargetView;
};
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/DepthStencilStateDescriptor.h | <reponame>jsbourdon/lwgl
#pragma once
namespace lwgl
{
namespace descriptors
{
enum class ComparisonFunction
{
NEVER,
LESS,
EQUAL,
LESS_EQUAL,
GREATER,
NOT_EQUAL,
GREATER_EQUAL,
ALWAYS,
EnumCount
};
enum class StencilOperation
{
KEEP,
ZERO,
REPLACE,
INCR_SAT,
DECR_SAT,
INVERT,
INCR,
DECR,
EnumCount
};
struct StencilOperationDescriptor
{
StencilOperation StencilFailOp;
StencilOperation DepthFailOp;
StencilOperation DepthStencilPassOp;
ComparisonFunction Function;
};
struct DepthStencilStateDescriptor
{
StencilOperationDescriptor FrontFaceStencil;
StencilOperationDescriptor BackFaceStencil;
ComparisonFunction DepthFunction;
uint8_t StencilReadMask;
uint8_t StencilWriteMask;
bool IsDepthTestEnabled;
bool IsDepthWriteEnabled;
bool IsStencilEnabled;
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/Buffer.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace descriptors
{
enum class BufferType;
}
using namespace descriptors;
namespace resources
{
class Buffer final : public RefCountedObject<Buffer>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
Buffer();
~Buffer();
private:
ID3D11Buffer* m_pD3DBuffer;
ID3D11ShaderResourceView* m_pD3DBufferSRV;
BufferType m_BufferType;
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/SamplerState.h | <reponame>jsbourdon/lwgl
#pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class SamplerState final : public RefCountedObject<SamplerState>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
SamplerState();
~SamplerState();
ID3D11SamplerState* m_pSamplerState;
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/TextureArray.h | <gh_stars>1-10
#pragma once
#include "Resources/Texture.h"
namespace lwgl
{
namespace descriptors
{
enum class TextureType;
}
using namespace descriptors;
namespace resources
{
class TextureArray final : public Texture
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
TextureArray() = default;
~TextureArray();
private:
union
{
ID3D11RenderTargetView** m_pRTVs { nullptr };
ID3D11DepthStencilView** m_pDSVs;
};
size_t m_ArraySize { 0 };
};
}
} |
jsbourdon/lwgl | LWGL/include/Resources/Shader.h | #pragma once
#include "Core/RefCountedObject.h"
#include "Descriptors/ShaderDescriptor.h"
namespace lwgl
{
using namespace descriptors;
namespace resources
{
class Shader final : public RefCountedObject<Shader>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
Shader();
~Shader();
private:
union
{
ID3D11VertexShader* m_pVertexShader { nullptr };
ID3D11PixelShader* m_pFragmentShader;
};
ID3DBlob* m_pShaderBuffer { nullptr };
ShaderType m_Type {};
};
}
} |
jsbourdon/lwgl | LWGL/include/Utilities/Camera.h | #pragma once
#include "Core/RefCountedObject.h"
#include "3rd/DXUT/Optional/DXUTCamera.h"
namespace lwgl
{
using namespace core;
namespace utilities
{
class Camera : public RefCountedObject<Camera>
{
friend base;
friend class RenderCore;
public:
Camera();
void Init(Vector4 worldPosition, Vector4 lookAtWorldPosition, float fov, float aspectRatio, float nearPlane, float farPlane);
Matrix4x4 GetViewMatrix() const;
Matrix4x4 GetProjMatrix() const;
Vector3 GetWorldPosition() const;
Vector3 GetLookAtDirection() const;
Vector3 GetLookAtPoint() const;
Vector2 GetViewSpaceZParams() const;
void GetClipPlanes(float &near, float &far) const;
private:
~Camera();
void HandleMessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void FrameMove(float fElapsedTime);
private:
CFirstPersonCamera m_DXUTCamera;
};
}
}
|
jsbourdon/lwgl | LWGL/include/Core/GfxDeviceContext.h | #pragma once
#include "Core/Constants.h"
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace descriptors
{
struct ClearDescriptor;
}
namespace resources
{
class Mesh;
class Buffer;
class SamplerState;
class Texture;
class TextureArray;
class Shader;
class InputLayout;
}
namespace pipeline
{
class GfxPipeline;
}
using namespace descriptors;
using namespace resources;
using namespace pipeline;
namespace core
{
enum class Stage
{
IA,
VS,
RS,
PS,
OM
};
enum class MapType
{
Read,
Write,
ReadWrite,
WriteDiscard,
WriteNoOverwrite
};
class GfxDeviceContext : public RefCountedObject<GfxDeviceContext>
{
friend base;
public:
GfxDeviceContext(ID3D11DeviceContext* d3dContext);
GfxNativeDeviceContext* GetNativeContext();
void SetupPipeline(GfxPipeline *pPipeline);
void DrawMesh(Mesh *mesh);
void DrawFullScreenTriangle();
void* MapBuffer(Buffer *pBuffer, MapType mapType);
void UnmapBuffer(Buffer *pBuffer);
void BindBuffer(const Buffer *pBuffer, Stage stage, uint32_t slot);
void BindTexture(const Texture *pTexture, Stage stage, uint32_t slot);
void BindSampler(SamplerState *pSampler, Stage stage, uint32_t slot);
void BindSwapChainDepthStencilToStage(Stage stage, uint32_t slot);
void BindSwapChain(bool bindDepthStencil = true);
void Unbind(Stage stage, uint32_t slot);
void UnbindRange(Stage stage, uint32_t slot, uint32_t count);
void BindRenderTargets(Texture *pRenderTargets[], uint32_t renderTargetCount, bool bindDepthStencil = true);
void BindRenderTargets(Texture *pRenderTargets[], uint32_t renderTargetCount, Texture *pDepthBuffer);
void BindRenderTargets(Texture *pRenderTargets[], uint32_t renderTargetCount, TextureArray *pDepthBuffer, uint32_t depthArrayIndex);
void BindRenderTargets(TextureArray *pRenderTargets, uint32_t rtStartIndex, uint32_t renderTargetCount, TextureArray *pDepthBuffer, uint32_t depthArrayIndex);
void BindRenderTargets(Texture *pRenderTargets[], uint32_t renderTargetCount, ID3D11DepthStencilView *pDepthBuffer);
void SetViewport(float width, float height);
void Clear(const ClearDescriptor &desc);
void SetSwapChainDepthStencil(Texture *pDepthStencil);
void SetFullScreenTriangleResources(Shader *pShader, InputLayout *pLayout);
private:
~GfxDeviceContext();
void BindBufferToVSStage(const Buffer *pBuffer, uint32_t slot);
void BindBufferToPSStage(const Buffer *pBuffer, uint32_t slot);
void UnbindRenderTargets();
void SetDepthStencil(Texture *pTexture, uint32_t arrayIndex = 0);
void SetViewport(Texture *pTexture);
static const D3D11_MAP s_MapTypes[];
static void* s_pNullResources[lwgl::core::MAX_SHADERRESOURCE_COUNT];
ID3D11DeviceContext* m_pD3DContext { nullptr };
GfxPipeline* m_pCurrentPipeline { nullptr };
Texture* m_pRenderTargets[lwgl::core::MAX_RENDERTARGET_COUNT] {};
Texture* m_pSwapChainDepthStencil { nullptr };
Texture* m_pCurrentDepthStencil { nullptr };
Shader* m_pFullScreenTriangleVS { nullptr };
InputLayout* m_pFullScreenTiangleInputLayout { nullptr };
uint32_t m_RenderTargetCount { 0 };
uint32_t m_DepthStencilArrayIndex { 0 };
};
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/SurfaceDescriptor.h | <reponame>jsbourdon/lwgl
#pragma once
namespace lwgl
{
namespace descriptors
{
enum class PixelFormat;
struct SurfaceDescriptor
{
uint32_t Width;
uint32_t Height;
uint32_t SampleCount;
PixelFormat Format;
};
}
} |
jsbourdon/lwgl | LWGL/include/Debugging/DebugResourceManager.h | <gh_stars>1-10
#pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace descriptors
{
enum class PixelFormat;
struct SurfaceDescriptor;
}
using namespace core;
using namespace descriptors;
namespace debugging
{
class DebugResourceManager : public RefCountedObject<DebugResourceManager>
{
friend base;
friend class DebuggingFeatures;
void SetupDrawTextResources(GfxNativeDeviceContext *pContext);
void CleanDrawTextResources(GfxNativeDevice *pDevice, GfxNativeDeviceContext *pContext);
void GetBackBufferSize(uint32_t &width, uint32_t &height);
private:
DebugResourceManager() = default;
~DebugResourceManager();
bool Init(GfxNativeDevice *pDevice, GfxNativeDeviceContext *pContext);
bool OnSwapChainResized(GfxNativeDevice *pDevice, const NativeSurfaceDescriptor *pSurfaceDesc);
void OnSwapChainReleased();
public:
private:
CDXUTDialogResourceManager m_DXUTRscManager {};
};
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/ClearDescriptor.h | #pragma once
namespace lwgl
{
using namespace core;
namespace descriptors
{
struct ClearDescriptor
{
Vector4 ColorClearValue;
float DepthClearValue;
uint8_t StencilClearValue;
bool ClearColor;
bool ClearDepth;
bool ClearStencil;
};
}
} |
jsbourdon/lwgl | LWGL/include/Core/GfxDevice.h | #pragma once
#include "RefCountedObject.h"
namespace lwgl
{
namespace pipeline
{
class GfxPipeline;
}
namespace resources
{
class Mesh;
class Buffer;
class Shader;
class BlendState;
class InputLayout;
class DepthStencilState;
class Texture;
class TextureArray;
class SamplerState;
class RasterizerState;
}
namespace descriptors
{
struct ShaderDescriptor;
struct BlendStateDescriptor;
struct DepthStencilStateDescriptor;
struct PipelineDescriptor;
struct InputLayoutDescriptor;
struct InputLayoutElement;
struct BufferDescriptor;
struct TextureDescriptor;
struct SamplerStateDescriptor;
struct RasterizerStateDescriptor;
enum class InputLayoutSemantic;
enum class PixelFormat;
}
using namespace resources;
using namespace descriptors;
using namespace pipeline;
namespace core
{
class GfxDevice : public RefCountedObject<GfxDevice>
{
friend base;
public:
GfxDevice(ID3D11Device* d3dDevice);
GfxNativeDevice* GetNativeDevice();
GfxPipeline* CreatePipeline(const PipelineDescriptor &desc);
Mesh* CreateMesh(const wchar_t *filePath);
Buffer* CreateBuffer(const BufferDescriptor &desc);
Texture* CreateTexture(const TextureDescriptor &desc);
TextureArray* CreateTextureArray(const TextureDescriptor &desc);
SamplerState* CreateSamplerState(const SamplerStateDescriptor &desc);
Shader* CreateShader(const ShaderDescriptor &desc);
InputLayout* CreateInputLayout(const InputLayoutDescriptor &desc, Shader *pInputSignatureShader);
static NativePixelFormat ConvertToNativePixelFormat(PixelFormat format);
private:
~GfxDevice();
BlendState* CreateBlendState(const BlendStateDescriptor &desc);
DepthStencilState* CreateDepthStencilState(const DepthStencilStateDescriptor &desc);
RasterizerState* CreateRasterizerState(const RasterizerStateDescriptor &desc);
template<typename T> T* CreateTextureCore(const TextureDescriptor &desc);
Texture* CreateTextureViews(Texture *pTexture, const TextureDescriptor &desc);
TextureArray* CreateTextureViews(TextureArray *pTexture, const TextureDescriptor &desc);
static void AddInputLayoutElement(const InputLayoutElement &element, std::vector<D3D11_INPUT_ELEMENT_DESC> &elements);
static uint32_t GetInputLayoutSemanticIndex(InputLayoutSemantic elementSemantic, const std::vector<D3D11_INPUT_ELEMENT_DESC> &elements);
static uint32_t GetInputLayoutElementAlignedByteOffset(InputLayoutSemantic elementSemantic, const std::vector<D3D11_INPUT_ELEMENT_DESC> &elements);
private:
static const char *const s_ShaderModels[];
static const DXGI_FORMAT s_PixelFormats[];
static const D3D11_BLEND s_BlendValues[];
static const D3D11_BLEND_OP s_BlendOperations[];
static const LPCSTR s_SemanticNames[];
static const DXGI_FORMAT s_InputLayoutFormats[];
static const D3D11_STENCIL_OP s_StencilOps[];
static const D3D11_COMPARISON_FUNC s_ComparisonFuncs[];
static const uint32_t s_BufferBindFlags[];
static const uint32_t s_CPUAccessFlags[];
static const D3D11_USAGE s_ResourceUsages[];
static const D3D11_USAGE s_TextureUsages[];
static const D3D11_CULL_MODE s_CullModes[];
ID3D11Device* m_pD3DDevice;
};
}
} |
jsbourdon/lwgl | LWGL/include/pch.h | <reponame>jsbourdon/lwgl
#pragma once
#pragma comment( lib, "Usp10.lib" )
#define DXUT_AUTOLIB
#include <cstdint>
#include <malloc.h>
#include <assert.h>
#include <d3dcompiler.h>
#include "3rd/DXUT/Core/DXUT.h"
#include "3rd/DXUT/Optional/SDKmisc.h"
#include "3rd/DXUT/Optional/DXUTgui.h"
#include "Core/Macros.h"
#include "Core/TypeDefs.h"
#include "Core/Constants.h"
#include "Core/Globals.h"
|
jsbourdon/lwgl | LWGL/include/Resources/BlendState.h | #pragma once
#include "Core/RefCountedObject.h"
namespace lwgl
{
namespace resources
{
class BlendState final : public RefCountedObject<BlendState>
{
friend base;
friend class GfxDevice;
friend class GfxDeviceContext;
private:
BlendState();
~BlendState();
private:
ID3D11BlendState* m_pBlendState;
};
}
} |
jsbourdon/lwgl | LWGL/include/Descriptors/PipelineDescriptor.h | <filename>LWGL/include/Descriptors/PipelineDescriptor.h
#pragma once
#include "InputLayoutDescriptor.h"
#include "BlendStateDescriptor.h"
#include "ShaderDescriptor.h"
#include "DepthStencilStateDescriptor.h"
#include "RasterizerStateDescriptor.h"
#include "PixelFormats.h"
namespace lwgl
{
using namespace resources;
namespace descriptors
{
struct PipelineDescriptor
{
static constexpr size_t s_OMMaxRenderTargetCount = 8;
InputLayoutDescriptor InputLayout {};
ShaderDescriptor VertexShader { nullptr, nullptr, nullptr, nullptr, nullptr, ShaderType::VertexShader };
ShaderDescriptor FragmentShader { nullptr, nullptr, nullptr, nullptr, nullptr, ShaderType::FragmentShader };
BlendStateDescriptor BlendState {};
DepthStencilStateDescriptor DepthStencilState {};
RasterizerStateDescriptor RasterizerState {};
PixelFormat RenderTargetFormats[s_OMMaxRenderTargetCount] {};
PixelFormat DepthFormat {};
};
}
}
|
Piascore/onedrive-sdk-ios | Examples/iOSExplorer/iOSExplorer/iOSExplorer-Bridging-Header.h | <gh_stars>0
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "ODXItemCollectionViewController.h"
#import <OneDriveSDK/OneDriveSDK.h>
|
RogerNogue/MVJ_Engine_base | QuadTreeGnoblin.h | <filename>QuadTreeGnoblin.h
#ifndef __QuadTreeGnoblin_H__
#define __QuadTreeGnoblin_H__
#include "MathGeoLib/include/Geometry/AABB.h"
#include <vector>
class GameObject;
class QuadNode;
class QuadTreeGnoblin
{
public:
QuadTreeGnoblin();
~QuadTreeGnoblin();
void Create(AABB limits);
void Clear();
void Insert(GameObject* obj);
void CollectIntersect(std::vector<GameObject*>& objects, QuadNode& node);
void DrawQuadTree();
//variables
bool active = false;
QuadNode* rootNode = nullptr;
};
#endif
|
RogerNogue/MVJ_Engine_base | ComponentMaterial.h | <reponame>RogerNogue/MVJ_Engine_base<gh_stars>0
#ifndef __ComponentMaterial_H__
#define __ComponentMaterial_H__
#include "Component.h"
#include "MathGeoLib.h"
class JSON_Value;
class ComponentMaterial :
public Component
{
public:
ComponentMaterial(GameObject* dad);
ComponentMaterial(JSON_Value* matFile, GameObject* dad);
~ComponentMaterial();
bool CleanUp() override;
void saveMaterial(JSON_Value* val);
void setPath(const char* path);
//data structures
struct myMaterial {
unsigned texture0 = 0;
float sizeX = 0;
float sizeY = 0;
};
struct mySurface {
math::float4 ambientColor = math::float4(0, 0, 0, 1);
math::float4 difuseColor = math::float4(93, 154, 252, 1);
math::float4 specularColor = math::float4(0, 0, 0, 1);
math::float4 emisiveColor = math::float4(0, 0, 0, 1);
unsigned program = 0;
};
//vars
myMaterial material;
mySurface surface;
float k_specular = 0.6f;
float shininess = 64.0f;
float k_diffuse = 0.5f;
float k_ambient = 1.0f;
int numModel = 0;
int numMaterial = 0;
bool isTexture = true;
const char* path = "";
};
#endif |
RogerNogue/MVJ_Engine_base | ComponentTransform.h | #ifndef __ComponentTransform_H__
#define __ComponentTransform_H__
#include "Component.h"
#include "MathGeoLib.h"
class JSON_Value;
class ComponentTransform :
public Component
{
public:
ComponentTransform(GameObject* dad);
ComponentTransform(JSON_Value* transfFile, GameObject* dad);
~ComponentTransform();
update_status Update() override;
void UpdateFromGuizmo();
void placeAt000();
void saveTransform(JSON_Value* val);
void setValues(math::float4x4 newMat);
//variables
bool objectMoved = false;
math::float3 positionValues = math::float3(0, 0, 0);
math::float3 rotationValues = math::float3(0, 0, 0);
math::float3 scaleValues = math::float3 (1,1,1);
math::float4x4 transformMatrix = math::float4x4::identity;
};
#endif
|
RogerNogue/MVJ_Engine_base | ModuleProgram.h | #ifndef __ModuleProgram_H__
#define __ModuleProgram_H__
#include "Module.h"
#include "GL/glew.h"
class ModuleProgram :
public Module
{
public:
ModuleProgram();
~ModuleProgram();
bool Init() override;
GLuint loadShaders(char* dataVertex, char* dataFragment);
GLuint programTexture;
GLuint programGeometry;
GLuint programBlinnPhong;
GLuint programBlinnPhongTexture;
};
#endif |
RogerNogue/MVJ_Engine_base | ModuleModelLoader.h | <reponame>RogerNogue/MVJ_Engine_base<filename>ModuleModelLoader.h
#ifndef __ModuleModelLoader_H__
#define __ModuleModelLoader_H__
#include "Module.h"
#include <vector>
//#include "MathGeoLib.h"
class aiScene;
class aiMesh;
class aiMaterial;
class ComponentMesh;
class ComponentMaterial;
class ComponentShape;
class GameObject;
struct par_shapes_mesh;
class ModuleModelLoader :
public Module
{
public:
ModuleModelLoader();
~ModuleModelLoader();
void loadModel(unsigned model, GameObject* object);
void loadModelFromPath(const char* path);
void unloadModels();
void deleteVBO(unsigned vbo);
void deleteVIO(unsigned vio);
void unloadTexture(unsigned tex0);
bool CreateSphere(GameObject* object);
bool CreateCube(GameObject* object);
bool CreateCylinder(GameObject* object);
bool CreateTorus(GameObject* object);
bool LoadSphere(ComponentShape* sphere, bool newSphere);
bool LoadCube(ComponentShape* cube, bool newCube);
bool LoadCylinder(ComponentShape* cylinder, bool newCylinder);
bool LoadTorus(ComponentShape* torus, bool newTorus);
void GenerateOneMeshData(ComponentMesh* newMesh);
void GenerateOneMaterialData(ComponentMaterial* newMaterial);
void loadDroppedFile(char* path);
//variables
unsigned currentModel = 0;
int currentModelTriangleCount = 0;
std::vector<ComponentMesh*> allMeshes;
std::vector<ComponentShape*> allShapes;
private:
//const aiScene* scene;
void GenerateMeshData(const aiMesh* mesh, GameObject* Obj, int numMesh, int numModel, const char* path);
void GenerateMaterialData(const aiMaterial* mat, GameObject* Obj, int model, int i, const char* path);
void generateShape(par_shapes_mesh* shape, ComponentShape* comp, ComponentMaterial* mat, bool isNew);
void LoadMaterialFromPath(const char* path, int model);
//variables
};
#endif |
RogerNogue/MVJ_Engine_base | ComponentMesh.h | #ifndef __ComponentMesh_H__
#define __ComponentMesh_H__
#include "Component.h"
#include "MathGeoLib.h"
class JSON_Value;
class ComponentMesh :
public Component
{
public:
ComponentMesh(GameObject* dad);
ComponentMesh(JSON_Value* mesh, GameObject* dad);
~ComponentMesh();
bool CleanUp() override;
void saveMesh(JSON_Value* val);
void setPath(const char* path);
//data structures
struct myMesh {
unsigned vbo = 0;
unsigned vio = 0;
unsigned material = 0;
unsigned numVertices = 0;
unsigned numIndices = 0;
unsigned normalsOffset = 0;
unsigned texCoordsOffset = 0;
bool normals = false;
};
//vars
myMesh mesh;
float ambient = 0.3f;
int numModel = 0;
int numMesh = 0;
const char* path = "";
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.