data.cc 19.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

#include "data.h"

#include <cstdio>
#include <iostream>
#include <sstream>

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace ISC::Data;

const unsigned char PROTOCOL_VERSION[4] = { 0x53, 0x6b, 0x61, 0x6e };

const unsigned char ITEM_DATA = 0x01;
const unsigned char ITEM_HASH = 0x02;
const unsigned char ITEM_LIST = 0x03;
const unsigned char ITEM_NULL = 0x04;
const unsigned char ITEM_MASK = 0x0f;

const unsigned char ITEM_LENGTH_32   = 0x00;
const unsigned char ITEM_LENGTH_16   = 0x10;
const unsigned char ITEM_LENGTH_8    = 0x20;
const unsigned char ITEM_LENGTH_MASK = 0x30;

std::ostream& operator <<(std::ostream &out, const ISC::Data::ElementPtr& e) {
    return out << e->str();
}

30 31 32 33 34 35 36
const char*
ParseError::what() const throw() {
    stringstream ss;
    ss << msg << " line " << line << " pos " << pos;
    return ss.str().c_str();
}

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
//
// factory functions
//
ElementPtr
Element::create(const int i)
{
    try {
        return ElementPtr(new IntElement(i));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const double d)
{
    try {
        return ElementPtr(new DoubleElement(d));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::string& s)
{
    try {
        return ElementPtr(new StringElement(s));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const bool b)
{
    try {
        return ElementPtr(new BoolElement(b));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::vector<ElementPtr>& v)
{
    try {
        return ElementPtr(new ListElement(v));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::map<std::string, ElementPtr>& m)
{
    try {
        return ElementPtr(new MapElement(m));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}


//
// helper functions for create_from_string factory
// these should probably also be moved to member functions
//

static bool
char_in(char c, const char *chars)
{
    for (size_t i = 0; i < strlen(chars); i++) {
        if (chars[i] == c) {
            return true;
        }
    }
    return false;
}

static void
118
skip_chars(std::istream &in, const char *chars, int& line, int& pos)
119 120 121
{
    char c = in.peek();
    while (char_in(c, chars) && c != EOF) {
122 123 124 125 126 127
        if (c == '\n') {
            line++;
            pos = 1;
        } else {
            pos++;
        }
128 129 130 131
        in.get();
        c = in.peek();
    }
}
132 133 134 135 136 137
/*static void
skip_chars(std::istream &in, const char *chars)
{
    int l = 0, p = 0;
    skip_chars(in, chars, l, p);
}*/
138 139 140 141 142 143

// skip on the input stream to one of the characters in chars
// if another character is found this function returns false
// unles that character is specified in the optional may_skip
//
// the character found is left on the stream
144 145
static void
skip_to(std::istream &in, int& line, int& pos, const char* chars, const char* may_skip="")
146 147
{
    char c = in.get();
148
    pos++;
149
    while (c != EOF) {
150 151 152 153
        if (c == '\n') {
            pos = 1;
            line++;
        }
154 155
        if (char_in(c, may_skip)) {
            c = in.get();
156
            pos++;
157 158
        } else if (char_in(c, chars)) {
            while(char_in(in.peek(), may_skip)) {
159 160 161 162
                if (in.peek() == '\n') {
                    pos = 1;
                    line++;
                }
163
                in.get();
164
                pos++;
165 166
            }
            in.putback(c);
167 168
            pos--;
            return;
169
        } else {
170
            throw ParseError(std::string("'") + c + "' read, one of \"" + chars + "\" expected", line, pos);
171 172
        }
    }
173
    throw ParseError(std::string("EOF read, one of \"") + chars + "\" expected", line, pos);
174 175
}

176 177 178 179 180 181
/*static bool
skip_to(std::istream &in, const char *chars, const char *may_skip="") {
    int line = 0, pos = 0;
    return skip_to(in, line, pos, chars, may_skip);
}*/

182
static std::string
183
str_from_stringstream(std::istream &in, int& line, int& pos) throw (ParseError)
184 185 186 187
{
    char c = 0;
    std::stringstream ss;
    c = in.get();
188
    pos++;
189 190
    if (c == '"') {
        c = in.get();
191
        pos++;
192
    } else {
193
        throw ParseError("String expected", line, pos);
194 195 196 197 198
    }
    while (c != EOF && c != '"') {
        ss << c;
        if (c == '\\' && in.peek() == '"') {
            ss << in.get();
199
            pos++;
200 201
        }
        c = in.get();
202
        pos++;
203 204 205 206 207
    }
    return ss.str();
}

static std::string
208
word_from_stringstream(std::istream &in, int& line, int& pos)
209 210 211 212 213
{
    std::stringstream ss;
    while (isalpha(in.peek())) {
        ss << (char) in.get();
    }
214
    pos += ss.str().size();
215 216 217 218 219
    return ss.str();
}


static ElementPtr
220
from_stringstream_int_or_double(std::istream &in, int &line, int &pos)
221 222 223
{
    int i;
    in >> i;
224
    // TODO count pos
225 226 227 228 229 230 231 232 233 234 235
    if (in.peek() == '.') {
        double d;
        in >> d;
        d += i;
        return Element::create(d);
    } else {
        return Element::create(i);
    }
}

static ElementPtr
236
from_stringstream_bool(std::istream &in, int& line, int& pos)
237
{
238
    std::string word = word_from_stringstream(in, line, pos);
239 240 241 242 243 244 245 246 247 248
    if (boost::iequals(word, "True")) {
        return Element::create(true);
    } else if (boost::iequals(word, "False")) {
        return Element::create(false);
    } else {
        return ElementPtr();
    }
}

static ElementPtr
249
from_stringstream_string(std::istream &in, int& line, int& pos)
250
{
251
    return Element::create(str_from_stringstream(in, line, pos));
252 253 254
}

static ElementPtr
255
from_stringstream_list(std::istream &in, int& line, int& pos)
256 257 258 259
{
    char c = 0;
    std::vector<ElementPtr> v;
    ElementPtr cur_list_element;
260
    //cout << "reading list at line " << line << " pos " << pos << endl;
261

262
    skip_chars(in, " \t\n", line, pos);
263
    while (c != EOF && c != ']') {
264 265 266 267 268
        //cout << "at line " << line << " pos " << pos << " cur c: " << c << " next c: " << char(in.peek()) << endl;
        if (in.peek() != ']') {
            cur_list_element = Element::create_from_string(in, line, pos);
            v.push_back(cur_list_element);
            skip_to(in, line, pos, ",]", " \t\n");
269 270
        }
        c = in.get();
271
        pos++;
272 273 274 275 276
    }
    return Element::create(v);
}

static ElementPtr
277
from_stringstream_map(std::istream &in, int& line, int& pos)
278 279 280 281 282 283
{
    char c = 0;
    std::map<std::string, ElementPtr> m;
    std::pair<std::string, ElementPtr> p;
    std::string cur_map_key;
    ElementPtr cur_map_element;
284
    skip_chars(in, " \t\n", line, pos);
285
    while (c != EOF && c != '}') {
286 287 288 289 290 291
        p.first = str_from_stringstream(in, line, pos);
        skip_to(in, line, pos, ":", " \t\n");
        // skip the :
        in.get();
        pos++;
        p.second = Element::create_from_string(in, line, pos);
292 293
        if (!p.second) { return ElementPtr(); };
        m.insert(p);
294
        skip_to(in, line, pos, ",}", " \t\n");
295
        c = in.get();
296
        pos++;
297 298 299 300
    }
    return Element::create(m);
}

301 302
//ElementPtr
//Element::create_from_string(std::stringstream &in)
303
ElementPtr
304 305 306 307 308 309 310 311
Element::create_from_string(std::istream &in) throw(ParseError)
{
    int line = 1, pos = 1;
    return create_from_string(in, line, pos);
}

ElementPtr
Element::create_from_string(std::istream &in, int& line, int& pos) throw(ParseError)
312 313 314 315
{
    char c = 0;
    ElementPtr element;
    bool el_read = false;
316
    skip_chars(in, " \n\t", line, pos);
317 318
    while (c != EOF && !el_read) {
        c = in.get();
319 320
        pos++;
        //std::cout << c << std::endl;
321 322 323 324 325 326 327 328 329 330 331 332
        switch(c) {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                in.putback(c);
333
                element = from_stringstream_int_or_double(in, line, pos);
334 335 336 337 338 339 340
                el_read = true;
                break;
            case 't':
            case 'T':
            case 'f':
            case 'F':
                in.putback(c);
341
                element = from_stringstream_bool(in, line, pos);
342 343 344 345
                el_read = true;
                break;
            case '"':
                in.putback('"');
346
                element = from_stringstream_string(in, line, pos);
347 348 349
                el_read = true;
                break;
            case '[':
350
                element = from_stringstream_list(in, line, pos);
351 352 353
                el_read = true;
                break;
            case '{':
354
                element = from_stringstream_map(in, line, pos);
355 356
                el_read = true;
                break;
357 358
            case EOF:
                break;
359
            default:
360
                throw ParseError(std::string("error: unexpected character ") + c, line, pos);
361 362 363 364 365 366 367
                break;
        }
    }
    if (el_read) {
        return element;
    } else {
        // throw exception?
368
        throw ParseError("nothing read");
369 370 371
    }
}

372 373 374 375 376 377 378
ElementPtr
Element::create_from_string(const std::string &in)
{
    std::stringstream ss;
    ss << in;
    return create_from_string(ss);
}
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
//
// a general to_str() function
//
std::string
IntElement::str()
{
    std::stringstream ss;
    ss << int_value();
    return ss.str();
}

std::string
DoubleElement::str()
{
    std::stringstream ss;
    ss << double_value();
    return ss.str();
}

std::string
BoolElement::str()
{
    if (b) {
        return "True";
    } else {
        return "False";
    }
}

std::string
StringElement::str()
{
    std::stringstream ss;
    ss << "\"";
    ss << string_value();
    ss << "\"";
    return ss.str();
}

std::string
ListElement::str()
{
    std::stringstream ss;
    std::vector<ElementPtr> v;
    ss << "[ ";
    v = list_value();
    for (std::vector<ElementPtr>::iterator it = v.begin(); it != v.end(); ++it) {
        if (it != v.begin()) {
            ss << ", ";
        }
        ss << (*it)->str();
    }
    ss << " ]";
    return ss.str();
}

std::string
MapElement::str()
{
    std::stringstream ss;
    std::map<std::string, ElementPtr> m;
    ss << "{";
    m = map_value();
    for (std::map<std::string, ElementPtr>::iterator it = m.begin(); it != m.end(); ++it) {
        if (it != m.begin()) {
            ss << ", ";
        }
        ss << "\"" << (*it).first << "\": ";
        ss << (*it).second->str();
    }
    ss << "}";
    return ss.str();
}

//
// helpers for str_xml() functions
//

// prefix with 'prefix' number of spaces
static void
pre(std::ostream &out, size_t prefix)
{
    for (size_t i = 0; i < prefix; i++) {
        out << " ";
    }
}

std::string
IntElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    pre(ss, prefix);
    ss << str();
    return ss.str();
}

std::string
DoubleElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    pre(ss, prefix);
    ss << str();
    return ss.str();
}

std::string
BoolElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    pre(ss, prefix);
    ss << str();
    return ss.str();
}

std::string
StringElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    pre(ss, prefix);
    ss << string_value();
    return ss.str();
}

std::string
ListElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    std::vector<ElementPtr> v;
    pre(ss, prefix);
    ss << "<list>" << endl;;
    v = list_value();
    for (std::vector<ElementPtr>::iterator it = v.begin(); it != v.end(); ++it) {
        pre(ss, prefix + 4);
        ss << "<listitem>" << endl;
        ss << (*it)->str_xml(prefix + 8) << endl;
        pre(ss, prefix + 4);
        ss << "</listitem>" << endl;
    }
    pre(ss, prefix);
    ss << "</list>";
    return ss.str();
}

std::string
MapElement::str_xml(size_t prefix)
{
    std::stringstream ss;
    std::map<std::string, ElementPtr> m;
    m = map_value();
    pre(ss, prefix);
    ss << "<map>" << endl;
    for (std::map<std::string, ElementPtr>::iterator it = m.begin(); it != m.end(); ++it) {
        pre(ss, prefix + 4);
        ss << "<mapitem name=\"" << (*it).first << "\">" << endl;
        pre(ss, prefix);
        ss << (*it).second->str_xml(prefix+8) << endl;
        pre(ss, prefix + 4);
        ss << "</mapitem>" << endl;
    }
    pre(ss, prefix);
    ss << "</map>";
    return ss.str();
}

// currently throws when one of the types in the path (except the one
// we're looking for) is not a MapElement
// returns 0 if it could simply not be found
// should that also be an exception?
ElementPtr
MapElement::find(const std::string& id)
{
    if (get_type() != map) {
        throw TypeError();
    }
    size_t sep = id.find('/');
    if (sep == std::string::npos) {
        return get(id);
    } else {
        ElementPtr ce = get(id.substr(0, sep));
        if (ce) {
            return ce->find(id.substr(sep+1));
        } else {
            return ElementPtr();
        }
    }
}

//
// Decode from wire format.
//

ElementPtr decode_element(std::stringstream& in, int& in_length);

static unsigned char
get_byte(std::stringstream& in)
{
    int c = in.get();
    if (c == EOF) {
        throw DecodeError("End of data while decoding wire format message");
    }

    return c;
}

std::string
decode_tag(std::stringstream& in, int& item_length)
{
    char buf[256];

    int len = get_byte(in);
    item_length--;

    in.read(buf, len);
    if (in.fail()) {
        throw DecodeError();
    }
    buf[len] = 0;
    item_length -= len;

    return std::string(buf, len);
}

ElementPtr
decode_data(std::stringstream& in, int& item_length)
{
    char *buf = new char[item_length + 1];

    in.read(buf, item_length);
    if (in.fail()) {
        throw DecodeError();
    }
    buf[item_length] = 0;

    std::string s = std::string(buf, item_length);
    item_length -= item_length;

    delete [] buf;
    return Element::create(s);
}

ElementPtr
decode_hash(std::stringstream& in, int& item_length)
{
    std::map<std::string, ElementPtr> m;
    std::pair<std::string, ElementPtr> p;

    while (item_length > 0) {
        p.first = decode_tag(in, item_length);
        p.second = decode_element(in, item_length);
        m.insert(p);
    }

    return Element::create(m);
}

ElementPtr
decode_list(std::stringstream& in, int& item_length)
{
    std::vector<ElementPtr> v;

    while (item_length > 0) {
        v.push_back(decode_element(in, item_length));
    }
    return Element::create(v);
}

ElementPtr
decode_null(std::stringstream& in, int& item_length)
{
    return Element::create("NULL");
}

ElementPtr
decode_element(std::stringstream& in, int& in_length)
{
    ElementPtr element;

    unsigned char type_and_length = get_byte(in);
    unsigned char type = type_and_length & ITEM_MASK;
    unsigned char lenbytes = type_and_length & ITEM_LENGTH_MASK;
    in_length--;

    int item_length = 0;
    switch (lenbytes) {
    case ITEM_LENGTH_32:
        item_length |= get_byte(in);
        item_length <<= 8;
        item_length |= get_byte(in);
        item_length <<= 8;
        in_length -= 2;  // only 2 here, we will get more later
    case ITEM_LENGTH_16:
        item_length |= get_byte(in);
        item_length <<= 8;
        in_length--;  // only 1 here
    case ITEM_LENGTH_8:
        item_length |= get_byte(in);
        in_length--;
    }

    in_length -= item_length;

    switch (type) {
    case ITEM_DATA:
        element = decode_data(in, item_length);
        break;
    case ITEM_HASH:
        element = decode_hash(in, item_length);
        break;
    case ITEM_LIST:
        element = decode_list(in, item_length);
        break;
    case ITEM_NULL:
        element = decode_null(in, item_length);
        break;
    }

    return (element);
}

ElementPtr
Element::from_wire(const std::string& s)
{
    std::stringstream ss;
    ss << s;
    return from_wire(ss, s.length());
}

ElementPtr
Element::from_wire(std::stringstream& in, int length)
{
    //
    // Check protocol version
    //
    for (int i = 0 ; i < 4 ; i++) {
        unsigned char version_byte = get_byte(in);
        if (PROTOCOL_VERSION[i] != version_byte) {
            throw DecodeError("Protocol version incorrect");
        }
    }
    length -= 4;

    ElementPtr element;
    element = decode_hash(in, length);
    return (element);
}

//
// Encode into wire format.
//

std::string
encode_length(unsigned int length, unsigned char type)
{
    std::stringstream ss;

    if (length <= 0x000000ff) {
        unsigned char val = (length & 0x000000ff);
        type |= ITEM_LENGTH_8;
        ss << type << val;
    } else if (length <= 0x0000ffff) {
        unsigned char val[2];
        val[0] = (length & 0x0000ff00) >> 8;
        val[1] = (length & 0x000000ff);
        type |= ITEM_LENGTH_16;
        ss << type << val;
    } else {
        unsigned char val[4];
        val[0] = (length & 0xff000000) >> 24;
        val[1] = (length & 0x00ff0000) >> 16;
        val[2] = (length & 0x0000ff00) >> 8;
        val[3] = (length & 0x000000ff);
        type |= ITEM_LENGTH_32;
        ss << type << val;
    }
    return ss.str();
}

std::string
StringElement::to_wire(int omit_length)
{
    std::stringstream ss;

    int length = string_value().length();
    ss << encode_length(length, ITEM_DATA) << string_value();

    return ss.str();
}

std::string
IntElement::to_wire(int omit_length)
{
    std::stringstream ss;
    std::stringstream text;

    text << str();
    int length = text.str().length();
    ss << encode_length(length, ITEM_DATA) << text.str();

    return ss.str();
}

std::string
BoolElement::to_wire(int omit_length)
{
    std::stringstream ss;
    std::stringstream text;

    text << str();
    int length = text.str().length();
    ss << encode_length(length, ITEM_DATA) << text.str();

    return ss.str();
}

std::string
DoubleElement::to_wire(int omit_length)
{
    std::stringstream ss;
    std::stringstream text;

    text << str();
    int length = text.str().length();
    ss << encode_length(length, ITEM_DATA) << text.str();

    return ss.str();
}

std::string
ListElement::to_wire(int omit_length)
{
    std::stringstream ss;
    std::vector<ElementPtr> v;
    v = list_value();
    for (std::vector<ElementPtr>::iterator it = v.begin() ;
         it != v.end() ; ++it) {
        ss << (*it)->to_wire(0);
    }

    if (omit_length) {
        return ss.str();
    } else {
        std::stringstream ss_len;
        ss_len << encode_length(ss.str().length(), ITEM_LIST);
        ss_len << ss.str();
        return ss_len.str();
    }
}

std::string
encode_tag(const std::string &s)
{
    std::stringstream ss;
    int length = s.length();
    unsigned char val = length & 0x000000ff;

    ss << val << s;

    return ss.str();
}

std::string
MapElement::to_wire(int omit_length)
{
    std::stringstream ss;
    std::map<std::string, ElementPtr> m;

    //
    // If we don't want the length, we will want the protocol header
    //
    if (omit_length) {
        ss << PROTOCOL_VERSION[0] << PROTOCOL_VERSION[1];
        ss << PROTOCOL_VERSION[2] << PROTOCOL_VERSION[3];
    }

    m = map_value();
    for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
         it != m.end() ; ++it) {
        ss << encode_tag((*it).first);
        ss << (*it).second->to_wire(0);
    }

    //
    // add length if needed
    //
    if (omit_length) {
        return ss.str();
    } else {
        std::stringstream ss_len;
        ss_len << encode_length(ss.str().length(), ITEM_HASH);
        ss_len << ss.str();
        return ss_len.str();
    }
}

bool
MapElement::find(const std::string& id, ElementPtr& t) {
    ElementPtr p;
    try {
        p = find(id);
        if (p) {
            t = p;
            return true;
        }
    } catch (TypeError e) {
        // ignore
    }
    return false;
}