source: mainline/uspace/app/bdsh/cmds/modules/cat/cat.c@ b19e892

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since b19e892 was b19e892, checked in by Jakub Jermar <jakub@…>, 8 years ago

Merge open() with posix_open() and provide vfs_lookup_open() instead

vfs_lookup_open() is really just a convenience wrapper around
vfs_lookup() and vfs_open().

  • Property mode set to 100644
File size: 9.9 KB
Line 
1/*
2 * Copyright (c) 2008 Tim Post
3 * Copyright (c) 2011, Martin Sucha
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#include <stdio.h>
31#include <stdlib.h>
32#include <unistd.h>
33#include <getopt.h>
34#include <str.h>
35#include <io/console.h>
36#include <io/color.h>
37#include <io/style.h>
38#include <io/keycode.h>
39#include <errno.h>
40#include <vfs/vfs.h>
41#include <assert.h>
42
43#include "config.h"
44#include "util.h"
45#include "errors.h"
46#include "entry.h"
47#include "cat.h"
48#include "cmds.h"
49
50static const char *cmdname = "cat";
51#define CAT_VERSION "0.0.1"
52#define CAT_DEFAULT_BUFLEN 1024
53#define CAT_FULL_FILE 0
54
55static const char *hexchars = "0123456789abcdef";
56
57static bool paging_enabled = false;
58static size_t chars_remaining = 0;
59static size_t lines_remaining = 0;
60static sysarg_t console_cols = 0;
61static sysarg_t console_rows = 0;
62static bool should_quit = false;
63static bool dash_represents_stdin = false;
64static unsigned int lineno = 0;
65static bool number = false;
66static bool last_char_was_newline = false;
67
68static console_ctrl_t *console = NULL;
69
70static struct option const long_options[] = {
71 { "help", no_argument, 0, 'h' },
72 { "version", no_argument, 0, 'v' },
73 { "head", required_argument, 0, 'H' },
74 { "tail", required_argument, 0, 't' },
75 { "buffer", required_argument, 0, 'b' },
76 { "more", no_argument, 0, 'm' },
77 { "hex", no_argument, 0, 'x' },
78 { "stdin", no_argument, 0, 's' },
79 { "number", no_argument, 0, 'n' },
80 { 0, 0, 0, 0 }
81};
82
83/* Dispays help for cat in various levels */
84void help_cmd_cat(unsigned int level)
85{
86 if (level == HELP_SHORT) {
87 printf("`%s' shows the contents of files\n", cmdname);
88 } else {
89 help_cmd_cat(HELP_SHORT);
90 printf(
91 "Usage: %s [options] <file1> [file2] [...]\n"
92 "Options:\n"
93 " -h, --help A short option summary\n"
94 " -v, --version Print version information and exit\n"
95 " -H, --head ## Print only the first ## bytes\n"
96 " -t, --tail ## Print only the last ## bytes\n"
97 " -b, --buffer ## Set the read buffer size to ##\n"
98 " -m, --more Pause after each screen full\n"
99 " -x, --hex Print bytes as hex values\n"
100 " -s, --stdin Treat `-' in file list as standard input\n"
101 " -n, --number Number all output lines\n"
102 "Currently, %s is under development, some options don't work.\n",
103 cmdname, cmdname);
104 }
105
106 return;
107}
108
109static void waitprompt(void)
110{
111 console_set_pos(console, 0, console_rows-1);
112 console_set_color(console, COLOR_WHITE, COLOR_BLUE, 0);
113
114 printf("ENTER/SPACE/PAGE DOWN - next page, "
115 "ESC/Q - quit, C - continue unpaged");
116 fflush(stdout);
117
118 console_set_style(console, STYLE_NORMAL);
119}
120
121static void waitkey(void)
122{
123 cons_event_t ev;
124 kbd_event_t *kev;
125
126 while (true) {
127 if (!console_get_event(console, &ev)) {
128 return;
129 }
130 if (ev.type == CEV_KEY && ev.ev.key.type == KEY_PRESS) {
131 kev = &ev.ev.key;
132
133 if (kev->key == KC_ESCAPE || kev->key == KC_Q) {
134 should_quit = true;
135 return;
136 }
137 if (kev->key == KC_C) {
138 paging_enabled = false;
139 return;
140 }
141 if (kev->key == KC_ENTER || kev->key == KC_SPACE ||
142 kev->key == KC_PAGE_DOWN) {
143 return;
144 }
145 }
146 }
147 assert(false);
148}
149
150static void newpage(void)
151{
152 console_clear(console);
153 chars_remaining = console_cols;
154 lines_remaining = console_rows - 1;
155}
156
157static void paged_char(wchar_t c)
158{
159 if (last_char_was_newline && number) {
160 lineno++;
161 printf("%6u ", lineno);
162 }
163 putchar(c);
164 last_char_was_newline = c == '\n';
165 if (paging_enabled) {
166 chars_remaining--;
167 if (c == '\n' || chars_remaining == 0) {
168 chars_remaining = console_cols;
169 lines_remaining--;
170 }
171 if (lines_remaining == 0) {
172 fflush(stdout);
173 waitprompt();
174 waitkey();
175 newpage();
176 }
177 }
178}
179
180static unsigned int cat_file(const char *fname, size_t blen, bool hex,
181 off64_t head, off64_t tail, bool tail_first)
182{
183 int fd, bytes = 0, count = 0, reads = 0;
184 char *buff = NULL;
185 int i;
186 size_t offset = 0, copied_bytes = 0;
187 off64_t file_size = 0, length = 0;
188 aoff64_t pos = 0;
189
190 bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
191
192 if (reading_stdin) {
193 fd = fileno(stdin);
194 /* Allow storing the whole UTF-8 character. */
195 blen = STR_BOUNDS(1);
196 } else
197 fd = vfs_lookup_open(fname, WALK_REGULAR, MODE_READ);
198
199 if (fd < 0) {
200 printf("Unable to open %s\n", fname);
201 return 1;
202 }
203
204 if (NULL == (buff = (char *) malloc(blen + 1))) {
205 close(fd);
206 printf("Unable to allocate enough memory to read %s\n",
207 fname);
208 return 1;
209 }
210
211 if (tail != CAT_FULL_FILE) {
212 struct stat st;
213
214 if (vfs_stat(fd, &st) != EOK) {
215 close(fd);
216 free(buff);
217 printf("Unable to vfs_stat %d\n", fd);
218 return 1;
219 }
220 file_size = st.size;
221 if (head == CAT_FULL_FILE) {
222 head = file_size;
223 length = tail;
224 } else if (tail_first) {
225 length = head;
226 } else {
227 if (tail > head)
228 tail = head;
229 length = tail;
230 }
231
232 if (tail_first) {
233 pos = (tail >= file_size) ? 0 : (file_size - tail);
234 } else {
235 pos = ((head - tail) >= file_size) ? 0 : (head - tail);
236 }
237 } else
238 length = head;
239
240 do {
241 size_t bytes_to_read;
242 if (reading_stdin) {
243 bytes_to_read = 1;
244 } else {
245 if ((length != CAT_FULL_FILE) &&
246 (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
247 bytes_to_read = (size_t) (length - count);
248 } else {
249 bytes_to_read = blen - copied_bytes;
250 }
251 }
252
253 bytes = read(fd, &pos, buff + copied_bytes, bytes_to_read);
254 copied_bytes = 0;
255
256 if (bytes > 0) {
257 buff[bytes] = '\0';
258 offset = 0;
259 for (i = 0; i < bytes && !should_quit; i++) {
260 if (hex) {
261 paged_char(hexchars[((uint8_t)buff[i])/16]);
262 paged_char(hexchars[((uint8_t)buff[i])%16]);
263 paged_char(((count+i+1) & 0xf) == 0 ? '\n' : ' ');
264 }
265 else {
266 wchar_t c = str_decode(buff, &offset, bytes);
267 if (c == 0) {
268 /* Reached end of string */
269 break;
270 } else if (c == U_SPECIAL && offset + 2 >= (size_t)bytes) {
271 /* If an extended character is cut off due to the size of the buffer,
272 we will copy it over to the next buffer so it can be read correctly. */
273 copied_bytes = bytes - offset + 1;
274 memcpy(buff, buff + offset - 1, copied_bytes);
275 break;
276 }
277 paged_char(c);
278 }
279
280 }
281 count += bytes;
282 reads++;
283 }
284
285 if (reading_stdin)
286 fflush(stdout);
287 } while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
288
289 close(fd);
290 if (bytes == -1) {
291 printf("Error reading %s\n", fname);
292 free(buff);
293 return 1;
294 }
295
296 free(buff);
297
298 return 0;
299}
300
301/* Main entry point for cat, accepts an array of arguments */
302int cmd_cat(char **argv)
303{
304 unsigned int argc, i, ret = 0;
305 size_t buffer = 0;
306 int c, opt_ind;
307 aoff64_t head = CAT_FULL_FILE, tail = CAT_FULL_FILE;
308 bool hex = false;
309 bool more = false;
310 bool tailFirst = false;
311 sysarg_t rows, cols;
312 int rc;
313
314 /*
315 * reset global state
316 * TODO: move to structure?
317 */
318 paging_enabled = false;
319 chars_remaining = 0;
320 lines_remaining = 0;
321 console_cols = 0;
322 console_rows = 0;
323 should_quit = false;
324 console = console_init(stdin, stdout);
325 number = false;
326 lineno = 0;
327 /* This enables printing of the first number. */
328 last_char_was_newline = true;
329
330
331 argc = cli_count_args(argv);
332
333 for (c = 0, optreset = 1, optind = 0, opt_ind = 0; c != -1;) {
334 c = getopt_long(argc, argv, "xhvmH:t:b:s:n", long_options, &opt_ind);
335 switch (c) {
336 case 'h':
337 help_cmd_cat(HELP_LONG);
338 return CMD_SUCCESS;
339 case 'v':
340 printf("%s\n", CAT_VERSION);
341 return CMD_SUCCESS;
342 case 'H':
343 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &head) != EOK ) {
344 puts("Invalid head size\n");
345 return CMD_FAILURE;
346 }
347 break;
348 case 't':
349 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &tail) != EOK ) {
350 puts("Invalid tail size\n");
351 return CMD_FAILURE;
352 }
353 if (head == CAT_FULL_FILE)
354 tailFirst = true;
355 break;
356 case 'b':
357 if (!optarg || str_size_t(optarg, NULL, 10, false, &buffer) != EOK ) {
358 puts("Invalid buffer size\n");
359 return CMD_FAILURE;
360 }
361 break;
362 case 'm':
363 more = true;
364 break;
365 case 'x':
366 hex = true;
367 break;
368 case 's':
369 dash_represents_stdin = true;
370 break;
371 case 'n':
372 number = true;
373 break;
374 }
375 }
376
377 argc -= optind;
378
379 if (argc < 1) {
380 printf("%s - incorrect number of arguments. Try `%s --help'\n",
381 cmdname, cmdname);
382 return CMD_FAILURE;
383 }
384
385 if (buffer < 4)
386 buffer = CAT_DEFAULT_BUFLEN;
387
388 if (more) {
389 rc = console_get_size(console, &cols, &rows);
390 if (rc != EOK) {
391 printf("%s - cannot get console size\n", cmdname);
392 return CMD_FAILURE;
393 }
394 console_cols = cols;
395 console_rows = rows;
396 paging_enabled = true;
397 newpage();
398 }
399
400 for (i = optind; argv[i] != NULL && !should_quit; i++)
401 ret += cat_file(argv[i], buffer, hex, head, tail, tailFirst);
402
403 if (ret)
404 return CMD_FAILURE;
405 else
406 return CMD_SUCCESS;
407}
408
Note: See TracBrowser for help on using the repository browser.