repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
yoursunny/carepo
|
repo/ndnr_store.h
|
/**
* @file ndnr_store.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_STORE_DEFINED
#define NDNR_STORE_DEFINED
#include <ndn/ndn.h>
#include <ndn/hashtb.h>
#include "ndnr_private.h"
void r_store_init(struct ndnr_handle *h);
int r_store_final(struct ndnr_handle *h, int stable);
void r_store_set_content_timer(struct ndnr_handle *h,struct content_entry *content,struct ndn_parsed_ContentObject *pco);
void r_store_mark_stale(struct ndnr_handle *h,struct content_entry *content);
struct content_entry *r_store_next_child_at_level(struct ndnr_handle *h,struct content_entry *content,int level);
struct content_entry *r_store_content_next(struct ndnr_handle *h,struct content_entry *content);
int r_store_content_matches_interest_prefix(struct ndnr_handle *h,struct content_entry *content,const unsigned char *interest_msg, size_t interest_size);
struct content_entry *r_store_find_first_match_candidate(struct ndnr_handle *h,const unsigned char *interest_msg,const struct ndn_parsed_interest *pi);
ndnr_cookie r_store_enroll_content(struct ndnr_handle *h,struct content_entry *content);
struct content_entry *r_store_content_from_accession(struct ndnr_handle *h, ndnr_accession accession);
struct content_entry *r_store_content_from_cookie(struct ndnr_handle *h, ndnr_cookie cookie);
struct content_entry *r_store_lookup(struct ndnr_handle *h, const unsigned char *msg, const struct ndn_parsed_interest *pi, struct ndn_indexbuf *comps);
struct content_entry *r_store_lookup_ndnb(struct ndnr_handle *h, const unsigned char *namish, size_t size);
int r_store_content_field_access(struct ndnr_handle *h, struct content_entry *content, enum ndn_dtag dtag, const unsigned char **bufp, size_t *sizep);
void r_store_send_content(struct ndnr_handle *h, struct fdholder *fdholder, struct content_entry *content);
int r_store_name_append_components(struct ndn_charbuf *dst, struct ndnr_handle *h, struct content_entry *content, int skip, int count);
int r_store_content_flags(struct content_entry *content);
int r_store_content_change_flags(struct content_entry *content, int set, int clear);
int r_store_commit_content(struct ndnr_handle *h, struct content_entry *content);
void r_store_forget_content(struct ndnr_handle *h, struct content_entry **pentry);
void ndnr_debug_content(struct ndnr_handle *h, int lineno, const char *msg,
struct fdholder *fdholder,
struct content_entry *content);
int r_store_set_accession_from_offset(struct ndnr_handle *h, struct content_entry *content, struct fdholder *fdholder, off_t offset);
int r_store_content_trim(struct ndnr_handle *h, struct content_entry *content);
void r_store_trim(struct ndnr_handle *h, unsigned long limit);
ndnr_cookie r_store_content_cookie(struct ndnr_handle *h, struct content_entry *content);
ndnr_accession r_store_content_accession(struct ndnr_handle *h, struct content_entry *content);
const unsigned char *r_store_content_base(struct ndnr_handle *h, struct content_entry *content);
size_t r_store_content_size(struct ndnr_handle *h, struct content_entry *content);
void r_store_index_needs_cleaning(struct ndnr_handle *h);
struct ndn_charbuf *r_store_content_flatname(struct ndnr_handle *h, struct content_entry *content);
#endif
|
yoursunny/carepo
|
repo/ndnr_main.c
|
/**
* @file ndnr_main.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2009-2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <signal.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "ndnr_private.h"
#include "ndnr_init.h"
#include "ndnr_dispatch.h"
#include "ndnr_msg.h"
#include "ndnr_stats.h"
static int
stdiologger(void *loggerdata, const char *format, va_list ap)
{
FILE *fp = (FILE *)loggerdata;
return(vfprintf(fp, format, ap));
}
static struct ndnr_handle *global_h = NULL;
static void
handle_signal(int sig)
{
if (global_h != NULL)
global_h->running = 0;
signal(sig, SIG_DFL);
}
/**
* NDNR Usage message
*/
static const char *ndnr_usage_message =
"ndnr - NDNx Repository Daemon\n"
" options: none\n"
" arguments: none\n"
" configuration (via $NDNR_DIRECTORY/config or environment):\n"
" NDNR_DEBUG=WARNING\n"
" Debug logging level:\n"
" NONE - no messages\n"
" SEVERE - severe, probably fatal, errors\n"
" ERROR - errors\n"
" WARNING - warnings\n"
" INFO - informational messages\n"
" FINE, FINER, FINEST - debugging/tracing\n"
" NDNR_DIRECTORY=.\n"
" Directory where ndnr data is kept\n"
" Defaults to current directory\n"
" Ignored in config file\n"
" NDNR_GLOBAL_PREFIX=ndn:/named-data.net/ndn/Repos\n"
" NDNx URI representing the prefix where data/policy.xml is stored.\n"
" Only meaningful if no policy file exists at startup.\n"
" NDNR_START_WRITE_SCOPE_LIMIT=3\n"
" 0..3 (default 3) Process start-write(-checked) interests with a scope\n"
" not exceeding the given value. 0 is effectively read-only. 3 indicates unlimited.\n"
" NDNR_BTREE_MAX_FANOUT=1999\n"
" 4..9999 (default 1999) Maximum number of entries within a node.\n"
" NDNR_BTREE_MAX_LEAF_ENTRIES=1999\n"
" 4..9999 (default 1999) Maximum number of entries within a node at level 0.\n"
" NDNR_BTREE_MAX_NODE_BYTES=2097152\n"
" 1024..8388608 (default 2097152) Maximum node size (bytes).\n"
" NDNR_BTREE_NODE_POOL=512\n"
" 16..2000000 (default 512) Maximum number of btree nodes in memory.\n"
" NDNR_CONTENT_CACHE=4201\n"
" 16..2000000 (default 4201) Maximum number of ContentObjects cached in memory.\n"
" NDNR_MIN_SEND_BUFSIZE=16384\n"
" Minimum in bytes for output socket buffering.\n"
" NDNR_PROTO=unix\n"
" Specify 'tcp' to connect to ndnd using tcp instead of unix ipc.\n"
" NDNR_LISTEN_ON=\n"
" List of ip addresses to listen on for status; defaults to localhost addresses.\n"
" NDNR_STATUS_PORT=\n"
" Port to use for status server; default is to not serve status.\n"
" NDNS_DEBUG=WARNING\n"
" Same values as for NDNR_DEBUG.\n"
" NDNS_ENABLE=1\n"
" Disable (0) or enable (1, default) Sync processing.\n"
" NDNS_REPO_STORE=1\n"
" Disable (0) or enable (1, default) storing Sync state in repository.\n"
" NDNS_STABLE_ENABLED=1\n"
" Disable (0) or enable (1, default) storing Sync stable-points to repository.\n"
" NDNS_FAUX_ERROR=0\n"
" Disable (0, default) or enable (1-99) percent simulated random packet loss.\n"
" NDNS_HEARTBEAT_MICROS=200000\n"
" 100000..10000000 (default 200000) microseconds between Sync heartbeats.\n"
" NDNS_ROOT_ADVISE_FRESH=4\n"
" 1..30 (default 4) freshness (seconds) for Sync root advise response.\n"
" NDNS_ROOT_ADVISE_LIFETIME=20\n"
" 1..30 (default 20) lifetime (seconds) for Sync root advise response.\n"
" NDNS_NODE_FETCH_LIFETIME=4\n"
" 1..30 (default 4) lifetime (seconds) for Sync node fetch response.\n"
" NDNS_MAX_FETCH_BUSY=6\n"
" 1..100 (default 6) maximum simultaneous node or content fetches per Sync root.\n"
" NDNS_MAX_COMPARES_BUSY=4\n"
" 1..100 (default 4) maximum simultaneous Sync roots in compare state.\n"
" NDNS_NOTE_ERR=0\n"
" Disable (0, default) or enable (1) exceptional Sync error reporting.\n"
" NDNS_SYNC_SCOPE=2\n"
" The default (2) restricts sync traffic to directly connected peers,\n"
" which requires sync to be running on all nodes. Set to 3 to permit\n"
" forwarding of sync traffic.\n"
;
int
main(int argc, char **argv)
{
int s;
if (argc > 1) {
fprintf(stderr, "%s", ndnr_usage_message);
exit(1);
}
signal(SIGPIPE, SIG_IGN);
global_h = r_init_create(argv[0], stdiologger, stderr);
if (global_h == NULL)
exit(1);
signal(SIGINT, &handle_signal);
signal(SIGTERM, &handle_signal);
signal(SIGXFSZ, &handle_signal);
r_dispatch_run(global_h);
s = (global_h->running != 0);
ndnr_msg(global_h, "exiting.");
r_init_destroy(&global_h);
exit(s);
}
|
yoursunny/carepo
|
segment/metadata.h
|
#ifndef CAREPO_SEGMENT_METADATA_H_
#define CAREPO_SEGMENT_METADATA_H_
#include "segment.h"
void segment_list_to_metadata(const struct segment_list* self, struct ndn_charbuf* c);
struct segment_list* segment_list_from_metadata(const uint8_t* buf, size_t sz);
#endif//CAREPO_SEGMENT_METADATA_H_
|
yoursunny/carepo
|
repo/ndnr_sync.c
|
/**
* @file ndnr_sync.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <ndn/btree.h>
#include <ndn/btree_content.h>
#include <ndn/ndn.h>
#include <ndn/charbuf.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <sync/SyncBase.h>
#include "ndnr_private.h"
#include "ndnr_dispatch.h"
#include "ndnr_io.h"
#include "ndnr_link.h"
#include "ndnr_msg.h"
#include "ndnr_proto.h"
#include "ndnr_store.h"
#include "ndnr_sync.h"
#include "ndnr_util.h"
#include <sync/sync_plumbing.h>
#ifndef NDNLINT
/* Preliminary implementation - algorithm may change */
PUBLIC uintmax_t
ndnr_accession_encode(struct ndnr_handle *ndnr, ndnr_accession a)
{
return(a);
}
PUBLIC ndnr_accession
ndnr_accession_decode(struct ndnr_handle *ndnr, uintmax_t encoded)
{
return(encoded);
}
PUBLIC int
ndnr_accession_compare(struct ndnr_handle *ndnr, ndnr_accession x, ndnr_accession y)
{
if (x > y) return 1;
if (x == y) return 0;
if (x < y) return -1;
return NDNR_NOT_COMPARABLE;
}
PUBLIC uintmax_t
ndnr_hwm_encode(struct ndnr_handle *ndnr, ndnr_hwm hwm)
{
return(hwm);
}
PUBLIC ndnr_hwm
ndnr_hwm_decode(struct ndnr_handle *ndnr, uintmax_t encoded)
{
return(encoded);
}
PUBLIC int
ndnr_acc_in_hwm(struct ndnr_handle *ndnr, ndnr_accession a, ndnr_hwm hwm)
{
return(a <= hwm);
}
PUBLIC ndnr_hwm
ndnr_hwm_update(struct ndnr_handle *ndnr, ndnr_hwm hwm, ndnr_accession a)
{
return(a <= hwm ? hwm : a);
}
PUBLIC ndnr_hwm
ndnr_hwm_merge(struct ndnr_handle *ndnr, ndnr_hwm x, ndnr_hwm y)
{
return(x < y ? y : x);
}
PUBLIC int
ndnr_hwm_compare(struct ndnr_handle *ndnr, ndnr_hwm x, ndnr_hwm y)
{
if (x > y) return 1;
if (x == y) return 0;
if (x < y) return -1;
return NDNR_NOT_COMPARABLE;
}
#endif
/**
* A wrapper for ndnr_msg that takes a sync_plumbing instead of ndnr_handle
*/
PUBLIC void
r_sync_msg(struct sync_plumbing *sdd,
const char *fmt, ...)
{
struct ndnr_handle *ndnr = (struct ndnr_handle *)sdd->client_data;
va_list ap;
va_start(ap, fmt);
ndnr_vmsg(ndnr, fmt, ap);
va_end(ap);
}
PUBLIC int
r_sync_fence(struct sync_plumbing *sdd,
uint64_t seq_num)
{
struct ndnr_handle *h = (struct ndnr_handle *)sdd->client_data;
// TODO: this needs to do something more interesting.
ndnr_msg(h, "r_sync_fence: seq_num %ju", seq_num);
h->notify_after = (ndnr_accession) seq_num;
return (0);
}
/**
* A wrapper for the sync_notify method that takes a content entry.
*/
PUBLIC int
r_sync_notify_content(struct ndnr_handle *ndnr, int e, struct content_entry *content)
{
struct sync_plumbing *sync_plumbing = ndnr->sync_plumbing;
int res;
ndnr_accession acc = NDNR_NULL_ACCESSION;
if (sync_plumbing == NULL)
return (0);
if (content == NULL) {
if (e == 0)
abort();
res = sync_plumbing->sync_methods->sync_notify(ndnr->sync_plumbing, NULL, e, 0);
if (res < 0)
ndnr_msg(ndnr, "sync_notify(..., NULL, %d, 0) returned %d, expected >= 0",
e, res);
}
else {
struct ndn_charbuf *cb = r_util_charbuf_obtain(ndnr);
acc = r_store_content_accession(ndnr, content);
if (acc == NDNR_NULL_ACCESSION) {
ndnr_debug_content(ndnr, __LINE__, "r_sync_notify_content - not yet stable", NULL, content);
return(0);
}
/* This must get the full name, including digest. */
ndn_name_init(cb);
res = r_store_name_append_components(cb, ndnr, content, 0, -1);
if (res < 0) abort();
if (NDNSHOULDLOG(ndnr, r_sync_notify_content, NDNL_FINEST))
ndnr_debug_content(ndnr, __LINE__, "r_sync_notify_content", NULL, content);
res = sync_plumbing->sync_methods->sync_notify(ndnr->sync_plumbing, cb, e, acc);
r_util_charbuf_release(ndnr, cb);
}
if (NDNSHOULDLOG(ndnr, r_sync_notify_content, NDNL_FINEST))
ndnr_msg(ndnr, "sync_notify(..., %d, 0x%jx, ...) returned %d",
e, ndnr_accession_encode(ndnr, acc), res);
if (e == 0 && res == -1) {
// TODO: wrong in new sync interface terms
//r_sync_notify_after(ndnr, NDNR_MAX_ACCESSION); // XXXXXX should be hwm
}
return(res);
}
/**
* State for an ongoing sync enumeration.
*/
struct sync_enumeration_state {
int magic; /**< for sanity check - should be se_cookie */
int index; /**< Index into ndnr->active_enum */
ndnr_cookie cookie; /**< Resumption point */
struct ndn_parsed_interest parsed_interest;
struct ndn_charbuf *interest;
struct ndn_indexbuf *comps;
};
static const int se_cookie = __LINE__;
static struct sync_enumeration_state *
cleanup_se(struct ndnr_handle *ndnr, struct sync_enumeration_state *md)
{
if (md != NULL && md->magic == se_cookie) {
int i = md->index;
if (NDNSHOULDLOG(ndnr, cleanup_se, NDNL_FINEST))
ndnr_msg(ndnr, "sync_enum_cleanup %d", i);
if (0 < i && i < NDNR_MAX_ENUM)
ndnr->active_enum[i] = NDNR_NULL_ACCESSION;
ndn_indexbuf_destroy(&md->comps);
ndn_charbuf_destroy(&md->interest);
free(md);
}
return(NULL);
}
static int
r_sync_enumerate_action(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
struct sync_enumeration_state *md = NULL;
struct content_entry *content = NULL;
struct ndn_btree_node *leaf = NULL;
struct ndn_charbuf *interest = NULL;
struct ndn_parsed_interest *pi = NULL;
struct ndn_charbuf *scratch = NULL;
struct ndn_charbuf *flat = NULL;
int ndx;
int res;
int try;
int matches;
md = ev->evdata;
if (md->magic != se_cookie || md->index >= NDNR_MAX_ENUM) abort();
if ((flags & NDN_SCHEDULE_CANCEL) != 0) {
ev->evdata = cleanup_se(ndnr, md);
return(0);
}
pi = &md->parsed_interest;
interest = md->interest;
/*
* Recover starting point from either cookie or accession.
*
* The accession number might not be available yet (but we try to avoid
* suspending in such a case).
* The cookie might go away, but only if the content has been accessioned.
*/
content = r_store_content_from_cookie(ndnr, md->cookie);
if (content == NULL && md->cookie != 0)
content = r_store_content_from_accession(ndnr, ndnr->active_enum[md->index]);
for (try = 0, matches = 0; content != NULL; try++) {
if (scratch == NULL)
scratch = ndn_charbuf_create();
flat = r_store_content_flatname(ndnr, content);
res = ndn_btree_lookup(ndnr->btree, flat->buf, flat->length, &leaf);
if (NDN_BT_SRCH_FOUND(res) == 0) {
ndnr_debug_content(ndnr, __LINE__, "impossible", NULL, content);
break;
}
ndx = NDN_BT_SRCH_INDEX(res);
res = ndn_btree_match_interest(leaf, ndx, interest->buf, pi, scratch);
if (res == -1) {
ndnr_debug_content(ndnr, __LINE__, "impossible", NULL, content);
break;
}
if (res == 1) {
res = r_sync_notify_content(ndnr, md->index, content);
matches++;
if (res == -1) {
if (NDNSHOULDLOG(ndnr, r_sync_enumerate_action, NDNL_FINEST))
ndnr_debug_content(ndnr, __LINE__, "r_sync_enumerate_action", NULL,
content);
ev->evdata = cleanup_se(ndnr, md);
ndn_charbuf_destroy(&scratch);
return(0);
}
}
content = r_store_content_next(ndnr, content);
if (content != NULL &&
!r_store_content_matches_interest_prefix(ndnr, content,
interest->buf,
interest->length))
content = NULL;
if (content != NULL) {
md->cookie = r_store_content_cookie(ndnr, content);
ndnr->active_enum[md->index] = r_store_content_accession(ndnr, content);
if (ndnr->active_enum[md->index] != NDNR_NULL_ACCESSION &&
(matches >= 8 || try >= 200)) { // XXX - these numbers need tuning
ndn_charbuf_destroy(&scratch);
return(300);
}
}
}
r_sync_notify_content(ndnr, md->index, NULL);
ev->evdata = cleanup_se(ndnr, md);
ndn_charbuf_destroy(&scratch);
return(0);
}
/**
* Request that a SyncNotifyContent call be made for each content object
* in the repository that matches the interest.
*
* If SyncNotifyContent returns -1 the active enumeration will be cancelled.
*
* When there are no more matching objects, SyncNotifyContent will be called
* passing NULL for name.
*
* Content objects that arrive during an enumeration may or may not be included
* in that enumeration.
*
* @returns -1 for error, or an enumeration number which will also be passed
* in the SyncNotifyContent
*/
PUBLIC int
r_sync_enumerate(struct sync_plumbing *sdd,
struct ndn_charbuf *interest)
{
struct ndnr_handle *ndnr = (struct ndnr_handle *)sdd->client_data;
int ans = -1;
int i;
int res;
struct ndn_indexbuf *comps = NULL;
struct ndn_parsed_interest parsed_interest = {0};
struct ndn_parsed_interest *pi = &parsed_interest;
struct content_entry *content = NULL;
struct sync_enumeration_state *md = NULL;
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_FINEST))
ndnr_debug_ndnb(ndnr, __LINE__, "sync_enum_start", NULL,
interest->buf, interest->length);
comps = ndn_indexbuf_create();
res = ndn_parse_interest(interest->buf, interest->length, pi, comps);
if (res < 0) {
ndnr_debug_ndnb(ndnr, __LINE__, "bogus r_sync_enumerate request", NULL,
interest->buf, interest->length);
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_FINEST)) {
struct ndn_charbuf *temp = ndn_charbuf_create();
ndn_charbuf_putf(temp, "interest_dump ");
for (i = 0; i < interest->length; i++)
ndn_charbuf_putf(temp, "%02X", interest->buf[i]);
ndnr_msg(ndnr, ndn_charbuf_as_string(temp));
ndn_charbuf_destroy(&temp);
}
goto Bail;
}
/* 0 is for notify_after - don't allocate it here. */
for (i = 1; i < NDNR_MAX_ENUM; i++) {
if (ndnr->active_enum[i] == NDNR_NULL_ACCESSION) {
ans = i;
ndnr->active_enum[ans] = NDNR_MAX_ACCESSION; /* for no-match case */
break;
}
}
if (ans < 0) {
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_WARNING))
ndnr_msg(ndnr, "sync_enum - Too many active enumerations!", ans);
goto Bail;
}
content = r_store_find_first_match_candidate(ndnr, interest->buf, pi);
if (content == NULL) {
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "sync_enum_nomatch", NULL,
interest->buf, interest->length);
}
else if (r_store_content_matches_interest_prefix(ndnr,
content, interest->buf, interest->length)) {
ndnr->active_enum[ans] = r_store_content_accession(ndnr, content);
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_FINEST))
ndnr_msg(ndnr, "sync_enum id=%d starting accession=0x%jx",
ans, ndnr_accession_encode(ndnr, ndnr->active_enum[ans]));
}
/* Set up the state for r_sync_enumerate_action */
md = calloc(1, sizeof(*md));
if (md == NULL) { ndnr->active_enum[ans] = NDNR_NULL_ACCESSION; ans = -1; goto Bail; }
md->magic = se_cookie;
md->cookie = content == NULL ? 0 : r_store_content_cookie(ndnr, content);
md->index = ans;
md->interest = ndn_charbuf_create();
if (md->interest == NULL) goto Bail;
ndn_charbuf_append(md->interest, interest->buf, interest->length);
md->parsed_interest = parsed_interest;
md->comps = comps;
comps = NULL;
/* All the upcalls happen in r_sync_enumerate_action. */
if (NULL != ndn_schedule_event(ndnr->sched, 123, r_sync_enumerate_action, md, 0))
md = NULL;
Bail:
if (md != NULL) {
ans = -1;
md = cleanup_se(ndnr, md);
}
ndn_indexbuf_destroy(&comps);
if (NDNSHOULDLOG(ndnr, r_sync_enumerate, NDNL_FINEST))
ndnr_msg(ndnr, "sync_enum %d", ans);
return(ans);
}
PUBLIC int
r_sync_lookup(struct sync_plumbing *sdd,
struct ndn_charbuf *interest,
struct ndn_charbuf *content_ndnb)
{
struct ndnr_handle *ndnr = (struct ndnr_handle *)sdd->client_data;
return(r_lookup(ndnr, interest, content_ndnb));
}
PUBLIC int
r_lookup(struct ndnr_handle *ndnr,
struct ndn_charbuf *interest,
struct ndn_charbuf *content_ndnb)
{
int ans = -1;
struct ndn_indexbuf *comps = r_util_indexbuf_obtain(ndnr);
struct ndn_parsed_interest parsed_interest = {0};
struct ndn_parsed_interest *pi = &parsed_interest;
struct content_entry *content = NULL;
if (NULL == comps || (ndn_parse_interest(interest->buf, interest->length, pi, comps) < 0))
abort();
content = r_store_lookup(ndnr, interest->buf, pi, comps);
if (content != NULL) {
ans = 0;
if (content_ndnb != NULL) {
const unsigned char *base = r_store_content_base(ndnr, content);
size_t size = r_store_content_size(ndnr, content);
if (base == NULL) {
ndnr_debug_ndnb(ndnr, __LINE__, "r_sync_lookup null content base", NULL,
interest->buf, interest->length);
ans = -1;
} else
ndn_charbuf_append(content_ndnb, base, size);
}
}
r_util_indexbuf_release(ndnr, comps);
return(ans);
}
/**
* Called when a content object is received by sync and needs to be
* committed to stable storage by the repo.
*/
PUBLIC enum ndn_upcall_res
r_sync_upcall_store(struct sync_plumbing *sdd,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info)
{
struct ndnr_handle *ndnr = (struct ndnr_handle *)sdd->client_data;
enum ndn_upcall_res ans = NDN_UPCALL_RESULT_OK;
const unsigned char *ndnb = NULL;
size_t ndnb_size = 0;
struct content_entry *content;
if (kind != NDN_UPCALL_CONTENT)
return(NDN_UPCALL_RESULT_ERR);
ndnb = info->content_ndnb;
ndnb_size = info->pco->offset[NDN_PCO_E];
content = process_incoming_content(ndnr, r_io_fdholder_from_fd(ndnr, ndn_get_connection_fd(info->h)),
(void *)ndnb, ndnb_size, NULL);
if (content == NULL) {
ndnr_msg(ndnr, "r_sync_upcall_store: failed to process incoming content");
return(NDN_UPCALL_RESULT_ERR);
}
// XXX - here we need to check if this is something we *should* be storing, according to our policy
if ((r_store_content_flags(content) & NDN_CONTENT_ENTRY_STABLE) == 0) {
r_store_commit_content(ndnr, content);
if (NDNSHOULDLOG(ndnr, r_sync_upcall_store, NDNL_FINE))
ndnr_debug_content(ndnr, __LINE__, "content_stored",
r_io_fdholder_from_fd(ndnr, ndnr->active_out_fd),
content);
}
r_proto_initiate_key_fetch(ndnr, ndnb, info->pco, 0,
r_store_content_cookie(ndnr, content));
return(ans);
}
/**
* Called when a content object has been constructed locally by sync
* and needs to be committed to stable storage by the repo.
* returns 0 for success, -1 for error.
*/
PUBLIC int
r_sync_local_store(struct sync_plumbing *sdd,
struct ndn_charbuf *content_cb)
{
struct ndnr_handle *ndnr = (struct ndnr_handle *)sdd->client_data;
struct content_entry *content = NULL;
// pretend it came from the internal client, for statistics gathering purposes
content = process_incoming_content(ndnr, ndnr->face0,
(void *)content_cb->buf, content_cb->length, NULL);
if (content == NULL) {
ndnr_msg(ndnr, "r_sync_local_store: failed to process content");
return(-1);
}
// XXX - we assume we must store things from sync independent of policy
// XXX - sync may want notification, or not, at least for now.
if ((r_store_content_flags(content) & NDN_CONTENT_ENTRY_STABLE) == 0) {
r_store_commit_content(ndnr, content);
if (NDNSHOULDLOG(ndnr, r_sync_local_store, NDNL_FINE))
ndnr_debug_content(ndnr, __LINE__, "content_stored_local",
r_io_fdholder_from_fd(ndnr, ndnr->active_out_fd),
content);
}
return(0);
}
|
yoursunny/carepo
|
repo/ndnr_io.h
|
/**
* @file ndnr_io.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_IO_DEFINED
#define NDNR_IO_DEFINED
#include "ndnr_private.h"
void r_io_shutdown_all(struct ndnr_handle *h);
void r_io_prepare_poll_fds(struct ndnr_handle *h);
void r_dispatch_process_internal_client_buffer(struct ndnr_handle *h);
void r_io_send(struct ndnr_handle *h,struct fdholder *fdholder,const void *data,size_t size,off_t *offsetp);
int r_io_destroy_face(struct ndnr_handle *h,unsigned filedesc);
int r_io_open_repo_data_file(struct ndnr_handle *h, const char *name, int output);
int r_io_repo_data_file_fd(struct ndnr_handle *h, unsigned repofile, int output);
void r_io_shutdown_client_fd(struct ndnr_handle *h,int fd);
int r_io_accept_connection(struct ndnr_handle *h,int listener_fd);
struct fdholder *r_io_record_fd(struct ndnr_handle *h,int fd,void *who,socklen_t wholen,int setflags);
void r_io_register_new_face(struct ndnr_handle *h,struct fdholder *fdholder);
int r_io_enroll_face(struct ndnr_handle *h,struct fdholder *fdholder);
struct fdholder *ndnr_r_io_fdholder_from_fd(struct ndnr_handle *h,unsigned filedesc);
struct fdholder *r_io_fdholder_from_fd(struct ndnr_handle *h,unsigned filedesc);
#endif
|
yoursunny/carepo
|
repo/ndnr_init.c
|
/**
* @file ndnr_init.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include <sync/sync_plumbing.h>
#include <sync/SyncActions.h>
#include "ndnr_private.h"
#include "ndnr_init.h"
#include "ndnr_dispatch.h"
#include "ndnr_forwarding.h"
#include "ndnr_internal_client.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
#include "ndnr_net.h"
#include "ndnr_proto.h"
#include "ndnr_sendq.h"
#include "ndnr_store.h"
#include "ndnr_sync.h"
#include "ndnr_util.h"
static int load_policy(struct ndnr_handle *h);
static int merge_files(struct ndnr_handle *h);
static struct sync_plumbing_client_methods sync_client_methods = {
.r_sync_msg = &r_sync_msg,
.r_sync_fence = &r_sync_fence,
.r_sync_enumerate = &r_sync_enumerate,
.r_sync_lookup = &r_sync_lookup,
.r_sync_local_store = &r_sync_local_store,
.r_sync_upcall_store = &r_sync_upcall_store
};
/**
* Read the contents of the repository config file
*
* Calls r_init_fail and returns NULL in case of error.
* @returns unparsed content of config file in a newly allocated charbuf
*/
struct ndn_charbuf *
r_init_read_config(struct ndnr_handle *h)
{
struct ndn_charbuf *path = NULL;
struct ndn_charbuf *contents = NULL;
size_t sz = 800;
ssize_t sres = -1;
int fd;
h->directory = getenv("NDNR_DIRECTORY");
if (h->directory == NULL || h->directory[0] == 0)
h->directory = ".";
path = ndn_charbuf_create();
contents = ndn_charbuf_create();
if (path == NULL || contents == NULL)
return(NULL);
ndn_charbuf_putf(path, "%s/config", h->directory);
fd = open(ndn_charbuf_as_string(path), O_RDONLY);
if (fd == -1) {
if (errno == ENOENT)
sres = 0;
else
r_init_fail(h, __LINE__, ndn_charbuf_as_string(path), errno);
}
else {
for (;;) {
sres = read(fd, ndn_charbuf_reserve(contents, sz), sz);
if (sres == 0)
break;
if (sres < 0) {
r_init_fail(h, __LINE__, "Read failed reading config", errno);
break;
}
contents->length += sres;
if (contents->length > 999999) {
r_init_fail(h, __LINE__, "config file too large", 0);
sres = -1;
break;
}
}
close(fd);
}
ndn_charbuf_destroy(&path);
if (sres < 0)
ndn_charbuf_destroy(&contents);
return(contents);
}
static int
r_init_debug_getenv(struct ndnr_handle *h, const char *envname)
{
const char *debugstr;
int debugval;
debugstr = getenv(envname);
debugval = ndnr_msg_level_from_string(debugstr);
/* Treat 1 and negative specially, for some backward compatibility. */
if (debugval == 1)
debugval = NDNL_WARNING;
if (debugval < 0) {
debugval = NDNL_FINEST;
if (h != NULL)
ndnr_msg(h, "%s='%s' is not valid, using FINEST", envname, debugstr);
}
return(debugval);
}
/**
* Get the specified numerical config value, subject to limits.
*/
intmax_t
r_init_confval(struct ndnr_handle *h, const char *key,
intmax_t lo, intmax_t hi, intmax_t deflt) {
const char *s;
intmax_t v;
char *ep;
if (!(lo <= deflt && deflt <= hi))
abort();
s = getenv(key);
if (s != NULL && s[0] != 0) {
ep = "x";
v = strtoimax(s, &ep, 10);
if (v != 0 || ep[0] == 0) {
if (v > hi)
v = hi;
if (v < lo)
v = lo;
if (NDNSHOULDLOG(h, mmm, NDNL_FINEST))
ndnr_msg(h, "Using %s=%jd", key, v);
return(v);
}
}
return (deflt);
}
#define NDNR_CONFIG_PASSMASK 0x003 /* config pass */
#define NDNR_CONFIG_IGNORELINE 0x100 /* Set if there are prior problems */
#define NDNR_CONFIG_ERR 0x200 /* Report error rather than warning */
/**
* Message helper for r_init_parse_config()
*/
static void
r_init_config_msg(struct ndnr_handle *h, int flags,
int line, int chindex, const char *msg)
{
const char *problem = "Problem";
int log_at = NDNL_WARNING;
log_at = NDNL_WARNING;
if ((flags & NDNR_CONFIG_ERR) != 0) {
problem = "Error";
log_at = NDNL_ERROR;
}
if ((flags & (NDNR_CONFIG_IGNORELINE|NDNR_CONFIG_PASSMASK)) == 1 &&
NDNSHOULDLOG(h, mmm, log_at)) {
ndnr_msg(h, "%s in config file %s/config - line %d column %d: %s",
problem, h->directory, line, chindex + 1, msg);
}
}
/**
* Parse the buffered configuration found in config
*
* The pass argument controls what is done with the result:
* 0 - silent check for syntax errors;
* 1 - check for syntax errors and warnings, logging the results,
* 2 - incorporate settings into environ.
*
* @returns -1 if an error is found, otherwise the count of warnings.
*/
int
r_init_parse_config(struct ndnr_handle *h, struct ndn_charbuf *config, int pass)
{
struct ndn_charbuf *key = NULL;
struct ndn_charbuf *value = NULL;
const unsigned char *b;
int line;
size_t i;
size_t sol; /* start of line */
size_t len; /* config->len */
size_t ndx; /* temp for column report*/
int ch;
int warns = 0;
int errors = 0;
int use_it = 0;
static const char pclegal[] =
"~@%-+=:,./[]"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"_"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *klegal = strchr(pclegal, 'a');
int flags; /* for reporting */
b = config->buf;
len = config->length;
if (len == 0)
return(0);
ndn_charbuf_as_string(config);
key = ndn_charbuf_create();
value = ndn_charbuf_create();
if (key == NULL || value == NULL)
return(-1);
/* Ensure there is null termination in the buffered config */
if (ndn_charbuf_as_string(config) == NULL)
return(-1);
for (line = 1, i = 0, ch = b[0], sol = 0; i < len;) {
flags = pass;
use_it = 0;
if (ch > ' ' && ch != '#') {
key->length = value->length = 0;
/* parse key */
while (i < len && ch != '\n' && ch != '=') {
ndn_charbuf_append_value(key, ch, 1);
ch = b[++i];
}
if (ch == '=')
ch = b[++i];
else {
r_init_config_msg(h, flags, line, key->length, "missing '='");
flags |= NDNR_CONFIG_IGNORELINE;
warns++;
ch = '\n';
}
/* parse value */
while (i < len && ch > ' ') {
ndn_charbuf_append_value(value, ch, 1);
ch = b[++i];
}
/* See if it might be one of ours */
if (key->length < 5 || (memcmp(key->buf, "NDNR_", 5) != 0 &&
memcmp(key->buf, "NDNS_", 5) != 0)) {
r_init_config_msg(h, flags, line, 0,
"ignoring unrecognized key");
flags |= NDNR_CONFIG_IGNORELINE;
warns++;
use_it = 0;
}
else
use_it = 1;
/* Check charset of key */
ndx = strspn(ndn_charbuf_as_string(key), klegal);
if (ndx != key->length) {
errors += use_it;
r_init_config_msg(h, (flags | NDNR_CONFIG_ERR), line, ndx,
"unexpected character in key");
flags |= NDNR_CONFIG_IGNORELINE;
warns++;
}
/* Check charset of value */
ndx = strspn(ndn_charbuf_as_string(value), pclegal);
if (ndx != value->length) {
errors += use_it;
r_init_config_msg(h, (flags | NDNR_CONFIG_ERR),
line, key->length + 1 + ndx,
"unexpected character in value");
flags |= NDNR_CONFIG_IGNORELINE;
warns++;
}
}
if (ch == '#') {
/* a comment line or error recovery. */
while (i < len && ch != '\n')
ch = b[++i];
}
while (i < len && ch <= ' ') {
if (ch == '\n') {
line++;
sol = i;
break;
}
if (memchr("\r\t ", ch, 3) == NULL) {
r_init_config_msg(h, pass, line, i - sol,
"non-whitespace control char at end of line");
warns++;
}
ch = b[++i];
}
if (i == len) {
r_init_config_msg(h, flags, line, i - sol,
"missing newline at end of file");
warns++;
ch = '\n';
}
else if (ch == '\n')
ch = b[++i];
else {
r_init_config_msg(h, flags, line, i - sol, "junk at end of line");
flags |= NDNR_CONFIG_IGNORELINE;
warns++;
ch = '#';
}
if (flags == 0 && strcmp(ndn_charbuf_as_string(key), "NDNR_DEBUG") == 0) {
/* Set this on pass 0 so that it takes effect sooner. */
h->debug = 1;
setenv("NDNR_DEBUG", ndn_charbuf_as_string(value), 1);
h->debug = r_init_debug_getenv(h, "NDNR_DEBUG");
}
if (pass == 2 && use_it) {
if (NDNSHOULDLOG(h, mmm, NDNL_FINEST))
ndnr_msg(h, "config: %s=%s",
ndn_charbuf_as_string(key),
ndn_charbuf_as_string(value));
setenv(ndn_charbuf_as_string(key), ndn_charbuf_as_string(value), 1);
}
}
ndn_charbuf_destroy(&key);
ndn_charbuf_destroy(&value);
return(errors ? -1 : warns);
}
static int
establish_min_send_bufsize(struct ndnr_handle *h, int fd, int minsize)
{
int res;
int bufsize;
int obufsize;
socklen_t bufsize_sz;
bufsize_sz = sizeof(bufsize);
res = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bufsize, &bufsize_sz);
if (res == -1)
return (res);
obufsize = bufsize;
if (bufsize < minsize) {
bufsize = minsize;
res = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
if (res == -1)
return(res);
}
if (NDNSHOULDLOG(h, sdfdsf, NDNL_INFO))
ndnr_msg(h, "SO_SNDBUF for fd %d is %d (was %d)", fd, bufsize, obufsize);
return(bufsize);
}
/**
* If so configured, replace fd with a tcp socket
* @returns new address family
*/
static int
try_tcp_instead(int fd)
{
struct addrinfo hints = {0};
struct addrinfo *ai = NULL;
const char *port = NULL;
const char *proto = NULL;
int res;
int sock;
int ans = AF_UNIX;
int yes = 1;
proto = getenv("NDNR_PROTO");
if (proto == NULL || strcasecmp(proto, "tcp") != 0)
return(ans);
port = getenv("NDN_LOCAL_PORT");
if (port == NULL || port[0] == 0)
port = "6363";
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
res = getaddrinfo(NULL, port, &hints, &ai);
if (res == 0) {
sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (sock != -1) {
res = connect(sock, ai->ai_addr, ai->ai_addrlen);
if (res == 0) {
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
dup2(sock, fd);
ans = ai->ai_family;
}
else
close(sock);
}
freeaddrinfo(ai);
}
return(ans);
}
PUBLIC struct ndnr_parsed_policy *
ndnr_parsed_policy_create(void)
{
struct ndnr_parsed_policy *pp;
pp = calloc(1, sizeof(struct ndnr_parsed_policy));
pp->store = ndn_charbuf_create();
pp->namespaces = ndn_indexbuf_create();
return(pp);
}
PUBLIC void
ndnr_parsed_policy_destroy(struct ndnr_parsed_policy **ppp)
{
struct ndnr_parsed_policy *pp;
if (*ppp == NULL)
return;
pp = *ppp;
ndn_charbuf_destroy(&pp->store);
ndn_indexbuf_destroy(&pp->namespaces);
free(pp);
*ppp = NULL;
}
/**
* Create a new ndnr instance
* @param progname - name of program binary, used for locating helpers
* @param logger - logger function
* @param loggerdata - data to pass to logger function
*/
PUBLIC struct ndnr_handle *
r_init_create(const char *progname, ndnr_logger logger, void *loggerdata)
{
char *sockname = NULL;
const char *portstr = NULL;
const char *listen_on = NULL;
const char *d = NULL;
struct ndnr_handle *h = NULL;
struct hashtb_param param = {0};
struct ndn_charbuf *config = NULL;
int res;
h = calloc(1, sizeof(*h));
if (h == NULL)
return(h);
h->notify_after = 0; //NDNR_MAX_ACCESSION;
h->logger = logger;
h->loggerdata = loggerdata;
h->logpid = (int)getpid();
h->progname = progname;
h->debug = -1;
config = r_init_read_config(h);
if (config == NULL)
goto Bail;
r_init_parse_config(h, config, 0); /* silent pass to pick up NDNR_DEBUG */
h->debug = 1; /* so that we see any complaints */
h->debug = r_init_debug_getenv(h, "NDNR_DEBUG");
res = r_init_parse_config(h, config, 1);
if (res < 0) {
h->running = -1;
goto Bail;
}
r_init_parse_config(h, config, 2);
sockname = r_net_get_local_sockname();
h->skiplinks = ndn_indexbuf_create();
h->face_limit = 10; /* soft limit */
h->fdholder_by_fd = calloc(h->face_limit, sizeof(h->fdholder_by_fd[0]));
param.finalize_data = h;
param.finalize = &r_fwd_finalize_nameprefix;
h->nameprefix_tab = hashtb_create(sizeof(struct nameprefix_entry), ¶m);
param.finalize = 0; // PRUNED &r_fwd_finalize_propagating;
h->propagating_tab = hashtb_create(sizeof(struct propagating_entry), ¶m);
param.finalize = &r_proto_finalize_enum_state;
h->enum_state_tab = hashtb_create(sizeof(struct enum_state), ¶m);
h->min_stale = ~0;
h->max_stale = 0;
h->unsol = ndn_indexbuf_create();
h->ticktock.descr[0] = 'C';
h->ticktock.micros_per_base = 1000000;
h->ticktock.gettime = &r_util_gettime;
h->ticktock.data = h;
h->sched = ndn_schedule_create(h, &h->ticktock);
h->starttime = h->sec;
h->starttime_usec = h->usec;
h->oldformatcontentgrumble = 1;
h->oldformatinterestgrumble = 1;
h->cob_limit = 4201;
h->start_write_scope_limit = r_init_confval(h, "NDNR_START_WRITE_SCOPE_LIMIT", 0, 3, 3);
h->debug = 1; /* so that we see any complaints */
h->debug = r_init_debug_getenv(h, "NDNR_DEBUG");
h->syncdebug = r_init_debug_getenv(h, "NDNS_DEBUG");
portstr = getenv("NDNR_STATUS_PORT");
if (portstr == NULL || portstr[0] == 0 || strlen(portstr) > 10)
portstr = "";
h->portstr = portstr;
ndnr_msg(h, "NDNR_DEBUG=%d NDNR_DIRECTORY=%s NDNR_STATUS_PORT=%s", h->debug, h->directory, h->portstr);
listen_on = getenv("NDNR_LISTEN_ON");
if (listen_on != NULL && listen_on[0] != 0)
ndnr_msg(h, "NDNR_LISTEN_ON=%s", listen_on);
if (ndnr_init_repo_keystore(h, NULL) < 0) {
h->running = -1;
goto Bail;
}
r_util_reseed(h);
r_store_init(h);
if (h->running == -1) goto Bail;
while (h->active_in_fd >= 0) {
r_dispatch_process_input(h, h->active_in_fd);
r_store_trim(h, h->cob_limit);
ndn_schedule_run(h->sched);
}
ndnr_msg(h, "Repository file is indexed");
if (h->face0 == NULL) {
struct fdholder *fdholder;
fdholder = calloc(1, sizeof(*fdholder));
if (dup2(open("/dev/null", O_RDONLY), 0) == -1)
ndnr_msg(h, "stdin: %s", strerror(errno));
fdholder->filedesc = 0;
fdholder->flags = (NDNR_FACE_GG | NDNR_FACE_NORECV);
r_io_enroll_face(h, fdholder);
}
ndnr_direct_client_start(h);
d = getenv("NDNR_SKIP_VERIFY");
#if (NDN_API_VERSION >= 4004)
if (d != NULL && strcmp(d, "1") == 0) {
ndnr_msg(h, "NDNR_SKIP_VERIFY=%s", d);
ndn_defer_verification(h->direct_client, 1);
}
#endif
if (ndn_connect(h->direct_client, NULL) != -1) {
int af = 0;
int bufsize;
int flags;
int fd;
struct fdholder *fdholder;
fd = ndn_get_connection_fd(h->direct_client);
// Play a dirty trick here - if this wins, we can fix it right in the c lib later on...
af = try_tcp_instead(fd);
flags = NDNR_FACE_NDND;
if (af == AF_INET)
flags |= NDNR_FACE_INET;
else if (af == AF_INET6)
flags |= NDNR_FACE_INET6;
else
flags |= NDNR_FACE_LOCAL;
fdholder = r_io_record_fd(h, fd, "NDND", 5, flags);
if (fdholder == NULL) abort();
ndnr_uri_listen(h, h->direct_client, "ndn:/%C1.M.S.localhost/%C1.M.SRV/repository",
&ndnr_answer_req, OP_SERVICE);
ndnr_uri_listen(h, h->direct_client, "ndn:/%C1.M.S.neighborhood/%C1.M.SRV/repository",
&ndnr_answer_req, OP_SERVICE);
bufsize = r_init_confval(h, "NDNR_MIN_SEND_BUFSIZE", 1, 2097152, 16384);
establish_min_send_bufsize(h, fd, bufsize);
}
else
ndn_disconnect(h->direct_client); // Apparently ndn_connect error case needs work.
if (1 == r_init_confval(h, "NDNS_ENABLE", 0, 1, 1)) {
h->sync_plumbing = calloc(1, sizeof(struct sync_plumbing));
h->sync_plumbing->ndn = h->direct_client;
h->sync_plumbing->sched = h->sched;
h->sync_plumbing->client_methods = &sync_client_methods;
h->sync_plumbing->client_data = h;
h->sync_base = SyncNewBaseForActions(h->sync_plumbing);
}
if (-1 == load_policy(h))
goto Bail;
r_net_listen_on(h, listen_on);
ndnr_internal_client_start(h);
r_proto_init(h);
r_proto_activate_policy(h, h->parsed_policy);
if (merge_files(h) == -1)
r_init_fail(h, __LINE__, "Unable to merge additional repository data files.", errno);
if (h->running == -1) goto Bail;
if (h->sync_plumbing) {
// Start sync running
// returns < 0 if a failure occurred
// returns 0 if the name updates should fully restart
// returns > 0 if the name updates should restart at last fence
res = h->sync_plumbing->sync_methods->sync_start(h->sync_plumbing, NULL);
if (res < 0) {
r_init_fail(h, __LINE__, "starting sync", res);
abort();
}
else if (res > 0) {
// XXX: need to work out details of starting from last fence.
// By examination of code, SyncActions won't take this path
}
}
Bail:
if (sockname)
free(sockname);
sockname = NULL;
ndn_charbuf_destroy(&config);
if (h->running == -1)
r_init_destroy(&h);
return(h);
}
void
r_init_fail(struct ndnr_handle *ndnr, int line, const char *culprit, int err)
{
if (err > 0)
ndnr_msg(ndnr, "Startup failure %d %s - %s", line, culprit,
strerror(err));
else {
ndnr_msg(ndnr, "Startup failure %d %s - error %d", line, culprit, err);
}
ndnr->running = -1;
}
/**
* Destroy the ndnr instance, releasing all associated resources.
*/
PUBLIC void
r_init_destroy(struct ndnr_handle **pndnr)
{
struct ndnr_handle *h = *pndnr;
int stable;
if (h == NULL)
return;
stable = h->active_in_fd == -1 ? 1 : 0;
r_io_shutdown_all(h);
ndnr_direct_client_stop(h);
ndn_schedule_destroy(&h->sched);
hashtb_destroy(&h->propagating_tab);
hashtb_destroy(&h->nameprefix_tab);
hashtb_destroy(&h->enum_state_tab);
hashtb_destroy(&h->content_by_accession_tab);
// SyncActions sync_stop method should be shutting down heartbeat
if (h->sync_plumbing) {
h->sync_plumbing->sync_methods->sync_stop(h->sync_plumbing, NULL);
free(h->sync_plumbing);
h->sync_plumbing = NULL;
h->sync_base = NULL; // freed by sync_stop ?
}
r_store_final(h, stable);
if (h->fds != NULL) {
free(h->fds);
h->fds = NULL;
h->nfds = 0;
}
if (h->fdholder_by_fd != NULL) {
free(h->fdholder_by_fd);
h->fdholder_by_fd = NULL;
h->face_limit = h->face_gen = 0;
}
if (h->content_by_cookie != NULL) {
free(h->content_by_cookie);
h->content_by_cookie = NULL;
h->cookie_limit = 1;
}
ndn_charbuf_destroy(&h->scratch_charbuf);
ndn_indexbuf_destroy(&h->skiplinks);
ndn_indexbuf_destroy(&h->scratch_indexbuf);
ndn_indexbuf_destroy(&h->unsol);
if (h->parsed_policy != NULL) {
ndn_indexbuf_destroy(&h->parsed_policy->namespaces);
ndn_charbuf_destroy(&h->parsed_policy->store);
free(h->parsed_policy);
h->parsed_policy = NULL;
}
ndn_charbuf_destroy(&h->policy_name);
ndn_charbuf_destroy(&h->policy_link_cob);
ndn_charbuf_destroy(&h->ndnr_keyid);
free(h);
*pndnr = NULL;
}
int
r_init_map_and_process_file(struct ndnr_handle *h, struct ndn_charbuf *filename, int add_content)
{
int res = 0;
int dres;
struct stat statbuf;
unsigned char *mapped_file = MAP_FAILED;
unsigned char *msg;
size_t size;
int fd = -1;
struct content_entry *content;
struct ndn_skeleton_decoder *d;
struct fdholder *fdholder;
fd = r_io_open_repo_data_file(h, ndn_charbuf_as_string(filename), 0);
if (fd == -1) // Normal exit
return(1);
res = fstat(fd, &statbuf);
if (res != 0) {
ndnr_msg(h, "stat failed for %s (fd=%d), %s (errno=%d)",
ndn_charbuf_as_string(filename), fd, strerror(errno), errno);
res = -errno;
goto Bail;
}
if (statbuf.st_size == 0)
goto Bail;
mapped_file = mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (mapped_file == MAP_FAILED) {
ndnr_msg(h, "mmap failed for %s (fd=%d), %s (errno=%d)",
ndn_charbuf_as_string(filename), fd, strerror(errno), errno);
res = -errno;
goto Bail;
}
fdholder = r_io_fdholder_from_fd(h, fd);
d = &fdholder->decoder;
msg = mapped_file;
size = statbuf.st_size;
while (d->index < size) {
dres = ndn_skeleton_decode(d, msg + d->index, size - d->index);
if (!NDN_FINAL_DSTATE(d->state))
break;
if (add_content) {
content = process_incoming_content(h, fdholder, msg + d->index - dres, dres, NULL);
if (content != NULL)
r_store_commit_content(h, content);
}
}
if (d->index != size || !NDN_FINAL_DSTATE(d->state)) {
ndnr_msg(h, "protocol error on fdholder %u (state %d), discarding %d bytes",
fdholder->filedesc, d->state, (int)(size - d->index));
res = -1;
goto Bail;
}
Bail:
if (mapped_file != MAP_FAILED)
munmap(mapped_file, statbuf.st_size);
r_io_shutdown_client_fd(h, fd);
return (res);
}
static int
merge_files(struct ndnr_handle *h)
{
int i, last_file;
int res;
struct ndn_charbuf *filename = ndn_charbuf_create();
// first parse the file(s) making sure there are no errors
for (i = 2;; i++) {
filename->length = 0;
ndn_charbuf_putf(filename, "repoFile%d", i);
res = r_init_map_and_process_file(h, filename, 0);
if (res == 1)
break;
if (res < 0) {
ndnr_msg(h, "Error parsing repository file %s", ndn_charbuf_as_string(filename));
return (-1);
}
}
last_file = i - 1;
for (i = 2; i <= last_file; i++) {
filename->length = 0;
ndn_charbuf_putf(filename, "repoFile%d", i);
res = r_init_map_and_process_file(h, filename, 1);
if (res < 0) {
ndnr_msg(h, "Error in phase 2 incorporating repository file %s", ndn_charbuf_as_string(filename));
return (-1);
}
}
for (i = last_file; i > 1; --i) {
filename->length = 0;
ndn_charbuf_putf(filename, "%s/repoFile%d", h->directory, i);
if (NDNSHOULDLOG(h, LM_128, NDNL_INFO))
ndnr_msg(h, "unlinking %s", ndn_charbuf_as_string(filename));
unlink(ndn_charbuf_as_string(filename));
}
ndn_charbuf_destroy(&filename);
return (0);
}
static struct ndn_charbuf *
ndnr_init_policy_cob(struct ndnr_handle *ndnr, struct ndn *h,
struct ndn_charbuf *basename,
int freshness, struct ndn_charbuf *content)
{
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
struct ndn_charbuf *name = ndn_charbuf_create();
struct ndn_charbuf *pubid = ndn_charbuf_create();
struct ndn_charbuf *pubkey = ndn_charbuf_create();
struct ndn_charbuf *keyid = ndn_charbuf_create();
struct ndn_charbuf *tcob = ndn_charbuf_create();
struct ndn_charbuf *cob = NULL; // result
int res;
res = ndn_get_public_key(h, NULL, pubid, pubkey);
if (res < 0)
goto Leave;
res = ndn_charbuf_append_charbuf(name, basename);
if (ndn_name_from_uri(name, "%00") < 0)
goto Leave;
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
sp.type = NDN_CONTENT_DATA;
sp.freshness = freshness;
res |= ndn_sign_content(h, tcob, name, &sp, content->buf, content->length);
if (res == 0) {
cob = tcob;
tcob = NULL;
}
Leave:
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&pubid);
ndn_charbuf_destroy(&pubkey);
ndn_charbuf_destroy(&keyid);
ndn_charbuf_destroy(&tcob);
return (cob);
}
/**
* should probably return a new cob, rather than reusing one.
* should publish link as:
* NDNRID_POLICY_URI("ndn:/%C1.M.S.localhost/%C1.M.SRV/repository/POLICY)/%C1.M.K--pubid--/--version--/%00
* should have key locator which is the key name of the repository
*/
PUBLIC struct ndn_charbuf *
ndnr_init_policy_link_cob(struct ndnr_handle *ndnr, struct ndn *h,
struct ndn_charbuf *targetname)
{
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
struct ndn_charbuf *name = ndn_charbuf_create();
struct ndn_charbuf *pubid = ndn_charbuf_create();
struct ndn_charbuf *pubkey = ndn_charbuf_create();
struct ndn_charbuf *keyid = ndn_charbuf_create();
struct ndn_charbuf *content = ndn_charbuf_create();
struct ndn_charbuf *cob = ndn_charbuf_create();
struct ndn_charbuf *answer = NULL;
int res;
res = ndn_get_public_key(h, NULL, pubid, pubkey);
if (res < 0)
goto Bail;
if (ndn_name_from_uri(name, NDNRID_POLICY_URI) < 0)
goto Bail;
res |= ndn_charbuf_append_value(keyid, NDN_MARKER_CONTROL, 1);
res |= ndn_charbuf_append_string(keyid, ".M.K");
res |= ndn_charbuf_append_value(keyid, 0, 1);
res |= ndn_charbuf_append_charbuf(keyid, pubid);
res |= ndn_name_append(name, keyid->buf, keyid->length);
res |= ndn_create_version(h, name, NDN_V_NOW, 0, 0);
if (ndn_name_from_uri(name, "%00") < 0)
goto Bail;
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
sp.type = NDN_CONTENT_LINK;
res |= ndnb_append_Link(content, targetname, "Repository Policy", NULL);
if (res != 0)
goto Bail;
res |= ndn_sign_content(h, cob, name, &sp, content->buf, content->length);
if (res != 0)
goto Bail;
answer = cob;
cob = NULL;
Bail:
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&pubid);
ndn_charbuf_destroy(&pubkey);
ndn_charbuf_destroy(&keyid);
ndn_charbuf_destroy(&content);
ndn_charbuf_destroy(&cob);
return (answer);
}
/**
* Load a link to the repo policy from the repoPolicy file and load the link
* target to extract the actual policy.
* If a policy file does not exist a new one is created, with a link to a policy
* based either on the environment variable NDNR_GLOBAL_PREFIX or the system
* default value of ndn:/named-data.net/ndn/Repos, plus the system defaults for
* other fields.
* This routine must be called after the btree code is initialized and capable
* of returning content objects.
* Sets the parsed_policy field of the handle to be the new policy.
*/
static int
load_policy(struct ndnr_handle *ndnr)
{
int fd;
ssize_t res;
struct content_entry *content = NULL;
const unsigned char *content_msg = NULL;
struct ndn_parsed_ContentObject pco = {0};
struct ndn_parsed_Link pl = {0};
struct ndn_indexbuf *nc = NULL;
struct ndn_charbuf *basename = NULL;
struct ndn_charbuf *policy = NULL;
struct ndn_charbuf *policy_cob = NULL;
struct ndn_charbuf *policyFileName;
const char *global_prefix;
const unsigned char *buf = NULL;
size_t length = 0;
int segment = 0;
int final = 0;
struct ndn_buf_decoder decoder;
struct ndn_buf_decoder *d;
policyFileName = ndn_charbuf_create();
ndn_charbuf_putf(policyFileName, "%s/repoPolicy", ndnr->directory);
ndnr->parsed_policy = ndnr_parsed_policy_create();
fd = open(ndn_charbuf_as_string(policyFileName), O_RDONLY);
if (fd >= 0) {
ndnr->policy_link_cob = ndn_charbuf_create();
ndn_charbuf_reserve(ndnr->policy_link_cob, 4096); // limits the size of the policy link
ndnr->policy_link_cob->length = 0; // clear the buffer
res = read(fd, ndnr->policy_link_cob->buf, ndnr->policy_link_cob->limit - ndnr->policy_link_cob->length);
close(fd);
if (res == -1) {
r_init_fail(ndnr, __LINE__, "Error reading repoPolicy file.", errno);
ndn_charbuf_destroy(&ndnr->policy_link_cob);
ndn_charbuf_destroy(&policyFileName);
return(-1);
}
ndnr->policy_link_cob->length = res;
nc = ndn_indexbuf_create();
res = ndn_parse_ContentObject(ndnr->policy_link_cob->buf,
ndnr->policy_link_cob->length, &pco, nc);
res = ndn_ref_tagged_BLOB(NDN_DTAG_Content, ndnr->policy_link_cob->buf,
pco.offset[NDN_PCO_B_Content],
pco.offset[NDN_PCO_E_Content],
&buf, &length);
d = ndn_buf_decoder_start(&decoder, buf, length);
res = ndn_parse_Link(d, &pl, NULL);
if (res <= 0) {
ndnr_msg(ndnr, "Policy link is malformed.");
goto CreateNewPolicy;
}
basename = ndn_charbuf_create();
ndn_charbuf_append(basename, buf + pl.offset[NDN_PL_B_Name],
pl.offset[NDN_PL_E_Name] - pl.offset[NDN_PL_B_Name]);
ndnr->policy_name = ndn_charbuf_create(); // to detect writes to this name
ndn_charbuf_append_charbuf(ndnr->policy_name, basename); // has version
ndn_name_chop(ndnr->policy_name, NULL, -1); // get rid of version
policy = ndn_charbuf_create();
// if we fail to retrieve the link target, report and then create a new one
do {
ndn_name_append_numeric(basename, NDN_MARKER_SEQNUM, segment++);
content = r_store_lookup_ndnb(ndnr, basename->buf, basename->length);
if (content == NULL) {
ndnr_debug_ndnb(ndnr, __LINE__, "policy lookup failed for", NULL,
basename->buf, basename->length);
break;
}
ndn_name_chop(basename, NULL, -1);
content_msg = r_store_content_base(ndnr, content);
if (content_msg == NULL) {
ndnr_debug_ndnb(ndnr, __LINE__, "Unable to read policy object", NULL,
basename->buf, basename->length);
break;
}
res = ndn_parse_ContentObject(content_msg, r_store_content_size(ndnr, content), &pco, nc);
res = ndn_ref_tagged_BLOB(NDN_DTAG_Content, content_msg,
pco.offset[NDN_PCO_B_Content],
pco.offset[NDN_PCO_E_Content],
&buf, &length);
ndn_charbuf_append(policy, buf, length);
final = ndn_is_final_pco(content_msg, &pco, nc);
} while (!final && segment < 100);
if (policy->length == 0) {
ndnr_msg(ndnr, "Policy link points to empty or non-existent policy.");
goto CreateNewPolicy;
}
if (segment >= 100) {
r_init_fail(ndnr, __LINE__, "Policy link points to policy with too many segments.", 0);
return(-1);
}
if (r_proto_parse_policy(ndnr, policy->buf, policy->length, ndnr->parsed_policy) < 0) {
ndnr_msg(ndnr, "Policy link points to malformed policy.");
goto CreateNewPolicy;
}
res = ndn_name_comp_get(content_msg, nc, nc->n - 3, &buf, &length);
if (length != 7 || buf[0] != NDN_MARKER_VERSION) {
ndnr_msg(ndnr, "Policy link points to unversioned policy.");
goto CreateNewPolicy;
}
memmove(ndnr->parsed_policy->version, buf, sizeof(ndnr->parsed_policy->version));
ndn_indexbuf_destroy(&nc);
ndn_charbuf_destroy(&basename);
ndn_charbuf_destroy(&policy);
ndn_charbuf_destroy(&policyFileName);
return (0);
}
CreateNewPolicy:
// clean up if we had previously done some allocation
ndn_indexbuf_destroy(&nc);
ndn_charbuf_destroy(&basename);
ndn_charbuf_destroy(&policy);
ndn_charbuf_destroy(&ndnr->policy_name);
ndnr_msg(ndnr, "Creating new policy file.");
// construct the policy content object
global_prefix = getenv ("NDNR_GLOBAL_PREFIX");
if (global_prefix != NULL)
ndnr_msg(ndnr, "NDNR_GLOBAL_PREFIX=%s", global_prefix);
else
global_prefix = "ndn:/named-data.net/ndn/Repos";
policy = ndn_charbuf_create();
r_proto_policy_append_basic(ndnr, policy, "1.5", "Repository", global_prefix);
r_proto_policy_append_namespace(ndnr, policy, "/");
basename = ndn_charbuf_create();
res = ndn_name_from_uri(basename, global_prefix);
res |= ndn_name_from_uri(basename, "data/policy.xml");
if (res < 0) {
r_init_fail(ndnr, __LINE__, "Global prefix is not a valid URI", 0);
return(-1);
}
ndnr->policy_name = ndn_charbuf_create(); // to detect writes to this name
ndn_charbuf_append_charbuf(ndnr->policy_name, basename);
ndn_create_version(ndnr->direct_client, basename, 0,
ndnr->starttime, ndnr->starttime_usec * 1000);
policy_cob = ndnr_init_policy_cob(ndnr, ndnr->direct_client, basename,
600, policy);
// save the policy content object to the repository
content = process_incoming_content(ndnr, ndnr->face0,
(void *)policy_cob->buf,
policy_cob->length, NULL);
r_store_commit_content(ndnr, content);
ndn_charbuf_destroy(&policy_cob);
// make a link to the policy content object
ndn_charbuf_destroy(&ndnr->policy_link_cob);
ndnr->policy_link_cob = ndnr_init_policy_link_cob(ndnr, ndnr->direct_client,
basename);
if (ndnr->policy_link_cob == NULL) {
r_init_fail(ndnr, __LINE__, "Unable to create policy link object", 0);
return(-1);
}
fd = open(ndn_charbuf_as_string(policyFileName), O_WRONLY | O_CREAT, 0666);
if (fd < 0) {
r_init_fail(ndnr, __LINE__, "Unable to open repoPolicy file for write", errno);
return(-1);
}
lseek(fd, 0, SEEK_SET);
res = write(fd, ndnr->policy_link_cob->buf, ndnr->policy_link_cob->length);
if (res == -1) {
r_init_fail(ndnr, __LINE__, "Unable to write repoPolicy file", errno);
return(-1);
}
res = ftruncate(fd, ndnr->policy_link_cob->length);
close(fd);
if (res == -1) {
r_init_fail(ndnr, __LINE__, "Unable to truncate repoPolicy file", errno);
return(-1);
}
// parse the policy for later use
if (r_proto_parse_policy(ndnr, policy->buf, policy->length, ndnr->parsed_policy) < 0) {
r_init_fail(ndnr, __LINE__, "Unable to parse new repoPolicy file", 0);
return(-1);
}
// get the pp->version from the policy_cob base name .../policy.xml/<ver>
nc = ndn_indexbuf_create();
ndn_name_split(basename, nc);
res = ndn_name_comp_get(basename->buf, nc, nc->n - 2, &buf, &length);
if (length != 7 || buf[0] != NDN_MARKER_VERSION) {
r_init_fail(ndnr, __LINE__, "Unable to get repository policy object version", 0);
return(-1);
}
memmove(ndnr->parsed_policy->version, buf, sizeof(ndnr->parsed_policy->version));
ndn_indexbuf_destroy(&nc);
ndn_charbuf_destroy(&basename);
ndn_charbuf_destroy(&policy);
ndn_charbuf_destroy(&policyFileName);
return(0);
}
|
yoursunny/carepo
|
repo/ndnr_forwarding.h
|
<gh_stars>0
/**
* @file ndnr_forwarding.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_FORWARDING_DEFINED
#define NDNR_FORWARDING_DEFINED
#include <ndn/ndn.h>
#include <ndn/hashtb.h>
#include "ndnr_private.h"
int r_fwd_nameprefix_longest_match(struct ndnr_handle *h,const unsigned char *msg,struct ndn_indexbuf *comps,int ncomps);
int r_fwd_is_duplicate_flooded(struct ndnr_handle *h,unsigned char *msg,struct ndn_parsed_interest *pi,unsigned filedesc);
int r_fwd_propagate_interest(struct ndnr_handle *h,struct fdholder *fdholder,unsigned char *msg,struct ndn_parsed_interest *pi,struct nameprefix_entry *npe);
void r_fwd_append_plain_nonce(struct ndnr_handle *h,struct fdholder *fdholder,struct ndn_charbuf *cb);
void r_fwd_append_debug_nonce(struct ndnr_handle *h,struct fdholder *fdholder,struct ndn_charbuf *cb);
void r_fwd_update_forward_to(struct ndnr_handle *h,struct nameprefix_entry *npe);
void r_fwd_reg_uri_list(struct ndnr_handle *h,struct ndn_charbuf *uris,unsigned filedesc,int flags,int expires);
int r_fwd_reg_uri(struct ndnr_handle *h,const char *uri,unsigned filedesc,int flags,int expires);
int r_fwd_nameprefix_seek(struct ndnr_handle *h,struct hashtb_enumerator *e,const unsigned char *msg,struct ndn_indexbuf *comps,int ncomps);
void r_fwd_age_forwarding_needed(struct ndnr_handle *h);
void r_fwd_reap_needed(struct ndnr_handle *h,int init_delay_usec);
void r_fwd_adjust_npe_predicted_response(struct ndnr_handle *h,struct nameprefix_entry *npe,int up);
void r_fwd_finalize_propagating(struct hashtb_enumerator *e);
void r_fwd_finalize_nameprefix(struct hashtb_enumerator *e);
#endif
|
yoursunny/carepo
|
repo/ndnr_msg.h
|
<gh_stars>0
/**
* @file ndnr_msg.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2012 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_MSG_DEFINED
#define NDNR_MSG_DEFINED
#include <ndn/loglevels.h>
#include <stdarg.h>
struct ndnr_handle;
struct fdholder;
int ndnr_msg_level_from_string(const char *s);
void ndnr_debug_ndnb(struct ndnr_handle *h,
int lineno,
const char *msg,
struct fdholder *fdholder,
const unsigned char *ndnb,
size_t ndnb_size);
void ndnr_msg(struct ndnr_handle *h, const char *fmt, ...);
void ndnr_vmsg(struct ndnr_handle *h, const char *fmt, va_list ap);
#endif
|
yoursunny/carepo
|
repo/ndnr_private.h
|
/**
* @file ndnr_private.h
*
* Private definitions for ndnr - the NDNx daemon.
* Data structures are described here so that logging and status
* routines can be compiled separately.
*
* Part of ndnr - the NDNx Repository Daemon.
*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2008-2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_PRIVATE_DEFINED
#define NDNR_PRIVATE_DEFINED
#include <poll.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <ndn/ndn_private.h>
#include <ndn/coding.h>
#include <ndn/reg_mgmt.h>
#include <ndn/schedule.h>
#include <ndn/seqwriter.h>
/*
* These are defined in other ndn headers, but the incomplete types suffice
* for the purposes of this header.
*/
struct ndn_charbuf;
struct ndn_indexbuf;
struct hashtb;
struct ndnr_meter;
struct ndn_btree;
struct sync_plumbing;
struct SyncBaseStruct;
#define CAREPO
#ifdef CAREPO
struct hash_store;
#define REPO_SHA256 "\xC1.R.SHA256"
#endif
/*
* These are defined in this header.
*/
struct ndnr_handle;
struct fdholder;
struct content_entry;
struct nameprefix_entry;
struct propagating_entry;
struct content_tree_node;
struct ndn_forwarding;
struct enum_state;
struct ndnr_parsed_policy;
/* Repository-specific content identifiers */
#if (defined(NDNLINT) && (NDNLINT == 1))
/* This is where we probably want to end up for declaring this type */
typedef uint_least64_t ndnr_accession;
#define NDNR_NULL_ACCESSION ((ndnr_accession)(0))
#define NDNR_MIN_ACCESSION ((ndnr_accession)(1))
#define NDNR_MAX_ACCESSION ((ndnr_accession)(~NDNR_NULL_ACCESSION))
#elif (defined(NDNLINT) && (NDNLINT == 2))
#error "Not expected to work - this is for detecting illegitimate comparisons"
struct intentionally_incomplete;
typedef struct intentionally_incomplete *ndnr_accession;
#define NDNR_NULL_ACCESSION ((ndnr_accession)(0))
#define NDNR_MIN_ACCESSION ((ndnr_accession)(0x10000000))
#define NDNR_MAX_ACCESSION ((ndnr_accession)(0x7fffffff))
#elif (defined(NDNLINT) && (NDNLINT == 3))
#error "Not expected to work - this is for detecting illegitimate casts"
typedef struct ndnr_accession_rep {unsigned a; unsigned b;} ndnr_accession;
struct ndnr_accession_rep ndnr_null_accession;
struct ndnr_accession_rep ndnr_min_accession;
struct ndnr_accession_rep ndnr_max_accession;
#define NDNR_NULL_ACCESSION ndnr_null_accession
#define NDNR_MIN_ACCESSION ndnr_min_accession
#define NDNR_MAX_ACCESSION ndnr_max_accession
#else
typedef uint_least64_t ndnr_accession;
#define NDNR_NULL_ACCESSION ((ndnr_accession)(0))
#define NDNR_MIN_ACCESSION ((ndnr_accession)(1))
#define NDNR_MAX_ACCESSION ((ndnr_accession)(~NDNR_NULL_ACCESSION))
#endif
#define NDNR_NOT_COMPARABLE (-2)
/* Encode/decode a ndnr_accession as an unsigned number. */
uintmax_t ndnr_accession_encode(struct ndnr_handle *, ndnr_accession);
ndnr_accession ndnr_accession_decode(struct ndnr_handle *, uintmax_t);
/* Return 1 if x dominates (is newer than) y, 0 if x equals y, -1 if y dominates x,
* and NDNR_NOT_COMPARABLE if the ordering is not determined
*/
int ndnr_accession_compare(struct ndnr_handle *ndnr, ndnr_accession x, ndnr_accession y);
/* Repository-specific high water marks */
/* XXX - ndnr_hwm should be a distinct type */
typedef uintmax_t ndnr_hwm;
#define NDNR_NULL_HWM ((ndnr_hwm)(0))
/* Encode a high water mark as an unsigned number */
uintmax_t ndnr_hwm_encode(struct ndnr_handle *, ndnr_hwm);
ndnr_hwm ndnr_hwm_decode(struct ndnr_handle *, uintmax_t);
/* Return 1 if a is in the hwm set, 0 if not, -1 if unknown. */
int ndnr_acc_in_hwm(struct ndnr_handle *, ndnr_accession a, ndnr_hwm hwm);
/* Produce a new high water mark that includes the given content */
ndnr_hwm ndnr_hwm_update(struct ndnr_handle *, ndnr_hwm, ndnr_accession);
ndnr_hwm ndnr_hwm_merge(struct ndnr_handle *, ndnr_hwm, ndnr_hwm);
/* Return 1 if x dominates y, 0 if x equals y, -1 if y dominates x,
* and NDNR_NOT_COMPARABLE if the ordering is not determined
*/
int ndnr_hwm_compare(struct ndnr_handle *ndnr, ndnr_hwm x, ndnr_hwm y);
/**
* A cookie is used as a more ephemeral way of holding a reference to a
* content object, without the danger of an undetected dangling reference
* when the in-memory content handle is destroyed. This is for internal
* data structures such as queues or enumeration states, but should not
* be stored in any long-term way. Use a ndnr_accession, content name, or
* digest for that.
*
* Holding a cookie does not prevent the in-memory content handle from being
* destroyed, either explicitly or to conserve resources.
*/
typedef unsigned ndnr_cookie;
/** Logger type (ndnr_logger) */
typedef int (*ndnr_logger)(void *loggerdata, const char *format, va_list ap);
/**
* This is true if we should log at the given level.
*
*/
#define NDNSHOULDLOG(h, who, level) (((h)->debug >= (level)) != 0)
/* XXX - these are the historical bitfields. */
#define LM_2 2
#define LM_4 4
#define LM_8 8
#define LM_16 16
#define LM_32 32
#define LM_64 64
#define LM_128 128
/**
* Limit on how many active sync enumerations we are willing to have going.
*/
#define NDNR_MAX_ENUM 64
/**
* We pass this handle almost everywhere within ndnr
*/
struct ndnr_handle {
unsigned char ndnr_id[32]; /**< sha256 digest of our public key */
struct ndn_charbuf *ndnr_keyid; /**< public key digest in keyid format %C1.M.K.%00... */
struct hashtb *nameprefix_tab; /**< keyed by name prefix components */
struct hashtb *propagating_tab; /**< keyed by nonce */
struct hashtb *enum_state_tab; /**< keyed by enumeration interest */
struct ndn_indexbuf *skiplinks; /**< skiplist for content-ordered ops */
struct ndn_btree *btree; /**< btree index of content */
unsigned forward_to_gen; /**< for forward_to updates */
unsigned face_gen; /**< filedesc generation number */
unsigned face_rover; /**< for filedesc allocation */
unsigned face_limit; /**< current number of fdholder slots */
struct fdholder **fdholder_by_fd; /**< array with face_limit elements */
int active_in_fd; /**< data currently being indexed */
int active_out_fd; /**< repo file we will write to */
int repofile1_fd; /**< read-only access to repoFile1 */
off_t startupbytes; /**< repoFile1 size at startup */
off_t stable; /**< repoFile1 size at shutdown */
struct ndn_scheduled_event *reaper;
struct ndn_scheduled_event *age;
struct ndn_scheduled_event *clean;
struct ndn_scheduled_event *age_forwarding;
struct ndn_scheduled_event *reap_enumerations; /**< cleans out old enumeration state */
struct ndn_scheduled_event *index_cleaner; /**< writes out btree nodes */
struct ndn_indexbuf *toclean; /**< for index_cleaner use */
const char *portstr; /**< port number for status display */
nfds_t nfds; /**< number of entries in fds array */
struct pollfd *fds; /**< used for poll system call */
struct ndn_gettime ticktock; /**< our time generator */
long sec; /**< cached gettime seconds */
unsigned usec; /**< cached gettime microseconds */
long starttime; /**< ndnr start time, in seconds */
unsigned starttime_usec; /**< ndnr start time fractional part */
struct ndn_schedule *sched; /**< our schedule */
struct ndn_charbuf *scratch_charbuf; /**< one-slot scratch cache */
struct ndn_indexbuf *scratch_indexbuf; /**< one-slot scratch cache */
/** Next two fields are used for direct cookie-to-content table */
unsigned cookie_limit; /**< content_by_cookie size(power of 2)*/
struct content_entry **content_by_cookie; /**< cookie-to-content table */
struct hashtb *content_by_accession_tab; /**< keyed by accession */
ndnr_cookie cookie; /**< newest used cookie number */
ndnr_cookie min_stale; /**< smallest cookie of stale content */
ndnr_cookie max_stale; /**< largest cookie of stale content */
ndnr_cookie trim_rover; /**< where we left off trimming */
unsigned long n_stale; /**< Number of stale content objects */
struct ndn_indexbuf *unsol; /**< unsolicited content */
unsigned long cob_count; /**< count of accessioned content objects in memory */
unsigned long cob_limit; /**< trim when we get beyond this */
unsigned long oldformatcontent;
unsigned long oldformatcontentgrumble;
unsigned long oldformatinterests;
unsigned long oldformatinterestgrumble;
unsigned long content_dups_recvd;
unsigned long content_items_sent;
unsigned long interests_accepted;
unsigned long interests_dropped;
unsigned long interests_sent;
unsigned long interests_stuffed;
unsigned long content_from_accession_hits;
unsigned long content_from_accession_misses;
unsigned long count_lmc_found;
unsigned long count_lmc_found_iters;
unsigned long count_lmc_notfound;
unsigned long count_lmc_notfound_iters;
unsigned long count_rmc_found;
unsigned long count_rmc_found_iters;
unsigned long count_rmc_notfound;
unsigned long count_rmc_notfound_iters;
/* Control switches and knobs */
unsigned start_write_scope_limit; /**< Scope on start-write must be <= this value. 3 indicates unlimited */
unsigned short seed[3]; /**< for PRNG */
int running; /**< true while should be running */
int debug; /**< For controlling debug output */
int syncdebug; /**< For controlling debug output from sync */
ndnr_logger logger; /**< For debug output */
void *loggerdata; /**< Passed to logger */
int logbreak; /**< see ndnr_msg() */
unsigned long logtime; /**< see ndnr_msg() */
int logpid; /**< see ndnr_msg() */
int flood; /**< Internal control for auto-reg */
unsigned interest_faceid; /**< for self_reg internal client */
const char *progname; /**< our name, for locating helpers */
struct ndn *direct_client; /**< this talks directly with ndnd */
struct ndn *internal_client; /**< internal client */
struct fdholder *face0; /**< special fdholder for internal client */
struct ndn_charbuf *service_ndnb; /**< for local service discovery */
struct ndn_charbuf *neighbor_ndnb; /**< for neighbor service discovery */
struct ndnr_parsed_policy *parsed_policy; /**< offsets for parsed fields of policy */
struct ndn_charbuf *policy_name;
struct ndn_charbuf *policy_link_cob;
struct ndn_seqwriter *notice; /**< for notices of status changes */
struct ndn_indexbuf *chface; /**< faceids w/ recent status changes */
struct ndn_scheduled_event *internal_client_refresh;
struct ndn_scheduled_event *direct_client_refresh;
struct ndn_scheduled_event *notice_push;
/* items related to sync/repo integration */
struct sync_plumbing *sync_plumbing; /**< encapsulates methods and data */
struct SyncBaseStruct *sync_base;
ndnr_accession notify_after; /**< starting item for notifying sync */
ndnr_accession active_enum[NDNR_MAX_ENUM]; /**< active sync enumerations */
const char *directory; /**< the repository directory */
#ifdef CAREPO
struct hash_store* hashstore;
#endif
};
struct content_queue {
unsigned burst_nsec; /**< nsec per KByte, limits burst rate */
unsigned min_usec; /**< minimum delay for this queue */
unsigned rand_usec; /**< randomization range */
unsigned ready; /**< # that have waited enough */
unsigned nrun; /**< # sent since last randomized delay */
struct ndn_indexbuf *send_queue; /**< cookie numbers of pending content */
struct ndn_scheduled_event *sender;
};
enum cq_delay_class {
NDN_CQ_ASAP,
NDN_CQ_NORMAL,
NDN_CQ_SLOW,
NDN_CQ_N
};
/**
* fdholder meter index
*/
enum ndnr_face_meter_index {
FM_BYTI,
FM_BYTO,
FM_DATI,
FM_INTO,
FM_DATO,
FM_INTI,
NDNR_FACE_METER_N
};
/**
* Each fdholder is referenced by its file descriptor.
*/
struct fdholder {
unsigned filedesc; /**< file descriptor */
int flags; /**< NDNR_FACE_* fdholder flags */
unsigned recvcount; /**< for activity level monitoring */
struct content_queue *q[NDN_CQ_N]; /**< outgoing content, per delay class */
off_t bufoffset;
struct ndn_charbuf *inbuf; /** Buffered input data */
struct ndn_skeleton_decoder decoder;
size_t outbufindex; /** Buffered output data */
struct ndn_charbuf *outbuf;
struct ndn_charbuf *name; /** a sockaddr or file name, depending on flags */
int pending_interests;
struct ndnr_meter *meter[NDNR_FACE_METER_N];
};
/** fdholder flags */
#define NDNR_FACE_DGRAM (1 << 1) /**< Datagram interface, respect packets */
#define NDNR_FACE_GG (1 << 2) /**< Considered friendly */
#define NDNR_FACE_LOCAL (1 << 3) /**< PF_UNIX socket */
#define NDNR_FACE_INET (1 << 4) /**< IPv4 */
#define NDNR_FACE_INET6 (1 << 6) /**< IPv6 */
#define NDNR_FACE_NOSEND (1 << 8) /**< Don't send anymore */
#define NDNR_FACE_UNDECIDED (1 << 9) /**< Might not be talking ndn */
#define NDNR_FACE_PERMANENT (1 << 10) /**< No timeout for inactivity */
#define NDNR_FACE_CONNECTING (1 << 11) /**< Connect in progress */
#define NDNR_FACE_LOOPBACK (1 << 12) /**< v4 or v6 loopback address */
#define NDNR_FACE_CLOSING (1 << 13) /**< close stream when output is done */
#define NDNR_FACE_PASSIVE (1 << 14) /**< a listener or a bound dgram socket */
#define NDNR_FACE_NORECV (1 << 15) /**< use for sending only */
#define NDNR_FACE_REPODATA (1 << 19) /** A repository log-structured data file */
#define NDNR_FACE_NDND (1 << 20) /** A connection to our ndnd */
#define NDNR_FACE_SOCKMASK (NDNR_FACE_DGRAM | NDNR_FACE_INET | NDNR_FACE_INET6 | NDNR_FACE_LOCAL)
#define NDN_NOFACEID (-1) /** denotes no fdholder */
/**
* A pointer to this is used as a handle for a content object that we
* currently care about. Most details are private to the implementation.
*/
struct content_entry;
/**
* content_entry flags
*/
#define NDN_CONTENT_ENTRY_SLOWSEND 1
#define NDN_CONTENT_ENTRY_STALE 2
#define NDN_CONTENT_ENTRY_PRECIOUS 4
#define NDN_CONTENT_ENTRY_STABLE 8 /**< Repository-backed */
/**
* The content_by_accession hash table, keyed by accession, holds
* entries that have a known accession.
*/
struct content_by_accession_entry {
struct content_entry *content;
};
/**
* The propagating interest hash table is keyed by Nonce.
*
* While the interest is pending, the pe is also kept in a doubly-linked
* list off of a nameprefix_entry.
*
* When the interest is consumed, the pe is removed from the doubly-linked
* list and is cleaned up by freeing unnecessary bits (including the interest
* message itself). It remains in the hash table for a time, in order to catch
* duplicate nonces.
*/
struct propagating_entry {
struct propagating_entry *next;
struct propagating_entry *prev;
unsigned flags; /**< NDN_PR_xxx */
unsigned filedesc; /**< origin of the interest, dest for matches */
int usec; /**< usec until timeout */
int sent; /**< leading faceids of outbound processed */
struct ndn_indexbuf *outbound; /**< in order of use */
unsigned char *interest_msg; /**< pending interest message */
unsigned size; /**< size in bytes of interest_msg */
int fgen; /**< decide if outbound is stale */
};
// XXX - with new outbound/sent repr, some of these flags may not be needed.
#define NDN_PR_UNSENT 0x01 /**< interest has not been sent anywhere yet */
#define NDN_PR_WAIT1 0x02 /**< interest has been sent to one place */
#define NDN_PR_STUFFED1 0x04 /**< was stuffed before sent anywhere else */
#define NDN_PR_TAP 0x08 /**< at least one tap fdholder is present */
#define NDN_PR_EQV 0x10 /**< a younger similar interest exists */
#define NDN_PR_SCOPE0 0x20 /**< interest scope is 0 */
#define NDN_PR_SCOPE1 0x40 /**< interest scope is 1 (this host) */
#define NDN_PR_SCOPE2 0x80 /**< interest scope is 2 (immediate neighborhood) */
/**
* The nameprefix hash table is keyed by the Component elements of
* the Name prefix.
*/
struct nameprefix_entry {
struct propagating_entry pe_head; /**< list head for propagating entries */
struct ndn_indexbuf *forward_to; /**< faceids to forward to */
struct ndn_indexbuf *tap; /**< faceids to forward to as tap*/
struct ndn_forwarding *forwarding; /**< detailed forwarding info */
struct nameprefix_entry *parent; /**< link to next-shorter prefix */
int children; /**< number of children */
unsigned flags; /**< NDN_FORW_* flags about namespace */
int fgen; /**< used to decide when forward_to is stale */
unsigned src; /**< filedesc of recent content source */
unsigned osrc; /**< and of older matching content */
unsigned usec; /**< response-time prediction */
};
/**
* Keeps track of the faces that interests matching a given name prefix may be
* forwarded to.
*/
struct ndn_forwarding {
unsigned filedesc; /**< locally unique number identifying fdholder */
unsigned flags; /**< NDN_FORW_* - c.f. <ndn/reg_mgnt.h> */
int expires; /**< time remaining, in seconds */
struct ndn_forwarding *next;
};
/**
* Keeps track of the state of running and recently completed enumerations
* The enum_state hash table is keyed by the interest up to the segment id
*/
enum es_active_state {
ES_PENDING = -1,
ES_INACTIVE = 0,
ES_ACTIVE = 1,
ES_ACTIVE_PENDING_INACTIVE = 2
};
#define ENUM_N_COBS 9
struct enum_state {
struct ndn_charbuf *name;
struct content_entry *content;
struct ndn_charbuf *reply_body;
struct ndn_charbuf *interest;
struct ndn_indexbuf *interest_comps;
struct ndn_charbuf *cob[ENUM_N_COBS];
int cob_deferred[ENUM_N_COBS];
intmax_t next_segment;
ndnr_cookie starting_cookie;
enum es_active_state active;
long lifetime;
long lastuse_sec;
unsigned lastuse_usec;
};
/**
*/
#define NDN_FORW_PFXO (NDN_FORW_ADVERTISE | NDN_FORW_CAPTURE | NDN_FORW_LOCAL)
#define NDN_FORW_REFRESHED (1 << 16) /**< private to ndnr */
/**
* Determines how frequently we age our forwarding entries
*/
#define NDN_FWU_SECS 5
/**
* URIs for prefixes served by the internal client
*/
#define NDNRID_LOCAL_URI "ndn:/%C1.M.S.localhost/%C1.M.SRV/repository/KEY"
#define NDNRID_NEIGHBOR_URI "ndn:/%C1.M.S.neighborhood/%C1.M.SRV/repository/KEY"
#define NDNRID_POLICY_URI "ndn:/%C1.M.S.localhost/%C1.M.SRV/repository/POLICY"
#define PUBLIC
struct ndnr_handle *r_init_create(const char *, ndnr_logger, void *);
void r_init_run(struct ndnr_handle *h);
void r_init_destroy(struct ndnr_handle **);
#endif
|
yoursunny/carepo
|
rabin/rabin_polynomial.c
|
/*
* rabin_polynomial.c
*
* Created by <NAME> on 09-March-2011.
*
* Copyright (c) 2011 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the project's author nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "rabin_polynomial.h"
#include "rabin_polynomial_constants.h"
uint64_t rabin_polynomial_prime=RAB_POLYNOMIAL_REM;
unsigned int rabin_sliding_window_size=RAB_POLYNOMIAL_WIN_SIZE;
unsigned int rabin_polynomial_max_block_size=RAB_MAX_BLOCK_SIZE;
unsigned int rabin_polynomial_min_block_size=RAB_MIN_BLOCK_SIZE;
unsigned int rabin_polynomial_average_block_size=RAB_POLYNOMIAL_AVG_BLOCK_SIZE;
int rabin_poly_init_completed=0;
uint64_t *polynomial_lookup_buf;
/**
* Prints the list of rabin polynomials to the given file
*/
void print_rabin_poly_list_to_file(FILE *out_file, struct rabin_polynomial *poly) {
struct rabin_polynomial *cur_poly=poly;
while(cur_poly != NULL) {
print_rabin_poly_to_file(out_file,cur_poly,1);
cur_poly=cur_poly->next_polynomial;
}
}
/**
* Prints a given rabin polynomial to file in the format:
* start,length hash
*/
void print_rabin_poly_to_file(FILE *out_file, struct rabin_polynomial *poly,int new_line) {
if(poly == NULL)
return;
fprintf(out_file, "%" PRIu64 ",%" PRIu16 " %" PRIu64 "",poly->start,poly->length,poly->polynomial);
if(new_line)
fprintf(out_file, "\n");
}
/*
* Initialize the algorithm with the default params.
*/
int initialize_rabin_polynomial_defaults() {
if(rabin_poly_init_completed != 0)
return 1; //Nothing to do
polynomial_lookup_buf=malloc(sizeof(uint64_t)*RAB_POLYNOMIAL_MAX_WIN_SIZE);
if(polynomial_lookup_buf == NULL) {
fprintf(stderr, "Could not initialize rabin polynomial lookaside buffer, out of memory\n");
return 0;
}
int index=0;
uint64_t curPower=1;
//Initialize the lookup values we will need later
for(index=0;index<RAB_POLYNOMIAL_MAX_WIN_SIZE;index++) {
//TODO check if max window size is a power of 2
//and if so use shifters instead of multiplication
polynomial_lookup_buf[index]=curPower;
curPower*=rabin_polynomial_prime;
}
rabin_poly_init_completed=1;
return 1;
}
/**
* Modifies the average block size, checking to make sure it doesn't
* go above the max or below the min
*/
void change_average_rabin_block_size(int increment_mode) {
if(increment_mode && rabin_polynomial_average_block_size < rabin_polynomial_max_block_size) {
rabin_polynomial_average_block_size++;
} else if(!increment_mode && rabin_polynomial_average_block_size > rabin_polynomial_min_block_size) {
rabin_polynomial_average_block_size--;
}
}
/**
* Initalizes the algorithm with the provided paramters
*/
int initialize_rabin_polynomial(uint64_t prime, unsigned max_size, unsigned int min_size, unsigned int average_block_size) {
rabin_polynomial_prime=prime;
rabin_polynomial_max_block_size=max_size;
rabin_polynomial_min_block_size=min_size;
rabin_polynomial_average_block_size=average_block_size;
return initialize_rabin_polynomial_defaults();
}
/*
* Generate a new fingerprint with the given info and add it to the tail
*/
struct rabin_polynomial *gen_new_polynomial(struct rabin_polynomial *tail, uint64_t total_len, uint16_t length, uint64_t rab_sum) {
struct rabin_polynomial *next=malloc(sizeof(struct rabin_polynomial));
if(next == NULL) {
fprintf(stderr, "Could not allocate memory for rabin fingerprint record!");
return NULL;
}
if(tail != NULL)
tail->next_polynomial=next;
next->next_polynomial=NULL;
next->start=total_len-length;
next->length=length;
next->polynomial=rab_sum;
return next;
}
/*
* Writes out the fingerprint list in binary form
*/
int write_rabin_fingerprints_to_binary_file(FILE *file,struct rabin_polynomial *head) {
struct rabin_polynomial *poly=head;
while(poly != NULL) {
size_t ret_val=fwrite(poly, sizeof(struct rabin_polynomial), 1, file);
if(ret_val == 0) {
fprintf(stderr, "Could not write rabin polynomials to file.");
return -1;
}
poly=poly->next_polynomial;
}
return 0;
}
/**
* Reads a list of rabin fingerprints in binary form
*/
struct rabin_polynomial *read_rabin_polys_from_file_binary(FILE *file) {
struct rabin_polynomial *head=gen_new_polynomial(NULL,0,0,0);
struct rabin_polynomial *tail=head;
if(head == NULL)
return NULL;
size_t polys_read=fread(head, sizeof(struct rabin_polynomial), 1, file);
while(polys_read != 0 && tail != NULL) {
struct rabin_polynomial *cur_poly=gen_new_polynomial(tail,0,0,0);
fread(cur_poly, sizeof(struct rabin_polynomial), 1, file);
tail=cur_poly;
}
return head;
}
/*
* Deallocates the entire fingerprint list
*/
void free_rabin_fingerprint_list(struct rabin_polynomial *head) {
struct rabin_polynomial *cur_poly,*next_poly;
cur_poly=head;
while(cur_poly != NULL) {
next_poly=cur_poly->next_polynomial;
free(cur_poly);
cur_poly=next_poly;
}
}
/*
* Gets the list of fingerprints from the given file
*/
struct rabin_polynomial *get_file_rabin_polys(FILE *file_to_read) {
initialize_rabin_polynomial_defaults();
struct rab_block_info *block=NULL;
char *file_data=malloc(RAB_FILE_READ_BUF_SIZE);
if(file_data == NULL) {
fprintf(stderr,"Could not allocate buffer for reading input file to rabin polynomial.\n");
return NULL;
}
ssize_t bytes_read=fread(file_data,1,RAB_FILE_READ_BUF_SIZE,file_to_read);
while(bytes_read != 0) {
block=read_rabin_block(file_data,bytes_read,block);
bytes_read=fread(file_data,1,RAB_FILE_READ_BUF_SIZE,file_to_read);
}
free(file_data);
struct rabin_polynomial *head=block->head;
free(block);
return head;
}
/**
* Allocates an empty block
*/
struct rab_block_info *init_empty_block(void) {
initialize_rabin_polynomial_defaults();
struct rab_block_info *block=malloc(sizeof(struct rab_block_info));
if(block == NULL) {
fprintf(stderr,"Could not allocate rabin polynomial block, no memory left!\n");
return NULL;
}
block->head=gen_new_polynomial(NULL,0,0,0);
if(block->head == NULL)
return NULL; //Couldn't allocate memory
block->tail=block->head;
block->cur_roll_checksum=0;
block->total_bytes_read=0;
block->window_pos=0;
block->current_poly_finished=0;
block->current_window_data=malloc(sizeof(char)*rabin_sliding_window_size);
if(block->current_window_data == NULL) {
fprintf(stderr,"Could not allocate buffer for sliding window data!\n");
free(block);
return NULL;
}
int i;
for(i=0;i<rabin_sliding_window_size;i++) {
block->current_window_data[i]=0;
}
return block;
}
/**
* Reads a block of memory and generates a rabin fingerprint list from it.
* Since most of the time we will not end on a border, the function returns
* a block struct, which keeps track of the current blocksum and rolling checksum
*/
struct rab_block_info *read_rabin_block(void *buf, ssize_t size, struct rab_block_info *cur_block) {
struct rab_block_info *block;
if(cur_block == NULL) {
block=init_empty_block();
if(block == NULL)
return NULL;
}
else {
block=cur_block;
}
//We ended on a border, gen a new tail
if(block->current_poly_finished) {
struct rabin_polynomial *new_poly=gen_new_polynomial(NULL,0,0,0);
block->tail->next_polynomial=new_poly;
block->tail=new_poly;
block->current_poly_finished=0;
}
ssize_t i;
for(i=0;i<size;i++) {
char cur_byte=*((char *)(buf)+i);
char pushed_out=block->current_window_data[block->window_pos];
block->current_window_data[block->window_pos]=cur_byte;
block->cur_roll_checksum=(block->cur_roll_checksum*rabin_polynomial_prime)+cur_byte;
block->tail->polynomial=(block->tail->polynomial*rabin_polynomial_prime)+cur_byte;
block->cur_roll_checksum-=(pushed_out*polynomial_lookup_buf[rabin_sliding_window_size]);
block->window_pos++;
block->total_bytes_read++;
block->tail->length++;
if(block->window_pos == rabin_sliding_window_size) //Loop back around
block->window_pos=0;
//If we hit our special value or reached the max win size create a new block
if((block->tail->length >= rabin_polynomial_min_block_size && (block->cur_roll_checksum % rabin_polynomial_average_block_size) == rabin_polynomial_prime)|| block->tail->length == rabin_polynomial_max_block_size) {
block->tail->start=block->total_bytes_read-block->tail->length;
struct rabin_polynomial *new_poly=gen_new_polynomial(NULL,0,0,0);
block->tail->next_polynomial=new_poly;
block->tail=new_poly;
if(i==size-1)
block->current_poly_finished=1;
}
}
return block;
}
|
yoursunny/carepo
|
repo/ndnr_match.c
|
/**
* @file ndnr_match.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/btree_content.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_match.h"
#include "ndnr_forwarding.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
#include "ndnr_sendq.h"
#include "ndnr_store.h"
PUBLIC void
r_match_consume_interest(struct ndnr_handle *h, struct propagating_entry *pe)
{
struct fdholder *fdholder = NULL;
ndn_indexbuf_destroy(&pe->outbound);
if (pe->interest_msg != NULL) {
free(pe->interest_msg);
pe->interest_msg = NULL;
fdholder = r_io_fdholder_from_fd(h, pe->filedesc);
if (fdholder != NULL)
fdholder->pending_interests -= 1;
}
if (pe->next != NULL) {
pe->next->prev = pe->prev;
pe->prev->next = pe->next;
pe->next = pe->prev = NULL;
}
pe->usec = 0;
}
/**
* Consume matching interests
* given a nameprefix_entry and a piece of content.
*
* If fdholder is not NULL, pay attention only to interests from that fdholder.
* It is allowed to pass NULL for pc, but if you have a (valid) one it
* will avoid a re-parse.
* @returns number of matches found.
*/
PUBLIC int
r_match_consume_matching_interests(struct ndnr_handle *h,
struct nameprefix_entry *npe,
struct content_entry *content,
struct ndn_parsed_ContentObject *pc,
struct fdholder *fdholder)
{
int matches = 0;
struct propagating_entry *head;
struct propagating_entry *next;
struct propagating_entry *p;
const unsigned char *content_msg;
size_t content_size;
struct fdholder *f;
head = &npe->pe_head;
// XXX - i do not think this is called in practice
content_msg = r_store_content_base(h, content);
content_size = r_store_content_size(h, content);
f = fdholder;
for (p = head->next; p != head; p = next) {
next = p->next;
if (p->interest_msg != NULL &&
((fdholder == NULL && (f = r_io_fdholder_from_fd(h, p->filedesc)) != NULL) ||
(fdholder != NULL && p->filedesc == fdholder->filedesc))) {
if (ndn_content_matches_interest(content_msg, content_size, 1, pc,
p->interest_msg, p->size, NULL)) {
r_sendq_face_send_queue_insert(h, f, content);
if (NDNSHOULDLOG(h, (32 | 8), NDNL_FINE))
ndnr_debug_ndnb(h, __LINE__, "consume", f,
p->interest_msg, p->size);
matches += 1;
r_match_consume_interest(h, p);
}
}
}
return(matches);
}
/**
* Find and consume interests that match given content.
*
* Schedules the sending of the content.
* If fdholder is not NULL, pay attention only to interests from that fdholder.
* It is allowed to pass NULL for pc, but if you have a (valid) one it
* will avoid a re-parse.
* For new content, from_face is the source; for old content, from_face is NULL.
* @returns number of matches, or -1 if the new content should be dropped.
*/
PUBLIC int
r_match_match_interests(struct ndnr_handle *h, struct content_entry *content,
struct ndn_parsed_ContentObject *pc,
struct fdholder *fdholder, struct fdholder *from_face)
{
int n_matched = 0;
int new_matches;
struct nameprefix_entry *npe = NULL;
int ci = 0;
// int cm = 0;
struct ndn_charbuf *name = NULL;
struct ndn_indexbuf *namecomps = NULL;
unsigned c0 = 0;
name = ndn_charbuf_create();
ndn_name_init(name);
r_store_name_append_components(name, h, content, 0, -1);
namecomps = ndn_indexbuf_create();
ndn_name_split(name, namecomps);
c0 = namecomps->buf[0];
for (ci = namecomps->n - 1; ci >= 0; ci--) {
int size = namecomps->buf[ci] - c0;
npe = hashtb_lookup(h->nameprefix_tab, name->buf + c0, size);
if (npe != NULL)
break;
}
ndn_charbuf_destroy(&name);
ndn_indexbuf_destroy(&namecomps);
for (; npe != NULL; npe = npe->parent, ci--) {
// if (npe->fgen != h->forward_to_gen)
// r_fwd_update_forward_to(h, npe);
if (from_face != NULL && (npe->flags & NDN_FORW_LOCAL) != 0 &&
(from_face->flags & NDNR_FACE_GG) == 0)
return(-1);
new_matches = r_match_consume_matching_interests(h, npe, content, pc, fdholder);
// if (from_face != NULL && (new_matches != 0 || ci + 1 == cm))
// note_content_from(h, npe, from_face->filedesc, ci);
if (new_matches != 0) {
// cm = ci; /* update stats for this prefix and one shorter */
n_matched += new_matches;
}
}
return(n_matched);
}
|
yoursunny/carepo
|
rabin/rabin_polynomial.h
|
/*
* rabin_polynomial.h
*
* Created by <NAME> on 09-March-2011.
*
* Copyright (c) 2011 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the project's author nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <inttypes.h>
#include <stdio.h>
#ifdef __APPLE__
#include <unistd.h>
#endif
#ifndef JOEL_TUCCI_RABIN_POLY_C
#define JOEL_TUCCI_RABIN_POLY_C
extern uint64_t rabin_polynomial_prime;
extern unsigned int rabin_sliding_window_size;
extern unsigned int rabin_polynomial_max_block_size;
extern unsigned int rabin_polynomial_min_block_size;
extern unsigned int rabin_polynomial_average_block_size;
/**
* All the info needed for a rabin polynomial list, namely the start position in the file,
* the length of the block, the checksum, and the next polynomial
*/
struct rabin_polynomial{
uint64_t start;
uint16_t length;
uint64_t polynomial;
struct rabin_polynomial *next_polynomial;
};
/*
* Struct used to keep track of rabin polynomials for blocks of memory,
* since the blocks may or may not end on a boundary, we have to save the
* current rolling checksum, length, and block checksum so that we can
* pick up were we left off
*/
struct rab_block_info {
struct rabin_polynomial *head;
struct rabin_polynomial *tail;
uint64_t total_bytes_read;
unsigned int window_pos;
char current_poly_finished;
char *current_window_data;
uint64_t cur_roll_checksum;
uint64_t current_block_checksum;
uint64_t curr_roll_offset;
};
void change_average_rabin_block_size(int increment_mode);
int write_rabin_fingerprints_to_binary_file(FILE *file,struct rabin_polynomial *head);
struct rabin_polynomial *read_rabin_polys_from_file_binary(FILE *file);
void free_rabin_fingerprint_list(struct rabin_polynomial *head);
struct rabin_polynomial *gen_new_polynomial(struct rabin_polynomial *tail, uint64_t total_len, uint16_t length, uint64_t rab_sum);
int initialize_rabin_polynomial_defaults(void);
int initialize_rabin_polynomial(uint64_t prime, unsigned max_size, unsigned int min_size, unsigned int average_block_size);
void print_rabin_poly_to_file(FILE *out_file, struct rabin_polynomial *poly,int new_line);
void print_rabin_poly_list_to_file(FILE *out_file, struct rabin_polynomial *poly);
/*
* Reads the block given, continuing using the info given in rab_block
*/
struct rab_block_info *read_rabin_block(void *buf, ssize_t size, struct rab_block_info *cur_block);
struct rabin_polynomial *get_file_rabin_polys(FILE *file_to_read);
#endif
|
yoursunny/carepo
|
segment/writer.c
|
#include "writer.h"
struct file_writer* file_writer_ctor(struct segment_list* sl, FILE* file, struct ndn* h, struct ndn_charbuf* name, bool sign_segments) {
struct file_writer* self = calloc(1, sizeof(*self));
self->h = h;
self->file = file;
self->name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(self->name, name);
ndn_create_version(self->h, self->name, NDN_V_NOW, 0, 0);
self->name_comps = ndn_indexbuf_create();
ndn_name_split(self->name, self->name_comps);
self->sl = sl;
self->sign_segments = sign_segments;
self->sent_segments = calloc(sl->count, sizeof(bool));
self->remaining_segments = sl->count;
self->metadata_name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(self->metadata_name, self->name);
ndn_name_from_uri(self->metadata_name, "%C1.META/SHA256");
ndn_create_version(self->h, self->metadata_name, NDN_V_NOW, 0, 0);
self->metadata = ndn_charbuf_create();
segment_list_to_metadata(sl, self->metadata);
self->total_metadata_blocks = self->remaining_metadata_blocks = self->metadata->length/FILE_WRITER_METADATA_BLOCKSZ + (self->metadata->length%FILE_WRITER_METADATA_BLOCKSZ == 0 ? 0 : 1);
self->sent_metadata_blocks = calloc(self->total_metadata_blocks, sizeof(bool));
LOG("file_writer_ctor "); LOG_name(self->name->buf, self->name->length);
LOG("\n %" PRIu32 " segments, %d metadata blocks\n", self->sl->count, self->total_metadata_blocks);
return self;
}
void file_writer_dtor(struct file_writer** selfp) {
struct file_writer* self = *selfp;
if (self == NULL) return;
ndn_charbuf_destroy(&self->name);
ndn_indexbuf_destroy(&self->name_comps);
ndn_charbuf_destroy(&self->metadata_name);
free(self->sent_segments);
free(self->sent_metadata_blocks);
free(self);
*selfp = NULL;
}
bool file_writer_run(struct file_writer* self) {
int res;
self->closure = calloc(1, sizeof(*self->closure));
self->closure->p = &file_writer_incoming_interest;
self->closure->data = self;
res = ndn_set_interest_filter(self->h, self->name, self->closure);
if (res < 0) return false;
if (!file_writer_startwrite(self)) return false;
do {
self->recent_interests = 0;
ndn_run(self->h, FILE_WRITER_RUN_TIMEOUT_INTERVAL);
} while ((self->remaining_segments > 0 || self->remaining_metadata_blocks > 0) && (self->recent_interests > 0));
if (self->remaining_segments == 0 && self->remaining_metadata_blocks == 0) {
ndn_set_interest_filter(self->h, self->name, NULL);
ndn_run(self->h, 1);
LOG("file_writer_run OK\n");
return true;
}
LOG("file_writer_run TIMEOUT\n");
return false;
}
bool file_writer_startwrite(struct file_writer* self) {
int res;
struct ndn_charbuf* sw_name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(sw_name, self->name);
ndn_name_from_uri(sw_name, "%C1.R.sw");
ndn_name_append_nonce(sw_name);
res = ndn_get(self->h, sw_name, NULL, FILE_WRITER_STARTWRITE_TIMEOUT, NULL, NULL, NULL, 0);
if (res < 0) { ndn_charbuf_destroy(&sw_name); return false; }
ndn_charbuf_reset(sw_name);
ndn_charbuf_append_charbuf(sw_name, self->metadata_name);
ndn_name_from_uri(sw_name, "%C1.R.sw");
ndn_name_append_nonce(sw_name);
res = ndn_get(self->h, sw_name, NULL, FILE_WRITER_STARTWRITE_TIMEOUT, NULL, NULL, NULL, 0);
if (res < 0) { ndn_charbuf_destroy(&sw_name); return false; }
LOG("file_writer_startwrite OK\n");
ndn_charbuf_destroy(&sw_name); return true;
}
enum ndn_upcall_res file_writer_incoming_interest(struct ndn_closure* closure, enum ndn_upcall_kind kind, struct ndn_upcall_info* info) {
if (kind == NDN_UPCALL_FINAL) free(closure);
struct file_writer* self = closure->data;
assert(self != NULL && closure == self->closure);
if (kind != NDN_UPCALL_INTEREST) return NDN_UPCALL_RESULT_OK;
LOG("file_writer_incoming_interest "); LOG_name(info->interest_ndnb+info->pi->offset[NDN_PI_B_Name], info->pi->offset[NDN_PI_E_Name]-info->pi->offset[NDN_PI_B_Name]);
LOG("\n");
++self->recent_interests;
bool ok = false;
if (info->pi->prefix_comps == self->name_comps->n) {
ok = file_writer_respond_segment(self, info);
} else if (info->pi->prefix_comps == self->name_comps->n + 3) {
ok = file_writer_respond_metadata(self, info);
}
return ok ? NDN_UPCALL_RESULT_INTEREST_CONSUMED : NDN_UPCALL_RESULT_OK;
}
uintmax_t file_writer_extract_number(struct ndn_upcall_info* info) {
const uint8_t* comp; size_t compsz;
int res = ndn_name_comp_get(info->interest_ndnb, info->interest_comps, info->pi->prefix_comps-1, &comp, &compsz);
if (res == -1 || compsz == 0 || comp[0] != '\0') return (uintmax_t)-1;
uintmax_t n = 0;
for (size_t i = 1; i < compsz; ++i) {
n = (n << 8) + comp[i];
}
return n;
}
bool file_writer_respond_segment(struct file_writer* self, struct ndn_upcall_info* info) {
uint32_t seg_i = (uint32_t)file_writer_extract_number(info);
if (seg_i >= self->sl->count) return false;
if (!self->sent_segments[seg_i]) {
self->sent_segments[seg_i] = true;
--self->remaining_segments;
}
struct segment* seg = self->sl->list + seg_i;
struct ndn_charbuf* reply = ndn_charbuf_create();
if (self->sign_segments) {
file_writer_segment_sign(self, reply, info, seg_i, seg);
} else {
file_writer_segment_hash(self, reply, info, seg_i, seg);
}
ndn_put(self->h, reply->buf, reply->length);
ndn_charbuf_destroy(&reply);
return true;
}
bool file_writer_segment_sign(struct file_writer* self, struct ndn_charbuf* reply, struct ndn_upcall_info* info, uint32_t seg_i, struct segment* seg) {
struct ndn_charbuf* c = ndn_charbuf_create();
if (!file_writer_segment_readfile(self, c, seg)) { ndn_charbuf_destroy(&c); return false; }
struct ndn_charbuf* name = ndn_charbuf_create();
ndn_charbuf_append(name, info->interest_ndnb+info->pi->offset[NDN_PI_B_Name], info->pi->offset[NDN_PI_E_Name]-info->pi->offset[NDN_PI_B_Name]);
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
if (seg_i+1 == self->sl->count) {
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
}
int res = ndn_sign_content(self->h, reply, name, &sp, c->buf, c->length);
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&c);
return res==0;
}
bool file_writer_segment_hash(struct file_writer* self, struct ndn_charbuf* reply, struct ndn_upcall_info* info, uint32_t seg_i, struct segment* seg) {
ndnb_element_begin(reply, NDN_DTAG_ContentObject);
ndnb_element_begin(reply, NDN_DTAG_Signature);
ndnb_tagged_putf(reply, NDN_DTAG_DigestAlgorithm, "SHA256");
ndnb_append_tagged_blob(reply, NDN_DTAG_SignatureBits, seg->hash, sizeof(seg->hash));
ndnb_element_end(reply);//Signature
ndn_charbuf_append(reply, info->interest_ndnb+info->pi->offset[NDN_PI_B_Name], info->pi->offset[NDN_PI_E_Name]-info->pi->offset[NDN_PI_B_Name]);
ndnb_element_begin(reply, NDN_DTAG_SignedInfo);
ndnb_append_tagged_blob(reply, NDN_DTAG_PublisherPublicKeyDigest, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 32);
ndnb_element_begin(reply, NDN_DTAG_Timestamp);
ndnb_append_now_blob(reply, NDN_MARKER_NONE);
ndnb_element_end(reply);//Timestamp
if (seg_i+1 == self->sl->count) {
const uint8_t* comp; size_t compsz;
ndn_name_comp_get(info->interest_ndnb, info->interest_comps, info->pi->prefix_comps-1, &comp, &compsz);
ndnb_element_begin(reply, NDN_DTAG_FinalBlockID);
ndn_charbuf_append_tt(reply, compsz, NDN_BLOB);
ndn_charbuf_append(reply, comp, compsz);
ndnb_element_end(reply);//FinalBlockID
}
ndnb_element_end(reply);//SignedInfo
ndnb_element_begin(reply, NDN_DTAG_Content);
ndn_charbuf_append_tt(reply, seg->length, NDN_BLOB);
if (!file_writer_segment_readfile(self, reply, seg)) return false;
ndnb_element_end(reply);//Content
ndnb_element_end(reply);//ContentObject
return true;
}
bool file_writer_segment_readfile(struct file_writer* self, struct ndn_charbuf* c, struct segment* seg) {
if (0 != fseek(self->file, seg->start, SEEK_SET)) return false;
size_t read_size = 0;
uint8_t* buffer = ndn_charbuf_reserve(c, seg->length);
while (read_size < seg->length) {
size_t read_want = seg->length - read_size;
size_t read_res = fread(buffer + read_size, 1, read_want, self->file);
if (read_res == 0) return false;
read_size += read_res;
}
c->length += seg->length;
return true;
}
bool file_writer_respond_metadata(struct file_writer* self, struct ndn_upcall_info* info) {
uintmax_t seg_i = file_writer_extract_number(info);
if (seg_i >= self->total_metadata_blocks) return false;
if (!self->sent_metadata_blocks[seg_i]) {
self->sent_metadata_blocks[seg_i] = true;
--self->remaining_metadata_blocks;
}
struct ndn_charbuf* name = ndn_charbuf_create();
ndn_charbuf_append(name, info->interest_ndnb+info->pi->offset[NDN_PI_B_Name], info->pi->offset[NDN_PI_E_Name]-info->pi->offset[NDN_PI_B_Name]);
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
if (seg_i+1 == self->total_metadata_blocks) {
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
}
struct ndn_charbuf* reply = ndn_charbuf_create();
int res = ndn_sign_content(self->h, reply, name, &sp, self->metadata->buf + FILE_WRITER_METADATA_BLOCKSZ*seg_i, seg_i+1 == self->total_metadata_blocks ? self->metadata->length-FILE_WRITER_METADATA_BLOCKSZ*seg_i : FILE_WRITER_METADATA_BLOCKSZ);
ndn_charbuf_destroy(&name);
ndn_put(self->h, reply->buf, reply->length);
ndn_charbuf_destroy(&reply);
return res==0;
}
|
yoursunny/carepo
|
segment/segment_test.c
|
#include <CUnit/CUnit.h>
#include "segment.h"
void test_segment_ctor(void) {
struct segment_list* sl = segment_list_ctor(2);
CU_ASSERT_PTR_NOT_NULL(sl);
CU_ASSERT_PTR_NOT_NULL(sl->list);
CU_ASSERT_EQUAL(sl->count, 2);
segment_list_dtor(&sl);
CU_ASSERT_PTR_NULL(sl);
segment_list_dtor(&sl);
CU_ASSERT_PTR_NULL(sl);
}
|
yoursunny/carepo
|
defs.h
|
#ifndef CAREPO_DEFS_H_
#define CAREPO_DEFS_H_
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <ndn/ndn.h>
#include <ndn/uri.h>
static inline void LOG(const char* format, ...) {
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
}
static inline void LOG_name(const uint8_t* name, size_t namesz) {
struct ndn_charbuf* uri = ndn_charbuf_create();
ndn_uri_append(uri, name, namesz, 0);
LOG("%s", uri->buf);
ndn_charbuf_destroy(&uri);
}
static inline void LOG_hash(const uint8_t* hash, size_t hashsz) {
for (size_t i = 0; i < hashsz; ++i) LOG("%02x", hash[i]);
}
#endif//CAREPO_DEFS_H_
|
yoursunny/carepo
|
segment/rabin_test.c
|
<reponame>yoursunny/carepo<filename>segment/rabin_test.c
#include <CUnit/CUnit.h>
#include "rabin.h"
#include "metadata.h"
void test_segment_rabin(void) {
FILE* file = fopen("waf", "r");
struct segment_list* sl = segment_rabin(file);
CU_ASSERT_PTR_NOT_NULL(sl);
fclose(file);
struct ndn_charbuf* c = ndn_charbuf_create();
segment_list_to_metadata(sl, c);
CU_ASSERT(c->length > 0);
struct segment_list* sl2 = segment_list_from_metadata(c->buf, c->length);
CU_ASSERT_PTR_NOT_NULL(sl2);
CU_ASSERT_EQUAL(sl2->count, sl->count);
for (uint32_t i = 0; i < sl->count; ++i) {\
CU_ASSERT_EQUAL(sl2->list[i].start, sl->list[i].start);
CU_ASSERT_EQUAL(sl2->list[i].length, sl->list[i].length);
CU_ASSERT(0 == memcmp(sl2->list[i].hash, sl->list[i].hash, sizeof(sl->list[i].hash)));
}
segment_list_dtor(&sl);
segment_list_dtor(&sl2);
ndn_charbuf_destroy(&c);
}
|
yoursunny/carepo
|
repo/ndnr_sync.h
|
/**
* @file ndnr_sync.h
*
* Part of ndnr - NDNx Repository Daemon.
*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_SYNC_DEFINED
#define NDNR_SYNC_DEFINED
#include "ndnr_private.h"
/** Report message from sync code back through ndnr message infrastructure
*
*/
void r_sync_msg(struct sync_plumbing *sdd, const char *fmt, ...);
/**
* A call to r_sync_fence sets a "fence" marker that is remembered for any
* clean shut down of a repo/sync pair.
*/
int r_sync_fence(struct sync_plumbing *sdd, uint64_t seq_num);
/** Notify repo of starting point for new names to be passed to sync.
* Use item = 0 as the initial value.
* Following a call to r_sync_notify_after, the repository will call
* SyncNotifyContent(struct SyncBaseStruct *,
* int enumeration,
* ndnr_accession item,
* struct ndn_charbuf *name);
* periodically while there are no un-notified objects.
* enumeration is 0 for "time-based" notifications, or the value passed
* in when the enumeration was started. This may not end up an int.
* if the call is for an explicit enumeration, and there are no more
* objects, name and content_comps will be NULL.
* If SyncNotifyContent returns -1 then the active enumeration, or the
* r_sync_notify_after() will be cancelled.
*/
void
r_sync_notify_after(struct ndnr_handle *ndnr, ndnr_hwm item);
/** Request that a SyncNotifyContent call is made for each content object
* matching the interest.
* returns -1 for error, or an enumeration number which will also be passed
* in the SyncNotifyContent
*/
int
r_sync_enumerate(struct sync_plumbing *sdd, struct ndn_charbuf *interest);
/** Look up a content object that is stored locally in the repository
* based on the supplied interest.
* appends the content object to the content_ndnb.
* returns 0 for success, -1 for error.
*/
int
r_sync_lookup(struct sync_plumbing *sdd, struct ndn_charbuf *interest,
struct ndn_charbuf *content_ndnb);
/** Look up a content object that is stored locally in the repository
* based on the supplied interest. Takes a ndnr handle instead of sync data.
* appends the content object to the content_ndnb.
* returns 0 for success, -1 for error.
*/
int
r_lookup(struct ndnr_handle *ndnr, struct ndn_charbuf *interest,
struct ndn_charbuf *content_ndnb);
/**
* Called when a content object is received by sync and needs to be
* committed to stable storage by the repo.
*/
enum ndn_upcall_res
r_sync_upcall_store(struct sync_plumbing *sdd, enum ndn_upcall_kind kind,
struct ndn_upcall_info *info);
/**
* Called when a content object has been constructed locally by sync
* and needs to be committed to stable storage by the repo.
* returns 0 for success, -1 for error.
*/
int
r_sync_local_store(struct sync_plumbing *sdd, struct ndn_charbuf *content_cb);
/**
* A wrapper for the sync_notify method that takes a content entry.
*/
int
r_sync_notify_content(struct ndnr_handle *ndnr, int e, struct content_entry *content);
#endif
|
yoursunny/carepo
|
repo/ndnr_sendq.c
|
<reponame>yoursunny/carepo<filename>repo/ndnr_sendq.c
/**
* @file ndnr_sendq.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_sendq.h"
#include "ndnr_io.h"
#include "ndnr_link.h"
#include "ndnr_msg.h"
#include "ndnr_store.h"
static int
choose_face_delay(struct ndnr_handle *h, struct fdholder *fdholder, enum cq_delay_class c)
{
if (fdholder->flags & NDNR_FACE_NDND)
return(1);
if (fdholder->flags & NDNR_FACE_REPODATA)
return(1);
return(1);
}
static struct content_queue *
content_queue_create(struct ndnr_handle *h, struct fdholder *fdholder, enum cq_delay_class c)
{
struct content_queue *q;
unsigned usec;
q = calloc(1, sizeof(*q));
if (q != NULL) {
usec = choose_face_delay(h, fdholder, c);
q->burst_nsec = (usec <= 500 ? 500 : 150000); // XXX - needs a knob
q->min_usec = usec;
q->rand_usec = 2 * usec;
q->nrun = 0;
q->send_queue = ndn_indexbuf_create();
if (q->send_queue == NULL) {
free(q);
return(NULL);
}
q->sender = NULL;
}
return(q);
}
PUBLIC void
r_sendq_content_queue_destroy(struct ndnr_handle *h, struct content_queue **pq)
{
struct content_queue *q;
if (*pq != NULL) {
q = *pq;
ndn_indexbuf_destroy(&q->send_queue);
if (q->sender != NULL) {
ndn_schedule_cancel(h->sched, q->sender);
q->sender = NULL;
}
free(q);
*pq = NULL;
}
}
static enum cq_delay_class
choose_content_delay_class(struct ndnr_handle *h, unsigned filedesc, int content_flags)
{
return(NDN_CQ_NORMAL); /* default */
}
static unsigned
randomize_content_delay(struct ndnr_handle *h, struct content_queue *q)
{
unsigned usec;
usec = q->min_usec + q->rand_usec;
if (usec < 2)
return(1);
if (usec <= 20 || q->rand_usec < 2) // XXX - what is a good value for this?
return(usec); /* small value, don't bother to randomize */
usec = q->min_usec + (nrand48(h->seed) % q->rand_usec);
if (usec < 2)
return(1);
return(usec);
}
static int
content_sender(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
int i, j;
int delay;
int nsec;
int burst_nsec;
int burst_max;
struct ndnr_handle *h = clienth;
struct content_entry *content = NULL;
unsigned filedesc = ev->evint;
struct fdholder *fdholder = NULL;
struct content_queue *q = ev->evdata;
(void)sched;
if ((flags & NDN_SCHEDULE_CANCEL) != 0)
goto Bail;
fdholder = r_io_fdholder_from_fd(h, filedesc);
if (fdholder == NULL)
goto Bail;
if (q->send_queue == NULL)
goto Bail;
if ((fdholder->flags & NDNR_FACE_NOSEND) != 0)
goto Bail;
/* Send the content at the head of the queue */
if (q->ready > q->send_queue->n ||
(q->ready == 0 && q->nrun >= 12 && q->nrun < 120))
q->ready = q->send_queue->n;
nsec = 0;
burst_nsec = q->burst_nsec;
burst_max = 2;
if (q->ready < burst_max)
burst_max = q->ready;
if (burst_max == 0)
q->nrun = 0;
for (i = 0; i < burst_max && nsec < 1000000; i++) {
content = r_store_content_from_cookie(h, q->send_queue->buf[i]);
if (content == NULL)
q->nrun = 0;
else {
r_link_send_content(h, fdholder, content);
/* fdholder may have vanished, bail out if it did */
if (r_io_fdholder_from_fd(h, filedesc) == NULL)
goto Bail;
// nsec += burst_nsec * (unsigned)((content->size + 1023) / 1024);
q->nrun++;
}
}
if (q->ready < i) abort();
q->ready -= i;
/* Update queue */
for (j = 0; i < q->send_queue->n; i++, j++)
q->send_queue->buf[j] = q->send_queue->buf[i];
q->send_queue->n = j;
/* Do a poll before going on to allow others to preempt send. */
delay = (nsec + 499) / 1000 + 1;
if (q->ready > 0) {
return(delay);
}
q->ready = j;
if (q->nrun >= 12 && q->nrun < 120) {
/* We seem to be a preferred provider, forgo the randomized delay */
if (j == 0)
delay += burst_nsec / 50;
return(delay);
}
/* Determine when to run again */
for (i = 0; i < q->send_queue->n; i++) {
content = r_store_content_from_cookie(h, q->send_queue->buf[i]);
if (content != NULL) {
q->nrun = 0;
delay = randomize_content_delay(h, q);
if (NDNSHOULDLOG(h, LM_8, NDNL_FINER))
ndnr_msg(h, "fdholder %u queued %u delay %i",
(unsigned)ev->evint, q->ready, delay);
return(delay);
}
}
q->send_queue->n = q->ready = 0;
Bail:
q->sender = NULL;
return(0);
}
PUBLIC int
r_sendq_face_send_queue_insert(struct ndnr_handle *h,
struct fdholder *fdholder, struct content_entry *content)
{
int ans = -1;
int delay;
enum cq_delay_class c;
struct content_queue *q;
if (fdholder == NULL || content == NULL || (fdholder->flags & NDNR_FACE_NOSEND) != 0)
return(-1);
c = choose_content_delay_class(h, fdholder->filedesc, r_store_content_flags(content));
if (fdholder->q[c] == NULL)
fdholder->q[c] = content_queue_create(h, fdholder, c);
q = fdholder->q[c];
if (q == NULL)
return(-1);
ans = ndn_indexbuf_set_insert(q->send_queue, r_store_content_cookie(h, content));
if (q->sender == NULL) {
delay = randomize_content_delay(h, q);
q->ready = q->send_queue->n;
q->sender = ndn_schedule_event(h->sched, delay,
content_sender, q, fdholder->filedesc);
if (NDNSHOULDLOG(h, LM_8, NDNL_FINER))
ndnr_msg(h, "fdholder %u q %d delay %d usec", fdholder->filedesc, c, delay);
}
return (ans);
}
|
yoursunny/carepo
|
repo/ndnr_store.c
|
/**
* @file ndnr_store.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/btree_content.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_stats.h"
#include "ndnr_store.h"
#include "ndnr_init.h"
#include "ndnr_link.h"
#include "ndnr_util.h"
#include "ndnr_proto.h"
#include "ndnr_msg.h"
#include "ndnr_sync.h"
#include "ndnr_match.h"
#include "ndnr_sendq.h"
#include "ndnr_io.h"
#ifdef CAREPO
#include "hash_store.h"
#endif
struct content_entry {
ndnr_accession accession; /**< permanent repository id */
ndnr_cookie cookie; /**< for in-memory references */
int flags; /**< see below - use accessor functions */
int size; /**< size of ContentObject */
struct ndn_charbuf *flatname; /**< for skiplist, et. al. */
struct ndn_charbuf *cob; /**< may contain ContentObject, or be NULL */
};
static const unsigned char *bogon = NULL;
const ndnr_accession r_store_mark_repoFile1 = ((ndnr_accession)1) << 48;
static int
r_store_set_flatname(struct ndnr_handle *h, struct content_entry *content,
struct ndn_parsed_ContentObject *pco);
static int
r_store_content_btree_insert(struct ndnr_handle *h,
struct content_entry *content,
struct ndn_parsed_ContentObject *pco,
ndnr_accession *accession);
#define FAILIF(cond) do {} while ((cond) && r_store_fatal(h, __func__, __LINE__))
#define CHKSYS(res) FAILIF((res) == -1)
#define CHKRES(res) FAILIF((res) < 0)
#define CHKPTR(p) FAILIF((p) == NULL)
static int
r_store_fatal(struct ndnr_handle *h, const char *fn, int lineno)
{
if (h != NULL) {
ndnr_msg(h,
"fatal error in %s, line %d, errno %d%s",
fn, lineno, errno, strerror(errno));
}
abort();
}
PUBLIC ndnr_accession
r_store_content_accession(struct ndnr_handle *h, struct content_entry *content)
{
return(content->accession);
}
PUBLIC ndnr_cookie
r_store_content_cookie(struct ndnr_handle *h, struct content_entry *content)
{
return(content->cookie);
}
PUBLIC size_t
r_store_content_size(struct ndnr_handle *h, struct content_entry *content)
{
return(content->size);
}
static off_t
r_store_offset_from_accession(struct ndnr_handle *h, ndnr_accession a)
{
return(a & ((((ndnr_accession)1) << 48) - 1));
}
static unsigned
r_store_repofile_from_accession(struct ndnr_handle *h, ndnr_accession a)
{
/* Initially this should always be 1 */
return(a >> 48);
}
static const unsigned char *
r_store_content_mapped(struct ndnr_handle *h, struct content_entry *content)
{
return(NULL);
}
static const unsigned char *
r_store_content_read(struct ndnr_handle *h, struct content_entry *content)
{
unsigned repofile;
off_t offset;
struct ndn_charbuf *cob = NULL;
ssize_t rres = 0;
int fd = -1;
unsigned char buf[8800];
struct ndn_skeleton_decoder decoder = {0};
struct ndn_skeleton_decoder *d = &decoder;
ssize_t dres;
repofile = r_store_repofile_from_accession(h, content->accession);
offset = r_store_offset_from_accession(h, content->accession);
if (repofile != 1)
goto Bail;
if (content->cob != NULL)
goto Bail;
fd = r_io_repo_data_file_fd(h, repofile, 0);
if (fd == -1)
goto Bail;
cob = ndn_charbuf_create_n(content->size);
if (cob == NULL)
goto Bail;
if (content->size > 0) {
rres = pread(fd, cob->buf, content->size, offset);
if (rres == content->size) {
cob->length = content->size;
content->cob = cob;
h->cob_count++;
return(cob->buf);
}
if (rres == -1)
ndnr_msg(h, "r_store_content_read %u :%s (errno = %d)",
fd, strerror(errno), errno);
else
ndnr_msg(h, "r_store_content_read %u expected %d bytes, but got %d",
fd, (int)content->size, (int)rres);
} else {
rres = pread(fd, buf, 8800, offset); // XXX - should be symbolic
if (rres == -1) {
ndnr_msg(h, "r_store_content_read %u :%s (errno = %d)",
fd, strerror(errno), errno);
goto Bail;
}
dres = ndn_skeleton_decode(d, buf, rres);
if (d->state != 0) {
ndnr_msg(h, "r_store_content_read %u : error parsing cob", fd);
goto Bail;
}
content->size = dres;
if (ndn_charbuf_append(cob, buf, dres) < 0)
goto Bail;
content->cob = cob;
h->cob_count++;
return(cob->buf);
}
Bail:
ndn_charbuf_destroy(&cob);
return(NULL);
}
/**
* If the content appears to be safely stored in the repository,
* removes any buffered copy.
* @returns 0 if buffer was removed, -1 if not.
*/
PUBLIC int
r_store_content_trim(struct ndnr_handle *h, struct content_entry *content)
{
if (content->accession != NDNR_NULL_ACCESSION && content->cob != NULL) {
ndn_charbuf_destroy(&content->cob);
h->cob_count--;
return(0);
}
return(-1);
}
/**
* Evict recoverable content from in-memory buffers
*/
PUBLIC void
r_store_trim(struct ndnr_handle *h, unsigned long limit)
{
struct content_entry *content = NULL;
int checklimit;
unsigned before;
unsigned rover;
unsigned mask;
r_store_index_needs_cleaning(h);
before = h->cob_count;
if (before <= limit)
return;
checklimit = h->cookie_limit;
mask = h->cookie_limit - 1;
for (rover = (h->trim_rover & mask);
checklimit > 0 && h->cob_count > limit;
checklimit--, rover = (rover + 1) & mask) {
content = h->content_by_cookie[rover];
if (content != NULL)
r_store_content_trim(h, content);
}
h->trim_rover = rover;
if (NDNSHOULDLOG(h, sdf, NDNL_FINER))
ndnr_msg(h, "trimmed %u cobs", before - h->cob_count);
}
/**
* Get the base address of the content object
*
* This may involve reading the object in. Caller should not assume that
* the address will stay valid after it relinquishes control, either by
* returning or by calling routines that might invalidate objects.
*
*/
PUBLIC const unsigned char *
r_store_content_base(struct ndnr_handle *h, struct content_entry *content)
{
const unsigned char *ans = NULL;
if (content->cob != NULL && content->cob->length == content->size) {
ans = content->cob->buf;
goto Finish;
}
if (content->accession == NDNR_NULL_ACCESSION)
goto Finish;
ans = r_store_content_mapped(h, content);
if (ans != NULL)
goto Finish;
ans = r_store_content_read(h, content);
Finish:
if (ans != NULL) {
/* Sanity check - make sure first 2 and last 2 bytes are good */
if (content->size < 5 || ans[0] != 0x04 || ans[1] != 0x82 ||
ans[content->size - 1] != 0 || ans[content->size - 2] != 0) {
bogon = ans; /* for debugger */
ans = NULL;
}
}
if (ans == NULL || NDNSHOULDLOG(h, xxxx, NDNL_FINEST))
ndnr_msg(h, "r_store_content_base.%d returning %p (acc=0x%jx, cookie=%u)",
__LINE__,
ans,
ndnr_accession_encode(h, content->accession),
(unsigned)content->cookie);
return(ans);
}
PUBLIC int
r_store_name_append_components(struct ndn_charbuf *dst,
struct ndnr_handle *h,
struct content_entry *content,
int skip,
int count)
{
int res;
res = ndn_name_append_flatname(dst,
content->flatname->buf,
content->flatname->length, skip, count);
return(res);
}
PUBLIC int
r_store_content_flags(struct content_entry *content)
{
return(content->flags);
}
PUBLIC int
r_store_content_change_flags(struct content_entry *content, int set, int clear)
{
int old = content->flags;
content->flags |= set;
content->flags &= ~clear;
return(old);
}
/**
* Write a file named index/stable that contains the size of
* repoFile1 when the repository is shut down.
*/
static int
r_store_write_stable_point(struct ndnr_handle *h)
{
struct ndn_charbuf *path = NULL;
struct ndn_charbuf *cb = NULL;
int fd, res;
path = ndn_charbuf_create();
cb = ndn_charbuf_create();
if (path == NULL || cb == NULL) {
ndnr_msg(h, "memory allocation failure writing stable mark");
goto Bail;
}
ndn_charbuf_putf(path, "%s/index/stable", h->directory);
unlink(ndn_charbuf_as_string(path)); /* Should not exist, but just in case. */
fd = open(ndn_charbuf_as_string(path),
O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, 0666);
if (fd == -1) {
ndnr_msg(h, "cannot write stable mark %s: %s",
ndn_charbuf_as_string(path), strerror(errno));
unlink(ndn_charbuf_as_string(path));
}
else {
ndn_charbuf_putf(cb, "%ju", (uintmax_t)(h->stable));
res = write(fd, cb->buf, cb->length);
close(fd);
if (res != cb->length) {
unlink(ndn_charbuf_as_string(path));
ndnr_msg(h, "cannot write stable mark %s: unexpected write result %d",
ndn_charbuf_as_string(path), res);
}
if (NDNSHOULDLOG(h, dfsdf, NDNL_INFO))
ndnr_msg(h, "Index marked stable - %s", ndn_charbuf_as_string(cb));
}
Bail:
ndn_charbuf_destroy(&path);
ndn_charbuf_destroy(&cb);
return(0);
}
/**
* Read the former size of repoFile1 from index/stable, and remove
* the latter.
*/
static void
r_store_read_stable_point(struct ndnr_handle *h)
{
struct ndn_charbuf *path = NULL;
struct ndn_charbuf *cb = NULL;
int fd;
int i;
ssize_t rres;
uintmax_t val;
unsigned char c;
path = ndn_charbuf_create();
cb = ndn_charbuf_create();
ndn_charbuf_putf(path, "%s/index/stable", h->directory);
fd = open(ndn_charbuf_as_string(path), O_RDONLY, 0666);
if (fd != -1) {
rres = read(fd, ndn_charbuf_reserve(cb, 80), 80);
if (rres > 0)
cb->length = rres;
close(fd);
if (NDNSHOULDLOG(h, dfsdf, NDNL_INFO))
ndnr_msg(h, "Last stable at %s", ndn_charbuf_as_string(cb));
}
for (val = 0, i = 0; i < cb->length; i++) {
c = cb->buf[i];
if ('0' <= c && c <= '9')
val = val * 10 + (c - '0');
else
break;
}
if (i == 0 || i < cb->length) {
ndnr_msg(h, "Bad stable mark - %s", ndn_charbuf_as_string(cb));
h->stable = 0;
}
else {
h->stable = val;
unlink(ndn_charbuf_as_string(path));
}
ndn_charbuf_destroy(&path);
ndn_charbuf_destroy(&cb);
}
/**
* Log a bit if we are taking a while to re-index.
*/
static int
r_store_reindexing(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *h = clienth;
struct fdholder *in = NULL;
unsigned pct;
if ((flags & NDN_SCHEDULE_CANCEL) != 0)
return(0);
in = r_io_fdholder_from_fd(h, h->active_in_fd);
if (in == NULL)
return(0);
pct = ndnr_meter_total(in->meter[FM_BYTI]) / ((h->startupbytes / 100) + 1);
if (pct >= 100)
return(0);
ndnr_msg(h, "indexing %u%% complete", pct);
return(2000000);
}
/**
* Select power of 2 between l and m + 1 (if possible).
*/
static unsigned
choose_limit(unsigned l, unsigned m)
{
unsigned k;
for (k = 0; k < l; k = 2 * k + 1)
continue;
while (k > (m | 1) || k + 1 < k)
k >>= 1;
return(k + 1);
}
static void
cleanup_content_entry(struct ndnr_handle *h, struct content_entry *content)
{
unsigned i;
if ((content->flags & NDN_CONTENT_ENTRY_STALE) != 0)
h->n_stale--;
if (NDNSHOULDLOG(h, LM_4, NDNL_FINER))
ndnr_debug_content(h, __LINE__, "remove", NULL, content);
/* Remove the cookie reference */
i = content->cookie & (h->cookie_limit - 1);
if (h->content_by_cookie[i] == content)
h->content_by_cookie[i] = NULL;
content->cookie = 0;
ndn_charbuf_destroy(&content->flatname);
if (content->cob != NULL) {
h->cob_count--;
ndn_charbuf_destroy(&content->cob);
}
free(content);
}
static void
finalize_accession(struct hashtb_enumerator *e)
{
struct ndnr_handle *h = hashtb_get_param(e->ht, NULL);
struct content_by_accession_entry *entry = e->data;
cleanup_content_entry(h, entry->content);
}
PUBLIC void
r_store_init(struct ndnr_handle *h)
{
struct ndn_btree *btree = NULL;
struct ndn_btree_node *node = NULL;
struct hashtb_param param = {0};
int i;
int j;
int res;
struct ndn_charbuf *path = NULL;
struct ndn_charbuf *msgs = NULL;
off_t offset;
path = ndn_charbuf_create();
param.finalize_data = h;
param.finalize = &finalize_accession;
h->cob_limit = r_init_confval(h, "NDNR_CONTENT_CACHE", 16, 2000000, 4201);
h->cookie_limit = choose_limit(h->cob_limit, (ndnr_cookie)(~0U));
h->content_by_cookie = calloc(h->cookie_limit, sizeof(h->content_by_cookie[0]));
CHKPTR(h->content_by_cookie);
h->content_by_accession_tab = hashtb_create(sizeof(struct content_by_accession_entry), ¶m);
CHKPTR(h->content_by_accession_tab);
h->btree = btree = ndn_btree_create();
CHKPTR(btree);
FAILIF(btree->nextnodeid != 1);
ndn_charbuf_putf(path, "%s/index", h->directory);
res = mkdir(ndn_charbuf_as_string(path), 0700);
if (res != 0 && errno != EEXIST)
r_init_fail(h, __LINE__, ndn_charbuf_as_string(path), errno);
else {
msgs = ndn_charbuf_create();
btree->io = ndn_btree_io_from_directory(ndn_charbuf_as_string(path), msgs);
if (btree->io == NULL)
res = errno;
if (msgs->length != 0 && NDNSHOULDLOG(h, sffdsdf, NDNL_WARNING)) {
ndnr_msg(h, "while initializing %s - %s",
ndn_charbuf_as_string(path),
ndn_charbuf_as_string(msgs));
}
ndn_charbuf_destroy(&msgs);
if (btree->io == NULL)
r_init_fail(h, __LINE__, ndn_charbuf_as_string(path), res);
}
node = ndn_btree_getnode(btree, 1, 0);
if (btree->io != NULL)
btree->nextnodeid = btree->io->maxnodeid + 1;
CHKPTR(node);
if (node->buf->length == 0) {
res = ndn_btree_init_node(node, 0, 'R', 0);
CHKSYS(res);
}
ndn_charbuf_destroy(&path);
if (h->running == -1)
return;
r_store_read_stable_point(h);
h->active_in_fd = -1;
h->active_out_fd = r_io_open_repo_data_file(h, "repoFile1", 1); /* output */
offset = lseek(h->active_out_fd, 0, SEEK_END);
h->startupbytes = offset;
if (offset != h->stable || node->corrupt != 0) {
ndnr_msg(h, "Index not current - resetting");
ndn_btree_init_node(node, 0, 'R', 0);
node = NULL;
ndn_btree_destroy(&h->btree);
path = ndn_charbuf_create();
/* Remove old index files to avoid confusion */
for (i = 1, j = 0; i > 0 && j < 3; i++) {
path->length = 0;
res = ndn_charbuf_putf(path, "%s/index/%d", h->directory, i);
if (res >= 0)
res = unlink(ndn_charbuf_as_string(path));
if (res < 0)
j++;
}
h->btree = btree = ndn_btree_create();
path->length = 0;
ndn_charbuf_putf(path, "%s/index", h->directory);
btree->io = ndn_btree_io_from_directory(ndn_charbuf_as_string(path), msgs);
CHKPTR(btree->io);
btree->io->maxnodeid = 0;
btree->nextnodeid = 1;
node = ndn_btree_getnode(btree, 1, 0);
btree->nextnodeid = btree->io->maxnodeid + 1;
ndn_btree_init_node(node, 0, 'R', 0);
h->stable = 0;
h->active_in_fd = r_io_open_repo_data_file(h, "repoFile1", 0); /* input */
ndn_charbuf_destroy(&path);
if (NDNSHOULDLOG(h, dfds, NDNL_INFO))
ndn_schedule_event(h->sched, 50000, r_store_reindexing, NULL, 0);
}
if (NDNSHOULDLOG(h, weuyg, NDNL_FINEST)) {
FILE *dumpfile = NULL;
path = ndn_charbuf_create();
ndn_charbuf_putf(path, "%s/index/btree_check.out", h->directory);
dumpfile = fopen(ndn_charbuf_as_string(path), "w");
res = ndn_btree_check(btree, dumpfile);
if (dumpfile != NULL) {
fclose(dumpfile);
dumpfile = NULL;
}
else
path->length = 0;
ndnr_msg(h, "ndn_btree_check returned %d (%s)",
res, ndn_charbuf_as_string(path));
ndn_charbuf_destroy(&path);
if (res < 0)
r_init_fail(h, __LINE__, "index is corrupt", res);
}
btree->full = r_init_confval(h, "NDNR_BTREE_MAX_FANOUT", 4, 9999, 1999);
btree->full0 = r_init_confval(h, "NDNR_BTREE_MAX_LEAF_ENTRIES", 4, 9999, 1999);
btree->nodebytes = r_init_confval(h, "NDNR_BTREE_MAX_NODE_BYTES", 1024, 8388608, 2097152);
btree->nodepool = r_init_confval(h, "NDNR_BTREE_NODE_POOL", 16, 2000000, 512);
if (h->running != -1)
r_store_index_needs_cleaning(h);
#ifdef CAREPO
hash_store_ctor(h);
#endif
}
PUBLIC int
r_store_final(struct ndnr_handle *h, int stable) {
int res;
res = ndn_btree_destroy(&h->btree);
if (res < 0)
ndnr_msg(h, "r_store_final.%d-%d Errors while closing index", __LINE__, res);
if (res >= 0 && stable)
res = r_store_write_stable_point(h);
#ifdef CAREPO
hash_store_dtor(&h->hashstore);
#endif
return(res);
}
PUBLIC struct content_entry *
r_store_content_from_accession(struct ndnr_handle *h, ndnr_accession accession)
{
struct ndn_parsed_ContentObject obj = {0};
struct content_entry *content = NULL;
struct content_by_accession_entry *entry;
const unsigned char *content_base = NULL;
int res;
ndnr_accession acc;
if (accession == NDNR_NULL_ACCESSION)
return(NULL);
entry = hashtb_lookup(h->content_by_accession_tab,
&accession, sizeof(accession));
if (entry != NULL) {
h->content_from_accession_hits++;
return(entry->content);
}
h->content_from_accession_misses++;
content = calloc(1, sizeof(*content));
CHKPTR(content);
content->cookie = 0;
content->accession = accession;
content->cob = NULL;
content->size = 0;
content_base = r_store_content_base(h, content);
if (content_base == NULL || content->size == 0)
goto Bail;
res = r_store_set_flatname(h, content, &obj);
if (res < 0) goto Bail;
r_store_enroll_content(h, content);
res = r_store_content_btree_insert(h, content, &obj, &acc);
if (res < 0) goto Bail;
if (res == 1 || NDNSHOULDLOG(h, sdf, NDNL_FINEST))
ndnr_debug_content(h, __LINE__, "content/accession", NULL, content);
return(content);
Bail:
ndnr_msg(h, "r_store_content_from_accession.%d failed 0x%jx",
__LINE__, ndnr_accession_encode(h, accession));
r_store_forget_content(h, &content);
return(content);
}
PUBLIC struct content_entry *
r_store_content_from_cookie(struct ndnr_handle *h, ndnr_cookie cookie)
{
struct content_entry *ans = NULL;
ans = h->content_by_cookie[cookie & (h->cookie_limit - 1)];
if (ans != NULL && ans->cookie != cookie)
ans = NULL;
return(ans);
}
/**
* This makes a cookie for content, and, if it has an accession number already,
* enters it into the content_by_accession_tab. Does not index by name.
*/
PUBLIC ndnr_cookie
r_store_enroll_content(struct ndnr_handle *h, struct content_entry *content)
{
ndnr_cookie cookie;
unsigned mask;
mask = h->cookie_limit - 1;
cookie = ++(h->cookie);
if (cookie == 0)
cookie = ++(h->cookie); /* Cookie numbers may wrap */
// XXX - check for persistence here, if we add that
r_store_forget_content(h, &(h->content_by_cookie[cookie & mask]));
content->cookie = cookie;
h->content_by_cookie[cookie & mask] = content;
if (content->accession != NDNR_NULL_ACCESSION) {
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
ndnr_accession accession = content->accession;
struct content_by_accession_entry *entry = NULL;
hashtb_start(h->content_by_accession_tab, e);
hashtb_seek(e, &accession, sizeof(accession), 0);
entry = e->data;
if (entry != NULL)
entry->content = content;
hashtb_end(e);
content->flags |= NDN_CONTENT_ENTRY_STABLE;
}
return(cookie);
}
/** @returns 2 if content was added to index, 1 if it was there but had no accession, 0 if it was already there, -1 for error */
static int
r_store_content_btree_insert(struct ndnr_handle *h,
struct content_entry *content,
struct ndn_parsed_ContentObject *pco,
ndnr_accession *accp)
{
const unsigned char *content_base = NULL;
struct ndn_btree *btree = NULL;
struct ndn_btree_node *leaf = NULL;
struct ndn_btree_node *node = NULL;
struct ndn_charbuf *flat = NULL;
int i;
int limit;
int res;
btree = h->btree;
if (btree == NULL)
return(-1);
flat = content->flatname;
if (flat == NULL)
return(-1);
res = ndn_btree_lookup(h->btree, flat->buf, flat->length, &leaf);
if (res < 0)
return(-1);
i = NDN_BT_SRCH_INDEX(res);
if (NDN_BT_SRCH_FOUND(res)) {
*accp = ndnr_accession_decode(h, ndn_btree_content_cobid(leaf, i));
return(*accp == NDNR_NULL_ACCESSION);
}
else {
content_base = r_store_content_base(h, content);
if (content_base == NULL)
return(-1);
res = ndn_btree_prepare_for_update(h->btree, leaf);
if (res < 0)
return(-1);
res = ndn_btree_insert_content(leaf, i,
ndnr_accession_encode(h, content->accession),
content_base,
pco,
content->flatname);
if (res < 0)
return(-1);
if (ndn_btree_oversize(btree, leaf)) {
res = ndn_btree_split(btree, leaf);
for (limit = 100; res >= 0 && btree->nextsplit != 0; limit--) {
if (limit == 0) abort();
node = ndn_btree_getnode(btree, btree->nextsplit, 0);
if (node == NULL)
return(-1);
res = ndn_btree_split(btree, node);
}
}
r_store_index_needs_cleaning(h);
*accp = content->accession;
return(2);
}
}
/**
* Remove internal representation of a content object
*/
PUBLIC void
r_store_forget_content(struct ndnr_handle *h, struct content_entry **pentry)
{
struct content_entry *entry = *pentry;
if (entry == NULL)
return;
*pentry = NULL;
/* Remove the accession reference */
/* more cleanup, including the content_by_cookie cleanup,
* is done by the finalizer for the accession hash table
*/
if (entry->accession != NDNR_NULL_ACCESSION) {
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
hashtb_start(h->content_by_accession_tab, e);
if (hashtb_seek(e, &entry->accession, sizeof(entry->accession), 0) ==
HT_NEW_ENTRY) {
ndnr_msg(h, "orphaned content %llu",
(unsigned long long)(entry->accession));
hashtb_delete(e);
hashtb_end(e);
return;
}
entry->accession = NDNR_NULL_ACCESSION;
hashtb_delete(e);
hashtb_end(e);
} else {
if (NDNSHOULDLOG(h, sdf, NDNL_FINER)) {
ndnr_debug_content(h, __LINE__, "removing unenrolled content", NULL, entry);
}
cleanup_content_entry(h, entry);
}
}
/**
* Get a handle on the content object that matches key, or if there is
* no match, the one that would come just after it.
*
* The key is in flatname format.
*/
static struct content_entry *
r_store_look(struct ndnr_handle *h, const unsigned char *key, size_t size)
{
struct content_entry *content = NULL;
struct ndn_btree_node *leaf = NULL;
ndnr_accession accession;
int ndx;
int res;
res = ndn_btree_lookup(h->btree, key, size, &leaf);
if (res >= 0) {
ndx = NDN_BT_SRCH_INDEX(res);
if (ndx == ndn_btree_node_nent(leaf)) {
res = ndn_btree_next_leaf(h->btree, leaf, &leaf);
if (res <= 0)
return(NULL);
ndx = 0;
}
accession = ndnr_accession_decode(h, ndn_btree_content_cobid(leaf, ndx));
if (accession != NDNR_NULL_ACCESSION) {
struct content_by_accession_entry *entry;
entry = hashtb_lookup(h->content_by_accession_tab,
&accession, sizeof(accession));
if (entry != NULL)
content = entry->content;
if (content == NULL) {
/* Construct handle without actually reading the cob */
res = ndn_btree_content_cobsz(leaf, ndx);
content = calloc(1, sizeof(*content));
if (res > 0 && content != NULL) {
content->accession = accession;
content->cob = NULL;
content->size = res;
content->flatname = ndn_charbuf_create();
CHKPTR(content->flatname);
res = ndn_btree_key_fetch(content->flatname, leaf, ndx);
CHKRES(res);
r_store_enroll_content(h, content);
}
}
}
}
return(content);
}
/**
* Extract the flatname representations of the bounds for the
* next component after the name prefix of the interest.
* These are exclusive bounds. The results are appended to
* lower and upper (when not NULL). If there is
* no lower bound, lower will be unchanged.
* If there is no upper bound, a sentinel value is appended to upper.
*
* @returns on success the number of Components in Exclude.
* A negative value indicates an error.
*/
static int
ndn_append_interest_bounds(const unsigned char *interest_msg,
const struct ndn_parsed_interest *pi,
struct ndn_charbuf *lower,
struct ndn_charbuf *upper)
{
struct ndn_buf_decoder decoder;
struct ndn_buf_decoder *d = NULL;
size_t xstart = 0;
size_t xend = 0;
int atlower = 0;
int atupper = 0;
int res = 0;
int nexcl = 0;
if (pi->offset[NDN_PI_B_Exclude] < pi->offset[NDN_PI_E_Exclude]) {
d = ndn_buf_decoder_start(&decoder,
interest_msg + pi->offset[NDN_PI_B_Exclude],
pi->offset[NDN_PI_E_Exclude] -
pi->offset[NDN_PI_B_Exclude]);
ndn_buf_advance(d);
if (ndn_buf_match_dtag(d, NDN_DTAG_Any)) {
ndn_buf_advance(d);
ndn_buf_check_close(d);
atlower = 1; /* look for <Exclude><Any/><Component>... case */
}
else if (ndn_buf_match_dtag(d, NDN_DTAG_Bloom))
ndn_buf_advance_past_element(d);
while (ndn_buf_match_dtag(d, NDN_DTAG_Component)) {
nexcl++;
xstart = pi->offset[NDN_PI_B_Exclude] + d->decoder.token_index;
ndn_buf_advance_past_element(d);
xend = pi->offset[NDN_PI_B_Exclude] + d->decoder.token_index;
if (atlower && lower != NULL && d->decoder.state >= 0) {
res = ndn_flatname_append_from_ndnb(lower,
interest_msg + xstart, xend - xstart, 0, 1);
if (res < 0)
d->decoder.state = - __LINE__;
}
atlower = 0;
atupper = 0;
if (ndn_buf_match_dtag(d, NDN_DTAG_Any)) {
atupper = 1; /* look for ...</Component><Any/></Exclude> case */
ndn_buf_advance(d);
ndn_buf_check_close(d);
}
else if (ndn_buf_match_dtag(d, NDN_DTAG_Bloom))
ndn_buf_advance_past_element(d);
}
ndn_buf_check_close(d);
res = d->decoder.state;
}
if (upper != NULL) {
if (atupper && res >= 0)
res = ndn_flatname_append_from_ndnb(upper,
interest_msg + xstart, xend - xstart, 0, 1);
else
ndn_charbuf_append(upper, "\377\377\377", 3);
}
return (res < 0 ? res : 0);
}
static struct content_entry *
r_store_lookup_backwards(struct ndnr_handle *h,
const unsigned char *interest_msg,
const struct ndn_parsed_interest *pi,
struct ndn_indexbuf *comps)
{
struct content_entry *content = NULL;
struct ndn_btree_node *leaf = NULL;
struct ndn_charbuf *lower = NULL;
struct ndn_charbuf *f = NULL;
size_t size;
size_t fsz;
int errline = 0;
int try = 0;
int ndx;
int res;
int rnc;
size = pi->offset[NDN_PI_E];
f = ndn_charbuf_create_n(pi->offset[NDN_PI_E_Name]);
lower = ndn_charbuf_create();
if (f == NULL || lower == NULL) { errline = __LINE__; goto Done; };
rnc = ndn_flatname_from_ndnb(f, interest_msg, size);
fsz = f->length;
res = ndn_charbuf_append_charbuf(lower, f);
if (rnc < 0 || res < 0) { errline = __LINE__; goto Done; };
res = ndn_append_interest_bounds(interest_msg, pi, lower, f);
if (res < 0) { errline = __LINE__; goto Done; };
/* Now f is beyond any we care about */
res = ndn_btree_lookup(h->btree, f->buf, f->length, &leaf);
if (res < 0) { errline = __LINE__; goto Done; };
ndx = NDN_BT_SRCH_INDEX(res);
for (try = 1;; try++) {
if (ndx == 0) {
res = ndn_btree_prev_leaf(h->btree, leaf, &leaf);
if (res != 1) goto Done;
ndx = ndn_btree_node_nent(leaf);
if (ndx <= 0) goto Done;
}
ndx -= 1;
res = ndn_btree_compare(lower->buf, lower->length, leaf, ndx);
if (res > 0 || (res == 0 && lower->length > fsz))
goto Done;
f->length = 0;
res = ndn_btree_key_fetch(f, leaf, ndx);
if (res < 0) { errline = __LINE__; goto Done; }
if (f->length > fsz) {
rnc = ndn_flatname_next_comp(f->buf + fsz, f->length - fsz);
if (rnc < 0) { errline = __LINE__; goto Done; };
f->length = fsz + NDNFLATDELIMSZ(rnc) + NDNFLATDATASZ(rnc);
res = ndn_btree_lookup(h->btree, f->buf, f->length, &leaf);
if (res < 0) { errline = __LINE__; goto Done; };
ndx = NDN_BT_SRCH_INDEX(res);
}
else if (f->length < fsz) { errline = __LINE__; goto Done; }
res = ndn_btree_match_interest(leaf, ndx, interest_msg, pi, f);
if (res == 1) {
res = ndn_btree_key_fetch(f, leaf, ndx);
if (res < 0) { errline = __LINE__; goto Done; }
content = r_store_look(h, f->buf, f->length);
goto Done;
}
else if (res != 0) { errline = __LINE__; goto Done; }
}
Done:
if (errline != 0)
ndnr_debug_ndnb(h, errline, "match_error", NULL, interest_msg, size);
else {
if (content != NULL) {
h->count_rmc_found += 1;
h->count_rmc_found_iters += try;
}
else {
h->count_rmc_notfound += 1;
h->count_rmc_notfound_iters += try;
}
}
ndn_charbuf_destroy(&lower);
ndn_charbuf_destroy(&f);
return(content);
}
PUBLIC struct content_entry *
r_store_find_first_match_candidate(struct ndnr_handle *h,
const unsigned char *interest_msg,
const struct ndn_parsed_interest *pi)
{
struct ndn_charbuf *flatname = NULL;
struct content_entry *content = NULL;
flatname = ndn_charbuf_create_n(pi->offset[NDN_PI_E]);
ndn_flatname_from_ndnb(flatname, interest_msg, pi->offset[NDN_PI_E]);
ndn_append_interest_bounds(interest_msg, pi, flatname, NULL);
content = r_store_look(h, flatname->buf, flatname->length);
ndn_charbuf_destroy(&flatname);
return(content);
}
PUBLIC int
r_store_content_matches_interest_prefix(struct ndnr_handle *h,
struct content_entry *content,
const unsigned char *interest_msg,
size_t interest_size)
{
struct ndn_charbuf *flatname = ndn_charbuf_create_n(interest_size);
int ans;
int cmp;
ndn_flatname_from_ndnb(flatname, interest_msg, interest_size);
cmp = ndn_flatname_charbuf_compare(flatname, content->flatname);
ans = (cmp == 0 || cmp == -9999);
ndn_charbuf_destroy(&flatname);
return(ans);
}
PUBLIC struct content_entry *
r_store_content_next(struct ndnr_handle *h, struct content_entry *content)
{
if (content == NULL)
return(0);
/* We need to go past the current name, so make sure there is a 0 byte */
ndn_charbuf_as_string(content->flatname);
content = r_store_look(h, content->flatname->buf, content->flatname->length + 1);
return(content);
}
PUBLIC struct content_entry *
r_store_next_child_at_level(struct ndnr_handle *h,
struct content_entry *content, int level)
{
struct content_entry *next = NULL;
struct ndn_charbuf *name;
struct ndn_charbuf *flatname = NULL;
int res;
if (content == NULL)
return(NULL);
name = ndn_charbuf_create();
ndn_name_init(name);
res = ndn_name_append_flatname(name,
content->flatname->buf,
content->flatname->length, 0, level + 1);
if (res < level)
goto Bail;
if (res == level)
res = ndn_name_append(name, NULL, 0);
else if (res == level + 1)
res = ndn_name_next_sibling(name); // XXX - would be nice to have a flatname version of this
if (res < 0)
goto Bail;
if (NDNSHOULDLOG(h, LM_8, NDNL_FINER))
ndnr_debug_ndnb(h, __LINE__, "child_successor", NULL,
name->buf, name->length);
flatname = ndn_charbuf_create();
ndn_flatname_from_ndnb(flatname, name->buf, name->length);
next = r_store_look(h, flatname->buf, flatname->length);
if (next == content) {
// XXX - I think this case should not occur, but just in case, avoid a loop.
ndnr_debug_content(h, __LINE__, "urp", NULL, next);
next = NULL;
}
Bail:
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&flatname);
return(next);
}
PUBLIC struct content_entry *
r_store_lookup(struct ndnr_handle *h,
const unsigned char *msg,
const struct ndn_parsed_interest *pi,
struct ndn_indexbuf *comps)
{
struct content_entry *content = NULL;
struct ndn_btree_node *leaf = NULL;
ndnr_cookie last_match = 0;
ndnr_accession last_match_acc = NDNR_NULL_ACCESSION;
struct ndn_charbuf *scratch = NULL;
size_t size = pi->offset[NDN_PI_E];
int ndx;
int res;
int try;
if ((pi->orderpref & 1) == 1) {
content = r_store_lookup_backwards(h, msg, pi, comps);
return(content);
}
content = r_store_find_first_match_candidate(h, msg, pi);
if (content != NULL && NDNSHOULDLOG(h, LM_8, NDNL_FINER))
ndnr_debug_content(h, __LINE__, "first_candidate", NULL,
content);
if (content != NULL &&
!r_store_content_matches_interest_prefix(h, content, msg, size)) {
if (NDNSHOULDLOG(h, LM_8, NDNL_FINER))
ndnr_debug_ndnb(h, __LINE__, "prefix_mismatch", NULL,
msg, size);
content = NULL;
}
scratch = ndn_charbuf_create();
for (try = 1; content != NULL; try++) {
res = ndn_btree_lookup(h->btree,
content->flatname->buf,
content->flatname->length,
&leaf);
if (NDN_BT_SRCH_FOUND(res) == 0) {
ndnr_debug_content(h, __LINE__, "impossible", NULL, content);
content = NULL;
break;
}
ndx = NDN_BT_SRCH_INDEX(res);
res = ndn_btree_match_interest(leaf, ndx, msg, pi, scratch);
if (res == -1) {
ndnr_debug_ndnb(h, __LINE__, "match_error", NULL, msg, size);
content = NULL;
break;
}
if (res == 1) {
if ((pi->orderpref & 1) == 0) // XXX - should be symbolic
break;
last_match = content->cookie;
last_match_acc = content->accession;
content = r_store_next_child_at_level(h, content, comps->n - 1);
}
else
content = r_store_content_next(h, content);
if (content != NULL &&
!r_store_content_matches_interest_prefix(h, content, msg, size))
content = NULL;
}
if (last_match != 0) {
content = r_store_content_from_cookie(h, last_match);
if (content == NULL)
content = r_store_content_from_accession(h, last_match_acc);
}
ndn_charbuf_destroy(&scratch);
if (content != NULL) {
h->count_lmc_found += 1;
h->count_lmc_found_iters += try;
}
else {
h->count_lmc_notfound += 1;
h->count_lmc_notfound_iters += try;
}
return(content);
}
/**
* Find the first content handle that matches the prefix given by the namish,
* which may be a Name, Interest, ContentObject, ...
*
* Does not check the other parts of namish, in particular, does not generate
* the digest component of a ContentObject.
*/
PUBLIC struct content_entry *
r_store_lookup_ndnb(struct ndnr_handle *h,
const unsigned char *namish, size_t size)
{
struct content_entry *content = NULL;
struct ndn_charbuf *flatname = NULL;
int res;
flatname = ndn_charbuf_create();
if (flatname == NULL)
goto Bail;
res = ndn_flatname_from_ndnb(flatname, namish, size);
if (res < 0)
goto Bail;
content = r_store_look(h, flatname->buf, flatname->length);
if (content != NULL) {
res = ndn_flatname_charbuf_compare(flatname, content->flatname);
if (res == 0 || res == -9999) {
/* prefix matches */
}
else
content = NULL;
}
Bail:
ndn_charbuf_destroy(&flatname);
return(content);
}
/**
* Mark content as stale
*/
PUBLIC void
r_store_mark_stale(struct ndnr_handle *h, struct content_entry *content)
{
ndnr_cookie cookie = content->cookie;
if ((content->flags & NDN_CONTENT_ENTRY_STALE) != 0)
return;
if (NDNSHOULDLOG(h, LM_4, NDNL_FINE))
ndnr_debug_content(h, __LINE__, "stale", NULL, content);
content->flags |= NDN_CONTENT_ENTRY_STALE;
h->n_stale++;
if (cookie < h->min_stale)
h->min_stale = cookie;
if (cookie > h->max_stale)
h->max_stale = cookie;
}
/**
* Scheduled event that makes content stale when its FreshnessSeconds
* has expired.
*/
static int
expire_content(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *h = clienth;
ndnr_cookie cookie = ev->evint;
struct content_entry *content = NULL;
if ((flags & NDN_SCHEDULE_CANCEL) != 0)
return(0);
content = r_store_content_from_cookie(h, cookie);
if (content != NULL)
r_store_mark_stale(h, content);
return(0);
}
/**
* Schedules content expiration based on its FreshnessSeconds.
*
*/
PUBLIC void
r_store_set_content_timer(struct ndnr_handle *h, struct content_entry *content,
struct ndn_parsed_ContentObject *pco)
{
int seconds = 0;
int microseconds = 0;
size_t start = pco->offset[NDN_PCO_B_FreshnessSeconds];
size_t stop = pco->offset[NDN_PCO_E_FreshnessSeconds];
const unsigned char *content_msg = NULL;
if (start == stop)
return;
content_msg = r_store_content_base(h, content);
if (content_msg == NULL) {
ndnr_debug_content(h, __LINE__, "Missing_content_base", NULL,
content);
return;
}
seconds = ndn_fetch_tagged_nonNegativeInteger(
NDN_DTAG_FreshnessSeconds,
content_msg,
start, stop);
if (seconds <= 0)
return;
if (seconds > ((1U<<31) / 1000000)) {
ndnr_debug_content(h, __LINE__, "FreshnessSeconds_too_large", NULL,
content);
return;
}
microseconds = seconds * 1000000;
ndn_schedule_event(h->sched, microseconds,
&expire_content, NULL, content->cookie);
}
/**
* Parses content object and sets content->flatname
*/
static int
r_store_set_flatname(struct ndnr_handle *h, struct content_entry *content,
struct ndn_parsed_ContentObject *pco)
{
int res;
struct ndn_charbuf *flatname = NULL;
const unsigned char *msg = NULL;
size_t size;
msg = r_store_content_base(h, content);
size = content->size;
if (msg == NULL)
goto Bail;
flatname = ndn_charbuf_create();
if (flatname == NULL)
goto Bail;
res = ndn_parse_ContentObject(msg, size, pco, NULL);
if (res < 0) {
ndnr_msg(h, "error parsing ContentObject - code %d", res);
goto Bail;
}
ndn_digest_ContentObject(msg, pco);
if (pco->digest_bytes != 32)
goto Bail;
res = ndn_flatname_from_ndnb(flatname, msg, size);
if (res < 0) goto Bail;
res = ndn_flatname_append_component(flatname, pco->digest, pco->digest_bytes);
if (res < 0) goto Bail;
content->flatname = flatname;
flatname = NULL;
return(0);
Bail:
ndn_charbuf_destroy(&flatname);
return(-1);
}
/**
* Get the flatname associated with content
*
* @returns flatname in a charbuf, which should be treated as read-only.
*/
PUBLIC struct ndn_charbuf *
r_store_content_flatname(struct ndnr_handle *h, struct content_entry *content)
{
return(content->flatname);
}
PUBLIC struct content_entry *
process_incoming_content(struct ndnr_handle *h, struct fdholder *fdholder,
unsigned char *msg, size_t size, off_t *offsetp)
{
struct ndn_parsed_ContentObject obj = {0};
int res;
struct content_entry *content = NULL;
ndnr_accession accession = NDNR_NULL_ACCESSION;
content = calloc(1, sizeof(*content));
if (content == NULL)
goto Bail;
content->cob = ndn_charbuf_create();
if (content->cob == NULL)
goto Bail;
res = ndn_charbuf_append(content->cob, msg, size);
if (res < 0) goto Bail;
content->size = size;
res = r_store_set_flatname(h, content, &obj);
if (res < 0) goto Bail;
ndnr_meter_bump(h, fdholder->meter[FM_DATI], 1);
content->accession = NDNR_NULL_ACCESSION;
if (fdholder->filedesc == h->active_in_fd && offsetp != NULL) {
// if we are reading from repoFile1 to rebuild the index we already know
// the accession number
content->accession = ((ndnr_accession)*offsetp) | r_store_mark_repoFile1;
}
r_store_enroll_content(h, content);
if (NDNSHOULDLOG(h, LM_4, NDNL_FINE))
ndnr_debug_content(h, __LINE__, "content_from", fdholder, content);
res = r_store_content_btree_insert(h, content, &obj, &accession);
if (res < 0) goto Bail;
if (res == 0) {
/* Content was there, with an accession */
if (NDNSHOULDLOG(h, LM_4, NDNL_FINER))
ndnr_debug_content(h, __LINE__, "content_duplicate",
fdholder, content);
h->content_dups_recvd++;
r_store_forget_content(h, &content);
content = r_store_content_from_accession(h, accession);
if (content == NULL)
goto Bail;
}
r_store_set_content_timer(h, content, &obj);
r_match_match_interests(h, content, &obj, NULL, fdholder);
return(content);
Bail:
r_store_forget_content(h, &content);
return(content);
}
PUBLIC int
r_store_content_field_access(struct ndnr_handle *h,
struct content_entry *content,
enum ndn_dtag dtag,
const unsigned char **bufp, size_t *sizep)
{
int res = -1;
const unsigned char *content_msg;
struct ndn_parsed_ContentObject pco = {0};
content_msg = r_store_content_base(h, content);
if (content_msg == NULL)
return(-1);
res = ndn_parse_ContentObject(content_msg, content->size, &pco, NULL);
if (res < 0)
return(-1);
if (dtag == NDN_DTAG_Content)
res = ndn_ref_tagged_BLOB(NDN_DTAG_Content, content_msg,
pco.offset[NDN_PCO_B_Content],
pco.offset[NDN_PCO_E_Content],
bufp, sizep);
return(res);
}
PUBLIC int
r_store_set_accession_from_offset(struct ndnr_handle *h,
struct content_entry *content,
struct fdholder *fdholder, off_t offset)
{
struct ndn_btree_node *leaf = NULL;
uint_least64_t cobid;
int ndx;
int res = -1;
if (offset != (off_t)-1 && content->accession == NDNR_NULL_ACCESSION) {
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
struct content_by_accession_entry *entry = NULL;
content->flags |= NDN_CONTENT_ENTRY_STABLE;
content->accession = ((ndnr_accession)offset) | r_store_mark_repoFile1;
hashtb_start(h->content_by_accession_tab, e);
hashtb_seek(e, &content->accession, sizeof(content->accession), 0);
entry = e->data;
if (entry != NULL) {
entry->content = content;
if (content->cob != NULL)
h->cob_count++;
}
hashtb_end(e);
if (content->flatname != NULL) {
res = ndn_btree_lookup(h->btree,
content->flatname->buf,
content->flatname->length, &leaf);
if (res >= 0 && NDN_BT_SRCH_FOUND(res)) {
ndx = NDN_BT_SRCH_INDEX(res);
cobid = ndnr_accession_encode(h, content->accession);
ndn_btree_prepare_for_update(h->btree, leaf);
res = ndn_btree_content_set_cobid(leaf, ndx, cobid);
}
else
res = -1;
}
if (res >= 0 && content->accession >= h->notify_after)
r_sync_notify_content(h, 0, content);
}
return(res);
}
PUBLIC void
r_store_send_content(struct ndnr_handle *h, struct fdholder *fdholder, struct content_entry *content)
{
const unsigned char *content_msg = NULL;
off_t offset;
content_msg = r_store_content_base(h, content);
if (content_msg == NULL) {
ndnr_debug_content(h, __LINE__, "content_missing", fdholder, content);
return;
}
if (NDNSHOULDLOG(h, LM_4, NDNL_FINE))
ndnr_debug_content(h, __LINE__, "content_to", fdholder, content);
r_link_stuff_and_send(h, fdholder, content_msg, content->size, NULL, 0, &offset);
if (offset != (off_t)-1 && content->accession == NDNR_NULL_ACCESSION) {
int res;
res = r_store_set_accession_from_offset(h, content, fdholder, offset);
if (res == 0)
if (NDNSHOULDLOG(h, LM_4, NDNL_FINE))
ndnr_debug_content(h, __LINE__, "content_stored",
r_io_fdholder_from_fd(h, h->active_out_fd),
content);
}
}
PUBLIC int
r_store_commit_content(struct ndnr_handle *h, struct content_entry *content)
{
struct fdholder *fdholder = r_io_fdholder_from_fd(h, h->active_out_fd);
// XXX - here we need to check if this is something we *should* be storing, according to our policy
if ((r_store_content_flags(content) & NDN_CONTENT_ENTRY_STABLE) == 0) {
if (fdholder == NULL)
{
ndnr_msg(h, "Repository shutting down due to error storing content.");
h->running = 0;
return(-1);
}
r_store_send_content(h, r_io_fdholder_from_fd(h, h->active_out_fd), content);
r_store_content_change_flags(content, NDN_CONTENT_ENTRY_STABLE, 0);
}
#ifdef CAREPO
hash_store_insert(h->hashstore, content->accession, content->cob, NULL);
#endif
return(0);
}
PUBLIC void
ndnr_debug_content(struct ndnr_handle *h,
int lineno,
const char *msg,
struct fdholder *fdholder,
struct content_entry *content)
{
struct ndn_charbuf *c = ndn_charbuf_create();
struct ndn_charbuf *flat = content->flatname;
if (c == NULL)
return;
ndn_charbuf_putf(c, "debug.%d %s ", lineno, msg);
if (fdholder != NULL)
ndn_charbuf_putf(c, "%u ", fdholder->filedesc);
if (flat != NULL)
ndn_uri_append_flatname(c, flat->buf, flat->length, 1);
ndn_charbuf_putf(c, " (%d bytes)", content->size);
ndnr_msg(h, "%s", ndn_charbuf_as_string(c));
ndn_charbuf_destroy(&c);
}
/** Number of btree index writes to do in a batch */
#define NDN_BT_CLEAN_BATCH 3
/** Approximate delay between batches of btree index writes */
#define NDN_BT_CLEAN_TICK_MICROS 65536
static int
r_store_index_cleaner(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *h = clienth;
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
struct ndn_btree_node *node = NULL;
int k;
int res;
int overquota;
(void)(sched);
(void)(ev);
if ((flags & NDN_SCHEDULE_CANCEL) != 0 ||
h->btree == NULL || h->btree->io == NULL) {
h->index_cleaner = NULL;
ndn_indexbuf_destroy(&h->toclean);
return(0);
}
/* First, work on cleaning the things we already know need cleaning */
if (h->toclean != NULL) {
for (k = 0; k < NDN_BT_CLEAN_BATCH && h->toclean->n > 0; k++) {
node = ndn_btree_rnode(h->btree, h->toclean->buf[--h->toclean->n]);
if (node != NULL && node->iodata != NULL) {
res = ndn_btree_chknode(node); /* paranoia */
if (res < 0 || NDNSHOULDLOG(h, sdfsdffd, NDNL_FINER))
ndnr_msg(h, "write index node %u (err %d)",
(unsigned)node->nodeid, node->corrupt);
if (res >= 0) {
if (node->clean != node->buf->length)
res = h->btree->io->btwrite(h->btree->io, node);
if (res < 0)
ndnr_msg(h, "failed to write index node %u",
(unsigned)node->nodeid);
else
node->clean = node->buf->length;
}
if (res >= 0 && node->iodata != NULL && node->activity == 0) {
if (NDNSHOULDLOG(h, sdfsdffd, NDNL_FINER))
ndnr_msg(h, "close index node %u",
(unsigned)node->nodeid);
res = ndn_btree_close_node(h->btree, node);
}
}
}
if (h->toclean->n > 0)
return(nrand48(h->seed) % (2U * NDN_BT_CLEAN_TICK_MICROS) + 500);
}
/* Sweep though and find the nodes that still need cleaning */
overquota = 0;
if (h->btree->nodepool >= 16)
overquota = hashtb_n(h->btree->resident) - h->btree->nodepool;
hashtb_start(h->btree->resident, e);
for (node = e->data; node != NULL; node = e->data) {
if (overquota > 0 &&
node->activity == 0 &&
node->iodata == NULL &&
node->clean == node->buf->length) {
overquota -= 1;
if (NDNSHOULDLOG(h, sdfsdffd, NDNL_FINEST))
ndnr_msg(h, "prune index node %u",
(unsigned)node->nodeid);
hashtb_delete(e);
continue;
}
node->activity /= 2; /* Age the node's activity */
if (node->clean != node->buf->length ||
(node->iodata != NULL && node->activity == 0)) {
if (h->toclean == NULL) {
h->toclean = ndn_indexbuf_create();
if (h->toclean == NULL)
break;
}
ndn_indexbuf_append_element(h->toclean, node->nodeid);
}
hashtb_next(e);
}
hashtb_end(e);
/* If nothing to do, shut down cleaner */
if ((h->toclean == NULL || h->toclean->n == 0) && overquota <= 0 &&
h->btree->io->openfds <= NDN_BT_OPEN_NODES_IDLE) {
h->btree->cleanreq = 0;
h->index_cleaner = NULL;
ndn_indexbuf_destroy(&h->toclean);
if (NDNSHOULDLOG(h, sdfsdffd, NDNL_FINE))
ndnr_msg(h, "index btree nodes all clean");
return(0);
}
return(nrand48(h->seed) % (2U * NDN_BT_CLEAN_TICK_MICROS) + 500);
}
PUBLIC void
r_store_index_needs_cleaning(struct ndnr_handle *h)
{
int k;
if (h->btree != NULL && h->btree->io != NULL && h->btree->cleanreq > 0) {
if (h->index_cleaner == NULL) {
h->index_cleaner = ndn_schedule_event(h->sched,
NDN_BT_CLEAN_TICK_MICROS,
r_store_index_cleaner, NULL, 0);
if (NDNSHOULDLOG(h, sdfsdffd, NDNL_FINER))
ndnr_msg(h, "index cleaner started");
}
/* If necessary, clean in a hurry. */
for (k = 30; /* Backstop to make sure we do not loop here */
k > 0 && h->index_cleaner != NULL &&
h->btree->io->openfds > NDN_BT_OPEN_NODES_LIMIT - 2; k--)
r_store_index_cleaner(h->sched, h, h->index_cleaner, 0);
if (k == 0)
ndnr_msg(h, "index cleaner is in trouble");
}
}
#undef FAILIF
#undef CHKSYS
#undef CHKRES
#undef CHKPTR
|
yoursunny/carepo
|
command/unittest.c
|
#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
int main(void) {
CU_initialize_registry();
CU_pSuite suite;
#define SUITE(name) { suite = CU_add_suite(#name, NULL, NULL); }
#define TEST(f) { void test_##f(void); CU_add_test(suite, #f, test_##f); }
#include "segment/testsuite.h"
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
CU_cleanup_registry();
return 0;
}
|
yoursunny/carepo
|
segment/testsuite.h
|
<gh_stars>0
SUITE(segment);
TEST(segment_ctor);
TEST(segment_rabin);
|
yoursunny/carepo
|
repo/ndnr_util.c
|
/**
* @file ndnr_util.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_util.h"
PUBLIC struct ndn_charbuf *
r_util_charbuf_obtain(struct ndnr_handle *h)
{
struct ndn_charbuf *c = h->scratch_charbuf;
if (c == NULL)
return(ndn_charbuf_create());
h->scratch_charbuf = NULL;
c->length = 0;
return(c);
}
PUBLIC void
r_util_charbuf_release(struct ndnr_handle *h, struct ndn_charbuf *c)
{
c->length = 0;
if (h->scratch_charbuf == NULL)
h->scratch_charbuf = c;
else
ndn_charbuf_destroy(&c);
}
PUBLIC struct ndn_indexbuf *
r_util_indexbuf_obtain(struct ndnr_handle *h)
{
struct ndn_indexbuf *c = h->scratch_indexbuf;
if (c == NULL)
return(ndn_indexbuf_create());
h->scratch_indexbuf = NULL;
c->n = 0;
return(c);
}
PUBLIC void
r_util_indexbuf_release(struct ndnr_handle *h, struct ndn_indexbuf *c)
{
c->n = 0;
if (h->scratch_indexbuf == NULL)
h->scratch_indexbuf = c;
else
ndn_indexbuf_destroy(&c);
}
PUBLIC void
r_util_reseed(struct ndnr_handle *h)
{
int fd;
ssize_t res;
res = -1;
fd = open("/dev/urandom", O_RDONLY);
if (fd != -1) {
res = read(fd, h->seed, sizeof(h->seed));
close(fd);
}
if (res != sizeof(h->seed)) {
h->seed[1] = (unsigned short)getpid(); /* better than no entropy */
h->seed[2] = (unsigned short)time(NULL);
}
/*
* The call to seed48 is needed by cygwin, and should be harmless
* on other platforms.
*/
seed48(h->seed);
}
PUBLIC void
r_util_gettime(const struct ndn_gettime *self, struct ndn_timeval *result)
{
struct ndnr_handle *h = self->data;
struct timeval now = {0};
gettimeofday(&now, 0);
result->s = now.tv_sec;
result->micros = now.tv_usec;
h->sec = now.tv_sec;
h->usec = now.tv_usec;
}
PUBLIC int
r_util_timecmp(long secA, unsigned usecA, long secB, unsigned usecB)
{
if (secA < secB) return (-1);
if (secA > secB) return (1);
if (usecA < usecB) return (-1);
if (usecA > usecB) return (1);
return (0);
}
PUBLIC intmax_t
r_util_segment_from_component(const unsigned char *ndnb, size_t start, size_t stop)
{
const unsigned char *data = NULL;
size_t len = 0;
intmax_t segment;
int i;
if (start < stop) {
ndn_ref_tagged_BLOB(NDN_DTAG_Component, ndnb, start, stop, &data, &len);
if (len > 0 && data != NULL && data[0] == 0 && len <= (1 + sizeof(intmax_t))) {
// parse big-endian encoded number with leading 0 byte
segment = 0;
for (i = 1; i < len; i++) {
segment = segment * 256 + data[i];
}
return(segment);
}
}
return(-1);
}
/**
* Compare a name component at index i to bytes in buf and return 0
* if they are equal length and equal value.
* In the case of inequality, a negative or positive value is returned,
* according to the canonical ordering of names.
*/
int
r_util_name_comp_compare(const unsigned char *data,
const struct ndn_indexbuf *indexbuf,
unsigned int i, const void *buf, size_t length)
{
const unsigned char *comp_ptr;
size_t comp_size;
if (ndn_name_comp_get(data, indexbuf, i, &comp_ptr, &comp_size) != 0)
return(-1);
if (comp_size < length)
return(-1);
if (comp_size > length)
return(1);
return(memcmp(comp_ptr, buf, length));
}
|
yoursunny/carepo
|
repo/ndnr_proto.c
|
<gh_stars>0
/**
* @file ndnr_proto.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <ndn/ndn.h>
#include <ndn/charbuf.h>
#include <ndn/ndn_private.h>
#include <ndn/hashtb.h>
#include <ndn/schedule.h>
#include <ndn/sockaddrutil.h>
#include <ndn/uri.h>
#include <ndn/coding.h>
#include <sync/SyncBase.h>
#include "ndnr_private.h"
#include "ndnr_proto.h"
#include "ndnr_dispatch.h"
#include "ndnr_forwarding.h"
#include "ndnr_init.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
#include "ndnr_sendq.h"
#include "ndnr_store.h"
#include "ndnr_sync.h"
#include "ndnr_util.h"
#define NDNR_MAX_RETRY 5
static enum ndn_upcall_res
r_proto_start_write(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp);
static enum ndn_upcall_res
r_proto_start_write_checked(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp);
static enum ndn_upcall_res
r_proto_begin_enumeration(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp);
static enum ndn_upcall_res
r_proto_continue_enumeration(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp);
static enum ndn_upcall_res
r_proto_bulk_import(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp);
#ifdef CAREPO
enum ndn_upcall_res hash_store_handle_proto_sha256(struct hash_store* self, struct ndn_upcall_info* info);
#endif
static int
name_comp_equal_prefix(const unsigned char *data,
const struct ndn_indexbuf *indexbuf,
unsigned int i, const void *buf, size_t length);
PUBLIC enum ndn_upcall_res
r_proto_answer_req(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info)
{
struct ndn_charbuf *msg = NULL;
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *keylocator = NULL;
struct ndn_charbuf *signed_info = NULL;
struct ndn_charbuf *reply_body = NULL;
struct ndnr_handle *ndnr = NULL;
struct content_entry *content = NULL;
int res = 0;
int ncomps;
int marker_comp;
// struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
switch (kind) {
case NDN_UPCALL_FINAL:
free(selfp);
return(NDN_UPCALL_RESULT_OK);
case NDN_UPCALL_INTEREST:
break;
case NDN_UPCALL_CONSUMED_INTEREST:
return(NDN_UPCALL_RESULT_OK);
default:
return(NDN_UPCALL_RESULT_ERR);
}
ndnr = (struct ndnr_handle *)selfp->data;
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_answer_req", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
content = r_store_lookup(ndnr, info->interest_ndnb, info->pi, info->interest_comps);
if (content != NULL) {
struct fdholder *fdholder = r_io_fdholder_from_fd(ndnr, ndn_get_connection_fd(info->h));
if (fdholder != NULL)
r_sendq_face_send_queue_insert(ndnr, r_io_fdholder_from_fd(ndnr, ndn_get_connection_fd(info->h)), content);
res = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
goto Finish;
}
/* commands will potentially generate new content, test if new content is ok */
if ((info->pi->answerfrom & NDN_AOK_NEW) == 0) {
goto Bail;
}
/* check for command markers */
ncomps = info->interest_comps->n;
if (((marker_comp = ncomps - 2) >= 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, NAME_BE, strlen(NAME_BE))) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "name_enumeration", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_begin_enumeration(selfp, kind, info, marker_comp);
goto Finish;
} else if (((marker_comp = ncomps - 3) >= 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, NAME_BE, strlen(NAME_BE)) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp + 1, ndnr->ndnr_keyid->buf, ndnr->ndnr_keyid->length)) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "name_enumeration_repoid", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_begin_enumeration(selfp, kind, info, marker_comp);
goto Finish;
} else if (((marker_comp = ncomps - 5) >= 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, NAME_BE, strlen(NAME_BE)) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp + 1, ndnr->ndnr_keyid->buf, ndnr->ndnr_keyid->length)) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "name_enumeration_continuation",
NULL, info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_continue_enumeration(selfp, kind, info, marker_comp);
goto Finish;
} else if (((marker_comp = ncomps - 3) > 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, REPO_SW, strlen(REPO_SW))) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "repo_start_write", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_start_write(selfp, kind, info, marker_comp);
goto Finish;
} else if (((marker_comp = ncomps - 5) > 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, REPO_SWC, strlen(REPO_SWC))) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "repo_start_write_checked",
NULL, info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_start_write_checked(selfp, kind, info, marker_comp);
goto Finish;
} else if (((marker_comp = 0) == 0) &&
name_comp_equal_prefix(info->interest_ndnb, info->interest_comps, marker_comp, REPO_AF, strlen(REPO_AF))) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "repo_bulk_import",
NULL, info->interest_ndnb, info->pi->offset[NDN_PI_E]);
res = r_proto_bulk_import(selfp, kind, info, marker_comp);
goto Finish;
#ifdef CAREPO
} else if (((marker_comp = ncomps - 3) == 0) &&
0 == r_util_name_comp_compare(info->interest_ndnb, info->interest_comps, marker_comp, REPO_SHA256, strlen(REPO_SHA256))) {
res = hash_store_handle_proto_sha256(ndnr->hashstore, info);
goto Finish;
#endif
}
goto Bail;
Bail:
res = NDN_UPCALL_RESULT_ERR;
Finish:
ndn_charbuf_destroy(&msg);
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&keylocator);
ndn_charbuf_destroy(&reply_body);
ndn_charbuf_destroy(&signed_info);
return(res);
}
// XXX these should probably be rationalized and added to ndn_name_util.c
/**
* Compare a name component at index i to bytes in buf and return 1
* if they are equal in the first length bytes. The name component
* must contain at least length bytes for this comparison to return
* equality.
* @returns 1 for equality, 0 for inequality.
*/
static int
name_comp_equal_prefix(const unsigned char *data,
const struct ndn_indexbuf *indexbuf,
unsigned int i, const void *buf, size_t length)
{
const unsigned char *comp_ptr;
size_t comp_size;
if (ndn_name_comp_get(data, indexbuf, i, &comp_ptr, &comp_size) != 0)
return(0);
if (comp_size < length || memcmp(comp_ptr, buf, length) != 0)
return(0);
return(1);
}
PUBLIC void
r_proto_uri_listen(struct ndnr_handle *ndnr, struct ndn *ndn, const char *uri,
ndn_handler p, intptr_t intdata)
{
struct ndn_charbuf *name;
struct ndn_closure *closure = NULL;
name = ndn_charbuf_create();
ndn_name_from_uri(name, uri);
if (p != NULL) {
closure = calloc(1, sizeof(*closure));
closure->p = p;
closure->data = ndnr;
closure->intdata = intdata;
}
ndn_set_interest_filter(ndn, name, closure);
ndn_charbuf_destroy(&name);
}
// XXX - need an r_proto_uninit to uninstall the policy
PUBLIC void
r_proto_init(struct ndnr_handle *ndnr) {
// nothing to do
}
/**
* Install the listener for the namespaces that the parsed policy says to serve
*
* Normal usage is to deactivate the old policy and then activate the new one
*/
PUBLIC void
r_proto_activate_policy(struct ndnr_handle *ndnr, struct ndnr_parsed_policy *pp) {
int i;
for (i = 0; i < pp->namespaces->n; i++) {
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_INFO))
ndnr_msg(ndnr, "Adding listener for policy namespace %s",
(char *)pp->store->buf + pp->namespaces->buf[i]);
r_proto_uri_listen(ndnr, ndnr->direct_client,
(char *)pp->store->buf + pp->namespaces->buf[i],
r_proto_answer_req, 0);
}
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_INFO))
ndnr_msg(ndnr, "Adding listener for policy global prefix %s",
(char *)pp->store->buf + pp->global_prefix_offset);
r_proto_uri_listen(ndnr, ndnr->direct_client,
(char *)pp->store->buf + pp->global_prefix_offset,
r_proto_answer_req, 0);
}
/**
* Uninstall the listener for the namespaces that the parsed policy says to serve
*/
PUBLIC void
r_proto_deactivate_policy(struct ndnr_handle *ndnr, struct ndnr_parsed_policy *pp) {
int i;
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_INFO))
ndnr_msg(ndnr, "Removing listener for policy global prefix %s",
(char *)pp->store->buf + pp->global_prefix_offset);
r_proto_uri_listen(ndnr, ndnr->direct_client,
(char *)pp->store->buf + pp->global_prefix_offset,
NULL, 0);
for (i = 0; i < pp->namespaces->n; i++) {
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_INFO))
ndnr_msg(ndnr, "Removing listener for policy namespace %s",
(char *)pp->store->buf + pp->namespaces->buf[i]);
r_proto_uri_listen(ndnr, ndnr->direct_client,
(char *)pp->store->buf + pp->namespaces->buf[i],
NULL, 0);
}
}
/**
* Construct a charbuf with an encoding of a RepositoryInfo
*/
PUBLIC int
r_proto_append_repo_info(struct ndnr_handle *ndnr,
struct ndn_charbuf *rinfo,
struct ndn_charbuf *names,
const char *info) {
int res;
struct ndn_charbuf *name = ndn_charbuf_create();
if (name == NULL) return (-1);
res = ndnb_element_begin(rinfo, NDN_DTAG_RepositoryInfo);
res |= ndnb_tagged_putf(rinfo, NDN_DTAG_Version, "%s", "1.1");
res |= ndnb_tagged_putf(rinfo, NDN_DTAG_Type, "%s", (names != NULL) ? "DATA" : "INFO");
res |= ndnb_tagged_putf(rinfo, NDN_DTAG_RepositoryVersion, "%s", "2.0");
res |= ndnb_element_begin(rinfo, NDN_DTAG_GlobalPrefixName); // same structure as Name
res |= ndnb_element_end(rinfo);
ndn_name_init(name);
res |= ndn_name_from_uri(name, (char *)ndnr->parsed_policy->store->buf + ndnr->parsed_policy->global_prefix_offset);
res |= ndn_name_append_components(rinfo, name->buf, 1, name->length - 1);
res |= ndnb_tagged_putf(rinfo, NDN_DTAG_LocalName, "%s", "Repository");
if (names != NULL)
res |= ndn_charbuf_append_charbuf(rinfo, names);
if (info != NULL)
res |= ndnb_tagged_putf(rinfo, NDN_DTAG_InfoString, "%s", info);
// There is an optional NDN_DTAG_InfoString in the encoding here, like the LocalName
res |= ndnb_element_end(rinfo); // NDN_DTAG_RepositoryInfo
ndn_charbuf_destroy(&name);
return (res);
}
static struct ndn_charbuf *
r_proto_mktemplate(struct ndnr_expect_content *md, struct ndn_upcall_info *info)
{
struct ndn_charbuf *templ = ndn_charbuf_create();
ndnb_element_begin(templ, NDN_DTAG_Interest); // same structure as Name
ndnb_element_begin(templ, NDN_DTAG_Name);
ndnb_element_end(templ); /* </Name> */
// XXX - use pubid if possible
// XXX - if start-write was scoped, use scope here?
ndnb_tagged_putf(templ, NDN_DTAG_MinSuffixComponents, "%d", 1);
ndnb_tagged_putf(templ, NDN_DTAG_MaxSuffixComponents, "%d", 1);
ndnb_element_end(templ); /* </Interest> */
return(templ);
}
PUBLIC enum ndn_upcall_res
r_proto_expect_content(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info)
{
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *templ = NULL;
const unsigned char *ndnb = NULL;
size_t ndnb_size = 0;
const unsigned char *ib = NULL; /* info->interest_ndnb */
struct ndn_indexbuf *ic = NULL;
int res;
struct ndnr_expect_content *md = selfp->data;
struct ndnr_handle *ndnr = NULL;
struct content_entry *content = NULL;
int i;
int empty_slots;
intmax_t segment;
if (kind == NDN_UPCALL_FINAL) {
if (md != NULL) {
selfp->data = NULL;
free(md);
md = NULL;
}
free(selfp);
return(NDN_UPCALL_RESULT_OK);
}
if (md == NULL) {
return(NDN_UPCALL_RESULT_ERR);
}
if (md->done)
return(NDN_UPCALL_RESULT_ERR);
ndnr = (struct ndnr_handle *)md->ndnr;
if (kind == NDN_UPCALL_INTEREST_TIMED_OUT) {
if (md->tries > NDNR_MAX_RETRY) {
ndnr_debug_ndnb(ndnr, __LINE__, "fetch_failed", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
return(NDN_UPCALL_RESULT_ERR);
}
md->tries++;
return(NDN_UPCALL_RESULT_REEXPRESS);
}
if (kind == NDN_UPCALL_CONTENT_UNVERIFIED) {
// XXX - Some forms of key locator can confuse libndn. Don't provoke it to fetch keys until that is hardened.
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "key_needed", NULL, info->content_ndnb, info->pco->offset[NDN_PCO_E]);
}
switch (kind) {
case NDN_UPCALL_CONTENT:
case NDN_UPCALL_CONTENT_UNVERIFIED:
#if (NDN_API_VERSION >= 4004)
case NDN_UPCALL_CONTENT_RAW:
case NDN_UPCALL_CONTENT_KEYMISSING:
#endif
break;
default:
return(NDN_UPCALL_RESULT_ERR);
}
ndnb = info->content_ndnb;
ndnb_size = info->pco->offset[NDN_PCO_E];
ib = info->interest_ndnb;
ic = info->interest_comps;
content = process_incoming_content(ndnr, r_io_fdholder_from_fd(ndnr, ndn_get_connection_fd(info->h)),
(void *)ndnb, ndnb_size, NULL);
if (content == NULL) {
ndnr_msg(ndnr, "r_proto_expect_content: failed to process incoming content");
return(NDN_UPCALL_RESULT_ERR);
}
r_store_commit_content(ndnr, content);
r_proto_initiate_key_fetch(ndnr, ndnb, info->pco, 0,
r_store_content_cookie(ndnr, content));
md->tries = 0;
segment = r_util_segment_from_component(ib, ic->buf[ic->n - 2], ic->buf[ic->n - 1]);
if (ndn_is_final_block(info) == 1)
md->final = segment;
if (md->keyfetch != 0 && segment <= 0) {
/* This should either be a key, or a link to get to it. */
if (info->pco->type == NDN_CONTENT_LINK) {
r_proto_initiate_key_fetch(ndnr, ndnb, info->pco, 1, md->keyfetch);
}
else if (info->pco->type == NDN_CONTENT_KEY) {
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_FINE))
ndnr_msg(ndnr, "key_arrived %u", (unsigned)(md->keyfetch));
// XXX - should check that we got the right key.
}
else {
// not a key or a link. Log it so we have a clue.
ndnr_msg(ndnr, "ERROR - got something else when trying to fetch key for item %u", (unsigned)(md->keyfetch));
}
}
// Unsegmented content should skip pipeline processing.
if (segment < 0) {
if (md->expect_complete != NULL) {
(md->expect_complete)(selfp, kind, info);
}
return(NDN_UPCALL_RESULT_OK);
}
/* retire the current segment and any segments beyond the final one */
empty_slots = 0;
for (i = 0; i < NDNR_PIPELINE; i++) {
if (md->outstanding[i] == segment || ((md->final > -1) && (md->outstanding[i] > md->final)))
md->outstanding[i] = -1;
if (md->outstanding[i] == -1)
empty_slots++;
}
md->done = (md->final > -1) && (empty_slots == NDNR_PIPELINE);
// if there is a completion handler set up, and we've got all the blocks
// call it -- note that this may not be the last block if they arrive out of order.
if (md->done && (md->expect_complete != NULL))
(md->expect_complete)(selfp, kind, info);
if (md->final > -1) {
return (NDN_UPCALL_RESULT_OK);
}
name = ndn_charbuf_create();
if (ic->n < 2) abort();
templ = r_proto_mktemplate(md, info);
/* fill the pipeline with new requests */
for (i = 0; i < NDNR_PIPELINE; i++) {
if (md->outstanding[i] == -1) {
ndn_name_init(name);
res = ndn_name_append_components(name, ib, ic->buf[0], ic->buf[ic->n - 2]);
if (res < 0) abort();
ndn_name_append_numeric(name, NDN_MARKER_SEQNUM, ++(selfp->intdata));
res = ndn_express_interest(info->h, name, selfp, templ);
if (res < 0) abort();
md->outstanding[i] = selfp->intdata;
}
}
ndn_charbuf_destroy(&templ);
ndn_charbuf_destroy(&name);
return(NDN_UPCALL_RESULT_OK);
}
static int
r_proto_policy_update(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
struct ndn_charbuf *name = ev->evdata;
struct content_entry *content = NULL;
const unsigned char *content_msg = NULL;
const unsigned char *vers = NULL;
size_t vers_size = 0;
struct ndn_parsed_ContentObject pco = {0};
struct ndn_indexbuf *nc;
struct ndn_charbuf *policy = NULL;
struct ndn_charbuf *policy_link_cob = NULL;
struct ndn_charbuf *policyFileName = NULL;
const unsigned char *buf = NULL;
size_t length = 0;
struct ndnr_parsed_policy *pp;
int segment = -1;
int final = 0;
int res;
int ans = -1;
int fd = -1;
if ((flags & NDN_SCHEDULE_CANCEL) != 0) {
ans = 0;
goto Bail;
}
policy = ndn_charbuf_create();
nc = ndn_indexbuf_create();
do {
ndn_name_append_numeric(name, NDN_MARKER_SEQNUM, ++segment);
content = r_store_lookup_ndnb(ndnr, name->buf, name->length);
if (content == NULL) {
ndnr_debug_ndnb(ndnr, __LINE__, "policy lookup failed for", NULL,
name->buf, name->length);
goto Bail;
}
ndn_name_chop(name, NULL, -1);
content_msg = r_store_content_base(ndnr, content);
if (content_msg == NULL) {
ndnr_debug_ndnb(ndnr, __LINE__, "Policy read failed for", NULL,
name->buf, name->length);
goto Bail;
}
res = ndn_parse_ContentObject(content_msg, r_store_content_size(ndnr, content), &pco, nc);
res = ndn_ref_tagged_BLOB(NDN_DTAG_Content, content_msg,
pco.offset[NDN_PCO_B_Content],
pco.offset[NDN_PCO_E_Content],
&buf, &length);
ndn_charbuf_append(policy, buf, length);
final = ndn_is_final_pco(content_msg, &pco, nc);
} while (!final);
pp = ndnr_parsed_policy_create();
if (pp == NULL) {
ndnr_msg(ndnr, "Parsed policy allocation error");
goto Bail;
}
memmove(pp->version, vers, vers_size);
if (r_proto_parse_policy(ndnr, policy->buf, policy->length, pp) < 0) {
ndnr_msg(ndnr, "Malformed policy");
goto Bail;
}
res = strcmp((char *)pp->store->buf + pp->global_prefix_offset,
(char *)ndnr->parsed_policy->store->buf + ndnr->parsed_policy->global_prefix_offset);
if (0 != res) {
ndnr_msg(ndnr, "Policy global prefix mismatch");
goto Bail;
}
policy_link_cob = ndnr_init_policy_link_cob(ndnr, ndnr->direct_client, name);
if (policy_link_cob != NULL) {
ndn_charbuf_destroy(&ndnr->policy_link_cob);
ndnr->policy_link_cob = policy_link_cob;
}
policyFileName = ndn_charbuf_create();
ndn_charbuf_putf(policyFileName, "%s/repoPolicy", ndnr->directory);
fd = open(ndn_charbuf_as_string(policyFileName), O_WRONLY | O_CREAT, 0666);
if (fd < 0) {
ndnr_msg(ndnr, "open policy: %s (errno = %d)", strerror(errno), errno);
goto Bail;
}
lseek(fd, 0, SEEK_SET);
res = write(fd, ndnr->policy_link_cob->buf, ndnr->policy_link_cob->length);
if (res == -1) {
ndnr_msg(ndnr, "write policy: %s (errno = %d)", strerror(errno), errno);
goto Bail;
}
res = ftruncate(fd, ndnr->policy_link_cob->length);
if (res == -1) {
ndnr_msg(ndnr, "Policy truncate %u :%s (errno = %d)",
fd, strerror(errno), errno);
goto Bail;
}
close(fd);
fd = -1;
r_proto_deactivate_policy(ndnr, ndnr->parsed_policy);
ndnr_parsed_policy_destroy(&ndnr->parsed_policy);
ndnr->parsed_policy = pp;
r_proto_activate_policy(ndnr, pp);
ans = 0;
Bail:
ndn_charbuf_destroy(&name);
ndn_indexbuf_destroy(&nc);
ndn_charbuf_destroy(&policy);
ndn_charbuf_destroy(&policyFileName);
if (fd >= 0) close(fd);
return (ans);
}
static enum ndn_upcall_res
r_proto_policy_complete(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info)
{
struct ndnr_expect_content *md = selfp->data;
struct ndnr_handle *ndnr = (struct ndnr_handle *)md->ndnr;
const unsigned char *ndnb;
size_t ndnb_size;
const unsigned char *vers = NULL;
size_t vers_size = 0;
struct ndn_indexbuf *cc;
struct ndn_charbuf *name;
// the version of the new policy must be greater than the exist one
// or we will not activate it and update the link to point to it.
ndnb = info->content_ndnb;
ndnb_size = info->pco->offset[NDN_PCO_E];
cc = info->content_comps;
ndn_name_comp_get(ndnb, cc, cc->n - 3, &vers, &vers_size);
if (vers_size != 7 || vers[0] != NDN_MARKER_VERSION)
return(NDN_UPCALL_RESULT_ERR);
if (memcmp(vers, ndnr->parsed_policy->version, sizeof(ndnr->parsed_policy->version)) <= 0) {
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_INFO))
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_policy_complete older policy ignored", NULL,
ndnb, ndnb_size);
return (NDN_UPCALL_RESULT_ERR);
}
// all components not including segment
name = ndn_charbuf_create();
if (name == NULL || ndn_name_init(name) < 0) {
ndnr_msg(ndnr,"r_proto_policy_complete no memory to update policy");
ndn_charbuf_destroy(&name);
return (NDN_UPCALL_RESULT_ERR);
}
ndn_name_append_components(name, ndnb, cc->buf[0], cc->buf[cc->n - 2]);
ndn_schedule_event(ndnr->sched, 500, r_proto_policy_update, name, 0);
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINEST))
ndnr_msg(ndnr,"r_proto_policy_complete update scheduled");
return (NDN_UPCALL_RESULT_OK);
}
static enum ndn_upcall_res
r_proto_start_write(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp)
{
struct ndnr_handle *ndnr = NULL;
struct ndn_charbuf *templ = NULL;
struct ndn_closure *incoming = NULL;
struct ndnr_expect_content *expect_content = NULL;
struct ndn_charbuf *reply_body = NULL;
struct ndn_charbuf *name = NULL;
struct ndn_indexbuf *ic = NULL;
enum ndn_upcall_res ans = NDN_UPCALL_RESULT_ERR;
struct ndn_charbuf *msg = NULL;
int res = 0;
int start = 0;
int end = 0;
int is_policy = 0;
int i;
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
// XXX - Check for valid nonce
// XXX - Check for pubid - if present and not ours, do not respond.
// Check for answer origin kind.
// If Exclude is there, there might be something fishy going on.
ndnr = (struct ndnr_handle *)selfp->data;
if (ndnr->start_write_scope_limit < 3) {
start = info->pi->offset[NDN_PI_B_Scope];
end = info->pi->offset[NDN_PI_E_Scope];
if (start == end || info->pi->scope > ndnr->start_write_scope_limit) {
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_INFO))
ndnr_msg(ndnr, "r_proto_start_write: interest scope exceeds limit");
return(NDN_UPCALL_RESULT_OK);
}
}
// don't handle the policy file here
start = info->pi->offset[NDN_PI_B_Name];
end = info->interest_comps->buf[marker_comp - 1]; // not including version or marker
name = ndn_charbuf_create();
ndn_charbuf_append(name, info->interest_ndnb + start, end - start);
ndn_charbuf_append_closer(name);
if (0 ==ndn_compare_names(name->buf, name->length,
ndnr->policy_name->buf, ndnr->policy_name->length))
is_policy = 1;
/* Generate our reply */
start = info->pi->offset[NDN_PI_B_Name];
end = info->interest_comps->buf[info->pi->prefix_comps];
name->length = 0;
ndn_charbuf_append(name, info->interest_ndnb + start, end - start);
ndn_charbuf_append_closer(name);
msg = ndn_charbuf_create();
reply_body = ndn_charbuf_create();
r_proto_append_repo_info(ndnr, reply_body, NULL, NULL);
sp.freshness = 12; /* seconds */
res = ndn_sign_content(info->h, msg, name, &sp,
reply_body->buf, reply_body->length);
if (res < 0)
goto Bail;
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_start_write response", NULL,
msg->buf, msg->length);
res = ndn_put(info->h, msg->buf, msg->length);
if (res < 0) {
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_start_write ndn_put FAILED", NULL,
msg->buf, msg->length);
goto Bail;
}
/* Send an interest for segment 0 */
expect_content = calloc(1, sizeof(*expect_content));
if (expect_content == NULL)
goto Bail;
expect_content->ndnr = ndnr;
expect_content->final = -1;
for (i = 0; i < NDNR_PIPELINE; i++)
expect_content->outstanding[i] = -1;
if (is_policy) {
expect_content->expect_complete = &r_proto_policy_complete;
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_msg(ndnr, "r_proto_start_write: is policy file");
}
incoming = calloc(1, sizeof(*incoming));
if (incoming == NULL)
goto Bail;
incoming->p = &r_proto_expect_content;
incoming->data = expect_content;
templ = r_proto_mktemplate(expect_content, NULL);
ic = info->interest_comps;
ndn_name_init(name);
ndn_name_append_components(name, info->interest_ndnb, ic->buf[0], ic->buf[marker_comp]);
ndn_name_append_numeric(name, NDN_MARKER_SEQNUM, 0);
expect_content->outstanding[0] = 0;
res = ndn_express_interest(info->h, name, incoming, templ);
if (res >= 0) {
/* upcall will free these when it is done. */
incoming = NULL;
expect_content = NULL;
ans = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
}
else {
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_start_write ndn_express_interest FAILED", NULL,
name->buf, name->length);
goto Bail;
}
Bail:
if (incoming != NULL)
free(incoming);
if (expect_content != NULL)
free(expect_content);
ndn_charbuf_destroy(&templ);
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&reply_body);
ndn_charbuf_destroy(&msg);
return(ans);
}
static enum ndn_upcall_res
r_proto_start_write_checked(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp)
{
struct ndnr_handle *ndnr = NULL;
enum ndn_upcall_res ans = NDN_UPCALL_RESULT_OK;
struct ndn_indexbuf *ic = NULL;
struct content_entry *content = NULL;
struct ndn_parsed_interest parsed_interest = {0};
struct ndn_parsed_interest *pi = &parsed_interest;
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *interest = NULL;
struct ndn_indexbuf *comps = NULL;
struct ndn_charbuf *msg = NULL;
struct ndn_charbuf *reply_body = NULL;
int start = 0;
int end = 0;
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
int res = 0;
// XXX - do we need to disallow the policy file here too?
ndnr = (struct ndnr_handle *)selfp->data;
if (ndnr->start_write_scope_limit < 3) {
start = info->pi->offset[NDN_PI_B_Scope];
end = info->pi->offset[NDN_PI_E_Scope];
if (start == end || info->pi->scope > ndnr->start_write_scope_limit) {
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_INFO))
ndnr_msg(ndnr, "r_proto_start_write_checked: interest scope exceeds limit");
return(NDN_UPCALL_RESULT_OK);
}
}
name = ndn_charbuf_create();
ndn_name_init(name);
ic = info->interest_comps;
ndn_name_append_components(name, info->interest_ndnb, ic->buf[0], ic->buf[marker_comp]);
ndn_name_append_components(name, info->interest_ndnb, ic->buf[marker_comp + 2], ic->buf[ic->n - 1]);
// Make an interest for the exact item we're checking
interest = ndn_charbuf_create();
ndnb_element_begin(interest, NDN_DTAG_Interest);
ndn_charbuf_append_charbuf(interest, name);
ndnb_element_end(interest); /* </Interest> */
// Parse it
comps = ndn_indexbuf_create();
res = ndn_parse_interest(interest->buf, interest->length, pi, comps);
if (res < 0)
abort();
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_start_write_checked looking for", NULL,
interest->buf, interest->length);
content = r_store_lookup(ndnr, interest->buf, pi, comps);
ndn_charbuf_destroy(&interest);
ndn_indexbuf_destroy(&comps);
if (content == NULL) {
ndn_charbuf_destroy(&name);
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_msg(ndnr, "r_proto_start_write_checked: NOT PRESENT");
// XXX - dropping into the start_write case means we do not check the provided digest when fetching, so this is not completely right.
return(r_proto_start_write(selfp, kind, info, marker_comp));
}
// what's the return value if the item is in the repository already?
// if it does have it -- getRepoInfo(interest.name(), null, target_names)
// response has local name as the full name of the thing we claim to have --
// take the command marker and nonce out of the middle of the incoming interest,
// which is what we have in the "name" of the interest we created to check the content.
///// begin copied code
/* Generate our reply */
msg = ndn_charbuf_create();
reply_body = ndn_charbuf_create();
r_proto_append_repo_info(ndnr, reply_body, name, NULL);
start = info->pi->offset[NDN_PI_B_Name];
end = info->interest_comps->buf[info->pi->prefix_comps];
name->length = 0;
ndn_charbuf_append(name, info->interest_ndnb + start, end - start);
ndn_charbuf_append_closer(name);
sp.freshness = 12; /* Seconds */
res = ndn_sign_content(info->h, msg, name, &sp,
reply_body->buf, reply_body->length);
if (res < 0)
goto Bail;
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_msg(ndnr, "r_proto_start_write_checked PRESENT");
res = ndn_put(info->h, msg->buf, msg->length);
if (res < 0) {
// note the error somehow.
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_start_write_checked ndn_put FAILED", NULL,
msg->buf, msg->length);
}
//// end of copied code
Bail:
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&reply_body);
ndn_charbuf_destroy(&msg);
return(ans);
}
/**
* Returns 1 if the Exclude in the interest described by the info parameter
* would exclude the full name in name.
*/
static int
r_proto_check_exclude(struct ndnr_handle *ndnr,
struct ndn_upcall_info *info,
struct ndn_charbuf *name)
{
struct ndn_buf_decoder decoder;
struct ndn_buf_decoder *d = NULL;
const unsigned char *comp = NULL;
size_t comp_size;
size_t name_comp_size;
struct ndn_indexbuf *name_comps = NULL;
const unsigned char *name_string = NULL;
int ci;
int res;
int ans = 0;
if (info->pi->offset[NDN_PI_B_Exclude] < info->pi->offset[NDN_PI_E_Exclude]) {
d = ndn_buf_decoder_start(&decoder,
info->interest_ndnb + info->pi->offset[NDN_PI_B_Exclude],
info->pi->offset[NDN_PI_E_Exclude] -
info->pi->offset[NDN_PI_B_Exclude]);
// handle easy case of <Exclude><Component>...</Exclude>
// XXX - this may need to be better, but not necessarily complete
if (ndn_buf_match_dtag(d, NDN_DTAG_Exclude)) {
ndn_buf_advance(d);
} else
goto Bail;
// there may be something to check, so get the components of the name
name_comps = ndn_indexbuf_create();
if (ndn_name_split(name, name_comps) < 0)
goto Bail;
// the component in the name we are matching is last plus one of the interest
// but ci includes an extra value for the end of the last component
ci = info->interest_comps->n;
res = ndn_name_comp_get(name->buf, name_comps, ci - 1, &name_string, &name_comp_size);
if (res < 0)
goto Bail;
while (ndn_buf_match_dtag(d, NDN_DTAG_Component)) {
ndn_buf_advance(d);
comp_size = 0;
if (ndn_buf_match_blob(d, &comp, &comp_size))
ndn_buf_advance(d);
ndn_buf_check_close(d);
if (comp_size == name_comp_size) {
res = memcmp(comp, name_string, comp_size);
if (res == 0) {
ans = 1;
goto Bail; /* One of the explicit excludes */
}
if (res > 0)
break;
}
}
}
Bail:
ndn_indexbuf_destroy(&name_comps);
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINE))
ndnr_msg(ndnr, "r_proto_check_exclude: do%s exclude", (ans == 1) ? "" : " not");
return(ans);
}
void
r_proto_finalize_enum_state(struct hashtb_enumerator *e)
{
struct enum_state *es = e->data;
unsigned i;
ndn_charbuf_destroy(&es->name);
ndn_charbuf_destroy(&es->interest); // unnecessary?
ndn_charbuf_destroy(&es->reply_body);
ndn_indexbuf_destroy(&es->interest_comps);
for (i = 0; i < ENUM_N_COBS; i++)
ndn_charbuf_destroy(&(es->cob[i]));
return;
}
#define ENUMERATION_STATE_TICK_MICROSEC 1000000
/**
* Remove expired enumeration table entries
*/
static int
reap_enumerations(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
struct enum_state *es = NULL;
if ((flags & NDN_SCHEDULE_CANCEL) != 0) {
ndnr->reap_enumerations = NULL;
return(0);
}
hashtb_start(ndnr->enum_state_tab, e);
for (es = e->data; es != NULL; es = e->data) {
if (es->active != ES_ACTIVE &&
r_util_timecmp(es->lastuse_sec + es->lifetime, es->lastuse_usec,
ndnr->sec, ndnr->usec) <= 0) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_debug_ndnb(ndnr, __LINE__, "reap enumeration state", NULL,
es->name->buf, es->name->length); // remove the entry from the hash table, finalization frees data
hashtb_delete(e);
}
hashtb_next(e);
}
hashtb_end(e);
if (hashtb_n(ndnr->enum_state_tab) == 0) {
ndnr->reap_enumerations = NULL;
return(0);
}
return(ENUMERATION_STATE_TICK_MICROSEC);
}
static void
reap_enumerations_needed(struct ndnr_handle *ndnr)
{
if (ndnr->reap_enumerations == NULL)
ndnr->reap_enumerations = ndn_schedule_event(ndnr->sched,
ENUMERATION_STATE_TICK_MICROSEC,
reap_enumerations,
NULL, 0);
}
static enum ndn_upcall_res
r_proto_begin_enumeration(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp)
{
struct ndnr_handle *ndnr = NULL;
enum ndn_upcall_res ans = NDN_UPCALL_RESULT_ERR;
struct ndn_parsed_interest parsed_interest = {0};
struct ndn_parsed_interest *pi = &parsed_interest;
struct hashtb_enumerator enumerator = {0};
struct hashtb_enumerator *e = &enumerator;
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *cob = NULL;
struct ndn_charbuf *interest = NULL;
struct ndn_indexbuf *comps = NULL;
int res;
struct content_entry *content = NULL;
struct enum_state *es = NULL;
ndnr = (struct ndnr_handle *)selfp->data;
// Construct a name up to but not including the begin enumeration marker component
name = ndn_charbuf_create();
ndn_name_init(name);
ndn_name_append_components(name, info->interest_ndnb,
info->interest_comps->buf[0],
info->interest_comps->buf[marker_comp]);
// Make an interest for the part of the namespace we are after, from the name
interest = ndn_charbuf_create();
ndnb_element_begin(interest, NDN_DTAG_Interest);
ndn_charbuf_append_charbuf(interest, name);
ndnb_element_end(interest); /* </Interest> */
// Parse it
comps = ndn_indexbuf_create();
res = ndn_parse_interest(interest->buf, interest->length, pi, comps);
if (res < 0)
abort();
// Look for a previous enumeration under this prefix
hashtb_start(ndnr->enum_state_tab, e);
res = hashtb_seek(e, name->buf, name->length, 0);
es = e->data;
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "enumeration: begin hash key", NULL,
name->buf, name->length);
// Do not restart an active enumeration, it is probably a duplicate interest
// TODO: may need attention when es->active == ES_ACTIVE_PENDING_INACTIVE
if (res == HT_OLD_ENTRY && es->active != ES_INACTIVE) {
if (es->next_segment > 0)
cob = es->cob[(es->next_segment - 1) % ENUM_N_COBS];
if (cob && ndn_content_matches_interest(cob->buf, cob->length, 1, NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E], info->pi)) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: duplicate request for last cob");
ndn_put(info->h, cob->buf, cob->length);
es->cob_deferred[(es->next_segment - 1) % ENUM_N_COBS] = 0;
ans = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
} else {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINEST)) {
ndnr_msg(ndnr, "enumeration: restart of active enumeration, or excluded");
ndnr_debug_ndnb(ndnr, __LINE__, "enum interest: ", NULL, info->interest_ndnb, info->pi->offset[NDN_PI_E]);
if (cob != NULL)
ndnr_debug_ndnb(ndnr, __LINE__, "enum cob content: ", NULL, cob->buf, cob->length);
}
ans = NDN_UPCALL_RESULT_OK;
}
hashtb_end(e);
goto Bail;
}
// Continue to construct the name under which we will respond: %C1.E.be
ndn_name_append_components(name, info->interest_ndnb,
info->interest_comps->buf[marker_comp],
info->interest_comps->buf[marker_comp + 1]);
// Append the repository key id %C1.K.%00<repoid>
ndn_name_append(name, ndnr->ndnr_keyid->buf, ndnr->ndnr_keyid->length);
if (res == HT_NEW_ENTRY || es->starting_cookie != ndnr->cookie) {
// this is a new enumeration, the time is now.
res = ndn_create_version(info->h, name, NDN_V_NOW, 0, 0);
if (es->name != NULL)
ndn_charbuf_destroy(&es->name);
es->name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(es->name, name);
es->starting_cookie = ndnr->cookie; // XXX - a conservative indicator of change
}
ndn_charbuf_destroy(&name);
// check the exclude against the result name
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "begin enum: result name", NULL,
es->name->buf, es->name->length);
if (r_proto_check_exclude(ndnr, info, es->name) > 0) {
hashtb_end(e);
goto Bail;
}
// do we have anything that matches this enumeration request?
content = r_store_find_first_match_candidate(ndnr, interest->buf, pi);
if (content != NULL &&
!r_store_content_matches_interest_prefix(ndnr, content, interest->buf, interest->length))
content = NULL;
ndn_charbuf_destroy(&es->cob[0]);
es->cob[0] = ndn_charbuf_create();
memset(es->cob_deferred, 0, sizeof(es->cob_deferred));
ndn_charbuf_destroy(&es->reply_body);
es->reply_body = ndn_charbuf_create();
ndnb_element_begin(es->reply_body, NDN_DTAG_Collection);
es->content = content;
ndn_charbuf_destroy(&es->interest);
es->interest = interest;
interest = NULL;
ndn_indexbuf_destroy(&es->interest_comps);
es->interest_comps = comps;
comps = NULL;
es->next_segment = 0;
es->lastuse_sec = ndnr->sec;
es->lastuse_usec = ndnr->usec;
if (content) {
es->lifetime = 3 * ndn_interest_lifetime_seconds(info->interest_ndnb, pi);
es->active = ES_ACTIVE;
} else {
es->lifetime = ndn_interest_lifetime_seconds(info->interest_ndnb, pi);
es->active = ES_PENDING;
}
hashtb_end(e);
reap_enumerations_needed(ndnr);
if (content)
ans = r_proto_continue_enumeration(selfp, kind, info, marker_comp);
else
ans = NDN_UPCALL_RESULT_OK;
Bail:
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&interest);
ndn_indexbuf_destroy(&comps);
return(ans);
}
static enum ndn_upcall_res
r_proto_continue_enumeration(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp) {
// XXX - watch out for pipelined interests for the enumerations -- there
// MUST be an active enumeration continuation before we do anything here.
// Should chop 1 component off interest -- which will look like
// ndn:/.../%C1.E.be/%C1.M.K%00.../%FD.../%00%02
struct ndn_charbuf *hashkey = NULL;
struct ndn_charbuf *result_name = NULL;
struct ndn_charbuf *cob = NULL;
struct ndn_indexbuf *ic = NULL;
intmax_t segment;
struct enum_state *es = NULL;
struct ndnr_handle *ndnr = NULL;
struct hashtb_enumerator enumerator = {0};
struct hashtb_enumerator *e = &enumerator;
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
int cobs_deferred;
int i;
int res = 0;
ndnr = (struct ndnr_handle *)selfp->data;
ic = info->interest_comps;
hashkey=ndn_charbuf_create();
ndn_name_init(hashkey);
ndn_name_append_components(hashkey, info->interest_ndnb,
info->interest_comps->buf[0],
info->interest_comps->buf[marker_comp]);
hashtb_start(ndnr->enum_state_tab, e);
res = hashtb_seek(e, hashkey->buf, hashkey->length, 0);
ndn_charbuf_destroy(&hashkey);
if (res != HT_OLD_ENTRY) {
hashtb_end(e);
return(NDN_UPCALL_RESULT_ERR);
}
es = e->data;
if (es->active != ES_ACTIVE && es->active != ES_ACTIVE_PENDING_INACTIVE) {
hashtb_end(e);
return(NDN_UPCALL_RESULT_ERR);
}
// If there is a segment in the request, get the value.
segment = r_util_segment_from_component(info->interest_ndnb,
ic->buf[ic->n - 2],
ic->buf[ic->n - 1]);
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINE))
ndnr_msg(ndnr, "enumeration: requested %jd :: expected %jd", segment, es->next_segment);
if (segment >= 0 && segment != es->next_segment) {
// too far in the future for us to process
if (segment > es->next_segment + (ENUM_N_COBS / 2)) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: ignoring future segment requested %jd :: expected %jd", segment, es->next_segment);
hashtb_end(e);
return (NDN_UPCALL_RESULT_OK);
}
// if theres a possibility we could have it
if (segment >= es->next_segment - ENUM_N_COBS) {
cob = es->cob[segment % ENUM_N_COBS];
if (cob &&
ndn_content_matches_interest(cob->buf, cob->length, 1, NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E], info->pi)) {
if (NDNSHOULDLOG(ndnr, LM_8, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: putting cob for out-of-order segment %jd",
segment);
ndn_put(info->h, cob->buf, cob->length);
es->cob_deferred[segment % ENUM_N_COBS] = 0;
if (es->active == ES_ACTIVE_PENDING_INACTIVE) {
for (i = 0, cobs_deferred = 0; i < ENUM_N_COBS; i++) {
cobs_deferred += es->cob_deferred[i];
}
if (cobs_deferred == 0)
goto EnumerationComplete;
}
hashtb_end(e);
return (NDN_UPCALL_RESULT_INTEREST_CONSUMED);
}
}
}
NextSegment:
if (NDNSHOULDLOG(ndnr, blah, NDNL_FINE))
ndnr_msg(ndnr, "enumeration: generating segment %jd", es->next_segment);
es->lastuse_sec = ndnr->sec;
es->lastuse_usec = ndnr->usec;
while (es->content != NULL &&
r_store_content_matches_interest_prefix(ndnr, es->content,
es->interest->buf,
es->interest->length)) {
int save = es->reply_body->length;
ndnb_element_begin(es->reply_body, NDN_DTAG_Link);
ndnb_element_begin(es->reply_body, NDN_DTAG_Name);
ndnb_element_end(es->reply_body); /* </Name> */
res = r_store_name_append_components(es->reply_body, ndnr, es->content, es->interest_comps->n - 1, 1);
ndnb_element_end(es->reply_body); /* </Link> */
if (res == 0) {
/* The name matched exactly, need to skip. */
es->reply_body->length = save;
es->content = r_store_next_child_at_level(ndnr, es->content, es->interest_comps->n - 1);
continue;
}
if (res != 1) {
ndnr_debug_ndnb(ndnr, __LINE__, "oops", NULL, es->interest->buf, es->interest->length);
ndnr_debug_content(ndnr, __LINE__, "oops", NULL, es->content);
abort();
}
es->content = r_store_next_child_at_level(ndnr, es->content, es->interest_comps->n - 1);
if (es->reply_body->length >= 4096) {
result_name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(result_name, es->name);
ndn_name_append_numeric(result_name, NDN_MARKER_SEQNUM, es->next_segment);
sp.freshness = 60;
cob = es->cob[es->next_segment % ENUM_N_COBS];
if (cob == NULL) {
cob = ndn_charbuf_create();
es->cob[es->next_segment % ENUM_N_COBS] = cob;
}
cob->length = 0;
res = ndn_sign_content(info->h, cob, result_name, &sp,
es->reply_body->buf, 4096);
ndn_charbuf_destroy(&result_name);
if (segment == -1 || segment == es->next_segment) {
if (NDNSHOULDLOG(ndnr, blah, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: putting cob for segment %jd", es->next_segment);
ndn_put(info->h, cob->buf, cob->length);
} else {
es->cob_deferred[es->next_segment % ENUM_N_COBS] = 1;
}
es->next_segment++;
memmove(es->reply_body->buf, es->reply_body->buf + 4096, es->reply_body->length - 4096);
es->reply_body->length -= 4096;
if (segment >= es->next_segment)
goto NextSegment;
hashtb_end(e);
return (NDN_UPCALL_RESULT_INTEREST_CONSUMED);
}
}
// we will only get here if we are finishing an in-progress enumeration
ndnb_element_end(es->reply_body); /* </Collection> */
result_name = ndn_charbuf_create();
ndn_charbuf_append_charbuf(result_name, es->name);
ndn_name_append_numeric(result_name, NDN_MARKER_SEQNUM, es->next_segment);
sp.freshness = 60;
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
cob = es->cob[es->next_segment % ENUM_N_COBS];
if (cob == NULL) {
cob = ndn_charbuf_create();
es->cob[es->next_segment % ENUM_N_COBS] = cob;
}
cob->length = 0;
res = ndn_sign_content(info->h, cob, result_name, &sp, es->reply_body->buf,
es->reply_body->length);
ndn_charbuf_destroy(&result_name);
if (NDNSHOULDLOG(ndnr, blah, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: putting final cob for segment %jd", es->next_segment);
ndn_put(info->h, cob->buf, cob->length);
es->cob_deferred[es->next_segment % ENUM_N_COBS] = 0;
for (i = 0, cobs_deferred = 0; i < ENUM_N_COBS; i++) {
cobs_deferred += es->cob_deferred[i];
}
if (cobs_deferred > 0) {
if (NDNSHOULDLOG(ndnr, blah, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: %d pending cobs, inactive pending complete",
cobs_deferred);
es->active = ES_ACTIVE_PENDING_INACTIVE;
hashtb_end(e);
return (NDN_UPCALL_RESULT_INTEREST_CONSUMED);
}
EnumerationComplete:
if (NDNSHOULDLOG(ndnr, blah, NDNL_FINER))
ndnr_msg(ndnr, "enumeration: inactive", es->next_segment);
// The enumeration is complete, free charbufs but leave the name.
es->active = ES_INACTIVE;
ndn_charbuf_destroy(&es->interest);
ndn_charbuf_destroy(&es->reply_body);
for (i = 0; i < ENUM_N_COBS; i++)
ndn_charbuf_destroy(&es->cob[i]);
ndn_indexbuf_destroy(&es->interest_comps);
hashtb_end(e);
return(NDN_UPCALL_RESULT_INTEREST_CONSUMED);
}
void
r_proto_dump_enums(struct ndnr_handle *ndnr)
{
struct enum_state *es = NULL;
struct hashtb_enumerator enumerator = {0};
struct hashtb_enumerator *e = &enumerator;
for (hashtb_start(ndnr->enum_state_tab, e); e->data != NULL; hashtb_next(e)) {
es = e->data;
ndnr_msg(ndnr, "Enumeration active: %d, next segment %d, cookie %u",
es->active, es->next_segment, es->starting_cookie);
ndnr_debug_ndnb(ndnr, __LINE__, " enum name", NULL,
es->name->buf, es->name->length);
}
hashtb_end(e);
}
static enum ndn_upcall_res
r_proto_bulk_import(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info,
int marker_comp)
{
enum ndn_upcall_res ans = NDN_UPCALL_RESULT_ERR;
struct ndnr_handle *ndnr = NULL;
struct ndn_charbuf *filename = NULL;
struct ndn_charbuf *filename2 = NULL;
const unsigned char *mstart = NULL;
size_t mlength;
struct ndn_indexbuf *ic = NULL;
struct ndn_charbuf *msg = NULL;
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *reply_body = NULL;
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
const char *infostring = "OK";
int res;
ndnr = (struct ndnr_handle *)selfp->data;
ndn_name_comp_get(info->interest_ndnb, info->interest_comps, marker_comp,
&mstart, &mlength);
if (mlength <= strlen(REPO_AF) + 1 || mstart[strlen(REPO_AF)] != '~') {
infostring = "missing or malformed bulk import name component";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
goto Reply;
}
mstart += strlen(REPO_AF) + 1;
mlength -= (strlen(REPO_AF) + 1);
if (memchr(mstart, '/', mlength) != NULL) {
infostring = "bulk import filename must not include directory";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
goto Reply;
}
filename = ndn_charbuf_create();
ndn_charbuf_append_string(filename, "import/");
ndn_charbuf_append(filename, mstart, mlength);
res = r_init_map_and_process_file(ndnr, filename, 0);
if (res == 1) {
infostring = "unable to open bulk import file";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
goto Reply;
}
if (res < 0) {
infostring = "error parsing bulk import file";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
goto Reply;
}
/* we think we can process it */
filename->length = 0;
ndn_charbuf_putf(filename, "%s/import/", ndnr->directory);
ndn_charbuf_append(filename, mstart, mlength);
filename2 = ndn_charbuf_create();
ndn_charbuf_putf(filename2, "%s/import/.", ndnr->directory);
ndn_charbuf_append(filename2, mstart, mlength);
res = rename(ndn_charbuf_as_string(filename),
ndn_charbuf_as_string(filename2));
if (res < 0) {
infostring = "error renaming bulk import file";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
goto Reply;
}
filename->length = 0;
ndn_charbuf_append_string(filename, "import/.");
ndn_charbuf_append(filename, mstart, mlength);
res = r_init_map_and_process_file(ndnr, filename, 1);
if (res < 0) {
infostring = "error merging bulk import file";
ndnr_msg(ndnr, "r_proto_bulk_import: %s", infostring);
// fall through and unlink anyway
}
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_FINE))
ndnr_msg(ndnr, "unlinking bulk import file %s", ndn_charbuf_as_string(filename2));
unlink(ndn_charbuf_as_string(filename2));
Reply:
/* Generate our reply */
name = ndn_charbuf_create();
ndn_name_init(name);
ic = info->interest_comps;
ndn_name_append_components(name, info->interest_ndnb, ic->buf[0], ic->buf[ic->n - 1]);
msg = ndn_charbuf_create();
reply_body = ndn_charbuf_create();
r_proto_append_repo_info(ndnr, reply_body, NULL, infostring);
sp.freshness = 12; /* Seconds */
res = ndn_sign_content(info->h, msg, name, &sp,
reply_body->buf, reply_body->length);
if (res < 0)
goto Bail;
res = ndn_put(info->h, msg->buf, msg->length);
if (res < 0) {
ndnr_debug_ndnb(ndnr, __LINE__, "r_proto_bulk_import ndn_put FAILED", NULL,
msg->buf, msg->length);
goto Bail;
}
ans = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
Bail:
if (filename != NULL) ndn_charbuf_destroy(&filename);
if (filename2 != NULL) ndn_charbuf_destroy(&filename2);
if (name != NULL) ndn_charbuf_destroy(&name);
if (msg != NULL) ndn_charbuf_destroy(&msg);
if (reply_body != NULL) ndn_charbuf_destroy(&reply_body);
return (ans);
}
/* Construct a charbuf with an encoding of a Policy object
*
* <xs:complexType name="PolicyType">
* <xs:sequence>
* <xs:element name="PolicyVersion" type="xs:string"/>
* <xs:element name="LocalName" type="xs:string"/>
* <xs:element name="GlobalPrefix" type="xs:string"/>
* <!-- 0 or more names -->
* <xs:element name="Namespace" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
* </xs:sequence>
* </xs:complexType>
*/
PUBLIC int
r_proto_policy_append_basic(struct ndnr_handle *ndnr,
struct ndn_charbuf *policy,
const char *version, const char *local_name,
const char *global_prefix)
{
int res;
res = ndnb_element_begin(policy, NDN_DTAG_Policy);
res |= ndnb_tagged_putf(policy, NDN_DTAG_PolicyVersion, "%s", version);
res |= ndnb_tagged_putf(policy, NDN_DTAG_LocalName, "%s", local_name);
res |= ndnb_tagged_putf(policy, NDN_DTAG_GlobalPrefix, "%s", global_prefix);
res |= ndnb_element_end(policy);
return (res);
}
PUBLIC int
r_proto_policy_append_namespace(struct ndnr_handle *ndnr,
struct ndn_charbuf *policy,
const char *namespace)
{
int res;
if (policy->length < 2)
return(-1);
policy->length--; /* remove the closer */
res = ndnb_tagged_putf(policy, NDN_DTAG_Namespace, "%s", namespace);
ndnb_element_end(policy);
return(res);
}
/**
* Parse a ndnb-encoded policy content object and fill in a ndn_parsed_policy
* structure as the result.
*/
PUBLIC int
r_proto_parse_policy(struct ndnr_handle *ndnr, const unsigned char *buf, size_t length,
struct ndnr_parsed_policy *pp)
{
int res = 0;
struct ndn_buf_decoder decoder;
struct ndn_buf_decoder *d = ndn_buf_decoder_start(&decoder, buf,
length);
if (ndn_buf_match_dtag(d, NDN_DTAG_Policy)) {
ndn_buf_advance(d);
pp->policy_version_offset = ndn_parse_tagged_string(d, NDN_DTAG_PolicyVersion, pp->store);
pp->local_name_offset = ndn_parse_tagged_string(d, NDN_DTAG_LocalName, pp->store);
pp->global_prefix_offset = ndn_parse_tagged_string(d, NDN_DTAG_GlobalPrefix, pp->store);
pp->namespaces->n = 0;
while (ndn_buf_match_dtag(d, NDN_DTAG_Namespace)) {
ndn_indexbuf_append_element(pp->namespaces, ndn_parse_tagged_string(d, NDN_DTAG_Namespace, pp->store));
}
ndn_buf_check_close(d);
} else {
return(-1);
}
return (res);
}
/**
* Initiate a key fetch if necessary.
* @returns -1 if error or no name, 0 if fetch was issued, 1 if already stored.
*/
int
r_proto_initiate_key_fetch(struct ndnr_handle *ndnr,
const unsigned char *msg,
struct ndn_parsed_ContentObject *pco,
int use_link,
ndnr_cookie a)
{
/*
* Create a new interest in the key name, set up a callback that will
* insert the key into repo.
*/
int res;
struct ndn_charbuf *key_name = NULL;
struct ndn_closure *key_closure = NULL;
struct ndn_charbuf *templ = NULL;
struct ndnr_expect_content *expect_content = NULL;
const unsigned char *namestart = NULL;
int namelen = 0;
int keynamelen;
int i;
keynamelen = (pco->offset[NDN_PCO_E_KeyName_Name] -
pco->offset[NDN_PCO_B_KeyName_Name]);
if (use_link) {
/* Try to follow a link instead of using keyname */
if (pco->type == NDN_CONTENT_LINK) {
/* For now we only pay attention to the Name in the Link. */
const unsigned char *data = NULL;
size_t data_size = 0;
struct ndn_buf_decoder decoder;
struct ndn_buf_decoder *d;
res = ndn_content_get_value(msg, pco->offset[NDN_PCO_E], pco,
&data, &data_size);
if (res < 0)
return(-1);
d = ndn_buf_decoder_start(&decoder, data, data_size);
if (ndn_buf_match_dtag(d, NDN_DTAG_Link)) {
int start = 0;
int end = 0;
ndn_buf_advance(d);
start = d->decoder.token_index;
ndn_parse_Name(d, NULL);
end = d->decoder.token_index;
ndn_buf_check_close(d);
if (d->decoder.state < 0)
return(-1);
namestart = data + start;
namelen = end - start;
if (namelen == keynamelen &&
0 == memcmp(namestart, msg + pco->offset[NDN_PCO_B_KeyName_Name], namelen)) {
/*
* The link matches the key locator. There is no point
* in checking two times for the same thing.
*/
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "keyfetch_link_opt",
NULL, namestart, namelen);
return(-1);
}
}
}
}
else {
/* Use the KeyName if present */
namestart = msg + pco->offset[NDN_PCO_B_KeyName_Name];
namelen = (pco->offset[NDN_PCO_E_KeyName_Name] -
pco->offset[NDN_PCO_B_KeyName_Name]);
}
/*
* If there is no KeyName or link, provided, we can't ask, so do not bother.
*/
if (namelen == 0 || a == 0)
return(-1);
key_name = ndn_charbuf_create();
ndn_charbuf_append(key_name, namestart, namelen);
/* Construct an interest complete with Name so we can do lookup */
templ = ndn_charbuf_create();
ndn_charbuf_append_tt(templ, NDN_DTAG_Interest, NDN_DTAG);
ndn_charbuf_append(templ, key_name->buf, key_name->length);
ndnb_tagged_putf(templ, NDN_DTAG_MinSuffixComponents, "%d", 1);
ndnb_tagged_putf(templ, NDN_DTAG_MaxSuffixComponents, "%d", 3);
if (pco->offset[NDN_PCO_B_KeyName_Pub] < pco->offset[NDN_PCO_E_KeyName_Pub]) {
ndn_charbuf_append(templ,
msg + pco->offset[NDN_PCO_B_KeyName_Pub],
(pco->offset[NDN_PCO_E_KeyName_Pub] -
pco->offset[NDN_PCO_B_KeyName_Pub]));
}
ndn_charbuf_append_closer(templ); /* </Interest> */
/* See if we already have it - if so we declare we are done. */
if (r_lookup(ndnr, templ, NULL) == 0) {
res = 1;
// Note - it might be that the thing we found is not really the thing
// we were after. For now we don't check.
}
else {
/* We do not have it; need to ask */
res = -1;
expect_content = calloc(1, sizeof(*expect_content));
if (expect_content == NULL)
goto Bail;
expect_content->ndnr = ndnr;
expect_content->final = -1;
for (i = 0; i < NDNR_PIPELINE; i++)
expect_content->outstanding[i] = -1;
/* inform r_proto_expect_content we are looking for a key. */
expect_content->keyfetch = a;
key_closure = calloc(1, sizeof(*key_closure));
if (key_closure == NULL)
goto Bail;
key_closure->p = &r_proto_expect_content;
key_closure->data = expect_content;
res = ndn_express_interest(ndnr->direct_client, key_name, key_closure, templ);
if (res >= 0) {
if (NDNSHOULDLOG(ndnr, sdfdf, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "keyfetch_start",
NULL, templ->buf, templ->length);
key_closure = NULL;
expect_content = NULL;
res = 0;
}
}
Bail:
if (key_closure != NULL)
free(key_closure);
if (expect_content != NULL)
free(expect_content);
ndn_charbuf_destroy(&key_name);
ndn_charbuf_destroy(&templ);
return(res);
}
|
yoursunny/carepo
|
command/rabinseg.c
|
// segment a file using Rabin Fingerprint, and print the segment offsets and hashes
#include "segment/rabin.h"
#include "segment/metadata.h"
void usage(void) {
printf("Usage: rabinseg [-h] filename\n");
}
int main(int argc, char** argv) {
bool human_readable = false;
int opt;
while (-1 != (opt = getopt(argc, argv, "h"))) {
switch (opt) {
case 'h':
human_readable = true;
break;
}
}
if (optind >= argc) {
usage();
return 1;
}
const char* filename = argv[optind];
FILE* file = fopen(filename, "r");
if (file == NULL) return 2;
struct segment_list* sl = segment_rabin(file);
fclose(file);
if (sl == NULL) return 3;
if (human_readable) {
segment_list_print(sl, stdout);
} else {
struct ndn_charbuf* c = ndn_charbuf_create();
segment_list_to_metadata(sl, c);
write(1, c->buf, c->length);
ndn_charbuf_destroy(&c);
}
segment_list_dtor(&sl);
return 0;
}
|
yoursunny/carepo
|
command/caget.c
|
<reponame>yoursunny/carepo<filename>command/caget.c
// fetch a file based on metadata
#include "segment/fetcher.h"
void usage(void) {
printf("Usage: caget name metafile filename\n");
}
int main(int argc, char** argv) {
optind = 1;
if (argc-optind != 3) {
usage();
return 1;
}
const char* name_str = argv[optind+0];
const char* metadata_filename = argv[optind+1];
const char* filename = argv[optind+2];
struct ndn_charbuf* name = ndn_charbuf_create();
ndn_name_from_uri(name, name_str);
FILE* metadata_file = fopen(metadata_filename, "r");
if (metadata_file == NULL) return 2;
struct ndn_charbuf* metadata = ndn_charbuf_create();
while (0 == feof(metadata_file)) {
size_t read_res = fread(ndn_charbuf_reserve(metadata, 2048), 1, 2048, metadata_file);
if (read_res == 0) break;
metadata->length += read_res;
}
struct segment_list* sl = segment_list_from_metadata(metadata->buf, metadata->length);
if (sl == NULL) return 3;
ndn_charbuf_destroy(&metadata);
fclose(metadata_file);
FILE* file = fopen(filename, "w");
if (file == NULL) return 4;
struct ndn* h = ndn_create();
if (-1 == ndn_connect(h, NULL)) return 5;
struct file_fetcher* ff = file_fetcher_ctor(sl, file, h, name);
if (!file_fetcher_run(ff)) return 6;
file_fetcher_dtor(&ff);
fclose(file);
ndn_destroy(&h);
segment_list_dtor(&sl);
ndn_charbuf_destroy(&name);
return 0;
}
|
yoursunny/carepo
|
repo/ndnr_dispatch.c
|
<reponame>yoursunny/carepo
/**
* @file ndnr_dispatch.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include <sync/SyncBase.h>
#include "ndnr_private.h"
#include "ndnr_dispatch.h"
#include "ndnr_forwarding.h"
#include "ndnr_io.h"
#include "ndnr_link.h"
#include "ndnr_match.h"
#include "ndnr_msg.h"
#include "ndnr_proto.h"
#include "ndnr_sendq.h"
#include "ndnr_stats.h"
#include "ndnr_store.h"
#include "ndnr_sync.h"
#include "ndnr_util.h"
static void
process_input_message(struct ndnr_handle *h, struct fdholder *fdholder,
unsigned char *msg, size_t size, int pdu_ok,
off_t *offsetp)
{
struct ndn_skeleton_decoder decoder = {0};
struct ndn_skeleton_decoder *d = &decoder;
ssize_t dres = 0; dres = dres;
enum ndn_dtag dtag;
struct content_entry *content = NULL;
if ((fdholder->flags & NDNR_FACE_UNDECIDED) != 0) {
fdholder->flags &= ~NDNR_FACE_UNDECIDED;
if ((fdholder->flags & NDNR_FACE_LOOPBACK) != 0)
fdholder->flags |= NDNR_FACE_GG;
/* YYY This is the first place that we know that an inbound stream fdholder is speaking NDNx protocol. */
r_io_register_new_face(h, fdholder);
}
d->state |= NDN_DSTATE_PAUSE;
dres = ndn_skeleton_decode(d, msg, size);
if (d->state < 0)
abort(); /* cannot happen because of checks in caller */
if (NDN_GET_TT_FROM_DSTATE(d->state) != NDN_DTAG) {
ndnr_msg(h, "discarding unknown message; size = %lu", (unsigned long)size);
// XXX - keep a count?
return;
}
dtag = d->numval;
switch (dtag) {
// case NDN_DTAG_Interest:
// process_incoming_interest(h, fdholder, msg, size);
// return;
case NDN_DTAG_ContentObject:
content = process_incoming_content(h, fdholder, msg, size, offsetp);
if (content != NULL)
r_store_commit_content(h, content);
return;
default:
break;
}
ndnr_msg(h, "discarding unknown message; dtag=%u, size = %lu",
(unsigned)dtag,
(unsigned long)size);
}
/**
* Break up data in a face's input buffer buffer into individual messages,
* and call process_input_message on each one.
*
* This is used to handle things originating from the internal client -
* its output is input for fdholder 0.
*/
static void
process_input_buffer(struct ndnr_handle *h, struct fdholder *fdholder)
{
unsigned char *msg;
size_t size;
ssize_t dres;
struct ndn_skeleton_decoder *d;
if (fdholder == NULL || fdholder->inbuf == NULL)
return;
d = &fdholder->decoder;
msg = fdholder->inbuf->buf;
size = fdholder->inbuf->length;
while (d->index < size) {
dres = ndn_skeleton_decode(d, msg + d->index, size - d->index);
if (d->state != 0)
break;
process_input_message(h, fdholder, msg + d->index - dres, dres, 0, NULL);
}
if (d->index != size) {
ndnr_msg(h, "protocol error on fdholder %u (state %d), discarding %d bytes",
fdholder->filedesc, d->state, (int)(size - d->index));
// XXX - perhaps this should be a fatal error.
}
fdholder->inbuf->length = 0;
memset(d, 0, sizeof(*d));
}
/**
* Process the input from a socket or file.
*
* The fd has been found ready for input by the poll call.
* Decide what fdholder it corresponds to, and after checking for exceptional
* cases, receive data, parse it into ndnb-encoded messages, and call
* process_input_message for each one.
*/
PUBLIC void
r_dispatch_process_input(struct ndnr_handle *h, int fd)
{
struct fdholder *fdholder = NULL;
struct fdholder *source = NULL;
ssize_t res;
ssize_t dres = 0; dres = dres;
ssize_t msgstart;
unsigned char *buf;
struct ndn_skeleton_decoder *d;
struct sockaddr_storage sstor;
socklen_t addrlen = sizeof(sstor);
struct sockaddr *addr = (struct sockaddr *)&sstor;
fdholder = r_io_fdholder_from_fd(h, fd);
if (fdholder == NULL)
return;
if ((fdholder->flags & (NDNR_FACE_DGRAM | NDNR_FACE_PASSIVE)) == NDNR_FACE_PASSIVE) {
r_io_accept_connection(h, fd);
return;
}
if ((fdholder->flags & NDNR_FACE_NDND) != 0) {
res = ndn_run(h->direct_client, 0);
if (res < 0) {
// Deal with it somehow. Probably means ndnd went away.
// Should schedule reconnection.
ndnr_msg(h, "ndn_run returned error, shutting down direct client");
r_io_shutdown_client_fd(h, fd);
}
return;
}
d = &fdholder->decoder;
if (fdholder->inbuf == NULL) {
fdholder->inbuf = ndn_charbuf_create();
fdholder->bufoffset = 0;
}
if (fdholder->inbuf->length == 0)
memset(d, 0, sizeof(*d));
buf = ndn_charbuf_reserve(fdholder->inbuf, 8800);
memset(&sstor, 0, sizeof(sstor));
if ((fdholder->flags & NDNR_FACE_SOCKMASK) != 0) {
res = recvfrom(fdholder->filedesc, buf, fdholder->inbuf->limit - fdholder->inbuf->length,
/* flags */ 0, addr, &addrlen);
}
else {
res = read(fdholder->filedesc, buf, fdholder->inbuf->limit - fdholder->inbuf->length);
}
if (res == -1)
ndnr_msg(h, "read %u :%s (errno = %d)",
fdholder->filedesc, strerror(errno), errno);
else if (res == 0 && (fdholder->flags & NDNR_FACE_DGRAM) == 0) {
if (fd == h->active_in_fd && h->stable == 0) {
h->stable = lseek(fd, 0, SEEK_END);
ndnr_msg(h, "read %ju bytes", (uintmax_t)h->stable);
}
r_io_shutdown_client_fd(h, fd);
}
else {
off_t offset = (off_t)-1;
off_t *offsetp = NULL;
if ((fdholder->flags & NDNR_FACE_REPODATA) != 0)
offsetp = &offset;
source = fdholder;
ndnr_meter_bump(h, source->meter[FM_BYTI], res);
source->recvcount++;
fdholder->inbuf->length += res;
msgstart = 0;
if (((fdholder->flags & NDNR_FACE_UNDECIDED) != 0 &&
fdholder->inbuf->length >= 6 &&
0 == memcmp(fdholder->inbuf->buf, "GET ", 4))) {
ndnr_stats_handle_http_connection(h, fdholder);
return;
}
dres = ndn_skeleton_decode(d, buf, res);
while (d->state == 0) {
if (offsetp != NULL)
*offsetp = fdholder->bufoffset + msgstart;
process_input_message(h, source,
fdholder->inbuf->buf + msgstart,
d->index - msgstart,
(fdholder->flags & NDNR_FACE_LOCAL) != 0,
offsetp);
msgstart = d->index;
if (msgstart == fdholder->inbuf->length) {
fdholder->inbuf->length = 0;
fdholder->bufoffset += msgstart;
return;
}
dres = ndn_skeleton_decode(d,
fdholder->inbuf->buf + msgstart,
fdholder->inbuf->length - msgstart);
}
fdholder->bufoffset += msgstart;
if ((fdholder->flags & NDNR_FACE_DGRAM) != 0) {
ndnr_msg(h, "protocol error on fdholder %u, discarding %u bytes",
source->filedesc,
(unsigned)(fdholder->inbuf->length - msgstart));
fdholder->inbuf->length = 0;
/* XXX - should probably ignore this source for a while */
return;
}
else if (d->state < 0) {
ndnr_msg(h, "protocol error on fdholder %u", source->filedesc);
r_io_shutdown_client_fd(h, fd);
return;
}
if (msgstart < fdholder->inbuf->length && msgstart > 0) {
/* move partial message to start of buffer */
memmove(fdholder->inbuf->buf, fdholder->inbuf->buf + msgstart,
fdholder->inbuf->length - msgstart);
fdholder->inbuf->length -= msgstart;
d->index -= msgstart;
}
}
}
PUBLIC void
r_dispatch_process_internal_client_buffer(struct ndnr_handle *h)
{
struct fdholder *fdholder = h->face0;
if (fdholder == NULL)
return;
fdholder->inbuf = ndn_grab_buffered_output(h->internal_client);
if (fdholder->inbuf == NULL)
return;
ndnr_meter_bump(h, fdholder->meter[FM_BYTI], fdholder->inbuf->length);
process_input_buffer(h, fdholder);
ndn_charbuf_destroy(&(fdholder->inbuf));
}
/**
* Run the main loop of the ndnr
*/
PUBLIC void
r_dispatch_run(struct ndnr_handle *h)
{
int i;
int res;
int timeout_ms = -1;
int prev_timeout_ms = -1;
int usec;
int usec_direct;
if (h->running < 0) {
ndnr_msg(h, "Fatal error during initialization");
return;
}
for (h->running = 1; h->running;) {
r_dispatch_process_internal_client_buffer(h);
usec = ndn_schedule_run(h->sched);
usec_direct = ndn_process_scheduled_operations(h->direct_client);
if (usec_direct < usec)
usec = usec_direct;
if (1) {
/* If so requested, shut down when ndnd goes away. */
if (ndn_get_connection_fd(h->direct_client) == -1) {
/* XXX - since we cannot reasonably recover, always go away. */
ndnr_msg(h, "lost connection to ndnd");
h->running = 0;
break;
}
}
timeout_ms = (usec < 0) ? -1 : ((usec + 960) / 1000);
if (timeout_ms == 0 && prev_timeout_ms == 0)
timeout_ms = 1;
r_dispatch_process_internal_client_buffer(h);
r_store_trim(h, h->cob_limit);
r_io_prepare_poll_fds(h);
res = poll(h->fds, h->nfds, timeout_ms);
prev_timeout_ms = ((res == 0) ? timeout_ms : 1);
if (-1 == res) {
if (errno == EINTR)
continue;
ndnr_msg(h, "poll: %s (errno = %d)", strerror(errno), errno);
sleep(1);
continue;
}
for (i = 0; res > 0 && i < h->nfds; i++) {
if (h->fds[i].revents != 0) {
res--;
if (h->fds[i].revents & (POLLERR | POLLNVAL | POLLHUP)) {
if (h->fds[i].revents & (POLLIN))
r_dispatch_process_input(h, h->fds[i].fd);
else
r_io_shutdown_client_fd(h, h->fds[i].fd);
continue;
}
if (h->fds[i].revents & (POLLOUT))
r_link_do_deferred_write(h, h->fds[i].fd);
else if (h->fds[i].revents & (POLLIN))
r_dispatch_process_input(h, h->fds[i].fd);
else
ndnr_msg(h, "poll: UNHANDLED");
}
}
}
}
|
yoursunny/carepo
|
repo/ndnr_forwarding.c
|
/**
* @file ndnr_forwarding.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_forwarding.h"
#include "ndnr_io.h"
#include "ndnr_link.h"
#include "ndnr_match.h"
#include "ndnr_msg.h"
#include "ndnr_stats.h"
#include "ndnr_util.h"
PUBLIC void
r_fwd_finalize_nameprefix(struct hashtb_enumerator *e)
{
struct ndnr_handle *h = hashtb_get_param(e->ht, NULL);
struct nameprefix_entry *npe = e->data;
struct propagating_entry *head = &npe->pe_head;
if (head->next != NULL) {
while (head->next != head)
r_match_consume_interest(h, head->next);
}
ndn_indexbuf_destroy(&npe->forward_to);
ndn_indexbuf_destroy(&npe->tap);
while (npe->forwarding != NULL) {
struct ndn_forwarding *f = npe->forwarding;
npe->forwarding = f->next;
free(f);
}
}
|
yoursunny/carepo
|
segment/segment.h
|
#ifndef CAREPO_SEGMENT_SEGMENT_H_
#define CAREPO_SEGMENT_SEGMENT_H_
#include "defs.h"
#define SEGMENT_HASHSZ 32
struct segment {
uint64_t start;
uint16_t length;
uint8_t hash[SEGMENT_HASHSZ];
};
struct segment_list {
uint32_t count;
struct segment* list;
};
struct segment_list* segment_list_ctor(uint32_t count);
void segment_list_dtor(struct segment_list** selfp);
void segment_list_print(const struct segment_list* self, FILE* output);
#endif//CAREPO_SEGMENT_SEGMENT_H_
|
yoursunny/carepo
|
repo/hash_store.h
|
<reponame>yoursunny/carepo
#ifndef CAREPO_REPO_HASH_STORE_H_
#define CAREPO_REPO_HASH_STORE_H_
#include "defs.h"
#include <ndn/btree.h>
#include "ndnr_private.h"
struct hash_store {
struct ndnr_handle* h;
struct ndn_btree* btree;
};
struct hash_store* hash_store_ctor(struct ndnr_handle* h);
void hash_store_dtor(struct hash_store** selfp);
bool hash_store_insert(struct hash_store* self, ndnr_accession accession, struct ndn_charbuf* co, struct ndn_parsed_ContentObject* pco);
ndnr_accession hash_store_find(struct hash_store* self, const uint8_t* hash);
enum ndn_upcall_res hash_store_handle_proto_sha256(struct hash_store* self, struct ndn_upcall_info* info);
// private begin
void hash_store_clean(struct hash_store* self);
bool hash_store_verify_hash(struct hash_store* self, const uint8_t* payload, size_t payloadsz, const uint8_t* expect_hash);
bool hash_store_build_reply(struct hash_store* self, struct ndn_charbuf* reply, const uint8_t* hash, const uint8_t* payload, size_t payloadsz);
// private end
// to send something: create content_entry* with cob without accession, ++h->cob_count, r_store_enroll_content
#endif//CAREPO_REPO_HASH_STORE_H_
|
yoursunny/carepo
|
repo/ndnr_match.h
|
/**
* @file ndnr_match.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_MATCH_DEFINED
#define NDNR_MATCH_DEFINED
#include <ndn/ndn.h>
#include "ndnr_private.h"
void r_match_consume_interest(struct ndnr_handle *h,struct propagating_entry *pe);
int r_match_match_interests(struct ndnr_handle *h,struct content_entry *content,struct ndn_parsed_ContentObject *pc,struct fdholder *fdholder,struct fdholder *from_face);
int r_match_consume_matching_interests(struct ndnr_handle *h,struct nameprefix_entry *npe,struct content_entry *content,struct ndn_parsed_ContentObject *pc,struct fdholder *fdholder);
#endif
|
yoursunny/carepo
|
repo/ndnr_stats.c
|
<reponame>yoursunny/carepo
/**
* @file ndnr_stats.c
*
* Statistics presentation for ndnr.
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <time.h>
#include <unistd.h>
#include <ndn/ndn.h>
#include <ndn/charbuf.h>
#include <ndn/coding.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/sockaddrutil.h>
#include <ndn/hashtb.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_stats.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
#define CRLF "\r\n"
#define NL "\n"
/**
* Provide a way to monitor rates.
*/
struct ndnr_meter {
uintmax_t total;
char what[8];
unsigned rate; /** a scale factor applies */
unsigned lastupdate;
};
struct ndnr_stats {
long total_interest_counts;
long total_flood_control; /* done propagating, still recorded */
};
static int ndnr_collect_stats(struct ndnr_handle *h, struct ndnr_stats *ans);
static struct ndn_charbuf *collect_stats_html(struct ndnr_handle *h);
static void send_http_response(struct ndnr_handle *h, struct fdholder *fdholder,
const char *mime_type,
struct ndn_charbuf *response);
static struct ndn_charbuf *collect_stats_html(struct ndnr_handle *h);
static struct ndn_charbuf *collect_stats_xml(struct ndnr_handle *h);
/* HTTP */
static const char *resp404 =
"HTTP/1.1 404 Not Found" CRLF
"Connection: close" CRLF CRLF;
static const char *resp405 =
"HTTP/1.1 405 Method Not Allowed" CRLF
"Connection: close" CRLF CRLF;
static void
ndnr_stats_http_set_debug(struct ndnr_handle *h, struct fdholder *fdholder, int level)
{
struct ndn_charbuf *response = ndn_charbuf_create();
h->debug = 1;
ndnr_msg(h, "NDNR_DEBUG=%d", level);
h->debug = level;
ndn_charbuf_putf(response, "<title>NDNR_DEBUG=%d</title><tt>NDNR_DEBUG=%d</tt>" CRLF, level, level);
send_http_response(h, fdholder, "text/html", response);
ndn_charbuf_destroy(&response);
}
int
ndnr_stats_handle_http_connection(struct ndnr_handle *h, struct fdholder *fdholder)
{
struct ndn_charbuf *response = NULL;
char rbuf[16];
int i;
int nspace;
int n;
if (fdholder->inbuf->length < 4)
return(-1);
if ((fdholder->flags & NDNR_FACE_NOSEND) != 0) {
r_io_destroy_face(h, fdholder->filedesc);
return(-1);
}
n = sizeof(rbuf) - 1;
if (fdholder->inbuf->length < n)
n = fdholder->inbuf->length;
for (i = 0, nspace = 0; i < n && nspace < 2; i++) {
rbuf[i] = fdholder->inbuf->buf[i];
if (rbuf[i] == ' ')
nspace++;
}
rbuf[i] = 0;
if (nspace < 2 && i < sizeof(rbuf) - 1)
return(-1);
if (0 == strcmp(rbuf, "GET / ") ||
0 == strcmp(rbuf, "GET /? ")) {
response = collect_stats_html(h);
send_http_response(h, fdholder, "text/html", response);
}
else if (0 == strcmp(rbuf, "GET /?l=none ")) {
ndnr_stats_http_set_debug(h, fdholder, 0);
}
else if (0 == strcmp(rbuf, "GET /?l=low ")) {
ndnr_stats_http_set_debug(h, fdholder, 1);
}
else if (0 == strcmp(rbuf, "GET /?l=co ")) {
ndnr_stats_http_set_debug(h, fdholder, 4);
}
else if (0 == strcmp(rbuf, "GET /?l=med ")) {
ndnr_stats_http_set_debug(h, fdholder, 71);
}
else if (0 == strcmp(rbuf, "GET /?l=high ")) {
ndnr_stats_http_set_debug(h, fdholder, -1);
}
else if (0 == strcmp(rbuf, "GET /?f=xml ")) {
response = collect_stats_xml(h);
send_http_response(h, fdholder, "text/xml", response);
}
else if (0 == strcmp(rbuf, "GET "))
r_io_send(h, fdholder, resp404, strlen(resp404), NULL);
else
r_io_send(h, fdholder, resp405, strlen(resp405), NULL);
fdholder->flags |= (NDNR_FACE_NOSEND | NDNR_FACE_CLOSING);
ndn_charbuf_destroy(&response);
return(0);
}
static void
send_http_response(struct ndnr_handle *h, struct fdholder *fdholder,
const char *mime_type, struct ndn_charbuf *response)
{
struct linger linger = { .l_onoff = 1, .l_linger = 1 };
char buf[128];
int hdrlen;
/* Set linger to prevent quickly resetting the connection on close.*/
setsockopt(fdholder->filedesc, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
hdrlen = snprintf(buf, sizeof(buf),
"HTTP/1.1 200 OK" CRLF
"Content-Type: %s; charset=utf-8" CRLF
"Connection: close" CRLF
"Content-Length: %jd" CRLF CRLF,
mime_type,
(intmax_t)response->length);
r_io_send(h, fdholder, buf, hdrlen, NULL);
r_io_send(h, fdholder, response->buf, response->length, NULL);
}
/* Common statistics collection */
static int
ndnr_collect_stats(struct ndnr_handle *h, struct ndnr_stats *ans)
{
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
long sum;
unsigned i;
for (sum = 0, hashtb_start(h->nameprefix_tab, e);
e->data != NULL; hashtb_next(e)) {
struct nameprefix_entry *npe = e->data;
struct propagating_entry *head = &npe->pe_head;
struct propagating_entry *p;
for (p = head->next; p != head; p = p->next) {
if (ndnr_r_io_fdholder_from_fd(h, p->filedesc) != NULL)
sum += 1;
}
}
ans->total_interest_counts = sum;
hashtb_end(e);
for (sum = 0, hashtb_start(h->propagating_tab, e);
e->data != NULL; hashtb_next(e)) {
struct propagating_entry *pe = e->data;
if (pe->interest_msg == NULL)
sum += 1;
}
ans->total_flood_control = sum;
hashtb_end(e);
/* Do a consistency check on pending interest counts */
for (sum = 0, i = 0; i < h->face_limit; i++) {
struct fdholder *fdholder = h->fdholder_by_fd[i];
if (fdholder != NULL)
sum += fdholder->pending_interests;
}
if (sum != ans->total_interest_counts)
ndnr_msg(h, "ndnr_collect_stats found inconsistency %ld != %ld\n",
(long)sum, (long)ans->total_interest_counts);
ans->total_interest_counts = sum;
return(0);
}
/* HTML formatting */
static void
collect_faces_html(struct ndnr_handle *h, struct ndn_charbuf *b)
{
int i;
struct ndn_charbuf *nodebuf;
nodebuf = ndn_charbuf_create();
ndn_charbuf_putf(b, "<h4>Faces</h4>" NL);
ndn_charbuf_putf(b, "<ul>");
for (i = 0; i < h->face_limit; i++) {
struct fdholder *fdholder = h->fdholder_by_fd[i];
if (fdholder != NULL && (fdholder->flags & NDNR_FACE_UNDECIDED) == 0) {
ndn_charbuf_putf(b, " <li>");
ndn_charbuf_putf(b, "<b>fdholder:</b> %u <b>flags:</b> 0x%x",
fdholder->filedesc, fdholder->flags);
ndn_charbuf_putf(b, " <b>pending:</b> %d",
fdholder->pending_interests);
if (fdholder->recvcount != 0)
ndn_charbuf_putf(b, " <b>activity:</b> %d",
fdholder->recvcount);
nodebuf->length = 0;
#if 0
port = 0;
// XXX - fix for fdholder->name
int port = ndn_charbuf_append_sockaddr(nodebuf, fdholder->addr);
if (port > 0) {
const char *node = ndn_charbuf_as_string(nodebuf);
if ((fdholder->flags & NDNR_FACE_PASSIVE) == 0)
ndn_charbuf_putf(b, " <b>remote:</b> %s:%d",
node, port);
else
ndn_charbuf_putf(b, " <b>local:</b> %s:%d",
node, port);
if (fdholder->sendface != fdholder->filedesc &&
fdholder->sendface != NDN_NOFACEID)
ndn_charbuf_putf(b, " <b>via:</b> %u", fdholder->sendface);
}
#endif
ndn_charbuf_putf(b, "</li>" NL);
}
}
ndn_charbuf_putf(b, "</ul>");
ndn_charbuf_destroy(&nodebuf);
}
static void
collect_face_meter_html(struct ndnr_handle *h, struct ndn_charbuf *b)
{
int i;
ndn_charbuf_putf(b, "<h4>fdholder Activity Rates</h4>");
ndn_charbuf_putf(b, "<table cellspacing='0' cellpadding='0' class='tbl' summary='fdholder activity rates'>");
ndn_charbuf_putf(b, "<tbody>" NL);
ndn_charbuf_putf(b, " <tr><td> </td>\t"
" <td>Bytes/sec In/Out</td>\t"
" <td>recv data/intr sent</td>\t"
" <td>sent data/intr recv</td></tr>" NL);
for (i = 0; i < h->face_limit; i++) {
struct fdholder *fdholder = h->fdholder_by_fd[i];
if (fdholder != NULL && (fdholder->flags & (NDNR_FACE_UNDECIDED|NDNR_FACE_PASSIVE)) == 0) {
ndn_charbuf_putf(b, " <tr>");
ndn_charbuf_putf(b, "<td><b>fdholder:</b> %u</td>\t",
fdholder->filedesc);
ndn_charbuf_putf(b, "<td>%6u / %u</td>\t\t",
ndnr_meter_rate(h, fdholder->meter[FM_BYTI]),
ndnr_meter_rate(h, fdholder->meter[FM_BYTO]));
ndn_charbuf_putf(b, "<td>%9u / %u</td>\t\t",
ndnr_meter_rate(h, fdholder->meter[FM_DATI]),
ndnr_meter_rate(h, fdholder->meter[FM_INTO]));
ndn_charbuf_putf(b, "<td>%9u / %u</td>",
ndnr_meter_rate(h, fdholder->meter[FM_DATO]),
ndnr_meter_rate(h, fdholder->meter[FM_INTI]));
ndn_charbuf_putf(b, "</tr>" NL);
}
}
ndn_charbuf_putf(b, "</tbody>");
ndn_charbuf_putf(b, "</table>");
}
static void
collect_forwarding_html(struct ndnr_handle *h, struct ndn_charbuf *b)
{
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
struct ndn_forwarding *f;
int res;
struct ndn_charbuf *name = ndn_charbuf_create();
ndn_charbuf_putf(b, "<h4>Forwarding</h4>" NL);
ndn_charbuf_putf(b, "<ul>");
hashtb_start(h->nameprefix_tab, e);
for (; e->data != NULL; hashtb_next(e)) {
struct nameprefix_entry *ipe = e->data;
ndn_name_init(name);
res = ndn_name_append_components(name, e->key, 0, e->keysize);
if (res < 0)
abort();
if (0) {
ndn_charbuf_putf(b, " <li>");
ndn_uri_append(b, name->buf, name->length, 1);
ndn_charbuf_putf(b, "</li>" NL);
}
for (f = ipe->forwarding; f != NULL; f = f->next) {
if ((f->flags & (NDN_FORW_ACTIVE | NDN_FORW_PFXO)) != 0) {
ndn_name_init(name);
res = ndn_name_append_components(name, e->key, 0, e->keysize);
ndn_charbuf_putf(b, " <li>");
ndn_uri_append(b, name->buf, name->length, 1);
ndn_charbuf_putf(b,
" <b>fdholder:</b> %u"
" <b>flags:</b> 0x%x"
" <b>expires:</b> %d",
f->filedesc,
f->flags & NDN_FORW_PUBMASK,
f->expires);
ndn_charbuf_putf(b, "</li>" NL);
}
}
}
hashtb_end(e);
ndn_charbuf_destroy(&name);
ndn_charbuf_putf(b, "</ul>");
}
static unsigned
ndnr_colorhash(struct ndnr_handle *h)
{
unsigned const char *a = h->ndnr_id;
unsigned v;
v = (a[0] << 16) + (a[1] << 8) + a[2];
return (v | 0xC0C0C0);
}
static struct ndn_charbuf *
collect_stats_html(struct ndnr_handle *h)
{
struct ndnr_stats stats = {0};
struct ndn_charbuf *b = ndn_charbuf_create();
int pid;
struct utsname un;
uname(&un);
pid = getpid();
ndnr_collect_stats(h, &stats);
ndn_charbuf_putf(b,
"<html xmlns='http://www.w3.org/1999/xhtml'>"
"<head>"
"<title>%s ndnr[%d]</title>"
//"<meta http-equiv='refresh' content='3'>"
"<style type='text/css'>"
"/*<![CDATA[*/"
"p.header {color: white; background-color: blue; width: 100%%} "
"table.tbl {border-style: solid; border-width: 1.0px 1.0px 1.0px 1.0px; border-color: black} "
"td {border-style: solid; "
"border-width: 1.0px 1.0px 1.0px 1.0px; "
"border-color: #808080 #808080 #808080 #808080; "
"padding: 6px 6px 6px 6px; "
"margin-left: auto; margin-right: auto; "
"text-align: center"
"} "
"td.left {text-align: left} "
"/*]]>*/"
"</style>"
"</head>" NL
"<body bgcolor='#%06X'>"
"<p class='header'>%s ndnr[%d] local port %s api %d start %ld.%06u now %ld.%06u</p>" NL
"<div><b>Content items:</b> %llu accessioned,"
" %llu cached, %lu stale, %d sparse, %lu duplicate, %lu sent</div>" NL
"<div><b>Interests:</b> %d names,"
" %ld pending, %ld propagating, %ld noted</div>" NL
"<div><b>Interest totals:</b> %lu accepted,"
" %lu dropped, %lu sent, %lu stuffed</div>" NL,
un.nodename,
pid,
ndnr_colorhash(h),
un.nodename,
pid,
h->portstr,
(int)NDN_API_VERSION,
h->starttime, h->starttime_usec,
h->sec,
h->usec,
(unsigned long long)hashtb_n(h->content_by_accession_tab), // XXXXXX -
(unsigned long long)(h->cob_count),
h->n_stale,
hashtb_n(h->content_by_accession_tab),
h->content_dups_recvd,
h->content_items_sent,
hashtb_n(h->nameprefix_tab), stats.total_interest_counts,
hashtb_n(h->propagating_tab) - stats.total_flood_control,
stats.total_flood_control,
h->interests_accepted, h->interests_dropped,
h->interests_sent, h->interests_stuffed);
collect_faces_html(h, b);
collect_face_meter_html(h, b);
collect_forwarding_html(h, b);
ndn_charbuf_putf(b,
"</body>"
"</html>" NL);
return(b);
}
/* XML formatting */
static void
collect_meter_xml(struct ndnr_handle *h, struct ndn_charbuf *b, struct ndnr_meter *m)
{
uintmax_t total;
unsigned rate;
if (m == NULL)
return;
total = ndnr_meter_total(m);
rate = ndnr_meter_rate(h, m);
ndn_charbuf_putf(b, "<%s><total>%ju</total><persec>%u</persec></%s>",
m->what, total, rate, m->what);
}
static void
collect_faces_xml(struct ndnr_handle *h, struct ndn_charbuf *b)
{
int i;
int m;
struct ndn_charbuf *nodebuf;
nodebuf = ndn_charbuf_create();
ndn_charbuf_putf(b, "<faces>");
for (i = 0; i < h->face_limit; i++) {
struct fdholder *fdholder = h->fdholder_by_fd[i];
if (fdholder != NULL && (fdholder->flags & NDNR_FACE_UNDECIDED) == 0) {
ndn_charbuf_putf(b, "<fdholder>");
ndn_charbuf_putf(b,
"<filedesc>%u</filedesc>"
"<faceflags>%04x</faceflags>",
fdholder->filedesc, fdholder->flags);
ndn_charbuf_putf(b, "<pending>%d</pending>",
fdholder->pending_interests);
ndn_charbuf_putf(b, "<recvcount>%d</recvcount>",
fdholder->recvcount);
nodebuf->length = 0;
#if 0
port = 0;
// XXX - fix this to know about fdholder->name
int port = ndn_charbuf_append_sockaddr(nodebuf, fdholder->addr);
if (port > 0) {
const char *node = ndn_charbuf_as_string(nodebuf);
ndn_charbuf_putf(b, "<ip>%s:%d</ip>", node, port);
}
if (fdholder->sendface != fdholder->filedesc &&
fdholder->sendface != NDN_NOFACEID)
ndn_charbuf_putf(b, "<via>%u</via>", fdholder->sendface);
#endif
if (fdholder != NULL && (fdholder->flags & NDNR_FACE_PASSIVE) == 0) {
ndn_charbuf_putf(b, "<meters>");
for (m = 0; m < NDNR_FACE_METER_N; m++)
collect_meter_xml(h, b, fdholder->meter[m]);
ndn_charbuf_putf(b, "</meters>");
}
ndn_charbuf_putf(b, "</fdholder>" NL);
}
}
ndn_charbuf_putf(b, "</faces>");
ndn_charbuf_destroy(&nodebuf);
}
static void
collect_forwarding_xml(struct ndnr_handle *h, struct ndn_charbuf *b)
{
struct hashtb_enumerator ee;
struct hashtb_enumerator *e = ⅇ
struct ndn_forwarding *f;
int res;
struct ndn_charbuf *name = ndn_charbuf_create();
ndn_charbuf_putf(b, "<forwarding>");
hashtb_start(h->nameprefix_tab, e);
for (; e->data != NULL; hashtb_next(e)) {
struct nameprefix_entry *ipe = e->data;
for (f = ipe->forwarding, res = 0; f != NULL && !res; f = f->next) {
if ((f->flags & (NDN_FORW_ACTIVE | NDN_FORW_PFXO)) != 0)
res = 1;
}
if (res) {
ndn_name_init(name);
res = ndn_name_append_components(name, e->key, 0, e->keysize);
ndn_charbuf_putf(b, "<fentry>");
ndn_charbuf_putf(b, "<prefix>");
ndn_uri_append(b, name->buf, name->length, 1);
ndn_charbuf_putf(b, "</prefix>");
for (f = ipe->forwarding; f != NULL; f = f->next) {
if ((f->flags & (NDN_FORW_ACTIVE | NDN_FORW_PFXO)) != 0) {
ndn_charbuf_putf(b,
"<dest>"
"<filedesc>%u</filedesc>"
"<flags>%x</flags>"
"<expires>%d</expires>"
"</dest>",
f->filedesc,
f->flags & NDN_FORW_PUBMASK,
f->expires);
}
}
ndn_charbuf_putf(b, "</fentry>");
}
}
hashtb_end(e);
ndn_charbuf_destroy(&name);
ndn_charbuf_putf(b, "</forwarding>");
}
static struct ndn_charbuf *
collect_stats_xml(struct ndnr_handle *h)
{
struct ndnr_stats stats = {0};
struct ndn_charbuf *b = ndn_charbuf_create();
int i;
ndnr_collect_stats(h, &stats);
ndn_charbuf_putf(b,
"<ndnr>"
"<identity>"
"<ndnrid>");
for (i = 0; i < sizeof(h->ndnr_id); i++)
ndn_charbuf_putf(b, "%02X", h->ndnr_id[i]);
ndn_charbuf_putf(b, "</ndnrid>"
"<apiversion>%d</apiversion>"
"<starttime>%ld.%06u</starttime>"
"<now>%ld.%06u</now>"
"</identity>",
(int)NDN_API_VERSION,
h->starttime, h->starttime_usec,
h->sec,
h->usec);
ndn_charbuf_putf(b,
"<cobs>"
"<accessioned>%llu</accessioned>"
"<cached>%llu</cached>"
"<stale>%lu</stale>"
"<sparse>%d</sparse>"
"<duplicate>%lu</duplicate>"
"<sent>%lu</sent>"
"</cobs>"
"<interests>"
"<names>%d</names>"
"<pending>%ld</pending>"
"<propagating>%ld</propagating>"
"<noted>%ld</noted>"
"<accepted>%lu</accepted>"
"<dropped>%lu</dropped>"
"<sent>%lu</sent>"
"<stuffed>%lu</stuffed>"
"</interests>"
"<lookups>"
"<rightmost>"
"<found>%lu</found>"
"<iterations>%lu</iterations>"
"<notfound>%lu</notfound>"
"<iterations>%lu</iterations>"
"</rightmost>"
"<leftmost>"
"<found>%lu</found>"
"<iterations>%lu</iterations>"
"<notfound>%lu</notfound>"
"<iterations>%lu</iterations>"
"</leftmost>"
"</lookups>"
,
(unsigned long long)hashtb_n(h->content_by_accession_tab), // XXXXXX -
(unsigned long long)(h->cob_count),
h->n_stale,
hashtb_n(h->content_by_accession_tab),
h->content_dups_recvd,
h->content_items_sent,
hashtb_n(h->nameprefix_tab), stats.total_interest_counts,
hashtb_n(h->propagating_tab) - stats.total_flood_control,
stats.total_flood_control,
h->interests_accepted, h->interests_dropped,
h->interests_sent, h->interests_stuffed,
h->count_lmc_found,
h->count_lmc_found_iters,
h->count_lmc_notfound,
h->count_lmc_notfound_iters,
h->count_rmc_found,
h->count_rmc_found_iters,
h->count_rmc_notfound,
h->count_rmc_notfound_iters
);
collect_faces_xml(h, b);
collect_forwarding_xml(h, b);
ndn_charbuf_putf(b, "</ndnr>" NL);
return(b);
}
/**
* create and initialize separately allocated meter.
*/
struct ndnr_meter *
ndnr_meter_create(struct ndnr_handle *h, const char *what)
{
struct ndnr_meter *m;
m = calloc(1, sizeof(*m));
if (m == NULL)
return(NULL);
ndnr_meter_init(h, m, what);
return(m);
}
/**
* Destroy a separately allocated meter.
*/
void
ndnr_meter_destroy(struct ndnr_meter **pm)
{
if (*pm != NULL) {
free(*pm);
*pm = NULL;
}
}
/**
* Initialize a meter.
*/
void
ndnr_meter_init(struct ndnr_handle *h, struct ndnr_meter *m, const char *what)
{
if (m == NULL)
return;
memset(m, 0, sizeof(*m));
if (what != NULL)
strncpy(m->what, what, sizeof(m->what)-1);
ndnr_meter_bump(h, m, 0);
}
static const unsigned meterHz = 7; /* 1/ln(8/7) would give RC const of 1 sec */
/**
* Count something (messages, packets, bytes), and roll up some kind of
* statistics on it.
*/
void
ndnr_meter_bump(struct ndnr_handle *h, struct ndnr_meter *m, unsigned amt)
{
unsigned now; /* my ticks, wrap OK */
unsigned t;
unsigned r;
if (m == NULL)
return;
now = (((unsigned)(h->sec)) * meterHz) + (h->usec * meterHz / 1000000U);
t = m->lastupdate;
m->total += amt;
if (now - t > 166U)
m->rate = amt; /* history has decayed away */
else {
/* Decay the old rate exponentially based on time since last sample. */
for (r = m->rate; t != now && r != 0; t++)
r = r - ((r + 7U) / 8U); /* multiply by 7/8, truncating */
m->rate = r + amt;
}
m->lastupdate = now;
}
/**
* Return the average rate (units per second) of a metered quantity.
*
* m may be NULL.
*/
unsigned
ndnr_meter_rate(struct ndnr_handle *h, struct ndnr_meter *m)
{
unsigned denom = 8;
if (m == NULL)
return(0);
ndnr_meter_bump(h, m, 0);
if (m->rate > 0x0FFFFFFF)
return(m->rate / denom * meterHz);
return ((m->rate * meterHz + (denom - 1)) / denom);
}
/**
* Return the grand total for a metered quantity.
*
* m may be NULL.
*/
uintmax_t
ndnr_meter_total(struct ndnr_meter *m)
{
if (m == NULL)
return(0);
return (m->total);
}
|
yoursunny/carepo
|
repo/ndnr_io.c
|
<filename>repo/ndnr_io.c
/**
* @file ndnr_io.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011, 2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <ndn/bloom.h>
#include <ndn/ndn.h>
#include <ndn/ndn_private.h>
#include <ndn/charbuf.h>
#include <ndn/face_mgmt.h>
#include <ndn/hashtb.h>
#include <ndn/indexbuf.h>
#include <ndn/schedule.h>
#include <ndn/reg_mgmt.h>
#include <ndn/uri.h>
#include "ndnr_private.h"
#include "ndnr_io.h"
#include "ndnr_forwarding.h"
#include "ndnr_internal_client.h"
#include "ndnr_link.h"
#include "ndnr_msg.h"
#include "ndnr_sendq.h"
#include "ndnr_stats.h"
/**
* Looks up a fdholder based on its filedesc (private).
*/
PUBLIC struct fdholder *
r_io_fdholder_from_fd(struct ndnr_handle *h, unsigned filedesc)
{
unsigned slot = filedesc;
struct fdholder *fdholder = NULL;
if (slot < h->face_limit) {
fdholder = h->fdholder_by_fd[slot];
if (fdholder != NULL && fdholder->filedesc != filedesc)
fdholder = NULL;
}
return(fdholder);
}
/**
* Looks up a fdholder based on its filedesc.
*/
PUBLIC struct fdholder *
ndnr_r_io_fdholder_from_fd(struct ndnr_handle *h, unsigned filedesc)
{
return(r_io_fdholder_from_fd(h, filedesc));
}
/**
* Assigns the filedesc for a nacent fdholder,
* calls r_io_register_new_face() if successful.
*/
PUBLIC int
r_io_enroll_face(struct ndnr_handle *h, struct fdholder *fdholder)
{
unsigned i = fdholder->filedesc;
unsigned n = h->face_limit;
struct fdholder **a = h->fdholder_by_fd;
if (i < n && a[i] == NULL) {
if (a[i] == NULL)
goto use_i;
abort();
}
if (i > 65535)
abort();
a = realloc(a, (i + 1) * sizeof(struct fdholder *));
if (a == NULL)
return(-1); /* ENOMEM */
h->face_limit = i + 1;
while (n < h->face_limit)
a[n++] = NULL;
h->fdholder_by_fd = a;
use_i:
a[i] = fdholder;
if (i == 0)
h->face0 = fdholder; /* This one is special */
fdholder->filedesc = i;
fdholder->meter[FM_BYTI] = ndnr_meter_create(h, "bytein");
fdholder->meter[FM_BYTO] = ndnr_meter_create(h, "byteout");
fdholder->meter[FM_INTI] = ndnr_meter_create(h, "intrin");
fdholder->meter[FM_INTO] = ndnr_meter_create(h, "introut");
fdholder->meter[FM_DATI] = ndnr_meter_create(h, "datain");
fdholder->meter[FM_DATO] = ndnr_meter_create(h, "dataout");
r_io_register_new_face(h, fdholder);
return (fdholder->filedesc);
}
/**
* Close an open file descriptor quietly.
*/
static void
close_fd(int *pfd)
{
if (*pfd != -1) {
close(*pfd);
*pfd = -1;
}
}
/**
* Close an open file descriptor, and grumble about it.
*/
/* unused */ void
ndnr_close_fd(struct ndnr_handle *h, unsigned filedesc, int *pfd)
{
int res;
if (*pfd != -1) {
int linger = 0;
setsockopt(*pfd, SOL_SOCKET, SO_LINGER,
&linger, sizeof(linger));
res = close(*pfd);
if (res == -1)
ndnr_msg(h, "close failed for fdholder %u fd=%d: %s (errno=%d)",
filedesc, *pfd, strerror(errno), errno);
else if (NDNSHOULDLOG(h, io, NDNL_FINE))
ndnr_msg(h, "closing fd %d while finalizing fdholder %u", *pfd, filedesc);
*pfd = -1;
}
}
/**
* Initialize the fdholder flags based upon the addr information
* and the provided explicit setflags.
*/
static void
init_face_flags(struct ndnr_handle *h, struct fdholder *fdholder, int setflags)
{
const struct sockaddr *addr;
if ((setflags & (NDNR_FACE_REPODATA)) != 0) {
fdholder->flags |= setflags;
return;
}
addr = (void *)fdholder->name->buf;
if (addr->sa_family == AF_INET6) {
const struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
fdholder->flags |= NDNR_FACE_INET6;
#ifdef IN6_IS_ADDR_LOOPBACK
if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr))
fdholder->flags |= NDNR_FACE_LOOPBACK;
#endif
}
else if (addr->sa_family == AF_INET) {
const struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
const unsigned char *rawaddr;
rawaddr = (const unsigned char *)&addr4->sin_addr.s_addr;
fdholder->flags |= NDNR_FACE_INET;
if (rawaddr[0] == 127)
fdholder->flags |= NDNR_FACE_LOOPBACK;
else {
/* If our side and the peer have the same address, consider it loopback */
/* This is the situation inside of FreeBSD jail. */
struct sockaddr_in myaddr;
socklen_t myaddrlen = sizeof(myaddr);
if (0 == getsockname(fdholder->filedesc, (struct sockaddr *)&myaddr, &myaddrlen)) {
if (addr4->sin_addr.s_addr == myaddr.sin_addr.s_addr)
fdholder->flags |= NDNR_FACE_LOOPBACK;
}
}
}
else if (addr->sa_family == AF_UNIX)
fdholder->flags |= (NDNR_FACE_GG | NDNR_FACE_LOCAL);
fdholder->flags |= setflags;
}
/**
* Make a new fdholder corresponding to the fd
*/
PUBLIC struct fdholder *
r_io_record_fd(struct ndnr_handle *h, int fd,
void *who, socklen_t wholen,
int setflags)
{
int res;
struct fdholder *fdholder = NULL;
res = fcntl(fd, F_SETFL, O_NONBLOCK);
if (res == -1)
ndnr_msg(h, "fcntl: %s", strerror(errno));
fdholder = calloc(1, sizeof(*fdholder));
if (fdholder == NULL)
return(fdholder);
fdholder->name = ndn_charbuf_create();
if (fdholder->name == NULL)
abort();
if (who != NULL)
ndn_charbuf_append(fdholder->name, who, wholen);
fdholder->filedesc = fd;
init_face_flags(h, fdholder, setflags);
res = r_io_enroll_face(h, fdholder);
if (res == -1) {
ndn_charbuf_destroy(&fdholder->name);
free(fdholder);
fdholder = NULL;
}
return(fdholder);
}
/**
* Accept an incoming DGRAM_STREAM connection, creating a new fdholder.
* @returns fd of new socket, or -1 for an error.
*/
PUBLIC int
r_io_accept_connection(struct ndnr_handle *h, int listener_fd)
{
struct sockaddr_storage who;
socklen_t wholen = sizeof(who);
int fd;
struct fdholder *fdholder;
fd = accept(listener_fd, (struct sockaddr *)&who, &wholen);
if (fd == -1) {
ndnr_msg(h, "accept: %s", strerror(errno));
return(-1);
}
fdholder = r_io_record_fd(h, fd,
(struct sockaddr *)&who, wholen,
NDNR_FACE_UNDECIDED);
if (fdholder == NULL)
close_fd(&fd);
else if (NDNSHOULDLOG(h, io, NDNL_INFO))
ndnr_msg(h, "accepted client fd=%d id=%u", fd, fdholder->filedesc);
return(fd);
}
PUBLIC int
r_io_open_repo_data_file(struct ndnr_handle *h, const char *name, int output)
{
struct ndn_charbuf *temp = NULL;
int fd = -1;
struct fdholder *fdholder = NULL;
temp = ndn_charbuf_create();
ndn_charbuf_putf(temp, "%s/%s", h->directory, name);
fd = open(ndn_charbuf_as_string(temp), output ? (O_CREAT | O_WRONLY | O_APPEND) : O_RDONLY, 0666);
if (fd == -1) {
if (NDNSHOULDLOG(h, sdf, NDNL_FINE))
ndnr_msg(h, "open(%s): %s", ndn_charbuf_as_string(temp), strerror(errno));
ndn_charbuf_destroy(&temp);
return(-1);
}
fdholder = r_io_record_fd(h, fd,
temp->buf, temp->length,
NDNR_FACE_REPODATA | (output ? NDNR_FACE_NORECV : NDNR_FACE_NOSEND));
if (fdholder == NULL)
close_fd(&fd);
else {
if (!output) {
/* Use a larger buffer for indexing an existing repo file */
if (fdholder->inbuf == NULL) {
fdholder->inbuf = ndn_charbuf_create();
fdholder->bufoffset = 0;
}
if (fdholder->inbuf != NULL)
ndn_charbuf_reserve(fdholder->inbuf, 256 * 1024);
}
if (NDNSHOULDLOG(h, sdf, NDNL_INFO))
ndnr_msg(h, "opened fd=%d file=%s", fd, ndn_charbuf_as_string(temp));
}
ndn_charbuf_destroy(&temp);
return(fd);
}
PUBLIC int
r_io_repo_data_file_fd(struct ndnr_handle *h, unsigned repofile, int output)
{
if (repofile != 1)
return(-1);
if (output)
return(-1);
if (h->repofile1_fd > 0)
return(h->repofile1_fd);
h->repofile1_fd = r_io_open_repo_data_file(h, "repoFile1", 0);
return(h->repofile1_fd);
}
PUBLIC void
r_io_shutdown_client_fd(struct ndnr_handle *h, int fd)
{
struct fdholder *fdholder = NULL;
enum cq_delay_class c;
int m;
int res = 0; res = res;
fdholder = r_io_fdholder_from_fd(h, fd);
if (fdholder == NULL) {
ndnr_msg(h, "no fd holder for fd %d", fd);
return;
}
if (fdholder == h->face0)
(res = 0, h->face0 = NULL);
else if ((fdholder->flags & NDNR_FACE_NDND))
res = ndn_disconnect(h->direct_client);
else
res = close(fd);
if (NDNSHOULDLOG(h, sdfdf, NDNL_INFO))
ndnr_msg(h, "shutdown client fd=%d", fd);
ndn_charbuf_destroy(&fdholder->inbuf);
ndn_charbuf_destroy(&fdholder->outbuf);
for (c = 0; c < NDN_CQ_N; c++)
r_sendq_content_queue_destroy(h, &(fdholder->q[c]));
for (m = 0; m < NDNR_FACE_METER_N; m++)
ndnr_meter_destroy(&fdholder->meter[m]);
if (h->fdholder_by_fd[fd] != fdholder) abort();
h->fdholder_by_fd[fd] = NULL;
ndn_charbuf_destroy(&fdholder->name);
free(fdholder);
if (h->active_in_fd == fd)
h->active_in_fd = -1;
if (h->active_out_fd == fd)
h->active_out_fd = -1;
if (h->repofile1_fd == fd)
h->repofile1_fd = -1;
// r_fwd_reap_needed(h, 250000);
}
/**
* Destroys the fdholder identified by filedesc.
* @returns 0 for success, -1 for failure.
*/
PUBLIC int
r_io_destroy_face(struct ndnr_handle *h, unsigned filedesc)
{
r_io_shutdown_client_fd(h, filedesc);
return(0);
}
/**
* Called when a fdholder is first created, and (perhaps) a second time in the case
* that a fdholder transitions from the undecided state.
*/
PUBLIC void
r_io_register_new_face(struct ndnr_handle *h, struct fdholder *fdholder)
{
if (fdholder->filedesc != 0 && (fdholder->flags & (NDNR_FACE_UNDECIDED | NDNR_FACE_PASSIVE)) == 0) {
ndnr_face_status_change(h, fdholder->filedesc);
}
}
/**
* Handle errors after send() or sendto().
* @returns -1 if error has been dealt with, or 0 to defer sending.
*/
static int
handle_send_error(struct ndnr_handle *h, int errnum, struct fdholder *fdholder,
const void *data, size_t size)
{
int res = -1;
if (errnum == EAGAIN) {
res = 0;
}
else if (errnum == EPIPE) {
fdholder->flags |= NDNR_FACE_NOSEND;
fdholder->outbufindex = 0;
ndn_charbuf_destroy(&fdholder->outbuf);
}
else {
ndnr_msg(h, "send/write to fd %u failed: %s (errno = %d)",
fdholder->filedesc, strerror(errnum), errnum);
if (errnum == EISCONN || errnum == EFBIG || errnum == ENOSPC)
res = 0;
}
return(res);
}
static int
sending_fd(struct ndnr_handle *h, struct fdholder *fdholder)
{
return(fdholder->filedesc);
}
/**
* Send data to the fdholder.
*
* No direct error result is provided; the fdholder state is updated as needed.
*/
PUBLIC void
r_io_send(struct ndnr_handle *h,
struct fdholder *fdholder,
const void *data, size_t size,
off_t *offsetp)
{
ssize_t res;
off_t offset = -1;
if (offsetp != NULL)
*offsetp = (off_t)-1;
if ((fdholder->flags & NDNR_FACE_NOSEND) != 0)
return;
if (fdholder->outbuf != NULL) {
ndn_charbuf_append(fdholder->outbuf, data, size);
return;
}
if (fdholder == h->face0) {
ndnr_meter_bump(h, fdholder->meter[FM_BYTO], size);
ndn_dispatch_message(h->internal_client, (void *)data, size);
r_dispatch_process_internal_client_buffer(h);
return;
}
if ((fdholder->flags & NDNR_FACE_NDND) != 0) {
/* Writes here need to go via the direct client's handle. */
ndnr_meter_bump(h, fdholder->meter[FM_BYTO], size);
res = ndn_put(h->direct_client, data, size);
if (res < 0 && NDNSHOULDLOG(h, r_io_send, NDNL_WARNING))
ndnr_msg(h, "ndn_put failed");
if (res == 1 && NDNSHOULDLOG(h, r_io_send, NDNL_FINEST))
ndnr_msg(h, "ndn_put deferred output for later send");
return;
}
if ((fdholder->flags & NDNR_FACE_REPODATA) != 0) {
offset = lseek(fdholder->filedesc, 0, SEEK_END);
if (offset == (off_t)-1) {
ndnr_msg(h, "lseek(%d): %s", fdholder->filedesc, strerror(errno));
return;
}
if (offsetp != NULL)
*offsetp = offset;
if (fdholder->filedesc == h->active_out_fd) {
if (offset != h->stable && h->stable != 0)
ndnr_msg(h, "expected file size %ju, found %ju",
(uintmax_t)h->stable,
(uintmax_t)offset);
h->stable = offset + size;
}
}
if ((fdholder->flags & NDNR_FACE_DGRAM) == 0)
res = write(fdholder->filedesc, data, size);
else
res = sendto(sending_fd(h, fdholder), data, size, 0,
(struct sockaddr *)fdholder->name->buf,
fdholder->name->length);
if (res > 0)
ndnr_meter_bump(h, fdholder->meter[FM_BYTO], res);
if (res == size)
return;
if (res == -1) {
res = handle_send_error(h, errno, fdholder, data, size);
if (res == -1)
return;
}
if ((fdholder->flags & NDNR_FACE_DGRAM) != 0) {
ndnr_msg(h, "sendto short");
return;
}
if ((fdholder->flags & NDNR_FACE_REPODATA) != 0) {
// need to truncate back to last known good object then exit.
ndnr_msg(h, "Unrecoverable write error writing to repository. Content NOT stored.");
if (ftruncate(fdholder->filedesc, offset) < 0) {
ndnr_msg(h, "ftruncate: %s", strerror(errno));
}
h->running = 0;
return;
}
fdholder->outbufindex = 0;
fdholder->outbuf = ndn_charbuf_create();
if (fdholder->outbuf == NULL) {
ndnr_msg(h, "do_write: %s", strerror(errno));
return;
}
ndn_charbuf_append(fdholder->outbuf,
((const unsigned char *)data) + res, size - res);
}
/**
* Set up the array of fd descriptors for the poll(2) call.
*
*/
PUBLIC void
r_io_prepare_poll_fds(struct ndnr_handle *h)
{
int i, j, nfds;
for (i = 1, nfds = 0; i < h->face_limit; i++)
if (r_io_fdholder_from_fd(h, i) != NULL)
nfds++;
if (nfds != h->nfds) {
h->nfds = nfds;
h->fds = realloc(h->fds, h->nfds * sizeof(h->fds[0]));
memset(h->fds, 0, h->nfds * sizeof(h->fds[0]));
}
for (i = 1, j = 0; i < h->face_limit; i++) {
struct fdholder *fdholder = r_io_fdholder_from_fd(h, i);
if (fdholder != NULL) {
h->fds[j].fd = fdholder->filedesc;
h->fds[j].events = 0;
if ((fdholder->flags & (NDNR_FACE_NORECV|NDNR_FACE_REPODATA)) == 0)
h->fds[j].events |= POLLIN;
if (fdholder->filedesc == h->active_in_fd)
h->fds[j].events |= POLLIN;
if (((fdholder->flags & NDNR_FACE_REPODATA) == 0) &&
((fdholder->outbuf != NULL || (fdholder->flags & NDNR_FACE_CLOSING) != 0)))
h->fds[j].events |= POLLOUT;
if ((fdholder->flags & NDNR_FACE_NDND) != 0) {
if (ndn_output_is_pending(h->direct_client)) {
if (NDNSHOULDLOG(h, xxx, NDNL_FINEST))
ndnr_msg(h, "including direct client in poll set");
h->fds[j].events |= POLLOUT;
}
}
j++;
}
}
}
/**
* Shutdown all open fds.
*/
PUBLIC void
r_io_shutdown_all(struct ndnr_handle *h)
{
int i;
for (i = 1; i < h->face_limit; i++) {
if (r_io_fdholder_from_fd(h, i) != NULL)
r_io_shutdown_client_fd(h, i);
}
ndnr_internal_client_stop(h);
r_io_shutdown_client_fd(h, 0);
}
|
yoursunny/carepo
|
segment/rabin.c
|
<reponame>yoursunny/carepo
#include "rabin.h"
#include "rabin/rabin_polynomial.h"
#include <ndn/digest.h>
struct segment_list* segment_rabin(FILE* file) {
rabin_sliding_window_size = 31;
rabin_polynomial_max_block_size = 8192;
rabin_polynomial_min_block_size = 1024;
rabin_polynomial_average_block_size = 4096;
if (0 != fseek(file, 0, SEEK_SET)) return NULL;
struct rabin_polynomial* head = get_file_rabin_polys(file);
if (head == NULL) return NULL;
if (0 != fseek(file, 0, SEEK_END)) return NULL;
long int length = ftell(file);
if (length == -1L) return NULL;
if (0 != fseek(file, 0, SEEK_SET)) return NULL;
uint32_t count = 0;
for (struct rabin_polynomial* poly = head; poly != NULL; poly = poly->next_polynomial) {
++count;
length -= poly->length;
}
if (length != 0) return NULL;
struct segment_list* sl = segment_list_ctor(count);
int i = 0; uint64_t start = 0;
uint8_t buffer[65536];
struct ndn_digest* digest = ndn_digest_create(NDN_DIGEST_SHA256);
for (struct rabin_polynomial* poly = head; poly != NULL; poly = poly->next_polynomial) {
struct segment* seg = sl->list + i;
seg->start = start;
seg->length = poly->length;
ndn_digest_init(digest);
size_t read_size = 0;
while (read_size < poly->length) {
size_t read_want = poly->length - read_size;
if (read_want > sizeof(buffer)) read_want = sizeof(buffer);
size_t read_res = fread(buffer, 1, read_want, file);
ndn_digest_update(digest, buffer, read_res);
read_size += read_res;
}
ndn_digest_final(digest, seg->hash, sizeof(seg->hash));
++i;
start += poly->length;
}
ndn_digest_destroy(&digest);
return sl;
}
|
yoursunny/carepo
|
repo/ndnr_dispatch.h
|
<gh_stars>0
/**
* @file ndnr_dispatch.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_DISPATCH_DEFINED
#define NDNR_DISPATCH_DEFINED
#include "ndnr_private.h"
void r_dispatch_run(struct ndnr_handle *h);
void r_dispatch_process_internal_client_buffer(struct ndnr_handle *h);
struct content_entry *process_incoming_content(struct ndnr_handle *h, struct fdholder *fdholder,
unsigned char *msg, size_t size, off_t *offsetp);
void r_dispatch_process_input(struct ndnr_handle *h, int fd);
#endif
|
yoursunny/carepo
|
repo/ndnr_internal_client.h
|
/**
* @file ndnr_internal_client.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_INTERNAL_DEFINED
#define NDNR_INTERNAL_DEFINED
#include "ndnr_private.h"
void ndnr_internal_client_stop(struct ndnr_handle *ndnr);
int ndnr_internal_client_start(struct ndnr_handle *ndnr);
void ndnr_face_status_change(struct ndnr_handle *ndnr,unsigned filedesc);
int ndnr_init_repo_keystore(struct ndnr_handle *ndnr, struct ndn *ndn);
void ndnr_direct_client_stop(struct ndnr_handle *ndnr);
int ndnr_direct_client_start(struct ndnr_handle *ndnr);
/**
* Local interpretation of selfp->intdata
*/
#define MORECOMPS_MASK 0x007F
#define MUST_VERIFY 0x0080
#define MUST_VERIFY1 (MUST_VERIFY + 1)
#define OPER_MASK 0xFF00
#define OP_PING 0x0000
#define OP_NEWFACE 0x0200
#define OP_DESTROYFACE 0x0300
#define OP_PREFIXREG 0x0400
#define OP_SELFREG 0x0500
#define OP_UNREG 0x0600
#define OP_NOTICE 0x0700
#define OP_SERVICE 0x0800
void ndnr_uri_listen(struct ndnr_handle *ndnr, struct ndn *ndn, const char *uri,
ndn_handler p, intptr_t intdata);
enum ndn_upcall_res ndnr_answer_req(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info);
#endif
|
yoursunny/carepo
|
rabin/rabin_polynomial_constants.h
|
<reponame>yoursunny/carepo
/*
* rabin_polynomial_constants.h
*
* Created by <NAME> on 09-May-2011.
*
* Copyright (c) 2011 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the project's author nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
//List of constants, mostly constraints and defaults for various parameters
//to the Rabin Fingerprinting algorithm
#ifndef RAB_MAX_BLOCK_SIZE
#define RAB_MAX_BLOCK_SIZE 4096
#endif
#ifndef RAB_MIN_BLOCK_SIZE
#define RAB_MIN_BLOCK_SIZE 32
#endif
#ifndef RAB_POLYNOMIAL_REM
#define RAB_POLYNOMIAL_REM 3
#endif
#ifndef RAB_POLYNOMIAL_AVG_BLOCK_SIZE
#define RAB_POLYNOMIAL_AVG_BLOCK_SIZE 64
#endif
#ifndef RAB_POLYNOMIAL_WIN_SIZE
#define RAB_POLYNOMIAL_WIN_SIZE 31
#endif
#ifndef RAB_POLYNOMIAL_MIN_WIN_SIZE
#define RAB_POLYNOMIAL_MIN_WIN_SIZE 17
#endif
#ifndef RAB_POLYNOMIAL_MAX_WIN_SIZE
#define RAB_POLYNOMIAL_MAX_WIN_SIZE 63
#endif
//# of bytes to read at a time when reading through files
#ifndef RAB_FILE_READ_BUF_SIZE
#define RAB_FILE_READ_BUF_SIZE 1048576
#endif
|
yoursunny/carepo
|
repo/ndnr_link.h
|
/**
* @file ndnr_link.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_LINK_DEFINED
#define NDNR_LINK_DEFINED
#include "ndnr_private.h"
void r_link_do_deferred_write(struct ndnr_handle *h,int fd);
void r_link_stuff_and_send(struct ndnr_handle *h,
struct fdholder *fdholder,
const unsigned char *data1,
size_t size1,
const unsigned char *data2,
size_t size2,
off_t *offsetp);
void r_link_send_content(struct ndnr_handle *h,
struct fdholder *fdholder,
struct content_entry *content);
#endif
|
yoursunny/carepo
|
segment/fetcher.h
|
<reponame>yoursunny/carepo
#ifndef CAREPO_SEGMENT_WRITER_H_
#define CAREPO_SEGMENT_WRITER_H_
#include "metadata.h"
typedef uint8_t file_fetcher_req_status;
#define FILE_FETCHER_REQ_HWAIT 0
#define FILE_FETCHER_REQ_HSENT 1
#define FILE_FETCHER_REQ_NWAIT 2
#define FILE_FETCHER_REQ_NSENT 3
#define FILE_FETCHER_REQ_OK 4
#define FILE_FETCHER_REQ_FAIL 5
struct file_fetcher_req {
file_fetcher_req_status status;
const uint8_t* hash;
struct ndn_indexbuf* i;
int reexpress_limit;
};
struct file_fetcher {
struct ndn* h;
FILE* file;
struct ndn_charbuf* name;// Name with version
struct ndn_indexbuf* name_comps;
struct segment_list* sl;
struct file_fetcher_req* reqs;
int total_reqs;
int ok_reqs;
int fail_reqs;
int outstanding_hashreqs;
int outstanding_namereqs;
int complete_hashreqs;
int complete_namereqs;
};
#define FILE_FETCHER_HASHREQ_CONCURRENT 30
#define FILE_FETCHER_HASHREQ_TIMEOUT 500
#define FILE_FETCHER_NAMEREQ_CONCURRENT 10
#define FILE_FETCHER_NAMEREQ_REEXPRESS 2
struct file_fetcher* file_fetcher_ctor(struct segment_list* sl, FILE* file, struct ndn* h, struct ndn_charbuf* name);
void file_fetcher_dtor(struct file_fetcher** selfp);
bool file_fetcher_run(struct file_fetcher* self);
// private begin
void file_fetcher_build_reqs(struct file_fetcher* self);
void file_fetcher_next_reqs(struct file_fetcher* self);
struct ndn_charbuf* file_fetcher_hashreq_templ(void);
void file_fetcher_send_hashreq(struct file_fetcher* self, int j);
void file_fetcher_send_namereq(struct file_fetcher* self, int j);
enum ndn_upcall_res file_fetcher_incoming_co_hashreq(struct ndn_closure* closure, enum ndn_upcall_kind kind, struct ndn_upcall_info* info);
enum ndn_upcall_res file_fetcher_incoming_co_namereq(struct ndn_closure* closure, enum ndn_upcall_kind kind, struct ndn_upcall_info* info);
void file_fetcher_save_co(struct file_fetcher* self, struct file_fetcher_req* req, struct ndn_upcall_info* info);
// private end
#endif//CAREPO_SEGMENT_WRITER_H_
|
yoursunny/carepo
|
repo/ndnr_net.c
|
/**
* @file ndnr_net.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011-2012 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include "ndnr_private.h"
#include "ndnr_net.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
PUBLIC char *
r_net_get_local_sockname(void)
{
struct sockaddr_un sa;
ndn_setup_sockaddr_un(NULL, &sa);
return(strdup(sa.sun_path));
}
PUBLIC void
r_net_setsockopt_v6only(struct ndnr_handle *h, int fd)
{
int yes = 1;
int res = 0;
#ifdef IPV6_V6ONLY
res = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes));
#endif
if (res == -1)
ndnr_msg(h, "warning - could not set IPV6_V6ONLY on fd %d: %s",
fd, strerror(errno));
}
static const char *
af_name(int family)
{
switch (family) {
case AF_INET:
return("ipv4");
case AF_INET6:
return("ipv6");
default:
return("");
}
}
PUBLIC int
r_net_listen_on_address(struct ndnr_handle *h, const char *addr)
{
int fd;
int res;
struct addrinfo hints = {0};
struct addrinfo *addrinfo = NULL;
struct addrinfo *a;
int ok = 0;
if (NDNSHOULDLOG(h, listen_on_addr, NDNL_FINE))
ndnr_msg(h, "listen_on %s", addr);
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
res = getaddrinfo(addr, h->portstr, &hints, &addrinfo);
if (res == 0) {
for (a = addrinfo; a != NULL; a = a->ai_next) {
fd = socket(a->ai_family, SOCK_STREAM, 0);
if (fd != -1) {
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if (a->ai_family == AF_INET6)
r_net_setsockopt_v6only(h, fd);
res = bind(fd, a->ai_addr, a->ai_addrlen);
if (res != 0) {
close(fd);
continue;
}
res = listen(fd, 30);
if (res == -1) {
close(fd);
continue;
}
r_io_record_fd(h, fd,
a->ai_addr, a->ai_addrlen,
NDNR_FACE_PASSIVE);
if (NDNSHOULDLOG(h, listen_on, NDNL_INFO))
ndnr_msg(h, "accepting %s status connections on fd %d",
af_name(a->ai_family), fd);
ok++;
}
}
freeaddrinfo(addrinfo);
}
return(ok > 0 ? 0 : -1);
}
PUBLIC int
r_net_listen_on(struct ndnr_handle *h, const char *addrs)
{
unsigned char ch;
unsigned char dlm;
int res = 0;
int i;
struct ndn_charbuf *addr = NULL;
if (h->portstr == NULL || h->portstr[0] == 0)
return(-1);
if (addrs == NULL || !*addrs)
addrs="127.0.0.1,[::1]";
else if (0 == strcmp(addrs, "*"))
addrs="0.0.0.0,[::]";
addr = ndn_charbuf_create();
for (i = 0, ch = addrs[i]; addrs[i] != 0;) {
addr->length = 0;
dlm = 0;
if (ch == '[') {
dlm = ']';
ch = addrs[++i];
}
for (; ch > ' ' && ch != ',' && ch != ';' && ch != dlm; ch = addrs[++i])
ndn_charbuf_append_value(addr, ch, 1);
if (ch && ch == dlm)
ch = addrs[++i];
if (addr->length > 0) {
res |= r_net_listen_on_address(h, ndn_charbuf_as_string(addr));
}
while ((0 < ch && ch <= ' ') || ch == ',' || ch == ';')
ch = addrs[++i];
}
ndn_charbuf_destroy(&addr);
return(res);
}
|
yoursunny/carepo
|
segment/writer.h
|
<gh_stars>0
#ifndef CAREPO_SEGMENT_WRITER_H_
#define CAREPO_SEGMENT_WRITER_H_
#include "metadata.h"
struct file_writer {
struct ndn* h;
struct ndn_closure* closure;
FILE* file;
struct ndn_charbuf* name;// Name with version
struct ndn_indexbuf* name_comps;
struct segment_list* sl;
bool sign_segments;// use strong signature on segments instead of just hash
bool* sent_segments;
int remaining_segments;
struct ndn_charbuf* metadata_name;// Name of metadata with version
struct ndn_charbuf* metadata;
int total_metadata_blocks;
bool* sent_metadata_blocks;
int remaining_metadata_blocks;
int recent_interests;
};
#define FILE_WRITER_METADATA_BLOCKSZ 4096
#define FILE_WRITER_STARTWRITE_TIMEOUT 4000 // file_writer_startwrite fails if startwrite is not responded in this duration
#define FILE_WRITER_RUN_TIMEOUT_INTERVAL 10000 // file_writer_run fails if no incoming Interest in this duration
struct file_writer* file_writer_ctor(struct segment_list* sl, FILE* file, struct ndn* h, struct ndn_charbuf* name, bool sign_segments);
void file_writer_dtor(struct file_writer** selfp);
bool file_writer_run(struct file_writer* self);
// private begin
bool file_writer_startwrite(struct file_writer* self);
enum ndn_upcall_res file_writer_incoming_interest(struct ndn_closure* closure, enum ndn_upcall_kind kind, struct ndn_upcall_info* info);
uintmax_t file_writer_extract_number(struct ndn_upcall_info* info);
bool file_writer_respond_segment(struct file_writer* self, struct ndn_upcall_info* info);
bool file_writer_segment_sign(struct file_writer* self, struct ndn_charbuf* reply, struct ndn_upcall_info* info, uint32_t seg_i, struct segment* seg);
bool file_writer_segment_hash(struct file_writer* self, struct ndn_charbuf* reply, struct ndn_upcall_info* info, uint32_t seg_i, struct segment* seg);
bool file_writer_segment_readfile(struct file_writer* self, struct ndn_charbuf* c, struct segment* seg);
bool file_writer_respond_metadata(struct file_writer* self, struct ndn_upcall_info* info);
// private end
#endif//CAREPO_SEGMENT_WRITER_H_
|
yoursunny/carepo
|
segment/metadata.c
|
#include "metadata.h"
void segment_list_to_metadata(const struct segment_list* self, struct ndn_charbuf* c) {
ndnb_element_begin(c, NDN_DTAG_Collection);
ndnb_append_tagged_binary_number(c, NDN_DTAG_Count, self->count);
for (uint32_t i = 0; i < self->count; ++i) {
const struct segment* seg = self->list + i;
ndnb_element_begin(c, NDN_DTAG_Entry);
ndnb_append_tagged_binary_number(c, NDN_DTAG_Length, seg->length);
ndnb_append_tagged_blob(c, NDN_DTAG_ContentHash, seg->hash, sizeof(seg->hash));
ndnb_element_end(c);//Entry
}
ndnb_element_end(c);//Collection
}
struct segment_list* segment_list_from_metadata(const uint8_t* buf, size_t sz) {
struct ndn_buf_decoder decoder; struct ndn_buf_decoder* d = ndn_buf_decoder_start(&decoder, buf, sz);
if (!ndn_buf_match_dtag(d, NDN_DTAG_Collection)) return NULL;
ndn_buf_advance(d);
uintmax_t count = ndn_parse_required_tagged_binary_number(d, NDN_DTAG_Count, 0, 8);
if (d->decoder.state < 0) return NULL;
struct segment_list* self = segment_list_ctor((uint32_t)count);
#define return_FAIL { segment_list_dtor(&self); return NULL; }
uint64_t start = 0;
for (uint32_t i = 0; i < self->count; ++i) {
struct segment* seg = self->list + i;
if (!ndn_buf_match_dtag(d, NDN_DTAG_Entry)) return_FAIL;
ndn_buf_advance(d);
seg->length = (uint16_t)ndn_parse_required_tagged_binary_number(d, NDN_DTAG_Length, 0, 2);
size_t offset_B_hash = d->decoder.token_index;
ndn_parse_required_tagged_BLOB(d, NDN_DTAG_ContentHash, sizeof(seg->hash), sizeof(seg->hash));
size_t offset_E_hash = d->decoder.token_index;
if (d->decoder.state < 0) return_FAIL;
seg->start = start;
start += seg->length;
const uint8_t* hash; size_t hash_sz;
ndn_ref_tagged_BLOB(NDN_DTAG_ContentHash, buf, offset_B_hash, offset_E_hash, &hash, &hash_sz);
assert(sizeof(seg->hash) == hash_sz);
memcpy(seg->hash, hash, sizeof(seg->hash));
ndn_buf_check_close(d);
}
ndn_buf_check_close(d);
if (d->decoder.state < 0) return_FAIL;
#undef return_FAIL
return self;
}
|
yoursunny/carepo
|
segment/rabin.h
|
#ifndef CAREPO_SEGMENT_RABIN_H_
#define CAREPO_SEGMENT_RABIN_H_
#include "segment.h"
// segment a file according to Rabin Fingerprint boundary
struct segment_list* segment_rabin(FILE* file);
#endif//CAREPO_SEGMENT_RABIN_H_
|
yoursunny/carepo
|
repo/hash_store.c
|
#include "hash_store.h"
#include <ndn/digest.h>
#include <sys/stat.h>
#include <errno.h>
#include "segment/segment.h"
#include "ndnr_store.h"
#include <fcntl.h>
#include <unistd.h>
struct content_entry {
ndnr_accession accession;
ndnr_cookie cookie;
int flags;
int size;
struct ndn_charbuf* flatname;
struct ndn_charbuf* cob;
};
struct hash_store* hash_store_ctor(struct ndnr_handle* h) {
struct hash_store* self = calloc(1, sizeof(*self));
self->h = h;
h->hashstore = self;
// open btree with disk IO
struct ndn_charbuf* path = ndn_charbuf_create();
ndn_charbuf_putf(path, "%s/hashstore", h->directory);
int res = mkdir(ndn_charbuf_as_string(path), 0700);
if (res != 0 && errno != EEXIST) { free(self); ndn_charbuf_destroy(&path); return NULL; }
self->btree = ndn_btree_create();
self->btree->io = ndn_btree_io_from_directory(ndn_charbuf_as_string(path), NULL);
if (self->btree->io == NULL) { free(self); ndn_charbuf_destroy(&path); ndn_btree_destroy(&self->btree); return NULL; }
ndn_charbuf_destroy(&path);
struct ndn_btree_node* node = ndn_btree_getnode(self->btree, 1, 0);
self->btree->nextnodeid = self->btree->io->maxnodeid + 1;
if (node->buf->length == 0) {
res = ndn_btree_init_node(node, 0, 'R', 0);
}
LOG("hash_store_ctor\n");
return self;
}
void hash_store_dtor(struct hash_store** selfp) {
struct hash_store* self = *selfp;
if (self == NULL) return;
// TODO stable mark
ndn_btree_destroy(&self->btree);
free(self);
*selfp = NULL;
LOG("hash_store_dtor\n");
}
bool hash_store_insert(struct hash_store* self, ndnr_accession accession, struct ndn_charbuf* co, struct ndn_parsed_ContentObject* pco) {
int res;
// retrieve payload
struct ndn_parsed_ContentObject pco2 = {0};
if (pco == NULL) {
res = ndn_parse_ContentObject(co->buf, co->length, pco = &pco2, NULL);
if (res != 0) return false;
}
const uint8_t* payload; size_t payloadsz;
ndn_content_get_value(co->buf, co->length, pco, &payload, &payloadsz);
// calculate hash
uint8_t hash[SEGMENT_HASHSZ];
struct ndn_digest* digest = ndn_digest_create(NDN_DIGEST_SHA256);
ndn_digest_init(digest);
ndn_digest_update(digest, payload, payloadsz);
ndn_digest_final(digest, hash, sizeof(hash));
ndn_digest_destroy(&digest);
LOG("hash_store_insert(%" PRIx64 ") ", (uint64_t)ndnr_accession_encode(self->h, accession));
LOG_hash(hash, SEGMENT_HASHSZ);
// find where to insert
struct ndn_btree_node* leaf = NULL;
res = ndn_btree_lookup(self->btree, hash, sizeof(hash), &leaf);
int i = NDN_BT_SRCH_INDEX(res);
if (NDN_BT_SRCH_FOUND(res)) {
LOG(" duplicate(%u,%d)\n", leaf->nodeid, i);
return true;// already have it
}
LOG(" insert(%u,%d)\n", leaf->nodeid, i);
// prepare payload
uint64_t accession_encoded = ndnr_accession_encode(self->h, accession);
// insert index entry
res = ndn_btree_prepare_for_update(self->btree, leaf);
if (res < 0) return false;
res = ndn_btree_insert_entry(leaf, i, hash, sizeof(hash), &accession_encoded, sizeof(accession_encoded));
if (res < 0) return false;
// btree maintenance
if (ndn_btree_oversize(self->btree, leaf)) {
res = ndn_btree_split(self->btree, leaf);
for (int limit = 100; res >= 0 && self->btree->nextsplit != 0; --limit) {
if (limit == 0) abort();
struct ndn_btree_node* node = ndn_btree_getnode(self->btree, self->btree->nextsplit, 0);
if (node == NULL) break;
res = ndn_btree_split(self->btree, node);
}
}
hash_store_clean(self);
return true;
}
// TODO deferred cleaning
void hash_store_clean(struct hash_store* self) {
struct hashtb_enumerator ee; struct hashtb_enumerator* e = ⅇ
hashtb_start(self->btree->resident, e);
int overquota = 0;
if (self->btree->nodepool >= 16) overquota = hashtb_n(self->btree->resident) - self->btree->nodepool;
for (struct ndn_btree_node* node = e->data; node != NULL; node = e->data) {
if (overquota > 0 && node->activity == 0 && node->iodata == NULL && node->clean == node->buf->length) {
--overquota;
hashtb_delete(e);
continue;
}
//node->activity /= 2;
node->activity = 0;
if (node->clean != node->buf->length || (node->iodata != NULL && node->activity == 0)) {
int res = ndn_btree_chknode(node);
if (res < 0) continue;
if (node->clean != node->buf->length) {
res = self->btree->io->btwrite(self->btree->io, node);
if (res < 0) continue;
node->clean = node->buf->length;
}
if (node->iodata != NULL && node->activity == 0) {
res = ndn_btree_close_node(self->btree, node);
}
}
hashtb_next(e);
}
hashtb_end(e);
}
ndnr_accession hash_store_find(struct hash_store* self, const uint8_t* hash) {
// find entry
struct ndn_btree_node* leaf = NULL;
int res = ndn_btree_lookup(self->btree, hash, SEGMENT_HASHSZ, &leaf);
if (!NDN_BT_SRCH_FOUND(res)) return NDNR_NULL_ACCESSION;// not have it
int i = NDN_BT_SRCH_INDEX(res);
// read entry
uint64_t accession_encoded;
uint64_t* accession_p = ndn_btree_node_getentry(sizeof(accession_encoded), leaf, i);
accession_encoded = *accession_p;
return ndnr_accession_decode(self->h, accession_encoded);
}
enum ndn_upcall_res hash_store_handle_proto_sha256(struct hash_store* self, struct ndn_upcall_info* info) {
int res;
// extract hash
const uint8_t* hash; size_t hashsz;
res = ndn_name_comp_get(info->interest_ndnb, info->interest_comps, 1, &hash, &hashsz);
if (res != 0 || hashsz != SEGMENT_HASHSZ) return NDN_UPCALL_RESULT_ERR;
LOG("hash_store_handle_proto_sha256("); LOG_hash(hash, hashsz); LOG(") ");
// find content
ndnr_accession accession = hash_store_find(self, hash);
if (accession == NDNR_NULL_ACCESSION) {
LOG("MISS\n");
return NDN_UPCALL_RESULT_OK;
}
struct content_entry* orig_content = r_store_content_from_accession(self->h, accession);
if (orig_content == NULL) { LOG("LOST\n"); return NDN_UPCALL_RESULT_OK; }
if (orig_content->cob == NULL && r_store_content_base(self->h, orig_content) == NULL) { LOG("LOST\n"); return NDN_UPCALL_RESULT_OK; }
LOG("HIT %" PRIx64 ", ", (uint64_t)ndnr_accession_encode(self->h, accession));
// extract payload
struct ndn_parsed_ContentObject orig_pco = {0};
res = ndn_parse_ContentObject(orig_content->cob->buf, orig_content->cob->length, &orig_pco, NULL);
if (res != 0) { LOG("cannot parse\n"); return NDN_UPCALL_RESULT_OK; }
const uint8_t* payload; size_t payloadsz;
res = ndn_content_get_value(orig_content->cob->buf, orig_content->cob->length, &orig_pco, &payload, &payloadsz);
if (res != 0) { LOG("cannot extract payload\n"); return NDN_UPCALL_RESULT_OK; }
// verify hash
if (!hash_store_verify_hash(self, payload, payloadsz, hash)) { LOG("hash mismatch\n"); return NDN_UPCALL_RESULT_OK; }
// build reply
struct ndn_charbuf* reply = ndn_charbuf_create();
hash_store_build_reply(self, reply, hash, payload, payloadsz);
// send reply TODO use queues
res = ndn_put(info->h, reply->buf, reply->length);
if (res != 0) { LOG("cannot send\n"); ndn_charbuf_destroy(&reply); return NDN_UPCALL_RESULT_OK; }
ndn_charbuf_destroy(&reply);
LOG("OK\n");
return NDN_UPCALL_RESULT_INTEREST_CONSUMED;
}
bool hash_store_verify_hash(struct hash_store* self, const uint8_t* payload, size_t payloadsz, const uint8_t* expect_hash) {
uint8_t actual_hash[SEGMENT_HASHSZ];
struct ndn_digest* digest = ndn_digest_create(NDN_DIGEST_SHA256);
ndn_digest_init(digest);
ndn_digest_update(digest, payload, payloadsz);
ndn_digest_final(digest, actual_hash, sizeof(actual_hash));
ndn_digest_destroy(&digest);
return 0 == memcmp(expect_hash, actual_hash, sizeof(actual_hash));
}
bool hash_store_build_reply(struct hash_store* self, struct ndn_charbuf* reply, const uint8_t* hash, const uint8_t* payload, size_t payloadsz) {
ndnb_element_begin(reply, NDN_DTAG_ContentObject);
ndnb_element_begin(reply, NDN_DTAG_Signature);
ndnb_tagged_putf(reply, NDN_DTAG_DigestAlgorithm, "SHA256");
ndnb_append_tagged_blob(reply, NDN_DTAG_SignatureBits, hash, SEGMENT_HASHSZ);
ndnb_element_end(reply);//Signature
ndnb_element_begin(reply, NDN_DTAG_Name);
ndnb_append_tagged_blob(reply, NDN_DTAG_Component, REPO_SHA256, sizeof(REPO_SHA256)-1);
ndnb_append_tagged_blob(reply, NDN_DTAG_Component, hash, SEGMENT_HASHSZ);
ndnb_element_end(reply);//Name
ndnb_element_begin(reply, NDN_DTAG_SignedInfo);
ndnb_append_tagged_blob(reply, NDN_DTAG_PublisherPublicKeyDigest, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 32);
ndnb_element_begin(reply, NDN_DTAG_Timestamp);
ndnb_append_now_blob(reply, NDN_MARKER_NONE);
ndnb_element_end(reply);//Timestamp
ndnb_element_end(reply);//SignedInfo
ndnb_append_tagged_blob(reply, NDN_DTAG_Content, payload, payloadsz);
ndnb_element_end(reply);//ContentObject
return true;
}
|
yoursunny/carepo
|
repo/ndnr_proto.h
|
/**
* @file ndnr_proto.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_PROTO_DEFINED
#define NDNR_PROTO_DEFINED
#include "ndnr_private.h"
#define REPO_SW "\xC1.R.sw"
#define REPO_SWC "\xC1.R.sw-c"
#define REPO_AF "\xC1.R.af"
#define NAME_BE "\xC1.E.be"
struct ndnr_parsed_policy {
unsigned char version[7];
int policy_version_offset;
int local_name_offset;
int global_prefix_offset;
struct ndn_indexbuf *namespaces;
struct ndn_charbuf *store;
};
#define NDNR_PIPELINE 4
struct ndnr_expect_content {
struct ndnr_handle *ndnr;
int tries; /** counter so we can give up eventually */
int done;
ndnr_cookie keyfetch;
intmax_t outstanding[NDNR_PIPELINE];
intmax_t final;
ndn_handler expect_complete;
};
void r_proto_init(struct ndnr_handle *ndnr);
void r_proto_uri_listen(struct ndnr_handle *ndnr, struct ndn *ndn, const char *uri,
ndn_handler p, intptr_t intdata);
int r_proto_append_repo_info(struct ndnr_handle *ndnr,
struct ndn_charbuf *rinfo,
struct ndn_charbuf *names,
const char *info);
int r_proto_policy_append_basic(struct ndnr_handle *ndnr,
struct ndn_charbuf *policy,
const char *version, const char *local_name,
const char *global_prefix);
int r_proto_policy_append_namespace(struct ndnr_handle *ndnr,
struct ndn_charbuf *policy,
const char *namespace);
enum ndn_upcall_res r_proto_expect_content(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info);
int
r_proto_parse_policy(struct ndnr_handle *ndnr, const unsigned char *buf, size_t length,
struct ndnr_parsed_policy *pp);
void r_proto_activate_policy(struct ndnr_handle *ndnr, struct ndnr_parsed_policy *pp);
void r_proto_deactivate_policy(struct ndnr_handle *ndnr, struct ndnr_parsed_policy *pp);
int r_proto_initiate_key_fetch(struct ndnr_handle *ndnr,
const unsigned char *msg,
struct ndn_parsed_ContentObject *pco,
int use_link,
ndnr_cookie a);
void r_proto_finalize_enum_state(struct hashtb_enumerator *e);
#endif
|
yoursunny/carepo
|
repo/ndnr_util.h
|
<gh_stars>0
/**
* @file ndnr_util.h
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef NDNR_UTIL_DEFINED
#define NDNR_UTIL_DEFINED
#include "ndnr_private.h"
void r_util_gettime(const struct ndn_gettime *self,struct ndn_timeval *result);
int r_util_timecmp(long secA, unsigned usecA, long secB, unsigned usecB);
void r_util_reseed(struct ndnr_handle *h);
void r_util_indexbuf_release(struct ndnr_handle *h,struct ndn_indexbuf *c);
struct ndn_indexbuf *r_util_indexbuf_obtain(struct ndnr_handle *h);
void r_util_charbuf_release(struct ndnr_handle *h,struct ndn_charbuf *c);
struct ndn_charbuf *r_util_charbuf_obtain(struct ndnr_handle *h);
intmax_t r_util_segment_from_component(const unsigned char *ndnb, size_t start, size_t stop);
int r_util_name_comp_compare(const unsigned char *data, const struct ndn_indexbuf *indexbuf, unsigned int i, const void *val, size_t length);
#endif
|
yoursunny/carepo
|
repo/ndnr_internal_client.c
|
<filename>repo/ndnr_internal_client.c
/**
* @file ndnr_internal_client.c
*
* Part of ndnr - NDNx Repository Daemon.
*
*/
/*
* Portions Copyright (C) 2013 Regents of the University of California.
*
* Based on the CCNx C Library by PARC.
* Copyright (C) 2011-2013 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <ndn/ndn.h>
#include <ndn/charbuf.h>
#include <ndn/ndn_private.h>
#include <ndn/schedule.h>
#include <ndn/sockaddrutil.h>
#include <ndn/uri.h>
#include <ndn/keystore.h>
#include "ndnr_private.h"
#include "ndnr_internal_client.h"
#include "ndnr_forwarding.h"
#include "ndnr_io.h"
#include "ndnr_msg.h"
#include "ndnr_proto.h"
#include "ndnr_util.h"
static struct ndn_charbuf *
ndnr_init_service_ndnb(struct ndnr_handle *ndnr, struct ndn *h, const char *baseuri, int freshness)
{
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
struct ndn_charbuf *name = ndn_charbuf_create();
struct ndn_charbuf *pubid = ndn_charbuf_create();
struct ndn_charbuf *pubkey = ndn_charbuf_create();
struct ndn_charbuf *keyid = ndn_charbuf_create();
struct ndn_charbuf *cob = ndn_charbuf_create();
int res;
res = ndn_get_public_key(h, NULL, pubid, pubkey);
if (res < 0) abort();
ndn_name_from_uri(name, baseuri);
ndn_charbuf_append_value(keyid, NDN_MARKER_CONTROL, 1);
ndn_charbuf_append_string(keyid, ".M.K");
ndn_charbuf_append_value(keyid, 0, 1);
ndn_charbuf_append_charbuf(keyid, pubid);
ndn_name_append(name, keyid->buf, keyid->length);
ndn_create_version(h, name, 0, ndnr->starttime, ndnr->starttime_usec * 1000);
sp.template_ndnb = ndn_charbuf_create();
ndn_charbuf_append_tt(sp.template_ndnb, NDN_DTAG_SignedInfo, NDN_DTAG);
ndn_charbuf_append_tt(sp.template_ndnb, NDN_DTAG_KeyLocator, NDN_DTAG);
ndn_charbuf_append_tt(sp.template_ndnb, NDN_DTAG_KeyName, NDN_DTAG);
ndn_charbuf_append_charbuf(sp.template_ndnb, name);
ndn_charbuf_append_closer(sp.template_ndnb);
// ndn_charbuf_append_tt(sp.template_ndnb, NDN_DTAG_PublisherPublicKeyDigest,
// NDN_DTAG);
// ndn_charbuf_append_charbuf(sp.template_ndnb, pubid);
// ndn_charbuf_append_closer(sp.template_ndnb);
ndn_charbuf_append_closer(sp.template_ndnb);
ndn_charbuf_append_closer(sp.template_ndnb);
sp.sp_flags |= NDN_SP_TEMPL_KEY_LOCATOR;
ndn_name_from_uri(name, "%00");
sp.sp_flags |= NDN_SP_FINAL_BLOCK;
sp.type = NDN_CONTENT_KEY;
sp.freshness = freshness;
res = ndn_sign_content(h, cob, name, &sp, pubkey->buf, pubkey->length);
if (res != 0) abort();
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&pubid);
ndn_charbuf_destroy(&pubkey);
ndn_charbuf_destroy(&keyid);
ndn_charbuf_destroy(&sp.template_ndnb);
return(cob);
}
/**
* Common interest handler
*/
PUBLIC enum ndn_upcall_res
ndnr_answer_req(struct ndn_closure *selfp,
enum ndn_upcall_kind kind,
struct ndn_upcall_info *info)
{
struct ndn_charbuf *msg = NULL;
struct ndn_charbuf *name = NULL;
struct ndn_charbuf *keylocator = NULL;
struct ndn_charbuf *signed_info = NULL;
struct ndn_charbuf *reply_body = NULL;
struct ndnr_handle *ndnr = NULL;
int res = 0;
int morecomps = 0;
const unsigned char *final_comp = NULL;
size_t final_size = 0;
switch (kind) {
case NDN_UPCALL_FINAL:
free(selfp);
return(NDN_UPCALL_RESULT_OK);
case NDN_UPCALL_INTEREST:
break;
case NDN_UPCALL_CONSUMED_INTEREST:
return(NDN_UPCALL_RESULT_OK);
default:
return(NDN_UPCALL_RESULT_ERR);
}
ndnr = (struct ndnr_handle *)selfp->data;
if (NDNSHOULDLOG(ndnr, LM_128, NDNL_FINE))
ndnr_debug_ndnb(ndnr, __LINE__, "ndnr_answer_req", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
morecomps = selfp->intdata & MORECOMPS_MASK;
if ((info->pi->answerfrom & NDN_AOK_NEW) == 0 &&
selfp->intdata != OP_SERVICE)
return(NDN_UPCALL_RESULT_OK);
if (info->matched_comps >= info->interest_comps->n)
goto Bail;
if ((selfp->intdata & OPER_MASK) != OP_SERVICE &&
info->pi->prefix_comps != info->matched_comps + morecomps)
goto Bail;
if (morecomps == 1) {
res = ndn_name_comp_get(info->interest_ndnb, info->interest_comps,
info->matched_comps,
&final_comp, &final_size);
if (res < 0)
goto Bail;
}
if ((selfp->intdata & MUST_VERIFY) != 0) {
struct ndn_parsed_ContentObject pco = {0};
// XXX - probably should check for message origin BEFORE verify
res = ndn_parse_ContentObject(final_comp, final_size, &pco, NULL);
if (res < 0) {
ndnr_debug_ndnb(ndnr, __LINE__, "co_parse_failed", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
goto Bail;
}
res = ndn_verify_content(info->h, final_comp, &pco);
if (res != 0) {
ndnr_debug_ndnb(ndnr, __LINE__, "co_verify_failed", NULL,
info->interest_ndnb, info->pi->offset[NDN_PI_E]);
goto Bail;
}
}
switch (selfp->intdata & OPER_MASK) {
case OP_SERVICE:
if (ndnr->service_ndnb == NULL)
ndnr->service_ndnb = ndnr_init_service_ndnb(ndnr, info->h, NDNRID_LOCAL_URI, 600);
if (ndn_content_matches_interest(
ndnr->service_ndnb->buf,
ndnr->service_ndnb->length,
1,
NULL,
info->interest_ndnb,
info->pi->offset[NDN_PI_E],
info->pi
)) {
ndn_put(info->h, ndnr->service_ndnb->buf,
ndnr->service_ndnb->length);
res = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
goto Finish;
}
// XXX this needs refactoring.
if (ndnr->neighbor_ndnb == NULL)
ndnr->neighbor_ndnb = ndnr_init_service_ndnb(ndnr, info->h, NDNRID_NEIGHBOR_URI, 5);
if (ndn_content_matches_interest(
ndnr->neighbor_ndnb->buf,
ndnr->neighbor_ndnb->length,
1,
NULL,
info->interest_ndnb,
info->pi->offset[NDN_PI_E],
info->pi
)) {
ndn_put(info->h, ndnr->neighbor_ndnb->buf,
ndnr->neighbor_ndnb->length);
res = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
goto Finish;
}
if (ndn_content_matches_interest(
ndnr->policy_link_cob->buf,
ndnr->policy_link_cob->length,
1,
NULL,
info->interest_ndnb,
info->pi->offset[NDN_PI_E],
info->pi
)) {
ndn_put(info->h, ndnr->policy_link_cob->buf,
ndnr->policy_link_cob->length);
res = NDN_UPCALL_RESULT_INTEREST_CONSUMED;
goto Finish;
}
goto Bail;
break;
default:
// No other OP_xxx are supported here
goto Bail;
}
Bail:
res = NDN_UPCALL_RESULT_ERR;
Finish:
ndn_charbuf_destroy(&msg);
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&keylocator);
ndn_charbuf_destroy(&reply_body);
ndn_charbuf_destroy(&signed_info);
return(res);
}
static int
ndnr_internal_client_refresh(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
int microsec = 0;
if ((flags & NDN_SCHEDULE_CANCEL) == 0 &&
ndnr->internal_client != NULL &&
ndnr->internal_client_refresh == ev) {
microsec = ndn_process_scheduled_operations(ndnr->internal_client);
if (microsec > ev->evint)
microsec = ev->evint;
}
if (microsec <= 0 && ndnr->internal_client_refresh == ev)
ndnr->internal_client_refresh = NULL;
return(microsec);
}
#define NDNR_ID_TEMPL "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
PUBLIC void
ndnr_uri_listen(struct ndnr_handle *ndnr, struct ndn *ndn, const char *uri,
ndn_handler p, intptr_t intdata)
{
struct ndn_charbuf *name;
struct ndn_charbuf *uri_modified = NULL;
struct ndn_closure *closure;
struct ndn_indexbuf *comps;
const unsigned char *comp;
size_t comp_size;
size_t offset;
name = ndn_charbuf_create();
ndn_name_from_uri(name, uri);
comps = ndn_indexbuf_create();
if (ndn_name_split(name, comps) < 0)
abort();
if (ndn_name_comp_get(name->buf, comps, 1, &comp, &comp_size) >= 0) {
if (comp_size == 32 && 0 == memcmp(comp, NDNR_ID_TEMPL, 32)) {
/* Replace placeholder with our ndnr_id */
offset = comp - name->buf;
memcpy(name->buf + offset, ndnr->ndnr_id, 32);
uri_modified = ndn_charbuf_create();
ndn_uri_append(uri_modified, name->buf, name->length, 1);
uri = (char *)uri_modified->buf;
}
}
closure = calloc(1, sizeof(*closure));
closure->p = p;
closure->data = ndnr;
closure->intdata = intdata;
ndn_set_interest_filter(ndn, name, closure);
ndn_charbuf_destroy(&name);
ndn_charbuf_destroy(&uri_modified);
ndn_indexbuf_destroy(&comps);
}
/*
* This is used to shroud the contents of the keystore, which mainly serves
* to add integrity checking and defense against accidental misuse.
* The file permissions serve for restricting access to the private keys.
*/
#ifndef NDNR_KEYSTORE_PASS
#define NDNR_KEYSTORE_PASS "<PASSWORD>!"
#endif
/**
* Create the repository keystore if necessary,
* and load it into the client handle h.
*
* It is permitted for h to be NULL to skip the load.
* @returns -1 if there were problems.
*/
int
ndnr_init_repo_keystore(struct ndnr_handle *ndnr, struct ndn *h)
{
struct ndn_charbuf *temp = NULL;
struct ndn_charbuf *culprit = NULL;
struct stat statbuf;
int res = -1;
char *keystore_path = NULL;
struct ndn_signing_params sp = NDN_SIGNING_PARAMS_INIT;
temp = ndn_charbuf_create();
culprit = temp;
ndn_charbuf_putf(temp, "%s/", ndnr->directory);
res = stat(ndn_charbuf_as_string(temp), &statbuf);
if (res == -1)
goto Finish;
if ((statbuf.st_mode & S_IFDIR) == 0) {
res = -1;
errno = ENOTDIR;
goto Finish;
}
ndn_charbuf_putf(temp, "ndnx_repository_keystore");
keystore_path = strdup(ndn_charbuf_as_string(temp));
res = stat(keystore_path, &statbuf);
if (res == 0 && h != NULL)
res = ndn_load_default_key(h, keystore_path, NDNR_KEYSTORE_PASS);
if (res >= 0) {
culprit = NULL;
goto Finish;
}
/* No stored keystore that we can access. Create one if we can.*/
res = ndn_keystore_file_init(keystore_path, NDNR_KEYSTORE_PASS, "Repository", 0, 0);
if (res != 0) {
res = -1;
goto Finish;
}
if (NDNSHOULDLOG(ndnr, keystore, NDNL_WARNING))
ndnr_msg(ndnr, "New repository private key saved in %s", keystore_path);
if (h != NULL)
res = ndn_load_default_key(h, keystore_path, NDNR_KEYSTORE_PASS);
Finish:
if (res >= 0 && h != NULL)
res = ndn_chk_signing_params(h, NULL, &sp, NULL, NULL, NULL, NULL);
if (res >= 0 && h != NULL) {
memcpy(ndnr->ndnr_id, sp.pubid, sizeof(ndnr->ndnr_id));
if (ndnr->ndnr_keyid == NULL)
ndnr->ndnr_keyid = ndn_charbuf_create();
else
ndnr->ndnr_keyid->length = 0;
ndn_charbuf_append_value(ndnr->ndnr_keyid, NDN_MARKER_CONTROL, 1);
ndn_charbuf_append_string(ndnr->ndnr_keyid, ".M.K");
ndn_charbuf_append_value(ndnr->ndnr_keyid, 0, 1);
ndn_charbuf_append(ndnr->ndnr_keyid, ndnr->ndnr_id, sizeof(ndnr->ndnr_id));
}
if (res < 0) {
ndnr->running = -1; /* Make note of init failure */
if (culprit != NULL)
ndnr_msg(ndnr, "Error accessing keystore - %s: %s\n",
strerror(errno), ndn_charbuf_as_string(temp));
}
ndn_charbuf_destroy(&temp);
if (keystore_path != NULL)
free(keystore_path);
return(res);
}
static int
post_face_notice(struct ndnr_handle *ndnr, unsigned filedesc)
{
struct fdholder *fdholder = ndnr_r_io_fdholder_from_fd(ndnr, filedesc);
struct ndn_charbuf *msg = ndn_charbuf_create();
int res = -1;
int port;
// XXX - text version for trying out stream stuff - replace with ndnb
if (fdholder == NULL)
ndn_charbuf_putf(msg, "destroyface(%u);\n", filedesc);
else {
ndn_charbuf_putf(msg, "newface(%u, 0x%x", filedesc, fdholder->flags);
if (fdholder->name->length != 0 &&
(fdholder->flags & (NDNR_FACE_INET | NDNR_FACE_INET6)) != 0) {
ndn_charbuf_putf(msg, ", ");
port = ndn_charbuf_append_sockaddr(msg, (struct sockaddr *)fdholder->name->buf);
if (port < 0)
msg->length--;
else if (port > 0)
ndn_charbuf_putf(msg, ":%d", port);
}
ndn_charbuf_putf(msg, ");\n", filedesc);
}
res = ndn_seqw_write(ndnr->notice, msg->buf, msg->length);
ndn_charbuf_destroy(&msg);
return(res);
}
static int
ndnr_notice_push(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
struct ndn_indexbuf *chface = NULL;
int i = 0;
int j = 0;
int microsec = 0;
int res = 0;
if ((flags & NDN_SCHEDULE_CANCEL) == 0 &&
ndnr->notice != NULL &&
ndnr->notice_push == ev &&
ndnr->chface != NULL) {
chface = ndnr->chface;
ndn_seqw_batch_start(ndnr->notice);
for (i = 0; i < chface->n && res != -1; i++)
res = post_face_notice(ndnr, chface->buf[i]);
ndn_seqw_batch_end(ndnr->notice);
for (j = 0; i < chface->n; i++, j++)
chface->buf[j] = chface->buf[i];
chface->n = j;
if (res == -1)
microsec = 3000;
}
if (microsec <= 0)
ndnr->notice_push = NULL;
return(microsec);
}
/**
* Called by ndnr when a fdholder undergoes a substantive status change that
* should be reported to interested parties.
*
* In the destroy case, this is called from the hash table finalizer,
* so it shouldn't do much directly. Inspecting the fdholder is OK, though.
*/
void
ndnr_face_status_change(struct ndnr_handle *ndnr, unsigned filedesc)
{
struct ndn_indexbuf *chface = ndnr->chface;
if (chface != NULL) {
ndn_indexbuf_set_insert(chface, filedesc);
if (ndnr->notice_push == NULL)
ndnr->notice_push = ndn_schedule_event(ndnr->sched, 2000,
ndnr_notice_push,
NULL, 0);
}
}
int
ndnr_internal_client_start(struct ndnr_handle *ndnr)
{
if (ndnr->internal_client != NULL)
return(-1);
if (ndnr->face0 == NULL)
abort();
ndnr->internal_client = ndn_create();
if (ndnr_init_repo_keystore(ndnr, ndnr->internal_client) < 0) {
ndn_destroy(&ndnr->internal_client);
return(-1);
}
ndnr->internal_client_refresh = ndn_schedule_event(ndnr->sched, 50000,
ndnr_internal_client_refresh,
NULL, NDN_INTEREST_LIFETIME_MICROSEC);
return(0);
}
void
ndnr_internal_client_stop(struct ndnr_handle *ndnr)
{
ndnr->notice = NULL; /* ndn_destroy will free */
if (ndnr->notice_push != NULL)
ndn_schedule_cancel(ndnr->sched, ndnr->notice_push);
ndn_indexbuf_destroy(&ndnr->chface);
ndn_destroy(&ndnr->internal_client);
ndn_charbuf_destroy(&ndnr->service_ndnb);
ndn_charbuf_destroy(&ndnr->neighbor_ndnb);
if (ndnr->internal_client_refresh != NULL)
ndn_schedule_cancel(ndnr->sched, ndnr->internal_client_refresh);
}
// XXX - these are very similar to the above.
// If we keep multiple internal handles around, this will need refactoring.
static int
ndnr_direct_client_refresh(struct ndn_schedule *sched,
void *clienth,
struct ndn_scheduled_event *ev,
int flags)
{
struct ndnr_handle *ndnr = clienth;
int microsec = 0;
if ((flags & NDN_SCHEDULE_CANCEL) == 0 &&
ndnr->direct_client != NULL &&
ndnr->direct_client_refresh == ev) {
microsec = ndn_process_scheduled_operations(ndnr->direct_client);
// XXX - This is not really right, since an incoming request can cause us to need to reschedule this event.
if NDNSHOULDLOG(ndnr, refresh, NDNL_FINEST)
ndnr_msg(ndnr, "direct_client_refresh %d in %d usec",
ndn_get_connection_fd(ndnr->direct_client), microsec);
if (microsec > ev->evint)
microsec = ev->evint;
if (microsec == 0)
microsec = NDN_INTEREST_LIFETIME_MICROSEC;
}
if (microsec <= 0 && ndnr->direct_client_refresh == ev)
ndnr->direct_client_refresh = NULL;
return(microsec);
}
int
ndnr_direct_client_start(struct ndnr_handle *ndnr)
{
ndnr->direct_client = ndn_create();
if (ndnr_init_repo_keystore(ndnr, ndnr->direct_client) < 0) {
ndn_destroy(&ndnr->direct_client);
return(-1);
}
ndnr->direct_client_refresh = ndn_schedule_event(ndnr->sched, 50000,
ndnr_direct_client_refresh,
NULL, NDN_INTEREST_LIFETIME_MICROSEC);
return(0);
}
void
ndnr_direct_client_stop(struct ndnr_handle *ndnr)
{
if (ndnr->notice_push != NULL)
ndn_schedule_cancel(ndnr->sched, ndnr->notice_push);
ndn_indexbuf_destroy(&ndnr->chface);
ndn_destroy(&ndnr->direct_client);
ndn_charbuf_destroy(&ndnr->service_ndnb);
ndn_charbuf_destroy(&ndnr->neighbor_ndnb);
if (ndnr->direct_client_refresh != NULL)
ndn_schedule_cancel(ndnr->sched, ndnr->direct_client_refresh);
}
|
yoursunny/carepo
|
command/caput.c
|
<filename>command/caput.c
// put a file and SHA256 metadata into repository
#include "segment/rabin.h"
#include "segment/writer.h"
void usage(void) {
printf("Usage: caput [-s] name filename\n");
}
int main(int argc, char** argv) {
bool sign_segments = false;
int opt;
while (-1 != (opt = getopt(argc, argv, "s"))) {
switch (opt) {
case 's':
sign_segments = true;
break;
}
}
if (argc-optind != 2) {
usage();
return 1;
}
const char* name_str = argv[optind+0];
const char* filename = argv[optind+1];
struct ndn_charbuf* name = ndn_charbuf_create();
ndn_name_from_uri(name, name_str);
FILE* file = fopen(filename, "r");
if (file == NULL) return 2;
struct segment_list* sl = segment_rabin(file);
if (sl == NULL) return 3;
struct ndn* h = ndn_create();
if (-1 == ndn_connect(h, NULL)) return 4;
struct file_writer* fw = file_writer_ctor(sl, file, h, name, sign_segments);
if (!file_writer_run(fw)) return 5;
file_writer_dtor(&fw);
fclose(file);
ndn_destroy(&h);
segment_list_dtor(&sl);
ndn_charbuf_destroy(&name);
return 0;
}
|
acs6610987/SEAL
|
src/seal/secretkey.h
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include "seal/randomgen.h"
#include "seal/plaintext.h"
#include "seal/memorymanager.h"
#include "seal/util/common.h"
#include <iostream>
#include <cstdint>
#include <cstddef>
#include <memory>
#include <random>
namespace seal
{
/**
Class to store a secret key.
@par Thread Safety
In general, reading from SecretKey is thread-safe as long as no other thread
is concurrently mutating it. This is due to the underlying data structure
storing the secret key not being thread-safe.
@see KeyGenerator for the class that generates the secret key.
@see PublicKey for the class that stores the public key.
@see RelinKeys for the class that stores the relinearization keys.
@see GaloisKeys for the class that stores the Galois keys.
*/
class SecretKey
{
friend class KeyGenerator;
public:
/**
Creates an empty secret key.
*/
SecretKey() = default;
/**
Overwrites the key data by random data and destroys the SecretKey object.
*/
~SecretKey() noexcept
{
// We use a default factory from std::random_device to make sure
// randomize_key does not throw.
static std::unique_ptr<UniformRandomGeneratorFactory> random_factory(
std::make_unique<StandardRandomAdapterFactory<std::random_device>>());
randomize_secret(random_factory->create());
}
/**
Creates a new SecretKey by copying an old one.
@param[in] copy The SecretKey to copy from
*/
SecretKey(const SecretKey ©) = default;
/**
Creates a new SecretKey by moving an old one.
@param[in] source The SecretKey to move from
*/
SecretKey(SecretKey &&source) = default;
/**
Copies an old SecretKey to the current one.
@param[in] assign The SecretKey to copy from
*/
SecretKey &operator =(const SecretKey &assign)
{
sk_ = assign.sk_;
return *this;
}
/**
Moves an old SecretKey to the current one.
@param[in] assign The SecretKey to move from
*/
SecretKey &operator =(SecretKey &&assign) = default;
/**
Returns a reference to the underlying polynomial.
*/
inline auto &data() noexcept
{
return sk_;
}
/**
Returns a const reference to the underlying polynomial.
*/
inline auto &data() const noexcept
{
return sk_;
}
/**
Check whether the current SecretKey is valid for a given SEALContext. If
the given SEALContext is not set, the encryption parameters are invalid,
or the SecretKey data does not match the SEALContext, this function returns
false. Otherwise, returns true.
@param[in] context The SEALContext
*/
inline bool is_valid_for(std::shared_ptr<SEALContext> context) const
{
// Verify parameters
if (!context || !context->parameters_set())
{
return false;
}
auto parms_id = context->first_parms_id();
return sk_.is_valid_for(std::move(context)) &&
sk_.is_ntt_form() && sk_.parms_id() == parms_id;
}
/**
Saves the SecretKey to an output stream. The output is in binary format
and not human-readable. The output stream must have the "binary" flag set.
@param[in] stream The stream to save the SecretKey to
@throws std::exception if the plaintext could not be written to stream
*/
inline void save(std::ostream &stream) const
{
sk_.save(stream);
}
/**
Loads a SecretKey from an input stream overwriting the current SecretKey.
No checking of the validity of the SecretKey data against encryption
parameters is performed. This function should not be used unless the
SecretKey comes from a fully trusted source.
@param[in] stream The stream to load the SecretKey from
@throws std::exception if a valid SecretKey could not be read from stream
*/
inline void unsafe_load(std::istream &stream)
{
sk_.unsafe_load(stream);
}
/**
Loads a SecretKey from an input stream overwriting the current SecretKey.
The loaded SecretKey is verified to be valid for the given SEALContext.
@param[in] context The SEALContext
@param[in] stream The stream to load the SecretKey from
@throws std::invalid_argument if the context is not set or encryption
parameters are not valid
@throws std::exception if a valid SecretKey could not be read from stream
@throws std::invalid_argument if the loaded SecretKey is invalid for the
context
*/
inline void load(std::shared_ptr<SEALContext> context,
std::istream &stream)
{
unsafe_load(stream);
if (!is_valid_for(std::move(context)))
{
throw std::invalid_argument("SecretKey data is invalid");
}
}
/**
Returns a reference to parms_id.
@see EncryptionParameters for more information about parms_id.
*/
inline auto &parms_id() noexcept
{
return sk_.parms_id();
}
/**
Returns a const reference to parms_id.
@see EncryptionParameters for more information about parms_id.
*/
inline auto &parms_id() const noexcept
{
return sk_.parms_id();
}
/**
Returns the currently used MemoryPoolHandle.
*/
inline MemoryPoolHandle pool() const noexcept
{
return sk_.pool();
}
private:
inline void randomize_secret(
std::shared_ptr<UniformRandomGenerator> random) noexcept
{
std::size_t capacity = sk_.capacity();
volatile SEAL_BYTE *data_ptr = reinterpret_cast<SEAL_BYTE*>(sk_.data());
while (capacity--)
{
std::size_t pt_coeff_byte_count = sizeof(Plaintext::pt_coeff_type);
while (pt_coeff_byte_count--)
{
*data_ptr++ = static_cast<SEAL_BYTE>(random->generate());
}
}
}
/**
We use a fresh memory pool with `clear_on_destruction' enabled
*/
Plaintext sk_{ MemoryManager::GetPool(mm_prof_opt::FORCE_NEW, true) };
};
}
|
acs6610987/SEAL
|
src/seal/galoiskeys.h
|
<reponame>acs6610987/SEAL
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include <iostream>
#include <vector>
#include <numeric>
#include "seal/ciphertext.h"
#include "seal/memorymanager.h"
#include "seal/encryptionparams.h"
namespace seal
{
/**
Class to store Galois keys.
@par Slot Rotations
Galois keys are used together with batching (BatchEncoder). If the polynomial modulus
is a polynomial of degree N, in batching the idea is to view a plaintext polynomial as
a 2-by-(N/2) matrix of integers modulo plaintext modulus. Normal homomorphic computations
operate on such encrypted matrices element (slot) wise. However, special rotation
operations allow us to also rotate the matrix rows cyclically in either direction, and
rotate the columns (swap the rows). These operations require the Galois keys.
@par Decomposition Bit Count
Decomposition bit count (dbc) is a parameter that describes a performance trade-off in
the rotation operation. Its function is exactly the same as in relinearization. Namely,
the polynomials in the ciphertexts (with large coefficients) get decomposed into a smaller
base 2^dbc, coefficient-wise. Each of the decomposition factors corresponds to a piece of
data in the Galois keys, so the smaller the dbc is, the larger the Galois keys are.
Moreover, a smaller dbc results in less invariant noise budget being consumed in the
rotation operation. However, using a large dbc is much faster, and often one would want
to optimize the dbc to be as large as possible for performance. The dbc is upper-bounded
by the value of 60, and lower-bounded by the value of 1.
@par Thread Safety
In general, reading from GaloisKeys is thread-safe as long as no other thread is
concurrently mutating it. This is due to the underlying data structure storing the
Galois keys not being thread-safe.
@see SecretKey for the class that stores the secret key.
@see PublicKey for the class that stores the public key.
@see RelinKeys for the class that stores the relinearization keys.
@see KeyGenerator for the class that generates the Galois keys.
*/
class GaloisKeys
{
friend class KeyGenerator;
public:
/**
Creates an empty set of Galois keys.
*/
GaloisKeys() = default;
/**
Creates a new GaloisKeys instance by copying a given instance.
@param[in] copy The GaloisKeys to copy from
*/
GaloisKeys(const GaloisKeys ©) = default;
/**
Creates a new GaloisKeys instance by moving a given instance.
@param[in] source The GaloisKeys to move from
*/
GaloisKeys(GaloisKeys &&source) = default;
/**
Copies a given GaloisKeys instance to the current one.
@param[in] assign The GaloisKeys to copy from
*/
GaloisKeys &operator =(const GaloisKeys &assign);
/**
Moves a given GaloisKeys instance to the current one.
@param[in] assign The GaloisKeys to move from
*/
GaloisKeys &operator =(GaloisKeys &&assign) = default;
/**
Returns the current number of Galois keys.
*/
inline std::size_t size() const
{
return std::accumulate(keys_.begin(), keys_.end(), std::size_t(0),
[](std::size_t current_size, const std::vector<Ciphertext> &next_key)
{
return current_size + static_cast<std::size_t>(next_key.size() > 0);
});
}
/*
Returns the decomposition bit count.
*/
inline int decomposition_bit_count() const noexcept
{
return decomposition_bit_count_;
}
/**
Returns a reference to the Galois keys data.
*/
inline auto &data() noexcept
{
return keys_;
}
/**
Returns a const reference to the Galois keys data.
*/
inline auto &data() const noexcept
{
return keys_;
}
/**
Returns a const reference to a Galois key. The returned Galois key corresponds
to the given Galois element.
@param[in] galois_elt The Galois element
@throw std::invalid_argument if the key corresponding to galois_elt does not exist
*/
inline auto &key(std::uint64_t galois_elt) const
{
if (!has_key(galois_elt))
{
throw std::invalid_argument("requested key does not exist");
}
std::uint64_t index = (galois_elt - 1) >> 1;
return keys_[index];
}
/**
Returns whether a Galois key corresponding to a given Galois element exists.
@param[in] galois_elt The Galois element
@throw std::invalid_argument if Galois element is not valid
*/
inline bool has_key(std::uint64_t galois_elt) const
{
// Verify parameters
if (!(galois_elt & 1))
{
throw std::invalid_argument("galois element is not valid");
}
std::uint64_t index = (galois_elt - 1) >> 1;
return (index < keys_.size()) && !keys_[index].empty();
}
/**
Returns a reference to parms_id.
@see EncryptionParameters for more information about parms_id.
*/
inline auto &parms_id() noexcept
{
return parms_id_;
}
/**
Returns a const reference to parms_id.
@see EncryptionParameters for more information about parms_id.
*/
inline auto &parms_id() const noexcept
{
return parms_id_;
}
/**
Check whether the current GaloisKeys is valid for a given SEALContext. If
the given SEALContext is not set, the encryption parameters are invalid,
or the GaloisKeys data does not match the SEALContext, this function returns
false. Otherwise, returns true.
@param[in] context The SEALContext
*/
bool is_valid_for(std::shared_ptr<SEALContext> context) const noexcept;
/**
Saves the GaloisKeys instance to an output stream. The output is in binary
format and not human-readable. The output stream must have the "binary"
flag set.
@param[in] stream The stream to save the GaloisKeys to
@throws std::exception if the GaloisKeys could not be written to stream
*/
void save(std::ostream &stream) const;
/**
Loads a GaloisKeys from an input stream overwriting the current GaloisKeys.
No checking of the validity of the GaloisKeys data against encryption
parameters is performed. This function should not be used unless the
GaloisKeys comes from a fully trusted source.
@param[in] stream The stream to load the GaloisKeys from
@throws std::exception if a valid GaloisKeys could not be read from stream
*/
void unsafe_load(std::istream &stream);
/**
Loads a GaloisKeys from an input stream overwriting the current GaloisKeys.
The loaded GaloisKeys is verified to be valid for the given SEALContext.
@param[in] context The SEALContext
@param[in] stream The stream to load the GaloisKeys from
@throws std::invalid_argument if the context is not set or encryption
parameters are not valid
@throws std::exception if a valid GaloisKeys could not be read from stream
@throws std::invalid_argument if the loaded GaloisKeys is invalid for the
context
*/
inline void load(std::shared_ptr<SEALContext> context, std::istream &stream)
{
unsafe_load(stream);
if (!is_valid_for(std::move(context)))
{
throw std::invalid_argument("GaloisKeys data is invalid");
}
}
/**
Returns the currently used MemoryPoolHandle.
*/
inline MemoryPoolHandle pool() const noexcept
{
return pool_;
}
private:
MemoryPoolHandle pool_ = MemoryManager::GetPool();
parms_id_type parms_id_ = parms_id_zero;
/**
The vector of Galois keys.
*/
std::vector<std::vector<Ciphertext>> keys_{};
int decomposition_bit_count_ = 0;
};
}
|
acs6610987/SEAL
|
src/seal/context.h
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include <unordered_map>
#include <functional>
#include <memory>
#include "seal/encryptionparams.h"
#include "seal/memorymanager.h"
#include "seal/util/smallntt.h"
#include "seal/util/baseconverter.h"
#include "seal/util/pointer.h"
namespace seal
{
/**
Stores a set of attributes (qualifiers) of a set of encryption parameters.
These parameters are mainly used internally in various parts of the library, e.g.
to determine which algorithmic optimizations the current support. The qualifiers
are automatically created by the SEALContext class, silently passed on to classes
such as Encryptor, Evaluator, and Decryptor, and the only way to change them is by
changing the encryption parameters themselves. In other words, a user will never
have to create their own instance of EncryptionParameterQualifiers, and in most
cases never have to worry about them at all.
@see EncryptionParameters::GetQualifiers for obtaining the EncryptionParameterQualifiers
corresponding to the current parameter set.
*/
struct EncryptionParameterQualifiers
{
/**
If the encryption parameters are set in a way that is considered valid by SEAL, the
variable parameters_set is set to true.
*/
bool parameters_set;
/**
Tells whether FFT can be used for polynomial multiplication. If the polynomial modulus
is of the form X^N+1, where N is a power of two, then FFT can be used for fast
multiplication of polynomials modulo the polynomial modulus. In this case the
variable using_fft will be set to true. However, currently SEAL requires this
to be the case for the parameters to be valid. Therefore, parameters_set can only
be true if using_fft is true.
*/
bool using_fft;
/**
Tells whether NTT can be used for polynomial multiplication. If the primes in the
coefficient modulus are congruent to 1 modulo 2N, where X^N+1 is the polynomial
modulus and N is a power of two, then the number-theoretic transform (NTT) can be
used for fast multiplications of polynomials modulo the polynomial modulus and
coefficient modulus. In this case the variable using_ntt will be set to true. However,
currently SEAL requires this to be the case for the parameters to be valid. Therefore,
parameters_set can only be true if using_ntt is true.
*/
bool using_ntt;
/**
Tells whether batching is supported by the encryption parameters. If the plaintext
modulus is congruent to 1 modulo 2N, where X^N+1 is the polynomial modulus and N is
a power of two, then it is possible to use the BatchEncoder class to view plaintext
elements as 2-by-(N/2) matrices of integers modulo the plaintext modulus. This is
called batching, and allows the user to operate on the matrix elements (slots) in
a SIMD fashion, and rotate the matrix rows and columns. When the computation is
easily vectorizable, using batching can yield a huge performance boost. If the
encryption parameters support batching, the variable using_batching is set to true.
*/
bool using_batching;
/**
Tells whether fast plain lift is supported by the encryption parameters. A certain
performance optimization in multiplication of a ciphertext by a plaintext
(Evaluator::multiply_plain) and in transforming a plaintext element to NTT domain
(Evaluator::transform_to_ntt) can be used when the plaintext modulus is smaller than
each prime in the coefficient modulus. In this case the variable using_fast_plain_lift
is set to true.
*/
bool using_fast_plain_lift;
/**
Tells whether the encryption parameters are secure based on the standard parameters
from HomomorphicEncryption.org security standard.
*/
bool using_he_std_security;
private:
EncryptionParameterQualifiers() :
parameters_set(false),
using_fft(false),
using_ntt(false),
using_batching(false),
using_fast_plain_lift(false),
using_he_std_security(false)
{
}
friend class SEALContext;
};
/**
Performs sanity checks (validation) and pre-computations for a given set of encryption
parameters. While the EncryptionParameters class is intended to be a light-weight class
to store the encryption parameters, the SEALContext class is a heavy-weight class that
is constructed from a given set of encryption parameters. It validates the parameters
for correctness, evaluates their properties, and performs and stores the results of
several costly pre-computations.
After the user has set at least the poly_modulus, coeff_modulus, and plain_modulus
parameters in a given EncryptionParameters instance, the parameters can be validated
for correctness and functionality by constructing an instance of SEALContext. The
constructor of SEALContext does all of its work automatically, and concludes by
constructing and storing an instance of the EncryptionParameterQualifiers class, with
its flags set according to the properties of the given parameters. If the created
instance of EncryptionParameterQualifiers has the parameters_set flag set to true, the
given parameter set has been deemed valid and is ready to be used. If the parameters
were for some reason not appropriately set, the parameters_set flag will be false,
and a new SEALContext will have to be created after the parameters are corrected.
@see EncryptionParameters for more details on the parameters.
@see EncryptionParameterQualifiers for more details on the qualifiers.
*/
class SEALContext
{
public:
class ContextData
{
friend class SEALContext;
public:
ContextData() = delete;
ContextData(const ContextData ©) = delete;
ContextData(ContextData &&move) = default;
ContextData &operator =(ContextData &&move) = default;
/**
Returns a const reference to the underlying encryption parameters.
*/
inline auto &parms() const
{
return parms_;
}
/**
Returns a copy of EncryptionParameterQualifiers corresponding to the
current encryption parameters. Note that to change the qualifiers it is
necessary to create a new instance of SEALContext once appropriate changes
to the encryption parameters have been made.
*/
inline auto qualifiers() const
{
return qualifiers_;
}
/**
Returns a pointer to a pre-computed product of all primes in the coefficient
modulus. The security of the encryption parameters largely depends on the
bit-length of this product, and on the degree of the polynomial modulus.
*/
inline const std::uint64_t *total_coeff_modulus() const
{
return total_coeff_modulus_.get();
}
/**
Returns the significant bit count of the total coefficient modulus.
*/
inline auto total_coeff_modulus_bit_count() const
{
return total_coeff_modulus_bit_count_;
}
/**
Returns a const reference to the base converter.
*/
inline auto &base_converter() const
{
return base_converter_;
}
/**
Returns a const reference to the NTT tables.
*/
inline auto &small_ntt_tables() const
{
return small_ntt_tables_;
}
/**
Returns a const reference to the NTT tables.
*/
inline auto &plain_ntt_tables() const
{
return plain_ntt_tables_;
}
/**
Return a pointer to BFV "Delta", i.e. coefficient modulus divided by
plaintext modulus.
*/
inline const std::uint64_t *coeff_div_plain_modulus() const
{
return coeff_div_plain_modulus_.get();
}
/**
Return the threshold for the upper half of integers modulo plain_modulus.
This is simply (plain_modulus + 1) / 2.
*/
inline std::uint64_t plain_upper_half_threshold() const
{
return plain_upper_half_threshold_;
}
/**
Return a pointer to the plaintext upper half increment, i.e. coeff_modulus
minus plain_modulus. The upper half increment is represented as an integer
for the full product coeff_modulus if using_fast_plain_lift is false and is
otherwise represented modulo each of the coeff_modulus primes in order.
*/
inline const std::uint64_t *plain_upper_half_increment() const
{
return plain_upper_half_increment_.get();
}
/**
Return a pointer to the upper half threshold with respect to the total
coefficient modulus. This is needed in CKKS decryption.
*/
inline const std::uint64_t *upper_half_threshold() const
{
return upper_half_threshold_.get();
}
/**
Return a pointer to the upper half increment used for computing Delta*m
and converting the coefficients to modulo coeff_modulus. For example,
t-1 in plaintext should change into
q - Delta = Delta*t + r_t(q) - Delta
= Delta*(t-1) + r_t(q)
so multiplying the message by Delta is not enough and requires also an
addition of r_t(q). This is precisely the upper_half_increment. Note that
this operation is only done for negative message coefficients, i.e. those
that exceed plain_upper_half_threshold.
*/
inline const std::uint64_t *upper_half_increment() const
{
return upper_half_increment_.get();
}
/**
Returns a shared_ptr to the context data corresponding to the next parameters
in the modulus switching chain. If the current data is the last one in the
chain, then the result is nullptr.
*/
inline auto next_context_data() const
{
return next_context_data_;
}
/**
Returns the index of the parameter set in a chain. The initial parameters
have index 0 and the index increases sequentially in the parameter chain.
*/
inline std::size_t chain_index() const
{
return chain_index_;
}
private:
ContextData(EncryptionParameters parms, MemoryPoolHandle pool) :
pool_(std::move(pool)), parms_(parms)
{
if (!pool_)
{
throw std::invalid_argument("pool is uninitialized");
}
}
MemoryPoolHandle pool_;
EncryptionParameters parms_;
EncryptionParameterQualifiers qualifiers_;
util::Pointer<util::BaseConverter> base_converter_;
util::Pointer<util::SmallNTTTables> small_ntt_tables_;
util::Pointer<util::SmallNTTTables> plain_ntt_tables_;
util::Pointer<std::uint64_t> total_coeff_modulus_;
int total_coeff_modulus_bit_count_;
util::Pointer<std::uint64_t> coeff_div_plain_modulus_;
std::uint64_t plain_upper_half_threshold_;
util::Pointer<std::uint64_t> plain_upper_half_increment_;
util::Pointer<std::uint64_t> upper_half_threshold_;
util::Pointer<std::uint64_t> upper_half_increment_;
std::shared_ptr<const ContextData> next_context_data_{ nullptr };
std::size_t chain_index_ = 0;
};
SEALContext() = delete;
/**
Creates an instance of SEALContext, and performs several pre-computations
on the given EncryptionParameters.
@param[in] parms The encryption parameters
@param[in] expand_mod_chain Determines whether the modulus switching chain
should be created
*/
static auto Create(const EncryptionParameters &parms,
bool expand_mod_chain = true)
{
return std::shared_ptr<SEALContext>(
new SEALContext(parms, expand_mod_chain,
MemoryManager::GetPool()));
}
/**
Returns a const reference to ContextData class corresponding to the
encryption parameters. This is the first set of parameters in a chain
of parameters when modulus switching is used.
*/
inline auto context_data() const
{
return context_data_map_.at(first_parms_id_);
}
/**
Returns an optional const reference to ContextData class corresponding to
the parameters with a given parms_id. If parameters with the given parms_id
are not found then the function returns nullptr.
@param[in] parms_id The parms_id of the encryption parameters
*/
inline auto context_data(parms_id_type parms_id) const
{
auto data = context_data_map_.find(parms_id);
return (data != context_data_map_.end()) ?
data->second : std::shared_ptr<ContextData>{ nullptr };
}
/**
Returns whether the encryption parameters are valid.
*/
inline auto parameters_set() const
{
return context_data()->qualifiers_.parameters_set;
}
/**
Returns a parms_id_type corresponding to the first set
of encryption parameters.
*/
inline auto &first_parms_id() const
{
return first_parms_id_;
}
/**
Returns a parms_id_type corresponding to the last set
of encryption parameters.
*/
inline auto &last_parms_id() const
{
return last_parms_id_;
}
private:
SEALContext(const SEALContext ©) = delete;
SEALContext(SEALContext &&source) = delete;
SEALContext &operator =(const SEALContext &assign) = delete;
SEALContext &operator =(SEALContext &&assign) = delete;
/**
Creates an instance of SEALContext, and performs several pre-computations
on the given EncryptionParameters.
@param[in] parms The encryption parameters
@param[in] expand_mod_chain Determines whether the modulus switching chain
should be created
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if pool is uninitialized
*/
SEALContext(EncryptionParameters parms, bool expand_mod_chain,
MemoryPoolHandle pool);
ContextData validate(EncryptionParameters parms);
MemoryPoolHandle pool_;
parms_id_type first_parms_id_;
parms_id_type last_parms_id_;
std::unordered_map<
parms_id_type, std::shared_ptr<const ContextData>> context_data_map_{};
};
}
|
wbhsm/react-native
|
ReactCommon/react/renderer/components/image/conversions.h
|
<gh_stars>1-10
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <better/map.h>
#include <folly/dynamic.h>
#include <react/debug/react_native_assert.h>
#include <react/renderer/graphics/conversions.h>
#include <react/renderer/imagemanager/primitives.h>
namespace facebook {
namespace react {
inline void fromRawValue(const RawValue &value, ImageSource &result) {
if (value.hasType<std::string>()) {
result = {
/* .type = */ ImageSource::Type::Remote,
/* .uri = */ (std::string)value,
};
return;
}
if (value.hasType<better::map<std::string, RawValue>>()) {
auto items = (better::map<std::string, RawValue>)value;
result = {};
result.type = ImageSource::Type::Remote;
if (items.find("__packager_asset") != items.end()) {
result.type = ImageSource::Type::Local;
}
if (items.find("width") != items.end() &&
items.find("height") != items.end() &&
// The following checks have to be removed after codegen is shipped.
// See T45151459.
items.at("width").hasType<Float>() &&
items.at("height").hasType<Float>()) {
result.size = {(Float)items.at("width"), (Float)items.at("height")};
}
if (items.find("scale") != items.end() &&
// The following checks have to be removed after codegen is shipped.
// See T45151459.
items.at("scale").hasType<Float>()) {
result.scale = (Float)items.at("scale");
} else {
result.scale = items.find("deprecated") != items.end() ? 0.0 : 1.0;
}
if (items.find("url") != items.end() &&
// The following should be removed after codegen is shipped.
// See T45151459.
items.at("url").hasType<std::string>()) {
result.uri = (std::string)items.at("url");
}
if (items.find("uri") != items.end() &&
// The following should be removed after codegen is shipped.
// See T45151459.
items.at("uri").hasType<std::string>()) {
result.uri = (std::string)items.at("uri");
}
if (items.find("bundle") != items.end() &&
// The following should be removed after codegen is shipped.
// See T45151459.
items.at("bundle").hasType<std::string>()) {
result.bundle = (std::string)items.at("bundle");
result.type = ImageSource::Type::Local;
}
return;
}
// The following should be removed after codegen is shipped.
// See T45151459.
result = {};
result.type = ImageSource::Type::Invalid;
}
inline std::string toString(const ImageSource &value) {
return "{uri: " + value.uri + "}";
}
inline void fromRawValue(const RawValue &value, ImageResizeMode &result) {
react_native_assert(value.hasType<std::string>());
auto stringValue = (std::string)value;
if (stringValue == "cover") {
result = ImageResizeMode::Cover;
return;
}
if (stringValue == "contain") {
result = ImageResizeMode::Contain;
return;
}
if (stringValue == "stretch") {
result = ImageResizeMode::Stretch;
return;
}
if (stringValue == "center") {
result = ImageResizeMode::Center;
return;
}
if (stringValue == "repeat") {
result = ImageResizeMode::Repeat;
return;
}
abort();
}
inline std::string toString(const ImageResizeMode &value) {
switch (value) {
case ImageResizeMode::Cover:
return "cover";
case ImageResizeMode::Contain:
return "contain";
case ImageResizeMode::Stretch:
return "stretch";
case ImageResizeMode::Center:
return "center";
case ImageResizeMode::Repeat:
return "repeat";
}
}
} // namespace react
} // namespace facebook
|
sachinkesiraju/SKObserver
|
NSObject+SKObserver.h
|
//
// NSObject+SKObserver.h
// SKObserver
//
// Created by <NAME> on 1/19/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (SKObserver)
typedef void (^SKObserverBlock)(NSDictionary <NSKeyValueChangeKey, id> *change);
- (id) sk_addObserverForKeyPath:(NSString *) keyPath withBlock:(SKObserverBlock) block;
- (void) sk_removeObserver:(id) observer;
- (void) sk_removeAllObservers;
@end
NS_ASSUME_NONNULL_END
|
adaedra/ttyctl
|
ttyctl.c
|
#include <sys/ioctl.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
static char const * TTY_ERROR = "Cannot open TTY ";
static char const * TTY_PREFIX = "/dev/";
void strapnd(char ** ptr, char const * str) {
strcpy(*ptr, str);
*ptr += strlen(str);
**ptr = 0;
}
int cmd_blank(int tty) {
char cmd[] = {14};
return ioctl(tty, TIOCLINUX, cmd);
}
int cmd_wake(int tty) {
char cmd[] = {4};
return ioctl(tty, TIOCLINUX, cmd);
}
typedef int (*cmd_t)(int);
int open_and_run(char const * tty, cmd_t cmd) {
size_t size = strlen(TTY_ERROR) + strlen(tty) + 1;
if (!strchr(tty, '/')) {
size += strlen(TTY_PREFIX);
}
char * buffer = calloc(size, sizeof(char));
if (buffer == NULL) {
perror("Cannot allocate memory");
return 1;
}
char * cur = buffer;
strapnd(&cur, TTY_ERROR);
if (strchr(tty, '/')) {
strapnd(&cur, tty);
} else {
strapnd(&cur, TTY_PREFIX);
strapnd(&cur, tty);
}
int fd = open(buffer + strlen(TTY_ERROR), O_RDWR);
if (fd == -1) {
perror(buffer);
free(buffer);
return 1;
}
free(buffer);
return cmd(fd);
}
struct {
char const * cmd_string;
cmd_t cmd;
char const * cmd_help;
} COMMANDS[] = {
{ "blank", cmd_blank, "Blanks the TTY screen" },
{ "wake", cmd_wake, "Wakes up the TTY screen" }
};
int usage(char const * cmd) {
printf("Usage: %s command tty\n\nWhere command is one of:\n", cmd);
for (int i = 0; i < sizeof(COMMANDS) / sizeof(*COMMANDS); ++i) {
printf("\t% 5s %s\n", COMMANDS[i].cmd_string, COMMANDS[i].cmd_help);
}
return 0;
}
int main(int argc, char const ** argv) {
if (argc != 3) {
return 1 + usage(*argv);
}
for (int i = 0; i < sizeof(COMMANDS) / sizeof(*COMMANDS); ++i) {
if (strcmp(COMMANDS[i].cmd_string, argv[1]) == 0) {
return open_and_run(argv[2], COMMANDS[i].cmd);
}
}
fprintf(stderr, "Unknown command %s\n", argv[1]);
return 1 + usage(*argv);
}
|
pipelining/POICore
|
POICore/UIImage+WGAddCorner.h
|
//
// UIImage+WGAddCorner.h
// 微感科技
//
// Created by 张冬冬 on 2016/12/28.
// Copyright © 2016年 张冬冬. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (WGAddCorner)
- (instancetype)drawRectWithRoundedCornerRadius:(CGFloat)radius AndSize:(CGSize)sizeToFit;
@end
|
pipelining/POICore
|
POICore/UIView+BlurredImage.h
|
<filename>POICore/UIView+BlurredImage.h
//
// UIView+BlurredImage.h
//
#import <UIKit/UIKit.h>
@interface UIView (BlurredImage)
-(UIImage *)blurredImage;
-(UIImage *)imageWithBlur;
-(UIImage *)imageWithDarkEffect;
-(UIImage *)imageWithLightEffect;
-(UIImage *)imageWithExtraLightEffect;
-(UIImage *)imageWithTint:(UIColor*)color;
@end
|
pipelining/POICore
|
POICore/NSString+md5.h
|
//
// NSString+md5.h
// 微感科技
//
// Created by 张冬冬 on 2016/12/27.
// Copyright © 2016年 张冬冬. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (md5)
- (NSString *)md5String;
@end
|
pipelining/POICore
|
POICore/ZHNAlert.h
|
//
// ZHNAlert.h
// ZHNCosmos
//
// Created by zhn on 2018/1/17.
// Copyright © 2018年 zhn. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void(^ZHNAlertClickAction)();
@interface ZHNAlert : NSObject
/**
Show alert ,show one btn only
@param message message
@param confirmTitle confirm title
@param confirmAction confirm handle
*/
+ (void)zhn_showAlertWithMessage:(NSString *)message
confirmTitle:(NSString *)confirmTitle
confirmAction:(ZHNAlertClickAction)confirmAction;
/**
Show alert, show two btn
@param message message
@param cancleTitle cancle title
@param cancleAction cancle handle
@param confirmTitle confirm title
@param confirmAction confirm handle
*/
+ (void)zhn_showAlertWithMessage:(NSString *)message
CancleTitle:(NSString *)cancleTitle
cancleAction:(ZHNAlertClickAction)cancleAction
confirmTitle:(NSString *)confirmTitle
confirmAction:(ZHNAlertClickAction)confirmAction;
@end
////////////////////////////////////////////////////////
@interface ZHNALertMenuView : UIView
+ (ZHNALertMenuView *)zhn_menuWithMessage:(NSString *)message
cancleTitle:(NSString *)cancleTitle
confirmTitle:(NSString *)confrimTitle
cancleAction:(ZHNAlertClickAction)cancleAction
confirmAction:(ZHNAlertClickAction)confrimAction
blurView:(UIVisualEffectView *)blurView;
@property (nonatomic,strong) UIColor *alertColor;
- (CGSize)alertFitSize;
@end
|
pipelining/POICore
|
POICore/NSTimer+MFWeakTimer.h
|
//
// NSTimer+MFWeakTimer.h
// 软装
//
// Created by 张冬冬 on 2017/5/17.
// Copyright © 2017年 张冬冬. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSTimer (MFWeakTimer)
+ (NSTimer *)mf_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(void))block;
@end
|
pipelining/POICore
|
POICore/MFDeviceInfoManager.h
|
// Copyright © 2017年 张冬冬. All rights reserved.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface MFDeviceInfoManager : NSObject
//Screen scale
+ (CGFloat)scale;
//生成GUID
+ (NSString *)GUID;
//磁盘全部空间
+ (CGFloat)diskOfAllSizeGBytes;
//磁盘可用空间
+ (CGFloat)diskOfFreeSizeGBytes;
//获取文件大小
+ (long long)fileSizeAtPath:(NSString *)filePath;
//获取文件夹下所有文件的大小
+ (long long)folderSizeAtPath:(NSString *)folderPath;
//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile;
//利用正则表达式验证
+ (BOOL)isAvailableEmail:(NSString *)email;
//将十六进制颜色转换为 UIColor 对象
+ (UIColor *)colorWithHexString:(NSString *)color;
//获取设备 IP 地址
+ (NSString *)getIPAddress;
//压缩图片到指定文件大小
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size;
//压缩图片到指定尺寸大小
+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size;
//截取view中某个区域生成一张图片
+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope;
//截取view生成一张图片
+ (UIImage *)shotWithView:(UIView *)view;
//全屏截图
+ (UIImage *)shotScreen;
//实时模糊
+ (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame;
// CIGaussianBlur ---> 高斯模糊
// CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later)
// CIDiscBlur ---> 环形卷积模糊(Available in iOS 9.0 and later)
// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)
// CIMotionBlur ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)
+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius;
// 怀旧 --> CIPhotoEffectInstant 单色 --> CIPhotoEffectMono
// 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade
// 色调 --> CIPhotoEffectTonal 冲印 --> CIPhotoEffectProcess
// 岁月 --> CIPhotoEffectTransfer 铬黄 --> CIPhotoEffectChrome
// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name;
@end
|
pipelining/POICore
|
POICore/MFManager.h
|
<filename>POICore/MFManager.h
//
// MFManager.h
// 微感科技
//
// Created by 张冬冬 on 2017/6/28.
// Copyright © 2017年 张冬冬. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface MFManager : NSObject
+ (NSArray *)distinctUnionOfArray:(NSArray *)originArray;
+ (UIImage *)getImageFromCurrentView:(UIView *)view;
+ (UIImage *)getVideoImageByURL:(NSURL *)url;
+ (NSInteger)getVideoTimeByURL:(NSURL *)url;
+ (void)animatedSetKeyWindow:(UIViewController *)controller;
@end
|
pipelining/POICore
|
POICore/UIImageView+WGAddCorner.h
|
<filename>POICore/UIImageView+WGAddCorner.h
//
// UIImageView+WGAddCorner.h
// 微感科技
//
// Created by 张冬冬 on 2016/12/28.
// Copyright © 2016年 张冬冬. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImageView (WGAddCorner)
- (void)addCornerWithRadius:(CGFloat)radius;
@end
|
pipelining/POICore
|
POICore/UIColor+CustomColors.h
|
//
// UIColor+CustomColors.h
// 家装
//
// Created by 张冬冬 on 2016/12/15.
// Copyright © 2016年 张冬冬. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (CustomColors)
+ (UIColor *)customGrayColor;
+ (UIColor *)customRedColor;
+ (UIColor *)customYellowColor;
+ (UIColor *)customGreenColor;
+ (UIColor *)customBlueColor;
+ (UIColor *)customPurpleColor;
+ (UIColor *)customReloadColor;
+ (UIColor *)loginColor;
+ (UIColor *)facebookColor;
+ (UIColor *)jkColor;
+ (UIColor *)toastColor;
+ (UIColor *)toastActivityColor;
+ (UIColor *)tabbarButtonColor;
+ (UIColor *)unselectedTabbarButtonColor;
+ (UIColor *)customCyanColor;
+ (UIColor *)customTableViewBGColor;
+ (UIColor *)startColor;
+ (UIColor *)endColor;
+ (UIColor *)textfieldBGColor;
+ (UIColor *)couldColor;
+ (UIColor *)couldnotColor;
+ (UIColor *)mainNaviColor;
+ (UIColor *)mainBGColor;
//gradient
+ (UIColor *)gradientColor1;
+ (UIColor *)gradientColor2;
+ (UIColor *)gradientColor3;
+ (UIColor *)gradientColor4;
+ (UIColor *)gradientColor5;
+ (UIColor *)gradientColor6;
+ (UIColor *)gradientColor7;
+ (UIColor *)gradientColor8;
+ (UIColor *)gradientColor9;
+ (UIColor *)gradientColor10;
+ (UIColor *)gradientColor11;
+ (UIColor *)gradientColor12;
+ (UIColor *)gradientColor13;
+ (UIColor *)gradientColor14;
+ (UIColor *)gradientColor15;
+ (UIColor *)gradientColor16;
@end
|
pipelining/POICore
|
POICore/ZHNImageSaveToIphoneManager.h
|
<reponame>pipelining/POICore
//
// ZHNImageSaveToIphoneManager.h
// ZHNCosmos
//
// Created by zhn on 2017/11/23.
// Copyright © 2017年 zhn. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ZHNImageSaveToIphoneManager : NSObject
+ (void)zhn_saveImageDataToIphone:(NSData *)imageDate
imageType:(NSString *)imageType
success:(void(^)())successHandle
failure:(void(^)())failureHanlde;
@end
|
pipelining/POICore
|
POICore/UIColor+HexColor.h
|
//
// UIColor+HexColor.h
// 家装
//
// Created by 张冬冬 on 2016/11/23.
// Copyright © 2016年 张冬冬. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (HexColor)
+ (UIColor *)colorwithHexString:(NSString *)hexStr;
@end
|
tatsuhiroiida/mbed-os-pelion-sensor
|
MQTT_server_setting.h
|
#ifndef __MQTT_SERVER_SETTING_H__
#define __MQTT_SERVER_SETTING_H__
const char MQTT_SERVER_HOST_NAME[] = "<< REPLACE_HERE >>";
const char MQTT_CLIENT_ID[] = "device-1";
const char MQTT_TOPIC_CMD[] = "cmd/area-1/device-1";
const char MQTT_TOPIC_DATA[] = "data/area-1/device-1";
const int MQTT_SERVER_PORT = 8883;
/*
* Root CA certificate here in PEM format.
* "-----BEGIN CERTIFICATE-----\n"
* ...
* "-----END CERTIFICATE-----\n";
*/
const char* SSL_CA_PEM =
/* Amazon Root CA 1 */
"-----BEGIN CERTIFICATE-----\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"-----END CERTIFICATE-----\n"
/* */
/* Verysign */
"-----BEGIN CERTIFICATE-----\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"-----END CERTIFICATE-----\n"
/* */;
/*
* (optional) Client certificate here in PEM format.
* Set NULL if you don't use.
* "-----BEGIN CERTIFICATE-----\n"
* ...
* "-----END CERTIFICATE-----\n";
*/
const char* SSL_CLIENT_CERT_PEM = NULL;
/*
* (optional) Client private key here in PEM format.
* Set NULL if you don't use.
* "-----BEGIN RSA PRIVATE KEY-----\n"
* ...
* "-----END RSA PRIVATE KEY-----\n";
*/
const char* SSL_CLIENT_PRIVATE_KEY_PEM = NULL;
#endif /* __MQTT_SERVER_SETTING_H__ */
|
WiseLabCMU/slam3d
|
particlefilter/include/pfRandom.h
|
/*
* pfRandom.h
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef _PFRANDOM_H
#define _PFRANDOM_H
#ifdef __cplusplus
extern "C" {
#endif
extern unsigned int PF_SEED;
extern int PF_SEED_SET;
void pfRandom_init(void);
float pfRandom_uniform(void);
void pfRandom_normal2(float* x, float* y);
void pfRandom_sphere(float* x, float* y, float* z, float range, float stdRange);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
WiseLabCMU/slam3d
|
particlefilter/src/particleFilter.c
|
/*
* particleFilter.c
* Created by <NAME> on 11/1/18.
*
* Copyright (c) 2018, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <math.h>
#include <stdint.h>
#include "particleFilter.h"
#include "pfInit.h"
#include "pfMeasurement.h"
#include "pfRandom.h"
#include "pfResample.h"
static void _commitVioLoc(particleFilterLoc_t* pf);
static void _commitTagVioSlam(particleFilterSlam_t* pf);
static void _commitBcnVioSlam(bcn_t* bcn);
void particleFilterSeed_set(unsigned int seed)
{
PF_SEED = seed;
PF_SEED_SET = 1;
}
void particleFilterLoc_init(particleFilterLoc_t* pf)
{
pf->firstT = 0.0;
pf->firstX = 0.0f;
pf->firstY = 0.0f;
pf->firstZ = 0.0f;
pf->firstDist = 0.0f;
pf->lastT = 0.0;
pf->lastX = 0.0f;
pf->lastY = 0.0f;
pf->lastZ = 0.0f;
pf->lastDist = 0.0f;
pfRandom_init();
pf->initialized = 0;
}
void particleFilterSlam_init(particleFilterSlam_t* pf)
{
pf->firstT = 0.0;
pf->firstX = 0.0f;
pf->firstY = 0.0f;
pf->firstZ = 0.0f;
pf->firstDist = 0.0f;
pf->lastT = 0.0;
pf->lastX = 0.0f;
pf->lastY = 0.0f;
pf->lastZ = 0.0f;
pf->lastDist = 0.0f;
pfRandom_init();
pfInit_initTagSlam(pf);
pf->initialized = 1;
}
void particleFilterSlam_addBcn(bcn_t* bcn)
{
bcn->initialized = 0;
}
void particleFilterLoc_depositVio(particleFilterLoc_t* pf, double t, float x, float y, float z, float dist)
{
float dx, dy, dz;
if (pf->firstT == 0.0)
{
pf->firstT = t;
pf->firstX = x;
pf->firstY = y;
pf->firstZ = z;
pf->firstDist = dist;
pf->lastT = t;
pf->lastX = x;
pf->lastY = y;
pf->lastZ = z;
pf->lastDist = dist;
return;
}
if (dist > pf->lastDist)
{
pf->lastDist = dist;
}
else
{
dx = x - pf->lastX;
dy = y - pf->lastY;
dz = z - pf->lastZ;
pf->lastDist += sqrtf(dx * dx + dy * dy + dz * dz);
}
pf->lastT = t;
pf->lastX = x;
pf->lastY = y;
pf->lastZ = z;
}
void particleFilterSlam_depositTagVio(particleFilterSlam_t* pf, double t, float x, float y, float z, float dist)
{
float dx, dy, dz;
if (pf->firstT == 0.0)
{
pf->firstT = t;
pf->firstX = x;
pf->firstY = y;
pf->firstZ = z;
pf->firstDist = dist;
pf->lastT = t;
pf->lastX = x;
pf->lastY = y;
pf->lastZ = z;
pf->lastDist = dist;
return;
}
if (dist > pf->lastDist)
{
pf->lastDist = dist;
}
else
{
dx = x - pf->lastX;
dy = y - pf->lastY;
dz = z - pf->lastZ;
pf->lastDist += sqrtf(dx * dx + dy * dy + dz * dz);
}
pf->lastT = t;
pf->lastX = x;
pf->lastY = y;
pf->lastZ = z;
}
void particleFilterSlam_depositBcnVio(bcn_t* bcn, double t, float x, float y, float z, float dist)
{
float dx, dy, dz;
if (bcn->firstT == 0.0)
{
bcn->firstT = t;
bcn->firstX = x;
bcn->firstY = y;
bcn->firstZ = z;
bcn->firstDist = dist;
bcn->lastT = t;
bcn->lastX = x;
bcn->lastY = y;
bcn->lastZ = z;
bcn->lastDist = dist;
return;
}
if (dist > bcn->lastDist)
{
bcn->lastDist = dist;
}
else
{
dx = x - bcn->lastX;
dy = y - bcn->lastY;
dz = z - bcn->lastZ;
bcn->lastDist += sqrtf(dx * dx + dy * dy + dz * dz);
}
bcn->lastT = t;
bcn->lastX = x;
bcn->lastY = y;
bcn->lastZ = z;
}
void particleFilterLoc_depositRange(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange)
{
_commitVioLoc(pf);
if (pf->initialized)
{
pfMeasurement_applyRangeLoc(pf, bx, by, bz, range, stdRange);
pfResample_resampleLoc(pf, bx, by, bz, range, stdRange);
}
else
{
pfInit_initTagLoc(pf, bx, by, bz, range, stdRange);
pf->initialized = 1;
}
}
void particleFilterSlam_depositRange(particleFilterSlam_t* pf, bcn_t* bcn, float range, float stdRange, bcn_t** allBcns, int numBcns)
{
int i;
_commitTagVioSlam(pf);
for (i = 0; i < numBcns; ++i)
_commitBcnVioSlam(allBcns[i]);
if (bcn->initialized)
{
pfMeasurement_applyRangeSlam(pf, bcn, range, stdRange);
pfResample_resampleSlam(pf, bcn, range, stdRange, allBcns, numBcns);
}
else
{
pfInit_initBcnSlam(bcn, pf, range, stdRange);
bcn->initialized = 1;
}
}
void particleFilterLoc_depositRssi(particleFilterLoc_t* pf, float bx, float by, float bz, int rssi)
{
_commitVioLoc(pf);
if (pf->initialized)
{
pfMeasurement_applyRangeLoc(pf, bx, by, bz, 1.5f, 0.5f);
pfResample_resampleLoc(pf, bx, by, bz, 1.5f, 0.5f);
}
else
{
pfInit_initTagLoc(pf, bx, by, bz, 1.5f, 0.5f);
pf->initialized = 1;
}
}
void particleFilterSlam_depositRssi(particleFilterSlam_t* pf, bcn_t* bcn, int rssi, bcn_t** allBcns, int numBcns)
{
int i;
_commitTagVioSlam(pf);
for (i = 0; i < numBcns; ++i)
_commitBcnVioSlam(allBcns[i]);
if (bcn->initialized)
{
pfMeasurement_applyRangeSlam(pf, bcn, 1.5f, 0.5f);
pfResample_resampleSlam(pf, bcn, 1.5f, 0.5f, allBcns, numBcns);
}
else
{
pfInit_initBcnSlam(bcn, pf, 1.5f, 0.5f);
bcn->initialized = 1;
}
}
uint8_t particleFilterLoc_getTagLoc(const particleFilterLoc_t* pf, double* t, float* x, float* y, float* z, float* theta)
{
int i;
const tagParticle_t* tp;
float w, s, xsum, ysum, zsum, csum, ssum, dx, dy, dz, co, si;
if (!pf->initialized)
return 0;
s = 0.0f;
xsum = 0.0f;
ysum = 0.0f;
zsum = 0.0f;
csum = 0.0f;
ssum = 0.0f;
for (i = 0; i < PF_N_TAG_LOC; ++i)
{
tp = &pf->pTag[i];
w = tp->w;
s += w;
xsum += w * tp->x;
ysum += w * tp->y;
zsum += w * tp->z;
csum += w * cosf(tp->theta);
ssum += w * sinf(tp->theta);
}
*t = pf->lastT;
*x = xsum / s;
*y = ysum / s;
*z = zsum / s;
*theta = atan2f(ssum, csum);
dx = pf->lastX - pf->firstX;
dy = pf->lastY - pf->firstY;
dz = pf->lastZ - pf->firstZ;
co = cosf(*theta);
si = sinf(*theta);
*x += dx * co - dy * si;
*y += dx * si + dy * co;
*z += dz;
return 1;
}
uint8_t particleFilterSlam_getTagLoc(const particleFilterSlam_t* pf, double* t, float* x, float* y, float* z, float* theta)
{
int i;
const tagParticle_t* tp;
float w, s, xsum, ysum, zsum, csum, ssum, dx, dy, dz, co, si;
if (!pf->initialized)
return 0;
s = 0.0f;
xsum = 0.0f;
ysum = 0.0f;
zsum = 0.0f;
csum = 0.0f;
ssum = 0.0f;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
tp = &pf->pTag[i];
w = tp->w;
s += w;
xsum += w * tp->x;
ysum += w * tp->y;
zsum += w * tp->z;
csum += w * cosf(tp->theta);
ssum += w * sinf(tp->theta);
}
*t = pf->lastT;
*x = xsum / s;
*y = ysum / s;
*z = zsum / s;
*theta = atan2f(ssum, csum);
dx = pf->lastX - pf->firstX;
dy = pf->lastY - pf->firstY;
dz = pf->lastZ - pf->firstZ;
co = cosf(*theta);
si = sinf(*theta);
*x += dx * co - dy * si;
*y += dx * si + dy * co;
*z += dz;
return 1;
}
uint8_t particleFilterSlam_getBcnLoc(const particleFilterSlam_t* pf, const bcn_t* bcn, double* t, float* x, float* y, float* z, float* theta)
{
int i, j;
const bcnParticle_t* bp;
float w1, w2, s1, s2, xsum1, xsum2, ysum1, ysum2, zsum1, zsum2, csum1, csum2, ssum1, ssum2;
if (!bcn->initialized)
return 0;
s1 = 0.0f;
xsum1 = 0.0f;
ysum1 = 0.0f;
zsum1 = 0.0f;
csum1 = 0.0f;
ssum1 = 0.0f;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
w1 = pf->pTag[i].w;
s1 += w1;
s2 = 0.0f;
xsum2 = 0.0f;
ysum2 = 0.0f;
zsum2 = 0.0f;
csum2 = 0.0f;
ssum2 = 0.0f;
for (j = 0; j < PF_N_BCN; ++j)
{
bp = &bcn->pBcn[i][j];
w2 = bp->w;
s2 += w2;
xsum2 += w2 * bp->x;
ysum2 += w2 * bp->y;
zsum2 += w2 * bp->z;
csum2 += w2 * cosf(bp->theta);
ssum2 += w2 * sinf(bp->theta);
}
xsum1 += w1 * xsum2 / s2;
ysum1 += w1 * ysum2 / s2;
zsum1 += w1 * zsum2 / s2;
csum1 += w1 * csum2 / s2;
ssum1 += w1 * ssum2 / s2;
}
*t = pf->lastT;
*x = xsum1 / s1;
*y = ysum1 / s1;
*z = zsum1 / s1;
*theta = atan2f(ssum1, csum1);
return 1;
}
static void _commitVioLoc(particleFilterLoc_t* pf)
{
float dt, dx, dy, dz, ddist;
dt = (float)(pf->lastT - pf->firstT);
dx = pf->lastX - pf->firstX;
dy = pf->lastY - pf->firstY;
dz = pf->lastZ - pf->firstZ;
ddist = pf->lastDist - pf->firstDist;
pf->firstT = pf->lastT;
pf->firstX = pf->lastX;
pf->firstY = pf->lastY;
pf->firstZ = pf->lastZ;
pf->firstDist = pf->lastDist;
pfMeasurement_applyVioLoc(pf, dt, dx, dy, dz, ddist);
}
static void _commitTagVioSlam(particleFilterSlam_t* pf)
{
float dt, dx, dy, dz, ddist;
dt = (float)(pf->lastT - pf->firstT);
dx = pf->lastX - pf->firstX;
dy = pf->lastY - pf->firstY;
dz = pf->lastZ - pf->firstZ;
ddist = pf->lastDist - pf->firstDist;
pf->firstT = pf->lastT;
pf->firstX = pf->lastX;
pf->firstY = pf->lastY;
pf->firstZ = pf->lastZ;
pf->firstDist = pf->lastDist;
pfMeasurement_applyTagVioSlam(pf, dt, dx, dy, dz, ddist);
}
static void _commitBcnVioSlam(bcn_t* bcn)
{
float dt, dx, dy, dz, ddist;
dt = (float)(bcn->lastT - bcn->firstT);
dy = bcn->lastY - bcn->firstY;
dz = bcn->lastZ - bcn->firstZ;
dx = bcn->lastX - bcn->firstX;
ddist = bcn->lastDist - bcn->firstDist;
bcn->firstT = bcn->lastT;
bcn->firstX = bcn->lastX;
bcn->firstY = bcn->lastY;
bcn->firstZ = bcn->lastZ;
bcn->firstDist = bcn->lastDist;
pfMeasurement_applyBcnVioSlam(bcn, dt, dx, dy, dz, ddist);
}
|
WiseLabCMU/slam3d
|
particlefilter/src/pfMeasurement.c
|
/*
* pfMeasurement.c
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#define _USE_MATH_DEFINES
#include <math.h>
#undef _USE_MATH_DEFINES
#include "pfMeasurement.h"
#include "pfRandom.h"
#define VIO_STD_XYZ (1e-3f)
#define VIO_STD_THETA (1e-6f)
#define MIN_WEIGHT(range) ((range < 3.0f) ? 0.1f : 0.5f)
void pfMeasurement_applyVioLoc(particleFilterLoc_t* pf, float dt, float dx, float dy, float dz, float ddist)
{
int i;
tagParticle_t* tp;
float c, s, pDx, pDy, stdXyz, stdTheta;
float rx, ry, rz, rtheta;
stdXyz = sqrtf(ddist) * VIO_STD_XYZ;
stdTheta = sqrtf(dt) * VIO_STD_THETA;
for (i = 0; i < PF_N_TAG_LOC; ++i)
{
tp = &pf->pTag[i];
c = cosf(tp->theta);
s = sinf(tp->theta);
pDx = dx * c - dy * s;
pDy = dx * s + dy * c;
pfRandom_normal2(&rx, &ry);
pfRandom_normal2(&rz, &rtheta);
tp->x += pDx + stdXyz * rx;
tp->y += pDy + stdXyz * ry;
tp->z += dz + stdXyz * rz;
tp->theta = fmodf(tp->theta + stdTheta * rtheta, 2 * (float)M_PI);
}
}
void pfMeasurement_applyTagVioSlam(particleFilterSlam_t* pf, float dt, float dx, float dy, float dz, float ddist)
{
int i;
tagParticle_t* tp;
float c, s, pDx, pDy, stdXyz, stdTheta;
float rx, ry, rz, rtheta;
stdXyz = sqrtf(ddist) * VIO_STD_XYZ;
stdTheta = sqrtf(dt) * VIO_STD_THETA;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
tp = &pf->pTag[i];
c = cosf(tp->theta);
s = sinf(tp->theta);
pDx = dx * c - dy * s;
pDy = dx * s + dy * c;
pfRandom_normal2(&rx, &ry);
pfRandom_normal2(&rz, &rtheta);
tp->x += pDx + stdXyz * rx;
tp->y += pDy + stdXyz * ry;
tp->z += dz + stdXyz * rz;
tp->theta = fmodf(tp->theta + stdTheta * rtheta, 2 * (float)M_PI);
}
}
void pfMeasurement_applyBcnVioSlam(bcn_t* bcn, float dt, float dx, float dy, float dz, float ddist)
{
int i, j;
bcnParticle_t* bp;
float c, s, pDx, pDy, stdXyz, stdTheta;
float rx, ry, rz, rtheta;
stdXyz = sqrtf(ddist) * VIO_STD_XYZ;
stdTheta = sqrtf(dt) * VIO_STD_THETA;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
for (j = 0; j < PF_N_BCN; ++j)
{
bp = &bcn->pBcn[i][j];
c = cosf(bp->theta);
s = sinf(bp->theta);
pDx = dx * c - dy * s;
pDy = dx * s + dy * c;
pfRandom_normal2(&rx, &ry);
pfRandom_normal2(&rz, &rtheta);
bp->x += pDx + stdXyz * rx;
bp->y += pDy + stdXyz * ry;
bp->z += dz + stdXyz * rz;
bp->theta = fmodf(bp->theta + stdTheta * rtheta, 2 * (float)M_PI);
}
}
}
void pfMeasurement_applyRangeLoc(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange)
{
int i;
tagParticle_t* tp;
float minWeight, dx, dy, dz, pRange;
minWeight = MIN_WEIGHT(range);
for (i = 0; i < PF_N_TAG_LOC; ++i)
{
tp = &pf->pTag[i];
dx = tp->x - bx;
dy = tp->y - by;
dz = tp->z - bz;
pRange = sqrtf(dx * dx + dy * dy + dz * dz);
if (fabsf(pRange - range) > 3 * stdRange)
tp->w *= minWeight;
}
}
void pfMeasurement_applyRangeSlam(particleFilterSlam_t* pf, bcn_t* bcn, float range, float stdRange)
{
int i, j;
tagParticle_t* tp;
bcnParticle_t* bp;
float minWeight, dx, dy, dz, pRange, bcnSum;
minWeight = MIN_WEIGHT(range);
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
tp = &pf->pTag[i];
bcnSum = 0.0f;
for (j = 0; j < PF_N_BCN; ++j)
{
bp = &bcn->pBcn[i][j];
dx = tp->x - bp->x;
dy = tp->y - bp->y;
dz = tp->z - bp->z;
pRange = sqrtf(dx * dx + dy * dy + dz * dz);
if (fabsf(pRange - range) > 3 * stdRange)
bp->w *= minWeight;
bcnSum += bp->w;
}
tp->w *= bcnSum;
}
}
|
WiseLabCMU/slam3d
|
particlefilter/include/particleFilter.h
|
/*
* particleFilter.h
* Created by <NAME> on 11/1/18.
*
* Copyright (c) 2018, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef _PARTICLEFILTER_H
#define _PARTICLEFILTER_H
#include <stdint.h>
#define PF_N_TAG_LOC (10000)
#define PF_N_TAG_SLAM (100)
#define PF_N_BCN (1000)
#ifdef __cplusplus
extern "C" {
#endif
void particleFilterSeed_set(unsigned int seed);
typedef struct
{
float w;
float x;
float y;
float z;
float theta;
} tagParticle_t;
typedef struct
{
float w;
float x;
float y;
float z;
float theta;
} bcnParticle_t;
typedef struct
{
tagParticle_t pTag[PF_N_TAG_LOC];
tagParticle_t pTagBuf[PF_N_TAG_LOC];
uint8_t initialized;
double firstT;
float firstX;
float firstY;
float firstZ;
float firstDist;
double lastT;
float lastX;
float lastY;
float lastZ;
float lastDist;
} particleFilterLoc_t;
typedef struct
{
tagParticle_t pTag[PF_N_TAG_SLAM];
tagParticle_t pTagBuf[PF_N_TAG_SLAM];
uint8_t initialized;
double firstT;
float firstX;
float firstY;
float firstZ;
float firstDist;
double lastT;
float lastX;
float lastY;
float lastZ;
float lastDist;
} particleFilterSlam_t;
typedef struct
{
bcnParticle_t pBcn[PF_N_TAG_SLAM][PF_N_BCN];
bcnParticle_t pBcnBuf[PF_N_BCN];
uint8_t initialized;
double firstT;
float firstX;
float firstY;
float firstZ;
float firstDist;
double lastT;
float lastX;
float lastY;
float lastZ;
float lastDist;
} bcn_t;
void particleFilterLoc_init(particleFilterLoc_t* pf);
void particleFilterSlam_init(particleFilterSlam_t* pf);
void particleFilterSlam_addBcn(bcn_t* bcn);
void particleFilterLoc_depositVio(particleFilterLoc_t* pf, double t, float x, float y, float z, float dist);
void particleFilterSlam_depositTagVio(particleFilterSlam_t* pf, double t, float x, float y, float z, float dist);
void particleFilterSlam_depositBcnVio(bcn_t* bcn, double t, float x, float y, float z, float dist);
void particleFilterLoc_depositRange(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange);
void particleFilterSlam_depositRange(particleFilterSlam_t* pf, bcn_t* bcn, float range, float stdRange, bcn_t** allBcns, int numBcns);
void particleFilterLoc_depositRssi(particleFilterLoc_t* pf, float bx, float by, float bz, int rssi);
void particleFilterSlam_depositRssi(particleFilterSlam_t* pf, bcn_t* bcn, int rssi, bcn_t** allBcns, int numBcns);
uint8_t particleFilterLoc_getTagLoc(const particleFilterLoc_t* pf, double* t, float* x, float* y, float* z, float* theta);
uint8_t particleFilterSlam_getTagLoc(const particleFilterSlam_t* pf, double* t, float* x, float* y, float* z, float* theta);
uint8_t particleFilterSlam_getBcnLoc(const particleFilterSlam_t* pf, const bcn_t* bcn, double* t, float* x, float* y, float* z, float* theta);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
WiseLabCMU/slam3d
|
csvslam/csvslam.c
|
//
// csvslam.c
//
// Created by <NAME> on 11/1/18.
// Copyright � 2018 CMU. All rights reserved.
//
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "particleFilter.h"
#define DATA_DIR "../sampledata/"
#define TRACE_DIR DATA_DIR "cic/0/"
#define NUM_BCNS (12)
#define UWB_STD (0.1f)
#define UWB_BIAS (0.4f)
#define SKIP_TO_WAYPOINT (1)
#define VIO_FILE TRACE_DIR "vio.csv"
#define UWB_FILE TRACE_DIR "uwb.csv"
#define TAG_OUT_FILE TRACE_DIR "tag.csv"
#define BCN_OUT_FILE TRACE_DIR "bcn.csv"
#define LINE_LEN (1024)
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint);
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint);
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta);
static void _writeBcnLoc(FILE* outFile, uint8_t b, float x, float y, float z, float theta);
static particleFilterSlam_t _particleFilter;
static bcn_t _bcns[NUM_BCNS];
static bcn_t *_bcnPtrs[NUM_BCNS];
int main(int argc, char** argv)
{
FILE* vioFile;
FILE* uwbFile;
FILE* tagOutFile;
FILE* bcnOutFile;
double vioT, uwbT, outT;
float vioX, vioY, vioZ, uwbR, outX, outY, outZ, outTheta;
uint8_t uwbB, haveVio, haveUwb;
int i;
printf("Starting localization\n");
vioFile = fopen(VIO_FILE, "r");
uwbFile = fopen(UWB_FILE, "r");
tagOutFile = fopen(TAG_OUT_FILE, "w");
bcnOutFile = fopen(BCN_OUT_FILE, "w");
particleFilterSlam_init(&_particleFilter);
for (i = 0; i < NUM_BCNS; ++i)
{
particleFilterSlam_addBcn(&_bcns[i]);
_bcnPtrs[i] = &_bcns[i];
}
printf("Initialized\n");
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, SKIP_TO_WAYPOINT);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, SKIP_TO_WAYPOINT);
while (haveVio || haveUwb)
{
if (haveVio && (!haveUwb || vioT < uwbT))
{
particleFilterSlam_depositTagVio(&_particleFilter, vioT, vioX, vioY, vioZ, 0.0f);
if (particleFilterSlam_getTagLoc(&_particleFilter, &outT, &outX, &outY, &outZ, &outTheta))
_writeTagLoc(tagOutFile, outT, outX, outY, outZ, outTheta);
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, 0);
}
else if (haveUwb)
{
uwbR -= UWB_BIAS;
if (uwbR > 0.0f && uwbR < 30.0f)
particleFilterSlam_depositRange(&_particleFilter, &_bcns[uwbB], uwbR, UWB_STD, _bcnPtrs, NUM_BCNS);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, 0);
}
}
printf("Finished localization\n");
for (uwbB = 0; uwbB < NUM_BCNS; ++uwbB)
{
if (particleFilterSlam_getBcnLoc(&_particleFilter, &_bcns[uwbB], &outT, &outX, &outY, &outZ, &outTheta))
_writeBcnLoc(bcnOutFile, uwbB, outX, outY, outZ, outTheta);
}
fclose(vioFile);
fclose(uwbFile);
fclose(tagOutFile);
fclose(bcnOutFile);
printf("Done\n");
return 0;
}
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint)
{
static char _lineBuf[LINE_LEN];
char waypoint;
do
{
if (fgets(_lineBuf, LINE_LEN, vioFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
strtok(NULL, ","); // Skip "position" or "orientation" string
waypoint = strtok(NULL, ",")[0]; // Skip waypoint number
strtok(NULL, ","); // Skip accuracy number
*y = (float)atof(strtok(NULL, ",")); // VIO on iOS is reported in a different order (y, z, x)
*z = (float)atof(strtok(NULL, ","));
*x = (float)atof(strtok(NULL, ",\n"));
fgets(_lineBuf, LINE_LEN, vioFile); // Skip line for orientation
} while (skipToWaypoint && waypoint < '4');
return 1;
}
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint)
{
static char _lineBuf[LINE_LEN];
char waypoint;
do
{
if (fgets(_lineBuf, LINE_LEN, uwbFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
strtok(NULL, ","); // Skip "uwb_range" string
waypoint = strtok(NULL, ",")[0]; // Skip waypoint number
*b = strtok(NULL, ",")[0] - 'a';
*r = (float)atof(strtok(NULL, ",\n"));
} while (skipToWaypoint && waypoint < '4');
assert(*b < NUM_BCNS);
return 1;
}
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta)
{
static uint8_t printedHeaders = 0;
if (!printedHeaders)
{
fprintf(outFile, "t,x,y,z,theta\n");
printedHeaders = 1;
}
fprintf(outFile, "%lf,%f,%f,%f,%f\n", t, x, y, z, theta);
}
static void _writeBcnLoc(FILE* outFile, uint8_t b, float x, float y, float z, float theta)
{
static uint8_t printedHeaders = 0;
if (!printedHeaders)
{
fprintf(outFile, "b,x,y,z,theta\n");
printedHeaders = 1;
}
fprintf(outFile, "%hhu,%f,%f,%f,%f\n", b, x, y, z, theta);
}
|
WiseLabCMU/slam3d
|
csvlocalize/csvlocalize.c
|
<filename>csvlocalize/csvlocalize.c
//
// csvlocalize.c
//
// Created by <NAME> on 11/1/18.
// Copyright � 2018 CMU. All rights reserved.
//
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "particleFilter.h"
//#define DATA_DIR "../sampledata/"
//#define TRACE_DIR DATA_DIR "cic/0/"
//#define NUM_BCNS (12)
//#define UWB_STD (0.1f)
//#define UWB_BIAS (0.4f)
//#define SKIP_TO_WAYPOINT (1)
//
//#define VIO_FILE TRACE_DIR "vio.csv"
//#define UWB_FILE TRACE_DIR "uwb.csv"
//#define DEPLOY_FILE TRACE_DIR "deploy.csv"
//#define TAG_OUT_FILE TRACE_DIR "tag.csv"
//#define LINE_LEN (1024)
#define DATA_DIR "../mqttlogger/"
#define TRACE_DIR DATA_DIR
#define NUM_BCNS (4)
#define UWB_STD (0.1f)
#define UWB_BIAS (0.2f)
#define SKIP_TO_WAYPOINT (0)
#define VIO_FILE TRACE_DIR "vio.csv"
#define UWB_FILE TRACE_DIR "uwb.csv"
#define DEPLOY_FILE TRACE_DIR "../sampledata/arena/deploy.csv"
#define TAG_OUT_FILE TRACE_DIR "tag.csv"
#define LINE_LEN (1024)
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint);
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint);
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3]);
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta);
static particleFilterLoc_t _particleFilter;
int main(int argc, char** argv)
{
FILE* vioFile;
FILE* uwbFile;
FILE* deployFile;
FILE* tagOutFile;
float deployment[NUM_BCNS][3];
double vioT, uwbT, outT;
float vioX, vioY, vioZ, uwbR, outX, outY, outZ, outTheta;
uint8_t uwbB, haveVio, haveUwb;
printf("Starting localization\n");
vioFile = fopen(VIO_FILE, "r");
uwbFile = fopen(UWB_FILE, "r");
tagOutFile = fopen(TAG_OUT_FILE, "w");
particleFilterLoc_init(&_particleFilter);
deployFile = fopen(DEPLOY_FILE, "r");
_getDeployment(deployFile, deployment);
fclose(deployFile);
printf("Initialized\n");
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, SKIP_TO_WAYPOINT);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, SKIP_TO_WAYPOINT);
while (haveVio || haveUwb)
{
if (haveVio && (!haveUwb || vioT < uwbT))
{
particleFilterLoc_depositVio(&_particleFilter, vioT, vioX, vioY, vioZ, 0.0f);
if (particleFilterLoc_getTagLoc(&_particleFilter, &outT, &outX, &outY, &outZ, &outTheta))
_writeTagLoc(tagOutFile, outT, outX, outY, outZ, outTheta);
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, 0);
}
else if (haveUwb)
{
uwbR -= UWB_BIAS;
if (uwbR > 0.0f && uwbR < 30.0f)
particleFilterLoc_depositRange(&_particleFilter, deployment[uwbB][0], deployment[uwbB][1], deployment[uwbB][2], uwbR, UWB_STD);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, 0);
}
}
printf("Finished localization\n");
fclose(vioFile);
fclose(uwbFile);
fclose(tagOutFile);
printf("Done\n");
return 0;
}
//static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint)
//{
// static char _lineBuf[LINE_LEN];
// char waypoint;
//
// do
// {
// if (fgets(_lineBuf, LINE_LEN, vioFile) == NULL)
// return 0;
// *t = atof(strtok(_lineBuf, ","));
// strtok(NULL, ","); // Skip "position" or "orientation" string
// waypoint = strtok(NULL, ",")[0]; // Skip waypoint number
// strtok(NULL, ","); // Skip accuracy number
// *y = (float)atof(strtok(NULL, ",")); // VIO on iOS is reported in a different order (y, z, x)
// *z = (float)atof(strtok(NULL, ","));
// *x = (float)atof(strtok(NULL, ",\n"));
// fgets(_lineBuf, LINE_LEN, vioFile); // Skip line for orientation
// } while (skipToWaypoint && waypoint < '4');
//
// return 1;
//}
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint)
{
static char _lineBuf[LINE_LEN];
if (fgets(_lineBuf, LINE_LEN, vioFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
*y = (float)atof(strtok(NULL, ",")); // VIO on iOS is reported in a different order (y, z, x)
*z = (float)atof(strtok(NULL, ","));
*x = (float)atof(strtok(NULL, ",\n"));
return 1;
}
//static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint)
//{
// static char _lineBuf[LINE_LEN];
// char waypoint;
//
// do
// {
// if (fgets(_lineBuf, LINE_LEN, uwbFile) == NULL)
// return 0;
// *t = atof(strtok(_lineBuf, ","));
// strtok(NULL, ","); // Skip "uwb_range" string
// waypoint = strtok(NULL, ",")[0]; // Skip waypoint number
// *b = strtok(NULL, ",")[0] - 'a';
// *r = (float)atof(strtok(NULL, ",\n"));
// } while (skipToWaypoint && waypoint < '4');
//
// assert(*b < NUM_BCNS);
// return 1;
//}
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint)
{
static char _lineBuf[LINE_LEN];
if (fgets(_lineBuf, LINE_LEN, uwbFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
*b = (uint8_t)atoi(strtok(NULL, ","));
*r = (float)atof(strtok(NULL, ",\n"));
assert(*b < NUM_BCNS);
return 1;
}
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3])
{
static char _lineBuf[LINE_LEN];
int i;
uint8_t b;
for (i = 0; i < NUM_BCNS; ++i)
{
if (fgets(_lineBuf, LINE_LEN, deployFile) == NULL)
return;
b = (uint8_t)atoi(strtok(_lineBuf, ","));
assert(b < NUM_BCNS);
deployment[b][1] = (float)atof(strtok(NULL, ","));
deployment[b][2] = (float)atof(strtok(NULL, ","));
deployment[b][0] = (float)atof(strtok(NULL, ",\n"));
}
}
//static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta)
//{
// static uint8_t printedHeaders = 0;
// if (!printedHeaders)
// {
// fprintf(outFile, "t,x,y,z,theta\n");
// printedHeaders = 1;
// }
// fprintf(outFile, "%lf,%f,%f,%f,%f\n", t, x, y, z, theta);
//}
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta)
{
static uint8_t printedHeaders = 0;
if (!printedHeaders)
{
fprintf(outFile, "t,x,y,z,theta\n");
printedHeaders = 1;
}
fprintf(outFile, "%lf,%f,%f,%f,%f\n", t, y, z, x, theta);
}
|
WiseLabCMU/slam3d
|
mqttlocalize/mqttlocalize.c
|
//
// mqttlocalize.c
//
// Created by <NAME> on 11/1/18.
// Copyright � 2018 CMU. All rights reserved.
//
// Solver coordinates are "Z up";
// Coordinate input/output functions:
// _getVio(),
// _getDeployment(),
// _publishLoc()
// have to transform to/from this coordinate system
//
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>
#include "particleFilter.h"
#include "MQTTClient.h"
#include "cJSON.h"
#define DATA_DIR "../sampledata/"
#define TRACE_DIR DATA_DIR "arena/"
#define NUM_BCNS (12)
#define UWB_STD (0.1f)
#define UWB_BIAS (0.2f)
#define SKIP_TO_WAYPOINT (1)
#define UPDATE_INTERVAL_us 500000
#define DEPLOY_FILE TRACE_DIR "deploy.csv"
#define LINE_LEN (1024)
#define ADDRESS "oz.andrew.cmu.edu:1883"
#define CLIENTID "localize"
#define QOS 1
#define TIMEOUT 10000L
#define FRMT_TAG_LOC_MSG "%f,%f,%f,%f,%f,%f,%f"
#define FRMT_TAG_LOC_JSON "{\"object_id\" : \"%s\", \"action\": \"update\", \"type\": \"rig\", \"data\": {\"position\": {\"x\": %f, \"y\": %f, \"z\": %f}, \"rotation\": {\"x\": %f, \"y\": %f, \"z\": %f, \"w\": %f}}}"
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3]);
static void _publishLoc(MQTTClient client, char *topic, char *objid, double t, float x, float y, float z, float theta);
void delivered(void *context, MQTTClient_deliveryToken dt);
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message);
void connlost(void *context, char *cause);
static particleFilterLoc_t _particleFilter;
static float deployment[NUM_BCNS][3];
static char *topicName_VIO;
static char *topicName_UWB;
static MQTTClient client;
static int8_t _getVio(char *_lineBuf, double* t, float* x, float* y, float* z);
int main(int argc, char* argv[])
{
FILE* deployFile;
double outT;
float outX, outY, outZ, outTheta, dx, dy, dz, c, s, rigX, rigY, rigZ;
char clientid[LINE_LEN];
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
int rc;
int ch=0;
char *topicName_RigOut;
char *cameraObjId;
if (argc <5) printf("Usage: %s <Subscribe_VIO_Topic> <Subscribe_UWB_Topic> <Publish_Rig_Topic> <Rig_Obj_id>\n", argv[0]);
snprintf(clientid, LINE_LEN, "%s%ld", CLIENTID, time(NULL) % 1000);
printf("Client ID:%s\n", clientid);
MQTTClient_create(&client, ADDRESS, clientid,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
topicName_VIO = argv[1];
topicName_UWB = argv[2];
topicName_RigOut = argv[3];
cameraObjId = argv[4];
printf("\nSubscribing to topic %s\nfor client %s using QoS%d\n\n", topicName_VIO, clientid, QOS);
MQTTClient_subscribe(client, argv[1], QOS);
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n", topicName_UWB, clientid, QOS);
MQTTClient_subscribe(client, topicName_UWB, QOS);
printf("Starting localization\n");
particleFilterLoc_init(&_particleFilter);
deployFile = fopen(DEPLOY_FILE, "r");
_getDeployment(deployFile, deployment);
fclose(deployFile);
printf("Initialized\n");
printf("'Ctrl+c' to quit.\n");
do
{
if (particleFilterLoc_getTagLoc(&_particleFilter, &outT, &outX, &outY, &outZ, &outTheta))
{
// To get ARKit objects to align with world coordinates, we have to
// figure out the orientation and position of the ARKit origin
// w.r.t the global origin
// a rig transform (used by A frame) is the location of the global
// origin in the ARKit coordinate frame
// dx, dy, dz: are VIO estimates of phone position
// theta: is angle we must rotate VIO X axis to get global X axis
// outX, outY, outZ: are particle filter's estimates of phone
// position
dx = _particleFilter.lastX;
dy = _particleFilter.lastY;
dz = _particleFilter.lastZ;
c = cosf(outTheta);
s = sinf(outTheta);
rigX = outX - (dx * c - dy * s);
rigY = outY - (dx * s + dy * c);
rigZ = outZ - dz;
// additional pi/2 added to theta for axis alignment - Adwait
_publishLoc(client, topicName_RigOut, cameraObjId, outT, rigX, rigY, rigZ, outTheta);
}
usleep(UPDATE_INTERVAL_us);
} while(1);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
static int8_t _getVio(char *_lineBuf, double* t, float* x, float* y, float* z)
{
struct timeval tv;
gettimeofday(&tv, NULL);
int8_t status = 0; // return 0 on success
cJSON *data = NULL, *position = NULL, *pos_x = NULL, *pos_y = NULL, *pos_z = NULL;
// we add a timestamp based on reception; TODO: add timestamp on the client side
*t = tv.tv_sec + tv.tv_usec / 1000000.0;
// parse VIO message
// Example:
// {"object_id":"camera_jerry_jerry","action":"update","type":"object","data":{"position":{"x":0.788,"y":1.105,"z":-0.235},"rotation":{"x":0.024,"y":0.701,"z":0.712,"w":0.026}}}
cJSON *vio_json = cJSON_Parse(_lineBuf);
if (vio_json == NULL)
{
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL)
{
fprintf(stderr, "Error parsing VIO JSON before: %s\n", error_ptr);
}
status = -1;
goto end;
}
data = cJSON_GetObjectItemCaseSensitive(vio_json, "data");
if (data == NULL) {
printf("Error parsing VIO JSON: Could not get data obj\n");
status = -1;
goto end;
}
position = cJSON_GetObjectItemCaseSensitive(data, "position");
if (position == NULL) {
printf("Error parsing VIO JSON: Could not get position obj\n");
status = -1;
goto end;
}
pos_x = cJSON_GetObjectItemCaseSensitive(position, "x");
pos_y = cJSON_GetObjectItemCaseSensitive(position, "y");
pos_z = cJSON_GetObjectItemCaseSensitive(position, "z");
if (!cJSON_IsNumber(pos_x) || !cJSON_IsNumber(pos_y) || !cJSON_IsNumber(pos_z)) {
printf("Error parsing VIO JSON: Could not get coordinates\n");
status = -1;
goto end;
}
// note the coordinate system transform
*y = (float)pos_x->valuedouble;
*z = (float)pos_y->valuedouble;
*x = (float)pos_z->valuedouble;
end:
cJSON_Delete(vio_json);
return status;
}
static uint8_t _getUwb(char *_lineBuf, double* t, uint8_t* b, float* r)
{
struct timeval tv;
gettimeofday(&tv, NULL);
*t = tv.tv_sec + tv.tv_usec / 1000000.0;
*b = atoi(strtok(_lineBuf, ","));
// adding 0.3 to range to deal with bias observed on the UWB nodes
*r = (float)atof(strtok(NULL, ","));//+0.3;
return 1;
}
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3])
{
static char _lineBuf[LINE_LEN];
int i;
uint8_t b;
for (i = 0; i < NUM_BCNS; ++i)
{
if (fgets(_lineBuf, LINE_LEN, deployFile) == NULL)
return;
b = (uint8_t)atoi(strtok(_lineBuf, ","));
assert(b < NUM_BCNS);
// note the coordinate system transform
deployment[b][1] = (float)atof(strtok(NULL, ","));
deployment[b][2] = (float)atof(strtok(NULL, ","));
deployment[b][0] = (float)atof(strtok(NULL, ",\n"));
}
}
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta)
{
static uint8_t printedHeaders = 0;
if (!printedHeaders)
{
fprintf(outFile, "t,x,y,z,theta\n");
printedHeaders = 1;
}
fprintf(outFile, "%lf,%f,%f,%f,%f\n", t, x, y, z, theta);
}
static void _publishLoc(MQTTClient client, char *topic, char *objid, double t, float x, float y, float z, float theta)
{
MQTTClient_deliveryToken token;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
char str_msg[500];
//FRMT_TAG_LOC_JSON "{\"object_id\" : \"%s\", \"action\": \"update\", \"type\": \"rig\", \"data\": {\"position\": {\"x\": %f, \"y\": %f, \"z\": %f}, \"rotation\": {\"x\": %f, \"y\": %f, \"z\": %f, \"w\": %f}}}"
snprintf(str_msg, 500, FRMT_TAG_LOC_JSON, objid, y, z, x, 0.0f, sinf(theta/2), 0.0f, cosf(theta/2));
pubmsg.payload = str_msg;
pubmsg.payloadlen = strlen(str_msg);
pubmsg.qos = QOS;
pubmsg.retained = 0;
printf("UPDT : [%s] %s\n", topic, str_msg);
MQTTClient_publishMessage(client, topic, &pubmsg, &token);
}
void delivered(void *context, MQTTClient_deliveryToken dt)
{
//printf("Message with token value %d delivery confirmed\n", dt);
//deliveredtoken = dt;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
double vioT, uwbT, outT;
float vioX, vioY, vioZ, uwbR, outX, outY, outZ, outTheta;
uint8_t uwbB;
char payload_str[LINE_LEN];
assert(message->payloadlen < LINE_LEN-1);
memcpy(payload_str, message->payload, message->payloadlen);
payload_str[message->payloadlen] = '\0';
//printf("#topic: %s; message:%s", topicName, payload_str);
printf("#topic: %s ", topicName);
if (strncmp(topicName, topicName_VIO, strlen(topicName_VIO)) == 0) {
_getVio(payload_str, &vioT, &vioX, &vioY, &vioZ);
printf("VIO :%lf,%f,%f,%f\n", vioT, vioX, vioY, vioZ);
particleFilterLoc_depositVio(&_particleFilter, vioT, vioX, vioY, vioZ, 0.0f);
} else if (strncmp(topicName, topicName_UWB, strlen(topicName_UWB)) == 0) {
_getUwb(payload_str, &uwbT, &uwbB, &uwbR);
printf("UWB :%lf,%d,%f\n", uwbT, uwbB, uwbR);
assert(uwbB<NUM_BCNS);
uwbR -= UWB_BIAS;
if (uwbR > 0.0f && uwbR < 30.0f)
particleFilterLoc_depositRange(&_particleFilter, deployment[uwbB][0], deployment[uwbB][1], deployment[uwbB][2], uwbR, UWB_STD);
}
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
printf("\nConnection lost\n");
printf(" cause: %s\n", cause);
}
|
WiseLabCMU/slam3d
|
particlefilter/include/pfResample.h
|
<gh_stars>1-10
/*
* pfResample.h
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef _PFRESAMPLE_H
#define _PFRESAMPLE_H
#include "particleFilter.h"
#ifdef __cplusplus
extern "C" {
#endif
void pfResample_resampleLoc(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange);
void pfResample_resampleSlam(particleFilterSlam_t* pf, bcn_t* bcn, float range, float stdRange, bcn_t** allBcns, int numBcns);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
WiseLabCMU/slam3d
|
particlefilter/include/pfInit.h
|
/*
* pfInit.h
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef _PFINIT_H
#define _PFINIT_H
#include "particleFilter.h"
#ifdef __cplusplus
extern "C" {
#endif
void pfInit_initTagLoc(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange);
void pfInit_initTagSlam(particleFilterSlam_t* pf);
void pfInit_initBcnSlam(bcn_t* bcn, const particleFilterSlam_t* pf, float range, float stdRange);
void pfInit_spawnTagParticleZero(tagParticle_t* tp);
void pfInit_spawnTagParticleFromRange(tagParticle_t* tp, float bx, float by, float bz, float range, float stdRange);
void pfInit_spawnTagParticleFromOther(tagParticle_t* tp, const tagParticle_t* other, float hXyz, float hTheta);
void pfInit_spawnBcnParticleFromRange(bcnParticle_t* bp, const tagParticle_t* tp, float range, float stdRange);
void pfInit_spawnBcnParticleFromOther(bcnParticle_t* bp, const bcnParticle_t* other, float hXyz, float hTheta);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
WiseLabCMU/slam3d
|
particlefilter/include/pfMeasurement.h
|
/*
* pfMeasurement.h
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef _PFMEASUREMENT_H
#define _PFMEASUREMENT_H
#include "particleFilter.h"
#ifdef __cplusplus
extern "C" {
#endif
void pfMeasurement_applyVioLoc(particleFilterLoc_t* pf, float dt, float dx, float dy, float dz, float ddist);
void pfMeasurement_applyTagVioSlam(particleFilterSlam_t* pf, float dt, float dx, float dy, float dz, float ddist);
void pfMeasurement_applyBcnVioSlam(bcn_t* bcn, float dt, float dx, float dy, float dz, float ddist);
void pfMeasurement_applyRangeLoc(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange);
void pfMeasurement_applyRangeSlam(particleFilterSlam_t* pf, bcn_t* bcn, float range, float stdRange);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
WiseLabCMU/slam3d
|
ArSlam/app/src/main/jni/slam3d-jni.c
|
//
// slam3d-jni.c
//
// Created by <NAME> on 1/22/19.
// Copyright © 2019 CMU. All rights reserved.
//
#include <android/log.h>
#include <malloc.h>
#include <jni.h>
#include <particleFilter.h>
#define APPNAME "ArSlam"
JNIEXPORT jlong JNICALL Java_com_example_arslam_Slam3dJni_particleFilterNewPf(
JNIEnv* env, jclass clazz) {
particleFilterSlam_t* pf = (particleFilterSlam_t*)malloc(sizeof(particleFilterSlam_t));
particleFilterSlam_init(pf);
return (jlong)pf;
}
JNIEXPORT jlong JNICALL Java_com_example_arslam_Slam3dJni_particleFilterNewBcn(
JNIEnv* env, jclass clazz) {
bcn_t* bcn = (bcn_t*)malloc(sizeof(bcn_t));
particleFilterSlam_addBcn(bcn);
return (jlong)bcn;
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterFreePf(
JNIEnv* env, jclass clazz, jlong pf) {
free((particleFilterSlam_t*)pf);
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterFreeBcn(
JNIEnv* env, jclass clazz, jlong bcn) {
free((bcn_t*)bcn);
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterDepositTagVio(
JNIEnv* env, jclass clazz, jlong pf, jdouble t, jfloat x, jfloat y, jfloat z, jfloat dist) {
particleFilterSlam_depositTagVio((particleFilterSlam_t*)pf, (double)t, (float)x, (float)y, (float)z, (float)dist);
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterDepositBcnVio(
JNIEnv *env, jclass clazz, jlong bcn, jdouble t, jfloat x, jfloat y, jfloat z, jfloat dist) {
particleFilterSlam_depositBcnVio((bcn_t*)bcn, (double)t, (float)x, (float)y, (float)z, (float)dist);
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterDepositRange(
JNIEnv* env, jclass clazz, jlong pf, jlong bcn, jfloat range, jfloat stdRange, jlongArray bcnArray) {
bcn_t** allBcns = (bcn_t**)(*env)->GetLongArrayElements(env, bcnArray, NULL);
int numBcns = (int)(*env)->GetArrayLength(env, bcnArray);
particleFilterSlam_depositRange((particleFilterSlam_t*)pf, (bcn_t*)bcn, (float)range, (float)stdRange, allBcns, numBcns);
(*env)->ReleaseLongArrayElements(env, bcnArray, (jlong*)allBcns, 0);
}
JNIEXPORT void JNICALL Java_com_example_arslam_Slam3dJni_particleFilterDepositRssi(
JNIEnv* env, jclass clazz, jlong pf, jlong bcn, jint rssi, jlongArray bcnArray) {
bcn_t** allBcns = (bcn_t**)(*env)->GetLongArrayElements(env, bcnArray, NULL);
int numBcns = (int)(*env)->GetArrayLength(env, bcnArray);
particleFilterSlam_depositRssi((particleFilterSlam_t*)pf, (bcn_t*)bcn, (int)rssi, allBcns, numBcns);
(*env)->ReleaseLongArrayElements(env, bcnArray, (jlong*)allBcns, 0);
}
JNIEXPORT jobject JNICALL Java_com_example_arslam_Slam3dJni_particleFilterGetTagLoc(
JNIEnv* env, jclass clazz, jlong pf) {
double t;
float x, y, z, theta;
jclass class = (*env)->FindClass(env, "com/example/arslam/Slam3dJni$TagLocation");
jmethodID cid = (*env)->GetMethodID(env, class, "<init>", "(DFFFF)V");
particleFilterSlam_getTagLoc((const particleFilterSlam_t*)pf, &t, &x, &y, &z, &theta);
return (*env)->NewObject(env, class, cid, t, x, y, z, theta);
}
JNIEXPORT jobject JNICALL Java_com_example_arslam_Slam3dJni_particleFilterGetBcnLoc(
JNIEnv* env, jclass clazz, jlong pf, jlong bcn) {
double t;
float x, y, z, theta;
jclass class = (*env)->FindClass(env, "com/example/arslam/Slam3dJni$BcnLocation");
jmethodID cid = (*env)->GetMethodID(env, class, "<init>", "(DFFFF)V");
particleFilterSlam_getBcnLoc((const particleFilterSlam_t*)pf, (const bcn_t*)bcn, &t, &x, &y, &z, &theta);
return (*env)->NewObject(env, class, cid, t, x, y, z, theta);
}
|
WiseLabCMU/slam3d
|
particlefilter/src/pfInit.c
|
<reponame>WiseLabCMU/slam3d
/*
* pfInit.c
* Created by <NAME> on 11/1/19.
*
* Copyright (c) 2019, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#define _USE_MATH_DEFINES
#include <math.h>
#undef _USE_MATH_DEFINES
#include "pfInit.h"
#include "pfRandom.h"
void pfInit_initTagLoc(particleFilterLoc_t* pf, float bx, float by, float bz, float range, float stdRange)
{
int i;
for (i = 0; i < PF_N_TAG_LOC; ++i)
pfInit_spawnTagParticleFromRange(&pf->pTag[i], bx, by, bz, range, stdRange);
}
void pfInit_initTagSlam(particleFilterSlam_t* pf)
{
int i;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
pfInit_spawnTagParticleZero(&pf->pTag[i]);
}
void pfInit_initBcnSlam(bcn_t* bcn, const particleFilterSlam_t* pf, float range, float stdRange)
{
int i, j;
const tagParticle_t* tp;
for (i = 0; i < PF_N_TAG_SLAM; ++i)
{
tp = &pf->pTag[i];
for (j = 0; j < PF_N_BCN; ++j)
pfInit_spawnBcnParticleFromRange(&bcn->pBcn[i][j], tp, range, stdRange);
}
}
void pfInit_spawnTagParticleZero(tagParticle_t* tp)
{
tp->w = 1.0f;
tp->x = 0.0f;
tp->y = 0.0f;
tp->z = 0.0f;
tp->theta = 0.0f;
}
void pfInit_spawnTagParticleFromRange(tagParticle_t* tp, float bx, float by, float bz, float range, float stdRange)
{
float dx, dy, dz;
pfRandom_sphere(&dx, &dy, &dz, range, stdRange);
tp->w = 1.0f;
tp->x = bx + dx;
tp->y = by + dy;
tp->z = bz + dz;
tp->theta = pfRandom_uniform() * 2 * (float)M_PI;
}
void pfInit_spawnTagParticleFromOther(tagParticle_t* tp, const tagParticle_t* other, float hXyz, float hTheta)
{
float dx, dy, dz, dtheta;
pfRandom_normal2(&dx, &dy);
pfRandom_normal2(&dz, &dtheta);
tp->w = 1.0f;
tp->x = other->x + dx * hXyz;
tp->y = other->y + dy * hXyz;
tp->z = other->z + dz * hXyz;
tp->theta = fmodf(other->theta + dtheta * hTheta, 2 * (float)M_PI);
}
void pfInit_spawnBcnParticleFromRange(bcnParticle_t* bp, const tagParticle_t* tp, float range, float stdRange)
{
float dx, dy, dz;
pfRandom_sphere(&dx, &dy, &dz, range, stdRange);
bp->w = 1.0f;
bp->x = tp->x + dx;
bp->y = tp->y + dy;
bp->z = tp->z + dz;
bp->theta = pfRandom_uniform() * 2 * (float)M_PI;
}
void pfInit_spawnBcnParticleFromOther(bcnParticle_t* bp, const bcnParticle_t* other, float hXyz, float hTheta)
{
float dx, dy, dz, dtheta;
pfRandom_normal2(&dx, &dy);
pfRandom_normal2(&dz, &dtheta);
bp->w = 1.0f;
bp->x = other->x + dx * hXyz;
bp->y = other->y + dy * hXyz;
bp->z = other->z + dz * hXyz;
bp->theta = fmodf(other->theta + dtheta * hTheta, 2 * (float)M_PI);
}
|
WiseLabCMU/slam3d
|
test/test.c
|
<gh_stars>1-10
/*
* test.c
* Created by <NAME> on 6/25/21.
*
* Copyright (c) 2021, Wireless Sensing and Embedded Systems Lab, Carnegie
* Mellon University
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include "particleFilter.h"
// Only one test for now, so keep it simple
#define NUM_BCNS (4)
#define UWB_STD (0.1f)
#define UWB_BIAS (0.2f)
#define SKIP_TO_WAYPOINT (0)
#define VIO_FILE "/test1_ParticleFilterLoc_vio.csv"
#define UWB_FILE "/test1_ParticleFilterLoc_uwb.csv"
#define DEPLOY_FILE "/test1_ParticleFilterLoc_deploy.csv"
#define TEST_FOLDER argv[1 + noFail]
#define TAG_OUT_FILE argv[2 + noFail]
#define EXPECTED_FILE argv[3 + noFail]
#define LINE_LEN (1024)
#define SEED (123456789)
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint);
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint);
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3]);
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta);
static particleFilterLoc_t _particleFilter;
int main(int argc, char** argv) {
if (argc < 4) {
printf("Test folder, out file, expected file, and/or --nofail not specified!\n");
printf("test [--nofail] <test folder> <output file> [expected file (required without --nofail)]\n");
return 1;
}
int noFail = (strcmp(argv[1], "--nofail") == 0);
char vioFilePath[1024];
char uwbFilePath[1024];
char deployFilePath[1024];
strcpy(vioFilePath, TEST_FOLDER);
strcpy(uwbFilePath, TEST_FOLDER);
strcpy(deployFilePath, TEST_FOLDER);
strcat(vioFilePath, VIO_FILE);
strcat(uwbFilePath, UWB_FILE);
strcat(deployFilePath, DEPLOY_FILE);
printf("Starting test\n");
particleFilterSeed_set(SEED);
FILE* vioFile;
FILE* uwbFile;
FILE* deployFile;
FILE* tagOutFile;
float deployment[NUM_BCNS][3];
double vioT, uwbT, outT;
float vioX, vioY, vioZ, uwbR, outX, outY, outZ, outTheta;
uint8_t uwbB, haveVio, haveUwb;
clock_t t_measure;
printf("Starting localization\n");
vioFile = fopen(vioFilePath, "r");
uwbFile = fopen(uwbFilePath, "r");
tagOutFile = fopen(TAG_OUT_FILE, "w");
particleFilterLoc_init(&_particleFilter);
deployFile = fopen(deployFilePath, "r");
_getDeployment(deployFile, deployment);
fclose(deployFile);
printf("Initialized\n");
t_measure = clock();
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, SKIP_TO_WAYPOINT);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, SKIP_TO_WAYPOINT);
while (haveVio || haveUwb) {
if (haveVio && (!haveUwb || vioT < uwbT)) {
particleFilterLoc_depositVio(&_particleFilter, vioT, vioX, vioY, vioZ, 0.0f);
if (particleFilterLoc_getTagLoc(&_particleFilter, &outT, &outX, &outY, &outZ, &outTheta))
_writeTagLoc(tagOutFile, outT, outX, outY, outZ, outTheta);
haveVio = _getVio(vioFile, &vioT, &vioX, &vioY, &vioZ, 0);
} else if (haveUwb) {
uwbR -= UWB_BIAS;
if (uwbR > 0.0f && uwbR < 30.0f)
particleFilterLoc_depositRange(&_particleFilter, deployment[uwbB][0], deployment[uwbB][1], deployment[uwbB][2], uwbR, UWB_STD);
haveUwb = _getUwb(uwbFile, &uwbT, &uwbB, &uwbR, 0);
}
}
t_measure = clock() - t_measure;
printf("Finished localization\n");
double time_taken = ((double)t_measure)/CLOCKS_PER_SEC;
printf("Loop took %f seconds to execute\n", time_taken);
fclose(vioFile);
fclose(uwbFile);
fclose(tagOutFile);
FILE* expectedFileCompare;
FILE* tagOutFileCompare;
if (argc == 4 && noFail) {
printf("Expected compare file not provided and called with --nofail, exiting\n");
return 0;
}
expectedFileCompare = fopen(EXPECTED_FILE, "r");
tagOutFileCompare = fopen(TAG_OUT_FILE, "r");
char ch1, ch2;
int res = 0;
if (expectedFileCompare == NULL || tagOutFileCompare == NULL) {
printf("Could not open files to compare!\n");
if (expectedFileCompare != NULL)
fclose(expectedFileCompare);
if (tagOutFileCompare != NULL)
fclose(tagOutFileCompare);
return 1;
}
while (!feof(expectedFileCompare) && !feof(tagOutFileCompare)) {
ch1 = fgetc(expectedFileCompare);
ch2 = fgetc(tagOutFileCompare);
if (ch1 != ch2) {
res = 1;
break;
}
}
if (feof(expectedFileCompare) != feof(tagOutFileCompare)) {
res = 1;
}
fclose(expectedFileCompare);
fclose(tagOutFileCompare);
if (!res) {
printf("Test passed\n");
return 0;
} else if (res && noFail) {
printf("Test failed, but called with --nofail\n");
return 0;
} else {
printf("Test failed\n");
return 1;
}
}
static uint8_t _getVio(FILE* vioFile, double* t, float* x, float* y, float* z, uint8_t skipToWaypoint) {
static char _lineBuf[LINE_LEN];
if (fgets(_lineBuf, LINE_LEN, vioFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
*y = (float)atof(strtok(NULL, ",")); // VIO on iOS is reported in a different order (y, z, x)
*z = (float)atof(strtok(NULL, ","));
*x = (float)atof(strtok(NULL, ",\n"));
return 1;
}
static uint8_t _getUwb(FILE* uwbFile, double* t, uint8_t* b, float* r, uint8_t skipToWaypoint) {
static char _lineBuf[LINE_LEN];
if (fgets(_lineBuf, LINE_LEN, uwbFile) == NULL)
return 0;
*t = atof(strtok(_lineBuf, ","));
*b = (uint8_t)atoi(strtok(NULL, ","));
*r = (float)atof(strtok(NULL, ",\n"));
assert(*b < NUM_BCNS);
return 1;
}
static void _getDeployment(FILE* deployFile, float deployment[NUM_BCNS][3]) {
static char _lineBuf[LINE_LEN];
int i;
uint8_t b;
for (i = 0; i < NUM_BCNS; ++i) {
if (fgets(_lineBuf, LINE_LEN, deployFile) == NULL)
return;
b = (uint8_t)atoi(strtok(_lineBuf, ","));
assert(b < NUM_BCNS);
deployment[b][1] = (float)atof(strtok(NULL, ","));
deployment[b][2] = (float)atof(strtok(NULL, ","));
deployment[b][0] = (float)atof(strtok(NULL, ",\n"));
}
}
static void _writeTagLoc(FILE* outFile, double t, float x, float y, float z, float theta) {
static uint8_t printedHeaders = 0;
if (!printedHeaders) {
fprintf(outFile, "t,x,y,z,theta\n");
printedHeaders = 1;
}
fprintf(outFile, "%lf,%f,%f,%f,%f\n", t, y, z, x, theta);
}
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/logging.h
|
<reponame>ajbennieston/ssh-tunnel<gh_stars>1-10
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#ifndef SSH_TUNNELD_LOGGING_H
#define SSH_TUNNELD_LOGGING_H
#include <stdio.h>
void write_log_connect(int num_connections);
void write_log(const char* message);
extern FILE* logfile;
#endif
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/ssh-control.h
|
<filename>ssh-tunneld/ssh-control.h
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#ifndef SSH_TUNNELD_SSHCONTROL_H
#define SSH_TUNNELD_SSHCONTROL_H
#include <sys/types.h>
pid_t start_ssh_tunnel(char* hostname, char* port, char* proxy_port);
void stop_ssh_tunnel(pid_t process_id);
#endif
|
ajbennieston/ssh-tunnel
|
ssh-tunnelc/options.h
|
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#ifndef SSH_TUNNELC_OPTIONS_H
#define SSH_TUNNELC_OPTIONS_H
struct program_options {
/* Address of the proxy to connect to */
char* proxy_host;
char* proxy_port;
/* Port used by ssh-tunneld */
char* tunnel_port;
/* Remote tunnelled endpoint */
char* remote_host;
char* remote_port;
};
void print_usage(const char* program_name);
void process_arguments(int argc, char** argv, struct program_options* options);
#endif
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/logging.c
|
<filename>ssh-tunneld/logging.c
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#include "logging.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
/* Global variables */
FILE* logfile;
char *terminated_strncpy(char *dest, const char *src, size_t n)
{
/* Wrapper for strncpy() that ensures correct string termination */
size_t source_length = strlen(src);
strncpy(dest, src, n); /* null termination of dest will be enforced */
if (source_length >= n)
{
/* Source string was too big, so we terminate at the end
* of destination buffer
*/
dest[n-1] = '\0';
}
else
{
/* Source string fits inside destination buffer, so we
* can terminate immediately after it
*/
dest[source_length] = '\0';
}
return dest;
}
/* Function definitions */
void write_log_connect(int num_connections)
{
/* Duplicate some of the logging code to avoid
* using snprintf(), which triggers a warning
* on FreeBSD 9 when compiling with
* -pedantic -std=c99 -Wall -Wextra
*/
if (logfile != NULL)
{
char time_string[64];
time_t t = time(NULL);
char* str_time = ctime(&t);
terminated_strncpy(time_string, str_time, sizeof(time_string));
size_t stime = strlen(time_string);
time_string[stime-1] = '\0'; /* remove '\n' from time string */
fprintf(logfile, "[%s] Connections: %d.\n", time_string, num_connections);
fflush(logfile);
}
}
void write_log(const char* message)
{
/* write a log message that is prefixed with the current date & time */
if (logfile != NULL)
{
char time_string[64];
time_t t = time(NULL);
char* str_time = ctime(&t); /* obtain time as string */
terminated_strncpy(time_string, str_time, sizeof(time_string));
size_t stime = strlen(time_string);
time_string[stime-1] = '\0'; /* remove '\n' from time string */
fprintf(logfile, "[%s] %s\n", time_string, message);
fflush(logfile);
}
}
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/options.h
|
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#ifndef SSH_TUNNELD_OPTIONS_H
#define SSH_TUNNELD_OPTIONS_H
void print_usage(const char* program_name);
struct program_options {
/* Remote details */
char* remote_host;
char* remote_port;
/* Local details */
char* proxy_port;
char* tunnel_port;
/* Logging */
char* log_filename;
/* Option switches */
int nofork;
int accept_remote;
};
void process_options(int argc, char** argv, struct program_options* options);
#endif
|
ajbennieston/ssh-tunnel
|
ssh-tunnelc/ssh-tunnelc.c
|
<reponame>ajbennieston/ssh-tunnel<filename>ssh-tunnelc/ssh-tunnelc.c
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
/* Project headers */
#include "control.h"
#include "options.h"
void sig_handler(int signum);
char* build_host_port(const char* host, const char* port);
void register_signal_handlers();
int main(int argc, char** argv)
{
struct program_options options;
process_arguments(argc, argv, &options);
/* Set tunneld_host to point to proxy_host */
tunneld_host = options.proxy_host;
tunneld_port = options.tunnel_port;
char* proxy_host_port = build_host_port(options.proxy_host,
options.proxy_port);
if (proxy_host_port == NULL)
{
/* malloc() failed */
fprintf(stderr, "Unable to allocate memory. Exiting.\n");
return EXIT_FAILURE;
}
/* Deal with SIGTERM, SIGCHLD, SIGHUP and SIGINT */
register_signal_handlers();
/* Send a message to ssh-tunneld telling it we
* want to open an ssh connection through the tunnel
* While we do this, block SIGINT and SIGTERM so
* the tunneld has a chance of keeping track of state.
*/
sigset_t sigmask;
if ((sigemptyset(&sigmask) == -1)
|| (sigaddset(&sigmask, SIGTERM) == -1)
|| (sigaddset(&sigmask, SIGINT) == -1)
|| sigprocmask(SIG_BLOCK, &sigmask, NULL))
{
perror("Failed to block SIGINT and SIGTERM");
}
connection_start();
if (sigprocmask(SIG_UNBLOCK, &sigmask, NULL) == -1)
{
perror("Failed to unblock SIGINT and SIGTERM");
}
/* fork and execute:
* nc -X 5 -x proxyhost:proxyport host port
*/
pid_t id = fork();
if (id < 0)
{
/* something went wrong... */
fprintf(stderr, "fork() failed.\n");
exit(EXIT_FAILURE);
}
else if (id == 0)
{
/* in child process */
int status = execlp("nc", "nc", "-X", "5", "-x", proxy_host_port,
options.remote_host, options.remote_port, (char *) NULL);
/* if the exec succeeded, we should never get here */
if (status == -1)
{
fprintf(stderr, "Failed to execute nc.\n");
exit(EXIT_FAILURE);
}
}
else
{
/* in parent process; id is the process id
* of the child. Wait for it to finish.
*/
wait(NULL);
if (proxy_host_port != NULL)
free(proxy_host_port);
}
return EXIT_SUCCESS;
}
char* build_host_port(const char* host, const char* port)
{
/* Obtain sufficient memory */
size_t host_len = strlen(host);
size_t port_len = strlen(port);
size_t result_len = host_len + port_len + 2; /* colon and null char */
char* result = malloc(result_len * sizeof(char));
if (result == NULL)
{
/* malloc() failed */
return NULL;
}
/* Build the string "host:port" and ensure that it is null-terminated */
strncpy(result, host, host_len);
result[host_len] = ':';
strncpy(result + host_len + 1, port, port_len);
result[host_len + port_len + 1] = '\0';
return result;
}
void register_signal_handlers()
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sig_handler;
sigaddset(&(sa.sa_mask), SIGTERM);
sigaddset(&(sa.sa_mask), SIGCHLD);
sigaddset(&(sa.sa_mask), SIGHUP);
sigaddset(&(sa.sa_mask), SIGINT);
sa.sa_flags = SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, NULL) != 0)
{
perror("sigaction");
}
if (sigaction(SIGTERM, &sa, NULL) != 0)
{
perror("sigaction");
}
if (sigaction(SIGHUP, &sa, NULL) != 0)
{
perror("sigaction");
}
if (sigaction(SIGINT, &sa, NULL) != 0)
{
perror("sigaction");
}
}
void sig_handler(int signum)
{
switch (signum)
{
case SIGCHLD:
case SIGTERM:
case SIGINT:
case SIGHUP:
connection_stop();
exit(EXIT_SUCCESS);
break;
default:
break;
}
}
|
ajbennieston/ssh-tunnel
|
ssh-tunnelc/control.h
|
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#ifndef SSH_TUNNELC_CONTROL_H
#define SSH_TUNNELC_CONTROL_H
void connection_start(void);
void connection_stop(void);
extern char* tunneld_host;
extern char* tunneld_port;
#endif
|
ajbennieston/ssh-tunnel
|
ssh-tunnelc/control.c
|
<filename>ssh-tunnelc/control.c
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#include "control.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
/* Global variables */
char* tunneld_host;
char* tunneld_port;
/* Internal helper functions - declarations */
int establish_connection(const char* hostname, const char* port);
void send_message(const char* hostname, const char* port, char message);
/* Definitions of functions declared in the header */
void connection_start(void)
{
send_message(tunneld_host, tunneld_port, 'C');
}
void connection_stop(void)
{
send_message(tunneld_host, tunneld_port, 'D');
}
/* Internal helper functions - definitions */
int establish_connection(const char* hostname, const char* port)
{
/*
* Looks up hostname:port and attempts to connect to it.
* Returns a socket descriptor if a successful connection
* was established, or -1 on error.
*/
struct addrinfo hints;
struct addrinfo *result, *rp;
int socket_fd;
int gai_return_value;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
if ((gai_return_value = getaddrinfo(hostname, port, &hints, &result)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_return_value));
exit(EXIT_FAILURE);
}
/*
* Try each address returned by getaddrinfo
* in turn
*/
for(rp = result; rp != NULL; rp = rp->ai_next)
{
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (socket_fd == -1)
continue;
if (connect(socket_fd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Successfully connected */
close(socket_fd);
}
if (rp == NULL)
{
/* no attempt to connect succeeded */
fprintf(stderr, "Could not connect to %s:%s\n", hostname, port);
socket_fd = -1;
}
freeaddrinfo(result); /* no longer need the address structures */
return socket_fd;
}
void send_message(const char* hostname, const char* port, char message)
{
/* Connect to ssh-tunneld and deliver the message
* to either open or close a connection.
* Expect ssh-tunneld to be listening on port 1081.
*/
int sock_fd = establish_connection(hostname, port);
if (sock_fd == -1)
{
fprintf(stderr, "Could not connect to ssh-tunneld running on %s:%s\n", hostname, port);
exit(EXIT_FAILURE);
}
/* now send a message to the ssh-tunneld */
if (send(sock_fd, &message, sizeof(message), 0) != 1)
{
perror("send");
exit(EXIT_FAILURE);
}
/* read the response that tells us when the tunnel is active (or that our disconnect request
* was acknowledge)
*/
char buffer[1];
if (recv(sock_fd, &buffer, sizeof(buffer), 0) != 1)
{
perror("recv");
exit(EXIT_FAILURE);
}
if (buffer[0] != message)
{
fprintf(stderr, "Received incorrect response from ssh-tunneld. Exiting.\n");
exit(EXIT_FAILURE);
}
/* finally close the socket */
close(sock_fd);
}
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/ssh-control.c
|
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#include "ssh-control.h"
#include "logging.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
pid_t start_ssh_tunnel(char* hostname, char* port, char* proxy_port)
{
write_log("Starting ssh process.");
char* argv[] = {
"ssh",
"-T",
"-n",
"-N",
"-D",
proxy_port,
"-p",
port,
hostname,
NULL
};
int process_id = fork();
if (process_id < 0)
{
write_log("Error while trying to fork ssh process. Exiting.");
exit(EXIT_FAILURE);
}
if (process_id == 0)
{
/* In child process, execute ssh */
if(execvp("ssh", argv) == -1)
{
write_log("Error while trying to exec ssh process. Exiting.");
exit(EXIT_FAILURE);
}
}
/* Only get here if we're in the parent process */
return process_id;
}
void stop_ssh_tunnel(pid_t process_id)
{
write_log("Stopping ssh process.");
if(kill(process_id, SIGTERM) != 0)
{
perror("kill");
exit(EXIT_FAILURE);
}
wait(NULL);
}
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/ssh-tunneld.c
|
<reponame>ajbennieston/ssh-tunnel<gh_stars>1-10
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include "logging.h"
#include "options.h"
#include "ssh-control.h"
int tunneld_main(struct program_options* options);
void sig_handler(int signum);
int test_connection(char* proxy_port);
void daemonize(int nofork);
int main(int argc, char** argv)
{
/* Keep the program options together */
struct program_options options;
memset(&options, 0, sizeof(struct program_options));
process_options(argc, argv, &options);
/* open a logfile */
if (options.nofork)
{
logfile = stderr;
}
else if (options.log_filename != NULL)
{
logfile = fopen(options.log_filename, "a");
if (logfile == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
}
else
{
// No log file
logfile = NULL;
}
/* Become a daemon */
daemonize(options.nofork);
/* Set up signal handlers */
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sig_handler;
sigaddset(&(sa.sa_mask), SIGTERM);
if (sigaction(SIGTERM, &sa, NULL) != 0)
{
write_log("Could not set signal handler for SIGTERM. Exiting.");
exit(EXIT_FAILURE);
}
/* Run tunneld_main() */
tunneld_main(&options);
return 0;
}
void sig_handler(int signum)
{
switch(signum)
{
case SIGTERM:
write_log("Received SIGTERM. Stopping.");
kill(0, SIGTERM); /* Send child processes the same signal */
exit(EXIT_SUCCESS);
default:
break;
}
}
int tunneld_main(struct program_options* options)
{
int socket_fd = 0; /* listen on socket_fd... */
int new_fd = 0; /* ... accept new connections -> new_fd */
struct addrinfo *result = 0; /* Structure to hold addresses from getaddrinfo() */
struct addrinfo *rp = 0; /* Pointer for our convenience */
struct addrinfo hints; /* hints to getaddrinfo() */
char buf[1]; /* future-proof; if we have bigger messages we can expand this here */
unsigned int n_connected = 0; /* number of clients using the SSH tunnel */
pid_t ssh_tunnel_process = 0; /* process ID for "ssh -D ..." */
/* Hint that we want to bind to any interface...
* Would be better to bind to local interface only (by default)
*/
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (options->accept_remote)
{
hints.ai_flags = AI_PASSIVE;
}
hints.ai_protocol = 0;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
const int yes = 1;
/* Use the hints to find address(es) to bind to */
int gai_result = 0;
if (options->accept_remote)
{
gai_result = getaddrinfo(NULL, options->tunnel_port, &hints, &result);
}
else
{
gai_result = getaddrinfo("127.0.0.1", options->tunnel_port, &hints, &result);
}
if(gai_result != 0)
{
write_log("Error looking up address. Exiting.");
exit(EXIT_FAILURE);
}
/* Try to bind to an interface on requested port*/
for(rp = result; rp != NULL; rp = rp->ai_next)
{
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (socket_fd == -1)
continue; /* try next address */
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
write_log("Error in setsockopt. Exiting.");
exit(EXIT_FAILURE);
}
if (bind(socket_fd, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* successfully bound */
close(socket_fd);
}
if (rp == NULL)
{
/* no address was successfully bound */
write_log("Error binding to port. Exiting.");
exit(EXIT_FAILURE);
}
freeaddrinfo(result); /* don't need this any more */
/* listen on the port we just bound
* Keep a maximum of 10 pending connections in the "backlog"
*/
if (listen(socket_fd, 10) == -1)
{
write_log("Error listening on port. Exiting.");
exit(EXIT_FAILURE);
}
write_log("tunneld: Started.");
/* now accept connections and deal with them one by one */
while(1)
{
/*
* No need to use select()... accept() blocks until a client connects, and
* the processing time is typically short. In any case, if another client
* connects while we're in the sleep() period waiting for an ssh tunnel,
* we want to wait anyway, rather than creating a second tunnel!
*/
new_fd = accept(socket_fd, NULL, NULL); /* don't care about client address */
if (new_fd == -1)
{
write_log("Error while accepting connection. Continuing.");
continue;
}
/* Read a message from the client to see what it wants us to do */
if(recv(new_fd, buf, 1, 0) != 1)
{
write_log("Received unexpected data. Closing connection.");
close(new_fd);
continue;
}
if (buf[0] == 'C') /* client wants to connect through tunnel */
{
if (n_connected == 0)
{
/* no tunnel exists; start it */
ssh_tunnel_process = start_ssh_tunnel(options->remote_host, options->remote_port, options->proxy_port);
/* Test the connection every second until we
* successfully connect to it
*/
do {
sleep(1);
} while ( test_connection(options->proxy_port) );
}
n_connected += 1;
write_log_connect(n_connected);
/* tell the client it can proceed */
char message = 'C';
send(new_fd, &message, sizeof(message), 0);
}
else if (buf[0] == 'D') /* client telling us it is done with tunnel */
{
n_connected -= 1;
write_log_connect(n_connected);
if (n_connected <= 0)
{
/* nothing using the tunnel any more; stop it. */
n_connected = 0;
stop_ssh_tunnel(ssh_tunnel_process);
ssh_tunnel_process = 0;
}
/* tell the client we acted on their message */
char message = 'D';
send(new_fd, &message, sizeof(message), 0);
}
close(new_fd); /* close client socket */
}
return 0;
}
int test_connection(char* proxy_port)
{
const char* hostname = "127.0.0.1";
struct addrinfo hints;
struct addrinfo *result = 0;
struct addrinfo *rp = 0;
int socket_fd = 0;
int gai_return_value = 0;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
if ((gai_return_value = getaddrinfo(hostname, proxy_port, &hints, &result)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_return_value));
exit(EXIT_FAILURE);
}
/*
* Try each address returned by getaddrinfo
* in turn
*/
for(rp = result; rp != NULL; rp = rp->ai_next)
{
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (socket_fd == -1)
continue;
if (connect(socket_fd, rp->ai_addr, rp->ai_addrlen) != -1)
{
/* Successfully connected */
freeaddrinfo(result);
close(socket_fd);
return 0;
}
close(socket_fd);
}
/* If we got here, we didn't manage to connect successfully */
freeaddrinfo(result); /* no longer need the address structures */
return 1;
}
void daemonize(int nofork)
{
pid_t process_id = 0;
if (! nofork)
process_id = fork();
if (process_id > 0)
{
/* In parent process; exit */
_exit(EXIT_SUCCESS);
}
else if (process_id < 0)
{
/* Something went wrong */
perror("fork");
exit(EXIT_FAILURE);
}
/* If we get here, we're in the child process,
* or no fork was requested. Now do some other
* things to play nicely with others.
*/
/* Become the session leader if we forked */
if (! nofork)
{
pid_t session_id = setsid();
if (session_id < 0)
{
write_log("Could not create session. Exiting.");
exit(EXIT_FAILURE);
}
}
umask(077); /* set umask to sensible default */
/* Change the working directory */
if (chdir("/") < 0)
{
write_log("Could not change directory to /. Exiting.");
exit(EXIT_FAILURE);
}
/* Close standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
if (! nofork)
close(STDERR_FILENO);
}
|
ajbennieston/ssh-tunnel
|
ssh-tunnelc/options.c
|
<filename>ssh-tunnelc/options.c
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#define _POSIX_C_SOURCE 200809L
#include "options.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *checked_strdup(const char *s)
{
/* Wrap strdup() and check for NULL return value,
* indicating that memory allocation failed. */
char *duplicate = strdup(s); /* NULL check follows */
if (duplicate == NULL)
{
fprintf(stderr, "Unable to allocate memory. Exiting.\n");
exit(EXIT_FAILURE);
}
return duplicate;
}
void print_usage(const char* program_name)
{
fprintf(stderr,
"Usage:\n %s [-h hostname] [-p port] [-t port] ssh_hostname ssh_port\n\n", program_name);
fprintf(stderr,
" -h hostname\n SOCKS5 proxy and ssh-tunneld hostname.\n Default: 127.0.0.1.\n\n");
fprintf(stderr,
" -p port\n SOCKS5 proxy port.\n Default: 1080.\n\n");
fprintf(stderr,
" -t port\n ssh-tunneld control port.\n Default: 1081.\n\n");
}
void process_arguments(int argc, char** argv, struct program_options* options)
{
/*
* Usage: progname [-h hostname] [-p port] [-t port] ssh_hostname ssh_port
*
* Options:
* -h hostname
* sets proxy_host : hostname of both the SOCKS5 proxy *and* the ssh-tunneld process
* -p port
* sets proxy_port : port for the SOCKS5 proxy
* -t port
* sets tun_port : port for the ssh-tunneld process
*
* ssh_hostname and ssh_port are set from the remaining values of argv after option
* processing has completed. These must always be present.
*/
int opt;
int set_proxy_host = 0;
int set_proxy_port = 0;
int set_tun_port = 0;
while ((opt = getopt(argc, argv, "h:p:t:")) != -1)
{
switch (opt)
{
case 'h':
/* Set proxy host */
if (! set_proxy_host)
{
options->proxy_host = optarg;
set_proxy_host = 1;
}
break;
case 'p':
if (! set_proxy_port)
{
options->proxy_port = optarg;
set_proxy_port = 1;
}
break;
case 't':
if (! set_tun_port)
{
options->tunnel_port = optarg;
set_tun_port = 1;
}
break;
default:
print_usage(argv[0]);
exit(EXIT_FAILURE);
break;
}
}
if (optind + 2 > argc)
{
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
/* The remaining options should now be the ssh host and port */
options->remote_host = argv[optind];
options->remote_port = argv[optind+1];
/* And set default values if we didn't receive them from the options */
if (! set_proxy_host)
{
char* default_proxy_host = "127.0.0.1";
options->proxy_host = checked_strdup(default_proxy_host);
}
if (! set_proxy_port)
{
char* default_proxy_port = "1080";
options->proxy_port = checked_strdup(default_proxy_port);
}
if (! set_tun_port)
{
char* default_tun_port = "1081";
options->tunnel_port = checked_strdup(default_tun_port);
}
}
|
ajbennieston/ssh-tunnel
|
ssh-tunneld/options.c
|
<filename>ssh-tunneld/options.c
/*
* This file is part of ssh-tunnel.
* See the LICENSE file in the top-level directory
* of the source distribution for further details.
*/
#define _XOPEN_SOURCE 500
#define _POSIX_C_SOURCE 200112L
#include "options.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *checked_strdup(const char *s)
{
/* Wrap strdup() and check for NULL return value,
* indicating that memory allocation failed. */
char *duplicate = strdup(s); /* NULL check follows */
if (duplicate == NULL)
{
fprintf(stderr, "Unable to allocate memory. Exiting.\n");
exit(EXIT_FAILURE);
}
return duplicate;
}
void print_usage(const char* program_name)
{
fprintf(stderr,
"Usage:\n %s [-d port] [-f] [-l file] [-p port] [-r] [-t port] hostname\n\n",
program_name);
fprintf(stderr,
" -d port\n Local port for SSH SOCKS5 proxy.\n Default: 1080.\n\n");
fprintf(stderr,
" -f\n Don't fork. Remain attached to terminal and log to stderr.\n\n");
fprintf(stderr,
" -l file\n Append log messages to file.\n\n");
fprintf(stderr,
" -p port\n Remote port for SSH connection.\n Default: 22.\n\n");
fprintf(stderr,
" -r\n Accept remote connections on control port.\n Default: Accept only local connections.\n\n");
fprintf(stderr,
" -t port\n Local port to listen on for control connections.\n Default: 1081.\n\n");
}
void process_options(int argc, char** argv, struct program_options* options)
{
/*
* Usage:
* progname [-f] [-d port] [-l logfile] [-p port] [-r] [-t port] hostname
*
* Options:
* -d port
* Local port to use for SOCKS5 proxy (ssh -D port)
* -f
* Don't fork; stays attached to terminal and logs to stderr
* -l logfile
* Append log messages to the filename specified.
* Ignored if -f was given.
* -p port
* Remote port for ssh -D
* -r
* Accept remote connections on the control port
* Default: Accept only local connections
* -t port
* Local port to use for control connections
*
* hostname must be specified. Default options as follows:
* proxy port : 1080
* logfile : none
* tunneld port : 1081
* remote port : 22
*
* The default behaviour is to fork and detach from the
* controlling terminal. Only the first occurrence of an
* option argument will be used.
*/
int opt;
/* Set defaults */
options->nofork = 0;
options->accept_remote = 0;
options->proxy_port = NULL;
options->log_filename = NULL;
options->remote_port = NULL;
options->tunnel_port = NULL;
options->remote_host = NULL;
while ((opt = getopt(argc, argv, "d:fl:p:rt:")) != -1)
{
switch(opt)
{
case 'd': /* local proxy port */
if (options->proxy_port == NULL)
options->proxy_port = optarg;
break;
case 'f': /* nofork */
options->nofork = 1;
break;
case 'l': /* log filename */
if (options->log_filename == NULL)
options->log_filename = optarg;
break;
case 'p': /* remote port */
if (options->remote_port == NULL)
options->remote_port = optarg;
break;
case 'r':
options->accept_remote = 1;
break;
case 't': /* tunneld port */
if (options->tunnel_port == NULL)
options->tunnel_port = optarg;
break;
default:
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (optind + 1 > argc)
{
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
options->remote_host = argv[optind];
/* Set default values */
if (options->proxy_port == NULL)
{
char* default_proxy_port = "1080";
options->proxy_port = checked_strdup(default_proxy_port);
}
if (options->remote_port == NULL)
{
char* default_remote_port = "22";
options->remote_port = checked_strdup(default_remote_port);
}
if (options->tunnel_port == NULL)
{
char* default_tun_port = "1081";
options->tunnel_port = checked_strdup(default_tun_port);
}
}
|
zj-insist/QSCommonViews
|
QSCommonViews/Classes/QSAlertView.h
|
//
// QSAlertView.h
// Pods-QSCommonViews_Example
//
// Created by ZJ-Jie on 2017/12/1.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, QSAlertButtonStyle) {
QSAlertButtonStyleCancel,
QSAlertButtonStyleImport,
QSAlertButtonStyleNormal
};
@interface QSAlertButton : UIButton
+ (instancetype)createAlertButtonWithTitle:(NSString *)title action:(dispatch_block_t)action;
+ (instancetype)createAlertButtonWithTitle:(NSString *)title style:(QSAlertButtonStyle)style action:(dispatch_block_t)action;
@end
@interface QSAlertView : UIView
+ (instancetype)createAlertWithTitle:(NSString *)title message:(NSString *)message cancelButton:(QSAlertButton *)cancel otherButtons:(QSAlertButton *)otherButtons, ...;
- (void)show;
@end
|
zj-insist/QSCommonViews
|
Example/Pods/Target Support Files/QSCommonViews/QSCommonViews-umbrella.h
|
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "QSAlertView.h"
#import "QSAlertViewsMacro.h"
#import "QSCommonViews.h"
#import "UIView+Tools.h"
FOUNDATION_EXPORT double QSCommonViewsVersionNumber;
FOUNDATION_EXPORT const unsigned char QSCommonViewsVersionString[];
|
zj-insist/QSCommonViews
|
QSCommonViews/Classes/QSCommonViews.h
|
<gh_stars>0
//
// QSCommonViews.h
// Pods
//
// Created by ZJ-Jie on 2017/12/1.
//
#import <Foundation/Foundation.h>
#if __has_include(<QSCommonViews/QSCommonViews.h>)
#import <QSCommonViews/QSAlertView.h>
#else
#import "QSAlertView.h"
#endif
|
zj-insist/QSCommonViews
|
Example/QSCommonViews/QSViewController.h
|
<reponame>zj-insist/QSCommonViews<gh_stars>0
//
// QSViewController.h
// QSCommonViews
//
// Created by <EMAIL> on 12/01/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface QSViewController : UIViewController
@end
|
zj-insist/QSCommonViews
|
QSCommonViews/Classes/QSAlertViewsMacro.h
|
<gh_stars>0
//
// QSAlertViewsMacro.h
// Pods
//
// Created by ZJ-Jie on 2017/12/1.
//
#ifndef QSAlertViewsMacro_h
#define QSAlertViewsMacro_h
//屏幕信息
#define Screen_Bounds [UIScreen mainScreen].bounds
#define Screen_Height [UIScreen mainScreen].bounds.size.height
#define Screen_Width [UIScreen mainScreen].bounds.size.width
#define Screen_Scale [UIScreen mainScreen].scale
//缩放比例
#define ratio2_scale (Screen_Width/375.f)
#define UIScale(x) ((x)*ratio2_scale)
#define UIScaleHeight(x) ((x)*Screen_Height/667.f)
// RGB颜色
#define RGBCOLOR(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
#define HEXRGBCOLOR(h) RGBCOLOR(((h>>16)&0xFF), ((h>>8)&0xFF), (h&0xFF))
#define HEXRGBACOLOR(h,a) RGBACOLOR(((h>>16)&0xFF), ((h>>8)&0xFF), (h&0xFF), a)
#define kKeyWindow [UIApplication sharedApplication].keyWindow
#endif /* QSAlertViewsMacro_h */
|
zj-insist/QSCommonViews
|
Example/QSCommonViews/QSAppDelegate.h
|
//
// QSAppDelegate.h
// QSCommonViews
//
// Created by <EMAIL> on 12/01/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface QSAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
melton1968/uSockets
|
tests/sni_test.c
|
<reponame>melton1968/uSockets
extern "C" {
void *sni_new();
void sni_free(void *sni, void (*cb)(void *user));
int sni_add(void *sni, const char *hostname, void *user);
void *sni_remove(void *sni, const char *hostname);
void *sni_find(void *sni, const char *hostname);
}
#include <assert.h>
#include <stdio.h>
/* Todo: replace 13, 14 and 15 with malloc */
//void *WILDCARD_GOOGLE_COM = strdup("*.google.com");
//void *TEST_GOOGLE_COM = strdup("test.google.com");
void sni_free_cb(void *user) {
printf("Freeing %p\n", user);
}
int main() {
void *sni = sni_new();
/* Adding should succeed */
assert(sni_add(sni, "*.google.com", 13) == 0);
assert(sni_add(sni, "test.google.com", 14) == 0);
/* Adding the same name should not overwrite existing */
assert(sni_add(sni, "*.google.com", 15) != 0);
assert(sni_find(sni, "anything.google.com") == 13);
assert(sni_find(sni, "docs.google.com") == 13);
assert(sni_find(sni, "*.google.com") == 13);
assert(sni_find(sni, "test.google.com") == 14);
assert(sni_find(sni, "yolo.nothing.com") == 0);
assert(sni_find(sni, "yolo.google.com") == 13);
/* Removing should work */
assert(sni_remove(sni, "test.google.com") == 14);
assert(sni_find(sni, "test.google.com") == 13);
assert(sni_remove(sni, "*.google.com") == 13);
assert(sni_find(sni, "test.google.com") == 0);
/* Removing parent with data should not remove child with data */
assert(sni_add(sni, "www.google.com", 16) == 0);
assert(sni_add(sni, "www.google.com.au.ck.uk", 17) == 0);
assert(sni_find(sni, "www.google.com") == 16);
assert(sni_find(sni, "www.google.com.au.ck.uk") == 17);
assert(sni_remove(sni, "www.google.com.yolo") == 0);
assert(sni_remove(sni, "www.google.com.au.ck.uk") == 17);
assert(sni_find(sni, "www.google.com") == 16);
/* Free should not leave anything remaining (test with ASAN leaksanitizer) */
sni_free(sni, sni_free_cb);
printf("OK\n");
}
|
lbruun/netbeans-profiler
|
profiler/lib.profiler/native/src-jdk15/config.c
|
#include <stdio.h>
#include "jni.h"
int main(int argc, char* argv[]) {
if (sizeof(jint) == sizeof(jmethodID)) {
puts("#undef NEEDS_CONVERSION");
} else {
puts("#define NEEDS_CONVERSION");
}
return 0;
}
|
guaraqe/qhull-simple
|
foreign-src/qhull_wrapper.c
|
<filename>foreign-src/qhull_wrapper.c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <libqhull/libqhull.h>
#include <libqhull/qset.h>
#include <libqhull/poly.h>
#include <pthread.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "qhull_wrapper.h"
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static char *outbuf = NULL;
static size_t outbuf_size = 0;
static char *errbuf = NULL;
static size_t errbuf_size = 0;
static FILE *outfile = NULL;
static FILE *errfile = NULL;
static bool initialized = 0;
int qhull_wrapper(int d, int m, double *indata, char *cmd, int *n, int **outdata, char **errmsg)
{
int lock_ret;
#ifdef NDEBUG
lock_ret = pthread_mutex_lock(&lock);
#else
lock_ret = pthread_mutex_trylock(&lock);
if (lock_ret == EBUSY)
{
printf("qhull_wrapper.c: Lock busy. Waiting.\n");
lock_ret = pthread_mutex_lock(&lock);
}
#endif
if (lock_ret)
return lock_ret;
#ifndef NDEBUG
printf("qhull_wrapper.c: Lock obtained.\n");
#endif
if (!initialized)
{
#ifdef NDEBUG
outfile = open_memstream(&outbuf, &outbuf_size);
errfile = open_memstream(&errbuf, &errbuf_size);
#else
printf("qhull_wrapper.c: Initializing.\n");
printf("qhull_wrapper.c: Note: In debug mode, so error messages will not be relayed to Haskell, but instead go straight to stdout and stderr.\n");
outfile = stdout;
errfile = stderr;
#endif
initialized = true;
}
int code = qh_new_qhull(d, m, indata, 0, cmd, outfile, errfile);
if (code)
{
#ifdef NDEBUG
fflush(errfile); // Makes errbuf_size valid.
//fflush(outfile); // Makes outbuf_size valid.
//*outmsg = (char *)malloc(outbuf_size+1); // We're not saving the out message afterall.
*errmsg = (char *)malloc(errbuf_size+1);
//memcpy(*outmsg, outbuf, outbuf_size);
//(*outmsg)[outbuf_size] = '\0';
memcpy(*errmsg, errbuf, errbuf_size);
(*errmsg)[errbuf_size] = '\0';
rewind(outfile);
rewind(errfile);
#else
printf("qhull_wrapper.c: qh_new_qhull failed with code %d.\n", code);
#endif
cleanup();
return code;
}
*n = qh num_facets;
*outdata = (int *)malloc((d+1)*(*n)*sizeof(int)); // We're assuming the "Qt" option so that facets are triangulated.
//*k = (int *)malloc((*n)*sizeof(int)); // Not needed when triangulating.
facetT *facet;
int i = 0;
FORALLfacets
{
if (!(facet->upperdelaunay)){
//printf("toporient=%d orientCLOCK=%d\n", facet->toporient, qh_ORIENTclock);
vertexT *vertex, **vertexp;
int j = 0;
if (!(facet->toporient) != (!qh_ORIENTclock)) // Only do if toporiented OR clockwise oriented.
{
FOREACHvertex_ (facet->vertices)
{
(*outdata)[(d+1)*i + j] = qh_pointid(vertex->point);
j++;
}
}
else
{
FOREACHvertexreverse12_ (facet->vertices)
{
(*outdata)[(d+1)*i + j] = qh_pointid(vertex->point);
j++;
}
}
/*
(*k)[i] = j;
while (j <= d)
{
(*outdata)[(d+1)*i + j] = -1;
j++;
}
*/
#ifndef NDEBUG
if (j < d)
printf("qhull_wrapper.c: Facet %d only has %d vertices. Expected %d.\n", i, j, d);
#endif
i++;
}
*n = i;
}
#ifndef NDEBUG
if (i < *n)
printf("qhull_wrapper.c: Only saw %d facets. Expected %d.\n", i, *n);
#endif
cleanup();
return 0;
}
void cleanup()
{
qh_freeqhull(!qh_ALL);
int freecurlong, freetotlong;
qh_memfreeshort(&freecurlong, &freetotlong);
#ifndef NDEBUG
if (freecurlong || freetotlong)
printf("qhull_wrapper.c: Failed to free %d bytes of memory.\n", freetotlong);
#endif
pthread_mutex_unlock(&lock);
}
|
guaraqe/qhull-simple
|
foreign-src/qhull_wrapper.h
|
<gh_stars>0
#pragma once
#include <stdbool.h>
int qhull_wrapper(int d, int m, double *indata, char *cmd, int *n, int **outdata, char **errmsg);
void cleanup();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.