summaryrefslogtreecommitdiff
path: root/cli.c
blob: f3659915368a1d514fbb6c56db88e9b01d0f48cc (plain)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
 * basE91 command line front-end
 *
 * Copyright (c) 2000-2006 Joachim Henke
 * 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 Joachim Henke nor the names of his 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 OWNER 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 <string.h>
#ifdef _WIN32
#include <fcntl.h>
#include <unistd.h>
#endif
#include <getopt.h>
#include "base91.h"

#define FLG_D 1
#define FLG_V 2
#define FLG_VV 4

static char status[32];
static const char *progname;
static char *ibuf, *obuf;
static size_t ibuf_size, llen;
static struct basE91 b91;

static void stream_b91enc_p(void)
{
	size_t itotal = 0;
	size_t ototal = 0;
	size_t s;

	while ((s = fread(ibuf, 1, ibuf_size, stdin)) > 0) {
		itotal += s;
		s = basE91_encode(&b91, ibuf, s, obuf);
		ototal += s;
		fwrite(obuf, 1, s, stdout);
	}
	s = basE91_encode_end(&b91, obuf);	/* empty bit queue */
	ototal += s;
	fwrite(obuf, 1, s, stdout);

	sprintf(status, "\t%.2f%%\n", itotal ? (float) ototal / itotal * 100.0 : 1.0);
}

static void stream_b91enc_w(void)
{
	size_t l = llen;
	size_t ltotal = 0;
	size_t i, s;
	char x;

	while ((s = fread(ibuf, 1, ibuf_size, stdin)) > 0) {
		s = basE91_encode(&b91, ibuf, s, obuf);
		for (i = 0; l <= s; l += llen) {
			x = obuf[l];
			obuf[l] = '\0';
			puts(obuf + i);
			++ltotal;
			obuf[l] = x;
			i = l;
		}
		fwrite(obuf + i, 1, s - i, stdout);
		l -= s;
	}
	s = basE91_encode_end(&b91, obuf);
	if (s || l < llen) {
		obuf[s] = '\0';
		if (s > l) {
			x = obuf[1];
			obuf[1] = '\0';
			puts(obuf);
			++ltotal;
			obuf[0] = x;
		}
		puts(obuf);
		++ltotal;
	}

	sprintf(status, "\t%lu lines\n", (unsigned long) ltotal);
}

static void stream_b91dec(void)
{
	size_t s;

	while ((s = fread(ibuf, 1, ibuf_size, stdin)) > 0) {
		s = basE91_decode(&b91, ibuf, s, obuf);
		fwrite(obuf, 1, s, stdout);
	}
	s = basE91_decode_end(&b91, obuf);	/* empty bit queue */
	fwrite(obuf, 1, s, stdout);

	sprintf(status, "done\n");
}

static int init_flags(const char *p)
{
	size_t l = strlen(p);

	if (l > 5) {
		progname = p + l - 6;
		if (!strcmp(progname, "b91enc"))
			return 0;
		if (!strcmp(progname, "b91dec"))
			return FLG_D;
	}
	llen = 76;
	progname = "base91";

	return 0;
}

