File: cbordump.c

package info (click to toggle)
tinycbor 7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 856 kB
  • sloc: ansic: 3,968; cpp: 3,494; perl: 156; sh: 44; makefile: 26
file content (164 lines) | stat: -rw-r--r-- 5,665 bytes parent folder | download | duplicates (2)
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
30
31
32
33
34
35
36
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/****************************************************************************
**
** Copyright (C) 2021 Intel Corporation
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
**
****************************************************************************/

#define _POSIX_C_SOURCE 200809L
#include "cbor.h"
#include "cborjson.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void *xrealloc(void *old, size_t size, const char *fname)
{
    old = realloc(old, size);
    if (old == NULL) {
        fprintf(stderr, "%s: %s\n", fname, strerror(errno));
        exit(EXIT_FAILURE);
    }
    return old;
}

void printerror(CborError err, const char *fname)
{
    fprintf(stderr, "%s: %s\n", fname, cbor_error_string(err));
    exit(EXIT_FAILURE);
}

void dumpFile(FILE *in, const char *fname, bool printJson, int flags)
{
    static const size_t chunklen = 16 * 1024;
    static size_t bufsize = 0;
    static uint8_t *buffer = NULL;

    size_t buflen = 0;
    do {
        if (bufsize == buflen)
            buffer = xrealloc(buffer, bufsize += chunklen, fname);

        size_t n = fread(buffer + buflen, 1, bufsize - buflen, in);
        buflen += n;
        if (n == 0) {
            if (!ferror(in))
                continue;
            fprintf(stderr, "%s: %s\n", fname, strerror(errno));
            exit(EXIT_FAILURE);
        }
    } while (!feof(in));

    CborParser parser;
    CborValue value;
    CborError err = cbor_parser_init(buffer, buflen, 0, &parser, &value);
    if (!err) {
        if (printJson)
            err = cbor_value_to_json_advance(stdout, &value, flags);
        else
            err = cbor_value_to_pretty_advance_flags(stdout, &value, flags);
        if (!err)
            puts("");
    }
    if (!err && cbor_value_get_next_byte(&value) != buffer + buflen)
        err = CborErrorGarbageAtEnd;
    if (err)
        printerror(err, fname);
}

int main(int argc, char **argv)
{
    bool printJson = false;
    int json_flags = CborConvertDefaultFlags;
    int cbor_flags = CborPrettyDefaultFlags;
    int c;
    while ((c = getopt(argc, argv, "MOSUcjhfn")) != -1) {
        switch (c) {
        case 'c':
            printJson = false;
            break;
        case 'j':
            printJson = true;
            break;

        case 'f':
            cbor_flags |= CborPrettyShowStringFragments;
            break;
        case 'n':
            cbor_flags |= CborPrettyIndicateIndeterminateLength | CborPrettyNumericEncodingIndicators;
            break;

        case 'M':
            json_flags |= CborConvertAddMetadata;
            break;
        case 'O':
            json_flags |= CborConvertTagsToObjects;
            break;
        case 'S':
            json_flags |= CborConvertStringifyMapKeys;
            break;
        case 'U':
            json_flags |= CborConvertByteStringsToBase64Url;
            break;

        case '?':
            fprintf(stderr, "Unknown option -%c.\n", optopt);
            /* fall through */
        case 'h':
            puts("Usage: cbordump [OPTION]... [FILE]...\n"
                 "Interprets FILEs as CBOR binary data and dumps the content to stdout.\n"
                 "\n"
                 "Options:\n"
                 " -c       Print a CBOR dump (see RFC 7049) (default)\n"
                 " -j       Print a JSON equivalent version\n"
                 " -h       Print this help output and exit\n"
                 "When JSON output is active, the following options are recognized:\n"
                 " -M       Add metadata so converting back to CBOR is possible\n"
                 " -O       Convert CBOR tags to JSON objects\n"
                 " -S       Stringify non-text string map keys\n"
                 " -U       Convert all CBOR byte strings to Base64url regardless of tags\n"
                 "When CBOR dump is active, the following options are recognized:\n"
                 " -f       Show text and byte string fragments\n"
                 " -n       Show overlong encoding of CBOR numbers and length"
                 "");
            return c == '?' ? EXIT_FAILURE : EXIT_SUCCESS;
        }
    }

    char **fname = argv + optind;
    if (!*fname) {
        dumpFile(stdin, "-", printJson, printJson ? json_flags : cbor_flags);
    } else {
        for ( ; *fname; ++fname) {
            FILE *in = fopen(*fname, "rb");
            if (!in) {
                perror("open");
                return EXIT_FAILURE;
            }

            dumpFile(in, *fname, printJson, printJson ? json_flags : cbor_flags);
            fclose(in);
        }
    }

    return EXIT_SUCCESS;
}