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

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

Rename stat() to vfs_stat_path() and fstat() to vfs_stat()

  • 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 <fcntl.h>
36#include <io/console.h>
37#include <io/color.h>
38#include <io/style.h>
39#include <io/keycode.h>
40#include <errno.h>
41#include <vfs/vfs.h>
42#include <assert.h>
43
44#include "config.h"
45#include "util.h"
46#include "errors.h"
47#include "entry.h"
48#include "cat.h"
49#include "cmds.h"
50
51static const char *cmdname = "cat";
52#define CAT_VERSION "0.0.1"
53#define CAT_DEFAULT_BUFLEN 1024
54#define CAT_FULL_FILE 0
55
56static const char *hexchars = "0123456789abcdef";
57
58static bool paging_enabled = false;
59static size_t chars_remaining = 0;
60static size_t lines_remaining = 0;
61static sysarg_t console_cols = 0;
62static sysarg_t console_rows = 0;
63static bool should_quit = false;
64static bool dash_represents_stdin = false;
65static unsigned int lineno = 0;
66static bool number = false;
67static bool last_char_was_newline = false;
68
69static console_ctrl_t *console = NULL;
70
71static struct option const long_options[] = {
72 { "help", no_argument, 0, 'h' },
73 { "version", no_argument, 0, 'v' },
74 { "head", required_argument, 0, 'H' },
75 { "tail", required_argument, 0, 't' },
76 { "buffer", required_argument, 0, 'b' },
77 { "more", no_argument, 0, 'm' },
78 { "hex", no_argument, 0, 'x' },
79 { "stdin", no_argument, 0, 's' },
80 { "number", no_argument, 0, 'n' },
81 { 0, 0, 0, 0 }
82};
83
84/* Dispays help for cat in various levels */
85void help_cmd_cat(unsigned int level)
86{
87 if (level == HELP_SHORT) {
88 printf("`%s' shows the contents of files\n", cmdname);
89 } else {
90 help_cmd_cat(HELP_SHORT);
91 printf(
92 "Usage: %s [options] <file1> [file2] [...]\n"
93 "Options:\n"
94 " -h, --help A short option summary\n"
95 " -v, --version Print version information and exit\n"
96 " -H, --head ## Print only the first ## bytes\n"
97 " -t, --tail ## Print only the last ## bytes\n"
98 " -b, --buffer ## Set the read buffer size to ##\n"
99 " -m, --more Pause after each screen full\n"
100 " -x, --hex Print bytes as hex values\n"
101 " -s, --stdin Treat `-' in file list as standard input\n"
102 " -n, --number Number all output lines\n"
103 "Currently, %s is under development, some options don't work.\n",
104 cmdname, cmdname);
105 }
106
107 return;
108}
109
110static void waitprompt(void)
111{
112 console_set_pos(console, 0, console_rows-1);
113 console_set_color(console, COLOR_WHITE, COLOR_BLUE, 0);
114
115 printf("ENTER/SPACE/PAGE DOWN - next page, "
116 "ESC/Q - quit, C - continue unpaged");
117 fflush(stdout);
118
119 console_set_style(console, STYLE_NORMAL);
120}
121
122static void waitkey(void)
123{
124 cons_event_t ev;
125 kbd_event_t *kev;
126
127 while (true) {
128 if (!console_get_event(console, &ev)) {
129 return;
130 }
131 if (ev.type == CEV_KEY && ev.ev.key.type == KEY_PRESS) {
132 kev = &ev.ev.key;
133
134 if (kev->key == KC_ESCAPE || kev->key == KC_Q) {
135 should_quit = true;
136 return;
137 }
138 if (kev->key == KC_C) {
139 paging_enabled = false;
140 return;
141 }
142 if (kev->key == KC_ENTER || kev->key == KC_SPACE ||
143 kev->key == KC_PAGE_DOWN) {
144 return;
145 }
146 }
147 }
148 assert(false);
149}
150
151static void newpage(void)
152{
153 console_clear(console);
154 chars_remaining = console_cols;
155 lines_remaining = console_rows - 1;
156}
157
158static void paged_char(wchar_t c)
159{
160 if (last_char_was_newline && number) {
161 lineno++;
162 printf("%6u ", lineno);
163 }
164 putchar(c);
165 last_char_was_newline = c == '\n';
166 if (paging_enabled) {
167 chars_remaining--;
168 if (c == '\n' || chars_remaining == 0) {
169 chars_remaining = console_cols;
170 lines_remaining--;
171 }
172 if (lines_remaining == 0) {
173 fflush(stdout);
174 waitprompt();
175 waitkey();
176 newpage();
177 }
178 }
179}
180
181static unsigned int cat_file(const char *fname, size_t blen, bool hex,
182 off64_t head, off64_t tail, bool tail_first)
183{
184 int fd, bytes = 0, count = 0, reads = 0;
185 char *buff = NULL;
186 int i;
187 size_t offset = 0, copied_bytes = 0;
188 off64_t file_size = 0, length = 0;
189 aoff64_t pos = 0;
190
191 bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
192
193 if (reading_stdin) {
194 fd = fileno(stdin);
195 /* Allow storing the whole UTF-8 character. */
196 blen = STR_BOUNDS(1);
197 } else
198 fd = open(fname, O_RDONLY);
199
200 if (fd < 0) {
201 printf("Unable to open %s\n", fname);
202 return 1;
203 }
204
205 if (NULL == (buff = (char *) malloc(blen + 1))) {
206 close(fd);
207 printf("Unable to allocate enough memory to read %s\n",
208 fname);
209 return 1;
210 }
211
212 if (tail != CAT_FULL_FILE) {
213 struct stat st;
214
215 if (vfs_stat(fd, &st) != EOK) {
216 close(fd);
217 free(buff);
218 printf("Unable to vfs_stat %d\n", fd);
219 return 1;
220 }
221 file_size = st.size;
222 if (head == CAT_FULL_FILE) {
223 head = file_size;
224 length = tail;
225 } else if (tail_first) {
226 length = head;
227 } else {
228 if (tail > head)
229 tail = head;
230 length = tail;
231 }
232
233 if (tail_first) {
234 pos = (tail >= file_size) ? 0 : (file_size - tail);
235 } else {
236 pos = ((head - tail) >= file_size) ? 0 : (head - tail);
237 }
238 } else
239 length = head;
240
241 do {
242 size_t bytes_to_read;
243 if (reading_stdin) {
244 bytes_to_read = 1;
245 } else {
246 if ((length != CAT_FULL_FILE) &&
247 (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
248 bytes_to_read = (size_t) (length - count);
249 } else {
250 bytes_to_read = blen - copied_bytes;
251 }
252 }
253
254 bytes = read(fd, &pos, buff + copied_bytes, bytes_to_read);
255 copied_bytes = 0;
256
257 if (bytes > 0) {
258 buff[bytes] = '\0';
259 offset = 0;
260 for (i = 0; i < bytes && !should_quit; i++) {
261 if (hex) {
262 paged_char(hexchars[((uint8_t)buff[i])/16]);
263 paged_char(hexchars[((uint8_t)buff[i])%16]);
264 paged_char(((count+i+1) & 0xf) == 0 ? '\n' : ' ');
265 }
266 else {
267 wchar_t c = str_decode(buff, &offset, bytes);
268 if (c == 0) {
269 /* Reached end of string */
270 break;
271 } else if (c == U_SPECIAL && offset + 2 >= (size_t)bytes) {
272 /* If an extended character is cut off due to the size of the buffer,
273 we will copy it over to the next buffer so it can be read correctly. */
274 copied_bytes = bytes - offset + 1;
275 memcpy(buff, buff + offset - 1, copied_bytes);
276 break;
277 }
278 paged_char(c);
279 }
280
281 }
282 count += bytes;
283 reads++;
284 }
285
286 if (reading_stdin)
287 fflush(stdout);
288 } while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
289
290 close(fd);
291 if (bytes == -1) {
292 printf("Error reading %s\n", fname);
293 free(buff);
294 return 1;
295 }
296
297 free(buff);
298
299 return 0;
300}
301
302/* Main entry point for cat, accepts an array of arguments */
303int cmd_cat(char **argv)
304{
305 unsigned int argc, i, ret = 0;
306 size_t buffer = 0;
307 int c, opt_ind;
308 aoff64_t head = CAT_FULL_FILE, tail = CAT_FULL_FILE;
309 bool hex = false;
310 bool more = false;
311 bool tailFirst = false;
312 sysarg_t rows, cols;
313 int rc;
314
315 /*
316 * reset global state
317 * TODO: move to structure?
318 */
319 paging_enabled = false;
320 chars_remaining = 0;
321 lines_remaining = 0;
322 console_cols = 0;
323 console_rows = 0;
324 should_quit = false;
325 console = console_init(stdin, stdout);
326 number = false;
327 lineno = 0;
328 /* This enables printing of the first number. */
329 last_char_was_newline = true;
330
331
332 argc = cli_count_args(argv);
333
334 for (c = 0, optreset = 1, optind = 0, opt_ind = 0; c != -1;) {
335 c = getopt_long(argc, argv, "xhvmH:t:b:s:n", long_options, &opt_ind);
336 switch (c) {
337 case 'h':
338 help_cmd_cat(HELP_LONG);
339 return CMD_SUCCESS;
340 case 'v':
341 printf("%s\n", CAT_VERSION);
342 return CMD_SUCCESS;
343 case 'H':
344 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &head) != EOK ) {
345 puts("Invalid head size\n");
346 return CMD_FAILURE;
347 }
348 break;
349 case 't':
350 if (!optarg || str_uint64_t(optarg, NULL, 10, false, &tail) != EOK ) {
351 puts("Invalid tail size\n");
352 return CMD_FAILURE;
353 }
354 if (head == CAT_FULL_FILE)
355 tailFirst = true;
356 break;
357 case 'b':
358 if (!optarg || str_size_t(optarg, NULL, 10, false, &buffer) != EOK ) {
359 puts("Invalid buffer size\n");
360 return CMD_FAILURE;
361 }
362 break;
363 case 'm':
364 more = true;
365 break;
366 case 'x':
367 hex = true;
368 break;
369 case 's':
370 dash_represents_stdin = true;
371 break;
372 case 'n':
373 number = true;
374 break;
375 }
376 }
377
378 argc -= optind;
379
380 if (argc < 1) {
381 printf("%s - incorrect number of arguments. Try `%s --help'\n",
382 cmdname, cmdname);
383 return CMD_FAILURE;
384 }
385
386 if (buffer < 4)
387 buffer = CAT_DEFAULT_BUFLEN;
388
389 if (more) {
390 rc = console_get_size(console, &cols, &rows);
391 if (rc != EOK) {
392 printf("%s - cannot get console size\n", cmdname);
393 return CMD_FAILURE;
394 }
395 console_cols = cols;
396 console_rows = rows;
397 paging_enabled = true;
398 newpage();
399 }
400
401 for (i = optind; argv[i] != NULL && !should_quit; i++)
402 ret += cat_file(argv[i], buffer, hex, head, tail, tailFirst);
403
404 if (ret)
405 return CMD_FAILURE;
406 else
407 return CMD_SUCCESS;
408}
409
Note: See TracBrowser for help on using the repository browser.