int main(int argc, char **argv)
{
	size_t buf_size = 65536;	/* buffer memory defaults to 64 KiB */
	int flags = init_flags(*argv);
	char *ifile = "from standard input";
	char *ofile = NULL;
	int opt;
	struct option longopts[8] = {
		{"decode", no_argument, NULL, 'd'},
		{"output", required_argument, NULL, 'o'},
		{"verbose", no_argument, NULL, 'v'},
		{"wrap", required_argument, NULL, 'w'},
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{NULL, 0, NULL, 0}
	};

	while ((opt = getopt_long(argc, argv, "dem:o:vw:hV", longopts, NULL)) != -1)
		switch (opt) {
		case 'd':
			flags |= FLG_D;
			break;
		case 'e':
			flags &= ~FLG_D;
			break;
		case 'm':
			{
				char *t;
				long l = strtol(optarg, &t, 0);

				if (t == optarg || strlen(t) > 1 || l < 0) {
					fprintf(stderr, "invalid SIZE argument: `%s'\n", optarg);
					return EXIT_FAILURE;
				}
				buf_size = l;
				switch (*t | 32) {
				case ' ':
				case 'b':
					break;
				case 'k':
					buf_size <<= 10;
					break;
				case 'm':
					buf_size <<= 20;
					break;
				default:
					fprintf(stderr, "invalid SIZE suffix: `%s'\n", t);
					return EXIT_FAILURE;
				}
			}
			break;
		case 'o':
			if (strcmp(optarg, "-"))
				ofile = optarg;
			break;
		case 'v':
			flags |= (flags & FLG_V) ? FLG_VV : FLG_V;
			break;
		case 'w':
			{
				char *t;
				long l = strtol(optarg, &t, 0);

				if (*t || l < 0) {
					fprintf(stderr, "invalid number of columns: `%s'\n", optarg);
					return EXIT_FAILURE;
				}
				llen = l;
			}
			break;
		case 'h':
			printf("Usage: %s [OPTION]... [FILE]\n"
				"basE91 encode or decode FILE, or standard input, to standard output.\n", progname);
			puts("\n  -d, --decode\t\tdecode data\n"
				"  -m SIZE\t\tuse SIZE bytes of memory for buffers (suffixes b, K, M)\n"
				"  -o, --output=FILE\twrite to FILE instead of standard output\n"
				"  -v, --verbose\t\tverbose mode\n"
				"  -w, --wrap=COLS\twrap encoded lines after COLS characters (default 76)\n"
				"  --help\t\tdisplay this help and exit\n"
				"  --version\t\toutput version information and exit\n\n"
				"With no FILE, or when FILE is -, read standard input.");
			return EXIT_SUCCESS;
		case 'V':
			printf("%s 0.6.0\nCopyright (c) 2000-2006 Joachim Henke\n", progname);
			return EXIT_SUCCESS;
		default:
			fprintf(stderr, "Try `%s --help' for more information.\n", *argv);
			return EXIT_FAILURE;
		}

	if (flags & FLG_D) {
		ibuf_size = (buf_size - 1) << 3;
		if (ibuf_size < 15) {
			fputs("SIZE must be >= 3 for decoding\n", stderr);
			return EXIT_FAILURE;
		}
		ibuf_size /= 15;
	} else {
		ibuf_size = (buf_size - 2) << 4;
		if (ibuf_size < 29) {
			fputs("SIZE must be >= 4 for encoding\n", stderr);
			return EXIT_FAILURE;
		}
		ibuf_size /= 29;
	}

	if (optind < argc && strcmp(argv[optind], "-")) {
		ifile = argv[optind];
		if (freopen(ifile, "r", stdin) != stdin) {
			perror(ifile);
			return EXIT_FAILURE;
		}
	}
	if (ofile)
		if (freopen(ofile, "w", stdout) != stdout) {
			perror(ofile);
			return EXIT_FAILURE;
		}

	if (flags & FLG_VV)
		fprintf(stderr, "using %lu bytes for buffers; input buffer: %lu bytes\n", (unsigned long) buf_size, (unsigned long) ibuf_size);
	obuf = malloc(buf_size);
	if (!obuf) {
		fputs("failed to allocate buffer memory\n", stderr);
		return EXIT_FAILURE;
	}

	basE91_init(&b91);
#ifdef _WIN32
	_setmode(_fileno(stdin), _O_BINARY);
#endif

	if (flags & FLG_D) {
#ifdef _WIN32
		_setmode(_fileno(stdout), _O_BINARY);
#endif
		ibuf = obuf + 1;	/* create overlapping buffers to use memory efficiently */
		if (flags & FLG_V)
			fprintf(stderr, "decoding %s ...", ifile);
		stream_b91dec();
	} else {
		ibuf = obuf + buf_size - ibuf_size;	/* partial overlap */
		if (flags & FLG_V)
			fprintf(stderr, "encoding %s ...", ifile);
		if (llen)
			stream_b91enc_w();
		else
			stream_b91enc_p();
	}
	free(obuf);

	if (flags & FLG_V)
		fputs(status, stderr);

	return EXIT_SUCCESS;
}