blob: 95d31300c40159d1f9c5c904526c57372c23da8f [file] [log] [blame]
Zhenkai Zhu1ddeb6f2012-12-27 14:04:18 -08001#include "ccnx-wrapper.h"
2#include <poll.h>
3#include <boost/throw_exception.hpp>
4#include <boost/date_time/posix_time/posix_time.hpp>
5#include <boost/random.hpp>
6#include <sstream>
7
8typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
9typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int;
10
11using namespace std;
12using namespace boost;
13
14namespace Ccnx {
15
16ContentObject::ContentObject(const char *data, size_t len)
17{
18 m_data = new char[len];
19 m_len = len;
20 memcpy(m_data, data, len);
21}
22
23ContentObject::~ContentObject()
24{
25 delete m_data;
26}
27
28void
29ContentObject::dup(char **data, size_t *len)
30{
31 char *tmp = new char[m_len];
32 memcpy(tmp, m_data, m_len);
33 (*data) = tmp;
34 (*len) = m_len;
35}
36
37CcnxWrapper::CcnxWrapper()
38 : m_handle (0)
39 , m_keyStore (0)
40 , m_keyLoactor (0)
41 , m_running (true)
42 , m_connected (false)
43{
44 connectCcnd();
45 initKeyStore ();
46 createKeyLocator ();
47 m_thread = thread (&CcnxWrapper::ccnLoop, this);
48}
49
50void
51CcnxWrapper::connectCcnd()
52{
53 recursive_mutex::scoped_lock lock (m_mutex);
54
55 if (m_handle != 0) {
56 ccn_disconnect (m_handle);
57 ccn_destroy (&m_handle);
58 }
59
60 m_handle = ccn_create ();
61 if (ccn_connect(m_handle, NULL) < 0)
62 {
63 BOOST_THROW_EXCEPTION (CcnxOperationException() << errmsg_info_str("connection to ccnd failed"));
64 }
65 m_connected = true;
66
67 if (!m_registeredInterests.empty())
68 {
69 for (map<std::string, InterestCallback>::const_iterator it = m_registeredInterests.begin(); it != m_registeredInterests.end(); ++it)
70 {
71 // clearInterestFilter(it->first);
72 setInterestFilter(it->first, it->second);
73 }
74 }
75}
76
77CcnxWrapper::~CcnxWrapper()
78{
79 {
80 recursive_mutex::scoped_lock lock(m_mutex);
81 m_running = false;
82 }
83
84 m_thread.join ();
85 ccn_disconnect (m_handle);
86 ccn_destroy (&m_handle);
87 ccn_charbuf_destroy (&m_keyLoactor);
88 ccn_keystore_destroy (&m_keyStore);
89}
90
91void
92CcnxWrapper::createKeyLocator ()
93{
94 m_keyLoactor = ccn_charbuf_create();
95 ccn_charbuf_append_tt (m_keyLoactor, CCN_DTAG_KeyLocator, CCN_DTAG);
96 ccn_charbuf_append_tt (m_keyLoactor, CCN_DTAG_Key, CCN_DTAG);
97 int res = ccn_append_pubkey_blob (m_keyLoactor, ccn_keystore_public_key(m_keyStore));
98 if (res >= 0)
99 {
100 ccn_charbuf_append_closer (m_keyLoactor); /* </Key> */
101 ccn_charbuf_append_closer (m_keyLoactor); /* </KeyLocator> */
102 }
103}
104
105const ccn_pkey*
106CcnxWrapper::getPrivateKey ()
107{
108 return ccn_keystore_private_key (m_keyStore);
109}
110
111const unsigned char*
112CcnxWrapper::getPublicKeyDigest ()
113{
114 return ccn_keystore_public_key_digest(m_keyStore);
115}
116
117ssize_t
118CcnxWrapper::getPublicKeyDigestLength ()
119{
120 return ccn_keystore_public_key_digest_length(m_keyStore);
121}
122
123void
124CcnxWrapper::initKeyStore ()
125{
126 m_keyStore = ccn_keystore_create ();
127 string keyStoreFile = string(getenv("HOME")) + string("/.ccnx/.ccnx_keystore");
128 if (ccn_keystore_init (m_keyStore, (char *)keyStoreFile.c_str(), (char*)"Th1s1sn0t8g00dp8ssw0rd.") < 0)
129 BOOST_THROW_EXCEPTION(CcnxOperationException() << errmsg_info_str(keyStoreFile.c_str()));
130}
131
132void
133CcnxWrapper::ccnLoop ()
134{
135 static boost::mt19937 randomGenerator (static_cast<unsigned int> (std::time (0)));
136 static boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rangeUniformRandom (randomGenerator, uniform_int<> (0,1000));
137
138 while (m_running)
139 {
140 try
141 {
142 int res = 0;
143 {
144 recursive_mutex::scoped_lock lock (m_mutex);
145 res = ccn_run (m_handle, 0);
146 }
147
148 if (!m_running) break;
149
150 if (res < 0)
151 BOOST_THROW_EXCEPTION (CcnxOperationException()
152 << errmsg_info_str("ccn_run returned error"));
153
154
155 pollfd pfds[1];
156 {
157 recursive_mutex::scoped_lock lock (m_mutex);
158
159 pfds[0].fd = ccn_get_connection_fd (m_handle);
160 pfds[0].events = POLLIN;
161 if (ccn_output_is_pending (m_handle))
162 pfds[0].events |= POLLOUT;
163 }
164
165 int ret = poll (pfds, 1, 1);
166 if (ret < 0)
167 {
168 BOOST_THROW_EXCEPTION (CcnxOperationException() << errmsg_info_str("ccnd socket failed (probably ccnd got stopped)"));
169 }
170 }
171 catch (CcnxOperationException &e)
172 {
173 // do not try reconnect for now
174 throw e;
175 /*
176 m_connected = false;
177 // probably ccnd has been stopped
178 // try reconnect with sleep
179 int interval = 1;
180 int maxInterval = 32;
181 while (m_running)
182 {
183 try
184 {
185 this_thread::sleep (boost::get_system_time () + TIME_SECONDS(interval) + TIME_MILLISECONDS (rangeUniformRandom ()));
186
187 connectCcnd();
188 _LOG_DEBUG("reconnect to ccnd succeeded");
189 break;
190 }
191 catch (CcnxOperationException &e)
192 {
193 this_thread::sleep (boost::get_system_time () + TIME_SECONDS(interval) + TIME_MILLISECONDS (rangeUniformRandom ()));
194
195 // do exponential backup for reconnect interval
196 if (interval < maxInterval)
197 {
198 interval *= 2;
199 }
200 }
201 }
202 */
203 }
204 catch (const std::exception &exc)
205 {
206 // catch anything thrown within try block that derives from std::exception
207 std::cerr << exc.what();
208 }
209 catch (...)
210 {
211 cout << "UNKNOWN EXCEPTION !!!" << endl;
212 }
213 }
214}
215
216
217ContentObjectPtr
218CcnxWrapper::createContentObject(const std::string &name, const char *buf, size_t len, int freshness)
219{
220 ccn_charbuf *pname = ccn_charbuf_create();
221 ccn_charbuf *signed_info = ccn_charbuf_create();
222 ccn_charbuf *content = ccn_charbuf_create();
223
224 ccn_name_from_uri(pname, name.c_str());
225 ccn_signed_info_create(signed_info,
226 getPublicKeyDigest(),
227 getPublicKeyDigestLength(),
228 NULL,
229 CCN_CONTENT_DATA,
230 freshness,
231 NULL,
232 m_keyLoactor);
233 if(ccn_encode_ContentObject(content, pname, signed_info,
234 (const unsigned char *)buf, len,
235 NULL, getPrivateKey()) < 0)
236 {
237 // BOOST_THROW_EXCEPTION(CcnxOperationException() << errmsg_info_str("encode content failed"));
238 }
239
240 ContentObjectPtr co(new ContentObject((const char*)content->buf, content->length));
241
242 ccn_charbuf_destroy (&pname);
243 ccn_charbuf_destroy (&signed_info);
244 ccn_charbuf_destroy (&content);
245
246 return co;
247}
248
249int
250CcnxWrapper::putToCcnd (ContentObjectPtr co)
251{
252 recursive_mutex::scoped_lock lock(m_mutex);
253 if (!m_running || !m_connected)
254 return -1;
255
256
257 if (ccn_put(m_handle, co->m_data, co->m_len) < 0)
258 {
259 // BOOST_THROW_EXCEPTION(CcnxOperationException() << errmsg_info_str("ccnput failed"));
260 }
261
262 return 0;
263}
264
265int
266CcnxWrapper::publishData (const string &name, const char *buf, size_t len, int freshness)
267{
268 ContentObjectPtr co = createContentObject(name, buf, len, freshness);
269 return putToCcnd(co);
270}
271
272std::string
273CcnxWrapper::getInterestName(ccn_upcall_info *info)
274{
275 ostringstream interest (ostringstream::out);
276 for (int i = 0; i < info->interest_comps->n - 1; i++)
277 {
278 char *comp;
279 size_t size;
280 interest << "/";
281 ccn_name_comp_get(info->interest_ccnb, info->interest_comps, i, (const unsigned char **)&comp, &size);
282 string compStr(comp, size);
283 interest << compStr;
284 }
285
286 return interest.str();
287}
288
289std::string
290CcnxWrapper::getDataName(ccn_upcall_info *info)
291{
292 ostringstream name (ostringstream::out);
293 for (int i = 0; i < info->content_comps->n - 1; i++)
294 {
295 char *comp;
296 size_t size;
297 name << "/";
298 ccn_name_comp_get(info->content_ccnb, info->content_comps, i, (const unsigned char **)&comp, &size);
299 string compStr(comp, size);
300 name << compStr;
301 }
302
303 return name.str();
304}
305
306int
307CcnxWrapper::getContentFromContentObject(ContentObjectPtr co, char **content, size_t *len)
308{
309 struct ccn_parsed_ContentObject pco;
310 struct ccn_indexbuf *comps = ccn_indexbuf_create();
311 int res1 = ccn_parse_ContentObject((const unsigned char *)co->m_data, co->m_len, &pco, comps);
312 int res2;
313
314 if (res1 >= 0)
315 {
316 res2 = ccn_content_get_value((const unsigned char *)co->m_data, pco.offset[CCN_PCO_E], &pco, (const unsigned char **)content, len);
317 }
318
319 ccn_indexbuf_destroy(&comps);
320
321 return (res1 < res2) ? res1 : res2;
322}
323
324static ccn_upcall_res
325incomingInterest(ccn_closure *selfp,
326 ccn_upcall_kind kind,
327 ccn_upcall_info *info)
328{
329 CcnxWrapper::InterestCallback *f = static_cast<CcnxWrapper::InterestCallback*> (selfp->data);
330
331 switch (kind)
332 {
333 case CCN_UPCALL_FINAL: // effective in unit tests
334 delete f;
335 delete selfp;
336 return CCN_UPCALL_RESULT_OK;
337
338 case CCN_UPCALL_INTEREST:
339 break;
340
341 default:
342 return CCN_UPCALL_RESULT_OK;
343 }
344
345 string interest = CcnxWrapper::getInterestName(info);
346
347 (*f) (interest);
348 return CCN_UPCALL_RESULT_OK;
349}
350
351static ccn_upcall_res
352incomingData(ccn_closure *selfp,
353 ccn_upcall_kind kind,
354 ccn_upcall_info *info)
355{
356 ClosurePass *cp = static_cast<ClosurePass *> (selfp->data);
357
358 switch (kind)
359 {
360 case CCN_UPCALL_FINAL: // effecitve in unit tests
361 delete cp;
362 cp = NULL;
363 delete selfp;
364 return CCN_UPCALL_RESULT_OK;
365
366 case CCN_UPCALL_CONTENT:
367 break;
368
369 case CCN_UPCALL_INTEREST_TIMED_OUT: {
370 if (cp != NULL && cp->getRetry() > 0) {
371 cp->decRetry();
372 return CCN_UPCALL_RESULT_REEXPRESS;
373 }
374
375 string interest = CcnxWrapper::getInterestName(info);
376 CcnxWrapper::TimeoutCallbackReturnValue rv = cp->runTimeoutCallback(interest);
377 switch(rv)
378 {
379 case CcnxWrapper::RESULT_OK : return CCN_UPCALL_RESULT_OK;
380 case CcnxWrapper::RESULT_REEXPRESS : return CCN_UPCALL_RESULT_REEXPRESS;
381 default : break;
382 }
383 return CCN_UPCALL_RESULT_OK;
384 }
385
386 default:
387 return CCN_UPCALL_RESULT_OK;
388 }
389
390 char *pcontent;
391 size_t len;
392 if (ccn_content_get_value(info->content_ccnb, info->pco->offset[CCN_PCO_E], info->pco, (const unsigned char **)&pcontent, &len) < 0)
393 {
394 // BOOST_THROW_EXCEPTION(CcnxOperationException() << errmsg_info_str("decode ContentObject failed"));
395 }
396
397 string name = CcnxWrapper::getDataName(info);
398
399 cp->runCallback(name, pcontent, len);
400
401 return CCN_UPCALL_RESULT_OK;
402}
403
404
405int CcnxWrapper::sendInterest (const string &strInterest, const DataCallback &dataCallback, int retry, const TimeoutCallback &timeoutCallback)
406{
407 ClosurePass * pass = new ClosurePass(retry, dataCallback, timeoutCallback);
408 sendInterest(strInterest, pass);
409}
410
411int CcnxWrapper::sendInterest (const string &strInterest, void *dataPass)
412{
413 recursive_mutex::scoped_lock lock(m_mutex);
414 if (!m_running || !m_connected)
415 return -1;
416
417 ccn_charbuf *pname = ccn_charbuf_create();
418 ccn_closure *dataClosure = new ccn_closure;
419
420 ccn_name_from_uri (pname, strInterest.c_str());
421 dataClosure->data = dataPass;
422
423 dataClosure->p = &incomingData;
424 if (ccn_express_interest (m_handle, pname, dataClosure, NULL) < 0)
425 {
426 }
427
428 ccn_charbuf_destroy (&pname);
429 return 0;
430}
431
432int CcnxWrapper::setInterestFilter (const string &prefix, const InterestCallback &interestCallback)
433{
434 recursive_mutex::scoped_lock lock(m_mutex);
435 if (!m_running || !m_connected)
436 return -1;
437
438 ccn_charbuf *pname = ccn_charbuf_create();
439 ccn_closure *interestClosure = new ccn_closure;
440
441 ccn_name_from_uri (pname, prefix.c_str());
442 interestClosure->data = new InterestCallback (interestCallback); // should be removed when closure is removed
443 interestClosure->p = &incomingInterest;
444 int ret = ccn_set_interest_filter (m_handle, pname, interestClosure);
445 if (ret < 0)
446 {
447 }
448
449 m_registeredInterests.insert(pair<std::string, InterestCallback>(prefix, interestCallback));
450 ccn_charbuf_destroy(&pname);
451}
452
453void
454CcnxWrapper::clearInterestFilter (const std::string &prefix)
455{
456 recursive_mutex::scoped_lock lock(m_mutex);
457 if (!m_running || !m_connected)
458 return;
459
460 ccn_charbuf *pname = ccn_charbuf_create();
461
462 ccn_name_from_uri (pname, prefix.c_str());
463 int ret = ccn_set_interest_filter (m_handle, pname, 0);
464 if (ret < 0)
465 {
466 }
467
468 m_registeredInterests.erase(prefix);
469 ccn_charbuf_destroy(&pname);
470}
471
472string
473CcnxWrapper::getLocalPrefix ()
474{
475 struct ccn * tmp_handle = ccn_create ();
476 int res = ccn_connect (tmp_handle, NULL);
477 if (res < 0)
478 {
479 return "";
480 }
481
482 string retval = "";
483
484 struct ccn_charbuf *templ = ccn_charbuf_create();
485 ccn_charbuf_append_tt(templ, CCN_DTAG_Interest, CCN_DTAG);
486 ccn_charbuf_append_tt(templ, CCN_DTAG_Name, CCN_DTAG);
487 ccn_charbuf_append_closer(templ); /* </Name> */
488 // XXX - use pubid if possible
489 ccn_charbuf_append_tt(templ, CCN_DTAG_MaxSuffixComponents, CCN_DTAG);
490 ccnb_append_number(templ, 1);
491 ccn_charbuf_append_closer(templ); /* </MaxSuffixComponents> */
492 ccnb_tagged_putf(templ, CCN_DTAG_Scope, "%d", 2);
493 ccn_charbuf_append_closer(templ); /* </Interest> */
494
495 struct ccn_charbuf *name = ccn_charbuf_create ();
496 res = ccn_name_from_uri (name, "/local/ndn/prefix");
497 if (res < 0) {
498 }
499 else
500 {
501 struct ccn_fetch *fetch = ccn_fetch_new (tmp_handle);
502
503 struct ccn_fetch_stream *stream = ccn_fetch_open (fetch, name, "/local/ndn/prefix",
504 NULL, 4, CCN_V_HIGHEST, 0);
505 if (stream == NULL) {
506 }
507 else
508 {
509 ostringstream os;
510
511 int counter = 0;
512 char buf[256];
513 while (true) {
514 res = ccn_fetch_read (stream, buf, sizeof(buf));
515
516 if (res == 0) {
517 break;
518 }
519
520 if (res > 0) {
521 os << string(buf, res);
522 } else if (res == CCN_FETCH_READ_NONE) {
523 if (counter < 2)
524 {
525 ccn_run(tmp_handle, 1000);
526 counter ++;
527 }
528 else
529 {
530 break;
531 }
532 } else if (res == CCN_FETCH_READ_END) {
533 break;
534 } else if (res == CCN_FETCH_READ_TIMEOUT) {
535 break;
536 } else {
537 break;
538 }
539 }
540 retval = os.str ();
541 stream = ccn_fetch_close(stream);
542 }
543 fetch = ccn_fetch_destroy(fetch);
544 }
545
546 ccn_charbuf_destroy (&name);
547
548 ccn_disconnect (tmp_handle);
549 ccn_destroy (&tmp_handle);
550
551 return retval;
552}
553
554
555ClosurePass::ClosurePass(int retry, const CcnxWrapper::DataCallback &dataCallback, const CcnxWrapper::TimeoutCallback &timeoutCallback)
556 : m_retry(retry), m_timeoutCallback(NULL)
557{
558 m_timeoutCallback = new CcnxWrapper::TimeoutCallback (timeoutCallback);
559 m_dataCallback = new CcnxWrapper::DataCallback (dataCallback);
560}
561
562ClosurePass::~ClosurePass ()
563{
564 delete m_dataCallback;
565 delete m_timeoutCallback;
566 m_dataCallback = NULL;
567 m_timeoutCallback = NULL;
568}
569
570CcnxWrapper::TimeoutCallbackReturnValue
571ClosurePass::runTimeoutCallback(std::string interest)
572{
573 if ((*m_timeoutCallback).empty())
574 {
575 return CcnxWrapper::RESULT_OK;
576 }
577
578 return (*m_timeoutCallback)(interest);
579}
580
581
582void
583ClosurePass::runCallback(std::string name, const char *data, size_t len)
584{
585 if (m_callback != NULL) {
586 (*m_callback)(name, data, len);
587 }
588}
589
590}